content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
from corehq import toggles from corehq.apps.app_manager.app_schemas.case_properties import ( ParentCasePropertyBuilder, get_usercase_properties, ) from corehq.apps.app_manager.const import USERCASE_TYPE from corehq.apps.app_manager.util import is_usercase_in_use from corehq.apps.data_dictionary.util import get_case_property_description_dict def get_casedb_schema(form): """Get case database schema definition for vellum to display as an external data source. This lists all case types and their properties for the given app. """ app = form.get_app() base_case_type = form.get_module().case_type if form.requires_case() else None builder = ParentCasePropertyBuilder.for_app(app, ['case_name'], include_parent_properties=False) related = builder.get_parent_type_map(None) map = builder.get_properties_by_case_type() descriptions_dict = get_case_property_description_dict(app.domain) if base_case_type: # Generate hierarchy of case types, represented as a list of lists of strings: # [[base_case_type], [parent_type1, parent_type2...], [grandparent_type1, grandparent_type2...]] # Vellum case management only supports three levels generation_names = ['case', 'parent', 'grandparent'] generations = [[] for g in generation_names] _add_ancestors(base_case_type, 0) # Remove any duplicate types or empty generations generations = [set(g) for g in generations if len(g)] else: generations = [] subsets = [{ "id": generation_names[i], "name": "{} ({})".format(generation_names[i], " or ".join(ctypes)) if i > 0 else base_case_type, "structure": { p: {"description": descriptions_dict.get(t, {}).get(p, '')} for t in ctypes for p in map[t]}, "related": {"parent": { "hashtag": "#case/" + generation_names[i + 1], "subset": generation_names[i + 1], "key": "@case_id", }} if i < len(generations) - 1 else None, } for i, ctypes in enumerate(generations)] if is_usercase_in_use(app.domain): subsets.append({ "id": USERCASE_TYPE, "name": "user", "key": "@case_type", "structure": {p: {} for p in get_usercase_properties(app)[USERCASE_TYPE]}, }) return { "id": "casedb", "uri": "jr://instance/casedb", "name": "case", "path": "/casedb/case", "structure": {}, "subsets": subsets, }
[ 6738, 4755, 71, 80, 1330, 284, 32723, 198, 6738, 4755, 71, 80, 13, 18211, 13, 1324, 62, 37153, 13, 1324, 62, 1416, 4411, 292, 13, 7442, 62, 48310, 1330, 357, 198, 220, 220, 220, 16774, 20448, 21746, 32875, 11, 198, 220, 220, 220, ...
2.447343
1,035
matches = True if mat<caret>
[ 6759, 2052, 796, 6407, 198, 361, 2603, 27, 6651, 83, 29 ]
2.545455
11
import math import aerospike from aerospike import predicates as p from aerospike import exception as ex from flask import current_app aerospike_host = current_app.config['AEROSPIKE_HOST'] aerospike_port = current_app.config['AEROSPIKE_PORT'] namespace = current_app.config['AEROSPIKE_NAMESPACE'] set_name = current_app.config['AEROSPIKE_SET_NAME'] n_replicas = 1 config = { 'hosts': [ (aerospike_host, aerospike_port) ], 'policies': { 'timeout': 1000 # milliseconds } } client = aerospike.client(config).connect() # cannot limit the number of rows, only percent # there is no start offset option # https://discuss.aerospike.com/t/can-you-limit-the-number-of-returned-records/1330/2 # https://discuss.aerospike.com/t/official-as-approach-to-pagination/2532 # https://stackoverflow.com/questions/25927736/limit-number-of-records-in-aerospike-select-query # if there is no more record, return -1 as next # cannot limit the number of rows, only percent # there is no start offset option # https://discuss.aerospike.com/t/can-you-limit-the-number-of-returned-records/1330/2 # https://discuss.aerospike.com/t/official-as-approach-to-pagination/2532 # https://stackoverflow.com/questions/25927736/limit-number-of-records-in-aerospike-select-query # if there is no more record, return -1 as next
[ 11748, 10688, 198, 11748, 9551, 2117, 522, 198, 198, 6738, 9551, 2117, 522, 1330, 2747, 16856, 355, 279, 198, 6738, 9551, 2117, 522, 1330, 6631, 355, 409, 198, 198, 6738, 42903, 1330, 1459, 62, 1324, 198, 198, 25534, 2117, 522, 62, 47...
2.714575
494
""" author: @nimrobotics description: calculates the effective connectivity between regions and plots them """ import numpy as np import scipy.io import glob import sys sys.path.append('../utils') from plots import plotData dir = "./process3/" #directory of the data outdir = 'process3/' #directory to save the plots regions = 3 #number of regions files = glob.glob(dir+'/*_.mat') # get all the files in the directory for file in files: print('Processing condition: ', file) data = scipy.io.loadmat(file) #load data from the directory fval = data['fval'] #fval pval = data['pval'] #pval sig = data['sig'] #sig cd = data['cd'] #cd print('fval shape: ',fval.shape) print('\nfval \n',fval) print('pval shape: ',pval.shape) print('sig shape: ',sig.shape) print('\nsig \n',sig) print(cd.shape) # elementwise multiplication of fval and sig(0/1) fval_sig = np.multiply(fval, sig) print(fval_sig.shape) print('\nfval_sig \n',fval_sig) # fval_sig = np.mean(fval_sig, axis=2) # average over files # print(fval_sig.shape) # fval = np.mean(fval, axis=2) labels = ['PFC', 'PM-MC', 'VC'] #labels for the regions condition = file.split('/')[-1].split('.')[0] #get the condition name plot = plotData(fval_sig, labels, outdir, colormap='viridis', dpi=300, title='EC: '+condition, filename='EC_'+condition +'.png') plot.matrixPlot() plot.circularPlot()
[ 37811, 198, 9800, 25, 2488, 77, 320, 305, 13645, 873, 198, 11213, 25, 43707, 262, 4050, 19843, 1022, 7652, 290, 21528, 606, 198, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 629, 541, 88, 13, 952, 198, 11748, 15095, 198...
2.521053
570
from django.db import models from sorl.thumbnail import ImageField # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 25655, 75, 13, 400, 20566, 1330, 7412, 15878, 198, 198, 2, 13610, 534, 4981, 994, 13 ]
3.76
25
# os import sys, os, time, logging # CPU DS stack import pandas as pd import numpy as np import sklearn # GPU DS stack [ rapids ] import gcsfs # scaling library import dask # data ingestion [ CPU ] from pyarrow import orc as pyarrow_orc # ML models from sklearn import ensemble import xgboost # data set splits from sklearn.model_selection import train_test_split as sklearn_train_test_split # device query ##hack try: import cudf, cuml from cuml.preprocessing.model_selection import train_test_split as cuml_train_test_split import pynvml import cupy except: print("Caught import failures -- probably missing GPU") # memory query import psutil # i/o import logging, json, pprint default_sagemaker_paths = { 'base': '/opt/ml', 'code': '/opt/ml/code', 'data': '/opt/ml/input', 'train_data': '/opt/ml/input/data/training', 'hyperparams': '/opt/ml/input/config/hyperparameters.json', 'model': '/opt/ml/model', 'output': '/opt/ml/output', } # perf_counter = highest available timer resolution ''' https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html#sklearn.ensemble.RandomForestClassifier.fit n_estimators=100, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, bootstrap=True, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, class_weight=None, ccp_alpha=0.0, max_samples=None '''
[ 2, 28686, 198, 11748, 25064, 11, 28686, 11, 640, 11, 18931, 198, 198, 2, 9135, 17400, 8931, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 1341, 35720, 198, 198, 2, 11362, 17400, 8931, 685, 4095,...
2.690189
581
#!/usr/bin/env python3 import pyglet import glooey import autoprop import datetime from pyglet.gl import * from vecrec import Vector, Rect window = pyglet.window.Window() gui = glooey.Gui(window) gui.add(LineClock()) pyglet.app.run()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 12972, 70, 1616, 198, 11748, 1278, 2238, 2959, 198, 11748, 22320, 1773, 198, 11748, 4818, 8079, 198, 6738, 12972, 70, 1616, 13, 4743, 1330, 1635, 198, 6738, 1569, 7513, ...
2.677778
90
# coding=utf-8 # Generated by Django 2.0.7 on 2018-07-27 10:56 from django.db import migrations, models
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 2980, 515, 416, 37770, 362, 13, 15, 13, 22, 319, 2864, 12, 2998, 12, 1983, 838, 25, 3980, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.717949
39
import os import re import sys import json #upper import sys.path.append("../../") from utils import levenshtein from utils.io import load_json, write_to def strQ2B(ustring): """""" rstring = "" for uchar in ustring: inside_code=ord(uchar) if inside_code == 12288: # inside_code = 32 elif (inside_code >= 65281 and inside_code <= 65374): # inside_code -= 65248 rstring += chr(inside_code) return rstring def generate(need_preprocess=True): """ split raw data(train.json) to preprocessed target """ #file = open("../../data/rawdata/ctc2021/train.json", 'r', encoding='utf-8') data = get_sighan_from_json() train_source, train_target = json2list(data["train"], need_preprocess) valid14_source, valid14_target = json2list(data["valid14"], need_preprocess) valid_source, valid_target = json2list(data["valid"], need_preprocess) print(train_source[:3], train_target[:3]) print(len(train_source), len(train_target)) print(valid_source[:3], valid_target[:3]) print(len(valid_source), len(valid_target)) need_remove = {} # cluster all need_remove for i, sample in enumerate(valid_source): for j, char in enumerate(sample): tgt = valid_target[i][j] if char != tgt: need_remove[ (char, tgt) ] = 0 for i, sample in enumerate(valid14_source): for j, char in enumerate(sample): tgt = valid14_target[i][j] if char != tgt: need_remove[ (char, tgt) ] = 0 #remove remove_count = 0 new_train_source, new_train_target = [], [] for i, sample in enumerate(train_source): skip = False for j, char in enumerate(sample): tgt = train_target[i][j] if char != tgt: key = (char, tgt) if key in need_remove: skip = True remove_count += 1 break if not skip: new_train_source.append(sample) new_train_target.append(train_target[i]) print("Total Skip: ", remove_count) train_source, train_target = new_train_source, new_train_target #f_src = levenstein.tokenize(source, vocab_file_path="vocab.txt") train_through = levenshtein.convert_from_sentpair_through(train_source, train_target, train_source) valid14_through = levenshtein.convert_from_sentpair_through(valid14_source, valid14_target, valid14_source) valid_through = levenshtein.convert_from_sentpair_through(valid_source, valid_target, valid_source) #print(train_through[0], valid_through[0]) #output_name = "enchanted" #output_name = "raw" output_name = "holy" write_to("../../data/rawdata/sighan/" + output_name + "/train.src", "\n".join(train_source)) write_to("../../data/rawdata/sighan/"+output_name+"/train.tgt", "\n".join(train_target)) #write_to("../../data/rawdata/sighan/std/train.through", "\n".join(train_through)) write_to("../../data/rawdata/sighan/"+output_name+"/valid14.src", "\n".join(valid14_source)) write_to("../../data/rawdata/sighan/"+output_name+"/valid14.tgt", "\n".join(valid14_target)) #write_to("../../data/rawdata/sighan/std/valid14.through", "\n".join(valid14_through)) write_to("../../data/rawdata/sighan/"+output_name+"/test.src", "\n".join(valid_source)) write_to("../../data/rawdata/sighan/"+output_name+"/test.tgt", "\n".join(valid_target)) #write_to("../../data/rawdata/sighan/std/test.through", "\n".join(valid_through)) write_to("../../data/rawdata/sighan/"+output_name+"/valid.src", "\n".join(valid_source)) write_to("../../data/rawdata/sighan/"+output_name+"/valid.tgt", "\n".join(valid_target)) #write_to("../../data/rawdata/sighan/std/valid.through", "\n".join(valid_through[:500])) if __name__ == "__main__": generate()
[ 11748, 28686, 198, 11748, 302, 198, 11748, 25064, 198, 11748, 33918, 198, 198, 2, 45828, 1330, 220, 198, 17597, 13, 6978, 13, 33295, 7203, 40720, 40720, 4943, 220, 198, 6738, 3384, 4487, 1330, 443, 574, 1477, 22006, 198, 6738, 3384, 448...
2.280138
1,742
# from .backend import * # noqa: F401,F403 from .sbackend import *
[ 2, 422, 764, 1891, 437, 1330, 1635, 220, 1303, 645, 20402, 25, 376, 21844, 11, 37, 31552, 198, 6738, 764, 82, 1891, 437, 1330, 1635 ]
2.68
25
# ---------------------------------------------------------------------------- # Copyright (C) Microsoft. All rights reserved. # Licensed under the MIT license. # ---------------------------------------------------------------------------- import os import binascii import struct import shutil import inspect import sys if __name__ == '__main__': binary_hook(sys.argv[1], sys.argv[2])
[ 2, 16529, 10541, 198, 2, 220, 15069, 357, 34, 8, 5413, 13, 1439, 2489, 10395, 13, 198, 2, 220, 49962, 739, 262, 17168, 5964, 13, 198, 2, 16529, 10541, 198, 198, 11748, 28686, 198, 11748, 9874, 292, 979, 72, 198, 11748, 2878, 198, ...
4.55814
86
import versioneer from setuptools import setup setup(name='firex-bundle-ci', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='FireX CI services', url='https://github.com/FireXStuff/firex-bundle-ci.git', author='Core FireX Team', author_email='firex-dev@gmail.com', license='BSD-3-Clause', packages=['firex_bundle_ci'], zip_safe=True, install_requires=[ "firexapp", "firex-keeper", "lxml", "xunitmerge", "unittest-xml-reporting" ], )
[ 11748, 2196, 28153, 198, 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 40406, 7, 3672, 11639, 6495, 87, 12, 65, 31249, 12, 979, 3256, 198, 220, 220, 220, 220, 220, 2196, 28, 690, 7935, 263, 13, 1136, 62, 9641, 22784, 198, 220, 220,...
2.092199
282
# Copyright (c) 2016 SwiftStack, Inc. # # 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.
[ 2, 15069, 357, 66, 8, 1584, 15608, 25896, 11, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789,...
3.762821
156
""" Introduces utilities used throughout the package, including: - interfaces for making objects `distpy.util.Savable.Savable` and `distpy.util.Loadable.Loadable` in binary hdf5 files using h5py - helper methods for using h5py to save and load variables and arrays (`h5py_extensions`) - type category definitions (`distpy.util.TypeCategories`) - functions for making univariate histograms, bivariate histograms, and triangle plots (`distpy.util.TrianglePlot`) - a class that uses strings to represent an `distpy.util.Expression.Expression` that can be modified and have arguments passed to it before being evaluated - a class that represents **File**: $DISTPY/distpy/util/\\_\\_init\\_\\_.py **Author**: Keith Tauscher **Date**: 14 May 2021 """ from distpy.util.Savable import Savable from distpy.util.Loadable import Loadable from distpy.util.TypeCategories import bool_types, int_types, float_types,\ real_numerical_types, complex_numerical_types, numerical_types,\ sequence_types from distpy.util.h5py_extensions import create_hdf5_dataset, get_hdf5_value,\ HDF5Link, save_dictionary, load_dictionary from distpy.util.TrianglePlot import univariate_histogram,\ confidence_contour_2D, bivariate_histogram, triangle_plot from distpy.util.Expression import Expression from distpy.util.SparseSquareBlockDiagonalMatrix import\ SparseSquareBlockDiagonalMatrix
[ 37811, 198, 15005, 728, 20081, 973, 3690, 262, 5301, 11, 1390, 25, 198, 198, 12, 20314, 329, 1642, 5563, 4600, 17080, 9078, 13, 22602, 13, 47362, 540, 13, 47362, 540, 63, 290, 198, 220, 4600, 17080, 9078, 13, 22602, 13, 8912, 540, 1...
3.175
440
flag = "flag{b3453333-9da9-49ae-b4ed-0017c392d58e}" e1 = 65537 e2 = 368273
[ 32109, 796, 366, 32109, 90, 65, 27712, 24840, 12, 24, 6814, 24, 12, 2920, 3609, 12, 65, 19, 276, 12, 405, 1558, 66, 32321, 67, 3365, 68, 36786, 198, 68, 16, 796, 45021, 2718, 198, 68, 17, 796, 43019, 27367 ]
1.85
40
import itertools from .base import Package
[ 11748, 340, 861, 10141, 198, 198, 6738, 764, 8692, 1330, 15717, 628, 628 ]
3.615385
13
from __future__ import with_statement from nose.tools import assert_true from os.path import exists import numpy as np from nibabel import Nifti1Image from numpy.testing import assert_equal from ...utils.simul_multisubject_fmri_dataset import surrogate_3d_dataset from ..bsa_io import make_bsa_image from nibabel.tmpdirs import InTemporaryDirectory def test_parcel_intra_from_3d_images_list(): """Test that a parcellation is generated, starting from a list of 3D images """ # Generate an image shape = (5, 5, 5) contrast_id = 'plop' mask_image = Nifti1Image(np.ones(shape), np.eye(4)) #mask_images = [mask_image for _ in range(5)] with InTemporaryDirectory() as dir_context: data_image = ['image_%d.nii' % i for i in range(5)] for datim in data_image: surrogate_3d_dataset(mask=mask_image, out_image_file=datim) #run the algo landmark, hrois = make_bsa_image( mask_image, data_image, threshold=10., smin=0, sigma=1., prevalence_threshold=0, prevalence_pval=0.5, write_dir=dir_context, algorithm='density', contrast_id=contrast_id) assert_equal(landmark, None) assert_equal(len(hrois), 5) assert_true(exists('density_%s.nii' % contrast_id)) assert_true(exists('prevalence_%s.nii' % contrast_id)) assert_true(exists('AR_%s.nii' % contrast_id)) assert_true(exists('CR_%s.nii' % contrast_id)) if __name__ == "__main__": import nose nose.run(argv=['', __file__])
[ 6738, 11593, 37443, 834, 1330, 351, 62, 26090, 198, 6738, 9686, 13, 31391, 1330, 6818, 62, 7942, 198, 6738, 28686, 13, 6978, 1330, 7160, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 33272, 9608, 1330, 399, 2135, 72, 16, 5159, 198, 6...
2.376161
646
#!/usr/bin/env python-real # -*- coding: utf-8 -*- """ Run script: multivariate functional shape data analysis (MFSDA). Author: Chao Huang (chaohuang.stat@gmail.com) Last update: 2017-08-14 """ import sys,os sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)),os.path.join('Resources','Libraries'))) import numpy as np from scipy import stats from statsmodels.sandbox.stats.multicomp import fdrcorrection0 from stat_read_x import read_x from stat_lpks import lpks from stat_sif import sif from stat_wald_ht import wald_ht from stat_bstrp_pvalue import bstrp_pvalue import MFSDA_stat as mfsda import timeit import vtk import argparse import os import json """installed all the libraries above""" def run_script(args): """ Run the commandline script for MFSDA. """ """+++++++++++++++++++++++++++++++++++""" """Step 1. load dataset """ print("loading data ......") print("+++++++Read the surface shape data+++++++") fh = open(args.shapeData, 'rU') y_design = [] nshape = 0 numpoints = -1 header = fh.readline() toks = header.split(sep=',') covs_tmp = [] for line in fh.readlines(): toks = line.strip().split(sep=',') # Read VTK file vtkfilename = toks[0].rstrip() print("Reading {}".format(vtkfilename)) reader = vtk.vtkPolyDataReader() reader.SetFileName(vtkfilename) reader.Update() shapedata = reader.GetOutput() shapedatapoints = shapedata.GetPoints() y_design.append([]) if numpoints == -1: numpoints = shapedatapoints.GetNumberOfPoints() if numpoints != shapedatapoints.GetNumberOfPoints(): print("WARNING! The number of points is not the same for the shape:", vtkfilename) for i in range(shapedatapoints.GetNumberOfPoints()): p = shapedatapoints.GetPoint(i) y_design[nshape].append(p) nshape += 1 # Build covariate matrix covs_tmp.append(toks[1:]) y_design = np.array(y_design) y_design.reshape(nshape, numpoints, 3) y_design = np.array(y_design) y_design.reshape(nshape, numpoints, 3) print("The dimension of shape matrix is " + str(y_design.shape)) print("+++++++Read the sphere coordinate data+++++++") print("Reading", args.coordData) reader = vtk.vtkPolyDataReader() reader.SetFileName(args.coordData) reader.Update() coordData = reader.GetOutput() shapedatapoints = coordData.GetPoints() if numpoints != shapedatapoints.GetNumberOfPoints(): print("WARNING! The template does not have the same number of points as the shapes") coord_mat = [] for i in range(shapedatapoints.GetNumberOfPoints()): p = shapedatapoints.GetPoint(i) coord_mat.append(p) coord_mat = np.array(coord_mat) # Set up design matrix design_data = np.array(covs_tmp,dtype=float) # read the covariate type var_type = getCovariateType(design_data) """+++++++++++++++++++++++++++++++++++""" """Step 2. Statistical analysis: including (1) smoothing and (2) hypothesis testing""" gpvals, lpvals_fdr, clu_pvals, efit_beta, efity_design, efit_eta = mfsda.run_stats(y_design, coord_mat, design_data, var_type) """+++++++++++++++++++++++++++++++++++""" """Step3. Save all the results""" if not os.path.exists(args.outputDir): os.makedirs(args.outputDir) pvalues = {} pvalues['Gpvals'] = gpvals.tolist() pvalues['clu_pvals'] = clu_pvals.tolist() pvalues['Lpvals_fdr'] = lpvals_fdr.tolist() with open(os.path.join(args.outputDir,'pvalues.json'), 'w') as outfile: json.dump(pvalues, outfile) efit = {} efit['efitBetas'] = efit_beta.tolist() efit['efitYdesign'] = efity_design.tolist() efit['efitEtas'] = efit_eta.tolist() with open(os.path.join(args.outputDir,'efit.json'), 'w') as outfile: json.dump(efit, outfile) if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 12, 5305, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 10987, 4226, 25, 1963, 42524, 10345, 5485, 1366, 3781, 357, 44, 10652, 5631, 737, 198, 198, 13838...
2.444444
1,647
import os from typing import TYPE_CHECKING from modules.base import ModuleProcessor from opta.core.terraform import get_terraform_outputs from opta.exceptions import UserErrors if TYPE_CHECKING: from opta.layer import Layer from opta.module import Module
[ 11748, 28686, 198, 6738, 19720, 1330, 41876, 62, 50084, 2751, 198, 198, 6738, 13103, 13, 8692, 1330, 19937, 18709, 273, 198, 6738, 2172, 64, 13, 7295, 13, 353, 430, 687, 1330, 651, 62, 353, 430, 687, 62, 22915, 82, 198, 6738, 2172, ...
3.283951
81
"""Auto-generated file, do not edit by hand. HU metadata""" from phonenumbers.phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_HU = PhoneMetadata(id='HU', country_code=36, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='30\\d{7}', possible_length=(9,)), mobile=PhoneNumberDesc(national_number_pattern='30\\d{7}', example_number='301234567', possible_length=(9,)), national_prefix='06', national_prefix_for_parsing='06')
[ 37811, 27722, 12, 27568, 2393, 11, 466, 407, 4370, 416, 1021, 13, 367, 52, 20150, 37811, 198, 6738, 32896, 268, 17024, 13, 746, 261, 19261, 14706, 1330, 7913, 26227, 11, 14484, 15057, 24564, 11, 14484, 9171, 14706, 198, 198, 11909, 1165...
2.988095
168
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import boto3 import csv import json import logging from budget_retrieval import get_budget from budget_placement import place_budget def lambda_handler(event: dict, context: dict) -> dict: '''Demonstrates a simple HTTP endpoint using API Gateway. You have full access to the request and response payload, including headers and status code. ''' path = event['path'] user_uid = event['requestContext']['authorizer']['claims']['sub'] body = json.loads(event['body']) path = '/retrieve' if body['RetrieveOrPlace'].endswith('retrieve') else '/place' entity = 'budget' if body['Entity'].endswith('budget') else 'account' print(path) if path.endswith('/retrieve'): response = get_budget(user_uid, entity) elif path.endswith('/place'): response = place_budget(user_uid, body, entity) return respond(err=None, res=response) # with open('event.json') as f: # e = json.load(f) # lambda_handler(e, {})
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 275, 2069, 18, 198, 11748, 269, 21370, 198, 11748, 33918, 198, 11748, 18931, 198, 6738, 4466, 62, 1186, 380,...
2.769022
368
"""Utilities for working with Doxygen tag files. """ __all__ = ["get_tag_entity_names"] import xml.etree.ElementTree as ET from pathlib import Path from typing import List, Optional, Sequence, Union try: from sphinxcontrib.doxylink import doxylink except ImportError: print( "sphinxcontrib.doxylink is missing. Install documenteer with the " "pipelines extra:\n\n pip install documenteer[pipelines]" ) def get_tag_entity_names( tag_path: Union[str, Path], kinds: Optional[Sequence[str]] = None ) -> List[str]: """Get the list of API names in a Doxygen tag file. Parameters ---------- tag_path : `str` or `~pathlib.Path` File path of the Doxygen tag file. kinds : sequence of `str`, optional If provided, a sequence of API kinds to include in the listing. Doxygen types are: - namespace - struct - class - file - define - group - variable - typedef - enumeration - function Returns ------- names : `list` of `str` List of API names. """ doc = ET.parse(str(tag_path)) symbol_map = doxylink.SymbolMap(doc) keys = [] for key in symbol_map._mapping.keys(): entry = symbol_map[key] if kinds: if entry.kind in kinds: keys.append(key) else: keys.append(key) keys.sort() return keys
[ 37811, 18274, 2410, 329, 1762, 351, 360, 23536, 5235, 7621, 3696, 13, 198, 37811, 198, 198, 834, 439, 834, 796, 14631, 1136, 62, 12985, 62, 26858, 62, 14933, 8973, 198, 198, 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 12152, 19...
2.329053
623
# Shell Game, by Al Sweigart al@inventwithpython.com # A random gambling game. import random, time, sys print('''SHELL GAME By Al Sweigart al@inventwithpython.com Try to find the diamond! Press Enter to continue...''') input() CUPS = ['diamond', 'pocket lint', 'nothing'] while True: print() print('Shuffling the cups', end='') random.shuffle(CUPS) # This happens instantly. # We add fake pauses to make it seem more interesting: time.sleep(0.3) print('.', end='') time.sleep(0.3) print('.', end='') time.sleep(0.3) print('.', end='') time.sleep(0.3) print() while True: print('Okay! Pick a cup 1-{}'.format(len(CUPS))) pickedCup = input() if pickedCup.isdecimal() and 1 <= int(pickedCup) <= len(CUPS): break print('Type a number between 1 and {}.'.format(len(CUPS))) print() if CUPS[int(pickedCup) - 1] == 'diamond': print('You found the cup with the diamond!') else: print('Nope! You picked the cup that had {} in it.'.format(CUPS[int(pickedCup) - 1])) print('Would you like to play again? Y/N') response = input().upper() if not response.startswith('Y'): print('Thanks for playing!') sys.exit()
[ 2, 17537, 3776, 11, 416, 978, 19372, 328, 433, 435, 31, 259, 1151, 4480, 29412, 13, 785, 198, 2, 317, 4738, 19029, 983, 13, 198, 198, 11748, 4738, 11, 640, 11, 25064, 198, 198, 4798, 7, 7061, 6, 9693, 23304, 30517, 198, 3886, 978,...
2.396584
527
import pyttsx3 import speech_recognition as sr import openai as op import os op.api_key = os.getenv("OPENAI_API_KEY") engine = pyttsx3.init() engine.setProperty('rate', 150) engine.setProperty('volume', 1.0) voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) while True: query = takecommand() response = op.Completion.create( engine="text-davinci-001", prompt="The following is a conversation with an AI friend. The friend is helpful, creative, clever, and very friendly.\n\nHuman: " + query + "\nAI: ", temperature=0.9, max_tokens=150, top_p=1, frequency_penalty=0, presence_penalty=0.6, ) presponse= response["choices"][0]["text"] print(presponse) tell(presponse)
[ 11748, 12972, 83, 912, 87, 18, 198, 11748, 4046, 62, 26243, 653, 355, 19677, 198, 11748, 1280, 1872, 355, 1034, 198, 11748, 28686, 628, 198, 404, 13, 15042, 62, 2539, 796, 28686, 13, 1136, 24330, 7203, 3185, 1677, 20185, 62, 17614, 62...
2.620209
287
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** 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 from ._enums import * __all__ = [ 'CreationDataArgs', 'DataDiskImageEncryptionArgs', 'DisallowedArgs', 'DiskSkuArgs', 'EncryptionImagesArgs', 'EncryptionSetIdentityArgs', 'EncryptionSettingsCollectionArgs', 'EncryptionSettingsElementArgs', 'EncryptionArgs', 'ExtendedLocationArgs', 'GalleryApplicationVersionPublishingProfileArgs', 'GalleryArtifactVersionSourceArgs', 'GalleryDataDiskImageArgs', 'GalleryImageFeatureArgs', 'GalleryImageIdentifierArgs', 'GalleryImageVersionPublishingProfileArgs', 'GalleryImageVersionStorageProfileArgs', 'GalleryOSDiskImageArgs', 'ImageDiskReferenceArgs', 'ImagePurchasePlanArgs', 'KeyForDiskEncryptionSetArgs', 'KeyVaultAndKeyReferenceArgs', 'KeyVaultAndSecretReferenceArgs', 'OSDiskImageEncryptionArgs', 'PrivateLinkServiceConnectionStateArgs', 'PurchasePlanArgs', 'RecommendedMachineConfigurationArgs', 'ResourceRangeArgs', 'SharingProfileArgs', 'SnapshotSkuArgs', 'SourceVaultArgs', 'TargetRegionArgs', 'UserArtifactManageArgs', 'UserArtifactSourceArgs', ]
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 21624, 12994, 26144, 35986, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760, 644, 345, 389, 1804, 0, 17202, ...
3.059794
485
# To run the job: # pyats run job BGP_check_job.py --testbed-file <testbed_file.yaml> # Description: This job file checks that all BGP neighbors are in Established state import os # All run() must be inside a main function
[ 2, 1675, 1057, 262, 1693, 25, 198, 2, 12972, 1381, 1057, 1693, 347, 16960, 62, 9122, 62, 21858, 13, 9078, 1377, 9288, 3077, 12, 7753, 1279, 9288, 3077, 62, 7753, 13, 88, 43695, 29, 198, 2, 12489, 25, 770, 1693, 2393, 8794, 326, 47...
3.294118
68
import os
[ 11748, 28686, 628 ]
3.666667
3
from django.contrib import admin from create_lesson_plan.models import * admin.site.register(lesson) admin.site.register(lesson_plan) admin.site.register(Engage_Urls) admin.site.register(Explain_Urls) admin.site.register(Evaluate_Urls) admin.site.register(MCQ) admin.site.register(FITB) admin.site.register(Engage_Images) admin.site.register(Explain_Images) admin.site.register(Evaluate_Images) admin.site.register(Document) admin.site.register(Image) admin.site.register(TestScore) admin.site.register(OfflineDocument)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 2251, 62, 1203, 261, 62, 11578, 13, 27530, 1330, 1635, 198, 198, 28482, 13, 15654, 13, 30238, 7, 1203, 261, 8, 198, 28482, 13, 15654, 13, 30238, 7, 1203, 261, 62, 11578, 8, ...
2.894444
180
import torch from torch import nn from transformers import BertTokenizer, VisualBertModel, VisualBertConfig import numpy as np if __name__ == '__main__': bert_text_tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") inputs = bert_text_tokenizer("What is the man eating?", return_tensors="pt") text_input_ids = inputs.data['input_ids'].to('cuda') text_token_type_ids = inputs.data['token_type_ids'].to('cuda') text_attention_mask = inputs.data['attention_mask'].to('cuda') sample_face_body_embedding_path = "/home/gsoykan20/Desktop/self_development/emotion-recognition-drawings/data/emoreccom_face_body_embeddings_96d/train/0_3_4.jpg.npy" sample_face_body_embedding = np.load(sample_face_body_embedding_path) visual_embeds = torch.from_numpy(sample_face_body_embedding) visual_embeds = visual_embeds.to('cuda') visual_embeds = torch.unsqueeze(visual_embeds, 0) visual_token_type_ids = torch.ones(visual_embeds.shape[:-1], dtype=torch.long).to('cuda') visual_attention_mask = torch.ones(visual_embeds.shape[:-1], dtype=torch.float).to('cuda') classifier = VisualBertClassifier() classifier.to('cuda') classifier.forward(text_input_ids, text_token_type_ids, text_attention_mask, visual_embeds, visual_token_type_ids, visual_attention_mask)
[ 11748, 28034, 198, 6738, 28034, 1330, 299, 77, 198, 6738, 6121, 364, 1330, 22108, 30642, 7509, 11, 15612, 33, 861, 17633, 11, 15612, 33, 861, 16934, 198, 11748, 299, 32152, 355, 45941, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, ...
2.33279
613
from narrative2vec.logging_instance.logging_instance import LoggingInstance, _get_first_rdf_query_result from narrative2vec.logging_instance.reasoning_task import ReasoningTask from narrative2vec.ontology.neemNarrativeDefinitions import QUATERNION from narrative2vec.ontology.ontologyHandler import get_knowrob_uri
[ 6738, 8689, 17, 35138, 13, 6404, 2667, 62, 39098, 13, 6404, 2667, 62, 39098, 1330, 5972, 2667, 33384, 11, 4808, 1136, 62, 11085, 62, 4372, 69, 62, 22766, 62, 20274, 198, 6738, 8689, 17, 35138, 13, 6404, 2667, 62, 39098, 13, 41181, 2...
3.539326
89
# -*- coding: utf-8 -*- from . import * SECRET_KEY = env.str('KOBRA_SECRET_KEY', 'Unsafe_development_key._Never_use_in_production.') DEBUG = env.bool('KOBRA_DEBUG_MODE', True) DATABASES = { 'default': env.db_url('KOBRA_DATABASE_URL', 'sqlite:///db.sqlite3') }
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 764, 1330, 1635, 198, 198, 23683, 26087, 62, 20373, 796, 17365, 13, 2536, 10786, 42, 9864, 3861, 62, 23683, 26087, 62, 20373, 3256, 198, 220, 220, 220, 220, 220, ...
2.057143
140
#!/usr/bin/env python from pyfoobot import Foobot import requests import matplotlib matplotlib.use('Agg') import matplotlib.dates import matplotlib.pyplot import datetime from imgurpython import ImgurClient import ConfigParser if __name__ == "__main__": getSensorReadings(True)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 12972, 6513, 672, 313, 1330, 19434, 672, 313, 198, 11748, 7007, 198, 11748, 2603, 29487, 8019, 198, 6759, 29487, 8019, 13, 1904, 10786, 46384, 11537, 198, 11748, 2603, 29487, ...
3.122222
90
# Copyright (c) 2020 safexl from safexl.toolkit import * import safexl.xl_constants as xl_constants import safexl.colors as colors __author__ = "Eric Smith" __email__ = "ThePoetCoder@gmail.com" __license__ = "MIT" __version__ = "0.0.7"
[ 2, 15069, 357, 66, 8, 12131, 1932, 1069, 75, 198, 198, 6738, 1932, 1069, 75, 13, 25981, 15813, 1330, 1635, 198, 11748, 1932, 1069, 75, 13, 87, 75, 62, 9979, 1187, 355, 2124, 75, 62, 9979, 1187, 198, 11748, 1932, 1069, 75, 13, 4033...
2.542553
94
# Generated by Django 2.0.4 on 2018-05-01 05:22 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 362, 13, 15, 13, 19, 319, 2864, 12, 2713, 12, 486, 8870, 25, 1828, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, 6...
2.818182
44
# Generated by Django 3.0.9 on 2020-08-24 20:44 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 15, 13, 24, 319, 12131, 12, 2919, 12, 1731, 1160, 25, 2598, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
# -*- coding: utf-8 -*- """ (SHORT NAME EXPLANATION) >>>DOCTEST COMMANDS (THE TEST ANSWER) @author: Yi Zhang. Created on Mon Jul 10 20:12:27 2017 Department of Aerodynamics Faculty of Aerospace Engineering TU Delft #SUMMARY---------------- #INPUTS----------------- #ESSENTIAL: #OPTIONAL: #OUTPUTS---------------- #EXAMPLES--------------- #NOTES------------------ """ # -*- coding: utf-8 -*- """ (SHORT NAME EXPLANATION) >>>DOCTEST COMMANDS (THE TEST ANSWER) @author: Yi Zhang . Created on Thu Jul 6 16:00:33 2017 Department of Aerodynamics Faculty of Aerospace Engineering TU Delft #SUMMARY---------------- #INPUTS----------------- #ESSENTIAL: #OPTIONAL: #OUTPUTS---------------- #EXAMPLES--------------- #NOTES------------------ """ from function_space import FunctionSpace import numpy as np from mesh import CrazyMesh from forms import Form from hodge import hodge from coboundaries import d from assemble import assemble from _assembling import assemble_, integral1d_ import matplotlib.pyplot as plt from quadrature import extended_gauss_quad from scipy.integrate import quad from sympy import Matrix import scipy.io from scipy import sparse import scipy as sp from inner_product import inner # %% exact solution define # u^{(1)} = { u, v }^T # %% define the mesh mesh = CrazyMesh( 2, (2, 2), ((-1, 1), (-1, 1)), 0.05 ) func_space_gauss1 = FunctionSpace(mesh, '1-gauss', (5, 5), is_inner=False) func_space_lobatto1 = FunctionSpace(mesh, '1-lobatto', (5, 5), is_inner=False) form_1_gauss = Form(func_space_gauss1) form_1_lobatto = Form(func_space_lobatto1) M = inner(form_1_lobatto.basis,form_1_gauss.basis)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 7, 9693, 9863, 36751, 7788, 6489, 1565, 6234, 8, 198, 220, 220, 220, 220, 198, 33409, 18227, 4177, 6465, 9440, 10725, 5258, 220, 198, 7, 10970, 43001, 3537, ...
2.591928
669
import json from bs4 import BeautifulSoup import pandas as pd import sys # Argparsing argument_index = 1 template = sys.argv[argument_index] argument_index +=1 recall_json = sys.argv[argument_index] argument_index +=1 recall_plot = sys.argv[argument_index] argument_index +=1 precision_jsons_list = [sys.argv[i] for i in range(argument_index, len(sys.argv))] precision_rows_list = [] # convert jsons back to dicts for html conversion for json_path in precision_jsons_list: with open(json_path, 'r') as json_file: data = json.load(json_file) precision_rows_list.append(data) precision_df = pd.DataFrame(precision_rows_list) precision_df = precision_df.sort_values(by='Round #') precision_html_table = precision_df.to_html(index=False) # Same for recall json recall_rows_list = [] with open(recall_json, 'r') as json_file: data=json.load(json_file) recall_rows_list.append(data) recall_df = pd.DataFrame(recall_rows_list) recall_html_table = recall_df.to_html(index=False) # Create html with open(template, 'r') as template_file: contents = template_file.read() template_soup = BeautifulSoup(contents, features="html.parser") p_list = template_soup.find_all('p') p_index = 0 # Read recall table tag recall_soup = BeautifulSoup(recall_html_table, features="html.parser") table_tag = recall_soup.find('table') p_list[p_index].insert_after(table_tag) p_index+=1 image_tag = template_soup.new_tag('img') image_tag['src']= f"./recall/{recall_plot}" image_tag['width']= 700 image_tag['height']= 500 p_list[p_index].insert_after(image_tag) p_index+=1 precision_soup = BeautifulSoup(precision_html_table, features="html.parser") table_tag = precision_soup.find('table') p_list[p_index].insert_after(table_tag) p_index+=1 with open('spot_detection_qc_report.html', 'w') as result_file: result_file.write(str( template_soup ))
[ 11748, 33918, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 25064, 198, 198, 2, 20559, 79, 945, 278, 198, 49140, 62, 9630, 796, 352, 198, 28243, 796, 25064, 13, 853, 85, 58, 49140,...
2.642655
708
import pytest import torch as th from syft.frameworks.torch.mpc.fss import DPF, DIF, n
[ 11748, 12972, 9288, 198, 11748, 28034, 355, 294, 198, 198, 6738, 827, 701, 13, 19298, 19653, 13, 13165, 354, 13, 3149, 66, 13, 69, 824, 1330, 27704, 37, 11, 360, 5064, 11, 299, 628 ]
2.617647
34
from allennlp.common.testing import AllenNlpTestCase from allennlp.data.tokenizers import PretrainedTransformerTokenizer
[ 6738, 477, 1697, 34431, 13, 11321, 13, 33407, 1330, 9659, 45, 34431, 14402, 20448, 198, 6738, 477, 1697, 34431, 13, 7890, 13, 30001, 11341, 1330, 37123, 13363, 8291, 16354, 30642, 7509, 628 ]
3.8125
32
"""Key OpenMDAO classes can be imported from here.""" # Core from openmdao.core.problem import Problem from openmdao.core.group import Group from openmdao.core.parallel_group import ParallelGroup from openmdao.core.explicitcomponent import ExplicitComponent from openmdao.core.implicitcomponent import ImplicitComponent from openmdao.core.indepvarcomp import IndepVarComp from openmdao.core.analysis_error import AnalysisError # Components from openmdao.components.deprecated_component import Component from openmdao.components.exec_comp import ExecComp from openmdao.components.linear_system_comp import LinearSystemComp from openmdao.components.meta_model import MetaModel from openmdao.components.multifi_meta_model import MultiFiMetaModel # Solvers from openmdao.solvers.linear.linear_block_gs import LinearBlockGS from openmdao.solvers.linear.linear_block_jac import LinearBlockJac from openmdao.solvers.linear.direct import DirectSolver from openmdao.solvers.linear.petsc_ksp import PetscKSP from openmdao.solvers.linear.linear_runonce import LinearRunOnce from openmdao.solvers.linear.scipy_iter_solver import ScipyIterativeSolver from openmdao.solvers.linesearch.backtracking import ArmijoGoldsteinLS from openmdao.solvers.linesearch.backtracking import BoundsEnforceLS from openmdao.solvers.nonlinear.nonlinear_block_gs import NonlinearBlockGS from openmdao.solvers.nonlinear.nonlinear_block_jac import NonlinearBlockJac from openmdao.solvers.nonlinear.newton import NewtonSolver from openmdao.solvers.nonlinear.nonlinear_runonce import NonLinearRunOnce # Surrogate Models from openmdao.surrogate_models.kriging import KrigingSurrogate, FloatKrigingSurrogate from openmdao.surrogate_models.multifi_cokriging import MultiFiCoKrigingSurrogate, \ FloatMultiFiCoKrigingSurrogate from openmdao.surrogate_models.nearest_neighbor import NearestNeighbor from openmdao.surrogate_models.response_surface import ResponseSurface from openmdao.surrogate_models.surrogate_model import SurrogateModel, \ MultiFiSurrogateModel # Vectors from openmdao.vectors.default_vector import DefaultVector try: from openmdao.vectors.petsc_vector import PETScVector except ImportError: PETScVector = None # Developer Tools from openmdao.devtools.problem_viewer.problem_viewer import view_model from openmdao.devtools.viewconns import view_connections # Derivative Specification from openmdao.jacobians.assembled_jacobian import AssembledJacobian, \ DenseJacobian, COOJacobian, CSRJacobian, CSCJacobian # Drivers try: from openmdao.drivers.pyoptsparse_driver import pyOptSparseDriver except ImportError: pass from openmdao.drivers.scipy_optimizer import ScipyOptimizer # System-Building Tools from openmdao.utils.options_dictionary import OptionsDictionary # Recorders from openmdao.recorders.sqlite_recorder import SqliteRecorder from openmdao.recorders.openmdao_server_recorder import OpenMDAOServerRecorder
[ 37811, 9218, 4946, 44, 5631, 46, 6097, 460, 307, 17392, 422, 994, 526, 15931, 198, 198, 2, 7231, 198, 6738, 1280, 9132, 5488, 13, 7295, 13, 45573, 1330, 20647, 198, 6738, 1280, 9132, 5488, 13, 7295, 13, 8094, 1330, 4912, 198, 6738, ...
3.221122
909
import os from getArgs import getArgs from modules import python, javascript, html, php, bootstrap, cca # from folder import file # code-buddy.py create (file type) (directory name) # Checks for "create" if getArgs(1) == "create": # Checks for which file type projectType = getArgs(2) # Checks for file name if projectType == "python": name = getArgs(3) python.createPythonProject(name) print("Folder created succesfully") elif projectType == "javascript": name = getArgs(3) javascript.createJavascriptProject(name) print("Folder created succesfully") elif projectType == "html": name = getArgs(3) html.createHtmlProject(name) print("Folder created succesfully") elif projectType == "php": name = getArgs(3) php.createPhpProject(name) print("Folder created succesfully") elif projectType == "bootstrap": name = getArgs(3) bootstrap.createPhpProject(name) print("Folder created succesfully") elif projectType == "cca" name = getArgs(3) cca.createCcaProject(name) print("Folder created succesfully") # If not valid file type else: print(f"argument {getArgs(2)} is unknown, try: 'python, javascript, html, php or bootstrap'") else: # If invalid "create" print(f"argument {getArgs(1)} is unknown, use 'create' to create a folder")
[ 11748, 28686, 198, 6738, 651, 42035, 1330, 651, 42035, 198, 6738, 13103, 1330, 21015, 11, 44575, 11, 27711, 11, 39347, 11, 6297, 26418, 11, 269, 6888, 198, 2, 422, 9483, 1330, 2393, 198, 198, 2, 2438, 12, 65, 21584, 13, 9078, 2251, ...
2.553982
565
from contextlib import contextmanager from distutils.sysconfig import get_config_var from io import open as io_open import os from os.path import join, exists import shutil import sys import tempfile from textwrap import dedent from multiprocessing import Pool from unittest import TestCase, main try: from unittest import mock except ImportError: import mock from ..ext_module import get_md5, ExtModule, get_ext_extension, get_unicode def _check_write_source(root): """Used to create an ExtModule and test if a file was opened. It returns the number of times "open" was called. """ m = mock.mock_open() orig_side_effect = m.side_effect m.side_effect = _side_effect with mock.patch('compyle.ext_module.io.open', m, create=True): s = ExtModule("print('hello')", root=root) s.write_source() return m.call_count if __name__ == '__main__': main()
[ 6738, 4732, 8019, 1330, 4732, 37153, 198, 6738, 1233, 26791, 13, 17597, 11250, 1330, 651, 62, 11250, 62, 7785, 198, 6738, 33245, 1330, 1280, 355, 33245, 62, 9654, 198, 11748, 28686, 198, 6738, 28686, 13, 6978, 1330, 4654, 11, 7160, 198,...
2.901587
315
# -*- coding: UTF-8 -*- """ collector.xhn - http://www.xinhuanet.com/ 1. http://qc.wa.news.cn/nodeart/list?nid=115093&pgnum=1&cnt=10000 http://www.xinhuanet.com/politics/qmtt/index.htm ==================================================================== """ import requests import re from datetime import datetime from bs4 import BeautifulSoup from zb.crawlers.utils import get_header import traceback import pandas as pd from tqdm import tqdm import tma home_url = "http://www.xinhuanet.com/" def get_special_topics(pgnum=1): """""" url = "http://qc.wa.news.cn/nodeart/list?" \ "nid=115093&pgnum=%s&cnt=200" % str(pgnum) res = requests.get(url).text res = res.replace("null", "\'\'") res = eval(res) assert res['status'] == 0, "" data = res['data']['list'] specials = [] for a in data: special = { "Abstract": a['Abstract'], "Author": a['Author'], "LinkUrl": a['LinkUrl'], "PubTime": a['PubTime'], "Title": a['Title'], "allPics": a['allPics'], } specials.append(special) return specials def get_article_detail(article_url): """article_url :param article_url: url :return: { "url": article_url, "title": title, "pub_time": pub_time, "source": source, "content": content } """ # article_url = "http://www.xinhuanet.com/fortune/2018-06/20/c_129897476.htm" html = requests.get(article_url, headers=get_header()) bsobj = BeautifulSoup(html.content.decode('utf-8'), 'lxml') # cols = bsobj.find('div', {"class": "h-news"}).text.strip().split("\r\n") title = cols[0].strip() pub_time = cols[1].strip() source = cols[-1].strip() # content = bsobj.find('div', {"id": "p-detail"}).text.strip() content = content.replace("\u3000\u3000", "") content = [x.strip() for x in content.split("\n")] content = [x for x in content if x != ""] content = "\n".join(content) return { "url": article_url, "title": title, "pub_time": pub_time, "source": source, "content": content }
[ 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 33327, 273, 13, 87, 21116, 532, 220, 198, 198, 4023, 1378, 2503, 13, 87, 259, 71, 7258, 316, 13, 785, 14, 628, 198, 16, 13, 220, 198, 4023, 1378, 80, ...
2.186508
1,008
import unittest from plugins.onetv import OneTV
[ 11748, 555, 715, 395, 198, 198, 6738, 20652, 13, 36823, 85, 1330, 1881, 6849, 628 ]
3.333333
15
""" This is a test file used for testing the pytest plugin. """ def test_function_passed(snapshot): """ The snapshot for this function is expected to exist. """ snapshot.assert_match(3 + 4j) def test_function_new(snapshot): """ The snapshot for this function is expected to exist, but only one assertion is expected. """ snapshot.assert_match(3 + 4j) snapshot.assert_match(3 + 4j)
[ 37811, 770, 318, 257, 1332, 2393, 973, 329, 4856, 262, 12972, 9288, 13877, 13, 37227, 628, 198, 4299, 1332, 62, 8818, 62, 6603, 276, 7, 45380, 9442, 2599, 198, 220, 220, 220, 37227, 383, 27479, 329, 428, 2163, 318, 2938, 284, 2152, ...
3.24
125
from __future__ import print_function from __future__ import absolute_import from __future__ import division from random import uniform from compas.geometry import transform_points from compas.geometry import centroid_points from compas.geometry import bounding_box from compas.geometry import Primitive from compas.geometry import Point __all__ = ['Pointcloud'] def __eq__(self, other): """Is this pointcloud equal to the other pointcloud? Two pointclouds are considered equal if they have the same number of points and if the XYZ coordinates of the corresponding points are identical. Parameters ---------- other : :class:`compas.geometry.Pointcloud` | list[[float, float, float] | :class:`compas.geometry.Point`] The pointcloud to compare. Returns ------- bool True if the pointclouds are equal. False otherwise. """ if len(self) != len(other): return False A = sorted(self, key=lambda point: (point[0], point[1], point[2])) B = sorted(other, key=lambda point: (point[0], point[1], point[2])) return all(a == b for a, b in zip(A, B)) # ========================================================================== # constructors # ========================================================================== # ========================================================================== # methods # ========================================================================== def transform(self, T): """Apply a transformation to the pointcloud. Parameters ---------- T : :class:`compas.geometry.Transformation` The transformation. Returns ------- None The cloud is modified in place. """ for index, point in enumerate(transform_points(self.points, T)): self.points[index].x = point[0] self.points[index].y = point[1] self.points[index].z = point[2]
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 198, 6738, 4738, 1330, 8187, 198, 6738, 552, 292, 13, 469, 15748, 1330, 6121, 62, 13033, ...
2.831293
735
"""Handle regex conversions.""" from builtins import object import re import operator from functools import reduce import oa.errors # Map of perl flags and the corresponding re ones. FLAGS = { "i": re.IGNORECASE, "s": re.DOTALL, "m": re.MULTILINE, "x": re.VERBOSE, } DELIMS = { "/": "/", "{": "}", "%": "%", "<": ">", "'": "'", "~": "~", ",": ",", "!": "!", ";": ";", } # Regex substitution for Perl -> Python compatibility _CONVERTS = ( (re.compile(r""" # Python does not support local extensions so remove those. For example: # (?i:test) becomes (?:test) (?<=\(\?) # Look-behind and match (? (([adlupimsx-]*?)|(\^[?^alupimsx]*?)) # Capture the extension (?=:) # Look-ahead and match the : """, re.VERBOSE), r""), (re.compile(r""" # Python doesn't have support for expression such as \b? # Replace it with (\b)? (\\b) # Capture group that matches \b or \B (?=\?) # Look-ahead that matches ? """, re.VERBOSE | re.IGNORECASE), r"(\1)"), (re.compile(r""" # Python doesn't have support for "independent" subexpression (?>) # Replace those with non capturing groups (?:) (?<=\(\?) # Look-behind and match (? (>) # Match > """, re.VERBOSE), r":"), ) def perl2re(pattern, match_op="=~"): """Convert a Perl type regex to a Python one.""" # We don't need to consider the pre-flags pattern = pattern.strip().lstrip("mgs") delim = pattern[0] try: rev_delim = DELIMS[delim] except KeyError: raise oa.errors.InvalidRegex("Invalid regex delimiter %r in %r" % (delim, pattern)) try: pattern, flags_str = pattern.lstrip(delim).rsplit(rev_delim, 1) except ValueError: raise oa.errors.InvalidRegex("Invalid regex %r. Please make sure you " "have escaped all the special characters " "when you defined the regex in " "configuration file" % pattern) for conv_p, repl in _CONVERTS: pattern = conv_p.sub(repl, pattern) flags = reduce(operator.or_, (FLAGS.get(flag, 0) for flag in flags_str), 0) try: if match_op == "=~": return MatchPattern(re.compile(pattern, flags)) elif match_op == "!~": return NotMatchPattern(re.compile(pattern, flags)) except re.error as e: raise oa.errors.InvalidRegex("Invalid regex %r: %s" % (pattern, e))
[ 37811, 37508, 40364, 32626, 526, 15931, 198, 198, 6738, 3170, 1040, 1330, 2134, 198, 198, 11748, 302, 198, 11748, 10088, 198, 6738, 1257, 310, 10141, 1330, 4646, 198, 198, 11748, 267, 64, 13, 48277, 198, 198, 2, 9347, 286, 48746, 9701, ...
2.147514
1,227
import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider from kalman_filter import KalmanFilter raw_data = np.loadtxt("barometer_data.txt") # Truncate raw data (it's super long) raw_data = raw_data[:raw_data.size//4] raw_data_step = np.loadtxt("barometer_data_step.txt") t1 = np.arange(0, raw_data.size/12.5, 1/12.5) t2 = np.arange(0, raw_data_step.size/12.5, 1/12.5) fig1 = plt.figure("Data") ax1 = fig1.add_subplot(121) ax2 = fig1.add_subplot(122) fig1.subplots_adjust(bottom=0.25) [unfiltered_raw_line] = ax1.plot(t1, raw_data) [unfiltered__step_line] = ax2.plot(t2, raw_data_step) P0 = 2 Q0 = 1e-4 [filtered_raw_line] = ax1.plot(t1, filter_data(raw_data, 0, P0, Q0, R=raw_data.var())[0]) [filtered_step_line] = ax2.plot(t2, filter_data(raw_data_step, 0, P0, Q0, R=raw_data.var())[0]) P_slider_ax = fig1.add_axes([0.25, 0.15, 0.65, 0.03]) Q_slider_ax = fig1.add_axes([0.25, 0.1, 0.65, 0.03]) P_slider = Slider(P_slider_ax, 'P', 0.5, 5, valinit=P0) Q_slider = Slider(Q_slider_ax, 'Q', 1e-4, 1e-3, valinit=Q0) P_slider.on_changed(sliders_on_changed) Q_slider.on_changed(sliders_on_changed) plt.show()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 2603, 29487, 8019, 13, 28029, 11407, 1330, 3454, 1304, 198, 6738, 479, 282, 805, 62, 24455, 1330, 12612, 805, 22417, 198, 198, 1831,...
2.07441
551
import heapq from typing import List
[ 11748, 24575, 80, 198, 6738, 19720, 1330, 7343, 628 ]
4.222222
9
import pandas as pd import numpy as np import matplotlib.pyplot as plt # 1: YOLOv2, 2: AlexNet, 3: VGG-16, 4: GoogLeNet model = 4 LINEPLOT = True dfs = pd.read_excel("t.xlsx", sheet_name=None, header=None) if model == 1: ms = "YOLOv2" elif model == 2: ms = "AlexNet" elif model == 3: ms = "VGG-16" elif model == 4: ms = "GoogLeNet" sh = dfs[ms] print(sh) labels = ["1", "2", "3", "4", "5", "6"] x = np.arange(len(labels)) plt.rcParams.update({"font.size": 11}) fig, ax = plt.subplots() plt.subplots_adjust(top=0.95, right=0.95) # Workaround for this: https://bugs.python.org/issue32790 def autolabel(rects): """Attach a text label above each bar in *rects*, displaying its height.""" for rect in rects: height = rect.get_height() ax.annotate(fmtFlt(height, 3), xy=(rect.get_x() + 1.2*rect.get_width() / 2, height), xytext=(0, 3), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom', rotation=90, fontsize=9.5) # 1: 1gbit, 2: 100mbit, 3: 10mbit addData(1, True) addData(1, False) addData(2, True) addData(2, False) addData(3, True) addData(3, False) #plt.ylim(plt.ylim()*1.1) ybot, ytop = plt.ylim() plt.ylim(ybot, ytop*1.05) ax.set_xlabel("Number of devices") ax.set_ylabel("Run time speedup over one device") ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() plt.savefig("plot_runtime.pdf") plt.show()
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 2, 352, 25, 575, 3535, 46, 85, 17, 11, 362, 25, 4422, 7934, 11, 513, 25, 569, 11190, 12, ...
2.138806
670
from setuptools import setup, find_packages from myriad import meta from myriad.util import dist setup( name=meta.display_name, version=meta.version, description=meta.description, long_description=meta.long_description, author=meta.author, author_email=meta.author_email, url=meta.url, license=meta.license, packages=find_packages() + ["twisted.plugins"], package_data={ "twisted": ['plugins/example_server.py'] }, install_requires=meta.requires, zip_safe=False ) dist.refresh_plugin_cache()
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 6738, 24862, 1330, 13634, 198, 6738, 24862, 13, 22602, 1330, 1233, 628, 198, 40406, 7, 198, 220, 220, 220, 1438, 28, 28961, 13, 13812, 62, 3672, 11, 198, 220, 220, ...
2.690476
210
from subprocess import run # python -u val_resnet.py cuda = 0 # which gpu to use dataset = 'cifar10' logs_path = 'logs_resnet' + '_' + dataset manualSeed = 99 workers = 0 for model in ['resnet20', 'preact_resnet20']: commands = [ 'python', '-u', 'validate_resnet.py', '--dataset=' + dataset, '--model=' + model, '-c=' + str(cuda), '--workers=' + str(workers), '--manualSeed=' + str(manualSeed), '--logs_path=' + logs_path, ] run(commands) for model in ['resnet20', 'preact_resnet20']: f = True for k in [1, 3]: for ff in [False, True]: commands = [ 'python', '-u', 'validate_resnet.py', '--dataset=' + dataset, '--model=' + model, '-k=' + str(k), '-c=' + str(cuda), '--workers=' + str(workers), '--manualSeed=' + str(manualSeed), '--logs_path=' + logs_path, ] if f: commands.append('-f') if ff: commands.append('--ff') run(commands)
[ 6738, 850, 14681, 1330, 1057, 198, 2, 21015, 532, 84, 1188, 62, 411, 3262, 13, 9078, 198, 198, 66, 15339, 796, 657, 220, 1303, 543, 308, 19944, 284, 779, 198, 19608, 292, 316, 796, 705, 66, 361, 283, 940, 6, 198, 6404, 82, 62, 6...
1.837748
604
from temboo.Library.KhanAcademy.Badges.AllCategories import AllCategories, AllCategoriesInputSet, AllCategoriesResultSet, AllCategoriesChoreographyExecution from temboo.Library.KhanAcademy.Badges.BadgesByCategory import BadgesByCategory, BadgesByCategoryInputSet, BadgesByCategoryResultSet, BadgesByCategoryChoreographyExecution from temboo.Library.KhanAcademy.Badges.GetBadges import GetBadges, GetBadgesInputSet, GetBadgesResultSet, GetBadgesChoreographyExecution
[ 6738, 2169, 2127, 78, 13, 23377, 13, 42, 7637, 12832, 324, 3065, 13, 22069, 3212, 13, 3237, 34, 26129, 1330, 1439, 34, 26129, 11, 1439, 34, 26129, 20560, 7248, 11, 1439, 34, 26129, 23004, 7248, 11, 1439, 34, 26129, 1925, 382, 4867, ...
3.328571
140
from akagi.data_source import DataSource from akagi.data_file import DataFile
[ 6738, 47594, 18013, 13, 7890, 62, 10459, 1330, 6060, 7416, 198, 6738, 47594, 18013, 13, 7890, 62, 7753, 1330, 6060, 8979, 628 ]
3.590909
22
""" File: my_drawing.py Name: ---------------------- TODO: """ from campy.graphics.gobjects import GOval, GRect, GLine, GLabel, GPolygon, GArc from campy.graphics.gwindow import GWindow def main(): """ Meet Snorlax () of stanCode! He dreams of Python when he sleeps. Be like Snorlax. """ window = GWindow(width=300, height=300) face_outer = GOval(120, 75, x=(window.width-120)/2, y=50) face_outer.filled = True face_outer.fill_color = 'darkcyan' face_outer.color = 'darkcyan' window.add(face_outer) face_inner = GOval(100, 65, x=(window.width-100)/2, y=60) face_inner.filled = True face_inner.fill_color = 'lightsalmon' face_inner.color = 'lightsalmon' window.add(face_inner) forehead = GPolygon() forehead.add_vertex((135, 60)) forehead.add_vertex((165, 60)) forehead.add_vertex((150, 68)) forehead.filled = True forehead.fill_color = 'darkcyan' forehead.color = 'darkcyan' window.add(forehead) r_ear = GPolygon() r_ear.add_vertex((113, 35)) r_ear.add_vertex((95, 75)) r_ear.add_vertex((140, 50)) r_ear.filled = True r_ear.fill_color = 'darkcyan' r_ear.color = 'darkcyan' window.add(r_ear) l_ear = GPolygon() l_ear.add_vertex((187, 35)) l_ear.add_vertex((205, 75)) l_ear.add_vertex((160, 50)) l_ear.filled = True l_ear.fill_color = 'darkcyan' l_ear.color = 'darkcyan' window.add(l_ear) r_eye = GLine (120, 75, 140, 75) window.add(r_eye) l_eye = GLine(180, 75, 160, 75) window.add(l_eye) mouth = GLine(135, 85, 165, 85) window.add(mouth) r_tooth = GPolygon() r_tooth.add_vertex((135, 84)) r_tooth.add_vertex((139, 84)) r_tooth.add_vertex((137, 80)) r_tooth.filled = True r_tooth.fill_color = 'white' r_tooth.color = 'white' window.add(r_tooth) l_tooth = GPolygon() l_tooth.add_vertex((165, 84)) l_tooth.add_vertex((161, 84)) l_tooth.add_vertex((163, 80)) l_tooth.filled = True l_tooth.fill_color = 'white' l_tooth.color = 'white' window.add(l_tooth) r_arm = GOval(100, 45, x=25, y=98) r_arm.filled = True r_arm.fill_color = 'darkcyan' r_arm.color = 'darkcyan' window.add(r_arm) l_arm = GOval(100, 45, x=175, y=98) l_arm.filled = True l_arm.fill_color = 'darkcyan' l_arm.color = 'darkcyan' window.add(l_arm) body = GOval(200, 160, x=(window.width - 200) / 2, y=95) body.filled = True body.fill_color = 'darkcyan' body.color = 'darkcyan' window.add(body) belly = GOval(176, 120, x=(window.width - 176) / 2, y=95) belly.filled = True belly.fill_color = 'lightsalmon' window.add(belly) r_claw1 = GPolygon() r_claw1.add_vertex((38, 100)) r_claw1.add_vertex((44, 102)) r_claw1.add_vertex((40, 106)) r_claw1.filled = True r_claw1.fill_color = 'white' window.add(r_claw1) r_claw2 = GPolygon() r_claw2.add_vertex((32, 102)) r_claw2.add_vertex((38, 104)) r_claw2.add_vertex((35, 108)) r_claw2.filled = True r_claw2.fill_color = 'white' window.add(r_claw2) r_claw3 = GPolygon() r_claw3.add_vertex((28, 104)) r_claw3.add_vertex((34, 106)) r_claw3.add_vertex((31, 110)) r_claw3.filled = True r_claw3.fill_color = 'white' window.add(r_claw3) r_claw4 = GPolygon() r_claw4.add_vertex((24, 109)) r_claw4.add_vertex((30, 111)) r_claw4.add_vertex((27, 115)) r_claw4.filled = True r_claw4.fill_color = 'white' window.add(r_claw4) r_claw5 = GPolygon() r_claw5.add_vertex((19, 122)) r_claw5.add_vertex((25, 121)) r_claw5.add_vertex((28, 127)) r_claw5.filled = True r_claw5.fill_color = 'white' window.add(r_claw5) l_claw1 = GPolygon() l_claw1.add_vertex((262, 100)) l_claw1.add_vertex((256, 102)) l_claw1.add_vertex((260, 106)) l_claw1.filled = True l_claw1.fill_color = 'white' window.add(l_claw1) l_claw2 = GPolygon() l_claw2.add_vertex((268, 102)) l_claw2.add_vertex((262, 104)) l_claw2.add_vertex((265, 108)) l_claw2.filled = True l_claw2.fill_color = 'white' window.add(l_claw2) l_claw3 = GPolygon() l_claw3.add_vertex((272, 104)) l_claw3.add_vertex((266, 106)) l_claw3.add_vertex((269, 110)) l_claw3.filled = True l_claw3.fill_color = 'white' window.add(l_claw3) r_claw4 = GPolygon() r_claw4.add_vertex((276, 109)) r_claw4.add_vertex((270, 111)) r_claw4.add_vertex((273, 115)) r_claw4.filled = True r_claw4.fill_color = 'white' window.add(r_claw4) r_claw5 = GPolygon() r_claw5.add_vertex((281, 122)) r_claw5.add_vertex((275, 121)) r_claw5.add_vertex((272, 127)) r_claw5.filled = True r_claw5.fill_color = 'white' window.add(r_claw5) r_foot = GOval(65, 60, x=50, y=220) r_foot.filled = True r_foot.fill_color = 'lightsalmon' r_foot.color = 'lightsalmon' window.add(r_foot) r_palm = GOval(45, 40, x=65, y=235) r_palm.filled = True r_palm.fill_color = 'Chocolate' r_palm.color = 'Chocolate' window.add(r_palm) r_nail1 = GPolygon() r_nail1.add_vertex((80, 210)) r_nail1.add_vertex((88, 223)) r_nail1.add_vertex((78, 224)) r_nail1.filled = True r_nail1.fill_color = 'white' window.add(r_nail1) r_nail2 = GPolygon() r_nail2.add_vertex((52, 220)) r_nail2.add_vertex((65, 228)) r_nail2.add_vertex((57, 235)) r_nail2.filled = True r_nail2.fill_color = 'white' window.add(r_nail2) r_nail3 = GPolygon() r_nail3.add_vertex((43, 250)) r_nail3.add_vertex((54, 248)) r_nail3.add_vertex((52, 258)) r_nail3.filled = True r_nail3.fill_color = 'white' window.add(r_nail3) l_foot = GOval(65, 60, x=185, y=220) l_foot.filled = True l_foot.fill_color = 'lightsalmon' l_foot.color = 'lightsalmon' window.add(l_foot) l_palm = GOval(45, 40, x=190, y=235) l_palm.filled = True l_palm.fill_color = 'Chocolate' l_palm.color = 'Chocolate' window.add(l_palm) l_nail1 = GPolygon() l_nail1.add_vertex((220, 210)) l_nail1.add_vertex((212, 223)) l_nail1.add_vertex((222, 224)) l_nail1.filled = True l_nail1.fill_color = 'white' window.add(l_nail1) r_nail2 = GPolygon() r_nail2.add_vertex((248, 220)) r_nail2.add_vertex((235, 228)) r_nail2.add_vertex((243, 235)) r_nail2.filled = True r_nail2.fill_color = 'white' window.add(r_nail2) r_nail3 = GPolygon() r_nail3.add_vertex((257, 250)) r_nail3.add_vertex((246, 248)) r_nail3.add_vertex((248, 258)) r_nail3.filled = True r_nail3.fill_color = 'white' window.add(r_nail3) word = GLabel('stanCode', x=123, y=185) word.font = '-8-bold' window.add(word) bubble1 = GOval(10, 10, x=140, y=35) window.add(bubble1) bubble2 = GOval(15, 15, x=155, y=23) window.add(bubble2) bubble3 = GOval(20, 20, x=175, y=12) window.add(bubble3) bubble4 = GOval(95, 85, x=200, y=5) window.add(bubble4) word2 = GLabel('Python', x=207, y=50) word2.font = 'Courier-18' window.add(word2) word3 = GLabel('Python', x=220, y=80) word3.font = 'Courier-13' window.add(word3) word4 = GLabel('Python', x=242, y=60) word4.font = 'Courier-8' window.add(word4) if __name__ == '__main__': main()
[ 37811, 198, 8979, 25, 616, 62, 19334, 278, 13, 9078, 198, 5376, 25, 220, 198, 19351, 438, 198, 51, 3727, 46, 25, 198, 37811, 198, 198, 6738, 1413, 88, 13, 70, 11549, 13, 70, 48205, 1330, 10351, 2100, 11, 10863, 478, 11, 10188, 500...
2.001353
3,695
''' Clipboard xsel: an implementation of the Clipboard using xsel command line tool. ''' __all__ = ('ClipboardXsel', ) from kivy.utils import platform from kivy.core.clipboard._clipboard_ext import ClipboardExternalBase if platform != 'linux': raise SystemError('unsupported platform for xsel clipboard') try: import subprocess p = subprocess.Popen(['xsel'], stdout=subprocess.PIPE) p.communicate() except: raise
[ 7061, 6, 198, 2601, 541, 3526, 2124, 741, 25, 281, 7822, 286, 262, 42512, 3526, 1262, 2124, 741, 3141, 1627, 2891, 13, 198, 7061, 6, 198, 198, 834, 439, 834, 796, 19203, 2601, 541, 3526, 55, 741, 3256, 1267, 198, 198, 6738, 479, 4...
2.926667
150
from girder.exceptions import ValidationException from girder.utility import setting_utilities
[ 6738, 37370, 1082, 13, 1069, 11755, 1330, 3254, 24765, 16922, 198, 6738, 37370, 1082, 13, 315, 879, 1330, 4634, 62, 315, 2410, 628, 628 ]
4.083333
24
from collections import defaultdict, namedtuple from dataclasses import dataclass import distutils.util import functools import itertools import json import math import operator import os import random import uuid import shutil import logging import time from typing import List, Dict, NamedTuple, Optional from django.db.models import Q from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.shortcuts import get_object_or_404, get_list_or_404 from django.conf import settings from google.cloud import storage from rest_framework.decorators import api_view import requests from expiringdict import ExpiringDict from .models import ( Dataset, DatasetItem, Category, Mode, User, Annotation, DNNModel, CategoryCount, ) BUILTIN_MODES = ["POSITIVE", "NEGATIVE", "HARD_NEGATIVE", "UNSURE"] logger = logging.getLogger(__name__) # # V2 ENDPOINTS # TODO(mihirg): Make these faster # Tag = namedtuple("Tag", "category value") # type: NamedTuple[str, str] Box = namedtuple( "Box", "category value x1 y1 x2 y2" ) # type: NamedTuple[str, str, float, float, float, float] PkType = int # TODO(fpoms): this needs to be wrapped in a lock so that # updates are atomic across concurrent requests current_result_sets = ExpiringDict( max_age_seconds=30 * 60, max_len=50, ) # type: Dict[str, ResultSet] # # ACTIVE VALIDATION # VAL_NEGATIVE_TYPE = "model_val_negative" # DATASET INFO def model_info(model): if model is None: return None pos_tags = parse_tag_set_from_query_v2(model.category_spec.get("pos_tags", [])) neg_tags = parse_tag_set_from_query_v2(model.category_spec.get("neg_tags", [])) augment_negs_include = parse_tag_set_from_query_v2( model.category_spec.get("augment_negs_include", []) ) return { "model_id": model.model_id, "timestamp": model.last_updated, "has_checkpoint": model.checkpoint_path is not None, "has_output": model.output_directory is not None, "pos_tags": serialize_tag_set_for_client_v2(pos_tags), "neg_tags": serialize_tag_set_for_client_v2(neg_tags | augment_negs_include), "augment_negs": model.category_spec.get("augment_negs", False), "epoch": model.epoch, } def bulk_add_single_tag_annotations_v2(payload, images): '''Adds annotations for a single tag to many dataset items''' if not images: return 0 user_email = payload["user"] category_name = payload["category"] mode_name = payload["mode"] created_by = payload.get("created_by", "tag" if len(images) == 1 else "tag-bulk") dataset = None if len(images) > 0: dataset = images[0].dataset user, _ = User.objects.get_or_create(email=user_email) category, _ = Category.objects.get_or_create(name=category_name) mode, _ = Mode.objects.get_or_create(name=mode_name) Annotation.objects.filter( dataset_item__in=images, category=category, is_box=False).delete() # TODO: Add an actual endpoint to delete annotations (probably by pk); don't rely # on this hacky "TOMBSTONE" string annotations = [ Annotation( dataset_item=di, user=user, category=category, mode=mode, is_box=False, misc_data={"created_by": created_by}, ) for di in images ] bulk_add_annotations_v2(dataset, annotations) return len(annotations) def bulk_add_multi_annotations_v2(payload : Dict): '''Adds multiple annotations for the same dataset and user to the database at once''' dataset_name = payload["dataset"] dataset = get_object_or_404(Dataset, name=dataset_name) user_email = payload["user"] user, _ = User.objects.get_or_create(email=user_email) created_by = payload.get("created_by", "tag" if len(payload["annotations"]) == 1 else "tag-bulk") # Get pks idents = [ann['identifier'] for ann in payload["annotations"] if 'identifier' in ann] di_pks = list(DatasetItem.objects.filter( dataset=dataset, identifier__in=idents ).values_list("pk", "identifier")) ident_to_pk = {ident: pk for pk, ident in di_pks} cats = {} modes = {} to_delete = defaultdict(set) annotations = [] for ann in payload["annotations"]: db_ann = Annotation() category_name = ann["category"] mode_name = ann["mode"] if category_name not in cats: cats[category_name] = Category.objects.get_or_create( name=category_name)[0] if mode_name not in modes: modes[mode_name] = Mode.objects.get_or_create( name=mode_name)[0] if "identifier" in ann: pk = ident_to_pk[ann["identifier"]] else: pk = ann["pk"] db_ann.dataset_item_id = pk db_ann.user = user db_ann.category = cats[category_name] db_ann.mode = modes[mode_name] db_ann.is_box = ann.get("is_box", False) if db_ann.is_box: db_ann.bbox_x1 = ann["x1"] db_ann.bbox_y1 = ann["y1"] db_ann.bbox_x2 = ann["x2"] db_ann.bbox_y2 = ann["y2"] else: to_delete[db_ann.category].add(pk) db_ann.misc_data={"created_by": created_by} annotations.append(db_ann) for cat, pks in to_delete.items(): # Delete per-frame annotations for the category if they exist since # we should only have on mode per image Annotation.objects.filter( category=cat, dataset_item_id__in=pks, is_box=False).delete() # TODO: Add an actual endpoint to delete annotations (probably by pk); don't rely # on this hacky "TOMBSTONE" string bulk_add_annotations_v2(dataset, annotations) return len(annotations) def bulk_add_annotations_v2(dataset, annotations): '''Handles book keeping for adding many annotations at once''' Annotation.objects.bulk_create(annotations) counts = defaultdict(int) for ann in annotations: counts[(ann.category, ann.mode)] += 1 for (cat, mode), count in counts.items(): category_count, _ = CategoryCount.objects.get_or_create( dataset=dataset, category=cat, mode=mode ) category_count.count += count category_count.save()
[ 6738, 17268, 1330, 4277, 11600, 11, 3706, 83, 29291, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 11748, 1233, 26791, 13, 22602, 198, 11748, 1257, 310, 10141, 198, 11748, 340, 861, 10141, 198, 11748, 33918, 198, 11748, 10688,...
2.338583
2,794
from __future__ import absolute_import import os import yaml from ccmlib import common, extension, repository from ccmlib.cluster import Cluster from ccmlib.dse_cluster import DseCluster from ccmlib.node import Node from distutils.version import LooseVersion #pylint: disable=import-error, no-name-in-module
[ 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 11748, 28686, 198, 198, 11748, 331, 43695, 198, 198, 6738, 36624, 4029, 571, 1330, 2219, 11, 7552, 11, 16099, 198, 6738, 36624, 4029, 571, 13, 565, 5819, 1330, 38279, 198, ...
3.270833
96
# Copyright 2019-2020 QuantumBlack Visual Analytics 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 # # 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 WILL THE LICENSOR OR OTHER CONTRIBUTORS # 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. # # The QuantumBlack Visual Analytics Limited ("QuantumBlack") name and logo # (either separately or in combination, "QuantumBlack Trademarks") are # trademarks of QuantumBlack. The License does not grant you any right or # license to the QuantumBlack Trademarks. You may not use the QuantumBlack # Trademarks or any confusingly similar mark as a trademark for your product, # or use the QuantumBlack Trademarks in any other manner that might cause # confusion in the marketplace, including but not limited to in advertising, # on websites, or on software. # # See the License for the specific language governing permissions and # limitations under the License. """ ``causalnex.pytorch.dist_type._base`` defines the distribution type class interface and default behavior. """ import itertools from abc import ABCMeta, abstractmethod from copy import deepcopy from typing import Dict, List, Tuple import numpy as np import torch from causalnex.structure.structuremodel import StructureModel
[ 2, 15069, 13130, 12, 42334, 29082, 9915, 15612, 30437, 15302, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13...
3.755319
470
# # -*- coding: utf-8 -*- # # Copyright (c) 2019 Jared Crapo # # 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. # """ Utility functions (not classes) """ import inspect import types from typing import Callable def validate_callable_param_count(func: Callable, count: int) -> None: """Ensure a function has the given number of parameters.""" signature = inspect.signature(func) # validate that the callable has the right number of parameters nparam = len(signature.parameters) if nparam != count: raise TypeError('{} has {} positional arguments, expected {}'.format( func.__name__, nparam, count, )) def validate_callable_argument(func, argnum, typ) -> None: """Validate that a certain argument of func is annotated for a specific type""" signature = inspect.signature(func) paramname = list(signature.parameters.keys())[argnum-1] param = signature.parameters[paramname] if param.annotation != typ: raise TypeError('argument {} of {} has incompatible type {}, expected {}'.format( argnum, func.__name__, param.annotation, typ.__name__, )) def validate_callable_return(func, typ) -> None: """Validate that func is annotated to return a specific type""" signature = inspect.signature(func) if typ: typname = typ.__name__ else: typname = 'None' if signature.return_annotation != typ: raise TypeError("{} must declare return a return type of '{}'".format( func.__name__, typname, )) def rebind_method(method, obj) -> None: """Rebind method from one object to another Call it something like this: rebind_method(obj1, obj2.do_command) This rebinds the ``do_command`` method from obj2 to obj1. Meaning after this function call you can: obj1.do_command() This works only on instantiated objects, not on classes. """ # # this is dark python magic # # if we were doing this in a hardcoded way, we might do: # # obj.method_name = types.MethodType(self.method_name.__func__, obj) # # TODO add force keyword parameter which defaults to false. If false, raise an # exception if the method already exists on obj method_name = method.__name__ setattr(obj, method_name, types.MethodType(method.__func__, obj)) def bind_function(func, obj) -> None: """Bind a function to an object You must define func with a ``self`` parameter, which is gonna look wierd: def myfunc(self, param): return param shell = cmdsh.Shell() utils.bind_function(myfunc, shell) You can use this function to bind a function to a class, so that all future objects of that class have the method: cmdsh.utils.bind_function(cmdsh.parsers.SimpleParser.parse, cmdsh.Shell) """ # # this is dark python magic # # if we were doing this in a hardcoded way, we would: # # obj.method_name = types.Methodtype(func, obj) # func_name = func.__name__ setattr(obj, func_name, types.MethodType(func, obj)) # TODO write bind_attribute()
[ 2, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 357, 66, 8, 13130, 19116, 327, 2416, 78, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 25...
2.868296
1,473
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # 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. # ============================================================================== """Tests for TPU outside compilation.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.distribute import tpu_strategy as tpu_lib from tensorflow.python.distribute.cluster_resolver import tpu_cluster_resolver from tensorflow.python.eager import def_function from tensorflow.python.eager import remote from tensorflow.python.eager import test from tensorflow.python.framework import constant_op from tensorflow.python.ops import logging_ops from tensorflow.python.ops import variables from tensorflow.python.platform import flags from tensorflow.python.tpu import tpu from tensorflow.python.tpu import tpu_strategy_util FLAGS = flags.FLAGS flags.DEFINE_string("tpu", "", "Name of TPU to connect to.") flags.DEFINE_string("project", None, "Name of GCP project with TPU.") flags.DEFINE_string("zone", None, "Name of GCP zone with TPU.") if __name__ == "__main__": test.main()
[ 2, 15069, 12131, 383, 309, 22854, 37535, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846,...
3.625821
457
from flask import Flask, request from flask_restful import Resource, Api from test import get_models, getTextFromImage from testDocument import getText from time import time app = Flask(__name__) api = Api(app) net, refine_net = get_models() api.add_resource(TextRecognizerService, "/recognize-text") if __name__ == "__main__": port = 5006 app.run(debug=True, port=port)
[ 6738, 42903, 1330, 46947, 11, 2581, 198, 6738, 42903, 62, 2118, 913, 1330, 20857, 11, 5949, 72, 198, 6738, 1332, 1330, 651, 62, 27530, 11, 651, 8206, 4863, 5159, 198, 6738, 1332, 24941, 1330, 651, 8206, 198, 6738, 640, 1330, 640, 198,...
2.984496
129
"""Module for BlameInteractionGraph plots.""" import typing as tp from datetime import datetime from pathlib import Path import click import matplotlib.pyplot as plt import networkx as nx import pandas as pd import plotly.offline as offply from matplotlib import style from varats.data.reports.blame_interaction_graph import ( create_blame_interaction_graph, CIGNodeAttrs, CIGEdgeAttrs, AIGNodeAttrs, CAIGNodeAttrs, ) from varats.data.reports.blame_report import BlameReport from varats.mapping.commit_map import get_commit_map from varats.paper_mgmt.case_study import ( newest_processed_revision_for_case_study, ) from varats.plot.plot import Plot, PlotDataEmpty from varats.plot.plots import ( PlotGenerator, REQUIRE_CASE_STUDY, REQUIRE_REVISION, ) from varats.plots.chord_plot_utils import ( make_chord_plot, make_arc_plot, NodeTy, ChordPlotNodeInfo, ChordPlotEdgeInfo, ArcPlotEdgeInfo, ArcPlotNodeInfo, ) from varats.ts_utils.cli_util import CLIOptionTy, make_cli_option from varats.utils.git_util import ( CommitRepoPair, create_commit_lookup_helper, UNCOMMITTED_COMMIT_HASH, FullCommitHash, ShortCommitHash, ) NodeInfoTy = tp.TypeVar("NodeInfoTy", ChordPlotNodeInfo, ArcPlotNodeInfo) EdgeInfoTy = tp.TypeVar("EdgeInfoTy", ChordPlotEdgeInfo, ArcPlotEdgeInfo) OPTIONAL_SORT_METHOD: CLIOptionTy = make_cli_option( "--sort-by", type=click.Choice(["degree", "time"]), default="degree", required=False, help="Sort method for commit interaction graph nodes." )
[ 37811, 26796, 329, 1086, 480, 9492, 2673, 37065, 21528, 526, 15931, 198, 198, 11748, 19720, 355, 256, 79, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 3904, 198, 11748, 2603, 29487, 8019, ...
2.631229
602
import re if __name__ == "__main__": main()
[ 11748, 302, 628, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419, 198 ]
2.304348
23
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** 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 from . import outputs from ._enums import * __all__ = [ 'ApiKeyStageKey', 'ApiKeyTag', 'ClientCertificateTag', 'DeploymentAccessLogSetting', 'DeploymentCanarySetting', 'DeploymentCanarySettings', 'DeploymentMethodSetting', 'DeploymentStageDescription', 'DeploymentTag', 'DocumentationPartLocation', 'DomainNameEndpointConfiguration', 'DomainNameMutualTlsAuthentication', 'DomainNameTag', 'MethodIntegration', 'MethodIntegrationResponse', 'MethodResponse', 'RestApiEndpointConfiguration', 'RestApiS3Location', 'RestApiTag', 'StageAccessLogSetting', 'StageCanarySetting', 'StageMethodSetting', 'StageTag', 'UsagePlanApiStage', 'UsagePlanQuotaSettings', 'UsagePlanTag', 'UsagePlanThrottleSettings', 'VpcLinkTag', ]
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 21624, 12994, 26144, 35986, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760, 644, 345, 389, 1804, 0, 17202, ...
2.89604
404
#!/.conda/envs/hodemulator/bin/python from pearce.emulator import make_training_data from pearce.emulator import DEFAULT_PARAMS as ordered_params ordered_params['f_c'] = (0.05, .5) ordered_params['logMmin'] = (11.5, 13.0)#(13.0, 14.5) ordered_params['sigma_logM'] = (0.05, 1.0) ordered_params['logM1'] = (12.0, 15.0) ordered_params['alpha'] = (0.8, 1.5) ordered_params.update({'mean_occupation_centrals_assembias_param1':( -1.0, 1.0), 'mean_occupation_satellites_assembias_param1':( -1.0, 1.0)}) make_training_data('/u/ki/swmclau2/Git/pearce/bin/training_data/ds_redmagic.cfg',ordered_params)
[ 2, 0, 11757, 66, 13533, 14, 268, 14259, 14, 2065, 368, 8927, 14, 8800, 14, 29412, 198, 6738, 25286, 344, 13, 368, 8927, 1330, 787, 62, 34409, 62, 7890, 198, 6738, 25286, 344, 13, 368, 8927, 1330, 5550, 38865, 62, 27082, 40834, 355, ...
2.234657
277
# ------------------------------------------------------------------------------ # Project: legohdl # Script: workspace.py # Author: Chase Ruskin # Description: # The Workspace class. A Workspace object has a path and a list of available # vendors. This is what the user keeps their work's scope within for a given # "organization". # ------------------------------------------------------------------------------ import os, shutil, glob import logging as log from datetime import datetime from .vendor import Vendor from .apparatus import Apparatus as apt from .cfg import Cfg, Section, Key from .map import Map from .git import Git from .block import Block def getPath(self): '''Returns the local path where downloaded blocks are located (str).''' return self._path def getDir(self): '''Returns the base hidden directory where the workspace data is kept (str).''' return self._ws_dir def getCachePath(self): '''Returns the hidden directory where workspace installations are kept. (str).''' return self.getDir()+"cache/" def getName(self): '''Returns the workspace's identifier (str).''' return self._name def isActive(self): '''Returns is this workspace is the active workspace (bool).''' return self == self.getActive() def getVendors(self, returnnames=False, lowercase=True): ''' Return the vendor objects associated with the given workspace. Parameters: returnnames (bool): true will return vendor names lowercase (bool): true will return lower-case names if returnnames is enabled Returns: ([Vendor]) or ([str]): list of available vendors ''' if(returnnames): vndr_names = [] for vndr in self._vendors: name = vndr.getName() if(lowercase): name = name.lower() vndr_names += [name] return vndr_names else: return self._vendors # uncomment to use for debugging # def __str__(self): # return f''' # ID: {hex(id(self))} # Name: {self.getName()} # Path: {self.getPath()} # Active: {self.isActive()} # Hidden directory: {self.getDir()} # Linked to: {self.isLinked()} # Vendors: {self.getVendors(returnnames=True)} # ''' pass
[ 2, 16529, 26171, 198, 2, 4935, 25, 1232, 1219, 25404, 198, 2, 12327, 25, 44573, 13, 9078, 198, 2, 6434, 25, 16346, 9223, 5116, 198, 2, 12489, 25, 198, 2, 220, 220, 383, 10933, 10223, 1398, 13, 317, 10933, 10223, 2134, 468, 257, 31...
2.569937
958
# -*- coding: utf-8 -*- """ Created on Wed Dec 16 18:01:24 2015 @author: Avinash """ import numpy as np from numpy import * import numpy from math import * import ev_charge_schedule_modification1 as ev #import ev_charge_schedule.static as func1 #import ev_charge_schedule.dynamic as func2 import time #from numba import double from numba.decorators import autojit func1=ev.static func=autojit(func1) mode=1 runs=1 maxiter=2000 F=0.5 # Mutation Factor between 0 to 2 CR=0.2 # Probability 1. Put 0.9 if parameters are dependent while 0.2 if parameters are independent(seperable) N=40 D=100*24 # Number of particles ev.global_var(var_set=0,N_veh=int(D/float(24))) # boundary constraints ub=numpy.random.random(size=(1,D))[0] lb=numpy.random.random(size=(1,D))[0] i=0 while i<D: ub[i]=8.8 lb[i]=2.2 i+=1 fitness_val=numpy.zeros(shape=(runs,maxiter)) best_pos=numpy.zeros(shape=(runs,D)) for run_no in range(runs): # target vector initializtion x=numpy.random.uniform(size=(N,D)) i=0 while i<N: j=0 while j<D: x[i][j]=lb[j]+x[i][j]*(ub[j]-lb[j]) j+=1 i+=1 v=np.zeros_like(x) # donar vectors u=np.zeros_like(x) # trail vector g=numpy.zeros(shape=(1,D))[0] # best vector found so far # target vector initial fitness evaluation x_fit=numpy.random.uniform(size=(1,N))[0] i=0 while i<N: x_fit[i]=func(x[i],mode=mode) i+=1 u_fit=np.zeros_like(x_fit) j=0 i=1 while i<N: if x_fit[j]>x_fit[i]: j=i i+=1 g_fit=x_fit[j] g=x[j].copy() time1=time.time() it=0 while it<maxiter: # Mutation stage for i in range(N): r1=i while r1==i: r1=np.random.randint(low=0,high=N) r2=i while r2==i or r2==r1: r2=np.random.randint(low=0,high=N) r3=i while r3==i or r3==r1 or r3==r2: r3=np.random.randint(low=0,high=N) v[i]=x[r1]+(x[r2]-x[r3])*F for j in range(D): # if v[i][j]>ub[j]: # v[i][j]=v[i][j]-(1+numpy.random.rand())*(v[i][j]-ub[j]) # if v[i][j]<lb[j]: # v[i][j]=v[i][j]-(1+numpy.random.rand())*(v[i][j]-lb[j]) # if v[i][j]>ub[j]: # v[i][j]=ub[j] # if v[i][j]<lb[j]: # v[i][j]=lb[j] if v[i][j]>ub[j]: #v[i][j]=v[i][j]-1.1*(v[i][j]-ub[j]) v[i][j]=lb[j]+numpy.random.random()*(ub[j]-lb[j]) if v[i][j]<lb[j]: v[i][j]=lb[j]+numpy.random.random()*(ub[j]-lb[j]) #v[i][j]=v[i][j]-1.1*(v[i][j]-lb[j]) # Recombination stage for i in range(N): for j in range(D): if np.random.random()<=CR or j==numpy.random.randint(0,D): u[i][j]=v[i][j] else: u[i][j]=x[i][j] # Selection stage for i in range(N): u_fit[i]=func(u[i],mode=mode) if u_fit[i]<x_fit[i]: x[i]=u[i].copy() x_fit[i]=u_fit[i] if u_fit[i]<g_fit: g=u[i].copy() g_fit=u_fit[i] fitness_val[run_no][it]=g_fit print it,g_fit it+=1 best_pos[run_no]=g.copy() time2=time.time() print time2-time1 run_no+=1 numpy.savetxt("DE_fitness_d1_m2"+str(mode)+str(D)+".csv",fitness_val,delimiter=",") numpy.savetxt("DE_bestpos_d1_m2"+str(mode)+str(D)+".csv",best_pos,delimiter=",")
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 41972, 319, 3300, 4280, 1467, 1248, 25, 486, 25, 1731, 1853, 201, 198, 201, 198, 31, 9800, 25, 5184, 259, 1077, 201, 198, 37811, 201, 198, 201, ...
1.606891
2,409
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import *
[ 2, 15069, 2211, 12, 42334, 13914, 45036, 3549, 2351, 4765, 11, 11419, 290, 584, 198, 2, 1338, 441, 4935, 34152, 13, 4091, 262, 1353, 12, 5715, 27975, 38162, 9947, 2393, 329, 3307, 13, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, 33234,...
3.47619
63
import logging from functools import wraps from flask import request, session from prometheus_client import Counter from auth.basic import validate_basic_auth from auth.oauth import validate_bearer_auth from auth.cookie import validate_session_cookie from auth.signedgrant import validate_signed_grant from util.http import abort logger = logging.getLogger(__name__) authentication_count = Counter( "quay_authentication_attempts_total", "number of authentication attempts accross the registry and API", labelnames=["auth_kind", "success"], ) def _auth_decorator(pass_result=False, handlers=None): """ Builds an auth decorator that runs the given handlers and, if any return successfully, sets up the auth context. The wrapped function will be invoked *regardless of success or failure of the auth handler(s)* """ return processor process_oauth = _auth_decorator(handlers=[validate_bearer_auth, validate_session_cookie]) process_auth = _auth_decorator(handlers=[validate_signed_grant, validate_basic_auth]) process_auth_or_cookie = _auth_decorator(handlers=[validate_basic_auth, validate_session_cookie]) process_basic_auth = _auth_decorator(handlers=[validate_basic_auth], pass_result=True) process_basic_auth_no_pass = _auth_decorator(handlers=[validate_basic_auth]) def require_session_login(func): """ Decorates a function and ensures that a valid session cookie exists or a 401 is raised. If a valid session cookie does exist, the authenticated user and identity are also set. """ return wrapper def extract_namespace_repo_from_session(func): """ Extracts the namespace and repository name from the current session (which must exist) and passes them into the decorated function as the first and second arguments. If the session doesn't exist or does not contain these arugments, a 400 error is raised. """ return wrapper
[ 11748, 18931, 198, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 6738, 42903, 1330, 2581, 11, 6246, 198, 6738, 1552, 36916, 62, 16366, 1330, 15034, 198, 198, 6738, 6284, 13, 35487, 1330, 26571, 62, 35487, 62, 18439, 198, 6738, 6284, 13...
3.4
565
import os from PIL import Image import seaborn as sn import matplotlib.pyplot as plt import torch import torch.nn.functional as F from sidechainnet.utils.sequence import ProteinVocabulary from einops import rearrange # general functions # singleton msa transformer msa_instances = None # MSA embedding related functions VOCAB = ProteinVocabulary() # getting a single MSA attention embedding, with caching CACHE_PATH = default(os.getenv('CACHE_PATH'), os.path.expanduser('~/.cache.ddpm-proteins')) FETCH_FROM_CACHE = not exists(os.getenv('CLEAR_CACHE')) os.makedirs(CACHE_PATH, exist_ok = True) # training utils
[ 11748, 28686, 198, 6738, 350, 4146, 1330, 7412, 198, 11748, 384, 397, 1211, 355, 3013, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 198, ...
2.906542
214
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # 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 os import sys import argparse import logging import tensorflow as tf import onnx_graphsurgeon as gs import numpy as np import onnx from onnx import shape_inference from tf2onnx import tfonnx, optimizer, tf_loader import onnx_utils logging.basicConfig(level=logging.INFO) logging.getLogger("EfficientDetGraphSurgeon").setLevel(logging.INFO) log = logging.getLogger("EfficientDetGraphSurgeon") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-m", "--saved_model", required=True, help="The TensorFlow saved model directory to load") parser.add_argument("-o", "--onnx", required=True, help="The output ONNX model file to write") parser.add_argument("-f", "--input_format", default="NHWC", choices=["NHWC", "NCHW"], help="Set the input data format of the graph, either NCHW or NHWC, default: NHWC") parser.add_argument("-i", "--input_size", default="512,512", help="Set the input shape of the graph, as a comma-separated dimensions in H,W format, " "default: 512,512") parser.add_argument("-p", "--preprocessor", default="imagenet", choices=["imagenet", "scale_range"], help="Set the preprocessor to apply on the graph, either 'imagenet' for standard mean " "subtraction and stdev normalization, or 'scale_range' for uniform [-1,+1] " "normalization as is used in the AdvProp models, default: imagenet") parser.add_argument("-t", "--nms_threshold", type=float, help="Override the NMS score threshold, default: use the original value in the model") parser.add_argument("-d", "--nms_detections", type=int, help="Override the NMS max detections, default: use the original value in the model") parser.add_argument("--tf2onnx", help="The path where to save the intermediate ONNX graph generated by tf2onnx, useful" "for graph debugging purposes, default: not saved") args = parser.parse_args() main(args)
[ 2, 198, 2, 30628, 55, 12, 8979, 15269, 8206, 25, 15069, 357, 66, 8, 9656, 12, 1238, 1828, 15127, 23929, 44680, 6234, 1222, 317, 5777, 4146, 40, 29462, 13, 1439, 2489, 10395, 13, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 2...
2.606143
1,107
''' matrix matrix ''' from typing import List ''' m*nn*m ''' s = Solution() print(s.transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) print(s.transpose([[1, 2, 3], [4, 5, 6]]))
[ 7061, 6, 628, 198, 17593, 220, 17593, 220, 220, 220, 628, 220, 220, 198, 7061, 6, 198, 198, 6738, 19720, 1330, 7343, 198, 7061, 6, 198, 76, 9, 20471, 9, 76, 198, 7061, 6, 628, 198, 198, 82, 796, 28186, 3419, 198, 4798, 7, 82, ...
1.978947
95
from adam_visual_perception import LandmarkDetector from adam_visual_perception.utility import * import numpy as np import math import cv2 import os import sys
[ 6738, 23197, 62, 41464, 62, 525, 4516, 1330, 6379, 4102, 11242, 9250, 198, 6738, 23197, 62, 41464, 62, 525, 4516, 13, 315, 879, 1330, 1635, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 10688, 198, 11748, 269, 85, 17, 198, 11748, 28...
3.5
46
# -*- coding: utf-8 -*- import disnake from disnake.ext import commands from pypoca.config import COLOR, URLS from pypoca.database import Server from pypoca.ext import ALL, DEFAULT, Choice, Option
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 595, 77, 539, 198, 6738, 595, 77, 539, 13, 2302, 1330, 9729, 198, 198, 6738, 279, 4464, 11216, 13, 11250, 1330, 20444, 1581, 11, 37902, 6561, 198, 6738, 279, 44...
2.941176
68
from rest_framework.decorators import api_view, permission_classes from rest_framework.parsers import MultiPartParser from rest_framework.response import Response from rest_framework import permissions from rest_framework.exceptions import APIException from rest_framework.decorators import parser_classes from django.shortcuts import get_object_or_404 from manager.models import Agent
[ 6738, 1334, 62, 30604, 13, 12501, 273, 2024, 1330, 40391, 62, 1177, 11, 7170, 62, 37724, 198, 6738, 1334, 62, 30604, 13, 79, 945, 364, 1330, 15237, 7841, 46677, 198, 6738, 1334, 62, 30604, 13, 26209, 1330, 18261, 198, 6738, 1334, 62, ...
4.172043
93
# Copyright 2020 The TensorFlow Probability Authors. # # 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. # ============================================================================ """Drivers for streaming reductions framework.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import warnings # Dependency imports import tensorflow.compat.v2 as tf from tensorflow_probability.python.experimental.mcmc import sample as exp_sample_lib from tensorflow_probability.python.experimental.mcmc import sample_discarding_kernel from tensorflow_probability.python.experimental.mcmc import tracing_reducer from tensorflow_probability.python.experimental.mcmc import with_reductions from tensorflow_probability.python.mcmc import sample from tensorflow.python.util import nest # pylint: disable=g-direct-tensorflow-import __all__ = [ 'sample_chain', 'sample_fold', ] def sample_fold( num_steps, current_state, previous_kernel_results=None, kernel=None, reducer=None, num_burnin_steps=0, num_steps_between_results=0, parallel_iterations=10, seed=None, name=None, ): """Computes the requested reductions over the `kernel`'s samples. To wit, runs the given `kernel` for `num_steps` steps, and consumes the stream of samples with the given `Reducer`s' `one_step` method(s). This runs in constant memory (unless a given `Reducer` builds a large structure). The driver internally composes the correct onion of `WithReductions` and `SampleDiscardingKernel` to implement the requested optionally thinned reduction; however, the kernel results of those applied Transition Kernels will not be returned. Hence, if warm-restarting reductions is desired, one should manually build the Transition Kernel onion and use `tfp.experimental.mcmc.step_kernel`. An arbitrary collection of `reducer` can be provided, and the resulting finalized statistic(s) will be returned in an identical structure. Args: num_steps: Integer or scalar `Tensor` representing the number of `Reducer` steps. current_state: `Tensor` or Python `list` of `Tensor`s representing the current state(s) of the Markov chain(s). previous_kernel_results: A `Tensor` or a nested collection of `Tensor`s. Warm-start for the auxiliary state needed by the given `kernel`. If not supplied, `sample_fold` will cold-start with `kernel.bootstrap_results`. kernel: An instance of `tfp.mcmc.TransitionKernel` which implements one step of the Markov chain. reducer: A (possibly nested) structure of `Reducer`s to be evaluated on the `kernel`'s samples. If no reducers are given (`reducer=None`), then `None` will be returned in place of streaming calculations. num_burnin_steps: Integer or scalar `Tensor` representing the number of chain steps to take before starting to collect results. Defaults to 0 (i.e., no burn-in). num_steps_between_results: Integer or scalar `Tensor` representing the number of chain steps between collecting a result. Only one out of every `num_steps_between_samples + 1` steps is included in the returned results. Defaults to 0 (i.e., no thinning). parallel_iterations: The number of iterations allowed to run in parallel. It must be a positive integer. See `tf.while_loop` for more details. seed: Optional seed for reproducible sampling. name: Python `str` name prefixed to Ops created by this function. Default value: `None` (i.e., 'mcmc_sample_fold'). Returns: reduction_results: A (possibly nested) structure of finalized reducer statistics. The structure identically mimics that of `reducer`. end_state: The final state of the Markov chain(s). final_kernel_results: `collections.namedtuple` of internal calculations used to advance the supplied `kernel`. These results do not include the kernel results of `WithReductions` or `SampleDiscardingKernel`. """ with tf.name_scope(name or 'mcmc_sample_fold'): num_steps = tf.convert_to_tensor( num_steps, dtype=tf.int32, name='num_steps') current_state = tf.nest.map_structure( lambda x: tf.convert_to_tensor(x, name='current_state'), current_state) reducer_was_none = False if reducer is None: reducer = [] reducer_was_none = True reduction_kernel = with_reductions.WithReductions( inner_kernel=sample_discarding_kernel.SampleDiscardingKernel( inner_kernel=kernel, num_burnin_steps=num_burnin_steps, num_steps_between_results=num_steps_between_results), reducer=reducer, ) end_state, final_kernel_results = exp_sample_lib.step_kernel( num_steps=num_steps, current_state=current_state, previous_kernel_results=previous_kernel_results, kernel=reduction_kernel, return_final_kernel_results=True, parallel_iterations=parallel_iterations, seed=seed, name=name, ) reduction_results = nest.map_structure_up_to( reducer, lambda r, s: r.finalize(s), reducer, final_kernel_results.streaming_calculations, check_types=False) if reducer_was_none: reduction_results = None return (reduction_results, end_state, final_kernel_results.inner_results.inner_results) def sample_chain( num_results, current_state, previous_kernel_results=None, kernel=None, num_burnin_steps=0, num_steps_between_results=0, trace_fn=_trace_kernel_results, return_final_kernel_results=False, parallel_iterations=10, seed=None, name=None, ): """Implements Markov chain Monte Carlo via repeated `TransitionKernel` steps. This function samples from a Markov chain at `current_state` whose stationary distribution is governed by the supplied `TransitionKernel` instance (`kernel`). This function can sample from multiple chains, in parallel. (Whether or not there are multiple chains is dictated by the `kernel`.) The `current_state` can be represented as a single `Tensor` or a `list` of `Tensors` which collectively represent the current state. Since MCMC states are correlated, it is sometimes desirable to produce additional intermediate states, and then discard them, ending up with a set of states with decreased autocorrelation. See [Owen (2017)][1]. Such 'thinning' is made possible by setting `num_steps_between_results > 0`. The chain then takes `num_steps_between_results` extra steps between the steps that make it into the results. The extra steps are never materialized, and thus do not increase memory requirements. In addition to returning the chain state, this function supports tracing of auxiliary variables used by the kernel. The traced values are selected by specifying `trace_fn`. By default, all kernel results are traced but in the future the default will be changed to no results being traced, so plan accordingly. See below for some examples of this feature. Args: num_results: Integer number of Markov chain draws. current_state: `Tensor` or Python `list` of `Tensor`s representing the current state(s) of the Markov chain(s). previous_kernel_results: A `Tensor` or a nested collection of `Tensor`s representing internal calculations made within the previous call to this function (or as returned by `bootstrap_results`). kernel: An instance of `tfp.mcmc.TransitionKernel` which implements one step of the Markov chain. num_burnin_steps: Integer number of chain steps to take before starting to collect results. Default value: 0 (i.e., no burn-in). num_steps_between_results: Integer number of chain steps between collecting a result. Only one out of every `num_steps_between_samples + 1` steps is included in the returned results. The number of returned chain states is still equal to `num_results`. Default value: 0 (i.e., no thinning). trace_fn: A callable that takes in the current chain state and the previous kernel results and return a `Tensor` or a nested collection of `Tensor`s that is then traced along with the chain state. return_final_kernel_results: If `True`, then the final kernel results are returned alongside the chain state and the trace specified by the `trace_fn`. parallel_iterations: The number of iterations allowed to run in parallel. It must be a positive integer. See `tf.while_loop` for more details. seed: Optional, a seed for reproducible sampling. name: Python `str` name prefixed to Ops created by this function. Default value: `None` (i.e., 'experimental_mcmc_sample_chain'). Returns: checkpointable_states_and_trace: if `return_final_kernel_results` is `True`. The return value is an instance of `CheckpointableStatesAndTrace`. all_states: if `return_final_kernel_results` is `False` and `trace_fn` is `None`. The return value is a `Tensor` or Python list of `Tensor`s representing the state(s) of the Markov chain(s) at each result step. Has same shape as input `current_state` but with a prepended `num_results`-size dimension. states_and_trace: if `return_final_kernel_results` is `False` and `trace_fn` is not `None`. The return value is an instance of `StatesAndTrace`. #### References [1]: Art B. Owen. Statistically efficient thinning of a Markov chain sampler. _Technical Report_, 2017. http://statweb.stanford.edu/~owen/reports/bestthinning.pdf """ with tf.name_scope(name or 'experimental_mcmc_sample_chain'): if not kernel.is_calibrated: warnings.warn('supplied `TransitionKernel` is not calibrated. Markov ' 'chain may not converge to intended target distribution.') if trace_fn is None: trace_fn = lambda *args: () no_trace = True else: no_trace = False if trace_fn is sample_chain.__defaults__[4]: warnings.warn('Tracing all kernel results by default is deprecated. Set ' 'the `trace_fn` argument to None (the future default ' 'value) or an explicit callback that traces the values ' 'you are interested in.') # `WithReductions` assumes all its reducers want to reduce over the # immediate inner results of its kernel results. However, # We don't care about the kernel results of `SampleDiscardingKernel`; hence, # we evaluate the `trace_fn` on a deeper level of inner results. trace_reducer = tracing_reducer.TracingReducer( trace_fn=real_trace_fn, size=num_results ) trace_results, _, final_kernel_results = sample_fold( num_steps=num_results, current_state=current_state, previous_kernel_results=previous_kernel_results, kernel=kernel, reducer=trace_reducer, num_burnin_steps=num_burnin_steps, num_steps_between_results=num_steps_between_results, parallel_iterations=parallel_iterations, seed=seed, name=name, ) all_states, trace = trace_results if return_final_kernel_results: return sample.CheckpointableStatesAndTrace( all_states=all_states, trace=trace, final_kernel_results=final_kernel_results) else: if no_trace: return all_states else: return sample.StatesAndTrace(all_states=all_states, trace=trace)
[ 2, 15069, 12131, 383, 309, 22854, 37535, 30873, 1799, 46665, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262,...
2.97612
4,062
import time from collections import deque import gym import numpy as np from stable_baselines import logger, PPO2 from stable_baselines.a2c.utils import total_episode_reward_logger from stable_baselines.common import explained_variance, TensorboardWriter from stable_baselines.common.runners import AbstractEnvRunner from stable_baselines.ppo2.ppo2 import get_schedule_fn, safe_mean, swap_and_flatten
[ 11748, 640, 198, 6738, 17268, 1330, 390, 4188, 198, 198, 11748, 11550, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 8245, 62, 12093, 20655, 1330, 49706, 11, 350, 16402, 17, 198, 6738, 8245, 62, 12093, 20655, 13, 64, 17, 66, 13, 2679...
3.452991
117
#!/usr/bin/env python2 """ Copyright (c) 2014-2019 Maltrail developers (https://github.com/stamparm/maltrail/) See the file 'LICENSE' for copying permission """ from craw.modules.trail.plugins.util import wget_content __url__ = "http://www.urlvir.com/export-hosts/" __check__ = "Updated on" __info__ = "malware" __reference__ = "urlvir.com" maintainer_url = __reference__ maintainer = "urlvir" list_source_url = __url__ category = __info__
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 198, 37811, 198, 15269, 357, 66, 8, 1946, 12, 23344, 23729, 30224, 6505, 357, 5450, 1378, 12567, 13, 785, 14, 301, 696, 1670, 14, 76, 2501, 30224, 34729, 198, 6214, 262, 2393, 70...
2.834395
157
import os import subprocess import sys import unittest # TODO: these command should be written at once, at only .travis.yml or at only here paths = ['oj', 'onlinejudge', 'setup.py', 'tests']
[ 11748, 28686, 198, 11748, 850, 14681, 198, 11748, 25064, 198, 11748, 555, 715, 395, 198, 198, 2, 16926, 46, 25, 777, 3141, 815, 307, 3194, 379, 1752, 11, 379, 691, 764, 83, 16956, 13, 88, 4029, 393, 379, 691, 994, 198, 198, 6978, ...
3.129032
62
# -*- coding: utf-8 -*- # # ----------------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved. # # The MIT License (MIT) # # 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. # ----------------------------------------------------------------------------------- # "javascript" section for javascript. see @app.route('/config.js') in app/views.py # NOTE: all following key/secrets for test purpose. HOSTNAME = "http://localhost" # host name of the UI site # hacking.kaiyuanshe.cn is used for wechat oauth login # HOSTNAME = "http://hacking.kaiyuanshe.cn" # HOSTNAME = "http://open-hackathon-dev.chinacloudapp.cn" # host name of the UI site # HOSTNAME = "http://hacking.kaiyuanshe.cn" QQ_OAUTH_STATE = "openhackathon" # todo state should be constant. Actually it should be unguessable to prevent CSFA HACKATHON_API_ENDPOINT = "http://localhost:15000" # HACKATHON_API_ENDPOINT = "http://open-hackathon-dev.chinacloudapp.cn:15000" # HACKATHON_API_ENDPOINT = "http://hacking.kaiyuanshe.cn:15000" # github key for `localhost` GITHUB_CLIENT_ID = "b44f3d47bdeb26b9c4e6" GITHUB_CLIENT_SECRET = "98de14161c4b2ed3ea7a19787d62cda73b8e292c" # github oauth key for `open-hackathon-dev.chinacloudapp.cn` # GITHUB_CLIENT_ID = "b8e407813350f26bf537" # GITHUB_CLIENT_SECRET = "daa78ae27e13c9f5b4a884bd774cadf2f75a199f" QQ_CLIENT_ID = "101200890" QQ_CLIENT_SECRET = "88ad67bd4521c4cc47136854781cb9b5" QQ_META_CONTENT = "274307566465013314076545663016134754100636" WECHAT_APP_ID = "wxe75b8aef71c2059f" WECHAT_SECRET = "4532b90750f4c7bc70fcfbc42d881622" WECHAT_OAUTH_STATE = "openhackathon" # NOTE: may be should be same as QQ_OAUTH_STATE? WEIBO_CLIENT_ID = "479757037" WEIBO_CLIENT_SECRET = "efc5e75ff8891be37d90b4eaec5c02de" WEIBO_META_CONTENT = "ae884e09bc02b700" LIVE_CLIENT_ID = "000000004414E0A6" LIVE_CLIENT_SECRET = "b4mkfVqjtwHY2wJh0T4tj74lxM5LgAT2" ALAUDA_CLIENT_ID = "4VR9kzNZVyWcnk9OnAwMuSus7xOOcozJIpic6W6y" ALAUDA_CLIENT_SECRET = "E5PUL5h9feLlEirec5HQhjIzYecv7vVbEBjWLBkRMoCoFXdvS1PzNmd4AAeNgu4M2AJ87uGnnJaoDLCcDuVxkBoHRWCn6LmfB4SKK1Dty1SkGukkTcZPEk9wpHLSiRQ3" Config = { "environment": "local", "app": { "secret_key": "secret_key" }, "login": { "github": { "client_id": GITHUB_CLIENT_ID, "access_token_url": 'https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&redirect_uri=%s/github&code=' % ( GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, HOSTNAME), "user_info_url": 'https://api.github.com/user?access_token=', "emails_info_url": 'https://api.github.com/user/emails?access_token=' }, "qq": { "client_id": QQ_CLIENT_ID, "meta_content": QQ_META_CONTENT, "access_token_url": 'https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=%s&client_secret=%s&redirect_uri=%s/qq&code=' % ( QQ_CLIENT_ID, QQ_CLIENT_SECRET, HOSTNAME), "openid_url": 'https://graph.qq.com/oauth2.0/me?access_token=', "user_info_url": 'https://graph.qq.com/user/get_user_info?access_token=%s&oauth_consumer_key=%s&openid=%s' }, "wechat": { "client_id": WECHAT_APP_ID, "access_token_url": "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%%s&grant_type=authorization_code" % ( WECHAT_APP_ID, WECHAT_SECRET), "user_info_url": "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s" }, "weibo": { "client_id": WEIBO_CLIENT_ID, "meta_content": WEIBO_META_CONTENT, "user_info_url": 'https://api.weibo.com/2/users/show.json?access_token=', "email_info_url": 'https://api.weibo.com/2/account/profile/email.json?access_token=', "access_token_url": 'https://api.weibo.com/oauth2/access_token?client_id=%s&client_secret=%s&grant_type=authorization_code&redirect_uri=%s/weibo&code=' % ( WEIBO_CLIENT_ID, WEIBO_CLIENT_SECRET, HOSTNAME) }, "live": { "client_id": LIVE_CLIENT_ID, "client_secret": LIVE_CLIENT_SECRET, "redirect_uri": '%s/live' % HOSTNAME, "access_token_url": 'https://login.live.com/oauth20_token.srf', "user_info_url": 'https://apis.live.net/v5.0/me?access_token=' }, "alauda": { "client_id": ALAUDA_CLIENT_ID, "client_secret": ALAUDA_CLIENT_SECRET, "redirect_uri": '%s/alauda' % HOSTNAME, "access_token_url": 'http://console.int.alauda.io/oauth/token' }, "provider_enabled": ["github", "wechat"], "session_valid_time_minutes": 60 }, "hackathon-api": { "endpoint": HACKATHON_API_ENDPOINT }, "javascript": { "github": { "authorize_url": "https://github.com/login/oauth/authorize?client_id=%s&redirect_uri=%s/github&scope=user" % ( GITHUB_CLIENT_ID, HOSTNAME) }, "weibo": { "authorize_url": "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s/weibo&scope=all" % ( WEIBO_CLIENT_ID, HOSTNAME) }, "qq": { "authorize_url": "https://graph.qq.com/oauth2.0/authorize?client_id=%s&redirect_uri=%s/qq&scope=get_user_info&state=%s&response_type=code" % ( QQ_CLIENT_ID, HOSTNAME, QQ_OAUTH_STATE) }, "wechat": { "authorize_url": "https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s/wechat&response_type=code&scope=snsapi_login&state=%s#wechat_redirect" % ( WECHAT_APP_ID, HOSTNAME, WECHAT_OAUTH_STATE) }, "live": { "authorize_url": "https://login.live.com/oauth20_authorize.srf?client_id=%s&scope=wl.basic+,wl.emails&response_type=code&redirect_uri=%s/live" % ( LIVE_CLIENT_ID, HOSTNAME) }, "alauda": { "authorize_url": "http://console.int.alauda.io/oauth/authorize?response_type=code&client_id=%s&state=state&redirect_uri=%s/alauda" % ( ALAUDA_CLIENT_ID, HOSTNAME) }, "hackathon": { "endpoint": HACKATHON_API_ENDPOINT }, "apiconfig": { "proxy": HACKATHON_API_ENDPOINT, "api": { "admin": { "hackathon": { "": ["get", "post", "put", "delete"], "checkname": ["get"], "list": ["get"], "online": ["post"], "applyonline": ["post"], "offline": ["post"], "tags": ["get", "post", "put", "delete"], "config": ["get", "post", "put", "delete"], "administrator": { "": ["put", "post", "delete"], "list": ["get"] }, "template": { "": ["post", "delete"], "list": ["get"], "check": ["get"] }, "organizer": { "": ["get", "post", "put", "delete"] }, "award": { "": ["get", "post", "put", "delete"], "list": ["get"] }, "notice": { "": ["get", "post", "put", "delete"] } }, "registration": { "": ["get", "post", "delete", "put"], "list": ["get"] }, "azure": { "": ["get", "post", "delete", "put"], "checksubid": ["post"] }, "experiment": { "list": ["get"], "": ["post", "put"] }, "team": { "list": ["get"], "score": { "list": ["get"] }, "award": ["get", "post", "delete"] }, "user": { "list": ["get"] }, "hostserver": { "": ["get", "post", "delete", "put"], "list": ["get"] } }, "template": { "": ["get", "post", "delete", "put"], "file": ["post"], "list": ["get"], "check": ["get"] }, "user": { "": ["get"], "login": ["post", "delete"], "experiment": { "": ["get", "post", "delete", "put"] }, "registration": { "": ["put", "post", "get"], "checkemail": ["get"], "list": ["get"] }, "profile": { "": ["post", "put"] }, "picture": { "": ["put"] }, "team": { "member": ["get"] }, "hackathon": { "like": ["get", "post", "delete"] }, "notice": { "read": ["put"] }, "show": { "list": ["get"] }, "file": { "": ["post"] } }, "hackathon": { "": ["get"], "list": ["get"], "stat": ["get"], "template": ["get"], "team": { "list": ["get"] }, "registration": { "list": ["get"] }, "show": { "list": ["get"] }, "grantedawards": ["get"], "notice": { "list": ["get"] } }, "team": { "": ["get", "post", "put", "delete"], "score": ["get", "post", "put"], "member": { "": ["post", "put", "delete"], "list": ["get"] }, "show": ["get", "post", "delete"], "template": ["post", "delete"] }, "talent": { "list": ["get"] }, "grantedawards": ["get"] } } } }
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 16529, 1783, 6329, 198, 2, 15069, 357, 66, 8, 5413, 4946, 21852, 357, 2484, 272, 20380, 8, 1766, 13, 12052, 13, 220, 1439, 2489, 10395, 13, 198, 2, 198, ...
1.746018
7,032
# -*- coding: utf-8 -*- """ fillRasterwithPatches.py *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Leandro Frana' __date__ = '2020-09-01' __copyright__ = '(C) 2020, Leandro Frana' from PyQt5.QtCore import QCoreApplication, QVariant from qgis.core import (QgsProcessing, QgsFeatureSink, QgsWkbTypes, QgsFields, QgsField, QgsFeature, QgsPointXY, QgsGeometry, QgsProcessingException, QgsProcessingAlgorithm, QgsProcessingParameterString, QgsProcessingParameterField, QgsProcessingParameterBoolean, QgsProcessingParameterCrs, QgsProcessingParameterEnum, QgsFeatureRequest, QgsExpression, QgsProcessingParameterFeatureSource, QgsProcessingParameterFeatureSink, QgsProcessingParameterFileDestination, QgsProcessingParameterMultipleLayers, QgsProcessingParameterRasterLayer, QgsProcessingParameterRasterDestination, QgsApplication, QgsProject, QgsRasterLayer, QgsCoordinateTransform, QgsCoordinateReferenceSystem) from osgeo import osr, gdal_array, gdal #https://gdal.org/python/ from math import floor, ceil import numpy as np from lftools.geocapt.dip import Interpolar from lftools.geocapt.imgs import Imgs import os from qgis.PyQt.QtGui import QIcon
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 20797, 49, 1603, 4480, 12130, 2052, 13, 9078, 198, 17174, 17174, 4557, 8162, 198, 9, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
1.865079
1,260
import matplotlib.patches as patches import matplotlib.pyplot as plt import numpy as np
[ 11748, 2603, 29487, 8019, 13, 8071, 2052, 355, 16082, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 628 ]
3.296296
27
from PyQt5.QtWidgets import QDialog from PyQt5.QtGui import QFont from PyQt5.QtCore import Qt from dockwina import Ui_Form as docka
[ 6738, 9485, 48, 83, 20, 13, 48, 83, 54, 312, 11407, 1330, 1195, 44204, 201, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 8205, 72, 1330, 1195, 23252, 201, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 14055, 1330, 33734, 201, 198, 6738, ...
2.344828
58
import bokeh.palettes
[ 11748, 1489, 365, 71, 13, 18596, 23014, 628 ]
2.875
8
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import os, sys, warnings parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_project.settings") import django from django.core.management import execute_from_command_line if django.VERSION < (1, 6): default_test_apps = [ 'sortedm2m_tests', 'test_south_support', ] else: default_test_apps = [ 'sortedm2m_tests', ] # Only test south support for Django 1.6 and lower. if django.VERSION < (1, 7): default_test_apps += [ 'test_south_support', ] if __name__ == '__main__': runtests(*sys.argv[1:])
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 11748, 28686, 11, 25064, 11, 14601, 628, 198, 8000, 79...
2.311728
324
#!/usr/bin/env python3 import concurrent.futures import logging import requests from sys import argv, exit from urllib.parse import urlparse logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) HEADERS = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.30 Safari/537.36' } MIN_RESPONSE_LENGTH = 100 NUM_WORKERS = 50 urls = [] if len(argv) < 2: exit("Please specify a URLs file.") with open(argv[1]) as f: urls = [line.rstrip() for line in f] with open('results.csv', 'w') as w: print('url,SAMEORIGIN_OK,CROSSORIGIN_OK,SAMEORIGIN_KO_STATUS,SAMEORIGIN_KO_RESPONSE,CROSSORIGIN_KO_STATUS,CROSSORIGIN_KO_RESPONSE', file=w) with concurrent.futures.ThreadPoolExecutor(max_workers=NUM_WORKERS) as executor: future_to_result = {executor.submit(check, url): url for url in urls} for future in concurrent.futures.as_completed(future_to_result): try: result = future.result() except: continue else: if result: print('{},{},{},{},{},{},{}'.format(result['url'], int(result['SAMEORIGIN_OK']), int(result['CROSSORIGIN_OK']), int(result['SAMEORIGIN_KO_STATUS']), int(result['SAMEORIGIN_KO_RESPONSE']), int(result['CROSSORIGIN_KO_STATUS']), int(result['CROSSORIGIN_KO_RESPONSE']) ), file=w)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 24580, 13, 69, 315, 942, 198, 11748, 18931, 198, 11748, 7007, 198, 6738, 25064, 1330, 1822, 85, 11, 8420, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 19016, 29572, 198, 198,...
1.748555
1,038
# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr> # License: BSD Style. import os import numpy if __name__ == "__main__": from numpy.distutils.core import setup setup(**configuration(top_path="").todict())
[ 2, 6434, 25, 21000, 260, 20159, 3319, 1279, 1000, 87, 49078, 13, 4546, 3319, 31, 259, 7496, 13, 8310, 29, 198, 2, 13789, 25, 347, 10305, 17738, 13, 198, 11748, 28686, 198, 198, 11748, 299, 32152, 628, 198, 198, 361, 11593, 3672, 834...
2.746988
83
#!/usr/bin/env python3 import sys from math import sqrt # (n * (n + 1)) / 2 -> n ** 2 + n - (2 * x) # Solved with quadratic equation # https://en.wikipedia.org/wiki/Quadratic_equation for _ in range(int(input().strip())): t = int(input().strip()) d = (sqrt(4 * 2 * t + 1) - 1) if d.is_integer(): print(int(d) // 2) else: print(-1)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 25064, 198, 6738, 10688, 1330, 19862, 17034, 628, 198, 2, 357, 77, 1635, 357, 77, 1343, 352, 4008, 1220, 362, 4613, 299, 12429, 362, 1343, 299, 532, 357, 17, 1635, 2124, 8...
2.208333
168
""" Copyright (c) 2017 Robbin Bouwmeester 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.""" __author__ = "Robbin Bouwmeester" __copyright__ = "Copyright 2017" __credits__ = ["Robbin Bouwmeester"] __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Robbin Bouwmeester" __email__ = "Robbin.bouwmeester@ugent.be" __status__ = "nightly funzies" import pandas as pd from itertools import groupby import logging if __name__ == "__main__": logging.basicConfig(filename="prec_filter.log", level=logging.DEBUG, filemode="w", format="%(levelname)s:%(created)f:%(asctime)s:%(message)s") logging.info("Reading the LPB database ...") lpb = LipidBLAST() logging.info("Done reading the LPB database ...") logging.info(lpb) step_three_df = pd.read_csv("stepone_new.csv") precf = Precursor_filter(lpb) prec_filt_result = [] for index,row in step_three_df.iterrows(): if (index % 10000==0): logging.info("Analyzing row number and m/z: %s - %s" % (index,row["mz"])) prec_hits = precf.retrieve_entry_pre_c_mass(row["mz"]) for hit in prec_hits: prec_filt_result.append([row["mz"],hit[2].mw,hit[1],hit[0].split("|")[0],hit[2].chem_form,hit[0].split("|")[1]]) prec_filt_result = pd.DataFrame(prec_filt_result) prec_filt_result.columns = ["Input Mass","Matched Mass","Delta","Abbreviation","Formula","Ion"] prec_filt_result.to_excel("batch_results.xlsx",index=False)
[ 37811, 198, 15069, 357, 66, 8, 2177, 3851, 8800, 14551, 86, 1326, 7834, 198, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 198, 16727, 257, 4866, 286, 428, 3788, 290, 3917, 10314, 198, 3696, 357, 1169, 366, ...
2.890229
829
from . import ( yaw, layout, base_COE, optimization, layout_height, power_density, yaw_wind_rose, power_density_1D, yaw_wind_rose_parallel, )
[ 6738, 764, 1330, 357, 198, 220, 220, 220, 331, 707, 11, 198, 220, 220, 220, 12461, 11, 198, 220, 220, 220, 2779, 62, 8220, 36, 11, 198, 220, 220, 220, 23989, 11, 198, 220, 220, 220, 12461, 62, 17015, 11, 198, 220, 220, 220, 1176...
2.045977
87
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License 2.0; # This module is used for version 2 of the Google Data APIs. """Provides classes and constants for the XML in the Google Spreadsheets API. Documentation for the raw XML which these classes represent can be found here: http://code.google.com/apis/spreadsheets/docs/3.0/reference.html#Elements """ # __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core import gdata.data GS_TEMPLATE = '{http://schemas.google.com/spreadsheets/2006}%s' GSX_NAMESPACE = 'http://schemas.google.com/spreadsheets/2006/extended' INSERT_MODE = 'insert' OVERWRITE_MODE = 'overwrite' WORKSHEETS_REL = 'http://schemas.google.com/spreadsheets/2006#worksheetsfeed' BATCH_POST_ID_TEMPLATE = ('https://spreadsheets.google.com/feeds/cells' '/%s/%s/private/full') BATCH_ENTRY_ID_TEMPLATE = '%s/R%sC%s' BATCH_EDIT_LINK_TEMPLATE = '%s/batch' def build_batch_cells_update(spreadsheet_key, worksheet_id): """Creates an empty cells feed for adding batch cell updates to. Call batch_set_cell on the resulting CellsFeed instance then send the batch request TODO: fill in Args: spreadsheet_key: The ID of the spreadsheet worksheet_id: """ feed_id_text = BATCH_POST_ID_TEMPLATE % (spreadsheet_key, worksheet_id) return CellsFeed( id=atom.data.Id(text=feed_id_text), link=[atom.data.Link( rel='edit', href=BATCH_EDIT_LINK_TEMPLATE % (feed_id_text,))]) BuildBatchCellsUpdate = build_batch_cells_update
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 15069, 357, 34, 8, 3717, 3012, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 362, 13, 15, 26, 628, 198, 198, 2, 770, 8265, 318, 973, 329, 2196, 362, 286, ...
2.573955
622
import unittest from pyjsg.validate_json import JSGPython if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 198, 6738, 12972, 8457, 70, 13, 12102, 378, 62, 17752, 1330, 26755, 16960, 7535, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, ...
2.534884
43
"""Define abstract base classes to construct FileFinder classes.""" import os import shutil from abc import ABC, abstractmethod from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Sequence, Union import mne_bids
[ 37811, 7469, 500, 12531, 2779, 6097, 284, 5678, 9220, 37, 5540, 6097, 526, 15931, 198, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 11, ...
3.880597
67
import glob import time from os import path from flask import Blueprint, jsonify, current_app, request, Response, json from flask_login import login_required from .. import pz_server_state from ..services.power_actions_service import is_valid_power_action, execute_action from ..services.server_options_service import read_config, save_config, prepared_config_to_view, formatted_config_lines from ..services.server_status_service import get_server_status from ..utils.resources_functions import server_resources server_blueprint = Blueprint('server', __name__, url_prefix='/server') def get_config(pz_server_config): config = read_config(pz_server_config) return { "WorkshopItems": config["WorkshopItems"], "Mods": config["Mods"] }
[ 11748, 15095, 198, 11748, 640, 198, 6738, 28686, 1330, 3108, 198, 198, 6738, 42903, 1330, 39932, 11, 33918, 1958, 11, 1459, 62, 1324, 11, 2581, 11, 18261, 11, 33918, 198, 6738, 42903, 62, 38235, 1330, 17594, 62, 35827, 198, 198, 6738, ...
3.299145
234
# ----------------------------------------------------------------------------- # Copyright (c) 2021 Trevor P. Martin. All rights reserved. # Distributed under the MIT License. # ----------------------------------------------------------------------------- from Data import encode_data # from utils import cross_validation from Models import utils from Models import build_models from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.linear_model import Perceptron from sklearn.svm import LinearSVC import matplotlib.pyplot as plt import matplotlib.font_manager as font_manager import numpy as np import pandas as pd import tensorflow as tf import copy def run(datasets, splice_sites, sub_models, save, vis, iter, metrics, summary, config, num_folds, bal, imbal, imbal_t, imbal_f, batch_size, epochs ): """ Parameters ---------- dataset: a string {nn269, ce, hs3d} indicating which dataset to use splice_site_type: a string {acceptor, donor} indicating which splice site to train on model_architecture: a string {cnn, dnn, rnn} indicating which model architecture to use for training save_model: boolean, whether to save the current model bal: boolean, whether to balance the dataset summary: boolean, whether to print out the model architecture summary config: boolean, whether to print out the model's configuration visualize: boolean, whether to save a performance graph of the model metrics: boolean, whether to print out the evaluation metrics for the model num_folds: int (default 10), the number of folds for k-fold cross validation epochs: int (default 15), the number of epochs for the chosen model batch_size: int (default 32), the model batch size model_iter: integer, the iteration of the current model architecture (e.g. if this is the third cnn architecture you are testing, use 3) """ # (acceptor row len, donor row len) by dataset network_rows = { 'acceptor':{ 'nn269':90, 'ce':141, 'hs3d':140, 'hs2':602, 'ce2':602, 'dm':602, 'ar':602, 'or':602, }, 'donor':{ 'nn269':15, 'ce':141, 'hs3d':140, 'hs2':602, 'ce2':602, 'dm':602, 'ar':602, 'or':602, }, } # initialize selected sub models to_run = dict( [ (sub_model,{ 'nn269':'', 'ce':'', 'hs3d':'', 'hs2':'', 'ce2':'', 'dm':'', 'ar':'', 'or':'' }) for sub_model in sub_models ] ) # results dictionary results = copy.deepcopy(to_run) # populate sub models with encoded data for sub_model in sub_models: for dataset in datasets: # encode datasets -> return (acc_x, acc_y, don_x, don_y) to_run[sub_model][dataset] = encode_data.encode(dataset, sub_model, bal) # get a metrics dictionary evals = dict( [ (sub_model, { 'f1':'', 'precision':'', 'sensitivity':'', 'specificity':'', 'recall':'', 'mcc':'', 'err_rate':'' }) for sub_model in sub_models ] ) # accumulate results from running cross validation for sub_model in sub_models: for dataset in datasets: if to_run[sub_model][dataset] == '': pass else: results[sub_model][dataset] = utils.cross_validation( num_folds, sub_model, splice_sites, dataset, to_run[sub_model][dataset],# encoded data for dataset (ds) network_rows, # donor, acceptor rows for ds evals, summary, config, batch_size, epochs, save, ) # if vis: print(results) return results # plot results # loss_acc_sub_models( # results, # datasets, # sub_models, # epochs, # num_folds, # bal # ) # # different by splice site type # if splice_site_type == 'acceptor': # cnn_X_train, cnn_y_train = cnn_acc_x, acc_y # # same name to preserve for loop structure # X_train, y_train = rd_acc_x, acc_y # dataset_row_num = network_rows[dataset][0] # if splice_site_type == 'donor': # cnn_X_train, cnn_y_train = cnn_don_x, don_y # X_train, y_train = rd_don_x, don_y # dataset_row_num = network_rows[dataset][1] # # # # if tune_rnn: # # tune_rnn() # # # perform cross validation # # general # trn_fold_accs, trn_fold_losses = [], [] # val_fold_accs, val_fold_losses = [], [] # # esplice # rnn_va, rnn_vl, cnn_vl, cnn_va, dnn_vl, dnn_va = [],[],[],[],[],[] # rnn_ta, rnn_tl, cnn_tl, cnn_ta, dnn_tl, dnn_ta = [],[],[],[],[],[] # # # this loop inspired by https://www.machinecurve.com/ # #index.php/2020/02/18/how-to-use-k-fold-cross-validation-with-keras/ # k_fold = KFold(n_splits=num_folds, shuffle=False) # fold = 1 # for train, test in k_fold.split(X_train, y_train): # if model_architecture != 'esplice': # X_trn, y_trn = X_train[train], y_train[train] # X_val, y_val = X_train[test], y_train[test] # if model_architecture=='cnn': # history, model = build_cnn( # dataset_row_num, # summary, # X_trn, # y_trn, # batch_size, # epochs, # X_val,#becomes X_val # y_val,#becomes y_val # fold, # num_folds # ) # if model_architecture=='dnn': # history, model = build_dnn( # dataset_row_num, # summary, # X_trn, # y_trn, # batch_size, # epochs, # X_val,#becomes X_val # y_val,#becomes y_val # fold, # num_folds # ) # if model_architecture=='rnn': # history, model = build_rnn( # dataset_row_num, # summary, # X_trn, # y_trn, # batch_size, # epochs, # X_val,#becomes X_val # y_val,#becomes y_val # fold, # num_folds # ) # # model.predict(X_trn) # val_fold_accs.append(history.history['val_accuracy']) # val_fold_losses.append(history.history['val_loss']) # trn_fold_accs.append(history.history['accuracy']) # trn_fold_losses.append(history.history['loss']) # fold += 1 # else: # # set up submodel datasets # cnn_X_trn, cnn_y_trn = cnn_X_train[train], cnn_y_train[train] # cnn_X_val, cnn_y_val = cnn_X_train[test], cnn_y_train[test] # rd_X_trn, rd_y_trn = X_train[train], y_train[train] # rd_X_val, rd_y_val = X_train[test], y_train[test] # # build each submodel # hist01, submodel_01 = build_cnn( # dataset_row_num, # summary, # cnn_X_trn, # cnn_y_trn, # batch_size, # epochs, # cnn_X_val, # cnn_y_val, # fold, # num_folds # ) # hist02, submodel_02 = build_dnn( # dataset_row_num, # summary, # rd_X_trn, # rd_y_trn, # batch_size, # epochs, # rd_X_val, # rd_y_val, # fold, # num_folds # ) # # hist03, submodel_03 = build_rnn( # # dataset_row_num, # # summary, # # rd_X_trn, # # rd_y_trn, # # batch_size, # # epochs, # # rd_X_val, # # rd_y_val, # # fold, # # num_folds # # ) # models = [submodel_01, submodel_02]#, submodel_03] # trn_scores, val_scores = EnsembleSplice.build( # models, # batch_size, # cnn_X_trn, # cnn_y_trn, # cnn_X_val, # cnn_y_val, # rd_X_trn, # rd_y_trn, # rd_X_val, # rd_y_val, # ) # # get final epoch accuracy # trn_fold_accs.append(trn_scores) # val_fold_accs.append(val_scores) # # rnn_va.append(hist03.history['val_accuracy']) # # rnn_vl.append(hist03.history['val_loss']) # # rnn_ta.append(hist03.history['accuracy']) # # rnn_tl.append(hist03.history['loss']) # # cnn_vl.append(hist01.history['val_loss']) # # cnn_va.append(hist01.history['val_accuracy']) # # cnn_tl.append(hist01.history['loss']) # # cnn_ta.append(hist01.history['accuracy']) # # dnn_vl.append(hist02.history['val_loss']) # # dnn_va.append(hist02.history['val_accuracy']) # # dnn_tl.append(hist02.history['loss']) # # dnn_ta.append(hist02.history['accuracy']) # # # rnn_va.append(hist03.history['val_accuracy'][-1]) # # rnn_vl.append(hist03.history['val_loss'][-1]) # # rnn_ta.append(hist03.history['accuracy'][-1]) # # rnn_tl.append(hist03.history['loss'][-1]) # cnn_vl.append(hist01.history['val_loss'][-1]) # cnn_va.append(hist01.history['val_accuracy'][-1]) # cnn_tl.append(hist01.history['loss'][-1]) # cnn_ta.append(hist01.history['accuracy'][-1]) # dnn_vl.append(hist02.history['val_loss'][-1]) # dnn_va.append(hist02.history['val_accuracy'][-1]) # dnn_tl.append(hist02.history['loss'][-1]) # dnn_ta.append(hist02.history['accuracy'][-1]) # # fold += 1 # # # do something with predicted values and real values to get AUC-ROC scores # # sklearn.metrics.roc_auc_score # # also get f-score and other scores here # # maybe connect tune_rnn and build_rnn -> get tuned parameters and plug them # # in automatically to RNN # # if model_architecture != 'esplice': # # val_acc_by_epoch = np.apply_along_axis(lambda row: np.mean(row), 1, np.asarray(val_fold_accs).T) # val_loss_by_epoch = np.apply_along_axis(lambda row: np.mean(row), 1, np.asarray(val_fold_losses).T) # trn_acc_by_epoch = np.apply_along_axis(lambda row: np.mean(row), 1, np.asarray(trn_fold_accs).T) # trn_loss_by_epoch = np.apply_along_axis(lambda row: np.mean(row), 1, np.asarray(trn_fold_losses).T) # # std_val_acc = np.apply_along_axis(lambda row: np.std(row), 1, np.asarray(val_fold_accs).T) # std_val_loss = np.apply_along_axis(lambda row: np.std(row), 1, np.asarray(val_fold_losses).T) # std_trn_acc = np.apply_along_axis(lambda row: np.std(row), 1, np.asarray(trn_fold_accs).T) # std_trn_loss = np.apply_along_axis(lambda row: np.std(row), 1, np.asarray(trn_fold_losses).T) # # values = [ # val_acc_by_epoch, # std_val_acc, # trn_acc_by_epoch, # std_trn_acc, # val_loss_by_epoch, # std_val_loss, # trn_loss_by_epoch, # std_trn_loss # ] # # if model_architecture == 'esplice': # # # make a DICTIONARY AREY # # ES_Val_ACc: (vacc, std_va) # mean_good = lambda seq: np.apply_along_axis(lambda row: np.mean(row), 1, np.asarray(seq).T) # std_good = lambda seq: np.apply_along_axis(lambda row: np.std(row), 1, np.asarray(seq).T) # vacc = val_fold_accs # tacc = trn_fold_accs # # std_va = val_fold_accs # # std_ta = trn_fold_accs # # values = [ # val_fold_accs, # trn_fold_accs, # #rnn_va, # # rnn_vl, # #rnn_ta, # # rnn_tl, # # cnn_vl, # cnn_va, # # cnn_tl, # cnn_ta, # # dnn_vl, # dnn_va, # # dnn_tl, # dnn_ta # ] # # # cnn_mva = mean_good(cnn_va) # # cnn_mvl = mean_good(cnn_vl) # # cnn_mta = mean_good(cnn_ta) # # cnn_mtl = mean_good(cnn_tl) # # cnn_sva = std_good(cnn_va) # # cnn_svl = std_good(cnn_vl) # # cnn_sta = std_good(cnn_ta) # # cnn_stl = std_good(cnn_tl) # # # # dnn_mva = mean_good(dnn_va) # # dnn_mvl = mean_good(dnn_vl) # # dnn_mta = mean_good(dnn_ta) # # dnn_mtl = mean_good(dnn_tl) # # dnn_sva = std_good(dnn_va) # # dnn_svl = std_good(dnn_vl) # # dnn_sta = std_good(dnn_ta) # # dnn_stl = std_good(dnn_tl) # # # # rnn_mva = mean_good(rnn_va) # # rnn_mvl = mean_good(rnn_vl) # # rnn_mta = mean_good(rnn_ta) # # rnn_mtl = mean_good(rnn_tl) # # rnn_sva = std_good(rnn_va) # # rnn_svl = std_good(rnn_vl) # # rnn_sta = std_good(rnn_ta) # # rnn_stl = std_good(rnn_tl) # # # values = [ # # vacc, # # # std_va, # # tacc, # # # std_ta, # # cnn_mva, # # cnn_sva, # # cnn_mvl, # # cnn_svl, # # cnn_mta, # # cnn_sta, # # cnn_mtl, # # cnn_stl, # # dnn_mva, # # dnn_sva, # # dnn_mvl, # # dnn_svl, # # dnn_mta, # # dnn_sta, # # dnn_mtl, # # dnn_stl, # # rnn_mva, # # rnn_sva, # # rnn_mvl, # # rnn_svl, # # rnn_mta, # # rnn_sta, # # rnn_mtl, # # rnn_stl, # # ] # if config: # print(model.get_config()) # if save_model: # name = input('What would you like to name this model?: ') # model.save(f'{name}') # tf.keras.utils.plot_model(model, f'{name}.png', show_shapes=True) # if visualize: # loss_acc_esplice( # values, # model_architecture, # dataset, # splice_site_type, # num_folds, # epochs, # bal, # )
[ 2, 16529, 32501, 198, 2, 15069, 357, 66, 8, 33448, 25389, 350, 13, 5780, 13, 1439, 2489, 10395, 13, 198, 2, 4307, 6169, 739, 262, 17168, 13789, 13, 198, 2, 16529, 32501, 198, 6738, 6060, 1330, 37773, 62, 7890, 198, 2, 422, 3384, 4...
1.750342
8,776
#! -*- coding: utf-8 -*- # # (C) 2013 Internet Initiative Japan Inc. # All rights reserved. # # Created on 2013/05/15 # @author: yosinobu@iij.ad.jp """Notify project owner with email when the project created successfully.""" from pkg_resources import resource_filename from trac.config import Option, ListOption from trac.core import Component, implements from trac.notification import Notify, NotifyEmail from trac.web.chrome import ITemplateProvider from tracportal.i18n import _ from tracportal.project.api import IProjectCreationInterceptor
[ 2, 0, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 357, 34, 8, 2211, 4455, 18362, 2869, 3457, 13, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 15622, 319, 2211, 14, 2713, 14, 1314, 198, 2, 2488, 9...
3.301205
166
#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import glob import os.path import sys DIR = os.path.dirname(os.path.abspath(__file__)) REPO = os.path.dirname(os.path.dirname(DIR)) SRC_DIR = os.path.join(REPO, "src") if __name__ == "__main__": main()
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 15095, 198, 11748, 28686, 13, 6978, 198, 11748, ...
2.365079
126
# Created by Egor Kostan. # GitHub: https://github.com/ikostan # LinkedIn: https://www.linkedin.com/in/egor-kostan/ def length(head) -> int: """ The method length, which accepts a linked list (head), and returns the length of the list. :param head: :return: """ i = 0 if head is None: return 0 while head.next is not None: head = head.next i += 1 return i + 1
[ 2, 220, 15622, 416, 412, 7053, 509, 455, 272, 13, 198, 2, 220, 21722, 25, 3740, 1378, 12567, 13, 785, 14, 1134, 455, 272, 198, 2, 220, 27133, 25, 3740, 1378, 2503, 13, 25614, 259, 13, 785, 14, 259, 14, 1533, 273, 12, 74, 455, ...
2.38674
181