content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
#!/bin/env python # Vulture often detects false positives when analyzing a code # base. If there are particular things you wish to ignore, # add them below. This file is consumed by # scripts/dead_code/find-dead-code.sh from vulture.whitelist_utils import Whitelist view_whitelilst = Whitelist() # Example: # view_whitelist.name_of_function_to_whitelist
[ 2, 48443, 8800, 14, 24330, 21015, 198, 198, 2, 569, 6456, 1690, 39382, 3991, 38548, 618, 22712, 257, 2438, 198, 2, 2779, 13, 1002, 612, 389, 1948, 1243, 345, 4601, 284, 8856, 11, 198, 2, 751, 606, 2174, 13, 770, 2393, 318, 13529, ...
3.263636
110
# Copyright (c) OpenMMLab. All rights reserved. import warnings from collections import abc from contextlib import contextmanager from functools import wraps import torch from mmdet.utils import get_root_logger def cast_tensor_type(inputs, src_type=None, dst_type=None): """Recursively convert Tensor in inputs from ``src_type`` to ``dst_type``. Args: inputs: Inputs that to be casted. src_type (torch.dtype | torch.device): Source type. src_type (torch.dtype | torch.device): Destination type. Returns: The same type with inputs, but all contained Tensors have been cast. """ assert dst_type is not None if isinstance(inputs, torch.Tensor): if isinstance(dst_type, torch.device): # convert Tensor to dst_device if hasattr(inputs, 'to') and \ hasattr(inputs, 'device') and \ (inputs.device == src_type or src_type is None): return inputs.to(dst_type) else: return inputs else: # convert Tensor to dst_dtype if hasattr(inputs, 'to') and \ hasattr(inputs, 'dtype') and \ (inputs.dtype == src_type or src_type is None): return inputs.to(dst_type) else: return inputs # we need to ensure that the type of inputs to be casted are the same # as the argument `src_type`. elif isinstance(inputs, abc.Mapping): return type(inputs)({ k: cast_tensor_type(v, src_type=src_type, dst_type=dst_type) for k, v in inputs.items() }) elif isinstance(inputs, abc.Iterable): return type(inputs)( cast_tensor_type(item, src_type=src_type, dst_type=dst_type) for item in inputs) # TODO: Currently not supported # elif isinstance(inputs, InstanceData): # for key, value in inputs.items(): # inputs[key] = cast_tensor_type( # value, src_type=src_type, dst_type=dst_type) # return inputs else: return inputs # To use AvoidOOM as a decorator AvoidCUDAOOM = AvoidOOM()
[ 2, 15069, 357, 66, 8, 4946, 44, 5805, 397, 13, 1439, 2489, 10395, 13, 198, 11748, 14601, 198, 6738, 17268, 1330, 450, 66, 198, 6738, 4732, 8019, 1330, 4732, 37153, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 198, 11748, 28034, 198,...
2.185885
1,006
# import packages to extend python (just like we extend sublime, or Atom, or VSCode) from random import randint from gameComponents import gameVars, chooseWinner while gameVars.player is False: print("=======================*/ RPS CONTEST /*=======================") print("Computer Lives: ", gameVars.ai_lives, "/", gameVars.total_lives) print("Player Lives: ", gameVars.player_lives, "/", gameVars.total_lives) print("==============================================") print("Choose your weapon! or type quit to leave\n") gameVars.player = input("Choose rock, paper or scissors: \n") # if the player chose to quit then exit the game if gameVars.player == "quit": print("You chose to quit") exit() #player = True -> it has a value (rock, paper, or scissors) # this will be the AI choice -> a random pick from the choices array computer = gameVars.choices[randint(0, 2)] # check to see what the user input # print outputs whatever is in the round brackets -> in this case it outputs player to the command prompt window print("user chose: " + gameVars.player) # validate that the random choice worked for the AI print("AI chose: " + computer) #--------------------------- MOVE THIS CHUNK OF CODE TO A PACKAGE - START HERE -------------------- if (computer == gameVars.player): print("tie") # always check for negative conditions first (the losing case) elif (computer == "rock"): if (gameVars.player == "scissors"): print("you lose") gameVars.player_lives -= 1 else: print("you win!") gameVars.ai_lives -= 1 elif (computer == "paper"): if (gameVars.player == "rock"): print("you lose") gameVars.player_lives -= 1 else: print("you win!") gameVars.ai_lives -= 1 elif (computer == "scissors"): if (gameVars.player == "paper"): print("you lose") gameVars.player_lives -= 1 else: print("you win!") gameVars.ai_lives -= 1 #--------------------------- stop here - all of the above needs to move ----------------------- if gameVars.player_lives is 0: chooseWinner.winorlose("lost") if gameVars.ai_lives is 0: chooseWinner.winorlose("won") print("Player has", gameVars.player_lives, "lives left") print("AI has", gameVars.ai_lives, "lives left") gameVars.player = False
[ 2, 1330, 10392, 284, 9117, 21015, 357, 3137, 588, 356, 9117, 41674, 11, 393, 33102, 11, 393, 569, 6173, 1098, 8, 198, 6738, 4738, 1330, 43720, 600, 198, 6738, 983, 7293, 3906, 1330, 983, 53, 945, 11, 3853, 48056, 628, 198, 198, 4514...
3.005277
758
import pandas as pd import os
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 28686 ]
3.222222
9
import time from threading import Timer i = 0 if __name__ == "__main__": print("Starting...") rt = RepeatedTimer(0.05, timeTest) # it auto start ,so dont need rt.start() try: ST = time.time() time.sleep(5) except Exception as e: raise e finally: rt.stop() print(time.time() - ST)
[ 11748, 640, 220, 201, 198, 6738, 4704, 278, 1330, 5045, 263, 201, 198, 201, 198, 72, 796, 657, 201, 198, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 201, 198, 220, 220, 220, 3601, 7203, 22851, 9313, ...
2.039106
179
# coding: utf-8 # In[1]: import keras # In[2]: # scipy import scipy print( ' scipy: %s ' % scipy.__version__) # numpy import numpy print( ' numpy: %s ' % numpy.__version__) # matplotlib import matplotlib print( ' matplotlib: %s ' % matplotlib.__version__) # pandas import pandas print( ' pandas: %s ' % pandas.__version__) # statsmodels import statsmodels print( ' statsmodels: %s ' % statsmodels.__version__) # scikit-learn import sklearn print( ' sklearn: %s ' % sklearn.__version__) # In[3]: # theano import theano print( ' theano: %s ' % theano.__version__) # tensorflow import tensorflow print( ' tensorflow: %s ' % tensorflow.__version__) # keras import keras print( ' keras: %s ' % keras.__version__)
[ 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 554, 58, 16, 5974, 628, 198, 11748, 41927, 292, 628, 198, 2, 554, 58, 17, 5974, 628, 198, 2, 629, 541, 88, 198, 11748, 629, 541, 88, 198, 4798, 7, 705, 629, 541, 88, 25, 4064...
2.520979
286
from .DefaultColorScheme import DefaultColorScheme
[ 6738, 764, 19463, 10258, 27054, 1326, 1330, 15161, 10258, 27054, 1326, 628 ]
4.333333
12
# 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. load("@bazel_skylib//lib:shell.bzl", "shell") json_extract = rule( implementation = _json_extract_impl, attrs = { "srcs": attr.label_list( mandatory = True, allow_files = [".json"], doc = "List of inputs. Must all be valid JSON files.", ), "suffix": attr.string( default = "", doc = ("Output file extensions. Each input file will be renamed " + "from basename.json to basename+suffix."), ), "raw": attr.bool( default = False, doc = ("Whether or not to pass -r to jq. Passing -r will result " + "in raw data being extracted, i.e. non-JSQN output."), ), "query": attr.string( default = ".", doc = ("Query to pass to the jq binary. The default is '.', " + "meaning just copy the validated input."), ), "flags": attr.string_list( allow_empty = True, doc = "List of flags to pass to the jq binary.", ), "_jq": attr.label( executable = True, cfg = "host", default = Label("@jq"), ), }, ) json_test = rule( implementation = _json_test_impl, attrs = { "srcs": attr.label_list( mandatory = True, allow_files = [".json"], doc = ("List of inputs. The test will verify that they are " + "valid JSON files."), ), "_jq": attr.label( executable = True, cfg = "host", default = Label("@jq"), ), }, outputs = {"test": "%{name}.sh"}, test = True, )
[ 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.242395
1,019
import matplotlib.pyplot as plt plt.switch_backend('agg') import seaborn as sns sns_plot = \ (sns.jointplot(psi, phi, size=12, space=0, xlim=(-190, 190), ylim=(-190, 190)).plot_joint(sns.kdeplot, zorder=0, n_levels=6)) # sns_plot = sns.jointplot(psi_list_numpy, phi_list_numpy, kind="hex", color="#4CB391") # stat_func=kendalltau # sns_plot.ylim(-180, 180) print "plotting: ", pfam sns_plot.savefig("Ramachandranplot_scatter/ramachandranplot_" + pfam + ".png")
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 489, 83, 13, 31943, 62, 1891, 437, 10786, 9460, 11537, 198, 11748, 384, 397, 1211, 355, 3013, 82, 628, 198, 198, 82, 5907, 62, 29487, 796, 3467, 198, 7, 82, 5907, 13, 7...
1.871622
296
from unittest import mock import pytest get_tracer = pytest.importorskip('opentelemetry.trace.get_tracer')
[ 6738, 555, 715, 395, 1330, 15290, 198, 198, 11748, 12972, 9288, 198, 198, 1136, 62, 2213, 11736, 796, 12972, 9288, 13, 11748, 669, 74, 541, 10786, 404, 298, 11129, 41935, 13, 40546, 13, 1136, 62, 2213, 11736, 11537, 628 ]
2.820513
39
from logic import *
[ 6738, 9156, 1330, 1635, 198 ]
4
5
# Definition for singly-linked list. def initlist(listnum): head = ListNode(listnum[0]) tail = head for num in listnum[1:]: tail.next = ListNode(num) tail = tail.next return head if __name__ == "__main__": sol = Solution() sol.swapPairs(initlist([1,2,3,4]))
[ 2, 30396, 329, 1702, 306, 12, 25614, 1351, 13, 198, 198, 4299, 2315, 4868, 7, 4868, 22510, 2599, 198, 220, 1182, 796, 7343, 19667, 7, 4868, 22510, 58, 15, 12962, 198, 220, 7894, 796, 1182, 198, 220, 329, 997, 287, 1351, 22510, 58, ...
2.513514
111
#!/usr/bin/python #coding=utf-8 import os from flask import Flask from flask import Response from flask import request app = Flask(__name__) if __name__ == "__main__": app.run()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 66, 7656, 28, 40477, 12, 23, 198, 11748, 28686, 198, 6738, 42903, 1330, 46947, 198, 6738, 42903, 1330, 18261, 198, 6738, 42903, 1330, 2581, 198, 198, 1324, 796, 46947, 7, 834, 3672, 834, ...
2.904762
63
""" Ahira Justice, ADEFOKUN justiceahira@gmail.com """ import os import pygame BASE_DIR = os.path.dirname(os.path.abspath(__file__)) IMAGE_DIR = os.path.join(BASE_DIR, "images") BLACK = "BLACK" WHITE = "WHITE" BISHOP = "BISHOP" KING = "KING" KNGHT = "KNIGHT" PAWN = "PAWN" QUEEN = "QUEEN" ROOK = "ROOK"
[ 37811, 198, 220, 220, 220, 7900, 8704, 4796, 11, 5984, 36, 6080, 42, 4944, 198, 220, 220, 220, 5316, 993, 8704, 31, 14816, 13, 785, 198, 37811, 628, 198, 11748, 28686, 198, 11748, 12972, 6057, 628, 198, 33, 11159, 62, 34720, 796, 28...
2.10596
151
from resource_management.core.resources.system import Execute from resource_management.libraries.script import Script from resource_management.core.resources.system import Directory from resource_management.core.resources.system import File from resource_management.core.source import InlineTemplate from resource_management.libraries.functions.check_process_status import check_process_status import os if __name__ == "__main__": Rocketmq().execute()
[ 6738, 8271, 62, 27604, 13, 7295, 13, 37540, 13, 10057, 1330, 8393, 1133, 198, 6738, 8271, 62, 27604, 13, 75, 11127, 13, 12048, 1330, 12327, 198, 198, 6738, 8271, 62, 27604, 13, 7295, 13, 37540, 13, 10057, 1330, 27387, 198, 6738, 8271,...
3.957265
117
"""Cue: Script Orchestration for Data Analysis Cue lets your package your data analysis into simple actions which can be connected into a dynamic data analysis pipeline with coverage over even complex data sets. """ DOCLINES = (__doc__ or '').split('\n') from setuptools import find_packages, setup setup( name='py-cue', package_dir={'cue/cue': 'cue'}, packages=find_packages(include=['cue']), version='0.1.0', description=DOCLINES[0], long_description="\n".join(DOCLINES[2:]), project_urls={ "Source Code": "https://github.com/ktvng/cue" }, author='ktvng', license='MIT', python_requires='>=3.8', install_requires=['pyyaml>=5.2'], entry_points={ 'console_scripts': { 'cue=cue.cli:run' } } )
[ 37811, 34, 518, 25, 12327, 30369, 12401, 329, 6060, 14691, 201, 198, 201, 198, 34, 518, 8781, 534, 5301, 534, 1366, 3781, 656, 2829, 4028, 543, 460, 307, 5884, 220, 201, 198, 20424, 257, 8925, 1366, 3781, 11523, 351, 5197, 625, 772, ...
2.367052
346
#!/usr/bin/python3.2 # # Zabbix API Python usage example # Christoph Haas <email@christoph-haas.de> # username='' password='1' hostgroup='' item_name='system.cpu.load[,avg1]' zabbix_url='' import zabbix_api import sys # Connect to Zabbix server z=zabbix_api.ZabbixAPI(server=zabbix_url) z.login(user=username, password=password) # Get hosts in the hostgroup hostgroup = z.hostgroup.get( { 'filter': { 'name':hostgroup }, 'sortfield': 'name', 'sortorder': 'ASC', 'limit':2, 'select_hosts':'extend' }) print(hostgroup[0]) print("\n") for host in hostgroup[0]['name']: hostname = host['host'] print("Host:", hostname) print("Host-ID:", host['hostid']) item = z.item.get({ 'output':'extend', 'hostids':host['hostid'], 'filter':{'key_':item_name}}) if item: print(item[0]['lastvalue']) print("Item-ID:", item[0]['itemid']) # Get history lastvalue = z.history.get({ 'history': item[0]['value_type'], 'itemids': item[0]['itemid'], 'output': 'extend', # Sort by timestamp from new to old 'sortfield':'clock', 'sortorder':'DESC', # Get only the first (=newest) entry 'limit': 1, }) # CAVEAT! The history.get function must be told which type the # values are (float, text, etc.). The item.value_type contains # the number that needs to be passed to history.get. if lastvalue: lastvalue = lastvalue[0]['value'] print("Last value:", lastvalue) else: print("No item....") print("---------------------------")
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 13, 17, 198, 2, 198, 2, 1168, 6485, 844, 7824, 11361, 8748, 1672, 198, 2, 1951, 2522, 50090, 1279, 12888, 31, 43533, 2522, 12, 3099, 292, 13, 2934, 29, 198, 2, 198, 198, 29460, 28, 7061, ...
2.202086
767
import copy import math import os import random import cherrypy """ This is a simple Battlesnake server written in Python. For instructions see https://github.com/BattlesnakeOfficial/starter-snake-python/README.md """ if __name__ == "__main__": server = Battlesnake() cherrypy.config.update({"server.socket_host": "0.0.0.0"}) cherrypy.config.update({ "server.socket_port": int(os.environ.get("PORT", "8080")), }) print("Starting Battlesnake Server...") cherrypy.quickstart(server)
[ 11748, 4866, 198, 11748, 10688, 198, 11748, 28686, 198, 11748, 4738, 198, 198, 11748, 23612, 9078, 198, 198, 37811, 198, 1212, 318, 257, 2829, 25467, 77, 539, 4382, 3194, 287, 11361, 13, 198, 1890, 7729, 766, 3740, 1378, 12567, 13, 785,...
2.823864
176
# $Header: /nfs/slac/g/glast/ground/cvs/GlastRelease-scons/EventIntegrity/EventIntegrityLib.py,v 1.2 2008/08/28 21:50:54 ecephas Exp $
[ 2, 720, 39681, 25, 1220, 77, 9501, 14, 6649, 330, 14, 70, 14, 4743, 459, 14, 2833, 14, 66, 14259, 14, 9861, 459, 26362, 12, 1416, 684, 14, 9237, 34500, 10138, 14, 9237, 34500, 10138, 25835, 13, 9078, 11, 85, 352, 13, 17, 3648, 1...
2.288136
59
"""Gives users direct access to class and functions.""" from mr4mp.mr4mp import pool, mapreduce, mapconcat
[ 37811, 38, 1083, 2985, 1277, 1895, 284, 1398, 290, 5499, 526, 15931, 198, 6738, 285, 81, 19, 3149, 13, 43395, 19, 3149, 1330, 5933, 11, 3975, 445, 7234, 11, 3975, 1102, 9246, 198 ]
3.242424
33
# -*- coding: utf-8 -*- # Copyright 2020 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 # # 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 proto # type: ignore from google.protobuf import duration_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( package='google.devtools.testing.v1', manifest={ 'OrchestratorOption', 'RoboActionType', 'InvalidMatrixDetails', 'TestState', 'OutcomeSummary', 'TestMatrix', 'TestExecution', 'TestSpecification', 'SystraceSetup', 'TestSetup', 'IosTestSetup', 'EnvironmentVariable', 'Account', 'GoogleAuto', 'Apk', 'AppBundle', 'DeviceFile', 'ObbFile', 'RegularFile', 'IosDeviceFile', 'AndroidTestLoop', 'IosXcTest', 'IosTestLoop', 'AndroidInstrumentationTest', 'AndroidRoboTest', 'RoboDirective', 'RoboStartingIntent', 'LauncherActivityIntent', 'StartActivityIntent', 'EnvironmentMatrix', 'AndroidDeviceList', 'IosDeviceList', 'AndroidMatrix', 'ClientInfo', 'ClientInfoDetail', 'ResultStorage', 'ToolResultsHistory', 'ToolResultsExecution', 'ToolResultsStep', 'GoogleCloudStorage', 'FileReference', 'Environment', 'AndroidDevice', 'IosDevice', 'TestDetails', 'InvalidRequestDetail', 'ShardingOption', 'UniformSharding', 'ManualSharding', 'TestTargetsForShard', 'Shard', 'CreateTestMatrixRequest', 'GetTestMatrixRequest', 'CancelTestMatrixRequest', 'CancelTestMatrixResponse', }, ) __all__ = tuple(sorted(__protobuf__.manifest))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 12131, 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, 2...
2.337561
1,025
from collections import defaultdict # Your WordDistance object will be instantiated and called as such: # wordDistance = WordDistance(words) # wordDistance.shortest("word1", "word2") # wordDistance.shortest("anotherWord1", "anotherWord2")
[ 6738, 17268, 1330, 4277, 11600, 628, 198, 198, 2, 3406, 9678, 45767, 2134, 481, 307, 9113, 12931, 290, 1444, 355, 884, 25, 198, 2, 1573, 45767, 796, 9678, 45767, 7, 10879, 8, 198, 2, 1573, 45767, 13, 19509, 395, 7203, 4775, 16, 1600...
3.723077
65
from perceptron import train_network, create_perceptron, test_network from preprocessingData import get_ids_matrix, separate_test_and_training_data, read_word_list from extractRawData import get_raw_data from lstm import create_lstm, create_lstm_with_tensorflow if __name__ == "__main__": main()
[ 6738, 34953, 1313, 1330, 4512, 62, 27349, 11, 2251, 62, 525, 984, 1313, 11, 1332, 62, 27349, 198, 6738, 662, 36948, 6601, 1330, 651, 62, 2340, 62, 6759, 8609, 11, 4553, 62, 9288, 62, 392, 62, 34409, 62, 7890, 11, 1100, 62, 4775, 6...
3.103093
97
# Databricks notebook source import builtins as BI # Setup the capstone import re, uuid from pyspark.sql.types import StructType, StringType, IntegerType, TimestampType, DoubleType from pyspark.sql.functions import col, to_date, weekofyear from pyspark.sql import DataFrame static_tests = None bronze_tests = None silver_tests = None gold_tests = None registration_id = None final_passed = False course_name = "Core Partner Enablement" username = spark.sql("SELECT current_user()").first()[0] clean_username = re.sub("[^a-zA-Z0-9]", "_", username) user_db = f"dbacademy_{clean_username}_dev_ess_cap" working_dir = f"dbfs:/user/{username}/dbacademy/dev-ess-cap" outputPathBronzeTest = f"{working_dir}/bronze_test" outputPathSilverTest = f"{working_dir}/silver_test" outputPathGoldTest = f"{working_dir}/gold_test" source_path = f"wasbs://courseware@dbacademy.blob.core.windows.net/developer-essentials-capstone/v01" eventSchema = ( StructType() .add('eventName', StringType()) .add('eventParams', StructType() .add('game_keyword', StringType()) .add('app_name', StringType()) .add('scoreAdjustment', IntegerType()) .add('platform', StringType()) .add('app_version', StringType()) .add('device_id', StringType()) .add('client_event_time', TimestampType()) .add('amount', DoubleType()) ) ) print(f"Declared the following variables:") print(f" * user_db: {user_db}") print(f" * working_dir: {working_dir}") print() print(f"Declared the following function:") print(f" * realityCheckBronze(..)") print(f" * realityCheckStatic(..)") print(f" * realityCheckSilver(..)") print(f" * realityCheckGold(..)") print(f" * realityCheckFinal()") # COMMAND ---------- try: reinstall = dbutils.widgets.get("reinstall").lower() == "true" except: reinstall = False install_exercise_datasets(reinstall) print(f"\nYour Registration ID is {registration_id}") # COMMAND ---------- # Setup Bronze from pyspark.sql import DataFrame import time None # COMMAND ---------- # Setup Static None # COMMAND ---------- # Setup Silver None # COMMAND ---------- # Setup Gold None # COMMAND ---------- html_passed = f""" <html> <body> <h2>Congratulations! You're all done!</h2> While the preliminary evaluation of your project indicates that you have passed, we have a few more validation steps to run on the back-end:<br/> <ul style="margin:0"> <li> Code & statistical analysis of your capstone project</li> <li> Correlation of your account in our LMS via your email address, <b>{username}</b></li> <li> Final preparation of your badge </ul> <p>Assuming there are no issues with our last few steps, you will receive your <b>Databricks Developer Essentials Badge</b> within 2 weeks. Notification will be made by email to <b>{username}</b> regarding the availability of your digital badge via <b>Accredible</b>. Should we have any issues, such as not finding your email address in our LMS, we will do our best to resolve the issue using the email address provided here. </p> <p>Your digital badge will be available in a secure, verifiable, and digital format that you can easily retrieve via <b>Accredible</b>. You can then share your achievement via any number of different social media platforms.</p> <p>If you have questions about the status of your badge after the initial two-week window, or if the email address listed above is incorrect, please <a href="https://help.databricks.com/s/contact-us?ReqType=training" target="_blank">submit a ticket</a> with the subject "Core Capstone" and your Registration ID (<b>{registration_id}</b>) in the message body. Please allow us 3-5 business days to respond.</p> One final note: In order to comply with <a href="https://oag.ca.gov/privacy/ccpa" target="_blank">CCPA</a> and <a href="https://gdpr.eu/" target="_blank">GDPR</a>, which regulate the collection of your personal information, the status of this capstone and its correlation to your email address will be deleted within 30 days of its submission. </body> </html> """ html_failed = f""" <html> <body> <h2>Almost There!</h2> <p>Our preliminary evaluation of your project indicates that you have not passed.</p> <p>In order for your project to be submitted <b>all</b> reality checks must pass.</p> <p>In some cases this problem can be resolved by simply clearning the notebook's state (<b>Clear State & Results</b>) and then selecting <b>Run All</b> from the toolbar above.</p> <p>If your project continues to fail validation, please review each step above to ensure that you are have properly addressed all the corresponding requirements.</p> </body> </html> """ # Setup Final None # COMMAND ---------- daLogger = CapstoneLogger() None # COMMAND ---------- # These imports are OK to provide for students import pyspark from typing import Callable, Any, Iterable, List, Set, Tuple import uuid ############################################# # Test Suite classes ############################################# # Test case # Test result # Decorator to lazy evaluate - used by TestSuite def lazy_property(fn): '''Decorator that makes a property lazy-evaluated. ''' attr_name = '_lazy_' + fn.__name__ return _lazy_property testResultsStyle = """ <style> table { text-align: left; border-collapse: collapse; margin: 1em; caption-side: bottom; font-family: Sans-Serif; font-size: 16px} caption { text-align: left; padding: 5px } th, td { border: 1px solid #ddd; padding: 5px } th { background-color: #ddd } .passed { background-color: #97d897 } .failed { background-color: #e2716c } .skipped { background-color: #f9d275 } .results .points { display: none } .results .message { display: none } .results .passed::before { content: "Passed" } .results .failed::before { content: "Failed" } .results .skipped::before { content: "Skipped" } .grade .passed .message:empty::before { content:"Passed" } .grade .failed .message:empty::before { content:"Failed" } .grade .skipped .message:empty::before { content:"Skipped" } </style> """.strip() # Test suite class class __TestResultsAggregator(object): testResults = dict() def displayResults(self): displayHTML(testResultsStyle + f""" <table class='results'> <tr><th colspan="2">Test Summary</th></tr> <tr><td>Number of Passing Tests</td><td style="text-align:right">{self.score}</td></tr> <tr><td>Number of Failing Tests</td><td style="text-align:right">{self.maxScore-self.score}</td></tr> <tr><td>Percentage Passed</td><td style="text-align:right">{self.percentage}%</td></tr> </table> """) # Lazy-man's singleton TestResultsAggregator = __TestResultsAggregator() None # COMMAND ---------- from pyspark.sql import Row, DataFrame None # COMMAND ---------- from pyspark.sql import DataFrame from pyspark.sql.functions import col, sum import os print("Finished setting up the capstone environment.")
[ 2, 16092, 397, 23706, 20922, 2723, 198, 11748, 3170, 1040, 355, 20068, 198, 198, 2, 31122, 262, 1451, 6440, 198, 11748, 302, 11, 334, 27112, 198, 6738, 279, 893, 20928, 13, 25410, 13, 19199, 1330, 32112, 6030, 11, 10903, 6030, 11, 341...
3.08071
2,255
import requests from bs4 import BeautifulSoup as bs, BeautifulSoup import pandas as pd import numpy as np import re import logging def get_houses_in_location( self, location_url_: str, houses_in_location: set = set(), page_limit: int = 1, page_number: int = 1, ) -> list: """ Accepts location url and goes through pages in that location scraping every house until page limit is reached. Returns list of dicts with scraped information about every house in that location. :param location_url_: string with link to specific location in California state :param houses_in_location: set with already scraped links. Since retrieved links can be repetitive, there is no need to go to the same link which has already been scraped. Set is used for faster search :param page_limit: how many pages to scraped. If not passed by the user, default is 1 :param page_number: Current page to scrape. Starting number is 1 :return: list of dictionaries """ houses_information = [] try: new_url = self.basic_url + location_url_ + f"?page={page_number}" page_ = self.get_page(new_url) if page_.find_all("li", class_="lslide"): for elem in page_.find_all("li", class_="lslide"): link = elem.find("a")["href"] if link.startswith("/US") and link not in houses_in_location: houses_information.append( self.scrape_info_one_house( self.get_page(self.basic_url + link) ) ) houses_in_location.add(link) if page_number <= page_limit: page_number += 1 self.get_houses_in_location( location_url_, houses_in_location, page_limit, page_number=page_number, ) except Exception as err: logging.error(f"Error occurred while scraping locations. Message: {err}") return houses_information def scrape_platform(self, page_limit: int = 1) -> None: """ Main scraping function. Accepts page limit - how many pages to scrape, default is 1. The flow: - First, all California areas (locations) are extracted and put into a list. - Area list is iterated over. Each area has a number of pages with real estate descriptions. User can select how many pages he wants to go through. - Scraper visits every real estate link in the page and scrapes required information. After all houses are scraped, scraper moves to the next page. When no more pages are left or user denoted page limit is reached, scraper moves to the next category. :param page_limit: how many pages to scrape per area :return: None. """ starting_url = "https://www.point2homes.com/US/Real-Estate-Listings/CA.html" houses = [] starting_page = self.get_page(starting_url) locations = self.get_location_urls(starting_page) for location in locations: houses.extend( self.get_houses_in_location(location, set(), page_limit=page_limit) ) self.to_dataframe(houses).to_csv("California Housing.csv")
[ 11748, 7007, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 355, 275, 82, 11, 23762, 50, 10486, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 302, 198, 11748, 18931, 628, 198, 220, 220, 220, ...
2.300066
1,523
from selenium import webdriver from scrapy.selector import Selector import time chrome_opt = webdriver.ChromeOptions() prefs = {"profile.managed_default_content_settings.images": 2} chrome_opt.add_experimental_option("prefs", prefs) browser = webdriver.Chrome(executable_path="H:\chromedriver.exe", chrome_options=chrome_opt) browser.get("https://www.taobao.com") # time.sleep(5) # browser.find_element_by_css_selector() # t_selector = Selector(text=browser.page_source) # t_selector.css() # for i in range(3): # browser.execute_script("window.scrollTo(0, document.body.scrollHeight); var lenOfPage=document.body.scrollHeight; return lenOfPage;") # time.sleep(3) # browser.quit()
[ 6738, 384, 11925, 1505, 1330, 3992, 26230, 198, 6738, 15881, 88, 13, 19738, 273, 1330, 9683, 273, 198, 11748, 640, 198, 198, 46659, 62, 8738, 796, 3992, 26230, 13, 1925, 5998, 29046, 3419, 198, 3866, 9501, 796, 19779, 13317, 13, 39935, ...
2.8875
240
from nine import str from Qt.QtWidgets import QApplication, QStyleFactory from Qt import QtGui from Qt import QtCore import sys import os from PyFlow.App import PyFlow FILE_DIR = os.path.abspath(os.path.dirname(__file__)) SETTINGS_PATH = os.path.join(FILE_DIR, "PyFlow", "appConfig.ini") STYLE_PATH = os.path.join(FILE_DIR, "PyFlow", "style.css") app = QApplication(sys.argv) app.setStyle(QStyleFactory.create("plastique")) dark_palette = app.palette() dark_palette.setColor(QtGui.QPalette.Window, QtGui.QColor(53, 53, 53)) dark_palette.setColor(QtGui.QPalette.WindowText, QtCore.Qt.white) dark_palette.setColor(QtGui.QPalette.Base, QtGui.QColor(25, 25, 25)) dark_palette.setColor(QtGui.QPalette.AlternateBase, QtGui.QColor(53, 53, 53)) dark_palette.setColor(QtGui.QPalette.ToolTipBase, QtCore.Qt.white) dark_palette.setColor(QtGui.QPalette.ToolTipText, QtCore.Qt.white) dark_palette.setColor(QtGui.QPalette.Text, QtCore.Qt.black) dark_palette.setColor(QtGui.QPalette.Button, QtGui.QColor(53, 53, 53)) dark_palette.setColor(QtGui.QPalette.ButtonText, QtCore.Qt.black) dark_palette.setColor(QtGui.QPalette.BrightText, QtCore.Qt.red) dark_palette.setColor(QtGui.QPalette.Link, QtGui.QColor(42, 130, 218)) dark_palette.setColor(QtGui.QPalette.Highlight, QtGui.QColor(42, 130, 218)) dark_palette.setColor(QtGui.QPalette.HighlightedText, QtCore.Qt.black) app.setPalette(dark_palette) try: with open(STYLE_PATH, 'r') as f: styleString = f.read() app.setStyleSheet(styleString) except Exception as e: print(e) instance = PyFlow.instance() app.setActiveWindow(instance) instance.show() try: sys.exit(app.exec_()) except Exception as e: print(e)
[ 6738, 5193, 1330, 965, 198, 6738, 33734, 13, 48, 83, 54, 312, 11407, 1330, 1195, 23416, 11, 1195, 21466, 22810, 198, 6738, 33734, 1330, 33734, 8205, 72, 198, 6738, 33734, 1330, 33734, 14055, 198, 11748, 25064, 198, 11748, 28686, 198, 19...
2.353436
713
import pandas as pd from dash import Dash, html, dcc, Input, Output import altair as alt df = pd.read_csv('../../data/raw/world-data-gapminder_raw.csv') # local run # df = pd.read_csv('data/raw/world-data-gapminder_raw.csv') # heroku deployment url = '/dash_app2/' def add_dash(server): """ It creates a Dash app that plots a line chart of children per woman from gapminder dataset with 2 widgets : rangeslider for years and dropdown for filter :param server: The Flask app object :return: A Dash server """ app = Dash(server=server, url_base_pathname=url) app.layout = html.Div([ html.Iframe( id='line_children', style={'border-width': '0', 'width': '600px', 'height': '400px', 'display': 'block', 'margin-left': 'auto', 'margin-right': 'auto'}), html.Label([ 'Zoom in years: ', dcc.RangeSlider(1918, 2018, 10, value=[1918, 2018], id='year_range_slider', marks={str(year): str(year) for year in range(1918, 2028, 10)}), ]), html.Label([ 'See breakdown number by: ', dcc.Dropdown(options=[ {'label': 'All', 'value': 'all'}, {'label': 'Income Group', 'value': 'income_group'}, {'label': 'Region', 'value': 'region'} ], value='', id='filter_dropdown') ]), html.Div(id="data_card_2", **{'data-card_2_data': []}) ]) # Set up callbacks/backend return app.server
[ 11748, 19798, 292, 355, 279, 67, 198, 6738, 14470, 1330, 16189, 11, 27711, 11, 288, 535, 11, 23412, 11, 25235, 198, 11748, 5988, 958, 355, 5988, 198, 198, 7568, 796, 279, 67, 13, 961, 62, 40664, 10786, 40720, 40720, 7890, 14, 1831, ...
2.163662
721
# Author: Arrykrishna Mootoovaloo # Collaborators: Alan Heavens, Andrew Jaffe, Florent Leclercq # Email : a.mootoovaloo17@imperial.ac.uk # Affiliation : Imperial Centre for Inference and Cosmology # Status : Under Development ''' Perform all additional operations such as interpolations ''' import os import logging import numpy as np import scipy.interpolate as itp from typing import Tuple def indices(nzmax: int) -> Tuple[list, tuple]: ''' Generates indices for double sum power spectra :param: nzmax (int) - the maximum number of redshifts (assuming first redshift is zero) :return: di_ee (list), idx_gi (tuple) - double indices for EE and indices for GI ''' # create emty lists to recod all indices # for EE power spectrum di_ee = [] # for GI power spectrum # ab means alpha, beta Lab_1 = [] Lab_2 = [] Lba_1 = [] Lba_2 = [] for i in range(1, nzmax + 1): for j in range(1, nzmax + 1): di_ee.append(np.min([i, j])) if i > j: Lab_1.append(i) Lab_2.append(j) elif j > i: Lba_1.append(i) Lba_2.append(j) Lab_1 = np.asarray(Lab_1) Lab_2 = np.asarray(Lab_2) Lba_1 = np.asarray(Lba_1) Lba_2 = np.asarray(Lba_2) di_ee = np.asarray(di_ee) idx_gi = (Lab_1, Lab_2, Lba_1, Lba_2) return di_ee, idx_gi def dvalues(d: dict) -> np.ndarray: ''' Returns an array of values instead of dictionary format :param: d (dict) - a dictionary with keys and values :return: v (np.ndarray) - array of values ''' v = np.array(list(d.values())) return v def like_interp_2d(inputs: list, int_type: str = 'cubic') -> object: ''' We want to predict the function for any new point of k and z (example) :param: inputs (list) - a list containing x, y, f(x,y) :param: int_type (str) - interpolation type (default: 'cubic') :return: f (object) - the interpolator ''' k, z, f_kz = np.log(inputs[0]), inputs[1], inputs[2] inputs_trans = [k, z, f_kz] f = itp.interp2d(*inputs_trans) return f def two_dims_interpolate(inputs: list, grid: list) -> np.ndarray: ''' Function to perform 2D interpolation using interpolate.interp2d :param: inputs (list) : inputs to the interpolation module, that is, we need to specify the following: - x - y - f(x,y) - 'linear', 'cubic', 'quintic' :param: grid (list) : a list containing xnew and ynew :return: pred_new (np.ndarray) : the predicted values on the 2D grid ''' # check that all elements are greater than 0 for log-transformation to be used condition = np.all(inputs[2] > 0) if condition: # transform k and f to log k, z, f_kz, int_type = np.log(inputs[0]), inputs[1], np.log(inputs[2]), inputs[3] else: # transform in k to log k, z, f_kz, int_type = np.log(inputs[0]), inputs[1], inputs[2], inputs[3] inputs_trans = [k, z, f_kz, int_type] # tranform the grid to log knew, znew = np.log(grid[0]), grid[1] grid_trans = [knew, znew] f = itp.interp2d(*inputs_trans) if condition: pred_new = np.exp(f(*grid_trans)) else: pred_new = f(*grid_trans) return pred_new def interpolate(inputs: list) -> np.ndarray: ''' Function to interpolate the power spectrum along the redshift axis :param: inputs (list or tuple) : x values, y values and new values of x :return: ynew (np.ndarray) : an array of the interpolated power spectra ''' x, y, xnew = inputs[0], inputs[1], inputs[2] spline = itp.splrep(x, y) ynew = itp.splev(xnew, spline) return ynew def get_logger(name: str, log_name: str, folder_name: str = 'logs'): ''' Create a log file for each Python scrip :param: name (str) - name of the Python script :param: log_name (str) - name of the output log file ''' # create the folder if it does not exist if not os.path.exists(folder_name): os.makedirs(folder_name) log_format = '%(asctime)s %(name)8s %(levelname)5s %(message)s' logging.basicConfig(level=logging.DEBUG, format=log_format, filename=folder_name + '/' + log_name + '.log', filemode='w') console = logging.StreamHandler() console.setLevel(logging.DEBUG) console.setFormatter(logging.Formatter(log_format)) logging.getLogger(name).addHandler(console) return logging.getLogger(name)
[ 2, 6434, 25, 943, 563, 74, 37518, 2616, 337, 1025, 78, 8325, 2238, 198, 2, 37322, 2024, 25, 12246, 11225, 82, 11, 6858, 449, 21223, 11, 23347, 429, 1004, 565, 2798, 80, 198, 2, 9570, 1058, 257, 13, 76, 1025, 78, 8325, 2238, 1558, ...
2.324229
1,977
from pybench import Test # First imports: import os import package.submodule
[ 6738, 12972, 26968, 1330, 6208, 198, 198, 2, 3274, 17944, 25, 198, 11748, 28686, 198, 11748, 5301, 13, 7266, 21412, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
2.212766
47
from unittest import TestCase
[ 6738, 555, 715, 395, 1330, 6208, 20448, 628 ]
3.875
8
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
3.888889
9
# Copyright 2020 Michael Thies <mail@mhthies.de> # # 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. from . import base from . import supervisor from . import variables from . import datatypes from . import conversion from . import timer from .base import handler, blocking_handler from .variables import Variable from .supervisor import main
[ 2, 15069, 12131, 3899, 536, 444, 1279, 4529, 31, 76, 71, 400, 444, 13, 2934, 29, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846,...
3.920188
213
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Simple Http Client, to request html files Modification: 11/09/2017 Author: J. Jnior ''' import httplib import sys #get http server ip - pass in the command line http_server = sys.argv[1] #create a connection with the server conn = httplib.HTTPConnection(http_server) while 1: cmd = raw_input('input command (ex. GET index.html): ') cmd = cmd.split() if cmd[0] == 'exit': #type exit to end it break #request command to server conn.request(cmd[0], cmd[1]) #get response from server rsp = conn.getresponse() #print server response and data print(rsp.status, rsp.reason) print(rsp.getheaders()) data_received = rsp.read() print(data_received) #close connection conn.close()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 7061, 6, 198, 220, 220, 220, 17427, 367, 29281, 20985, 11, 284, 2581, 27711, 3696, 198, 220, 220, 220, 3401, 2649, 25...
2.713287
286
"""Implement asymmetric cryptography. """ from __future__ import print_function, division, absolute_import from __future__ import unicode_literals from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import rsa, dsa, utils, padding from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 from cryptography.hazmat.backends import default_backend from collections import OrderedDict import io from builtins import int #pylint: disable=redefined-builtin from pyssh.constants import ENC_SSH_RSA, ENC_SSH_DSS from pyssh.base_types import String, MPInt # pylint:disable=invalid-name #TODO: ECDSA (RFC 5656) def pack_pubkey(self): """Pack a public key into bytes.""" raise NotImplementedError('not implemented') def verify_signature(self, signature, data): """Verify the signature against the given data. Pubkey must be set.""" raise NotImplementedError('not implemented') def sign(self, data): """Sign some data. Privkey must be set.""" raise NotImplementedError('not implemented') def read_pubkey(self, data): """Read a public key from data in the ssh public key format. :param bytes data: the data to read. Sets self.pubkey. """ pubkey = serialization.load_ssh_public_key(data, default_backend()) assert isinstance(pubkey.public_numbers(), self.PUBKEY_CLASS) self.pubkey = pubkey def read_privkey(self, data, password=None): """Read a PEM-encoded private key from data. If a password is set, it will be used to decode the key. :param bytes data: the data to read :param bytes password: The password. Sets self.privkey. """ privkey = serialization.load_pem_private_key(data, password, default_backend()) assert isinstance(privkey.private_numbers(), self.PRIVKEY_CLASS) self.privkey = privkey class RSAAlgorithm(BaseAlgorithm): """Support for the RSA algorithm.""" FORMAT_STR = String(ENC_SSH_RSA) PRIVKEY_CLASS = rsa.RSAPrivateNumbers PUBKEY_CLASS = rsa.RSAPublicNumbers class DSAAlgorithm(BaseAlgorithm): """Support for the DSA.""" FORMAT_STR = String(ENC_SSH_DSS) PRIVKEY_CLASS = dsa.DSAPrivateNumbers PUBKEY_CLASS = dsa.DSAPublicNumbers PUBLIC_KEY_PROTOCOLS = OrderedDict(( (ENC_SSH_RSA, RSAAlgorithm), (ENC_SSH_DSS, DSAAlgorithm) )) def get_asymmetric_algorithm(keytype): """Get the referenced public key type. If a signature_blob blob is included, validate it. """ try: handler = PUBLIC_KEY_PROTOCOLS[keytype] except KeyError: raise UnsupportedKeyProtocol(keytype) return handler()
[ 37811, 3546, 26908, 30372, 19482, 45898, 13, 198, 37811, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 11, 7297, 11, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 45898, 13, 71, ...
2.588398
1,086
""" @ jetou @ cart decision_tree @ date 2017 10 31 """ import numpy as np
[ 37811, 198, 220, 220, 220, 2488, 12644, 280, 198, 220, 220, 220, 2488, 6383, 2551, 62, 21048, 198, 220, 220, 220, 2488, 3128, 2177, 838, 3261, 198, 198, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 628 ]
2.405405
37
from . import frame_manager
[ 6738, 764, 1330, 5739, 62, 37153 ]
4.5
6
import os import sys if sys.version_info[:2] >= (3, 4): import configparser config = configparser.ConfigParser() else: import ConfigParser config = ConfigParser.ConfigParser() config.readfp(open('app/config/config_%s.cfg' % os.environ.get('APP_ENV', 'dev')))
[ 11748, 28686, 198, 11748, 25064, 198, 361, 25064, 13, 9641, 62, 10951, 58, 25, 17, 60, 18189, 357, 18, 11, 604, 2599, 198, 220, 220, 220, 1330, 4566, 48610, 198, 220, 220, 220, 4566, 796, 4566, 48610, 13, 16934, 46677, 3419, 198, 17...
2.732673
101
import tkinter from tkinter import * from rsa_decryption_125 import decryptor if __name__ == '__main__': main()
[ 11748, 256, 74, 3849, 198, 6738, 256, 74, 3849, 1330, 1635, 198, 6738, 374, 11400, 62, 12501, 13168, 62, 11623, 1330, 42797, 273, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419 ...
2.833333
42
import paddle.fluid as fluid import parl from parl import layers
[ 11748, 39517, 13, 35522, 312, 355, 11711, 198, 11748, 1582, 75, 198, 6738, 1582, 75, 1330, 11685, 628, 198 ]
3.526316
19
from PyQt4.QtGui import QPalette, QColor __author__ = 'pawel' from PyQt4 import QtGui from PyQt4.QtCore import Qt
[ 6738, 9485, 48, 83, 19, 13, 48, 83, 8205, 72, 1330, 1195, 11531, 5857, 11, 1195, 10258, 198, 198, 834, 9800, 834, 796, 705, 79, 707, 417, 6, 198, 198, 6738, 9485, 48, 83, 19, 1330, 33734, 8205, 72, 198, 6738, 9485, 48, 83, 19, ...
2.230769
52
import sys, os, urllib, StringIO, traceback, cgi, binascii, getopt, shutil import zipfile, gzip, tarfile #sys.path.append('/usr/local/pypi/lib') import store, config def set_password(store, name, pw): """ Reset the user's password and send an email to the address given. """ user = store.get_user(name.strip()) if user is None: raise ValueError, 'user name unknown to me' store.store_user(user['name'], pw.strip(), user['email'], None) print 'done' def remove_package(store, name): ''' Remove a package from the database ''' store.remove_package(name) print 'done' def add_classifier(st, classifier): ''' Add a classifier to the trove_classifiers list ''' cursor = st.get_cursor() cursor.execute("select max(id) from trove_classifiers") id = cursor.fetchone()[0] if id: id = int(id) + 1 else: id = 1 fields = [f.strip() for f in classifier.split('::')] for f in fields: assert ':' not in f levels = [] for l in range(2, len(fields)): c2 = ' :: '.join(fields[:l]) store.safe_execute(cursor, 'select id from trove_classifiers where classifier=%s', (c2,)) l = cursor.fetchone() if not l: raise ValueError, c2 + " is not a known classifier" levels.append(l[0]) levels += [id] + [0]*(3-len(levels)) store.safe_execute(cursor, 'insert into trove_classifiers (id, classifier, l2, l3, l4, l5) ' 'values (%s,%s,%s,%s,%s,%s)', [id, classifier]+levels) def rename_package(store, old, new): ''' Rename a package. ''' if not store.has_package(old): raise ValueError, 'no such package' if store.has_package(new): raise ValueError, new+' exists' store.rename_package(old, new) print "Please give www-data permissions to all files of", new def add_mirror(store, root, user): ''' Add a mirror to the mirrors list ''' store.add_mirror(root, user) print 'done' def delete_mirror(store, root): ''' Delete a mirror ''' store.delete_mirror(root) print 'done' def delete_old_docs(config, store): '''Delete documentation directories for packages that have been deleted''' for i in os.listdir(config.database_docs_dir): if not store.has_package(i): path = os.path.join(config.database_docs_dir, i) print "Deleting", path shutil.rmtree(path) if __name__ == '__main__': config = config.Config('/data/pypi/config.ini') st = store.Store(config) st.open() command = sys.argv[1] args = (st, ) + tuple(sys.argv[2:]) try: if command == 'password': set_password(*args) elif command == 'rmpackage': remove_package(*args) elif command == 'addclass': add_classifier(*args) print 'done' elif command == 'addowner': add_owner(*args) elif command == 'delowner': delete_owner(*args) elif command == 'rename': rename_package(*args) elif command == 'addmirror': add_mirror(*args) elif command == 'delmirror': delete_mirror(*args) elif command == 'delolddocs': delete_old_docs(config, *args) elif command == 'send_comments': send_comments(*args) elif command == 'mergeuser': merge_user(*args) elif command == 'nuke_nested_lists': nuke_nested_lists(*args) else: print "unknown command '%s'!"%command st.changed() finally: st.close()
[ 198, 11748, 25064, 11, 28686, 11, 2956, 297, 571, 11, 10903, 9399, 11, 12854, 1891, 11, 269, 12397, 11, 9874, 292, 979, 72, 11, 651, 8738, 11, 4423, 346, 198, 11748, 19974, 7753, 11, 308, 13344, 11, 13422, 7753, 198, 2, 17597, 13, ...
2.248602
1,609
import random import re import six from itertools import izip from geodata.address_expansions.gazetteers import * from geodata.encoding import safe_decode, safe_encode from geodata.text.normalize import normalized_tokens from geodata.text.tokenize import tokenize_raw, token_types from geodata.text.utils import non_breaking_dash_regex def equivalent(s1, s2, gazetteer, language): ''' Address/place equivalence ------------------------- OSM discourages abbreviations, but to make our training data map better to real-world input, we can safely replace the canonical phrase with an abbreviated version and retain the meaning of the words ''' tokens_s1 = normalized_tokens(s1) tokens_s2 = normalized_tokens(s2) abbreviated_s1 = list(abbreviations_gazetteer.filter(tokens_s1)) abbreviated_s2 = list(abbreviations_gazetteer.filter(tokens_s2)) if len(abbreviated_s1) != len(abbreviated_s2): return False for ((t1, c1, l1, d1), (t2, c2, l2, d2)) in izip(abbreviated_s1, abbreviated_s2): if c1 != token_types.PHRASE and c2 != token_types.PHRASE: if t1 != t2: return False elif c2 == token_types.PHRASE and c2 == token_types.PHRASE: canonicals_s1 = canonicals_for_language(d1, language) canonicals_s2 = canonicals_for_language(d2, language) if not canonicals_s1 & canonicals_s2: return False else: return False return True
[ 11748, 4738, 198, 11748, 302, 198, 11748, 2237, 198, 198, 6738, 340, 861, 10141, 1330, 220, 528, 541, 198, 198, 6738, 4903, 375, 1045, 13, 21975, 62, 11201, 504, 507, 13, 70, 1031, 5857, 364, 1330, 1635, 198, 6738, 4903, 375, 1045, ...
2.4096
625
num = 1 while num <= 10: # Fill in the condition x = num ** 2# Print num squared num = num + 1# Increment num (make sure to do this!) print x print num
[ 22510, 796, 352, 198, 198, 4514, 997, 19841, 838, 25, 220, 1303, 27845, 287, 262, 4006, 198, 220, 220, 220, 2124, 796, 997, 12429, 362, 2, 12578, 997, 44345, 198, 220, 220, 220, 997, 796, 997, 1343, 352, 2, 10791, 434, 997, 357, 1...
2.741935
62
from setuptools import setup, find_packages setup( name='udptest', version='0.1.0', description='UDP benchmarking/testing tool.', long_description=open('README.rst').read(), url='https://github.com/povilasb/httpmeter', author='Povilas Balciunas', author_email='balciunas90@gmail.com', license='MIT', packages=find_packages(exclude=('tests')), entry_points={ 'console_scripts': [ 'udptestd = udptest.server:main', 'udptest = udptest.client:main', ] }, classifiers=[ 'Programming Language :: Python :: 3.6', 'Operating System :: POSIX :: Linux', 'Natural Language :: English', 'Development Status :: 3 - Alpha', 'Topic :: System :: Networking', 'Topic :: Internet :: UDP', ], install_requires=requirements(), )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 628, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 11639, 463, 457, 395, 3256, 198, 220, 220, 220, 2196, 11639, 15, 13, 16, 13, 15, 3256, 198, 220, 220, 220, 6764, 11639, 5...
2.364641
362
from __future__ import division import numpy as np from untwist import data from untwist import transforms def target_accompaniment(target, others, sample_rate=None): """ Given a target source and list of 'other' sources, this function returns the target and accompaniment as untwist.data.audio.Wave objects. The accompaniment is defined as the sum of the other sources. Parameters ---------- target : np.ndarray or Wave, shape=(num_samples, num_channels) The true target source. others : List or single np.ndarray or Wave object Each object should have the shape=(num_samples, num_channels) If a single array is given, this should correspond to the accompaniment. sample_rate : int, optional Only needed if Wave objects not provided. Returns ------- target : Wave, shape=(num_samples, num_channels) accompaniment : Wave, shape=(num_samples, num_channels) """ if isinstance(others, list): if not isinstance(others[0], data.audio.Wave): others = [data.audio.Wave(_, sample_rate) for _ in others] accompaniment = sum(other for other in others) else: if not isinstance(others, data.audio.Wave): others = data.audio.Wave(others, sample_rate) accompaniment = others if not isinstance(target, data.audio.Wave): target = data.audio.Wave(target, sample_rate) return target, accompaniment def stft_istft(num_points=2048, window='hann'): """ Returns an STFT and an ISTFT Processor object, both configured with the same window and transform length. These objects are to be used as follows: >>> stft, istft = stft_istft() >>> x = untwist.data.audio.Wave.tone() # Or some Wave >>> y = stft.process(x) >>> x = istft.process(y) Parameters ---------- num_points : int The number of points to use for the window and the fft transform. window : str The type of window to use. Returns ------- stft : untwist.transforms.stft.STFT An STFT processor. itft : untwist.transforms.stft.ITFT An ISTFT processor. """ stft = transforms.STFT(window, num_points, num_points // 2) istft = transforms.ISTFT(window, num_points, num_points // 2) return stft, istft def ensure_audio_doesnt_clip(list_of_arrays): """ Takes a list of arrays and scales them by the same factor such that none clip. Parameters ---------- list_of_arrays : list A list of array_like objects Returns ------- new_list_of_arrays : list A list of scaled array_like objects. """ max_peak = 1 for audio in list_of_arrays: audio_peak = np.max(np.abs(audio)) if audio_peak > max_peak: max_peak = audio_peak if max_peak >= 1: print('Warning: Audio has been attenuated to prevent clipping') gain = 0.999 / max_peak new_list_of_arrays = [] for audio in list_of_arrays: new_list_of_arrays.append(audio * gain) else: new_list_of_arrays = list_of_arrays return new_list_of_arrays
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1418, 86, 396, 1330, 1366, 198, 6738, 1418, 86, 396, 1330, 31408, 628, 198, 4299, 2496, 62, 41974, 3681, 7, 16793, 11, 1854, 11, 6291, 62, 4873, 28, ...
2.588997
1,236
import os import re
[ 11748, 28686, 198, 11748, 302 ]
3.8
5
from unittest import TestCase
[ 6738, 555, 715, 395, 1330, 6208, 20448, 628 ]
3.875
8
''' Statement Fibonacci numbers are the numbers in the integer sequence starting with 1, 1 where every number after the first two is the sum of the two preceding ones: 1, 1, 2, 3, 5, 8, 13, 21, 34, ... Given a positive integer n, print the nth Fibonacci number. Example input 6 Example output 8 ''' num = int(input()) before, curr, i = 0, 1, 1 while num > i: before, curr = curr, curr + before i += 1 print(curr)
[ 7061, 6, 198, 48682, 198, 37, 571, 261, 44456, 3146, 389, 262, 3146, 287, 262, 18253, 8379, 3599, 351, 352, 11, 352, 810, 790, 1271, 706, 262, 717, 734, 318, 262, 2160, 286, 262, 734, 18148, 3392, 25, 198, 198, 16, 11, 352, 11, ...
2.865772
149
from src.sum_up import *
[ 6738, 12351, 13, 16345, 62, 929, 1330, 1635 ]
3
8
# -*- coding: utf-8 -*- """ Created on Fri Jul 13 15:38:11 2018 @author: Yekta """ import csv import numpy as np from sklearn.cluster import KMeans clon = list(csv.reader(open("C:/Users/Yekta/Desktop/stajvol3/MoS2BP Binding Characterization_07-11-17_DY.csv"))) for k in range(1,15): fin=[] for m in range(1,13): dataFromCSV = list(csv.reader(open("C:/Users/Yekta/Desktop/stajvol3/573x96/recon/location"+str(m)+"/PCA"+str(k)+".csv"))) dataFromCSV=np.asarray(dataFromCSV) dataFromCSV=dataFromCSV.T temp=dataFromCSV[1:,1:] temp=temp.astype(np.float) #clusters according to properties kmeans = KMeans(n_clusters = 3, init = 'k-means++', random_state = 42) y_kmeans = kmeans.fit_predict(temp) fin.append(y_kmeans) fin=np.asarray(fin) fin=fin.T matrix = [[0 for x in range(13)] for y in range(97)] matrix[0][0]="Index" for z in range(1,97): matrix[z][0]=clon[z+1][11] for x in range(1,13): matrix[0][x]=x for y in range(1,97): matrix[y][x]=fin[y-1,x-1] matrix=np.asarray(matrix) with open("C:/Users/Yekta/Desktop/stajvol3/573x96/cluster/clusteredPCA"+str(k)+".csv", 'w', newline='') as myfile: wr = csv.writer(myfile) wr.writerows(matrix)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 41972, 319, 19480, 5979, 1511, 1315, 25, 2548, 25, 1157, 2864, 201, 198, 201, 198, 31, 9800, 25, 575, 988, 8326, 201, 198, 37811, 201, 198, 201, ...
1.905817
722
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_collision.test_discretedynamicsworld """ from __future__ import unicode_literals, print_function, absolute_import import unittest import bullet from .test_worlds import WorldTestDataMixin
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 9288, 62, 26000, 1166, 13, 9288, 62, 15410, 1186, 276, 4989, 873, 6894, 198, 37811, 198, 6738, 11593, 37443...
2.940476
84
# (C) Copyright 2010-2020 Enthought, Inc., Austin, TX # All rights reserved. import unittest from force_wfmanager.notifications.ui_notification_hooks_manager \ import \ UINotificationHooksManager from force_wfmanager.notifications.ui_notification_plugin import \ UINotificationPlugin
[ 2, 220, 357, 34, 8, 15069, 3050, 12, 42334, 2039, 28895, 11, 3457, 1539, 9533, 11, 15326, 198, 2, 220, 1439, 2489, 10395, 13, 198, 198, 11748, 555, 715, 395, 198, 198, 6738, 2700, 62, 86, 35826, 3536, 13, 1662, 6637, 13, 9019, 62,...
3.071429
98
from django.shortcuts import redirect from .models import UserLanguage
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 18941, 198, 198, 6738, 764, 27530, 1330, 11787, 32065, 628 ]
4.294118
17
money = 2000 print(money) # money5000money money += 5000 # money print (money)
[ 26316, 796, 4751, 198, 4798, 7, 26316, 8, 198, 198, 2, 1637, 27641, 26316, 198, 26316, 15853, 23336, 198, 198, 2, 1637, 198, 4798, 357, 26316, 8 ]
2.962963
27
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import redirect, request, url_for from flask.views import MethodView from flask.ext.security import current_user
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 42903, 1330, 18941, 11, 2581, 11, 19016, 62, 1640, 198, 6738, 42903, 13, 33571, 1330, 11789, 7680, 198, 6738...
3.185185
54
"""Randomised linear algebra.""" import numpy.linalg as la
[ 37811, 29531, 1417, 14174, 37139, 526, 15931, 198, 198, 11748, 299, 32152, 13, 75, 1292, 70, 355, 8591, 628 ]
3.210526
19
from bt_utils.console import Console from bt_utils.config import cfg from bt_utils.embed_templates import SuccessEmbed, WarningEmbed from bt_utils.handle_sqlite import DatabaseHandler SHL = Console('BundestagsBot Reload') DB = DatabaseHandler() settings = { 'name': 'reload', 'channels': ['team'], 'mod_cmd': True }
[ 6738, 275, 83, 62, 26791, 13, 41947, 1330, 24371, 198, 6738, 275, 83, 62, 26791, 13, 11250, 1330, 30218, 70, 198, 6738, 275, 83, 62, 26791, 13, 20521, 62, 11498, 17041, 1330, 16282, 31567, 276, 11, 15932, 31567, 276, 198, 6738, 275, ...
2.903509
114
#! /usr/bin/env python2.7 import getopt, sys, time, util from wmbus import WMBusFrame from Crypto.Cipher import AES if __name__ == "__main__": main(sys.argv[1:]) ''' Class Scanner(threading.Thread): def __init__(self,dev): #something here that initialize serial port def run(): while True: def pack(self): #something def checksum(self): #something def write(self): #something '''
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 17, 13, 22, 198, 198, 11748, 651, 8738, 11, 25064, 11, 640, 11, 7736, 198, 6738, 266, 2022, 385, 1330, 370, 10744, 385, 19778, 198, 6738, 36579, 13, 34, 10803, 1330, 34329, 198, 220, ...
2.123932
234
# encoding: utf-8 # module gi._gi # from /usr/lib/python3/dist-packages/gi/_gi.cpython-35m-x86_64-linux-gnu.so # by generator 1.145 # no doc # imports import _gobject as _gobject # <module '_gobject'> import _glib as _glib # <module '_glib'> import gi as __gi import gobject as __gobject from .object import object
[ 2, 21004, 25, 3384, 69, 12, 23, 198, 2, 8265, 308, 72, 13557, 12397, 198, 2, 422, 1220, 14629, 14, 8019, 14, 29412, 18, 14, 17080, 12, 43789, 14, 12397, 47835, 12397, 13, 13155, 7535, 12, 2327, 76, 12, 87, 4521, 62, 2414, 12, 23...
2.622951
122
#!/usr/bin/env python # -*- coding: utf-8 -*- from selecta import __version__ from setuptools import setup options = dict( name='python-selecta', version=__version__, url='http://github.com/ntamas/python-selecta', description='Python port of @garybernhardt/selecta', license='MIT', author='Tamas Nepusz', author_email='ntamas@gmail.com', package_dir={'selecta': 'selecta'}, packages=['selecta'], entry_points={ "console_scripts": [ 'selecta = selecta.__main__:main' ] }, test_suite="tests", platforms='ALL', classifiers=[ # TODO 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python' ] ) setup(**options)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 2922, 64, 1330, 11593, 9641, 834, 198, 6738, 900, 37623, 10141, 1330, 9058, 628, 198, 25811, 796, 8633, 7, ...
2.428152
341
# cython: language_level=3 from distutils.core import setup, Extension from Cython.Build import cythonize import numpy # import cython_utils import os os.environ["CC"] = "/opt/homebrew/Cellar/gcc/11.2.0_3/bin/g++-11" os.environ["CXX"] = "/opt/homebrew/Cellar/gcc/11.2.0_3/bin/g++-11" setup(ext_modules=cythonize(["graphsaint/cython_sampler.pyx", "graphsaint/cython_utils.pyx", "graphsaint/norm_aggr.pyx"]), include_dirs=[numpy.get_include()]) # to compile: python graphsaint/setup.py build_ext --inplace
[ 2, 3075, 400, 261, 25, 3303, 62, 5715, 28, 18, 201, 198, 6738, 1233, 26791, 13, 7295, 1330, 9058, 11, 27995, 201, 198, 6738, 327, 7535, 13, 15580, 1330, 3075, 400, 261, 1096, 201, 198, 11748, 299, 32152, 201, 198, 2, 1330, 3075, 4...
2.312775
227
import sys def get_network(args): """ return given network """ if args.MODEL.NAME == 'vgg16': from models.vgg import vgg16_bn net = vgg16_bn() elif args.MODEL.NAME == 'vgg13': from models.vgg import vgg13_bn net = vgg13_bn() elif args.MODEL.NAME == 'vgg11': from models.vgg import vgg11_bn net = vgg11_bn() elif args.MODEL.NAME == 'vgg19': from models.vgg import vgg19_bn net = vgg19_bn() elif args.MODEL.NAME == 'densenet121': from models.densenet import densenet121 net = densenet121() elif args.MODEL.NAME == 'densenet161': from models.densenet import densenet161 net = densenet161() elif args.MODEL.NAME == 'densenet169': from models.densenet import densenet169 net = densenet169() elif args.MODEL.NAME == 'densenet201': from models.densenet import densenet201 net = densenet201() elif args.MODEL.NAME == 'googlenet': from models.googlenet import googlenet net = googlenet() elif args.MODEL.NAME == 'inceptionv3': from models.inceptionv3 import inceptionv3 net = inceptionv3() elif args.MODEL.NAME == 'inceptionv4': from models.inceptionv4 import inceptionv4 net = inceptionv4() elif args.MODEL.NAME == 'inceptionresnetv2': from models.inceptionv4 import inception_resnet_v2 net = inception_resnet_v2() elif args.MODEL.NAME == 'xception': from models.xception import xception net = xception() elif args.MODEL.NAME == 'resnet18': from models.resnet import resnet18 net = resnet18() elif args.MODEL.NAME == 'resnet34': from models.resnet import resnet34 net = resnet34() elif args.MODEL.NAME == 'resnet50': from models.resnet import resnet50 net = resnet50() elif args.MODEL.NAME == 'resnet101': from models.resnet import resnet101 net = resnet101() elif args.MODEL.NAME == 'resnet152': from models.resnet import resnet152 net = resnet152() elif args.MODEL.NAME == 'preactresnet18': from models.preactresnet import preactresnet18 net = preactresnet18() elif args.MODEL.NAME == 'preactresnet34': from models.preactresnet import preactresnet34 net = preactresnet34() elif args.MODEL.NAME == 'preactresnet50': from models.preactresnet import preactresnet50 net = preactresnet50() elif args.MODEL.NAME == 'preactresnet101': from models.preactresnet import preactresnet101 net = preactresnet101() elif args.MODEL.NAME == 'preactresnet152': from models.preactresnet import preactresnet152 net = preactresnet152() elif args.MODEL.NAME == 'resnext50': from models.resnext import resnext50 net = resnext50() elif args.MODEL.NAME == 'resnext101': from models.resnext import resnext101 net = resnext101() elif args.MODEL.NAME == 'resnext152': from models.resnext import resnext152 net = resnext152() elif args.MODEL.NAME == 'shufflenet': from models.shufflenet import shufflenet net = shufflenet() elif args.MODEL.NAME == 'shufflenetv2': from models.shufflenetv2 import shufflenetv2 net = shufflenetv2() elif args.MODEL.NAME == 'squeezenet': from models.squeezenet import squeezenet net = squeezenet() elif args.MODEL.NAME == 'mobilenet': from models.mobilenet import mobilenet net = mobilenet() elif args.MODEL.NAME == 'mobilenetv2': from models.mobilenetv2 import mobilenetv2 net = mobilenetv2() elif args.MODEL.NAME == 'nasnet': from models.nasnet import nasnet net = nasnet() elif args.MODEL.NAME == 'attention56': from models.attention import attention56 net = attention56() elif args.MODEL.NAME == 'attention92': from models.attention import attention92 net = attention92() elif args.MODEL.NAME == 'seresnet18': from models.senet import seresnet18 net = seresnet18() elif args.MODEL.NAME == 'seresnet34': from models.senet import seresnet34 net = seresnet34() elif args.MODEL.NAME == 'seresnet50': from models.senet import seresnet50 net = seresnet50() elif args.MODEL.NAME == 'seresnet101': from models.senet import seresnet101 net = seresnet101() elif args.MODEL.NAME == 'seresnet152': from models.senet import seresnet152 net = seresnet152() elif args.MODEL.NAME == 'wideresnet': from models.wideresidual import wideresnet net = wideresnet() elif args.MODEL.NAME == 'stochasticdepth18': from models.stochasticdepth import stochastic_depth_resnet18 net = stochastic_depth_resnet18() elif args.MODEL.NAME == 'stochasticdepth34': from models.stochasticdepth import stochastic_depth_resnet34 net = stochastic_depth_resnet34() elif args.MODEL.NAME == 'stochasticdepth50': from models.stochasticdepth import stochastic_depth_resnet50 net = stochastic_depth_resnet50() elif args.MODEL.NAME == 'stochasticdepth101': from models.stochasticdepth import stochastic_depth_resnet101 net = stochastic_depth_resnet101() elif args.MODEL.NAME == 'vit': from models.vit import vit net =vit() else: print('the network name you have entered is not supported yet') sys.exit() if args.MODEL.USE_GPU: # use_gpu net = net.cuda() return net
[ 11748, 25064, 628, 198, 4299, 651, 62, 27349, 7, 22046, 2599, 198, 197, 37811, 1441, 1813, 3127, 198, 197, 37811, 198, 197, 361, 26498, 13, 33365, 3698, 13, 20608, 6624, 705, 85, 1130, 1433, 10354, 198, 197, 197, 6738, 4981, 13, 85, ...
2.559628
1,937
import pytest from hypothesis import ( given, settings, strategies as st, ) from eth_utils import ( ValidationError, ) from eth.constants import ( ZERO_HASH32, ) from eth2.beacon.committee_helpers import ( get_crosslink_committees_at_slot, ) from eth2.beacon.state_machines.forks.serenity.block_validation import ( validate_attestation_aggregate_signature, validate_attestation_latest_crosslink_root, validate_attestation_justified_block_root, validate_attestation_justified_epoch, validate_attestation_crosslink_data_root, validate_attestation_slot, ) from eth2.beacon.tools.builder.validator import ( create_mock_signed_attestation, ) from eth2.beacon.types.attestation_data import AttestationData from eth2.beacon.types.crosslink_records import CrosslinkRecord
[ 11748, 12972, 9288, 198, 6738, 14078, 1330, 357, 198, 220, 220, 220, 1813, 11, 198, 220, 220, 220, 6460, 11, 198, 220, 220, 220, 10064, 355, 336, 11, 198, 8, 198, 198, 6738, 4555, 62, 26791, 1330, 357, 198, 220, 220, 220, 3254, 24...
2.812287
293
########################################################################################################### ########################################################################################################### ## SeqtaToSDS ## ## Jacob Curulli ## ## This code is shared as is, under Creative Commons Attribution Non-Commercial 4.0 License ## ## Permissions beyond the scope of this license may be available at http://creativecommons.org/ns ## ########################################################################################################### # Read Me # This script will likely not work out of the box and will need to be customised # 1. The approvedClassesCSV is a list of classes in Seqta that will be exported, # the list is checked against the 'name' column in the public.classunit table. # 2. A directory called 'sds' will need to be created in the root of where the script is run. # 3. This script allows for an admin user to be added to every class (section) # import required modules # psycopg2 isn't usually included with python and may need to be installed separately # see www.psycopg.org for instructions import psycopg2 import csv import os.path import configparser from datetime import datetime # Get the date dateNow = datetime.now() # Read the config.ini file config = configparser.ConfigParser() config.read('config.ini') # read config file for seqta database connection details db_user=config['db']['user'] db_port=config['db']['port'] db_password=config['db']['password'] db_database=config['db']['database'] db_host=config['db']['host'] db_sslmode=config['db']['sslmode'] # read config file for school details teamsAdminUsername=config['school']['teamsAdminUsername'] teamsAdminFirstName=config['school']['teamsAdminFirstName'] teamsAdminLastName=config['school']['teamsAdminLastName'] teamsAdminID=config['school']['teamsAdminID'] schoolName =config['school']['schoolName'] schoolSISId=config['school']['schoolSISId'] classTermName=config['school']['classTermName'] # declare some variables here so we can make sure they are present staffList = set() studentList = set() classArray = tuple() currentYear = dateNow.strftime("%Y") print("current year is:", currentYear) # file locations, this can be changed to suit your environment csvApprovedClasses = "approved_classes.csv" csvSchoolFilename = "sds/School.csv" csvSectionFileName = "sds/Section.csv" csvStudentFileName = "sds/Student.csv" csvTeacherFileName = "sds/Teacher.csv" csvTeacherRosterFileName = "sds/TeacherRoster.csv" csvStudentEnrollmentFileName = "sds/StudentEnrollment.csv" # remove the csv files if they already exist. This is a messy way of doing it but I learnt python 2 days ago so whatever if os.path.exists(csvSchoolFilename): os.remove(csvSchoolFilename) if os.path.exists(csvSectionFileName): os.remove(csvSectionFileName) if os.path.exists(csvStudentFileName): os.remove(csvStudentFileName) if os.path.exists(csvTeacherFileName): os.remove(csvTeacherFileName) if os.path.exists(csvTeacherRosterFileName): os.remove(csvTeacherRosterFileName) if os.path.exists(csvStudentEnrollmentFileName): os.remove(csvStudentEnrollmentFileName) try: # Import CSV file for approved class lists with open(csvApprovedClasses, newline='', encoding='utf-8-sig') as csvfile: classList = list(csv.reader(csvfile)) print (type(classList)) print (classList) print ("Number of classes imported from csv list: ",len(classList)) except: print("***************************") print("Error importing csv file") # Open connection to Seqta try: connection = psycopg2.connect(user=db_user, port=db_port, password=db_password, database=db_database, host = db_host, sslmode = db_sslmode) cursor = connection.cursor() print(connection.get_dsn_parameters(), "\n") except (Exception, psycopg2.Error) as error: print("Error while connecting to PostgreSQL", error) # Fetch data for classlists try: for i in classList: className = str(('[%s]' % ', '.join(map(str, (i))))[1:-1]) print ("**") print (className) # Print PostgreSQL version cursor.execute("SELECT version();") record = cursor.fetchone() # Lookup classID from Class name in Seqta sq_classUnitQuery = "SELECT * FROM public.classunit WHERE name = (%s);" cursor.execute(sq_classUnitQuery,(className,)) classUnitPull = cursor.fetchall() print("Getting class information for:", (className)) for row in classUnitPull: classUnitID = row[0] classSubjectID = row[4] classTermID = row[7] print("Class unit ID (classUnitID) is:", classUnitID) print("Class subject ID (classSubjectID) is:", classSubjectID) print("Class term ID (classTermID) is:", classTermID) # Check if class has a staff member or students # If they don't we need to stop processing the class and drop it gracefully # Get subject description for Class sq_classSubjectQuery = "SELECT * FROM subject WHERE id = (%s);" cursor.execute(sq_classSubjectQuery, (classSubjectID,)) classSubjectPull = cursor.fetchall() for row in classSubjectPull: classSubjectDescription = row[3] classSubjectName = row[2] classTeamName = (className + " - " + classSubjectDescription) print("Class subject Description (classSubjectDescription) is:", classSubjectDescription) print("Class team name (classTeamName) is:", classTeamName) print("Class subject Name (classSubjectName) is:", classSubjectName) # Get StaffID in this classUnit sq_staffIDQuery = "SELECT staff from public.classinstance WHERE classunit = (%s) and date <= current_date ORDER BY id DESC LIMIT 1;" cursor.execute(sq_staffIDQuery, (classUnitID,)) staffID_pre = cursor.fetchone() if staffID_pre is None: print("Couldn't find a class today or previously for classunit:", classUnitID) print("Checking for a class up to 14 days in the future and selecting the closest date to today") sq_staffIDQuery = "SELECT staff from public.classinstance WHERE classunit = (%s) date = current_date + interval '14 day' ORDER BY id DESC LIMIT 1;" cursor.execute(sq_staffIDQuery, (classUnitID,)) staffID_pre = cursor.fetchone() staffID = int(staffID_pre[0]) print("Staff ID is:", (staffID)) # Write to teacher ID list staffList.add(staffID) else: staffID = int(staffID_pre[0]) print("Staff ID is:", (staffID)) # Write to teacher ID list staffList.add(staffID) # Get Student ID's for this classUnit sq_studentIDListQuery = "SELECT student from \"classunitStudent\" WHERE classunit = (%s) and removed is NULL;" cursor.execute(sq_studentIDListQuery, (classUnitID,)) studentIDArray = tuple([r[0] for r in cursor.fetchall()]) print("List of students in class name:", className) print(studentIDArray) for row in studentIDArray: studentList.add(row) # Check if the csv section file exists csvSectionFileExists = os.path.isfile(csvSectionFileName) # Write to the section csv file with open(csvSectionFileName, 'a', newline='') as csvSection: writer = csv.writer(csvSection) # If the csv doesn't exist already we'll need to put in the headers if not csvSectionFileExists: writer.writerow(["SIS ID", "School SIS ID", "Section Name", "Section Number", "Term SIS ID", "Term Name", "Course SIS ID", "Course Name", "Course Description"]) writer.writerow([(classUnitID), (schoolSISId), (classTeamName), (classUnitID), (classTermID), (classTermName), (classUnitID), (classSubjectName), (classSubjectDescription)]) print ("Writing class section row") # Check if the csv teacher roster file exists csvTeacherRosterFileExists = os.path.isfile(csvTeacherRosterFileName) # Write to the teacher roster csv file with open(csvTeacherRosterFileName, 'a', newline='') as csvTeacherRoster: writer = csv.writer(csvTeacherRoster) # If the csv doesn't exist already we'll need to put in the headers if not csvTeacherRosterFileExists: writer.writerow(["Section SIS ID", "SIS ID"]) writer.writerow([(classUnitID), (staffID)]) # Also include the Teams Admin account as a teacher writer.writerow([(classUnitID), (teamsAdminID)]) print("Written staff to roster") # Check if the csv student enrollment file exists csvStudentEnrollmentFileNameExists = os.path.isfile(csvStudentEnrollmentFileName) # Write to the student enrollment csv file with open(csvStudentEnrollmentFileName, 'a', newline='') as csvStudentEnrollment: writer = csv.writer(csvStudentEnrollment) # If the csv doesn't exist already we'll need to put in the headers if not csvStudentEnrollmentFileNameExists: writer.writerow(["Section SIS ID", "SIS ID"]) for studentInArray in studentIDArray: writer.writerow([(classUnitID), (studentInArray)]) except: print("") print("***************************") print("Error fetching class list data") print("") # Now we will fetch the staff information try: print("Print the staff lists now") print(staffList) for staff in staffList: # Now get the staff information sq_staffQuery = "SELECT * from public.staff WHERE id = (%s);" cursor.execute(sq_staffQuery, (staff,)) staffPull = cursor.fetchall() for row in staffPull: staffFirstName = row[4] staffLastName = row[7] staffUsername = row[21] print("Staff First Name (staffFirstName) is:", staffFirstName) print("Staff Last Name (staffLastName) is:", staffLastName) print("Staff username (staffUsername) is:", staffUsername) print("Staff ID is (staff) is:", staff) # Now we write this information to the Teacher.csv file # Check if the csv teacher file exists csvTeacherFileNameExists = os.path.isfile(csvTeacherFileName) # Write to the teacher csv file with open(csvTeacherFileName, 'a', newline='') as csvTeacher: writer = csv.writer(csvTeacher) # If the csv doesn't exist already we'll need to put in the headers if not csvTeacherFileNameExists: writer.writerow(["SIS ID", "School SIS ID", "First Name", "Last Name", "Username", "Teacher Number"]) # Also include the Teams Admin user as a teacher writer.writerow( [(teamsAdminID), (schoolSISId), (teamsAdminFirstName), (teamsAdminLastName), (teamsAdminUsername), (teamsAdminID)]) writer.writerow([(staff), (schoolSISId), (staffFirstName), (staffLastName), (staffUsername), (staff)]) except: print("something went wrong getting the staff data") # Now we will fetch the student information try: print("Print the student lists now") print(studentList) for student in studentList: # Now get the student information sq_studentQuery = "SELECT * from student WHERE id = (%s) AND status = 'FULL';" cursor.execute(sq_studentQuery, (student,)) studentPull = cursor.fetchall() for row in studentPull: studentFirstName = row[3] studentLastName = row[6] studentUsername = row[47] print("Student First Name (studentFirstName) is:", studentFirstName) print("Student Last Name (studentLastName) is:", studentLastName) print("Student username (studentUsername) is:", studentUsername) print("Student ID is (student) is:", student) # Now we write this information to the Student.csv file # Check if the csv Student file exists csvStudentFileNameExists = os.path.isfile(csvStudentFileName) # Write to the student enrollment csv file with open(csvStudentFileName, 'a', newline='') as csvStudent: writer = csv.writer(csvStudent) # If the csv doesn't exist already we'll need to put in the headers if not csvStudentFileNameExists: writer.writerow(["SIS ID", "School SIS ID", "First Name", "Last Name", "Username", "Student Number"]) writer.writerow([(student), (schoolSISId), (studentFirstName), (studentLastName), (studentUsername), (student)]) except: print("something went wrong getting the student data") # write the School.csv file try: with open('sds/School.csv', 'a', newline='') as csvSchool: writer = csv.writer(csvSchool) writer.writerow(["SIS ID","Name"]) writer.writerow([(schoolSISId),(schoolName)]) except: print("something went wrong writing the school csv file") finally: # closing database connection. if (connection): cursor.close() connection.close() print("PostgreSQL connection is closed")
[ 29113, 29113, 29113, 7804, 21017, 198, 29113, 29113, 29113, 7804, 21017, 198, 2235, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220...
2.5868
5,288
""" """ import os from PIL import Image from numpy import * def get_imlist(path): """ JPG :param path: :return: """ return [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.jpg')] def imresize(im, sz): """ :param im: :param sz: :return: """ pil_im = Image.fromarray(uint8(im)) return array(pil_im.resize(sz)) print(get_imlist('.'))
[ 37811, 198, 198, 37811, 198, 11748, 28686, 198, 6738, 350, 4146, 1330, 7412, 198, 6738, 299, 32152, 1330, 1635, 198, 198, 4299, 651, 62, 320, 4868, 7, 6978, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 449, 6968, 198, 220, 2...
2.081218
197
from django.shortcuts import ( render, redirect, reverse, get_object_or_404, HttpResponse) from django.contrib import messages from shop.models import Product from members.models import Member def load_cart(request): """This view render's the user's cart contents""" return render(request, 'cart/cart.html') def add_item_to_cart(request, item_id): """This view lets the user add an item to their shopping cart""" item = get_object_or_404(Product, pk=item_id) quantity = int(request.POST.get('quantity')) redirect_url = request.POST.get('redirect_url') size = None if 'item_size' in request.POST: size = request.POST['item_size'] cart = request.session.get('cart', {}) if size: if item_id in list(cart.keys()): if size in cart[item_id]['items_by_size'].keys(): cart[item_id]['items_by_size'][size] += quantity messages.success(request, f'Updated size {size.upper()} ' f'of {item.friendly_name} to ' f'{cart[item_id]["items_by_size"][size]}') else: cart[item_id]['items_by_size'][size] = quantity messages.success(request, f'Added {quantity}x ' f'{item.friendly_name} in {size.upper()}') else: cart[item_id] = {'items_by_size': {size: quantity}} messages.success(request, f'Added {quantity}x {item.friendly_name}' f' in size {size.upper()}') else: if item_id in list(cart.keys()): cart[item_id] += quantity messages.success(request, f'Added {quantity}x {item.friendly_name}' f' to your cart. You now have {cart[item_id]} of' f' {item.friendly_name} in your cart') else: cart[item_id] = quantity messages.success(request, f'{cart[item_id]}x {item.friendly_name} ' f'was added to your cart') request.session['cart'] = cart return redirect(redirect_url) def update_cart(request, item_id): """This view lets the user update the quantity of an item in their cart""" item = get_object_or_404(Product, pk=item_id) quantity = int(request.POST.get('quantity')) size = None if 'item_size' in request.POST: size = request.POST['item_size'] cart = request.session.get('cart', {}) if size: if quantity > 99: messages.error(request, 'You cannot add this many units of a ' 'product. The maximum possible quantity is 99. ' 'Please enter a quantity within the accepted ' 'range.') elif quantity > 0: cart[item_id]['items_by_size'][size] = quantity messages.success(request, f'Updated quantity of ' f'{item.friendly_name} in size {size.upper()} ' f'to to {cart[item_id]["items_by_size"][size]}.') else: del cart[item_id]['items_by_size'][size] if not cart[item_id]['items_by_size']: cart.pop(item_id) messages.success(request, f'Removed {item.friendly_name} in size ' f'{size.upper()} from your cart.') else: if quantity > 99: messages.error(request, 'You cannot add this many units of a ' 'product. The maximum possible quantity is 99. ' 'Please enter a quantity within the accepted ' 'range.') elif quantity > 0: cart[item_id] = quantity messages.success(request, f'Successfully updated quantity of ' f'{item.friendly_name} to {cart[item_id]}.') else: cart.pop(item_id) messages.success(request, f'{item.friendly_name} was removed from ' 'your cart.') request.session['cart'] = cart return redirect(reverse('load_cart')) def remove_item_from_cart(request, item_id): """This view lets the user delete an item from their shopping cart""" try: item = get_object_or_404(Product, pk=item_id) size = None if 'item_size' in request.POST: size = request.POST['item_size'] cart = request.session.get('cart', {}) if size: del cart[item_id]['items_by_size'][size] if not cart[item_id]['items_by_size']: cart.pop(item_id) messages.success(request, f'Removed {item.friendly_name} in size ' f'{size.upper()} from your cart.') else: cart.pop(item_id) messages.success(request, f'{item.friendly_name} was deleted from ' 'your cart.') request.session['cart'] = cart return HttpResponse(status=200) except Exception as e: messages.error(request, f'There was a a problem removing the item.' '{e}') return HttpResponse(status=500)
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 357, 198, 220, 220, 220, 8543, 11, 18941, 11, 9575, 11, 651, 62, 15252, 62, 273, 62, 26429, 11, 367, 29281, 31077, 8, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 6218, 198, 6738, 6128, 1...
2.062798
2,516
from confess import app from confess.config import PORT, DEBUG if __name__ == '__main__': app.run( host='0.0.0.0', port=PORT, debug=DEBUG )
[ 6738, 22127, 1330, 598, 198, 6738, 22127, 13, 11250, 1330, 350, 9863, 11, 16959, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 598, 13, 5143, 7, 198, 220, 220, 220, 220, 220, 220, 220, 2583,...
2.15
80
""" Plots analysis on the workflow variables for experiments with different workflow types and different %of workflow core hours in the workload. Resuls are plotted as barchars that show how much the vas deviate in single and multi from aware. """ import matplotlib from orchestration import get_central_db from orchestration.definition import ExperimentDefinition from plot import (plot_multi_bars, produce_plot_config, extract_results, gen_trace_ids_exps, calculate_diffs, get_args, join_rows, replace) from stats.trace import ResultTrace # remote use no Display matplotlib.use('Agg') base_trace_id_percent, lim = get_args(2459, True) print("Base Exp", base_trace_id_percent) print("Using analysis of limited workflows:", lim) db_obj = get_central_db() edge_keys= {0: "[0,48] core.h", 48*3600:"(48, 960] core.h", 960*3600:"(960, inf.) core.h"} trace_id_rows = [] base_exp=170 exp=ExperimentDefinition() exp.load(db_obj, base_exp) core_seconds_edges=exp.get_machine().get_core_seconds_edges() # trace_id_rows = [ # [ 4166, 4167, 4168, 4184, 4185, 4186, 4202, 4203, 4204, # 4220, 4221, 4222, 4238, 4239, 4240 ], # [ 4169, 4170, 4171, 4187, 4188, 4189, 4205, 4206, 4207, # 4223, 4224, 4225, 4241, 4242, 4243 ], # [ 4172, 4173, 4174, 4190, 4191, 4192, 4208, 4209, 4210, # 4226, 4227, 4228, 4244, 4245, 4246 ], # [ 4175, 4176, 4177, 4193, 4194, 4195, 4211, 4212, 4213, # 4229, 4230, 4231, 4247, 4248, 4249], # [ 4178, 4179, 4180, 4196, 4197, 4198, 4214, 4215, 4216, # 4232, 4233, 4234, 4250, 4251, 4252], # [ 4181, 4182, 4183, 4199, 4200, 4201, 4217, 4218, 4219, # 4235, 4236, 4237, 4253, 4254, 4255], # ] pre_base_trace_id_percent = 2549+18 trace_id_rows= join_rows( gen_trace_ids_exps(pre_base_trace_id_percent, inverse=False, group_jump=18, block_count=6, base_exp_group=None, group_count=1), gen_trace_ids_exps(base_trace_id_percent, inverse=False, group_jump=18, block_count=6, base_exp_group=None, group_count=5) ) trace_id_colors=join_rows( gen_trace_ids_exps(pre_base_trace_id_percent+1, inverse=False, skip=1, group_jump=18, block_count=6, base_exp_group=None, group_count=1, group_size=2), gen_trace_ids_exps(base_trace_id_percent+1, inverse=False,skip=1, group_jump=18, block_count=6, base_exp_group=None, group_count=5, group_size=2) ) print("IDS", trace_id_rows) trace_id_rows=replace(trace_id_rows, [2489, 2490, 2491, 2507, 2508, 2509, 2525, 2526, 2527], [2801, 2802, 2803, 2804, 2805, 2806, 2807, 2808, 2809]) print("IDS", trace_id_rows) print("COLORS", trace_id_colors) time_labels = ["", "5%", "", "10%", "", "25%", "", "50%", "", "75%", "", "100%"] manifest_label=["floodP", "longW", "wideL", "cybers", "sipht", "montage"] y_limits_dic={"[0,48] core.h": (1, 1000), "(48, 960] core.h":(1,100), "(960, inf.) core.h":(1,20)} target_dir="percent" grouping_types = [["bar", "bar"], ["bar", "bar"], ["bar", "bar"], ["bar", "bar"], ["bar", "bar"], ["bar", "bar"]] colors, hatches, legend = produce_plot_config(db_obj, trace_id_colors) #head_file_name="percent" head_file_name="wf_percent-b{0}".format(base_trace_id_percent) for (name, result_type) in zip(["Turnaround speedup", "wait time(h.)", "runtime (h.)", "stretch factor"], ["wf_turnaround", "wf_waittime", "wf_runtime", "wf_stretch_factor"]): if lim: result_type="lim_{0}".format(result_type) print("Loading: {0}".format(name)) factor=1.0/3600.0 if result_type in ("wf_stretch_factor", "lim_wf_stretch_factor"): factor=None edge_plot_results = extract_results(db_obj, trace_id_rows, result_type, factor=factor, second_pass=lim) diffs_results = calculate_diffs(edge_plot_results, base_index=0, group_count=3, speedup=True) # for res_row in edge_plot_results: # print [ x._get("median") for x in res_row] title="{0}".format(name) y_limits=(0,4) print("Plotting figure") ref_level=1.0 plot_multi_bars( name=title, file_name=target_dir+"/{0}-{1}-bars.png".format(head_file_name, result_type), title=title, exp_rows=diffs_results, y_axis_labels=manifest_label, x_axis_labels=time_labels, y_axis_general_label=name, type_rows=grouping_types, colors=colors, hatches=hatches, y_limits=y_limits, y_log_scale=False, legend=legend, y_tick_count=3, subtitle="% workflow workload", ncols=2, ref_line=ref_level )
[ 37811, 1345, 1747, 3781, 319, 262, 30798, 9633, 329, 10256, 351, 1180, 198, 1818, 11125, 3858, 290, 1180, 4064, 1659, 30798, 4755, 2250, 287, 262, 26211, 13, 198, 198, 4965, 5753, 389, 37515, 355, 275, 998, 945, 326, 905, 703, 881, 26...
1.738813
3,419
from __future__ import annotations from .title import TitleFromGroupChat, Base
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 764, 7839, 1330, 11851, 4863, 13247, 30820, 11, 7308, 628 ]
4.263158
19
import requests import pandas as pd import matplotlib.pyplot as plt url_gas_data = 'https://raw.githubusercontent.com/KeithGalli/matplotlib_tutorial/master/gas_prices.csv' res1 = requests.get(url_gas_data, allow_redirects=True) with open('gas_prices.csv', 'wb') as file: file.write(res1.content) plt.figure(figsize=(12, 5)) gas = pd.read_csv('gas_prices.csv') plt.title('Gas prices overtime (in USD)', fontdict={ 'fontweight': 'bold', 'fontsize': 16 }) countries_to_look_at = ['USA', 'Australia', 'South Korea', 'Canada'] for country in gas: if country in countries_to_look_at: plt.plot(gas.Year, gas[country], label=country, marker='.') """ Other way to pass data: plt.plot(gas.Year, gas.USA, 'b.-', label='United States') plt.plot(gas.Year, gas.Canada, 'r.-', label='Canada') plt.plot(gas.Year, gas['South Korea'], 'g.-', label='South Korea') plt.plot(gas.Year, gas.Australia, 'y.-', label='Australia') """ plt.xticks(gas.Year[::3]) plt.xlabel('Year') plt.ylabel('US Dollars') plt.legend() plt.show()
[ 11748, 7007, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 6371, 62, 22649, 62, 7890, 796, 705, 5450, 1378, 1831, 13, 12567, 43667, 13, 785, 14, 46868, 38, 36546, 14, 6...
2.546798
406
import unittest import uuid from app import survey_loader from app import message_manager from app.tester import run_survey
[ 11748, 555, 715, 395, 198, 11748, 334, 27112, 198, 198, 6738, 598, 1330, 5526, 62, 29356, 198, 6738, 598, 1330, 3275, 62, 37153, 198, 6738, 598, 13, 4879, 353, 1330, 1057, 62, 11793, 3304, 628 ]
3.6
35
from os import environ from azure.storage.table import TableService azure_account_name = environ['AZURE_ACCOUNT_NAME'] azure_account_key = environ['AZURE_ACCOUNT_KEY'] azure_table_name = environ['AZURE_TABLE_NAME'] table = TableService(azure_account_name, azure_account_key) get_entity = table.get_entity
[ 6738, 28686, 1330, 551, 2268, 198, 198, 6738, 35560, 495, 13, 35350, 13, 11487, 1330, 8655, 16177, 198, 198, 1031, 495, 62, 23317, 62, 3672, 796, 551, 2268, 17816, 22778, 11335, 62, 26861, 28270, 62, 20608, 20520, 198, 1031, 495, 62, ...
2.933333
105
import logging import h5py import numpy as np from sklearn.utils import check_random_state from csrank.constants import OBJECT_RANKING from csrank.dataset_reader.letor_dataset_reader import LetorDatasetReader from csrank.dataset_reader.objectranking.util import sub_sampling NAME = "LetorObjectRankingDatasetReader" # if __name__ == '__main__': # import sys # import os # import inspect # dirname = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # logging.basicConfig(filename=os.path.join(dirname, 'log.log'), level=logging.DEBUG, # format='%(asctime)s %(name)s %(levelname)-8s %(message)s', # datefmt='%Y-%m-%d %H:%M:%S') # logger = logging.getLogger(name='letor') # sys.path.append("..") # for n in [2008, 2007]: # ds = LetorObjectRankingDatasetReader(year=n) # logger.info(ds.X_train.shape) # logger.info(np.array(ds.X_test.keys).shape)
[ 11748, 18931, 198, 198, 11748, 289, 20, 9078, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1341, 35720, 13, 26791, 1330, 2198, 62, 25120, 62, 5219, 198, 198, 6738, 269, 27891, 962, 13, 9979, 1187, 1330, 25334, 23680, 62, 49, 15154, ...
2.230594
438
from sklearn.preprocessing import QuantileTransformer, PowerTransformer from hydroDL.data import usgs, gageII, gridMET, ntn, GLASS, transform, dbBasin import numpy as np import matplotlib.pyplot as plt from hydroDL.post import axplot, figplot from hydroDL import kPath import json import os import importlib importlib.reload(axplot) importlib.reload(figplot) dm = dbBasin.DataFrameBasin('weathering') # subset dm.saveSubset('B10', ed='2009-12-31') dm.saveSubset('A10', sd='2010-01-01') yrIn = np.arange(1985, 2020, 5).tolist() t1 = dbBasin.func.pickByYear(dm.t, yrIn, pick=False) t2 = dbBasin.func.pickByYear(dm.t, yrIn) dm.createSubset('rmYr5', dateLst=t1) dm.createSubset('pkYr5', dateLst=t2) codeSel = ['00915', '00925', '00930', '00935', '00940', '00945', '00955'] d1 = dbBasin.DataModelBasin(dm, varY=codeSel, subset='rmYr5') d2 = dbBasin.DataModelBasin(dm, varY=codeSel, subset='pkYr5') mtdY = ['QT' for var in codeSel] d1.trans(mtdY=mtdY) d1.saveStat('temp') # d2.borrowStat(d1) d2.loadStat('temp') yy = d2.y yP = d2.transOutY(yy) yO = d2.Y # TS indS = 1 fig, axes = figplot.multiTS(d1.t, [yO[:, indS, :], yP[:, indS, :]]) fig.show() indS = 1 fig, axes = figplot.multiTS(d1.t, [yy[:, indS, :]]) fig.show()
[ 6738, 1341, 35720, 13, 3866, 36948, 1330, 16972, 576, 8291, 16354, 11, 4333, 8291, 16354, 198, 6738, 17173, 19260, 13, 7890, 1330, 514, 14542, 11, 308, 496, 3978, 11, 10706, 47123, 11, 299, 34106, 11, 10188, 10705, 11, 6121, 11, 20613, ...
2.279851
536
""" The :mod:`pysad.statistics` module contains methods to keep track of statistics on streaming data. """ from .abs_statistic import AbsStatistic from .average_meter import AverageMeter from .count_meter import CountMeter from .max_meter import MaxMeter from .median_meter import MedianMeter from .min_meter import MinMeter from .running_statistic import RunningStatistic from .sum_meter import SumMeter from .sum_squares_meter import SumSquaresMeter from .variance_meter import VarianceMeter __all__ = ["AbsStatistic", "AverageMeter", "CountMeter", "MaxMeter", "MedianMeter", "MinMeter", "RunningStatistic", "SumMeter", "SumSquaresMeter", "VarianceMeter"]
[ 37811, 198, 464, 1058, 4666, 25, 63, 79, 893, 324, 13, 14269, 3969, 63, 8265, 4909, 5050, 284, 1394, 2610, 286, 7869, 319, 11305, 1366, 13, 198, 37811, 198, 6738, 764, 8937, 62, 14269, 2569, 1330, 13051, 17126, 2569, 198, 6738, 764, ...
3.311558
199
"""Global index view.""" import pkg_resources from django.shortcuts import render def index(request): """Basic view.""" plugins = \ [plugin.load() for plugin in pkg_resources.iter_entry_points(group='elrados.plugins')] return render(request, "index.html", { "plugins": plugins })
[ 37811, 22289, 6376, 1570, 526, 15931, 198, 11748, 279, 10025, 62, 37540, 198, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 628, 198, 4299, 6376, 7, 25927, 2599, 198, 220, 220, 220, 37227, 26416, 1570, 526, 15931, 198, 220, 220...
2.634146
123
import pandas as pd import matplotlib.pyplot as plt from zipline.finance.commission import PerShare from zipline.api import set_commission, symbol, order_target_percent import zipline from models.live_momentum import LiveMomentum with open('/Users/landey/Desktop/Eonum/live_model/eouniverse/stock_list.txt', 'r') as f: data = f.read().split() tickers = data[:20] etf_list = tickers[15:] start = pd.Timestamp('2020-3-22', tz='utc') end = pd.Timestamp('2020-4-28', tz='utc') perf = zipline.run_algorithm(start=start, end=end, initialize=initialize, capital_base=100000, handle_data=handle_data, bundle='sep') perf.portfolio_value.plot() plt.show()
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 6738, 1976, 24705, 500, 13, 69, 14149, 13, 785, 3411, 1330, 2448, 11649, 198, 6738, 1976, 24705, 500, 13, 15042, 1330, 900, 62, ...
2.027708
397
# Copyright 2020 Jan Feitsma (Falcons) # SPDX-License-Identifier: Apache-2.0 #!/usr/bin/env python3 # Jan Feitsma, March 2020 # Robot will continuously intercept around current position. # # For description and usage hints, execute with '-h' import sys, os import time import logging, signal logging.basicConfig(level=logging.INFO) import math, random import argparse import falconspy import rtdb2tools from robotLibrary import RobotLibrary from worldState import WorldState from FalconsCoordinates import * def calcCirclePos(robotIdx, numRobots, radius=3, center=(0,0)): """ Helper function to distribute robot positions on a circle. """ gamma = 2*math.pi / numRobots x = radius * math.cos(gamma * robotIdx) + center[0] y = radius * math.sin(gamma * robotIdx) + center[1] phi = gamma * robotIdx - math.pi return (x, y, phi) if __name__ == '__main__': args = parse_arguments() if args.robot == 0 or args.robot == None: raise RuntimeError("Error: could not determine robot ID, this script should run on a robot") main(args)
[ 2, 15069, 12131, 2365, 5452, 896, 2611, 357, 41129, 5936, 8, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 2365, 5452, 896, 2611, 11, ...
2.940541
370
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec, GridSpecFromSubplotSpec from matplotlib.ticker import FuncFormatter def plot_dynamic_strats(t, v_t_strat, v_t_risky, w_t_risky, h_t_risky, num, j_sel): """For details, see here. Parameters ---------- t : array, shape (t_,) v_t_strat : array, shape (j_,t_) v_t_risky : array, shape (j_,t_) w_t_risky : array, shape (j_,t_) h_t_risky: array, shape (j_,t_) num: int j_sel: int """ # adjust v_t_risky so that it has the same initial value as v_t_strat v_t_risky = v_t_risky * v_t_strat[0, 0] / v_t_risky[0, 0] mu_risky = np.mean(v_t_risky, axis=0, keepdims=True).reshape(-1) sig_risky = np.std(v_t_risky, axis=0, keepdims=True).reshape(-1) mu_strat = np.mean(v_t_strat, axis=0, keepdims=True).reshape(-1) sig_strat = np.std(v_t_strat, axis=0, keepdims=True).reshape(-1) plt.style.use('arpm') fig = plt.figure() gs = GridSpec(1, 2) gs1 = GridSpecFromSubplotSpec(3, 1, subplot_spec=gs[0]) num_bins = int(round(100 * np.log(v_t_strat.shape[1]))) lgrey = [0.8, 0.8, 0.8] # light grey dgrey = [0.4, 0.4, 0.4] # dark grey j_ = v_t_risky.shape[0] x_min = t[0] x_max = 1.25 * t[-1] y_min = v_t_strat[0, 0] / 4 y_max = v_t_strat[0, 0] * 2.25 # scatter plot ax4 = plt.subplot(gs[1]) plt.scatter(v_t_risky[:, -1], v_t_strat[:, -1], marker='.', s=2) so = np.sort(v_t_risky[:, -1]) plt.plot(so, so, label='100% risky instrument', color='r') plt.plot([y_min, v_t_risky[j_sel, -1], v_t_risky[j_sel, -1]], [v_t_strat[j_sel, -1], v_t_strat[j_sel, -1], y_min], 'b--') plt.plot(v_t_risky[j_sel, -1], v_t_strat[j_sel, -1], 'bo') ax4.set_xlim(y_min, y_max) ax4.set_ylim(y_min, y_max) ax4.xaxis.set_major_formatter(FuncFormatter(tick_label_func)) ax4.yaxis.set_major_formatter(FuncFormatter(tick_label_func)) plt.xlabel('Strategy') plt.ylabel('Risky instrument') plt.legend() # weights and holdings ax3 = plt.subplot(gs1[2]) y_min_3 = np.min(h_t_risky[j_sel, : -1]) y_max_3 = np.max(h_t_risky[j_sel, : -1]) plt.sca(ax3) plt.plot(t, w_t_risky[j_sel, :], color='b') plt.axis([x_min, x_max, 0, 1]) plt.xticks(np.linspace(t[0], 1.2 * t[-1], 7)) plt.yticks(np.linspace(0, 1, 3), color='b') plt.ylabel('Weights', color='b') plt.xlabel('Time') ax3_2 = ax3.twinx() plt.plot(t, h_t_risky[j_sel, :], color='black') plt.ylabel('Holdings', color='black') plt.axis([x_min, x_max, y_min_3 - 1, y_max_3 + 1]) plt.yticks(np.linspace(y_min_3, y_max_3, 3)) ax3_2.yaxis.set_major_formatter(FuncFormatter(tick_label_func_1)) ax1 = plt.subplot(gs1[0], sharex=ax3, sharey=ax4) # simulated path, standard deviation of strategy for j in range(j_ - num, j_): plt.plot(t, v_t_strat[j, :], color=lgrey) plt.plot(t, v_t_strat[j_sel, :], color='b') plt.plot(t, mu_strat + sig_strat, color='orange') plt.plot(t, mu_strat - sig_strat, color='orange') plt.xticks(np.linspace(t[0], 1.2 * t[-1], 7)) # histogram y_hist, x_hist = np.histogram(v_t_strat[:, -1], num_bins) scale = 0.25 * t[-1] / np.max(y_hist) y_hist = y_hist * scale plt.barh(x_hist[: -1], y_hist, height=(max(x_hist) - min(x_hist)) / (len(x_hist) - 1), left=t[-1], facecolor=dgrey, edgecolor=dgrey) plt.setp(ax1.get_xticklabels(), visible=False) plt.ylabel('Strategy') ax1.set_ylim(y_min, y_max) ax1.yaxis.set_major_formatter(FuncFormatter(tick_label_func)) # risky instrument ax2 = plt.subplot(gs1[1], sharex=ax3, sharey=ax4) # simulated path, standard deviation of risky instrument for j in range(j_ - num, j_): plt.plot(t, v_t_risky[j, :], color=lgrey) plt.plot(t, v_t_risky[j_sel, :], color='b') plt.plot(t, mu_risky + sig_risky, color='orange') plt.plot(t, mu_risky - sig_risky, color='orange') plt.xticks(np.linspace(t[0], 1.2 * t[-1], 7)) # histogram y_hist, x_hist = np.histogram(v_t_risky[:, -1], num_bins) scale = 0.25 * t[-1] / np.max(y_hist) y_hist = y_hist * scale plt.barh(x_hist[: -1], y_hist, height=(max(x_hist) - min(x_hist)) / (len(x_hist) - 1), left=t[-1], facecolor=dgrey, edgecolor=dgrey) plt.setp(ax2.get_xticklabels(), visible=False) plt.ylabel('Risky instrument') ax2.set_ylim(y_min, y_max) ax2.yaxis.set_major_formatter(FuncFormatter(tick_label_func)) plt.grid(True) plt.tight_layout() return fig, gs
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 6738, 2603, 29487, 8019, 13, 2164, 2340, 43106, 1330, 24846, ...
1.899477
2,487
import sys import subprocess import time import json import krpc import math import scipy.integrate import numpy as np from PrePlanningChecklist import PrePlanningChecklist from PlannerUiPanel import PlannerUiPanel from MainUiPanel import MainUiPanel from ConfigUiPanel import ConfigUiPanel from AutopilotUiPanel import AutopilotUiPanel from predict_orbit_BCBF import predict_orbit_BCBF while True: try: main() #time.sleep(2.0) except krpc.error.RPCError: time.sleep(4.0) #except ValueError: # time.sleep(4.0)
[ 11748, 25064, 198, 11748, 850, 14681, 198, 11748, 640, 198, 11748, 33918, 198, 11748, 479, 81, 14751, 198, 11748, 10688, 198, 11748, 629, 541, 88, 13, 18908, 4873, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 3771, 20854, 768, 9787, 4...
2.668269
208
import os from discord import Webhook, RequestsWebhookAdapter, Colour, Embed
[ 11748, 28686, 198, 198, 6738, 36446, 1330, 5313, 25480, 11, 9394, 3558, 13908, 25480, 47307, 11, 38773, 11, 13302, 276, 628 ]
3.761905
21
#%% #https://github.com/timesler/facenet-pytorch from facenet_pytorch import MTCNN, extract_face import torch import numpy as np import mmcv, cv2 import os import matplotlib.pyplot as plt from PIL import Image # %% #%% device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('Running on device: {}'.format(device)) print(os.getcwd()) mtcnn = MTCNN(keep_all=True, device=device,image_size=100) video_dir = "VIDEO_FILES/" dest_path = 'VIDEO_PROCESSED/' dir_list = os.listdir(video_dir) dir_list.sort() if not os.path.exists(dest_path): os.makedirs(dest_path) #%% # %% #iemocap k = 1 #session to process video_dir = "IEMOCAP_full_release.tar/IEMOCAP_full_release/Session{}/dialog/avi/DivX".format(k) dir_list = os.listdir(video_dir) dir_list.sort() dir_list = [x for x in dir_list if x[0] =='S'] i=0 #%% dir_list path = 'datasets/IEMOCAP/CLIPPED_VIDEOS/' + 'Session{}/'.format(k) if not os.path.exists(path): os.makedirs(path) dir_list #%% #divide each video and manually crop around face video_dir = "IEMOCAP_full_release.tar/IEMOCAP_full_release/Session{}/dialog/avi/DivX".format(k) dir_list = os.listdir(video_dir) dir_list.sort() dir_list = [x for x in dir_list if x[0] =='S'] path = 'IEMOCAP/CLIPPED_VIDEOS/' + 'Session{}/'.format(k) if not os.path.exists(path): os.makedirs(path) for file_name in dir_list: print(file_name) video = mmcv.VideoReader(video_dir + '/'+file_name) if 'F_' in file_name: new_file_left = path + file_name[:-4] + '_F.avi' new_file_right = path +file_name[:-4] + '_M.avi' else: new_file_left = path +file_name[:-4] + '_M.avi' new_file_right = path + file_name[:-4] + '_F.avi' h,w,c = video[0].shape dim = (300,280) fourcc = cv2.VideoWriter_fourcc(*'FMP4') #left video_tracked = cv2.VideoWriter(new_file_left, fourcc, 25.0, dim) i=0 for frame in video: h,w,c = frame.shape #left #different boxes for each session #box (left, upper, right, lower)-tuple #ses1 [120:int(h- 690),120:int(w/2.4)] #ses2 [150:int(h - 660),120:int(w/2.4)] #ses5 [120:int(h - 690),120:int(w/2.4)] #[130:int(h/2.18),120:int(w/2.4)] video_tracked.write(frame[100:h-100,:300]) video_tracked.release() del video_tracked print(h,w,c) dim = (370,280) # #right video_tracked = cv2.VideoWriter(new_file_right, fourcc, 25.0, dim) for frame in video: h,w,c = frame.shape #right #ses1 [150:int(h - 660),int(w/1.5):int(w-60)] #ses2 [150:int(h - 660),int(w/1.5):int(w-60)] #ses5 [150:int(h - 660),int(w/1.5):int(w-60)] video_tracked.write(frame[100:h-100,350:]) video_tracked.release() del video, video_tracked #%% device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('Running on device: {}'.format(device)) print(os.getcwd()) mtcnn = MTCNN(keep_all=True, device=device,image_size=2000,margin=5) i = 1 video_dir = "../../../../datasets/IEMOCAP/CLIPPED_VIDEOS/Session{}/".format(i) dir_list = os.listdir(video_dir) dir_list.sort() dir_list = [x for x in dir_list if x[0] =='S'] dir_list #%% file_list = dir_list path = '../datasets/IEMOCAP/FACE_VIDEOS/Session{}/'.format(i) if not os.path.exists(path): os.makedirs(path) #%% #%% #track using mtcnn for file_name in file_list: video = mmcv.VideoReader(video_dir + file_name) frames = [Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) for frame in video] frames_tracked = [] for x, frame in enumerate(frames): #print('\rTracking frame: {}'.format(i + 1), end='') # Detect faces boxes, _ = mtcnn.detect(frame) if not boxes is None: # print(boxes[0]) im_array = extract_face(frame, boxes[0],image_size=112,margin=50) #im_array = im_array.permute(1,2,0) img = im_array #Image.fromar ray(np.uint8(im_array.numpy())) # Add to frame list frames_tracked.append(img) else: frames_tracked.append(img) dim = frames_tracked[0].size print(len(frames),len(frames_tracked)) new_file = path + '/' + file_name print(new_file) fourcc = cv2.VideoWriter_fourcc(*'FMP4') video_tracked = cv2.VideoWriter(new_file, fourcc, 25.0, dim) for frame in frames_tracked: video_tracked.write(cv2.cvtColor(np.array(frame), cv2.COLOR_RGB2BGR)) video_tracked.release() del video, video_tracked, frames_tracked, frames
[ 2, 16626, 198, 2, 5450, 1378, 12567, 13, 785, 14, 22355, 1754, 14, 38942, 268, 316, 12, 9078, 13165, 354, 198, 6738, 1777, 268, 316, 62, 9078, 13165, 354, 1330, 337, 4825, 6144, 11, 7925, 62, 2550, 220, 198, 11748, 28034, 198, 11748...
2.099177
2,188
"""Launch Gazebo server and client with command line arguments.""" from launch import LaunchDescription from launch.substitutions import LaunchConfiguration from launch.actions import DeclareLaunchArgument from launch.actions import IncludeLaunchDescription from launch.actions import ExecuteProcess from launch.conditions import IfCondition from launch.launch_description_sources import PythonLaunchDescriptionSource from ament_index_python.packages import get_package_share_directory
[ 37811, 38296, 21347, 1765, 78, 4382, 290, 5456, 351, 3141, 1627, 7159, 526, 15931, 198, 198, 6738, 4219, 1330, 21225, 11828, 198, 6738, 4219, 13, 7266, 301, 270, 3508, 1330, 21225, 38149, 198, 6738, 4219, 13, 4658, 1330, 16691, 533, 382...
4.692308
104
from contextlib import contextmanager import torch.nn as nn
[ 6738, 4732, 8019, 1330, 4732, 37153, 198, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198 ]
3.8125
16
import unittest from calculator import tokens, evaluator from calculator.parser import tokenize, infix_to_postfix
[ 11748, 555, 715, 395, 198, 198, 6738, 28260, 1330, 16326, 11, 5418, 84, 1352, 198, 6738, 28260, 13, 48610, 1330, 11241, 1096, 11, 1167, 844, 62, 1462, 62, 7353, 13049, 628 ]
3.741935
31
from flask import Flask, render_template, request import requests import json import os app = Flask(__name__) picfolder = os.path.join('static','pics') app.config['UPLOAD_FOLDER'] = picfolder if __name__ == '__main__': app.run(debug=True)
[ 6738, 42903, 1330, 46947, 11, 220, 201, 198, 220, 220, 220, 220, 8543, 62, 28243, 11, 2581, 201, 198, 11748, 7007, 201, 198, 11748, 33918, 201, 198, 11748, 28686, 201, 198, 201, 198, 1324, 796, 46947, 7, 834, 3672, 834, 8, 201, 198,...
2.52381
105
from django.conf.urls import url from core.views import me from core.rest import CardViewSet, UserViewSet, NfcCardViewSet, GroupViewSet from core.utils import SharedAPIRootRouter # SharedAPIRootRouter is automatically imported in global urls config router = SharedAPIRootRouter() router.register(r"core/users", UserViewSet, basename="users") router.register(r"core/cards", CardViewSet, basename="voucher_cards") router.register(r"core/nfc", NfcCardViewSet) router.register(r"core/groups", GroupViewSet) urlpatterns = [ url(r"^api/me$", me, name="me"), ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 6738, 4755, 13, 33571, 1330, 502, 198, 198, 6738, 4755, 13, 2118, 1330, 5172, 7680, 7248, 11, 11787, 7680, 7248, 11, 399, 16072, 16962, 7680, 7248, 11, 4912, 7680, 7248, 1...
2.921875
192
from flora_tools.experiment import *
[ 6738, 48037, 62, 31391, 13, 23100, 3681, 1330, 1635, 628 ]
3.8
10
from rest_framework import serializers from main.models import Suco
[ 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 6738, 1388, 13, 27530, 1330, 1778, 1073, 198 ]
4.25
16
from .matern_kernel import MaternKernel from .rbf_kernel import RBFKernel from .spectralgp_kernel import SpectralGPKernel __all__ = ["MaternKernel", "RBFKernel", "SpectralGPKernel"]
[ 6738, 764, 76, 9205, 62, 33885, 1330, 337, 9205, 42, 7948, 198, 6738, 764, 81, 19881, 62, 33885, 1330, 17986, 26236, 7948, 198, 6738, 764, 4443, 1373, 31197, 62, 33885, 1330, 13058, 1373, 16960, 42, 7948, 198, 198, 834, 439, 834, 796,...
3
61
# Generated by Django 2.2.10 on 2020-03-24 16:30 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 940, 319, 12131, 12, 3070, 12, 1731, 1467, 25, 1270, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.8
30
import requests import os from datetime import datetime import pandas as pd if __name__ == "__main__": main()
[ 11748, 7007, 198, 11748, 28686, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 19798, 292, 355, 279, 67, 628, 628, 628, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419, 198 ]
2.97561
41
import os import yoloCarAccident as yc # yc.find('test.txt') f1 = open('result2.txt','r') i = 0 s = "" for lines in f1: if(i<80000): s += lines i+=1 else: f2 = open('test.txt','w') f2.write(s) f2.close() try: yc.find('test.txt') except ValueError: pass s = "" i = 0 # break # f2 = open('test.txt','w') # f2.write(s) # f2.close() # yc.find('test.txt')
[ 11748, 28686, 198, 11748, 331, 14057, 9914, 17320, 738, 355, 331, 66, 198, 198, 2, 331, 66, 13, 19796, 10786, 9288, 13, 14116, 11537, 198, 198, 69, 16, 796, 1280, 10786, 20274, 17, 13, 14116, 41707, 81, 11537, 198, 198, 72, 796, 657...
1.919598
199
import socketserver import socket
[ 11748, 37037, 18497, 198, 11748, 17802, 628, 198 ]
4.5
8
#!/usr/bin/env python3 import os, sys sys.path.append(os.path.abspath(__file__ + "/../../")) # just so we can use 'libs' import torch.utils.data import torch.optim as optim from torch import nn import numpy as np import torch from libs.Loader import Dataset from libs.shufflenetv2 import ShuffleNetV2AutoEncoder BATCH_SIZE = 32 CROP_SIZE = 400 ENCODER_SAVE_PATH = f'models/regular/shufflenetv2_x1_encoder.pth' DECODER_SAVE_PATH = f'models/regular/shufflenetv2_x1_decoder.pth' EPOCHS = 20 if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 28686, 11, 25064, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 6978, 13, 397, 2777, 776, 7, 834, 7753, 834, 1343, 12813, 40720, 492, 30487, 4008, 220, 220, 1303, 655,...
2.438356
219
from .progress_bar import ProgressBar from .read_config import read_config
[ 6738, 764, 33723, 62, 5657, 1330, 18387, 10374, 198, 6738, 764, 961, 62, 11250, 1330, 1100, 62, 11250, 198 ]
3.947368
19
#%% # PAGE EXAMPLE # {'title': 'Zuppa_di_pesce_(film)', # 'chains': [{'revisions': ['95861493', '95861612', '95973728'], # 'users': {'93.44.99.33': '', 'Kirk39': '63558', 'AttoBot': '482488'}, # 'len': 3, # 'start': '2018-04-01 04:54:40.0', # 'end': '2018-04-05 07:36:26.0'}], # 'n_chains': 1, # 'n_reverts': 3, # 'mean': 3.0, # 'longest': 3, # 'M': 0, # 'lunghezze': {'3': 1}} import json from datetime import datetime import numpy as np import pandas as pd import os import shutil from utils import utils import sys language = sys.argv[1] dataset_folder = f'/home/gandelli/dev/data/{language}/chains/page/' output = f'/home/gandelli/dev/data/{language}/chains/user/' #%% get users from the json page # input a dict of users with the chains joined #%% shutil.rmtree(output) os.mkdir(output) users = get_users() compute_users(users) # %%
[ 198, 2, 16626, 198, 2, 48488, 7788, 2390, 16437, 198, 2, 1391, 6, 7839, 10354, 705, 57, 7211, 64, 62, 10989, 62, 12272, 344, 41052, 26240, 8, 3256, 198, 2, 220, 705, 38861, 10354, 685, 90, 6, 18218, 3279, 10354, 37250, 24, 29796, ...
2.221374
393
from django.contrib.auth.forms import AuthenticationForm from django.core.urlresolvers import reverse from django.views.generic.base import View from django.views.generic.detail import SingleObjectMixin,DetailView from django.shortcuts import render,get_object_or_404,redirect from django.http import HttpResponseRedirect,Http404,JsonResponse from django.views.generic.edit import FormMixin from orders.forms import GuestCheckoutForm from products.models import Variation from carts.models import Cart,CartItem # Create your views here.
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 23914, 1330, 48191, 8479, 198, 6738, 42625, 14208, 13, 7295, 13, 6371, 411, 349, 690, 1330, 9575, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 13, 8692, 1330, 3582, 198, 6738, 42625, ...
3.696552
145
#!/usr/bin/python ''' Created on May 23, 2012 @author: Charlie ''' import unittest from mock import patch import xml.etree.ElementTree as ET from TestCgiMainBase import TestCgiMainBase if __name__ == "__main__": unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 7061, 6, 198, 41972, 319, 1737, 2242, 11, 2321, 198, 198, 31, 9800, 25, 11526, 198, 7061, 6, 198, 11748, 555, 715, 395, 198, 6738, 15290, 1330, 8529, 198, 11748, 35555, 13, 316, 631, 13, ...
2.755814
86