content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import re from enum import Enum from typing import List import libkol from .request import Request furniture_pattern = re.compile(r"rump([0-9])_([0-9])\.gif")
[ 11748, 302, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 19720, 1330, 7343, 198, 198, 11748, 9195, 74, 349, 198, 198, 6738, 764, 25927, 1330, 19390, 628, 198, 198, 69, 700, 8089, 62, 33279, 796, 302, 13, 5589, 576, 7, 81, 1, 81, ...
2.79661
59
# -*- coding: utf-8 -*- # __author__:Song Zhenqi # 2021-01-20 import os import sys import yaml import logging import functools logger_initialized = set() def get_config(file): """ yaml :param file: yaml/yml :return: dict """ _, ext = os.path.splitext(file) assert ext in ['.yaml', '.yml'], "yaml/yml" config = yaml.load(open(file, 'rb'), Loader=yaml.Loader) return config
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 11593, 9800, 834, 25, 44241, 1168, 831, 40603, 198, 2, 33448, 12, 486, 12, 1238, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 331, 43695, 198, 11748, 18931,...
2.292818
181
from monitoring.uss_qualifier.test_data import test_report from monitoring.uss_qualifier.utils import USSQualifierTestConfiguration from monitoring.uss_qualifier.main import uss_test_executor from monitoring.uss_qualifier.rid.simulator import flight_state_from_kml from monitoring.uss_qualifier.rid.utils import FullFlightRecord from monitoring.uss_qualifier.rid.utils import FullFlightRecord import json from typing import List import redis import rq import uuid from . import resources from monitoring.monitorlib.typing import ImplicitDict def remove_rq_job(job_id): """Removes a job from the queue.""" try: rq_job = resources.qualifier_queue.remove(job_id) except (redis.exceptions.RedisError, rq.exceptions.NoSuchJobError): return None return rq_job
[ 6738, 9904, 13, 1046, 62, 13255, 7483, 13, 9288, 62, 7890, 1330, 1332, 62, 13116, 198, 6738, 9904, 13, 1046, 62, 13255, 7483, 13, 26791, 1330, 23116, 46181, 7483, 14402, 38149, 198, 6738, 9904, 13, 1046, 62, 13255, 7483, 13, 12417, 13...
3.151394
251
""" BasketManagementRelated modules """ # import basket models from basket.models import Basket from basket.models import BasketProductLine # import configuration models from grenades_services.all_configuration_data import get_currency_instance from grenades_services.all_configuration_data import get_customer_instance_from_request_user from grenades_services.all_configuration_data import product_price_calculator # import home modules from grenades_services.modules.home import Home # import serializers modules from grenades_services.separate_serializers.basket_serializers import \ BasketProductSerializer def collect_basket_product_values(self): """collect_basket_product_values This 'collect_basket_product_values' method used to collect the all basket related value data to entered in basket table with customer and session maintain instance """ home_instance = self._use_common_module(dict( product_get_data={ 'product_alias_name': self.basket_data['product_alias_name'] } ) ) product_instance = home_instance.get_product_instance() if product_instance: home_instance = self._use_common_module( dict(filter_input_data={'mapped_products__id__in': [product_instance.id]})) category_product_mapping_instance = \ home_instance.category_product_mapping_instance() home_instance = self._use_common_module( dict(filter_input_data={ 'included_products__id__in': [product_instance.id], 'offer_type': 'offer' }) ) product_offer_instance = home_instance.offer_products() payable_amount = self.calculate_offer_value( product_offer_instance, product_instance.price) if product_offer_instance else product_instance.price return (product_instance, category_product_mapping_instance, payable_amount) def collect_basket_details(self, basket_instance): """ This 'collect_basket_details' method collect the basket common code details """ product_instance, category_product_mapping_instance, payable_amount = \ self.collect_basket_product_values() return { 'basket': basket_instance, 'line_reference': str(product_instance.id), 'product': product_instance, 'category': category_product_mapping_instance.last( ).category if category_product_mapping_instance else None, 'quantity': self.basket_data.get('quantity', 1), 'price_currency': get_currency_instance(), 'price_excl_tax': None, 'price_incl_tax': None, 'payable_amount': payable_amount } def add_new_basket(self): """ This 'add_new_basket' method used to create a fresh basket for a customer or user """ if self.customer_instance: self.filter_query_data['owner'] = self.customer_instance create_basket = Basket.objects.create(**self.filter_query_data) print("63546735435463543564", create_basket) if create_basket: if self.create_basket_product_line(self.collect_basket_details(create_basket)): self._request.session['basket_id'] = create_basket.id return True return False def update_product_basket(self): """ This 'update_product_basket' method used to update the product in the basket """ if self.basket_id: self.filter_query_data['id'] = self.basket_id if self.customer_instance: self.filter_query_data['owner'] = self.customer_instance basket_instance = self.get_basket_instance() if basket_instance: if self.create_basket_product_line(self.collect_basket_details( basket_instance)): return True else: return False def add_to_basket(self): """ This 'add_to_basket' method used to add the product in the basket """ self.customer_instance = get_customer_instance_from_request_user( self._request.user) if 'basket_id' in self._request.session.keys(): self.basket_id = self._request.session['basket_id'] return self.update_product_basket() else: return self.add_new_basket() class DisplayProductsBasket(UpdateProductsBasket): """ DisplayProductsBasket return: { 'products_description': { 'id': 14, 'products_list': [], 'line_reference': '2', 'quantity': 1, 'price_currency': 'INR', 'price_excl_tax': None, 'price_incl_tax': None, 'payable_amount': '1000.00', 'date_created': '2021-11-01T10:29:50.091484Z', 'date_updated': '2021-11-01T10:29:50.091502Z', 'basket': 5, 'product': 2, 'category': 5, 'collection': None }, 'product_price_details': {'total_item': 0}, 'random_products_list': <QuerySet [<Product: Instruments>]> } """ def basket_product_description(self): """basket_product_description This 'basket_product_description' method used to get the all product description with all products details from baskets """ if self.basket_id: self.filter_data['id'] = self.basket_id if self.customer_instance: self.filter_data['owner'] = self.customer_instance basket_instance = self.get_basket_instance(self.filter_data) if basket_instance: product_line_last_obj = self.get_basket_product_lines( {'basket': basket_instance}).last() self.products_description_data = BasketProductSerializer( product_line_last_obj).data def create_product_order_summary_dict(self, order_summary_dict): """ This 'create_product_order_summary_dict' method used to create dict for product order summary total_price, coupon_price, offer_price """ self.product_price_details['total'] = order_summary_dict['total_price'] self.product_price_details['sub_total'] = order_summary_dict['total_price'] self.product_price_details['estimate_tax'] = self.estimate_tax self.product_price_details['coupon_name'] = self.coupon_name self.product_price_details['coupon_price'] = order_summary_dict['coupon_price'] self.product_price_details['offer_name'] = self.offer_name self.product_price_details['offer_price'] = order_summary_dict['offer_price'] def order_product_price_details(self): """order_product_price_details This 'order_product_price_details' method used to get the all product order summary with price calculation and manage the all coupon and offers """ self.product_price_details['total_item'] = len( self.products_description_data['products_list']) for _products_details in self.products_description_data['products_list']: order_summary_dict = product_price_calculator(_products_details, self.coupon_details, self.offer_details) # create product order summary # return total_price, coupon_price, offer_price self.create_product_order_summary_dict(order_summary_dict) def display_products(self): """ This 'display_products' method used to get the all session and customer related basket products for help on display """ if 'basket_id' in self._request.session.keys(): self.basket_id = self._request.session.get('basket_id') else: self.basket_id = None self.customer_instance = get_customer_instance_from_request_user( self._request.user) self.basket_product_description() self.order_product_price_details() home_instance = Home() random_products_list = home_instance.random_products_list() return { 'products_description': self.products_description_data, 'product_price_details': self.product_price_details, 'random_products_list': random_products_list if random_products_list else [] }
[ 37811, 198, 33, 11715, 48032, 9819, 13103, 198, 37811, 198, 2, 1330, 7988, 4981, 198, 6738, 7988, 13, 27530, 1330, 347, 11715, 198, 6738, 7988, 13, 27530, 1330, 347, 11715, 15667, 13949, 198, 198, 2, 1330, 8398, 4981, 198, 6738, 28850, ...
2.300906
3,752
import numpy as np import matplotlib.pyplot as plt acc = np.array([7.95549917, 7.46641684, 8.16141701, 8.80025005, 7.29208231, 7.73391724, 8.16333294, 9.02033329, 7.60566664, 7.88175011, 7.77574968, 8.79116631, 8.24524975, 8.98549938, 7.3717494 , 7.32324982, 8.14583302, 8.53608322, 9.30125046, 8.53458309, 8.01708317, 8.36941624, 8.23241711, 8.93550014, 8.73683262, 8.05008316, 8.68758297, 8.59083271, 9.0852499 , 9.07924938, 7.3904171 , 8.82283497, 9.41650009, 8.45791626, 8.04416656, 7.70391607, 9.05191612, 7.78883314, 8.56858349, 9.07366657, 8.77991581, 7.94008255, 8.1746664 , 8.28074932, 7.91550064, 7.4872508 , 8.59158325, 9.33758259, 8.21591663, 8.64350033, 9.00899982, 9.26983356, 8.7885828 , 9.43066692, 9.09299946, 8.55266666, 8.73725033, 7.50575018, 7.99300003, 8.16366673, 8.97633266, 8.19683361, 7.71091652, 8.65974998, 8.97108364, 8.03375053, 8.99700069, 9.18599987, 8.26491737, 8.64508343, 8.00825024, 7.80483294, 7.45008326, 8.23791695, 8.90425014, 9.47108269, 8.0963335 , 8.88658333, 7.99116659, 7.48541689, 8.23633289, 8.61583424, 7.75775003, 8.10883331, 8.57058334, 7.72616577, 7.29199982, 8.26725006, 7.80841637, 8.8257494 , 9.35824871, 8.85208321, 7.50433302, 8.03266716, 8.77825069, 8.94516659, 8.56558323, 8.64266682, 8.70541668, 8.4321661 ]) spd = np.array([-15.733922 , -17.69332123, -15.09789562, -14.98722076, -19.22259712, -20.7837429 , -19.90324211, -13.48655987, -13.42676544, -10.76375103, -18.15335083, -9.28313065, -11.35249805, -12.09126663, -13.63445187, -17.17600822, -11.39536953, -13.01688385, -14.5902586 , -9.40825558, -11.72452641, -9.74875546, -15.47906494, -17.58286476, -13.81764889, -15.5894928 , -9.33745289, -11.58790493, -12.6633606 , -12.95300007, -6.5169816 , -15.54349899, -9.18311691, -11.59814739, -11.74293232, -18.68121147, -12.44590282, -13.20860291, -8.75187683, -23.9044342 , -10.90840054, -11.39770985, -14.83057499, -13.2543335 , -13.18600559, -13.31662369, -12.91320515, -9.9495573 , -10.87206936, -11.35480595, -13.06026745, -10.52530384, -13.57276917, -13.95710754, -9.0244627 , -12.21132755, -9.00012493, -9.07794476, -12.50325108, -9.44294643, -12.86182499, -8.95974827, -10.34585476, -16.70100594, -7.63287163, -11.60797215, -11.73308086, -10.89833736, -11.40105438, -8.59499645, -11.1452837 , -11.61797333, -9.25040531, -9.30110741, -8.68466759, -10.68533611, -11.68466282, -10.05351353, -11.61765003, -9.72268772, -9.05587578, -10.88561535, -11.85619068, -12.46191692, -8.43530369, -6.79801893, -9.91088772, -9.89115238, -16.34910393, -12.32227421, -13.36759472, -17.33267021, -10.66337585, -10.35019398, -11.29328632, -9.45415211, -10.61021137, -14.06766415, -8.31783295, -11.77228069])
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 628, 198, 4134, 796, 45941, 13, 18747, 26933, 22, 13, 24, 2816, 28324, 1558, 11, 220, 767, 13, 3510, 2414, 1433, 5705, 11, 220, 807, 13, 14...
1.725456
1,701
""" BPF-related stuff. """
[ 37811, 198, 20866, 37, 12, 5363, 3404, 13, 198, 37811, 198 ]
2.454545
11
import os import json import geojson import mappyfile_geojson import mappyfile import pytest def test_pointZ(): """ Z-values are simply removed as they are not supported by inline MapServer Features """ gj = get_geojson("PointZ.json") layer = mappyfile_geojson.convert(gj) s = mappyfile.dumps(layer) print(s) assert s == """LAYER EXTENT 102 0.5 102 0.5 STATUS ON TYPE POINT PROCESSING "ITEMS=prop0" FEATURE POINTS 102.0 0.5 END ITEMS "value0" END END""" if __name__ == '__main__': # test_multipolygon() run_tests() print("Done!")
[ 11748, 28686, 201, 198, 11748, 33918, 201, 198, 11748, 4903, 13210, 1559, 201, 198, 11748, 285, 7774, 7753, 62, 469, 13210, 1559, 201, 198, 11748, 285, 7774, 7753, 201, 198, 11748, 12972, 9288, 201, 198, 201, 198, 201, 198, 201, 198, ...
2.035714
336
''' @Author: Hata @Date: 2020-05-24 15:30:19 @LastEditors: Hata @LastEditTime: 2020-05-24 15:32:04 @FilePath: \LeetCode\230.py @Description: https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/ '''
[ 7061, 6, 198, 31, 13838, 25, 367, 1045, 198, 31, 10430, 25, 12131, 12, 2713, 12, 1731, 1315, 25, 1270, 25, 1129, 198, 31, 5956, 18378, 669, 25, 367, 1045, 198, 31, 5956, 18378, 7575, 25, 12131, 12, 2713, 12, 1731, 1315, 25, 2624, ...
2.210526
95
# ---------------------------------------------------------------------- # | # | PythonUnittestTestParser.py # | # | David Brownell <db@DavidBrownell.com> # | 2018-05-22 07:59:46 # | # ---------------------------------------------------------------------- # | # | Copyright David Brownell 2018-22. # | Distributed under the Boost Software License, Version 1.0. # | (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # | # ---------------------------------------------------------------------- """Contains the TestParser object""" import os import re import CommonEnvironment from CommonEnvironment.Interface import staticderived, override, DerivedProperty from CommonEnvironment.TestParserImpl import TestParserImpl # ---------------------------------------------------------------------- _script_fullpath = CommonEnvironment.ThisFullpath() _script_dir, _script_name = os.path.split(_script_fullpath) # ---------------------------------------------------------------------- # ----------------------------------------------------------------------
[ 2, 16529, 23031, 201, 198, 2, 930, 201, 198, 2, 930, 220, 11361, 3118, 715, 395, 14402, 46677, 13, 9078, 201, 198, 2, 930, 201, 198, 2, 930, 220, 3271, 4373, 695, 1279, 9945, 31, 11006, 20644, 695, 13, 785, 29, 201, 198, 2, 930,...
4.236842
266
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os from typing import Any, Dict from fairseq import checkpoint_utils from fairseq.data.legacy.masked_lm_dictionary import MaskedLMDictionary from fairseq.models import register_model, register_model_architecture from fairseq.models.transformer import ( TransformerDecoder, TransformerEncoder, TransformerModel, base_architecture as transformer_base_architecture, ) def upgrade_state_dict_with_xlm_weights( state_dict: Dict[str, Any], pretrained_xlm_checkpoint: str ) -> Dict[str, Any]: """ Load XLM weights into a Transformer encoder or decoder model. Args: state_dict: state dict for either TransformerEncoder or TransformerDecoder pretrained_xlm_checkpoint: checkpoint to load XLM weights from Raises: AssertionError: If architecture (num layers, attention heads, etc.) does not match between the current Transformer encoder or decoder and the pretrained_xlm_checkpoint """ if not os.path.exists(pretrained_xlm_checkpoint): raise IOError( "Model file not found: {}".format(pretrained_xlm_checkpoint)) state = checkpoint_utils.load_checkpoint_to_cpu(pretrained_xlm_checkpoint) xlm_state_dict = state["model"] for key in xlm_state_dict.keys(): for search_key in ["embed_tokens", "embed_positions", "layers"]: if search_key in key: subkey = key[key.find(search_key):] if "in_proj_weight" in subkey or \ "in_proj_bias" in subkey: continue else: assert subkey in state_dict, ( "{} \nTransformer encoder / decoder " "state_dict does not contain {}. \nCannot " "load {} from pretrained XLM checkpoint " "{} into Transformer.".format( str(state_dict.keys()), subkey, key, pretrained_xlm_checkpoint ) ) state_dict[subkey] = xlm_state_dict[key] return state_dict # class TransformerDecoderFromPretrainedXLM(TransformerDecoder): # def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False): # super().__init__(args, dictionary, embed_tokens, no_encoder_attn) # if getattr(args, "init_encoder_only", False): # # Don't load XLM weights for decoder if --init-encoder-only # return # assert hasattr(args, "pretrained_xlm_checkpoint"), ( # "--pretrained-xlm-checkpoint must be specified to load Transformer " # "decoder from pretrained XLM" # ) # # xlm_loaded_state_dict = upgrade_state_dict_with_xlm_weights( # state_dict=self.state_dict(), # pretrained_xlm_checkpoint=args.pretrained_xlm_checkpoint, # ) # self.load_state_dict(xlm_loaded_state_dict, strict=True)
[ 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 198, 2, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 17168, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287, 262, 6808, 8619, 286, 428, 2723, 5509, 13, 198, ...
2.201936
1,446
#!/usr/bin/python # Classification (U) """Program: process_request.py Description: Unit testing of process_request in mysql_db_admin.py. Usage: test/unit/mysql_db_admin/process_request.py Arguments: """ # Libraries and Global Variables # Standard import sys import os if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest # Third-party import mock # Local sys.path.append(os.getcwd()) import mysql_db_admin import lib.gen_libs as gen_libs import version __version__ = version.__version__ def func_holder(server, dbs, tbl): """Method: func_holder Description: Function stub holder for a generic function call. Arguments: server dbs tbl """ status = True if server and dbs and tbl: status = True return status if __name__ == "__main__": unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 40984, 357, 52, 8, 198, 198, 37811, 15167, 25, 220, 1429, 62, 25927, 13, 9078, 628, 220, 220, 220, 12489, 25, 220, 11801, 4856, 286, 1429, 62, 25927, 287, 48761, 62, 9945, 62, 28482, 1...
2.595376
346
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ FST test -- test your Foma finite-state transducers! """ from .__version__ import VERSION as __version__ from ._fst import FST from ._results import FailedTestResult, PassedTestResult, TestResults from ._run import execute_test_case, run_tests from ._test_case import TestCase from .exceptions import FSTTestError, TestCaseDefinitionError __all__ = [ "FST", "FSTTestError", "FailedTestResult", "PassedTestResult", "TestCase", "TestCaseDefinitionError", "TestResults", "execute_test_case", "run_tests", ]
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 37, 2257, 1332, 1377, 1332, 534, 376, 6086, 27454, 12, 5219, 1007, 41213, 0, 198, 37811, 198, 198, ...
2.815166
211
import copy import numpy as np import torch from scipy import optimize import logging def sharpness(model, criterion_fn, A, epsilon=1e-3, p=0, bounds=None): """Computes sharpness metric according to https://arxiv.org/abs/1609.04836. Args: model: Model on which to compute sharpness criterion_fn: Function that takes in a model and returns the loss value and gradients on the appropriate data that will be used in the loss maximization done in the sharpness calculation. A: Projection matrix that defines the subspace in which the loss maximization will be done. If A=1, no projection will be done. epsilon: Defines the size of the neighborhood that will be used in the loss maximization. p: The dimension of the random projection subspace in which maximization will be done. If 0, assumed to be the full parameter space. """ run_fn = create_run_model(model, A, criterion_fn) if bounds is None: bounds = compute_bounds(model, A, epsilon) dim = flatten_parameters(model).shape[0] if p == 0 else p # Find the maximum loss in the neighborhood of the minima y = optimize.minimize( lambda x: run_fn(x), np.zeros(dim), method="L-BFGS-B", bounds=bounds, jac=True, options={"maxiter": 10}, ).x.astype(np.float32) model_copy = copy.deepcopy(model) if A is 1: flat_diffs = y else: flat_diffs = A @ y apply_diffs(model_copy, flat_diffs) maximum = criterion_fn(model_copy)["loss"] loss_value = criterion_fn(model)["loss"] sharpness = 100 * (maximum - loss_value) / (1 + loss_value) return sharpness def flatten_parameters(model): """Returns a flattened numpy array with the parameters of the model.""" return np.concatenate( [ param.detach().cpu().numpy().flatten() for param in model.parameters() if param.requires_grad ] ) def compute_bounds(model, A, epsilon): """Computes the bounds in which to search for the maximum loss.""" x = flatten_parameters(model) if A is 1: bounds = epsilon * (np.abs(x) + 1) else: b, _, _, _ = np.linalg.lstsq(A, x) bounds = epsilon * (np.abs(b) + 1) return optimize.Bounds(-bounds, bounds) def create_run_model(model, A, criterion_fn): """Creates a run function that takes in parameters in the subspace that loss maximization takes place in, and computes the loss and gradients corresponding to those parameters. """ return run def apply_diffs(model, diffs): """Adds deltas to the parameters in the model corresponding to diffs.""" parameters = model.parameters() idx = 0 for parameter in parameters: if parameter.requires_grad: n_elements = parameter.nelement() cur_diff = diffs[idx : idx + n_elements] parameter.data = parameter.data + torch.tensor( cur_diff.reshape(parameter.shape) ).to(device=parameter.device) idx += n_elements
[ 11748, 4866, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 629, 541, 88, 1330, 27183, 198, 11748, 18931, 628, 198, 4299, 7786, 1108, 7, 19849, 11, 34054, 62, 22184, 11, 317, 11, 304, 862, 33576, 28, 16, 68, ...
2.49166
1,259
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Standalone benchmark runner """ import cProfile import pstats import profile import numpy as np print("Running Rust + Cython benchmarks") # calibrate pr = profile.Profile() calibration = np.mean([pr.calibrate(100000) for x in xrange(5)]) # add the bias profile.Profile.bias = calibration cProfile.run(open('simplification/test/cprofile_rust_cython.py', 'rb'), 'simplification/test/output_stats_rust_cython') rust_cython = pstats.Stats('simplification/test/output_stats_rust_cython') cProfile.run(open('simplification/test/cprofile_rust_cython_complex.py', 'rb'), 'simplification/test/output_stats_rust_cython_complex') rust_cython_c = pstats.Stats('simplification/test/output_stats_rust_cython_complex') cProfile.run(open('simplification/test/cprofile_rust_cython_shapely.py', 'rb'), 'simplification/test/output_stats_rust_cython_shapely') shapely = pstats.Stats('simplification/test/output_stats_rust_cython_shapely') print("Rust Cython Benchmarks\n") rust_cython.sort_stats('cumulative').print_stats(5) rust_cython_c.sort_stats('cumulative').print_stats(5) shapely.sort_stats('cumulative').print_stats(5)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 1273, 7642, 505, 18335, 17490, 198, 37811, 198, 198, 11748, 269, 37046, 198, 11748, 279, 34242, 198, 11748, ...
2.758294
422
import time from random import randint random_list = random_int(100000) #list2 = [0,0,99,34,56,54,-1,-1,32,2.5,-1.1,1000,1000,-2,30,21,24,15,10,6] t1 = time.time() Quick_sort(random_list) t2 = time.time() print(t2-t1) # def Quick_Sort(list1): # if (list1[0]<list1[-1]): # partition_index =partition(list1) # quicksort(list1,) # quicksort()
[ 11748, 640, 198, 6738, 4738, 1330, 43720, 600, 628, 198, 25120, 62, 4868, 796, 4738, 62, 600, 7, 3064, 830, 8, 198, 2, 4868, 17, 796, 685, 15, 11, 15, 11, 2079, 11, 2682, 11, 3980, 11, 4051, 12095, 16, 12095, 16, 11, 2624, 11, ...
1.968254
189
#REST from rest_framework import viewsets,mixins from rest_framework.permissions import IsAuthenticated #Filters from rest_framework.filters import SearchFilter,OrderingFilter from django_filters.rest_framework import DjangoFilterBackend #Models, serializers from cride.circles.models import Circle,Membership from cride.circles.serializers import CircleModelSerializer #Permission from cride.circles.permissions import IsCircleAdmin
[ 2, 49, 6465, 198, 6738, 1334, 62, 30604, 1330, 5009, 1039, 11, 19816, 1040, 198, 6738, 1334, 62, 30604, 13, 525, 8481, 1330, 1148, 47649, 3474, 198, 198, 2, 11928, 1010, 198, 6738, 1334, 62, 30604, 13, 10379, 1010, 1330, 11140, 22417,...
3.57377
122
from adminweb.services import cep_service from adminweb.models import Profissional from rest_framework import serializers import json
[ 6738, 13169, 12384, 13, 30416, 1330, 269, 538, 62, 15271, 198, 6738, 13169, 12384, 13, 27530, 1330, 4415, 1480, 282, 198, 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 11748, 33918, 628, 198 ]
4.121212
33
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait import shutil import os domain_competitors = GoogleKeywordScreenshooter("buy domain", "screenshots") domain_competitors.start() domain_competitors.finish() domain_competitors.tozipfile() # python_competitors = GoogleKeywordScreenshooter("python book", "screenshots") # python_competitors.start() # python_competitors.finish()
[ 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 11321, 13, 13083, 1330, 26363, 198, 6738, 384, 11925, 1505, 13, 12384, 26230, 13, 11321, 13, 1525, 1330, 2750, 198, 6738, 384, 11925, 1505, 13...
3.300578
173
"""Extension function related to numpy """ from __future__ import annotations from typing import List, Tuple import numpy as np import pandas from numpy.typing import ArrayLike def dict_to_numpy_array(d: dict, dtype: List[Tuple]) -> np.array: """convert dictionary to numpy array Examples: >>> d = {"aaron": 5, "jack": 6} >>> dtype = [("name", "S8"), ("score", "<i4")] >>> dict_to_numpy_array(d, dtype) array([(b'aaron', 5), (b'jack', 6)], dtype=[('name', 'S8'), ('score', '<i4')]) Args: d (dict): [description] dtype (List[Tuple]): [description] Returns: np.array: [description] """ return np.fromiter(d.items(), dtype=dtype, count=len(d)) def dataframe_to_structured_array( df: pandas.DataFrame, dtypes: List[Tuple] = None ) -> ArrayLike: """convert dataframe (with all columns, and index possibly) to numpy structured arrays `len(dtypes)` should be either equal to `len(df.columns)` or `len(df.columns) + 1`. In the later case, it implies to include `df.index` into converted array. Args: df: the one needs to be converted dtypes: Defaults to None. If it's `None`, then dtypes of `df` is used, in such case, the `index` of `df` will not be converted. Returns: ArrayLike: [description] """ v = df if dtypes is not None: dtypes_in_dict = {key: value for key, value in dtypes} col_len = len(df.columns) if len(dtypes) == col_len + 1: v = df.reset_index() rename_index_to = set(dtypes_in_dict.keys()).difference(set(df.columns)) v.rename(columns={"index": list(rename_index_to)[0]}, inplace=True) elif col_len != len(dtypes): raise ValueError( f"length of dtypes should be either {col_len} or {col_len + 1}, is {len(dtypes)}" ) # re-arrange order of dtypes, in order to align with df.columns dtypes = [] for name in v.columns: dtypes.append((name, dtypes_in_dict[name])) else: dtypes = df.dtypes return np.array(np.rec.fromrecords(v.values), dtype=dtypes) def find_runs(x): """Find runs of consecutive items in an array.""" # ensure array x = np.asanyarray(x) if x.ndim != 1: raise ValueError("only 1D array supported") n = x.shape[0] # handle empty array if n == 0: return np.array([]), np.array([]), np.array([]) else: # find run starts loc_run_start = np.empty(n, dtype=bool) loc_run_start[0] = True np.not_equal(x[:-1], x[1:], out=loc_run_start[1:]) run_starts = np.nonzero(loc_run_start)[0] # find run values run_values = x[loc_run_start] # find run lengths run_lengths = np.diff(np.append(run_starts, n)) return run_values, run_starts, run_lengths def count_between(arr, start, end): """`start``end` arr Examples: >>> arr = [20050104, 20050105, 20050106, 20050107, 20050110, 20050111] >>> count_between(arr, 20050104, 20050111) 6 >>> count_between(arr, 20050104, 20050109) 4 """ pos_start = np.searchsorted(arr, start, side="right") pos_end = np.searchsorted(arr, end, side="right") counter = pos_end - pos_start + 1 if start < arr[0]: counter -= 1 if end > arr[-1]: counter -= 1 return counter def shift(arr, start, offset): """numpyarrstart(offset `arr``offset``offset` Examples: >>> arr = [20050104, 20050105, 20050106, 20050107, 20050110, 20050111] >>> shift(arr, 20050104, 1) 20050105 >>> shift(arr, 20050105, -1) 20050104 >>> # shift >>> shift(arr, 20050120, 1) 20050120 Args: arr : start : numpy offset (int): [description] Returns: """ pos = np.searchsorted(arr, start, side="right") if pos + offset - 1 >= len(arr): return start else: return arr[pos + offset - 1] def floor(arr, item): """ arritemitemarrarr[0];item arrarr[-1] `minute_frames_floor`. Examples: >>> a = [3, 6, 9] >>> floor(a, -1) 3 >>> floor(a, 9) 9 >>> floor(a, 10) 9 >>> floor(a, 4) 3 >>> floor(a,10) 9 Args: arr: item: Returns: """ if item < arr[0]: return arr[0] index = np.searchsorted(arr, item, side="right") return arr[index - 1] def join_by_left(key, r1, r2, mask=True): """ `r1`, `r2` by `key` `r1``r2``r2``fill` same as numpy.lib.recfunctions.join_by(key, r1, r2, jointype='leftouter'), but allows r1 have duplicat keys [Reference: stackoverflow](https://stackoverflow.com/a/53261882/13395693) Examples: >>> # to join the following >>> # [[ 1, 2], >>> # [ 1, 3], x [[1, 5], >>> # [ 2, 3]] [4, 7]] >>> # only first two rows in left will be joined >>> r1 = np.array([(1, 2), (1,3), (2,3)], dtype=[('seq', 'i4'), ('score', 'i4')]) >>> r2 = np.array([(1, 5), (4,7)], dtype=[('seq', 'i4'), ('age', 'i4')]) >>> joined = join_by_left('seq', r1, r2) >>> print(joined) [(1, 2, 5) (1, 3, 5) (2, 3, --)] >>> print(joined.dtype) (numpy.record, [('seq', '<i4'), ('score', '<i4'), ('age', '<i4')]) >>> joined[2][2] masked >>> joined.tolist()[2][2] == None True Args: key : join r1 : 1 r2 : 2 fill : cell Returns: a numpy array """ # figure out the dtype of the result array descr1 = r1.dtype.descr descr2 = [d for d in r2.dtype.descr if d[0] not in r1.dtype.names] descrm = descr1 + descr2 # figure out the fields we'll need from each array f1 = [d[0] for d in descr1] f2 = [d[0] for d in descr2] # cache the number of columns in f1 ncol1 = len(f1) # get a dict of the rows of r2 grouped by key rows2 = {} for row2 in r2: rows2.setdefault(row2[key], []).append(row2) # figure out how many rows will be in the result nrowm = 0 for k1 in r1[key]: if k1 in rows2: nrowm += len(rows2[k1]) else: nrowm += 1 # allocate the return array # ret = np.full((nrowm, ), fill, dtype=descrm) _ret = np.recarray(nrowm, dtype=descrm) if mask: ret = np.ma.array(_ret, mask=True) else: ret = _ret # merge the data into the return array i = 0 for row1 in r1: if row1[key] in rows2: for row2 in rows2[row1[key]]: ret[i] = tuple(row1[f1]) + tuple(row2[f2]) i += 1 else: for j in range(ncol1): ret[i][j] = row1[j] i += 1 return ret def numpy_append_fields(base, names, data, dtypes): """`base` `numpy.lib.recfunctions.rec_append_fields``rec_append_fields` `data`Object Example: >>> # >>> import numpy >>> old = np.array([i for i in range(3)], dtype=[('col1', '<f4')]) >>> new_list = [2 * i for i in range(3)] >>> res = numpy_append_fields(old, 'new_col', new_list, [('new_col', '<f4')]) >>> print(res) ... # doctest: +NORMALIZE_WHITESPACE [(0., 0.) (1., 2.) (2., 4.)] >>> # >>> data = [res['col1'].tolist(), res['new_col'].tolist()] >>> print(numpy_append_fields(old, ('col3', 'col4'), data, [('col3', '<f4'), ('col4', '<f4')])) ... # doctest: +NORMALIZE_WHITESPACE [(0., 0., 0.) (1., 1., 2.) (2., 2., 4.)] Args: base ([numpy.array]): name ([type]): data (list): list dtypes ([type]): dtype """ if isinstance(names, str): names = [ names, ] data = [ data, ] result = np.empty(base.shape, dtype=base.dtype.descr + dtypes) for col in base.dtype.names: result[col] = base[col] for i in range(len(names)): result[names[i]] = data[i] return result def ffill_na(s: np.array) -> np.array: """np.NaN snp.NaNnp.NaN Examples: >>> arr = np.arange(6, dtype=np.float32) >>> arr[3:5] = np.NaN >>> ffill_na(arr) ... # doctest: +NORMALIZE_WHITESPACE array([0., 1., 2., 2., 2., 5.], dtype=float32) >>> arr[0:2] = np.nan >>> ffill_na(arr) ... # doctest: +NORMALIZE_WHITESPACE array([nan, nan, 2., 2., 2., 5.], dtype=float32) Args: s (np.array): [description] Returns: np.array: [description] """ mask = np.isnan(s) idx = np.where(~mask, np.arange(len(mask)), 0) np.maximum.accumulate(idx, out=idx) return s[idx]
[ 37811, 11627, 3004, 2163, 3519, 284, 299, 32152, 198, 37811, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 19720, 1330, 7343, 11, 309, 29291, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 198, 6738, 299, ...
2.04286
4,363
from datetime import date from typing import List from attr import attrs, attrib
[ 6738, 4818, 8079, 1330, 3128, 198, 6738, 19720, 1330, 7343, 198, 198, 6738, 708, 81, 1330, 708, 3808, 11, 708, 822, 628, 628 ]
3.695652
23
""" This script computes word masks based on sentiment lexicons """ import os import torch import argparse from tqdm import tqdm from transformers import AutoTokenizer from transformers import GlueDataTrainingArguments as DataTrainingArguments from transformers import GlueDataset as Dataset parser = argparse.ArgumentParser() parser.add_argument("--data-dir", type=str, default="./data/SST-2", help="path to the dir containing lm data.") parser.add_argument("--lexicon-dir", type=str, default="./data/sentiment_lexicon", help="path to the dir containing sentiment lexicon.") parser.add_argument("--tokenizer-name", type=str, default="bert-base-uncased", help="name of the tokenizer to use.") parser.add_argument("--block_size", type=int, default=72, help="maximum length of the mask") args = parser.parse_args() positive_words = set() with open(os.path.join(args.lexicon_dir, "positive-words.txt"), "r", encoding="ISO-8859-1") as f: for line in f: line = line.strip() # skip the initial comments with ; and empty lines if not line.startswith(";") and len(line) > 0: positive_words.add(line.lower()) negative_words = set() with open(os.path.join(args.lexicon_dir, "negative-words.txt"), "r", encoding="ISO-8859-1") as f: for line in f: line = line.strip() # skip the initial comments with ; and empty lines if not line.startswith(";") and len(line) > 0: negative_words.add(line.lower()) salient_words = positive_words | negative_words tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name) splits = ["train", "dev", "test"] for split in splits: with open(os.path.join(args.data_dir, f"{split}.lm"), "r") as f: all_sens = [s.strip() for s in f.readlines()] salient_word_masks = torch.zeros(len(all_sens), args.block_size, dtype=torch.bool) total_word_count = 0 salient_word_count = 0 # Main loop that handles subword tokenization for i, sen in tqdm(enumerate(all_sens), total=len(all_sens)): words = sen.split() curr_idx = 1 # skip the [CLS] token total_word_count += len(words) for word in words: tokens = tokenizer.tokenize(word) # Need to truncate SQuAD if curr_idx + len(tokens) > args.block_size: raise ValueError("Encountered examples longer than block size.") if word in salient_words: salient_word_count += 1 for j in range(len(tokens)): salient_word_masks[i, curr_idx + j] = 1 curr_idx += len(tokens) print(f"{(salient_word_count/total_word_count):.2%} salient words") salient_pct = salient_word_masks.any(dim=1).sum().float() / len(all_sens) print(f"{split} {salient_pct:.2%} documents have salient words") torch.save( salient_word_masks, os.path.join( args.data_dir, f"cached_{split}_{args.tokenizer_name.replace('-', '_')}_{args.block_size}.sentiment_mask", ), )
[ 37811, 198, 1212, 4226, 552, 1769, 1573, 20680, 1912, 319, 15598, 31191, 34280, 198, 37811, 198, 11748, 28686, 198, 11748, 28034, 198, 11748, 1822, 29572, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 198, 6738, 6121, 364, 1330, ...
2.450806
1,240
from logger import Logger from numpy import average log = Logger(None)
[ 6738, 49706, 1330, 5972, 1362, 198, 6738, 299, 32152, 1330, 2811, 198, 198, 6404, 796, 5972, 1362, 7, 14202, 8, 628, 628, 628, 628 ]
3.291667
24
import repo import export.csv as csv # CONSTANTS milk_q = "SELECT * FROM \"%s\" WHERE price != 0 AND discount = false AND (name ILIKE '%%1l%%' OR name ILIKE '%%1 l%%') AND (name ILIKE '%%piim %%' OR name ILIKE '%%piim,%%') AND name NOT ILIKE '%%juust%%' AND name NOT ILIKE '%%kohupiim%%' AND name NOT ILIKE '%%laktoos%%' AND name NOT ILIKE '%%tis%%' AND name NOT ILIKE '%%kookos%%' AND name NOT ILIKE '%%latte%%'" wheat_kilos = 1 query_to_parse: dict = { "milk": milk_q, "cookies": "SELECT * FROM \"%s\" WHERE price != 0 AND discount = false AND (name ILIKE '%%kpsised %%' OR name ILIKE '%%kpsis %%') AND name NOT ILIKE '%%koer%%';", "sugar": "SELECT * FROM \"%s\" WHERE price != 0 AND discount = false AND name ILIKE '%%suhkur%%'", #"rimi milk": f"{milk_q} AND shop ILIKE '%%rimi%%'", #"other shop milk": f"{milk_q} AND shop NOT ILIKE '%%rimi%%'", #"eggs": f"SELECT * FROM \"%s\" WHERE price != 0 AND discount = false AND (name ILIKE '%%munad %%' OR name ILIKE '%%munad, %%' OR name ILIKE '%%muna,%%') AND name NOT ilike '%%salvrt%%' AND name NOT ILIKE '%%okolaad%%' AND name NOT ILIKE '%%Martsipani%%' AND name NOT ILIKE '%%SELVERI KK%%' AND name NOT ILIKE '%%kitkat%%'" , "wheat": f"SELECT * FROM \"%s\" WHERE price != 0 AND discount = false AND (name ILIKE '%%{wheat_kilos}kg%%' OR name ILIKE '%%{wheat_kilos} kg%%') AND (name ILIKE '%%nisujahu %%' OR name ILIKE '%%nisujahu,%%')", "beef": f"SELECT * FROM \"%s\" WHERE price != 0 AND discount = false AND (name ILIKE '%%veise %%' OR name ILIKE '%%veisepraad%%' OR name ILIKE '%%lihaveise%%') AND name NOT ILIKE '%%koera%%' AND name NOT ILIKE '%%pelmeen%%' AND name NOT ILIKE '%%pltsama%%' AND name NOT ILIKE '%%sink%%'", "tomatoes": "SELECT * FROM \"%s\" WHERE price != 0 AND discount = false AND (name ILIKE '%%tomat %%' OR name ILIKE '%%tomat, %%') AND name NOT ILIKE '%%pasta%%' AND name NOT ILIKE '%%0g%%' AND name NOT ILIKE '%%0 g%%' AND name NOT ILIKE '%%harilik%%' AND name NOT ILIKE '%%krpsud%%' AND name NOT ILIKE '%%marinaad%%' AND name NOT ILIKE '%%eine%%'", #"cucumber": "SELECT * FROM \"%s\" WHERE price != 0 AND discount = false AND name ILIKE '%%kg%%' AND (name ILIKE '%%kurk %%' OR name ILIKE '%%kurk,%%')", #"banana": "SELECT * FROM \"%s\" WHERE price != 0 AND discount = false AND (name ILIKE '%%kg%%' OR name ILIKE '%%chiq%%') AND (name ILIKE '%%banaan %%' OR name ILIKE '%%banaan,%%')", "apple": "SELECT * FROM \"%s\" WHERE price != 0 AND discount = false AND name ILIKE '%%kg%%' AND (name ILIKE '%%un %%' OR name ILIKE '%%un,%%')", "pear": "SELECT * FROM \"%s\" WHERE price != 0 AND discount = false AND name ILIKE '%%kg%%' AND (name ILIKE '%%pirn %%' OR name ILIKE '%%pirn,%%')", "pizza": "SELECT * FROM \"%s\" WHERE price != 0 AND discount = false AND (name ILIKE '%%pizza%%' OR name ILIKE '%%pitsa%%' AND name NOT ILIKE '%%pitsamaitseline%%')", "pig meat": f"SELECT * FROM \"%s\" WHERE price != 0 AND discount = false AND (name ILIKE '%%sea kaela%%' OR name ILIKE '%%sea vlisfilee%%' OR name ILIKE '%%sea sisefilee%%')", "cake": f"SELECT * FROM \"%s\" WHERE price != 0 AND discount = false AND (name ILIKE '%%kook,%%' OR name ILIKE '%%kook%%') AND name NOT ILIKE '%%van kook%%' AND name NOT ILIKE '%%selveri kk%%' AND name NOT ILIKE '%%kookos%%' AND name NOT LIKE '%%smuuti%%' AND name NOT ILIKE '%%pannkook%%'", "chicken": "SELECT * FROM \"%s\" WHERE price != 0 AND discount = false AND (name ILIKE '%%broileri rinnafilee%%' OR name ILIKE '%%pooltiivad%%' OR name ILIKE '%%poolkoivad%%' OR name ILIKE '%%kanafilee%%' OR name ILIKE '%%broilerifilee%%') AND name NOT ILIKE '%%HAU-HAU%%'" } # def save_to_excel(dataset, sheet_name: str = "Sheet") -> None: # tables = [i[0] for i in main.get_tables(main.connect(db="naive_products"))] # # tables.remove("initial_products") # header = ["Product name", "Shop name"] + tables # data = [] # for item in dataset: # prices = get_normalized_price( # [dataset[item]["prices"][value] # for value in dataset[item]["prices"]] # ) # prices = get_trend(prices) # value = [item, dataset[item]["shop"]] + prices # data.append(value) # table.append_header(header, sheet_name) # table.put_data(data, sheet_name) for i in query_to_parse: products = get_products_by_name(query=query_to_parse[i]) save_to_csv(i, products)
[ 11748, 29924, 198, 11748, 10784, 13, 40664, 355, 269, 21370, 198, 198, 2, 7102, 2257, 1565, 4694, 198, 25433, 74, 62, 80, 796, 366, 46506, 1635, 16034, 19990, 4, 82, 7879, 33411, 2756, 14512, 657, 5357, 9780, 796, 3991, 5357, 357, 367...
2.467823
1,787
# EX1 # if x < y: # y = 0 # x = x + 1 # else: # x = y max(30, 28, 18) # def triangleType(a, b, c): # isATriangle = False # if (a < b + c) and\ # (b < a + c) and\ # (c < a + b): # isATriangle = True # if isATriangle: # if (a == b) and (b == c): # print("the triangle was a EQUILATERAL") # elif (a != b) and \ # (a != c) and \ # (b != c): # print("the triangle was a SCALENE") # else: # print("invalid") # # triangleType(3, 5, 8) # def testfunc(x, y): # if x >= 0 and y >= 0: # if y*y >= x*10 and y <= math.sin(math.radians(x*30))*25: # if y >= math.cos(math.radians(x*40))*15: # print('oooookk') # testfunc(2, 3) # EX2 # if (x < y): # y = 0 # x = x + 1 # EX3 # if x < y: # return # print(x) # return # EX4 # x = 0 # while (x < y): # y = f(x,y) # x = x + 1 # EX5 # for x in range(10): # y = f(x,y) # a = [2 * x for x in y if x > 0 for y in z if y[0] < 3] # # digits = [0, 1, 5] # a = 0 # # for i in digits: # a += i # if i == 5: # print("5 in list") # break # else: # print("out of the loop") # try: # b = b + 5 # except KeyError: # a += 1 # except ZeroDivisionError: # a += 2 # else: # a += 3 # finally: # b += 1 # a = a - b # # x = 0 # while(x < y): # y = f(x, y) # if(y == 0): # break # elif(y < 0): # y = y * 2 # continue # x = x + 1
[ 2, 7788, 16, 198, 2, 611, 2124, 1279, 331, 25, 198, 2, 220, 220, 220, 220, 331, 796, 657, 198, 2, 220, 220, 220, 220, 2124, 796, 2124, 1343, 352, 198, 2, 2073, 25, 198, 2, 220, 220, 220, 220, 2124, 796, 331, 198, 198, 9806, ...
1.698795
913
import random import time while (1): wmsg = "Good morning!" events = { 1 : "calm", 2 : "calm", 3 : "rainy", 4 : "rainy", 5 : "rainy", 6 : "thunder", } array = [1,2,3,4,5,6] ## Array used to get events or smth output = random.choice(array) defevent = events[output] if defevent == "calm": print(wmsg ,"It's a sunny day outside.") clear() elif defevent == "rainy": print(wmsg, "You can hear the droplets falling onto your tent.") clear() else: print(wmsg,"You hear thunder rumbling outside") clear() del array[output - 1] if len(array) == 0: ##Array reset array.append('1','2','3','4','5','6') ##Actually, we could throw out them specifics outta window and use it's skelly as ##our primary dice. def could take out the variables from other files and juggle them to our delight break
[ 11748, 4738, 201, 198, 11748, 640, 201, 198, 201, 198, 4514, 357, 16, 2599, 201, 198, 220, 220, 220, 220, 201, 198, 220, 220, 220, 266, 19662, 796, 366, 10248, 3329, 2474, 201, 198, 220, 220, 220, 220, 201, 198, 220, 220, 220, 299...
2.133612
479
import numpy as np import OpenEXR as exr import cv2 import Imath import matplotlib.pyplot as plt
[ 11748, 299, 32152, 355, 45941, 198, 11748, 4946, 6369, 49, 355, 409, 81, 198, 11748, 269, 85, 17, 198, 11748, 1846, 776, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 628, 198 ]
2.828571
35
from yggdrasil.serialize.SerializeBase import SerializeBase
[ 6738, 331, 1130, 7109, 292, 346, 13, 46911, 1096, 13, 32634, 1096, 14881, 1330, 23283, 1096, 14881, 628 ]
3.388889
18
''' This file is the glue between the Discord bot and the game logic. ''' from wordle_logic import evaluate_guess, generate_new_word from wordy_types import ActiveGame, EndResult, LetterState def begin_game() -> ActiveGame: """ Begin a game for a user. """ # Select a word answer = generate_new_word() # Create and store new game state new_game = ActiveGame(answer=answer) return new_game def enter_guess(guess: str, game: ActiveGame) -> EndResult: """ Enter a guess for a user's game, updating the game state. >>> game=ActiveGame(answer="abcd") >>> enter_guess("aaaa", game) == EndResult.PLAYING True >>> render_result(game.results[-1]) '' >>> game=ActiveGame(answer="abca") >>> enter_guess("aaaz", game) == EndResult.PLAYING True >>> render_result(game.results[-1]) '' >>> game=ActiveGame(answer="abca") >>> enter_guess("aaab", game) == EndResult.PLAYING True >>> render_result(game.results[-1]) '' """ if game.state != EndResult.PLAYING: return game.state # Evaluate guess result = tuple(evaluate_guess(guess, game.answer)) # Update game state game.board_state.append(guess) game.results.append(result) # Check if game is over if result == (LetterState.CORRECT,)*len(game.answer): game.state = EndResult.WIN elif len(game.board_state) > len(game.answer): game.state = EndResult.LOSE return game.state def render_result(result: tuple[LetterState]) -> str: """ Render a result to a string. >>> render_result((LetterState.ABSENT, LetterState.PRESENT, LetterState.CORRECT)) '' >>> render_result((LetterState.ABSENT,)*4) '' """ absent, present, correct = '', '', '' return "".join( absent if state == LetterState.ABSENT else present if state == LetterState.PRESENT else correct for state in result )
[ 7061, 6, 201, 198, 1212, 2393, 318, 262, 22749, 1022, 262, 39462, 10214, 290, 262, 983, 9156, 13, 201, 198, 7061, 6, 201, 198, 201, 198, 6738, 1573, 293, 62, 6404, 291, 1330, 13446, 62, 5162, 408, 11, 7716, 62, 3605, 62, 4775, 201...
2.459295
823
import numpy as np def readNNet(nnetFile, withNorm=False): ''' Read a .nnet file and return list of weight matrices and bias vectors Inputs: nnetFile: (string) .nnet file to read withNorm: (bool) If true, return normalization parameters Returns: weights: List of weight matrices for fully connected network biases: List of bias vectors for fully connected network ''' # Open NNet file f = open(nnetFile,'r') # Skip header lines line = f.readline() while line[:2]=="//": line = f.readline() # Extract information about network architecture record = line.split(',') numLayers = int(record[0]) inputSize = int(record[1]) line = f.readline() record = line.split(',') layerSizes = np.zeros(numLayers+1,'int') for i in range(numLayers+1): layerSizes[i]=int(record[i]) # Skip extra obsolete parameter line f.readline() # Read the normalization information line = f.readline() inputMins = [float(x) for x in line.strip().split(",")[:-1]] line = f.readline() inputMaxes = [float(x) for x in line.strip().split(",")[:-1]] line = f.readline() means = [float(x) for x in line.strip().split(",")[:-1]] line = f.readline() ranges = [float(x) for x in line.strip().split(",")[:-1]] # Initialize list of weights and biases weights = [np.zeros((layerSizes[i],layerSizes[i+1])) for i in range(numLayers)] biases = [np.zeros(layerSizes[i+1]) for i in range(numLayers)] # Read remainder of file and place each value in the correct spot in a weight matrix or bias vector layer=0 i=0 j=0 line = f.readline() record = line.split(',') while layer+1 < len(layerSizes): while i<layerSizes[layer+1]: while record[j]!="\n": weights[layer][j,i] = float(record[j]) j+=1 j=0 i+=1 line = f.readline() record = line.split(',') i=0 while i<layerSizes[layer+1]: biases[layer][i] = float(record[0]) i+=1 line = f.readline() record = line.split(',') layer+=1 i=0 j=0 f.close() if withNorm: return weights, biases, inputMins, inputMaxes, means, ranges return weights, biases
[ 11748, 299, 32152, 355, 45941, 220, 198, 198, 4299, 1100, 6144, 316, 7, 77, 3262, 8979, 11, 351, 35393, 28, 25101, 2599, 198, 220, 220, 220, 705, 7061, 198, 220, 220, 220, 4149, 257, 764, 77, 3262, 2393, 290, 1441, 1351, 286, 3463, ...
2.211872
1,095
from typing import Dict import neptune.new as neptune import numpy as np import pytorch_lightning as pl import torch import torch.nn as nn from config import NEPTUNE_API_TOKEN, NEPTUNE_PROJECT_NAME from sklearn.metrics import classification_report, f1_score from utils.summary_loss import SummaryLoss from math import ceil from models.feature_extractors.multi_frame_feature_extractor import ( MultiFrameFeatureExtractor, ) from models.model_loader import ModelLoader from models.common.simple_sequential_model import SimpleSequentialModel from models.landmarks_models.lanmdarks_sequential_model import LandmarksSequentialModel from models.head_models.head_sequential_model import HeadClassificationSequentialModel # initialize neptune logging
[ 6738, 19720, 1330, 360, 713, 198, 198, 11748, 497, 457, 1726, 13, 3605, 355, 497, 457, 1726, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 12972, 13165, 354, 62, 2971, 768, 355, 458, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, ...
3.509346
214
from functools import lru_cache from collections import defaultdict import pandas as pd import numpy as np with open('input.txt') as fh: depthmap = pd.DataFrame([{ 'row': row, 'col': col, 'height': int(d) } for row, line in enumerate(fh) for col, d in enumerate(line.strip()) ]).pivot_table( index='row', columns='col', values='height' ).values idx = ( # right neighbor np.pad( depthmap[:, :-1] < depthmap[:, 1:], ((0, 0), (0, 1)), 'constant', constant_values=1 ) & # left neighbor np.pad( depthmap[:, 1:] < depthmap[:, :-1], ((0, 0), (1, 0)), 'constant', constant_values=1 ) & # lower neighbor np.pad( depthmap[:-1, :] < depthmap[1:, :], ((0, 1), (0, 0)), 'constant', constant_values=1 ) & # upper neighbor np.pad( depthmap[1:, :] < depthmap[:-1, :], ((1, 0), (0, 0)), 'constant', constant_values=1 ) ) print('part 1', (depthmap[np.where(idx)] + 1).sum()) # lru_cache here is essentially cheap DP - once we've calculated # the basin for any point A, we know the basin for any point B that # flows through point A lowpoint_to_basin = defaultdict(list) for r in range(depthmap.shape[0]): for c in range(depthmap.shape[1]): lowpoint_to_basin[lowpoint(r, c)].append((r, c)) print( 'part 2', np.prod(sorted([ len(points) for basin, points in lowpoint_to_basin.items() if basin ])[-3:]) ) # part 1 now that we solved part 2... print( 'part 1 redux', sum([ depthmap[lowpoint] + 1 for lowpoint in lowpoint_to_basin if lowpoint ]) )
[ 6738, 1257, 310, 10141, 1330, 300, 622, 62, 23870, 198, 6738, 17268, 1330, 4277, 11600, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 628, 198, 4480, 1280, 10786, 15414, 13, 14116, 11537, 355, 277, 71, 25, ...
2.078363
855
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html import re import subprocess import sys from pathlib import Path # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, str(Path(__file__).parent.parent.parent.resolve())) from pystac_client import __version__ # noqa: E402 git_branch = ( subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"]) .decode("utf-8") .strip() ) # -- Project information ----------------------------------------------------- project = 'pystac-client' copyright = '2021, Jon Duckworth' author = 'Matthew Hanson, Jon Duckworth' github_user = 'stac-utils' github_repo = 'pystac-client' package_description = 'A Python client for the STAC and STAC-API specs' # The full version, including alpha/beta/rc tags version = re.fullmatch(r'^(\d+\.\d+\.\d).*$', __version__).group(1) release = __version__ # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'sphinx.ext.napoleon', 'sphinx.ext.extlinks', 'sphinxcontrib.fulltoc', 'nbsphinx', 'myst_parser' ] extlinks = { "tutorial": ( "https://github.com/stac-utils/pystac-client/" "tree/{}/docs/tutorials/%s".format(git_branch), "tutorial", ) } nbsphinx_allow_errors = True # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. source_suffix = [".rst", "*.md", "*.ipynb"] exclude_patterns = ['build/*'] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' html_theme_options = { # 'sidebar_collapse': False, 'fixed_sidebar': True, 'github_button': True, 'github_user': github_user, 'github_repo': github_repo, 'description': package_description } # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [] # -- Options for intersphinx extension --------------------------------------- intersphinx_mapping = { 'python': ('https://docs.python.org/3', None), 'requests': ('https://requests.readthedocs.io/en/master', None), 'pystac': ('https://pystac.readthedocs.io/en/latest', None), 'dateutil': ('https://dateutil.readthedocs.io/en/stable/', None), } # -- Options for autodoc extension ------------------------------------------- autodoc_typehints = "none"
[ 2, 28373, 2393, 329, 262, 45368, 28413, 10314, 27098, 13, 198, 2, 198, 2, 770, 2393, 691, 4909, 257, 6356, 286, 262, 749, 2219, 3689, 13, 1114, 257, 1336, 198, 2, 1351, 766, 262, 10314, 25, 198, 2, 3740, 1378, 2503, 13, 82, 746, ...
3.154686
1,099
from .token_types import TT from .token_types import BadTT from .position import Position from .keywords import is_keyword from .keywords import keyword_declared_type from ..lexer import errors
[ 6738, 764, 30001, 62, 19199, 1330, 26653, 198, 6738, 764, 30001, 62, 19199, 1330, 7772, 15751, 198, 6738, 764, 9150, 1330, 23158, 198, 6738, 764, 2539, 10879, 1330, 318, 62, 2539, 4775, 198, 6738, 764, 2539, 10879, 1330, 21179, 62, 3244...
3.730769
52
#!/usr/bin/env python3 """Squares and Cubes for a range of numbers. Given a start and end, calucate the Square x**2 and the Cube x**3 for all numbers. Example of generator and functools.partial. """ from functools import partial def power(base, exponent): """Raise a base to the exponent.""" return base ** exponent square = partial(power, exponent=2) cube = partial(power, exponent=3) if __name__ == "__main__": print("number\tsquare\tcube") for x in main(1, 10): print("{}\t{}\t{}".format(*x))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 37811, 22266, 3565, 290, 7070, 274, 329, 257, 2837, 286, 3146, 13, 198, 198, 15056, 257, 923, 290, 886, 11, 2386, 1229, 378, 262, 9276, 2124, 1174, 17, 290, 198, 1169, 23315...
2.78534
191
#program to find the index of an item in a specified list. num =[10, 30, 4, -6] print(num.index(30))
[ 2, 23065, 284, 1064, 262, 6376, 286, 281, 2378, 287, 257, 7368, 1351, 13, 198, 22510, 796, 58, 940, 11, 1542, 11, 604, 11, 532, 21, 60, 198, 4798, 7, 22510, 13, 9630, 7, 1270, 4008, 198 ]
2.72973
37
from django.test import TestCase from django.core.exceptions import ValidationError from mozdns.txt.models import TXT from mozdns.domain.models import Domain
[ 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 3254, 24765, 12331, 198, 198, 6738, 6941, 89, 67, 5907, 13, 14116, 13, 27530, 1330, 15326, 51, 198, 6738, 6941, 89, 67, 5907, 1...
3.333333
48
#!/usr/bin/env python # Copyright (c) 2019 Orange and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 """Define the classes required to fully cover behave.""" import logging import os import unittest import mock from xtesting.core import behaveframework __author__ = "Deepak Chandella <deepak.chandella@orange.com>" def test_parse_results_exc_console(self): self.test_parse_results_exc(console=True) if __name__ == "__main__": logging.disable(logging.CRITICAL) unittest.main(verbosity=2)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 15069, 357, 66, 8, 13130, 11942, 290, 1854, 13, 198, 2, 198, 2, 1439, 2489, 10395, 13, 770, 1430, 290, 262, 19249, 5696, 198, 2, 389, 925, 1695, 739, 262, 2846, 286, 262, ...
3.161572
229
# coding=utf-8 from fabric.api import env, run COMMAND_COLLECTSTATIC = 'collectstatic' COMMAND_SYNCDB = 'syncdb' COMMAND_MIGRATE = 'migrate' _default_command = '{python} {manage} {command}' _commands_list = { COMMAND_COLLECTSTATIC: 'yes yes | {python} {manage} {command}', COMMAND_MIGRATE: '{python} {manage} {command} --noinput', }
[ 2, 19617, 28, 40477, 12, 23, 198, 6738, 9664, 13, 15042, 1330, 17365, 11, 1057, 628, 198, 9858, 44, 6981, 62, 25154, 16779, 35744, 2149, 796, 705, 33327, 12708, 6, 198, 9858, 44, 6981, 62, 23060, 7792, 11012, 796, 705, 27261, 9945, ...
2.443662
142
from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.conf import settings from django.core.exceptions import ValidationError from datetime import datetime, timedelta from commercialoperator.components.main.models import Park from commercialoperator.components.proposals.models import Proposal from ledger.checkout.utils import create_basket_session, create_checkout_session, calculate_excl_gst from ledger.payments.models import Invoice from ledger.payments.utils import oracle_parser import json from decimal import Decimal from commercialoperator.components.bookings.models import Booking, ParkBooking, ApplicationFee import logging logger = logging.getLogger('payment_checkout') def create_booking(request, proposal_id): """ Create the ledger lines - line items for invoice sent to payment system """ #import ipdb; ipdb.set_trace() booking = Booking.objects.create(proposal_id=proposal_id) tbody = json.loads(request.POST['payment'])['tbody'] for row in tbody: park_id = row[0]['value'] arrival = row[1] no_adults = int(row[2]) if row[2] else 0 no_children = int(row[3]) if row[3] else 0 no_free_of_charge = int(row[4]) if row[4] else 0 park = Park.objects.get(id=park_id) if any([no_adults, no_children, no_free_of_charge]) > 0: park_booking = ParkBooking.objects.create( booking = booking, park_id = park_id, arrival = datetime.strptime(arrival, '%Y-%m-%d').date(), no_adults = no_adults, no_children = no_children, no_free_of_charge = no_free_of_charge, cost = no_adults*park.adult_price + no_children*park.child_price ) if not park_booking: raise ValidationError('Must have at least one person visiting the park') return booking def get_session_application_invoice(session): """ Application Fee session ID """ if 'cols_app_invoice' in session: application_fee_id = session['cols_app_invoice'] else: raise Exception('Application not in Session') try: #return Invoice.objects.get(id=application_invoice_id) #return Proposal.objects.get(id=proposal_id) return ApplicationFee.objects.get(id=application_fee_id) except Invoice.DoesNotExist: raise Exception('Application not found for application {}'.format(application_fee_id)) def set_session_application_invoice(session, application_fee): """ Application Fee session ID """ session['cols_app_invoice'] = application_fee.id session.modified = True def delete_session_application_invoice(session): """ Application Fee session ID """ if 'cols_app_invoice' in session: del session['cols_app_invoice'] session.modified = True def create_fee_lines(proposal, invoice_text=None, vouchers=[], internal=False): """ Create the ledger lines - line item for application fee sent to payment system """ #import ipdb; ipdb.set_trace() now = datetime.now().strftime('%Y-%m-%d %H:%M') price = proposal.application_type.application_fee line_items = [{ 'ledger_description': 'Application Fee - {} - {}'.format(now, proposal.lodgement_number), 'oracle_code': proposal.application_type.oracle_code, 'price_incl_tax': price, 'price_excl_tax': price if proposal.application_type.is_gst_exempt else calculate_excl_gst(price), 'quantity': 1, }] logger.info('{}'.format(line_items)) return line_items def create_lines(request, invoice_text=None, vouchers=[], internal=False): """ Create the ledger lines - line items for invoice sent to payment system """ #import ipdb; ipdb.set_trace() lines = [] tbody = json.loads(request.POST['payment'])['tbody'] for row in tbody: park_id = row[0]['value'] arrival = row[1] no_adults = int(row[2]) if row[2] else 0 no_children = int(row[3]) if row[3] else 0 no_free_of_charge = int(row[4]) if row[4] else 0 park= Park.objects.get(id=park_id) if no_adults > 0: lines.append(add_line_item(park, arrival, 'Adult', price=park.adult_price, no_persons=no_adults)) if no_children > 0: lines.append(add_line_item(park, arrival, 'Child', price=park.child_price, no_persons=no_children)) if no_free_of_charge > 0: lines.append(add_line_item(park, arrival, 'Free', price=0.0, no_persons=no_free_of_charge)) return lines
[ 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 7738, 1060, 198, 6738, 42625, 14208, 13, 7295, 13, 6371, 411, 349, 690, 1330, 9575, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 1175...
2.542448
1,814
""" models.py App Engine datastore models Documentation: https://developers.google.com/appengine/docs/python/ndb/entities """ from google.appengine.ext import ndb from google.appengine.ext import blobstore from google.appengine.api import users import functools import flask from flaskext import login from flaskext.login import current_user from flaskext import oauth from hashlib import md5 import util import model import config from application import app import urls # from application.metadata import Session, Base ################################################################################ # Flaskext Login ################################################################################ login_manager = login.LoginManager() login_manager.anonymous_user = AnonymousUser login_manager.init_app(app) login_manager.login_view = 'signin'
[ 37811, 198, 27530, 13, 9078, 198, 198, 4677, 7117, 4818, 459, 382, 4981, 198, 24941, 341, 25, 3740, 1378, 16244, 364, 13, 13297, 13, 785, 14, 1324, 18392, 14, 31628, 14, 29412, 14, 358, 65, 14, 298, 871, 198, 198, 37811, 628, 198, ...
3.977169
219
import pygame import math import path_planning as pp
[ 11748, 12972, 6057, 198, 11748, 10688, 198, 11748, 3108, 62, 11578, 768, 355, 9788, 628 ]
3.6
15
#coding:utf-8 ''' Demo for calling API of deepnlp.org web service Anonymous user of this package have limited access on the number of API calling 100/day Please Register and Login Your Account to deepnlp.org to get unlimited access to fully support api_service API module, now supports both windows and linux platforms. ''' from __future__ import unicode_literals import json, requests, sys, os if (sys.version_info>(3,0)): from urllib.parse import quote else : from urllib import quote from deepnlp import api_service login = api_service.init() # registration, if failed, load default empty login {} with limited access login = {} # use your personal login {'username': 'your_user_name' , 'password': 'your_password'} conn = api_service.connect(login) # save the connection with login cookies # API Setting text = ("").encode('utf-8') # convert text from unicode to utf-8 bytes, quote() function # Segmentation url_segment = "http://www.deepnlp.org/api/v1.0/segment/?" + "lang=zh" + "&text=" + quote(text) web = requests.get(url_segment, cookies = conn) tuples = json.loads(web.text) wordsList = tuples['words'] # segmentation json {'words', [w1, w2,...]} return list print ("Segmentation API:") print (" ".join(wordsList).encode("utf-8")) # POS tagging url_pos = "http://www.deepnlp.org/api/v1.0/pos/?"+ "lang=zh" + "&text=" + quote(text) web = requests.get(url_pos, cookies = conn) tuples = json.loads(web.text) pos_str = tuples['pos_str'] # POS json {'pos_str', 'w1/t1 w2/t2'} return string print ("POS API:") print (pos_str.encode("utf-8")) # NER tagging url_ner = "http://www.deepnlp.org/api/v1.0/ner/?" + "lang=zh" + "&text=" + quote(text) web = requests.get(url_ner, cookies = conn) tuples = json.loads(web.text) ner_str = tuples['ner_str'] # NER json {'ner_str', 'w1/t1 w2/t2'} return list print ("NER API:") print (ner_str.encode("utf-8")) # Pipeline annotators = "segment,pos,ner" url_pipeline = "http://www.deepnlp.org/api/v1.0/pipeline/?" + "lang=zh" + "&text=" + quote(text) + "&annotators=" + quote(annotators) web = requests.get(url_pipeline, cookies = conn) tuples = json.loads(web.text) segment_str = tuples['segment_str'] # segment module pos_str = tuples['pos_str'] # pos module ner_str = tuples['ner_str'] # ner module ner_json = tuples['ner_json'] # ner result in json # output print ("Pipeline API:") print (segment_str.encode("utf-8")) print (pos_str.encode("utf-8")) print (ner_str.encode("utf-8")) print ("NER JSON:") print (json_to_str(ner_json).encode("utf-8"))
[ 2, 66, 7656, 25, 40477, 12, 23, 198, 7061, 6, 198, 11522, 78, 329, 4585, 7824, 286, 2769, 21283, 79, 13, 2398, 3992, 2139, 198, 20660, 2836, 286, 428, 5301, 423, 3614, 1895, 319, 262, 1271, 286, 7824, 4585, 1802, 14, 820, 198, 549...
2.717949
936
# -*- coding: utf-8 -*- """ The built-in Round-Robin algorithm. """ # standard library from typing import Union # scip plugin from spring_cloud.commons.client.service_instance import ServiceInstance from spring_cloud.utils.atomic import AtomicInteger from .loadbalancer import LoadBalancer from .supplier import ServiceInstanceListSupplier __author__ = "Waterball (johnny850807@gmail.com)" __license__ = "Apache 2.0"
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 464, 3170, 12, 259, 10485, 12, 40656, 11862, 13, 198, 37811, 198, 198, 2, 3210, 5888, 198, 6738, 19720, 1330, 4479, 198, 198, 2, 629, 541, 13877, 198, 6738...
3.349206
126
import os import sys import numpy as np import torch from torchvision import datasets, transforms ROOT_DIR = os.path.dirname(os.getcwd()) if ROOT_DIR not in sys.path: sys.path.append(ROOT_DIR) import DeepSparseCoding.utils.data_processing as dp import DeepSparseCoding.datasets.synthetic as synthetic
[ 11748, 28686, 198, 11748, 25064, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 28034, 10178, 1330, 40522, 11, 31408, 198, 198, 13252, 2394, 62, 34720, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 418, 13, 1136, 66,...
3
102
#!/usr/bin/env python3 from ctypes import * import m2m2_core
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 6738, 269, 19199, 1330, 1635, 198, 198, 11748, 285, 17, 76, 17, 62, 7295, 198 ]
2.423077
26
import networkx as nx import numpy as np import argparse if __name__ == '__main__': np.random.seed(555) NUM = 10000 parser = argparse.ArgumentParser() parser.add_argument('-d', type=str, default='music') args = parser.parse_args() DATASET = args.d kg_np = np.load('../data/' + DATASET + '/kg_final.npy') kg = nx.Graph() kg.add_edges_from([(triple[0], triple[2]) for triple in kg_np]) # construct knowledge graph rating_np = np.load('../data/' + DATASET + '/ratings_final.npy') item_history = dict() item_set = set() for record in rating_np: user = record[0] item = record[1] rating = record[2] if rating == 1: if item not in item_history: item_history[item] = set() item_history[item].add(user) item_set.add(item) item_pair_num_no_common_rater = 0 item_pair_num_with_common_rater = 0 sp_no_common_rater = dict() sp_with_common_rater = dict() while True: item1, item2 = np.random.choice(list(item_set), size=2, replace=False) if item_pair_num_no_common_rater == NUM and item_pair_num_with_common_rater == NUM: break if item_pair_num_no_common_rater < NUM and len(item_history[item1] & item_history[item2]) == 0: item_pair_num_no_common_rater += 1 if not nx.has_path(kg, item1, item2): sp = 'infinity' else: sp = nx.shortest_path_length(kg, item1, item2) if sp not in sp_no_common_rater: sp_no_common_rater[sp] = 0 sp_no_common_rater[sp] += 1 print(item_pair_num_no_common_rater, item_pair_num_with_common_rater) if item_pair_num_with_common_rater < NUM and len(item_history[item1] & item_history[item2]) > 0: item_pair_num_with_common_rater += 1 if not nx.has_path(kg, item1, item2): sp = 'infinity' else: sp = nx.shortest_path_length(kg, item1, item2) if sp not in sp_with_common_rater: sp_with_common_rater[sp] = 0 sp_with_common_rater[sp] += 1 print(item_pair_num_no_common_rater, item_pair_num_with_common_rater) print(sp_no_common_rater) print(sp_with_common_rater)
[ 11748, 3127, 87, 355, 299, 87, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 1822, 29572, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 45941, 13, 25120, 13, 28826, 7, 31046, 8, 198, 220, ...
2.014719
1,155
import pygame from pygame.locals import* from pygame import mixer pygame.init() # loading in background image backgroundClassic_image=pygame.image.load('image/WallPaper.png') backgroundAncient_image=pygame.image.load('image/WallPaper2.png') # loading in player image player_imageClassic=pygame.image.load('image/player.png') player_imageAncient=pygame.image.load('image/player2.png') player_imageClassicR=pygame.image.load('image/playerR.png') player_imageAncientR=pygame.image.load('image/player2R.png') #loading sound for bullet BulletSound=mixer.Sound('sound/bullet.wav') #Loading sound for collision with enemy: CollidewithEnemy=mixer.Sound('sound/Collide.wav') #Loading sound for opening of game: Opening_Sound=mixer.Sound('sound/opening.wav') Mouse_Sound=mixer.Sound('sound/mouseclick.wav') Selection_Sound=mixer.Sound('sound/selection.wav') #loading sound for end of game: End_GameSound=mixer.Sound('sound/gameover.wav') #loading sound for win game: Win_GameSound=mixer.Sound('sound/wingame.wav') Door_GameSound=mixer.Sound('sound/doorappear.wav') #Loading in image for opening animation: Opening_Image= [pygame.image.load('image/opening.png'),pygame.image.load('image/opening.png'), pygame.image.load('image/opening.png'),pygame.image.load('image/opening.png'), pygame.image.load('image/opening.png'),pygame.image.load('image/opening.png'), pygame.image.load('image/opening.png'),pygame.image.load('image/opening.png'), pygame.image.load('image/opening.png'),pygame.image.load('image/opening.png'), pygame.image.load('image/opening.png'),pygame.image.load('image/opening.png'), pygame.image.load('image/opening.png'),pygame.image.load('image/opening.png'), pygame.image.load('image/opening.png'),pygame.image.load('image/opening.png'), pygame.image.load('image/opening.png'),pygame.image.load('image/opening1.png'), pygame.image.load('image/opening1.png'),pygame.image.load('image/opening1.png'), pygame.image.load('image/opening.png')] #loading in image for opening game mode selection: OpeningSelect_BG=pygame.image.load('image/ModeSelection.png') ClassicMode_image=pygame.image.load('image/ClassicMode.png') AncientMode_image=pygame.image.load('image/AncientMode.png') Glow_image=pygame.image.load('image/glow.png') #Loading image for win game: Won_Light=pygame.image.load('image/light.png') Won_Door=pygame.image.load('image/door.png') #Loading win game page: Escape_image=pygame.image.load('image/Wingame.png') #loading in image: direction_key=pygame.image.load('image/direction1.png') direction_arrow=pygame.image.load('image/direction2.png') #loading in endgame page: End_image=pygame.image.load('image/gameover.png') # load in image of platform platformClassic_img= pygame.image.load('image/icicle.png') platformAncient_img=pygame.image.load('image/brickwall.png') #Game map for two different game modes: Classic_map = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0], [1,1,1,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,1,1,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0], [0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]] Ancient_map=[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [1,1,0,0,1,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,1,1,0,0,0], [1,1,0,0,1,1,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,1,1,0,0,0,1,0,0,1,1,1,0,1,0,0,1,0,0,0,0,1,1,1,1,0,0,0], [1,1,0,0,1,1,1,0,0,1,1,0,0,1,0,0,1,0,0,0,0,1,1,0,1,0,1,0,0,1,1,1,0,1,0,0,1,0,0,0,0,1,1,0,0,0,0,0], [1,1,0,0,1,1,1,0,0,1,1,0,0,1,0,0,1,0,0,0,0,1,1,0,1,0,1,0,0,1,1,1,0,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0], [1,1,0,0,1,1,1,0,0,1,1,0,0,1,0,0,1,0,0,0,0,1,1,0,1,0,1,0,0,1,1,1,0,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0]] #Upload font type: fontd1= pygame.font.Font('font/Pieces.ttf',32) fontd2= pygame.font.Font('font/OldeEnglish.ttf',18) fontdO= pygame.font.Font('font/Opening.ttf',28) # Font (Opening) fontdS= pygame.font.Font('font/Pieces.ttf',30) # Font (For Game Mode Selection)
[ 11748, 12972, 6057, 201, 198, 6738, 12972, 6057, 13, 17946, 874, 1330, 9, 201, 198, 6738, 12972, 6057, 1330, 33938, 201, 198, 201, 198, 201, 198, 9078, 6057, 13, 15003, 3419, 201, 198, 201, 198, 201, 198, 201, 198, 2, 11046, 287, 44...
1.493381
4,230
import filters as f from filters.test import BaseFilterTestCase # noinspection PyProtectedMember from iso3166 import Country, countries_by_alpha3 from language_tags import tags from language_tags.Tag import Tag from moneyed import Currency, get_currency
[ 11748, 16628, 355, 277, 198, 6738, 16628, 13, 9288, 1330, 7308, 22417, 14402, 20448, 198, 2, 645, 1040, 14978, 9485, 19703, 11197, 27608, 198, 6738, 47279, 18, 23055, 1330, 12946, 11, 2678, 62, 1525, 62, 26591, 18, 198, 6738, 3303, 62, ...
3.953846
65
''' Equivalence of AR(1) and MA(infinity) To better understand the relationship between MA models and AR models, you will demonstrate that an AR(1) model is equivalent to an MA( ) model with the appropriate parameters. You will simulate an MA model with parameters 0.8,0.82,0.83, 0.8 , 0.8 2 , 0.8 3 , for a large number (30) lags and show that it has the same Autocorrelation Function as an AR(1) model with =0.8 = 0.8 . INSTRUCTIONS 100XP Import the modules for simulating data and plotting the ACF from statsmodels Use a list comprehension to build a list with exponentially decaying MA parameters: 1,0.8,0.82,0.83, 1 , 0.8 , 0.8 2 , 0.8 3 , Simulate 5000 observations of the MA(30) model Plot the ACF of the simulated series ''' # import the modules for simulating data and plotting the ACF from statsmodels.tsa.arima_process import ArmaProcess from statsmodels.graphics.tsaplots import plot_acf # Build a list MA parameters ma = [0.8**i for i in range(30)] # Simulate the MA(30) model ar = np.array([1]) AR_object = ArmaProcess(ar, ma) simulated_data = AR_object.generate_sample(nsample=5000) # Plot the ACF plot_acf(simulated_data, lags=30) plt.show()
[ 7061, 6, 198, 23588, 2473, 594, 286, 5923, 7, 16, 8, 290, 8779, 7, 10745, 6269, 8, 198, 198, 2514, 1365, 1833, 262, 2776, 1022, 8779, 4981, 290, 5923, 4981, 11, 345, 481, 10176, 326, 281, 5923, 7, 16, 8, 2746, 318, 7548, 284, 28...
2.912935
402
import PIL.Image import random import numpy as np import cv2 def HWC_to_CHW(img): return np.transpose(img, (2, 0, 1))
[ 11748, 350, 4146, 13, 5159, 198, 11748, 4738, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 628, 198, 198, 4299, 367, 27353, 62, 1462, 62, 3398, 54, 7, 9600, 2599, 198, 220, 220, 220, 1441, 45941, 13, 7645, 3455, 7, ...
2.358491
53
#!/usr/bin/env python3 import os import subprocess if __name__ == '__main__': out_dir = 'out' if not os.path.exists(out_dir): os.mkdir(out_dir) subprocess.run(['cargo', 'build', '--release']) exe = 'target/release/svg' subprocess.run([exe, '-i', 'test/simple-text.svg', '-o', 'out/simple-text.png', '--perf', '--dump-svg', 'out/simple-text.svg'])
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 28686, 198, 11748, 850, 14681, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 503, 62, 15908, 796, 705, 448, 6, 198, 220, 220, 220...
2.08377
191
""" String format type value enumeration. """ TRUE = '1' FALSE = '0' NONE = ''
[ 37811, 198, 10100, 5794, 2099, 1988, 27056, 341, 13, 198, 37811, 198, 5446, 8924, 796, 705, 16, 6, 198, 37, 23719, 796, 705, 15, 6, 198, 45, 11651, 796, 10148, 198 ]
2.548387
31
from django.contrib import admin from .models import Museums admin.site.register(Museums)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 764, 27530, 1330, 32887, 5700, 198, 198, 28482, 13, 15654, 13, 30238, 7, 44, 1904, 5700, 8 ]
3.333333
27
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ setup ~~~~~ Setup Script Run the build process by running the command 'python setup.py build' :copyright: (c) 2018 by Oleksii Lytvyn. :license: MIT, see LICENSE for more details. """ import osc.osc as osc try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='osc', version=osc.__version__, author='Oleksii Lytvyn', author_email='grailapplication@gmail.com', description='OSC implementation in pure Python', long_description=open('README.rst').read(), url='https://bitbucket.org/grailapp/osc', download_url='https://bitbucket.org/grailapp/osc/get/default.zip', platforms='any', packages=['osc'], keywords=['osc', 'protocol', 'utilities', 'osc-1.0', 'network', 'communication', 'udp'], zip_safe=False, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Programming Language :: Python :: 3', "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: Multimedia :: Sound/Audio', 'Topic :: System :: Networking', 'License :: OSI Approved :: MIT License' ], install_requires=[] )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 37811, 198, 220, 220, 220, 9058, 198, 220, 220, 220, 220, 8728, 93, 628, 220, 220, 220, 31122, 12327, 198, 220, 220, 220...
2.653266
597
import asyncio import ssl import aiohttp from . import constants as c def _get_rate_limit_wait(log, resp, opts): """ Returns the number of seconds we should wait given a 429 HTTP response and HTTP options. """ max_wait = 3600 wait = opts['wait'] header_name = opts['rate_limit_reset_header_name'] if header_name and header_name in resp.headers: header_value = resp.headers[header_name] try: new_wait = float(header_value) # Make sure we have a valid value (not negative, NaN, or Inf) if 0 <= new_wait <= max_wait: wait = new_wait elif new_wait > max_wait: log.warn('rate reset value too high', name=header_name, value=header_value) wait = max_wait else: log.warn('invalid rate reset value', name=header_name, value=header_value) except ValueError: log.warn('invalid rate reset value', name=header_name, value=header_value) return wait
[ 11748, 30351, 952, 198, 11748, 264, 6649, 198, 198, 11748, 257, 952, 4023, 628, 198, 6738, 764, 1330, 38491, 355, 269, 628, 198, 4299, 4808, 1136, 62, 4873, 62, 32374, 62, 17077, 7, 6404, 11, 1217, 11, 2172, 82, 2599, 198, 220, 220,...
2.147002
517
#!/usr/bin/env python3 from kubernetes.shell_utils import simple_run as run run(( "python3 gcloud_dataproc/v02/run_script.py " "--cluster create-ht-clinvar " "download_and_create_reference_datasets/v02/hail_scripts/write_clinvar_ht.py"))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 6738, 479, 18478, 3262, 274, 13, 29149, 62, 26791, 1330, 2829, 62, 5143, 355, 1057, 198, 198, 5143, 19510, 198, 220, 220, 220, 366, 29412, 18, 308, 17721, 62, 19608, 499, 12...
2.4
105
from discord.ext import commands from flegelapi.pg import default, server from distutils.util import strtobool import discord member_table= """ member_( id serial PRIMARY KEY, server_id interger NOT NULL, role_ld interger, channel_id interger, custom_mes character varying DEFAULT , on_off boolean DEFAULT False)"""
[ 6738, 36446, 13, 2302, 1330, 9729, 198, 6738, 277, 1455, 417, 15042, 13, 6024, 1330, 4277, 11, 4382, 198, 6738, 1233, 26791, 13, 22602, 1330, 965, 83, 672, 970, 198, 11748, 36446, 198, 198, 19522, 62, 11487, 28, 37227, 2888, 41052, 19...
2.75
132
import gym import numpy as np import sys import theano import theano.tensor as T import layers from layers import FullyConnectedLayer, SoftmaxLayer env = gym.make('CartPole-v0') #Number of actions action_n = env.action_space.n #Number of features observed feature_n = env.observation_space.shape[0] epochs = 100 mini_batch_size = 10 timesteps = 100 learning_rate = 1.0 epsilon_decay_rate = -0.04 initial_epsilon = 1.0 #avg_solved_perc = 97.5 #avg_solved_threshold = (avg_solved_perc/100*timesteps) render = False #Initialize network layers = [ FullyConnectedLayer(n_in=4, n_out=10), FullyConnectedLayer(n_in=10, n_out=10), SoftmaxLayer(n_in=10, n_out=2) ] params = [param for layer in layers for param in layer.params] iterations = mini_batch_size x = T.vector("x") y = T.ivector("y") init_layer = layers[0] init_layer.set_inpt(x, 1) for j in xrange(1, len(layers)): prev_layer, layer = layers[j-1], layers[j] layer.set_inpt( prev_layer.output, 1) cost = T.argmax(T.log(layers[-1].output)) R = 0 #iter_grads = [theano.shared([np.zeros(shape=param.get_value().shape, dtype=theano.config.floatX) for param in params])] #grads = [theano.shared([np.zeros(shape=param.get_value().shape, dtype=theano.config.floatX) for param in params])] grads = T.grad(cost, params) iter_grads = [T.zeros_like(grad) for grad in grads] t_updates = [] iter_updates = [] mb_updates = [] #t_updates.append((iter_grads, iter_grads+T.grad(cost, params))) #iter_updates.append((iter_grads, T.dot(T.dot(iter_grads, R), 1/mini_batch_size))) #iter_updates.append((grads, grads+iter_grads)) #mb_updates.append((params, params+learning_rate*grads)) for param, grad in zip(params, grads): mb_updates.append((param, param+learning_rate*grad))#Update our params as we were #To execute our updates when necessary exec_t_updates = theano.function([], None, updates=t_updates) exec_iter_updates = theano.function([], None, updates=iter_updates) #exec_mb_updates = theano.function([], None, updates=mb_updates) """ mb = T.iscalar() train_mb = theano.function( [], cost, updates=mb_updates) """ #To get our action a possibilities from state s s = T.vector() NN_output = theano.function( [s], layers[-1].output, givens={ x: s }) for e in range(epochs): #grads = T.set_subtensor(grads, T.zeros_like(grads)) grads = grads * 0 epsilon = exp_decay(initial_epsilon, epsilon_decay_rate, e) for mb in range(mini_batch_size): s = env.reset() R = 0 #iter_grads = T.set_subtensor(iter_grads, T.zeros_like(iter_grads)) iter_grads = grads * 0 for t in range(timesteps): if render: env.render() if epsilon_greedy(epsilon): #Random action action = env.action_space.sample() tmp = T.scalar("tmp") max_action = T.ones_like(tmp) else: #Policy Action a = NN_output(s) action = np.argmax(a, axis=1)[0] max_action = T.max(a) #exec_t_update() iter_grads = iter_grads + T.grad(max_action, params) s, r, done, info = env.step(action) R += r if done: break #exec_iter_update() iter_grads = [iter_grad * R / mini_batch_size for iter_grad in iter_grads] grads += iter_grads print "Epoch: %i, Reward: %i, Epsilon: %f" % (e, R, epsilon) #exec_mb_updates() #cost_asdf = train_mb() #print "Updating params..." for param, grad in zip(params, grads): param = param + learning_rate * grad
[ 11748, 11550, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 25064, 198, 11748, 262, 5733, 198, 11748, 262, 5733, 13, 83, 22854, 355, 309, 198, 11748, 11685, 198, 198, 6738, 11685, 1330, 40234, 13313, 276, 49925, 11, 8297, 9806, 49925, ...
2.125705
1,774
#!/usr/bin/python ''' Andrei Dorin 06/10/2018 User interface for WISP chat implementation ''' import argparse import logging import signal import sys import time import queue import select import getpass from wisp_client import WispClient from wisp_common import State, WispRequest, WispResponse, WispMessage, WISP_DEFAULT_PORT def signal_sigint(_, __): ''' Signal handler for KeyboardInterrupt or SIGINT ''' print('SIGINT Received, shutting down') sys.exit(0) def main(): ''' Main entry point of client Argument parsing and initializing client ''' parser = argparse.ArgumentParser(description='WISP protocol chat client') parser.add_argument('-H', '--host', type=str, help='IP of server, if none is specified, service discovery will be attempted') parser.add_argument('-p', '--port', type=int, default=32500, help='Port of server to connect, if none is specified, protocol default 32500 will be used') parser.add_argument('-v', '--verbosity', type=int, default=4, choices=[4, 3, 2, 1], help='Verbosity of logger, 4: Error, 3: Warning, 2: Info, 1: Debug') args = parser.parse_args() logging.basicConfig() logging.getLogger().setLevel(args.verbosity * 10) signal.signal(signal.SIGINT, signal_sigint) # CLIENT client = Client() if args.host: client.connect(args.host, args.port) else: client.discover() client.start() if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 7061, 6, 198, 31258, 72, 12528, 259, 198, 3312, 14, 940, 14, 7908, 198, 12982, 7071, 329, 370, 1797, 47, 8537, 7822, 198, 7061, 6, 198, 198, 11748, 1822, 29572, 198, 11748, 18931, 198, 1174...
2.619048
588
from newpy.loggers.colored_formatter import ColoredFormatter
[ 6738, 649, 9078, 13, 6404, 5355, 13, 25717, 62, 687, 1436, 1330, 1623, 1850, 8479, 1436, 198 ]
3.588235
17
# coding: utf8 """Sources provide an abstraction between a source of music notes and putao projects.""" from . import mml # noqa from .reg import formats, loads, register # noqa
[ 2, 19617, 25, 3384, 69, 23, 198, 37811, 21188, 2148, 281, 34651, 1022, 257, 2723, 286, 2647, 4710, 290, 1234, 5488, 4493, 526, 15931, 198, 198, 6738, 764, 1330, 285, 4029, 220, 1303, 645, 20402, 198, 6738, 764, 2301, 1330, 17519, 11, ...
3.62
50
# -*- coding: utf-8 -*- """ Created by libsedmlscript v0.0.1 """ from sed_roadrunner import model, task, plot from mpmath import csc #---------------------------------------------- csc(0.5)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 201, 198, 41972, 416, 9195, 36622, 4029, 12048, 410, 15, 13, 15, 13, 16, 201, 198, 37811, 201, 198, 201, 198, 6738, 10081, 62, 6344, 16737, 1330,...
2.607595
79
import redis
[ 11748, 2266, 271 ]
4
3
from pyftdi.spi import SpiController from pyftdi.gpio import GpioSyncController import serial import time import sys import JSONFile dbg = False def ui_hex(str): return int(str,16) def uiLoopHelp(): print() print("Command set:") print() print("write <REG_NAME> XXXX1010 1XXXXXX0 | Write bits (any char not 0 or 1 is a don't-care)") print("writeRaw 0xXX 0xXX 0xXX | Write a raw sequence of bytes") print("read <REG_NAME> | Read register") print("all | Read all registers") print("save <fileName> | Save registers to JSON file") print("load <fileName> | Load and write registers from JSON file") print("loadCSV <fileName> | Write bytes from CSV file (each line is one transaction)") print("loadDefault | Load datasheet default JSON configuration") print("help | Print this command set") print("exit | Exit the program") def uiLoop(spiObject, printHelp=True): if printHelp: uiLoopHelp() jsonObject = None ui = [""] while (ui[0] != "exit"): print("\n> ", end='') ui = sys.stdin.readline().rstrip().split(' ') if (ui[0] == "read"): spiObject.readStruct({ ui[1] : {} }, display=True) if (ui[0] == "write"): dataRegs = [] for i in range(2,len(ui)): dataRegs.append( ui[i] ) spiObject.writeBits( ui[1], dataRegs ) if (ui[0] == "all"): spiObject.readState() if (ui[0] == "compare"): spiObject.compare() if (ui[0] == "trigger"): while(1): spiObject.trigger(pre_display=chr(27)+"[2J") time.sleep(1) if (ui[0] == "save"): if jsonObject is None: if len(ui) > 1: jsonObject = JSONFile.new(ui[1]) else: jsonObject = JSONFile.new(input("\nSave as: ")) jsonObject.write( spiObject.readState() ) if (ui[0] == "load"): if jsonObject is None: jsonObject = JSONFile.load(ui[1]) spiObject.writeStruct(jsonObject.read()) spiObject.readState() if (ui[0] == "loadCSV"): spiObject.writeCSV(ui[1]) print("Comparing changes...") spiObject.compare() if (ui[0] == "writeRaw"): print("Writing raw bytes...") byteList = [] for i in range(1,len(ui)): byteList.append( int(ui[i],16) ) print(byteList) spiObject.writeRaw( byteList ) if (ui[0] == "loadDefault"): spiObject.writeDefault() if (ui[0] == "help"): uiLoopHelp()
[ 6738, 12972, 701, 10989, 13, 2777, 72, 1330, 1338, 72, 22130, 198, 6738, 12972, 701, 10989, 13, 31197, 952, 1330, 402, 79, 952, 28985, 22130, 198, 11748, 11389, 198, 11748, 640, 198, 11748, 25064, 198, 11748, 19449, 8979, 198, 198, 9945...
1.860465
1,591
from morepath import redirect from onegov.core.security import Private from onegov.gazette import _ from onegov.gazette import GazetteApp from onegov.gazette.forms import EmptyForm from onegov.gazette.layout import Layout from onegov.user import UserGroup from onegov.user import UserGroupCollection from onegov.user.forms import UserGroupForm
[ 6738, 517, 6978, 1330, 18941, 198, 6738, 530, 9567, 13, 7295, 13, 12961, 1330, 15348, 198, 6738, 530, 9567, 13, 70, 1031, 5857, 1330, 4808, 198, 6738, 530, 9567, 13, 70, 1031, 5857, 1330, 38772, 4677, 198, 6738, 530, 9567, 13, 70, 1...
3.663158
95
from . import utils from . import pth from . import proc from . import log from . import json from . import time from . import importer
[ 6738, 764, 1330, 3384, 4487, 198, 6738, 764, 1330, 279, 400, 198, 6738, 764, 1330, 13834, 198, 6738, 764, 1330, 2604, 198, 6738, 764, 1330, 33918, 198, 6738, 764, 1330, 640, 198, 6738, 764, 1330, 848, 4337, 198 ]
3.578947
38
import numpy as np
[ 11748, 299, 32152, 355, 45941, 628, 628 ]
3.142857
7
# ---------------------------------------------------------------------------- # Copyright (c) 2020 Legorooj <legorooj@protonmail.com> # Copyright (c) 2020 FluffyKoalas <github.com/fluffykoalas> # This file and all others in this project are licensed under the MIT license. # Please see the LICENSE file in the root of this repository for more details. # ---------------------------------------------------------------------------- from .timers import Timer from .raw import tests, runners __all__ = [ 'call_after', 'time_callable', 'time_eval', 'time_exec' ]
[ 2, 16529, 10541, 198, 2, 15069, 357, 66, 8, 12131, 3564, 273, 2238, 73, 1279, 1455, 273, 2238, 73, 31, 1676, 1122, 4529, 13, 785, 29, 198, 2, 15069, 357, 66, 8, 12131, 1610, 15352, 48735, 282, 292, 1279, 12567, 13, 785, 14, 2704, ...
4.014085
142
import netifaces import argparse import os import zmq import threading if __name__ == '__main__': main()
[ 11748, 2010, 361, 2114, 198, 11748, 1822, 29572, 198, 11748, 28686, 198, 11748, 1976, 76, 80, 198, 11748, 4704, 278, 220, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 198 ]
2.756098
41
a = [1, 2, 3] b = a a[0] = 'gouliguojiashengsiyi' print('a =', a) print('b =', b)
[ 64, 796, 685, 16, 11, 362, 11, 513, 60, 198, 65, 796, 257, 198, 198, 64, 58, 15, 60, 796, 705, 70, 2852, 328, 84, 13210, 4448, 31753, 82, 7745, 72, 6, 198, 4798, 10786, 64, 796, 3256, 257, 8, 198, 4798, 10786, 65, 796, 3256, ...
1.693878
49
#!/usr/bin/env python # -*- encoding: utf-8 -*- # @Time : 2021/12/1 13:27 import numpy as np from numpy import random import matplotlib.pyplot as plt from trajectory import Trajectory from rnd import stable_rnd, skewed_stable_rnd if __name__ == "__main__": m1 = CTRW(100, 1, 2) t1, x1 = m1.get() fig1 = plt.figure(1) plt.step(t1, x1, where="post") plt.xlabel("t") plt.ylabel("x") fig1.savefig("../figures/ctrw1.png") m2 = CTRW(100, 0.7, 2) t2, x2 = m2.get() fig2 = plt.figure(2) plt.step(t2, x2, where="post") plt.xlabel("t") plt.ylabel("x") fig2.savefig("../figures/ctrw2.png") m3 = CTRW(100, 1, 1.5) t3, x3 = m3.get() fig3 = plt.figure(3) plt.step(t3, x3, where="post") plt.xlabel("t") plt.ylabel("x") fig3.savefig("../figures/ctrw3.png") m4 = CTRW(100, 0.7, 1.5) t4, x4 = m4.get() fig4 = plt.figure(4) plt.step(t4, x4, where="post") plt.xlabel("t") plt.ylabel("x") fig4.savefig("../figures/ctrw4.png")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 7575, 1058, 33448, 14, 1065, 14, 16, 1511, 25, 1983, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 299, 321...
1.91215
535
import aiofiles import asyncstdlib from pydantic.types import PositiveFloat from conversion_parameters import ConversionParameters from conversion_spec import ConversionSpec, Currency from conversion_spec_provider import ConversionSpecProvider
[ 11748, 257, 952, 16624, 198, 11748, 30351, 19282, 8019, 198, 6738, 279, 5173, 5109, 13, 19199, 1330, 33733, 43879, 198, 198, 6738, 11315, 62, 17143, 7307, 1330, 44101, 48944, 198, 6738, 11315, 62, 16684, 1330, 44101, 22882, 11, 20113, 198...
4.730769
52
from sqlite3 import Date from twilio.rest import Client from datetime import datetime from playsound import playsound from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager import csv import time ################################ "PREFCTURE DE PARIS" ##################################### ######################## "Remise d'un titre de sjour tranger" ########################### while True: # New instance for Chrome browser = webdriver.Chrome(ChromeDriverManager().install()) # Open the webpage try: browser.get('https://pprdv.interieur.gouv.fr/booking/create/989') time.sleep(3) # Save the window opener (current window, do not mistaken with tab... not the same) main_window = browser.current_window_handle # Accepter les cookies : browser.find_element_by_xpath("//a[@onclick='javascript:accepter()']").click() time.sleep(2) # Click in checkbox "Veuillez cocher la case pour..." : browser.find_element_by_xpath("//input[@name='condition']").click() time.sleep(3) # Click in the submit button : browser.find_element_by_xpath("//input[@name='nextButton']").click() time.sleep(3) # Click in the radio button "Guichets 1-2 &3" : browser.find_element_by_xpath("//input[@id='planning990']").click() time.sleep(3) # Click in the submit button 1 : browser.find_element_by_xpath("//input[@type='submit']").click() time.sleep(4) ################################################## # Variables : textNo = "Il n'existe plus de plage horaire libre pour votre demande de rendez-vous" textOui = "Choix d'une plage horaire" son = "./alert.wav" # ajouter le chemin de votre fichier audio pour l'alerte url = browser.current_url now = datetime.now() Heure = now.strftime("%H:%M:%S") Date = datetime.now().strftime("%d/%m/%Y") #account Twilio : account_sid = 'SID' # ajouter le SID Twilio auth_token = 'token' # ajouter le Token Twilio client = Client(account_sid, auth_token) #log CSV: header = ['Date', 'Heure', 'Prfecture', 'Disponibilit'] DataNo = [Date, Heure,'Paris G 1-2 et 3', 'Pas de Rendez-vous'] DataOui = [Date, Heure, 'Paris G 1-2 et 3', 'Rendez-vous Disponible'] ################################################## #Conditions : if (textOui in browser.page_source): browser.find_element_by_xpath("//input[@type='submit']").click() print("") print("RDV Disponible") print("") with open('./log.csv', 'a', newline='') as f: #ajouter le chemin de votre fichier log writer = csv.writer(f) writer.writerow(DataOui) """ # Send SMS Alert : message = client.messages.create( from_='votre numero twilio', body = 'Rendez-vous prefecture disponible, https://pprdv.interieur.gouv.fr/booking/create/989', to ='votre numero perso' ) print(message.sid) """ #alert sound : playsound(son) time.sleep(900) break elif (textNo in browser.page_source): playsound(son) print("") print("Pas de RDV") print("") with open('./log.csv', 'a', newline='') as f: #ajouter le chemin de votre fichier log writer = csv.writer(f) writer.writerow(DataNo) time.sleep(30) browser.quit() except: browser.quit() time.sleep(60)
[ 6738, 44161, 578, 18, 1330, 7536, 201, 198, 6738, 665, 346, 952, 13, 2118, 1330, 20985, 201, 198, 6738, 4818, 8079, 1330, 4818, 8079, 201, 198, 6738, 5341, 633, 1330, 5341, 633, 201, 198, 6738, 384, 11925, 1505, 1330, 3992, 26230, 201...
2.08661
1,882
#!/usr/bin/env python import rospy import math import tf import geometry_msgs.msg from geometry_msgs.msg import PoseStamped from si_utils.lx_transformerROS import my_transformer if __name__ == '__main__': rospy.init_node('my_tf_listener') listener = tf.TransformListener() # my_trans = my_transformer() rate = rospy.Rate(10.0) while not rospy.is_shutdown(): try: # look1 = listener.lookupTransform('/left_ee_link', '/link1', rospy.Time(0)) # look2 = listener.lookupTransform('/base_link', '/left_ee_link', rospy.Time(0)) # look3 = listener.lookupTransform('/base_link', '/link1', rospy.Time(0)) # rospy.loginfo(look3) # rospy.loginfo(look2) pose = PoseStamped() pose.header.frame_id = '/link1' pose2 = listener.transformPose('/base_link', pose) rospy.loginfo(pose2) # (trans,rot) = listener.lookupTransform('/base_link', '/ar_marker_1', rospy.Time(0)) # (trans,rot) = listener.lookupTransform('/base_link', '/left_ee_link', rospy.Time(0)) # (trans1,rot1) = listener.lookupTransform('/movo_camera_color_optical_frame', '/ar_marker_17', rospy.Time(0)) # (trans,rot) = listener.lookupTransform('/base_link', '/movo_camera_color_optical_frame', rospy.Time(0)) # (trans,rot) = listener.lookupTransform('/movo_camera_color_optical_frame', '/base_link', rospy.Time(0)) # (trans,rot) = listener.lookupTransform('/base_link', '/ar_marker_1', rospy.Time(0)) # pose = PoseStamped() # pose.header.frame_id = 'ar_marker_1' # rospy.loginfo("========== First trans ===========") # pose1 = listener.transformPose('/movo_camera_color_optical_frame', pose) # rospy.loginfo(pose1) # rospy.loginfo("========== Second trans ===========") # rospy.loginfo(listener.transformPose('/base_link', pose1)) # print(trans) # print(rot) except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException): print('test') # rate.sleep() ''' pose = PoseStamped() pose.header.frame_id = '/ar_marker_17' rospy.loginfo("========== First trans ===========") listener.waitForTransform("/ar_marker_17", "/movo_camera_color_optical_frame", rospy.Time(), rospy.Duration(4.0)) pose1 = listener.transformPose('/movo_camera_color_optical_frame', pose) rospy.loginfo(pose1) rospy.loginfo("========== Second trans ===========") rospy.loginfo(listener.transformPose('/base_link', pose1)) pose_nutStart_nut = PoseStamped() pose_nutStart_nut.header.frame_id = '/nutStart' pose_nutStart_ar = my_trans.tf.transformPose('/ar_marker_17', pose_nutStart_nut) rospy.loginfo(pose_nutStart_ar) pose_nutStart_ca = listener.transformPose('/movo_camera_color_optical_frame', pose_nutStart_ar) rospy.loginfo(pose_nutStart_ca) '''
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 220, 220, 198, 11748, 686, 2777, 88, 198, 11748, 10688, 198, 11748, 48700, 198, 11748, 22939, 62, 907, 14542, 13, 19662, 198, 6738, 22939, 62, 907, 14542, 13, 19662, 1330, 37557, 1273, 13322,...
2.225331
1,358
#!/usr/bin/env python import argparse, subprocess, json, os, os.path, urllib2, sys, base64, binascii, time, \ hashlib, re, copy, textwrap #CA = "https://acme-staging.api.letsencrypt.org" CA = "https://acme-v01.api.letsencrypt.org" if __name__ == "__main__": parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent("""\ This script automates the process of getting a signed TLS certificate from Let's Encrypt using the ACME protocol. It will need to be run on your server and have access to your private account key, so PLEASE READ THROUGH IT! It's only ~200 lines, so it won't take long. ===Example Usage=== python acme_tiny.py --account-key ./account.key --csr ./domain.csr --acme-dir /usr/share/nginx/html/.well-known/acme-challenge/ > signed.crt =================== ===Example Crontab Renewal (once per month)=== 0 0 1 * * python /path/to/acme_tiny.py --account-key /path/to/account.key --csr /path/to/domain.csr --acme-dir /usr/share/nginx/html/.well-known/acme-challenge/ > /path/to/signed.crt 2>> /var/log/acme_tiny.log ============================================== """) ) parser.add_argument("--account-key", required=True, help="path to your Let's Encrypt account private key") parser.add_argument("--csr", required=True, help="path to your certificate signing request") parser.add_argument("--acme-dir", required=True, help="path to the .well-known/acme-challenge/ directory") args = parser.parse_args() signed_crt = get_crt(args.account_key, args.csr, args.acme_dir) sys.stdout.write(signed_crt)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 1822, 29572, 11, 850, 14681, 11, 33918, 11, 28686, 11, 28686, 13, 6978, 11, 2956, 297, 571, 17, 11, 25064, 11, 2779, 2414, 11, 9874, 292, 979, 72, 11, 640, 11, 3467, 198, 22...
2.563504
685
''' imput1: exome capture, biallelic indel matrix input2: exome capture, biallelic SNP matrix input3: GBS, biallelic indel matrix input4: GBS, biallelic SNP matrix input5: allele count file for exome homozygous or heterozygous genotype input6: allele count file for GBS homozygous or heterozygous genotype input7: tetraploid or octaploid ''' import sys,os import numpy as np exome_indel = open(sys.argv[1],'r').readlines() exome_snp = open(sys.argv[2],'r').readlines() gbs_indel = open(sys.argv[3],'r').readlines() gbs_snp = open(sys.argv[4],'r').readlines() EP = {} #EP[pos] = 1 for inl in exome_indel[1:]: tem = inl.split('\t') EP[tem[0] + '_' + tem[1]] = 1 for inl in exome_snp[1:]: tem = inl.split('\t') EP[tem[0] + '_' + tem[1]] = 1 S = {} #shared position, S[pos] = 1 for inl in gbs_indel[1:]: tem = inl.split('\t') if tem[0] + '_' + tem[1] in EP: S[tem[0] + '_' + tem[1]] = 1 for inl in gbs_snp[1:]: tem = inl.split('\t') if tem[0] + '_' + tem[1] in EP: S[tem[0] + '_' + tem[1]] = 1 E = {} # E[pos][ind] = A/T G = {} # G[pos][ind] = A/T EN = {} # EN[i] = ind GN = {} # GN[i] = ind IND = {} # IND[ind] = 1 tem = exome_indel[0].strip().split('\t') for i in range(4,len(tem)): EN[i] = tem[i] IND[tem[i]] = 1 tem = gbs_indel[0].strip().split('\t') for i in range(4,len(tem)): GN[i] = tem[i] for inl in exome_indel[1:]: tem = inl.strip().split('\t') if tem[0] + '_' + tem[1] in S: pos = tem[0] + '_' + tem[1] E[pos] = {} E[pos]['ref'] = tem[2] E[pos]['alt'] = tem[3] for i in range(4,len(tem)): E[pos][EN[i]] = tem[i] for inl in exome_snp[1:]: tem = inl.strip().split('\t') if tem[0] + '_' + tem[1] in S: pos = tem[0] + '_' + tem[1] E[pos] = {} E[pos]['ref'] = tem[2] E[pos]['alt'] = tem[3] for i in range(4,len(tem)): E[pos][EN[i]] = tem[i] for inl in gbs_indel[1:]: tem = inl.strip().split('\t') if tem[0] + '_' + tem[1] in S: pos = tem[0] + '_' + tem[1] G[pos] = {} G[pos]['ref'] = tem[2] G[pos]['alt'] = tem[3] for i in range(4,len(tem)): G[pos][GN[i]] = tem[i] for inl in gbs_snp[1:]: tem = inl.strip().split('\t') if tem[0] + '_' + tem[1] in S: pos = tem[0] + '_' + tem[1] G[pos] = {} G[pos]['ref'] = tem[2] G[pos]['alt'] = tem[3] for i in range(4,len(tem)): G[pos][GN[i]] = tem[i] out = open('Biallelic_variation_%s_Exome_VS_GBS.txt'%sys.argv[7],'w') Ind = sorted(IND.keys()) title = 'Chr\tPos\tRef\tAlt' for ind in Ind: title = title + '\t' + ind out.write(title + '\n') for pos in S: res = pos.split('_')[0] + '\t' + pos.split('_')[1] if E[pos]['ref'] == G[pos]['ref']: res = res + '\t' + E[pos]['ref'] else: res = res + '\t' + E[pos]['ref'] + '|' + G[pos]['ref'] if E[pos]['alt'] == G[pos]['alt']: res = res + '\t' + E[pos]['alt'] else: res = res + '\t' + E[pos]['alt'] + '|' + G[pos]['alt'] for ind in Ind: if E[pos][ind] == G[pos][ind] or (E[pos][ind].split('/')[0] == G[pos][ind].split('/')[1] and E[pos][ind].split('/')[1] == G[pos][ind].split('/')[0]): res = res + '\t' + E[pos][ind] else: res = res + '\t' + E[pos][ind] + '|' + G[pos][ind] out.write(res + '\n') out.close() ori_exome_indel = open(sys.argv[1],'r').readlines() ori_exome_snp = open(sys.argv[2],'r').readlines() ori_gbs_indel = open(sys.argv[3],'r').readlines() ori_gbs_snp = open(sys.argv[4],'r').readlines() ori_out = open('Shared_Biallelic_variation_%s_original_Exome_VS_GBS.txt'%sys.argv[7],'w') out = open('Distribution_of_discrepancy_Biallelic_variation_%s_between_exome_and_GBS.txt'%sys.argv[7],'w') ori_out.write(title + '\n') O_exome = {} O_gbs = {} EN = {} # EN[i] = ind GN = {} # GN[i] = ind tem = ori_exome_indel[0].strip().split('\t') for i in range(4,len(tem)): EN[i] = tem[i] IND[tem[i]] = 1 tem = ori_gbs_indel[0].strip().split('\t') for i in range(4,len(tem)): GN[i] = tem[i] for inl in ori_exome_indel[1:]: tem = inl.strip().split('\t') if tem[0] + '_' + tem[1] in S: pos = tem[0] + '_' + tem[1] O_exome[pos] = {} O_exome[pos]['ref'] = tem[2] O_exome[pos]['alt'] = tem[3] for i in range(4,len(tem)): O_exome[pos][EN[i]] = tem[i] for inl in ori_exome_snp[1:]: tem = inl.strip().split('\t') if tem[0] + '_' + tem[1] in S: pos = tem[0] + '_' + tem[1] O_exome[pos] = {} O_exome[pos]['ref'] = tem[2] O_exome[pos]['alt'] = tem[3] for i in range(4,len(tem)): O_exome[pos][EN[i]] = tem[i] for inl in ori_gbs_indel[1:]: tem = inl.strip().split('\t') if tem[0] + '_' + tem[1] in S: pos = tem[0] + '_' + tem[1] O_gbs[pos] = {} O_gbs[pos]['ref'] = tem[2] O_gbs[pos]['alt'] = tem[3] for i in range(4,len(tem)): O_gbs[pos][GN[i]] = tem[i] for inl in ori_gbs_snp[1:]: tem = inl.strip().split('\t') if tem[0] + '_' + tem[1] in S: pos = tem[0] + '_' + tem[1] O_gbs[pos] = {} O_gbs[pos]['ref'] = tem[2] O_gbs[pos]['alt'] = tem[3] for i in range(4,len(tem)): O_gbs[pos][GN[i]] = tem[i] if sys.argv[7] == 'octaploid': N1 = 0 ### Exome has variation, GBS is ./. N2 = 0 ### have same variation N3 = 0 ### Exome has heteo(AATT), GBS has homo N3_02 = 0 ### Exome has heteo(ATTT or AAAT), GBS has homo N3_03 = 0 ### Exome has heteo(ATTT or AAAT), GBS has hetero(AATT) N4 = 0 ### Exome is ./., GBS has variation N5 = 0 ### Exome has homo, GBS has heteo(AATT) N5_02 = 0 ### Exome has homo, GBS has heteo(ATTT or AAAT) N5_03 = 0 ### Exome has hetero(AATT), GBS has heteo(ATTT or AAAT) N5_04 = 0 ### Exome has hetero(ATTT), GBS has heteo(TTTA) N6 = 0 ### both are ./. N7 = 0 ### both homo but different variation out.write('Chr\tpos\tID\tExome_SNP\tGBS_SNP\tType\n') for pos in S: res = pos.split('_')[0] + '\t' + pos.split('_')[1] if O_exome[pos]['ref'] == O_gbs[pos]['ref']: res = res + '\t' + O_exome[pos]['ref'] else: res = res + '\t' + O_exome[pos]['ref'] + '|' + O_gbs[pos]['ref'] print(pos) if O_exome[pos]['alt'] == O_gbs[pos]['alt']: res = res + '\t' + O_exome[pos]['alt'] else: res = res + '\t' + O_exome[pos]['alt'] + '|' + O_gbs[pos]['alt'] print(pos) for ind in Ind: if O_exome[pos][ind] == O_gbs[pos][ind] or sorted(O_exome[pos][ind].split('/')) == sorted(O_gbs[pos][ind].split('/')): res = res + '\t' + O_exome[pos][ind] else: res = res + '\t' + O_exome[pos][ind] + '|' + O_gbs[pos][ind] ### have same SNPs, AATT == TTAA, ATTT == TTTA if (O_exome[pos][ind] == O_gbs[pos][ind] or sorted(O_exome[pos][ind].split('/')) == sorted(O_gbs[pos][ind].split('/'))) and O_exome[pos][ind]!= './././.': N2 += 1 ### both are ./. elif O_exome[pos][ind] == O_gbs[pos][ind] and O_exome[pos][ind]== './././.': N6 += 1 ### Exome has SNPs, GBS is ./. elif O_exome[pos][ind] != './././.' and O_gbs[pos][ind] == './././.': N1 += 1 ### Exome is ./., GBS has SNPs elif O_exome[pos][ind] == './././.' and O_gbs[pos][ind] != './././.': N4 += 1 ### Exome has homo, GBS has hetero(AATT) elif len(np.unique(O_exome[pos][ind].split('/'))) == 1 and len(np.unique(O_gbs[pos][ind].split('/'))) == 2 and O_exome[pos][ind]!= './.' and O_gbs[pos][ind].split('/')[1] != O_gbs[pos][ind].split('/')[2]: N5 += 1 out.write('%s\t%s\t%s\t%s\t%s\tExome_homo_GBS_hetero_AATT\n'%(pos.split('_')[0],pos.split('_')[1],ind,O_exome[pos][ind],O_gbs[pos][ind])) ### Exome has homo, GBS has hetero(ATTT or AAAT) elif len(np.unique(O_exome[pos][ind].split('/'))) == 1 and len(np.unique(O_gbs[pos][ind].split('/'))) == 2 and O_exome[pos][ind]!= './.' and O_gbs[pos][ind].split('/')[1] == O_gbs[pos][ind].split('/')[2]: N5_02 += 1 out.write('%s\t%s\t%s\t%s\t%s\tExome_homo_GBS_hetero_ATTT\n'%(pos.split('_')[0],pos.split('_')[1],ind,O_exome[pos][ind],O_gbs[pos][ind])) ### Exome has AATT, GBS has hetero(ATTT or AAAT) elif len(np.unique(O_exome[pos][ind].split('/'))) == 2 and len(np.unique(O_gbs[pos][ind].split('/'))) == 2 and O_gbs[pos][ind].split('/')[1] == O_gbs[pos][ind].split('/')[2] and O_exome[pos][ind].split('/')[1] != O_exome[pos][ind].split('/')[2]: N5_03 += 1 out.write('%s\t%s\t%s\t%s\t%s\tExome_hetero_AATT_GBS_hetero_ATTT\n'%(pos.split('_')[0],pos.split('_')[1],ind,O_exome[pos][ind],O_gbs[pos][ind])) ### Exome has ATTT, GBS has heteroTTTA elif len(np.unique(O_exome[pos][ind].split('/'))) == 2 and len(np.unique(O_gbs[pos][ind].split('/'))) == 2 and O_gbs[pos][ind].split('/')[1] == O_gbs[pos][ind].split('/')[2] and O_exome[pos][ind].split('/')[1] == O_exome[pos][ind].split('/')[2] and sorted(O_exome[pos][ind].split('/')) != sorted(O_gbs[pos][ind].split('/')): N5_04 += 1 out.write('%s\t%s\t%s\t%s\t%s\tExome_hetero_ATTT_GBS_hetero_AAAT\n'%(pos.split('_')[0],pos.split('_')[1],ind,O_exome[pos][ind],O_gbs[pos][ind])) ### Exome has hetero(AATT), GBS has homo elif len(np.unique(O_exome[pos][ind].split('/'))) == 2 and len(np.unique(O_gbs[pos][ind].split('/'))) == 1 and O_exome[pos][ind].split('/')[1] != O_exome[pos][ind].split('/')[2] and O_gbs[pos][ind] != './.': N3 += 1 out.write('%s\t%s\t%s\t%s\t%s\tExome_hetero_AATT_GBS_homo\n'%(pos.split('_')[0],pos.split('_')[1],ind,O_exome[pos][ind],O_gbs[pos][ind])) ### Exome has hetero(ATTT or AAAT), GBS has homo elif len(np.unique(O_exome[pos][ind].split('/'))) == 2 and len(np.unique(O_gbs[pos][ind].split('/'))) == 1 and O_exome[pos][ind].split('/')[1] == O_exome[pos][ind].split('/')[2] and O_gbs[pos][ind] != './.': N3_02 += 1 out.write('%s\t%s\t%s\t%s\t%s\tExome_hetero_ATTT_GBS_homo\n'%(pos.split('_')[0],pos.split('_')[1],ind,O_exome[pos][ind],O_gbs[pos][ind])) ### Exome has hetero(ATTT or AAAT), GBS has hetero(AATT) elif len(np.unique(O_exome[pos][ind].split('/'))) == 2 and len(np.unique(O_gbs[pos][ind].split('/'))) == 2 and O_exome[pos][ind].split('/')[1] == O_exome[pos][ind].split('/')[2] and O_gbs[pos][ind].split('/')[1] != O_gbs[pos][ind].split('/')[2] : N3_03 += 1 out.write('%s\t%s\t%s\t%s\t%s\tExome_hetero_ATTT_GBS_hetero_AATT\n'%(pos.split('_')[0],pos.split('_')[1],ind,O_exome[pos][ind],O_gbs[pos][ind])) ### both homo, but diff elif len(np.unique(O_exome[pos][ind].split('/'))) == 1 and len(np.unique(O_gbs[pos][ind].split('/'))) == 1 and O_exome[pos][ind]!=O_gbs[pos][ind] and O_exome[pos][ind] != './././.' and O_gbs[pos][ind]!= './././.': N7 += 1 print([O_exome[pos][ind],O_gbs[pos][ind]]) out.write('%s\t%s\t%s\t%s\t%s\tBoth_homo_differ\n'%(pos.split('_')[0],pos.split('_')[1],ind,O_exome[pos][ind],O_gbs[pos][ind])) ori_out.write(res + '\n') ori_out.close() out.close() print([N1,N2,N3,N3_02,N3_03,N4,N5,N5_02,N5_03,N5_04,N6,N7]) if sys.argv[7] == 'tetraploid': N1 = 0 ### Exome has SNPs, GBS is ./. N2 = 0 ### have same SNPs N3 = 0 ### Exome has heteo, GBS has homo N4 = 0 ### Exome is ./., GBS has SNPs N5 = 0 ### Exome has homo, GBS has heteo N6 = 0 ### both are ./. N7 = 0 ### both homo but different SNPs out.write('Chr\tpos\tID\tExome_SNP\tGBS_SNP\tType\n') for pos in S: res = pos.split('_')[0] + '\t' + pos.split('_')[1] if O_exome[pos]['ref'] == O_gbs[pos]['ref']: res = res + '\t' + O_exome[pos]['ref'] else: res = res + '\t' + O_exome[pos]['ref'] + '|' + O_gbs[pos]['ref'] if O_exome[pos]['alt'] == O_gbs[pos]['alt']: res = res + '\t' + O_exome[pos]['alt'] else: res = res + '\t' + O_exome[pos]['alt'] + '|' + O_gbs[pos]['alt'] for ind in Ind: if O_exome[pos][ind] == O_gbs[pos][ind] or (O_exome[pos][ind].split('/')[0] == O_gbs[pos][ind].split('/')[1] and O_exome[pos][ind].split('/')[1] == O_gbs[pos][ind].split('/')[0]): res = res + '\t' + O_exome[pos][ind] else: res = res + '\t' + O_exome[pos][ind] + '|' + O_gbs[pos][ind] ### have same SNPs if (O_exome[pos][ind] == O_gbs[pos][ind] or (O_exome[pos][ind].split('/')[0] == O_gbs[pos][ind].split('/')[1] and O_exome[pos][ind].split('/')[1] == O_gbs[pos][ind].split('/')[0])) and O_exome[pos][ind]!= './.': N2 += 1 ### both are ./. elif O_exome[pos][ind] == O_gbs[pos][ind] and O_exome[pos][ind]== './.': N6 += 1 ### Exome has SNPs, GBS is ./. elif O_exome[pos][ind] != './.' and O_gbs[pos][ind] == './.': N1 += 1 ### Exome is ./., GBS has SNPs elif O_exome[pos][ind] == './.' and O_gbs[pos][ind] != './.': N4 += 1 ### Exome has homo, GBS has hetero elif O_exome[pos][ind].split('/')[0] == O_exome[pos][ind].split('/')[1] and O_exome[pos][ind]!= './.' and O_gbs[pos][ind].split('/')[0] != O_gbs[pos][ind].split('/')[1]: N5 += 1 out.write('%s\t%s\t%s\t%s\t%s\tExome_homo_GBS_hetero\n'%(pos.split('_')[0],pos.split('_')[1],ind,O_exome[pos][ind],O_gbs[pos][ind])) ### Exome has hetero, GBS has homo elif O_exome[pos][ind].split('/')[0] != O_exome[pos][ind].split('/')[1] and O_gbs[pos][ind].split('/')[0] == O_gbs[pos][ind].split('/')[1] and O_gbs[pos][ind] != './.': N3 += 1 out.write('%s\t%s\t%s\t%s\t%s\tExome_hetero_GBS_homo\n'%(pos.split('_')[0],pos.split('_')[1],ind,O_exome[pos][ind],O_gbs[pos][ind])) else: N7 += 1 print([O_exome[pos][ind],O_gbs[pos][ind]]) out.write('%s\t%s\t%s\t%s\t%s\tBoth_homo_differ\n'%(pos.split('_')[0],pos.split('_')[1],ind,O_exome[pos][ind],O_gbs[pos][ind])) ori_out.write(res + '\n') ori_out.close() out.close() print([N1,N2,N3,N4,N5,N6,N7]) inp = open('Distribution_of_discrepancy_Biallelic_variation_%s_between_exome_and_GBS.txt'%sys.argv[7],'r').readlines() out = open('Distribution_of_discrepancy_Biallelic_variation_%s_between_exome_and_GBS_alle_count.txt'%sys.argv[7],'w') P = {} for inl in inp[1:]: tem = inl.split('\t') chr = tem[0] pos = tem[1] ind = tem[2] if chr not in P: P[chr] = {} if pos not in P[chr]: P[chr][pos] = {} if ind not in P[chr][pos]: P[chr][pos][ind] = [0,0,0,0] Exome = open(sys.argv[5],'r') inl = Exome.readline() inl = Exome.readline() while inl: tem = inl.split('\t') chr = tem[0] pos = tem[1] ind = tem[2] if chr in P: if pos in P[chr]: if ind in P[chr][pos]: P[chr][pos][ind][0] = int(tem[6]) P[chr][pos][ind][1] = int(tem[7]) inl = Exome.readline() GBS = open(sys.argv[6],'r') inl = GBS.readline() inl = GBS.readline() while inl: tem = inl.split('\t') chr = tem[0] pos = tem[1] ind = tem[2] if chr in P: if pos in P[chr]: if ind in P[chr][pos]: P[chr][pos][ind][2] = int(tem[6]) P[chr][pos][ind][3] = int(tem[7]) inl = GBS.readline() out.write('Chr\tPos\tInd\tExome_SNP\tGBS_SNP\tType\tExome_alle_count\tExome_read_count\tGBS_alle_count\tGBS_read_count\n') for inl in inp[1:]: tem = inl.split('\t') chr = tem[0] pos = tem[1] ind = tem[2] if chr not in P: P[chr] = {} if pos not in P[chr]: P[chr][pos] = {} if ind not in P[chr][pos]: P[chr][pos][ind] = [0,0,0,0] out.write('%s\t%s\t%s\t%s\t%s\n'%(inl.strip(),P[chr][pos][ind][0],P[chr][pos][ind][1],P[chr][pos][ind][2],P[chr][pos][ind][3])) out.close()
[ 7061, 6, 198, 320, 1996, 16, 25, 409, 462, 8006, 11, 275, 498, 293, 677, 773, 417, 17593, 198, 15414, 17, 25, 409, 462, 8006, 11, 275, 498, 293, 677, 25632, 17593, 198, 15414, 18, 25, 402, 4462, 11, 275, 498, 293, 677, 773, 417,...
1.898553
7,738
from pyradioconfig.parts.bobcat.calculators.calc_frame import Calc_Frame_Bobcat
[ 6738, 279, 2417, 9189, 36221, 5647, 13, 42632, 13, 65, 672, 9246, 13, 9948, 3129, 2024, 13, 9948, 66, 62, 14535, 1330, 2199, 66, 62, 19778, 62, 18861, 9246 ]
2.724138
29
import glob import subprocess import os import argparse import shutil input_parser = argparse.ArgumentParser( description="Run RegTools stats script", ) input_parser.add_argument( 'tag', help="Variant tag parameter used to run RegTools.", ) args = input_parser.parse_args() tag = args.tag cwd = os.getcwd() lines_per_file = 25000 smallfile = None with open(f'all_splicing_variants_{tag}.bed', 'r') as bigfile: header = bigfile.readline() for lineno, line in enumerate(bigfile): if lineno % lines_per_file == 0: if smallfile: smallfile.close() small_filename = 'small_file_{}.txt'.format(lineno + lines_per_file) smallfile = open(small_filename, "w") smallfile.write(header) smallfile.write(line) if smallfile: smallfile.close() #get chunks files = glob.glob('small_file_*') files.sort() number_of_in_files = len(files) for file in files: subprocess.run(f'Rscript --vanilla compare_junctions_hist_v2.R {tag} {file}', shell=True, check=True) output_files = glob.glob("*_out.tsv") output_files.sort()# glob lacks reliable ordering, so impose your own if output order matters number_of_out_files = len(output_files) if number_of_in_files == number_of_out_files: with open(f'compare_junctions/hist/junction_pvalues_{tag}.tsv', 'wb') as outfile: for i, fname in enumerate(output_files): with open(fname, 'rb') as infile: if i != 0: infile.readline() # Throw away header on all but first file # Block copy rest of file from input to output without parsing shutil.copyfileobj(infile, outfile) print(fname + " has been imported.") else: print("Number of output files doesn't match the number of input files that should have been processed") files = glob.glob('small_file_*') for file in files: os.remove(file)
[ 11748, 15095, 198, 11748, 850, 14681, 198, 11748, 28686, 198, 11748, 1822, 29572, 198, 11748, 4423, 346, 198, 198, 15414, 62, 48610, 796, 1822, 29572, 13, 28100, 1713, 46677, 7, 198, 220, 220, 220, 6764, 2625, 10987, 3310, 33637, 9756, ...
2.483995
781
import numpy as np import matplotlib.pyplot as plt import os
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 28686 ]
3.157895
19
# Copyright (C) 2018-2019 Tormod Landet # SPDX-License-Identifier: Apache-2.0 """ A timeout context manager based on SIGALRM, Permits multiple SIGALRM events to be queued. Uses a `heapq` to store the objects to be called when an alarm signal is raised, so that the next alarm is always at the top of the heap. Note: SIGALRM does not work on Windows! Code from ActiveState Python recipes http://code.activestate.com/recipes/577600-queue-for-managing-multiple-sigalrm-alarms-concurr/ modified by stackoverflow user "James": https://stackoverflow.com/a/34999808 """ import heapq import signal from time import time alarmlist = [] def __clear_alarm(): """ Clear an existing alarm. If the alarm signal was set to a callable other than our own, queue the previous alarm settings. """ oldsec = signal.alarm(0) oldfunc = signal.signal(signal.SIGALRM, __alarm_handler) if oldsec > 0 and oldfunc != __alarm_handler: heapq.heappush(alarmlist, (__new_alarm(oldsec, oldfunc, [], {}))) def __alarm_handler(*_args): """ Handle an alarm by calling any due heap entries and resetting the alarm. Note that multiple heap entries might get called, especially if calling an entry takes a lot of time. """ try: nextt = __next_alarm() while nextt is not None and nextt <= 0: (_tm, func, args, keys) = heapq.heappop(alarmlist) func(*args, **keys) nextt = __next_alarm() finally: if alarmlist: __set_alarm() def alarm(sec, func, *args, **keys): """ Set an alarm. When the alarm is raised in `sec` seconds, the handler will call `func`, passing `args` and `keys`. Return the heap entry (which is just a big tuple), so that it can be cancelled by calling `cancel()`. """ __clear_alarm() try: newalarm = __new_alarm(sec, func, args, keys) heapq.heappush(alarmlist, newalarm) return newalarm finally: __set_alarm() def cancel(alarm): """ Cancel an alarm by passing the heap entry returned by `alarm()`. It is an error to try to cancel an alarm which has already occurred. """ __clear_alarm() try: alarmlist.remove(alarm) heapq.heapify(alarmlist) finally: if alarmlist: __set_alarm()
[ 2, 15069, 357, 34, 8, 2864, 12, 23344, 309, 579, 375, 6379, 316, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 37811, 198, 32, 26827, 4732, 4706, 1912, 319, 33993, 1847, 29138, 11, 2448, 24883, 329...
2.58022
910
import folium import altair as alt import leafmap.foliumap as leafmap import pandas as pd import streamlit as st
[ 11748, 5955, 1505, 198, 11748, 5988, 958, 355, 5988, 198, 11748, 12835, 8899, 13, 9062, 1505, 499, 355, 12835, 8899, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 4269, 18250, 355, 336, 628 ]
3.352941
34
from utils import LOG_INFO import numpy as np
[ 6738, 3384, 4487, 1330, 41605, 62, 10778, 198, 11748, 299, 32152, 355, 45941, 628, 198 ]
3.2
15
# ----------- # User Instructions # # Modify the valid_month() function to verify # whether the data a user enters is a valid # month. If the passed in parameter 'month' # is not a valid month, return None. # If 'month' is a valid month, then return # the name of the month with the first letter # capitalized. # import string import cgi months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
[ 2, 24200, 6329, 198, 2, 11787, 27759, 198, 2, 220, 198, 2, 3401, 1958, 262, 4938, 62, 8424, 3419, 2163, 284, 11767, 220, 198, 2, 1771, 262, 1366, 257, 2836, 14170, 318, 257, 4938, 220, 198, 2, 1227, 13, 1002, 262, 3804, 287, 11507...
2.339921
253
import sys import weakref import json import logging from .utils import opt_json, Response2JSONLinesIterator from six import StringIO log = logging.getLogger(__name__)
[ 11748, 25064, 198, 11748, 4939, 5420, 198, 11748, 33918, 198, 11748, 18931, 198, 6738, 764, 26791, 1330, 2172, 62, 17752, 11, 18261, 17, 40386, 43, 1127, 37787, 198, 6738, 2237, 1330, 10903, 9399, 198, 198, 6404, 796, 18931, 13, 1136, 1...
3.489796
49
#-*- coding:utf-8 -*- #''' # Created on 19-7-16 2:14 # # @Author: Greg Gao(laygin) #''' from .synth_text import SynthTextConfig, SynthTextDataset from .icdar13 import IcdarConfig, IcdarDataset from .img_aug import resize_image
[ 2, 12, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 2, 7061, 6, 198, 2, 15622, 319, 678, 12, 22, 12, 1433, 362, 25, 1415, 198, 2, 198, 2, 2488, 13838, 25, 8547, 402, 5488, 7, 10724, 1655, 8, 198, 2, 7061, 6, 198, 6738...
2.430108
93
from alberto.annotation import annotation_set from pandas import np from deepposekit.io import TrainingGenerator, DataGenerator from deepposekit.augment import FlipAxis import imgaug.augmenters as iaa import imgaug as ia from deepposekit.models import StackedHourglass from deepposekit.models import load_model import matplotlib.pyplot as plt from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping from deepposekit.callbacks import Logger, ModelCheckpoint import time from os.path import expanduser HOME = annotation_set.HOME IMAGE_SIZE = annotation_set.IMAGE_SIZE TYPE = annotation_set.TYPE data_generator = DataGenerator( datapath=HOME + '/deepposekit-data/datasets/{}/annotation_set_{}_{}.h5'.format(TYPE, IMAGE_SIZE[0], IMAGE_SIZE[1])) image, keypoints = data_generator[0] plt.figure(figsize=(5, 5)) image = image[0] if image.shape[-1] is 3 else image[0, ..., 0] cmap = None if image.shape[-1] is 3 else 'gray' plt.imshow(image, cmap=cmap, interpolation='none') for idx, jdx in enumerate(data_generator.graph): if jdx > -1: x1 = keypoints[0, idx, 0] x2 = keypoints[0, jdx, 0] if (0 <= x1 <= IMAGE_SIZE[0]) and (0 <= x2 <= IMAGE_SIZE[0]): plt.plot( [keypoints[0, idx, 0], keypoints[0, jdx, 0]], [keypoints[0, idx, 1], keypoints[0, jdx, 1]], 'r-' ) plt.scatter(keypoints[0, :, 0], keypoints[0, :, 1], c=np.arange(data_generator.keypoints_shape[0]), s=50, cmap=plt.cm.hsv, zorder=3) plt.show() # Augmentation augmenter = [] augmenter.append(FlipAxis(data_generator, axis=0)) # flip image up-down augmenter.append(FlipAxis(data_generator, axis=1)) # flip image left-right sometimes = [] sometimes.append(iaa.Affine(scale={"x": (0.95, 1.05), "y": (0.95, 1.05)}, translate_percent={'x': (-0.05, 0.05), 'y': (-0.05, 0.05)}, shear=(-8, 8), order=ia.ALL, cval=ia.ALL, mode=ia.ALL) ) sometimes.append(iaa.Affine(scale=(0.8, 1.2), mode=ia.ALL, order=ia.ALL, cval=ia.ALL) ) augmenter.append(iaa.Sometimes(0.75, sometimes)) augmenter.append(iaa.Affine(rotate=(-180, 180), mode=ia.ALL, order=ia.ALL, cval=ia.ALL) ) augmenter = iaa.Sequential(augmenter) # image, keypoints = data_generator[0] # image, keypoints = augmenter(images=image, keypoints=keypoints) # plt.figure(figsize=(5, 5)) # image = image[0] if image.shape[-1] is 3 else image[0, ..., 0] # cmap = None if image.shape[-1] is 3 else 'gray' # plt.imshow(image, cmap=cmap, interpolation='none') # for idx, jdx in enumerate(data_generator.graph): # if jdx > -1: # x1 = keypoints[0, idx, 0] # x2 = keypoints[0, jdx, 0] # if (0 <= x1 <= IMAGE_SIZE[0]) and (0 <= x2 <= IMAGE_SIZE[0]): # plt.plot( # [keypoints[0, idx, 0], keypoints[0, jdx, 0]], # [keypoints[0, idx, 1], keypoints[0, jdx, 1]], # 'r-' # ) plt.scatter(keypoints[0, :, 0], keypoints[0, :, 1], c=np.arange(data_generator.keypoints_shape[0]), s=50, cmap=plt.cm.hsv, zorder=3) # plt.show() train_generator = TrainingGenerator(generator=data_generator, downsample_factor=3, augmenter=augmenter, sigma=5, validation_split=0, use_graph=False, random_seed=1, graph_scale=1) train_generator.get_config() # n_keypoints = data_generator.keypoints_shape[0] # batch = train_generator(batch_size=1, validation=False)[0] # inputs = batch[0] # outputs = batch[1] # fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(10, 10)) # ax1.set_title('image') # ax1.imshow(inputs[0, ..., 0], vmin=0, vmax=255) # # ax2.set_title('posture graph') # ax2.imshow(outputs[0, ..., n_keypoints:-1].max(-1)) # # ax3.set_title('keypoints confidence') # ax3.imshow(outputs[0, ..., :n_keypoints].max(-1)) # # ax4.set_title('posture graph and keypoints confidence') # ax4.imshow(outputs[0, ..., -1], vmin=0) # plt.show() train_generator.on_epoch_end() # Define a model model = StackedHourglass(train_generator) model.get_config() # data_size = (10,) + data_generator.image_shape # x = np.random.randint(0, 255, data_size, dtype="uint8") # y = model.predict(x[:100], batch_size=100) # make sure the model is in GPU memory # t0 = time.time() # y = model.predict(x, batch_size=100, verbose=1) # t1 = time.time() # print(x.shape[0] / (t1 - t0)) # logger = Logger(validation_batch_size=10, # # filepath saves the logger data to a .h5 file # filepath=HOME + "/deepposekit-data/datasets/{}/log_densenet.h5".format(TYPE) # ) # Remember, if you set validation_split=0 for your TrainingGenerator, # which will just use the training set for model fitting, # make sure to set monitor="loss" instead of monitor="val_loss". reduce_lr = ReduceLROnPlateau(monitor="loss", factor=0.2, verbose=1, patience=20) model_checkpoint = ModelCheckpoint( HOME + "/deepposekit-data/datasets/{}/model_densenet.h5".format(TYPE), monitor="loss", # monitor="loss" # use if validation_split=0 verbose=1, save_best_only=True, ) early_stop = EarlyStopping( monitor="loss", # monitor="loss" # use if validation_split=0 min_delta=0.001, patience=100, verbose=1 ) callbacks = [early_stop, reduce_lr, model_checkpoint] model.fit( batch_size=5, validation_batch_size=10, callbacks=callbacks, # epochs=1000, # Increase the number of epochs to train the model longer epochs=50, n_workers=8, steps_per_epoch=None, ) # model = load_model( # HOME + "/deepposekit-data/datasets/{}/model_densenet.h5".format(TYPE), # augmenter=augmenter, # generator=data_generator, # ) # # model.fit( # batch_size=2, # validation_batch_size=10, # callbacks=callbacks, # epochs=50, # n_workers=8, # steps_per_epoch=None, # )
[ 6738, 435, 32371, 13, 1236, 14221, 1330, 23025, 62, 2617, 198, 6738, 19798, 292, 1330, 45941, 198, 198, 6738, 390, 68, 381, 577, 15813, 13, 952, 1330, 13614, 8645, 1352, 11, 6060, 8645, 1352, 198, 6738, 390, 68, 381, 577, 15813, 13, ...
2.020919
3,155
from .base import * from dotenv import load_dotenv load_dotenv(dotenv_path='northpole/.staging.env', verbose=True) ALLOWED_HOSTS = ['*'] EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.getenv('POSTGRES_DB', 'northpole-staging'), 'USER': os.getenv('POSTGRES_USER'), 'PASSWORD': os.getenv('POSTGRES_PASSWORD'), 'HOST': os.getenv('POSTGRES_HOST'), 'PORT': os.getenv('POSTGRES_PORT', '5432'), } } STATIC_ROOT = os.path.join(BASE_DIR, '..', 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, '..', 'static_source'), ) MEDIA_ROOT = os.path.join(BASE_DIR, '..' 'media') MEDIA_URL = '/media/'
[ 6738, 764, 8692, 1330, 1635, 198, 198, 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 198, 2220, 62, 26518, 24330, 7, 26518, 24330, 62, 6978, 11639, 43588, 36869, 11757, 301, 3039, 13, 24330, 3256, 15942, 577, 28, 17821, 8, 628, 198,...
2.149296
355
#!/usr/bin/env python # # Copyright 2014 Corgan Labs # See LICENSE.txt for distribution terms # from bc4py.bip32.base58 import check_decode, check_encode from bc4py_extension import PyAddress from ecdsa.curves import SECP256k1 from ecdsa.keys import SigningKey, VerifyingKey, square_root_mod_prime as mod_sqrt from ecdsa.ecdsa import generator_secp256k1, int_to_string from ecdsa.ellipticcurve import Point, INFINITY from os import urandom import hmac import hashlib import codecs import struct CURVE_GEN = generator_secp256k1 # Point class CURVE_ORDER = CURVE_GEN.order() # int FIELD_ORDER = SECP256k1.curve.p() # int MIN_ENTROPY_LEN = 128 # bits BIP32_HARDEN = 0x80000000 # choose from hardened set of child keys EX_MAIN_PRIVATE = [codecs.decode('0488ade4', 'hex')] # Version strings for mainnet extended private keys EX_MAIN_PUBLIC = [codecs.decode('0488b21e', 'hex'), codecs.decode('049d7cb2', 'hex')] # Version strings for mainnet extended public keys EX_TEST_PRIVATE = [codecs.decode('04358394', 'hex')] # Version strings for testnet extended private keys EX_TEST_PUBLIC = [codecs.decode('043587CF', 'hex')] # Version strings for testnet extended public keys WALLET_VERSION = b'\x80' def CKDpriv(self, i): """ Create a child key of index 'i'. If the most significant bit of 'i' is set, then select from the hardened key set, otherwise, select a regular child key. Returns a BIP32Key constructed with the child key parameters, or None if i index would result in an invalid key. """ # Index as bytes, BE i_str = struct.pack(">L", i) # Data to HMAC if i & BIP32_HARDEN: data = b'\0' + self.get_private_key() + i_str path = self.path + '/' + str(i % BIP32_HARDEN) + '\'' else: data = self.get_public_key() + i_str path = self.path + '/' + str(i) # Get HMAC of data (Il, Ir) = self._hmac(data) # Construct new key material from Il and current private key Il_int = int.from_bytes(Il, 'big') if Il_int > CURVE_ORDER: return None sec_int = int.from_bytes(self.secret.to_string(), 'big') k_int = (Il_int + sec_int) % CURVE_ORDER if k_int == 0: return None # Construct and return a new BIP32Key secret = SigningKey.from_string(int_to_string(k_int), SECP256k1) public = secret.verifying_key return Bip32(secret=secret, public=public, chain=Ir, depth=self.depth + 1, index=i, fpr=self.fingerprint(), path=path) def CKDpub(self, i): """ Create a publicly derived child key of index 'i'. If the most significant bit of 'i' is set, this is an error. Returns a BIP32Key constructed with the child key parameters, or None if index would result in invalid key. """ if i & BIP32_HARDEN: raise Exception("Cannot create a hardened child key using public child derivation") # Data to HMAC. Same as CKDpriv() for public child key. data = self.get_public_key() + struct.pack(">L", i) # Get HMAC of data (Il, Ir) = self._hmac(data) # Construct curve point Il*G+K Il_int = int.from_bytes(Il, 'big') if Il_int >= CURVE_ORDER: return None point = Il_int*CURVE_GEN + self.public.pubkey.point if point == INFINITY: return None public = VerifyingKey.from_public_point(point, SECP256k1) # Construct and return a new BIP32Key path = self.path + '/' + str(i) return Bip32( secret=None, public=public, chain=Ir, depth=self.depth + 1, index=i, fpr=self.fingerprint(), path=path) def child_key(self, i): """ Create and return a child key of this one at index 'i'. The index 'i' should be summed with BIP32_HARDEN to indicate to use the private derivation algorithm. """ if self.secret is None: return self.CKDpub(i) else: return self.CKDpriv(i) def get_address(self, hrp, ver) -> PyAddress: """Return bech32 compressed address""" return PyAddress.from_param(hrp, ver, self.identifier()) def identifier(self): """Return key identifier as string""" pk = self.get_public_key() return hashlib.new('ripemd160', hashlib.sha256(pk).digest()).digest() def fingerprint(self): """Return key fingerprint as string""" return self.identifier()[:4] def extended_key(self, is_private=True, encoded=True, is_testnet=False): """Return extended private or public key as string, optionally base58 encoded""" if self.secret is None and is_private is True: raise Exception("Cannot export an extended private key from a public-only deterministic key") if is_testnet: version = EX_TEST_PRIVATE[0] if is_private else EX_TEST_PUBLIC[0] else: version = EX_MAIN_PRIVATE[0] if is_private else EX_MAIN_PUBLIC[0] depth = self.depth.to_bytes(1, 'big') fpr = self.parent_fpr child = struct.pack('>L', self.index) chain = self.chain if self.secret is None or is_private is False: # startswith b'\x02' or b'\x03' data = self.get_public_key() else: # startswith b'\x00' data = b'\x00' + self.get_private_key() if encoded: return check_encode(version + depth + fpr + child + chain + data) else: return depth + fpr + child + chain + data def wallet_import_format(self, prefix=WALLET_VERSION): """Returns private key encoded for wallet import""" if self.secret is None: raise Exception("Publicly derived deterministic keys have no private half") raw = prefix + self.get_private_key() + b'\x01' # Always compressed return check_encode(raw) def dump(self): """Dump key fields mimicking the BIP0032 test vector format""" print(" * Identifier") print(" * (hex): ", self.identifier().hex()) print(" * (fpr): ", self.fingerprint().hex()) print(" * (main addr):", self.get_address('bc', 0)) print(" * (path): ", self.path) if self.secret: print(" * Secret key") print(" * (hex): ", self.get_private_key().hex()) print(" * (wif): ", self.wallet_import_format()) print(" * Public key") print(" * (hex): ", self.get_public_key().hex()) print(" * Chain code") print(" * (hex): ", self.chain.hex()) print(" * Serialized") print(" * (pub hex): ", self.extended_key(is_private=False, encoded=False).hex()) print(" * (pub b58): ", self.extended_key(is_private=False, encoded=True)) if self.secret: print(" * (prv hex): ", self.extended_key(is_private=True, encoded=False).hex()) print(" * (prv b58): ", self.extended_key(is_private=True, encoded=True)) def parse_bip32_path(path): """parse BIP32 format""" r = list() for s in path.split('/'): if s == 'm': continue elif s.endswith("'") or s.endswith('h'): r.append(int(s[:-1]) + BIP32_HARDEN) else: r.append(int(s)) return r def struct_bip32_path(path): """struct BIP32 string path""" s = 'm' for p in path: if p & BIP32_HARDEN: s += "/{}'".format(p % BIP32_HARDEN) else: s += "/{}".format(p) return s __all__ = [ "BIP32_HARDEN", "Bip32", "parse_bip32_path", "struct_bip32_path", ]
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 15069, 1946, 2744, 1030, 23500, 198, 2, 4091, 38559, 24290, 13, 14116, 329, 6082, 2846, 198, 2, 198, 198, 6738, 47125, 19, 9078, 13, 65, 541, 2624, 13, 8692, 3365, 1330, ...
2.236016
3,504
import random from loguru import logger from lib.vars.vars import conf, th, paths from lib.vars.ua import UA_LIST
[ 11748, 4738, 198, 6738, 2604, 14717, 1330, 49706, 198, 6738, 9195, 13, 85, 945, 13, 85, 945, 1330, 1013, 11, 294, 11, 13532, 198, 6738, 9195, 13, 85, 945, 13, 6413, 1330, 46164, 62, 45849, 628, 628, 628, 628, 628 ]
3.075
40
import numpy as np from sympy import * from math import * from timeit import default_timer as timer start = None end = None A = np.matrix(eval(input("Digite uma matriz : "))) A = A.astype(float) X = np.matrix(eval(input("Digite X : "))) e = float(input("Digite a preciso: ")) B = np.copy(A[:,A.shape[1]-1]) A = np.delete(np.copy(A),A.shape[1]-1,1) C = np.asmatrix(np.zeros([A.shape[0],A.shape[1]])) C = C.astype(float) G = np.copy(B) for i in range(C.shape[0]): for j in range(C.shape[1]): if i != j: C[i,j] = (np.copy(A[i,j])/np.copy(A[i,i]))*(-1) G[i,0] = (np.copy(G[i,0]))/(np.copy(A[i,i])) C[i,i] = 0 Xn = None z = True print("Matriz C:\n",C) print("Matriz G:\n",G) start = timer() while(z): Xn = (np.copy(C) @ np.copy(X)) + np.copy(G) d = maxXi(np.copy(Xn),np.copy(X)) if(d < e): z = False else: X = np.copy(Xn) end = timer() print("Resposta de Gauss-Jacobi: ") print(Xn) print("Tempo de execucao total: %e segundos" % (end - start))
[ 11748, 299, 32152, 355, 45941, 198, 6738, 10558, 88, 1330, 1635, 198, 6738, 10688, 1330, 1635, 198, 198, 6738, 640, 270, 1330, 4277, 62, 45016, 355, 19781, 198, 198, 9688, 796, 6045, 198, 437, 796, 6045, 628, 198, 32, 796, 45941, 13, ...
1.969052
517
import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import numpy as np
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 2603, 29487, 8019, 13, 4033, 669, 1330, 406, 6347, 5216, 579, 499, 198, 11748, 299, 32152, 355, 45941, 198 ]
3.096774
31
import sys if __name__ == "__main__": if len(sys.argv) == 1: nums = [int(e) for e in input('>>> Enter the numbers with comma-separeted: ').split(',')] print(square_sum(numbers=nums)) else: sys.exit(1)
[ 11748, 25064, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 611, 18896, 7, 17597, 13, 853, 85, 8, 6624, 352, 25, 198, 220, 220, 220, 220, 220, 220, 220, 997, 82, 796, 685, 600, 7, 68...
2.136364
110
import os import pickle from abc import ABC, abstractmethod import h5py import numpy as np from .folders import get_pickle_lazy_loader_data_path, hdf5_lazy_loader_data_path from .unpickler import CustomUnpickler def load_data(self, store_precomputation_on_disk=True): if self.associated_instance is None: raise ValueError(f'self.associated_instance = {self.associated_instance}') if not self.has_data_already_been_precomputed(): # print('precomputing') data = self.precompute() if data is None: raise ValueError(f'data = {data}') if store_precomputation_on_disk: self._save_data(data) return data else: # print('loading') return self._load_precomputed_data() if not os.path.isfile(hdf5_lazy_loader_data_path): f = h5py.File(hdf5_lazy_loader_data_path, 'w') f.close() if __name__ == '__main__': from spatial_ops.data import JacksonFischerDataset as jfd from spatial_ops.data import Patient patient = jfd.patients[15] derived_quantity = NumberOfPlatesLoader0(patient) print(derived_quantity.load_data()) derived_quantity = NumberOfPlatesLoader1(patient) # derived_quantity.delete_precomputation() print(derived_quantity.load_data())
[ 11748, 28686, 198, 11748, 2298, 293, 198, 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 198, 11748, 289, 20, 9078, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 764, 11379, 364, 1330, 651, 62, 27729, 293, 62, 75, 12582, 62, ...
2.353147
572
# @date 2020-01-31 # @author Frederic Scherma, All rights reserved without prejudices. # @license Copyright (c) 2020 Dream Overflow # Binance Websocket connector. import json import threading import traceback from autobahn.twisted.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS from twisted.internet import ssl, reactor # , reactor from twisted.internet.protocol import ReconnectingClientFactory from connector.binance.client import Client from monitor.service import MonitorService import logging logger = logging.getLogger('siis.connector.binance.ws') error_logger = logging.getLogger('siis.error.connector.binance.ws') traceback_logger = logging.getLogger('siis.traceback.connector.binance.ws')
[ 2, 2488, 4475, 12131, 12, 486, 12, 3132, 198, 2, 2488, 9800, 18669, 291, 47956, 2611, 11, 1439, 2489, 10395, 1231, 39800, 13, 198, 2, 2488, 43085, 15069, 357, 66, 8, 12131, 7610, 3827, 11125, 198, 2, 347, 14149, 47736, 5459, 21716, ...
3.521531
209
list_0 = [1, 2, 3, 6] print(list_slicing(list_0, 1, 4)) print(list_slicing(list_0, 2, 4)) list_1 = [1, 2, 4, 5, 6, 9, 4, 6, 5, 8, 1, 4] print(list_slicing(list_1, 3, 4)) print(list_slicing(list_1, 4, 3)) print(list_slicing(list_1, 2, 6)) print(list_slicing(list_1, 6, 2)) print(list_slicing(list_1, 5, 3)) print(list_slicing(list_1, 2, 5))
[ 198, 4868, 62, 15, 796, 685, 16, 11, 362, 11, 513, 11, 718, 60, 198, 4798, 7, 4868, 62, 82, 677, 278, 7, 4868, 62, 15, 11, 352, 11, 604, 4008, 198, 4798, 7, 4868, 62, 82, 677, 278, 7, 4868, 62, 15, 11, 362, 11, 604, 4008, ...
1.879121
182
from OnePy.sys_module.metabase_env import OnePyEnvBase
[ 6738, 1881, 20519, 13, 17597, 62, 21412, 13, 4164, 5754, 62, 24330, 1330, 1881, 20519, 4834, 85, 14881, 628, 628 ]
2.9
20
""" Test cases for the regi0.geographic.duplicates.find_grid_duplicates function. """ import numpy as np import pandas as pd from regi0.geographic.duplicates import find_grid_duplicates
[ 37811, 198, 14402, 2663, 329, 262, 842, 72, 15, 13, 469, 6826, 13, 646, 489, 16856, 13, 19796, 62, 25928, 62, 646, 489, 16856, 2163, 13, 198, 37811, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 198,...
2.938462
65
import platform from django.core.exceptions import ObjectDoesNotExist from morango.models import InstanceIDModel import kolibri def get_device_info(): """Returns metadata information about the device""" instance_model = InstanceIDModel.get_or_create_current_instance()[0] try: device_name = kolibri.core.device.models.DeviceSettings.objects.get().name # When Koliri starts at the first time, and device hasn't been created except ObjectDoesNotExist: device_name = instance_model.hostname info = { "application": "kolibri", "kolibri_version": kolibri.__version__, "instance_id": instance_model.id, "device_name": device_name, "operating_system": platform.system(), } return info
[ 11748, 3859, 198, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 9515, 13921, 3673, 3109, 396, 198, 6738, 2146, 14208, 13, 27530, 1330, 2262, 590, 2389, 17633, 198, 198, 11748, 479, 349, 571, 380, 628, 198, 4299, 651, 62, 2...
2.71831
284
import os import json import logging # cellcraft node CELLCRAFT_NODE_URL="http://192.168.178.29:4534" # path to cache where pickle files will be stored PATH_RESOURCES='cellcraft/resources' PATH_CACHE='cellcraft/resources/cache/' PATH_TEST_CACHE='test/fixtures/cache/' # path to fixtures PATH_TO_FIXTURES="test/fixtures" # path to cellpack structures after processing them PATH_CELLPACK = 'cellcraft/resources/cellpack/' # cellpack parameters envelop_id = 22 # database name to store biological information and coordinates of structures DB='cellcraft' TEST_DB='test' # fix maximum amount of structures saved on cache MAXIMUM_NUM_STRUCTURES_CACHE = 8 # load block appear appearance json current_env = os.environ.get('app_env') root_logger = logging.getLogger() current_env = 'test' if current_env == 'cellcraft': DB_HOST = '127.0.0.1' DB_PORT = 27017 root_logger.setLevel(logging.INFO) elif current_env == 'test': DB_HOST = '127.0.0.1' DB_PORT = 27017 root_logger.setLevel(logging.DEBUG) else: logging.warning('Please configure a environment using now default dev environment for config') root_logger.setLevel(logging.DEBUG)
[ 11748, 28686, 198, 11748, 33918, 198, 11748, 18931, 628, 198, 2, 2685, 3323, 10139, 198, 5222, 3069, 34, 44700, 62, 45, 16820, 62, 21886, 2625, 4023, 1378, 17477, 13, 14656, 13, 23188, 13, 1959, 25, 2231, 2682, 1, 628, 198, 2, 3108, ...
2.84466
412
# -*- coding: utf-8 -*- """ Simple folder synchronization using FTP. (c) 2012-2021 Martin Wendt; see https://github.com/mar10/pyftpsync Licensed under the MIT license: https://www.opensource.org/licenses/mit-license.php Usage examples: > pyftpsync.py --help > pyftpsync.py upload . ftps://example.com/myfolder """ import argparse import platform import sys from pprint import pprint from ftpsync import __version__ from ftpsync.cli_common import ( common_parser, creds_parser, matcher_parser, verbose_parser, ) from ftpsync.run_command import add_run_parser, handle_run_command from ftpsync.scan_command import add_scan_parser from ftpsync.synchronizers import ( BiDirSynchronizer, DownloadSynchronizer, UploadSynchronizer, ) from ftpsync.targets import FsTarget, make_target from ftpsync.tree_command import add_tree_parser from ftpsync.util import ( DEBUG_FLAGS, PYTHON_VERSION, check_cli_verbose, namespace_to_dict, set_pyftpsync_logger, ) # =============================================================================== # run # =============================================================================== def run(): """CLI main entry point.""" # Use print() instead of logging when running in CLI mode: set_pyftpsync_logger(None) parser = argparse.ArgumentParser( description="Synchronize folders over FTP.", epilog="See also https://github.com/mar10/pyftpsync", parents=[verbose_parser], ) # Note: we want to allow --version to be combined with --verbose. However # on Py2, argparse makes sub-commands mandatory, unless `action="version"` is used. if check_cli_verbose(3) > 3: version_info = "pyftpsync/{} Python/{} {}".format( __version__, PYTHON_VERSION, platform.platform() ) else: version_info = "{}".format(__version__) parser.add_argument("-V", "--version", action="version", version=version_info) subparsers = parser.add_subparsers(help="sub-command help") # --- Create the parser for the "upload" command --------------------------- sp = subparsers.add_parser( "upload", parents=[verbose_parser, common_parser, matcher_parser, creds_parser], help="copy new and modified files to remote folder", ) sp.add_argument( "local", metavar="LOCAL", default=".", help="path to local folder (default: %(default)s)", ) sp.add_argument("remote", metavar="REMOTE", help="path to remote folder") sp.add_argument( "--force", action="store_true", help="overwrite remote files, even if the target is newer " "(but no conflict was detected)", ) sp.add_argument( "--resolve", default="ask", choices=["local", "skip", "ask"], help="conflict resolving strategy (default: '%(default)s')", ) sp.add_argument( "--delete", action="store_true", help="remove remote files if they don't exist locally", ) sp.add_argument( "--delete-unmatched", action="store_true", help="remove remote files if they don't exist locally " "or don't match the current filter (implies '--delete' option)", ) sp.set_defaults(command="upload") # --- Create the parser for the "download" command ------------------------- sp = subparsers.add_parser( "download", parents=[verbose_parser, common_parser, matcher_parser, creds_parser], help="copy new and modified files from remote folder to local target", ) sp.add_argument( "local", metavar="LOCAL", default=".", help="path to local folder (default: %(default)s)", ) sp.add_argument("remote", metavar="REMOTE", help="path to remote folder") sp.add_argument( "--force", action="store_true", help="overwrite local files, even if the target is newer " "(but no conflict was detected)", ) sp.add_argument( "--resolve", default="ask", choices=["remote", "skip", "ask"], help="conflict resolving strategy (default: '%(default)s')", ) sp.add_argument( "--delete", action="store_true", help="remove local files if they don't exist on remote target", ) sp.add_argument( "--delete-unmatched", action="store_true", help="remove local files if they don't exist on remote target " "or don't match the current filter (implies '--delete' option)", ) sp.set_defaults(command="download") # --- Create the parser for the "sync" command ----------------------------- sp = subparsers.add_parser( "sync", parents=[verbose_parser, common_parser, matcher_parser, creds_parser], help="synchronize new and modified files between remote folder and local target", ) sp.add_argument( "local", metavar="LOCAL", default=".", help="path to local folder (default: %(default)s)", ) sp.add_argument("remote", metavar="REMOTE", help="path to remote folder") sp.add_argument( "--resolve", default="ask", choices=["old", "new", "local", "remote", "skip", "ask"], help="conflict resolving strategy (default: '%(default)s')", ) sp.set_defaults(command="sync") # --- Create the parser for the "run" command ----------------------------- add_run_parser(subparsers) # --- Create the parser for the "scan" command ----------------------------- add_scan_parser(subparsers) # --- Create the parser for the "tree" command ----------------------------- add_tree_parser(subparsers) # --- Parse command line --------------------------------------------------- args = parser.parse_args() args.verbose -= args.quiet del args.quiet # print("verbose", args.verbose) ftp_debug = 0 if args.verbose >= 6: ftp_debug = 1 if args.debug: if args.verbose < 4: parser.error("'--debug' requires verbose level >= 4") DEBUG_FLAGS.update(args.debug) # Modify the `args` from the `pyftpsync.yaml` config: if getattr(args, "command", None) == "run": handle_run_command(parser, args) if callable(getattr(args, "command", None)): # scan_handler try: return args.command(parser, args) except KeyboardInterrupt: print("\nAborted by user.", file=sys.stderr) sys.exit(3) elif not hasattr(args, "command"): parser.error( "missing command (choose from 'upload', 'download', 'run', 'sync', 'scan')" ) # Post-process and check arguments if hasattr(args, "delete_unmatched") and args.delete_unmatched: args.delete = True args.local_target = make_target(args.local, {"ftp_debug": ftp_debug}) if args.remote == ".": parser.error("'.' is expected to be the local target (not remote)") args.remote_target = make_target(args.remote, {"ftp_debug": ftp_debug}) if not isinstance(args.local_target, FsTarget) and isinstance( args.remote_target, FsTarget ): parser.error("a file system target is expected to be local") # Let the command handler do its thing opts = namespace_to_dict(args) if args.command == "upload": s = UploadSynchronizer(args.local_target, args.remote_target, opts) elif args.command == "download": s = DownloadSynchronizer(args.local_target, args.remote_target, opts) elif args.command == "sync": s = BiDirSynchronizer(args.local_target, args.remote_target, opts) else: parser.error("unknown command '{}'".format(args.command)) s.is_script = True try: s.run() except KeyboardInterrupt: print("\nAborted by user.", file=sys.stderr) sys.exit(3) finally: # Prevent sporadic exceptions in ftplib, when closing in __del__ s.local.close() s.remote.close() stats = s.get_stats() if args.verbose >= 5: pprint(stats) elif args.verbose >= 1: if args.dry_run: print("(DRY-RUN) ", end="") print( "Wrote {}/{} files in {} directories, skipped: {}.".format( stats["files_written"], stats["local_files"], stats["local_dirs"], stats["conflict_files_skipped"], ), end="", ) if stats["interactive_ask"]: print() else: print(" Elap: {}.".format(stats["elap_str"])) return # Script entry point if __name__ == "__main__": # Just in case... from multiprocessing import freeze_support freeze_support() run()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 26437, 9483, 42133, 1262, 45854, 13, 201, 198, 201, 198, 7, 66, 8, 2321, 12, 1238, 2481, 5780, 21042, 83, 26, 766, 3740, 1378, 12567, 13, 785, ...
2.368995
3,851