content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import socket import sys import os import optparse from threading import * clients = [] if __name__ == '__main__': main()
[ 11748, 17802, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 2172, 29572, 198, 6738, 4704, 278, 1330, 1635, 628, 628, 198, 198, 565, 2334, 796, 17635, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 197, 1241...
3
43
#!/usr/bin/python # -*- coding: ascii -*- """ Byte utilities testing. :date: 2021 :author: Christian Wiche :contact: cwichel@gmail.com :license: The MIT License (MIT) """ import unittest from embutils.utils import bitmask, reverse_bits, reverse_bytes # -->> Definitions <<------------------ # -->> Test API <<--------------------- # -->> Test Execution <<--------------- if __name__ == '__main__': unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 355, 979, 72, 532, 9, 12, 198, 37811, 198, 40778, 20081, 4856, 13, 198, 198, 25, 4475, 25, 220, 220, 220, 220, 220, 33448, 198, 25, 9800, 25, 220, 220, 220, ...
2.946309
149
# Generated by Django 2.0 on 2018-03-24 02:55 import datetime import django.db.models.deletion from django.db import migrations, models import mptt.fields
[ 2, 2980, 515, 416, 37770, 362, 13, 15, 319, 2864, 12, 3070, 12, 1731, 7816, 25, 2816, 198, 198, 11748, 4818, 8079, 198, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, 198, 6738, 42625, 14208, 13, 9945, 1330, 157...
2.890909
55
# -*- coding: utf-8 -*- """Ant_Algorithm.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1Zjt1SInhoaFEqSmsPjEfWQE7jhugAvZA # **ANT ALGORITHM BY KELOMPOK 9** 1. Heri Khariono - 18081010002 2. Devan Cakra Mudra Wijaya - 18081010013 3. Ika Nur Habibah - 18081010033 4. Trisa Pratiwi - 18081010036 5. Rifky Akhmad Fernanda - 18081010126 # **1. Import Libraries** """ #**********************************IMPORT LIBRARIES******************************* #Library untuk operasi matematika import math #Library untuk membentuk dan memanipulasi segala bentuk graf dan jaringan import networkx as nx #Library untuk visualisasi grafik from matplotlib import pyplot as plt import matplotlib.patches as mpatches from pylab import * #Library untuk mendukung komputasi numerik import numpy as np #Library untuk analisis dan manipulasi data tingkat tinggi import pandas as pn #Library untuk untuk mengukur waktu eksekusi from time import time """# **2. Read Data**""" read_jarak_antarkota = pn.read_excel('https://raw.githubusercontent.com/devancakra/Ant-Algorithm-Pencarian-Rute-Tercepat/master/jarak_antarkota.xlsx') read_kota = pn.read_excel('https://raw.githubusercontent.com/devancakra/Ant-Algorithm-Pencarian-Rute-Tercepat/master/kota.xlsx') arr_kota = np.array(read_kota) arr_jarak_antarkota = np.array(read_jarak_antarkota) #Grafik Map Grafik_Map(arr_kota,arr_jarak_antarkota) """# **3. Implementasi Algoritma Ant** 1. Transisi status, Pembaruan Feromon Lokal, Pembaruan Feromon Global """ import random """2. Konfigurasi perutean""" #Mendefinisikan fungsi untuk mengirim konfigurasi yang berbeda secara teratur #Konfigurasi yang berbeda didefinisikan txt_config = [] #Teks konfigurasi jumlah_semut = [] #Ukuran koloni langkah = [] #Jumlah langkah total rho = [] #Tingkat penguapan fermones ANTARA 0 dan 1 txt_config.append('Konfigurasi 1'); jumlah_semut.append(50); langkah.append(10); rho.append(0.1); txt_config.append('Konfigurasi 2'); jumlah_semut.append(100); langkah.append(10); rho.append(0.1); txt_config.append('Konfigurasi 3'); jumlah_semut.append(250); langkah.append(10); rho.append(0.1); txt_config.append('Konfigurasi 4'); jumlah_semut.append(50); langkah.append(30); rho.append(0.5); txt_config.append('Konfigurasi 5'); jumlah_semut.append(90); langkah.append(40); rho.append(0.5); txt_config.append('Konfigurasi 6'); jumlah_semut.append(150); langkah.append(30); rho.append(0.5); txt_config.append('Konfigurasi 7'); jumlah_semut.append(50); langkah.append(50); rho.append(0.1); txt_config.append('Konfigurasi 8'); jumlah_semut.append(200); langkah.append(90); rho.append(0.1); txt_config.append('Konfigurasi 9'); jumlah_semut.append(150); langkah.append(50); rho.append(0.1); txt_config.append('Konfigurasi 10'); jumlah_semut.append(80); langkah.append(100); rho.append(0.5); txt_config.append('Konfigurasi 11'); jumlah_semut.append(100); langkah.append(100); rho.append(0.5); txt_config.append('Konfigurasi 12'); jumlah_semut.append(150); langkah.append(100); rho.append(0.5); jarak_ab = [] #Vektor perpindahan akhir di setiap konfigurasi tempo = [] #Vektor waktu eksekusi algoritma di setiap konfigurasi for i in range(len(txt_config)): start_time = time() jarak_ab.append(config(txt_config[i], jumlah_semut[i], langkah[i], rho[i])) tempo.append(time()-start_time) """3. Pemilihan Hasil Terbaik""" #Grafik hasil tiga rute terbaik berdasarkan jarak index1=jarak_ab.index(sorted(jarak_ab,reverse=False)[0]) index2=jarak_ab.index(sorted(jarak_ab,reverse=False)[1]) index3=jarak_ab.index(sorted(jarak_ab,reverse=False)[2]) if index2==index1: index2=index2+1 if index2==index3: index3=index3+1 plt.style.use('ggplot') fig = plt.figure(figsize=(10.80,5)) plt.bar(range(3),sorted(jarak_ab,reverse=False)[0:3], edgecolor='#93329F', color='#5D87B6') plt.xticks(range(3),(txt_config[index1],txt_config[index2],txt_config[index3]), rotation=70) plt.ylim(min(jarak_ab[index1],jarak_ab[index2],jarak_ab[index3])-1, max(jarak_ab[index1],jarak_ab[index2],jarak_ab[index3])+1) plt.title("Hasil konfigurasi terbaik berdasarkan jarak") plt.ylabel('Jarak tempuh') plt.xlabel('Konfigurasi rute yang digunakan (jarak)\n\n') plt.show() #Grafik hasil tiga rute terbaik berdasarkan waktu plt.style.use('ggplot') fig = plt.figure(figsize=(10.80,5)) plt.bar(range(3),(tempo[index1],tempo[index2],tempo[index3]), edgecolor='#282623', color='#138d90') plt.xticks(range(3),(txt_config[index1],txt_config[index2],txt_config[index3]), rotation=70) plt.ylim(min(tempo[index1],tempo[index2],tempo[index3])-1, max(tempo[index1],tempo[index2],tempo[index3])+10) plt.title("Hasil konfigurasi terbaik berdasarkan waktu") plt.ylabel('Waktu tempuh') plt.xlabel('Konfigurasi rute yang digunakan (waktu)\n\n') plt.show() #Grafik hasil tiga rute terbaik berdasarkan jalur plt.style.use('ggplot') fig = plt.figure(figsize=(10.80,5)) plt.bar(range(3),(langkah[index1],langkah[index2],langkah[index3]), edgecolor='#F387FF', color='#0D3E00') plt.xticks(range(3),(txt_config[index1],txt_config[index2],txt_config[index3]), rotation=70) plt.ylim(min(langkah[index1],langkah[index2],langkah[index3])-1, max(langkah[index1],langkah[index2],langkah[index3])+1) plt.title("Hasil konfigurasi terbaik berdasarkan jalur") plt.ylabel('Jalur tempuh') plt.xlabel('Konfigurasi rute yang digunakan (jalur)\n\n') plt.show()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 13217, 62, 2348, 42289, 13, 541, 2047, 65, 198, 198, 38062, 4142, 7560, 416, 1623, 4820, 2870, 13, 198, 198, 20556, 2393, 318, 5140, 379, 198, 220, 220, 220, 37...
2.353712
2,290
import numpy as np from scipy.ndimage import maximum_filter def signal2noise(r_map): """ Compute the signal-to-noise ratio of correlation plane. w*h*c""" r = r_map.copy() max_r = maximum_filter(r_map, (5,5,1)) ind = max_r> (r_map+1e-3) r[ind] = 0.05 r = np.reshape(r, (-1, r.shape[-1])) r = np.sort(r,axis=0) ratio = r[-1,:]/r[-2,:] return ratio if __name__=='__main__': main()
[ 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 358, 9060, 1330, 5415, 62, 24455, 628, 198, 198, 4299, 6737, 17, 3919, 786, 7, 81, 62, 8899, 2599, 198, 220, 220, 220, 37227, 3082, 1133, 262, 6737, 12, 1462, 12, 3919, 7...
2.033019
212
import os import time import argparse from tqdm import tqdm import torch from torch import optim from torch import nn from fastNLP import BucketSampler from fastNLP import logger from fastNLP import DataSetIter from fastNLP import Tester from fastNLP import cache_results from bjtunlp.models import BertParser from bjtunlp.models.metrics import SegAppCharParseF1Metric, CWSPOSMetric, ParserMetric from bjtunlp.modules.trianglelr import TriangleLR from bjtunlp.modules.chart import save_table from bjtunlp.modules.pipe import CTBxJointPipe from bjtunlp.modules.word_batch import BatchSampler from bjtunlp.modules.embedding import ElectraEmbedding if __name__ == '__main__': main()
[ 11748, 28686, 198, 11748, 640, 198, 11748, 1822, 29572, 198, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 198, 11748, 28034, 198, 6738, 28034, 1330, 6436, 198, 6738, 28034, 1330, 299, 77, 198, 198, 6738, 3049, 45, 19930, 1330, ...
3.112613
222
import time import torch from torch.autograd import Variable from torch.utils.data.sampler import SubsetRandomSampler from archived.elasticache import redis_init from archived.s3.get_object import get_object from archived.old_model import LogisticRegression from data_loader.libsvm_dataset import DenseDatasetWithLines # lambda setting redis_location = "test.fifamc.ng.0001.euc1.cache.amazonaws.com" grad_bucket = "tmp-grads" model_bucket = "tmp-updates" local_dir = "/tmp" w_prefix = "w_" b_prefix = "b_" w_grad_prefix = "w_grad_" b_grad_prefix = "b_grad_" # algorithm setting learning_rate = 0.1 batch_size = 100 num_epochs = 2 validation_ratio = .2 shuffle_dataset = True random_seed = 42 endpoint = redis_init(redis_location)
[ 11748, 640, 201, 198, 201, 198, 11748, 28034, 201, 198, 6738, 28034, 13, 2306, 519, 6335, 1330, 35748, 201, 198, 6738, 28034, 13, 26791, 13, 7890, 13, 37687, 20053, 1330, 3834, 2617, 29531, 16305, 20053, 201, 198, 201, 198, 6738, 33962,...
2.546358
302
from enum import Enum
[ 6738, 33829, 1330, 2039, 388, 628 ]
3.833333
6
from typing import List from backend.common.cache_clearing import get_affected_queries from backend.common.manipulators.manipulator_base import ManipulatorBase from backend.common.models.cached_model import TAffectedReferences from backend.common.models.team import Team
[ 6738, 19720, 1330, 7343, 198, 198, 6738, 30203, 13, 11321, 13, 23870, 62, 2375, 1723, 1330, 651, 62, 43958, 62, 421, 10640, 198, 6738, 30203, 13, 11321, 13, 805, 541, 24325, 13, 805, 541, 8927, 62, 8692, 1330, 35045, 8927, 14881, 198,...
3.9
70
from django.conf import settings INFUSIONSOFT_COMPANY = getattr(settings, 'INFUSIONSOFT_COMPANY_ID', None) INFUSIONSOFT_API_KEY = getattr(settings, 'INFUSIONSOFT_API_KEY', None)
[ 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 198, 1268, 37, 2937, 11053, 46, 9792, 62, 9858, 47, 31827, 796, 651, 35226, 7, 33692, 11, 705, 1268, 37, 2937, 11053, 46, 9792, 62, 9858, 47, 31827, 62, 2389, 3256, 6045, 8, 198, 1268,...
2.452055
73
# MIT License # # Copyright (c) 2020 HENSOLDT # # 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. # Python implementation of the under/over-exposure measure. We focus on simplicity and readability rather than efficiency. # # This code is related to the paper # M. Teutsch, S. Sedelmaier, S. Moosbauer, G. Eilertsen, T. Walter, # "An Evaluation of Objective Image Quality Assessment for Thermal Infrared Video Tone Mapping", IEEE CVPR Workshops, 2020. # # Please cite the paper if you use the code for your evaluations. # This measure was originally proposed here: # G. Eilertsen, R. Mantiuk, J. Unger, "A comparative review of tone-mapping algorithms for high dynamic range video", Eurographics, 2017. import numpy as np import cv2 ## Calcuate the over- and under-exposure measure (number of over- and under-exposed pixels) for one given tone mapped LDR image. # @param image_ldr Low Definition Range image (processed image after tone mapping). ## Calculate over- and under-exposure measure for all (already tone mapped) images in given path. # @param images_ldr_path Directory path that contains the tone mapped images of one sequence.
[ 2, 17168, 13789, 198, 2, 198, 2, 15069, 357, 66, 8, 12131, 367, 16938, 15173, 51, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 2, 286, 428, 3788, 290, 3917, 10314, ...
3.746087
575
from pilco.models.pilco import PILCO import jax.numpy as jnp import numpy as np import objax import os import oct2py import logging oc = oct2py.Oct2Py(logger=oct2py.get_log()) oc.logger = oct2py.get_log("new_log") oc.logger.setLevel(logging.INFO) dir_path = os.path.dirname(os.path.realpath("__file__")) + "/tests/Matlab Code" oc.addpath(dir_path) if __name__ == "__main__": test_cascade()
[ 6738, 5560, 1073, 13, 27530, 13, 79, 346, 1073, 1330, 350, 4146, 8220, 198, 11748, 474, 897, 13, 77, 32152, 355, 474, 37659, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 26181, 897, 198, 11748, 28686, 198, 11748, 19318, 17, 9078, 1...
2.441718
163
from flask import Blueprint, redirect, url_for from server.utils.core_utils import logger # Create Blueprint main = Blueprint("main", __name__) # redirect when you visit /
[ 6738, 42903, 1330, 39932, 11, 18941, 11, 19016, 62, 1640, 198, 6738, 4382, 13, 26791, 13, 7295, 62, 26791, 1330, 49706, 198, 198, 2, 13610, 39932, 198, 12417, 796, 39932, 7203, 12417, 1600, 11593, 3672, 834, 8, 628, 198, 2, 18941, 618...
3.804348
46
# Generated by Django 3.1.7 on 2021-03-07 06:43 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 22, 319, 33448, 12, 3070, 12, 2998, 9130, 25, 3559, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, ...
2.818182
44
from .odefunc import (ODEnet, ODEfunc) from .cnf import CNF from .diffeq_layers import *
[ 6738, 764, 375, 891, 19524, 1330, 357, 16820, 3262, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 440, 7206, 20786, 8, 198, 198, 6738, 764, 31522, 69, 1330, 327, ...
1.982143
56
import urllib, urllib2, json, time, os username = "username" #CHANGE password = "password" #CHANGE replicaURL = "feature service url/FeatureServer/createReplica" #CHANGE replicaLayers = [0] #CHANGE replicaName = "replicaTest" #CHANGE print("Generating token") url = "https://arcgis.com/sharing/rest/generateToken" data = {'username': username, 'password': password, 'referer': "https://www.arcgis.com", 'f': 'json'} request = urllib2.Request(url, urllib.urlencode(data)) jsonResponse = sendRequest(request) token = jsonResponse['token'] print("Creating the replica") data = {'f' : 'json', 'replicaName' : replicaName, 'layers' : replicaLayers, 'returnAttachments' : 'true', 'returnAttachmentsDatabyURL' : 'false', 'syncModel' : 'none', 'dataFormat' : 'filegdb', 'async' : 'true', 'token': token} request = urllib2.Request(replicaURL, urllib.urlencode(data)) jsonResponse = sendRequest(request) print(jsonResponse) print("Pinging the server") responseUrl = jsonResponse['statusUrl'] url = "{}?f=json&token={}".format(responseUrl, token) request = urllib2.Request(url) jsonResponse = sendRequest(request) while not jsonResponse.get("status") == "Completed": time.sleep(5) request = urllib2.Request(url) jsonResponse = sendRequest(request) userDownloads = os.environ['USERPROFILE'] + "\\Downloads" print("Downloading the replica. In case this fails note that the replica URL is: \n") jres = jsonResponse['resultUrl'] url = "{0}?token={1}".format(jres, token) print(url) f = urllib2.urlopen(url) with open(userDownloads + "\\" + os.path.basename(jres), "wb") as local_file: local_file.write(f.read()) print("\n Finished!")
[ 11748, 2956, 297, 571, 11, 2956, 297, 571, 17, 11, 33918, 11, 640, 11, 28686, 198, 198, 29460, 796, 366, 29460, 1, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220...
2.348808
797
import re import textwrap import yaml from osc_trino_acl_dsl.dsl2rules import dsl_to_rules def rule_matches(rule: dict, table: Table, user: User) -> bool: """emulates trino rule matching semantics""" if ("catalog" in rule) and (not re.fullmatch(rule["catalog"], table.catalog)): return False if ("schema" in rule) and (not re.fullmatch(rule["schema"], table.schema)): return False if ("table" in rule) and (not re.fullmatch(rule["table"], table.table)): return False if ("user" in rule) and (not re.fullmatch(rule["user"], user.user)): return False if "group" in rule: x = [e for e in list(user.groups) if re.fullmatch(rule["group"], e)] if len(x) == 0: return False return True def first_matching_rule(user: User, table: Table, rules: list) -> dict: for rule in rules: if rule_matches(rule, table, user): return rule return None def rule_permissions(user: User, table: Table, rules: dict) -> tuple: assert type(rules) == dict assert "catalogs" in rules assert "schemas" in rules assert "tables" in rules crule = first_matching_rule(user, table, rules["catalogs"]) assert type(crule) == dict assert "allow" in crule allow = crule["allow"] srule = first_matching_rule(user, table, rules["schemas"]) assert type(srule) == dict assert "owner" in srule owner = srule["owner"] trule = first_matching_rule(user, table, rules["tables"]) assert type(trule) == dict assert "privileges" in trule privs = trule["privileges"] return (allow, owner, privs) _admin = ["SELECT", "INSERT", "DELETE", "OWNERSHIP"] _public = ["SELECT"]
[ 11748, 302, 198, 11748, 2420, 37150, 198, 198, 11748, 331, 43695, 198, 198, 6738, 267, 1416, 62, 2213, 2879, 62, 37779, 62, 67, 6649, 13, 67, 6649, 17, 38785, 1330, 288, 6649, 62, 1462, 62, 38785, 628, 628, 198, 4299, 3896, 62, 6759...
2.528634
681
import os from distutils.command.build import build from django.core import management from setuptools import find_packages, setup try: with open(os.path.join(os.path.dirname(__file__), 'README.rst'), encoding='utf-8') as f: long_description = f.read() except: long_description = '' cmdclass = { 'build': CustomBuild } setup( name='byro-cnss', version='0.0.1', description='Byro plugin for CNSS (Clausewitz-Netzwerk fr Strategische Studien e.V.)', long_description=long_description, url='https://github.com/henryk/byro-cnss', author='Henryk Pltz', author_email='henryk@ploetzli.ch', license='Apache Software License', install_requires=[], packages=find_packages(exclude=['tests', 'tests.*']), include_package_data=True, cmdclass=cmdclass, entry_points=""" [byro.plugin] byro_cnss=byro_cnss:ByroPluginMeta """, )
[ 11748, 28686, 198, 6738, 1233, 26791, 13, 21812, 13, 11249, 1330, 1382, 198, 198, 6738, 42625, 14208, 13, 7295, 1330, 4542, 198, 6738, 900, 37623, 10141, 1330, 1064, 62, 43789, 11, 9058, 198, 198, 28311, 25, 198, 220, 220, 220, 351, 1...
2.570605
347
# Copyright 2018, The TensorFlow Federated 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. import numpy as np import tensorflow as tf from utils import tensor_utils if __name__ == '__main__': tf.test.main()
[ 2, 15069, 2864, 11, 383, 309, 22854, 37535, 35089, 515, 46665, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, ...
3.59204
201
#!/usr/bin/env python3 import logging.handlers import sys from sys import argv, modules from os.path import join from autonmap import cron_scheduler from autonmap import launch_client from autonmap import launch_server from autonmap.server import server_config as sconfig """ This module allows autonmap to interact with the server and client process to preform the tasks each is assigned. """ LOG_FILE = "/tmp/autonmap.log" LOGGING_LEVEL = logging.INFO logger = logging.getLogger(__name__) logger.setLevel(LOGGING_LEVEL) handler = logging.handlers.TimedRotatingFileHandler(LOG_FILE, when='midnight', backupCount=3) formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) def main(): """ Main routine :return: None """ if len(argv) > 1: print("Automated nMap Server/Client Manager") if argv[1] == 'cron': cron_scheduler.main() elif argv[1] == "update": if len(argv) == 3: file_location = join(sconfig.get_base(), "work.txt") if str(argv[2]).lower() == "delete": with open(file_location, "w") as file: pass # This empties the file of all contents else: with open(argv[2], "r") as infile: with open(file_location, "w+") as outfile: subnets = set() for in_line in infile: subnets.add(in_line) for out_line in outfile: subnets.add(out_line) outfile.seek(0) outfile.truncate() for item in subnets: outfile.write("{}\n".format(item)) elif len(argv) == 3: if argv[2] in ['start', 'stop', 'update', 'report']: if argv[1] == 'server': sys.stdout = Log(log=logger, level=logging.INFO) sys.stderr = Log(log=logger, level=logging.ERROR) launch_server.main(argv[2]) elif argv[1] == 'client': sys.stdout = Log(log=logger, level=logging.INFO) sys.stderr = Log(log=logger, level=logging.ERROR) launch_client.main(argv[2]) else: print("Invalid arguments") else: print("Invalid arguments") else: print("Usage: {} {} {}".format("python3 -m autonmap", "client|server|update", "start<client>|stop|report|update|" "location<update>|delete<update>")) print("Usage: {} {}".format("python3 -m autonmap", "cron")) print("\t{} {}".format("python3 -m autonmap", "update ~/workfile.txt")) print("Client script is located at: \n\t\t{}".format(modules[launch_client.__name__])) print("The log is located in /tmp/autonmap.log") if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 18931, 13, 4993, 8116, 198, 11748, 25064, 198, 6738, 25064, 1330, 1822, 85, 11, 13103, 198, 6738, 28686, 13, 6978, 1330, 4654, 198, 198, 6738, 1960, 261, 8899, 1330, 10...
1.92561
1,640
# import random # from typing import List, Dict import numpy as np # import matplotlib.pyplot as plt def get_info() -> dict: """ This controls your Battlesnake appearance and author permissions. For customization options, see https://docs.battlesnake.com/references/personalization TIP: If you open your Battlesnake URL in browser you should see this data. """ return { "apiversion": "1", "author": "Mex", # TODO: Your Battlesnake Username "color": "#888889", # TODO: Personalize "head": "silly", # TODO: Personalize "tail": "curled", # TODO: Personalize } # Globals food_weight = 9 snake_weight = -9 snake_head_weight = -2 wall_weight = -9 board_centre = 1 board_x = None board_y = None def gkern(l=10, scale=4): """\ creates gaussian kernel with side length `l` and a sigma of `sig` """ sig = (l-1)/3 ax = np.linspace(-(l - 1) / 2., (l - 1) / 2., l) gauss = np.exp(-0.5 * np.square(ax) / np.square(sig)) kernel = np.outer(gauss, gauss) return scale * kernel / np.max(kernel) data = { "turn": 14, "board": { "height": 11, "width": 11, "food": [ {"x": 5, "y": 5}, {"x": 9, "y": 0}, {"x": 2, "y": 6} ], "hazards": [ {"x": 3, "y": 2} ], "snakes": [ { "id": "snake-508e96ac-94ad-11ea-bb37", "name": "My Snake", "health": 54, "body": [ {"x": 0, "y": 0}, {"x": 1, "y": 0}, {"x": 2, "y": 0} ], "latency": "111", "head": {"x": 0, "y": 0}, "length": 3, "shout": "why are we shouting??", "squad": "", "customizations":{ "color":"#FF0000", "head":"pixel", "tail":"pixel" } }, { "id": "snake-b67f4906-94ae-11ea-bb37", "name": "Another Snake", "health": 16, "body": [ {"x": 5, "y": 4}, {"x": 5, "y": 3}, {"x": 6, "y": 3}, {"x": 6, "y": 2} ], "latency": "222", "head": {"x": 5, "y": 4}, "length": 4, "shout": "I'm not really sure...", "squad": "", "customizations":{ "color":"#26CF04", "head":"silly", "tail":"curled" } } ] }, "you": { "id": "snake-508e96ac-94ad-11ea-bb37", "name": "My Snake", "health": 54, "body": [ {"x": 0, "y": 0}, {"x": 1, "y": 0}, {"x": 2, "y": 0} ], "latency": "111", "head": {"x": 0, "y": 0}, "length": 3, "shout": "why are we shouting??", "squad": "", "customizations":{ "color":"#FF0000", "head":"pixel", "tail":"pixel" } } } if False: board = centre_grad(data) board_x, board_y = 11, 11 populate_other_snakes(board, data) populate_food(board, data) board = np.pad(board, 1, 'constant', constant_values=snake_weight) # plt.imshow(np.rot90(np.fliplr(board)), interpolation='none', origin="lower") # plt.show()
[ 2, 1330, 4738, 198, 2, 422, 19720, 1330, 7343, 11, 360, 713, 198, 11748, 299, 32152, 355, 45941, 198, 2, 1330, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 4299, 651, 62, 10951, 3419, 4613, 8633, 25, 198, 220, 220, ...
1.912937
1,631
# pdf.244
[ 198, 2, 37124, 13, 25707, 198 ]
1.833333
6
import os import sys from dataclasses import dataclass, field from typing import List, Set, Optional from nuclear.builder.rule import PrimaryOptionRule, ParameterRule, FlagRule, CliRule, SubcommandRule, \ PositionalArgumentRule, ManyArgumentsRule, DictionaryRule, ValueRule from nuclear.parser.context import RunContext from nuclear.parser.keyword import format_var_names, format_var_name from nuclear.parser.parser import Parser from nuclear.parser.transform import filter_rules from nuclear.parser.value import generate_value_choices from nuclear.version import __version__ internal_options = {'--autocomplete', '--install-bash', '--install-autocomplete'}
[ 11748, 28686, 198, 11748, 25064, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 11, 2214, 198, 6738, 19720, 1330, 7343, 11, 5345, 11, 32233, 198, 198, 6738, 4523, 13, 38272, 13, 25135, 1330, 21087, 19722, 31929, 11, 25139, 2357, 3...
3.586735
196
#The MIT License (MIT) # #Copyright (c) 2015 Geoffroy Givry # #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 nuke LookAtName = "LookAt"
[ 2, 464, 17168, 13789, 357, 36393, 8, 201, 198, 2, 201, 198, 2, 15269, 357, 66, 8, 1853, 24688, 3287, 402, 452, 563, 201, 198, 2, 201, 198, 2, 5990, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 486...
3.403509
342
""" `main` is the top level module where AppEngine gets access to your Flask application. """ from app import create_app from config import config from os import environ if environ['SERVER_SOFTWARE'].startswith('Development'): app_config = config['development'] else: app_config = config['production'] app = create_app(app_config) # Note: We don't need to call run() since our application is # embedded within the App Engine WSGI application server.
[ 37811, 198, 63, 12417, 63, 318, 262, 1353, 1241, 8265, 810, 2034, 13798, 3011, 1895, 198, 1462, 534, 46947, 3586, 13, 198, 37811, 628, 198, 6738, 598, 1330, 2251, 62, 1324, 198, 6738, 4566, 1330, 4566, 198, 6738, 28686, 1330, 551, 226...
3.569231
130
#!/usr/bin/env python3 # -*-coding:utf-8-*- """ This module is used to extract features from the data """ import numpy as np from scipy.fftpack import fft from scipy.fftpack.realtransforms import dct import python_speech_features eps = 0.00000001 def file_length(soundParams): """Returns the file length, in seconds""" return soundParams[3] / soundParams[2] def zcr(frame): """Computes zero crossing rate of frame""" count = len(frame) countZ = np.sum(np.abs(np.diff(np.sign(frame)))) / 2 return countZ / (count - 1) def energy(frame): """Computes signal energy of frame""" return np.sum(frame ** 2) / len(frame) def energy_entropy(frame, numOfShortBlocks=10): """Computes entropy of energy""" tfe = np.sum(frame ** 2) # total frame energy L = len(frame) subWinLength = int(np.floor(L / numOfShortBlocks)) if L != subWinLength * numOfShortBlocks: frame = frame[0:subWinLength * numOfShortBlocks] # subWindows is of size [numOfShortBlocks x L] subWindows = frame.reshape(subWinLength, numOfShortBlocks, order='F').copy() # Compute normalized sub-frame energies: s = np.sum(subWindows ** 2, axis=0) / (tfe + eps) # Compute entropy of the normalized sub-frame energies: entropy = -1 * np.sum(s * np.log2(s + eps)) return entropy def spectral_centroid_and_spread(X, fs): """Computes spectral centroid of frame (given abs(FFT))""" ind = (np.arange(1, len(X) + 1)) * (fs/(2.0 * len(X))) Xt = X.copy() Xt = Xt / Xt.max() NUM = np.sum(ind * Xt) DEN = np.sum(Xt) + eps C = (NUM / DEN) # Centroid S = np.sqrt(np.sum(((ind - C) ** 2) * Xt) / DEN) # Spread # Normalize: C = C / (fs / 2.0) S = S / (fs / 2.0) return (C, S) def avg_mfcc(sound_obj, avg=True): """Extract the MFCC from the sound object""" soundD = sound_obj["sound"] # raw data sr = sound_obj["params"][2] # samplerate # nf = sound_obj["params"][3] # nframes all_mfcc = python_speech_features.mfcc(soundD, samplerate=sr, winlen=0.025, winstep=1) if avg: return np.mean(all_mfcc, axis=0) return all_mfcc def mfcc_init_filter_banks(fs, nfft): """Computes the triangular filterbank for MFCC computation""" # filter bank params: lowfreq = 133.33 linsc = 200/3. logsc = 1.0711703 numLinFiltTotal = 13 numLogFilt = 27 # Total number of filters nFiltTotal = numLinFiltTotal + numLogFilt # Compute frequency points of the triangle: freqs = np.zeros(nFiltTotal+2) freqs[:numLinFiltTotal] = lowfreq + np.arange(numLinFiltTotal) * linsc freqs[numLinFiltTotal:] = freqs[numLinFiltTotal-1] * logsc ** np.arange(1, numLogFilt + 3) heights = 2./(freqs[2:] - freqs[0:-2]) # Compute filterbank coeff (in fft domain, in bins) fbank = np.zeros((nFiltTotal, nfft)) nfreqs = np.arange(nfft) / (1. * nfft) * fs for i in range(nFiltTotal): lowTrFreq = freqs[i] cenTrFreq = freqs[i+1] highTrFreq = freqs[i+2] lid = np.arange(np.floor(lowTrFreq * nfft / fs) + 1, np.floor(cenTrFreq * nfft / fs) + 1, dtype=np.int) lslope = heights[i] / (cenTrFreq - lowTrFreq) rid = np.arange(np.floor(cenTrFreq * nfft / fs) + 1, np.floor(highTrFreq * nfft / fs) + 1, dtype=np.int) rslope = heights[i] / (highTrFreq - cenTrFreq) fbank[i][lid] = lslope * (nfreqs[lid] - lowTrFreq) fbank[i][rid] = rslope * (highTrFreq - nfreqs[rid]) return fbank, freqs def mfcc(X, fbank, nceps=13): """Computes the MFCCs of a frame, given the fft mag""" mspec = np.log10(np.dot(X, fbank.T)+eps) ceps = dct(mspec, type=2, norm='ortho', axis=-1)[:nceps] return ceps def extract_all_features0(sound_obj): """Extract the features from the sound object""" # fl = file_length(sound_obj["params"]) test_mfcc_avg = avg_mfcc(sound_obj) # return np.concatenate(([fl], test_mfcc_avg)) return test_mfcc_avg def features_labels0(): """Give a name to each feature""" return ["mfcc{}".format(i) for i in range(13)] def extract_all_features(sound_obj, wins=None, steps=None): """Extract the features from the sound object""" sr = sound_obj["params"][2] # samplerate nbs = sound_obj["params"][3] # number of samples if wins is None: wins = int(0.050 * sr) if steps is None: steps = int(nbs/15 - wins) # Signal normalization signal = sound_obj["sound"] signal = signal / (2.0 ** 15) DC = signal.mean() MAX = (np.abs(signal)).max() signal = (signal - DC) / (MAX + 0.0000000001) N = len(signal) # total number of samples curPos = steps // 2 # skip the very beginning nFFT = wins // 2 # compute the triangular filter banks used in the mfcc calculation #[fbank, _] = mfcc_init_filter_banks(sr, nFFT) totalNumOfFeatures = 5 + 13 stFeatures = [] while curPos + wins - 1 < N: # for each short-term window until the end of signal x = signal[curPos:curPos+wins] # get current window curPos = curPos + steps # update window position X = abs(fft(x)) # get fft magnitude X = X[0:nFFT] # normalize fft X = X / len(X) curFV = np.zeros(totalNumOfFeatures) curFV[0] = zcr(x) # zero crossing rate curFV[1] = energy(x) # short-term energy curFV[2] = energy_entropy(x) # short-term entropy of energy [curFV[3], curFV[4]] = spectral_centroid_and_spread(X, sr) # spectral centroid and spread # curFV[5] = stSpectralEntropy(X) # spectral entropy # curFV[6] = stSpectralFlux(X, Xprev) # spectral flux # curFV[7] = stSpectralRollOff(X, 0.90, sr) # spectral rolloff # curFV[numOfTimeSpectralFeatures:numOfTimeSpectralFeatures+nceps, 0] = stMFCC(X, fbank, nceps).copy() # MFCCs # # chromaNames, chromaF = stChromaFeatures(X, sr, nChroma, nFreqsPerChroma) # curFV[numOfTimeSpectralFeatures + nceps: numOfTimeSpectralFeatures + nceps + numOfChromaFeatures - 1] = chromaF # curFV[numOfTimeSpectralFeatures + nceps + numOfChromaFeatures - 1] = chromaF.std() #curFV[5:18] = mfcc(X, fbank, 13) #curFV[0:13] = mfcc(X, fbank, 13) curFV[5:18] = python_speech_features.mfcc(x, samplerate=sr, winlen=wins/sr, winstep=steps/sr) # TEMP #curFV = python_speech_features.mfcc(signal, samplerate=sr, winlen=wins, winstep=steps).T stFeatures.append(curFV) # stFeatures = np.array(stFeatures) stFeatures = np.concatenate(stFeatures, 0).flatten() #stFeatures = np.mean(stFeatures, axis=0) # stFeatures = python_speech_features.mfcc(signal, samplerate=sr, winlen=wins/sr, winstep=steps/sr) # stFeatures = np.mean(stFeatures, axis=0) return stFeatures # sound_obj2 = sound_obj.copy() # sound_obj2["sound"] = signal # # # fl = file_length(sound_obj["params"]) # test_mfcc_avg = avg_mfcc(sound_obj2) # # return np.concatenate(([fl], test_mfcc_avg)) # return test_mfcc_avg def features_labels(): """Give a name to each feature""" return ["zrc", "energy", "en_ent", "centr", "spread"] + ["mfcc{}".format(i) for i in range(13)]
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 66, 7656, 25, 40477, 12, 23, 12, 9, 12, 198, 198, 37811, 198, 1212, 8265, 318, 973, 284, 7925, 3033, 422, 262, 1366, 198, 37811, 198, 198, 11748, 299, 32152, 3...
2.204552
3,383
from .combine_sector_results import * from .DiagnosticsLog import * from .EstimationModel import * from .format_regression_table import * from .save_and_load import * from .SlimResults import * from .Specification import * from .visualize_results import *
[ 6738, 764, 24011, 500, 62, 34914, 62, 43420, 1330, 1635, 198, 6738, 764, 18683, 4660, 34558, 11187, 1330, 1635, 198, 6738, 764, 22362, 18991, 17633, 1330, 1635, 198, 6738, 764, 18982, 62, 2301, 2234, 62, 11487, 1330, 1635, 198, 6738, 76...
3.541667
72
# Part of the Engi-WebGL suite. from bpy.props import * from bpy_extras.io_utils import ExportHelper from mathutils import * from functools import reduce import os, sys, os.path, bpy, bmesh, math, struct, base64, itertools bl_info = { 'name': 'Curve Export (.json)', 'author': 'Lasse Nielsen', 'version': (0, 2), 'blender': (2, 72, 0), 'location': 'File > Export > Curve (.json)', 'description': 'Curve Export (.json)', 'category': 'Import-Export' } # Compress number representation to save as much space as possible. if __name__ == '__main__': register()
[ 2, 2142, 286, 262, 1985, 72, 12, 13908, 8763, 18389, 13, 198, 198, 6738, 275, 9078, 13, 1676, 862, 1330, 1635, 198, 6738, 275, 9078, 62, 2302, 8847, 13, 952, 62, 26791, 1330, 36472, 47429, 198, 6738, 10688, 26791, 1330, 1635, 198, 6...
2.821782
202
import mimetypes from pathlib import Path from organize.utils import DotDict, flatten from .filter import Filter
[ 11748, 17007, 2963, 12272, 198, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 16481, 13, 26791, 1330, 22875, 35, 713, 11, 27172, 268, 198, 198, 6738, 764, 24455, 1330, 25853, 628 ]
3.741935
31
from conans import ConanFile, CMake, tools
[ 6738, 369, 504, 1330, 31634, 8979, 11, 327, 12050, 11, 4899, 628 ]
3.666667
12
import numpy as np VEC_FORWARD = np.array([0, 0, 1]) VEC_UP = np.array([0, 1, 0]) VEC_RIGHT = np.array([1, 0, 0]) STYLE_NOMOVE = np.array([1, 0, 0, 0, 0, 0]) STYLE_TROT = np.array([0, 1, 0, 0, 0, 0]) STYLE_JUMP = np.array([0, 0, 1, 0, 0, 0]) STYLE_SIT = np.array([0, 0, 0, 1, 0, 0]) STYLE_STAND = np.array([0, 0, 0, 0, 1, 0]) STYLE_LAY = np.array([0, 0, 0, 0, 0, 1]) NUM_STYLES = 6 SYS_FREQ = 60 DURATION = 9 NUM_QUERIES = SYS_FREQ * DURATION MOCAP_SAMPLE_PATH = "animation/data/mocap-sample.txt"
[ 11748, 299, 32152, 355, 45941, 201, 198, 201, 198, 53, 2943, 62, 13775, 39743, 796, 45941, 13, 18747, 26933, 15, 11, 657, 11, 352, 12962, 201, 198, 53, 2943, 62, 8577, 796, 45941, 13, 18747, 26933, 15, 11, 352, 11, 657, 12962, 201, ...
1.788396
293
#!/usr/bin/python import argparse,codes3d,configparser, os if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create a BED file detailing the locations of genes in the genome, and a database containing additional gene information. Note: If a file in .gtf format is supplied, no other arguments are required.") parser.add_argument("-i","--gene_files",required=True,nargs='+',help="The gene file/s to be indexed; either in tabular format, or, by default, the .gtf file format, as supplied by the GTEx project.") parser.add_argument("-g","--symbol_col",type=int,help="The index of the column containing the gene symbol (non-zero based; default: ).") parser.add_argument("-c","--chr_col",type=int,help="The index of the column containing the chromosome name (non-zero based; default: ).") parser.add_argument("-s","--start_col",type=int,help="The index of the column containing the gene start site (non-zero based; default: ).") parser.add_argument("-e","--end_col",type=int,help="The index of the column containing the gene end site (non-zero based; default: ).") parser.add_argument("-p","--p_threshold_col",type=int,help="The index of the column containing the GTEx p-threshold for this gene (optional; non-zero based; default: ).") parser.add_argument("-H","--no_header",action="store_true",help="Use this option if the table has no header.") parser.add_argument("-b","--output_bed_fp",help="The path to which to output the resultant BED file of gene locations (default: the input file name with the extension \".bed\").") parser.add_argument("-o","--output_db",help="The path to which to output the resultant gene index database (default: the input file name with the extension \".db\").") parser.add_argument("-C","--config_file",default=os.path.join(os.path.dirname(__file__),"../docs/codes3d.conf"),help="The configuration file specifying the location of the CoDeS3D library (default: docs/codes3d.conf).") args = parser.parse_args() config = configparser.ConfigParser() config.read(args.config_file) codes3d.build_gene_index(args.gene_files,args.output_bed_fp,args.output_db,config,args.symbol_col,args.chr_col,args.start_col,args.end_col,args.p_threshold_col,args.no_header)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 11748, 1822, 29572, 11, 40148, 18, 67, 11, 11250, 48610, 11, 28686, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 197, 48610, 796, 1822, 29572, 13, 28100, 1713,...
3.258065
682
import numpy as np from Optimizer.path import get_x_substeps from Kinematic import frames, chain as kc # General def frames2spheres(f, robot): """ x_spheres (n_samples, n_wp, n_links, n_dim) """ return frames2pos(f, frame_idx=robot.spheres_frame_idx, rel_pos=robot.spheres_position) def frames2spheres_jac(f, j, robot): """ x_spheres (n_samples, n_wp, n_spheres, n_dim) dx_dq (n_samples, n_wp, n_dof, n_spheres, n_dim) """ x_spheres = frames2spheres(f=f, robot=robot) dx_dq = (j[:, :, :, robot.spheres_frame_idx, :, :] @ robot.spheres_position[:, :, np.newaxis])[..., :-1, 0] return x_spheres, dx_dq # nfi - next frame index # iff - influence frame frame # Helper # Combine fun def create_frames_dict(f, nfi): """ Create a dict to minimize the calculation of unnecessary transformations between the frames The value to the key 0 holds all transformations form the origin to the whole chain. Each next field holds the transformation from the current frame to all frames to come. The calculation happens from back to front, to save some steps # 0 1 2 3 4 # F01 # F02 F12 # F03 F13 F23 # F04 F14 F24 F34 # F05 F15 F25 F35 F45 """ n_frames = f.shape[-3] d = {} for i in range(n_frames - 1, -1, -1): nfi_i = nfi[i] if nfi_i == -1: d[i] = f[..., i:i + 1, :, :] elif isinstance(nfi_i, (list, tuple)): d[i] = np.concatenate([ f[..., i:i + 1, :, :], f[..., i:i + 1, :, :] @ np.concatenate([d[j] for j in nfi_i], axis=-3)], axis=-3) else: d[i] = np.concatenate([f[..., i:i + 1, :, :], f[..., i:i + 1, :, :] @ d[nfi_i]], axis=-3) return d
[ 11748, 299, 32152, 355, 45941, 198, 198, 6738, 30011, 7509, 13, 6978, 1330, 651, 62, 87, 62, 7266, 20214, 198, 6738, 509, 7749, 1512, 1330, 13431, 11, 6333, 355, 479, 66, 628, 628, 198, 2, 3611, 628, 628, 198, 198, 4299, 13431, 17, ...
2.045204
907
import dns.resolver import dns.ipv4 import argparse parser = argparse.ArgumentParser() parser.add_argument('-l', "--list", help="List of dns names you want IP's for") parser.add_argument('-o', "--output", help="Output file to save list") args = parser.parse_args() ip_list = [...] subs = open(args.list, 'r', newline='') if args.list: for host in subs: host = host.strip('\n',) host = host.strip('https://') host = host.strip('http://') # print(host) try: i = dns.resolver.query(host,'A' ) #print(i.rrset.items[0]) for item in i: if not item in ip_list: ip_list.append(item) print(item) except Exception as error: a = error if args.output: file = open(args.output, "w") for p in ip_list: file.write(str(p)) file.write("\n") file.close()
[ 11748, 288, 5907, 13, 411, 14375, 198, 11748, 288, 5907, 13, 541, 85, 19, 198, 11748, 1822, 29572, 198, 198, 48610, 796, 1822, 29572, 13, 28100, 1713, 46677, 3419, 198, 48610, 13, 2860, 62, 49140, 10786, 12, 75, 3256, 366, 438, 4868, ...
1.954
500
import pandas import numpy as np import math import os import sys import re from utils import * DIR_PATH = os.path.dirname(os.path.realpath(__file__)) percentiles = [ 10, 25, 50, 75, 90, 95, 99, 99.9 ] DATA_FOLDER = DIR_PATH + '/data' if __name__ == "__main__": main()
[ 11748, 19798, 292, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 10688, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 302, 198, 198, 6738, 3384, 4487, 1330, 1635, 198, 198, 34720, 62, 34219, 796, 28686, 13, 6978, 13, 15908, 3672, ...
2.536364
110
from typing import Optional from platypush.backend import Backend from platypush.context import get_plugin from platypush.message.event.foursquare import FoursquareCheckinEvent # vim:sw=4:ts=4:et:
[ 6738, 19720, 1330, 32233, 198, 198, 6738, 40315, 4464, 1530, 13, 1891, 437, 1330, 5157, 437, 198, 6738, 40315, 4464, 1530, 13, 22866, 1330, 651, 62, 33803, 198, 6738, 40315, 4464, 1530, 13, 20500, 13, 15596, 13, 69, 4662, 421, 533, 13...
3.045455
66
import os import time import pandas as pd from src.utils import get_project_root from src.data.item_names_replacement import REPLACE_DICT1, REPLACE_DICT1 YEARS = [str(x) for x in list(range(2013,2021))] ROOT_DIR = get_project_root() def load_data(data_abs_path: str) -> pd.DataFrame: """Load raw data Parameters: ----------- data_abs_path: absolute path of csv data Returns: -------- data_df: raw data dataframe """ data_df = pd.read_csv(data_abs_path) data_df.sales_datetime = pd.to_datetime(data_df.sales_datetime, format='%Y-%m-%d', utc=True) data_df.set_index('sales_datetime', inplace=True) return data_df
[ 11748, 28686, 198, 11748, 640, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 12351, 13, 26791, 1330, 651, 62, 16302, 62, 15763, 198, 6738, 12351, 13, 7890, 13, 9186, 62, 14933, 62, 35666, 5592, 1330, 45285, 11598, 62, 35, 18379, 16...
2.42029
276
""" This file contains assorted general utility functions used by other modules in the aiml_bot package. """ # TODO: Correctly handle abbreviations. def split_sentences(text: str) -> list: """Split the string s into a list of sentences.""" if not isinstance(text, str): raise TypeError(text) position = 0 results = [] length = len(text) while position < length: try: period = text.index('.', position) except ValueError: period = length + 1 try: question = text.index('?', position) except ValueError: question = length + 1 try: exclamation = text.index('!', position) except ValueError: exclamation = length + 1 end = min(period, question, exclamation) sentence = text[position:end].strip() if sentence: results.append(sentence) position = end + 1 # If no sentences were found, return a one-item list containing # the entire input string. if not results: results.append(text.strip()) # print(results) return results
[ 37811, 198, 1212, 2393, 4909, 46603, 2276, 10361, 5499, 973, 416, 584, 198, 18170, 287, 262, 4031, 75, 62, 13645, 5301, 13, 198, 37811, 628, 198, 2, 16926, 46, 25, 22941, 306, 5412, 37640, 602, 13, 198, 4299, 6626, 62, 34086, 3007, ...
2.490196
459
import os, time, random from collections import defaultdict from System import Console, ConsoleColor, ConsoleKey from System.Threading import Thread, ThreadStart if __name__ == "__main__": screen = Screen(); logic = GameLogic(); stats = Stastics(); fruit = Fruit(); snake = Snake() while snake.position_in_buffer(fruit.current_position): fruit.reset_position() screen.color(fruit.current_position,1,1,screen.red) while logic.update(screen, snake, fruit, stats): time.sleep(0.05) logic.end()
[ 11748, 28686, 11, 640, 11, 4738, 198, 6738, 17268, 1330, 4277, 11600, 198, 6738, 4482, 1330, 24371, 11, 24371, 10258, 11, 24371, 9218, 198, 6738, 4482, 13, 16818, 278, 1330, 14122, 11, 14122, 10434, 198, 198, 361, 11593, 3672, 834, 6624...
3.339869
153
# #! coding:utf-8 import xml.etree.ElementTree as ET from xml.etree import ElementTree import base64 import binascii import numpy as np import matplotlib.pyplot as plt from collections import OrderedDict SubType = {'1':'ASD','2':'CSD','3':'TF','4':'???','5':'COH'} average_type = {'0':'Fixed','1':'Exponential','2':'Accumulative'} # not comfirmed window_type = {'0':'Uniform','1':'Hanning','2':'Flat-top', '3':'Welch','4':'Bartlet','5':'BMH'} # not comfirmed
[ 2, 198, 2, 0, 19617, 25, 40477, 12, 23, 198, 198, 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 12152, 198, 6738, 35555, 13, 316, 631, 1330, 11703, 27660, 198, 11748, 2779, 2414, 198, 11748, 9874, 292, 979, 72, 198, 11748, 299,...
2.211454
227
# Copyright 2019 Google LLC # # 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 # # https://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. r"""Program to build a graph based on dense input features (embeddings). This is a wrapper around the `nsl.tools.build_graph` API. See its documentation for more details. USAGE: `python graph_builder.py` [*flags*] *input_features.tfr... output_graph.tsv* For details about this program's flags, run `python graph_builder.py --help`. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import app from absl import flags from neural_structured_learning.tools import graph_builder_lib import tensorflow as tf def _main(argv): """Main function for running the graph_builder program.""" flag = flags.FLAGS flag.showprefixforinfo = False if len(argv) < 3: raise app.UsageError( 'Invalid number of arguments; expected 2 or more, got %d' % (len(argv) - 1)) graph_builder_lib.build_graph(argv[1:-1], argv[-1], flag.similarity_threshold, flag.id_feature_name, flag.embedding_feature_name) if __name__ == '__main__': flags.DEFINE_string( 'id_feature_name', 'id', """Name of the singleton bytes_list feature in each input Example whose value is the Example's ID.""") flags.DEFINE_string( 'embedding_feature_name', 'embedding', """Name of the float_list feature in each input Example whose value is the Example's (dense) embedding.""") flags.DEFINE_float( 'similarity_threshold', 0.8, """Lower bound on the cosine similarity required for an edge to be created between two nodes.""") # Ensure TF 2.0 behavior even if TF 1.X is installed. tf.compat.v1.enable_v2_behavior() app.run(_main)
[ 2, 15069, 13130, 3012, 11419, 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, 743, 733...
2.983073
768
import torch from torch.utils import data import sys from sklearn.utils import shuffle import numpy as np import argparse import matplotlib.pyplot as plt def get_PostSet(pcounts_name = "opt_pcounts", pcounts_path = "results/metadata", pc_split=0.1, seed = 0, metadata_name = "opt_tags", metadata_path = "results/metadata", bias_top=1, bias_normal=1): """ ONLY VALID FOR METADATA THAT IS A LIST FOR EACH SONG """ # LOAD PCOUNTS AND METADATA pcounts = torch.load(pcounts_path + "/" + pcounts_name) #list index2 = int(len(pcounts)*(1 - pc_split)) pcounts = shuffle(pcounts, random_state=seed)[index2:] # Test partition metadata, meta = torch.load(metadata_path + "/" + metadata_name) Nclasses = len(meta) meta2idx = {meta[i]:i for i in range(Nclasses)} idx2meta = {i:meta[i] for i in range(Nclasses)} # CHANGE METADATA print("Metadata2num and opt_pcounts to dict...") idx_metadata = {} # same as metadata but using the index of meta2idx for i in range(len(metadata)): if metadata[i] == -1: idx_metadata[i] = -1 else: idx_metadata[i] = [meta2idx[m] for m in metadata[i]] dict_pcounts = {} for i in range(len(pcounts)): dict_pcounts[i] = pcounts[i] # USER META COUNT print("Before filtering users without metadata,", len(pcounts)) user2class_counts = {} total = len(dict_pcounts) for b, user in enumerate(list(dict_pcounts.keys())): print(" {0:0.3f}% \r".format((b+1.)*100./total), end="") class_counts = torch.zeros(Nclasses) for song in dict_pcounts[user]: if idx_metadata[song] != -1: class_counts[idx_metadata[song]] += 1 if (class_counts != 0).any(): user2class_counts[user] = class_counts.data.tolist() else: del dict_pcounts[user] # GET TOP CLASS print("After filtering users without metadata,", len(user2class_counts), len(dict_pcounts)) user2topclass = {} for user in user2class_counts.keys(): user2topclass[user] = idx2meta[torch.argmax(torch.tensor(user2class_counts[user])).data.tolist()] # SPLIT INTO [SONGS, TOP CLASS SONGS, TOP TAG] user2topsongs = {} user2normalsongs = {} total = len(dict_pcounts) for b, user in enumerate(dict_pcounts.keys()): print(" {0:0.3f}%\r".format((b+1.)/total*100), end="") top = [] normal = [] Ntop = 0 for song in dict_pcounts[user]: if metadata[song] != -1: if (user2topclass[user] in metadata[song]) and Ntop<100: top += [song] Ntop += 1 else: normal += [song] else: normal += [song] user2topsongs[user] = top user2normalsongs[user] = normal # DELETE USERS (BIAS_TOP, BIAS_NORMAL) predict_dataset = [] for b, user in enumerate(dict_pcounts.keys()): print(" {0:0.3f}%\r".format((b+1.)/total*100), end="") if len(user2topsongs[user]) >= bias_top and len(user2normalsongs[user]) >= bias_normal: predict_dataset += [[user2normalsongs[user], user2topsongs[user], user2topclass[user]]] print("# Users (after deleting top<{}, inp<{}): ".format(bias_top, bias_normal), len(predict_dataset)) torch.save(predict_dataset, metadata_path + "/postset_{}_t{}_n{}".format(metadata_name, bias_top, bias_normal)) return def get_topclass2Ntopclass(bias_top=1, bias_normal=1, metadata_path="results/metadata", metadata_name="opt_tags"): print("Calculating topclass2Ntopclass...") PostSet = torch.load(metadata_path + "/postset_{}_t{}_n{}".format(metadata_name, bias_top, bias_normal)) topclass2Ntopclass = {} for b, (inp, out, c) in enumerate(PostSet): if c not in list(topclass2Ntopclass.keys()): topclass2Ntopclass[c] = 0 topclass2Ntopclass[c] += 1 torch.save(topclass2Ntopclass, metadata_path + "/topclass2Ntopclass_{}_t{}_n{}".format(metadata_name, bias_top, bias_normal)) return def get_class2song(metadata_path="results/metadata", metadata_name="opt_tags"): print("Calculating class2song...") metadata, meta = torch.load(metadata_path + "/" + metadata_name) class2song = {c:[] for c in meta} total = len(metadata) for i in range(total): print(" {0:0.3f}%\r".format((i+1.)/total*100), end="") if metadata[i] == -1: continue for c in metadata[i]: class2song[c] += [i] torch.save(class2song, metadata_path + "/{}2song".format(metadata_name)) return def get_class2vector(metadata_path="results/metadata", metadata_name="opt_tags", Nsongs=180198): print("Calculating get_class2vector...") class2song = torch.load(metadata_path + "/{}2song".format(metadata_name)) _, meta = torch.load(metadata_path + "/" + metadata_name) # for idx2meta Nclasses = len(meta) meta2idx = {meta[i]:i for i in range(Nclasses)} idx2meta = {i:meta[i] for i in range(Nclasses)} total = len(class2song) class2vector = torch.zeros(total,Nsongs).long() for i in range(total): print(" {0:0.3f}%\r".format((i+1.)/total*100), end="") class2vector[i][class2song[idx2meta[i]]] = 1 torch.save(class2vector, metadata_path + "/{}2vector".format(metadata_name)) return if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--bias_top', type=int, default=1, help="Minimum number of songs in user_topsongs to be taken in care") parser.add_argument('--bias_normal', type=int, default=1, help="Minimum number of songs in user_normalsongs to be taken in care") parser.add_argument('--Nsongs', type=int, default=180198, help="Number of different songs") parser.add_argument('--metadata_name', type=str, default="opt_tags", help="Name of the metadata to use") parser.add_argument('--metadata_path', type=str, default="results/metadata", help="Path of the metadata to use") parser.add_argument('--pcounts_name', type=str, default="opt_pcounts", help="Name of the pcounts to use") parser.add_argument('--pcounts_path', type=str, default="results/metadata", help="Path of the pcounts to use") parser.add_argument('--TODO', nargs='+', type=str, default=["all"], help="Things to calculate") args = parser.parse_args() if args.TODO == ["all"]: args.TODO = ["postset", "topclass2Ntopclass", "class2song", "class2vector"] print("METADATA: {}\nBIAS TOP: {}\nBIAS NORMAL: {}\n".format(args.metadata_name, args.bias_top, args.bias_normal)) if "postset" in args.TODO: get_PostSet(bias_normal=args.bias_normal, bias_top=args.bias_top, metadata_name=args.metadata_name, metadata_path=args.metadata_path, pcounts_name=args.pcounts_name, pcounts_path=args.pcounts_path) if "topclass2Ntopclass" in args.TODO: get_topclass2Ntopclass(bias_normal=args.bias_normal, bias_top=args.bias_top, metadata_name=args.metadata_name, metadata_path=args.metadata_path) if "class2song" in args.TODO: get_class2song(metadata_name=args.metadata_name, metadata_path=args.metadata_path) if "class2vector" in args.TODO: get_class2vector(metadata_name=args.metadata_name, metadata_path=args.metadata_path, Nsongs=args.Nsongs)
[ 11748, 28034, 198, 6738, 28034, 13, 26791, 1330, 1366, 198, 11748, 25064, 198, 6738, 1341, 35720, 13, 26791, 1330, 36273, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 1822, 29572, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 45...
2.54566
2,650
import json from typing import List from LocationObject import LocationObject # add geocoding for each location
[ 11748, 33918, 198, 6738, 19720, 1330, 7343, 198, 6738, 13397, 10267, 1330, 13397, 10267, 198, 198, 2, 751, 4903, 420, 7656, 329, 1123, 4067, 628 ]
4.56
25
#!/usr/bin/env python3 #-*- codin:utf-8 -*- ''' django + celery + redis python manage.py migrate -- looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your mysite/settings.py file and the database migrations shipped with the app python manage.py runserver -- python manage.py startapp app_name -- python manage.py makemigrations app_name -- python manage.py sqlmigrate app_name 0001 -- ''' import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "picha.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 12, 9, 12, 14873, 259, 25, 40477, 12, 23, 532, 9, 12, 198, 7061, 6, 198, 28241, 14208, 1343, 18725, 1924, 1343, 2266, 271, 628, 198, 29412, 6687, 13, 9078, 32492, 1377, 3073...
3.113122
221
import os from datetime import datetime from sqlalchemy.orm import sessionmaker import nfp.servicos.model as tables from nfp import CONEXAO # ---------------- Funes de mdulo ------ def selecionar_ultima_tarefa_remota_finalizada(tarefa_remota_id): ctrl = ControleExecucao() ctrl.table_name = 'tarefas' ctrl.configurar_base_de_dados() return ctrl.selecionar_ultima_tarefa_remota_finalizada(tarefa_remota_id) def get_id_tarefa_remota(tarefa_id): ctrl = ControleExecucao() ctrl.table_name = 'tarefas' ctrl.configurar_base_de_dados() return ctrl.get_id_tarefa_remota(tarefa_id) def get_tarefa(tarefa_id): ctrl = ControleExecucao() ctrl.table_name = 'tarefas' ctrl.configurar_base_de_dados() return ctrl.get_tarefa(tarefa_id) def reativar_tarefa(tarefa_id): ctrl = ControleExecucao() ctrl.table_name = 'tarefas' ctrl.configurar_base_de_dados() return ctrl.reativar_tarefa(tarefa_id) # ---------------------------------------- if __name__ == "__main__": pass
[ 11748, 28686, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 44161, 282, 26599, 13, 579, 1330, 6246, 10297, 198, 11748, 299, 46428, 13, 3168, 291, 418, 13, 19849, 355, 8893, 198, 6738, 299, 46428, 1330, 7102, 6369, 32, 46, 628, 1...
2.275938
453
# -*- coding: utf-8 -*- """ Artifactory repository endpoint """ __copyright__ = "Copyright (C) 2016 Veritas Technologies LLC. All rights reserved." # project imports from ..http import HTTP from .repotype import RepositoryType from .virtual import Virtual from .local import Local from .remote import Remote # define all repo types REPO_TYPE = { "local": Local, "remote": Remote, "virtual": Virtual, }
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 8001, 361, 9548, 16099, 36123, 198, 37811, 198, 834, 22163, 4766, 834, 796, 366, 15269, 357, 34, 8, 1584, 4643, 21416, 21852, 11419, 13, 1439, 2489, 10395, 5...
3.013793
145
"""Adoption application.""" from flask import Flask, request, redirect, render_template from models import db, connect_db, Pets from wtforms import StringField, IntegerField, TextAreaField, BooleanField from wtforms.validators import DataRequired,InputRequired,AnyOf,URL, NumberRange from flask_wtf import FlaskForm from petfunctions import get_random_pet app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///adopt' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_ECHO'] = True connect_db(app) db.create_all() from flask_debugtoolbar import DebugToolbarExtension app.config['SECRET_KEY'] ='SOSECRET' debug=DebugToolbarExtension(app)
[ 37811, 2782, 18076, 3586, 526, 15931, 198, 198, 6738, 42903, 1330, 46947, 11, 2581, 11, 18941, 11, 8543, 62, 28243, 198, 6738, 4981, 1330, 20613, 11, 2018, 62, 9945, 11, 43578, 198, 6738, 266, 83, 23914, 1330, 10903, 15878, 11, 34142, ...
3.084821
224
""" Utilities for (weighted) bootstrap resampling applied to geoscientific point-data. """ import numpy as np import pandas as pd from .meta import subkwargs from .spatial import great_circle_distance, _get_sqare_grid_segment_indicies from .log import Handle logger = Handle(__name__) try: import sklearn HAVE_SKLEARN = True except ImportError: msg = "scikit-learn not installed" logger.warning(msg) HAVE_SKLEARN = False def _segmented_univariate_distance_matrix( A, B, distance_metric, dtype="float32", segs=10 ): """ A method to generate a point-to-point distance matrix in segments to be softer on memory requirements yet retain precision (e.g. beyond a few thousand points). Parameters ----------- A, B : :class:`numpy.ndarray` Numpy arrays with positions of points. distance_metric Callable function f(a, b) from which to derive a distance metric. dtype : :class:`str` | :class:`numpy.dtype` Data type to use for the matrix. segs : :class:`int` Number of segments to split the matrix into (note that this will effectively squared - i.e. 10 -> 100 individual segments). Returns ------- dist : :class:`numpy.ndarray` 2D point-to-point distance matrix. """ max_size = np.max([a.shape[0] for a in [A, B]]) dist = np.zeros((max_size, max_size), dtype=dtype) # full matrix # note that this could be parallelized; the calcuations are independent for ix_s, ix_e, iy_s, iy_e in _get_sqare_grid_segment_indicies(max_size, segs): dist[ix_s:ix_e, iy_s:iy_e] = distance_metric( A[ix_s:ix_e][:, np.newaxis], B[iy_s:iy_e][np.newaxis, :], ) return dist def univariate_distance_matrix(a, b=None, distance_metric=None): """ Get a distance matrix for a single column or array of values (here used for ages). Parameters ----------- a, b : :class:`numpy.ndarray` Points or arrays to calculate distance between. If only one array is specified, a full distance matrix (i.e. calculate a point-to-point distance for every combination of points) will be returned. distance_metric Callable function f(a, b) from which to derive a distance metric. Returns ------- :class:`numpy.ndarray` 2D distance matrix. """ if distance_metric is None: distance_metric = lambda a, b: np.abs(a - b) a = np.atleast_1d(np.array(a).astype(np.float)) full_matrix = False if b is not None: # a second set of points is specified; the return result will be 1D b = np.atleast_1d(np.array(b).astype(np.float)) else: # generate a full point-to-point matrix for a single set of points full_matrix = True b = a.copy() return _segmented_univariate_distance_matrix(a, b, distance_metric) def get_spatiotemporal_resampling_weights( df, spatial_norm=1.8, temporal_norm=38, latlong_names=["Latitude", "Longitude"], age_name="Age", max_memory_fraction=0.25, normalized_weights=True, **kwargs ): """ Takes a dataframe with lat, long and age and returns a sampling weight for each sample which is essentailly the inverse of the mean distance to other samples. Parameters ----------- df : :class:`pandas.DataFrame` Dataframe to calculate weights for. spatial_norm : :class:`float` Normalising constant for spatial measures (1.8 arc degrees). temporal_norm : :class:`float` Normalising constant for temporal measures (38 Mya). latlong_names : :class:`list` List of column names referring to latitude and longitude. age_name : :class:`str` Column name corresponding to geological age or time. max_memory_fraction : :class:`float` Constraint to switch to calculating mean distances where :code:`matrix=True` and the distance matrix requires greater than a specified fraction of total avaialbe physical memory. This is passed on to :func:`~pyrolite.util.spatial.great_circle_distance`. normalized_weights : :class:`bool` Whether to renormalise weights to unity. Returns -------- weights : :class:`numpy.ndarray` Sampling weights. Notes ------ This function is equivalent to Eq(1) from Keller and Schone: .. math:: W_i \\propto 1 \\Big / \\sum_{j=1}^{n} \\Big ( \\frac{1}{((z_i - z_j)/a)^2 + 1} + \\frac{1}{((t_i - t_j)/b)^2 + 1} \\Big ) """ weights = pd.Series(index=df.index, dtype="float") z = great_circle_distance( df[[*latlong_names]], absolute=False, max_memory_fraction=max_memory_fraction, **subkwargs(kwargs, great_circle_distance) ) # angular distances _invnormdistances = np.zeros_like(z) # where the distances are zero, these weights will go to inf # instead we replace with the smallest non-zero distance/largest non-inf # inverse weight norm_inverse_distances = 1.0 / ((z / spatial_norm) ** 2 + 1) norm_inverse_distances[~np.isfinite(norm_inverse_distances)] = 1 _invnormdistances += norm_inverse_distances # ages - might want to split this out as optional for spatial resampling only? t = univariate_distance_matrix(df[age_name]) norm_inverse_time = 1.0 / ((t / temporal_norm) ** 2 + 1) norm_inverse_time[~np.isfinite(norm_inverse_time)] = 1 _invnormdistances += norm_inverse_time weights = 1.0 / np.sum(_invnormdistances, axis=0) if normalized_weights: weights = weights / weights.sum() return weights def add_age_noise( df, min_sigma=50, noise_level=1.0, age_name="Age", age_uncertainty_name="AgeUncertainty", min_age_name="MinAge", max_age_name="MaxAge", ): """ Add gaussian noise to a series of geological ages based on specified uncertainties or age ranges. Parameters ----------- df : :class:`pandas.DataFrame` Dataframe with age data within which to look up the age name and add noise. min_sigma : :class:`float` Minimum uncertainty to be considered for adding age noise. noise_level : :class:`float` Scaling of the noise added to the ages. By default the uncertaines are unscaled, but where age uncertaines are specified and are the one standard deviation level this can be used to expand the range of noise added (e.g. to 2SD). age_name : :class:`str` Column name for absolute ages. age_uncertainty_name : :class:`str` Name of the column specifiying absolute age uncertainties. min_age_name : :class:`str` Name of the column specifying minimum absolute ages (used where uncertainties are otherwise unspecified). max_age_name : :class:`str` Name of the column specifying maximum absolute ages (used where uncertainties are otherwise unspecified). Returns -------- df : :class:`pandas.DataFrame` Dataframe with noise-modified ages. Notes ------ This modifies the dataframe which is input - be aware of this if using outside of the bootstrap resampling for which this was designed. """ # try and get age uncertainty try: age_uncertainty = df[age_uncertainty_name] except KeyError: # otherwise get age min age max # get age uncertainties age_uncertainty = ( np.abs(df[max_age_name] - df[min_age_name]) / 2 ) # half bin width age_uncertainty[ ~np.isfinite(age_uncertainty) | age_uncertainty < min_sigma ] = min_sigma # generate gaussian age noise age_noise = np.random.randn(df.index.size) * age_uncertainty.values age_noise *= noise_level # scale the noise # add noise to ages df[age_name] += age_noise return df def spatiotemporal_bootstrap_resample( df, columns=None, uncert=None, weights=None, niter=100, categories=None, transform=None, boostrap_method="smooth", add_gaussian_age_noise=True, metrics=["mean", "var"], default_uncertainty=0.02, relative_uncertainties=True, noise_level=1, age_name="Age", latlong_names=["Latitude", "Longitude"], **kwargs ): """ Resample and aggregate metrics from a dataframe, optionally aggregating by a given set of categories. Formulated specifically for dealing with resampling to address uneven sampling density in space and particularly geological time. Parameters ----------- df : :class:`pandas.DataFrame` Dataframe to resample. columns : :class:`list` Columns to provide bootstrap resampled estimates for. uncert : :class:`float` | :class:`numpy.ndarray` | :class:`pandas.Series` | :class:`pandas.DataFrame` Fractional uncertainties for the dataset. weights : :class:`numpy.ndarray` | :class:`pandas.Series` Array of weights for resampling, if precomputed. niter : :class:`int` Number of resampling iterations. This will be the minimum index size of the output metric dataframes. categories : :class:`list` | :class:`numpy.ndarray` | :class:`pandas.Series` List of sample categories to group the ouputs by, which has the same size as the dataframe index. transform Callable function to transform input data prior to aggregation functions. Note that the outputs will need to be inverse-transformed. boostrap_method : :class:`str` Which method to use to add gaussian noise to the input dataset parameters. add_gaussian_age_noise : :class:`bool` Whether to add gassian noise to the input dataset ages, where present. metrics : :class:`list` List of metrics to use for dataframe aggregation. default_uncertainty : :class:`float` Default (fractional) uncertainty where uncertainties are not given. relative_uncertainties : :class:`bool` Whether uncertainties are relative (:code:`True`, i.e. fractional proportions of parameter values), or absolute (:code:`False`) noise_level : :class:`float` Multiplier for the random gaussian noise added to the dataset and ages. age_name : :class:`str` Column name for geological age. latlong_names : :class:`list` Column names for latitude and longitude, or equvalent orthogonal spherical spatial measures. Returns -------- :class:`dict` Dictionary of aggregated Dataframe(s) indexed by statistical metrics. If categories are specified, the dataframe(s) will have a hierarchical index of :code:`categories, iteration`. """ # uncertainty managment ############################################################ uncertainty_type = None if uncert is not None: if isinstance(uncert, float): uncertainty_type = "0D" # e.g. 2% elif isinstance(uncert, (list, pd.Series)) or ( isinstance(uncert, np.ndarray) and np.array(uncert).ndim < 2 ): uncertainty_type = "1D" # e.g. [0.5%, 1%, 2%] # shape should be equal to parameter column number elif isinstance(uncert, (pd.DataFrame)) or ( isinstance(uncert, np.ndarray) and np.array(uncert).ndim >= 2 ): uncertainty_type = "2D" # e.g. [[0.5%, 1%, 2%], [1.5%, 0.6%, 1.7%]] # shape should be equal to parameter column number by rows else: raise NotImplementedError("Unknown format for uncertainties.") # weighting ######################################################################## # generate some weights for resampling - here addressing specifically spatial # and temporal resampling if weights is None: weights = get_spatiotemporal_resampling_weights( df, age_name=age_name, latlong_names=latlong_names, **subkwargs(kwargs, get_spatiotemporal_resampling_weights) ) # to efficiently manage categories we can make sure we have an iterable here if categories is not None: if isinstance(categories, (list, tuple, pd.Series, np.ndarray)): pass elif isinstance(categories, str) and categories in df.columns: categories = df[categories] else: msg = "Categories unrecognized" raise NotImplementedError(msg) # column selection ################################################################# # get the subset of parameters to be resampled, removing spatial and age names # and only taking numeric data subset = columns or [ c for c in df.columns if c not in [[i for i in df.columns if age_name in i], *latlong_names] and np.issubdtype(df.dtypes[c], np.number) ] # resampling ####################################################################### metric_data = {_metric_name(metric): [] for metric in metrics} # samples are independent, so this could be processed in parallel for repeat in range(niter): # take a new sample with replacement equal in size to the original dataframe smpl = df.sample(weights=weights, frac=1, replace=True) # whether to specfically add noise to the geological ages # note that the metadata around age names are passed through to this function # TODO: Update to have external disambiguation of ages/min-max ages, # and just pass an age series to this function. if add_gaussian_age_noise: smpl = add_age_noise( smpl, min_sigma=50, age_name=age_name, noise_level=noise_level, **subkwargs(kwargs, add_age_noise) ) # transform the parameters to be estimated before adding parameter noise? if transform is not None: smpl[subset] = smpl[subset].apply(transform, axis="index") # whether to add parameter noise, and if so which method to use? # TODO: Update the naming of this? this is only one part of the bootstrap process if boostrap_method is not None: # try to get uncertainties for the data, otherwise use standard deviations? if boostrap_method.lower() == "smooth": # add random noise within uncertainty bounds # this is essentially smoothing # consider modulating the noise model using the covariance structure? # this could be done by individual group to preserve varying covariances # between groups? if uncert is None: noise = ( smpl[subset].values * default_uncertainty * np.random.randn(*smpl[subset].shape) ) * noise_level else: noise = np.random.randn(*smpl[subset].shape) * noise_level if uncertainty_type in ["0D", "1D"]: # this should work if a float or series is passed noise *= uncert else: # need to get indexes of the sample to look up uncertainties # need to extract indexes for the uncertainties, which might be arrays arr_idxs = df.index.take(smpl.index).values noise *= uncert[arr_idxs, :] if relative_uncertainties: noise *= smpl[subset].values smpl[subset] += noise elif (boostrap_method.upper() == "GP") or ( "process" in bootstrap_method.lower() ): # gaussian process regression to adapt to covariance matrix msg = "Gaussian Process boostrapping not yet implemented." raise NotImplementedError(msg) else: msg = "Bootstrap method {} not recognised.".format(boostrap_method) raise NotImplementedError(msg) # whether to independently estimate metric values for individual categories? # TODO: Should the categories argument be used to generate indiviudal # bootstrap resampling processes? if categories is not None: for metric in metrics: metric_data[_metric_name(metric)].append( smpl[subset].groupby(categories).agg(metric) ) else: # generate the metric summaries for the overall dataset for metric in metrics: metric_data[_metric_name(metric)].append(smpl[subset].agg(metric)) # where the whole dataset is presented if categories is not None: # the dataframe will be indexed by iteration of the bootstrap return { metric: pd.concat(data, keys=range(niter), names=["Iteration"]) .swaplevel(0, 1) .sort_index() for metric, data in metric_data.items() } else: # the dataframe will be indexed by categories and iteration # TODO: add iteration level to this index? return {metric: pd.DataFrame(data) for metric, data in metric_data.items()}
[ 37811, 201, 198, 18274, 2410, 329, 357, 6551, 276, 8, 6297, 26418, 581, 321, 11347, 5625, 284, 4903, 418, 3456, 811, 966, 12, 7890, 13, 201, 198, 37811, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 19798, 292, 355, 279, ...
2.411669
7,353
# TODO: add unit tests for test_nhdplus_utils.py
[ 2, 16926, 46, 25, 751, 4326, 5254, 329, 1332, 62, 77, 31298, 9541, 62, 26791, 13, 9078, 198 ]
2.722222
18
import numpy as np import seaborn as sns import matplotlib.pyplot as plt from task import SequenceLearning sns.set(style='white', palette='colorblind', context='poster') np.random.seed(0) '''how to use''' # init n_param, n_branch = 16, 4 pad_len = 0 n_parts = 2 n_samples = 256 p_rm_ob_enc = 0 p_rm_ob_rcl = 0 n_rm_fixed = False task = SequenceLearning( n_param, n_branch, pad_len=pad_len, p_rm_ob_enc=p_rm_ob_enc, p_rm_ob_rcl=p_rm_ob_rcl, n_rm_fixed=n_rm_fixed, ) # take sample X, Y = task.sample(n_samples, to_torch=False) print(f'X shape = {np.shape(X)}, n_example x time x x-dim') print(f'Y shape = {np.shape(Y)}, n_example x time x y-dim') '''visualize the sample''' # pick a sample i = 0 x, y = X[i], Y[i] cmap = 'bone' x_split = np.split(x, (n_param, n_param + n_branch), axis=1) mat_list = x_split + [y] f, axes = plt.subplots( 2, 4, figsize=(14, 11), sharey=True, gridspec_kw={ 'width_ratios': [n_param, n_branch, n_param, n_branch], 'height_ratios': [n_param, n_param] }, ) title_list = ['Observed feature', 'Observed value', 'Queried feature', 'Queried value'] ylabel_list = ['Part one', 'Part two'] for i, mat in enumerate(mat_list): [mat_p1, mat_p2] = np.split(mat, [n_param], axis=0) axes[0, i].imshow(mat[:n_param, :], cmap=cmap) axes[1, i].imshow(mat[n_param:, :], cmap=cmap) axes[0, i].set_title(title_list[i], fontname='Helvetica') axes[0, i].set_xticks([]) for i in [1, 3]: axes[1, i].set_xticks(range(n_branch)) axes[1, i].set_xticklabels(i for i in np.arange(4) + 1) for i in range(2): axes[i, 0].set_yticks(np.arange(0, n_param, 5)) axes[i, 0].set_ylabel(ylabel_list[i], fontname='Helvetica') f.tight_layout() f.savefig(f'examples/figs/stimulus-rep.png', dpi=100, bbox_inches='tight')
[ 11748, 299, 32152, 355, 45941, 198, 11748, 384, 397, 1211, 355, 3013, 82, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 4876, 1330, 45835, 41730, 198, 82, 5907, 13, 2617, 7, 7635, 11639, 11186, 3256, 27043, ...
2.128235
850
""" Custom exceptions """ from __future__ import annotations __all__ = [ "AlreadyRegistered", "ConsumerError", "EventBusError", "UnknownEvent", ]
[ 37811, 198, 15022, 13269, 198, 37811, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 834, 439, 834, 796, 685, 198, 220, 220, 220, 366, 37447, 47473, 1600, 198, 220, 220, 220, 366, 49106, 12331, 1600, 198, 220, 220, 220, 366, 923...
2.896552
58
from sparse_ct.tool import plot_grid from sparse_ct.data import image_to_sparse_sinogram from sparse_ct.reconstructor_2d import ( IRadonReconstructor, SartReconstructor, SartTVReconstructor, DgrReconstructor, SartBM3DReconstructor) import logging logging.basicConfig( filename='dgr_example_32_35.log', filemode='a', format='%(asctime)s - %(levelname)s - %(message)s', level=logging.DEBUG ) if __name__ == "__main__": # test("../data/shepp_logan.jpg", "shepp_logan_32_35", n_proj=32, noise_pow=35.0) test("../data/ct2.jpg", "ct2_32_35", n_proj=32, noise_pow=35.0) test("../data/ct1.jpg", "ct1_32_35", n_proj=32, noise_pow=35.0) test("../data/LoDoPaB/004013_02_01_119.png", "LoDoPaB1_32_35", n_proj=32, noise_pow=35.0) test("../data/LoDoPaB/004017_01_01_151.png", "LoDoPaB2_32_35", n_proj=32, noise_pow=35.0) test("../data/LoDoPaB/004028_01_04_109.png", "LoDoPaB3_32_35", n_proj=32, noise_pow=35.0) test("../data/LoDoPaB/004043_01_01_169.png", "LoDoPaB4_32_35", n_proj=32, noise_pow=35.0) test("../data/LoDoPaB/004049_04_01_062.png", "LoDoPaB5_32_35", n_proj=32, noise_pow=35.0)
[ 198, 6738, 29877, 62, 310, 13, 25981, 1330, 7110, 62, 25928, 198, 6738, 29877, 62, 310, 13, 7890, 1330, 2939, 62, 1462, 62, 82, 29572, 62, 31369, 21857, 198, 6738, 29877, 62, 310, 13, 260, 41571, 273, 62, 17, 67, 1330, 357, 198, 2...
1.972789
588
from pathlib import Path from typing import Optional from starlette.config import Config from starlette.datastructures import CommaSeparatedStrings from ..models.pydantic.database import DatabaseURL p: Path = Path(__file__).parents[2] / ".env" config: Config = Config(p if p.exists() else None) DATABASE: str = config("POSTGRES_DB", cast=str) DB_USER: Optional[str] = config("POSTGRES_USER", cast=str, default=None) DB_PASSWORD: Optional[str] = config( "POSTGRES_PASSWORD", cast=str, default=None ) DB_HOST: str = config("DB_HOST", cast=str, default="postgres_db") DB_PORT: int = config("DB_PORT", cast=int, default=5432) DATABASE_CONFIG: DatabaseURL = DatabaseURL( drivername="asyncpg", username=DB_USER, password=DB_PASSWORD, host=DB_HOST, port=DB_PORT, database=DATABASE, ) ALEMBIC_CONFIG: DatabaseURL = DatabaseURL( drivername="postgresql+psycopg2", username=DB_USER, password=DB_PASSWORD, host=DB_HOST, port=DB_PORT, database=DATABASE, ) REDIS_IP: str = config("REDIS_IP", cast=str, default="redis") REDIS_PORT: int = config("REDIS_PORT", cast=int, default=6379) REDIS_PASSWORD: str = config("REDIS_PASSWORD", cast=str, default=None) ARQ_BACKGROUND_FUNCTIONS: Optional[CommaSeparatedStrings] = config( "ARQ_BACKGROUND_FUNCTIONS", cast=CommaSeparatedStrings, default=None )
[ 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 32233, 198, 198, 6738, 3491, 21348, 13, 11250, 1330, 17056, 198, 6738, 3491, 21348, 13, 19608, 459, 1356, 942, 1330, 1520, 64, 19117, 283, 515, 13290, 654, 198, 198, 6738, 11485, 27...
2.571977
521
fruit = str(input()) day_of_the_week = str(input()) quantity = float(input()) price = 0 if fruit == 'banana' or \ fruit == 'apple' or \ fruit == 'orange' or \ fruit == 'grapefruit' or \ fruit == 'kiwi' or \ fruit == 'pineapple' or \ fruit == 'grapes': if day_of_the_week == 'Monday' or day_of_the_week == 'Tuesday' or \ day_of_the_week == 'Wednesday' or \ day_of_the_week == 'Thursday' or \ day_of_the_week == 'Friday': if fruit == 'banana': price = 2.50 elif fruit == 'apple': price = 1.20 elif fruit == 'orange': price = 0.85 elif fruit == 'grapefruit': price = 1.45 elif fruit == 'kiwi': price = 2.70 elif fruit == 'pineapple': price = 5.50 elif fruit == 'grapes': price = 3.85 total_price = quantity * price print(f'{total_price:.2f}') elif day_of_the_week == 'Saturday' or day_of_the_week == 'Sunday': if fruit == 'banana': price = 2.70 elif fruit == 'apple': price = 1.25 elif fruit == 'orange': price = 0.90 elif fruit == 'grapefruit': price = 1.60 elif fruit == 'kiwi': price = 3 elif fruit == 'pineapple': price = 5.60 elif fruit == 'grapes': price = 4.20 total_price = quantity * price print(f'{total_price:.2f}') else: print('error') else: print('error')
[ 34711, 796, 965, 7, 15414, 28955, 198, 820, 62, 1659, 62, 1169, 62, 10464, 796, 965, 7, 15414, 28955, 198, 40972, 414, 796, 12178, 7, 15414, 28955, 198, 20888, 796, 657, 198, 198, 361, 8234, 6624, 705, 3820, 2271, 6, 393, 3467, 198,...
1.933815
831
import unittest from trajectories.dynamic_time_warper import * from trajectories.trajectory import Trajectory from trajectories.point import Point if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 6738, 20134, 1749, 13, 67, 28995, 62, 2435, 62, 5767, 525, 1330, 1635, 198, 6738, 20134, 1749, 13, 9535, 752, 652, 1330, 4759, 752, 652, 198, 6738, 20134, 1749, 13, 4122, 1330, 6252, 198, 198, 361, 11593, ...
3.196721
61
while True: h1,m1,h2,m2=map(int,input().split()) i=f=0 if m1+m2+h1+h2==0:break if h1==0:i=(24*60)+m1 else:i=(h1*60)+m1 if h2==0:f=(24*60)+m2 else:f=(h2*60)+m2 print(f-i) if f>i else print((24*60)-(i-f))
[ 4514, 6407, 25, 198, 220, 220, 220, 289, 16, 11, 76, 16, 11, 71, 17, 11, 76, 17, 28, 8899, 7, 600, 11, 15414, 22446, 35312, 28955, 198, 220, 220, 220, 1312, 28, 69, 28, 15, 198, 220, 220, 220, 611, 285, 16, 10, 76, 17, 10, ...
1.577181
149
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.db.models import Count from django.template import RequestContext from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponseRedirect from .models import * from .forms import * import os from django.http import HttpResponse from portfolio_pj import settings # Create your views here. # Private Methods
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 42625, 14208, 13, 7295, 13, 79, 363, 2...
3.358974
156
import datetime from ..databases.postgresql import session from ..models.bookmark_model import Bookmark # Select one # Insert # Update # Count by post id
[ 11748, 4818, 8079, 198, 6738, 11485, 19608, 18826, 13, 7353, 34239, 13976, 1330, 6246, 198, 6738, 11485, 27530, 13, 2070, 4102, 62, 19849, 1330, 4897, 4102, 198, 198, 2, 9683, 530, 198, 198, 2, 35835, 198, 220, 220, 220, 220, 198, 2, ...
3.176471
51
#!/usr/bin/python3 # # User management application # """ pythoncgi 1. (get) 2. (post) 3. (post) 4. (post) 1. REQUEST_METHOD getpost 2. QUERY_STRING 3. subprocess.getoutput, os.system shell 4. grep ^root /etc/passwd useradd user-name usermod user-name userdel user-name """ import os import sys import subprocess as sub def read_user_info(name): """ /etc/passwd """ db = '/etc/passwd' info = [line.split(':') for line in open(db).read().splitlines()] user_info = [i for i in info if i[0] == name] if not user_info: # return user_info = user_info[0] colnames = ('name', 'password', 'uid', 'gid', 'comment', 'home', 'shell') return dict(zip(colnames, user_info)) if __name__ == '__main__': headers = [] headers.append('Content-Type: text/plain') if os.getenv('REQUEST_METHOD') == 'GET': params = os.getenv('QUERY_STRING', '') get_user_info(params, headers) elif os.getenv('REQUEST_METHOD') == 'POST': alter_user(headers) else: headers.append('Status: 405 METHOD_NOT_ALLOWED') response(headers, [])
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 2, 198, 2, 11787, 4542, 3586, 198, 2, 198, 198, 37811, 198, 29412, 37157, 628, 220, 220, 220, 352, 13, 220, 357, 1136, 8, 198, 220, 220, 220, 362, 13, 220, 357, 7353, 8, 198, 220, ...
2.266284
522
bl_info = { "name": "Universal Exporter", "category": "Import & Export", } import bpy if __name__ == "__main__": register()
[ 2436, 62, 10951, 796, 1391, 198, 220, 220, 220, 366, 3672, 1298, 366, 38747, 1475, 26634, 1600, 198, 220, 220, 220, 366, 22872, 1298, 366, 20939, 1222, 36472, 1600, 198, 92, 198, 198, 11748, 275, 9078, 628, 628, 198, 361, 11593, 3672,...
2.517857
56
import random # Parameters states_num: int = 900 trans_per_state: int = 3 transitions_num: int = trans_per_state * states_num num_non_zero_start_probs: int = 2 emit_range: int = 20 file_name: str = "random_" + \ str(states_num) + "_" + str(transitions_num) + "_" + \ str(emit_range) + "_" + str(num_non_zero_start_probs) + ".chmm" # Implicit parameter for probabilities generation rng_range: int = 100 # Generation with open(file_name, 'w') as f: f.write(str(states_num) + '\n') # Start probabilities pairs info start_probs: list = generate_probability_list(num_non_zero_start_probs) f.write(str(num_non_zero_start_probs) + '\n') for i in range(num_non_zero_start_probs): f.write(str(i) + ' ' + start_probs[i] + '\n') # Emissions probabilities for each state f.write(str(emit_range) + '\n') for _ in range(states_num): emit_probs: list = generate_probability_list(emit_range) emit_str: str = ' '.join(emit_probs) + '\n' f.write(emit_str) # Transitions info f.write(str(transitions_num) + '\n') for src in range(states_num): used_dst: list = [] for _ in range(trans_per_state): dst: int = random.randrange(states_num) while (dst in used_dst): dst = random.randrange(states_num) used_dst.append(dst) trans_probs: list = generate_probability_list(trans_per_state) for i in range(trans_per_state): f.write(str(src) + ' ' + str(used_dst[i]) + ' ' + trans_probs[i] + '\n')
[ 11748, 4738, 198, 198, 2, 40117, 198, 27219, 62, 22510, 25, 493, 796, 15897, 198, 7645, 62, 525, 62, 5219, 25, 493, 796, 513, 198, 7645, 1756, 62, 22510, 25, 493, 796, 1007, 62, 525, 62, 5219, 1635, 2585, 62, 22510, 198, 22510, 62...
2.194715
719
# Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. # # This is case sensitive, for example "Aa" is not considered a palindrome here. # # Note: # Assume the length of given string will not exceed 1,010. # # # Example: # # Input: # "abccccdd" # # Output: # 7 # # Explanation: # One longest palindrome that can be built is "dccaccd", whose length is 7. # # # # @lc app=leetcode id=409 lang=python3 # # [409] Longest Palindrome # # https://leetcode.com/problems/longest-palindrome/description/ # # algorithms # Easy (48.27%) # Likes: 547 # Dislikes: 56 # Total Accepted: 100.6K # Total Submissions: 208.5K # Testcase Example: '"abccccdd"' # # Given a string which consists of lowercase or uppercase letters, find the # length of the longest palindromes that can be built with those letters. # # This is case sensitive, for example "Aa" is not considered a palindrome # here. # # Note: # Assume the length of given string will not exceed 1,010. # # # Example: # # Input: # "abccccdd" # # Output: # 7 # # Explanation: # One longest palindrome that can be built is "dccaccd", whose length is 7. # # #
[ 2, 11259, 257, 4731, 543, 10874, 286, 2793, 7442, 393, 334, 39921, 589, 7475, 11, 1064, 262, 4129, 286, 262, 14069, 6340, 521, 398, 274, 326, 460, 307, 3170, 351, 883, 7475, 13, 201, 198, 2, 198, 2, 770, 318, 1339, 8564, 11, 329, ...
2.810185
432
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
3.888889
9
import socketio import socketio sio = socketio.Client() sio.connect('http://localhost:5000') sio.wait()
[ 11748, 17802, 952, 201, 198, 201, 198, 11748, 17802, 952, 201, 198, 201, 198, 82, 952, 796, 17802, 952, 13, 11792, 3419, 201, 198, 201, 198, 82, 952, 13, 8443, 10786, 4023, 1378, 36750, 25, 27641, 11537, 201, 198, 82, 952, 13, 17077...
2.5
46
import requests import requests_cache requests_cache.install_cache() from ricecooker.config import LOGGER STUDIO_URL = 'https://studio.learningequality.org' NODES_ENDPOINT = STUDIO_URL + '/api/get_nodes_by_ids_complete/' LICENSES_LIST_ENDPOINT = STUDIO_URL + '/api/license' # TODO https://studio.learningequality.org/api/get_node_path/ca8f380/18932/41b2549 # TODO http://develop.studio.learningequality.org/api/channel/094097ce6f395ec0b50aabd04943c6b3
[ 11748, 7007, 198, 11748, 7007, 62, 23870, 198, 8897, 3558, 62, 23870, 13, 17350, 62, 23870, 3419, 198, 198, 6738, 11464, 27916, 263, 13, 11250, 1330, 41605, 30373, 628, 198, 2257, 8322, 9399, 62, 21886, 796, 705, 5450, 1378, 19149, 952,...
2.505376
186
# Supostamente no funciona from aresta import Aresta from insert import insert_sort from collections import defaultdict if __name__ == "__main__": arestas = list() # arestas.append(Aresta(1, 'a', 'b')) # arestas.append(Aresta(8, 'a', 'c')) # arestas.append(Aresta(3, 'c', 'b')) # arestas.append(Aresta(4, 'b', 'd')) # arestas.append(Aresta(2, 'd', 'e')) # arestas.append(Aresta(3, 'b', 'e')) # arestas.append(Aresta(-1, 'c', 'd')) # arestas.append(Aresta(13, '0', '3')) # arestas.append(Aresta(24, '0', '1')) # arestas.append(Aresta(13, '0', '2')) # arestas.append(Aresta(22, '0', '4')) # arestas.append(Aresta(13, '1', '3')) # arestas.append(Aresta(22, '1', '2')) # arestas.append(Aresta(13, '1', '4')) # arestas.append(Aresta(19, '2', '3')) # arestas.append(Aresta(14, '2', '4')) # arestas.append(Aresta(19, '3', '4')) arestas.append(Aresta(2, "0", "1")) arestas.append(Aresta(-10, "0", "3")) arestas.append(Aresta(3, "0", "2")) arestas.append(Aresta(5, "1", "2")) arestas.append(Aresta(0, "1", "3")) arestas.append(Aresta(4, "2", "3")) grafo = kruskal(arestas) print("Imprimindo rvore geradora mnima:") for aresta in grafo: print(f"Peso {aresta.peso:2}: {aresta.first:1} para {aresta.second:2}")
[ 2, 5200, 455, 3263, 68, 645, 25439, 32792, 198, 198, 6738, 389, 38031, 1330, 317, 2118, 64, 198, 6738, 7550, 1330, 7550, 62, 30619, 198, 6738, 17268, 1330, 4277, 11600, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298...
1.93695
682
# coding: utf-8 import sys __author__ = "Paulo Srgio dos Santos Araujo" __license__ = "MIT" __version__ = "1.0.0" __email__ = "paulo.araujo [at] splab.ufcg.edu.br" if __name__ == "__main__": msn = Msn(eq="-x**2 + 3", tol=0.01, alg="false_position") msn.findRoots(-2, 3) # -1.7320508075688774 e 1.7320508075688776 msn2 = Msn(eq="-x**2 + 3", tol=0.01, alg="bisection") msn2.findRoots(-2, 3) # -1.736328125 e 1.740234375
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 11748, 25064, 198, 198, 834, 9800, 834, 796, 366, 12041, 78, 21714, 27769, 23430, 28458, 30574, 84, 7639, 1, 198, 834, 43085, 834, 796, 366, 36393, 1, 198, 834, 9641, 834, 796, 366, 16, 13, 15,...
1.995434
219
""" Project: Data Types Notes Author: Mr. Buckley Last update: 8/25/2018 Description: Goes over comments, int, float, str, and type casting """ # *** COMMENTS *** # This is a comment (with a "#") # Comments are only for the user's eyes, the program doesn't read them. # Describe what sections of code do with a comment. """ This is a multiline comment """ # *** DATA TYPE: INTEGER *** # TODO: An integer number (no decimal) integer = 5 print (integer) print (type(integer)) # *** DATA TYPE: FLOAT *** # TODO: A decimal number decimal = 4.85 print (decimal) print (type(decimal)) # *** DATA TYPE: STRING *** # TODO: A string of characters enclosed in quotes word = "these are my words" print (word) print (type(word)) # *** TYPE CASTING *** # This converts one type to another # TODO: Cast float to int decimal = 55.55 dec_to_int = int(decimal) print(dec_to_int) # TODO: Cast int to string number = "8" print (int(number)+2) # TODO: Cast number string to int print ("give me add I'll add 1 to it") number = float (input()) print (number + 1) # TODO: Input demo (str to float)
[ 37811, 198, 16775, 25, 220, 220, 220, 220, 6060, 24897, 11822, 198, 13838, 25, 220, 220, 220, 220, 220, 1770, 13, 41493, 198, 5956, 4296, 25, 807, 14, 1495, 14, 7908, 198, 11828, 25, 31914, 625, 3651, 11, 493, 11, 12178, 11, 965, ...
2.986376
367
import os import zarr import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from torch.utils.data import Dataset from tqdm import tqdm, trange def main(batch_size=64, epochs=50): data_train = FaceDataset('data/anime_faces/train.lmdb') device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') loader = DataLoader(data_train, batch_size=batch_size, num_workers=10) model = Model() model.to(device) model.train() optim = torch.optim.Adam(model.parameters(), lr=0.001) for epoch in trange(epochs): t = tqdm(loader) for i, (images, labels) in enumerate(t): images = images.to(device) labels = labels.to(device) optim.zero_grad() logits = model(images) loss = model.criteria(logits, labels) loss.backward() optim.step() predicts = torch.argmax(F.softmax(logits, dim=1), dim=1) accuracy = (predicts == labels).to(torch.float32).mean() t.set_postfix( epoch=epoch, i=i, loss=loss.item(), accuracy=accuracy.item()) data_val = FaceDataset('data/anime_faces/val.lmdb') val_loader = DataLoader(data_val, batch_size=batch_size, num_workers=0) total = len(data_val) total_correct = 0 model.eval() for images, labels in val_loader: images = images.to(device) labels = labels.to(device) logits = model(images) predicts = torch.argmax(F.softmax(logits, dim=1), dim=1) correct = (predicts == labels).sum() total_correct += correct.item() print('Val accuracy = {}'.format(total_correct / total)) if __name__ == '__main__': main()
[ 11748, 28686, 198, 198, 11748, 1976, 3258, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 6060, 17401, 198, 6738, 28034, 13,...
2.2979
762
import os import scrapy from pepper.items import PepperItem
[ 11748, 28686, 198, 198, 11748, 15881, 88, 198, 198, 6738, 13385, 13, 23814, 1330, 24346, 7449, 628 ]
3.705882
17
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from django.test import TestCase from django.test.client import Client from django.test.utils import override_settings import simplejson as json from spotseeker_server.models import Spot, SpotExtendedInfo from spotseeker_server.org_filters import SearchFilterChain def spot_with_noise_level(name, noise_level): """Create a spot with the given noise level""" spot = Spot.objects.create(name=name) spot.spotextendedinfo_set.create(key='noise_level', value=noise_level) return spot
[ 2, 15069, 33448, 33436, 12, 2043, 11, 2059, 286, 2669, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 198, 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 6738, 42625, 14208, 13, 9288, 13, 16366...
2.870968
217
__all__ = ["des"]
[ 834, 439, 834, 796, 14631, 8906, 8973 ]
2.428571
7
from spotdl.metadata.providers.spotify import ProviderSpotify from spotdl.metadata.providers.youtube import ProviderYouTube from spotdl.metadata.providers.youtube import YouTubeSearch
[ 6738, 4136, 25404, 13, 38993, 13, 15234, 4157, 13, 20485, 1958, 1330, 32549, 32565, 1958, 198, 6738, 4136, 25404, 13, 38993, 13, 15234, 4157, 13, 11604, 1330, 32549, 33869, 198, 6738, 4136, 25404, 13, 38993, 13, 15234, 4157, 13, 11604, ...
4.204545
44
from math import floor first_num = Integer(10) second_num = Integer.from_roman("IV") print(Integer.from_float("2.6")) print(Integer.from_string(2.6)) print(first_num.add(second_num))
[ 6738, 10688, 1330, 4314, 628, 198, 198, 11085, 62, 22510, 796, 34142, 7, 940, 8, 198, 12227, 62, 22510, 796, 34142, 13, 6738, 62, 47119, 7203, 3824, 4943, 198, 198, 4798, 7, 46541, 13, 6738, 62, 22468, 7203, 17, 13, 21, 48774, 198, ...
2.710145
69
import datetime from typing import Optional from pydantic import BaseModel
[ 11748, 4818, 8079, 198, 6738, 19720, 1330, 32233, 198, 198, 6738, 279, 5173, 5109, 1330, 7308, 17633, 628, 628, 198 ]
4
20
import json from urllib.request import urlopen import requests from bs4 import BeautifulSoup
[ 198, 11748, 33918, 198, 6738, 2956, 297, 571, 13, 25927, 1330, 19016, 9654, 198, 11748, 7007, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 628, 628 ]
3.592593
27
# -*- coding: utf-8 -*- # # Copyright (c) 2017~2999 - cologler <skyoflw@gmail.com> # ---------- # # ---------- from .common import LifeTime, IServiceProvider, ICallSiteResolver from .descriptors import CallableDescriptor
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 357, 66, 8, 2177, 93, 1959, 2079, 532, 269, 928, 1754, 1279, 15688, 1659, 75, 86, 31, 14816, 13, 785, 29, 198, 2, 24200, 438, 198, 2, 198, 2, 2...
2.740741
81
from joblib import Memory cachedir = "cache" memory = Memory(cachedir, verbose=10) # @memory.cache
[ 6738, 1693, 8019, 1330, 14059, 198, 198, 66, 2317, 343, 796, 366, 23870, 1, 198, 31673, 796, 14059, 7, 66, 2317, 343, 11, 15942, 577, 28, 940, 8, 628, 198, 198, 2, 2488, 31673, 13, 23870 ]
2.833333
36
import sys import helpers.printer import helpers.parser import helpers.config import program.obfuscation import program.bypass modes = helpers.config.Modes bypass_methods = helpers.config.BypassMethods obfuscation_methods = helpers.config.ObfuscationMethods printer = helpers.printer.Printer() parser = helpers.parser.Parser( printer, modes, bypass_methods, obfuscation_methods) bypass = program.bypass.Bypass() obfuscation = program.obfuscation.Obfuscation() if __name__ == "__main__": main()
[ 11748, 25064, 198, 11748, 49385, 13, 1050, 3849, 198, 11748, 49385, 13, 48610, 198, 11748, 49385, 13, 11250, 198, 11748, 1430, 13, 672, 37695, 341, 198, 11748, 1430, 13, 1525, 6603, 198, 198, 76, 4147, 796, 49385, 13, 11250, 13, 44, 4...
3.161491
161
import torch import torchvision import torchvision.transforms as transforms from torch.utils.data.sampler import SubsetRandomSampler from torch.utils.data import DataLoader import os path = os.path.abspath(__file__) dir_path = os.path.dirname(path) resnet_18_default = 224
[ 11748, 28034, 198, 11748, 28034, 10178, 198, 11748, 28034, 10178, 13, 7645, 23914, 355, 31408, 198, 6738, 28034, 13, 26791, 13, 7890, 13, 37687, 20053, 1330, 3834, 2617, 29531, 16305, 20053, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 60...
3.031915
94
from scipy import io import numpy as np import random import tensorflow as tf class_num = 10 image_size = 32 img_channels = 3
[ 6738, 629, 541, 88, 1330, 33245, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 4738, 198, 11748, 11192, 273, 11125, 355, 48700, 628, 198, 4871, 62, 22510, 796, 838, 198, 9060, 62, 7857, 796, 3933, 198, 9600, 62, 354, 8961, 796, 513,...
2.933333
45
""" User models module """ from sqlalchemy import Column, Integer, String from app.models import Base
[ 37811, 198, 12982, 4981, 8265, 198, 37811, 198, 198, 6738, 44161, 282, 26599, 1330, 29201, 11, 34142, 11, 10903, 198, 198, 6738, 598, 13, 27530, 1330, 7308, 628 ]
3.75
28
from pathlib import Path from fhir.resources.valueset import ValueSet as _ValueSet from oops_fhir.utils import ValueSet from oops_fhir.r4.code_system.v3_role_code import v3RoleCode __all__ = ["ParentRelationshipCodes"] _resource = _ValueSet.parse_file(Path(__file__).with_suffix(".json"))
[ 6738, 3108, 8019, 1330, 10644, 198, 198, 6738, 277, 71, 343, 13, 37540, 13, 27160, 316, 1330, 11052, 7248, 355, 4808, 11395, 7248, 198, 198, 6738, 267, 2840, 62, 69, 71, 343, 13, 26791, 1330, 11052, 7248, 628, 198, 6738, 267, 2840, ...
2.801887
106
counter = 0 interpolations = None padding = None
[ 24588, 796, 657, 198, 3849, 16104, 602, 796, 6045, 198, 39231, 796, 6045, 628 ]
3.571429
14
"""Code related to ``django-plugins``. First, it creates a ``ProjectAppPluginPoint`` for the ``bgjobs`` app. Second, it creates a new plugin point for the registering ``BackgroundJob`` specializations. """ from djangoplugins.point import PluginPoint from projectroles.plugins import ProjectAppPluginPoint from .urls import urlpatterns
[ 37811, 10669, 3519, 284, 7559, 28241, 14208, 12, 37390, 15506, 13, 198, 198, 5962, 11, 340, 8075, 257, 7559, 16775, 4677, 37233, 12727, 15506, 329, 262, 7559, 35904, 43863, 15506, 598, 13, 198, 198, 12211, 11, 340, 8075, 257, 649, 13877...
3.706522
92
import discord as nextcord import asyncio from discord.ext import commands import json import time import typing
[ 11748, 36446, 355, 1306, 66, 585, 201, 198, 11748, 30351, 952, 201, 198, 6738, 36446, 13, 2302, 1330, 9729, 201, 198, 11748, 33918, 201, 198, 11748, 640, 201, 198, 11748, 19720, 201, 198 ]
3.606061
33
# Adam # A program that reads in a text # file and outputs the number of e's it contains # The program takes the filename from # an argument on the command line. # I found information on this website: # https://www.sanfoundry.com/python-program-read-file-counts-number/ #fname = input("Enter file name: ") #l = input("Enter letter to be searched: ") #e = 0 #with open(fname, "r") as f: #for line in f: #words = line.split() #for i in words: #for letter in i: #if(letter == e): #e = e+1 #print("Occurences of the letter: ") #print(e) # Requirement for this assignmnet is to only print # The occurence of letter E. fname = input("Enter file name: ") e = 0 with open(fname, "r") as f: for line in f: words = line.split() for i in words: for letter in i: if(letter == "e"): e = e+1 print(e)
[ 2, 7244, 198, 2, 317, 1430, 326, 9743, 287, 257, 2420, 198, 2, 220, 2393, 290, 23862, 262, 1271, 286, 304, 338, 340, 4909, 198, 2, 383, 1430, 2753, 262, 29472, 422, 220, 198, 2, 281, 4578, 319, 262, 3141, 1627, 13, 198, 2, 314, ...
2.186788
439
""" Tests for tinypages build using sphinx extensions """ from os.path import (join as pjoin, dirname, isdir) import sphinx SPHINX_ge_1p5 = sphinx.version_info[:2] >= (1, 5) from sphinxtesters import PageBuilder HERE = dirname(__file__) PAGES = pjoin(HERE, 'tinypages') from texext.tests.test_plotdirective import format_math_block
[ 37811, 30307, 329, 7009, 31126, 1382, 1262, 599, 20079, 87, 18366, 37227, 198, 198, 6738, 28686, 13, 6978, 1330, 357, 22179, 355, 279, 22179, 11, 26672, 3672, 11, 318, 15908, 8, 198, 198, 11748, 599, 20079, 87, 198, 4303, 39, 1268, 55...
2.756098
123
import logging from django.core.exceptions import ObjectDoesNotExist from django.db import transaction from django.http import HttpRequest from rest_framework.exceptions import NotFound from rest_framework.test import APIRequestFactory from rest_framework.views import exception_handler, APIView from typing import List, TypeVar logger = logging.getLogger(__name__) T = TypeVar('T') NON_CLONEABLE_MODELS: List[str] = [ 'User', ] def exception_logging_handler(exc: Exception, context: dict): """ Intercept DRF error handler to log the error message Update the REST_FRAMEWORK setting in settings.py to use this handler REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'core.exception_logging_handler', } """ logger.warning(exc) # translate uncaught Django ObjectDoesNotExist exception to NotFound if isinstance(exc, ObjectDoesNotExist): logger.error(f'uncaught ObjectDoesNotExist error: {exc} - {context}') exc = NotFound(str(exc)) # follow DRF default exception handler response = exception_handler(exc, context) return response def make_drf_request(request: HttpRequest = None, headers: dict = None): """ The request object made by APIRequestFactory is `WSGIRequest` which doesn't have `.query_params` or `.data` method as recommended by DRF. It only gets "upgraded" to DRF `Request` class after passing through the `APIView`, which invokes `.initialize_request` internally. This helper method uses a dummy API view to return a DRF `Request` object for testing purpose. Ref: https://stackoverflow.com/questions/28421797/django-rest-framework-apirequestfactory-request-object-has-no-attribute-query-p https://github.com/encode/django-rest-framework/issues/3608 """ if request is None: # use a default request request = APIRequestFactory().get('/') drf_request = DummyView().initialize_request(request) if headers: drf_request.headers = headers return drf_request
[ 11748, 18931, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 9515, 13921, 3673, 3109, 396, 198, 6738, 42625, 14208, 13, 9945, 1330, 8611, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 18453, 198, 6738, 1334, 62, 30604, ...
2.979472
682
S = input() arr = [] now = [] counter = 0 for s in S: now.append(s.lower()) if s.isupper(): if counter == 0: counter += 1 else: arr.append(''.join(now)) now = [] counter = 0 arr.sort() for word in arr: for i, s in enumerate(word): if i == 0 or i == len(word) - 1: print(s.upper(), end='') else: print(s, end='') print()
[ 50, 796, 5128, 3419, 198, 3258, 796, 17635, 198, 2197, 796, 17635, 198, 24588, 796, 657, 198, 1640, 264, 287, 311, 25, 198, 220, 220, 220, 783, 13, 33295, 7, 82, 13, 21037, 28955, 198, 220, 220, 220, 611, 264, 13, 271, 45828, 3352...
1.847458
236
from lesson12_projects.house3.data.const import E_TURNED_KNOB, MSG_TURN_KNOB, E_FAILED
[ 6738, 11483, 1065, 62, 42068, 13, 4803, 18, 13, 7890, 13, 9979, 1330, 412, 62, 51, 27064, 1961, 62, 29132, 9864, 11, 49064, 62, 51, 27064, 62, 29132, 9864, 11, 412, 62, 7708, 4146, 1961, 628 ]
2.444444
36
# -*- coding: utf-8 -*- """setup.py""" import os import sys from setuptools import setup from setuptools.command.test import test as TestCommand classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", ] long_description = ( read_content("README.rst") + read_content(os.path.join("docs/source", "CHANGELOG.rst"))) requires = ['setuptools', 'typeguard==2.5.0', 'pyspark==3.0.1', 'findspark'] extras_require = { 'reST': ['Sphinx'], } if os.environ.get('READTHEDOCS', None): extras_require['reST'].append('recommonmark') setup(name='pysequila', version=os.getenv('VERSION', '0.1.0'), description='An SQL-based solution for large-scale genomic analysis', long_description=long_description, long_description_content_type='text/x-rst', author='biodatageeks', author_email='team@biodatageeks.org', url='https://pysequila.biodatageeks.org', classifiers=classifiers, packages=['pysequila'], data_files=[], install_requires=requires, include_package_data=True, extras_require=extras_require, tests_require=['tox'], cmdclass={'test': Tox},)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 40406, 13, 9078, 37811, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 6738, 900, 37623, 10141, 1330, 9058, 198, 6738, 900, 37623, 10141, 13, 21812, 13, 9288, 1330...
2.64903
567
from sys import stdin, stdout from struct import pack, unpack def blob_vertex_write(attrs, verts, out=stdout, little_endian = True): for blob in blob_vertices(attrs, verts, little_endian): out.write(blob)
[ 6738, 25064, 1330, 14367, 259, 11, 14367, 448, 198, 6738, 2878, 1330, 2353, 11, 555, 8002, 198, 198, 4299, 44812, 62, 332, 16886, 62, 13564, 7, 1078, 3808, 11, 3326, 912, 11, 503, 28, 19282, 448, 11, 1310, 62, 437, 666, 796, 6407, ...
2.626506
83
from config import * from template import * from dictasobject import DictAsObject
[ 6738, 4566, 1330, 1635, 198, 6738, 11055, 1330, 1635, 198, 6738, 8633, 292, 15252, 1330, 360, 713, 1722, 10267, 198 ]
4.1
20
import os import torch import torch.nn as nn import torch.optim as optim from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm import matplotlib.pyplot as plt import architecture.default from architecture.default import Defender DEBUG=False BATCH_SIZE=32 FIXED_POLICY=False NORMALIZE=False K=10 PENALTY=10 MAX_TARGET_POS=10 torch.set_default_tensor_type(torch.DoubleTensor)
[ 11748, 28686, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 40085, 355, 6436, 198, 6738, 28034, 13, 26791, 13, 83, 22854, 3526, 1330, 21293, 34379, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020,...
2.947761
134
import pygame import random from time import sleep white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) pygame.init() largura = 320 altura = 320 fundo = pygame.display.set_mode((largura, altura)) pygame.display.set_caption("TicTacToe") game = True fimdejogo = False evento = True trava = True resultado = 0 mousex = -1 mousey = 0 fundo.fill(white) cerca() matriz = [0, 0, 0, 0, 0, 0, 0, 0, 0] pygame.display.update() while game: while fimdejogo: sleep(0.5) fundo.fill(white) texto('Fim de Jogo', red, 50, 65, 30) if resultado == 1: texto('Vitoria!!!', black, 30, 70, 80) if resultado == 3: texto('Velha', black, 30, 70, 80) if resultado == 2: texto('Derrota!!', black, 30, 70, 80) pygame.draw.rect(fundo, black, [45, 120, 135, 27]) texto('Continuar(C)', white, 30, 50, 125) pygame.draw.rect(fundo, black, [190, 120, 75, 27]) texto('Sair(S)', white, 30, 195, 125) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: game = False fimdejogo = False trava = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_c: game = True fimdejogo = False evento = True trava = True resultado = 0 mousex = -1 mousey = 0 fundo.fill(white) cerca() matriz = [0, 0, 0, 0, 0, 0, 0, 0, 0] pygame.display.update() if event.key == pygame.K_s: game = False fimdejogo = False evento = False trava = False while evento: for event in pygame.event.get(): if event.type == pygame.QUIT: game = False evento = False trava = False if event.type == pygame.MOUSEBUTTONDOWN: mousex = pygame.mouse.get_pos()[0] mousey = pygame.mouse.get_pos()[1] evento = False evento = True if mousex < 106 and mousey < 106 and mousex != -1 and matriz[0] == 0: cruz(35, 35) matriz[0] = 1 if mousex < 212 and mousex > 106 and mousey < 106 and matriz[1] == 0: cruz(141, 35) matriz[1] = 1 if mousex < 320 and mousex > 212 and mousey < 106 and matriz[2] == 0: cruz(247, 35) matriz[2] = 1 if mousex < 106 and mousey > 106 and mousey < 212 and matriz[3] == 0: cruz(35, 141) matriz[3] = 1 if mousex < 212 and mousex > 106 and mousey < 212 and mousey > 106 and matriz[4] == 0: cruz(141, 141) matriz[4] = 1 if mousex < 320 and mousex > 212 and mousey < 212 and mousey > 106 and matriz[5] == 0: cruz(247, 141) matriz[5] = 1 if mousex < 106 and mousey < 320 and mousey > 212 and matriz[6] == 0: cruz(35, 247) matriz[6] = 1 if mousex < 212 and mousex > 106 and mousey < 320 and mousey > 212 and matriz[7] == 0: cruz(141, 247) matriz[7] = 1 if mousex < 320 and mousex > 212 and mousey < 320 and mousey > 212 and matriz[8] == 0: cruz(247, 247) matriz[8] = 1 endgame() pygame.display.update() sleep(0.5) if trava: while True: jogada = random.randint(0, 8) if matriz[jogada] == 0: circulo(jogada) matriz[jogada] = 2 break else: if 0 in matriz: jogada = random.randint(0, 8) else: break endgame() pygame.display.update() pygame.display.update()
[ 11748, 12972, 6057, 198, 11748, 4738, 198, 6738, 640, 1330, 3993, 198, 198, 11186, 796, 357, 13381, 11, 14280, 11, 14280, 8, 198, 13424, 796, 357, 15, 11, 657, 11, 657, 8, 198, 445, 796, 357, 13381, 11, 657, 11, 657, 8, 198, 14809...
1.800813
2,214
#/usr/bin/env python # -*- coding: Utf8 -*- import event
[ 2, 14, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 7273, 69, 23, 532, 9, 12, 198, 198, 11748, 1785, 198 ]
2.230769
26
""" Copyright (C) 2012 Alan J Lockett 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. """ """ Parse .net format for Bayes nets and return a bayes net """ from pyec.config import Config from pyec.distribution.bayes.net import * from pyec.distribution.bayes.structure.proposal import StructureProposal
[ 37811, 198, 15269, 357, 34, 8, 2321, 12246, 449, 13656, 3087, 198, 198, 5990, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 286, 428, 3788, 290, 3917, 10314, 3696, 357, 1169, 366, 25423, 12340, 284...
3.99375
320
nome = str(input('Digite seu nome completo: ')).strip() if 'silva' in nome.lower(): print('Sim, seu nome tem Silva.') else: print('No , seu nome no tem Silva')
[ 77, 462, 796, 965, 7, 15414, 10786, 19511, 578, 384, 84, 299, 462, 1224, 1462, 25, 705, 29720, 36311, 3419, 198, 361, 705, 18217, 6862, 6, 287, 299, 462, 13, 21037, 33529, 198, 220, 220, 220, 3601, 10786, 8890, 11, 384, 84, 299, 4...
2.492537
67
"""empty message Revision ID: 8b664608a7c7 Revises: ec21e19825ff Create Date: 2021-06-01 14:37:20.327189 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '8b664608a7c7' down_revision = 'ec21e19825ff' branch_labels = None depends_on = None
[ 37811, 28920, 3275, 198, 198, 18009, 1166, 4522, 25, 807, 65, 21, 2414, 28688, 64, 22, 66, 22, 198, 18009, 2696, 25, 9940, 2481, 68, 22337, 1495, 487, 198, 16447, 7536, 25, 33448, 12, 3312, 12, 486, 1478, 25, 2718, 25, 1238, 13, 3...
2.491667
120