content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import pandas as pd from typing import List, NamedTuple from .timeseries import agg_by_category_by_date from primitive_interfaces.base import PrimitiveBase
[ 11748, 19798, 292, 355, 279, 67, 198, 6738, 19720, 1330, 7343, 11, 34441, 51, 29291, 198, 198, 6738, 764, 22355, 10640, 1330, 4194, 62, 1525, 62, 22872, 62, 1525, 62, 4475, 198, 6738, 20049, 62, 3849, 32186, 13, 8692, 1330, 11460, 180...
3.568182
44
# 804. Unique Morse Code Words """ https://leetcode.com/problems/unique-morse-code-words/discuss/120675/\ Easy-and-Concise-Solution-C++JavaPython def uniqueMorseRepresentations(self, words): d = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."] return len({''.join(d[ord(i) - ord('a')] for i in w) for w in words}) """ # 771. Jewels and Stones, 98.33% # https://leetcode.com/problems/jewels-and-stones/description/ def numJewelsInStones(self, J, S): """ :type J: str :type S: str :rtype: int """ count = 0 for jewel in J: for stone in S: if jewel == stone: count += 1 return count """ https://leetcode.com/problems/jewels-and-stones/discuss/113553/\ Easy-and-Concise-Solution-using-hash-set-C++JavaPython def numJewelsInStones(self, J, S): setJ = set(J) return sum(s in setJ for s in S) """ # 806. Number of Lines To Write String # https://leetcode.com/problems/number-of-lines-to-write-string/ def numberOfLines(self, widths, S): """ :type widths: List[int] :type S: str :rtype: List[int] """ lines = 1 line_width = 0 for ch in S: index = ord(ch) - ord('a') if line_width + widths[index] <= 100: line_width += widths[index] else: lines += 1 line_width = widths[index] return [lines, line_width] """ https://leetcode.com/problems/number-of-lines-to-write-string/discuss/\ 120666/Easy-Solution-6-lines-C++JavaPython def numberOfcurs(self, widths, S): res, cur = 1, 0 for i in S: width = widths[ord(i) - ord('a')] res += 1 if cur + width > 100 else 0 cur = width if cur + width > 100 else cur + width return [res, cur] """
[ 2, 807, 3023, 13, 30015, 44049, 6127, 23087, 628, 198, 198, 37811, 3740, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 34642, 12, 4491, 325, 12, 8189, 12, 10879, 14, 15410, 1046, 14, 1065, 3312, 2425, 14, 59, 198, 220, 220, ...
2.207094
874
import networkx as nx import matplotlib.pyplot as plt import matplotlib.patches as mpatches import numpy as np import logging from pygna import output from pygna.utils import YamlConfig import pandas as pd import random import string import seaborn as sns import pygna.output as output def generate_graph_from_sm(n_nodes: int, block_model: pd.DataFrame, nodes_in_block: list = False, node_names: list = None, nodes_percentage: list = None) -> nx.Graph: """ This function creates a graph with n_nodes number of vertices and a matrix block_model that describes the intra e inter-block connectivity. The nodes_in_block is parameter, list, to control the number of nodes in each cluster :param n_nodes: the number of nodes in the block model :param block_model: the block model to elaborate :param nodes_in_block: the list of nodes in the block model :param node_names: the list of names in the block model :param nodes_percentage: the percentage of nodes to use for the calculations, passed through a list for example [0.5, 0.5] Example _______ >>> bm = pd.DataFrame(mydata_matrix) >>> nodes = list("A","B","C") >>> graph = generate_graph_from_sm(n_nodes, bm, nodes_in_block, nodes, nodes_percentage) """ if not node_names: node_names = range(n_nodes) edges = [] G = nx.Graph() if nodes_percentage: cluster = np.random.choice(block_model.shape[0], size=n_nodes, p=nodes_percentage) np.random.shuffle(cluster) elif nodes_in_block: list_temp = [nodes_in_block[i] * [i] for i in range(len(nodes_in_block))] cluster = np.array([val for sublist in list_temp for val in sublist]) np.random.shuffle(cluster) else: # cluster is an array of random numbers corresponding to the cluster of each node cluster = np.random.randint(block_model.shape[0], size=n_nodes) for i in range(n_nodes): G.add_node(node_names[i], cluster=cluster[i]) for i in range(n_nodes): for j in range(i + 1, n_nodes): if np.random.rand() < block_model[cluster[i], cluster[j]]: edges.append((node_names[i], node_names[j])) G.add_edges_from(edges) return G def plot_bm_graph(graph: nx.Graph, block_model: pd.DataFrame, output_folder: str = None) -> None: """ Save the graph on a file :param graph: the graph with name of the nodes :param block_model: the block model :param output_folder: the folder where to save the file Example _______ >>> bm = pd.DataFrame(mydata_matrix) >>> graph = nx.complete_graph(100) >>> plot_bm_graph(graph, bm, output_folder="./results/") """ nodes = graph.nodes() colors = ['#b15928', '#1f78b4', '#6a3d9a', '#33a02c', '#ff7f00'] cluster = nx.get_node_attributes(graph, 'cluster') labels = [colors[cluster[n]] for n in nodes] layout = nx.spring_layout(graph) plt.figure(figsize=(13.5, 5)) plt.subplot(1, 3, 1) nx.draw(graph, nodelist=nodes, pos=layout, node_color='#636363', node_size=50, edge_color='#bdbdbd') plt.title("Observed network") plt.subplot(1, 3, 2) plt.imshow(block_model, cmap='OrRd', interpolation='nearest') plt.title("Stochastic block matrix") plt.subplot(1, 3, 3) legend = [] for ix, c in enumerate(colors): legend.append(mpatches.Patch(color=c, label='C%d' % ix)) nx.draw(graph, nodelist=nodes, pos=layout, node_color=labels, node_size=50, edge_color='#bdbdbd') plt.legend(handles=legend, ncol=len(colors), mode="expand", borderaxespad=0) plt.title("SB clustering") plt.savefig(output_folder + 'block_model.pdf', bbox_inches='tight') def generate_sbm_network(input_file: "yaml configuration file") -> None: """ This function generates a simulated network, using the block model matrix given as input and saves both the network and the cluster nodes. All parameters must be specified in a yaml file. This function allows to create network and geneset for any type of SBM """ ym = YamlConfig() config = ym.load_config(input_file) print(config) bm = BlockModel(np.array(config["BlockModel"]["matrix"]), n_nodes=config["BlockModel"]["n_nodes"], nodes_percentage=config["BlockModel"]["nodes_percentage"]) outpath = config["Simulations"]["output_folder"] suffix = config["Simulations"]["suffix"] for i in range(config["Simulations"]["n_simulated"]): bm.create_graph() bm.write_network(outpath + suffix + "_s_" + str(i) + "_network.tsv") bm.write_cluster_genelist(outpath + suffix + "_s_" + str(i) + "_genes.gmt") # bm.plot_graph(outpath+suffix+"_s_"+str(i)) def generate_sbm2_network(output_folder: 'folder where the simulations are saved', prefix: 'prefix for the simulations' = 'sbm', n_nodes: 'nodes in the network' = 1000, theta0: 'probability of connection in the cluster' = '0.9,0.7,0.5,0.2', percentage: 'percentage of nodes in cluster 0, use ratio 0.1 = 10 percent' = '0.1', density: 'multiplicative parameter used to define network density' = '0.06,0.1,0.2', n_simulations: 'number of simulated networks for each configuration' = 3 ): """ This function generates the simulated networks and genesets using the stochastic block model with 2 BLOCKS as described in the paper. The output names are going to be prefix_t_<theta0>_p_<percentage>_d_<density>_s_<n_simulation>_network.tsv or _genes.gmt One connected cluster while the rest of the network has the same probability of connection. SBM = d *[theta0, 1-theta0 1-theta0, 1-theta0] The simulator checks for connectedness of the generated network, if the generated net is not connected, a new simulation is generated. """ teta_ii = [float(i) for i in theta0.replace(' ', '').split(',')] percentages = [float(i) for i in percentage.replace(' ', '').split(',')] density = [float(i) for i in density.replace(' ', '').split(',')] n_simulated = int(n_simulations) n_nodes = int(n_nodes) for p in percentages: for t in teta_ii: for d in density: matrix = np.array([[d * t, d * (1 - t)], [d * (1 - t), d * (1 - t)]]) bm = BlockModel(matrix, n_nodes=n_nodes, nodes_percentage=[p, 1 - p]) for i in range(n_simulated): name = output_folder + prefix + "_t_" + str(t) + "_p_" + str(p) + "_d_" + str(d) + "_s_" + str(i) bm.create_graph() bm.write_network(name + "_network.tsv") bm.write_cluster_genelist(name + "_genes.gmt") ######################################################################### ####### COMMAND LINE FUNCTIONS ########################################## ######################################################################### def generate_gna_sbm( output_tsv: 'output_network', output_gmt: 'output geneset filename, this contains only the blocks', output_gmt2: 'mixture output geneset filename, this contains the mixture blocks'=None, N:'number of nodes in the network' = 1000, block_size:'size of the first 8 blocks' = 50, d:'baseline probability of connection, p0 in the paper' = 0.06, fc_cis:'positive within-block scaling factor for the probability of connection, Mii = fc_cis * d (alpha parameter in the paper)' = 2., fc_trans:'positive between-block scaling factor for the probability of connection, (beta parameter in the paper)' = .5, pi : 'percentage of block-i nodes for the genesets made of block-i and block-j. Use symmetrical values (5,95),use string comma separated' = '4,6,10,12,88,90,94,96', descriptor='crosstalk_sbm', sbm_matrix_figure: 'shows the blockmodel matrix' = None): """ This function generates benchmark network and geneset to test the crosstalk between two blocks. This function generates 4 blocks with d*fold change probability and other 4 blocks with d probability. The crosstalk is set both between the the first 4 blocks and the others. Make sure that 8*cluster_size < N """ clusters = 8 lc = N - (block_size*clusters) if lc < 1: logging.error('nodes are less than cluster groups') d =float(d) sizes = clusters*[block_size] sizes.append(lc) print(sizes) probs = d*np.ones((9,9)) #pp = np.tril(d/100*(1+np.random.randn(ncluster+1,ncluster+1))) A = fc_cis*d B = d + fc_trans*(d*(fc_cis-1)) probs[0,1] = B probs[2,3] = B probs[1,0] = B probs[3,2] = B probs[4,5] = B probs[6,7] = B probs[5,4] = B probs[7,6] = B probs[0,0] = A probs[1,1] = A probs[2,2] = A probs[3,3] = A if type(sbm_matrix_figure)==str: f,ax = plt.subplots(1) sns.heatmap(probs, ax = ax, cmap = 'YlOrRd', annot=True) f.savefig(sbm_matrix_figure) ncycle = 0 k = 0 while (k<N): g = nx.stochastic_block_model(sizes, probs) g = max(nx.connected_component_subgraphs(g), key=len) k = len(g) ncycle +=1 if ncycle > 20: logging.error('density is too low') H = nx.relabel_nodes(g, lambda x:'n'+str(x)) gmt_diz = {} nodes = list(H.nodes) for p,l in enumerate(H.graph['partition'][:-1]): if p<4: name = 'positive_'+str(p) else: name = 'null_'+str(p) ll = [nodes[i] for i in l] gmt_diz[name]={} gmt_diz[name]['genes']=ll gmt_diz[name]['descriptor']=descriptor if type(output_gmt2)==str: perc = [float(i) for i in pi.split(',')] logging.info('Generating mixes with perc = %s') gmt_diz2={} mix_dix = get_mix_genesets(gmt_diz, perc = perc) for name,i in mix_dix.items(): gmt_diz2[name]={} gmt_diz2[name]['genes']=i gmt_diz2[name]['descriptor']=descriptor output.print_GMT(gmt_diz2, output_gmt2) write_network(H, output_tsv) output.print_GMT(gmt_diz, output_gmt) print('Generated'+output_tsv) def generate_gnt_sbm( output_tsv: 'output network filename', output_gmt: 'output geneset filename, this contains only the blocks', N:'number of nodes in the network' = 1000, block_size: 'size of the first 6 blocks'= 50, d: 'baseline probability of connection, p0 in the paper' = 0.06, fold_change:'positive within-block scaling factor for the probability of connection, Mii = fold_change * d (alpha parameter in the paper)' = 2., descriptor:'descriptor for the gmt file'='mixed_sbm'): """ This function generates 3 blocks with d*fold_change probability and other 3 blocks with d probability. Make sure that 6*cluster_size < N """ lc = N - (block_size*6) if lc < 1: logging.error('nodes are less than cluster groups') d =float(d) sizes = 6*[block_size] sizes.append(lc) print(sizes) probs = d*np.ones((7,7)) #pp = np.tril(d/100*(1+np.random.randn(ncluster+1,ncluster+1))) probs[0,0]=fold_change*d probs[1,1]=fold_change*d probs[2,2]=fold_change*d ncycle = 0 k = 0 while (k<N): g = nx.stochastic_block_model(sizes, probs) g = max(nx.connected_component_subgraphs(g), key=len) k = len(g) ncycle +=1 if ncycle > 20: logging.error('density is too low') H = nx.relabel_nodes(g, lambda x:'n'+str(x)) gmt_diz = {} nodes = list(H.nodes) for p,l in enumerate(H.graph['partition'][:-1]): if p<3: name = 'positive_'+str(p) else: name = 'null_'+str(p) ll = [nodes[i] for i in l] gmt_diz[name]={} gmt_diz[name]['genes']=ll gmt_diz[name]['descriptor']=descriptor write_network(H, output_tsv) output.print_GMT(gmt_diz, output_gmt)
[ 11748, 3127, 87, 355, 299, 87, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 2603, 29487, 8019, 13, 8071, 2052, 355, 285, 8071, 2052, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 18931, 198, 6738, 12972, ...
2.252817
5,502
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
3.888889
9
import pandas as pd people_dict = { "weight": pd.Series([145, 182, 191],index=["joan", "bob", "mike"]), "birthyear": pd.Series([2002, 2000, 1999], index=["bob", "joan", "mike"], name="year"), "children": pd.Series([1, 2], index=["mike", "bob"]), "hobby": pd.Series(["Rock Climbing", "Scuba Diving", "Sailing"], index=["joan", "bob", "mike"]), } people = pd.DataFrame(people_dict) print ( people )
[ 11748, 19798, 292, 355, 279, 67, 198, 198, 15332, 62, 11600, 796, 1391, 198, 220, 220, 220, 220, 220, 220, 220, 366, 6551, 1298, 279, 67, 13, 27996, 26933, 18781, 11, 28581, 11, 31009, 4357, 9630, 28, 14692, 7639, 272, 1600, 366, 65...
2.20398
201
# # Copyright (C) 2014 Dominik Oepen # # This file is part of virtualsmartcard. # # virtualsmartcard 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 3 of the License, or (at your option) any # later version. # # virtualsmartcard is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # virtualsmartcard. If not, see <http://www.gnu.org/licenses/>. # import unittest from virtualsmartcard.SmartcardSAM import * if __name__ == "__main__": unittest.main() # CF = CryptoflexSE(None) # print CF.generate_public_key_pair(0x00, 0x80, "\x01\x00\x01\x00") # print MyCard._get_referenced_key(0x01)
[ 2, 198, 2, 15069, 357, 34, 8, 1946, 11817, 1134, 440, 538, 268, 198, 2, 198, 2, 770, 2393, 318, 636, 286, 7166, 27004, 9517, 13, 198, 2, 198, 2, 7166, 27004, 9517, 318, 1479, 3788, 25, 345, 460, 17678, 4163, 340, 290, 14, 273, ...
3.211039
308
############################################################### # _ _ _ _ _ # | |__ (_) ___ _ __ __ _ _ __| |_(_) ___| | ___ # | '_ \| |/ _ \| '_ \ / _` | '__| __| |/ __| |/ _ \ # | |_) | | (_) | |_) | (_| | | | |_| | (__| | __/ # |_.__/|_|\___/| .__/ \__,_|_| \__|_|\___|_|\___| # |_| # ############################################################### # # $ python3 runTableCases.py [CASES.CSV] [TEMPLATE.IN] -run # # Where: # - [CASES.CSV] path to csv file with the list of # parameters and the corresponding tags # - [TEMPLATE.IN] input file template for PFLOTRAN and # the corresponding tags # - [shouldRunPFLOTRAN = "-run"] # ############################################################### import numpy as np import matplotlib.pyplot as plt from pandas import read_csv from os import system import sys ## Global variables ColumnLenght = 50.0 ConcentrationAtInlet = 1.66E-16 ## Non-dimensional numbers ## Tags dictionary for variables in input file tagsReplaceable = { "Porosity" : "<porosity>", "DarcyVel" : "<darcyVel>", # q = u*porosity "CleanTime" : "<elutionTime>", # t @ C0 = 0 "FinalTime" : "<endTime>", # @ 10 pore volumes "AttachRate": "<katt>", "DetachRate": "<kdet>", "DecayAq" : "<decayAq>", "DecayIm" : "<decayIm>", "LongDisp" : "<longDisp>" } ## Tags dictionary for other parameters tagsAccesory = { "FlowVel" : "poreWaterVel", "PoreVol" : "poreVolume", "pH" : "pH", "IonicStr" : "IS" } ## Path to PFLOTRAN executable PFLOTRAN_path = "$PFLOTRAN_DIR/src/pflotran/pflotran " ## Table with the set of parameters try: parameters_file = str(sys.argv[1]) except IndexError: sys.exit("Parameters file not defined :(") setParameters = read_csv(parameters_file) total_rows = setParameters.shape[0] ## Template for the PFLOTRAN input file try: template_file = str(sys.argv[2]) except IndexError: sys.exit("Template file not found :(") ## Run cases? try: shouldRunPFLOTRAN = "-run" in str(sys.argv[3]) except IndexError: shouldRunPFLOTRAN = False ## Delete previous cases system("rm -rf CASE*") ## Row in the set of parameters table = case to be run for i in range(total_rows): #for i in range(1): ## Create a folder for the case current_folder = "./CASE_" + "{0:03}".format(i+1) system("mkdir " + current_folder) ## Copy template input file to folder system("cp " + template_file + " " + current_folder+"/pflotran.in") current_file = current_folder + "/pflotran.in" ## Replace tags for values in case for current_tag in tagsReplaceable: COMM = "sed -i 's/" + tagsReplaceable[current_tag] + "/"\ +'{:.3E}'.format(setParameters.loc[i,tagsReplaceable[current_tag]])\ + "/g' " + current_file system(COMM) ## Run PFLOTRAN in that case if shouldRunPFLOTRAN: #print(PFLOTRAN_path + "-pflotranin " + current_file) system(PFLOTRAN_path + "-pflotranin " + current_file) #system("python3 ./miscellaneous/organizeResults.py " + current_folder + "/pflotran-obs-0.tec -clean") current_U = setParameters.loc[i,tagsAccesory["FlowVel"]] current_pH = setParameters.loc[i,tagsAccesory["pH"]] current_IS = setParameters.loc[i,tagsAccesory["IonicStr"]] current_PV = setParameters.loc[i,tagsAccesory["PoreVol"]] #Porosity = setParameters.loc[i,tagsReplaceable["Porosity"]] #input("Press Enter to continue...") plotResults(current_U,current_pH,current_IS,current_PV,\ setParameters.loc[i,tagsReplaceable["AttachRate"]],\ setParameters.loc[i,tagsReplaceable["DetachRate"]],\ setParameters.loc[i,tagsReplaceable["DecayAq"]],\ setParameters.loc[i,tagsReplaceable["DecayIm"]],\ setParameters.loc[i,tagsReplaceable["LongDisp"]]) #input("Press Enter to continue...") system("rm -r pictures ; mkdir pictures") system("cp CASE**/*.png ./pictures/")
[ 29113, 14468, 7804, 4242, 21017, 198, 2, 220, 4808, 220, 220, 220, 220, 4808, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 4808, 220, 220, 4808, 220, 220, 220, ...
2.482824
1,572
#!/usr/bin/python3 # # This software is covered by The Unlicense license # import os, pymongo, sys if __name__ == '__main__': try: main() except KeyboardInterrupt: print('Interrupted') try: sys.exit(0) except SystemExit: os._exit(0)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 2, 198, 2, 770, 3788, 318, 5017, 416, 383, 791, 43085, 5964, 198, 2, 198, 198, 11748, 28686, 11, 279, 4948, 25162, 11, 25064, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 124...
2.111888
143
# -*- coding: utf-8 -*-
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 628 ]
1.785714
14
import time import torch from torch import nn from torch.nn import functional as F #import spconv import torchplus from torchplus.nn import Empty, GroupNorm, Sequential from torchplus.ops.array_ops import gather_nd, scatter_nd from torchplus.tools import change_default_args import sys if '/opt/ros/kinetic/lib/python2.7/dist-packages' in sys.path: sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
[ 11748, 640, 198, 198, 11748, 28034, 198, 6738, 28034, 1330, 299, 77, 198, 6738, 28034, 13, 20471, 1330, 10345, 355, 376, 198, 2, 11748, 599, 42946, 198, 11748, 28034, 9541, 198, 6738, 28034, 9541, 13, 20471, 1330, 33523, 11, 4912, 35393...
3.142857
133
import string from typing import List, Dict # inject code here # _HYPHEN_CHARS = { '\u002D', # HYPHEN-MINUS '\u00AD', # SOFT HYPHEN '\u2010', # HYPHEN '\u2011', # NON-BREAKING HYPHEN }
[ 11748, 4731, 198, 6738, 19720, 1330, 7343, 11, 360, 713, 198, 2, 8677, 2438, 994, 1303, 628, 628, 628, 628, 198, 62, 42598, 11909, 1677, 62, 3398, 27415, 796, 1391, 198, 220, 220, 220, 705, 59, 84, 21601, 35, 3256, 220, 1303, 43624,...
2.14
100
from django.conf.urls import include from django.urls import path from django.contrib import admin from users.views import FacebookLogin import django_js_reverse.views from rest_framework.routers import DefaultRouter from common.routes import routes as common_routes router = DefaultRouter() routes = common_routes for route in routes: router.register(route['regex'], route['viewset'], basename=route['basename']) urlpatterns = [ path("", include("common.urls"), name="common"), path("assignments/", include("assignments.urls"), name='assignments'), path('api-auth/', include('rest_framework.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), path('rest-auth/facebook/', FacebookLogin.as_view(), name='fb_login'), path("admin/", admin.site.urls, name="admin"), path("jsreverse/", django_js_reverse.views.urls_js, name="js_reverse"), path("api/", include(router.urls), name="api"), path("api/assignments/", include("assignments.api.assignment.urls")), path("api/grade-assignment/", include("assignments.api.graded-assignment.urls")), path("api/", include("users.urls"), name="user"), ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 2291, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 2985, 13, 33571, 1330, 3203, 47790, 198, 198, 11748, 42625, 1420...
2.76392
449
import numpy as np from path import Path import random import pickle import torch import os import cv2 def load_as_float(path): """Loads image""" im = cv2.imread(path) im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB).astype(np.float32) return im
[ 11748, 299, 32152, 355, 45941, 201, 198, 6738, 3108, 1330, 10644, 201, 198, 11748, 4738, 201, 198, 11748, 2298, 293, 201, 198, 11748, 28034, 197, 201, 198, 11748, 28686, 201, 198, 11748, 269, 85, 17, 201, 198, 201, 198, 4299, 3440, 62...
2.229508
122
import Queue import select import socket from conf import ADDRESS, BACKLOG, SIZE server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setblocking(0) print 'starting up on %s port %s' % ADDRESS server.bind(ADDRESS) server.listen(BACKLOG) inputs = [server] outputs = [] message_queues = {} while inputs: readable, writable, exceptional = select.select(inputs, outputs, inputs) for s in readable: if s is server: connection, client_address = s.accept() print 'new connection from', client_address connection.setblocking(0) inputs.append(connection) message_queues[connection] = Queue.Queue() else: data = s.recv(SIZE) if data: print 'received from %s' % str(s.getpeername()) message_queues[s].put(data) if s not in outputs: outputs.append(s) else: print 'closing socket after reading no data' inputs.remove(s) s.close() del message_queues[s] for s in writable: try: next_msg = message_queues[s].get_nowait() print 'sending to %s' % str(s.getpeername()) s.send(next_msg) except Queue.Empty: print 'output queue for', s.getpeername(), 'is empty' outputs.remove(s) for s in exceptional: print 'handling exceptional condition for', s.getpeername() inputs.remove(s) if s in outputs: outputs.remove(s) s.close() del message_queues[s]
[ 11748, 4670, 518, 198, 11748, 2922, 198, 11748, 17802, 198, 198, 6738, 1013, 1330, 5984, 7707, 7597, 11, 28767, 25294, 11, 311, 35400, 198, 198, 15388, 796, 17802, 13, 44971, 7, 44971, 13, 8579, 62, 1268, 2767, 11, 17802, 13, 50, 1129...
2.092308
780
import re import copy from collections import defaultdict from string import Template # initialize the dictionary for the methods with checked exceptions such as {fake method: real method} method_dict_checked = {'deleteRecord' : 'delete', \ 'editText' : 'setText_new', \ 'insertData' : 'insert_new', \ 'setLayout' : 'setContentView_new', \ 'findViewId' : 'findViewById_new', \ 'changeTextColor' : 'setTextColor_new', \ 'getCursorString' : 'getString', \ 'queryData' : 'query_new', \ 'updateRecord' : 'update', \ 'drawTxt' : 'drawText_new'} # initialize the dictionary for the methods with unchecked exceptions such as {fake method: real method} method_dict_unchecked = {'deleteRecord' : 'delete', \ 'editText' : 'setText', \ 'insertData' : 'insert', \ 'setLayout' : 'setContentView', \ 'findViewId' : 'findViewById', \ 'changeTextColor' : 'setTextColor', \ 'getCursorString' : 'getString', \ 'queryData' : 'query', \ 'updateRecord' : 'update', \ 'drawTxt' : 'drawText'} # answer_block is a dict of user's answers, # i.e. answer_block = {'answer_1' : fake_answer} # survey type refers to the different surveys # (methods with checked exceptions Vs. methods with unchecked exceptions--documented and undocumented) # Bind the answers' methods to the real Android's API methods # answers is a dict, i.e. answers = {'answer_1' : fake_answer} # This function returns a dict of answers with real Android's # API methods, i.e. real_answers = {'answer_1' : real_answer} # dict depending on the survey type # replace line numbers with spaces # vim: tabstop=8 noexpandtab shiftwidth=8 softtabstop=0
[ 11748, 302, 198, 11748, 4866, 198, 198, 6738, 17268, 1330, 4277, 11600, 198, 6738, 4731, 1330, 37350, 198, 198, 2, 41216, 262, 22155, 329, 262, 5050, 351, 10667, 13269, 884, 355, 1391, 30706, 2446, 25, 1103, 2446, 92, 198, 24396, 62, ...
3.081132
530
# a = 1 # b = 1 # while (not ((a==0) and (b==0))): # a, b = map(int, input().split()) # print(a+b) while True: a, b = map(int, input().split()) if a == 0 and b == 0: break print(a+b)
[ 2, 257, 796, 352, 198, 2, 275, 796, 352, 198, 2, 981, 357, 1662, 14808, 64, 855, 15, 8, 290, 357, 65, 855, 15, 4008, 2599, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 257, 11, 275, 796, 3975, 7, 600, 11, 5128, 22446, 353...
1.6
170
from builtins import str from .helpers import run import logging import subprocess import functools import types logger = logging.getLogger("commander") def maestro(scriptId): """Run a Keyboard Maestro script by ID (more robust) or name.""" run( """osascript -e 'tell application "Keyboard Maestro Engine" to """ """do script "%s"'\n""" % scriptId )
[ 6738, 3170, 1040, 1330, 965, 198, 6738, 764, 16794, 364, 1330, 1057, 198, 11748, 18931, 198, 11748, 850, 14681, 198, 11748, 1257, 310, 10141, 198, 11748, 3858, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7203, 9503, 4066, 4...
2.976563
128
from planning_system.db.schema.views import _get_set_cols def definition(session): """ Return UI view. Complex view, which requires a dynamic pivot. """ pvt_list = _get_set_cols(session) sql = f""" SELECT costc, summary_code, summary, section, supersection, summary_order, sec_order, super_order, level, {pvt_list} FROM (SELECT costc, summary_code, summary, section, supersection, summary_order, sec_order, super_order, level, CAST(f_Set.acad_year as CHAR(4)) + ' ' + f_set.set_cat_id as finance_summary, amount as amount FROM [v_mri_finance_grouped_subtotal] f INNER JOIN f_set ON f_set.set_id = f.set_id) p PIVOT (SUM(amount) FOR finance_summary in ({pvt_list})) as pvt """ return sql
[ 6738, 5410, 62, 10057, 13, 9945, 13, 15952, 2611, 13, 33571, 1330, 4808, 1136, 62, 2617, 62, 4033, 82, 628, 198, 4299, 6770, 7, 29891, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 8229, 12454, 1570, 13, 628, 220, 220, 220, ...
2.504918
305
import torch import torchvision.models as models ''' Description: convert torch module to JIT TracedModule. torch JIT TracedModule ''' if __name__ == "__main__": dummy_input = torch.randn(1, 3, 224, 224) # dummy_input is customized by user model = models.resnet18(pretrained=True) # model is customized by user model = model.cpu().eval() traced_model = torch.jit.trace(model, dummy_input) model_name = 'model_name' # model_name is customized by user TracedModelFactory(model_name + '.pth', traced_model)
[ 11748, 28034, 198, 11748, 28034, 10178, 13, 27530, 355, 4981, 198, 198, 7061, 6, 198, 11828, 25, 198, 220, 220, 220, 10385, 28034, 8265, 284, 449, 2043, 833, 2286, 26796, 13, 628, 220, 220, 220, 28034, 220, 449, 2043, 833, 2286, 26796...
2.879581
191
# cppsimdata.py # written by Michael H. Perrott # with minor modifications by Doug Pastorello to work with both Python 2.7 and Python 3.4 # available at www.cppsim.com as part of the CppSim package # Copyright (c) 2013-2017 by Michael H. Perrott # This file is disributed under the MIT license (see Copying file) import ctypes as ct import numpy as np import sys import os import platform import subprocess as sp import contextlib from scipy.signal import lfilter,welch def cppsim_unbuffer_for_print(status, stream='stdout'): newline_chars = ['\r', '\n', '\r\n'] stream = getattr(status, stream) with contextlib.closing(stream): while True: out = [] last = stream.read(1) if last == '' and status.poll() is not None: break while last not in newline_chars: if last == '' and status.poll() is not None: break out.append(last) last = stream.read(1) out = ''.join(out) yield out def cppsim(sim_file="test.par"): if sim_file.find('.par') < 0: sim_file = sim_file + '.par' cppsim_home = os.getenv('CppSimHome') if cppsim_home == None: cppsim_home = os.getenv('CPPSIMHOME') if cppsim_home == None: home = os.getenv('HOME') if sys.platform == 'win32': default_cppsim_home = "%s\\CppSim" % (home) else: default_cppsim_home = "%s/CppSim" % (home) if os.path.isdir(default_cppsim_home): cppsim_home = default_cppsim_home else: print('Error running cppsim from Python: environment variable') print(' CPPSIMHOME is undefined') cppsimshared_home = os.getenv('CppSimSharedHome') if cppsimshared_home == None: cppsimshared_home = os.getenv('CPPSIMSHAREDHOME') if cppsimshared_home == None: if sys.platform == 'win32': default_cppsimshared_home = "%s\\CppSimShared" % (cppsim_home) else: default_cppsimshared_home = "%s/CppSimShared" % (cppsim_home) if os.path.isdir(default_cppsimshared_home): cppsimshared_home = default_cppsimshared_home else: print('Error running cppsim: environment variable') print(' CPPSIMSHAREDHOME is undefined') # print('cppsimhome: %s' % cppsim_home) # print('cppsimsharedhome: %s' % cppsimshared_home) cur_dir = os.getcwd() if sys.platform == 'win32': i = cur_dir.lower().find('\\simruns\\') else: i = cur_dir.lower().find('/simruns/') if i < 0: print('Error running cppsim: you need to run this Python script') print(' in a directory of form:') if sys.platform == 'win32': print(' .....\\SimRuns\\Library_name\\Module_name') else: print(' ...../SimRuns/Library_name/Module_name') print(' -> in this case, you ran in directory:') print(' %s' % cur_dir) sys.exit() library_cell = cur_dir[i+9:1000] if sys.platform == 'win32': i = library_cell.find('\\') else: i = library_cell.find('/') if i < 0: print('Error running cppsim: you need to run this Python script') print(' in a directory of form:') print(' ...../SimRuns/Library_name/Module_name') print(' -> in this case, you ran in directory:') print(' %s' % cur_dir) sys.exit() library_name = library_cell[0:i] cell_name = library_cell[i+1:1000] print("Running CppSim on module '%s' (Lib:'%s'):" % (cell_name, library_name)) print("\n... netlisting ...\n") if sys.platform == 'win32': rp_base = '%s/Sue2/bin/win32/sue_cppsim_netlister' % (cppsimshared_home) else: rp_base = '%s/Sue2/bin/sue_cppsim_netlister' % (cppsimshared_home) rp_arg1 = cell_name rp_arg2 = '%s/Sue2/sue.lib' % (cppsim_home) rp_arg3 = '%s/Netlist/netlist.cppsim' % (cppsim_home) rp = [rp_base, rp_arg1, rp_arg2, rp_arg3] status = sp.Popen(rp, stdout=sp.PIPE, stderr=sp.STDOUT, universal_newlines=True) for line in cppsim_unbuffer_for_print(status): print(line) if status.returncode != 0: print('************** ERROR: exited CppSim run prematurely! ****************') sys.exit() print('\n... running net2code ...\n') if sys.platform == 'win32': rp_base = '%s/bin/win32/net2code' % (cppsimshared_home) else: rp_base = '%s/bin/net2code' % (cppsimshared_home) rp_arg1 = '-cpp' rp_arg2 = sim_file rp = [rp_base, rp_arg1, rp_arg2] status = sp.Popen(rp, stdout=sp.PIPE, stderr=sp.STDOUT, universal_newlines=True) for line in cppsim_unbuffer_for_print(status): print(line) if status.returncode != 0: print('************** ERROR: exited CppSim run prematurely! ****************') sys.exit() print('... compiling ...\n') if sys.platform == 'win32': rp_base = '%s/msys/bin/make' % (cppsimshared_home) else: rp_base = 'make' rp = [rp_base] status = sp.Popen(rp, stdout=sp.PIPE, stderr=sp.STDOUT, universal_newlines=True) for line in cppsim_unbuffer_for_print(status): print(line) if status.returncode != 0: print('************** ERROR: exited CppSim run prematurely! ****************') sys.exit() # calculate phase noise: returns frequency (Hz) and specral density (dBc/Hz)
[ 2, 269, 381, 14323, 7890, 13, 9078, 198, 2, 3194, 416, 3899, 367, 13, 2448, 305, 926, 198, 2, 351, 4159, 19008, 416, 15115, 11303, 382, 18798, 284, 670, 351, 1111, 11361, 362, 13, 22, 290, 11361, 513, 13, 19, 198, 2, 1695, 379, ...
2.244889
2,397
# Lambda processing
[ 628, 628, 198, 2, 21114, 6814, 7587, 628, 628 ]
3.111111
9
import logging from datetime import datetime from typing import List from notify.backends import BackendFactory from notify.commands import Command from notify.config import Config, Stack from notify.notifications import Factory, Notification from notify.strategies import StrategyFactory
[ 11748, 18931, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 19720, 1330, 7343, 198, 198, 6738, 19361, 13, 1891, 2412, 1330, 5157, 437, 22810, 198, 6738, 19361, 13, 9503, 1746, 1330, 9455, 198, 6738, 19361, 13, 11250, 1330, 17056, ...
4.578125
64
technology = { 'kb': ''' Oculus(rift) HTC(vive) VR(Zuck, rift) VR(Gabe, vive) (Oculus(O) & HTC(H)) ==> Dominates(H, O) (VR(V)) ==> Technology(T) ''', 'queries':''' VR(x) Dominates(x, y) ''', } Examples = { 'technology': technology, }
[ 45503, 796, 1391, 198, 220, 220, 220, 705, 32812, 10354, 705, 7061, 198, 46, 17576, 7, 35357, 8, 198, 39, 4825, 7, 85, 425, 8, 198, 13024, 7, 57, 1347, 11, 36788, 8, 198, 13024, 7, 38, 11231, 11, 410, 425, 8, 198, 7, 46, 17576...
1.984375
128
import logging import multiprocessing import os import time from functools import partial from multiprocessing import Process, Queue, Pool from typing import Iterable import pandas as pd import pyarrow as pa from feast.feature_set import FeatureSet from feast.type_map import convert_dict_to_proto_values from feast.types.FeatureRow_pb2 import FeatureRow from kafka import KafkaProducer from tqdm import tqdm from feast.constants import DATETIME_COLUMN _logger = logging.getLogger(__name__) GRPC_CONNECTION_TIMEOUT_DEFAULT = 3 # type: int GRPC_CONNECTION_TIMEOUT_APPLY = 300 # type: int FEAST_SERVING_URL_ENV_KEY = "FEAST_SERVING_URL" # type: str FEAST_CORE_URL_ENV_KEY = "FEAST_CORE_URL" # type: str BATCH_FEATURE_REQUEST_WAIT_TIME_SECONDS = 300 CPU_COUNT = os.cpu_count() # type: int KAFKA_CHUNK_PRODUCTION_TIMEOUT = 120 # type: int def _kafka_feature_row_producer( feature_row_queue: Queue, row_count: int, brokers, topic, ctx: dict, pbar: tqdm ): """ Pushes Feature Rows to Kafka. Reads rows from a queue. Function will run until total row_count is reached. Args: feature_row_queue: Queue containing feature rows. row_count: Total row count to process brokers: Broker to push to topic: Topic to push to ctx: Context dict used to communicate with primary process pbar: Progress bar object """ # Callback for failed production to Kafka # Callback for succeeded production to Kafka producer = KafkaProducer(bootstrap_servers=brokers) processed_rows = 0 # Loop through feature rows until all rows are processed while processed_rows < row_count: # Wait if queue is empty if feature_row_queue.empty(): time.sleep(1) producer.flush(timeout=KAFKA_CHUNK_PRODUCTION_TIMEOUT) else: while not feature_row_queue.empty(): row = feature_row_queue.get() if row is not None: # Push row to Kafka producer.send(topic, row.SerializeToString()).add_callback( on_success ).add_errback(on_error) processed_rows += 1 # Force an occasional flush if processed_rows % 10000 == 0: producer.flush(timeout=KAFKA_CHUNK_PRODUCTION_TIMEOUT) del row pbar.refresh() # Ensure that all rows are pushed producer.flush(timeout=KAFKA_CHUNK_PRODUCTION_TIMEOUT) # Using progress bar as counter is much faster than incrementing dict ctx["success_count"] = pbar.n pbar.close() def ingest_table_to_kafka( feature_set: FeatureSet, table: pa.lib.Table, max_workers: int, chunk_size: int = 5000, disable_pbar: bool = False, timeout: int = None, ) -> None: """ Ingest a PyArrow Table to a Kafka topic based for a Feature Set Args: feature_set: FeatureSet describing PyArrow table. table: PyArrow table to be processed. max_workers: Maximum number of workers. chunk_size: Maximum size of each chunk when PyArrow table is batched. disable_pbar: Flag to indicate if tqdm progress bar should be disabled. timeout: Maximum time before method times out """ pbar = tqdm(unit="rows", total=table.num_rows, disable=disable_pbar) # Use a small DataFrame to validate feature set schema ref_df = table.to_batches(max_chunksize=100)[0].to_pandas() df_datetime_dtype = ref_df[DATETIME_COLUMN].dtype # Validate feature set schema _validate_dataframe(ref_df, feature_set) # Create queue through which encoding and production will coordinate row_queue = Queue() # Create a context object to send and receive information across processes ctx = multiprocessing.Manager().dict( {"success_count": 0, "error_count": 0, "last_exception": ""} ) # Create producer to push feature rows to Kafka ingestion_process = Process( target=_kafka_feature_row_producer, args=( row_queue, table.num_rows, feature_set.get_kafka_source_brokers(), feature_set.get_kafka_source_topic(), ctx, pbar, ), ) try: # Start ingestion process print( f"\n(ingest table to kafka) Ingestion started for {feature_set.name}:{feature_set.version}" ) ingestion_process.start() # Iterate over chunks in the table and return feature rows for row in _encode_pa_chunks( tbl=table, fs=feature_set, max_workers=max_workers, chunk_size=chunk_size, df_datetime_dtype=df_datetime_dtype, ): # Push rows onto a queue for the production process to pick up row_queue.put(row) while row_queue.qsize() > chunk_size: time.sleep(0.1) row_queue.put(None) except Exception as ex: _logger.error(f"Exception occurred: {ex}") finally: # Wait for the Kafka production to complete ingestion_process.join(timeout=timeout) failed_message = ( "" if ctx["error_count"] == 0 else f"\nFail: {ctx['error_count']}/{table.num_rows}" ) last_exception_message = ( "" if ctx["last_exception"] == "" else f"\nLast exception:\n{ctx['last_exception']}" ) print( f"\nIngestion statistics:" f"\nSuccess: {ctx['success_count']}/{table.num_rows}" f"{failed_message}" f"{last_exception_message}" ) def _validate_dataframe(dataframe: pd.DataFrame, feature_set: FeatureSet): """ Validates a Pandas dataframe based on a feature set Args: dataframe: Pandas dataframe feature_set: Feature Set instance """ if "datetime" not in dataframe.columns: raise ValueError( f'Dataframe does not contain entity "datetime" in columns {dataframe.columns}' ) for entity in feature_set.entities: if entity.name not in dataframe.columns: raise ValueError( f"Dataframe does not contain entity {entity.name} in columns {dataframe.columns}" ) for feature in feature_set.features: if feature.name not in dataframe.columns: raise ValueError( f"Dataframe does not contain feature {feature.name} in columns {dataframe.columns}" )
[ 11748, 18931, 198, 11748, 18540, 305, 919, 278, 198, 11748, 28686, 198, 11748, 640, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 6738, 18540, 305, 919, 278, 1330, 10854, 11, 4670, 518, 11, 19850, 198, 6738, 19720, 1330, 40806, 540, 19...
2.323229
2,837
import collections s = "abcd" t = "abcde" p = Solution() print(p.findTheDifference(s,t))
[ 11748, 17268, 198, 82, 796, 366, 397, 10210, 1, 198, 83, 796, 366, 39305, 2934, 1, 198, 79, 796, 28186, 3419, 198, 4798, 7, 79, 13, 19796, 464, 28813, 1945, 7, 82, 11, 83, 4008 ]
2.514286
35
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = ['BackendAddressPoolAddressArgs', 'BackendAddressPoolAddress'] class BackendAddressPoolAddress(pulumi.CustomResource): def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(BackendAddressPoolAddressArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, backend_address_pool_id: Optional[pulumi.Input[str]] = None, ip_address: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, virtual_network_id: Optional[pulumi.Input[str]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = BackendAddressPoolAddressArgs.__new__(BackendAddressPoolAddressArgs) if backend_address_pool_id is None and not opts.urn: raise TypeError("Missing required property 'backend_address_pool_id'") __props__.__dict__["backend_address_pool_id"] = backend_address_pool_id if ip_address is None and not opts.urn: raise TypeError("Missing required property 'ip_address'") __props__.__dict__["ip_address"] = ip_address __props__.__dict__["name"] = name if virtual_network_id is None and not opts.urn: raise TypeError("Missing required property 'virtual_network_id'") __props__.__dict__["virtual_network_id"] = virtual_network_id super(BackendAddressPoolAddress, __self__).__init__( 'azure:lb/backendAddressPoolAddress:BackendAddressPoolAddress', resource_name, __props__, opts)
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 21624, 12994, 24118, 687, 10290, 357, 27110, 5235, 8, 16984, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760...
2.394692
1,168
# -*- coding: utf-8 -*- import pickle import os # third-party imports import jsonpickle def writeOutSubmissionsAsJson(redditList, file): file.write('{\n'.encode('utf8')) for submission in redditList: outputString = submission.getJson() + u',\n' file.write(outputString.encode('utf8')) file.write('}'.encode('utf8')) def saveSubmissionsAsJson(submissions, fileName): outputFile = open(fileName, 'wb') writeOutSubmissionsAsJson(submissions, outputFile) outputFile.close() def writeOutSubmissionsAsHtml(redditList, file): submissionsStr = "" for submission in redditList: submissionsStr += submission.getHtml() + u'\n' htmlStructure = u"""<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Reddit Saved Comments</title> </head> <body> {0} </body> </html> """.format(submissionsStr) file.write(htmlStructure.encode('utf8')) def saveSubmissionsAsHtml(submissions, fileName): outputFile = open(fileName, 'wb') writeOutSubmissionsAsHtml(submissions, outputFile) outputFile.close() def writeOutSubmissionsAsXML(redditList, file): for submission in redditList: outputString = u'<submission>\n' + submission.getXML() + u'</submission>\n' file.write(outputString.encode('utf8'))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 2298, 293, 198, 11748, 28686, 198, 198, 2, 2368, 12, 10608, 17944, 198, 11748, 33918, 27729, 293, 198, 198, 4299, 3551, 7975, 7004, 8481, 1722, 41, 1559, 7, ...
2.536538
520
#!/usr/bin/env python3.7 from decimal import Decimal from collections import namedtuple EventPrizeLevel = namedtuple( "EventPrizeLevel", ["packs", "gems", "gold"], defaults=[0, 0, 0], )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 13, 22, 198, 6738, 32465, 1330, 4280, 4402, 198, 6738, 17268, 1330, 3706, 83, 29291, 198, 198, 9237, 34487, 2736, 4971, 796, 3706, 83, 29291, 7, 198, 220, 220, 220, 366, 9237, 34487, ...
2.893939
66
""" Escreva um programa que faa o computador 'Pensar' em um nmero inteiro entre 0 e 5 e pea para o usurio tentar descobrir qual foi o nmero escolhido pelo computador. """ from random import randint numero_gerado_aleatoriamente = randint(0,5) numero_digitado_pelo_usuario = int(input('Adivinhe qual nmero estou pensando, uma dica: entre 0 e 5! ')) if numero_digitado_pelo_usuario == numero_gerado_aleatoriamente: print(f'VOC ACERTOU! O nmero que estava pensando era mesmo o {numero_gerado_aleatoriamente}!') else: print(f'Voc errou! O nmero que pensei era {numero_gerado_aleatoriamente}')
[ 37811, 198, 220, 220, 220, 16319, 260, 6862, 23781, 1430, 64, 8358, 277, 7252, 220, 267, 2653, 7079, 705, 47, 641, 283, 6, 795, 23781, 299, 647, 78, 493, 68, 7058, 920, 260, 657, 304, 642, 198, 220, 220, 220, 304, 613, 64, 31215, ...
2.449799
249
import torch.nn as nn import torch.nn.functional as F from torch_geometric.nn import GCNConv, GATConv
[ 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 198, 6738, 28034, 62, 469, 16996, 13, 20471, 1330, 20145, 45, 3103, 85, 11, 402, 1404, 3103, 85, 628, 198 ]
2.837838
37
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # File : scene_graph.py # Author : Jiayuan Mao # Email : maojiayuan@gmail.com # Date : 07/19/2018 # # This file is part of NSCL-PyTorch. # Distributed under terms of the MIT license. """ Scene Graph generation. """ import os import torch import torch.nn as nn import jactorch import jactorch.nn as jacnn from . import functional DEBUG = bool(int(os.getenv('DEBUG_SCENE_GRAPH', 0))) __all__ = ['SceneGraph']
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 9220, 220, 220, 1058, 3715, 62, 34960, 13, 9078, 198, 2, 6434, 1058, 29380, 323, 7258, 22828, 198, 2, 9570...
2.638418
177
import re from abc import ABCMeta from dateutil import parser
[ 11748, 302, 198, 6738, 450, 66, 1330, 9738, 48526, 198, 6738, 3128, 22602, 1330, 30751, 628 ]
3.9375
16
import unittest import networkx as nx from core.placement.spsolver import DPShortestPathSolver if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 11748, 3127, 87, 355, 299, 87, 198, 6738, 4755, 13, 489, 5592, 13, 82, 862, 14375, 1330, 27704, 16438, 395, 15235, 50, 14375, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 2...
2.576271
59
""" # INTEGER BREAK Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get. Example 1: Input: 2 Output: 1 Explanation: 2 = 1 + 1, 1 1 = 1. Example 2: Input: 10 Output: 36 Explanation: 10 = 3 + 3 + 4, 3 3 4 = 36. Note: You may assume that n is not less than 2 and not larger than 58. """
[ 37811, 220, 198, 2, 17828, 7156, 1137, 29377, 10206, 198, 198, 15056, 257, 3967, 18253, 299, 11, 2270, 340, 656, 262, 2160, 286, 379, 1551, 734, 3967, 37014, 290, 20487, 262, 1720, 286, 883, 37014, 13, 8229, 262, 5415, 1720, 345, 460,...
2.971429
140
#!/usr/bin/env python from distutils.core import setup SHORT_DESCR = "CAmera MOtion COMPensation using image stiching techniques to generate stabilized videos" try: LONG_DESCR = open('README.rst').read() except IOError: LONG_DESCR = SHORT_DESCR setup( name='camocomp', version='0.1', author='Adrien Gaidon', author_email='easy_to_guess@googleme.com', keywords='camera motion compensation, video stabilization, stitching, opencv, hugin', packages=['camocomp'], url='http://pypi.python.org/pypi/camocomp/', license='New BSD License', description=SHORT_DESCR, long_description=LONG_DESCR, platforms=["Linux"], requires=['numpy', 'ffmpeg', 'cv2', 'hsi'], scripts=['scripts/camocomp_video'], classifiers=[ 'Intended Audience :: Science/Research', 'Intended Audience :: Developers', 'License :: OSI Approved', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Scientific/Engineering', 'Operating System :: POSIX :: Linux', 'Operating System :: Unix', ] )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 1233, 26791, 13, 7295, 1330, 9058, 198, 198, 9693, 9863, 62, 30910, 9419, 796, 366, 8141, 647, 64, 13070, 5378, 24301, 25742, 1262, 2939, 336, 488, 278, 7605, 284, 7716, 449...
2.598131
428
from flask import Flask, render_template app = Flask(__name__) # app.add_template_filter(li_reverse, 'li_rv') # if __name__ == "__main__": app.run(debug=True)
[ 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 198, 198, 1324, 796, 46947, 7, 834, 3672, 834, 8, 628, 628, 198, 2, 598, 13, 2860, 62, 28243, 62, 24455, 7, 4528, 62, 50188, 11, 705, 4528, 62, 81, 85, 11537, 220, 1303, 220, 220, 6...
2.507246
69
"""""" import matplotlib as mpl __all__ = ["set"] def set(tick_scale=1, rc=dict()): """ Control plot style and scaling using seaborn and the matplotlib rcParams interface. :param tick_scale: A scaler number controling the spacing on tick marks, defaults to 1. :type tick_scale: float :param rc: Additional settings to pass to rcParams. :type rc: dict """ rc_log_defaults = { 'xtick.major.size': 10. * tick_scale, 'xtick.minor.size': 6. * tick_scale, 'ytick.major.size': 10. * tick_scale, 'ytick.minor.size': 6. * tick_scale, 'xtick.color': '0.0', 'ytick.color': '0.0', 'axes.linewidth': 1.75, 'mathtext.default': 'regular' } mpl.rcParams.update(dict(rc_log_defaults, **rc))
[ 15931, 15931, 15931, 198, 198, 11748, 2603, 29487, 8019, 355, 285, 489, 198, 198, 834, 439, 834, 796, 14631, 2617, 8973, 198, 198, 4299, 900, 7, 42298, 62, 9888, 28, 16, 11, 48321, 28, 11600, 3419, 2599, 198, 220, 220, 220, 37227, 1...
2.200549
364
# M1 myresult = mul1(3) print(myresult(7)) #M-2 mul = lambda a = 3: (lambda b: a*b) myres = mul() print(myres) print(myres(7))
[ 2, 337, 16, 198, 1820, 20274, 796, 35971, 16, 7, 18, 8, 198, 4798, 7, 1820, 20274, 7, 22, 4008, 198, 198, 2, 44, 12, 17, 198, 76, 377, 796, 37456, 257, 796, 513, 25, 357, 50033, 275, 25, 257, 9, 65, 8, 198, 1820, 411, 796, ...
2
64
from enum import Enum, auto from typing import NamedTuple, Optional
[ 6738, 33829, 1330, 2039, 388, 11, 8295, 198, 6738, 19720, 1330, 34441, 51, 29291, 11, 32233, 628 ]
4.058824
17
# -*- coding: utf-8 -*- import numpy as np from odbAccess import * from abaqusConstants import * filename = 'Job-4e-SS-Pulse' """ LOAD DATA =============================================================================== """ results = np.load(filename + '.npz') vonMisesMax = results['vonMisesMax'].transpose() vonMisesMin = results['vonMisesMin'].transpose() vonMisesStatic = results['vonMisesStatic'].transpose() nodeNum = results['nodeNum'].transpose() nodeCoord = results['nodeCoord'] # Sort nodeCoord on nodal values nodeCoord = nodeCoord[nodeCoord[:,0].argsort()] # Calculate Mean and Amplitude vonMisesAmp = (vonMisesMax - vonMisesMin)/2 vonMisesMean = (vonMisesMax + vonMisesMin)/2 """ LOAD ODB =============================================================================== """ odb = openOdb(filename+'.odb',readOnly=False) # Get Instance allInstances = (odb.rootAssembly.instances.keys()) odbInstance = odb.rootAssembly.instances[allInstances[-1]] """ FORMAT AND SAVE DATA TO ODB =============================================================================== """ vMNodes = np.ascontiguousarray(nodeNum, dtype=np.int32) vMMax = np.ascontiguousarray(np.reshape(vonMisesMax,(-1,1)), dtype=np.float32) vMMin = np.ascontiguousarray(np.reshape(vonMisesMin,(-1,1)), dtype=np.float32) vMStatic = np.ascontiguousarray(np.reshape(vonMisesStatic,(-1,1)), dtype=np.float32) vMMean = np.ascontiguousarray(np.reshape(vonMisesMean,(-1,1)), dtype=np.float32) vMAmp = np.ascontiguousarray(np.reshape(vonMisesAmp,(-1,1)), dtype=np.float32) newFieldOutputMax = odb.steps['Step-6-Response'].frames[-1].FieldOutput(name = 'vMMax', description = 'Max Signed von Mises', type = SCALAR) newFieldOutputMax.addData(position=NODAL, instance = odbInstance, labels = vMNodes, data = vMMax.tolist()) newFieldOutputMin = odb.steps['Step-6-Response'].frames[-1].FieldOutput(name = 'vMMin', description = 'Min Signed von Mises', type = SCALAR) newFieldOutputMin.addData(position=NODAL, instance = odbInstance, labels = vMNodes, data = vMMin.tolist()) newFieldOutputMStatic = odb.steps['Step-6-Response'].frames[-1].FieldOutput(name = 'vMStatic', description = 'Static Signed von Mises', type = SCALAR) newFieldOutputMStatic.addData(position=NODAL, instance = odbInstance, labels = vMNodes, data = vMStatic.tolist()) newFieldOutputMean = odb.steps['Step-6-Response'].frames[-1].FieldOutput(name = 'vMMean', description = 'Signed von Mises Mean', type = SCALAR) newFieldOutputMean.addData(position=NODAL, instance = odbInstance, labels = vMNodes, data = vMMean.tolist()) newFieldOutputAmp = odb.steps['Step-6-Response'].frames[-1].FieldOutput(name = 'vMAmp', description = 'Signed von Mises Amplitude', type = SCALAR) newFieldOutputAmp.addData(position=NODAL, instance = odbInstance, labels = vMNodes, data = vMAmp.tolist()) """ SAVE AND CLOSE =============================================================================== """ odb.save() odb.close()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 267, 9945, 15457, 1330, 1635, 198, 6738, 450, 30188, 385, 34184, 1187, 1330, 1635, 198, 198, 34345, 796, 705, 33308, 12, 1...
2.931683
1,010
""" SSH reimplementation in Python, made by Unazed Spectaculum under the MIT license """ import socket import struct
[ 37811, 198, 5432, 39, 21123, 32851, 287, 11361, 11, 925, 416, 791, 13865, 13058, 330, 14452, 739, 262, 17168, 5964, 198, 37811, 198, 198, 11748, 17802, 198, 11748, 2878, 628 ]
3.966667
30
import random def find_spelling(n): """ Finds d, r s.t. n-1 = 2^r * d """ r = 0 d = n - 1 # divmod used for large numbers quotient, remainder = divmod(d, 2) # while we can still divide 2's into n-1... while remainder != 1: r += 1 d = quotient # previous quotient before we overwrite it quotient, remainder = divmod(d, 2) return r, d def probably_prime(n, k=10): """ Miller-Rabin primality test Input: n > 3 k: accuracy of test Output: True if n is "probably prime", False if it is composite From psuedocode at https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test """ if n == 2: return True if n % 2 == 0: return False r, d = find_spelling(n) for check in range(k): a = random.randint(2, n - 1) x = pow(a, d, n) # a^d % n if x == 1 or x == n - 1: continue for i in range(r): x = pow(x, 2, n) if x == n - 1: break else: return False return True
[ 11748, 4738, 201, 198, 201, 198, 201, 198, 4299, 1064, 62, 4125, 2680, 7, 77, 2599, 201, 198, 220, 220, 220, 37227, 201, 198, 220, 220, 220, 9938, 82, 288, 11, 374, 264, 13, 83, 13, 299, 12, 16, 796, 362, 61, 81, 1635, 288, 20...
1.982609
575
#MARTY I2C PI #SCRIPT BASED ON MATS WORK #SCRIPT PUSHED INSIDE inmoovCustom : https://github.com/MyRobotLab/inmoov/tree/master/InmoovScript raspi = Runtime.createAndStart("RasPi","RasPi") adaFruit16c = Runtime.createAndStart("AdaFruit16C","Adafruit16CServoDriver") adaFruit16c.setController("RasPi","1","0x40") # # This part is common for both devices and creates two servo instances # on port 3 and 8 on the Adafruit16CServoDriver # Change the names of the servos and the pin numbers to your usage cuisseDroite = Runtime.createAndStart("cuisseDroite", "Servo") genouDroite = Runtime.createAndStart("genouDroite", "Servo") chevilleDroite = Runtime.createAndStart("chevilleDroite", "Servo") cuisseGauche = Runtime.createAndStart("cuisseGauche", "Servo") genouGauche = Runtime.createAndStart("genouGauche", "Servo") chevilleGauche = Runtime.createAndStart("chevilleGauche", "Servo") eyes = Runtime.createAndStart("eyes", "Servo") armLeft = Runtime.createAndStart("armLeft", "Servo") armRight = Runtime.createAndStart("armRight", "Servo") sleep(1) ledBlue=14 ledRed=13 ledGreen=12 vitesse=80 cuisseDroiteRest=90 genouDroiteRest=90 chevilleDroiteRest=80 cuisseGaucheRest=97 genouGaucheRest=95 chevilleGaucheRest=90 armLeftRest=90 armRightRest=120 eyesRest=90 cuisseDroite.setRest(cuisseDroiteRest) genouDroite.setRest(genouDroiteRest) chevilleDroite.setRest(chevilleDroiteRest) cuisseGauche.setRest(cuisseGaucheRest) genouGauche.setRest(genouGaucheRest) chevilleGauche.setRest(chevilleGaucheRest) eyes.setRest(eyesRest) eyes.map(0,180,66,100) armLeft.setRest(armLeftRest) armRight.setRest(armRightRest) cuisseDroite.attach(adaFruit16c,0) genouDroite.attach(adaFruit16c,1) chevilleDroite.attach(adaFruit16c,2) cuisseGauche.attach(adaFruit16c,4) genouGauche.attach(adaFruit16c,5) chevilleGauche.attach(adaFruit16c,15) eyes.attach(adaFruit16c,8) armLeft.attach(adaFruit16c,9) armRight.attach(adaFruit16c,10) eyes.setVelocity(-1) armLeft.setVelocity(-1) armRight.setVelocity(-1) cuisseDroite.rest() genouDroite.rest() chevilleDroite.rest() cuisseGauche.rest() genouGauche.rest() chevilleGauche.rest() eyes.rest() armLeft.rest() armRight.rest() sleep(2) cuisseDroite.detach() genouDroite.detach() chevilleDroite.detach() cuisseGauche.detach() genouGauche.detach() chevilleGauche.detach() armLeft.detach() armRight.detach() adaFruit16c.setPinValue(7,0) adaFruit16c.setPinValue(ledGreen,0) adaFruit16c.setPinValue(ledRed,0) adaFruit16c.setPinValue(ledBlue,0) red() sleep(1) green() sleep(1) blue() sleep(1) noLed() led = Runtime.start("led","Clock") led.setInterval(100) global i i=0 led.addListener("pulse", python.name, "ledFunc")
[ 2, 44, 7227, 56, 314, 17, 34, 30434, 198, 2, 6173, 46023, 29809, 1961, 6177, 337, 33586, 30936, 198, 2, 6173, 46023, 350, 27143, 1961, 29194, 14114, 287, 5908, 709, 15022, 1058, 3740, 1378, 12567, 13, 785, 14, 3666, 14350, 313, 17822,...
2.502836
1,058
from sklearn import tree, svm from sklearn.neural_network import MLPClassifier from sklearn.multiclass import OneVsRestClassifier from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier, VotingClassifier from sklearn.linear_model import LogisticRegression, RidgeClassifier from sklearn.naive_bayes import GaussianNB import matplotlib.pyplot as plt import numpy as np from generate_dataset import generate_dataset, preparing_dataset from storeExperimentalInformations import store_experimental_informations, prepare_legends import baseGraph import ape_tabular import warnings import pickle #from keras.models import Sequential #from keras.layers import Dense if __name__ == "__main__": # Filter the warning from matplotlib warnings.filterwarnings("ignore") # Datasets used for the experiments dataset_names = ["generate_circles", "generate_moons", "blood", "diabete", "generate_blobs"]# "compas", "adult", "titanic" # array of the models used for the experiments models = [GradientBoostingClassifier(n_estimators=20, learning_rate=1.0), RandomForestClassifier(n_estimators=20), #MLPClassifier(random_state=1, activation="logistic"), VotingClassifier(estimators=[('lr', LogisticRegression()), ('gnb', GaussianNB()), ('rc', LogisticRegression())], voting="soft"), MLPClassifier(random_state=1), RidgeClassifier()]#, #LogisticRegression(), #tree.DecisionTreeClassifier(), #Sequential(), #models=[RidgeClassifier(), MLPClassifier(random_state=1)] # Number of instances explained by each model on each dataset max_instance_to_explain = 10 # Print explanation result illustrative_example = False """ All the variable necessaries for generating the graph results """ # Store results inside graph if set to True graph = True verbose = False growing_sphere = False if growing_sphere: label_graph = "growing spheres " growing_method = "GS" else: label_graph = "" growing_method = "GF" # Threshold for explanation method precision threshold_interpretability = 0.99 linear_separability_index = 1 interpretability_name = ['ls', 'ls regression', 'ls raw data', 'ls extend'] #interpretability_name = ['ls log reg', 'ls raw data'] # Initialize all the variable needed to store the result in graph for dataset_name in dataset_names: if graph: experimental_informations = store_experimental_informations(len(models), len(interpretability_name), interpretability_name, len(models)) models_name = [] # Store dataset inside x and y (x data and y labels), with aditional information x, y, class_names, regression, multiclass, continuous_features, categorical_features, \ categorical_values, categorical_names, transformations = generate_dataset(dataset_name) for nb_model, model in enumerate(models): model_name = type(model).__name__ if "MLP" in model_name and nb_model <=2 : model_name += "logistic" if growing_sphere: filename = "./results/"+dataset_name+"/"+model_name+"/growing_spheres/"+str(threshold_interpretability)+"/sup_mat_" filename_all = "./results/"+dataset_name+"/growing_spheres/"+str(threshold_interpretability)+"/sup_mat_" else: filename="./results/"+dataset_name+"/"+model_name+"/"+str(threshold_interpretability)+"/sup_mat_" filename_all="./results/"+dataset_name+"/"+str(threshold_interpretability)+"/sup_mat_" if graph: experimental_informations.initialize_per_models(filename) models_name.append(model_name) # Split the dataset inside train and test set (50% each set) dataset, black_box, x_train, x_test, y_train, y_test = preparing_dataset(x, y, dataset_name, model) print("###", model_name, "training on", dataset_name, "dataset.") if 'Sequential' in model_name: # Train a neural network classifier with 2 relu and a sigmoid activation function black_box.add(Dense(12, input_dim=len(x_train[0]), activation='relu')) black_box.add(Dense(8, activation='relu')) black_box.add(Dense(1, activation='sigmoid')) black_box.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) black_box.fit(x_train, y_train, epochs=50, batch_size=10) else: black_box = black_box.fit(x_train, y_train) predict = black_box.predict score = black_box.score print('### Accuracy:', score(x_test, y_test)) cnt = 0 explainer = ape_tabular.ApeTabularExplainer(x_train, class_names, predict, black_box.predict_proba, continuous_features=continuous_features, categorical_features=categorical_features, categorical_values=categorical_values, feature_names=dataset.feature_names, categorical_names=categorical_names, verbose=verbose, threshold_precision=threshold_interpretability, linear_separability_index=linear_separability_index, transformations=transformations) for instance_to_explain in x_test: if cnt == max_instance_to_explain: break print("### Instance number:", cnt + 1, "over", max_instance_to_explain) print("### Models ", nb_model + 1, "over", len(models)) print("instance to explain:", instance_to_explain) try: precision, coverage, f2 = explainer.explain_instance(instance_to_explain, growing_method=growing_method, local_surrogate_experiment=True) print("precision", precision) print("coverage", coverage) print("f2", f2) if graph: experimental_informations.store_experiments_information_instance(precision, 'precision.csv', coverage, 'coverage.csv', f2, 'f2.csv') cnt += 1 except Exception as inst: print(inst) if graph: experimental_informations.store_experiments_information(max_instance_to_explain, nb_model, 'precision.csv', 'coverage.csv', 'f2.csv', filename_all=filename_all)
[ 6738, 1341, 35720, 1330, 5509, 11, 264, 14761, 198, 6738, 1341, 35720, 13, 710, 1523, 62, 27349, 1330, 10373, 47, 9487, 7483, 198, 6738, 1341, 35720, 13, 16680, 291, 31172, 1330, 1881, 23266, 19452, 9487, 7483, 198, 6738, 1341, 35720, 1...
2.229052
3,091
import pandas as pd import numpy as np import data_inputs, evaluate_EWRs #-------------------------------------------------------------------------------------------------- def sum_events(events): '''returns a sum of events''' return int(round(events.sum(), 0)) def get_frequency(events): '''Returns the frequency of years they occur in''' if events.count() == 0: result = 0 else: result = (int(events.sum())/int(events.count()))*100 return int(round(result, 0)) def get_average(input_events): '''Returns overall average length of events''' events = input_events.dropna() if len(events) == 0: result = 0 else: result = round(sum(events)/len(events),1) return result def initialise_summary_df_columns(input_dict): '''Ingest a dictionary of ewr yearly results and a list of statistical tests to perform initialises a dataframe with these as a multilevel heading and returns this''' analysis = data_inputs.analysis() column_list = [] list_of_arrays = [] for scenario, scenario_results in input_dict.items(): for sub_col in analysis: column_list = tuple((scenario, sub_col)) list_of_arrays.append(column_list) array_of_arrays =tuple(list_of_arrays) multi_col_df = pd.MultiIndex.from_tuples(array_of_arrays, names = ['scenario', 'type']) return multi_col_df def initialise_summary_df_rows(input_dict): '''Ingests a dictionary of ewr yearly results pulls the location information and the assocaited ewrs at each location, saves these as respective indexes and return the multi-level index''' index_1 = list() index_2 = list() index_3 = list() combined_index = list() # Get unique col list: for scenario, scenario_results in input_dict.items(): for site, site_results in scenario_results.items(): for PU in site_results: site_list = [] for col in site_results[PU]: if '_' in col: all_parts = col.split('_') remove_end = all_parts[:-1] if len(remove_end) > 1: EWR_code = '_'.join(remove_end) else: EWR_code = remove_end[0] else: EWR_code = col if EWR_code in site_list: continue else: site_list.append(EWR_code) add_index = tuple((site, PU, EWR_code)) if add_index not in combined_index: combined_index.append(add_index) unique_index = tuple(combined_index) multi_index = pd.MultiIndex.from_tuples(unique_index, names = ['gauge', 'planning unit', 'EWR']) return multi_index def allocate(df, add_this, idx, site, PU, EWR, scenario, category): '''Save element to a location in the dataframe''' df.loc[idx[[site], [PU], [EWR]], idx[scenario, category]] = add_this return df def summarise(input_dict): '''Ingests a dictionary with ewr pass/fails summarises these results and returns a single summary dataframe''' PU_items = data_inputs.get_planning_unit_info() EWR_table, see_notes_ewrs, undefined_ewrs, noThresh_df, no_duration, DSF_ewrs = data_inputs.get_EWR_table() # Initialise dataframe with multi level column heading and multi-index: multi_col_df = initialise_summary_df_columns(input_dict) index = initialise_summary_df_rows(input_dict) df = pd.DataFrame(index = index, columns=multi_col_df) # Run the analysis and add the results to the dataframe created above: for scenario, scenario_results in input_dict.items(): for site, site_results in scenario_results.items(): for PU in site_results: for col in site_results[PU]: all_parts = col.split('_') remove_end = all_parts[:-1] if len(remove_end) > 1: EWR = '_'.join(remove_end) else: EWR = remove_end[0] idx = pd.IndexSlice if ('_eventYears' in col): S = sum_events(site_results[PU][col]) df = allocate(df, S, idx, site, PU, EWR, scenario, 'Event years') F = get_frequency(site_results[PU][col]) df = allocate(df, F, idx, site, PU, EWR, scenario, 'Frequency') PU_num = PU_items['PlanningUnitID'].loc[PU_items[PU_items['PlanningUnitName'] == PU].index[0]] EWR_info = evaluate_EWRs.get_EWRs(PU_num, site, EWR, EWR_table, None, ['TF']) TF = EWR_info['frequency'] df = allocate(df, TF, idx, site, PU, EWR, scenario, 'Target frequency') elif ('_numAchieved' in col): S = sum_events(site_results[PU][col]) df = allocate(df, S, idx, site, PU, EWR, scenario, 'Achievement count') ME = get_average(site_results[PU][col]) df = allocate(df, ME, idx, site, PU, EWR, scenario, 'Achievements per year') elif ('_numEvents' in col): S = sum_events(site_results[PU][col]) df = allocate(df, S, idx, site, PU, EWR, scenario, 'Event count') ME = get_average(site_results[PU][col]) df = allocate(df, ME, idx, site, PU, EWR, scenario, 'Events per year') elif ('_eventLength' in col): EL = get_event_length(site_results[PU][col], S) df = allocate(df, EL, idx, site, PU, EWR, scenario, 'Event length') elif ('_totalEventDays' in col): AD = get_average(site_results[PU][col]) df = allocate(df, AD, idx, site, PU, EWR, scenario, 'Threshold days') elif ('daysBetweenEvents' in col): PU_num = PU_items['PlanningUnitID'].loc[PU_items[PU_items['PlanningUnitName'] == PU].index[0]] EWR_info = evaluate_EWRs.get_EWRs(PU_num, site, EWR, EWR_table, None, ['MIE']) DB = count_exceedence(site_results[PU][col], EWR_info) df = allocate(df, DB, idx, site, PU, EWR, scenario, 'Inter-event exceedence count') # Also save the max inter-event period to the data summary for reference EWR_info = evaluate_EWRs.get_EWRs(PU_num, site, EWR, EWR_table, None, ['MIE']) MIE = EWR_info['max_inter-event'] df = allocate(df, MIE, idx, site, PU, EWR, scenario, 'Max inter event period (years)') elif ('_missingDays' in col): MD = sum_events(site_results[PU][col]) df = allocate(df, MD, idx, site, PU, EWR, scenario, 'No data days') elif ('_totalPossibleDays' in col): TD = sum_events(site_results[PU][col]) df = allocate(df, TD, idx, site, PU, EWR, scenario, 'Total days') return df
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 198, 11748, 1366, 62, 15414, 82, 11, 13446, 62, 6217, 31273, 198, 2, 10097, 3880, 438, 198, 198, 4299, 2160, 62, 31534, 7, 31534, 2599, 198, 220, 220, 220, 70...
2.006166
3,730
import pandas as pd writer = pd.ExcelWriter("data.xlsx", engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1', index=False) # Get the xlsxwriter workbook and worksheet objects. workbook = writer.book worksheet = writer.sheets['Sheet1']
[ 11748, 19798, 292, 355, 279, 67, 198, 198, 16002, 796, 279, 67, 13, 3109, 5276, 34379, 7203, 7890, 13, 87, 7278, 87, 1600, 3113, 11639, 87, 7278, 87, 16002, 11537, 198, 198, 7568, 13, 1462, 62, 1069, 5276, 7, 16002, 11, 9629, 62, ...
2.775281
89
from setuptools import setup with open('README.rst') as f: readme = f.read() setup( name="dem", version="0.0.8", author="Ian Macaulay, Jeremy Opalach", author_email="ismacaul@gmail.com", url="http://www.github.com/nitehawck/dem", description="An agnostic library/package manager for setting up a development project environment", long_description=readme, license="MIT License", classifiers=[ 'Development Status :: 3 - Alpha', #'Development Status :: 4 - Beta', #'Development Status :: 5 - Production / Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'Operating System :: MacOS :: MacOS X', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Build Tools', ], packages=['dem', 'dem.dependency', 'dem.project'], install_requires=[ 'virtualenv', 'PyYaml', 'wget', 'gitpython' ], tests_require=[ 'pyfakefs', 'mock' ], entry_points={ 'console_scripts': [ 'dem = dem.__main__:main' ] }, )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 4480, 1280, 10786, 15675, 11682, 13, 81, 301, 11537, 355, 277, 25, 198, 220, 220, 220, 1100, 1326, 796, 277, 13, 961, 3419, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 2625, 9536, 160...
2.459119
636
# django imports from django.contrib import admin # lfs imports from lfs.core.models import Action from lfs.core.models import ActionGroup from lfs.core.models import Shop from lfs.core.models import Country admin.site.register(Shop) admin.site.register(Action) admin.site.register(ActionGroup) admin.site.register(Country)
[ 2, 42625, 14208, 17944, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 2, 300, 9501, 17944, 198, 6738, 300, 9501, 13, 7295, 13, 27530, 1330, 7561, 198, 6738, 300, 9501, 13, 7295, 13, 27530, 1330, 7561, 13247, 198, 6738...
3.292929
99
#!/usr/bin/env python3 """TarSync.py: Synchronize .fcstd and .tar files. Usage: TarSync.py [OPTIONS] [DIR] ... Recursively scans directories searching for `.fcstd`/`.FCstd` files and synchronizes them with associated `.tar` files. The current directory is used if no explicit directory or files are listed. Options: * [-n] Visit all files without doing anything. Use with [-v] option. * [-v] Verbose mode. Rationale: A FreeCAD `.fcstd` file is basically a bunch of text files compressed with gzip. For fun, the `unzip -l XYZ.fcstd` command lists the files contained in `XYZ.fcstd`. Due to the repetitive nature of the text files contained therein, the gzip algorithm can achieve significant overall file compression. A `git` repository basically consists of a bunch files called blob's, where the term "blob" stands for Binary Large Object. Each blob represents some version of a file stored the repository. Being binary files, `.fcstd` files can be stored inside of a git repository. However, the compressed (i.e. binary) nature of `.fcstd` files can make the git repository storage requirements grow at a pretty rapid rate as multiple versions of the `.fcstd` files get stored into a git repository. To combat the storage growth requirements, `git` uses a compression algorithm that is applied to the repository as a whole. These compressed files are called Pack files. Pack files are generated and updated whenever git decides to do so. Over time, the overall git storage requirements associated with uncompressed files grows at a slower rate than gzip compressed files. In addition, each time a git repositories are synchronized, the over the wire protocol is via Pack file. This program will convert a file from compressed in gzip format into simpler uncompressed format call a `.tar` file. (`tar` stands for Tape ARchive for back in the days of magnetic tapes.) Basically, what this program does is manage two files in tandem, `XYZ.fcstd` and `XYZ.tar`. It does this by comparing the modification times between the two files translates the content of the newer file on top of the older file. When done, both files will have the same modification time. This program works recursively over an entire directory tree. To use this program with a git repository, configure your `.gitignore` to ignore `.fcstd` files in your repository by adding `*.fcstd` to your `.gitignore` file. Run this program before doing a `git commit` Whenever you update your git repository from a remote one, run this program to again, to keep the `.fcstd` files in sync with any updated `.tar` files. """ # [Basic Git Concepts] # (https://www.oreilly.com/library/view/version-control-with/9781449345037/ch04.html) # # FreeCAD forum topics: # [https://forum.freecadweb.org/viewtopic.php?t=38353&start=30](1) # [https://forum.freecadweb.org/viewtopic.php?f=8&t=36844a](2) # [https://forum.freecadweb.org/viewtopic.php?t=40029&start=10](3) # [https://forum.freecadweb.org/viewtopic.php?p=1727](4) # [https://forum.freecadweb.org/viewtopic.php?t=8688](5) # [https://forum.freecadweb.org/viewtopic.php?t=32521](6) # [https://forum.freecadweb.org/viewtopic.php?t=57737)(7) # [https://blog.lambda.cx/posts/freecad-and-git/](8) # [https://tante.cc/2010/06/23/managing-zip-based-file-formats-in-git/](9) from argparse import ArgumentParser from io import BytesIO import os from pathlib import Path from tarfile import TarFile, TarInfo from tempfile import TemporaryDirectory from typing import List, IO, Optional, Tuple import time from zipfile import ZIP_DEFLATED, ZipFile # main(): def main() -> None: """Execute the main program.""" # Create an *argument_parser*: parser: ArgumentParser = ArgumentParser( description="Synchronize .fcstd/.tar files." ) parser.add_argument("directories", metavar="DIR", type=str, nargs="*", help="Directory to recursively scan") parser.add_argument("-n", "--dry-run", action="store_true", help="verbose mode") parser.add_argument("-v", "--verbose", action="store_true", help="verbose mode") parser.add_argument("--unit-test", action="store_true", help="run unit tests") # Parse arguments: arguments = parser.parse_args() directories: Tuple[str, ...] = tuple(arguments.directories) if arguments.unit_test: # Run the unit test: unit_test() directories = () synchronize_directories(directories, arguments.dry_run, arguments.verbose) # synchronize_directories(): def synchronize_directories(directory_names: Tuple[str, ...], dry_run: bool, verbose: bool) -> Tuple[str, ...]: """Synchronize some directories. * Arguments: * *directory_names* (Tuple[str, ...): A list of directories to recursively synchronize. * dry_run (bool): If False, the directories are scanned, but not synchronized. If True, the directories are both scanned and synchronized. * verbose (bool): If True, the a summary message is printed if for each (possible) synchronization. The actual synchronization only occurs if *dry_run* is False. * Returns * (Tuple[str, ...]) containing the summary """ # Recursively find all *fcstd_paths* in *directories*: fcstd_paths: List[Path] = [] directory_name: str for directory_name in directory_names: suffix: str = "fcstd" for suffix in ("fcstd", "fcSTD"): fcstd_paths.extend(Path(directory_name).glob(f"**/*.{suffix}")) # Perform all of the synchronizations: summaries: List[str] = [] for fcstd_path in fcstd_paths: summary: str = synchronize(fcstd_path, dry_run) summaries.append(summary) if verbose: print(summary) # pragma: no unit cover return tuple(summaries) # Synchronize(): def synchronize(fcstd_path: Path, dry_run: bool = False) -> str: """Synchronize an .fcstd file with associated .tar file. * Arguments: * fcstd_path (Path): The `.fcstd` file to synchronize. * dry_run (bool): If True, no synchronization occurs and only the summary string is returned. (Default: False) * Returns: * (str) a summary string. Synchronizes an `.fcstd` file with an associated `.tar` file and. A summary is always returned even in *dry_run* mode. """ # Determine timestamps for *fstd_path* and associated *tar_path*: tar_path: Path = fcstd_path.with_suffix(".tar") fcstd_timestamp: int = int(fcstd_path.stat().st_mtime) if fcstd_path.exists() else 0 tar_timestamp: int = int(tar_path.stat().st_mtime) if tar_path.exists() else 0 # Using the timestamps do the synchronization (or not): zip_file: ZipFile tar_file: TarFile tar_info: TarInfo fcstd_name: str = str(fcstd_path) tar_name: str = str(tar_path) summary: str if fcstd_timestamp > tar_timestamp: # Update *tar_path* from *tar_path*: summary = f"{fcstd_name} => {tar_name}" if not dry_run: with ZipFile(fcstd_path, "r") as zip_file: with TarFile(tar_path, "w") as tar_file: from_names: Tuple[str, ...] = tuple(zip_file.namelist()) for from_name in from_names: from_content: bytes = zip_file.read(from_name) # print(f"Read {fcstd_path}:{from_name}:" # f"{len(from_content)}:{is_ascii(from_content)}") tar_info = TarInfo(from_name) tar_info.size = len(from_content) # print(f"tar_info={tar_info} size={tar_info.size}") tar_file.addfile(tar_info, BytesIO(from_content)) os.utime(tar_path, (fcstd_timestamp, fcstd_timestamp)) # Force modification time. elif tar_timestamp > fcstd_timestamp: # Update *fcstd_path* from *tar_path*: summary = f"{tar_name} => {fcstd_name}" if not dry_run: with TarFile(tar_path, "r") as tar_file: tar_infos: Tuple[TarInfo, ...] = tuple(tar_file.getmembers()) with ZipFile(fcstd_path, "w", ZIP_DEFLATED) as zip_file: for tar_info in tar_infos: buffered_reader: Optional[IO[bytes]] = tar_file.extractfile(tar_info) assert buffered_reader buffer: bytes = buffered_reader.read() # print(f"{tar_info.name}: {len(buffer)}") zip_file.writestr(tar_info.name, buffer) os.utime(fcstd_path, (tar_timestamp, tar_timestamp)) # Force modification time. else: summary = f"{fcstd_name} in sync with {tar_name}" return summary # unit_test(): def unit_test() -> None: """Run the unit test.""" directory_name: str # Use create a temporary *directory_path* to run the tests in: with TemporaryDirectory() as directory_name: a_content: str = "a contents" b_content: str = "b contents" buffered_reader: Optional[IO[bytes]] c_content: str = "c contents" directory_path: Path = Path(directory_name) tar_name: str tar_file: TarFile tar_path: Path = directory_path / "test.tar" tar_path_name: str = str(tar_path) zip_file: ZipFile zip_name: str zip_path: Path = directory_path / "test.fcstd" zip_path_name: str = str(zip_path) # Create *zip_file* with a suffix of `.fcstd`: with ZipFile(zip_path, "w", ZIP_DEFLATED) as zip_file: zip_file.writestr("a", a_content) zip_file.writestr("b", b_content) assert zip_path.exists(), f"{zip_path_name=} not created" zip_timestamp: int = int(zip_path.stat().st_mtime) assert zip_timestamp > 0, f"{zip_path=} had bad timestamp." # Perform synchronize with a slight delay to force a different modification time: time.sleep(1.1) summaries = synchronize_directories((directory_name, ), False, False) assert len(summaries) == 1, "Only 1 summary expected" summary: str = summaries[0] desired_summary: str = f"{zip_path_name} => {tar_path_name}" assert summary == desired_summary, f"{summary} != {desired_summary}" assert tar_path.exists(), f"{tar_path_name=} not created" tar_timestamp: int = int(tar_path.stat().st_mtime) assert tar_timestamp == zip_timestamp, f"{zip_timestamp=} != {tar_timestamp=}" # Now read *tar_file* and verify that it has the correct content: with TarFile(tar_path, "r") as tar_file: tar_infos: Tuple[TarInfo, ...] = tuple(tar_file.getmembers()) for tar_info in tar_infos: buffered_reader = tar_file.extractfile(tar_info) assert buffered_reader, f"Unable to read {tar_file=}" content: str = buffered_reader.read().decode("latin-1") found: bool = False if tar_info.name == "a": assert content == a_content, f"'{content}' != '{a_content}'" found = True elif tar_info.name == "b": assert content == b_content, f"'{content}' != '{b_content}'" found = True assert found, f"Unexpected tar file name {tar_info.name}" # Now run synchronize again and verify that nothing changed: summaries = synchronize_directories((directory_name, ), False, False) assert len(summaries) == 1, "Only one summary expected" summary = summaries[0] desired_summary = f"{str(zip_path)} in sync with {str(tar_path)}" assert summary == desired_summary, f"'{summary}' != '{desired_summary}'" zip_timestamp = int(zip_path.stat().st_mtime) tar_timestamp = int(tar_path.stat().st_mtime) assert tar_timestamp == zip_timestamp, f"timestamps {zip_timestamp=} != {tar_timestamp=}" # Now update *tar_file* with new content (i.e. `git pull`).: time.sleep(1.1) # Use delay to force a different timestamp. with TarFile(tar_path, "w") as tar_file: tar_info = TarInfo("c") tar_info.size = len(c_content) tar_file.addfile(tar_info, BytesIO(bytes(c_content, "latin-1"))) tar_info = TarInfo("a") tar_info.size = len(a_content) tar_file.addfile(tar_info, BytesIO(bytes(a_content, "latin-1"))) # Verify that the timestamp changed and force a synchronize(). new_tar_timestamp: int = int(tar_path.stat().st_mtime) assert new_tar_timestamp > tar_timestamp, f"{new_tar_timestamp=} <= {tar_timestamp=}" summary = synchronize(zip_path) desired_summary = f"{tar_path_name} => {zip_path_name}" assert summary == desired_summary, f"'{summary}' != '{desired_summary}'" # Verify that the *zip_path* got updated verify that the content changed: new_zip_timestamp: int = int(zip_path.stat().st_mtime) assert new_zip_timestamp == new_tar_timestamp, ( f"{new_zip_timestamp=} != {new_tar_timestamp=}") with ZipFile(zip_path, "r") as zip_file: zip_names: Tuple[str, ...] = tuple(zip_file.namelist()) for zip_name in zip_names: zip_content: str = zip_file.read(zip_name).decode("latin-1") assert buffered_reader found = False if zip_name == "a": assert zip_content == a_content, "Content mismatch" found = True elif zip_name == "c": assert zip_content == c_content, "Content mismatch" found = True assert found, "Unexpected file '{zip_name}'" if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 37811, 47079, 28985, 13, 9078, 25, 16065, 11413, 1096, 764, 16072, 19282, 290, 764, 18870, 3696, 13, 198, 198, 28350, 25, 14110, 28985, 13, 9078, 685, 3185, 51, 11053, 60, 685, 347...
2.415052
5,780
from tcga_encoder.utils.helpers import * from tcga_encoder.data.data import * #from tcga_encoder.data.pathway_data import Pathways from tcga_encoder.data.hallmark_data import Pathways from tcga_encoder.definitions.tcga import * #from tcga_encoder.definitions.nn import * from tcga_encoder.definitions.locations import * #from tcga_encoder.algorithms import * import seaborn as sns from sklearn.manifold import TSNE, locally_linear_embedding from scipy import stats if __name__ == "__main__": data_location = sys.argv[1] results_location = sys.argv[2] main( data_location, results_location )
[ 6738, 37096, 4908, 62, 12685, 12342, 13, 26791, 13, 16794, 364, 1330, 1635, 198, 6738, 37096, 4908, 62, 12685, 12342, 13, 7890, 13, 7890, 1330, 1635, 198, 2, 6738, 37096, 4908, 62, 12685, 12342, 13, 7890, 13, 6978, 1014, 62, 7890, 133...
2.775785
223
from XXX_PROJECT_NAME_XXX.settings import * # noqa # Override any settings required for tests here
[ 198, 6738, 27713, 62, 31190, 23680, 62, 20608, 62, 43145, 13, 33692, 1330, 1635, 220, 1303, 645, 20402, 198, 198, 2, 3827, 13154, 597, 6460, 2672, 329, 5254, 994, 198 ]
3.4
30
from django.db import models #from djangosphinx import SphinxSearch, SphinxRelation, SphinxQuerySet #import djangosphinx.apis.current as sphinxapi from advancedsearch.models import Movie, Episode, Song from browseNet.models import Host, Path # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 2, 6738, 42625, 648, 14222, 28413, 1330, 45368, 28413, 18243, 11, 45368, 28413, 6892, 341, 11, 45368, 28413, 20746, 7248, 198, 2, 11748, 42625, 648, 14222, 28413, 13, 499, 271, 13, 14421, 3...
3.493671
79
#!/usr/bin/env python3 # Copyright (c) 2016-2020, henry232323 # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE.
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 15069, 357, 66, 8, 1584, 12, 42334, 11, 30963, 563, 1954, 1954, 1954, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 198,...
3.761745
298
# # -*- coding: utf-8 -*- # # This file is part of reclass (http://github.com/madduck/reclass) # # Copyright 200714 martin f. krafft <madduck@madduck.net> # Released under the terms of the Artistic Licence 2.0 # from reclass.utils.refvalue import RefValue from reclass.defaults import PARAMETER_INTERPOLATION_SENTINELS, \ PARAMETER_INTERPOLATION_DELIMITER from reclass.errors import UndefinedVariableError, \ IncompleteInterpolationError import unittest CONTEXT = {'favcolour':'yellow', 'motd':{'greeting':'Servus!', 'colour':'${favcolour}' }, 'int':1, 'list':[1,2,3], 'dict':{1:2,3:4}, 'bool':True } if __name__ == '__main__': unittest.main()
[ 2, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 770, 2393, 318, 636, 286, 302, 4871, 357, 4023, 1378, 12567, 13, 785, 14, 9937, 646, 694, 14, 260, 4871, 8, 198, 2, 198, 2, 15069, 220, 4343, ...
2.075472
371
""" Author: Isamu Isozaki (isamu.website@gmail.com) Description: description Created: 2021-12-01T16:32:53.089Z Modified: !date! Modified By: modifier """ from flask import Blueprint, redirect, jsonify, url_for, request from neuroflow.repository import create_mood, get_authorized, load_moods_from_user from functools import wraps from flask_cors import cross_origin blueprint = Blueprint('mood', __name__, url_prefix='/mood')
[ 37811, 198, 13838, 25, 1148, 321, 84, 314, 568, 89, 8182, 357, 271, 321, 84, 13, 732, 12485, 31, 14816, 13, 785, 8, 198, 11828, 25, 6764, 198, 41972, 25, 220, 33448, 12, 1065, 12, 486, 51, 1433, 25, 2624, 25, 4310, 13, 49352, 57...
2.647399
173
import logging import time from pathlib import Path from configparser import ConfigParser import boto3 from botocore.exceptions import ClientError def create_bucket(bucket_name: str, region: str = 'us-west-2'): """ Create S3 bucket https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-example-creating-buckets.html :param bucket_name: Name of S3 bucket :param region: AWS region where bucket is created :return: True if bucket is created or already exists, False if ClientError occurs """ try: s3_client = boto3.client('s3', region=region) # list buckets response = s3_client.list_buckets() # check if bucket exists if bucket_name not in response['Buckets']: s3_client.create_bucket(Bucket=bucket_name) else: logging.warning(f"{bucket_name} already exist in AWS region {region}") except ClientError as e: logging.exception(e) return False return True def upload_file(file_name: str, bucket: str, object_name: str = None, region: str = 'us-west-2'): """ Upload file to S3 bucket https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-uploading-files.html :param file_name: Path to file including filename :param bucket: Bucket where file is uploaded to :param object_name: Name of file inside S3 bucket :param region: AWS region where bucket is located :return: True if upload succeeds, False if ClientError occurs """ if object_name is None: object_name = file_name try: s3_client = boto3.client('s3', region=region) s3_client.upload_file(file_name, bucket, object_name) except ClientError as e: logging.exception(e) return False return True if __name__ == '__main__': # load config config = ConfigParser() config.read('app.cfg') # start logging logging.basicConfig(level=config.get("logging", "level"), format="%(asctime)s - %(levelname)s - %(message)s") logging.info("Started") # start timer start_time = time.perf_counter() # define data_path = Path(__file__).parent.joinpath('data') # check if bucket exists create_bucket(bucket_name='fff-streams') # upload files to S3 upload_file(data_path.joinpath('world_happiness_2017.csv'), bucket='fff-streams', object_name='world_happiness.csv') upload_file(data_path.joinpath('temp_by_city_clean.csv'), bucket='fff-streams', object_name='temp_by_city.csv') # stop timer stop_time = time.perf_counter() logging.info(f"Uploaded files in {(stop_time - start_time):.2f} seconds") logging.info("Finished")
[ 11748, 18931, 198, 11748, 640, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 4566, 48610, 1330, 17056, 46677, 198, 11748, 275, 2069, 18, 198, 6738, 10214, 420, 382, 13, 1069, 11755, 1330, 20985, 12331, 628, 198, 4299, 2251, 62, 27041, ...
2.646943
1,014
# -*- coding: utf-8 -*- import time help_msg = '''------ aMCR f------ b!!time help f- c b!!time ct f- c b!!time timer [] f- c b!!time stopwatch start f- c b!!time stopwatch stop f- c --------------------------------''' no_input = '''------ a f------ c !!time help --------------------------------''' stop_T = False
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 640, 198, 198, 16794, 62, 19662, 796, 705, 7061, 23031, 257, 44, 9419, 220, 277, 23031, 198, 65, 3228, 2435, 1037, 277, 12, 269, 198, 65, 3228, 2435, 269, 83, ...
2.850877
114
#!/usr/bin/env python3 # # MIT License # # Copyright (c) 2020 EntySec # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # import sys import time import threading import os from core.badges import badges from core.helper import helper
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 198, 2, 17168, 13789, 198, 2, 198, 2, 15069, 357, 66, 8, 12131, 7232, 88, 6558, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048,...
3.732733
333
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 5 @author: Melisa Maidana This script runs different cropping parameters, motion correct the cropped images using reasonable motion correction parameters that were previously selected by using the parameters_setting_motion_correction scripts, and then run source extraction (with multiple parameters) and creates figures of the cropped image and the extracted cells from that image. The idea is to compare the resulting source extraction neural footprint for different cropping selections. Ideally the extracted sources should be similar. If that is the case, then all the parameter setting for every step can be run in small pieces of the image, select the best ones, and implemented lated in the complete image. """ import os import sys import psutil import logging import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Rectangle import pylab as pl # This should be in another file. Let's leave it here for now sys.path.append('/home/sebastian/Documents/Melisa/calcium_imaging_analysis/src/') sys.path.remove('/home/sebastian/Documents/calcium_imaging_analysis') import src.configuration import caiman as cm import src.data_base_manipulation as db from src.steps.cropping import run_cropper as main_cropping from src.steps.motion_correction import run_motion_correction as main_motion_correction from src.steps.source_extraction import run_source_extraction as main_source_extraction import src.analysis.metrics as metrics from caiman.source_extraction.cnmf.cnmf import load_CNMF #Paths analysis_states_database_path = 'references/analysis/analysis_states_database.xlsx' backup_path = 'references/analysis/backup/' #parameters_path = 'references/analysis/parameters_database.xlsx' ## Open thw data base with all data states_df = db.open_analysis_states_database() mouse = 51565 session = 1 trial = 1 is_rest = 1 # CROPPING # Select the rows for cropping x1_crops = np.arange(200,0,-50) x2_crops = np.arange(350,550,50) y1_crops = np.arange(200,0,-50) y2_crops = np.arange(350,550,50) n_processes = psutil.cpu_count() cm.cluster.stop_server() # Start a new cluster c, dview, n_processes = cm.cluster.setup_cluster(backend='local', n_processes=n_processes, # number of process to use, if you go out of memory try to reduce this one single_thread=False) logging.info(f'Starting cluster. n_processes = {n_processes}.') #parametrs for motion correction parameters_motion_correction = {'motion_correct': True, 'pw_rigid': True, 'save_movie_rig': False, 'gSig_filt': (5, 5), 'max_shifts': (25, 25), 'niter_rig': 1, 'strides': (48, 48), 'overlaps': (96, 96), 'upsample_factor_grid': 2, 'num_frames_split': 80, 'max_deviation_rigid': 15, 'shifts_opencv': True, 'use_cuda': False, 'nonneg_movie': True, 'border_nan': 'copy'} #parameters for source extraction gSig = 5 gSiz = 4 * gSig + 1 corr_limits = np.linspace(0.4, 0.6, 5) pnr_limits = np.linspace(3, 7, 5) cropping_v = np.zeros(5) motion_correction_v = np.zeros(5) selected_rows = db.select(states_df,'cropping', mouse = mouse, session = session, trial = trial , is_rest = is_rest) mouse_row = selected_rows.iloc[0] for kk in range(4): cropping_interval = [x1_crops[kk], x2_crops[kk], y1_crops[kk], y2_crops[kk]] parameters_cropping = {'crop_spatial': True, 'cropping_points_spatial': cropping_interval, 'crop_temporal': False, 'cropping_points_temporal': []} mouse_row = main_cropping(mouse_row, parameters_cropping) cropping_v[kk] = mouse_row.name[5] states_df = db.append_to_or_merge_with_states_df(states_df, mouse_row) db.save_analysis_states_database(states_df, path=analysis_states_database_path, backup_path = backup_path) states_df = db.open_analysis_states_database() for kk in range(4): selected_rows = db.select(states_df, 'motion_correction', 56165, cropping_v = cropping_v[kk]) mouse_row = selected_rows.iloc[0] mouse_row_new = main_motion_correction(mouse_row, parameters_motion_correction, dview) mouse_row_new = metrics.get_metrics_motion_correction(mouse_row_new, crispness=True) states_df = db.append_to_or_merge_with_states_df(states_df, mouse_row_new) db.save_analysis_states_database(states_df, path=analysis_states_database_path, backup_path = backup_path) motion_correction_v[kk]=mouse_row_new.name[6] states_df = db.open_analysis_states_database() for ii in range(corr_limits.shape[0]): for jj in range(pnr_limits.shape[0]): parameters_source_extraction = {'session_wise': False, 'fr': 10, 'decay_time': 0.1, 'min_corr': corr_limits[ii], 'min_pnr': pnr_limits[jj], 'p': 1, 'K': None, 'gSig': (gSig, gSig), 'gSiz': (gSiz, gSiz), 'merge_thr': 0.7, 'rf': 60, 'stride': 30, 'tsub': 1, 'ssub': 2, 'p_tsub': 1, 'p_ssub': 2, 'low_rank_background': None, 'nb': 0, 'nb_patch': 0, 'ssub_B': 2, 'init_iter': 2, 'ring_size_factor': 1.4, 'method_init': 'corr_pnr', 'method_deconvolution': 'oasis', 'update_background_components': True, 'center_psf': True, 'border_pix': 0, 'normalize_init': False, 'del_duplicates': True, 'only_init': True} for kk in range(4): selected_rows = db.select(states_df, 'source_extraction', 56165, cropping_v = cropping_v[kk]) mouse_row = selected_rows.iloc[0] mouse_row_new = main_source_extraction(mouse_row, parameters_source_extraction, dview) states_df = db.append_to_or_merge_with_states_df(states_df, mouse_row_new) db.save_analysis_states_database(states_df, path=analysis_states_database_path, backup_path=backup_path) states_df = db.open_analysis_states_database() for ii in range(corr_limits.shape[0]): for jj in range(pnr_limits.shape[0]): figure, axes = plt.subplots(4, 3, figsize=(50, 30)) version = ii * pnr_limits.shape[0] + jj +1 for kk in range(4): selected_rows = db.select(states_df, 'component_evaluation', 56165, cropping_v=cropping_v[kk], motion_correction_v = 1, source_extraction_v= version) mouse_row = selected_rows.iloc[0] decoding_output = mouse_row['decoding_output'] decoded_file = eval(decoding_output)['main'] m = cm.load(decoded_file) axes[kk,0].imshow(m[0, :, :], cmap='gray') cropping_interval = [x1_crops[kk], x2_crops[kk], y1_crops[kk], y2_crops[kk]] [x_, _x, y_, _y] = cropping_interval rect = Rectangle((y_, x_), _y - y_, _x - x_, fill=False, color='r', linestyle='--', linewidth = 3) axes[kk,0].add_patch(rect) output_cropping = mouse_row['cropping_output'] cropped_file = eval(output_cropping)['main'] m = cm.load(cropped_file) axes[kk,1].imshow(m[0, :, :], cmap='gray') output_source_extraction = eval(mouse_row['source_extraction_output']) cnm_file_path = output_source_extraction['main'] cnm = load_CNMF(db.get_file(cnm_file_path)) corr_path = output_source_extraction['meta']['corr']['main'] cn_filter = np.load(db.get_file(corr_path)) axes[kk, 2].imshow(cn_filter) coordinates = cm.utils.visualization.get_contours(cnm.estimates.A, np.shape(cn_filter), 0.2, 'max') for c in coordinates: v = c['coordinates'] c['bbox'] = [np.floor(np.nanmin(v[:, 1])), np.ceil(np.nanmax(v[:, 1])), np.floor(np.nanmin(v[:, 0])), np.ceil(np.nanmax(v[:, 0]))] axes[kk, 2].plot(*v.T, c='w',linewidth=3) fig_dir ='/home/sebastian/Documents/Melisa/calcium_imaging_analysis/data/interim/cropping/meta/figures/cropping_inicialization/' fig_name = fig_dir + db.create_file_name(2,mouse_row.name) + '_corr_' + f'{round(corr_limits[ii],1)}' + '_pnr_' + f'{round(pnr_limits[jj])}' + '.png' figure.savefig(fig_name)
[ 198, 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 3300, 5267, 642, 198, 198, 31, 9800, 25, 5616, 9160, 28454, 2271, 198, 198, 1212, 42...
2.201183
3,887
import pandas as pd import json import urllib2 def download_nordpool(limit, output_file): ''' The method downloads the nordpool available data from www.energidataservice.dk and saves it in a csv file limit: Int, the number of maximum rows of data to download output_file: Str, the name of the output file ''' url = 'https://api.energidataservice.dk/datastore_search?resource_id=8bd7a37f-1098-4643-865a-01eb55c62d21&limit=' + str(limit) print("downloading nordpool data ...") fileobj = urllib2.urlopen(url) data = json.loads(fileobj.read()) nordpool_df = pd.DataFrame.from_dict(data['result']['records']) # the data is stored inside two dictionaries nordpool_df.to_csv(output_file) print("nordpool data has been downloaded and saved") def download_dayforward(limit, output_file): ''' The method downloads the available day ahead spotprices in DK and neighboring countries data from www.energidataservice.dk and saves it in a csv file limit: Int, the number of maximum rows of data to download output_file: Str, the name of the output file ''' url = 'https://api.energidataservice.dk/datastore_search?resource_id=c86859d2-942e-4029-aec1-32d56f1a2e5d&limit=' + str(limit) print("downloading day forward data ...") fileobj = urllib2.urlopen(url) data = json.loads(fileobj.read()) nordpool_df = pd.DataFrame.from_dict(data['result']['records']) # the data is stored inside two dictionaries nordpool_df.to_csv(output_file) print("day forward data has been downloaded and saved") if __name__ == '__main__': print("connecting with the API") download_nordpool(10000000, 'nordpool_data.csv') download_dayforward(10000000, 'dayforward_data.csv')
[ 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 33918, 198, 11748, 2956, 297, 571, 17, 628, 198, 4299, 4321, 62, 77, 585, 7742, 7, 32374, 11, 5072, 62, 7753, 2599, 198, 197, 7061, 6, 198, 197, 464, 2446, 21333, 262, 299, 585, 77...
2.835871
591
from typing import Any import torch import torch.nn as nn import torch.nn.functional as F
[ 6738, 19720, 1330, 4377, 198, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198 ]
3.5
26
from rest_framework import generics from rest_framework.response import Response from rest_framework.views import APIView from .serializers import *
[ 6738, 1334, 62, 30604, 1330, 1152, 873, 198, 6738, 1334, 62, 30604, 13, 26209, 1330, 18261, 198, 6738, 1334, 62, 30604, 13, 33571, 1330, 3486, 3824, 769, 198, 6738, 764, 46911, 11341, 1330, 1635, 628, 628, 628, 628, 628, 628, 198 ]
3.926829
41
# -*- encoding:utf-8 -*-
[ 2, 532, 9, 12, 21004, 25, 40477, 12, 23, 532, 9, 12 ]
2
12
''' Created on 19 de ene. de 2016 @author: david ''' import time
[ 7061, 6, 198, 41972, 319, 678, 390, 551, 68, 13, 390, 1584, 198, 198, 31, 9800, 25, 21970, 198, 7061, 6, 198, 11748, 640, 628 ]
2.68
25
import asyncio from typing import Callable from typing import Dict from typing import List from typing import Optional from typing import Type from typing import Union try: import simplejson as json except ImportError: import json import websockets from valr_python.enum import AccountEvent from valr_python.enum import CurrencyPair from valr_python.enum import MessageFeedType from valr_python.enum import TradeEvent from valr_python.enum import WebSocketType from valr_python.exceptions import HookNotFoundError from valr_python.exceptions import WebSocketAPIException from valr_python.utils import JSONType from valr_python.utils import _get_valr_headers __all__ = ('WebSocketClient',)
[ 11748, 30351, 952, 198, 6738, 19720, 1330, 4889, 540, 198, 6738, 19720, 1330, 360, 713, 198, 6738, 19720, 1330, 7343, 198, 6738, 19720, 1330, 32233, 198, 6738, 19720, 1330, 5994, 198, 6738, 19720, 1330, 4479, 198, 198, 28311, 25, 198, 2...
3.661458
192
from enum import Enum
[ 6738, 33829, 1330, 2039, 388, 628 ]
3.833333
6
#!/usr/bin/env python3 from database import Database from rafflecollector import RaffleCollector import os import smtplib, ssl from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import schedule import time if __name__ == "__main__": e = Emailer() schedule.every().day.at("22:00").do(e.__init__) while True: schedule.run_pending() time.sleep(1)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 6738, 6831, 1330, 24047, 198, 6738, 374, 30697, 33327, 273, 1330, 371, 30697, 31337, 273, 198, 11748, 28686, 198, 11748, 895, 83, 489, 571, 11, 264, 6649, 198, 6738, 3053, 13, 76, ...
2.625806
155
import os import json import shutil import time from pathlib import Path from sys import platform # TODO: (stackoverflow.com/question/17136514/how-to-get-3rd-party-cookies) # stackoverflow.com/questions/22200134/make-selenium-grab-all-cookies, add the selenium, phantomjs part to catch ALL cookies # TODO: Maybe save cookies to global variable to compare them in another function without saving them? ''' loading more than one addon for firefox to use with selenium: extensions = [ 'jid1-KKzOGWgsW3Ao4Q@jetpack.xpi', '', '' ] for extension in extensions: driver.install_addon(extension_dir + extension, temporary=True) ''' def load_with_addon(driver, websites): """This method will load all websites with 'i don't care about cookies' preinstalled. Afterwards it will convert the cookies to dicts and save them locally for comparison Be aware that this method will delete all saved cookies""" print('creating dir for cookies with addon...') # checks if cookie dir already exists, creates an empty dir. if len(os.listdir('data/save/with_addon/')) != 0: shutil.rmtree('data/save/with_addon/') os.mkdir('data/save/with_addon/') print('saving cookies in firefox with addons ...') # the extension directory needs to be the one of your local machine # linux if platform == "linux": extension_dir = os.getenv("HOME") + "/.mozilla/firefox/7ppp44j6.default-release/extensions/" driver.install_addon(extension_dir + 'jid1-KKzOGWgsW3Ao4Q@jetpack.xpi', temporary=True) # windows if platform == "win32": extension_dir = str( Path.home()) + "/AppData/Roaming/Mozilla/Firefox/Profiles/shdzeteb.default-release/extensions/" print(extension_dir) driver.install_addon(extension_dir + 'jid1-KKzOGWgsW3Ao4Q@jetpack.xpi', temporary=True) for website in websites: name = website.split('www.')[1] driver.get(website) driver.execute_script("return document.readyState") cookies_addons = driver.get_cookies() cookies_dict = {} cookiecount = 0 for cookie in cookies_addons: cookies_dict = cookie print('data/save/with_addon/%s/%s_%s.json' % (name, name, cookiecount)) print(cookies_dict) # creates the website dir if not os.path.exists('data/save/with_addon/%s/' % name): os.mkdir('data/save/with_addon/%s/' % name) # saves the cookies into the website dir with open('data/save/with_addon/%s/%s_%s.json' % (name, name, cookiecount), 'w') as file: json.dump(cookies_dict, file, sort_keys=True) cookiecount += 1 def load_without_addon(driver, websites): """This method will load all websites on a vanilla firefox version. Afterwards it will convert the cookies to dicts and save them locally for comparison Be aware that this method will delete all saved cookies""" print('creating dir for cookies in vanilla...') # checks if cookie dir already exists, creates an empty dir. if len(os.listdir('data/save/without_addon/')) != 0: shutil.rmtree('data/save/without_addon/') os.mkdir('data/save/without_addon') print('saving cookies in firefox without addons ...') for website in websites: name = website.split('www.')[1] driver.get(website) driver.execute_script("return document.readyState") time.sleep(5) cookies_vanilla = driver.get_cookies() cookies_dict = {} cookiecount = 0 for cookie in cookies_vanilla: cookies_dict = cookie print('data/save/without_addon/%s/%s_%s.json' % (name, name, cookiecount)) print(cookies_dict) # creates the website dir if not os.path.exists('data/save/without_addon/%s/' % name): os.mkdir('data/save/without_addon/%s/' % name) # saves the cookies into the website dir with open('data/save/without_addon/%s/%s_%s.json' % (name, name, cookiecount), 'w') as file: json.dump(cookies_dict, file, sort_keys=True) cookiecount += 1 def close_driver_session(driver): """This method will end the driver session and close all windows. Driver needs to be initialized again afterwards""" driver.quit()
[ 11748, 28686, 198, 11748, 33918, 198, 11748, 4423, 346, 198, 11748, 640, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 25064, 1330, 3859, 628, 198, 2, 16926, 46, 25, 357, 25558, 2502, 11125, 13, 785, 14, 25652, 14, 1558, 1485, 2996, ...
2.554392
1,719
from flask import current_app from ..internals.database.database import get_cursor
[ 6738, 42903, 1330, 1459, 62, 1324, 198, 198, 6738, 11485, 23124, 874, 13, 48806, 13, 48806, 1330, 651, 62, 66, 21471, 198 ]
3.818182
22
""" Tank shapes package for Guns. This init file marks the package as a usable module. """
[ 37811, 15447, 15268, 5301, 329, 20423, 13, 198, 198, 1212, 2315, 2393, 8849, 262, 5301, 355, 257, 24284, 8265, 13, 198, 198, 37811, 198 ]
3.875
24
if __name__ == '__main__': main()
[ 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 198 ]
2.105263
19
import feedparser import vlc import argparse import sys import time import curses import wget if __name__ == '__main__': main()
[ 11748, 3745, 48610, 198, 11748, 410, 44601, 198, 11748, 1822, 29572, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 43878, 198, 11748, 266, 1136, 628, 628, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 2...
3.043478
46
#!/usr/bin/env python # -*- coding: utf-8 -*- """Convenience wrapper for running tfbs_footprinter directly from source tree.""" from tfbs_footprinter.tfbs_footprinter import main if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 220, 198, 220, 198, 37811, 3103, 574, 1240, 29908, 329, 2491, 48700, 1443, 62, 5898, 1050, 3849, 3264, 422, 2723, 5509,...
2.573034
89
import shap from pandas import DataFrame from sklearn.preprocessing import StandardScaler from metalfi.src.data.meta.importance.featureimportance import FeatureImportance
[ 11748, 427, 499, 198, 198, 6738, 19798, 292, 1330, 6060, 19778, 198, 6738, 1341, 35720, 13, 3866, 36948, 1330, 8997, 3351, 36213, 198, 198, 6738, 1138, 1604, 72, 13, 10677, 13, 7890, 13, 28961, 13, 11748, 590, 13, 30053, 11748, 590, 1...
3.782609
46
""" Original code Copyright 2009 [Waylan Limberg](http://achinghead.com) All changes Copyright 2008-2014 The Python Markdown Project Changed by Mohammad Tayseer to add CSS classes to table License: [BSD](http://www.opensource.org/licenses/bsd-license.php) """ from __future__ import absolute_import from __future__ import unicode_literals from markdown import Extension from markdown.extensions.tables import TableProcessor from markdown.util import etree def makeExtension(*args, **kwargs): return BootstrapTableExtension(*args, **kwargs)
[ 37811, 198, 20556, 2438, 15069, 3717, 685, 25309, 9620, 7576, 3900, 16151, 4023, 1378, 8103, 2256, 13, 785, 8, 198, 198, 3237, 2458, 15069, 3648, 12, 4967, 383, 11361, 2940, 2902, 4935, 198, 198, 31813, 416, 29674, 25569, 325, 263, 284,...
3.538462
156
import argparse import json import logging import os import sys import time import cv2 import numpy as np import PIL import torch import torch.nn as nn import torchvision.datasets as datasets import torchvision.transforms as transforms from PIL import Image from angle import generate_angle # from cifar100_dataset import get_dataset from slimmable_resnet20 import mutableResNet20 from utils import (ArchLoader, AvgrageMeter, CrossEntropyLabelSmooth, accuracy, get_lastest_model, get_parameters, save_checkpoint, bn_calibration_init) os.environ["CUDA_VISIBLE_DEVICES"] = "0" if __name__ == "__main__": main()
[ 11748, 1822, 29572, 198, 11748, 33918, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 640, 198, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 350, 4146, 198, 11748, 28034, 198, 11748, 28034...
2.900452
221
# -*- coding: utf-8 -*- """ Image, 2D{3} datasets ^^^^^^^^^^^^^^^^^^^^^ """ # %% # The 2D{3} dataset is two dimensional, :math:`d=2`, with # a single three-component dependent variable, :math:`p=3`. # A common example from this subset is perhaps the RGB image dataset. # An RGB image dataset has two spatial dimensions and one dependent # variable with three components corresponding to the red, green, and blue color # intensities. # # The following is an example of an RGB image dataset. import csdmpy as cp filename = "https://osu.box.com/shared/static/vdxdaitsa9dq45x8nk7l7h25qrw2baxt.csdf" ImageData = cp.load(filename) print(ImageData.data_structure) # %% # The tuple of the dimension and dependent variable instances from # ``ImageData`` instance are x = ImageData.dimensions y = ImageData.dependent_variables # %% # respectively. There are two dimensions, and the coordinates along each # dimension are print("x0 =", x[0].coordinates[:10]) # %% print("x1 =", x[1].coordinates[:10]) # %% # respectively, where only first ten coordinates along each dimension is displayed. # %% # The dependent variable is the image data, as also seen from the # :attr:`~csdmpy.DependentVariable.quantity_type` attribute # of the corresponding :ref:`dv_api` instance. print(y[0].quantity_type) # %% # From the value `pixel_3`, `pixel` indicates a pixel data, while `3` # indicates the number of pixel components. # %% # As usual, the components of the dependent variable are accessed through # the :attr:`~csdmpy.DependentVariable.components` attribute. # To access the individual components, use the appropriate array indexing. # For example, print(y[0].components[0]) # %% # will return an array with the first component of all data values. In this case, # the components correspond to the red color intensity, also indicated by the # corresponding component label. The label corresponding to # the component array is accessed through the # :attr:`~csdmpy.DependentVariable.component_labels` # attribute with appropriate indexing, that is print(y[0].component_labels[0]) # %% # To avoid displaying larger output, as an example, we print the shape of # each component array (using Numpy array's `shape` attribute) for the three # components along with their respective labels. # %% print(y[0].component_labels[0], y[0].components[0].shape) # %% print(y[0].component_labels[1], y[0].components[1].shape) # %% print(y[0].component_labels[2], y[0].components[2].shape) # %% # The shape (768, 1024) corresponds to the number of points from the each # dimension instances. # %% # .. note:: # In this example, since there is only one dependent variable, the index # of `y` is set to zero, which is ``y[0]``. The indices for the # :attr:`~csdmpy.DependentVariable.components` and the # :attr:`~csdmpy.DependentVariable.component_labels`, # on the other hand, spans through the number of components. # %% # Now, to visualize the dataset as an RGB image, import matplotlib.pyplot as plt ax = plt.subplot(projection="csdm") ax.imshow(ImageData, origin="upper") plt.tight_layout() plt.show()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 5159, 11, 362, 35, 90, 18, 92, 40522, 201, 198, 39397, 39397, 39397, 39397, 39397, 61, 201, 198, 37811, 201, 198, 2, 43313, 201, 198, 2, 383, 3...
2.950685
1,095
from .procedure import ( CrossCouplingBlueprint, GenericBlueprint )
[ 6738, 764, 1676, 771, 495, 1330, 357, 198, 220, 220, 220, 6372, 34, 280, 11347, 14573, 4798, 11, 198, 220, 220, 220, 42044, 14573, 4798, 198, 8, 198 ]
2.714286
28
s = float(input('Digite o valor do salrio: R$ ')) p = s + (s * 15 / 100) print('o salrio de R$ {} com mais 15% ficar {:.2f}'.format(s, p))
[ 82, 796, 12178, 7, 15414, 10786, 19511, 578, 267, 1188, 273, 466, 3664, 27250, 25, 371, 3, 705, 4008, 198, 79, 796, 264, 1343, 357, 82, 1635, 1315, 1220, 1802, 8, 198, 4798, 10786, 78, 3664, 27250, 390, 371, 3, 23884, 401, 285, 15...
2.262295
61
import codecs import sqlite3 import json from fnmatch import fnmatch from abc import ABC, abstractmethod
[ 11748, 40481, 82, 198, 11748, 44161, 578, 18, 198, 11748, 33918, 198, 6738, 24714, 15699, 1330, 24714, 15699, 198, 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198 ]
3.75
28
# Create your models here. import datetime from django.db import models from rest_framework.compat import MinValueValidator
[ 2, 13610, 534, 4981, 994, 13, 198, 11748, 4818, 8079, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 1334, 62, 30604, 13, 5589, 265, 1330, 1855, 11395, 47139, 1352, 628 ]
3.818182
33
"""An example of using Dakota as a component with PyMT. This example requires a WMT executor with PyMT installed, as well as the CSDMS Dakota interface and FrostNumberModel installed as components. """ import os from pymt.components import MultidimParameterStudy, FrostNumberModel from dakotathon.utils import configure_parameters c, d = FrostNumberModel(), MultidimParameterStudy() parameters = { "component": type(c).__name__, "descriptors": ["T_air_min", "T_air_max"], "partitions": [3, 3], "lower_bounds": [-20.0, 5.0], "upper_bounds": [-5.0, 20.0], "response_descriptors": [ "frostnumber__air", "frostnumber__surface", "frostnumber__stefan", ], "response_statistics": ["median", "median", "median"], } parameters, substitutes = configure_parameters(parameters) parameters["run_directory"] = c.setup(os.getcwd(), **substitutes) cfg_file = "frostnumber_model.cfg" # get from pymt eventually parameters["initialize_args"] = cfg_file dtmpl_file = cfg_file + ".dtmpl" os.rename(cfg_file, dtmpl_file) parameters["template_file"] = dtmpl_file d.setup(parameters["run_directory"], **parameters) d.initialize("dakota.yaml") d.update() d.finalize()
[ 37811, 2025, 1672, 286, 1262, 13336, 355, 257, 7515, 351, 9485, 13752, 13, 198, 198, 1212, 1672, 4433, 257, 370, 13752, 3121, 273, 351, 9485, 13752, 6589, 11, 355, 880, 355, 198, 1169, 9429, 35, 5653, 13336, 7071, 290, 15122, 15057, 1...
2.685144
451
from callback import ValidationHistory from dataloader import Dataloader from normalizer import Normalizer import tensorflow as tf import numpy as np import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() # Required arguments parser.add_argument( "-f", "--folder", required=True, help="Path to directory containing images") # Optional arguments. parser.add_argument( "-s", "--input_size", type=int, default=224, help="Input image size.") parser.add_argument( "-b", "--batch_size", type=int, default=2, help="Number of images in a training batch.") parser.add_argument( "-e", "--epochs", type=int, default=100, help="Number of training epochs.") parser.add_argument( "-seed", "--seed", type=int, default=42, help="Seed for data reproducing.") parser.add_argument( "-n", "--n_folds", type=int, default=5, help="Number of folds for CV Training") args = parser.parse_args() for fold_idx in range(args.n_folds): train(args, fold_idx)
[ 6738, 23838, 1330, 3254, 24765, 18122, 198, 6738, 4818, 282, 1170, 263, 1330, 360, 10254, 1170, 263, 198, 6738, 3487, 7509, 1330, 14435, 7509, 628, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 299, 32152, 355, 45941, 198, 11748,...
2.184211
570
# coding=utf-8 from orgmode_entry import OrgmodeEntry entry = u'#A Etwas machen:: DL: Morgen S: Heute Ausstellung am 23.09.2014 12:00 oder am Montag bzw. am 22.10 13:00 sollte man anschauen. ' org = OrgmodeEntry() # Use an absolute path org.inbox_file = '/Users/Alex/Documents/Planung/Planning/Inbox.org' org.delimiter = ':: ' # tag to separate the head from the body of the entry org.heading_suffix = "\n* " # depth of entry org.use_priority_tags = True # use priority tags: #b => [#B] org.priority_tag = '#' # tag that marks a priority value org.add_creation_date = True # add a creation date org.replace_absolute_dates = True # convert absolute dates like 01.10 15:00 into orgmode dates => <2016-10-01 Sun 15:00> org.replace_relative_dates = True # convert relative dates like monday or tomorrow into orgmode dates # Convert a schedule pattern into an org scheduled date org.convert_scheduled = True # convert sche org.scheduled_pattern = "S: " # Convert a deadline pattern into an org deadline org.convert_deadlines = True org.deadline_pattern = "DL: " org.smart_line_break = True # convert a pattern into a linebreak org.line_break_pattern = "\s\s" # two spaces # Cleanup spaces (double, leading, and trailing) org.cleanup_spaces = True entry = 'TODO ' + entry message = org.add_entry(entry).encode('utf-8') print(message)
[ 2, 19617, 28, 40477, 12, 23, 198, 198, 6738, 8745, 14171, 62, 13000, 1330, 1471, 70, 14171, 30150, 198, 198, 13000, 796, 334, 6, 2, 32, 412, 4246, 292, 8352, 831, 3712, 23641, 25, 37417, 268, 311, 25, 679, 1133, 27545, 301, 695, 2...
2.962801
457
import gzip import bz2 import lzma s = b'witch which has which witches wrist watch' with open('2.txt', 'wb') as f: f.write(s) with gzip.open('2.txt.gz', 'wb') as f: f.write(s) with bz2.open('2.txt.bz2', 'wb') as f: f.write(s) with lzma.open('2.txt.xz', 'wb') as f: f.write(s) print('txt', len(s)) print('gz ', len(gzip.compress(s))) print('bz2', len(bz2.compress(s))) print('xz ', len(lzma.compress(s)))
[ 11748, 308, 13344, 198, 11748, 275, 89, 17, 198, 11748, 300, 89, 2611, 198, 198, 82, 796, 275, 6, 42248, 543, 468, 543, 34773, 15980, 2342, 6, 198, 4480, 1280, 10786, 17, 13, 14116, 3256, 705, 39346, 11537, 355, 277, 25, 277, 13, ...
2.164894
188
import pytz from datetime import datetime MEETING_HOURS = range(6, 23) # meet from 6 - 22 max TIMEZONES = set(pytz.all_timezones) def within_schedule(utc, *timezones): """Receive a utc datetime and one or more timezones and check if they are all within schedule (MEETING_HOURS)""" times = [] timezone_list = list(timezones) for zone in timezone_list: if zone not in TIMEZONES: raise ValueError tz = pytz.timezone(zone) times.append(pytz.utc.localize(utc).astimezone(tz)) boolean = [] for time in times: if time.hour in MEETING_HOURS: boolean.append(True) else: boolean.append(False) return all(boolean) pass
[ 11748, 12972, 22877, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 11682, 2767, 2751, 62, 46685, 6998, 796, 2837, 7, 21, 11, 2242, 8, 220, 1303, 1826, 422, 718, 532, 2534, 3509, 198, 34694, 57, 39677, 796, 900, 7, 9078, 22877, ...
2.18314
344
from os import sys, environ from tracker.__main__ import args # Name of the file to save kernel versions json DB_FILE_NAME = "data.json" # By default looks up in env for api and chat id or just put your stuff in here # directly if you prefer it that way BOT_API = environ.get("BOT_API") CHAT_ID = environ.get("CHAT_ID") if args.notify: if (BOT_API and CHAT_ID) is None: print("Either BOT_API or CHAT_ID is empty!") sys.exit(1)
[ 6738, 28686, 1330, 25064, 11, 551, 2268, 198, 6738, 30013, 13, 834, 12417, 834, 1330, 26498, 198, 198, 2, 6530, 286, 262, 2393, 284, 3613, 9720, 6300, 33918, 198, 11012, 62, 25664, 62, 20608, 796, 366, 7890, 13, 17752, 1, 198, 198, ...
2.710843
166
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
3.888889
9
# test_utils.py overwrite(-a !) import pytest import pandas as pd import datetime from utils import is_working_day, load_data
[ 2, 1332, 62, 26791, 13, 9078, 220, 220, 49312, 32590, 64, 220, 5145, 8, 198, 11748, 12972, 9288, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 4818, 8079, 198, 6738, 3384, 4487, 1330, 318, 62, 16090, 62, 820, 11, 3440, 62, 7890,...
2.87234
47
import json import subprocess from CommonServerPython import * TWIST_EXE = '/dnstwist/dnstwist.py' if demisto.command() == 'dnstwist-domain-variations': KEYS_TO_MD = ["whois_updated", "whois_created", "dns_a", "dns_mx", "dns_ns"] DOMAIN = demisto.args()['domain'] LIMIT = int(demisto.args()['limit']) WHOIS = demisto.args().get('whois') dnstwist_result = get_dnstwist_result(DOMAIN, WHOIS == 'yes') new_result = get_domain_to_info_map(dnstwist_result) md = tableToMarkdown('dnstwist for domain - ' + DOMAIN, new_result, headers=["domain-name", "IP Address", "dns_mx", "dns_ns", "whois_updated", "whois_created"]) domain_context = new_result[0] # The requested domain for variations domains_context_list = new_result[1:LIMIT + 1] # The variations domains domains = [] for item in domains_context_list: temp = {"Name": item["domain-name"]} if "IP Address" in item: temp["IP"] = item["IP Address"] if "dns_mx" in item: temp["DNS-MX"] = item["dns_mx"] if "dns_ns" in item: temp["DNS-NS"] = item["dns_ns"] if "whois_updated" in item: temp["WhoisUpdated"] = item["whois_updated"] if "whois_created" in item: temp["WhoisCreated"] = item["whois_created"] domains.append(temp) ec = {"Domains": domains} if "domain-name" in domain_context: ec["Name"] = domain_context["domain-name"] if "IP Address" in domain_context: ec["IP"] = domain_context["IP Address"] if "dns_mx" in domain_context: ec["DNS-MX"] = domain_context["dns_mx"] if "dns_ns" in domain_context: ec["DNS-NS"] = domain_context["dns_ns"] if "whois_updated" in domain_context: ec["WhoisUpdated"] = domain_context["whois_updated"] if "whois_created" in domain_context: ec["WhoisCreated"] = domain_context["whois_created"] entry_result = { 'Type': entryTypes['note'], 'ContentsFormat': formats['json'], 'Contents': dnstwist_result, 'HumanReadable': md, 'ReadableContentsFormat': formats['markdown'], 'EntryContext': {'dnstwist.Domain(val.Name == obj.Name)': ec} } demisto.results(entry_result) if demisto.command() == 'test-module': # This is the call made when pressing the integration test button. subprocess.check_output([TWIST_EXE, '-h'], stderr=subprocess.STDOUT) demisto.results('ok') sys.exit(0)
[ 11748, 33918, 198, 11748, 850, 14681, 198, 198, 6738, 8070, 10697, 37906, 1330, 1635, 198, 198, 34551, 8808, 62, 6369, 36, 796, 31051, 32656, 301, 86, 396, 14, 32656, 301, 86, 396, 13, 9078, 6, 198, 198, 361, 1357, 396, 78, 13, 2181...
2.297521
1,089
# encoding: utf-8 import inspect def caller(frame=2): """ Returns the object that called the object that called this function. e.g. A calls B. B calls calling_object. calling object returns A. :param frame: 0 represents this function 1 represents the caller of this function (e.g. B) 2 (default) represents the caller of B :return: object reference """ stack = inspect.stack() try: obj = stack[frame][0].f_locals[u'self'] except KeyError: pass # Not called from an object else: return obj
[ 2, 21004, 25, 3384, 69, 12, 23, 198, 198, 11748, 10104, 628, 198, 4299, 24955, 7, 14535, 28, 17, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 16409, 262, 2134, 326, 1444, 262, 2134, 326, 1444, 428, 2163, 13, 628, 220, 220,...
2.575758
231
# pylint: disable=missing-docstring,protected-access """ Copyright 2017 ARM Limited 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. """ import unittest from icetea_lib.ResourceProvider.ResourceRequirements import ResourceRequirements if __name__ == '__main__': unittest.main()
[ 2, 279, 2645, 600, 25, 15560, 28, 45688, 12, 15390, 8841, 11, 24326, 12, 15526, 198, 198, 37811, 198, 15269, 2177, 20359, 15302, 198, 26656, 15385, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 583...
3.740196
204
#!/bin/python3 import sys prev = '' cnt = 0 for x in sys.stdin.readlines(): q, w = x.split('\t')[0], int(x.split('\t')[1]) if (prev == q): cnt += 1 else: if (cnt > 0): print(prev + '\t' + str(cnt)) prev = q cnt = w if (cnt > 0): print(prev + '\t' + str(cnt))
[ 2, 48443, 8800, 14, 29412, 18, 198, 198, 11748, 25064, 198, 198, 47050, 796, 10148, 198, 66, 429, 796, 657, 198, 1640, 2124, 287, 25064, 13, 19282, 259, 13, 961, 6615, 33529, 198, 220, 220, 220, 10662, 11, 266, 796, 2124, 13, 35312,...
1.773481
181
import attr from covid19_id.utils import ValueInt
[ 11748, 708, 81, 198, 198, 6738, 39849, 312, 1129, 62, 312, 13, 26791, 1330, 11052, 5317, 628 ]
3.058824
17
import json import hashlib from .test_case.blockchain import BlockchainTestCase
[ 11748, 33918, 198, 11748, 12234, 8019, 198, 198, 6738, 764, 9288, 62, 7442, 13, 9967, 7983, 1330, 29724, 14402, 20448, 628 ]
3.904762
21
import warnings import numpy as np import pandas as pd import xgboost as xgb import scipy.stats as st from sklearn.neighbors import BallTree from xgbse._base import XGBSEBaseEstimator from xgbse.converters import convert_data_to_xgb_format, convert_y from xgbse.non_parametric import ( calculate_kaplan_vectorized, get_time_bins, calculate_interval_failures, ) # at which percentiles will the KM predict KM_PERCENTILES = np.linspace(0, 1, 11) DEFAULT_PARAMS = { "objective": "survival:aft", "eval_metric": "aft-nloglik", "aft_loss_distribution": "normal", "aft_loss_distribution_scale": 1, "tree_method": "hist", "learning_rate": 5e-2, "max_depth": 8, "booster": "dart", "subsample": 0.5, "min_child_weight": 50, "colsample_bynode": 0.5, } DEFAULT_PARAMS_TREE = { "objective": "survival:cox", "eval_metric": "cox-nloglik", "tree_method": "exact", "max_depth": 100, "booster": "dart", "subsample": 1.0, "min_child_weight": 30, "colsample_bynode": 1.0, } # class to turn XGB into a kNN with a kaplan meier in the NNs # class to turn XGB into a kNN with a kaplan meier in the NNs
[ 11748, 14601, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 2124, 70, 39521, 355, 2124, 22296, 198, 11748, 629, 541, 88, 13, 34242, 355, 336, 198, 6738, 1341, 35720, 13, 710, 394, 32289, 13...
2.381339
493
import math import numpy as np import pandas as pd import tensorflow as tf import datetime as dt import matplotlib.pyplot as plt import matplotlib.dates as mdates import warnings warnings.filterwarnings('ignore') # Hiperparametri epoch_max = 10 alpha_max = 0.025 alpha_min = 0.001 batch_size = 32 window_size = 14 test_ratio = 0.1 max_time = 16 lstm_size = 64 # Ucitavanje podataka csv = pd.read_csv('data/sp500.csv') dates, data = csv['Date'].values, csv['Close'].values # Konverzija datuma dates = [dt.datetime.strptime(d, '%Y-%m-%d').date() for d in dates] dates = [dates[i + max_time] for i in range(len(dates) - max_time)] # Grupisanje podataka pomocu kliznog prozora data = [data[i : i + window_size] for i in range(len(data) - window_size)] # Normalizacija podataka norm = [data[0][0]] + [data[i-1][-1] for i, _ in enumerate(data[1:])] data = [curr / norm[i] - 1.0 for i, curr in enumerate(data)] nb_samples = len(data) - max_time nb_train = int(nb_samples * (1.0 - test_ratio)) nb_test = nb_samples - nb_train nb_batches = math.ceil(nb_train / batch_size) # Grupisanje podataka za propagaciju greske kroz vreme x = [data[i : i + max_time] for i in range(nb_samples)] y = [data[i + max_time][-1] for i in range(nb_samples)] # Skup podataka za treniranje train_x = [x[i : i + batch_size] for i in range(0, nb_train, batch_size)] train_y = [y[i : i + batch_size] for i in range(0, nb_train, batch_size)] # Skup podataka za testiranje test_x, test_y = x[-nb_test:], y[-nb_test:] # Skup podataka za denormalizaciju norm_y = [norm[i + max_time] for i in range(nb_samples)] norm_test_y = norm_y[-nb_test:] tf.reset_default_graph() # Cene tokom prethodnih dana X = tf.placeholder(tf.float32, [None, max_time, window_size]) # Cena na trenutni dan Y = tf.placeholder(tf.float32, [None]) # Stopa ucenja L = tf.placeholder(tf.float32) # LSTM sloj rnn = tf.contrib.rnn.MultiRNNCell([tf.contrib.rnn.LSTMCell(lstm_size)]) # Izlaz LSTM sloja val, _ = tf.nn.dynamic_rnn(rnn, X, dtype=tf.float32) val = tf.transpose(val, [1, 0, 2]) # Poslednji izlaz LSTM sloja last = tf.gather(val, val.get_shape()[0] - 1) # Obucavajuci parametri weight = tf.Variable(tf.random_normal([lstm_size, 1])) bias = tf.Variable(tf.constant(0.0, shape=[1])) # Predvidjena cena prediction = tf.add(tf.matmul(last, weight), bias) # MSE za predikciju loss = tf.reduce_mean(tf.square(tf.subtract(prediction, Y))) # Gradijentni spust pomocu Adam optimizacije optimizer = tf.train.AdamOptimizer(L).minimize(loss) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # Treniranje modela for epoch in range(epoch_max): # Adaptiranje stope ucenja epoch_loss, alpha = 0, max(alpha_min, alpha_max * (1 - epoch / epoch_max)) # Mini batch gradijentni spust for b in np.random.permutation(nb_batches): loss_val, _ = sess.run([loss, optimizer], {X: train_x[b], Y: train_y[b], L: alpha}) epoch_loss += loss_val print('Epoch: {}/{}\tLoss: {}'.format(epoch+1, epoch_max, epoch_loss)) # Testiranje modela test_pred = sess.run(prediction, {X: test_x, Y: test_y, L: alpha}) # Tacnost modela za predikciju monotonosti fluktuacije cene acc = sum(1 for i in range(nb_test) if test_pred[i] * test_y[i] > 0) / nb_test print('Accuracy: {}'.format(acc)) # Denormalizacija podataka denorm_y = [(curr + 1.0) * norm_test_y[i] for i, curr in enumerate(test_y)] denorm_pred = [(curr + 1.0) * norm_test_y[i] for i, curr in enumerate(test_pred)] # Prikazivanje predikcija plt.figure(figsize=(16,4)) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=7)) plt.plot(dates[-nb_test:], denorm_y, '-b', label='Actual') plt.plot(dates[-nb_test:], denorm_pred, '--r', label='Predicted') plt.gcf().autofmt_xdate() plt.legend() plt.show()
[ 11748, 10688, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 4818, 8079, 355, 288, 83, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, ...
2.257176
1,742
# Generated by Django 3.1 on 2020-10-10 14:31 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 319, 12131, 12, 940, 12, 940, 1478, 25, 3132, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.966667
30
from os import path package_dir = path.abspath(path.dirname(__file__))
[ 6738, 28686, 1330, 3108, 198, 198, 26495, 62, 15908, 796, 3108, 13, 397, 2777, 776, 7, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 4008, 628 ]
2.807692
26
# -*- coding: utf-8 -*- __author__ = 'S.I. Mimilakis' __copyright__ = 'MacSeNet' import torch from torch.autograd import Variable import numpy as np dtype = torch.DoubleTensor np.random.seed(2183) torch.manual_seed(2183) # D is the "batch size"; N is input dimension; # H is hidden dimension; N_out is output dimension. D, N, H, N_out = 1, 20, 20, 20 # Create random Tensors to hold input and outputs, and wrap them in Variables. # Setting requires_grad=False indicates that we do not need to compute gradients # with respect to these Variables during the backward pass. x = Variable(torch.randn(N, D).type(dtype), requires_grad=True) y = Variable(torch.randn(N_out, D).type(dtype), requires_grad=False) # Create random Tensors for weights, and wrap them in Variables. # Setting requires_grad=True indicates that we want to compute gradients with # respect to these Variables during the backward pass. layers = [] biases = [] w_e = Variable(torch.randn(N, H).type(dtype), requires_grad=True) b_e = Variable(torch.randn(H,).type(dtype), requires_grad=True) w_d = Variable(torch.randn(H, N_out).type(dtype), requires_grad=True) b_d = Variable(torch.randn(N_out,).type(dtype), requires_grad=True) layers.append(w_e) layers.append(w_d) biases.append(b_e) biases.append(b_d) # Matrices we need the gradients wrt parameters = torch.nn.ParameterList() p_e = torch.nn.Parameter(torch.randn(N, H).type(dtype), requires_grad=True) p_d = torch.nn.Parameter(torch.randn(H, N_out).type(dtype), requires_grad=True) parameters.append(p_e) parameters.append(p_d) # Non-linearity relu = torch.nn.ReLU() comb_matrix = torch.autograd.Variable(torch.eye(N), requires_grad=True).double() for index in range(2): b_sc_m = relu(parameters[index].mm((layers[index] + biases[index]).t())) b_scaled = layers[index] * b_sc_m comb_matrix = torch.matmul(b_scaled, comb_matrix) y_pred = torch.matmul(comb_matrix, x) loss = (y - y_pred).norm(1) loss.backward() delta_term = (torch.sign(y_pred - y)).mm(x.t()) # With relu w_tilde_d = relu(parameters[1].mm((layers[1] + biases[1]).t())) * w_d w_tilde_e = w_e * relu(parameters[0].mm((layers[0] + biases[0]).t())) relu_grad_dec = p_d.mm((w_d + b_d).t()).gt(0).double() relu_grad_enc = p_e.mm((w_e + b_e).t()).gt(0).double() p_d_grad_hat = (delta_term.mm(w_tilde_e.t()) * w_d * relu_grad_dec).mm((w_d + b_d)) p_e_grad_hat = (w_tilde_d.t().mm(delta_term) * w_e * relu_grad_enc).mm((w_e + b_e)) print('Error between autograd computation and calculated:'+str((parameters[1].grad - p_d_grad_hat).abs().max())) print('Error between autograd computation and calculated:'+str((parameters[0].grad - p_e_grad_hat).abs().max())) # EOF
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 834, 9800, 834, 796, 705, 50, 13, 40, 13, 337, 26641, 27321, 6, 198, 834, 22163, 4766, 834, 796, 705, 14155, 4653, 7934, 6, 198, 198, 11748, 28034, 198, 6738, 28034, ...
2.494403
1,072