content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
from RumourEval2019Models.CLEARumor.src.dataset import get_conversations_from_archive from src.feature_extractor import FeatureExtractor from itertools import chain from RumourEval2019Models.CLEARumor.src.dataset import load_posts, \ load_sdcq_instances, load_verif_instances if __name__ == '__main__': feature_extractor = FeatureExtractor() result = get_conversations_from_archive() single_sample = result['552783667052167168']['source'] print(single_sample) print(feature_extractor.pipeline(single_sample.raw_text)) sdqc_train_instances, sdqc_dev_instances, sdqc_test_instances = \ load_sdcq_instances() sdqc_all_instances = list(chain( sdqc_train_instances, sdqc_dev_instances, sdqc_test_instances)) verif_train_instances, verif_dev_instances, verif_test_instances = \ load_verif_instances() verif_all_instances = list(chain( verif_train_instances, verif_dev_instances, verif_test_instances)) print(sdqc_dev_instances)
[ 6738, 25463, 454, 36, 2100, 23344, 5841, 1424, 13, 29931, 1503, 388, 273, 13, 10677, 13, 19608, 292, 316, 1330, 651, 62, 1102, 690, 602, 62, 6738, 62, 17474, 198, 6738, 12351, 13, 30053, 62, 2302, 40450, 1330, 27018, 11627, 40450, 198...
2.5025
400
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of my-weather-indicator # # Copyright (c) 2012 Lorenzo Carbonell Cerezo <a.k.a. atareao> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from comun import AEMETDB import sqlite3 from xml.etree.ElementTree import parse from urllib.request import urlopen import datetime import math import time class Base(object): '''Interfaz publica''' class Localidad(Base): '''Fecha en formato dd/mm/AAAA''' '''Carga de los datos del XML para el dia seleccionado''' if __name__ == '__main__': print(AEMETDB) lat = 39.3527902 lon = -0.4016816 # lat = 39.3328701015343 # lon = -1.3254618644714355 sqlstring = """ SELECT ID, LATITUD, LONGITUD, IDAEMET, MIN((LATITUD+{0})*(LATITUD+{0}) + (LONGITUD+{1})*(LONGITUD+{1})) FROM SPAIN_FORECASTING_CITIES; """.format(-lat, -lon) print(sqlstring) conn = sqlite3.connect(AEMETDB) c = conn.cursor() c.execute(sqlstring) answer = c.fetchone() print(answer) print(dist(lat, lon, answer[1], answer[2])) print(time.strftime("%d/%m/%Y")) sqlstring = """ SELECT ID, LATITUD, LONGITUD, IDAEMET, MIN((LATITUD+{0})*(LATITUD+{0}) + (LONGITUD+{1})*(LONGITUD+{1})) FROM SPAIN_OBSERVATION_CITIES; """.format(-lat, -lon) print(sqlstring) conn = sqlite3.connect(AEMETDB) c = conn.cursor() c.execute(sqlstring) answer2 = c.fetchone() print(answer2) print(dist(lat, lon, answer2[1], answer2[2])) print(time.strftime("%d/%m/%Y")) base_url = 'http://www.aemet.es/es/eltiempo/observacion/ultimosdatos' print('---', answer2[3], '---') url = base_url + '?k=val&l={}&w=0&datos=det&x=h24&f=temperatura'.format( answer2[3]) print(url) urlpath = '_{0}_datos-horarios.csv?k=val&l={0}&datos=det&w=0' urlpath += '&f=temperatura&x=' url = base_url + urlpath.format(answer2[3]) print(url) response = urlopen(url) print(response.status) data = response.read().decode('ISO-8859-15') print(data) import csv from io import StringIO f = StringIO(data) reader = csv.reader(f, delimiter=',') data = [] values = [] for index, row in enumerate(reader): if index == 3: values = row elif index > 3: mr = {} for index, value in enumerate(values): mr[value] = row[index] data.append(mr) print(data) tiempo = Localidad(answer[3], '27/01/2017') print('27/01/2017') print('Localidad: ', tiempo.get_localidad()) print('Temp. max:', tiempo.get_temperatura_maxima()) print('Temp. min:', tiempo.get_temperatura_minima()) print('Precipitación:', tiempo.get_precipitacion()) print('Temperatura:', tiempo.get_temperatura_horas()) tiempo = Localidad(answer[3], '28/01/2017') print('28/01/2017') print('Localidad: ', tiempo.get_localidad()) print('Temp. max:', tiempo.get_temperatura_maxima()) print('Temp. min:', tiempo.get_temperatura_minima()) print('Precipitación:', tiempo.get_precipitacion()) print('Temperatura:', tiempo.get_temperatura_horas())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 770, 2393, 318, 636, 286, 616, 12, 23563, 12, 521, 26407, 198, 2, 198, 2, 15069, 357, 66, 8, 2321,...
2.426393
1,705
from .base import Predicate
[ 6738, 764, 8692, 1330, 14322, 5344, 628 ]
4.142857
7
# DEPRICATED from struct import unpack from node import Node from chunk import Chunk from texlist import Texlist from address import section_addresses from address import rawaddress from address import virtaddress from helpers import verify_file_arg_b from helpers import verify_file_arg_o
[ 2, 5550, 4805, 2149, 11617, 201, 198, 201, 198, 6738, 2878, 1330, 555, 8002, 201, 198, 6738, 10139, 1330, 19081, 201, 198, 6738, 16058, 1330, 609, 2954, 201, 198, 6738, 48659, 4868, 1330, 3567, 4868, 201, 198, 6738, 2209, 1330, 2665, ...
3.626506
83
import sys sys.path.insert(0, 'mako.zip') sys.path.insert(0, 'cherrypy.zip') import re from cherrypy import tools from mako.template import Template from mako.lookup import TemplateLookup first_cap_re = re.compile('(.)([A-Z][a-z]+)') all_cap_re = re.compile('([a-z0-9])([A-Z])')
[ 11748, 25064, 198, 17597, 13, 6978, 13, 28463, 7, 15, 11, 705, 76, 25496, 13, 13344, 11537, 198, 17597, 13, 6978, 13, 28463, 7, 15, 11, 705, 2044, 563, 9078, 13, 13344, 11537, 220, 220, 198, 11748, 302, 198, 198, 6738, 23612, 9078, ...
2.411765
119
from flask import Flask, jsonify, request, render_template, flash, redirect, url_for from flask_cors import CORS import pandas as pd import pickle import numpy as np from PIL import Image import os from werkzeug.utils import secure_filename from skimage import io, transform # import matplotlib.pyplot as plt # configuration DEBUG = True # load model logreg_model = pickle.load(open("model_.pkl", "rb")) # instatiate app app = Flask(__name__) app.config.from_object(__name__) UPLOAD_FOLDER = "static/uploads" app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg", "txt"} # define user defined functions def allowed_file(filename): """ read and test for allowed file types """ return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS # enable CORS CORS(app, resources={r"/*": {"origins": "*"}}) # define routes @app.route("/", methods=["GET", "POST"]) def logreg_form(): """ run simple logistic regression model and return output of model """ if request.method == "POST": input = request.form.get("submission") model_input = np.array(int(input)) result = logreg_model.predict(model_input.reshape(-1, 1)) return render_template("home.html", input=int(model_input), output=int(result)) else: return render_template("home.html", input="", output="") @app.route("/uploads/<filename>") def uploaded_file(filename): """ functioning, but not currently necessary. return url endpoint with uploaded filename. """ return send_from_directory(app.config["UPLOAD_FOLDER"], filename) @app.route("/image", methods=["GET", "POST"]) def image_transformation(): """ user submits an image to a form save image to local directory (UPLOAD_FOLDER) convert image to grayscale """ if request.method == "POST": file = request.files["image"] if file and allowed_file(file.filename): # save original to directory filename = secure_filename(file.filename) file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename)) # read image and transform to grayscale im = io.imread(file, plugin="matplotlib") gray = Image.fromarray(im).convert("L") # save grayscale gray_filename = "gray" + filename gray.save(os.path.join(app.config["UPLOAD_FOLDER"], gray_filename)) # define input image and output image prior to returning on webpage input = os.path.join(app.config["UPLOAD_FOLDER"], filename) output = os.path.join(app.config["UPLOAD_FOLDER"], gray_filename) return render_template("image.html", input=input, output=output) else: return render_template("image.html", input="", output="") if __name__ == "__main__": app.run()
[ 6738, 42903, 1330, 46947, 11, 33918, 1958, 11, 2581, 11, 8543, 62, 28243, 11, 7644, 11, 18941, 11, 19016, 62, 1640, 198, 6738, 42903, 62, 66, 669, 1330, 327, 20673, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 2298, 293, 198, 1...
2.640367
1,090
from setuptools import setup import sys extra = {} if sys.version_info >= (3,): extra['use_2to3'] = True setup( name="mr-monkeypatch", version="0.0.3", license='http://www.apache.org/licenses/LICENSE-2.0', description="A monkey patching library for python", author='phoeagon', author_email='admin@phoeagon.info', url='https://github.com/phoeagon/monkeypatch-python', download_url='https://github.com/phoeagon/monkeypatch-python/tarball/0.0.3', packages = ['monkeypatch'], package_dir = {'monkeypatch': 'src'}, test_suite = 'monkeypatch.monkeypatch_test', package_data={ 'monkeypatch': ['README', 'LICENSE'] }, install_requires=[], classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ], long_description="""Provide dynamic method name resolution and routing simulates monkey patching in Ruby.""", )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 11748, 25064, 198, 198, 26086, 796, 23884, 198, 361, 25064, 13, 9641, 62, 10951, 18189, 357, 18, 11, 2599, 198, 220, 220, 220, 3131, 17816, 1904, 62, 17, 1462, 18, 20520, 796, 6407, 198, 198, ...
2.71855
469
from datetime import datetime from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render, HttpResponseRedirect, reverse, redirect from django.views.decorators.http import require_POST from django.views.generic.edit import FormView from django.views.generic.base import TemplateView from django.contrib.auth.models import User from django.views.decorators.debug import sensitive_post_parameters, sensitive_variables from .forms import RevalidationLessonForm, AddRevalidationStudentForm from .models import RevalidationStudent from .plain_classes.vulcan_data import RevalidationVulcanData from .vulcan_management.revalidation_vulcan_runner import RevalidationVulcanRunner from base.utils.spared_time_counter import add_spared_time_to_total from base.models import LessonTopic, LessonCategory class RevalidationLessonFormView(LoginRequiredMixin, FormView): """ Main control panel to set parameters for RevalidationVulcanData and run sequence """ login_url = "/login" template_name = 'revalidation/index.html' form_class = RevalidationLessonForm success_url = '/eow/' initial = { 'date': datetime.now().strftime('%d.%m.%Y'), } @sensitive_variables() @sensitive_variables('logged_user') def save_revalidation_topic(form: RevalidationLessonForm, logged_user: User): """ Exception means that given topic wasn't found in associated user's topics. """ try: topic = form['topic'].data if LessonTopic.objects.filter(teacher=logged_user).get(topic__exact=topic): return None except Exception as e: revalidation_category = LessonCategory.objects.get(name__exact='rewalidacja'.title()) LessonTopic.objects.create( topic=topic, is_individual=True, teacher=logged_user, category=revalidation_category ) @sensitive_variables('user', 'request') @login_required(login_url='/login') @require_POST @sensitive_variables('request') @login_required(login_url="/login")
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 12501, 273, 2024, 1330, 17594, 62, 35827, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 19816, 1040, 1330, 23093, 37374, 35608, 259...
2.925
720
# Copyright (c) 2016 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from unittest import mock from neutron.plugins.ml2 import driver_context as ctx from neutron_lib.api.definitions import portbindings from neutron_lib import constants as n_constants from neutron_lib.plugins.ml2 import api from networking_odl.ml2 import legacy_port_binding from networking_odl.tests import base
[ 2, 15069, 357, 66, 8, 1584, 4946, 25896, 5693, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 4...
3.481752
274
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Standalone Python script to untar an archive. Intended to be used by 'tar' recipe module internally. Should not be used elsewhere. """ import json import os import shutil import subprocess import sys import tarfile def untar_with_subprocess(tar_file, output, quiet): """Untars an archive using 'tar' utility. Works only on Linux and Mac, uses system 'tar' program. Args: tar_file: absolute path to an archive to untar. output: existing directory to untar to. quiet (bool): If True, instruct the subprocess to untar with minimal output. Returns: Exit code (0 on success). """ args = ['tar', '-xf'] if not quiet: args += ['-v'] args += [tar_file] return subprocess.call( args=args, cwd=output) def untar_with_python(tar_file, output): """Untars an archive using 'tarfile' python module. Works everywhere where Python works (Windows and POSIX). Args: tar_file: absolute path to an archive to untar. output: existing directory to untar to. Returns: Exit code (0 on success). """ with tarfile.open(tar_file, 'r') as tf: for name in tf.getnames(): print 'Extracting %s' % name tf.extract(name, output) return 0 if __name__ == '__main__': sys.exit(main())
[ 2, 15069, 2177, 383, 18255, 1505, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, 198, 2, 1043, 287, 262, 38559, 24290, 2393, 13, 198, 198, 37811...
2.989562
479
# Import the standard modules import sqlite3 # Import installed modules from matplotlib import pyplot as plt import pandas as pd import numpy as np #%% # Connect to the comet database. This database has been created in tutorial # part 7, however, due to its small size the database is uploaded on GitHub con = sqlite3.connect('../_databases/_comets/mpc_comets.db') # Create a pandas dataframe that contains the perihelion and the absolute # magnitude COMETS_DF = pd.read_sql('SELECT PERIHELION_AU, ABSOLUTE_MAGNITUDE' \ ' FROM comets_main WHERE ECCENTRICITY < 1', \ con) #%% # Print some descriptive statistics print('Descriptive Statistics of the Absolute Magnitude of Comets') print(f'{COMETS_DF["ABSOLUTE_MAGNITUDE"].describe()}') #%% # Define a histogram bins array BINS_RANGE = np.arange(-2, 22 + 2, 2) # Let's set a dark background plt.style.use('dark_background') # Set a default font size for better readability plt.rcParams.update({'font.size': 14}) # Create a figure and axis fig, ax = plt.subplots(figsize=(12, 8)) # Plot a histogram of the absolute magnitude distribution ax.hist(COMETS_DF['ABSOLUTE_MAGNITUDE'], bins=BINS_RANGE, color='tab:orange', \ alpha=0.7) # Set labels for the x and y axes ax.set_xlabel('Absolute Magnitude') ax.set_ylabel('Number of Comets') # Set a grid ax.grid(axis='both', linestyle='dashed', alpha=0.2) # Save the figure plt.savefig('comets_abs_mag_hist.png', dpi=300) #%% # The histogram provides a simple overview of the distribution of the # Absolute Magnitudes ... what does it imply? Are there really, only a few # smaller comets in the Solar System? # Let's create a cumulative histogram as a scatter plot for a better # visibility of possible trends # Compute a cumulative distribution of the absolute magnitude ABS_MAG_HIST, BINS_EDGE = np.histogram(COMETS_DF['ABSOLUTE_MAGNITUDE'], \ bins=BINS_RANGE) CUMUL_HIST = np.cumsum(ABS_MAG_HIST) # Create a figure and axis fig, ax = plt.subplots(figsize=(12, 8)) # Create a scatter plot of the cumulative distribution. Consider, to shift the # bin array by half of the bins' width ax.scatter(BINS_EDGE[:-1]+1, CUMUL_HIST, color='tab:orange', alpha=0.7, \ marker='o') # Set labels for the x and y axes ax.set_xlabel('Absolute Magnitude') ax.set_ylabel('Cumulative Number of Comets') # Set a grid ax.grid(axis='both', linestyle='dashed', alpha=0.2) # Save the figure plt.savefig('comets_abs_mag_cumul_hist.png', dpi=300) #%% # The plot ... does not help a lot ... what about a logarithmic scale? # Create a figure and axis fig, ax = plt.subplots(figsize=(12, 8)) # Create a scatter plot of the cumulative distribution. ax.scatter(BINS_EDGE[:-1]+1, CUMUL_HIST, color='tab:orange', alpha=0.7, \ marker='o') # Set labels for the x and y axes ax.set_xlabel('Absolute Magnitude') ax.set_ylabel('Cumulative Number of Comets') # Set a grid ax.grid(axis='both', linestyle='dashed', alpha=0.2) # Set a logarithmic y axis ax.set_yscale('log') plt.savefig('comets_abs_mag_log10cumul_hist.png', dpi=300) #%% # The logarithmic plots appears to be promising. Let's assume that we know all # larger comets; we use the first 5 data points to create a linear regression # model in semi-log space # Create two arrays that contain the abs. mag. for the fitting and plotting # routine ABS_MAG_FIT = BINS_EDGE[:5]+1 ABS_MAG_PLOT = BINS_EDGE[:-1]+1 # Get the first 5 cumulative results CUMUL_FIT = CUMUL_HIST[:5] # Import the linear model from scikit-learn from sklearn import linear_model reg = linear_model.LinearRegression() # Fit the linear regression model with the data reg.fit(ABS_MAG_FIT.reshape(-1, 1), np.log10(CUMUL_FIT)) # Compute a linear plot for the entire abs. mag. range CUMULATIVE_ABS_MAG_PRED = reg.predict(ABS_MAG_PLOT.reshape(-1, 1)) #%% # Create a figure and axis fig, ax = plt.subplots(figsize=(12, 8)) # Plot the used data points as white dots and ... ax.scatter(ABS_MAG_FIT, CUMUL_FIT, color='white', alpha=0.7, marker='o', \ s=100) # ... plot also the complete data set ax.scatter(BINS_EDGE[:-1]+1, CUMUL_HIST, color='tab:orange', alpha=0.7, \ marker='o') # Plot the linear regression. ax.plot(ABS_MAG_PLOT, 10**CUMULATIVE_ABS_MAG_PRED, 'w--', alpha=0.7) # Set labels for the x and y axes as well as a grid ax.set_xlabel('Absolute Magnitude') ax.set_ylabel('Cumulative Number of Comets') ax.grid(axis='both', linestyle='dashed', alpha=0.2) # Set a log y scale ax.set_yscale('log') # Save the figure plt.savefig('comets_abs_mag_log10cumul_hist_linreg.png', dpi=300) #%% # Let's see wether we find a dependency between the perihelion and the abs. # mag. fig, ax = plt.subplots(figsize=(12, 8)) # To visualise the relation between abs. mag. and size better, we scale the # scatter plot dot size w.r.t. to the abs. mag. # A large abs. mag. corresponds to a small size. First, subtract the values # by the maximum and subtract 1 (otherwise the largest value will become 0) comet_size_plot = abs(COMETS_DF['ABSOLUTE_MAGNITUDE'] \ - COMETS_DF['ABSOLUTE_MAGNITUDE'].max() - 1) # Second and third, normalise the results and scale them by a factor of 100 comet_size_plot /= max(comet_size_plot) comet_size_plot *= 100 # Create a scatter plot of the perihelion vs. the abs. mag. with the marker # sizing ax.scatter(COMETS_DF['PERIHELION_AU'], COMETS_DF['ABSOLUTE_MAGNITUDE'], \ color='white', s=comet_size_plot, alpha=0.3) # Invert the y axis to create a graph that is similar to the logic of the # Malmquist Bias shown in the article ax.invert_yaxis() # Set labels and a grid ax.set_xlabel('Perihelion in AU') ax.set_ylabel('Absolute Magnitude') ax.grid(axis='both', linestyle='dashed', alpha=0.2) # Save the figure plt.savefig('comets_abs_mag_vs_perih.png', dpi=300)
[ 2, 17267, 262, 3210, 13103, 198, 11748, 44161, 578, 18, 198, 198, 2, 17267, 6589, 13103, 198, 6738, 2603, 29487, 8019, 1330, 12972, 29487, 355, 458, 83, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 19...
2.638689
2,228
""" Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from __future__ import absolute_import import argparse import glob import os import sys import numpy as np from setuptools import find_packages, setup from setuptools.command.install import install from setuptools.dist import Distribution # https://github.com/google/or-tools/issues/616 parser = argparse.ArgumentParser() parser.register("type", "bool", lambda v: v.lower() == "true") parser.add_argument("--package_name", type=str, default="oneflow") args, remain_args = parser.parse_known_args() sys.argv = ["setup.py"] + remain_args REQUIRED_PACKAGES = [ f"numpy>={np.__version__}", "protobuf>=3.9.2, <4.0", "tqdm", "requests", "pillow", "prettytable", ] # if python version < 3.7.x, than need pip install dataclasses if sys.version_info.minor < 7: REQUIRED_PACKAGES.append("dataclasses") include_files = glob.glob("oneflow/include/**/*", recursive=True) include_files = [os.path.relpath(p, "oneflow") for p in include_files] assert len(include_files) > 0, os.path.abspath("oneflow/include") package_data = {"oneflow": [get_oneflow_internal_so_path()] + include_files} setup( name=args.package_name, version=get_version(), url="https://www.oneflow.org/", install_requires=REQUIRED_PACKAGES, packages=find_packages(), package_dir={"oneflow": "oneflow"}, package_data=package_data, zip_safe=False, distclass=BinaryDistribution, cmdclass={"install": InstallPlatlib}, )
[ 37811, 198, 15269, 12131, 383, 1881, 37535, 46665, 13, 1439, 2489, 10395, 13, 198, 198, 26656, 15385, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 5832, 743, 407, 779, 428, 2393, 2845, 287, 11846, ...
2.994135
682
from __future__ import absolute_import import datetime import re from chat_unifier import models from chat_unifier.parsers.pidgin import html_reader _TITLE_PATTERN = re.compile( r'^Conversation with (?P<remote_username>.+) at (?P<start_date>\d{1,2}/\d{1,2}/\d{4}) (?P<start_time>\d{1,2}:\d{1,2}:\d{1,2}) (?P<am_pm>[AP]M) on (?P<local_username>.+) \((?P<medium>.+)\)$' )
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 11748, 4818, 8079, 198, 11748, 302, 198, 198, 6738, 8537, 62, 403, 7483, 1330, 4981, 198, 6738, 8537, 62, 403, 7483, 13, 79, 945, 364, 13, 35317, 1655, 1330, 27711, 62, 46862, ...
2.174157
178
# -*- coding: utf-8 -*- """ setup helpers for libev. """ from __future__ import print_function, absolute_import, division import sys import os.path from _setuputils import Extension from _setuputils import system from _setuputils import quoted_dep_abspath from _setuputils import WIN from _setuputils import make_universal_header from _setuputils import LIBRARIES from _setuputils import DEFINE_MACROS from _setuputils import glob_many from _setuputils import dep_abspath from _setuputils import should_embed from _setuputils import cythonize1 LIBEV_EMBED = should_embed('libev') # Configure libev in place; but cp the config.h to the old directory; # if we're building a CPython extension, the old directory will be # the build/temp.XXX/libev/ directory. If we're building from a # source checkout on pypy, OLDPWD will be the location of setup.py # and the PyPy branch will clean it up. libev_configure_command = ' '.join([ "(cd ", quoted_dep_abspath('libev'), " && sh ./configure ", " && cp config.h \"$OLDPWD\"", ")", '> configure-output.txt' ]) CORE = Extension(name='gevent.libev.corecext', sources=[ 'src/gevent/libev/corecext.pyx', 'src/gevent/libev/callbacks.c', ], include_dirs=['src/gevent/libev'] + [dep_abspath('libev')] if LIBEV_EMBED else [], libraries=list(LIBRARIES), define_macros=list(DEFINE_MACROS), depends=glob_many('src/gevent/libev/callbacks.*', 'src/gevent/libev/stathelper.c', 'src/gevent/libev/libev*.h', 'deps/libev/*.[ch]')) if WIN: CORE.define_macros.append(('EV_STANDALONE', '1')) # QQQ libev can also use -lm, however it seems to be added implicitly if LIBEV_EMBED: CORE.define_macros += [('LIBEV_EMBED', '1'), ('EV_COMMON', ''), # we don't use void* data # libev watchers that we don't use currently: ('EV_CLEANUP_ENABLE', '0'), ('EV_EMBED_ENABLE', '0'), ("EV_PERIODIC_ENABLE", '0')] CORE.configure = configure_libev if sys.platform == "darwin": os.environ["CPPFLAGS"] = ("%s %s" % (os.environ.get("CPPFLAGS", ""), "-U__llvm__")).lstrip() if os.environ.get('GEVENTSETUP_EV_VERIFY') is not None: CORE.define_macros.append(('EV_VERIFY', os.environ['GEVENTSETUP_EV_VERIFY'])) else: CORE.libraries.append('ev') CORE = cythonize1(CORE)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 40406, 49385, 329, 9195, 1990, 13, 198, 37811, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 11, 4112, 62, 11748, 11, 7297, 198, 198, 11748, 25064...
2.124088
1,233
# Copyright (C) 2021 Open Source Robotics Foundation # # 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 math import unittest from ignition.math import Pose3d from ignition.math import Quaterniond from ignition.math import Vector3d if __name__ == '__main__': unittest.main()
[ 2, 15069, 357, 34, 8, 33448, 4946, 8090, 47061, 5693, 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, 1...
3.655814
215
from uuid import uuid4 from ..api.test_event_source import create_event_source from ..utils import Endpoint endpoint = Endpoint()
[ 6738, 334, 27112, 1330, 334, 27112, 19, 198, 6738, 11485, 15042, 13, 9288, 62, 15596, 62, 10459, 1330, 2251, 62, 15596, 62, 10459, 198, 6738, 11485, 26791, 1330, 5268, 4122, 198, 198, 437, 4122, 796, 5268, 4122, 3419, 628 ]
3.384615
39
from linebot.models import *
[ 6738, 1627, 13645, 13, 27530, 1330, 1635 ]
4
7
from enum import Enum, auto # NOTE: This queries are meant to supervise the PICR netwrok during training. # NOTE: We currently remove all the training codes from the released CPF. # NOTE: Thus ContactQueries and all the methods that are related to it, are not avaliable.
[ 6738, 33829, 1330, 2039, 388, 11, 8295, 628, 198, 198, 2, 24550, 25, 770, 20743, 389, 4001, 284, 29745, 786, 262, 350, 2149, 49, 2010, 86, 305, 74, 1141, 3047, 13, 198, 2, 24550, 25, 775, 3058, 4781, 477, 262, 3047, 12416, 422, 26...
3.733333
75
from itertools import product import pytest import torch from torch_sparse import SparseTensor from .utils import grad_dtypes, devices @pytest.mark.parametrize('dtype,device', product(grad_dtypes, devices))
[ 6738, 340, 861, 10141, 1330, 1720, 198, 198, 11748, 12972, 9288, 198, 11748, 28034, 198, 6738, 28034, 62, 82, 29572, 1330, 1338, 17208, 51, 22854, 198, 198, 6738, 764, 26791, 1330, 3915, 62, 67, 19199, 11, 4410, 628, 198, 31, 9078, 92...
3.246154
65
import pygame from pygame.locals import * from enum import Enum X = 0 Y = 1 groundPos = 450 # global temporary variable (useless once collision is implemented) ; might use this for a global death barrier (below screen)
[ 11748, 12972, 6057, 201, 198, 6738, 12972, 6057, 13, 17946, 874, 1330, 1635, 201, 198, 6738, 33829, 1330, 2039, 388, 201, 198, 201, 198, 55, 796, 657, 201, 198, 56, 796, 352, 201, 198, 2833, 21604, 796, 18523, 1303, 3298, 8584, 7885, ...
3.492308
65
from pylab import * import scipy.signal as signal numtaps = 201 # number of coeffs #cut off is the normalised cut off in terms of nqy # window is the function # options = boxcar, triang, blackman, hamming, hann, bartlett, flattop, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs standard deviation), general_gaussian (needs power, width), slepian (needs width), chebwin (needs attenuation), exponential (needs decay scale), tukey (needs taper fraction) fir_coeff = signal.firwin(numtaps, cutoff = 0.2, window = ("gaussian",6), nyq = 500E3) mfreqz(fir_coeff) show()
[ 6738, 279, 2645, 397, 1330, 1635, 198, 11748, 629, 541, 88, 13, 12683, 282, 355, 6737, 628, 198, 22510, 83, 1686, 796, 580, 1303, 1271, 286, 763, 14822, 82, 198, 2, 8968, 572, 318, 262, 3487, 1417, 2005, 572, 287, 2846, 286, 299, ...
2.966346
208
'''https://leetcode.com/problems/add-two-numbers/''' # Definition for singly-linked list.
[ 7061, 6, 5450, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 2860, 12, 11545, 12, 77, 17024, 14, 7061, 6, 198, 198, 2, 30396, 329, 1702, 306, 12, 25614, 1351, 13, 198, 220, 220, 220, 220, 220, 220, 220, 220 ]
2.357143
42
""" Unit tests for bipartite edgelists. """ import pytest import io import tempfile import os import networkx as nx from networkx.testing import (assert_edges_equal, assert_nodes_equal, assert_graphs_equal) from networkx.algorithms import bipartite
[ 37811, 198, 220, 220, 220, 11801, 5254, 329, 14141, 433, 578, 1225, 25280, 1023, 13, 198, 37811, 198, 11748, 12972, 9288, 198, 11748, 33245, 198, 11748, 20218, 7753, 198, 11748, 28686, 198, 198, 11748, 3127, 87, 355, 299, 87, 198, 6738,...
2.567568
111
# Imports import os import shutil import tempfile from IPython.display import display from copy import copy from pyspark import SparkContext from pyspark.sql import SQLContext from pyspark.sql.functions import * from pyspark.sql.types import * from .spark_config import app_name, path_pkg from .spark_config import spark_conf, spark_master, spark_sys_properties class SparkClusterException(Exception): """ Raised if not possible to instantiate Spark handler from driver """ pass def show(r, n=3): """ Display nicely a PySpark dataframe in jupyter notebook :param r: dataframe :param n: number of rows to display :return: """ display(r.limit(n).toPandas()) def get_pathname(): """ Retrieve the pathname of this module. :return: string - path to this module """ path_elems = path_pkg.split('/')[0:-1] return '/'.join(path_elems) def create_spark_sql_context(app_name): """ Instantiates spark and sql contexts. If executed twice, it will return the first instance. :param app_name: name of the app to assign to the created spark context. :return: """ # Initialize Spark and SQL context # set spark config and master conf = copy(spark_conf) conf.setMaster(spark_master).setAppName(app_name) # set PROFILE environment in executors conf.setExecutorEnv('PROFILE', os.environ.get('PROFILE')) # set spark system properties for k, v in spark_sys_properties.items(): SparkContext.setSystemProperty(k, v) sc = SparkContext(conf=conf) if sc is None: raise SparkClusterException("Unable to instantiate SparkContext") # Adding spark_helpers.zip to SparkContext so that workers can load modules from spark_helpers # http://apache-spark-user-list.1001560.n3.nabble.com/Loading-Python-libraries-into-Spark-td7059.html tmp_dir = tempfile.mkdtemp() sc.addPyFile( shutil.make_archive(base_name='{}/spark_cluster_pkg'.format(tmp_dir), format='zip', root_dir=os.path.abspath(path_pkg))) sq = SQLContext(sc) if sq is None: raise SparkClusterException("Unable to instantiate SQLContext") return sc, sq class SparkSqlContext: """ Singleton that manages pyspark and sql contexts. In the future, it can be extended to support the creation of CassandraSparkContext. """ sc = None sq = None @classmethod def setup(cls, app_name=app_name): """ Create Spark and Sql contexts :param app_name: spark application name :return: pair (sc:SparkContext, sq:SQLContext) """ if not cls.sc: cls.sc, cls.sq = create_spark_sql_context(app_name) return cls.sc, cls.sq def create_df(*args, **kwargs): """ Helper function that creates a Spark DataFrame given rows and schema. :param args: positional arguments of createDataFrame :param kwargs: optional arguments of createDataFrame :return: dataframe """ (sp, sq) = SparkSqlContext.setup() return sq.createDataFrame(*args, **kwargs) def read_df(): """ Helper function that returns a dataframe reader object, can be used to read CSV and Parquet files. :return: PySpark DataFrame reader object """ (sp, sq) = SparkSqlContext.setup() return sq.read
[ 2, 1846, 3742, 198, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 11748, 20218, 7753, 198, 6738, 6101, 7535, 13, 13812, 1330, 3359, 198, 6738, 4866, 1330, 4866, 198, 6738, 279, 893, 20928, 1330, 17732, 21947, 198, 6738, 279, 893, 20928...
2.700161
1,244
import logging import sys import argparse logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def index_of_closing_parenthesis(words, start, left_enc ='(', right_enc =')'): """Returns index of the closing parenthesis of the parenthesis indicated by start.""" num_opened = 1 for i in range(start + 1, len(words)): if words[i] == left_enc: num_opened += 1 elif words[i] == right_enc: num_opened -= 1 if num_opened == 0: return i return -1 def index_of_opening_parenthesis(words, start, left_enc ='(', right_enc =')'): """Returns index of the opening parenthesis of the parenthesis indicated by start.""" num_opened = -1 i = start-1 while i >= 0: if words[i] == left_enc: num_opened += 1 elif words[i] == right_enc: num_opened -= 1 if num_opened == 0: return i i -= 1 return -1 def index_closest_left(words, start, what): """Returns index of the closest specified element to the left of the starting position or -1 if no such element was present.""" i = start - 1 while i >= 0: if words[i] == what: return i i -= 1 return -1 def index_closest_right(words, start, what): """Returns index of the closest specified element to the right of the starting position or -1 if no such element was present.""" i = start + 1 while i < len(words): if words[i] == what: return i i += 1 return -1 def parenthesis_enclosure(words, start, left_enc = '(', right_enc = ')'): """For a given position in the list finds left and right parenthesis (there is also an option to specify arbitrary symbols) and returns a list containing those parenthesis and all elements between them.""" opened = index_of_opening_parenthesis(words, start, left_enc, right_enc) if opened == -1: return [] ended = index_of_closing_parenthesis(words, opened, left_enc, right_enc) if ended == -1: return [] return words[opened:ended+1] def assertify(text): """Wraps text in the (assert ).""" return '(assert ' + text + ')' LANG_PYTHON = 'python' LANG_SMT2 = 'smt2' def alternative(seq, lang = LANG_PYTHON): """Produces a formula connecting all elements from the provided list with an alternative ('or').""" if lang == LANG_PYTHON: return merge_elements_by(seq, ' or ') elif lang == LANG_SMT2: return _join_smt2(seq, 'or') else: raise Exception("'{0}': Not recognized language!".format(lang)) def conjunction(seq, lang = LANG_PYTHON): """Produces a formula connecting all elements from the provided list with a conjunction ('and').""" if lang == LANG_PYTHON: return merge_elements_by(seq, ' and ') elif lang == LANG_SMT2: return _join_smt2(seq, 'and') else: raise Exception("'{0}': Not recognized language!".format(lang)) def conjunct_constrs_smt2(constr_list): """Merges constraints list using SMT-LIB 2.0 conjunction operator (and). If the list is empty, 'true' is returned.""" noncomments = [c for c in constr_list if c.lstrip()[0] != ';'] if len(noncomments) == 0: return 'true' elif len(noncomments) == 1: return noncomments[0] else: return _join_smt2(constr_list, 'and') def _join_smt2(seq, conn): """Produces a SMT-LIB 2.0 formula containing all elements of the sequence merged by a provided connective.""" if len(seq) == 0: return '' elif len(seq) == 1: return seq[0] else: return '({0} {1})'.format(conn, ' '.join(seq)) def merge_elements_by(seq, conn, wrapped_in_par = True): """Produces a string containing all elements of the sequence merged by a provided connective.""" if len(seq) == 0: return '' elif len(seq) == 1: return seq[0] else: sf = '({0})' if wrapped_in_par else '{0}' return conn.join(sf.format(el) for el in seq) def str_to_wlist(s, par_open = '(', par_close = ')'): """Converts a string to a list of words, where words are delimited by whitespaces.""" return s.replace(par_open, ' '+par_open+' ').replace(par_close, ' '+par_close+' ').split() def str_to_dict_parenthesis(s): """Converts a string in the format: '((n1 v1)...(nk vk))' to a dictionary {n1:v1, ..., nk:vk}.""" return wlist_to_dict_parenthesis(str_to_wlist(s)) def wlist_to_dict_parenthesis(words): """Converts a list of strings in the format: ['(', '(', 'n1', 'v1', ')', ..., '(', 'nk', 'vk', ')', ')'] to a dictionary {n1:v1, ..., nk:vk}.""" res = {} i = 1 while True: if words[i] == '(': res[words[i+1]] = words[i+2] i += 4 else: break return res class Options(object): """Options contains all settings which are used within the framework.""" MODE_NORMAL = 'normal' MODE_MIN = 'min' MODE_MAX = 'max' PYTHON = 'python' SMT2 = 'smt2'
[ 11748, 18931, 198, 11748, 25064, 198, 11748, 1822, 29572, 198, 198, 6404, 2667, 13, 35487, 16934, 7, 5715, 28, 6404, 2667, 13, 10778, 8, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 628, 198, 4299, 6376, ...
2.438554
2,075
# Generated by Django 2.2.2 on 2019-07-24 13:06 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 17, 319, 13130, 12, 2998, 12, 1731, 1511, 25, 3312, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
# cp download_execute_and_report.py /var/www/html/evil-files # service apache2 start # http://10.0.2.13/evil-files/ import requests import subprocess import smtplib import re import os import tempfile temp_directory = tempfile.gettempdir() os.chdir(temp_directory) download('http://10.0.2.13/evil-files/lazagne.exe') result = subprocess.check_output('lazagne.exe all', shell=True) send_mail('b06ffc432e3884', 'a5e72032e9c491', 'to@smtp.mailtrap.io', result) os.remove('lazagne.exe')
[ 2, 31396, 4321, 62, 41049, 62, 392, 62, 13116, 13, 9078, 1220, 7785, 14, 2503, 14, 6494, 14, 23542, 12, 16624, 198, 2, 2139, 2471, 4891, 17, 923, 198, 2, 2638, 1378, 940, 13, 15, 13, 17, 13, 1485, 14, 23542, 12, 16624, 14, 198, ...
2.623656
186
import pytest from pandas.util.testing import assert_frame_equal from .context import gtfstk, slow, HAS_GEOPANDAS, DATA_DIR, cairns, cairns_shapeless from gtfstk import * if HAS_GEOPANDAS: from geopandas import GeoDataFrame @pytest.mark.skipif(not HAS_GEOPANDAS, reason="Requires GeoPandas") @pytest.mark.skipif(not HAS_GEOPANDAS, reason="Requires GeoPandas") @pytest.mark.skipif(not HAS_GEOPANDAS, reason="Requires GeoPandas")
[ 11748, 12972, 9288, 198, 198, 6738, 19798, 292, 13, 22602, 13, 33407, 1330, 6818, 62, 14535, 62, 40496, 198, 198, 6738, 764, 22866, 1330, 308, 27110, 301, 74, 11, 3105, 11, 33930, 62, 8264, 3185, 6981, 1921, 11, 42865, 62, 34720, 11, ...
2.720497
161
""" Tests for GibbsEntrySet. """ import pytest from pymatgen.analysis.phase_diagram import PhaseDiagram from rxn_network.entries.entry_set import GibbsEntrySet @pytest.mark.parametrize( "e_above_hull, expected_phases", [ ( 0.030, { "Mn", "Mn2O3", "Mn3O4", "Mn5O8", "MnO", "MnO2", "O2", "Y", "Y2Mn2O7", "Y2O3", "YMn12", "YMn2O5", "YMnO3", }, ), ( 0.100, { "YMnO3", "Y", "Y2O3", "Mn5O8", "Mn", "Y2Mn2O7", "YMn2O4", "YMn2O5", "MnO2", "Mn21O40", "Mn3O4", "Mn7O12", "MnO", "O2", "Mn2O3", "YMn12", }, ), ], )
[ 37811, 30307, 329, 41071, 30150, 7248, 13, 37227, 198, 11748, 12972, 9288, 198, 6738, 279, 4948, 265, 5235, 13, 20930, 13, 40715, 62, 10989, 6713, 1330, 18983, 18683, 6713, 198, 198, 6738, 374, 87, 77, 62, 27349, 13, 298, 1678, 13, 13...
1.271879
857
import tensorflow as tf model = tf.keras.Sequential([ tf.keras.applications.resnet_v2.ResNet50V2(weights=None, input_shape=(32, 32, 3), include_top=False), tf.keras.layers.GlobalAveragePooling2D(), tf.keras.layers.Dense(1000, activation='softmax') ]) BATCH_SIZE = 16 train_loss = tf.keras.metrics.Mean(name='train_loss') train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy') test_loss = tf.keras.metrics.Mean(name='test_loss') test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy') dataset = tf.data.TFRecordDataset(["./cifar-10-train-data.tfrecords"]) dataset = dataset.map(map_func) dataset = dataset.batch(32) val_dataset = tf.data.TFRecordDataset(["./cifar-10-test-data.tfrecords"]) val_dataset = val_dataset.map(map_func) val_dataset = val_dataset.batch(32) optimizer = tf.keras.optimizers.SGD(learning_rate=0.001) loss_obj = tf.keras.losses.SparseCategoricalCrossentropy() if __name__ == '__main__': for epoch in range(5): train_loss.reset_states() train_accuracy.reset_states() test_loss.reset_states() test_accuracy.reset_states() for train_data, train_labels in dataset: train_data = train_data.numpy() train_data = train_data / 255.0 train_step(train_data, train_labels) for test_data, test_labels in val_dataset: test_data = test_data.numpy() test_data = test_data / 255.0 test_step(test_data, test_labels) print( f'Epoch {epoch + 1}, ' f'Loss: {train_loss.result()}, ' f'Accuracy: {train_accuracy.result() * 100}, ' f'Test Loss: {test_loss.result()}, ' f'Test Accuracy: {test_accuracy.result() * 100}' )
[ 11748, 11192, 273, 11125, 355, 48700, 628, 198, 19849, 796, 48700, 13, 6122, 292, 13, 44015, 1843, 26933, 198, 220, 220, 220, 220, 220, 220, 220, 48700, 13, 6122, 292, 13, 1324, 677, 602, 13, 411, 3262, 62, 85, 17, 13, 4965, 7934, ...
2.170644
838
#!/usr/bin/env python3 # vim: set fileencoding=utf-8: """Normalize file and add/update the language list at the bottom of all CC4 legalcode files. """ # Copyright 2016, 2017 Creative Commons # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Standard library from collections import OrderedDict import argparse import difflib import glob import os.path import re import sys import traceback # Local/library specific import lang_tag_to COMMENTS = OrderedDict( { "head_start": { "label": "Head Start", "regex": re.compile( r"""(?P<target> /errata[.]js['"]></script>\s* )""", re.IGNORECASE | re.VERBOSE, ), "include": "html-head.html", }, "head_end": { "label": "Head End", "regex": re.compile( r"""(?P<target> \s*</head> )""", re.IGNORECASE | re.VERBOSE, ), }, "site_header_start": { "label": "Site Header Start", "regex": re.compile( r"""(?P<target> <body[^>]+>\s )""", re.IGNORECASE | re.VERBOSE, ), "include": "site-header.html", }, "site_header_end": { "label": "Site Header End", "regex": re.compile( r"""(?P<target> <!--\ Language\ Selector\ Start | \s*<div\ id="language-selector-block" | \s*<div\ id="deed" )""", re.IGNORECASE | re.VERBOSE, ), }, "language_selector_start": { "label": "Language Selector Start", "regex": re.compile( r"""(?P<target> <!--\ Site\ Header\ End\ -\ DO\ NOT\ DELETE\ -->\s )""", re.IGNORECASE | re.VERBOSE, ), }, "language_selector_end": { "label": "Language Selector End", "regex": re.compile( r"""(?P<target> <!--\ Legalcode\ Start | \s*<div\ id="deed" )""", re.IGNORECASE | re.VERBOSE, ), }, "legalcode_start": { "label": "Legalcode Start", "regex": re.compile( r"""(?P<target> <!--\ Language\ Selector\ End\ -\ DO\ NOT\ DELETE\ -->\s )""", re.IGNORECASE | re.VERBOSE, ), }, "legalcode_end": { "label": "Legalcode End", "regex": re.compile( r"""(?P<target> \s*<p\ class="shaded">.*<br><br> )""", re.IGNORECASE | re.VERBOSE, ), }, "language_footer_start": { "label": "Language Footer Start", "regex": re.compile( r"""(?P<target> <a\ id="languages"></a>[^<]+\s )""", re.IGNORECASE | re.VERBOSE, ), }, "language_footer_end": { "label": "Language Footer End", "regex": re.compile( r"""(?P<target> (?<= # \u3002 is ideographic full stop </a>[.\u3002] ) \s*[^<]+<a\ href="/FAQ#officialtranslations"> )""", re.IGNORECASE | re.VERBOSE, ), }, "site_footer_start": { "label": "Site Footer Start", "regex": re.compile( r"""(?P<target> <div\ id="deed-foot">\s* <p[^<]+<a[^<]+</a></p>\s*</div>\s* </div>\s* )""", re.IGNORECASE | re.VERBOSE, ), "include": "site-footer.html", }, "site_footer_end": { "label": "Site Footer End", "regex": re.compile( r"""(?P<target> \s*</body> )""", re.IGNORECASE | re.VERBOSE, ), }, } ) FAQ_TRANSLATION_LINK = "/faq/#officialtranslations" def diff_changes(filename, old, new): """Display changes as a colorized unified diff. """ diff = list( difflib.unified_diff( old.split("\n"), new.split("\n"), fromfile=f"{filename}: current", tofile=f"{filename}: proposed", n=3, ) ) if not diff: return # Color diff output rst = "\033[0m" for i, line in enumerate(diff): if line.startswith("---"): diff[i] = f"\033[91m{line.rstrip()}{rst}" elif line.startswith("+++"): diff[i] = f"\033[92m{line.rstrip()}{rst}" elif line.startswith("@"): diff[i] = f"\033[36m{line.rstrip()}{rst}" elif line.startswith("-"): diff[i] = f"\033[31m{line}{rst}" elif line.startswith("+"): diff[i] = f"\033[32m{line}{rst}" else: diff[i] = f"\033[90m{line}{rst}" print("\n".join(diff)) def update_lang_selector(args, filename, content, lang_tags): """Replace the contents of the language selector (everything between language_selector_start and language_selector_end HTML comments) with a list of links based on the legalcode files currently being processed. """ current_language = lang_tags_from_filenames(filename)[0] selector = ( '<div id="language-selector-block" class="container">' '\n<div class="language-selector-inner">' f"\n{lang_tag_to.SELECT_TEXT[current_language]}" '\n<img class="language-icon"' ' src="/images/language_icon_x2.png" alt="Languages">' "\n<select>" ) for lang_tag in lang_tags: selected = "" if lang_tag == current_language: selected = ' selected="selected"' # Determine to option value for the language. English breaks the # pattern so handle it differently. if lang_tag == "en": index = "legalcode" else: index = f"legalcode.{lang_tag}" # Add the selector vlaue selector = ( f"{selector}\n" f'<option value="{index}"{selected}>' f"{lang_tag_to.LABEL[lang_tag]}</option>" ) selector = f"{selector}\n</select>\n</div>\n</div>" # Update the language selector block to the content label = COMMENTS["language_selector_start"]["label"] start = f"<!-- {label} - DO NOT DELETE -->" label = COMMENTS["language_selector_end"]["label"] end = f"<!-- {label} - DO NOT DELETE -->" target = re.search(f"{start}.*{end}", content, re.DOTALL).group() replacement = f"{start}\n{selector}\n{end}" if target == replacement: print( f"{filename}: Skipping unneeded update of language" " selector options" ) else: print(f"{filename}: Updating language selector options") new_content = content.replace(target, replacement, 1) if args.debug: diff_changes(filename, content, new_content) if new_content is None: sys.exit(1) return new_content def update_lang_footer(args, filename, content, lang_tags): """Replace the contents of the language footer (everything between language_footer_start and language_footer_end HTML comments) with a list of links based on the legalcode files currently being processed. """ current_language = lang_tags_from_filenames(filename)[0] license_type = filename.split("_")[0] footer = "" for lang_tag in lang_tags: if lang_tag == current_language: continue # Determine to option value for the language. English breaks the # pattern so handle it differently. if lang_tag == "en": index = "legalcode" else: index = f"legalcode.{lang_tag}" link = ( f'<a href="/licenses/{license_type}/4.0/{index}">' f"{lang_tag_to.LABEL[lang_tag]}</a>,\n" ) footer = f"{footer}{link}" footer = footer.rstrip(",\n") # Update the language footer block to the content label = COMMENTS["language_footer_start"]["label"] start = f"<!-- {label} - DO NOT DELETE -->" label = COMMENTS["language_footer_end"]["label"] end = f"<!-- {label} - DO NOT DELETE -->" target = re.search(f"{start}.*{end}", content, re.DOTALL).group() if current_language in ["ja", "zh-Hans", "zh-Hant"]: # Use ideographic full stop ("。") period = "\u3002" else: # Use ASCII period period = "." replacement = f"{start}\n{footer}{period}\n{end}" if target == replacement: print( f"{filename}: Skipping unneeded update of language footer" " links" ) else: print(f"{filename}: Updating language footer links") new_content = content.replace(target, replacement, 1) if args.debug: diff_changes(filename, content, new_content) if new_content is None: sys.exit(1) return new_content def insert_missing_comment(args, filename, content, comment_dict): """Insert the comment in the appropriate locations, if it is not already present. """ label = comment_dict["label"] comment = f"<!-- {label} - DO NOT DELETE -->" regex = comment_dict["regex"] if not content.find(comment) == -1: print( f"{filename}: Skipping unneeded {label} HTML comment insertion" ) return content print(f"{filename}: inserting {label } HTML comment") matches = regex.search(content) if matches is None: print( f"{filename}: ERROR: {label} insertion point not matched. Aborting" " processing" ) sys.exit(1) target = matches.group("target") if " start" in label.lower(): # Start comments are inserted after target regex target_new = target.rstrip() replacement = f"{target_new}\n{comment}\n" else: # End comments are inserted before target regex target_new = target.lstrip("\n") replacement = f"\n{comment}\n{target_new}" new_content = content.replace(target, replacement, 1) if args.debug: diff_changes(filename, content, new_content) if new_content is None: sys.exit(1) return new_content def has_correct_faq_officialtranslations(content): """Determine if the link to the translation FAQ is correct. """ if content.find(f'"{FAQ_TRANSLATION_LINK}"') == -1: return False return True def normalize_faq_translation_link(args, filename, content): """Replace various incorrect translation FAQ links with the correct link (FAQ_TRANSLATION_LINK). """ if has_correct_faq_officialtranslations(content): print( f"{filename}: Skipping unneeded translation FAQ link" " normalization" ) return content print(f"{filename}: normalizing translation FAQ link") re_pattern = re.compile( r""" (?P<prefix> href=['"] ) (?P<target> # Matches various translation FAQ URLs [^'"]*/[Ff][Aa][Qq]/?[#][^'"]* ) (?P<suffix> ['"] ) """, re.DOTALL | re.MULTILINE | re.VERBOSE, ) matches = re_pattern.search(content) if matches is None: print( f"{filename}: ERROR: translation link not matched. Aborting" " processing" ) sys.exit(1) target = matches.group("target") replacement = FAQ_TRANSLATION_LINK new_content = content.replace(target, replacement, 1) if args.debug: diff_changes(filename, content, new_content) if new_content is None: sys.exit(1) return new_content def has_correct_languages_anchor(content): """Determine if language anchor uses id """ if content.find('id="languages"') == -1: return False return True def normalize_languages_anchor(args, filename, content): """Replace name with id in languages anchor (HTML5 compatibility) """ if has_correct_languages_anchor(content): print( f"{filename}: Skipping unneeded language anchor normalization" ) return content print(f"{filename}: normalizing language anchor id") re_pattern = re.compile("name=['\"]languages['\"]", re.IGNORECASE) matches = re_pattern.search(content) if matches is None: print( f"{filename}: ERROR: languages anchor not matched. Aborting" " processing" ) sys.exit(1) target = matches.group() replacement = 'id="languages"' new_content = content.replace(target, replacement, 1) if args.debug: diff_changes(filename, content, new_content) if new_content is None: sys.exit(1) return new_content def normalize_line_endings(args, filename, content): """Normalize line endings to unix LF (\\n) """ re_pattern = re.compile("\r(?!\n)") matches = re_pattern.findall(content) message = "" if matches: message = f" {len(matches)} mac newlines (CR)" re_pattern = re.compile("\r\n") matches = re_pattern.findall(content) if matches: if message: message = f"{message} and" message = f"{message} {len(matches)} windows newlines (CRLF)" if message: print(f"{filename}: Converting{message} to unix newlines (LF)") return "\n".join(content.split("\r\n")) else: print(f"{filename}: Skipping unneeded newline conversion") return content def process_file_contents(args, file_list, lang_tags): """Process each of the CC4 legalcode files and update them, as necessary. """ for filename in file_list: with open(filename, "r", encoding="utf-8", newline="") as file_in: content = file_in.read() new_content = content new_content = normalize_line_endings(args, filename, new_content) new_content = normalize_languages_anchor(args, filename, new_content) new_content = normalize_faq_translation_link( args, filename, new_content ) for key in COMMENTS.keys(): new_content = insert_missing_comment( args, filename, new_content, COMMENTS[key] ) new_content = update_lang_selector( args, filename, new_content, lang_tags ) new_content = update_lang_footer( args, filename, new_content, lang_tags ) for section in ("head", "site_header", "site_footer"): new_content = update_include(args, filename, new_content, section) if content == new_content: print( f"{filename}: Skipping writing back to file (no changes)" ) elif args.debug: print(f"{filename}: DEBUG: Skipping writing changes to file") else: print(f"{filename}: Writing changes to file") with open(filename, "w", encoding="utf-8") as file_out: file_out.write(new_content) print() print() def lang_tags_from_filenames(file_list): """Extract RFC 5646 language tags from filename(s) """ if isinstance(file_list, str): lang_tags = [file_list.split(".")[1][2:]] else: lang_tags = list( set([filename.split(".")[1][2:] for filename in file_list]) ) try: lang_tags[lang_tags.index("")] = "en" except ValueError: pass lang_tags.sort() return lang_tags def setup(): """Instantiate and configure argparse and logging. Return argsparse namespace. """ default_glob = ["by*4.0*.html"] ap = argparse.ArgumentParser(description=__doc__) ap.add_argument( "-d", "--debug", action="store_true", help="Debug mode: list changes without modification", ) ap.add_argument( "globs", nargs="*", default=default_glob, help=( "Filename or shell glob of the file(s) that will be updated" f' (default: "{default_glob[0]}")' ), metavar="FILENAME", ) args = ap.parse_args() return args if __name__ == "__main__": try: main() except SystemExit as e: sys.exit(e.code) except KeyboardInterrupt: print("INFO (130) Halted via KeyboardInterrupt.", file=sys.stderr) sys.exit(130) except ToolError: error_type, error_value, error_traceback = sys.exc_info() print("CRITICAL {}".format(error_value), file=sys.stderr) sys.exit(error_value.code) except: # noqa: ignore flake8: E722 do not use bare 'except' print("ERROR (1) Unhandled exception:", file=sys.stderr) print(traceback.print_exc(), file=sys.stderr) sys.exit(1)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 43907, 25, 900, 2393, 12685, 7656, 28, 40477, 12, 23, 25, 198, 198, 37811, 26447, 1096, 2393, 290, 751, 14, 19119, 262, 3303, 1351, 379, 262, 4220, 286, 477, 12624, 19, 198, ...
2.109734
8,393
import os, glob, shutil, traceback import PIL_Helper TYPE, TITLE, COLOR, VALUE, FLAVOR = range(5) DIRECTORY = "BaBOC" PAGE_WIDTH = 3 PAGE_HEIGHT = 3 TOTAL_CARDS = PAGE_WIDTH*PAGE_HEIGHT workspace_path = os.path.dirname("workspace") card_set = os.path.dirname("deck.cards") CardPath = "BaBOC/cards/" ResourcePath = "BaBOC/resources/" VassalTemplatesPath = DIRECTORY+"/vassal templates" VassalWorkspacePath = DIRECTORY+"/vassal workspace" VassalImagesPath = os.path.join(VassalWorkspacePath, "images") VassalCard = [0] bleed_w = 788 bleed_h = 1088 w_marg = 31 h_marg = 36 bleedrect=[(w_marg,h_marg),(bleed_w-w_marg,bleed_h-h_marg)] textmaxwidth = 580 LineM=PIL_Helper.Image.open(ResourcePath+"line_M.png") LineH=PIL_Helper.Image.open(ResourcePath+"line_H.png") LineG=PIL_Helper.Image.open(ResourcePath+"line_G.png") LineS=PIL_Helper.Image.open(ResourcePath+"line_S.png") titlefont = ResourcePath+"ComicNeue-Regular.ttf" titleboldfont = ResourcePath+"ComicNeue-Bold.ttf" symbolfont = ResourcePath+"Eligible-Regular.ttf" TitleFont = PIL_Helper.BuildFont(titleboldfont, 60) SymbolFont = PIL_Helper.BuildFont(symbolfont, 150) BigSymbolFont = PIL_Helper.BuildFont(symbolfont, 200) ValueFont = PIL_Helper.BuildFont(symbolfont, 90) RulesFont = PIL_Helper.BuildFont(titlefont, 50) TypeFont = PIL_Helper.BuildFont(titleboldfont, 70) GenreFont = PIL_Helper.BuildFont(titleboldfont,50) FlavorFont = PIL_Helper.BuildFont("BaBOC/resources/KlinicSlabBookIt.otf", 40) CopyFont = PIL_Helper.BuildFont("BaBOC/resources/Barth_Regular.ttf", 10) TypeAnchor = (bleed_w/2+70, 50) TitleAnchor = (80, 60) FormTitleAnchor = (80, -60) SymbolAnchor = (80, -100) RulesAnchor = (bleed_w/2+70, 650) OneLineAnchor = (bleed_w/2+70, 160) TwoLineAnchor = (bleed_w/2+70, 220) FlavorAnchor = (bleed_w/2+70, -30) ColDict={ "G": (225,200,225), "S": (225,255,225), "H": (255,225,225), "M": (225,225,255), "+": (225,225,225), "-": (225,225,225) } ColDictDark={ "G": (100,0,100), "S": (25,150,25), "H": (255,25,25), "M": (25,25,255), "+": (225,225,225), "-": (125,125,125) } GenreDict={ "G": "Grimdark", "S": "Sci-Fi", "H": "Hardcore", "M": "Magick" } RulesDict={ "FORM": "Counts as a Feature.\n+1 for every card matching your genre.", "FEATURE": "Play this card to your play area. You may attach Modifiers to this card.", "MODIFIER": "Play this card on your Form or any Features in your play area.", "FORM MODIFIER": "Counts as a Modifier but can be played ONLY on your own Form.", "SWITCH": "Change the sign of a card in your play area to {0}. Can be used as an Interrupt.", "GENRE CHANGE": "Change the genre of any card in your play area (even your Form). Can be used as an Interrupt." } if __name__ == "__main__": print "Not a main module. Run GameGen.py"
[ 11748, 28686, 11, 15095, 11, 4423, 346, 11, 12854, 1891, 198, 11748, 350, 4146, 62, 47429, 198, 198, 25216, 11, 37977, 2538, 11, 20444, 1581, 11, 26173, 8924, 11, 9977, 10116, 1581, 796, 2837, 7, 20, 8, 198, 17931, 23988, 15513, 796, ...
2.365609
1,198
# Copyright The PyTorch Lightning team. # # 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 typing import Any import torch from torch import nn from torch.nn import functional as F from flash import Trainer from flash.core.classification import ClassificationTask from flash.core.finetuning import NoFreeze
[ 2, 15069, 383, 9485, 15884, 354, 12469, 1074, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 1...
3.903846
208
import numpy as np from sympy import var, Lambda, exp, log, sin, cos, tan, sqrt, diff, solve ''' x = [0, 10, 20, 30, 50] y1 = [50.8, 86.2, 136, 72.8, 51] y2 = [113.6, 144.5, 185, 171.2, 95.3] y = np.array(y2) - np.array(y1) y1 = Integrais(1, 1, 1, pts=(x[3:], y[3:])) print(y1.num_trapezio()) y2 = Integrais(1, 1, 1, pts=(x[:4], y[:4])) print(y2.num_13()) print(y1.num_trapezio() + y2.num_13()) '''
[ 11748, 299, 32152, 355, 45941, 198, 6738, 10558, 88, 1330, 1401, 11, 21114, 6814, 11, 1033, 11, 2604, 11, 7813, 11, 8615, 11, 25706, 11, 19862, 17034, 11, 814, 11, 8494, 198, 220, 220, 220, 220, 220, 220, 220, 220, 198, 220, 220, ...
1.772908
251
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging from .record import Record logger = logging.getLogger(__name__) # Module API
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834,...
3.392405
79
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 8 15:00:56 2018 @author: gaurav """ w1 = 'थव' word = 'का' for i in word: print(i) word[1] new = w1+word[1] print(new)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2892, 2556, 220, 807, 1315, 25, 405, 25, 3980, 2864, 198, 198, 31, 9800, 25, 308, 2899, ...
1.87037
108
import unittest import os import zserio from testutils import getZserioApi, getApiDir
[ 11748, 555, 715, 395, 198, 11748, 28686, 198, 11748, 1976, 2655, 952, 198, 198, 6738, 1332, 26791, 1330, 651, 57, 2655, 952, 32, 14415, 11, 651, 32, 14415, 35277, 198 ]
2.9
30
from django.test import TestCase from django.shortcuts import resolve_url as r from conceptus.core.forms import StoreModelForm from conceptus.core.models import Store
[ 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 10568, 62, 6371, 355, 374, 198, 198, 6738, 3721, 385, 13, 7295, 13, 23914, 1330, 9363, 17633, 8479, 198, 6738, 3721, 385, 13, 7295, 13, ...
3.755556
45
import requests class ModioClient(object): """ A REST client for http://mod.io, hiding the ugly http requests behind a nice interface :) """ HEADERS = { 'Accept': 'application/json' } BASE_URL = "https://api.mod.io/v1" @staticmethod
[ 11748, 7007, 628, 198, 4871, 3401, 952, 11792, 7, 15252, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 317, 30617, 5456, 329, 2638, 1378, 4666, 13, 952, 11, 11816, 262, 13400, 2638, 7007, 2157, 257, 3621, 7071, 14373, 198, 220,...
2.673077
104
#!/usr/bin/python3 import sys,os,re sys.path.append( "../lib" ) sys.path.append( "./lib" ) from Controller.message import * from Controller.local import * import unittest from pprint import pprint
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 11748, 25064, 11, 418, 11, 260, 198, 17597, 13, 6978, 13, 33295, 7, 366, 40720, 8019, 1, 1267, 198, 17597, 13, 6978, 13, 33295, 7, 366, 19571, 8019, 1, 1267, 198, 198, 6738, 2274...
2.6375
80
expected_output = { "SRTE_POL_1": { "name": "SRTE_POL_1", "color": 1, "end_point": "4.4.4.4", "owners": "CLI", "status": { "admin": "down", "operational": { "state": "down", "time_for_state": "00:00:06", "since": "10-21 07:10:38.262" } }, "candidate_paths": { "preference": { 1 : { "type": "CLI", "path_type": { "dynamic": { "status": "inactive", "metric_type": "TE", } } }, }, }, "attributes": { "binding_sid": { 18: { "allocation_mode": "dynamic", "state": "programmed" } }, } } }
[ 40319, 62, 22915, 796, 1391, 198, 220, 220, 220, 366, 12562, 9328, 62, 45472, 62, 16, 1298, 1391, 198, 220, 220, 220, 220, 220, 220, 220, 366, 3672, 1298, 366, 12562, 9328, 62, 45472, 62, 16, 1600, 198, 220, 220, 220, 220, 220, 22...
1.407355
707
# Generated by Django 2.2.26 on 2022-02-25 16:28 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 2075, 319, 33160, 12, 2999, 12, 1495, 1467, 25, 2078, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.875
32
# 171 # price_list = [32100, 32150, 32000, 32500] # for i in range(0, 4): # print(price_list[i]) # 172 # price_list = [32100, 32150, 32000, 32500] # # for i in range(0, 4): # print(i, price_list[i]) # 173 # price_list = [32100, 32150, 32000, 32500] # # for i in range(0, 4): # print(3-i, price_list[i]) # 174 # price_list = [32100, 32150, 32000, 32500] # # for i in range(1, 4): # print(90+10 * i, price_list[i]) # 175 # my_list = ["가", "나", "다", "라"] # for i in range(0, 3): # print(my_list[i], my_list[i+1] ) # 176 # my_list = ["가", "나", "다", "라", "마"] # for i in range(0, 3): # i -> 2 # print(my_list[i], my_list[i+1], my_list[i+2]) # 177 # my_list = ["가", "나", "다", "라"] # # for i in range(3, 0, -1): # print(my_list[i], my_list[i-1]) # 178 # my_list = [100, 200, 400, 800] # # for i in range(0, 3): # print(my_list[i+1] - my_list[i]) # 179 # my_list = [100, 200, 400, 800, 1000, 1300] # for i in range(0, 4): # i -> 1 # hap = my_list[i] + my_list[i+1] + my_list[i+2] # my_list[1]+my_list[2]+my_list[3] # print(hap/3) # 180 # low_prices = [100, 200, 400, 800, 1000] # high_prices = [150, 300, 430, 880, 1000] # # volatility = [ ] # for i in range(5): # 0, 1, 2, 3, 4 # diff = high_prices[i] - low_prices[i] # volatility.append(diff) # # print(volatility)
[ 2, 28369, 198, 2, 2756, 62, 4868, 796, 685, 36453, 405, 11, 39595, 1120, 11, 3933, 830, 11, 29524, 405, 60, 198, 2, 329, 1312, 287, 2837, 7, 15, 11, 604, 2599, 198, 2, 220, 220, 220, 220, 3601, 7, 20888, 62, 4868, 58, 72, 1296...
1.905036
695
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: # Author: Binux<roy@binux.me> # http://binux.me # Created on 2015-04-05 00:05:58 import sys import time import unittest2 as unittest from pyspider.libs import counter
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 43907, 25, 900, 2123, 1509, 28, 19, 40379, 28, 19, 39747, 28, 19, 31246, 28, 403, 844, 277, 12685, 28, 40477, 23...
2.247934
121
''' - Author: Zhengxiang (Jack) Wang - Date: 2021-08-25 - GitHub: https://github.com/jaaack-wang - About: Some handy wrapper functions for handling xml files. ''' from bs4 import BeautifulSoup as bs from lxml import etree from os.path import join def readXML(filepath): ''''Reads XML files as bs4.BeautifulSoup type.''' return bs(open(filepath, "rb"), "xml") def _get_node(soup, filepath, node_name, as_str=False): '''An abstract implementation for get_node.''' node = soup.find(node_name) if node: if as_str: return node.prettify() return node else: print(f"\033[32mNodeNotFound\033[0m: \"{node_name}\" not found in {filepath}." \ " Return empty string instead.") return "" def get_node(filepath, node_name, as_str=False): '''Returns the first node given a xml's filepath and the node_name. If as_str set True, returns formatted str. Otherwise, bs4.element.Tag. If the node_name is not found, returns an empty string.''' return _get_node(readXML(filepath), filepath, node_name, as_str) def get_nodes(filepath, node_name): '''Returns all bs4.element.Tags in a given xml file related to the queried node_name if any. Otherwise, Return NoneType.''' nodes = readXML(filepath).find_all(node_name) if nodes: return nodes else: print(f"\033[32mNodeNotFound\033[0m: \"{node_name}\" not found in {filepath}. Return None.") return def get_header(filepath, head_node, as_str=False): '''Return the header of a xml file.''' return get_node(filepath, head_node, as_str) def get_body(filepath, body_node, as_str=False): '''Return the body part of a xml file.''' return get_node(filepath, body_node, as_str) def get_header_body_as_str(filepath, head_node, body_node): '''Return formatted header and body parts of a xml file as str. If a node name is not found, return an empty string''' soup = readXML(filepath) header = _get_node(soup, filepath, head_node, as_str=True) body = _get_node(soup, filepath, body_node, as_str=True) return header, body def createXmlFileFromStr(filename=None, root_name="TEI.2", header="", body="", dst_dir="./", save=True): '''Creates a XML file given a set of xml-formatted strings. Args: - filename(str): filename for the new xml file, defaults to None. - root_name(str): the name of the first super node for the xml file, defaults to "TEI.2". The root name is loosely used. Does not refer to the real conceptual root. - header(str): xml-like string, header part, defaults to empty str. - body(str): xml-like string, body part, defaults to empty str. - dst_dir(str): path-like string. If not given, defaults to the current dir. - save(bool): whether to save, defaluts to True. Return: - if save set False, return lxml.etree._ElementTree. Otherwise, no returns. ''' if not filename: save = False else: filename = filename if filename.endswith('.xml') else filename + '.xml' content = f'<{root_name}>' + header + body + f'</{root_name}>' try: content = bs(content, 'xml').prettify() content = content.replace('<?xml version="1.0" encoding="utf-8"?>\n', '') except Exception as e: print(f"\033[32mGenerated XML text for {filename} cannot be prettified\033[0m due to ", e) print("But this has no really bad effects on the created xml file other than being less" \ " pretty when read in plain text software.") parser = etree.XMLParser(recover=True) try: root = etree.fromstring(content, parser=parser) tree = etree.ElementTree(root) if save: filepath = join(dst_dir, filename) tree.write(filepath) print(filepath + " has been created!") else: return tree except Exception as e: print(f"\033[1m\033[31mA problem creating {join(dst_dir, filename)} as follows: \033[0m{e}\n")
[ 7061, 6, 198, 12, 6434, 25, 44583, 87, 15483, 357, 14295, 8, 15233, 220, 198, 12, 7536, 25, 33448, 12, 2919, 12, 1495, 198, 12, 21722, 25, 3740, 1378, 12567, 13, 785, 14, 6592, 64, 441, 12, 47562, 220, 198, 12, 7994, 25, 2773, 1...
2.455516
1,686
# Copyright 2018 The Cirq Developers # # 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. from typing import Iterable, List import random import numpy as np import pytest import cirq from cirq.google import decompositions @pytest.mark.parametrize('intended_effect', [ np.array([[0, 1j], [1, 0]]), ] + [ cirq.testing.random_unitary(2) for _ in range(10) ]) @pytest.mark.parametrize('pre_turns,post_turns', [(random.random(), random.random()) for _ in range(10)]) @pytest.mark.parametrize('mat', [ np.eye(2), cirq.unitary(cirq.H), cirq.unitary(cirq.X), cirq.unitary(cirq.X**0.5), cirq.unitary(cirq.Y), cirq.unitary(cirq.Z), cirq.unitary(cirq.Z**0.5), ] + [ cirq.testing.random_unitary(2) for _ in range(10) ])
[ 2, 15069, 2864, 383, 21239, 80, 34152, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921,...
2.563353
513
from sc2 import UnitTypeId from sc2.ids.ability_id import AbilityId from .act_base import ActBase # Act of researching a technology or upgrade
[ 6738, 629, 17, 1330, 11801, 6030, 7390, 201, 198, 6738, 629, 17, 13, 2340, 13, 1799, 62, 312, 1330, 20737, 7390, 201, 198, 201, 198, 6738, 764, 529, 62, 8692, 1330, 2191, 14881, 201, 198, 201, 198, 201, 198, 2, 2191, 286, 24114, 2...
3.122449
49
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 11, 15720, 602, 628 ]
2.891892
37
import unittest from datetime import datetime import requests_mock from chartmogul import Config, Activity class ActivitiesTestCase(unittest.TestCase): """ Tests CustomerActivities """ @requests_mock.mock()
[ 11748, 555, 715, 395, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 11748, 7007, 62, 76, 735, 198, 198, 6738, 8262, 76, 519, 377, 1330, 17056, 11, 24641, 628, 198, 4871, 36270, 14402, 20448, 7, 403, 715, 395, 13, 14402, 20448, ...
2.986842
76
from rest_framework.routers import DefaultRouter from .views import ( PerfilViewSet, EnderecoViewSet, TelefoneViewSet, OutroEmailViewSet, CargoViewSet, DepartamentoViewSet ) router = DefaultRouter() router.register(r'perfis', PerfilViewSet, basename='perfil') router.register(r'enderecos', EnderecoViewSet, basename='endereco') router.register(r'telefones', TelefoneViewSet, basename='telefone') router.register(r'outros-emails', OutroEmailViewSet, basename='outroemail') router.register(r'cargos', CargoViewSet, basename='cargo') router.register(r'departamentos', DepartamentoViewSet, basename='departamento')
[ 6738, 1334, 62, 30604, 13, 472, 1010, 1330, 15161, 49, 39605, 198, 198, 6738, 764, 33571, 1330, 357, 198, 220, 220, 220, 2448, 10379, 7680, 7248, 11, 198, 220, 220, 220, 5268, 567, 1073, 7680, 7248, 11, 198, 220, 220, 220, 14318, 69...
2.694915
236
"""Unit test package for bettersocket."""
[ 37811, 26453, 1332, 5301, 329, 731, 1010, 5459, 526, 15931, 198 ]
3.818182
11
import collections import numpy as np import matplotlib import matplotlib.gridspec import matplotlib.pyplot as plt import scipy.optimize from helper import load, mean8, cropsave, grendel_dir """ SUBTILE POPULATION N = 512³, nprocs = 64. Two panels (left & right, spanning two cols). Left: Subtile population at z = 0 for various box sizes. Right: Subtile population over time for a particular box size. """ textwidth = 504 # mnras: 240 (single-column), 504 (both columns) width = textwidth/72.27 height = 2.84 # The general font size is 9 but in captions it is 8. # We choose to match this exactly. fontsize = 8 #9/1.2 latex_preamble = r''' \usepackage{lmodern} \usepackage{amsmath} \usepackage{amsfonts} \usepackage{mathtools} \usepackage{siunitx} \usepackage{xfrac} \usepackage{relsize} ''' matplotlib.rcParams.update({ 'text.usetex' : True, 'font.family' : 'serif', 'font.serif' : 'cmr10', 'font.size' : fontsize, 'mathtext.fontset' : 'cm', 'axes.formatter.use_mathtext': True, 'text.latex.preamble': latex_preamble, }) # Load cache_assume_uptodate = True output_dir = f'{grendel_dir}/powerspec/boxsize_scaling/64' infos_boxsize_time = load(output_dir, 'time', check_spectra=0, cache_assume_uptodate=cache_assume_uptodate) boxsize_max = 1024 infos_boxsize_time = {k: v for k, v in infos_boxsize_time.items() if k <= boxsize_max} # Plot fig, axes = plt.subplots(1, 2, figsize=(width, height)) boxsizes = np.array(sorted(list(infos_boxsize_time.keys()))) N = 512**3 nprocs = 64 subtiling_populations = [np.array(infos_boxsize_time[boxsize]['data'][-3].subtiling) for boxsize in boxsizes] subtiling_populations_padded = [] subtiling_max = 10 for i in range(1, subtiling_max + 1): tmp = [] for subtiling_population in subtiling_populations: tmp.append(collections.Counter(subtiling_population)[i]) #if i < len(subtiling_population): # tmp.append(subtiling_population[i]) #else: # tmp.append(0) subtiling_populations_padded.append(tmp) labels = [f'${boxsize}$' for boxsize in boxsizes] width = 0.24 i = subtiling_max + 1 running = np.zeros(len(boxsizes)) ax = axes[0] for subtiling_population_padded in reversed(subtiling_populations_padded): i -= 1 Y = np.array(subtiling_population_padded)/nprocs ax.bar(boxsizes, Y, width*boxsizes, bottom=running, label=rf'${i}\times {i}\times {i}$', color=f'C{i-1}') running += Y #ax.set_yscale('log') ymin = 0 ax.set_ylim(ymin, 1) ax.set_xscale('log') ax.invert_xaxis() #ax.legend() #handles, labels = ax.get_legend_handles_labels() #ax.legend(handles[::-1], labels[::-1], loc='center right') ax.set_xlabel('$L_{\mathrm{box}}\; [\mathrm{Mpc}/h]$') ax.set_ylabel('subtile distribution') ax_bot = ax ax_top = ax.twiny() frac = 1.125 ax_bot.set_xlim(boxsizes[0]/frac, boxsizes[-1]*frac) ax_bot.set_xticks(boxsizes) ax_bot.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter()) ax_bot.tick_params(axis='x', which='minor', bottom=False) ax_bot.invert_xaxis() boxsizes_axis = [] boxsize = boxsize_max while boxsize > 48: boxsizes_axis.append(boxsize) boxsizes_axis.append(boxsize//4*3) boxsize //= 2 boxsizes_axis.pop() boxsizes_axis.pop() boxsizes_axis = np.array(boxsizes_axis[::-1]) #ax_bot.set_xlim(boxsizes_axis[0], boxsizes_axis[-1]) ax_bot.set_xticks(boxsizes_axis) ax_bot.set_xticklabels([f'${b}$' for b in boxsizes_axis], rotation=34, ha='right', rotation_mode='anchor') k_Nyquist = 2*np.pi/boxsizes[::-1]*(512/2) xticks = np.log(k_Nyquist) xticks -= xticks[0] xticks = [xtick/xticks[-1] for xtick in xticks] xticklabels = [f'${k:.3g}$' for k in k_Nyquist] ax_top.set_xticks(xticks) #ax_top.set_xticklabels(xticklabels) ax_top.set_xticklabels(xticklabels, rotation=34, ha='left', rotation_mode='anchor') frac *= 0.98 # unexplained ax_top.set_xlim(0 - np.log10(frac), 1 + np.log10(frac)) ax_top.set_xlabel('$k_{\mathrm{Nyquist}}\; [h/\mathrm{Mpc}]$') # Right panel box = 128 ax = axes[1] time_steps = np.arange(len(infos_boxsize_time[box]['data'])) #ax.semilogy( # time_steps, # np.random.random(len(time_steps)), # '-', #) time_step_info = infos_boxsize_time[box]['data'] highest_subtiling = subtiling_max population = {i: np.zeros(len(time_step_info), dtype=int) for i in range(1, highest_subtiling + 1)} for step, d in enumerate(time_step_info): counter = collections.Counter(d.subtiling) for i in range(1, highest_subtiling + 1): population[i][step] += counter[i] # rp = list(d.subtiling) # for i, pop in enumerate(rp, 1): # if i > highest_subtiling: # i = highest_subtiling # population[i][step] += pop x = [d.time_step for d in time_step_info] population_fraction = list(population.values()) NN = np.sum([_[0] for _ in population_fraction]) population_fraction_new = [] for arr in population_fraction: l = 16 arr = list(arr) + [arr[-1]]*l meanarr = mean8(np.array(arr)/NN, period=16, n_steps=len(time_steps)+l) meanarr = meanarr[:-l] population_fraction_new.append( #np.array(_)/NN meanarr ) population_fraction = population_fraction_new ax.stackplot( x[len(x) - len(population_fraction[0]):], population_fraction[::-1], labels=[rf'${i}\times {i}\times {i}$' for i in range(1, highest_subtiling + 1)][::-1], colors=[ np.asarray(matplotlib.colors.ColorConverter().to_rgb(f'C{i-1}'), dtype=float) for i in range(1, highest_subtiling + 1) ][::-1], ) #ax.set_yscale('log') #ax.set_ylim(1e-5, 1) # Convert x axis to redshift, keeping it linear in time steps first_step_to_show = 12 ax.set_xlim(time_steps[first_step_to_show], time_steps[-1]) zticks = [99, 40, 20, 10, 5, 3, 2, 1, 0.5, 0] zticks = zticks[2:] z_timesteps = np.array([ 1/infos_boxsize_time[box]['data'][i].scale_factor - 1 for i in time_steps ]) xticks = [ np.interp(1/ztick, 1/z_timesteps, time_steps) if ztick > 0 else time_steps[-1] for ztick in zticks ] ax.set_xticks(xticks) ax.set_xticklabels([str(ztick) for ztick in zticks]) ax.set_xlabel('$z$') # Legend ax.legend() handles, labels = ax.get_legend_handles_labels() ax.legend(handles[::-1], labels[::-1], loc='upper left', framealpha=0.6) # "Inout" via plotted lines for y in (0.2, 0.4, 0.6, 0.8): ax.plot([9.4, 14.6], [y]*2, 'k', clip_on=False, zorder=np.inf, lw=0.75) #ax.tick_params('y', direction='inout', which='both') ax.yaxis.tick_right() ax.set_ylim(ymin, 1) #ax.set_yscale('log') #ax.set_yticks([1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1e-0]) #ax.set_yticklabels() ax.set_ylabel('subtile distribution') ax.yaxis.set_label_position('right') #ax.text(0.5, 0.5, rf'$L_{{\text{{box}}}} = {box}\,\mathrm{{Mpc}}/h$', transform=ax.transAxes) ax.set_title(rf'$L_{{\text{{box}}}} = \SI{{{box}}}{{Mpc}}/h$', fontsize=fontsize) #for ax in axes: # ax.set_yticks([1, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6]) # ax.set_yticklabels([r'$1$', r'$10^{-1}$', '$10^{-2}$', '$10^{-3}$', '$10^{-4}$', '$10^{-5}$', '$10^{-6}$']) # Save fig.subplots_adjust(wspace=0, hspace=0) cropsave(fig, '../figure/subtile.pdf') # no tight_layout() or bbox_inches()
[ 11748, 17268, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 198, 11748, 2603, 29487, 8019, 13, 2164, 2340, 43106, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 629, 541, 88, 13, 40085, 10...
2.220811
3,229
# find the species that should be the outgroup based solely on DNA sequence data # given in "phylo seqs.txt". Assumes the sequences are already aligned. # # python 3.6 # Oct 21, 2017 from my_lib import load_list from pprint import pprint as pp seqs = load_list("phylo seqs2.txt") seqs[0] = seqs[0][1:] pp(seqs) results = find_diffs(seqs) pp(results) # score positions scores = [] for i in results: pos_score = [] for j in i[1]: score = i[1].count(j) / len(i[1]) pos_score.append(score) scores.append(pos_score) # pp(scores) species_scores = [] for i in range(len(seqs)): species_scores.append(0) pp(species_scores) for i in scores: for j in range(len(i)): species_scores[j] += i[j] pp(species_scores) outgroup = species_scores.index(min(species_scores))+1 print(outgroup) print(seqs[outgroup-1])
[ 2, 1064, 262, 4693, 326, 815, 307, 262, 503, 8094, 1912, 9944, 319, 7446, 8379, 1366, 201, 198, 2, 1813, 287, 366, 746, 2645, 78, 33756, 82, 13, 14116, 1911, 2195, 8139, 262, 16311, 389, 1541, 19874, 13, 201, 198, 2, 201, 198, 2, ...
2.264631
393
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.orm import ( scoped_session, sessionmaker, relationship, backref ) DBSession = scoped_session(sessionmaker()) Base = declarative_base()
[ 6738, 44161, 282, 26599, 13, 2302, 13, 32446, 283, 876, 1330, 2377, 283, 876, 62, 8692, 198, 6738, 44161, 282, 26599, 13, 579, 13, 41194, 1330, 1400, 23004, 21077, 198, 6738, 44161, 282, 26599, 13, 579, 1330, 357, 198, 220, 220, 220, ...
2.884211
95
# -*- coding: utf-8 -*- import tarfile import os from tempfile import NamedTemporaryFile import librsync from dirtools import Dir class SigVault(object): """ Helper for choosing SigVault{Reader/Writer}. """ @classmethod bltn_open = open open_vault = SigVault.open
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 13422, 7753, 198, 11748, 28686, 198, 6738, 20218, 7753, 1330, 34441, 12966, 5551, 8979, 198, 198, 11748, 300, 2889, 27261, 198, 198, 6738, 13647, 10141, 1330, 36202, ...
2.876289
97
import attr import logging from .token import get_token from .caster import SlackCaster __all__ = ['SlackLogger'] log = logging.getLogger(__name__) @attr.s
[ 11748, 708, 81, 198, 11748, 18931, 198, 198, 6738, 764, 30001, 1330, 651, 62, 30001, 198, 6738, 764, 17970, 1330, 36256, 34, 1603, 198, 198, 834, 439, 834, 796, 37250, 11122, 441, 11187, 1362, 20520, 198, 198, 6404, 796, 18931, 13, 11...
2.875
56
#!/usr/bin/env python # encoding: utf-8 ''' @author: caroline @license: (C) Copyright 2019-2022, Node Supply Chain Manager Corporation Limited. @contact: caroline.fang.cc@gmail.com @software: pycharm @file: Utils.py @time: 2019/12/23 10:56 下午 @desc: ''' import xlrd import xlwt def get_real_value(value): """ 获取真实值,由于xlrd读取excel的整数时使用float表示,导致整数带有小数点,所以这里需要做处理 :param value: :return: """ if type(value) is float: if value % 1 == 0: return int(value) return value def excel_read(path, sheet_index=0): """ 读取Excel文件 :param path: 文件路径,包含文件名称 :param sheet_index: Excel表单索引 """ workbook = xlrd.open_workbook(path) sheet = workbook.sheet_by_index(sheet_index) rows = sheet.nrows data = [] for r in range(rows): data.append(list(map(get_real_value, sheet.row_values(r)))) return data def excel_read_dict(path, sheet_index=0): """ 读取Excel文件\n :param path: 文件路径,包含文件名称 :param sheet_index: Excel表单索引 """ workbook = xlrd.open_workbook(path) sheet = workbook.sheet_by_index(sheet_index) header = sheet.row_values(0) rows = [] for r in range(1, sheet.nrows): row_values = sheet.row_values(r) row_dict = {} for c in range(sheet.ncols): cell_value = get_real_value(row_values[c]) row_dict[header[c]] = cell_value rows.append(row_dict) return rows def excel_write(path, rows): """ 将数据写入Excel文件\n :param path: 文件路径,包含文件名称 :param rows: 二维数组数据列表 """ workbook = xlwt.Workbook(encoding='utf-8') # 创建表 worksheet = workbook.add_sheet('sheet 0') # 写数据 for row_index in range(len(rows)): row = rows[row_index] for col_index in range(len(row)): cell = row[col_index] worksheet.write(row_index, col_index, label=cell) # 保存 workbook.save(path) if __name__ == '__main__': excel_write('test.xls', [['编号', '姓名', '年龄'], ['1', '小明', 10], ['2', '花花', 8]]) excel_write('./before_price.xls', [['发送者', '接收者', '交易金额', '发送者交易前余额', '接收者交易前余额'], ["sendAccount", "receiveAccount", "price", "send_account_balance_before", "receive_account_balance_before"]]) print(excel_read_dict('test.xls'))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 21004, 25, 3384, 69, 12, 23, 198, 7061, 6, 198, 31, 9800, 25, 1097, 14453, 198, 31, 43085, 25, 357, 34, 8, 15069, 13130, 12, 1238, 1828, 11, 19081, 22663, 21853, 9142, 10501, 15...
1.691114
1,418
## Import The Modules import stox import pandas as pd stock_list = ['FB','AAPL','AMZN','NFLX','GOOG'] ## List Of Stocks You Would Want To Buy number_of_stocks = len(stock_list) print(number_of_stocks) x = 0 starting_cash = 10000 ## Amount Of Money In Trading Account current_cash = starting_cash percent_to_spend = 5 money_to_spend = (5/100)*percent_to_spend while x < number_of_stocks: ticker = stock_list[x] ## Get The Current Ticker Symbol data = stox.stox.exec(ticker,'list') ## Get Analysis From Stox ## Import All Needed Data (Price, Prediction, Analysis, etc.) df = pd.DataFrame() df['Ticker'] = ticker df['Price'] = data[1] df['Prediction'] = data[2] df['Analysis'] = data[3] df['DateFor'] = data[4] good_pct = data[1]*0.02 minus_pct = good_pct*-1 ## Run Scan For Buy/Up/Down/Sell if data[2] - data[1] >= good_pct: if data[3] == "Bullish (Starting)": df['Signal'] = "Buy" if money_to_spend <= current_cash: ## Check If Enough Money Left price = df.Price amt = price current_cash = buy(ticker, price, amt) ## Call Buy Function print("Bought "+ticker) else: print("Not Enough Money Left!") elif data[3] == "Bullish (Already)": df['Signal'] = "Up" print(ticker+" is in a Uptrend") elif data[2] - data[1] <= minus_pct: if data[3] == "Bearish (Starting)": df['Signal'] = "Sell" if money_to_spend <= current_cash: ## Check If Enough Money Left price = df.Price amt = price current_cash = short(ticker, price, amt) ## Call Short Function print("Shorted "+ticker) else: print("Not Enough Money Left!") elif data[3] == "Bearish (Already)": df['Signal'] = "Down" print(ticker+" is in a Downtrend") else: df['Signal'] = "None" print("No Signal For "+ticker) x = x+1 print("Done") ## Print 'Done' After Complete
[ 2235, 17267, 383, 3401, 5028, 198, 11748, 336, 1140, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 13578, 62, 4868, 796, 37250, 26001, 41707, 32, 2969, 43, 41707, 2390, 57, 45, 41707, 32078, 55, 41707, 38, 6684, 38, 20520, 22492, 73...
2.128283
990
# Using Filter Func # It will filter numer which is less than zero number_list = range(-5, 5) less_than_zero = list(filter(lambda x:x<0, number_list)) print(less_than_zero)
[ 2, 8554, 25853, 11138, 66, 198, 2, 632, 481, 8106, 5470, 543, 318, 1342, 621, 6632, 198, 17618, 62, 4868, 796, 2837, 32590, 20, 11, 642, 8, 198, 1203, 62, 14813, 62, 22570, 796, 1351, 7, 24455, 7, 50033, 2124, 25, 87, 27, 15, 11...
2.965517
58
from process.domain.aps.ApSchedulerEvent import ApSchedulerEvent from process.domain.aps.ApSchedulerJob import ApSchedulerJob from process.domain.aps.ApSchedulerJobEvent import ApSchedulerJobEvent
[ 6738, 1429, 13, 27830, 13, 1686, 13, 25189, 50, 1740, 18173, 9237, 1330, 5949, 50, 1740, 18173, 9237, 198, 6738, 1429, 13, 27830, 13, 1686, 13, 25189, 50, 1740, 18173, 33308, 1330, 5949, 50, 1740, 18173, 33308, 198, 6738, 1429, 13, 27...
3.338983
59
r"""Generate the physics of a hypothetical 2-D spherical world, and then generate seismic events and detections. Based on the codebase of: Nimar Arora https://github.com/nimar/seismic-2d/blob/master/generate.py """ import hypothesis import numpy as np import torch from hypothesis.simulation import Simulator as BaseSimulator
[ 81, 37811, 8645, 378, 262, 11887, 286, 257, 25345, 362, 12, 35, 43180, 995, 11, 290, 788, 7716, 198, 325, 1042, 291, 2995, 290, 4886, 507, 13, 198, 198, 15001, 319, 262, 2438, 8692, 286, 25, 27168, 283, 943, 5799, 3740, 1378, 12567,...
3.484211
95
#!/usr/bin/python3 from random import randint lst = [1, 4, 6, 2, 7, 8, 9, 10, 4, 6, 1] print(lst) ########## Recherche d'un element ########### print("Looking for 6:") print(search_truth(6, lst)) print(search_id(6, lst)) print(search_pos(6, lst)) print(search_s(6, lst)) ############# Recherche d'un mot ############ print("Looking for [2, 7, 8]:") print(search_word([2, 7, 8], lst)) print(search_word_sl([2, 7, 8], lst)) print("Looking for [1, 7, 1]:") print(search_word_nc([1, 7, 1], lst)) ############## Recherche dichotomique ############ print(search_dico_alea(5, range(30))) print(search_dico(5, range(30)))
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 6738, 4738, 1330, 43720, 600, 198, 198, 75, 301, 796, 685, 16, 11, 604, 11, 718, 11, 362, 11, 767, 11, 807, 11, 860, 11, 838, 11, 604, 11, 718, 11, 352, 60, 198, 4798, 7, 75, 30...
2.392308
260
############################################################################## # # Copyright (c) 2008 Zope Foundation and Contributors. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Namespace for CMF specific add views. """ from zope.component import adapts from zope.component import getUtility from zope.component import queryMultiAdapter from zope.interface import Interface from zope.interface import implementer from zope.location.interfaces import LocationError from zope.traversing.interfaces import ITraversable from .interfaces import IFolderish from .interfaces import ITypesTool @implementer(ITraversable) class AddViewTraverser(object): """Add view traverser. """ adapts(IFolderish, Interface)
[ 29113, 29113, 7804, 4242, 2235, 198, 2, 198, 2, 15069, 357, 66, 8, 3648, 1168, 3008, 5693, 290, 25767, 669, 13, 198, 2, 198, 2, 770, 3788, 318, 2426, 284, 262, 8617, 286, 262, 1168, 3008, 5094, 13789, 11, 198, 2, 10628, 362, 13, ...
3.834437
302
import os, sys help_msg = """ Usage: python remove_file_by_path.py list_file Note: 1. list_file contains a full file path list, such as: /sa/sample/normal/file_1 /sa/sample/normal/file_2 ... /sa/sample/normal/file_n """ if len(sys.argv) != 2: print help_msg exit(-1) with open(sys.argv[1], 'r') as fh: for line in fh.readlines(): file_path = line.strip() if os.path.exists(file_path): os.remove(file_path) else: print "[ERROR] cannot find " + file_path
[ 11748, 28686, 11, 25064, 198, 198, 16794, 62, 19662, 796, 37227, 198, 28350, 25, 198, 197, 29412, 4781, 62, 7753, 62, 1525, 62, 6978, 13, 9078, 1351, 62, 7753, 198, 198, 6425, 25, 198, 197, 16, 13, 1351, 62, 7753, 4909, 257, 1336, ...
2.3
210
# Generated by Django 2.2.10 on 2020-03-14 10:35 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 940, 319, 12131, 12, 3070, 12, 1415, 838, 25, 2327, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.875
32
#!/usr/bin/env python3 import sys, calendar, datetime, time from ii_functions import * args=sys.argv[1:] if len(args) < 2: print("Usage: archive.py echoarea YYYY.MM.DD") quit() date = args[1].split(".") date = calendar.timegm(datetime.date(int(date[0]), int(date[1]), int(date[2])).timetuple()) echoarea = getMsgList(args[0]) if len(echoarea) == 0: print("Echoarea is empty or it does not exist.") sys.exit(1) bundle = "" for msgid in echoarea: if len(msgid) == 20: msg=read_file(msgdir+msgid) if msg == "": print("msgid " + msgid + " is empty, continue") continue msgdate = int(getMsg(None, from_string=msg)["time"]) if msgdate < date: print("saving " + msgid) bundle += msgid+":"+b64c(msg)+"\n" filename=args[0] + "_" + args[1] + "_" + str(int(time.time())) + ".bundle" try: output=open(filename, "w") output.write(bundle) output.close() print("Бандл сохранён под именем "+ filename) except: print("Не могу открыть файл "+ filename +" для записи!") sys.exit(1)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 25064, 11, 11845, 11, 4818, 8079, 11, 640, 198, 6738, 21065, 62, 12543, 2733, 1330, 1635, 198, 198, 22046, 28, 17597, 13, 853, 85, 58, 16, 47715, 198, 198, 361, 18896...
2.205298
453
#!/usr/bin/python3 import os import logging import json from datetime import datetime import requests class FileNotFound(Exception): '''Exception class for file checking''' class Model: '''Class for managing requests''' def __init__(self, name): '''Constructor''' logging.info('init()') self.server_address = '' self.auth = '' self.time_changed = datetime.now() self.state = 'ON' self.name = name def get_settings(self): '''Get config env var''' logging.info('get_settings()') config_name = '/home/{}/Documents/HouseGuardServices/config.json' config_name = config_name.format(self.name) try: if not os.path.isfile(config_name): raise FileNotFound('File is missing') with open(config_name) as file: data = json.load(file) self.server_address = '{}/alarm'.format(data["server_address"]) except KeyError: logging.error("Variables not set") except FileNotFound: logging.error("File is missing") def publish_data(self): '''Send data to server if asked''' try: address = "{}/{}".format(self.server_address, self.state) response = requests.post(address, timeout=5) if response.status_code == 200: logging.info("Requests successful") else: logging.error('Response: {}'.format(response)) except requests.ConnectionError as error: logging.error("Connection error: {}".format(error)) except requests.Timeout as error: logging.error("Timeout on server: {}".format(error))
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 11748, 28686, 198, 11748, 18931, 198, 11748, 33918, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 7007, 628, 198, 4871, 9220, 3673, 21077, 7, 16922, 2599, 198, 220, 220, 220, ...
2.286842
760
from django_rest_admin.register import rest_admin from .models import TextContent rest_admin.register(TextContent)
[ 6738, 42625, 14208, 62, 2118, 62, 28482, 13, 30238, 1330, 1334, 62, 28482, 198, 6738, 764, 27530, 1330, 8255, 19746, 198, 198, 2118, 62, 28482, 13, 30238, 7, 8206, 19746, 8, 198 ]
3.625
32
# # Copyright (c) 2016 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # from django.utils.translation import ugettext_lazy as _ from horizon import tabs from starlingx_dashboard.dashboards.admin.providernets \ import tabs as project_tabs
[ 2, 198, 2, 15069, 357, 66, 8, 1584, 3086, 5866, 11998, 11, 3457, 13, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 2, 198, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 334, 1136, ...
2.966292
89
import os USBFile = open('test.txt.', 'r') i = 0 for line1 in USBFile: i += 1 for line
[ 11748, 28686, 198, 198, 27155, 8979, 796, 1280, 10786, 9288, 13, 14116, 2637, 11, 705, 81, 11537, 198, 198, 72, 796, 657, 198, 198, 1640, 1627, 16, 287, 8450, 8979, 25, 198, 220, 220, 220, 1312, 15853, 352, 628, 220, 220, 220, 329, ...
2.227273
44
from django.http import HttpResponse from django.http import Http404 from dojango.decorators import json_response from django.utils.translation import ugettext as _ from datable.core import formats from datetime import datetime from urllib.parse import urlencode class Table(object): """A table, which may be presented as JSON or XLS or CSV. """ filename = None columns = None widgets = None primaryKeySerializer = None def filterAndSort(self, request, method="GET"): """This function performs filtering and sorting of a QuerySet, based on settings found in request, sent by method (POST, GET)""" requestDict = getattr(request, method) sortColumn = self.getSortColumn(requestDict) return self.storage.filterAndSort(requestDict, sortColumn) def willHandle(self, request, method="GET"): """Will this datable handle this request?""" requestDict = getattr(request, method) if self.name in requestDict: return True @json_response
[ 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 26429, 198, 6738, 466, 73, 14208, 13, 12501, 273, 2024, 1330, 33918, 62, 26209, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1...
2.92437
357
from .vector_math import * # from quicktracer import trace # Note: "score" in this file is not scoring a goal, but an arbitrary reward class PosVelScorer(Scorer): """docstring for PosVel"""
[ 6738, 764, 31364, 62, 11018, 1330, 1635, 198, 2, 422, 2068, 2213, 11736, 1330, 12854, 198, 198, 2, 5740, 25, 366, 26675, 1, 287, 428, 2393, 318, 407, 9689, 257, 3061, 11, 475, 281, 14977, 6721, 198, 198, 4871, 18574, 46261, 3351, 11...
3.322034
59
import pytest from rosny.state import CommonState @pytest.fixture(scope='function')
[ 11748, 12972, 9288, 198, 6738, 686, 82, 3281, 13, 5219, 1330, 8070, 9012, 628, 198, 31, 9078, 9288, 13, 69, 9602, 7, 29982, 11639, 8818, 11537, 628 ]
3.222222
27
from mtools.mplotqueries.plottypes.base_type import BasePlotType import argparse import types import re import numpy as np try: from matplotlib.dates import date2num, num2date except ImportError: raise ImportError("Can't import matplotlib. See https://github.com/rueckstiess/mtools/blob/master/INSTALL.md for \ instructions how to install matplotlib or try mlogvis instead, which is a simplified version of mplotqueries \ that visualizes the logfile in a web browser.") from mtools.util.log2code import Log2CodeConverter def opened_closed(logevent): """ inspects a log line and groups it by connection being openend or closed. If neither, return False. """ if "connection accepted" in logevent.line_str: return "opened" elif "end connection" in logevent.line_str: return "closed" else: return False class ConnectionChurnPlotType(BasePlotType): """ plots a histogram plot over all logevents. The bucket size can be specified with the --bucketsize or -b parameter. Unit is in seconds. """ plot_type_str = 'connchurn' timeunits = {'sec':1, 's':1, 'min':60, 'm':1, 'hour':3600, 'h':3600, 'day':86400, 'd':86400} sort_order = 1 def accept_line(self, logevent): """ only return lines with 'connection accepted' or 'end connection'. """ return opened_closed(logevent) @classmethod def color_map(cls, group): """ change default color behavior to map certain states always to the same colors (similar to MMS). """ colors = {'opened': 'green', 'closed':'red', 'total':'black'} return colors[group], cls.markers[0] def clicked(self, event): """ print group name and number of items in bin. """ group = event.artist._mt_group n = event.artist._mt_n dt = num2date(event.artist._mt_bin) print "%4i connections %s in %s sec beginning at %s" % (n, group, self.bucketsize, dt.strftime("%b %d %H:%M:%S"))
[ 6738, 285, 31391, 13, 76, 29487, 421, 10640, 13, 29487, 19199, 13, 8692, 62, 4906, 1330, 7308, 43328, 6030, 198, 11748, 1822, 29572, 198, 11748, 3858, 198, 11748, 302, 198, 11748, 299, 32152, 355, 45941, 198, 198, 28311, 25, 198, 220, ...
2.738589
723
#peca um ano e diga se o ano é bisexto from datetime import date ano = int(input('Digite um ano: ')) resto_quatro = ano % 4 resto_cem = ano % 100 if ano == 0: ano = date.today().year if resto_quatro == 0 and resto_cem > 0: print('Ano {} é bisexto'.format(ano)) else: print('{} Não é bisexto'.format(ano))
[ 2, 431, 6888, 23781, 281, 78, 304, 3100, 64, 384, 267, 281, 78, 38251, 275, 786, 742, 78, 198, 6738, 220, 4818, 8079, 1330, 3128, 198, 5733, 796, 493, 7, 15414, 10786, 19511, 578, 23781, 281, 78, 25, 705, 4008, 198, 198, 2118, 78,...
2.248227
141
from django.contrib.auth.decorators import login_required from django.core.checks import messages from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from pbal.forms import ( PbalLibraryForm, PbalLibrarySampleDetailInlineFormset, PbalLibraryConstructionInfoInlineFormset, PbalLibraryQuantificationAndStorageInlineFormset, PbalSequencingForm, PbalLaneForm, PlateForm) from core.helpers import Render from core.views import ( LibraryList, LibraryDetail, LibraryDelete, LibraryCreate, LibraryUpdate, SequencingList, SequencingCreate, SequencingUpdate, SequencingDelete, LaneCreate, LaneUpdate, SequencingDetail, LaneDelete) from .models import PbalLibrary, PbalSequencing, PbalLane, Plate #============================ # Plate views #---------------------------- @Render("core/plate_create.html") @login_required @Render("core/plate_update.html") @login_required @Render("core/plate_delete.html") @login_required
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 12501, 273, 2024, 1330, 17594, 62, 35827, 198, 6738, 42625, 14208, 13, 7295, 13, 42116, 1330, 6218, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 7738, 1060, 198, 6738, 426...
3.183801
321
# Copyright 2021 MosaicML. All Rights Reserved. from composer.models.classify_mnist.mnist_hparams import MnistClassifierHparams as MnistClassifierHparams from composer.models.classify_mnist.model import MNIST_Classifier as MNIST_Classifier _task = 'Image Classification' _dataset = 'MNIST' _name = 'SimpleConvNet' _quality = '' _metric = 'Accuracy' _ttt = '?' _hparams = 'classify_mnist_cpu.yaml'
[ 2, 15069, 33448, 5826, 18452, 5805, 13, 1439, 6923, 33876, 13, 198, 198, 6738, 26777, 13, 27530, 13, 4871, 1958, 62, 10295, 396, 13, 10295, 396, 62, 71, 37266, 1330, 36030, 396, 9487, 7483, 39, 37266, 355, 36030, 396, 9487, 7483, 39, ...
2.933824
136
import os from flask import Flask from flask import request from flask import render_template from flask import send_from_directory import db import abstractDriver import messageAnnouncer from api import dbAPI from story import Story from api import adminAPI from api import streamAPI from api import scrapeAPI from dashboard import Dashboard announcer = messageAnnouncer.MessageAnnouncer() abstractDriver = abstractDriver.AbstractDriver(announcer) instance = db.Database(announcer) app = Flask(__name__) Dashboard(app, instance) Story(app, instance) app.register_blueprint(adminAPI.constructBlueprint( announcer, instance, abstractDriver ), url_prefix="/admin" ) app.register_blueprint(streamAPI.constructBlueprint( announcer, instance, abstractDriver ), url_prefix="/admin/stream" ) app.register_blueprint(dbAPI.constructBlueprint( announcer, instance, abstractDriver ), url_prefix="/admin/db" ) app.register_blueprint(scrapeAPI.constructBlueprint( announcer, instance, abstractDriver ), url_prefix="/admin/scrape" ) @app.before_request @app.route('/favicon.ico')
[ 11748, 28686, 198, 6738, 42903, 1330, 46947, 198, 6738, 42903, 1330, 2581, 198, 6738, 42903, 1330, 8543, 62, 28243, 198, 6738, 42903, 1330, 3758, 62, 6738, 62, 34945, 198, 11748, 20613, 198, 11748, 12531, 32103, 198, 11748, 3275, 18858, 9...
2.848341
422
'''Tests for pymica.multiregression.py ''' import unittest from pymica.multiregression import MultiRegression, MultiRegressionSigma
[ 7061, 6, 51, 3558, 329, 279, 4948, 3970, 13, 16680, 557, 32383, 13, 9078, 198, 7061, 6, 198, 11748, 555, 715, 395, 198, 198, 6738, 279, 4948, 3970, 13, 16680, 557, 32383, 1330, 15237, 8081, 2234, 11, 15237, 8081, 2234, 50, 13495, 62...
3.116279
43
"""Add user settings""" from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '2' down_revision = '1' branch_labels = None depends_on = None
[ 37811, 4550, 2836, 6460, 37811, 198, 6738, 31341, 2022, 291, 1330, 1034, 198, 11748, 44161, 282, 26599, 355, 473, 628, 198, 2, 18440, 42814, 11, 973, 416, 9300, 2022, 291, 13, 198, 260, 10178, 796, 705, 17, 6, 198, 2902, 62, 260, 10...
2.96875
64
""" Test job utils. """ from __future__ import absolute_import, division, print_function, unicode_literals import unittest from nose.tools import assert_equals, assert_raises assert_equals.__self__.maxDiff = None from pygenie.jobs.utils import arg_list class TestArgList(unittest.TestCase): """Test pygenie.jobs.utils.arg_list decorator.""" def test_strings(self): """Test pygenie.jobs.utils.arg_list with string arguments.""" arglist = ArgList() arglist.add_to_list('a') arglist.add_to_list('b') arglist.add_to_list('c') assert_equals( ['a', 'b', 'c'], arglist.my_list ) def test_lists(self): """Test pygenie.jobs.utils.arg_list with list of string arguments.""" arglist = ArgList() arglist.add_to_list(['1']) arglist.add_to_list(['2']) arglist.add_to_list(['3']) assert_equals( ['1', '2', '3'], arglist.my_list ) def test_duplicates_strs(self): """Test pygenie.jobs.utils.arg_list with duplicate arguments (strings).""" arglist = ArgList() arglist.add_to_list('f') arglist.add_to_list('e') arglist.add_to_list('f') assert_equals( ['f', 'e'], arglist.my_list ) def test_mixed_types(self): """Test pygenie.jobs.utils.arg_list with mixed type arguments.""" arglist = ArgList() arglist.add_to_list('g') arglist.add_to_list([{'h': 'h'}]) arglist.add_to_list('f') assert_equals( ["g", {"h": "h"}, "f"], arglist.my_list )
[ 37811, 198, 14402, 1693, 3384, 4487, 13, 198, 37811, 628, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 11, 28000, 1098, 62, 17201, 874, 198, 198, 11748, 555, 715, 395, 198, 198, 6738, 9686, 13, ...
2.038835
824
#!/usr/bin/env python #coding: utf-8 #from __future__ import unicode_literals from kasaya.conf import settings #from gevent import socket from kasaya.core.protocol import Serializer, messages from kasaya.core.lib import LOG #from kasaya.core.exceptions import NotOurMessage from kasaya.core.events import emit #import traceback """ self start 1. broadcast about host start Remote hosts 1. received broadcast about host start 2. if host is new, it is registered in database 3. wait random time (1-5 seconds) 5. request host status 6. connect to new host and send all known hosts 7. connect to new host and send all owne workers Local host start - broadcast host start (only host id is in packet) Remote host start - received broadcast about new host (including remote ip number) - registering host in local db with received IP - wait random time (1-5 seconds) - connect to new host and send known network status Local worker started / stopped. - loop over all known hosts - send current known network status Remote worker started / stopped. - remote host connect and bring new host status Kasaya daemon ============= - each kasaya daemon represent own host in network and all workers - each kasaya has unique ID - each kasaya can have more than one network adress (it usually bind to 0.0.0.0 address) - each kasaya is leader for own workers and own state in network without any election Kasaya daemon boot time activity 1. broadcast own ID 2. all hosts adds new host and his IP in local database each host send response to sender with own ID and IP new host stores remote hosts and their IP's in own local db 3. new host know all existing hosts in network all hosts know new host 5. kasaya iterate over all hosts and: - sends own status and informations - request current network state network state contains: - all known kasaya hosts (for comparision with received hosts via broadcast) - all workers currently working on host """ class Synchronizer(object): """ Network state synchronizing. """
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 66, 7656, 25, 3384, 69, 12, 23, 198, 2, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 6738, 479, 292, 11729, 13, 10414, 1330, 6460, 198, 2, 6738, 4903, 1151, ...
3.644991
569
""" file_cache_manager.py - Manage a local cache of files synchronized through S3 Copyright (c) 2020 by Thomas J. Daley, J.D. """ import boto3 from boto3.s3.transfer import TransferConfig from botocore.exceptions import ClientError import os from dotenv import load_dotenv from util.logger import get_logger load_dotenv() class FileCacheManager(object): """ Compares the update time on S3 to the local file's update time. If the S3 file is newer or the local file does not exist, downloads the latest file to the local cache folder then returns the path of the locally cached file. """ def get_filename(self, filename: str) -> str: """ Gets the full path name of the requested file. First checks to see if the local file exists. If not, then sees if the file exists in the S3 bucket. If not, returns None. If so, downloads the file from S3, saves it to the local_path, and returns the full file path of the requested file. If the file does exist locally, compares the update date/time of the local file to the corresponding object in S3. If the S3 object is newer, the S3 object is downloaded and cached. Args: filename (str): The name of the file to be retrieved Returns: (str): The absolute path of the file or None if not found. """ s3 = _connect() self.logger.debug("Searching S3 bucket '%s' for key '%s'", self.s3_path, filename) s3_modified_date = _s3_modified_date(s3, self.s3_path, filename) self.logger.debug("S3 modified: %s", s3_modified_date) local_modified_date = _local_modified_date(self.local_path, filename) self.logger.debug("Local modified: %s", local_modified_date) local_filename = os.path.join(self.local_path, filename) self.logger.debug("Local filename: %s", local_filename) # See if file exists anywhere if not s3_modified_date and not local_modified_date: self.logger.error("Template %s not found locally or on S3.", filename) return None # See if our file is newer than the S3 file if local_modified_date >= s3_modified_date: self.logger.debug("Local file is newer than S3") return local_filename # S3 file is newer . . . download it. self.logger.debug("S3 file is newer than local file") config = TransferConfig(use_threads=False) s3.Object(self.s3_path, filename).download_file(local_filename, Config=config) self.logger.debug("%s downloaded from S3", local_filename) return local_filename def synchronize_file(self, filename: str) -> bool: """ Copy a local file to the remote S3 service so that other nodes can pick it up. """ s3 = _connect() local_filename = os.path.join(self.local_path, filename) s3.Bucket(self.s3_path).upload_file(local_filename, filename) def _connect(): """ Connects to the S3 service and returns a Boto3 object. """ return boto3.resource('s3')
[ 37811, 198, 7753, 62, 23870, 62, 37153, 13, 9078, 532, 1869, 496, 257, 1957, 12940, 286, 3696, 47192, 832, 311, 18, 198, 198, 15269, 357, 66, 8, 12131, 416, 5658, 449, 13, 360, 16730, 11, 449, 13, 35, 13, 198, 37811, 198, 11748, 2...
2.624476
1,193
# # Depends # Copyright (C) 2014 by Andrew Gardner & Jonas Unger. All rights reserved. # BSD license (LICENSE.txt for details). # import math from PySide import QtCore, QtGui import node import undo_commands """ A collection of QT graphics widgets that displays and allows the user to manipulate a dependency graph. From the entire scene, to the nodes, to the connections between the nodes, to the nubs the connections connect to. """ ############################################################################### ############################################################################### class DrawNodeNub(QtGui.QGraphicsItem): """ A QGraphicsItem representing the small clickable nub at the end of a DAG node. New connections can be created by clicking and dragging from this. """ Type = QtGui.QGraphicsItem.UserType + 3 def __init__(self): """ """ QtGui.QGraphicsItem.__init__(self) self.setAcceptedMouseButtons(QtCore.Qt.LeftButton) self.setCacheMode(self.DeviceCoordinateCache) self.setZValue(-1) def type(self): """ Assistance for the QT windowing toolkit. """ return DrawNodeNub.Type def boundingRect(self): """ Defines the clickable hit box. """ return QtCore.QRectF(-5, self.parentItem().height/2.0-5.0, 10, 10) def paint(self, painter, option, widget): """ Draw the nub. """ painter.setBrush(QtGui.QBrush(QtCore.Qt.yellow)) painter.setPen(QtGui.QPen(QtCore.Qt.yellow, 0)) painter.drawPie(QtCore.QRectF(-5.0, self.parentItem().height/2.0-5.0, 10, 10), 16*180, 16*180) def mousePressEvent(self, event): """ Accept left-button clicks to create the new connection. """ tempEdge = DrawEdge(self.parentItem(), None, floatingDestinationPoint=event.scenePos()) self.scene().addItem(tempEdge) self.ungrabMouse() tempEdge.dragging = True # TODO: Probably better done with an DrawEdge function (still valid?) tempEdge.grabMouse() event.accept() return ############################################################################### ############################################################################### class DrawNode(QtGui.QGraphicsItem): """ A QGraphicsItem representing a node in a dependency graph. These can be selected, moved, and connected together with DrawEdges. """ Type = QtGui.QGraphicsItem.UserType + 1 def __init__(self, dagNode): """ """ QtGui.QGraphicsItem.__init__(self) # The corresponding DAG node self.dagNode = dagNode # Input and output edges self.incomingDrawEdgeList = list() self.outgoingDrawEdgeList = list() self.nub = DrawNodeNub() self.nub.setParentItem(self) self.setFlag(QtGui.QGraphicsItem.ItemIsMovable) self.setFlag(QtGui.QGraphicsItem.ItemIsSelectable) self.setFlag(QtGui.QGraphicsItem.ItemSendsGeometryChanges) self.setAcceptedMouseButtons(QtCore.Qt.LeftButton) self.setCacheMode(self.DeviceCoordinateCache) self.setZValue(-1) self.width = 150 self.height = 20 # For handling movement undo/redos of groups of objects # This is a little strange to be handled by the node itself # and maybe can move elsewhere? self.clickSnap = None self.clickPosition = None if type(self.dagNode) == node.DagNodeDot: self.width = 15 self.height = 15 def type(self): """ Assistance for the QT windowing toolkit. """ return DrawNode.Type def removeDrawEdge(self, edge): """ Removes the given edge from this node's list of edges. """ if edge in self.incomingDrawEdgeList: self.incomingDrawEdgeList.remove(edge) elif edge in self.outgoingDrawEdgeList: self.outgoingDrawEdgeList.remove(edge) else: raise RuntimeError("Attempting to remove drawEdge that doesn't exist from node %s." % self.dagNode.name) def addDrawEdge(self, edge): """ Add a given draw edge to this node. """ if edge.destDrawNode() == self: self.incomingDrawEdgeList.append(edge) elif edge.sourceDrawNode() == self: self.outgoingDrawEdgeList.append(edge) edge.adjust() def drawEdges(self): """ Return all incoming and outgoing edges in a list. """ return (self.incomingDrawEdgeList + self.outgoingDrawEdgeList) def incomingDrawEdges(self): """ Return only incoming edges in a list. """ return self.incomingDrawEdgeList def outgoingDrawEdges(self): """ Return only outgoing edges in a list. """ return self.outgoingDrawEdgeList def boundingRect(self): """ Defines the clickable hit-box. Simply returns a rectangle instead of a rounded rectangle for speed purposes. """ # TODO: Is this the right place to put this? Maybe setWidth (adjust) would be fine. #if len(self.dagNode.name)*10 != self.width: # self.prepareGeometryChange() # self.width = len(self.dagNode.name)*10 # if self.width < 9: # self.width = 9 adjust = 2.0 return QtCore.QRectF(-self.width/2 - adjust, -self.height/2 - adjust, self.width + 3 + adjust, self.height + 3 + adjust) def shape(self): """ The QT shape function. """ # TODO: Find out what this is for again? path = QtGui.QPainterPath() path.addRoundedRect(QtCore.QRectF(-self.width/2, -self.height/2, self.width, self.height), 5, 5) return path def paint(self, painter, option, widget): """ Draw the node, whether it's in the highlight list, selected or unselected, is currently executable, and its name. Also draws a little light denoting if it already has data present. """ #inputsFulfilled = self.scene().dag.nodeAllInputsDataPresent(self.dagNode) inputsFulfilled = False # Draw the box gradient = QtGui.QLinearGradient(0, -self.height/2, 0, self.height/2) if option.state & QtGui.QStyle.State_Selected: gradient.setColorAt(0, QtGui.QColor(255, 255 if inputsFulfilled else 172, 0)) gradient.setColorAt(1, QtGui.QColor(200, 128 if inputsFulfilled else 0, 0)) else: topGrey = 200 if inputsFulfilled else 128 bottomGrey = 96 if inputsFulfilled else 64 gradient.setColorAt(0, QtGui.QColor(topGrey, topGrey, topGrey)) gradient.setColorAt(1, QtGui.QColor(bottomGrey, bottomGrey, bottomGrey)) # Draw a fat, bright outline if it's a highlighted node if self in self.scene().highlightNodes: highlightColor = QtGui.QColor(0, 128, 255) if self.scene().highlightIntensities: intensityIndex = self.scene().highlightIntensities[self.scene().highlightNodes.index(self)] highlightColor.setGreen(highlightColor.green() * intensityIndex) highlightColor.setBlue(highlightColor.blue() * intensityIndex) painter.setPen(QtGui.QPen(highlightColor, 3)) else: painter.setPen(QtGui.QPen(QtCore.Qt.black, 0)) painter.setBrush(QtGui.QBrush(gradient)) fullRect = QtCore.QRectF(-self.width/2, -self.height/2, self.width, self.height) painter.drawRoundedRect(fullRect, 5, 5) # No lights or text for dot nodes if type(self.dagNode) == node.DagNodeDot: return # The "data present" light # painter.setPen(QtGui.QPen(QtGui.QColor(0, 0, 0), 0.25)) # for output in self.dagNode.outputs(): # if self.scene().dag.nodeOutputDataPacket(self.dagNode, output).dataPresent(): # painter.setBrush(QtGui.QBrush(QtGui.QColor(0, 255, 0))) # else: # painter.setBrush(QtGui.QBrush(QtGui.QColor(255, 0, 0))) # break # # painter.drawRect(QtCore.QRectF(-self.width/2+5, -self.height/2+5, 5, 5)) # Text (none for dot nodes) textRect = QtCore.QRectF(self.boundingRect().left() + 4, self.boundingRect().top(), self.boundingRect().width() - 4, self.boundingRect().height()) font = painter.font() font.setPointSize(10) painter.setFont(font) painter.setPen(QtCore.Qt.black) painter.drawText(textRect, QtCore.Qt.AlignCenter, self.dagNode.name) def mousePressEvent(self, event): """ Help manage mouse movement undo/redos. """ # Note: This works without an 'if' because the only mouse button that # comes through here is the left QtGui.QGraphicsItem.mousePressEvent(self, event) # Let the QT parent class handle the selection process before querying what's selected self.clickSnap = self.scene().dag.snapshot(nodeMetaDict=self.scene().nodeMetaDict(), connectionMetaDict=self.scene().connectionMetaDict()) self.clickPosition = self.pos() def mouseReleaseEvent(self, event): """ Help manage mouse movement undo/redos. """ # Don't register undos for selections without moves if self.pos() != self.clickPosition: currentSnap = self.scene().dag.snapshot(nodeMetaDict=self.scene().nodeMetaDict(), connectionMetaDict=self.scene().connectionMetaDict()) self.scene().undoStack().push(undo_commands.SceneOnlyUndoCommand(self.clickSnap, currentSnap, self.scene())) QtGui.QGraphicsItem.mouseReleaseEvent(self, event) def itemChange(self, change, value): """ If the node has been moved, update all of its draw edges. """ if change == QtGui.QGraphicsItem.ItemPositionHasChanged: for edge in self.drawEdges(): edge.adjust() return QtGui.QGraphicsItem.itemChange(self, change, value) ############################################################################### ############################################################################### class DrawEdge(QtGui.QGraphicsItem): """ A QGraphicsItem representing a connection between two DAG nodes. These can be clicked and dragged to change, add, or remove connections between nodes. """ TwoPi = 2.0 * math.pi Type = QtGui.QGraphicsItem.UserType + 2 def __init__(self, sourceDrawNode, destDrawNode, floatingDestinationPoint=0.0): """ """ QtGui.QGraphicsItem.__init__(self) self.arrowSize = 5.0 self.sourcePoint = QtCore.QPointF() self.destPoint = QtCore.QPointF() self.horizontalConnectionOffset = 0.0 self.setAcceptedMouseButtons(QtCore.Qt.LeftButton) self.setZValue(-2) self.source = sourceDrawNode self.dest = destDrawNode if not self.dest: self.floatingDestinationPoint = floatingDestinationPoint self.source.addDrawEdge(self) if self.dest: self.dest.addDrawEdge(self) self.adjust() # MouseMoved is a little hack to get around a bug where clicking the mouse and not dragging caused an error self.mouseMoved = False self.dragging = False def type(self): """ Assistance for the QT windowing toolkit. """ return DrawEdge.Type def sourceDrawNode(self): """ Simple accessor. """ return self.source def setSourceDrawNode(self, drawNode): """ Set the edge's source draw node and adjust the edge's representation. """ self.source = drawNode self.adjust() def destDrawNode(self): """ Simple accessor. """ return self.dest def setDestDrawNode(self, drawNode): """ Set the edge's destination draw node and adjust the edge's representation. """ self.dest = drawNode self.adjust() def adjust(self): """ Recompute where the line is pointing. """ if not self.source: return if self.dest: line = QtCore.QLineF(self.mapFromItem(self.source, 0, 0), self.mapFromItem(self.dest, 0, 0)) else: line = QtCore.QLineF(self.mapFromItem(self.source, 0, 0), self.floatingDestinationPoint) length = line.length() if length == 0.0: return self.prepareGeometryChange() self.sourcePoint = line.p1() + QtCore.QPointF(0, (self.sourceDrawNode().height/2) + 1) if self.dest: self.destPoint = line.p2() - QtCore.QPointF(0, self.destDrawNode().height/2) self.destPoint += QtCore.QPointF(self.horizontalConnectionOffset, 0.0) else: self.destPoint = line.p2() def boundingRect(self): """ Hit box assistance. Only let the user click on the tip of the line. """ if not self.source: # or not self.dest: return QtCore.QRectF() penWidth = 1 extra = (penWidth + self.arrowSize) / 2.0 return QtCore.QRectF(self.sourcePoint, QtCore.QSizeF(self.destPoint.x() - self.sourcePoint.x(), self.destPoint.y() - self.sourcePoint.y())).normalized().adjusted(-extra, -extra, extra, extra) def shape(self): """ The QT shape function. """ # Setup and stroke the line path = QtGui.QPainterPath(self.sourcePoint) path.lineTo(self.destPoint) stroker = QtGui.QPainterPathStroker() stroker.setWidth(2) stroked = stroker.createStroke(path) # Add a square at the tip stroked.addRect(self.destPoint.x()-10, self.destPoint.y()-10, 20, 20) return stroked def paint(self, painter, option, widget): """ Draw a line with an arrow at the end. """ if not self.source: # or not self.dest: return # Draw the line line = QtCore.QLineF(self.sourcePoint, self.destPoint) if line.length() == 0.0: return painter.setPen(QtGui.QPen(QtCore.Qt.white, 1, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin)) painter.drawLine(line) # Draw the arrows if there's enough room. angle = math.acos(line.dx() / line.length()) if line.dy() >= 0: angle = DrawEdge.TwoPi - angle destArrowP1 = self.destPoint + QtCore.QPointF(math.sin(angle - math.pi / 3) * self.arrowSize, math.cos(angle - math.pi / 3) * self.arrowSize) destArrowP2 = self.destPoint + QtCore.QPointF(math.sin(angle - math.pi + math.pi / 3) * self.arrowSize, math.cos(angle - math.pi + math.pi / 3) * self.arrowSize) painter.setBrush(QtCore.Qt.white) painter.drawPolygon(QtGui.QPolygonF([line.p2(), destArrowP1, destArrowP2])) def mousePressEvent(self, event): """ Accept left-button clicks to drag the arrow. """ event.accept() self.dragging = True #QtGui.QGraphicsItem.mousePressEvent(self, event) def mouseMoveEvent(self, event): """ Node head dragging. """ if self.dragging: self.mouseMoved = True self.floatingDestinationPoint = event.scenePos() if self.destDrawNode(): # Disconnect an edge from a node preSnap = self.scene().dag.snapshot(nodeMetaDict=self.scene().nodeMetaDict(), connectionMetaDict=self.scene().connectionMetaDict()) self.destDrawNode().removeDrawEdge(self) self.scene().nodesDisconnected.emit(self.sourceDrawNode().dagNode, self.destDrawNode().dagNode) self.setDestDrawNode(None) currentSnap = self.scene().dag.snapshot(nodeMetaDict=self.scene().nodeMetaDict(), connectionMetaDict=self.scene().connectionMetaDict()) self.scene().undoStack().push(undo_commands.DagAndSceneUndoCommand(preSnap, currentSnap, self.scene().dag, self.scene())) self.adjust() # TODO: Hoover-color nodes as potential targets QtGui.QGraphicsItem.mouseMoveEvent(self, event) def mouseReleaseEvent(self, event): """ Dropping the connection onto a node connects it to the node and emits an appropriate signal. Dropping the connection into space deletes the connection. """ if self.dragging and self.mouseMoved: self.dragging = False # A little weird - seems to be necessary when passing mouse control from the nub to here self.ungrabMouse() # Hits? nodes = [n for n in self.scene().items(self.floatingDestinationPoint) if type(n) == DrawNode] if nodes: topHitNode = nodes[0] duplicatingConnection = self.sourceDrawNode().dagNode in self.scene().dag.nodeConnectionsIn(topHitNode.dagNode) if topHitNode is not self.sourceDrawNode() and not duplicatingConnection: # Connect an edge to a node preSnap = self.scene().dag.snapshot(nodeMetaDict=self.scene().nodeMetaDict(), connectionMetaDict=self.scene().connectionMetaDict()) self.setDestDrawNode(topHitNode) self.dest.addDrawEdge(self) self.horizontalConnectionOffset = (event.pos() - self.mapFromItem(self.dest, 0, 0)).x() self.scene().nodesConnected.emit(self.sourceDrawNode().dagNode, self.destDrawNode().dagNode) self.adjust() currentSnap = self.scene().dag.snapshot(nodeMetaDict=self.scene().nodeMetaDict(), connectionMetaDict=self.scene().connectionMetaDict()) self.scene().undoStack().push(undo_commands.DagAndSceneUndoCommand(preSnap, currentSnap, self.scene().dag, self.scene())) return QtGui.QGraphicsItem.mouseReleaseEvent(self, event) # No hits? Delete yourself (You have no chance to win!) self.sourceDrawNode().removeDrawEdge(self) self.scene().removeItem(self) self.mouseMoved = False QtGui.QGraphicsItem.mouseReleaseEvent(self, event) ############################################################################### ############################################################################### class DrawGroupBox(QtGui.QGraphicsItem): """ A simple box that draws around groups of DrawNodes. Denotes which nodes are grouped together. """ Type = QtGui.QGraphicsItem.UserType + 4 def __init__(self, initialBounds=QtCore.QRectF(), name=""): """ """ QtGui.QGraphicsItem.__init__(self) self.name = name self.bounds = initialBounds self.setZValue(-3) def type(self): """ Assistance for the QT windowing toolkit. """ return DrawGroupBox.Type def boundingRect(self): """ Hit box assistance. """ return self.bounds def paint(self, painter, option, widget): """ Simply draw a grey box behind the nodes it encompasses. """ # TODO: This box is currently not dynamically-sizable. Fix! painter.setBrush(QtGui.QColor(62, 62, 62)) painter.setPen(QtCore.Qt.NoPen) painter.drawRect(self.bounds) ############################################################################### ############################################################################### class SceneWidget(QtGui.QGraphicsScene): """ The QGraphicsScene that contains the contents of a given dependency graph. """ # Signals nodesDisconnected = QtCore.Signal(node.DagNode, node.DagNode) nodesConnected = QtCore.Signal(node.DagNode, node.DagNode) def __init__(self, parent=None): """ """ QtGui.QGraphicsScene.__init__(self, parent) # Call setDag() when setting the dag to make sure everything is cleaned up properly self.dag = None # The lists of highlight nodes and their matching intensities. self.highlightNodes = list() self.highlightIntensities = list() def undoStack(self): """ An accessor to the application's global undo stack, guaranteed to be created by the time it's needed. """ return self.parent().parent().undoStack def drawNodes(self): """ Returns a list of all drawNodes present in the scene. """ nodes = list() for item in self.items(): if type(item).__name__ == 'DrawNode': nodes.append(item) return nodes def drawNode(self, dagNode): """ Returns the given dag node's draw node (or None if it doesn't exist in the scene). """ for item in self.items(): if type(item).__name__ != 'DrawNode': continue if item.dagNode == dagNode: return item return None def drawEdges(self): """ Return a list of all draw edges in the scene. """ edges = list() for item in self.items(): if type(item).__name__ == 'DrawEdge': edges.append(item) return edges def drawEdge(self, fromDrawNode, toDrawNode): """ Returns a drawEdge that links a given draw node to another given draw node. """ for item in self.items(): if type(item).__name__ != 'DrawEdge': continue if item.source == fromDrawNode and item.dest == toDrawNode: return item return None def setDag(self, dag): """ Sets the current dependency graph and refreshes the scene. """ self.clear() self.dag = dag def addExistingDagNode(self, dagNode, position): """ Adds a new draw node for a given dag node at a given position. """ newNode = DrawNode(dagNode) self.addItem(newNode) newNode.setPos(position) return newNode def addExistingConnection(self, fromDagNode, toDagNode): """ Adds a new draw edge for given from and to dag nodes. """ fromDrawNode = self.drawNode(fromDagNode) toDrawNode = self.drawNode(toDagNode) if not fromDrawNode: raise RuntimeError("Attempting to connect node %s which is not yet registered to QGraphicsScene." % fromDagNode.name) if not toDrawNode: raise RuntimeError("Attempting to connect node %s which is not yet registered to QGraphicsScene." % toDagNode.name) newDrawEdge = DrawEdge(fromDrawNode, toDrawNode) self.addItem(newDrawEdge) return newDrawEdge def addExistingGroupBox(self, name, groupDagNodeList): """ Add a group box from a given list of dag nodes & names it with a string. """ drawNodes = [self.drawNode(dn) for dn in groupDagNodeList] bounds = QtCore.QRectF() for drawNode in drawNodes: bounds = bounds.united(drawNode.sceneBoundingRect()) adjust = bounds.width() if bounds.width() > bounds.height() else bounds.height() adjust *= 0.05 bounds.adjust(-adjust, -adjust, adjust, adjust) newGroupBox = DrawGroupBox(bounds, name) self.addItem(newGroupBox) def removeExistingGroupBox(self, name): """ Removes a group box with a given name. """ boxes = [n for n in self.items() if type(n) == DrawGroupBox] for box in boxes: if box.name == name: self.removeItem(box) return raise RuntimeError("Group box named %s does not appear to exist in the QGraphicsScene." % name) def refreshDrawNodes(self, dagNodes): """ Refresh the draw nodes representing a given list of dag nodes. """ for drawNode in [self.drawNode(n) for n in dagNodes]: drawNode.update() def setHighlightNodes(self, drawNodes, intensities=None): """ Set which nodes are highlighted by giving a list of drawNodes and an optional list of intensities. """ self.highlightIntensities = intensities oldHighlightNodes = self.highlightNodes self.highlightNodes = drawNodes for drawNode in drawNodes+oldHighlightNodes: drawNode.update() def setCascadingHighlightNodesFromOrderedDependencies(self, dagNodeOrigin): """ Recover a list of ordered dependencies for a given dag node, and highlight each of the nodes it depends on. """ highlightDrawNodesDarkToLight = [self.drawNode(n) for n in self.dag.orderedNodeDependenciesAt(dagNodeOrigin, onlyUnfulfilled=False)] intensities = list() nodeCount = len(highlightDrawNodesDarkToLight) if nodeCount > 1: for i in range(nodeCount): intensities.append(0.65 + (0.35 * float(i)/float(nodeCount-1))) else: intensities = [1.0] self.setHighlightNodes(highlightDrawNodesDarkToLight, intensities) def mousePressEvent(self, event): """ Stifles a rubber-band box when clicking on a node and moving it. """ # This allows an event to propagate without actually doing what it wanted to do # in the first place (draw a rubber band box for all click-drags - including middle mouse) # (http://www.qtcentre.org/threads/36953-QGraphicsItem-deselected-on-contextMenuEvent) if event.button() != QtCore.Qt.LeftButton: event.accept() return QtGui.QGraphicsScene.mousePressEvent(self, event) def nodeMetaDict(self): """ Returns a dictionary containing meta information for each of the draw nodes in the scene. """ nodeMetaDict = dict() nodes = [n for n in self.items() if type(n) == DrawNode] for n in nodes: nodeMetaDict[str(n.dagNode.uuid)] = dict() nodeMetaDict[str(n.dagNode.uuid)]['locationX'] = str(n.pos().x()) nodeMetaDict[str(n.dagNode.uuid)]['locationY'] = str(n.pos().y()) return nodeMetaDict def connectionMetaDict(self): """ Returns a dictionary containing meta information for each of the draw edges in the scene. """ connectionMetaDict = dict() connections = [n for n in self.items() if type(n) == DrawEdge] for c in connections: if not c.sourceDrawNode() or not c.destDrawNode(): continue connectionString = "%s|%s" % (str(c.sourceDrawNode().dagNode.uuid), str(c.destDrawNode().dagNode.uuid)) connectionMetaDict[connectionString] = dict() connectionMetaDict[connectionString]['horizontalConnectionOffset'] = str(c.horizontalConnectionOffset) return connectionMetaDict def restoreSnapshot(self, snapshotDict): """ Given a dictionary that contains dag information and meta information for the dag, construct all draw objects and register them with the current scene. """ # Clear out the drawnodes and connections, then add 'em all back in. selectedItems = self.selectedItems() self.blockSignals(True) for dn in self.drawNodes(): self.removeItem(dn) for de in self.drawEdges(): self.removeItem(de) for dagNode in self.dag.nodes(): newNode = self.addExistingDagNode(dagNode, QtCore.QPointF(0,0)) if selectedItems and dagNode in [x.dagNode for x in selectedItems]: newNode.setSelected(True) for connection in self.dag.connections(): newDrawEdge = self.addExistingConnection(connection[1], connection[0]) self.blockSignals(False) # DrawNodes get their locations set from this meta entry expectedNodeMeta = snapshotDict["NODE_META"] if expectedNodeMeta: for dagNode in self.dag.nodes(): drawNode = self.drawNode(dagNode) nodeMeta = expectedNodeMeta[str(dagNode.uuid)] if 'locationX' in nodeMeta: locationX = float(nodeMeta['locationX']) if 'locationY' in nodeMeta: locationY = float(nodeMeta['locationY']) drawNode.setPos(QtCore.QPointF(locationX, locationY)) # DrawEdges get their insertion points set here expectedConnectionMeta = snapshotDict["CONNECTION_META"] if expectedConnectionMeta: for connection in self.dag.connections(): connectionIdString = "%s|%s" % (str(connection[1].uuid), str(connection[0].uuid)) connectionMeta = expectedConnectionMeta[connectionIdString] if 'horizontalConnectionOffset' in connectionMeta: # TODO: This code is a little verbose... drawEdge = self.drawEdge(self.drawNode(self.dag.node(nUUID=connection[1].uuid)), self.drawNode(self.dag.node(nUUID=connection[0].uuid))) drawEdge.horizontalConnectionOffset = float(connectionMeta['horizontalConnectionOffset']) drawEdge.adjust() ############################################################################### ############################################################################### class GraphicsViewWidget(QtGui.QGraphicsView): """ The QGraphicsView into a QGraphicsScene it owns. This object handles the mouse and board behavior of the dependency graph inside the view. """ # Signals createNode = QtCore.Signal(type, QtCore.QPointF) def __init__(self, parent=None): """ """ QtGui.QGraphicsView.__init__(self, parent) # Setup our own Scene Widget and assign it to the View. scene = SceneWidget(self) scene.setItemIndexMethod(QtGui.QGraphicsScene.NoIndex) scene.setSceneRect(-20000, -20000, 40000, 40000) self.setScene(scene) # Mouse Interaction #self.setCacheMode(QtGui.QGraphicsView.CacheBackground) self.setRenderHint(QtGui.QPainter.Antialiasing) self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse) self.setResizeAnchor(QtGui.QGraphicsView.AnchorUnderMouse) self.setDragMode(QtGui.QGraphicsView.RubberBandDrag) # Hide the scroll bars self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) brush = QtGui.QBrush(QtGui.QColor(0, 255, 0)) brush.setStyle(QtCore.Qt.SolidPattern) self.setBackgroundBrush(brush) # Window properties self.setWindowTitle(self.tr("Depends")) self.setMinimumSize(200, 200) self.scale(1.0, 1.0) # Context menu hookups self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.customContextMenuRequested.connect(self.showContextMenu) self.boxing = False self.modifierBoxOrigin = None self.modifierBox = QtGui.QRubberBand(QtGui.QRubberBand.Rectangle, self) def centerCoordinates(self): """ Returns a QPoint containing the scene location the center of this view is pointing at. """ topLeft = QtCore.QPointF(self.horizontalScrollBar().value(), self.verticalScrollBar().value()) topLeft += self.geometry().center() return topLeft def frameBounds(self, bounds): """ Frames a given bounding rectangle within the viewport. """ if bounds.isEmpty(): return widthAdjust = bounds.width() * 0.2 heightAdjust = bounds.height() * 0.2 bounds.adjust(-widthAdjust, -heightAdjust, widthAdjust, heightAdjust) self.fitInView(bounds, QtCore.Qt.KeepAspectRatio) def showContextMenu(self, menuLocation): """ Pop up a node creation context menu at a given location. """ contextMenu = QtGui.QMenu() menuActions = self.parent().createCreateMenuActions() for action in menuActions: action.setData((action.data()[0], self.mapToScene(menuLocation))) contextMenu.addAction(action) contextMenu.exec_(self.mapToGlobal(menuLocation)) def keyPressEvent(self, event): """ Stifles autorepeat and handles a few shortcut keys that aren't registered as functions in the main window. """ # This widget will never process auto-repeating keypresses so ignore 'em all if event.isAutoRepeat(): return # Frame selected/all items if event.key() == QtCore.Qt.Key_F: itemList = list() if self.scene().selectedItems(): itemList = self.scene().selectedItems() else: itemList = self.scene().items() bounds = QtCore.QRectF() for item in itemList: bounds |= item.sceneBoundingRect() self.frameBounds(bounds) # Highlight each node upstream that affects the selected node elif event.key() == QtCore.Qt.Key_Space: sel = self.scene().selectedItems() if len(sel) != 1: return self.scene().setCascadingHighlightNodesFromOrderedDependencies(sel[0].dagNode) def keyReleaseEvent(self, event): """ Stifle auto-repeats and handle letting go of the space bar. """ # Ignore auto-repeats if event.isAutoRepeat(): return # Clear the highlight list if you just released the space bar if event.key() == QtCore.Qt.Key_Space: self.scene().setHighlightNodes([], intensities=None) def mousePressEvent(self, event): """ Special handling is needed for a drag-box that toggles selected elements with the CTRL button. """ # Handle CTRL+MouseClick box behavior if event.modifiers() & QtCore.Qt.ControlModifier: itemUnderMouse = self.itemAt(event.pos().x(), event.pos().y()) if not itemUnderMouse: self.modifierBoxOrigin = event.pos() self.boxing = True event.accept() return QtGui.QGraphicsView.mousePressEvent(self, event) def mouseMoveEvent(self, event): """ Panning the viewport around and CTRL+mouse drag behavior. """ # Panning if event.buttons() & QtCore.Qt.MiddleButton: delta = event.pos() - self.lastMousePos self.verticalScrollBar().setValue(self.verticalScrollBar().value() - delta.y()) self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - delta.x()) self.lastMousePos = event.pos() else: self.lastMousePos = event.pos() # Handle Modifier+MouseClick box behavior if event.buttons() & QtCore.Qt.LeftButton and event.modifiers() & QtCore.Qt.ControlModifier: if self.boxing: self.modifierBox.setGeometry(QtCore.QRect(self.modifierBoxOrigin, event.pos()).normalized()) self.modifierBox.show() event.accept() return QtGui.QGraphicsView.mouseMoveEvent(self, event) def mouseReleaseEvent(self, event): """ The final piece of the CTRL+drag box puzzle. """ # Handle Modifier+MouseClick box behavior if self.boxing: # Blocking the scene's signals insures only a single selectionChanged # gets emitted at the very end. This was necessary since the way I # have written the property widget appears to freak out when refreshing # twice instantaneously (see MainWindow's constructor for additional details). nodesInHitBox = [x for x in self.items(QtCore.QRect(self.modifierBoxOrigin, event.pos()).normalized()) if type(x) is DrawNode] self.scene().blockSignals(True) for drawNode in nodesInHitBox: drawNode.setSelected(not drawNode.isSelected()) self.scene().blockSignals(False) self.scene().selectionChanged.emit() self.modifierBox.hide() self.boxing = False QtGui.QGraphicsView.mouseReleaseEvent(self, event) def wheelEvent(self, event): """ Zooming. """ self.scaleView(math.pow(2.0, event.delta() / 240.0)) def drawBackground(self, painter, rect): """ Filling. """ #sceneRect = self.sceneRect() ##painter.fillRect(rect.intersect(sceneRect), QtGui.QBrush(QtCore.Qt.black, QtCore.Qt.SolidPattern)) #painter.drawRect(sceneRect) # Draw grid gridSize = 25 left = int(rect.left()) - (int(rect.left()) % gridSize) top = int(rect.top()) - (int(rect.top()) % gridSize) lines = [] for x in xrange(left, int(rect.right())+1, gridSize): lines.append(QtCore.QLineF(x, rect.top(), x, rect.bottom())) for y in xrange(top, int(rect.bottom())+1, gridSize): lines.append(QtCore.QLineF(rect.left(), y, rect.right(), y)) p = QtGui.QPen() p.setWidth(0.0) p.setColor(QtGui.QColor(255, 255, 255, 25)) painter.setPen(p) painter.drawLines(lines) def scaleView(self, scaleFactor): """ Zoom helper function. """ factor = self.matrix().scale(scaleFactor, scaleFactor).mapRect(QtCore.QRectF(0, 0, 1, 1)).width() if factor < 0.07 or factor > 100: return self.scale(scaleFactor, scaleFactor)
[ 2, 198, 2, 2129, 2412, 198, 2, 15069, 357, 34, 8, 1946, 416, 6858, 27911, 1222, 40458, 44904, 263, 13, 220, 1439, 2489, 10395, 13, 198, 2, 347, 10305, 5964, 357, 43, 2149, 24290, 13, 14116, 329, 3307, 737, 198, 2, 198, 198, 11748,...
2.268556
17,218
######## Snakemake header ######## import sys sys.path.append( "/home/cmb-panasas2/skchoudh/software_frozen/anaconda27/envs/riboraptor/lib/python3.5/site-packages" ) import pickle snakemake = pickle.loads( b'\x80\x03csnakemake.script\nSnakemake\nq\x00)\x81q\x01}q\x02(X\t\x00\x00\x00resourcesq\x03csnakemake.io\nResources\nq\x04)\x81q\x05(K\x01K\x01e}q\x06(X\x06\x00\x00\x00_nodesq\x07K\x01X\x06\x00\x00\x00_coresq\x08K\x01X\x06\x00\x00\x00_namesq\t}q\n(h\x07K\x00N\x86q\x0bh\x08K\x01N\x86q\x0cuubX\x04\x00\x00\x00ruleq\rX\x0b\x00\x00\x00merge_fastqq\x0eX\x03\x00\x00\x00logq\x0fcsnakemake.io\nLog\nq\x10)\x81q\x11}q\x12h\t}q\x13sbX\x07\x00\x00\x00threadsq\x14K\x01X\t\x00\x00\x00wildcardsq\x15csnakemake.io\nWildcards\nq\x16)\x81q\x17X\n\x00\x00\x00SRX2536403q\x18a}q\x19(X\x06\x00\x00\x00sampleq\x1ah\x18h\t}q\x1bX\x06\x00\x00\x00sampleq\x1cK\x00N\x86q\x1dsubX\x05\x00\x00\x00inputq\x1ecsnakemake.io\nInputFiles\nq\x1f)\x81q (X\x1e\x00\x00\x00sratofastq/SRR5227288.fastq.gzq!X\x1e\x00\x00\x00sratofastq/SRR5227288.fastq.gzq"e}q#(X\r\x00\x00\x00dynamic_inputq$csnakemake.io\nNamedlist\nq%)\x81q&h!a}q\'h\t}q(sbh\t}q)(h$K\x00K\x01\x86q*X\t\x00\x00\x00all_fastqq+K\x01K\x02\x86q,uh+h%)\x81q-h"a}q.h\t}q/sbubX\x06\x00\x00\x00outputq0csnakemake.io\nOutputFiles\nq1)\x81q2X \x00\x00\x00fastq_merged/SRX2536403.fastq.gzq3a}q4h\t}q5sbX\x06\x00\x00\x00paramsq6csnakemake.io\nParams\nq7)\x81q8}q9h\t}q:sbX\x06\x00\x00\x00configq;}q<X\x0b\x00\x00\x00config_pathq=X\x19\x00\x00\x00configs/hg38_SRP098789.pyq>sub.' ) from snakemake.logging import logger logger.printshellcmds = True ######## Original script ######### import os from snakemake.shell import shell input = (' ').join(snakemake.input.dynamic_input) shell(r'''cat {input} > {snakemake.output}''')
[ 7804, 16705, 15883, 13639, 46424, 21017, 198, 11748, 25064, 198, 17597, 13, 6978, 13, 33295, 7, 198, 220, 220, 220, 12813, 11195, 14, 66, 2022, 12, 6839, 292, 292, 17, 14, 8135, 354, 2778, 71, 14, 43776, 62, 69, 42005, 14, 272, 330,...
1.701839
1,033
# maxLevel : keeps track of maximum # level seen so far. # res : Value of deepest node so far. # level : Level of root # Returns value of deepest node root = Node('a') root.left = Node('b') root.left.left = Node('d') root.right = Node('c') print(deepestNode(root)) # (d, 3)
[ 628, 198, 2, 3509, 4971, 1058, 7622, 2610, 286, 5415, 220, 220, 198, 2, 1241, 1775, 523, 1290, 13, 220, 220, 198, 2, 581, 1058, 11052, 286, 25420, 10139, 523, 1290, 13, 220, 220, 198, 2, 1241, 1058, 5684, 286, 6808, 220, 220, 198,...
2.550847
118
# Generated by Django 3.1.1 on 2020-10-26 14:06 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 16, 319, 12131, 12, 940, 12, 2075, 1478, 25, 3312, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, ...
2.818182
44
import queue #BFSで街を色分け N, Q = map(int, input().split()) a = [[] for i in range(N + 1)] for i in range(N - 1): st, ed = map(int, input().split()) a[st].append(ed) a[ed].append(st) que = queue.Queue() color = [-1] * (N + 1) color[1] = 0 que.put(1) while not que.empty(): now = que.get() for i in a[now]: if color[i] == -1: color[i] = 1 - color[now] que.put(i) for i in range(Q): st, ed = map(int, input().split()) if color[st] == color[ed]: print("Town") else: print("Road")
[ 11748, 16834, 198, 198, 2, 33, 10652, 30640, 26193, 245, 31758, 164, 231, 110, 26344, 228, 2515, 239, 198, 45, 11, 1195, 796, 3975, 7, 600, 11, 5128, 22446, 35312, 28955, 198, 64, 796, 16410, 60, 329, 1312, 287, 2837, 7, 45, 1343, ...
1.951049
286
import serial import os import mysql.connector import time mydb = mysql.connector.connect( host="185.104.29.34", user="schoolproject_laravel", passwd="kvLXsjsPS", database="schoolproject_laravel" ) port = serial.Serial("/dev/ttyUSB0", 9600, timeout=3.0) mycursor = mydb.cursor() while True: mycursor.execute("SELECT * FROM noodgeval;") for x in mycursor: print(x[1]) if x[1] == 'aan': print(x[1]) port.write("s1") else: port.write("s0") rcv = port.readline().strip() if(rcv == 'A'): print("wel") os.system("python updateWel.py") elif(rcv == 'N'): print("niet") os.system("python updateNiet.py") time.sleep(1) mydb.commit() mydb.close()
[ 11748, 11389, 198, 11748, 28686, 198, 11748, 48761, 13, 8443, 273, 198, 11748, 640, 198, 198, 1820, 9945, 796, 48761, 13, 8443, 273, 13, 8443, 7, 198, 220, 220, 220, 2583, 2625, 21652, 13, 13464, 13, 1959, 13, 2682, 1600, 198, 220, ...
2.099723
361
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test: - MyClass.Items() - MyClass.Keys() - MyClass.Values() - MyClass.Subclasses() - my_class.items() - my_class.keys() - my_class.values() - my_class.subclass() """ import time import pytest from constant2 import Constant from constant2._constant2 import is_same_dict food = Food() if __name__ == "__main__": import os basename = os.path.basename(__file__) pytest.main([basename, "-s", "--tb=native"])
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 14402, 25, 198, 198, 12, 2011, 9487, 13, 23022, 3419, 198, 12, 2011, 9487, 13, 40729, 3419, 198, 12,...
2.513228
189
# Copyright 2015 CloudShare Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
[ 2, 15069, 1853, 10130, 11649, 3457, 13, 201, 198, 201, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 201, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, ...
3.615854
164
from django.db import models
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198 ]
3.625
8
import re import requests def get(url: str) -> dict: """ title、videos """ data = {} headers = { "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36" } re_title = r'<title>(.*?)</title>' re_video = r'<video class="video" src=(.*?)></video>' with requests.get(url, headers=headers, timeout=10) as rep: if rep.status_code == 200: title = re.findall(re_title, rep.text) video = re.findall(re_video, rep.text) if title: data["title"] = title[0] if video: data["videos"] = video else: data["msg"] = "失败" return data if __name__ == "__main__": url = "https://haokan.baidu.com/v?vid=10422427972023610990&tab=recommend" print(get(url))
[ 198, 11748, 302, 198, 11748, 7007, 628, 198, 4299, 651, 7, 6371, 25, 965, 8, 4613, 8633, 25, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 3670, 23513, 32861, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 1366, 796, 23884, 198, ...
2.013953
430
import numpy as np import cv2, sys, os from datetime import datetime from OrientedGradientsComputer import OrientedGradientsComputer from GrayHistogramComputer import GrayHistogramComputer from DeCAF7Computer import DeCAF7Computer from ColorLayoutComputer import ColorLayoutComputer ''' This scripts computes the time it takes to compute the descriptors using a given set of images. ''' if len(sys.argv)<3: print "Usage: python descriptor_benchmark.py image_path output_path" exit(-1) image_path = sys.argv[1] output_path = sys.argv[2] CLDComputer = ColorLayoutComputer() HOGComputer = OrientedGradientsComputer(2,2,100) GHistComputer = GrayHistogramComputer(2,2,32) DeCAFComputer = DeCAF7Computer() images = os.listdir(image_path) images = [x for x in images if (x.endswith(".jpg") or x.endswith(".JPG") or x.endswith(".png"))] images_amount = len (images) print "Computing descriptors for %d files" % images_amount print "Computing CLD..." start = datetime.now() for image in images: img = cv2.imread(os.path.join(image_path, image)) if img is None: continue decaf = CLDComputer.compute(img) if decaf is None: print image continue np.save(open(os.path.join(output_path, image[:200]+".cld"), "w"), decaf) end = datetime.now() total_time = (end - start).total_seconds() print "CLD finished in %d seconds. %.8f seconds per image" % (total_time, total_time/images_amount) file = open("CLD results.txt", "w") file.write("CLD finished in %d seconds. %.8f seconds per image" % (total_time, total_time/images_amount)) file.close() print "Computing HOG..." start = datetime.now() for image in images: img = cv2.imread(os.path.join(image_path, image)) if img is None: continue hog = HOGComputer.compute(img) np.save(open(os.path.join(output_path, image[:200]+".hog"), "w"), hog) end = datetime.now() total_time = (end - start).total_seconds() print "HOG finished in %d seconds. %.8f seconds per image" % (total_time, total_time/images_amount) print "Computing EHD..." start = datetime.now() for image in images: img = cv2.imread(os.path.join(image_path, image)) if img is None: continue ehd = EHDComputer.compute(img) np.save(open(os.path.join(output_path, image[:200]+".ehd"), "w"), ehd) end = datetime.now() total_time = (end - start).total_seconds() print "EHD finished in %d seconds. %.8f seconds per image" % (total_time, total_time/images_amount) print "Computing Gray histogram..." start = datetime.now() for image in images: img = cv2.imread(os.path.join(image_path, image)) if img is None: continue ghist = GHistComputer.compute(img) np.save(open(os.path.join(output_path, image[:200]+".ghist"), "w"), ghist) end = datetime.now() total_time = (end - start).total_seconds() print "Gray histogram finished in %d seconds. %.8f seconds per image" % (total_time, total_time/images_amount) print "Computing DeCAF7..." start = datetime.now() for image in images: img = cv2.imread(os.path.join(image_path, image)) if img is None: continue decaf = DeCAFComputer.compute(img) np.save(open(os.path.join(output_path, image[:200]+".decaf"), "w"), decaf) end = datetime.now() total_time = (end - start).total_seconds() print "DeCAF7 finished in %d seconds. %.8f seconds per image" % (total_time, total_time/images_amount)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 11, 25064, 11, 28686, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 17954, 4714, 42731, 2334, 34556, 1330, 17954, 4714, 42731, 2334, 34556, 198, 6738, 12723, 13749, 21857, 3455...
2.824042
1,148
import unittest import matplotlib.pyplot as plt import numpy as np from vaws.model.curve import vulnerability_weibull, vulnerability_weibull_pdf def single_exponential_given_V(beta_, alpha_, x_arr): """ compute Args: beta_: parameter for vulnerability curve alpha_: parameter for vulnerability curve x_arr: 3sec gust wind speed at 10m height Returns: damage index """ exponent_ = -1.0 * np.power(x_arr / np.exp(beta_), 1.0 / alpha_) return 1 - np.exp(exponent_) if __name__ == '__main__': unittest.main() # suite = unittest.TestLoader().loadTestsFromTestCase(MyTestCase) # unittest.TextTestRunner(verbosity=2).run(suite)
[ 11748, 555, 715, 395, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 410, 8356, 13, 19849, 13, 22019, 303, 1330, 15131, 62, 732, 571, 724, 11, 15131, 62, 732, 571, 7...
2.592453
265
#!/usr/bin/env python # -*- encoding: utf-8 -*- # @Author : Ren Qiang # ACtion2 互补DNA 其中,A与T互补,C与G互补编写函数DNA_strand(dna) # %% 自己的做法 DNA_strand("ATTGC") DNA_strand("AAAA") DNA_strand("ATCGT") # %% 借鉴优秀案例1 Dict = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'} DNA_input = ['ATTGC', 'AAAA', 'ATCGT'] print('优秀案例1:') result = list(map(DNA_trans_1, DNA_input)) # %% 借鉴优秀案例2 DNA_input = ['qttgc', 'AAAA', 'ATCGT'] # 输入 print('优秀案例2:') result = list(map(DNA_trans_2, DNA_input)) # 调用转录函数 # %%
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 13838, 220, 1058, 220, 220, 7152, 1195, 15483, 198, 2, 7125, 5378, 17, 220, 12859, 240, 26193, 98, 28886, 10...
1.465875
337
# Generated by Django 3.1.2 on 2020-10-25 01:03 from django.db import migrations, models import django.db.models.deletion import uuid
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 17, 319, 12131, 12, 940, 12, 1495, 5534, 25, 3070, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, ...
2.833333
48
# Generated by Django 3.0.8 on 2020-09-21 09:26 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 513, 13, 15, 13, 23, 319, 12131, 12, 2931, 12, 2481, 7769, 25, 2075, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.766667
30
import skimage import numpy as np from radon_server.radon_thread import RadonTransformThread
[ 11748, 1341, 9060, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 2511, 261, 62, 15388, 13, 6335, 261, 62, 16663, 1330, 5325, 261, 41762, 16818, 628 ]
3.615385
26
from datetime import timedelta from idact.detail.deployment_sync.deployment_definitions import \ DeploymentDefinitions from idact.detail.helper.stage_info import stage_debug from idact.detail.helper.utc_now import utc_now from idact.detail.log.get_logger import get_logger DISCARD_DELTA_SECONDS = 30 """Discard deployments this number of seconds before the actual expiration date.""" # pylint: disable=bad-continuation def discard_expired_deployments( deployments: DeploymentDefinitions) -> DeploymentDefinitions: # noqa """Returns a new object that does not contain deployments that have expired, or will expire in the near future. :param deployments: Deployments to examine. """ log = get_logger(__name__) with stage_debug(log, "Discarding expired deployments."): now = utc_now() log.debug("Now: %s", now) log.debug("Will discard after the %d second mark" " before the expiration date.", DISCARD_DELTA_SECONDS) discard_now = utc_now() + timedelta(seconds=DISCARD_DELTA_SECONDS) unexpired_nodes = {} for uuid, node in deployments.nodes.items(): if node.expiration_date < discard_now: log.warning("Discarding a synchronized allocation deployment," " because it has expired: %s", uuid) else: unexpired_nodes[uuid] = node unexpired_jupyter_deployments = {} for uuid, jupyter in deployments.jupyter_deployments.items(): if jupyter.expiration_date < discard_now: log.warning("Discarding a Jupyter deployment," " because it has expired: %s", uuid) else: unexpired_jupyter_deployments[uuid] = jupyter unexpired_dask_deployments = {} for uuid, dask in deployments.dask_deployments.items(): if dask.expiration_date < discard_now: log.warning("Discarding a Dask deployment," " because it has expired: %s", uuid) else: unexpired_dask_deployments[uuid] = dask return DeploymentDefinitions( nodes=unexpired_nodes, jupyter_deployments=unexpired_jupyter_deployments, dask_deployments=unexpired_dask_deployments)
[ 6738, 4818, 8079, 1330, 28805, 12514, 198, 198, 6738, 4686, 529, 13, 49170, 13, 2934, 1420, 434, 62, 27261, 13, 2934, 1420, 434, 62, 4299, 50101, 1330, 3467, 198, 220, 220, 220, 34706, 434, 7469, 50101, 198, 6738, 4686, 529, 13, 49170...
2.252141
1,051