content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
#! /usr/bin/env python # # downloader_test.py # # Copyright (c) 2015-2016 Junpei Kawamoto # # This software is released under the MIT License. # # http://opensource.org/licenses/mit-license.php # """ Test for downloader module. """ import logging import shutil import sys import unittest import os from os import path import downloader # pylint: disable=import-error TARGET_FILE = "bin/entrypoint.sh" SAMPLE_FILE = "https://raw.githubusercontent.com/jkawamoto/roadie-gcp/master/bin/entrypoint.sh" ORIGINAL_FILE = path.normpath( path.join(path.dirname(__file__), "..", TARGET_FILE)) ARCHIVE_ROOT = "./roadie-gcp-20160618" ZIP_FILE = "https://github.com/jkawamoto/roadie-gcp/archive/v20160618.zip" TAR_FILE = "https://github.com/jkawamoto/roadie-gcp/archive/v20160618.tar.gz" if __name__ == "__main__": logging.basicConfig(level=logging.INFO, stream=sys.stderr) unittest.main()
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 4321, 263, 62, 9288, 13, 9078, 198, 2, 198, 2, 15069, 357, 66, 8, 1853, 12, 5304, 7653, 33265, 23043, 25384, 198, 2, 198, 2, 770, 3788, 318, 2716, 739, 262, 17168, ...
2.622807
342
import matplotlib.pyplot as pl import os import numpy as np from ticle.data.dataHandler import normalizeData,load_file from ticle.analysis.analysis import get_phases,normalize_phase pl.rc('xtick', labelsize='x-small') pl.rc('ytick', labelsize='x-small') pl.rc('font', family='serif') pl.rcParams.update({'font.size': 20}) pl.tight_layout() path = os.getcwd() phase_dir = f"{path}/results/phase_plots" try: os.makedirs(phase_dir) except FileExistsError: pass data_dir = f"{path}/data/" data_list_file = f"{data_dir}/dataList.txt" data_list = np.loadtxt(data_list_file) for data in data_list: star = f"0{int(data[0])}" file_name = f"{data_dir}/{star}/{star}_LC_destepped.txt" res_dir = f"{phase_dir}/{star}" try: os.mkdir(res_dir) except FileExistsError: pass t_series = load_file(file_name) t_series = normalizeData(t_series) p = [(f"Phaseplot {star} - literature","literature",data[2]), (f"Phaseplot {star} - P={data[1]} days",f"result",data[1])] for title,save_text,period in p: masks = get_phases(t_series,period) fig_phase = pl.figure(figsize=(10,7)) for i in masks: plot_data = normalize_phase(np.array((t_series[0][i],t_series[1][i]))) pl.plot(plot_data[0],plot_data[1],linewidth = 1) pl.xlabel("Phase") pl.ylabel("Flux") pl.title(title) fig_phase.savefig(f"{res_dir}/{star}_{save_text}_phase_.pdf") fig_lightcurve = pl.figure(figsize=(10,7)) for i in masks: pl.plot(t_series[0][i],t_series[1][i],linewidth = 1) pl.xlabel("Period(days)") pl.ylabel("Flux") pl.title(f"{star} Lightcurve {save_text}") fig_lightcurve.savefig(f"{res_dir}/{star}_{save_text}_lightcurve.pdf")
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 198, 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 256, 1548, 13, 7890, 13, 7890, 25060, 1330, 3487, 1096, 6601, 11, 2220, 62, 7753, 198, 6738, 256, 1548, 13, 20...
2.130178
845
#!/usr/bin/python import shlex import simplejson from putil.rabbitmq.rabbitmqadmin import Management, make_parser, LISTABLE, DELETABLE # TODO: Move the management calls from pyon.ion.exchange here # ------------------------------------------------------------------------- # Helpers # This function works on exchange, queue, vhost, user
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 427, 2588, 198, 11748, 2829, 17752, 198, 198, 6738, 1234, 346, 13, 81, 14229, 76, 80, 13, 81, 14229, 76, 80, 28482, 1330, 8549, 11, 787, 62, 48610, 11, 406, 1797, 38148, 11, 5...
3.574257
101
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Loads a GaterNet checkpoint and tests on Cifar-10 test set.""" import argparse import io import os from backbone_resnet import Network as Backbone from gater_resnet import Gater import torch import torch.nn as nn import torch.nn.functional as F from torchvision import datasets from torchvision import transforms def load_from_state(state_dict, model): """Loads the state dict of a checkpoint into model.""" tem_dict = dict() for k in state_dict.keys(): tem_dict[k.replace('module.', '')] = state_dict[k] state_dict = tem_dict ckpt_key = set(state_dict.keys()) model_key = set(model.state_dict().keys()) print('Keys not in current model: {}\n'.format(ckpt_key - model_key)) print('Keys not in checkpoint: {}\n'.format(model_key - ckpt_key)) model.load_state_dict(state_dict, strict=True) print('Successfully reload from state.') return model def test(backbone, gater, device, test_loader): """Tests the model on a test set.""" backbone.eval() gater.eval() loss = 0 correct = 0 with torch.no_grad(): for data, target in test_loader: data, target = data.to(device), target.to(device) gate = gater(data) output = backbone(data, gate) loss += F.cross_entropy(output, target, size_average=False).item() pred = output.max(1, keepdim=True)[1] correct += pred.eq(target.view_as(pred)).sum().item() loss /= len(test_loader.dataset) acy = 100. * correct / len(test_loader.dataset) print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.4f}%)\n'.format( loss, correct, len(test_loader.dataset), acy)) return acy def run(args, device, test_loader): """Loads checkpoint into GaterNet and runs test on the test data.""" with open(args.checkpoint_file, 'rb') as fin: inbuffer = io.BytesIO(fin.read()) state_dict = torch.load(inbuffer, map_location='cpu') print('Successfully load checkpoint file.\n') backbone = Backbone(depth=args.backbone_depth, num_classes=10) print('Loading checkpoint weights into backbone.') backbone = load_from_state(state_dict['backbone_state_dict'], backbone) backbone = nn.DataParallel(backbone).to(device) print('Backbone is ready after loading checkpoint and moving to device:') print(backbone) n_params_b = sum( [param.view(-1).size()[0] for param in backbone.parameters()]) print('Number of parameters in backbone: {}\n'.format(n_params_b)) gater = Gater(depth=20, bottleneck_size=8, gate_size=backbone.module.gate_size) print('Loading checkpoint weights into gater.') gater = load_from_state(state_dict['gater_state_dict'], gater) gater = nn.DataParallel(gater).to(device) print('Gater is ready after loading checkpoint and moving to device:') print(gater) n_params_g = sum( [param.view(-1).size()[0] for param in gater.parameters()]) print('Number of parameters in gater: {}'.format(n_params_g)) print('Total number of parameters: {}\n'.format(n_params_b + n_params_g)) print('Running test on test data.') test(backbone, gater, device, test_loader) def parse_flags(): """Parses input arguments.""" parser = argparse.ArgumentParser(description='GaterNet') parser.add_argument('--no-cuda', action='store_true', default=False, help='disables CUDA training') parser.add_argument('--backbone-depth', type=int, default=20, help='resnet depth of the backbone subnetwork') parser.add_argument('--checkpoint-file', type=str, default=None, help='checkpoint file to run test') parser.add_argument('--data-dir', type=str, default=None, help='the directory for storing data') args = parser.parse_args() return args if __name__ == '__main__': main(parse_flags())
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 15069, 33160, 383, 3012, 4992, 46665, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, ...
2.873203
1,530
#!/usr/bin/env python3 # Hydrus is released under WTFPL # You just DO WHAT THE FUCK YOU WANT TO. # https://github.com/sirkris/WTFPL/blob/master/WTFPL.md from hydrus import hydrus_client if __name__ == '__main__': hydrus_client.boot()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 15084, 14932, 318, 2716, 739, 41281, 5837, 43, 198, 2, 921, 655, 8410, 25003, 3336, 30998, 7013, 41300, 5390, 13, 198, 2, 3740, 1378, 12567, 13, 785, 14, 82, 14232, 2442,...
2.390476
105
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ExchangeConnector fixEngine Copyright (c) 2020 Hugo Nistal Gonzalez Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import asyncio import simplefix import threading import logging import time import sys import configparser from fixClientMessages import FixClientMessages from connectionHandler import FIXConnectionHandler, SocketConnectionState
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 3109, 3803, 34525, 4259, 13798, 198, 198, 15269, 357, 66, 8, 12131, 25930, 399, 396, 282, 24416, 198, ...
3.873596
356
from jadi import component from aj.api.http import url, HttpPlugin from aj.auth import authorize from aj.api.endpoint import endpoint, EndpointError import aj import gevent
[ 6738, 474, 9189, 1330, 7515, 198, 198, 6738, 257, 73, 13, 15042, 13, 4023, 1330, 19016, 11, 367, 29281, 37233, 198, 6738, 257, 73, 13, 18439, 1330, 29145, 198, 6738, 257, 73, 13, 15042, 13, 437, 4122, 1330, 36123, 11, 5268, 4122, 12...
2.876923
65
# Copyright (c) 2016 Universidade Federal Fluminense (UFF) # Copyright (c) 2016 Polytechnic Institute of New York University. # Copyright (c) 2018, 2019, 2020 President and Fellows of Harvard College. # This file is part of ProvBuild. """Capture arguments from calls""" from __future__ import (absolute_import, print_function, division, unicode_literals) import weakref import itertools import inspect from future.utils import viewitems from ...utils.functions import abstract from ..prov_definition.utils import ClassDef, Assert, With, Decorator WITHOUT_PARAMS = (ClassDef, Assert, With)
[ 2, 15069, 357, 66, 8, 1584, 26986, 312, 671, 5618, 1610, 7230, 1072, 357, 47588, 8, 198, 2, 15069, 357, 66, 8, 1584, 12280, 23873, 291, 5136, 286, 968, 1971, 2059, 13, 198, 2, 15069, 357, 66, 8, 2864, 11, 13130, 11, 12131, 1992, ...
3.272251
191
N = int(input()) entry = [input().split() for _ in range(N)] phoneBook = {name: number for name, number in entry} while True: try: name = input() if name in phoneBook: print(f"{name}={phoneBook[name]}") else: print("Not found") except: break
[ 45, 796, 493, 7, 15414, 28955, 198, 13000, 796, 685, 15414, 22446, 35312, 3419, 329, 4808, 287, 2837, 7, 45, 15437, 198, 4862, 10482, 796, 1391, 3672, 25, 1271, 329, 1438, 11, 1271, 287, 5726, 92, 198, 198, 4514, 6407, 25, 198, 220,...
2.161972
142
#Sequence model. != Recursive Neural Network #memory cell or RNN cell #hidden state #one-to-many_image captioning, many-to-one_sentiment classfication || spam detection, many-to-many_chat bot #2) create RNN in python import numpy as np timesteps=10# _ input_size=4# _ hidden_size=8# ( ) inputs=np.random.random((timesteps, input_size))# 2D hidden_state_t=np.zeros((hidden_size,))#jiddensize 0 print(hidden_state_t) Wx=np.random.random((hidden_size, input_size))# Wh=np.random.random((hidden_size, hidden_size))# b=np.random.random((hidden_size,)) print(np.shape(Wx)) print(np.shape(Wh)) print(np.shape(b)) total_hidden_states=[] #memory cell work for input_t in inputs: output_t=np.tanh(np.dot(Wx,input_t)+np.dot(Wh,hidden_state_t)+b) total_hidden_states.append(list(output_t))# print(np.shape(total_hidden_states)) hidden_state_t=output_t total_hidden_states=np.stack(total_hidden_states, axis=0)# print(total_hidden_states) #3) nn.RNN() in pytorch import torch import torch.nn as nn input_size=5# hidden_size=8# inputs=torch.Tensor(1, 10, 5)# 1 10 5 cell=nn.RNN(input_size, hidden_size, batch_first=True)# outputs, _status=cell(inputs)#2 . , print(outputs.shape) #4) Deep Recurrent Neural Network inputs=torch.Tensor(1, 10, 5) cell=nn.RNN(input_size=5, hidden_size=8, num_layers=2, batch_first=True)# 2(cell) print(outputs.shape) print(_status.shape)#, , #5) Bidirectional Recurrent Neural Network inputs=torch.Tensor(1, 10, 5) cell=nn.RNN(input_size=5, hidden_size=8, num_layers=2, batch_first=True, bidirectional=True)# outputs, _status=cell(inputs) print(outputs.shape)# 2 print(_status.shape)#2
[ 2, 44015, 594, 2746, 13, 14512, 3311, 30753, 47986, 7311, 198, 2, 31673, 2685, 393, 371, 6144, 2685, 198, 2, 30342, 1181, 198, 2, 505, 12, 1462, 12, 21834, 62, 9060, 8305, 278, 11, 867, 12, 1462, 12, 505, 62, 34086, 3681, 1398, 69...
2.391053
693
pet = { "name":"Doggo", "animal":"dog", "species":"labrador", "age":"5" } my_pet= Pet("Fido", 3, "dog") my_pet.is_hungry= True print("is my pet hungry? %s"% my_pet.is_hungry) my_pet.eat() print("how about now? %s" % my_pet.is_hungry) print ("My pet is feeling %s" % my_pet.mood)
[ 6449, 796, 1391, 198, 1, 3672, 2404, 32942, 2188, 1600, 198, 1, 41607, 2404, 9703, 1600, 198, 1, 35448, 2404, 23912, 40368, 1600, 198, 1, 496, 2404, 20, 1, 198, 92, 198, 198, 1820, 62, 6449, 28, 4767, 7203, 37, 17305, 1600, 513, 1...
2.230159
126
from dagster import job, repository from ops.sklearn_ops import ( fetch_freehand_text_to_generic_data, separate_features_from_target_label, label_encode_target, count_tfid_transform_train, count_tfid_transform_test, create_sgd_classifier_model, predict )
[ 6738, 48924, 1706, 1330, 1693, 11, 16099, 201, 198, 6738, 39628, 13, 8135, 35720, 62, 2840, 1330, 357, 201, 198, 220, 220, 220, 21207, 62, 5787, 4993, 62, 5239, 62, 1462, 62, 41357, 62, 7890, 11, 201, 198, 220, 220, 220, 4553, 62, ...
2.454545
121
resposta = 'S' soma = quant = media = maior = menor = 0 while resposta in 'Ss': n = int(input('Digite um nmero: ')) soma += n quant += 1 if quant == 1: maior = menor = n else: if n > maior: maior = n elif n < menor: menor = n resposta = str(input('Quer continuar? [S/N]: ')).upper().strip()[0] media = soma / quant print('Voc digitou {} nmeros e a soma foi de {} e media de {}.'.format(quant, soma, media)) print('O maior nmero {} e o menor nmero {}.'.format(maior, menor))
[ 4363, 39818, 796, 705, 50, 6, 198, 82, 6086, 796, 5554, 796, 2056, 796, 17266, 1504, 796, 1450, 273, 796, 657, 198, 4514, 1217, 39818, 287, 705, 50, 82, 10354, 198, 220, 220, 220, 299, 796, 493, 7, 15414, 10786, 19511, 578, 23781, ...
2.141176
255
from shapely.geometry import Polygon from ..point import Point
[ 198, 6738, 5485, 306, 13, 469, 15748, 1330, 12280, 14520, 198, 198, 6738, 11485, 4122, 1330, 6252, 198 ]
3.611111
18
import numpy as np import pandas as pd from sklearn.preprocessing import LabelEncoder, MinMaxScaler from numpy.random import uniform import matplotlib.pyplot as plt # Import Data training_amount = 4000 input_scaler = MinMaxScaler((-1, 1)) output_scaler = MinMaxScaler((-1, 1)) data = pd.read_csv('USA_Housing.csv').drop(columns=['Address']) data = np.insert(data.to_numpy(), 0, np.ones((1, len(data))), axis=1) x_scaled, y_scaled = input_scaler.fit_transform(data[:, :6]), output_scaler.fit_transform(data[:, 6:7]) x_train, y_train = x_scaled[:training_amount], y_scaled[:training_amount] x_test, y_test = x_scaled[training_amount:], y_scaled[training_amount:] hidden_neurons = 10 # Create NN & train it nn = NeuralNetwork(hidden_neurons, 0.7) nn.fit(x_train, y_train, epochs=75) error = 0 amount_to_check = 20 for x, y in zip(x_test[:amount_to_check, :], y_test[:amount_to_check]): error += abs(output_scaler.inverse_transform(y.reshape(-1, 1))[0][0] - output_scaler.inverse_transform(nn.f_propagate(x)[1].reshape(-1, 1))[0][0]) print( f"{output_scaler.inverse_transform(nn.f_propagate(x)[1].reshape(-1, 1))[0][0]} -> {output_scaler.inverse_transform(y.reshape(-1, 1))[0][0]}") print(f"{(error / len(x_test)):.9f}") """ # Keras Version of NN model = keras.models.Sequential() model.add(keras.layers.Dense(hidden_neurons, input_dim=5, activation='relu', kernel_initializer='he_normal')) model.add(keras.layers.Dense(1, input_dim=hidden_neurons, activation='linear')) model.compile(loss='mse', optimizer='adam', metrics=['mse']) history = model.fit(x_train, y_train, epochs=10, batch_size=10) plt.plot(history.history['mse']) plt.show() for x, y in zip(model.predict(x_test), y_test): print(f"{output_scaler.inverse_transform(y.reshape(-1, 1))[0][0]} -> {output_scaler.inverse_transform(x.reshape(-1, 1))[0][0]}") """
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 1341, 35720, 13, 3866, 36948, 1330, 36052, 27195, 12342, 11, 1855, 11518, 3351, 36213, 198, 6738, 299, 32152, 13, 25120, 1330, 8187, 198, 11748, 2603, 29487, ...
2.394872
780
import pytest from osxphotos._constants import _UNKNOWN_PERSON PHOTOS_DB = "./tests/Test-10.15.4.photoslibrary/database/photos.db" TOP_LEVEL_FOLDERS = ["Folder1"] TOP_LEVEL_CHILDREN = ["SubFolder1", "SubFolder2"] FOLDER_ALBUM_DICT = {"Folder1": [], "SubFolder1": [], "SubFolder2": ["AlbumInFolder"]} ALBUM_NAMES = ["Pumpkin Farm", "AlbumInFolder", "Test Album", "Test Album"] ALBUM_PARENT_DICT = { "Pumpkin Farm": None, "AlbumInFolder": "SubFolder2", "Test Album": None, } ALBUM_FOLDER_NAMES_DICT = { "Pumpkin Farm": [], "AlbumInFolder": ["Folder1", "SubFolder2"], "Test Album": [], } ALBUM_LEN_DICT = {"Pumpkin Farm": 3, "AlbumInFolder": 2, "Test Album": 1} ALBUM_PHOTO_UUID_DICT = { "Pumpkin Farm": [ "F12384F6-CD17-4151-ACBA-AE0E3688539E", "D79B8D77-BFFC-460B-9312-034F2877D35B", "1EB2B765-0765-43BA-A90C-0D0580E6172C", ], "Test Album": [ "F12384F6-CD17-4151-ACBA-AE0E3688539E", "D79B8D77-BFFC-460B-9312-034F2877D35B", ], "AlbumInFolder": [ "3DD2C897-F19E-4CA6-8C22-B027D5A71907", "E9BC5C36-7CD1-40A1-A72B-8B8FAC227D51", ], } UUID_DICT = { "two_albums": "F12384F6-CD17-4151-ACBA-AE0E3688539E", "in_album": "E9BC5C36-7CD1-40A1-A72B-8B8FAC227D51", "xmp": "F12384F6-CD17-4151-ACBA-AE0E3688539E", }
[ 11748, 12972, 9288, 198, 198, 6738, 28686, 87, 24729, 13557, 9979, 1187, 1330, 4808, 4944, 44706, 62, 47, 29086, 198, 198, 42709, 62, 11012, 796, 366, 19571, 41989, 14, 14402, 12, 940, 13, 1314, 13, 19, 13, 24729, 32016, 14, 48806, 14...
1.857343
715
# Copyright 2018 Deep Topology All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains model definitions.""" # noinspection PyUnresolvedReferences import pathmagic from tensorflow import flags import attention_modules import tensorflow as tf import tensorflow.contrib.slim as slim import models import math FLAGS = flags.FLAGS flags.DEFINE_integer( "moe_num_mixtures", 2, "The number of mixtures (excluding the dummy 'expert') used for MoeModel.") ############################################################################### # Baseline (Benchmark) models ################################################# ############################################################################### flags.DEFINE_float( "moe_l2", 1e-8, "L2 penalty for MoeModel.") flags.DEFINE_integer( "moe_low_rank_gating", -1, "Low rank gating for MoeModel.") flags.DEFINE_bool( "moe_prob_gating", False, "Prob gating for MoeModel.") flags.DEFINE_string( "moe_prob_gating_input", "prob", "input Prob gating for MoeModel.")
[ 2, 15069, 2864, 10766, 5849, 1435, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789,...
3.474614
453
#!/usr/bin/env python # coding: utf8 # # Copyright (c) 2021 Centre National d'Etudes Spatiales (CNES). # # This file is part of PANDORA2D # # https://github.com/CNES/Pandora2D # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ Test refinement step """ import unittest import numpy as np import xarray as xr import pytest from pandora2d import refinement, common
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 23, 198, 2, 198, 2, 15069, 357, 66, 8, 33448, 9072, 2351, 288, 6, 36, 83, 8401, 1338, 34961, 274, 357, 34, 37379, 737, 198, 2, 198, 2, 770, 2393, 318, 6...
3.324427
262
from unittest.mock import Mock from goblet import Goblet from goblet.resources.scheduler import Scheduler from goblet.test_utils import ( get_responses, get_response, mock_dummy_function, dummy_function, )
[ 6738, 555, 715, 395, 13, 76, 735, 1330, 44123, 198, 6738, 467, 903, 83, 1330, 16909, 1616, 198, 6738, 467, 903, 83, 13, 37540, 13, 1416, 704, 18173, 1330, 27774, 18173, 198, 6738, 467, 903, 83, 13, 9288, 62, 26791, 1330, 357, 198, ...
2.753086
81
import logging from functools import partial from arachnado.storages.mongotail import MongoTailStorage
[ 11748, 18931, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 198, 6738, 610, 620, 77, 4533, 13, 301, 273, 1095, 13, 31059, 313, 603, 1330, 42591, 51, 603, 31425, 628 ]
3.5
30
"""players module. Used for players data processes """ import numpy as np import pandas as pd import src.config as config import src.utilities as utilities from src.utilities import logging pd.set_option("display.max_columns", 500) pd.set_option("display.expand_frame_repr", False) # master_file = config.MASTER_FILES["ftb_players"] # distance_columns = ["Age", "ChancesInvolved", "DefensiveActions", "FoulsCommited", "FoulsSuffered", "Height", "Minutes", "NPG+A", "Points", "Weight", "SuccessfulPasses"] def get_outfile(source_name): """Return outfile stub for given source. INPUT: source_name: String containing name of the data source OUTPUT: outfile_stub: Stub to use when saving output """ logging.info("Mapping {0} to outfile".format(source_name)) if source_name == "tmk_cnt": outfile_stub = "players_contract" elif source_name == "tmk_psm": outfile_stub = "players_performance" logging.debug(outfile_stub) return outfile_stub def clean_data(source_name, directory=config.MASTER_DIR): """Clean raw player data and save processed version. INPUT: source_name: String containing name of the data source directory: Directory to save output to OUTPUT: df: Dataframe containing the cleaned data """ logging.info("Loading {0} data".format(source_name)) if source_name == "tmk_cnt": source_header = [ "Shirt number", "Position", "Name", "Date of birth", "Nationality", "Height", "Foot", "Joined", "Signed from", "Contract expires", "Market value", ] drop_cols = ["Nationality", "Signed from", "Competition"] notna_cols = ["Market value"] elif source_name == "tmk_psm": source_header = [ "Shirt number", "Position", "Name", "Age", "Nationality", "In squad", "Games started", "Goals", "Assists", "Yellow cards", "Second yellow cards", "Red cards", "Substitutions on", "Substitutions off", "PPG", "Minutes played", ] drop_cols = ["Nationality"] notna_cols = ["In squad"] df = utilities.folder_loader( source_name[:3], source_name, "comp_season", source_header=source_header ) ## Name and Position are mis-aligned in the source files df["Name"].fillna(method="bfill", inplace=True) df["Position"] = df.Name.shift(-1) df.loc[df.Position == df.Name, "Position"] = df.Name.shift(-2) df.drop(axis=1, columns=drop_cols, inplace=True) df.dropna(subset=notna_cols, inplace=True) df = df.apply(lambda x: x.str.strip() if x.dtype == "object" else x) df = df.replace("-", np.nan) df = df.replace("Was not used during this season", np.nan) df = df.replace("Not in squad during this season", np.nan) df = df.replace("Not used during this season", np.nan) df["Shirt number"] = pd.to_numeric(df["Shirt number"], downcast="integer") df["Position group"] = None df.loc[ (df.Position.str.upper().str.contains("KEEPER")) | (df.Position.str.upper().str.contains("GOAL")), "Position group", ] = "G" df.loc[ (df.Position.str.upper().str.contains("BACK")) | (df.Position.str.upper().str.contains("DEF")), "Position group", ] = "D" df.loc[ (df.Position.str.upper().str.contains("MID")) | (df.Position.str.upper().str.contains("MIT")) | (df.Position.str.upper().str.contains("WING")), "Position group", ] = "M" df.loc[ (df.Position.str.upper().str.contains("STRIKER")) | (df.Position.str.upper().str.contains("FORW")), "Position group", ] = "F" if source_name == "tmk_cnt": df["Age"] = ( df["Date of birth"].str.extract(r".*([0-9]{2})", expand=False).astype("int") ) df["Date of birth"] = pd.to_datetime( df["Date of birth"].str.extract(r"(.*) \([0-9]{2}\)", expand=False), format="%b %d, %Y", ) df["Joined"] = pd.to_datetime(df.Joined, format="%b %d, %Y") df["Contract expires"] = pd.to_datetime( df["Contract expires"], format="%d.%m.%Y" ) df["Height"] = ( df["Height"] .str.strip() .str.replace(" ", "") .str.replace(",", "") .str.replace("m", "") .replace({"-": np.nan, "": np.nan}) .astype(float) ) df.loc[ df.Name.isin(df[df.Height.notna()].Name.values) & df.Name.isin(df[df.Height.isna()].Name.values), "Height", ] = ( df.loc[ df.Name.isin(df[df.Height.notna()].Name.values) & df.Name.isin(df[df.Height.isna()].Name.values) ] .sort_values(by=["Name", "Season"]) .Height.fillna(method="bfill") ) df.loc[ df.Name.isin(df[df.Foot.notna()].Name.values) & df.Name.isin(df[df.Foot.isna()].Name.values), "Foot", ] = ( df.loc[ df.Name.isin(df[df.Foot.notna()].Name.values) & df.Name.isin(df[df.Foot.isna()].Name.values) ] .sort_values(by=["Name", "Season"]) .Foot.fillna(method="bfill") ) df["Market value"] = ( df["Market value"] .str.strip() .replace({"-": np.nan}) .replace(r"[kmTh\.]", "", regex=True) .astype(float) * df["Market value"] .str.extract(r"[\d\.]+([kmTh\.]+)", expand=False) .fillna(1) .replace(["k", "Th.", "m"], [10 ** 3, 10 ** 3, 10 ** 6]) .astype(int) / 10 ** 6 ) elif source_name == "tmk_psm": df["PPG"] = df["PPG"].str.strip().replace(r"[,]", ".", regex=True).astype(float) df["Minutes played"] = ( df["Minutes played"] .str.strip() .replace(r"[.\']", "", regex=True) .astype(float) ) df[ [ "In squad", "Games started", "Goals", "Assists", "Yellow cards", "Second yellow cards", "Red cards", "Substitutions on", "Substitutions off", "PPG", "Minutes played", ] ] = df[ [ "In squad", "Games started", "Goals", "Assists", "Yellow cards", "Second yellow cards", "Red cards", "Substitutions on", "Substitutions off", "PPG", "Minutes played", ] ].fillna( 0 ) df[ [ "In squad", "Games started", "Goals", "Assists", "Yellow cards", "Second yellow cards", "Red cards", "Substitutions on", "Substitutions off", "PPG", "Minutes played", ] ] = df[ [ "In squad", "Games started", "Goals", "Assists", "Yellow cards", "Second yellow cards", "Red cards", "Substitutions on", "Substitutions off", "PPG", "Minutes played", ] ].astype( float ) logging.debug(df.describe(include="all")) logging.info("Saving processed data to ") utilities.save_master(df, get_outfile(source_name), directory=directory) return df # def get_players(): # """ # INPUT: # None # OUTPUT: # df - Dataframe of aggregated player data # """ # logging.info("Fetching aggregated player data") # # fetch from master csv # # df = pd.read_csv(master_file, sep='|', encoding="ISO-8859-1") # df = utilities.get_master("players") # # filter unwanted records # df = df[(df["Season"] >= "s1314") & (df["Competition"].isin(["chm", "cpo", "prm"]))] # df.dropna(subset=["Name"], inplace=True) # # select columns # group_key = "Name" # max_cols = ["Age", "Height", "Weight"] # # p90_cols = ["AerialsWon", "ChancesInvolved", "DefensiveActions", "Dispossesed", "Dribbles", "FoulsCommited", "FoulsSuffered", "NPG+A", "SuccessfulPasses"] # p90_cols = [ # "AerialsWon", # "Assists", # "BadControl", # "Blocks", # "CalledOffside", # "Clearances", # "Crosses", # "Dispossesed", # "Dribbles", # "DribblesAgainst", # "FirstYellowCards", # "FoulsCommited", # "FoulsSuffered", # "GoalsConceded", # "Interceptions", # "KeyPasses", # "LongBalls", # "NonPenaltyGoals", # "OffsidesWon", # "OwnGoals", # "Passes", # "PenaltyGoals", # "RedCards", # "Saves", # "Shots", # "ShotsFaced", # "ShotsOnTarget", # "Tackles", # "ThroughBalls", # "YellowCards", # ] # pGm_cols = ["Appearances", "Minutes", "Points"] # sum_cols = p90_cols + pGm_cols # selected_columns = [group_key] + max_cols + sum_cols # df = df[selected_columns] # # aggregate to player level # df_max = df[[group_key] + max_cols].groupby(group_key).max() # df_sum = df[[group_key] + sum_cols].groupby(group_key).sum() # df = pd.concat([df_max, df_sum], axis=1) # df = df[(df["Minutes"] >= 900)] # # convert action totals to per90 # for col in p90_cols: # df[col + "P90"] = 90 * df[col] / df["Minutes"] # for col in pGm_cols: # df[col + "PGm"] = df[col] / df["Appearances"] # for col in sum_cols: # del df[col] # del df["AppearancesPGm"] # logging.debug(df.describe(include="all")) # return df # def find_similar(): # players = get_players() # # print players # print("\nNumber of players included: " + str(len(players))) # # Normalize all of the numeric columns # players_normalized = (players - players.mean()) / players.std() # players_normalized.fillna(0, inplace=True) # # players_normalized.info() # # print players_normalized.describe(include="all") # # print players_normalized.index.values # for ( # name # ) in ( # players_normalized.index.values # ): # ["Adam Clayton", "Ben Gibson", "Daniel Ayala", "Tomas Mejias"]: # # print "\n###############################" # print("\n" + name, end=" ") # # selected_player = players.loc[name] # # print selected_player.name # # print selected_player.to_frame().T #.name # # Normalize all of the numeric columns # selected_normalized = players_normalized.loc[name] # # print selected_normalized # # Find the distance between select player and everyone else. # euclidean_distances = players_normalized.apply( # lambda row: distance.euclidean(row, selected_normalized), axis=1 # ) # # Create a new dataframe with distances. # distance_frame = pd.DataFrame( # data={"dist": euclidean_distances, "idx": euclidean_distances.index} # ) # distance_frame.sort_values("dist", inplace=True) # most_similar_players = distance_frame.iloc[1:4]["idx"] # # most_similar_players = players.loc[nearest_neighbours] #["Name"] # # print most_similar_players # print("... is similar to... ", end=" ") # print(list(most_similar_players.index.values)) # def make_prediction(): # players = get_players() # pred_col = "AssistsP90" # x_columns = list(players.columns.values) # x_columns.remove(pred_col) # y_column = [pred_col] # # # The columns that we will be making predictions with. # # x_columns = ['Age', 'Height', 'Weight', 'AerialsWonP90', 'AssistsP90', 'BadControlP90', 'BlocksP90', 'CalledOffsideP90', 'ClearancesP90', 'CrossesP90', 'DispossesedP90', 'DribblesP90', 'DribblesAgainstP90', 'FirstYellowCardsP90', 'FoulsCommitedP90', 'FoulsSufferedP90', 'GoalsConcededP90', 'InterceptionsP90', 'KeyPassesP90', 'LongBallsP90', 'NonPenaltyGoalsP90', 'OffsidesWonP90', 'OwnGoalsP90', 'PassesP90', 'PenaltyGoalsP90', 'RedCardsP90', 'SavesP90', 'ShotsP90', 'ShotsFacedP90', 'ShotsOnTargetP90', 'TacklesP90', 'ThroughBallsP90', 'YellowCardsP90', 'MinutesPGm'] # # print x_columns # # # The column that we want to predict. # # y_column = [pred_col] # # print y_column # ###Generating training and testing sets # # Randomly shuffle the index of nba. # random_indices = permutation(players.index) # # Set a cutoff for how many items we want in the test set (in this case 1/3 of the items) # test_cutoff = math.floor(len(players) / 3) # # Generate the test set by taking the first 1/3 of the randomly shuffled indices. # test = players.loc[random_indices[1:test_cutoff]] # test.fillna(0, inplace=True) # # test.info() # # print test.describe(include="all") # # Generate the train set with the rest of the data. # train = players.loc[random_indices[test_cutoff:]] # train.fillna(0, inplace=True) # # train.info() # # print train.describe(include="all") # ###Using sklearn for k nearest neighbors # # print "Using sklearn for k nearest neighbors..." # from sklearn.neighbors import KNeighborsRegressor # # Create the knn model. # # Look at the five closest neighbors. # knn = KNeighborsRegressor(n_neighbors=5) # # print knn # # Fit the model on the training data. # knn.fit(train[x_columns], train[y_column]) # # print knn # # Make point predictions on the test set using the fit model. # predictions = knn.predict(test[x_columns]) # # print "\nPredicted PointsPGm:" # # print predictions.shape # ###Computing error # # Get the actual values for the test set. # actual = test[y_column].copy() # # Compute the mean squared error of our predictions. # mse = (((predictions - actual) ** 2).sum()) / len(predictions) # print("\nMean Squared Error:") # print(mse) # actual["Predicted" + pred_col] = predictions # actual["Diff"] = actual[pred_col] - actual["Predicted" + pred_col] # print("\nActual and Predicted " + pred_col + ":") # print(actual.sort_values(["Diff"], ascending=False)) # def test_opinions(): # players = get_players() # players = players.reset_index() # players = players[ # players["Name"].isin( # [ # "Alvaro Negredo", # "Patrick Bamford", # "Jordan Rhodes", # "Garcia Kike", # "Cristhian Stuani", # "David Nugent", # "Danny Graham", # "Jelle Vossen", # "Kei Kamara", # ] # ) # ] # # df_info(players) # players["ShotAccuracy"] = players["ShotsOnTargetP90"] / players["ShotsP90"] # players["ShotEfficiency"] = ( # players["NonPenaltyGoalsP90"] + players["PenaltyGoalsP90"].fillna(0) # ) / players["ShotsP90"] # players["ShotPercentage"] = ( # players["NonPenaltyGoalsP90"] + players["PenaltyGoalsP90"].fillna(0) # ) / players["ShotsOnTargetP90"] # players = players[ # [ # "Name", # "NonPenaltyGoalsP90", # "PenaltyGoalsP90", # "ShotsP90", # "ShotsOnTargetP90", # "ShotAccuracy", # "ShotEfficiency", # "ShotPercentage", # ] # ] # # df_info(players) # print(players.describe()) # print(players) def main(): """Use the Main for CLI usage.""" logging.info("Executing players module") clean_data("tmk_cnt") clean_data("tmk_psm") # get_players() # find_similar() # make_prediction() # test_opinions() if __name__ == "__main__": main()
[ 37811, 32399, 8265, 13, 198, 198, 38052, 329, 1938, 1366, 7767, 198, 37811, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 11748, 12351, 13, 11250, 355, 4566, 198, 11748, 12351, 13, 315, 2410, 355, ...
2.006153
8,288
import pandas as pd import os #opt = itertools.islice(ls, len(ls)) #st = map(lambda x : )
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 28686, 628, 198, 198, 2, 8738, 796, 340, 861, 10141, 13, 3044, 501, 7, 7278, 11, 18896, 7, 7278, 4008, 198, 2, 301, 796, 3975, 7, 50033, 2124, 1058, 1267, 628, 628, 220, 220, 220, 220, ...
2.244444
45
import socket import unittest from eats.webdriver import PytractorWebDriver from eats.tests.common import SimpleWebServerProcess as SimpleServer
[ 11748, 17802, 198, 11748, 555, 715, 395, 198, 6738, 25365, 13, 12384, 26230, 1330, 9485, 83, 40450, 13908, 32103, 198, 6738, 25365, 13, 41989, 13, 11321, 1330, 17427, 13908, 10697, 18709, 355, 17427, 10697 ]
4.235294
34
from autoprep.service.project_service import ProjectService
[ 6738, 22320, 7856, 13, 15271, 13, 16302, 62, 15271, 1330, 4935, 16177, 628 ]
4.692308
13
import torch import torch.nn as nn
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 220, 220, 220, 220 ]
2.6
15
ADDON_NAME = "pmx_bone_importer" LOG_FILE_NAME = "pmx_bone_importer.log"
[ 29266, 1340, 62, 20608, 796, 366, 4426, 87, 62, 15992, 62, 320, 26634, 1, 198, 25294, 62, 25664, 62, 20608, 796, 366, 4426, 87, 62, 15992, 62, 320, 26634, 13, 6404, 1, 628 ]
2.242424
33
# Copyright 2017 James McCauley # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Input and output from network interfaces. This wraps PCap, TunTap, etc., to provide a simple, universal, cooperative interface to network interfaces. Currently limited to Linux. """ from pox.lib.pxpcap import PCap from queue import Queue from pox.lib.revent import Event, EventMixin from pox.lib.ioworker.io_loop import ReadLoop from pox.core import core import struct from fcntl import ioctl import socket from pox.lib.addresses import EthAddr, IPAddr from pox.lib.addresses import parse_cidr, cidr_to_netmask import os import ctypes IFNAMESIZ = 16 IFREQ_SIZE = 40 # from linux/if_tun.h TUNSETIFF = 0x400454ca TUNGETIFF = 0x800454d2 IFF_TUN = 0x0001 IFF_TAP = 0x0002 IFF_NO_PI = 0x1000 IFF_ONE_QUEUE = 0x2000 IFF_VNET_HDR = 0x4000 IFF_TUN_EXCL = 0x8000 IFF_MULTI_QUEUE = 0x0100 IFF_ATTACH_QUEUE = 0x0200 IFF_DETACH_QUEUE = 0x0400 IFF_PERSIST = 0x0800 IFF_NOFILTER = 0x1000 #from linux/if.h (flags) IFF_UP = 1<<0 IFF_BROADCAST = 1<<1 IFF_DEBUG = 1<<2 IFF_LOOPBACK = 1<<3 IFF_POINTOPOINT = 1<<4 IFF_NOTRAILERS = 1<<5 IFF_RUNNING = 1<<6 IFF_NOARP = 1<<7 IFF_PROMISC = 1<<8 IFF_ALLMULTI = 1<<9 IFF_MASTER = 1<<10 IFF_SLAVE = 1<<11 IFF_MULTICAST = 1<<12 IFF_PORTSEL = 1<<13 IFF_AUTOMEDIA = 1<<14 IFF_DYNAMIC = 1<<15 IFF_LOWER_UP = 1<<16 IFF_DORMANT = 1<<17 IFF_ECHO = 1<<18 # Unless IFF_NO_PI, there's a header on packets: # 16 bits of flags # 16 bits (big endian?) protocol number # from /usr/include/linux/sockios.h SIOCGIFHWADDR = 0x8927 SIOCGIFMTU = 0x8921 SIOCSIFMTU = 0x8922 SIOCGIFFLAGS = 0x8913 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCGIFNETMASK = 0x891b SIOCSIFNETMASK = 0x891c SIOCGIFADDR = 0x8915 SIOCSIFADDR = 0x8916 SIOCGIFBRDADDR = 0x8919 SIOCSIFBRDADDR = 0x891a SIOCSIFNAME = 0x8923 SIOCADDRT = 0x890B # rtentry (route.h) for IPv4, in6_rtmsg for IPv6 SIOCDELRT = 0x890C # from /usr/include/linux/if_arp.h ARPHRD_ETHER = 1 ARPHRD_IEEE802 = 1 ARPHRD_IEEE1394 = 24 ARPHRD_EUI64 = 27 ARPHRD_LOOPBACK = 772 ARPHRD_IPGRE = 778 ARPHRD_IEE802_TR = 800 ARPHRD_IEE80211 = 801 ARPHRD_IEE80211_PRISM = 802 ARPHRD_IEE80211_RADIOTAP = 803 ARPHRD_IP6GRE = 823 def unset_flags (self, flags): self.flags = self.flags & (flags ^ 0xffFF) def _ioctl_get_ipv4 (self, which): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ifr = struct.pack(str(IFNAMESIZ) + "s", self.name) ifr += "\0" * (IFREQ_SIZE - len(ifr)) ret = ioctl(sock, which, ifr) return self._get_ipv4(ret[IFNAMESIZ:]) def _ioctl_set_ipv4 (self, which, value): value = IPAddr(value) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ifr = struct.pack(str(IFNAMESIZ) + "sHHI", self.name, socket.AF_INET, 0, value.toUnsigned(networkOrder=True)) ifr += "\0" * (IFREQ_SIZE - len(ifr)) ret = ioctl(sock, which, ifr) def add_default_route (self, *args, **kw): return self.add_route("0.0.0.0/0", *args, **kw) def add_route (self, network, gateway=None, dev=(), metric=0): """ Add routing table entry If dev is unspecified, it defaults to this device """ return self._add_del_route(network, gateway, dev, metric, SIOCADDRT) def del_route (self, network, gateway=None, dev=(), metric=0): """ Remove a routing table entry If dev is unspecified, it defaults to this device """ return self._add_del_route(network, gateway, dev, metric, SIOCDELRT) def _add_del_route (self, network, gateway=None, dev=(), metric=0, command=None): """ Add or remove a routing table entry If dev is unspecified, it defaults to this device """ r = rtentry() if isinstance(network, tuple): addr,mask = network addr = str(addr) if isinstance(mask, int): mask = cidr_to_netmask(mask) mask = str(mask) network = "%s/%s" % (addr,mask) host = False if isinstance(network, IPAddr) or (isinstance(network, str) and "/" not in network): host = True network,bits = parse_cidr(network) r.rt_dst = network r.rt_genmask = cidr_to_netmask(bits) if gateway is not None: r.rt_gateway = IPAddr(gateway) r.rt_flags |= r.RTF_GATEWAY r.rt_metric = metric if dev is (): dev = self if isinstance(dev, Interface): dev = dev.name if dev: r.rt_dev = dev if host: r.rt_flags |= r.RTF_HOST r.rt_flags |= r.RTF_UP sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) rv = ioctl(sock, command, r.pack()) class TunTap (object): """ Simple wrapper for tun/tap interfaces Looks like a file-like object. You should be able to read/write it, select on it, etc. """ def __init__ (self, name=None, tun=False, raw=False): """ Create tun or tap By default, it creates a new tun or tap with a default name. If you specify a name, it will either try to create it (if it doesn't exist), or try to use an existing interface (for which you must have permission). Defaults to tap (Ethernet) mode. Specify tun=True for tun (IP) mode. Specify raw=True to skip the 32 bits of flag/protocol metadata. """ if name is None: name = "" openflags = os.O_RDWR try: openflow |= os.O_BINARY except: pass self._f = os.open("/dev/net/tun", openflags) # an ifreq is IFREQ_SIZE bytes long, starting with an interface name # (IFNAMESIZ bytes) followed by a big union. self.is_tun = tun self.is_tap = not tun self.is_raw = raw flags = 0 if tun: flags |= IFF_TUN else: flags |= IFF_TAP if raw: flags |= IFF_NO_PI ifr = struct.pack(str(IFNAMESIZ) + "sH", name, flags) ifr += "\0" * (IFREQ_SIZE - len(ifr)) ret = ioctl(self.fileno(), TUNSETIFF, ifr) self.name = ret[:IFNAMESIZ] iflags = flags ifr = struct.pack(str(IFNAMESIZ) + "sH", name, 0) ifr += "\0" * (IFREQ_SIZE - len(ifr)) ret = ioctl(self.fileno(), TUNGETIFF, ifr) flags = struct.unpack("H", ret[IFNAMESIZ:IFNAMESIZ+2])[0] self.is_tun = (flags & IFF_TUN) == IFF_TUN self.is_tap = not self.is_tun #self.is_raw = (flags & IFF_NO_PI) == IFF_NO_PI def _do_rx (self): data = self.tap.read(self.max_read_size) if not self.tap.is_raw: flags,proto = struct.unpack("!HH", data[:4]) #FIXME: This may invert the flags... self.last_flags = flags self.last_protocol = proto data = data[4:] # Cut off header self.raiseEvent(RXData, self, data) def fileno (self): # Support fileno so that this can be used in IO loop directly return self.tap.fileno() def close (self): if self.tap: self.tap.close() self.tap = None self.io_loop.remove(self)
[ 2, 15069, 2177, 3700, 5108, 559, 1636, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921,...
2.31388
3,170
# 2020 Tommaso Ciussani and Giacomo Giuliari import os import json import numpy as np from typing import Set, List from geopy.distance import great_circle from scipy.spatial.ckdtree import cKDTree from shapely.geometry import Polygon, shape, Point from icarus_simulator.sat_core.coordinate_util import geo2cart from icarus_simulator.strategies.atk_geo_constraint.base_geo_constraint_strat import ( BaseGeoConstraintStrat, ) from icarus_simulator.structure_definitions import GridPos dirname = os.path.dirname(__file__) strategies_dirname = os.path.split(dirname)[0] library_dirname = os.path.split(strategies_dirname)[0] data_dirname = os.path.join(library_dirname, "data") COUNTRIES_FILE: str = os.path.join(data_dirname, "natural_earth_world_small.geo.json") # noinspection PyTypeChecker def get_allowed_gridpoints(geo_location: str, grid_pos: GridPos, geo_data) -> Set[int]: # Get a list of all possible source points if geo_location in geo_data["countries"]: indices = [geo_data["countries"][geo_location]] elif geo_location in geo_data["subregions"]: indices = geo_data["subregions"][geo_location] elif geo_location in geo_data["continents"]: indices = geo_data["continents"][geo_location] else: raise ValueError("Invalid geographic constraint") geometries = [geo_data["geometries"][index] for index in indices] allowed_points = set() # Create a unique shape, union of all shapes in the region, and take the points include within shp = Polygon() for idx, geo in enumerate(geometries): shp = shp.union(shape(geo)) for idx, pos in grid_pos.items(): if Point(pos.lat, pos.lon).within(shp): allowed_points.add(idx) # Extract the border points x, y = [], [] if shp.geom_type == "MultiPolygon": for idx, shap in enumerate(shp.geoms): if True: x1, y1 = shap.exterior.xy x.extend(x1) y.extend(y1) else: x1, y1 = shp.exterior.xy x.extend(x1) y.extend(y1) # plotter.plot_points({idx: GeodeticPosInfo({"lat": x[idx], "lon": y[idx], "elev": 0.0}) # for idx in range(len(x))}, "GRID", "TEST", "aa", "asas",) grid_cart = np.zeros((len(grid_pos), 3)) grid_map = {} i = 0 for idx, pos in grid_pos.items(): grid_map[i] = idx grid_cart[i] = geo2cart({"elev": 0, "lon": pos.lon, "lat": pos.lat}) i += 1 # Put the homogeneous grid into a KD-tree and query the border points to include also point slightly in the sea kd = cKDTree(grid_cart) for idx in range(len(x)): _, closest_grid_idx = kd.query( geo2cart({"elev": 0, "lon": y[idx], "lat": x[idx]}), k=1 ) grid_id = grid_map[closest_grid_idx] if ( great_circle( (grid_pos[grid_id].lat, grid_pos[grid_id].lon), (x[idx], y[idx]) ).meters < 300000 ): # 300000 -> number elaborated to keep the out-of-coast values without including wrong points allowed_points.add(grid_map[closest_grid_idx]) return allowed_points # noinspection PyTypeChecker
[ 2, 220, 12131, 309, 2002, 292, 78, 37685, 1046, 3216, 290, 8118, 330, 17902, 8118, 32176, 2743, 198, 11748, 28686, 198, 11748, 33918, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 19720, 1330, 5345, 11, 7343, 198, 6738, 4903, 1108...
2.245639
1,433
# coding: utf-8 """ Grafeas API An API to insert and retrieve annotations on cloud artifacts. # noqa: E501 OpenAPI spec version: v1alpha1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from grafeas.models.deployment_details_platform import DeploymentDetailsPlatform # noqa: F401,E501 def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, DeployableDeploymentDetails): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 220, 220, 220, 7037, 5036, 292, 7824, 628, 220, 220, 220, 1052, 7824, 284, 7550, 290, 19818, 37647, 319, 6279, 20316, 13, 220, 1303, 645, 20402, 25, 412, 33548, 628, 220, 220, ...
2.618785
362
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: stdrickforce (Tengyuan Fan) # Email: <stdrickforce@gmail.com> <fantengyuan@baixing.com> import cat import time def test2(): ''' Use via context manager ''' with cat.Transaction("Trans", "T2") as t: cat.log_event("Event", "E2") try: do_something() except Exception: t.set_status(cat.CAT_ERROR) t.add_data("context-manager") t.add_data("foo", "bar") if __name__ == '__main__': cat.init("pycat", debug=True, logview=False) for i in range(100): test1() test2() test3() time.sleep(0.01) time.sleep(1)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 6434, 25, 14367, 5557, 3174, 357, 24893, 1360, 7258, 13836, 8, 198, 2, 9570, 25, 1279, 19282, 5557, 3174, 31,...
2.035608
337
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file ui_hw_recovery_wdg.ui # # Created by: PyQt5 UI code generator # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 5178, 7822, 7560, 422, 3555, 334, 72, 2393, 334, 72, 62, 36599, 62, 260, 1073, 548, 62, 16993, 70, 13, 9019, 198, 2, 198, 2, 15622, 416, 25, 9485, 48, 83, ...
3
112
# -*- coding: utf-8 -*- import csv from matplotlib import pyplot as plt from matplotlib.backends.backend_pdf import PdfPages # CLASS ANALYSER
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 269, 21370, 198, 198, 6738, 2603, 29487, 8019, 1330, 12972, 29487, 355, 458, 83, 198, 6738, 2603, 29487, 8019, 13, 1891, 2412, 13, 1891, 437, 62, 12315, 1330, 350...
2.607143
56
# Definition for binary tree with next pointer.
[ 2, 30396, 329, 13934, 5509, 351, 1306, 17562, 13, 628 ]
4.9
10
#!/usr/bin/env python3 import sys, os, glob from glbase3 import * all_species = glload('species_annotations/species.glb') newl = [] for file in glob.glob('pep_counts/*.txt'): oh = open(file, 'rt') count = int(oh.readline().split()[0]) oh.close() species_name = os.path.split(file)[1].split('.')[0].lower() # seems a simple rule assembly_name = os.path.split(file)[1].replace('.txt', '') if count < 5000: continue newl.append({'species': species_name, 'assembly_name': assembly_name, 'num_pep': count}) pep_counts = genelist() pep_counts.load_list(newl) all_species = all_species.map(genelist=pep_counts, key='species') all_species = all_species.removeDuplicates('name') print(all_species) all_species = all_species.getColumns(['name', 'species', 'division' ,'num_pep', 'assembly_name']) all_species.sort('name') all_species.saveTSV('all_species.tsv') all_species.save('all_species.glb') # and add the peptide counts for all species
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 25064, 11, 28686, 11, 15095, 198, 6738, 1278, 8692, 18, 1330, 1635, 628, 198, 439, 62, 35448, 796, 308, 297, 1170, 10786, 35448, 62, 34574, 602, 14, 35448, 13, 4743, 65, 1...
2.591029
379
import boto3 from prettytable import PrettyTable
[ 11748, 275, 2069, 18, 198, 6738, 2495, 11487, 1330, 20090, 10962, 628, 198 ]
3.923077
13
import sys sys.path.append("..") # Adds higher directory to python modules path.
[ 11748, 25064, 198, 17597, 13, 6978, 13, 33295, 7203, 492, 4943, 1303, 34333, 2440, 8619, 284, 21015, 13103, 3108, 13 ]
4
20
from __future__ import absolute_import, division, print_function ''' Author : Lyubimov, A.Y. Created : 04/14/2014 Last Changed: 11/05/2018 Description : wxPython 3-4 compatibility tools The context managers, classes, and other tools below can be used to make the GUI code compatible with wxPython 3 and 4. Mostly, the tools convert the functions, enumerations, and classes which have been renamed in wxPython 4; the name mismatches result in exceptions. Use case 1: subclassing wx.PyControl or wx.Control: from wxtbx import wx4_compatibility as wx4c WxCtrl = wx4c.get_wx_mod(wx, wx.Control) class MyCustomControl(WxCtrl): ... Use case 2: brush style (NOTE: you can do that with fonts as well, but it doesn't seem to be necessary): from wxtbx import wx4_compatibility as wx4c bkgrd = self.GetBackgroundColour() with wx4c.set_brush_style(wx.BRUSHSTYLE_SOLID) as bstyle: brush = wx.Brush(bkgrd, bstyle) Use case 3: Toolbars from wxtbx import wx4_compatibility as wx4c, bitmaps class MyFrame(wx.Frame): def __init__(self, parent, id, title, *args, **kwargs): wx.Frame.__init__(self, parent, id, title, *args, **kwargs) self.toolbar = wx4c.ToolBar(self, style=wx.TB_TEXT) self.quit_button = self.toolbar.AddTool(toolId=wx.ID_ANY, label='Quit', kind=wx.ITEM_NORMAL, bitmap=bitmaps.fetch_icon_bitmap('actions', 'exit') shortHelp='Exit program') ... self.SetToolBar(self.toolbar) self.toolbar.Realize() ''' import wx from contextlib import contextmanager import importlib wx4 = wx.__version__[0] == '4' modnames = [ ('PyControl', 'Control'), ('PyDataObjectSimple', 'DataObjectSimple'), ('PyDropTarget', 'DropTarget'), ('PyEvtHandler', 'EvtHandler'), ('PyImageHandler', 'ImageHandler'), ('PyLocale', 'Locale'), ('PyLog', 'Log'), ('PyPanel', 'Panel'), ('PyPickerBase', 'PickerBase'), ('PyPreviewControlBar', 'PreviewControlBar'), ('PyPreviewFrame', 'PreviewFrame'), ('PyPrintPreview', 'PrintPreview'), ('PyScrolledWindow', 'ScrolledWindow'), ('PySimpleApp', 'App'), ('PyTextDataObject', 'TextDataObject'), ('PyTimer', 'Timer'), ('PyTipProvider', 'adv.TipProvider'), ('PyValidator', 'Validator'), ('PyWindow'', Window') ] font_families = [ (wx.DEFAULT, wx.FONTFAMILY_DEFAULT), (wx.DECORATIVE, wx.FONTFAMILY_DECORATIVE), (wx.ROMAN, wx.FONTFAMILY_ROMAN), (wx.SCRIPT, wx.FONTFAMILY_SCRIPT), (wx.SWISS, wx.FONTFAMILY_SWISS), (wx.MODERN, wx.FONTFAMILY_MODERN), (wx.TELETYPE, wx.FONTFAMILY_TELETYPE) ] font_weights = [ (wx.NORMAL, wx.FONTWEIGHT_NORMAL), (wx.LIGHT, wx.FONTWEIGHT_LIGHT), (wx.BOLD, wx.FONTWEIGHT_BOLD) ] font_styles = [ (wx.NORMAL, wx.FONTSTYLE_NORMAL), (wx.ITALIC, wx.FONTSTYLE_ITALIC), (wx.SLANT, wx.FONTSTYLE_SLANT) ] pen_styles = [ (wx.SOLID, wx.PENSTYLE_SOLID), (wx.DOT, wx.PENSTYLE_DOT), (wx.LONG_DASH, wx.PENSTYLE_LONG_DASH), (wx.SHORT_DASH, wx.PENSTYLE_SHORT_DASH), (wx.DOT_DASH, wx.PENSTYLE_DOT_DASH), (wx.USER_DASH, wx.PENSTYLE_USER_DASH), (wx.TRANSPARENT, wx.PENSTYLE_TRANSPARENT) ] brush_styles = [ (wx.SOLID, wx.BRUSHSTYLE_SOLID), (wx.TRANSPARENT, wx.BRUSHSTYLE_TRANSPARENT), (wx.STIPPLE_MASK_OPAQUE, wx.BRUSHSTYLE_STIPPLE_MASK_OPAQUE), (wx.STIPPLE_MASK, wx.BRUSHSTYLE_STIPPLE_MASK), (wx.STIPPLE, wx.BRUSHSTYLE_STIPPLE), (wx.BDIAGONAL_HATCH, wx.BRUSHSTYLE_BDIAGONAL_HATCH), (wx.CROSSDIAG_HATCH, wx.BRUSHSTYLE_CROSSDIAG_HATCH), (wx.FDIAGONAL_HATCH, wx.BRUSHSTYLE_FDIAGONAL_HATCH), (wx.CROSS_HATCH, wx.BRUSHSTYLE_CROSS_HATCH), (wx.HORIZONTAL_HATCH, wx.BRUSHSTYLE_HORIZONTAL_HATCH), (wx.VERTICAL_HATCH, wx.BRUSHSTYLE_VERTICAL_HATCH), ] class Wx3ToolBar(wx.ToolBar): ''' Special toolbar class that accepts wxPython 4-style AddTool command and converts it to a wxPython 3-style AddLabelTool command ''' def AddTool(self, toolId, label, bitmap, bmpDisabled=wx.NullBitmap, kind=wx.ITEM_NORMAL, shortHelp='', longHelp='', clientData=None): ''' Override to make this a very thin wrapper for AddLabelTool, which in wxPython 3 is the same as AddTool in wxPython 4 ''' return self.AddLabelTool(id=toolId, label=label, bitmap=bitmap, bmpDisabled=bmpDisabled, kind=kind, shortHelp=shortHelp, longHelp=longHelp, clientData=clientData) class Wx4ToolBar(wx.ToolBar): ''' Special toolbar class that accepts wxPython 3-style AddLabelTool command and converts it to a wxPython 4-style AddTool command ''' def AddLabelTool(self, id, label, bitmap, bmpDisabled=wx.NullBitmap, kind=wx.ITEM_NORMAL, shortHelp='', longHelp='', clientData=None): ''' Override to make this a very thin wrapper for AddTool, which in wxPython 4 is the same as AddLabelTool in wxPython 3 ''' return self.AddTool(toolId=id, label=label, bitmap=bitmap, bmpDisabled=bmpDisabled, kind=kind, shortHelp=shortHelp, longHelp=longHelp, clientData=clientData) # Use this ToolBar class to create toolbars in frames ToolBar = Wx4ToolBar if wx4 else Wx3ToolBar
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 198, 198, 7061, 6, 198, 13838, 220, 220, 220, 220, 220, 1058, 9334, 549, 44273, 11, 317, 13, 56, 13, 198, 41972, 220, 220, 220, 220, 1058, 8702, 14, 141...
2.203404
2,409
import torch import torch.nn as nn import csv #image quantization #picecwise-linear color filter #parsing the data annotation # simple Module to normalize an image # values are standard normalization for ImageNet images, # from https://github.com/pytorch/examples/blob/master/imagenet/main.py norm = Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 269, 21370, 628, 198, 2, 9060, 5554, 1634, 198, 198, 2, 79, 501, 66, 3083, 12, 29127, 3124, 8106, 198, 198, 2, 79, 945, 278, 262, 1366, 23025, 628, 198, 2, 2829...
2.914729
129
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"get_device": "00_basics.ipynb", "settings_template": "00_basics.ipynb", "read_settings": "00_basics.ipynb", "DEVICE": "00_basics.ipynb", "settings": "00_basics.ipynb", "DATA_STORE": "00_basics.ipynb", "LOG_STORE": "00_basics.ipynb", "MODEL_STORE": "00_basics.ipynb", "EXPERIMENT_STORE": "00_basics.ipynb", "PATH_1K": "00_basics.ipynb", "PATH_10K": "00_basics.ipynb", "PATH_20K": "00_basics.ipynb", "PATH_100K": "00_basics.ipynb", "FILENAMES": "00_basics.ipynb", "SYNTHEA_DATAGEN_DATES": "00_basics.ipynb", "CONDITIONS": "00_basics.ipynb", "LOG_NUMERICALIZE_EXCEP": "00_basics.ipynb", "read_raw_ehrdata": "01_preprocessing_clean.ipynb", "split_patients": "01_preprocessing_clean.ipynb", "split_ehr_dataset": "01_preprocessing_clean.ipynb", "cleanup_pts": "01_preprocessing_clean.ipynb", "cleanup_obs": "01_preprocessing_clean.ipynb", "cleanup_algs": "01_preprocessing_clean.ipynb", "cleanup_crpls": "01_preprocessing_clean.ipynb", "cleanup_meds": "01_preprocessing_clean.ipynb", "cleanup_img": "01_preprocessing_clean.ipynb", "cleanup_procs": "01_preprocessing_clean.ipynb", "cleanup_cnds": "01_preprocessing_clean.ipynb", "cleanup_immns": "01_preprocessing_clean.ipynb", "cleanup_dataset": "01_preprocessing_clean.ipynb", "extract_ys": "01_preprocessing_clean.ipynb", "insert_age": "01_preprocessing_clean.ipynb", "clean_raw_ehrdata": "01_preprocessing_clean.ipynb", "load_cleaned_ehrdata": "01_preprocessing_clean.ipynb", "load_ehr_vocabcodes": "01_preprocessing_clean.ipynb", "EhrVocab": "02_preprocessing_vocab.ipynb", "ObsVocab": "02_preprocessing_vocab.ipynb", "EhrVocabList": "02_preprocessing_vocab.ipynb", "get_all_emb_dims": "02_preprocessing_vocab.ipynb", "collate_codes_offsts": "03_preprocessing_transform.ipynb", "get_codenums_offsts": "03_preprocessing_transform.ipynb", "get_demographics": "03_preprocessing_transform.ipynb", "Patient": "03_preprocessing_transform.ipynb", "get_pckl_dir": "03_preprocessing_transform.ipynb", "PatientList": "03_preprocessing_transform.ipynb", "cpu_cnt": "03_preprocessing_transform.ipynb", "create_all_ptlists": "03_preprocessing_transform.ipynb", "preprocess_ehr_dataset": "03_preprocessing_transform.ipynb", "EHRDataSplits": "04_data.ipynb", "LabelEHRData": "04_data.ipynb", "EHRDataset": "04_data.ipynb", "EHRData": "04_data.ipynb", "accuracy": "05_metrics.ipynb", "null_accuracy": "05_metrics.ipynb", "ROC": "05_metrics.ipynb", "MultiLabelROC": "05_metrics.ipynb", "plot_rocs": "05_metrics.ipynb", "plot_train_valid_rocs": "05_metrics.ipynb", "auroc_score": "05_metrics.ipynb", "auroc_ci": "05_metrics.ipynb", "save_to_checkpoint": "06_learn.ipynb", "load_from_checkpoint": "06_learn.ipynb", "get_loss_fn": "06_learn.ipynb", "RunHistory": "06_learn.ipynb", "train": "06_learn.ipynb", "evaluate": "06_learn.ipynb", "fit": "06_learn.ipynb", "predict": "06_learn.ipynb", "plot_loss": "06_learn.ipynb", "plot_losses": "06_learn.ipynb", "plot_aurocs": "06_learn.ipynb", "plot_train_valid_aurocs": "06_learn.ipynb", "plot_fit_results": "06_learn.ipynb", "summarize_prediction": "06_learn.ipynb", "count_parameters": "06_learn.ipynb", "dropout_mask": "07_models.ipynb", "InputDropout": "07_models.ipynb", "linear_layer": "07_models.ipynb", "create_linear_layers": "07_models.ipynb", "init_lstm": "07_models.ipynb", "EHR_LSTM": "07_models.ipynb", "init_cnn": "07_models.ipynb", "conv_layer": "07_models.ipynb", "EHR_CNN": "07_models.ipynb", "get_data": "08_experiment.ipynb", "get_optimizer": "08_experiment.ipynb", "get_model": "08_experiment.ipynb", "Experiment": "08_experiment.ipynb"} modules = ["basics.py", "preprocessing/clean.py", "preprocessing/vocab.py", "preprocessing/transform.py", "data.py", "metrics.py", "learn.py", "models.py", "experiment.py"] doc_url = "https://corazonlabs.github.io/lemonpie/" git_url = "https://github.com/corazonlabs/lemonpie/tree/main/"
[ 2, 47044, 7730, 1677, 1137, 11617, 11050, 41354, 39345, 0, 8410, 5626, 48483, 0, 198, 198, 834, 439, 834, 796, 14631, 9630, 1600, 366, 18170, 1600, 366, 23144, 62, 15390, 62, 28751, 1600, 366, 18300, 62, 6371, 8973, 198, 198, 9630, 79...
1.903405
2,526
# Convert the caffe2 model into tensorboard GraphDef # # The details of caffe2 model is on the compat/proto/caffe2/caffe2.proto # And the details of GraphDef model is on the compat/proto/graph.proto # ################################################################################ from tensorboard.compat.proto import graph_pb2 from tensorboard.compat.proto import attr_value_pb2 from tensorboard.compat.proto import node_def_pb2 from tensorboard.compat.proto import tensor_shape_pb2 from tensorboard.compat.proto import tensor_pb2 from tensorboard.compat.proto import types_pb2 from tensorboard.compat.proto.caffe2 import caffe2_pb2 from tensorboard.util import tb_logging from tensorboard.plugins.graph_edit import tbgraph_base from google.protobuf import text_format logger = tb_logging.get_logger()
[ 2, 38240, 262, 21121, 17, 2746, 656, 11192, 273, 3526, 29681, 7469, 198, 2, 198, 2, 383, 3307, 286, 21121, 17, 2746, 318, 319, 262, 8330, 14, 1676, 1462, 14, 66, 21223, 17, 14, 66, 21223, 17, 13, 1676, 1462, 198, 2, 843, 262, 33...
3.181102
254
#!/usr/bin/env python # The MIT License (MIT) # Copyright (c) 2014 Alex Aquino dos Santos # Technische Universitt Mnchen (TUM) # Autonomous Navigation for Flying Robots # Homework 2.1 from plot import plot
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 383, 17168, 13789, 357, 36393, 8, 198, 2, 15069, 357, 66, 8, 1946, 4422, 11446, 2879, 23430, 28458, 198, 198, 2, 5429, 46097, 26986, 715, 36030, 6607, 357, 51, 5883, 8, 198, ...
3.265625
64
from configs import args import tensorflow as tf
[ 6738, 4566, 82, 1330, 26498, 198, 198, 11748, 11192, 273, 11125, 355, 48700, 628, 198 ]
3.466667
15
from datetime import datetime, timedelta from typing import Any, Union from jose import jwt from passlib.context import CryptContext from .config import settings pwd_context = CryptContext( default="django_pbkdf2_sha256", schemes=["django_argon2", "django_bcrypt", "django_bcrypt_sha256", "django_pbkdf2_sha256", "django_pbkdf2_sha1", "django_disabled"]) ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 8 # 8 days ''' Arquivo de configurao de segurana dos tokens JWT - Mtodos de verificao e criao de hash de senha - Mtodo para criar o token jwt vlido '''
[ 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 198, 6738, 19720, 1330, 4377, 11, 4479, 198, 198, 6738, 474, 577, 1330, 474, 46569, 198, 6738, 1208, 8019, 13, 22866, 1330, 15126, 21947, 198, 198, 6738, 764, 11250, 1330, 6460, 198,...
2.367424
264
#!/usr/bin/env python from flask import Flask from flask import jsonify, render_template, redirect from flask import request, Response from saml_auth import BaseAuth, SamlAuth import os, sys try: import json except ImportError: # couldn't find json, try simplejson library import simplejson as json import getopt from operator import itemgetter from distutils.version import LooseVersion from reposadolib import reposadocommon apple_catalog_version_map = { 'index-10.14-10.13-10.12-10.11-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog': '10.14', 'index-10.13-10.12-10.11-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog': '10.13', 'index-10.12-10.11-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog': '10.12', 'index-10.11-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog': '10.11', 'index-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog': '10.10', 'index-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog': '10.9', 'index-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog': '10.8', 'index-lion-snowleopard-leopard.merged-1.sucatalog': '10.7', 'index-leopard-snowleopard.merged-1.sucatalog': '10.6', 'index-leopard.merged-1.sucatalog': '10.5', 'index-1.sucatalog': '10.4', 'index.sucatalog': '10.4', } BASE_AUTH_CLASS = BaseAuth app, auth = build_app() # cache the keys of the catalog version map dict apple_catalog_suffixes = apple_catalog_version_map.keys() def versions_from_catalogs(cats): '''Given an iterable of catalogs return the corresponding OS X versions''' versions = set() for cat in cats: # take the last portion of the catalog URL path short_cat = cat.split('/')[-1] if short_cat in apple_catalog_suffixes: versions.add(apple_catalog_version_map[short_cat]) return versions def json_response(r): '''Glue for wrapping raw JSON responses''' return Response(json.dumps(r), status=200, mimetype='application/json') def get_description_content(html): if len(html) == 0: return None # in the interest of (attempted) speed, try to avoid regexps lwrhtml = html.lower() celem = 'p' startloc = lwrhtml.find('<' + celem + '>') if startloc == -1: startloc = lwrhtml.find('<' + celem + ' ') if startloc == -1: celem = 'body' startloc = lwrhtml.find('<' + celem) if startloc != -1: startloc += 6 # length of <body> if startloc == -1: # no <p> nor <body> tags. bail. return None endloc = lwrhtml.rfind('</' + celem + '>') if endloc == -1: endloc = len(html) elif celem != 'body': # if the element is a body tag, then don't include it. # DOM parsing will just ignore it anyway endloc += len(celem) + 3 return html[startloc:endloc] def product_urls(cat_entry): '''Retreive package URLs for a given reposado product CatalogEntry. Will rewrite URLs to be served from local reposado repo if necessary.''' packages = cat_entry.get('Packages', []) pkg_urls = [] for package in packages: pkg_urls.append({ 'url': reposadocommon.rewriteOneURL(package['URL']), 'size': package['Size'], }) return pkg_urls
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 6738, 42903, 1330, 46947, 198, 6738, 42903, 1330, 33918, 1958, 11, 8543, 62, 28243, 11, 18941, 198, 6738, 42903, 1330, 2581, 11, 18261, 198, 6738, 6072, 75, 62, 18439, 1330, 7308, 30515,...
2.507631
1,245
# -*- python -*- """@file @brief pyserial transport for pato Copyright (c) 2014-2015 Dimitry Kloper <kloper@users.sf.net>. All rights reserved. @page License Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the Pato Project. """ import serial from util.protocol import ProtocolException
[ 2, 532, 9, 12, 21015, 532, 9, 12, 198, 37811, 31, 7753, 198, 198, 31, 65, 3796, 279, 893, 48499, 4839, 329, 1458, 78, 198, 198, 15269, 357, 66, 8, 1946, 12, 4626, 14048, 270, 563, 14770, 3575, 1279, 41582, 3575, 31, 18417, 13, 2...
3.582979
470
import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import QFont, QPixmap from PyQt5.QtCore import QTimer from random import randint font = QFont("Times", 14) buttonFont = QFont("Arial", 12) computerScore = 0 playerScore = 0 if __name__ == '__main__': main()
[ 11748, 25064, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 54, 312, 11407, 1330, 1635, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 8205, 72, 1330, 1195, 23252, 11, 1195, 47, 844, 8899, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 14055, ...
2.570093
107
from os import walk import h5py import numpy as np from config.Database import Base from config.Database import engine from config.Database import Session from models.Music import Music from kmeans.kmeans import Kmeans mypath = './dataset/datatr/' if __name__ == "__main__": main()
[ 6738, 28686, 1330, 2513, 198, 11748, 289, 20, 9078, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 4566, 13, 38105, 1330, 7308, 198, 6738, 4566, 13, 38105, 1330, 3113, 198, 6738, 4566, 13, 38105, 1330, 23575, 198, 198, 6738, 4981, 13, ...
3.141304
92
import torch.nn as nn import pretrainedmodels
[ 11748, 28034, 13, 20471, 355, 299, 77, 201, 198, 11748, 2181, 13363, 27530, 201, 198, 201, 198 ]
2.941176
17
""" Given a Boolean function/network, get its algebraic state-space representation. A logical vector `\delta_n^i` is represented by an integer `i` for space efficiency. Consequently, a logical matrix is represented by a list, each element for one column, (also known as the "condensed form"). [1] Conversion from an infix expression to a postfix one: https://runestone.academy/runestone/books/published/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html [2] Logical connectives: https://en.wikipedia.org/wiki/Logical_connective Author: Gao Shuhua """ import operator import os from typing import List, Union, Tuple, Iterable, Dict from .bcn import BooleanNetwork, BooleanControlNetwork _COMMENT = '#' _STATES = '[STATES]' _CONTROLS = '[CONTROLS]' LOGICAL_CONNECTIVES = { 'NOT': LogicalConnective('NOT', 'not', 1, 0, operator.not_), 'XOR': LogicalConnective('XOR', 'exclusive disjunction', 2, 1, operator.xor), 'AND': LogicalConnective('AND', 'and', 2, 2, operator.and_), 'OR': LogicalConnective('OR', 'or', 2, 3, operator.or_), 'IMPLY': LogicalConnective('IMPLY', 'implication', 2, 4, _imply), 'EQUIV': LogicalConnective('EQUIV', 'equivalent', 2, 5, _xnor) } def _infix_to_postfix(expression: str) -> List[Union[LogicalConnective, str]]: """ Convert an infix expression to its postfix form. :param expression: infix, separated by spaces :return: postfix expression, a list, whose element is an operator (LogicalConnective) or a variable (str) """ # parse tokens: handle ( and ) specially, which may not be separated by spaces, e.g., 'A OR (B AND C)' items = expression.split() tokens = [] for item in items: token = '' for c in item: if c in '()': if token: tokens.append(token) token = '' tokens.append(c) else: token = token + c if token: tokens.append(token) # conversion op_stack = [] output = [] for token in tokens: if token.upper() in LOGICAL_CONNECTIVES: # an operator connective = LOGICAL_CONNECTIVES[token.upper()] while op_stack and isinstance(op_stack[-1], LogicalConnective) and \ op_stack[-1].precedence < connective.precedence: output.append(op_stack.pop()) op_stack.append(connective) elif token == '(': op_stack.append(token) elif token == ')': left_parenthesis_found = False while op_stack: top = op_stack.pop() if top == '(': left_parenthesis_found = True break else: output.append(top) if not left_parenthesis_found: raise RuntimeError("Unmatched parentheses are encountered: an extra ')'!") elif token.upper() in ['1', 'TRUE']: output.append('TRUE') elif token.upper() in ['0', 'FALSE']: output.append('FALSE') else: # a variable output.append(token) while op_stack: top = op_stack.pop() if top == '(': raise RuntimeError("Unmatched parentheses are encountered: an extra '('!") output.append(top) return output def _evaluate_postfix(expression, values: {}): """ Evaluate a postfix expression with the given parameter values. :param expression: postfix :param values: a dict: variable --> value (0/1 or False/True) :return: a Boolean variable, or 0/1 """ operand_stack = [] for token in expression: if isinstance(token, str): # a variable if token in values: val = values[token] operand_stack.append(val) elif token == 'TRUE': operand_stack.append(True) elif token == 'FALSE': operand_stack.append(False) else: raise RuntimeError(f"Unrecognized variable: '{token}'") else: # a logical connective arguments = [] for _ in range(token.arity): arguments.append(operand_stack.pop()) result = token(*arguments[::-1]) operand_stack.append(result) return operand_stack.pop() def _assr_function(pf_expr: List[Union[LogicalConnective, str]], states: List[str], controls: List[str]) -> List[int]: """ Compute the ASSR for a Boolean function. :param pf_expr: the postfix expression of a Boolean function :param states: the state variables :param controls: the control inputs. If `None`, then no inputs. :return: the structure matrix, a list of length MN """ n = len(states) m = len(controls) N = 2 ** n M = 2 ** m MN = M * N all_variables = controls + states structure_matrix = [None] * MN # enumerate the binary sequences to get the truth table for h in range(MN): bh = f'{h:0{m+n}b}' values = {var: int(val) for var, val in zip(all_variables, bh)} output = _evaluate_postfix(pf_expr, values) k = MN - h if output: # 1 (True) structure_matrix[k - 1] = 1 else: structure_matrix[k - 1] = 2 return structure_matrix def _tokenize(state_to_expr: Dict[str, str], controls: Iterable[str]=None) -> Tuple[Dict[str, List[Union[LogicalConnective, str]]], List[str]]: """ (1) Parse the `exprs` into postfix forms (2) Infer the control inputs, if `controls` is `None` :return: the tokenized expressions and the controls """ state_to_pf_expr = {s: _infix_to_postfix(e) for s, e in state_to_expr.items()} if controls is None: # infer controls controls = [] for pf_expr in state_to_pf_expr.values(): for t in pf_expr: if isinstance(t, str): # t is a variable, or 'TRUE' or 'FALSE' if t not in ['TRUE', 'FALSE'] and t not in state_to_pf_expr: # a control if t not in controls: controls.append(t) else: controls = list(controls) # validate for s, pf_expr in state_to_pf_expr.items(): for t in pf_expr: if isinstance(t, str): assert t in state_to_pf_expr or t in controls, f"Unrecognized variable: '{t}' in equation of {s}" return state_to_pf_expr, controls def _assr_network(state_to_pf_expr: Dict[str, List[Union[LogicalConnective, str]]], states: List[str], controls: List[str], verbose: bool=True) -> List[int]: """ Get the ASSR of a Boolean (control) network. :param state_to_pf_expr: state -> its postfix expression :param states: state variables :param controls: control inputs. :return: network transition matrix, each column is represented by an integer """ assert len(state_to_pf_expr) == len(states), 'The number of Boolean functions must be equal to the number of state states' # get the structure matrix of each state (i.e., its Boolean equation) state_to_sms = {} for s, pf_expr in state_to_pf_expr.items(): if verbose: print(f'\tComputing the structure matrix for state {s} ...') state_to_sms[s] = _assr_function(pf_expr, states, controls) n = len(states) m = len(controls) transition_matrix = [None] * (2 ** m * 2 ** n) stp = lambda i, j: (i - 1) * 2 + j if verbose: print('\tComposing the complete network transition matrix...') for k in range(len(transition_matrix)): # k-th column r = 1 for s in states: sm = state_to_sms[s] r = stp(r, sm[k]) transition_matrix[k] = r return transition_matrix def build_ASSR(source: Union[str, Iterable[str]], states: List[str]=None, controls: List[str]=None, verbose: bool=True) -> Union[BooleanNetwork, BooleanControlNetwork]: """ Build the ASSR for a given Boolean network in a string form. Each Boolean function is given by the form: state = f(states, controls). If a text file is given, each Boolean function is provided per line, and '#' starts a comment line :param source: str or a list of str. (1) str: a single Boolean function or a text file, which contains one or more Boolean functions (i.e., a network), each per line; (2) a list of str: multiple Boolean functions :param states: state variables. If `None`, then inferred automatically. :param controls: control inputs. If this a Boolean network with no inputs, then give it an empty List. If `None`, then inferred automatically. :param verbose: whether to print more information :return: a Boolean network if there are no inputs; otherwise, a Boolean control network .. note:: If the states and controls are inferred, the order of states corresponds to the line order, whereas the order of controls depend on their appearance order in the equations. To precisely control the order (especially for controls), two additional lines may be appended after the state equations that begin with "[STATES]" or "[CONTROLS]". For example, line "[STATES] AKT MKK EGFR" specifies the state order (AKT, MKK, EGFR). Of course, both "[STATES]" and "[CONTROLS]" lines are optional. The non-None arguments `states` and `controls` have higher precedence than "[STATES]" and "[CONTROLS]" lines respectively. """ # get the strings of a network net = [] if isinstance(source, str): if os.path.isfile(source): if verbose: print(f'User provided a network file: {source}\nParsing...') with open(source, 'r') as f: for line in f: line = line.strip() if line.startswith(_COMMENT): continue elif line.startswith(_STATES): if states is None: words = line.split() states = [w.strip() for w in words[1:]] elif line.startswith(_CONTROLS): if controls is None: words = line.split() controls = [w.strip() for w in words[1:]] else: if line: # skip empty lines if any net.append(line) else: if verbose: print(f'User provided a single Boolean equation.') net.append(source) else: if verbose: print(f'User provided a list of Boolean equations.') net = list(source) # extract the states and equations state_to_expr = {} inferred_states = [] for eq in net: state, expr = eq.split('=') state = state.strip() expr = expr.strip() if states is not None: assert state in states, f'Unexpected state {state} is encountered!' else: inferred_states.append(state) assert state not in state_to_expr, f'More than one equation is provided for state {state}' state_to_expr[state] = expr if states is not None: for s in states: assert s in state_to_expr, f'The equation for state {s} is missing' else: states = inferred_states if verbose: print('Tokenizing...') # tokenize state_to_pf_expr, controls = _tokenize(state_to_expr, controls) assert set(states).isdisjoint(controls), 'States and controls should be disjoint' if verbose: print(f'States are {states}') print(f'Controls are {controls}') print('Computing...') # get the ASSR the network L = _assr_network(state_to_pf_expr, states, controls, verbose) # wrap them into a Boolean (control) network m = len(controls) n = len(states) if m == 0: return BooleanNetwork(n, L, states) return BooleanControlNetwork(n, m, L, states, controls)
[ 37811, 198, 15056, 257, 41146, 2163, 14, 27349, 11, 651, 663, 37139, 291, 1181, 12, 13200, 10552, 13, 198, 198, 32, 12219, 15879, 4600, 59, 67, 12514, 62, 77, 61, 72, 63, 318, 7997, 416, 281, 18253, 4600, 72, 63, 329, 2272, 9332, ...
2.33269
5,182
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # Extended by Linjie Deng # -------------------------------------------------------- import os import cv2 import numpy as np import torch import torch.utils.data as data import xml.etree.ElementTree as ET from utils.bbox import quad_2_rbox if __name__ == '__main__': pass
[ 2, 20368, 22369, 198, 2, 12549, 371, 12, 18474, 198, 2, 15069, 357, 66, 8, 1853, 5413, 198, 2, 49962, 739, 383, 17168, 13789, 685, 3826, 38559, 24290, 329, 3307, 60, 198, 2, 22503, 416, 9847, 23837, 1477, 624, 198, 2, 24204, 416, ...
3.891667
120
import discord import random import asyncio import logging import urllib.request from discord.ext import commands bot = commands.Bot(command_prefix='nep ', description= "Nep Nep") counter = 0 countTask = None token = "insert token here" bot.run(token)
[ 11748, 36446, 198, 11748, 4738, 198, 11748, 30351, 952, 198, 11748, 18931, 198, 11748, 2956, 297, 571, 13, 25927, 198, 6738, 36446, 13, 2302, 1330, 9729, 198, 198, 13645, 796, 9729, 13, 20630, 7, 21812, 62, 40290, 11639, 77, 538, 46083,...
3.432432
74
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Turkey - Accounting', 'version': '1.0', 'category': 'Localization', 'description': """ Trkiye iin Tek dzen hesap plan ablonu Odoo Modl. ========================================================== Bu modl kurulduktan sonra, Muhasebe yaplandrma sihirbaz alr * Sihirbaz sizden hesap plan ablonu, plann kurulaca irket, banka hesap bilgileriniz, ilgili para birimi gibi bilgiler isteyecek. """, 'author': 'Ahmet Altnk, Can Tecim', 'maintainer':'https://launchpad.net/~openerp-turkey, http://www.cantecim.com', 'depends': [ 'account', ], 'data': [ 'data/l10n_tr_chart_data.xml', 'data/account.account.template.csv', 'data/l10n_tr_chart_post_data.xml', 'data/account_data.xml', 'data/account_tax_template_data.xml', 'data/account_chart_template_data.xml', ], 'license': 'LGPL-3', }
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2142, 286, 10529, 2238, 13, 4091, 38559, 24290, 2393, 329, 1336, 6634, 290, 15665, 3307, 13, 198, 198, 90, 198, 220, 220, 220, 705, 3672, 10354, 705, 31632, 532, 40...
2.314815
432
import os import time import argparse import pandas as pd from smf import SessionMF parser = argparse.ArgumentParser() parser.add_argument('--K', type=int, default=20, help="K items to be used in Recall@K and MRR@K") parser.add_argument('--factors', type=int, default=100, help="Number of latent factors.") parser.add_argument('--batch', type=int, default=32, help="Batch size for the training process") parser.add_argument('--momentum', type=float, default=0.0, help="Momentum of the optimizer adagrad_sub") parser.add_argument('--regularization', type=float, default=0.0001, help="Regularization Amount of the objective function") parser.add_argument('--dropout', type=float, default=0.0, help="Share of items that are randomly discarded from the current session while training") parser.add_argument('--skip', type=float, default=0.0, help="Probability that an item is skiped and the next one is used as the positive example") parser.add_argument('--neg_samples', type=int, default=2048, help="Number of items that are sampled as negative examples") parser.add_argument('--activation', type=str, default='linear', help="Final activation function (linear, sigmoid, uf_sigmoid, hard_sigmoid, relu, softmax, softsign, softplus, tanh)") parser.add_argument('--objective', type=str, default='bpr_max', help="Loss Function (bpr_max, top1_max, bpr, top1)") parser.add_argument('--epochs', type=int, default=10, help="Number of Epochs") parser.add_argument('--lr', type=float, default=0.001, help="Learning Rate") parser.add_argument('--itemid', default='ItemID', type=str) parser.add_argument('--sessionid', default='SessionID', type=str) parser.add_argument('--valid_data', default='recSys15Valid.txt', type=str) parser.add_argument('--train_data', default='recSys15TrainOnly.txt', type=str) parser.add_argument('--data_folder', default='/home/icvuser/Desktop/Recsys cleaned data/RecSys15 Dataset Splits', type=str) # Get the arguments args = parser.parse_args() train_data = os.path.join(args.data_folder, args.train_data) x_train = pd.read_csv(train_data) x_train.sort_values(args.sessionid, inplace=True) x_train = x_train.iloc[-int(len(x_train) / 64) :] #just take 1/64 last instances valid_data = os.path.join(args.data_folder, args.valid_data) x_valid = pd.read_csv(valid_data) x_valid.sort_values(args.sessionid, inplace=True) print('Finished Reading Data \nStart Model Fitting...') # Fitting Model t1 = time.time() model = SessionMF(factors = args.factors, session_key = args.sessionid, item_key = args.itemid, batch = args.batch, momentum = args.momentum, regularization = args.regularization, dropout = args.dropout, skip = args.skip, samples = args.neg_samples, activation = args.activation, objective = args.objective, epochs = args.epochs, learning_rate = args.lr) model.fit(x_train) t2 = time.time() print('End Model Fitting with total time =', t2 - t1, '\n Start Predictions...') # Test Set Evaluation test_size = 0.0 hit = 0.0 MRR = 0.0 cur_length = 0 cur_session = -1 last_items = [] t1 = time.time() index_item = x_valid.columns.get_loc(args.itemid) index_session = x_valid.columns.get_loc(args.sessionid) train_items = model.unique_items counter = 0 for row in x_valid.itertuples( index=False ): counter += 1 if counter % 10000 == 0: print('Finished Prediction for ', counter, 'items.') session_id, item_id = row[index_session], row[index_item] if session_id != cur_session: cur_session = session_id last_items = [] cur_length = 0 if item_id in model.item_map.keys(): if len(last_items) > cur_length: #make prediction cur_length += 1 test_size += 1 # Predict the most similar items to items predictions = model.predict_next(last_items, K = args.K) # Evaluation rank = 0 for predicted_item in predictions: #print(predicted_item, item_id, '###') rank += 1 if int(predicted_item) == item_id: hit += 1.0 MRR += 1/rank break last_items.append(item_id) t2 = time.time() print('Recall: {}'.format(hit / test_size)) print ('\nMRR: {}'.format(MRR / test_size)) print('End Model Predictions with total time =', t2 - t1)
[ 11748, 28686, 198, 11748, 640, 198, 11748, 1822, 29572, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 895, 69, 1330, 23575, 49800, 198, 198, 48610, 796, 1822, 29572, 13, 28100, 1713, 46677, 3419, 198, 48610, 13, 2860, 62, 49140, 1078...
2.628916
1,660
# coding: utf-8 """ App Center Client Microsoft Visual Studio App Center API # noqa: E501 OpenAPI spec version: preview Contact: benedetto.abbenanti@gmail.com Project Repository: https://github.com/b3nab/appcenter-sdks """ import pprint import re # noqa: F401 import six def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, Device): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 220, 220, 220, 2034, 3337, 20985, 628, 220, 220, 220, 5413, 15612, 11733, 2034, 3337, 7824, 220, 1303, 645, 20402, 25, 412, 33548, 628, 220, 220, 220, 4946, 17614, 1020, 2196, 25...
2.553191
329
#!/usr/bin/env python # -*- coding: utf-8 -*- # author : Thomas Cuthbert import os, sys from providers.provider import Provider from config.config import Config sys.path.append('../') def _strip_oid_from_list(oids, strip): """Iterates through list of oids and strips snmp tree off index. Returns sorted list of indexes. Keyword Arguments: self -- oid -- Regular numeric oid index strip -- Value to be stripped off index """ sorted_oids = [] for index in oids: s = index[0].replace(strip, "") sorted_oids.append((s, index[1])) return sorted(sorted_oids) def _get_snmp(oid, hostname, community): """SNMP Wrapper function. Returns tuple of oid, value Keyword Arguments: oid -- community -- """ from pysnmp.entity.rfc3413.oneliner import cmdgen cmd_gen = cmdgen.CommandGenerator() error_indication, error_status, error_index, var_bind = cmd_gen.getCmd( cmdgen.CommunityData(community), cmdgen.UdpTransportTarget((hostname, 161)), oid) if error_indication: print(error_indication) else: if error_status: print ('%s at %s' % ( error_status.prettyPrint(), error_index and var_bind[int(error_index)-1] or '?') ) else: for name, value in var_bind: return (name.prettyPrint(), value.prettyPrint())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 1772, 220, 220, 220, 1058, 5658, 327, 1071, 4835, 198, 11748, 28686, 11, 25064, 198, 6738, 9549, 13, 15234, 1304, ...
2.34684
617
import time import os import pickle import warnings from typing import Union, Type, Optional, Dict, Any, Callable import gym import torch as th import numpy as np from stable_baselines3.common import logger from stable_baselines3.common.base_class import BaseAlgorithm from stable_baselines3.common.policies import BasePolicy from stable_baselines3.common.utils import safe_mean from stable_baselines3.common.vec_env import VecEnv from stable_baselines3.common.type_aliases import GymEnv, RolloutReturn from stable_baselines3.common.callbacks import BaseCallback from stable_baselines3.common.noise import ActionNoise from stable_baselines3.common.buffers import ReplayBuffer
[ 11748, 640, 198, 11748, 28686, 198, 11748, 2298, 293, 198, 11748, 14601, 198, 6738, 19720, 1330, 4479, 11, 5994, 11, 32233, 11, 360, 713, 11, 4377, 11, 4889, 540, 198, 198, 11748, 11550, 198, 11748, 28034, 355, 294, 198, 11748, 299, 3...
3.573684
190
from django.conf.urls import url from django.contrib.auth import views as auth_views from django.contrib.auth.forms import AuthenticationForm from oscar.core.application import ( DashboardApplication as BaseDashboardApplication) from oscar.core.loading import get_class application = DashboardApplication()
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 5009, 355, 6284, 62, 33571, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 23914, 1330, 48191, 8479, 198, 198, ...
3.705882
85
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-04-07 20:17 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 940, 13, 19, 319, 2177, 12, 3023, 12, 2998, 1160, 25, 1558, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.888889
81
import pandas as pd import pickle
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 2298, 293 ]
3.3
10
from D_E_U import * D_E = DSS(*extra_layer(vgg(base['dss'], 3), extra['dss']),config.BATCH_SIZE).cuda() U = D_U().cuda() U.cuda() data_dirs = [ ("/home/rabbit/Datasets/DUTS/DUT-train/DUT-train-Image", "/home/rabbit/Datasets/DUTS/DUT-train/DUT-train-Mask"), ] test_dirs = [("/home/rabbit/Datasets/SED1/SED1-Image", "/home/rabbit/Datasets/SED1/SED1-Mask")] D_E.base.load_state_dict(torch.load('/home/rabbit/Desktop/DUT_train/weights/vgg16_feat.pth')) initialize_weights(U) DE_optimizer = optim.Adam(D_E.parameters(), lr=config.D_LEARNING_RATE, betas=(0.5, 0.999)) U_optimizer = optim.Adam(U.parameters(), lr=config.U_LEARNING_RATE, betas=(0.5, 0.999)) BCE_loss = torch.nn.BCELoss().cuda() batch_size =BATCH_SIZE DATA_DICT = {} IMG_FILES = [] GT_FILES = [] IMG_FILES_TEST = [] GT_FILES_TEST = [] for dir_pair in data_dirs: X, y = process_data_dir(dir_pair[0]), process_data_dir(dir_pair[1]) IMG_FILES.extend(X) GT_FILES.extend(y) for dir_pair in test_dirs: X, y = process_data_dir(dir_pair[0]), process_data_dir(dir_pair[1]) IMG_FILES_TEST.extend(X) GT_FILES_TEST.extend(y) IMGS_train, GT_train = IMG_FILES, GT_FILES train_folder = DataFolder(IMGS_train, GT_train, True) train_data = DataLoader(train_folder, batch_size=BATCH_SIZE, num_workers=NUM_WORKERS, shuffle=True, drop_last=True) test_folder = DataFolder(IMG_FILES_TEST, GT_FILES_TEST, trainable=False) test_data = DataLoader(test_folder, batch_size=1, num_workers=NUM_WORKERS, shuffle=False) best_eval = None x = 0 ma = 1 for epoch in range(1, config.NUM_EPOCHS + 1): sum_train_mae = 0 sum_train_loss = 0 sum_train_gan = 0 ##train for iter_cnt, (img_batch, label_batch, edges, shape, name) in enumerate(train_data): D_E.train() x = x + 1 # print(img_batch.size()) label_batch = Variable(label_batch).cuda() # print(torch.typename(label_batch)) print('training start!!') # for iter, (x_, _) in enumerate(train_data): img_batch = Variable(img_batch.cuda()) # ,Variable(z_.cuda()) edges = Variable(edges).cuda() ##########DSS######################### ######train dis ##fake f,y1,y2 = D_E(img_batch) m_l_1,e_l_1 = cal_DLoss(y1,y2,label_batch,edges) DE_optimizer.zero_grad() DE_l_1 = m_l_1 +e_l_1 DE_l_1.backward() DE_optimizer.step() w = [2,2,3,3] f, y1, y2 = D_E(img_batch) masks,DIC = U(f) pre_ms_l = 0 ma = torch.abs(label_batch-masks[4]).mean() pre_m_l = F.binary_cross_entropy(masks[4],label_batch) for i in range(4): pre_ms_l +=w[i] * F.binary_cross_entropy(masks[i],label_batch) DE_optimizer.zero_grad() DE_l_1 = pre_ms_l/20+30*pre_m_l DE_l_1.backward() DE_optimizer.step() f, y1, y2 = D_E(img_batch) masks,DIC = U(f) pre_ms_l = 0 ma = torch.abs(label_batch-masks[4]).mean() pre_m_l = F.binary_cross_entropy(masks[4], label_batch) for i in range(4): pre_ms_l += w[i] * F.binary_cross_entropy(masks[i], label_batch) U_optimizer.zero_grad() U_l_1 = pre_ms_l/20+30*pre_m_l U_l_1.backward() U_optimizer.step() sum_train_mae += ma.data.cpu() print("Epoch:{}\t {}/{}\ \t mae:{}".format(epoch, iter_cnt + 1, len(train_folder) / config.BATCH_SIZE, sum_train_mae / (iter_cnt + 1))) ##########save model # torch.save(D.state_dict(), './checkpoint/DSS/with_e_2/D15epoch%d.pkl' % epoch) torch.save(D_E.state_dict(), './checkpoint/DSS/with_e_2/D_Eepoch%d.pkl' % epoch) torch.save(U.state_dict(), './checkpoint/DSS/with_e_2/Uis.pkl') print('model saved') ###############test eval1 = 0 eval2 = 0 t_mae = 0 for iter_cnt, (img_batch, label_batch, edges, shape, name) in enumerate(test_data): D_E.eval() U.eval() label_batch = Variable(label_batch).cuda() print('val!!') # for iter, (x_, _) in enumerate(train_data): img_batch = Variable(img_batch.cuda()) # ,Variable(z_.cuda()) f,y1,y2 = D_E(img_batch) masks, DIC = U(f) mae_v2 = torch.abs(label_batch - masks[4]).mean().data[0] # eval1 += mae_v1 eval2 += mae_v2 # m_eval1 = eval1 / (iter_cnt + 1) m_eval2 = eval2 / (iter_cnt + 1) print("test mae", m_eval2) with open('results1.txt', 'a+') as f: f.write(str(epoch) + " 2:" + str(m_eval2) + "\n")
[ 6738, 360, 62, 36, 62, 52, 1330, 1635, 198, 198, 35, 62, 36, 796, 360, 5432, 46491, 26086, 62, 29289, 7, 85, 1130, 7, 8692, 17816, 67, 824, 6, 4357, 513, 828, 3131, 17816, 67, 824, 20520, 828, 11250, 13, 33, 11417, 62, 33489, 73...
1.905901
2,508
# Machine Learning Online Class - Exercise 2: Logistic Regression # # Instructions # ------------ # # This file contains code that helps you get started on the logistic # regression exercise. You will need to complete the following functions # in this exericse: # # sigmoid.py # costFunction.py # predict.py # costFunctionReg.py # # For this exercise, you will not need to change any code in this file, # or any other files other than those mentioned above. import matplotlib.pyplot as plt import numpy as np import scipy.optimize as opt from plotData import * import costFunction as cf import plotDecisionBoundary as pdb import predict as predict from sigmoid import * plt.ion() # Load data # The first two columns contain the exam scores and the third column contains the label. data = np.loadtxt('ex2data1.txt', delimiter=',') print('plot_decision_boundary data[0, 0:1] = \n{}'.format(data[0, 0:1])) print('plot_decision_boundary data[0, 0:2] = \n{}'.format(data[0, 0:2])) print('plot_decision_boundary data[0, 0:3] = \n{}'.format(data[0, 0:3])) print('plot_decision_boundary data[0, 1:1] = \n{}'.format(data[0, 1:1])) print('plot_decision_boundary data[0, 1:2] = \n{}'.format(data[0, 1:2])) print('plot_decision_boundary data[0, 1:3] = \n{}'.format(data[0, 1:3])) print('plot_decision_boundary data[0, 2:1] = \n{}'.format(data[0, 2:1])) print('plot_decision_boundary data[0, 2:2] = \n{}'.format(data[0, 2:2])) print('plot_decision_boundary data[0, 2:3] = \n{}'.format(data[0, 2:3])) X = data[:, 0:2] y = data[:, 2] # ===================== Part 1: Plotting ===================== # We start the exercise by first plotting the data to understand the # the problem we are working with. print('Plotting Data with + indicating (y = 1) examples and o indicating (y = 0) examples.') plot_data(X, y) plt.axis([30, 100, 30, 100]) # Specified in plot order. plt.legend(['Admitted', 'Not admitted'], loc=1) plt.xlabel('Exam 1 score') plt.ylabel('Exam 2 score') input('Program paused. Press ENTER to continue') # ===================== Part 2: Compute Cost and Gradient ===================== # In this part of the exercise, you will implement the cost and gradient # for logistic regression. You need to complete the code in # costFunction.py # Setup the data array appropriately, and add ones for the intercept term (m, n) = X.shape # Add intercept term X = np.c_[np.ones(m), X] # Initialize fitting parameters initial_theta = np.zeros(n + 1) # theta # Compute and display initial cost and gradient cost, grad = cf.cost_function(initial_theta, X, y) np.set_printoptions(formatter={'float': '{: 0.4f}\n'.format}) print('Cost at initial theta (zeros): {:0.3f}'.format(cost)) print('Expected cost (approx): 0.693') print('Gradient at initial theta (zeros): \n{}'.format(grad)) print('Expected gradients (approx): \n-0.1000\n-12.0092\n-11.2628') # Compute and display cost and gradient with non-zero theta test_theta = np.array([-24, 0.2, 0.2]) cost, grad = cf.cost_function(test_theta, X, y) print('Cost at test theta (zeros): {:0.3f}'.format(cost)) print('Expected cost (approx): 0.218') print('Gradient at test theta: \n{}'.format(grad)) print('Expected gradients (approx): \n0.043\n2.566\n2.647') input('Program paused. Press ENTER to continue') # ===================== Part 3: Optimizing using fmin_bfgs ===================== # In this exercise, you will use a built-in function (opt.fmin_bfgs) to find the # optimal parameters theta # Run fmin_bfgs to obtain the optimal theta theta, cost, *unused = opt.fmin_bfgs(f=cost_func, fprime=grad_func, x0=initial_theta, maxiter=400, full_output=True, disp=False) print('Cost at theta found by fmin: {:0.4f}'.format(cost)) print('Expected cost (approx): 0.203') print('theta: \n{}'.format(theta)) print('Expected Theta (approx): \n-25.161\n0.206\n0.201') # Plot boundary pdb.plot_decision_boundary(theta, X, y) plt.xlabel('Exam 1 score') plt.ylabel('Exam 2 score') input('Program paused. Press ENTER to continue') # ===================== Part 4: Predict and Accuracies ===================== # After learning the parameters, you'll like to use it to predict the outcomes # on unseen data. In this part, you will use the logistic regression model # to predict the probability that a student with score 45 on exam 1 and # score 85 on exam 2 will be admitted # # Furthermore, you will compute the training and test set accuracies of our model. # # Your task is to complete the code in predict.py # Predict probability for a student with score 45 on exam 1 # and score 85 on exam 2 prob = sigmoid(np.array([1, 45, 85]).dot(theta)) print('For a student with scores 45 and 85, we predict an admission probability of {:0.4f}'.format(prob)) print('Expected value : 0.775 +/- 0.002') # Compute the accuracy on our training set p = predict.predict(theta, X) print('Train accuracy: {}'.format(np.mean(y == p) * 100)) print('Expected accuracy (approx): 89.0') input('ex2 Finished. Press ENTER to exit')
[ 2, 10850, 18252, 7467, 5016, 532, 32900, 362, 25, 5972, 2569, 3310, 2234, 198, 2, 198, 2, 220, 27759, 198, 2, 220, 220, 10541, 198, 2, 198, 2, 220, 770, 2393, 4909, 2438, 326, 5419, 345, 651, 2067, 319, 262, 2604, 2569, 198, 2, ...
2.915789
1,710
# -*- coding: utf-8 -*- import pytest import goldsberry test_data = [ (goldsberry._nbaLeague, 'NBA', '00'), (goldsberry._nbaLeague, 'WNBA', '10'), (goldsberry._nbaLeague, 'NBADL', '20'), (goldsberry._nbaSeason, 1999, '1999-00'), (goldsberry._nbaSeason, 2000, '2000-01'), (goldsberry._seasonID, 1999, '21999'), (goldsberry._measureType, 1, 'Base'), (goldsberry._measureType, 2, 'Advanced'), (goldsberry._Scope, 1, ''), (goldsberry._PerModeSmall48, 1, 'Totals'), (goldsberry._PerModeSmall36, 1, 'Totals'), (goldsberry._PerModeMini, 1, 'Totals'), (goldsberry._PerModeLarge, 1, 'Totals'), (goldsberry._AheadBehind, 1, 'Ahead or Behind'), (goldsberry._ClutchTime, 1, 'Last 5 Minutes'), (goldsberry._GameScope, 2, 'Yesterday'), (goldsberry._PlayerExperience, 2, 'Rookie'), (goldsberry._PlayerPosition, 2, 'F'), (goldsberry._StarterBench, 2, 'Starters'), (goldsberry._PlusMinus, 2, 'Y'), (goldsberry._PaceAdjust, 2, 'Y'), (goldsberry._Rank, 2, 'Y'), (goldsberry._SeasonType, 1, 'Regular Season'), (goldsberry._SeasonType4, 1, 'Regular Season'), (goldsberry._Outcome, 2, 'W'), (goldsberry._Location, 2, 'Home'), (goldsberry._SeasonSegment, 2, 'Post All-Star'), (goldsberry._VsConference, 2, 'East'), (goldsberry._VsDivision, 2, 'Atlantic'), (goldsberry._GameSegment, 2, 'First Half'), (goldsberry._DistanceRange, 1, '5ft Range'), (goldsberry._valiDate, '', ''), (goldsberry._valiDate, '2015-01-02', '2015-01-02'), (goldsberry._ContextMeasure, 1, 'FGM'), (goldsberry._Position, 2, 'Guard'), (goldsberry._StatCategory, 1, 'MIN'), ]
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 12972, 9288, 198, 198, 11748, 3869, 82, 8396, 628, 198, 9288, 62, 7890, 796, 685, 198, 7, 70, 10119, 8396, 13557, 77, 7012, 24623, 11, 705, 32470, 3256, 705, 40...
2.541667
600
#poly_gauss_coil model #conversion of Poly_GaussCoil.py #converted by Steve King, Mar 2016 r""" This empirical model describes the scattering from *polydisperse* polymer chains in theta solvents or polymer melts, assuming a Schulz-Zimm type molecular weight distribution. To describe the scattering from *monodisperse* polymer chains, see the :ref:`mono-gauss-coil` model. Definition ---------- .. math:: I(q) = \text{scale} \cdot I_0 \cdot P(q) + \text{background} where .. math:: I_0 &= \phi_\text{poly} \cdot V \cdot (\rho_\text{poly}-\rho_\text{solv})^2 \\ P(q) &= 2 [(1 + UZ)^{-1/U} + Z - 1] / [(1 + U) Z^2] \\ Z &= [(q R_g)^2] / (1 + 2U) \\ U &= (Mw / Mn) - 1 = \text{polydispersity ratio} - 1 \\ V &= M / (N_A \delta) Here, $\phi_\text{poly}$, is the volume fraction of polymer, $V$ is the volume of a polymer coil, $M$ is the molecular weight of the polymer, $N_A$ is Avogadro's Number, $\delta$ is the bulk density of the polymer, $\rho_\text{poly}$ is the sld of the polymer, $\rho_\text{solv}$ is the sld of the solvent, and $R_g$ is the radius of gyration of the polymer coil. The 2D scattering intensity is calculated in the same way as the 1D, but where the $q$ vector is redefined as .. math:: q = \sqrt{q_x^2 + q_y^2} References ---------- .. [#] O Glatter and O Kratky (editors), *Small Angle X-ray Scattering*, Academic Press, (1982) Page 404 .. [#] J S Higgins, H C Benoit, *Polymers and Neutron Scattering*, Oxford Science Publications, (1996) .. [#] S M King, *Small Angle Neutron Scattering* in *Modern Techniques for Polymer Characterisation*, Wiley, (1999) .. [#] http://www.ncnr.nist.gov/staff/hammouda/distance_learning/chapter_28.pdf Authorship and Verification ---------------------------- * **Author:** * **Last Modified by:** * **Last Reviewed by:** """ import numpy as np from numpy import inf, expm1, power name = "poly_gauss_coil" title = "Scattering from polydisperse polymer coils" description = """ Evaluates the scattering from polydisperse polymer chains. """ category = "shape-independent" # pylint: disable=bad-whitespace, line-too-long # ["name", "units", default, [lower, upper], "type", "description"], parameters = [ ["i_zero", "1/cm", 70.0, [0.0, inf], "", "Intensity at q=0"], ["rg", "Ang", 75.0, [0.0, inf], "", "Radius of gyration"], ["polydispersity", "None", 2.0, [1.0, inf], "", "Polymer Mw/Mn"], ] # pylint: enable=bad-whitespace, line-too-long # NB: Scale and Background are implicit parameters on every model Iq.vectorized = True # Iq accepts an array of q values def random(): """Return a random parameter set for the model.""" rg = 10**np.random.uniform(0, 4) #rg = 1e3 polydispersity = 10**np.random.uniform(0, 3) pars = dict( #scale=1, background=0, i_zero=1e7, # i_zero is a simple scale rg=rg, polydispersity=polydispersity, ) return pars demo = dict(scale=1.0, i_zero=70.0, rg=75.0, polydispersity=2.0, background=0.0) # these unit test values taken from SasView 3.1.2 tests = [ [{'scale': 1.0, 'i_zero': 70.0, 'rg': 75.0, 'polydispersity': 2.0, 'background': 0.0}, [0.0106939, 0.469418], [57.6405, 0.169016]], ]
[ 2, 35428, 62, 4908, 1046, 62, 1073, 346, 2746, 198, 2, 1102, 9641, 286, 12280, 62, 35389, 1046, 7222, 346, 13, 9078, 198, 2, 1102, 13658, 416, 6542, 2677, 11, 1526, 1584, 198, 81, 37811, 198, 1212, 21594, 2746, 8477, 262, 45765, 422...
2.470808
1,336
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import ast import random import time import math from functools import partial import numpy as np import paddle from paddle.io import DataLoader import paddlenlp as ppnlp from paddlenlp.datasets import load_dataset from paddlenlp.data import Stack, Tuple, Pad, Dict from paddlenlp.transformers import BertForTokenClassification, BertTokenizer from paddlenlp.metrics import ChunkEvaluator parser = argparse.ArgumentParser() # yapf: disable parser.add_argument("--model_name_or_path", default=None, type=str, required=True, help="Path to pre-trained model or shortcut name selected in the list: " + ", ".join(list(BertTokenizer.pretrained_init_configuration.keys()))) parser.add_argument("--init_checkpoint_path", default=None, type=str, required=True, help="The model checkpoint path.", ) parser.add_argument("--max_seq_length", default=128, type=int, help="The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded.", ) parser.add_argument("--batch_size", default=8, type=int, help="Batch size per GPU/CPU for training.", ) parser.add_argument("--device", default="gpu", type=str, choices=["cpu", "gpu", "xpu"] ,help="The device to select to train the model, is must be cpu/gpu/xpu.") # yapf: enable if __name__ == "__main__": args = parser.parse_args() do_eval(args)
[ 2, 15069, 357, 66, 8, 33448, 350, 37382, 47, 37382, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845...
3.450947
581
import os from itertools import product from concurrent import futures from contextlib import closing from datetime import datetime import numpy as np from . import _z5py from .file import File, S3File from .dataset import Dataset from .shape_utils import normalize_slices def copy_dataset_impl(f_in, f_out, in_path_in_file, out_path_in_file, n_threads, chunks=None, block_shape=None, dtype=None, roi=None, fit_to_roi=False, **new_compression): """ Implementation of copy dataset. Used to implement `copy_dataset`, `convert_to_h5` and `convert_from_h5`. Can also be used for more flexible use cases, like copying from a zarr/n5 cloud dataset to a filesytem dataset. Args: f_in (File): input file object. f_out (File): output file object. in_path_in_file (str): name of input dataset. out_path_in_file (str): name of output dataset. n_threads (int): number of threads used for copying. chunks (tuple): chunks of the output dataset. By default same as input dataset's chunks. (default: None) block_shape (tuple): block shape used for copying. Must be a multiple of ``chunks``, which are used by default (default: None) dtype (str): datatype of the output dataset, default does not change datatype (default: None). roi (tuple[slice]): region of interest that will be copied. (default: None) fit_to_roi (bool): if given a roi, whether to set the shape of the output dataset to the roi's shape and align chunks with the roi's origin. (default: False) **new_compression: compression library and options for output dataset. If not given, the same compression as in the input is used. """ ds_in = f_in[in_path_in_file] # check if we can copy chunk by chunk in_is_z5 = isinstance(f_in, (File, S3File)) out_is_z5 = isinstance(f_out, (File, S3File)) copy_chunks = (in_is_z5 and out_is_z5) and (chunks is None or chunks == ds_in.chunks) and (roi is None) # get dataset metadata from input dataset if defaults were given chunks = ds_in.chunks if chunks is None else chunks dtype = ds_in.dtype if dtype is None else dtype # zarr objects may not have compression attribute. if so set it to the settings sent to this function if not hasattr(ds_in, "compression"): ds_in.compression = new_compression compression = new_compression.pop("compression", ds_in.compression) compression_opts = new_compression same_lib = in_is_z5 == out_is_z5 if same_lib and compression == ds_in.compression: compression_opts = compression_opts if compression_opts else ds_in.compression_opts if out_is_z5: compression = None if compression == 'raw' else compression compression_opts = {} if compression_opts is None else compression_opts else: compression_opts = {'compression_opts': None} if compression_opts is None else compression_opts # if we don't have block-shape explitictly given, use chunk size # otherwise check that it's a multiple of chunks if block_shape is None: block_shape = chunks else: assert all(bs % ch == 0 for bs, ch in zip(block_shape, chunks)),\ "block_shape must be a multiple of chunks" shape = ds_in.shape # we need to create the blocking here, before the shape is potentially altered # if fit_to_roi == True blocks = blocking(shape, block_shape, roi, fit_to_roi) if roi is not None: roi, _ = normalize_slices(roi, shape) if fit_to_roi: shape = tuple(rr.stop - rr.start for rr in roi) ds_out = f_out.require_dataset(out_path_in_file, dtype=dtype, shape=shape, chunks=chunks, compression=compression, **compression_opts) write_single = write_single_chunk if copy_chunks else write_single_block with futures.ThreadPoolExecutor(max_workers=n_threads) as tp: tasks = [tp.submit(write_single, bb) for bb in blocks] [t.result() for t in tasks] # copy attributes in_attrs = ds_in.attrs out_attrs = ds_out.attrs for key, val in in_attrs.items(): out_attrs[key] = val def copy_dataset(in_path, out_path, in_path_in_file, out_path_in_file, n_threads, chunks=None, block_shape=None, dtype=None, use_zarr_format=None, roi=None, fit_to_roi=False, **new_compression): """ Copy dataset, optionally change metadata. The input dataset will be copied to the output dataset chunk by chunk. Allows to change chunks, datatype, file format and compression. Can also just copy a roi. Args: in_path (str): path to the input file. out_path (str): path to the output file. in_path_in_file (str): name of input dataset. out_path_in_file (str): name of output dataset. n_threads (int): number of threads used for copying. chunks (tuple): chunks of the output dataset. By default same as input dataset's chunks. (default: None) block_shape (tuple): block shape used for copying. Must be a multiple of ``chunks``, which are used by default (default: None) dtype (str): datatype of the output dataset, default does not change datatype (default: None). use_zarr_format (bool): file format of the output file, default does not change format (default: None). roi (tuple[slice]): region of interest that will be copied. (default: None) fit_to_roi (bool): if given a roi, whether to set the shape of the output dataset to the roi's shape and align chunks with the roi's origin. (default: False) **new_compression: compression library and options for output dataset. If not given, the same compression as in the input is used. """ f_in = File(in_path) # check if the file format was specified # if not, keep the format of the input file # otherwise set the file format is_zarr = f_in.is_zarr if use_zarr_format is None else use_zarr_format f_out = File(out_path, use_zarr_format=is_zarr) copy_dataset_impl(f_in, f_out, in_path_in_file, out_path_in_file, n_threads, chunks=chunks, block_shape=block_shape, dtype=dtype, roi=roi, fit_to_roi=fit_to_roi, **new_compression) def copy_group(in_path, out_path, in_path_in_file, out_path_in_file, n_threads): """ Copy group recursively. Copy the group recursively, using copy_dataset. Metadata of datasets that are copied cannot be changed and rois cannot be applied. Args: in_path (str): path to the input file. out_path (str): path to the output file. in_path_in_file (str): name of input group. out_path_in_file (str): name of output group. n_threads (int): number of threads used to copy datasets. """ f_in = File(in_path) f_out = File(out_path) g_in = f_in[in_path_in_file] g_out = f_out.require_group(out_path_in_file) copy_attrs(g_in, g_out) g_in.visititems(copy_object) def remove_trivial_chunks(dataset, n_threads, remove_specific_value=None): """ Remove chunks that only contain a single value. The input dataset will be copied to the output dataset chunk by chunk. Allows to change datatype, file format and compression as well. Args: dataset (z5py.Dataset) n_threads (int): number of threads remove_specific_value (int or float): only remove chunks that contain (only) this specific value (default: None) """ dtype = dataset.dtype function = getattr(_z5py, 'remove_trivial_chunks_%s' % dtype) remove_specific = remove_specific_value is not None value = remove_specific_value if remove_specific else 0 function(dataset._impl, n_threads, remove_specific, value) def remove_dataset(dataset, n_threads): """ Remvoe dataset multi-threaded. """ _z5py.remove_dataset(dataset._impl, n_threads) def remove_chunk(dataset, chunk_id): """ Remove a chunk """ dataset._impl.remove_chunk(dataset._impl, chunk_id) def remove_chunks(dataset, bounding_box): """ Remove all chunks overlapping the bounding box """ shape = dataset.shape chunks = dataset.chunks blocks = blocking(shape, chunks, roi=bounding_box) for block in blocks: chunk_id = tuple(b.start // ch for b, ch in zip(block, chunks)) remove_chunk(dataset, chunk_id) def unique(dataset, n_threads, return_counts=False): """ Find unique values in dataset. Args: dataset (z5py.Dataset) n_threads (int): number of threads return_counts (bool): return counts of unique values (default: False) """ dtype = dataset.dtype if return_counts: function = getattr(_z5py, 'unique_with_counts_%s' % dtype) else: function = getattr(_z5py, 'unique_%s' % dtype) return function(dataset._impl, n_threads)
[ 11748, 28686, 198, 6738, 340, 861, 10141, 1330, 1720, 198, 6738, 24580, 1330, 25650, 198, 6738, 4732, 8019, 1330, 9605, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 764, 1330, 4808, 89, 20...
2.445818
3,802
"""Sensor platform support for Waste Collection Schedule.""" import collections import datetime import logging from enum import Enum import homeassistant.helpers.config_validation as cv import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_NAME, CONF_VALUE_TEMPLATE, STATE_UNKNOWN from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import Entity from .const import DOMAIN, UPDATE_SENSORS_SIGNAL _LOGGER = logging.getLogger(__name__) CONF_SOURCE_INDEX = "source_index" CONF_DETAILS_FORMAT = "details_format" CONF_COUNT = "count" CONF_LEADTIME = "leadtime" CONF_DATE_TEMPLATE = "date_template" CONF_APPOINTMENT_TYPES = "types" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_NAME): cv.string, vol.Optional(CONF_SOURCE_INDEX, default=0): cv.positive_int, vol.Optional(CONF_DETAILS_FORMAT, default="upcoming"): cv.enum(DetailsFormat), vol.Optional(CONF_COUNT): cv.positive_int, vol.Optional(CONF_LEADTIME): cv.positive_int, vol.Optional(CONF_APPOINTMENT_TYPES): cv.ensure_list, vol.Optional(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_DATE_TEMPLATE): cv.template, } ) def _set_state(self, upcoming): """Set entity state with default format.""" if len(upcoming) == 0: self._state = "" self._icon = None self._picture = None return appointment = upcoming[0] # appointment::=CollectionAppointmentGroup{date=2020-04-01, types=['Type1', 'Type2']} if self._value_template is not None: self._state = self._value_template.async_render_with_possible_json_value( appointment, None ) else: self._state = f"{self._separator.join(appointment.types)} in {appointment.daysTo} days" self._icon = appointment.icon self._picture = appointment.picture def _render_date(self, appointment): if self._date_template is not None: return self._date_template.async_render_with_possible_json_value( appointment, None ) else: return appointment.date.isoformat()
[ 37811, 47864, 3859, 1104, 329, 35304, 12251, 19281, 526, 15931, 198, 198, 11748, 17268, 198, 11748, 4818, 8079, 198, 11748, 18931, 198, 6738, 33829, 1330, 2039, 388, 198, 198, 11748, 1363, 562, 10167, 13, 16794, 364, 13, 11250, 62, 12102,...
2.398566
976
from concurrent.futures import ThreadPoolExecutor from functools import partial from json import JSONDecodeError import requests from funcy.calc import cache from funcy.debug import print_calls from funcy.simple_funcs import curry HEADERS = { "Accept": "application/json, text/javascript, */*; q=0.01", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/58.0.3029.110 Safari/537.36", "X-Requested-With": "XMLHttpRequest" } HOME_URL = "https://www.webnovel.com/" def novels(): for page in range(1, 10000): response = requests.get("https://www.webnovel.com/apiajax/listing/popularAjax", headers=HEADERS, params={ '_csrfToken': _get_csrftoken(), 'category': '', 'pageIndex': page }) data = _response_to_json(response) if 'data' not in data or 'items' not in data['data'] or 'isLast' not in data['data']: raise QidianException('Expected data not found') yield from data['data']['items'] if data['data']['isLast'] == 1: break
[ 6738, 24580, 13, 69, 315, 942, 1330, 14122, 27201, 23002, 38409, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 6738, 33918, 1330, 19449, 10707, 1098, 12331, 198, 198, 11748, 7007, 198, 6738, 1257, 948, 13, 9948, 66, 1330, 12940, 198, 6...
2.378151
476
# -*- coding: utf-8 -*- # Pour passer de TICDataXXXFromBitfields @ TICDataBatchXXXFromFieldIndex # Expressions rgulire notepad++ # Find : TICDataSelectorIfBit\( ([0-9]*), Struct\("([^\"]*)"\/([^\)]*).* # Replace: \1 : \3, # \2 from ._TIC_Tools import * from ._TIC_Types import * TICDataICEpFromBitfields = Struct( TICDataSelectorIfBit( 0, Struct("DEBUTp"/TYPE_DMYhms) ), TICDataSelectorIfBit( 1, Struct("FINp"/TYPE_DMYhms)), TICDataSelectorIfBit( 2, Struct("CAFp"/Int16ub) ), TICDataSelectorIfBit( 3, Struct("DATE_EAp"/TYPE_DMYhms) ), TICDataSelectorIfBit( 4, Struct("EApP"/Int24ub) ), TICDataSelectorIfBit( 5, Struct("EApPM"/Int24ub) ), TICDataSelectorIfBit( 6, Struct("EApHCE"/Int24ub) ), TICDataSelectorIfBit( 7, Struct("EApHCH"/Int24ub) ), TICDataSelectorIfBit( 8, Struct("EApHH"/Int24ub) ), TICDataSelectorIfBit( 9, Struct("EApHCD"/Int24ub) ), TICDataSelectorIfBit( 10, Struct("EApHD"/Int24ub) ), TICDataSelectorIfBit( 11, Struct("EApJA"/Int24ub) ), TICDataSelectorIfBit( 12, Struct("EApHPE"/Int24ub) ), TICDataSelectorIfBit( 13, Struct("EApHPH"/Int24ub) ), TICDataSelectorIfBit( 14, Struct("EApHPD"/Int24ub) ), TICDataSelectorIfBit( 15, Struct("EApSCM"/Int24ub) ), TICDataSelectorIfBit( 16, Struct("EApHM"/Int24ub) ), TICDataSelectorIfBit( 17, Struct("EApDSM"/Int24ub) ), TICDataSelectorIfBit( 18, Struct("DATE_ERPp"/TYPE_DMYhms) ), TICDataSelectorIfBit( 19, Struct("ERPpP"/Int24ub) ), TICDataSelectorIfBit( 20, Struct("ERPpPM"/Int24ub) ), TICDataSelectorIfBit( 21, Struct("ERPpHCE"/Int24ub) ), TICDataSelectorIfBit( 22, Struct("ERPpHCH"/Int24ub) ), TICDataSelectorIfBit( 23, Struct("ERPpHH"/Int24ub) ), TICDataSelectorIfBit( 24, Struct("ERPpHCD"/Int24ub) ), TICDataSelectorIfBit( 25, Struct("ERPpHD"/Int24ub) ), TICDataSelectorIfBit( 26, Struct("ERPpJA"/Int24ub) ), TICDataSelectorIfBit( 27, Struct("ERPpHPE"/Int24ub) ), TICDataSelectorIfBit( 28, Struct("ERPpHPH"/Int24ub) ), TICDataSelectorIfBit( 29, Struct("ERPpHPD"/Int24ub) ), TICDataSelectorIfBit( 30, Struct("ERPpSCM"/Int24ub) ), TICDataSelectorIfBit( 31, Struct("ERPpHM"/Int24ub) ), TICDataSelectorIfBit( 32, Struct("ERPpDSM"/Int24ub) ), TICDataSelectorIfBit( 33, Struct("DATE_ERNp"/TYPE_DMYhms) ), TICDataSelectorIfBit( 34, Struct("ERNpP"/Int24ub) ), TICDataSelectorIfBit( 35, Struct("ERNpPM"/Int24ub) ), TICDataSelectorIfBit( 36, Struct("ERNpHCE"/Int24ub) ), TICDataSelectorIfBit( 37, Struct("ERNpHCH"/Int24ub) ), TICDataSelectorIfBit( 38, Struct("ERNpHH"/Int24ub) ), TICDataSelectorIfBit( 39, Struct("ERNpHCD"/Int24ub) ), TICDataSelectorIfBit( 40, Struct("ERNpHD"/Int24ub) ), TICDataSelectorIfBit( 41, Struct("ERNpJA"/Int24ub) ), TICDataSelectorIfBit( 42, Struct("ERNpHPE"/Int24ub) ), TICDataSelectorIfBit( 43, Struct("ERNpHPH"/Int24ub) ), TICDataSelectorIfBit( 44, Struct("ERNpHPD"/Int24ub) ), TICDataSelectorIfBit( 45, Struct("ERNpSCM"/Int24ub) ), TICDataSelectorIfBit( 46, Struct("ERNpHM"/Int24ub) ), TICDataSelectorIfBit( 47, Struct("ERNpDSM"/Int24ub) ) ) # NOTE: For Batch only scalar/numeric values are accepeted TICDataBatchICEpFromFieldIndex = Switch( FindFieldIndex, { #0 : TYPE_DMYhms, # DEBUTp #1 : TYPE_DMYhms, # FINp 2 : Int16ub, # CAFp #3 : TYPE_DMYhms, # DATE_EAp 4 : Int24ub, # EApP 5 : Int24ub, # EApPM 6 : Int24ub, # EApHCE 7 : Int24ub, # EApHCH 8 : Int24ub, # EApHH 9 : Int24ub, # EApHCD 10 : Int24ub, # EApHD 11 : Int24ub, # EApJA 12 : Int24ub, # EApHPE 13 : Int24ub, # EApHPH 14 : Int24ub, # EApHPD 15 : Int24ub, # EApSCM 16 : Int24ub, # EApHM 17 : Int24ub, # EApDSM #18 : TYPE_DMYhms, # DATE_ERPp 19 : Int24ub, # ERPpP 20 : Int24ub, # ERPpPM 21 : Int24ub, # ERPpHCE 22 : Int24ub, # ERPpHCH 23 : Int24ub, # ERPpHH 24 : Int24ub, # ERPpHCD 25 : Int24ub, # ERPpHD 26 : Int24ub, # ERPpJA 27 : Int24ub, # ERPpHPE 28 : Int24ub, # ERPpHPH 29 : Int24ub, # ERPpHPD 30 : Int24ub, # ERPpSCM 31 : Int24ub, # ERPpHM 32 : Int24ub, # ERPpDSM #33 : TYPE_DMYhms, # DATE_ERNp 34 : Int24ub, # ERNpP 35 : Int24ub, # ERNpPM 36 : Int24ub, # ERNpHCE 37 : Int24ub, # ERNpHCH 38 : Int24ub, # ERNpHH 39 : Int24ub, # ERNpHCD 40 : Int24ub, # ERNpHD 41 : Int24ub, # ERNpJA 42 : Int24ub, # ERNpHPE 43 : Int24ub, # ERNpHPH 44 : Int24ub, # ERNpHPD 45 : Int24ub, # ERNpSCM 46 : Int24ub, # ERNpHM 47 : Int24ub, # ERNpDSM }, default = TICUnbatchableFieldError() )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 39128, 30286, 390, 309, 2149, 6601, 43145, 4863, 13128, 25747, 2488, 309, 2149, 6601, 33, 963, 43145, 4863, 15878, 15732, 198, 2, 10604, 507, 48670, 377, 557, 40...
2.074563
2,119
# -*- coding: utf-8 -*- # # Copyright (c) 2016 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import ovirtsdk4.services as services import ovirtsdk4.types as types import unittest from nose.tools import ( assert_in, assert_raises, ) from .server import TestServer
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 198, 2, 15069, 357, 66, 8, 1584, 2297, 10983, 11, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 1...
3.415584
231
import os import io import sys import subprocess import shlex import logging from threading import Timer from typing import Callable, Any, List from pathlib import Path # noqa: for doctest import tempfile # noqa: for doctest from .toolz import ( merge, map, pipe, curry, do, cprint ) log = logging.getLogger(__name__) log.addHandler(logging.NullHandler())
[ 11748, 28686, 198, 11748, 33245, 198, 11748, 25064, 198, 11748, 850, 14681, 198, 11748, 427, 2588, 198, 11748, 18931, 198, 6738, 4704, 278, 1330, 5045, 263, 198, 6738, 19720, 1330, 4889, 540, 11, 4377, 11, 7343, 198, 6738, 3108, 8019, 1...
2.865672
134
""" Data creation: Load the data, normalize it, and split into train and test. """ ''' Added the capability of loading pre-separated UCI train/test data function LoadData_Splitted_UCI ''' import numpy as np import os import pandas as pd import tensorflow as tf DATA_PATH = "../UCI_Datasets"
[ 37811, 198, 6601, 6282, 25, 198, 8912, 262, 1366, 11, 3487, 1096, 340, 11, 290, 6626, 656, 4512, 290, 1332, 13, 198, 37811, 628, 198, 198, 7061, 6, 198, 13003, 262, 12971, 286, 11046, 662, 12, 25512, 515, 14417, 40, 4512, 14, 9288, ...
3.02
100
from dataclasses import dataclass
[ 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 628, 628, 198 ]
3.454545
11
import pprint import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn import manifold from gensim.models import KeyedVectors # Download polish word embeddings for word2vec github/Google drive: # https://github.com/sdadas/polish-nlp-resources # with 100 dimensionality word2vec_100 = KeyedVectors.load("word2vec/word2vec_100_3_polish.bin") # with 300 dimensionality word2vec_300 = KeyedVectors.load("word2vec_300_3_polish/word2vec_300_3_polish.bin") # Using the downloaded models find the most similar words for the following expressions... # And display 5 most similar words according to each model: # kpk # szkoda # wypadek # kolizja # nieszczcie # rozwd words = ['kpk', 'szkoda', 'wypadek', 'kolizja', 'nieszczcie', 'rozwd'] for word in words: get_most_similar_words(word) # --------- Most similar words for kpk --------- # word2vec_100: # [('kilopond', 0.6665806770324707), # ('kpzs', 0.6363496780395508), # ('kpu', 0.6300562024116516), # ('sownarkomu', 0.6254925727844238), # ('wcik', 0.6224358677864075)] # word2vec_300: # [('ksh', 0.5774794220924377), # ('cywilnego', 0.5498510599136353), # ('postpowania', 0.5285828113555908), # ('kilopond', 0.5151568055152893), # ('kkkw', 0.48344212770462036)] # # --------- Most similar words for szkoda --------- # word2vec_100: # [('krzywda', 0.6817898750305176), # ('poytek', 0.6121943593025208), # ('strata', 0.5968126654624939), # ('ryzyko', 0.5745570659637451), # ('uszczerbek', 0.5639551877975464)] # word2vec_300: # [('uszczerbek', 0.6027276515960693), # ('krzywda', 0.5920778512954712), # ('strata', 0.550269365310669), # ('despekt', 0.5382484197616577), # ('poytek', 0.531347393989563)] # # --------- Most similar words for wypadek --------- # word2vec_100: # [('przypadek', 0.7544811964035034), # ('okolicznoci', 0.7268072366714478), # ('padku', 0.6788284182548523), # ('incydent', 0.6418948173522949), # ('zdarzenie', 0.6114422082901001)] # word2vec_300: # [('przypadek', 0.7066895961761475), # ('okolicznoci', 0.6121077537536621), # ('padku', 0.6056742072105408), # ('padki', 0.5596078634262085), # ('incydent', 0.5496981143951416)] # # --------- Most similar words for kolizja --------- # word2vec_100: # [('zderzenie', 0.8431548476219177), # ('awaria', 0.7090569734573364), # ('kraksa', 0.6777161359786987), # ('turbulencja', 0.6613468527793884), # ('polizg', 0.6391660571098328)] # word2vec_300: # [('zderzenie', 0.7603178024291992), # ('awaria', 0.611009955406189), # ('kraksa', 0.5939033031463623), # ('turbulencja', 0.5664489269256592), # ('polizg', 0.5569967031478882)] # # --------- Most similar words for nieszczcie --------- # word2vec_100: # [('niebezpieczestwo', 0.7519958019256592), # ('cierpienia', 0.7408335208892822), # ('strapienie', 0.7345459461212158), # ('cierpienie', 0.7262567281723022), # ('utrapienie', 0.7251379489898682)] # word2vec_300: # [('utrapienie', 0.6610732674598694), # ('cierpienia', 0.6526124477386475), # ('niedola', 0.6478177309036255), # ('strapienie', 0.6300181150436401), # ('cierpienie', 0.6248573064804077)] # # --------- Most similar words for rozwd --------- # word2vec_100: # [('maestwo', 0.7646843194961548), # ('separacja', 0.7547168135643005), # ('adopcja', 0.7333694696426392), # ('lub', 0.7324203848838806), # ('uniewanienie', 0.7096400856971741)] # word2vec_300: # [('separacja', 0.7053208351135254), # ('maestwo', 0.6689504384994507), # ('lub', 0.6553219556808472), # ('rozwodowy', 0.614338219165802), # ('uniewanienie', 0.6127183437347412)] # Find the most similar words for the following expressions (average the representations for each word): # sd najwyszy # trybuna konstytucyjny # szkoda majtkowy # kodeks cywilny # sd rejonowy # Display 7 most similar words according to each model. expressions = ['sd najwyszy', 'trybuna konstytucyjny', 'szkoda majtkowy', 'kodeks cywilny', 'sd rejonowy'] get_most_similiar_words_for_expression_avg(expressions) # --------- Most similar words for sd najwyszy --------- # word2vec_100: # [('sd', 0.8644266128540039), # ('trybuna', 0.7672435641288757), # ('najwyszy', 0.7527138590812683), # ('trybunat', 0.6843459010124207), # ('sdzia', 0.6718415021896362), # ('areopag', 0.6571060419082642), # ('sprawiedliwo', 0.6562486886978149)] # word2vec_300: # [('sd', 0.8261206150054932), # ('trybuna', 0.711520791053772), # ('najwyszy', 0.7068409323692322), # ('sdzia', 0.6023203730583191), # ('sdowy', 0.5670486688613892), # ('trybunat', 0.5525928735733032), # ('sprawiedliwo', 0.5319530367851257)] # # --------- Most similar words for trybuna konstytucyjny --------- # word2vec_100: # [('trybuna', 0.9073251485824585), # ('konstytucyjny', 0.7998723387718201), # ('sd', 0.7972990274429321), # ('buna', 0.7729247808456421), # ('senat', 0.7585273385047913), # ('bunau', 0.7441976070404053), # ('trybunat', 0.7347140908241272)] # word2vec_300: # [('trybuna', 0.8845913410186768), # ('konstytucyjny', 0.7739969491958618), # ('sd', 0.7300779819488525), # ('trybunat', 0.6758428812026978), # ('senat', 0.6632090210914612), # ('parlament', 0.6614581346511841), # ('bunau', 0.6404117941856384)] # # --------- Most similar words for szkoda majtkowy --------- # word2vec_100: # [('szkoda', 0.8172438144683838), # ('majtkowy', 0.7424530386924744), # ('krzywda', 0.6498408317565918), # ('wiadczenie', 0.6419471502304077), # ('odszkodowanie', 0.6392182111740112), # ('dochd', 0.637932538986206), # ('wydatek', 0.6325603127479553)] # word2vec_300: # [('szkoda', 0.7971925735473633), # ('majtkowy', 0.7278684973716736), # ('uszczerbek', 0.5841633081436157), # ('korzy', 0.5474051237106323), # ('krzywda', 0.5431190729141235), # ('majtek', 0.525060772895813), # ('strata', 0.5228629112243652)] # # --------- Most similar words for kodeks cywilny --------- # word2vec_100: # [('kodeks', 0.8756389617919922), # ('cywilny', 0.8532464504241943), # ('pasztunwali', 0.6438998579978943), # ('deksu', 0.6374959945678711), # ('teodozjaskim', 0.6283917427062988), # ('pozakodeksowy', 0.6153194904327393), # ('sdowo', 0.6136723160743713)] # word2vec_300: # [('kodeks', 0.8212110996246338), # ('cywilny', 0.7886406779289246), # ('amiatyski', 0.5660314559936523), # ('cywilnego', 0.5531740188598633), # ('deksu', 0.5472918748855591), # ('isps', 0.5369160175323486), # ('jei', 0.5361183881759644)] # # --------- Most similar words for sd rejonowy --------- # word2vec_100: # [('sd', 0.8773891925811768), # ('prokuratura', 0.8396657705307007), # ('rejonowy', 0.7694871425628662), # ('trybuna', 0.755321204662323), # ('sdowy', 0.7153753042221069), # ('magistrat', 0.7151126861572266), # ('prokurator', 0.7081375122070312)] # word2vec_300: # [('sd', 0.8507211208343506), # ('rejonowy', 0.7344856262207031), # ('prokuratura', 0.711697518825531), # ('trybuna', 0.6748420596122742), # ('sdowy', 0.6426382064819336), # ('okrgowy', 0.6349465847015381), # ('apelacyjny', 0.599929690361023)] # Find the result of the following equations (5 top results, both models): # sd + konstytucja - kpk # pasaer + kobieta - mczyzna # pilot + kobieta - mczyzna # lekarz + kobieta - mczyzna # nauczycielka + mczyzna - kobieta # przedszkolanka + mczyzna - 'kobieta # samochd + rzeka - droga equations = [(['sd', 'konstytucja'], ['kpk']), (['pasaer', 'kobieta'], ['mczyzna']), (['pilot', 'kobieta'], ['mczyzna']), (['lekarz', 'kobieta'], ['mczyzna']), (['nauczycielka', 'mczyzna'], ['kobieta']), (['przedszkolanka', 'mczyzna'], ['kobieta']), (['samochd', 'rzeka'], ['droga'])] for equa in equations: get_result_of_equation(equa[0], equa[1]) # --------- Result for + ['sd', 'konstytucja'] and - ['kpk'] --------- # word2vec_100: # [('trybuna', 0.6436409950256348), # ('ustawa', 0.6028786897659302), # ('elekcja', 0.5823959112167358), # ('deklaracja', 0.5771891474723816), # ('dekret', 0.5759621262550354)] # word2vec_300: # [('trybuna', 0.5860734581947327), # ('senat', 0.5112544298171997), # ('ustawa', 0.5023636817932129), # ('dekret', 0.48704710602760315), # ('wadza', 0.4868926703929901)] # # --------- Result for + ['pasaer', 'kobieta'] and - ['mczyzna'] --------- # word2vec_100: # [('pasaerka', 0.7234811186790466), # ('stewardessa', 0.6305270195007324), # ('stewardesa', 0.6282645463943481), # ('takswka', 0.619726300239563), # ('podrny', 0.614517092704773)] # word2vec_300: # [('pasaerka', 0.6741673946380615), # ('stewardesa', 0.5810248255729675), # ('stewardessa', 0.5653151273727417), # ('podrny', 0.5060371160507202), # ('pasaerski', 0.4896503686904907)] # # --------- Result for + ['pilot', 'kobieta'] and - ['mczyzna'] --------- # word2vec_100: # [('nawigator', 0.6925703287124634), # ('oblatywacz', 0.6686224937438965), # ('lotnik', 0.6569937467575073), # ('pilotka', 0.6518791913986206), # ('awionetka', 0.6428645849227905)] # word2vec_300: # [('pilotka', 0.6108255386352539), # ('lotnik', 0.6020804047584534), # ('stewardesa', 0.5943204760551453), # ('nawigator', 0.5849766731262207), # ('oblatywacz', 0.5674178600311279)] # # --------- Result for + ['lekarz', 'kobieta'] and - ['mczyzna'] --------- # word2vec_100: # [('lekarka', 0.7690489292144775), # ('ginekolog', 0.7575511336326599), # ('pediatra', 0.7478542923927307), # ('psychiatra', 0.732271671295166), # ('poona', 0.7268943786621094)] # word2vec_300: # [('lekarka', 0.7388788461685181), # ('pielgniarka', 0.6719920635223389), # ('ginekolog', 0.658279299736023), # ('psychiatra', 0.6389409303665161), # ('chirurg', 0.6305986642837524)] # # --------- Result for + ['nauczycielka', 'mczyzna'] and - ['kobieta'] --------- # word2vec_100: # [('uczennica', 0.7441667318344116), # ('studentka', 0.7274973392486572), # ('nauczyciel', 0.7176114916801453), # ('wychowawczyni', 0.7153530120849609), # ('koleanka', 0.678418755531311)] # word2vec_300: # [('nauczyciel', 0.6561620235443115), # ('wychowawczyni', 0.6211140155792236), # ('uczennica', 0.6142012476921082), # ('koleanka', 0.5501158237457275), # ('przedszkolanka', 0.5497692823410034)] # # --------- Result for + ['przedszkolanka', 'mczyzna'] and - ['kobieta'] --------- # word2vec_100: # [('staysta', 0.6987776756286621), # ('wychowawczyni', 0.6618361473083496), # ('krelarka', 0.6590923070907593), # ('pielgniarz', 0.6492814421653748), # ('siedmiolatek', 0.6483469009399414)] # word2vec_300: # [('staysta', 0.5117638111114502), # ('pierwszoklasista', 0.49398648738861084), # ('wychowawczyni', 0.49037522077560425), # ('praktykant', 0.48884207010269165), # ('pielgniarz', 0.4795262813568115)] # # --------- Result for + ['samochd', 'rzeka'] and - ['droga'] --------- # word2vec_100: # [('jeep', 0.6142987608909607), # ('buick', 0.5962571501731873), # ('dip', 0.5938510894775391), # ('ponton', 0.580719530582428), # ('landrower', 0.5799552202224731)] # word2vec_300: # [('dip', 0.5567235946655273), # ('jeep', 0.5533617734909058), # ('auto', 0.5478508472442627), # ('ciarwka', 0.5461742281913757), # ('wz', 0.5204571485519409)] # Using the t-SNE algorithm compute the projection of the random 1000 words with the following words highlighted (both models): # szkoda # strata # uszczerbek # krzywda # niesprawiedliwo # nieszczcie # kobieta # mczyzna # pasaer # pasaerka # student # studentka # lekarz # lekarka words = np.array(['szkoda', 'strata', 'uszczerbek', 'krzywda', 'niesprawiedliwo', 'nieszczcie', 'kobieta', 'mczyzna', 'pasaer', 'pasaerka', 'student', 'studentka', 'lekarz', 'lekarka']) wv = word2vec_300 plot_with_tsne(wv, words) wv = word2vec_100 plot_with_tsne(wv, words)
[ 11748, 279, 4798, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 384, 397, 1211, 355, 3013, 82, 198, 6738, 1341, 35720, 1330, 48048, 198, 6738, 308, 641, 320, 13, 27530, 1...
2.120869
5,477
# This script adds a new message to a specific SQS queue # # Author - Paul Doyle Aug 2013 # # #from __future__ import print_function import sys import Queue import boto.sqs import argparse import socket import datetime import sys import time from boto.sqs.attributes import Attributes parser = argparse.ArgumentParser() parser.add_argument('queuearg',help='name of the sqs queue to use',metavar="myQueueName") parser.add_argument('experiment',help='name of the experiment queue to use') args = parser.parse_args() from boto.sqs.message import Message import threading conn = boto.sqs.connect_to_region("us-east-1", aws_access_key_id='AKIAINWVSI3MIXIB5N3Q', aws_secret_access_key='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') sqs_queue = conn.get_queue(args.queuearg) queue = Queue.Queue(0) threads = [] for n in xrange(40): queue.put(n) t = Sender() t.start() threads.append(t) for t in threads: t.join()
[ 2, 770, 4226, 6673, 257, 649, 3275, 284, 257, 2176, 49747, 50, 16834, 198, 2, 198, 2, 6434, 532, 3362, 31233, 2447, 2211, 198, 2, 198, 2, 198, 2, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 25064, 198, 11748, 4670, ...
2.641618
346
from typing import Optional import pandas as pd from dero.ml.typing import ModelDict, AllModelResultsDict, DfDict
[ 6738, 19720, 1330, 32233, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 288, 3529, 13, 4029, 13, 774, 13886, 1330, 9104, 35, 713, 11, 1439, 17633, 25468, 35, 713, 11, 360, 69, 35, 713, 628, 628 ]
3.162162
37
import pygame from engine.utils import Rect from engine.app import get_screen_size # EXPORT
[ 11748, 12972, 6057, 198, 6738, 3113, 13, 26791, 1330, 48599, 198, 6738, 3113, 13, 1324, 1330, 651, 62, 9612, 62, 7857, 198, 198, 2, 7788, 15490, 198 ]
3.444444
27
import shelve, random arguments = ["self", "info", "args", "world"] minlevel = 2 helpstring = "coin <bet>" def main(connection, info, args, world) : """Decides heads or tails based on the coinchance variable. Adds or removes appropriate amount of money""" money = shelve.open("money-%s.db" % (connection.networkname), writeback=True) if money.has_key(info["sender"]) : bet = int(args[1]) if bet <= money[info["sender"]]["money"] and bet >= 1 : answer = random.choice(money[info["sender"]]["coinchance"]) if answer : money[info["sender"]]["money"] += bet money.sync() connection.msg(info["channel"], _("Congrats %(sender)s! You just won %(num)s dollars!") % dict(sender=info["sender"], num=args[1])) else : money[info["sender"]]["money"] -= bet money.sync() connection.msg(info["channel"], _("Sorry %(sender)s! You just lost %(num)s dollars!") % dict(sender=info["sender"], num=args[1])) if money[info["sender"]]["money"] > money[info["sender"]]["maxmoney"] : money[info["sender"]]["maxmoney"] = money[info["sender"]]["money"] money.sync() else : connection.msg(info["channel"], _("%(sender)s: You don't have enough money to do that!") % dict(sender=info["sender"])) else : connection.msg(info["channel"], _("%(sender)s: You have not set up a money account. If you aren't already, please register with me. Then, say moneyreset. After that you should be able to use this command.") % dict(sender=info["sender"]))
[ 11748, 7497, 303, 11, 4738, 198, 853, 2886, 796, 14631, 944, 1600, 366, 10951, 1600, 366, 22046, 1600, 366, 6894, 8973, 198, 1084, 5715, 796, 362, 198, 16794, 8841, 796, 366, 3630, 1279, 11181, 24618, 198, 198, 4299, 1388, 7, 38659, 1...
2.397661
684
from __future__ import print_function import emcee from multiprocessing import Pool import numpy as np import corner import matplotlib.pyplot as plt import sys import scipy.optimize as op from rbvfit.rb_vfit import rb_veldiff as rb_veldiff from rbvfit import rb_setline as rb import pdb ######## Computing Likelihoods######
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 795, 344, 68, 198, 6738, 18540, 305, 919, 278, 1330, 19850, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 5228, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, ...
2.742188
128
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Copyright (c) Megvii, Inc. and its affiliates. import torch from torch.utils.data.dataloader import DataLoader as torchDataLoader from torch.utils.data.dataloader import default_collate import os import random from .samplers import YoloBatchSampler def get_yolox_datadir(): """ get dataset dir of YOLOX. If environment variable named `YOLOX_DATADIR` is set, this function will return value of the environment variable. Otherwise, use data """ yolox_datadir = os.getenv("YOLOX_DATADIR", None) if yolox_datadir is None: import yolox yolox_path = os.path.dirname(os.path.dirname(yolox.__file__)) yolox_datadir = os.path.join(yolox_path, "datasets") return yolox_datadir def list_collate(batch): """ Function that collates lists or tuples together into one list (of lists/tuples). Use this as the collate function in a Dataloader, if you want to have a list of items as an output, as opposed to tensors (eg. Brambox.boxes). """ items = list(zip(*batch)) for i in range(len(items)): if isinstance(items[i][0], (list, tuple)): items[i] = list(items[i]) else: items[i] = default_collate(items[i]) return items
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 201, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 201, 198, 2, 15069, 357, 66, 8, 8336, 85, 4178, 11, 3457, 13, 290, 663, 29116, 13, 201, 198, 201, 198, 11748, 2803...
2.366548
562
#!/usr/bin/python # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = r''' --- module: ec2_vpc_vpn_info version_added: 1.0.0 short_description: Gather information about VPN Connections in AWS. description: - Gather information about VPN Connections in AWS. - This module was called C(ec2_vpc_vpn_facts) before Ansible 2.9. The usage did not change. requirements: [ boto3 ] author: Madhura Naniwadekar (@Madhura-CSI) options: filters: description: - A dict of filters to apply. Each dict item consists of a filter key and a filter value. See U(https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeVpnConnections.html) for possible filters. required: false type: dict vpn_connection_ids: description: - Get details of a specific VPN connections using vpn connection ID/IDs. This value should be provided as a list. required: false type: list elements: str extends_documentation_fragment: - amazon.aws.aws - amazon.aws.ec2 ''' EXAMPLES = r''' # # Note: These examples do not set authentication details, see the AWS Guide for details. - name: Gather information about all vpn connections community.aws.ec2_vpc_vpn_info: - name: Gather information about a filtered list of vpn connections, based on tags community.aws.ec2_vpc_vpn_info: filters: "tag:Name": test-connection register: vpn_conn_info - name: Gather information about vpn connections by specifying connection IDs. community.aws.ec2_vpc_vpn_info: filters: vpn-gateway-id: vgw-cbe66beb register: vpn_conn_info ''' RETURN = r''' vpn_connections: description: List of one or more VPN Connections. returned: always type: complex contains: category: description: The category of the VPN connection. returned: always type: str sample: VPN customer_gatway_configuration: description: The configuration information for the VPN connection's customer gateway (in the native XML format). returned: always type: str customer_gateway_id: description: The ID of the customer gateway at your end of the VPN connection. returned: always type: str sample: cgw-17a53c37 options: description: The VPN connection options. returned: always type: dict sample: { "static_routes_only": false } routes: description: List of static routes associated with the VPN connection. returned: always type: complex contains: destination_cidr_block: description: The CIDR block associated with the local subnet of the customer data center. returned: always type: str sample: 10.0.0.0/16 state: description: The current state of the static route. returned: always type: str sample: available state: description: The current state of the VPN connection. returned: always type: str sample: available tags: description: Any tags assigned to the VPN connection. returned: always type: dict sample: { "Name": "test-conn" } type: description: The type of VPN connection. returned: always type: str sample: ipsec.1 vgw_telemetry: description: Information about the VPN tunnel. returned: always type: complex contains: accepted_route_count: description: The number of accepted routes. returned: always type: int sample: 0 last_status_change: description: The date and time of the last change in status. returned: always type: str sample: "2018-02-09T14:35:27+00:00" outside_ip_address: description: The Internet-routable IP address of the virtual private gateway's outside interface. returned: always type: str sample: 13.127.79.191 status: description: The status of the VPN tunnel. returned: always type: str sample: DOWN status_message: description: If an error occurs, a description of the error. returned: always type: str sample: IPSEC IS DOWN certificate_arn: description: The Amazon Resource Name of the virtual private gateway tunnel endpoint certificate. returned: when a private certificate is used for authentication type: str sample: "arn:aws:acm:us-east-1:123456789101:certificate/c544d8ce-20b8-4fff-98b0-example" vpn_connection_id: description: The ID of the VPN connection. returned: always type: str sample: vpn-f700d5c0 vpn_gateway_id: description: The ID of the virtual private gateway at the AWS side of the VPN connection. returned: always type: str sample: vgw-cbe56bfb ''' import json try: from botocore.exceptions import ClientError, BotoCoreError except ImportError: pass # caught by AnsibleAWSModule from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule from ansible_collections.amazon.aws.plugins.module_utils.ec2 import (ansible_dict_to_boto3_filter_list, boto3_tag_list_to_ansible_dict, camel_dict_to_snake_dict, ) if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 15069, 25, 28038, 856, 4935, 198, 2, 22961, 3611, 5094, 13789, 410, 18, 13, 15, 10, 357, 3826, 27975, 45761, 393, 3740, 1378, 2503, 13, 41791, 13, 2398, 14, 677, 4541, 14, 70, 489, 12,...
2.283672
2,658
import discord from discord.ext import commands from pathlib import Path from config import bot from collections import OrderedDict import json
[ 11748, 36446, 198, 6738, 36446, 13, 2302, 1330, 9729, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 4566, 1330, 10214, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 11748, 33918, 628 ]
4.53125
32
# Define a procedure, fibonacci, that takes a natural number as its input, and # returns the value of that fibonacci number. # Two Base Cases: # fibonacci(0) => 0 # fibonacci(1) => 1 # Recursive Case: # n > 1 : fibonacci(n) => fibonacci(n-1) + fibonacci(n-2) print (fibonacci(0)) #>>> 0 print (fibonacci(1)) #>>> 1 print (fibonacci(15)) #>>> 610
[ 2, 2896, 500, 257, 8771, 11, 12900, 261, 44456, 11, 326, 2753, 257, 3288, 1271, 355, 663, 5128, 11, 290, 201, 198, 2, 5860, 262, 1988, 286, 326, 12900, 261, 44456, 1271, 13, 201, 198, 201, 198, 2, 4930, 7308, 35536, 25, 201, 198, ...
2.251497
167
#!/usr/bin/env python3 from .base_test import BaseTest from fbc.symphony.cli.graphql_compiler.gql.utils_codegen import CodeChunk
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 6738, 764, 8692, 62, 9288, 1330, 7308, 14402, 198, 6738, 277, 15630, 13, 37047, 23021, 13, 44506, 13, 34960, 13976, 62, 5589, 5329, 13, 70, 13976, 13, 26791, 62, 8189, 5235, ...
2.787234
47
from flask import Flask
[ 6738, 42903, 1330, 46947, 628 ]
5
5
import os import json def get_config(action, optimised = False): """ action: train, test, export or gdrive optimised: False --> DenseNet121 True --> DenseNet121Eff """ root_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) config_path = os.path.join(root_path, 'configs') if action == 'download': with open(os.path.join(config_path, 'download_configs.json')) as f1: config = json.load(f1) else: if optimised: with open(os.path.join(config_path, 'densenet121eff_config.json')) as f1: config_file = json.load(f1) config = config_file[action] else: with open(os.path.join(config_path, 'densenet121_config.json')) as f1: config_file = json.load(f1) config = config_file[action] return config
[ 11748, 28686, 198, 11748, 33918, 628, 198, 4299, 651, 62, 11250, 7, 2673, 11, 6436, 1417, 796, 10352, 2599, 198, 220, 220, 220, 37227, 2223, 25, 4512, 11, 1332, 11, 10784, 393, 308, 19472, 198, 220, 220, 220, 220, 220, 220, 220, 643...
2.138095
420
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: udpa/annotations/versioning.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.protobuf import descriptor_pb2 as google_dot_protobuf_dot_descriptor__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='udpa/annotations/versioning.proto', package='udpa.annotations', syntax='proto3', serialized_options=b'Z\"github.com/cncf/xds/go/annotations', create_key=_descriptor._internal_create_key, serialized_pb=b'\n!udpa/annotations/versioning.proto\x12\x10udpa.annotations\x1a google/protobuf/descriptor.proto\"5\n\x14VersioningAnnotation\x12\x1d\n\x15previous_message_type\x18\x01 \x01(\t:^\n\nversioning\x12\x1f.google.protobuf.MessageOptions\x18\xd3\x88\xe1\x03 \x01(\x0b\x32&.udpa.annotations.VersioningAnnotationB$Z\"github.com/cncf/xds/go/annotationsb\x06proto3' , dependencies=[google_dot_protobuf_dot_descriptor__pb2.DESCRIPTOR,]) VERSIONING_FIELD_NUMBER = 7881811 versioning = _descriptor.FieldDescriptor( name='versioning', full_name='udpa.annotations.versioning', index=0, number=7881811, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=True, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key) _VERSIONINGANNOTATION = _descriptor.Descriptor( name='VersioningAnnotation', full_name='udpa.annotations.VersioningAnnotation', filename=None, file=DESCRIPTOR, containing_type=None, create_key=_descriptor._internal_create_key, fields=[ _descriptor.FieldDescriptor( name='previous_message_type', full_name='udpa.annotations.VersioningAnnotation.previous_message_type', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=b"".decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=89, serialized_end=142, ) DESCRIPTOR.message_types_by_name['VersioningAnnotation'] = _VERSIONINGANNOTATION DESCRIPTOR.extensions_by_name['versioning'] = versioning _sym_db.RegisterFileDescriptor(DESCRIPTOR) VersioningAnnotation = _reflection.GeneratedProtocolMessageType('VersioningAnnotation', (_message.Message,), { 'DESCRIPTOR' : _VERSIONINGANNOTATION, '__module__' : 'udpa.annotations.versioning_pb2' # @@protoc_insertion_point(class_scope:udpa.annotations.VersioningAnnotation) }) _sym_db.RegisterMessage(VersioningAnnotation) versioning.message_type = _VERSIONINGANNOTATION google_dot_protobuf_dot_descriptor__pb2.MessageOptions.RegisterExtension(versioning) DESCRIPTOR._options = None # @@protoc_insertion_point(module_scope)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 262, 8435, 11876, 17050, 13, 220, 8410, 5626, 48483, 0, 198, 2, 2723, 25, 334, 67, 8957, 14, 34574, 602, 14, 9641, 278, 13, 1676, 1462, 198, 37811...
2.717427
1,228
import re from core.actionModule import actionModule from core.keystore import KeyStore as kb from core.utils import Utils
[ 11748, 302, 198, 198, 6738, 4755, 13, 2673, 26796, 1330, 2223, 26796, 198, 6738, 4755, 13, 2539, 8095, 1330, 7383, 22658, 355, 47823, 198, 6738, 4755, 13, 26791, 1330, 7273, 4487, 628 ]
3.90625
32
from numpy import logspace from sys import path as sysPath sysPath.append('../../src') #load the module from interfacePy import Cosmo cosmo=Cosmo('../../src/data/eos2020.dat',0,1e5) for T in logspace(-5,5,50): print( 'T=',T,'GeV\t', 'H=',cosmo.Hubble(T),'GeV\t', 'h_eff=',cosmo.heff(T),'\t', 'g_eff=',cosmo.geff(T),'\t', 's=',cosmo.s(T),'GeV^3\t', ) if False: import matplotlib.pyplot as plt #########-----g_eff and h_eff-----######### fig=plt.figure(figsize=(9,4)) fig.subplots_adjust(bottom=0.15, left=0.15, top = 0.95, right=0.9,wspace=0.0,hspace=0.0) fig.suptitle('') sub = fig.add_subplot(1,1,1) T=logspace(-5,5,500) gt=[cosmo.geff(i) for i in T] ht=[cosmo.heff(i) for i in T] sub.plot(T,gt,linestyle='--',c='xkcd:red',label=r"$g_{\rm eff} (T)$") sub.plot(T,ht,linestyle=':',c='xkcd:black',label=r"$h_{\rm eff} (T)$") sub.set_xlabel(r'$T ~ [{\rm GeV}]$') sub.set_ylabel(r'rel. dof') sub.legend(bbox_to_anchor=(1, 0.0),borderaxespad=0., borderpad=0.05,ncol=1,loc='lower right',fontsize=14,framealpha=0) sub.set_yscale('log') sub.set_xscale('log') fig.savefig('rdofs-T_examplePlot.pdf',bbox_inches='tight') #########-----dg_effdT and dh_effdT-----######### fig=plt.figure(figsize=(9,4)) fig.subplots_adjust(bottom=0.15, left=0.15, top = 0.95, right=0.9,wspace=0.0,hspace=0.0) fig.suptitle('') sub = fig.add_subplot(1,1,1) T=logspace(-5,5,500) dg=[cosmo.dgeffdT (i) for i in T] dh=[cosmo.dheffdT(i) for i in T] sub.plot(T,dg,linestyle='--',c='xkcd:red',label=r"$\dfrac{d g_{\rm eff}}{dT} (T)$") sub.plot(T,dh,linestyle=':',c='xkcd:black',label=r"$\dfrac{d h_{\rm eff}}{dT} (T)$") sub.set_xlabel(r'$T ~ [{\rm GeV}]$') sub.legend(bbox_to_anchor=(1, 0.5),borderaxespad=0., borderpad=0.05,ncol=1,loc='lower right',fontsize=14,framealpha=0) sub.set_yscale('symlog') sub.set_xscale('log') fig.savefig('drdofsdT-T_examplePlot.pdf',bbox_inches='tight') #########-----dh-----######### fig=plt.figure(figsize=(9,4)) fig.subplots_adjust(bottom=0.15, left=0.15, top = 0.95, right=0.9,wspace=0.0,hspace=0.0) fig.suptitle('') sub = fig.add_subplot(1,1,1) T=logspace(-5,5,500) dht=[cosmo.dh(i) for i in T] sub.plot(T,dht,linestyle='-',c='xkcd:black') sub.set_xlabel(r'$T ~ [{\rm GeV}]$') sub.set_ylabel(r'$\delta_h = 1 + \dfrac{1}{3} \dfrac{d \log h_{\rm eff} }{d \log T}$') sub.set_yscale('linear') sub.set_xscale('log') fig.savefig('dh-T_examplePlot.pdf',bbox_inches='tight')
[ 6738, 299, 32152, 1330, 2604, 13200, 628, 198, 6738, 25064, 1330, 3108, 355, 25064, 15235, 198, 17597, 15235, 13, 33295, 10786, 40720, 40720, 10677, 11537, 198, 198, 2, 2220, 262, 8265, 198, 6738, 7071, 20519, 1330, 10437, 5908, 220, 198,...
1.909287
1,389
from __future__ import annotations from typing import Optional from psion.oauth2.exceptions import InvalidClient, OAuth2Error, UnsupportedTokenType from psion.oauth2.models import JSONResponse, Request from .base import BaseEndpoint
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 19720, 1330, 32233, 198, 198, 6738, 26692, 295, 13, 12162, 1071, 17, 13, 1069, 11755, 1330, 17665, 11792, 11, 440, 30515, 17, 12331, 11, 791, 15999, 30642, 6030, 198, 6738, 26692, 29...
3.822581
62
#!/usr/bin/env python3 import argparse import logging import sys import zlib sys.path.append("../..") from bento.client.api import ClientConnection from bento.common.protocol import * import bento.common.util as util function_name= "browser" function_code= """ import requests import zlib import os def browser(url, padding): body= requests.get(url, timeout=1).content compressed= zlib.compress(body) final= compressed if padding - len(final) > 0: final= final + (os.urandom(padding - len(final))) else: final= final + (os.urandom((len(final) + padding) % padding)) api.send(final) """ if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 1822, 29572, 198, 11748, 18931, 198, 11748, 25064, 198, 11748, 1976, 8019, 198, 198, 17597, 13, 6978, 13, 33295, 7203, 40720, 492, 4943, 198, 6738, 17157, 78, 13, 16366, ...
2.761317
243
from app import webapp, mysql from app.models import Search , Utils, Collection, WebUtils from flask import request, jsonify from flask.ext.jsonpify import jsonify as jsonp import json ''' Generic search call @params q: search query page: the page number of search results (default 0) type: type of search: {default: free(all fields), category, isbn} @response List of search result objects(ES) '''
[ 6738, 598, 1330, 3992, 1324, 11, 48761, 198, 6738, 598, 13, 27530, 1330, 11140, 837, 7273, 4487, 11, 12251, 11, 5313, 18274, 4487, 198, 6738, 42903, 1330, 2581, 11, 33918, 1958, 198, 6738, 42903, 13, 2302, 13, 17752, 79, 1958, 1330, 3...
2.960265
151
from flask import Flask, make_response app = Flask(__name__) if __name__ == "__main__": app.run(debug=True,port=8080)
[ 6738, 42903, 1330, 46947, 11, 787, 62, 26209, 198, 198, 1324, 796, 46947, 7, 834, 3672, 834, 8, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 598, 13, 5143, 7, 24442, 28, 17821, 11, 634, 28...
2.583333
48
from .audio_source import AudioSource from engine import disk import pyglet.media
[ 6738, 764, 24051, 62, 10459, 1330, 13491, 7416, 198, 6738, 3113, 1330, 11898, 198, 11748, 12972, 70, 1616, 13, 11431, 628 ]
3.952381
21
import os import time print("=====================================================================") print(" ") print(" STARTING SYSTEM REPAIR ") print(" ") print("=====================================================================") print(" ") print("These are the jobs this application can do for you.") print("1.Clean The DISM Component Store") print("2.Repair Corrupted Windows Files Using SFC") print("3.Repair Corrupted Windows Files Using DISM") choice = input("Enter the serial number of the job which you want this application to do (1/2/3): ") if choice == "1": print("Analyzing Component Store") os.system("dism.exe /Online /Cleanup-Image /AnalyzeComponentStore") time.sleep(3) print("Warning: You have to cleanup component store only if necessary.") time.sleep(3) Confirmation = input("Do you want to cleanup the component store?(y/n): ") if Confirmation.upper() == "Y": os.system("dism.exe /Online /Cleanup-Image /StartComponentCleanup") time.sleep(3) print("Now Exiting!") elif Confirmation.upper() == "N": print("Skipping Component Cleanup As Per The User's Instructions") time.sleep(3) print("Now Exiting!") time.sleep(1) else: print('You have to enter only "y" or "n"') time.sleep(3) print("Now Exiting!") time.sleep(1) elif choice == "2": print("Starting SFC Repair Job") os.system("SFC /SCANNOW") time.sleep(3) print("Operation Cpmpleted Successfully!") time.sleep(3) print("Now Exiting!") elif choice == "3": Internet_Connection = input("Do you have an active internet connection?(y/n): ") if Internet_Connection.upper() == "N": iso_file = input("Do you have windows10 wim file?(y/n): ") if iso_file.upper() == "Y": Location = input("Enter the location of the wim file: ") print("Starting DISM") os.system("dism.exe /Online /Cleanup-Image /RestoreHealth /Source:" + Location + " /LimitAccess") time.sleep(3) print("Now Exiting!") else: print("Sorry but you need either internet connection or wim file in order to run Dism") time.sleep(3) print("Now Exiting!") elif Internet_Connection.upper() == "Y": print("Starting DISM") os.system("dism.exe /Online /Cleanup-Image /RestoreHealth") time.sleep(3) print("Now Exiting") else: print("You have to enter only Y/N") time.sleep(3) else: print("Choice Not Valid") time.sleep(3) print("Now Exiting!")
[ 11748, 28686, 198, 11748, 640, 198, 4798, 7203, 23926, 1421, 2625, 8, 198, 4798, 7203, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220...
2.290064
1,248
import numpy as np import pytest import torch from PIL import Image from pytorch_fid import fid_score, inception
[ 11748, 299, 32152, 355, 45941, 198, 11748, 12972, 9288, 198, 11748, 28034, 198, 6738, 350, 4146, 1330, 7412, 198, 198, 6738, 12972, 13165, 354, 62, 69, 312, 1330, 49909, 62, 26675, 11, 30839, 628, 628, 628 ]
3.305556
36
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import time if __name__=="__main__": emsc = emsc_client() emsc.run()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 17802, 198, 11748, 640, 628, 198, 198, 361, 11593, 3672, 834, 855, 1, 834, 12417, 834, 1298, 198, 220, 220, 22...
2.241935
62
""" SNMP subagent entrypoint. """ import asyncio import functools import os import signal import sys import ax_interface from sonic_ax_impl.mibs import ieee802_1ab from . import logger from .mibs.ietf import rfc1213, rfc2737, rfc2863, rfc3433, rfc4292, rfc4363 from .mibs.vendor import dell, cisco # Background task update frequency ( in seconds ) DEFAULT_UPDATE_FREQUENCY = 5 event_loop = asyncio.get_event_loop() shutdown_task = None
[ 37811, 198, 15571, 7378, 850, 25781, 5726, 4122, 13, 198, 37811, 198, 198, 11748, 30351, 952, 198, 11748, 1257, 310, 10141, 198, 11748, 28686, 198, 11748, 6737, 198, 11748, 25064, 198, 198, 11748, 7877, 62, 39994, 198, 6738, 36220, 62, ...
2.76875
160
#!/usr/bin/python3 from __future__ import absolute_import, print_function from optparse import OptionParser, make_option import os import sys import uuid import dbus import dbus.service import dbus.mainloop.glib import time import socket from gi.repository import GLib from dbus.mainloop.glib import DBusGMainLoop import logging from logging import debug, info, warning, error import keymap logging.basicConfig(level=logging.DEBUG) # main routine if __name__ == "__main__": try: DBusGMainLoop(set_as_default=True) myservice = BTKbService() loop = GLib.MainLoop() loop.run() except KeyboardInterrupt: sys.exit()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 3601, 62, 8818, 198, 6738, 2172, 29572, 1330, 16018, 46677, 11, 787, 62, 18076, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, ...
2.759336
241
import ai2thor.controller import numpy as np from PIL import Image, ImageDraw if __name__ == "__main__": # give the height and width of the 2D image and scene id w, h = 900, 900 scene = "FloorPlan2{:02d}_physics".format(1) # allocate controller and initialize the scene and agent # local_path = "src/ai2thor/unity/builds/thor-local-OSXIntel64.app/Contents/MacOS/AI2-Thor" local_path = "" controller = ai2thor.controller.Controller(local_path=local_path) _ = controller.start(width=w, height=h) _ = controller.reset(scene) event = controller.step(dict(action='Initialize', gridSize=0.25, renderClassImage=True, renderObjectImage=True, renderDepthImage=True, fieldOfView=90)) # do something then draw the 3D bbox in 2D image event = controller.step(dict(action="MoveAhead")) event = controller.step(dict(action="MoveAhead")) event = controller.step(dict(action="Rotate", rotation=dict(x=0, y=30, z=0))) event = draw_3d_bbox(event) img = Image.fromarray(event.bbox_3d_frame, "RGB") img.save("./output1.png") event = controller.step(dict(action="LookDown")) event = draw_3d_bbox(event) img = Image.fromarray(event.bbox_3d_frame, "RGB") img.save("./output2.png") event = controller.step(dict(action="LookDown")) event = draw_3d_bbox(event) img = Image.fromarray(event.bbox_3d_frame, "RGB") img.save("./output3.png")
[ 11748, 257, 72, 17, 400, 273, 13, 36500, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 350, 4146, 1330, 7412, 11, 7412, 25302, 628, 628, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1303, 1...
2.233803
710
# --------------------------------------------------------------------- # ElectronR.KO01M.get_metrics # --------------------------------------------------------------------- # Copyright (C) 2007-2020 The NOC Project # See LICENSE for details # --------------------------------------------------------------------- # NOC modules from noc.sa.profiles.Generic.get_metrics import Script as GetMetricsScript, metrics
[ 2, 16529, 30934, 198, 2, 5903, 1313, 49, 13, 22328, 486, 44, 13, 1136, 62, 4164, 10466, 198, 2, 16529, 30934, 198, 2, 15069, 357, 34, 8, 4343, 12, 42334, 383, 399, 4503, 4935, 198, 2, 4091, 38559, 24290, 329, 3307, 198, 2, 16529, ...
5.376623
77