content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
from django.conf.urls import url from django.urls import path, include,re_path from . import views from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ path('', views.index, name='index'), path('about', views.about, name='about'), path('projects', views.projects, name='projects'), path('photos', views.photos, name='photos'), re_path(r'^api/projects/$', views.ProjectList.as_view()), re_path(r'^api-token-auth/', obtain_auth_token), re_path(r'api/project/project-id/(?P<pk>[0-9]+)/$', views.ProjectDescription.as_view()), ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 11, 2291, 11, 260, 62, 6978, 198, 6738, 764, 1330, 5009, 198, 6738, 1334, 62, 30604, 13, 18439, 30001, 13, 33571, 1330, 7330,...
2.748815
211
from six.moves import urllib from kiwi.store.tracking.file_store import FileStore
[ 6738, 2237, 13, 76, 5241, 1330, 2956, 297, 571, 198, 198, 6738, 479, 14246, 72, 13, 8095, 13, 36280, 13, 7753, 62, 8095, 1330, 9220, 22658, 628 ]
3.111111
27
from io import BytesIO import json import urllib.parse from collections import OrderedDict from PIL import Image import numpy as np import pytest def test_get_keys(client, use_testdb): rv = client.get('/keys') expected_response = [ {'key': 'key1'}, {'key': 'akey'}, {'key': 'key2', 'description': 'key2'} ] assert rv.status_code == 200 assert expected_response == json.loads(rv.data)['keys'] def test_get_metadata(client, use_testdb): rv = client.get('/metadata/val11/x/val12/') assert rv.status_code == 200 assert ['extra_data'] == json.loads(rv.data)['metadata'] def test_get_metadata_nonexisting(client, use_testdb): rv = client.get('/metadata/val11/x/NONEXISTING/') assert rv.status_code == 404 def test_get_datasets(client, use_testdb): rv = client.get('/datasets') assert rv.status_code == 200 datasets = json.loads(rv.data, object_pairs_hook=OrderedDict)['datasets'] assert len(datasets) == 4 assert OrderedDict([('key1', 'val11'), ('akey', 'x'), ('key2', 'val12')]) in datasets def test_get_datasets_pagination(client, use_testdb): # no page (implicit 0) rv = client.get('/datasets?limit=2') assert rv.status_code == 200 response = json.loads(rv.data, object_pairs_hook=OrderedDict) assert response['limit'] == 2 assert response['page'] == 0 first_datasets = response['datasets'] assert len(first_datasets) == 2 assert OrderedDict([('key1', 'val11'), ('akey', 'x'), ('key2', 'val12')]) in first_datasets # second page rv = client.get('/datasets?limit=2&page=1') assert rv.status_code == 200 response = json.loads(rv.data, object_pairs_hook=OrderedDict) assert response['limit'] == 2 assert response['page'] == 1 last_datasets = response['datasets'] assert len(last_datasets) == 2 assert OrderedDict([('key1', 'val11'), ('akey', 'x'), ('key2', 'val12')]) not in last_datasets # page out of range rv = client.get('/datasets?limit=2&page=1000') assert rv.status_code == 200 assert not json.loads(rv.data)['datasets'] # invalid page rv = client.get('/datasets?page=-1') assert rv.status_code == 400 # invalid limit rv = client.get('/datasets?limit=-1') assert rv.status_code == 400 def test_get_datasets_selective(client, use_testdb): rv = client.get('/datasets?key1=val21') assert rv.status_code == 200 assert len(json.loads(rv.data)['datasets']) == 3 rv = client.get('/datasets?key1=val21&key2=val23') assert rv.status_code == 200 assert len(json.loads(rv.data)['datasets']) == 1 def test_get_datasets_unknown_key(client, use_testdb): rv = client.get('/datasets?UNKNOWN=val21') assert rv.status_code == 400 def test_get_singleband_greyscale(client, use_testdb, raster_file_xyz): import terracotta settings = terracotta.get_settings() x, y, z = raster_file_xyz rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png') assert rv.status_code == 200 img = Image.open(BytesIO(rv.data)) assert np.asarray(img).shape == settings.DEFAULT_TILE_SIZE def test_get_singleband_extra_args(client, use_testdb, raster_file_xyz): import terracotta settings = terracotta.get_settings() x, y, z = raster_file_xyz rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?foo=bar&baz=quz') assert rv.status_code == 200 img = Image.open(BytesIO(rv.data)) assert np.asarray(img).shape == settings.DEFAULT_TILE_SIZE def test_get_singleband_cmap(client, use_testdb, raster_file_xyz): import terracotta settings = terracotta.get_settings() x, y, z = raster_file_xyz rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?colormap=jet') assert rv.status_code == 200 img = Image.open(BytesIO(rv.data)) assert np.asarray(img).shape == settings.DEFAULT_TILE_SIZE def test_get_singleband_preview(client, use_testdb): import terracotta settings = terracotta.get_settings() rv = client.get(f'/singleband/val11/x/val12/preview.png?colormap=jet') assert rv.status_code == 200 img = Image.open(BytesIO(rv.data)) assert np.asarray(img).shape == settings.DEFAULT_TILE_SIZE def urlsafe_json(payload): payload_json = json.dumps(payload) return urllib.parse.quote_plus(payload_json, safe=r',.[]{}:"') def test_get_singleband_explicit_cmap(client, use_testdb, raster_file_xyz): import terracotta settings = terracotta.get_settings() x, y, z = raster_file_xyz explicit_cmap = {1: (0, 0, 0), 2.0: (255, 255, 255, 20), 3: '#ffffff', 4: 'abcabc'} rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?colormap=explicit' f'&explicit_color_map={urlsafe_json(explicit_cmap)}') assert rv.status_code == 200, rv.data.decode('utf-8') img = Image.open(BytesIO(rv.data)) assert np.asarray(img).shape == settings.DEFAULT_TILE_SIZE def test_get_singleband_explicit_cmap_invalid(client, use_testdb, raster_file_xyz): x, y, z = raster_file_xyz explicit_cmap = {1: (0, 0, 0), 2: (255, 255, 255), 3: '#ffffff', 4: 'abcabc'} rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?' f'explicit_color_map={urlsafe_json(explicit_cmap)}') assert rv.status_code == 400 rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?colormap=jet' f'&explicit_color_map={urlsafe_json(explicit_cmap)}') assert rv.status_code == 400 rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?colormap=explicit') assert rv.status_code == 400 explicit_cmap[3] = 'omgomg' rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?colormap=explicit' f'&explicit_color_map={urlsafe_json(explicit_cmap)}') assert rv.status_code == 400 explicit_cmap = [(255, 255, 255)] rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?colormap=explicit' f'&explicit_color_map={urlsafe_json(explicit_cmap)}') assert rv.status_code == 400 rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?colormap=explicit' f'&explicit_color_map=foo') assert rv.status_code == 400 def test_get_singleband_stretch(client, use_testdb, raster_file_xyz): import terracotta settings = terracotta.get_settings() x, y, z = raster_file_xyz for stretch_range in ('[0,1]', '[0,null]', '[null, 1]', '[null,null]', 'null'): rv = client.get(f'/singleband/val11/x/val12/{z}/{x}/{y}.png?stretch_range={stretch_range}') assert rv.status_code == 200 img = Image.open(BytesIO(rv.data)) assert np.asarray(img).shape == settings.DEFAULT_TILE_SIZE
[ 6738, 33245, 1330, 2750, 4879, 9399, 198, 11748, 33918, 198, 11748, 2956, 297, 571, 13, 29572, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 198, 6738, 350, 4146, 1330, 7412, 198, 11748, 299, 32152, 355, 45941, 198, 198, 11748, 129...
2.265101
2,980
def base_conv(n, input_base=10, output_base=10): """ Converts a number n from base input_base to base output_base. The following symbols are used to represent numbers: 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ n can be an int if input_base <= 10, and a string otherwise. The result will be a string. """ numbers = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ## base 10 conversion n = str(n) size = len(n) baseten = 0 for i in range(size): baseten += numbers.index(n[i]) * input_base ** (size - 1 - i) ## base output_base conversion # we search the biggest number m such that n^m < x max_power = 0 while output_base ** (max_power + 1) <= baseten: max_power += 1 result = "" for i in range(max_power + 1): coeff = baseten / (output_base ** (max_power - i)) baseten -= coeff * (output_base ** (max_power - i)) result += numbers[coeff] return result if __name__ == "__main__": assert(base_conv(10) == "10") assert(base_conv(42) == "42") assert(base_conv(5673576) == "5673576") assert(base_conv(10, input_base=2) == "2") assert(base_conv(101010, input_base=2) == "42") assert(base_conv(43, input_base=10, output_base=2) == "101011") assert(base_conv(256**3 - 1, input_base=10, output_base=16) == "ffffff") assert(base_conv("d9bbb9d0ceabf", input_base=16, output_base=8) == "154673563503165277") assert(base_conv("154673563503165277", input_base=8, output_base=10) == "3830404793297599") assert(base_conv(0, input_base=3, output_base=50) == "0")
[ 4299, 2779, 62, 42946, 7, 77, 11, 5128, 62, 8692, 28, 940, 11, 5072, 62, 8692, 28, 940, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 1482, 24040, 257, 1271, 299, 422, 2779, 5128, 62, 8692, 284, 2779, 5072, 62, 8692, 13, ...
2.230263
760
import logging from typing import Dict, List, Optional import numpy as np import qiskit from qiskit.circuit import Barrier, Delay, Reset from qiskit.circuit.library import (CRXGate, CRYGate, CRZGate, CZGate, PhaseGate, RXGate, RYGate, RZGate, U1Gate, U2Gate, U3Gate, UGate) from qiskit.circuit.library.standard_gates import (CU1Gate, RZZGate, SdgGate, SGate, TdgGate, TGate, ZGate) from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.converters.circuit_to_dag import circuit_to_dag from qiskit.dagcircuit import DAGCircuit from qiskit.transpiler.basepasses import TransformationPass logger = logging.getLogger(__name__)
[ 11748, 18931, 198, 6738, 19720, 1330, 360, 713, 11, 7343, 11, 32233, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 10662, 1984, 270, 198, 6738, 10662, 1984, 270, 13, 21170, 5013, 1330, 32804, 11, 42698, 11, 30027, 198, 6738, 1066...
2.029703
404
import IAFNNesterov import numpy as np from scipy import sparse import fil2mat if __name__ == "__main__": print(help())
[ 198, 11748, 314, 8579, 6144, 7834, 709, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 1330, 29877, 198, 11748, 1226, 17, 6759, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 628, 220, 220, 220, 3601,...
2.782609
46
import itertools import BTrees from persistent import Persistent from ZODB.broken import Broken from zope.interface import implementer _marker = object() from .. import exc from ..interfaces import ( IResultSet, STABLE, )
[ 11748, 340, 861, 10141, 198, 11748, 22205, 6037, 198, 198, 6738, 16218, 1330, 9467, 7609, 198, 6738, 1168, 3727, 33, 13, 25826, 1330, 22607, 198, 6738, 1976, 3008, 13, 39994, 1330, 3494, 263, 198, 198, 62, 4102, 263, 796, 2134, 3419, ...
3.232877
73
# Generated by Django 3.2.3 on 2021-05-30 04:28 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 18, 319, 33448, 12, 2713, 12, 1270, 8702, 25, 2078, 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.886792
53
import asyncio import discord # Just with a function to add to the bot. # A Listener already created with the function from discordEasy.objects import Listener listener_on_message = Listener(on_message)
[ 11748, 30351, 952, 198, 11748, 36446, 628, 198, 2, 2329, 351, 257, 2163, 284, 751, 284, 262, 10214, 13, 198, 198, 2, 317, 7343, 877, 1541, 2727, 351, 262, 2163, 198, 6738, 36446, 28406, 13, 48205, 1330, 7343, 877, 198, 198, 4868, 87...
3.745455
55
import os import random from flask import Flask, request, send_from_directory from werkzeug.utils import secure_filename from pianonet.core.pianoroll import Pianoroll from pianonet.model_inspection.performance_from_pianoroll import get_performance_from_pianoroll app = Flask(__name__) base_path = "/app/" # base_path = "/Users/angsten/PycharmProjects/pianonet" performances_path = os.path.join(base_path, 'data', 'performances') def get_random_midi_file_name(): """ Get a random midi file name that will not ever collide. """ return str(random.randint(0, 10000000000000000000)) + ".midi" def get_performance_path(midi_file_name): """ Returns full path to performaqnce midi file given a file name. """ return os.path.join(performances_path, midi_file_name) if __name__ == '__main__': app.run(host='0.0.0.0')
[ 11748, 28686, 198, 11748, 4738, 198, 198, 6738, 42903, 1330, 46947, 11, 2581, 11, 3758, 62, 6738, 62, 34945, 198, 6738, 266, 9587, 2736, 1018, 13, 26791, 1330, 5713, 62, 34345, 198, 198, 6738, 43923, 36823, 13, 7295, 13, 79, 666, 273,...
2.75641
312
import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html import plotly.graph_objects as go from plotly.subplots import make_subplots import logging import json import os import pandas as pd from datetime import datetime from datetime import timedelta from urllib import parse import requests logger = logging.getLogger(__name__) external_stylesheets = [dbc.themes.DARKLY] is_cf_instance = os.environ.get('CF_INSTANCE_GUID', '') != '' port = int(os.environ.get('PORT', 8050)) host = os.environ.get('CF_INSTANCE_INTERNAL_IP', '127.0.0.1') wml_api_key = os.environ['WML_API_KEY'] wml_scoring_url = os.environ['WML_SCORING_URL'] url = parse.urlparse(wml_scoring_url) wml_base_url = url._replace(path='').geturl() wml_instance_id = url.path.split('/')[3] logger.setLevel(logging.INFO if is_cf_instance else logging.DEBUG) logger.info('Starting %s server: %s:%d', 'CF' if is_cf_instance else 'local', host, port) logger.info('WML URL: %s', wml_base_url) logger.info('WML instance ID: %s', wml_instance_id) wml_credentials = { "apikey": wml_api_key, "instance_id": wml_instance_id, "url": wml_base_url, } iam_token_endpoint = 'https://iam.cloud.ibm.com/identity/token' app = dash.Dash(__name__, external_stylesheets=external_stylesheets) app.layout = serve_layout if __name__ == '__main__': app.run_server(debug=(not is_cf_instance), port=port, host=host)
[ 11748, 14470, 198, 11748, 14470, 62, 18769, 26418, 62, 5589, 3906, 355, 288, 15630, 198, 11748, 14470, 62, 7295, 62, 5589, 3906, 355, 288, 535, 198, 11748, 14470, 62, 6494, 62, 5589, 3906, 355, 27711, 198, 11748, 7110, 306, 13, 34960, ...
2.576512
562
# -*- coding: utf-8 -*- __author__ = "Paul Schifferer <dm@sweetrpg.com>" """ """ from flask_rest_jsonapi import ResourceList, ResourceDetail, ResourceRelationship from sweetrpg_library_objects.api.system.schema import SystemAPISchema from sweetrpg_api_core.data import APIData from sweetrpg_library_objects.model.system import System from sweetrpg_library_api.application.db import db from sweetrpg_library_api.application.blueprints.setup import model_info # class SystemAuthorRelationship(ResourceRelationship): # schema = SystemAPISchema # data_layer = { # "class": APIData, # "type": "system", # "model": System, # "db": db, # "model_info": model_info # }
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 834, 9800, 834, 796, 366, 12041, 41665, 11882, 1279, 36020, 31, 34751, 81, 6024, 13, 785, 24618, 198, 37811, 198, 37811, 198, 198, 6738, 42903, 62, 2118, 62, 17752, 1504...
2.659259
270
from robot import __version__ as ROBOT_VERSION import sys import tempfile import textwrap import unittest import shutil import subprocess
[ 6738, 9379, 1330, 11593, 9641, 834, 355, 36449, 2394, 62, 43717, 198, 11748, 25064, 198, 11748, 20218, 7753, 198, 11748, 2420, 37150, 198, 11748, 555, 715, 395, 198, 11748, 4423, 346, 198, 11748, 850, 14681, 628 ]
3.861111
36
#!/usr/bin/python # -*- coding: latin-1 -*- """Setup script.""" try: from setuptools import setup except ImportError: from distutils.core import setup try: import pageviewapi version = pageviewapi.__version__ except ImportError: version = 'Undefined' classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ] packages = ['pageviewapi'] requires = ['requests', 'attrdict'] setup( name='pageviewapi', version=version, author='Commonists', author_email='ps.huard@gmail.com', url='http://github.com/Commonists/pageview-api', description='Wikimedia Pageview API client', long_description=open('README.md').read(), license='MIT', packages=packages, install_requires=requires, classifiers=classifiers )
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3042, 259, 12, 16, 532, 9, 12, 198, 198, 37811, 40786, 4226, 526, 15931, 198, 198, 28311, 25, 198, 220, 220, 220, 422, 900, 37623, 10141, 1330, 9058, 198, 16341,...
2.877193
342
#a2_t1b.py #This program is to convert Celsius to Kelvin c = 25.0 f = 100.0 k = c_to_k(c) fa = f_to_c(f) print("Celsius of " + str(c) + " is " + str(k) + " in Kelvin") print("Farenheit of " + str(f) + " is " + str(fa) + " in Celsius")
[ 2, 64, 17, 62, 83, 16, 65, 13, 9078, 198, 2, 1212, 1430, 318, 284, 10385, 34186, 284, 46577, 198, 66, 796, 1679, 13, 15, 198, 69, 796, 1802, 13, 15, 198, 198, 74, 796, 269, 62, 1462, 62, 74, 7, 66, 8, 198, 13331, 796, 277, ...
2.153153
111
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse, reverse_lazy from django.core.mail import BadHeaderError, send_mail from django.http import HttpResponse, HttpResponseRedirect from django.utils.decorators import method_decorator from django.utils.translation import ugettext_lazy as _ from django.views.generic.edit import FormView from TWLight.emails.forms import ContactUsForm from TWLight.emails.signals import ContactUs
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 6218, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 12501, 273, 2024, 1330, 17594, 62, 35827, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 2448, 3411, 21306, 798, 198, 6738,...
3.5
162
"""Flask App configuration file.""" import logging import os import dotenv import frontend.constants as constants dotenv.load_dotenv(os.path.join(constants.BASEDIR, "frontend.env")) config = { "development": "frontend.config.Development", "staging": "frontend.config.Staging", "production": "frontend.config.Production", "default": "frontend.config.Development", } def configure_app(app): """Configures the Flask app according to the FLASK_ENV envar. In case FLASK_ENV is not defined, then use the 'default' configuration. Parameters ---------- app: flask.Flask Flask app Module. """ # Configure app config_name = os.environ.get("FLASK_ENV", "default") app.config.from_object(config[config_name]) # Configure logging handler = logging.FileHandler(app.config["LOGGING_LOCATION"]) handler.setLevel(app.config["LOGGING_LEVEL"]) formatter = logging.Formatter(app.config["LOGGING_FORMAT"]) handler.setFormatter(formatter) app.logger.addHandler(handler)
[ 37811, 7414, 2093, 2034, 8398, 2393, 526, 15931, 198, 198, 11748, 18931, 198, 11748, 28686, 198, 198, 11748, 16605, 24330, 198, 198, 11748, 2166, 437, 13, 9979, 1187, 355, 38491, 628, 198, 26518, 24330, 13, 2220, 62, 26518, 24330, 7, 41...
2.753927
382
# ElasticQuery # File: tests/test_dsl.py # Desc: tests for ElasticQuery DSL objects (Filter, Query, Aggregate) from os import path from unittest import TestCase from jsontest import JsonTest from elasticquery import Query, Aggregate, Suggester from elasticquery.exceptions import ( NoQueryError, NoAggregateError, NoSuggesterError, MissingArgError ) from .util import assert_equal CLASS_NAMES = { '_query': Query }
[ 2, 48567, 20746, 198, 2, 9220, 25, 5254, 14, 9288, 62, 67, 6649, 13, 9078, 198, 2, 39373, 25, 5254, 329, 48567, 20746, 32643, 5563, 357, 22417, 11, 43301, 11, 19015, 49373, 8, 198, 198, 6738, 28686, 1330, 3108, 198, 6738, 555, 715, ...
3.136691
139
import torch ckp_path = './checkpoints/fashion_PATN/latest_net_netG.pth' save_path = './checkpoints/fashion_PATN_v1.0/latest_net_netG.pth' states_dict = torch.load(ckp_path) states_dict_new = states_dict.copy() for key in states_dict.keys(): if "running_var" in key or "running_mean" in key: del states_dict_new[key] torch.save(states_dict_new, save_path)
[ 11748, 28034, 198, 198, 694, 79, 62, 6978, 796, 705, 19571, 9122, 13033, 14, 25265, 62, 47, 1404, 45, 14, 42861, 62, 3262, 62, 3262, 38, 13, 79, 400, 6, 198, 21928, 62, 6978, 796, 705, 19571, 9122, 13033, 14, 25265, 62, 47, 1404, ...
2.465753
146
#!/usr/bin/python # Copyright 2016 Preferred Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy import rospy import actionlib from geometry_msgs.msg import Twist, Vector3 from apc2016.msg import * if __name__ == '__main__': rospy.init_node("arm_control_dummy", anonymous=True) DummyArmControl() rospy.spin()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 2, 15069, 1584, 31278, 27862, 11, 3457, 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...
3.359684
253
import json import discord from utils.time import format_time from utils import utilities from discord.ext import commands from discord import Embed
[ 11748, 33918, 198, 11748, 36446, 198, 6738, 3384, 4487, 13, 2435, 1330, 5794, 62, 2435, 198, 6738, 3384, 4487, 1330, 20081, 198, 6738, 36446, 13, 2302, 1330, 9729, 198, 6738, 36446, 1330, 13302, 276 ]
4.352941
34
import multiprocessing # ========== #Python3 - concurrent from math import floor, sqrt numbers = [ 112272537195293, 112582718962171, 112272537095293, 115280098190773, 115797840077099, 1099726829285419] # numbers = [33, 44, 55, 275] # ========== #Python3 - concurrent if __name__ == '__main__': print('For these numbers:') print('\n '.join(str(p) for p in numbers)) number, all_factors = prime_factors_of_number_with_lowest_prime_factor(numbers) print(' The one with the largest minimum prime factor is {}:'.format(number)) print(' All its prime factors in order are: {}'.format(all_factors))
[ 11748, 18540, 305, 919, 278, 198, 198, 2, 796, 2559, 28, 1303, 37906, 18, 532, 24580, 198, 6738, 10688, 1330, 4314, 11, 19862, 17034, 198, 198, 77, 17024, 796, 685, 198, 220, 220, 220, 13539, 1983, 1495, 2718, 22186, 31675, 11, 198, ...
2.571429
252
from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='Project: Nowcasting the air pollution using online search log', author='Emory University(IR Lab)', license='MIT', )
[ 6738, 900, 37623, 10141, 1330, 1064, 62, 43789, 11, 9058, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 11639, 10677, 3256, 198, 220, 220, 220, 10392, 28, 19796, 62, 43789, 22784, 198, 220, 220, 220, 2196, 11639, 15, 13, 16, 13, 15,...
2.988506
87
""" Project Euler Problem 48 Self powers Solved by Ahrar Monsur The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. """ main()
[ 37811, 198, 16775, 412, 18173, 20647, 4764, 198, 24704, 5635, 198, 50, 5634, 416, 7900, 20040, 19853, 333, 198, 198, 464, 2168, 11, 352, 61, 16, 1343, 362, 61, 17, 1343, 513, 61, 18, 1343, 2644, 1343, 838, 61, 940, 796, 838, 1821, ...
2.560976
82
#!/usr/bin/python # -*- coding: utf-8 -*- """ @author: rainsty @file: test.py @time: 2020-01-04 18:36:57 @description: """ import os from pyspark.sql import SparkSession os.environ['JAVA_HOME'] = '/root/jdk' os.environ['SPARK_HOME'] = '/root/spark' os.environ['PYTHON_HOME'] = "/root/python" os.environ['PYSPARK_PYTHON'] = "/usr/bin/python" os.environ['SPARK_MASTER_IP'] = 'rainsty' logFile = "/root/spark/README.md" spark = create_spark_context() logData = spark.read.text(logFile).cache() numAs = logData.filter(logData.value.contains('a')).count() numBs = logData.filter(logData.value.contains('b')).count() print("Lines with a: %i, lines with b: %i" % (numAs, numBs)) spark.stop()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 31, 9800, 25, 6290, 34365, 198, 31, 7753, 25, 220, 220, 1332, 13, 9078, 198, 31, 2435, 25, 220, 220, 1213...
2.342282
298
import numpy as np import timeit numIntervalli = input('inserire il numero di intervalli in [0.0, 1.0] ') deltaIntervallo = 1.0 / float(numIntervalli) print "larghezza intervallo", deltaIntervallo start = timeit.default_timer() xIntervalli = [] yIntervalli = [] i = 0 while i < numIntervalli: xIntervallo = i*deltaIntervallo xIntervalli.append(xIntervallo) yIntervalli.append(effe(xIntervallo)) i += 1 areaSottesa = 0.0 for altezza in yIntervalli: areaSottesa += altezza * deltaIntervallo endOld = timeit.default_timer() print "l'area sottesa dalla curva vale ", areaSottesa xNPIntervalli = np.linspace(0.0, 1.0, numIntervalli, endpoint=False) yNPIntervalli = -xNPIntervalli * (xNPIntervalli - 1.0) npArea = np.sum(yNPIntervalli*deltaIntervallo) endNP = timeit.default_timer() # print xNPIntervalli # print xIntervalli # print yNPIntervalli # print yIntervalli print "area numpy = ", npArea print "old timing = ", endOld - start, "numPy timing = ", endNP - endOld
[ 11748, 299, 32152, 355, 45941, 198, 11748, 640, 270, 628, 198, 198, 22510, 9492, 85, 36546, 796, 5128, 10786, 1040, 263, 557, 4229, 997, 3529, 2566, 987, 85, 36546, 287, 685, 15, 13, 15, 11, 352, 13, 15, 60, 705, 8, 198, 198, 67, ...
2.54359
390
import ast from json_codegen.generators.python3_marshmallow.utils import Annotations, class_name
[ 11748, 6468, 198, 198, 6738, 33918, 62, 8189, 5235, 13, 8612, 2024, 13, 29412, 18, 62, 76, 5406, 42725, 13, 26791, 1330, 47939, 11, 1398, 62, 3672, 628 ]
3.535714
28
#!/usr/bin/env python # # $Id: ESMP_GridToMeshRegridCsrv.py,v 1.5 2012/04/23 23:00:14 rokuingh Exp $ #=============================================================================== # ESMP/examples/ESMP_GridToMeshRegrid.py #=============================================================================== """ ESMP_GridToMeshRegridCsrv.py Two ESMP_Field objects are created, one on a Grid and the other on a Mesh. The source Field is set to an analytic function, and a conservative regridding operation is performed from the source to the destination Field. After the regridding is completed, the destination Field is compared to the exact solution over that domain. """ import cdms2 import ESMP import numpy as _NP import unittest def grid_create(): ''' PRECONDITIONS: ESMP has been initialized. POSTCONDITIONS: A ESMP_Grid has been created. ''' ub_x = float(4) ub_y = float(4) lb_x = float(0) lb_y = float(0) max_x = float(4) max_y = float(4) min_x = float(0) min_y = float(0) cellwidth_x = (max_x-min_x)/(ub_x-lb_x) cellwidth_y = (max_y-min_y)/(ub_y-lb_y) cellcenter_x = cellwidth_x/2 cellcenter_y = cellwidth_y/2 maxIndex = _NP.array([ub_x,ub_y], dtype=_NP.int32) grid = ESMP.ESMP_GridCreateNoPeriDim(maxIndex, coordSys=ESMP.ESMP_COORDSYS_CART) ## CORNERS ESMP.ESMP_GridAddCoord(grid, staggerloc=ESMP.ESMP_STAGGERLOC_CORNER) exLB_corner, exUB_corner = ESMP.ESMP_GridGetCoord(grid, \ ESMP.ESMP_STAGGERLOC_CORNER) # get the coordinate pointers and set the coordinates [x,y] = [0, 1] gridXCorner = ESMP.ESMP_GridGetCoordPtr(grid, x, ESMP.ESMP_STAGGERLOC_CORNER) gridYCorner = ESMP.ESMP_GridGetCoordPtr(grid, y, ESMP.ESMP_STAGGERLOC_CORNER) #print 'lower corner bounds = [{0},{1}]'.format(exLB_corner[0],exLB_corner[1]) #print 'upper corner bounds = [{0},{1}]'.format(exUB_corner[0],exUB_corner[1]) p = 0 for i1 in range(exLB_corner[1], exUB_corner[1]): for i0 in range(exLB_corner[0], exUB_corner[0]): gridXCorner[p] = float(i0)*cellwidth_x gridYCorner[p] = float(i1)*cellwidth_y p = p + 1 #print 'Grid corner coordinates:' p = 0 for i1 in range(exLB_corner[1], exUB_corner[1]): for i0 in range(exLB_corner[0], exUB_corner[0]): #print '[{0},{1}]'.format(gridXCorner[p], gridYCorner[p]) p = p + 1 #print '\n' ## CENTERS ESMP.ESMP_GridAddCoord(grid, staggerloc=ESMP.ESMP_STAGGERLOC_CENTER) exLB_center, exUB_center = ESMP.ESMP_GridGetCoord(grid, \ ESMP.ESMP_STAGGERLOC_CENTER) # get the coordinate pointers and set the coordinates [x,y] = [0, 1] gridXCenter = ESMP.ESMP_GridGetCoordPtr(grid, x, ESMP.ESMP_STAGGERLOC_CENTER) gridYCenter = ESMP.ESMP_GridGetCoordPtr(grid, y, ESMP.ESMP_STAGGERLOC_CENTER) #print 'lower corner bounds = [{0},{1}]'.format(exLB_center[0],exLB_center[1]) #print 'upper corner bounds = [{0},{1}]'.format(exUB_center[0],exUB_center[1]) p = 0 for i1 in range(exLB_center[1], exUB_center[1]): for i0 in range(exLB_center[0], exUB_center[0]): gridXCenter[p] = float(i0)*cellwidth_x + cellwidth_x/2.0 gridYCenter[p] = float(i1)*cellwidth_y + cellwidth_y/2.0 p = p + 1 #print 'Grid center coordinates:' p = 0 for i1 in range(exLB_center[1], exUB_center[1]): for i0 in range(exLB_center[0], exUB_center[0]): #print '[{0},{1}]'.format(gridXCenter[p], gridYCenter[p]) p = p + 1 #print '\n' return grid def mesh_create_3x3(mesh): ''' PRECONDITIONS: An ESMP_Mesh has been declared. POSTCONDITIONS: A 3x3 ESMP_Mesh has been created. 3x3 Mesh 3.0 2.0 13 -------14 --------15--------16 | | | | | 7 | 8 | 9 | | | | | 2.5 1.5 9 ------- 10 --------11--------12 | | | | | 4 | 5 | 6 | | | | | 1.5 0.5 5 ------- 6 -------- 7-------- 8 | | | | | 1 | 2 | 3 | | | | | 1.0 0.0 1 ------- 2 -------- 3-------- 4 0.0 0.5 1.5 2.0 1.0 1.5 2.5 3.0 Node Ids at corners Element Ids in centers (Everything owned by PET 0) ''' # set up a simple mesh num_node = 16 num_elem = 9 nodeId = _NP.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]) ''' # this is for grid to mesh nodeCoord = _NP.array([1.0,1.0, 1.5,1.0, 2.5,1.0, 3.0,1.0, 1.0,1.5, 1.5,1.5, 2.5,1.5, 3.0,1.5, 1.0,2.5, 1.5,2.5, 2.5,2.5, 3.0,2.5, 1.0,3.0, 1.5,3.0, 2.5,3.0, 3.0,3.0]) ''' # this is for mesh to grid nodeCoord = _NP.array([0.0,0.0, 1.5,0.0, 2.5,0.0, 4.0,0.0, 0.0,1.5, 1.5,1.5, 2.5,1.5, 4.0,1.5, 0.0,2.5, 1.5,2.5, 2.5,2.5, 4.0,2.5, 0.0,4.0, 1.5,4.0, 2.5,4.0, 4.0,4.0]) nodeOwner = _NP.zeros(num_node, dtype=_NP.int32) elemId = _NP.array([1,2,3,4,5,6,7,8,9], dtype=_NP.int32) elemType = _NP.ones(num_elem, dtype=_NP.int32) elemType*=ESMP.ESMP_MESHELEMTYPE_QUAD elemConn = _NP.array([0,1,5,4, 1,2,6,5, 2,3,7,6, 4,5,9,8, 5,6,10,9, 6,7,11,10, 8,9,13,12, 9,10,14,13, 10,11,15,14], dtype=_NP.int32) ESMP.ESMP_MeshAddNodes(mesh,num_node,nodeId,nodeCoord,nodeOwner) ESMP.ESMP_MeshAddElements(mesh,num_elem,elemId,elemType,elemConn) #print 'Mesh coordinates:' for i in range(num_node): x = nodeCoord[2*i] y = nodeCoord[2*i+1] #print '[{0},{1}]'.format(x, y) #print '\n' return mesh, nodeCoord, elemType, elemConn def create_ESMPmesh_3x3(): ''' PRECONDITIONS: ESMP is initialized. POSTCONDITIONS: An ESMP_Mesh (3x3) has been created and returned as 'mesh'. ''' # Two parametric dimensions, and three spatial dimensions mesh = ESMP.ESMP_MeshCreate(2,2) mesh, nodeCoord, elemType, elemConn = mesh_create_3x3(mesh) return mesh, nodeCoord, elemType, elemConn def create_ESMPfieldgrid(grid, name): ''' PRECONDITIONS: An ESMP_Grid has been created, and 'name' is a string that will be used to initialize the name of a new ESMP_Field. POSTCONDITIONS: An ESMP_Field has been created. ''' # defaults to center staggerloc field = ESMP.ESMP_FieldCreateGrid(grid, name) return field def build_analyticfieldgrid(field, grid): ''' PRECONDITIONS: An ESMP_Field has been created. POSTCONDITIONS: The 'field' has been initialized to an analytic field. ''' # get the field pointer first fieldPtr = ESMP.ESMP_FieldGetPtr(field) # get the grid bounds and coordinate pointers exLB, exUB = ESMP.ESMP_GridGetCoord(grid, ESMP.ESMP_STAGGERLOC_CENTER) # get the coordinate pointers and set the coordinates [x,y] = [0, 1] gridXCoord = ESMP.ESMP_GridGetCoordPtr(grid, x, ESMP.ESMP_STAGGERLOC_CENTER) gridYCoord = ESMP.ESMP_GridGetCoordPtr(grid, y, ESMP.ESMP_STAGGERLOC_CENTER) #print "Grid center coordinates" p = 0 for i1 in range(exLB[1], exUB[1]): for i0 in range(exLB[0], exUB[0]): xc = gridXCoord[p] yc = gridYCoord[p] fieldPtr[p] = 20.0+xc+yc #fieldPtr[p] = 20.0+xc*yc+yc**2 #print '[{0},{1}] = {2}'.format(xc,yc,fieldPtr[p]) p = p + 1 #print "\n" return field def create_ESMPfield(mesh, name): ''' PRECONDITIONS: An ESMP_Mesh has been created, and 'name' is a string that will be used to initialize the name of a new ESMP_Field. POSTCONDITIONS: An ESMP_Field has been created. ''' field = ESMP.ESMP_FieldCreate(mesh, name, meshloc=ESMP.ESMP_MESHLOC_ELEMENT) return field def build_analyticfield(field, nodeCoord, elemType, elemConn): ''' PRECONDITIONS: An ESMP_Field has been created. POSTCONDITIONS: The 'field' has been initialized to an analytic field. ''' # get the field pointer first fieldPtr = ESMP.ESMP_FieldGetPtr(field, 0) # set the field to a vanilla initial field for now #print "Mesh center coordinates" offset = 0 for i in range(field.size): # this routine assumes this field is on elements if (elemType[i] == ESMP.ESMP_MESHELEMTYPE_TRI): raise NameError("Cannot compute a non-constant analytic field for a mesh\ with triangular elements!") x1 = nodeCoord[(elemConn[offset])*2] x2 = nodeCoord[(elemConn[offset+1])*2] y1 = nodeCoord[(elemConn[offset+1])*2+1] y2 = nodeCoord[(elemConn[offset+3])*2+1] x = (x1+x2)/2.0 y = (y1+y2)/2.0 fieldPtr[i] = 20.0+x+y #fieldPtr[i] = 20.0+x*y+y**2 #print '[{0},{1}] = {2}'.format(x,y,fieldPtr[i]) offset = offset + 4 #print "\n" return field def run_regridding(srcfield, dstfield): ''' PRECONDITIONS: Two ESMP_Fields have been created and a regridding operation is desired from 'srcfield' to 'dstfield'. POSTCONDITIONS: An ESMP regridding operation has set the data on 'dstfield'. ''' # call the regridding functions routehandle = ESMP.ESMP_FieldRegridStore(srcfield, dstfield, regridmethod=ESMP.ESMP_REGRIDMETHOD_CONSERVE, unmappedaction=ESMP.ESMP_UNMAPPEDACTION_ERROR) ESMP.ESMP_FieldRegrid(srcfield, dstfield, routehandle) ESMP.ESMP_FieldRegridRelease(routehandle) return dstfield def compare_fields(field1, field2): ''' PRECONDITIONS: Two ESMP_Fields have been created and a comparison of the the values is desired between 'srcfield' and 'dstfield'. POSTCONDITIONS: The values on 'srcfield' and 'dstfield' are compared. returns True if the fileds are comparable (success) ''' # get the data pointers for the fields field1ptr = ESMP.ESMP_FieldGetPtr(field1) field2ptr = ESMP.ESMP_FieldGetPtr(field2) # compare point values of field1 to field2 # first verify they are the same size if (field1.size != field2.size): raise NameError('compare_fields: Fields must be the same size!') # initialize to True, and check for False point values correct = True totalErr = 0.0 for i in range(field1.size): err = abs(field1ptr[i] - field2ptr[i])/abs(field2ptr[i]) if err > .06: correct = False print "ACCURACY ERROR - "+str(err) print "field1 = {0} : field2 = {1}\n".format(field1ptr[i], field2ptr[i]) totalErr += err if correct: print " - PASS - Total Error = "+str(totalErr) return True else: print " - FAIL - Total Error = "+str(totalErr) return False if __name__ == '__main__': ESMP.ESMP_LogSet(True) print "" # Spacer suite = unittest.TestLoader().loadTestsFromTestCase(TestESMP_GridToMeshRegridCsrv) unittest.TextTestRunner(verbosity = 1).run(suite)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 720, 7390, 25, 13380, 7378, 62, 41339, 2514, 37031, 8081, 6058, 34, 27891, 85, 13, 9078, 11, 85, 352, 13, 20, 2321, 14, 3023, 14, 1954, 2242, 25, 405, 25, 1415, 686, 7...
2.059277
5,449
# Copyright 2019 IBM Corporation # # 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 sklearn.neighbors # class that follows scikit-learn conventions but lacks schemas, # for the purpose of testing how to wrap an operator without schemas
[ 2, 15069, 13130, 19764, 10501, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 73...
3.978378
185
import json import re import sys def beautify(name): ''' Loading, filtering and saving the JSON tweet file to a newly generated .txt file :type: name: String :rtype: output: .txt ''' filename = name + '.json' output_name = name + "_filtered.txt" with open(filename, "r", encoding="utf-8") as input: with open(output_name, "w", encoding="utf-8") as output: document = json.load(input) # Filter only the messages that are not retweeted # >> Version i): for tweets from archive "master_XXXX.json" # document = [x['full_text'] for x in document if x['user']['screen_name'] == 'realDonaldTrump' and 'full_text' in x] # >> Version ii): for self-scraped tweets via https://github.com/bpb27/twitter_scraping # document = [x['text'] for x in document if x['user']['screen_name'] == 'realDonaldTrump' and 'text' in x] # >> Version iii): Data set from https://github.com/MatthewWolff/MarkovTweets/ document = [x['text'] for x in document] # Clean and only include not retweeted messages document = [deep_clean(x) for x in document if deep_clean(x) is not None] # Preventing unicode characters by ensuring false ascii encoding for _, value in enumerate(document): output.write(json.dumps(value, ensure_ascii=False) + "\n") # json.dump(document, output, ensure_ascii=False, indent=4) print(f">> Sucessfully cleaned {filename} and saved it to {output_name}") def deep_clean(s): ''' Deep cleaning of filtered tweets. Replaces common symbols and kills quotation marks/apostrophes. :type: s: String :rtype: s: String ''' # Return None if given tweet is a retweet if s[:2] == 'RT': return None # Delete all URLs because they don't make for interesting tweets. s = re.sub(r'http[\S]*', '', s) # Replace some common unicode symbols with raw character variants s = re.sub(r'\\u2026', '...', s) s = re.sub(r'', '', s) s = re.sub(r'\\u2019', "'", s) s = re.sub(r'\\u2018', "'", s) s = re.sub(r"&amp;", r"&", s) s = re.sub(r'\\n', r"", s) # Delete emoji modifying characters s = re.sub(chr(127996), '', s) s = re.sub(chr(65039), '', s) # Kill apostrophes & punctuation because they confuse things. s = re.sub(r"'", r"", s) s = re.sub(r"", r"", s) s = re.sub(r"", r"", s) s = re.sub('[()]', r'', s) s = re.sub(r'"', r"", s) # Collapse multiples of certain chars s = re.sub('([.-])+', r'\1', s) # Pad sentence punctuation chars with whitespace s = re.sub('([^0-9])([.,!?])([^0-9])', r'\1 \2 \3', s) # Remove extra whitespace (incl. newlines) s = ' '.join(s.split()).lower() # Define emoji_pattern emoji_pattern = re.compile("[" u"\U0001F600-\U0001F64F" # emoticons u"\U0001F300-\U0001F5FF" # symbols & pictographs u"\U0001F680-\U0001F6FF" # transport & map symbols u"\U0001F1E0-\U0001F1FF" # flags (iOS) u"\U0001F1F2-\U0001F1F4" # Macau flag u"\U0001F1E6-\U0001F1FF" # flags u"\U0001F600-\U0001F64F" u"\U00002702-\U000027B0" u"\U000024C2-\U0001F251" u"\U0001f926-\U0001f937" u"\U0001F1F2" u"\U0001F1F4" u"\U0001F620" u"\u200d" u"\u2640-\u2642" "]+", flags=re.UNICODE) s = emoji_pattern.sub(r'', s) # Care for a special case where the first char is a "." # return s[1:] if s[0] == "." else s if len(s): return s[1:] if s[0] == "." else s return None if __name__ == "__main__": if len(sys.argv) - 1: beautify(sys.argv[1])
[ 11748, 33918, 198, 11748, 302, 198, 11748, 25064, 628, 198, 4299, 3566, 1958, 7, 3672, 2599, 198, 220, 220, 220, 705, 7061, 12320, 11, 25431, 290, 8914, 262, 19449, 6126, 2393, 284, 257, 8308, 7560, 764, 14116, 2393, 198, 220, 220, 22...
2.182503
1,726
import BboxToolkit as bt import pickle import copy import numpy as np path1="/home/hnu1/GGM/OBBDetection/work_dir/oriented_obb_contrast_catbalance/dets.pkl" path2="/home/hnu1/GGM/OBBDetection/data/FaIR1M/test/annfiles/ori_annfile.pkl"# with open(path2,'rb') as f: #/home/disk/FAIR1M_1000_split/val/annfiles/ori_annfile.pkl data2 = pickle.load(f) with open(path1,'rb') as f: obbdets = pickle.load(f) polydets=copy.deepcopy(obbdets) for i in range(len(obbdets)): for j in range(len(obbdets[0][1])): data=obbdets[i][1][j] if data.size!= 0: polys=[] for k in range(len(data)): poly = bt.obb2poly(data[k][0:5]) poly=np.append(poly,data[k][5]) polys.append(poly) else: polys=[] polydets[i][1][j]=polys savepath="/home/hnu1/GGM/OBBDetection/work_dir/oriented_obb_contrast_catbalance/result_txt/" for i in range(len(polydets)): txtfile=savepath+polydets[i][0]+".txt" f = open(txtfile, "w") for j in range(len(polydets[0][1])): if polydets[i][1][j]!=[]: for k in range(len(polydets[i][1][j])): f.write(str(polydets[i][1][j][k][0])+" "+ str(polydets[i][1][j][k][1])+" "+ str(polydets[i][1][j][k][2])+" "+ str(polydets[i][1][j][k][3])+" "+ str(polydets[i][1][j][k][4])+" "+ str(polydets[i][1][j][k][5])+" "+ str(polydets[i][1][j][k][6])+" "+ str(polydets[i][1][j][k][7])+" "+ str(data2["cls"][j])+" "+ str(polydets[i][1][j][k][8])+"\n") f.close()
[ 11748, 347, 3524, 25391, 15813, 355, 275, 83, 198, 11748, 2298, 293, 198, 11748, 4866, 198, 11748, 299, 32152, 355, 45941, 198, 6978, 16, 35922, 11195, 14, 21116, 84, 16, 14, 11190, 44, 14, 9864, 33, 11242, 3213, 14, 1818, 62, 15908, ...
1.690223
1,033
import taichi as ti import utils from apic_extension import *
[ 11748, 20486, 16590, 355, 46668, 198, 11748, 3384, 4487, 198, 6738, 2471, 291, 62, 2302, 3004, 1330, 1635, 628 ]
3.315789
19
from copy import deepcopy import bifrost as bf from bifrost.pipeline import TransformBlock from bifrost.ndarray import copy_array bc = bf.BlockChainer() bc.blocks.read_wav(['hey_jude.wav'], gulp_nframe=4096) bc.custom(copy_block)(space='cuda')# $\tikzmark{gpu-start}$ bc.views.split_axis('time', 256, label='fine_time') bc.blocks.fft(axes='fine_time', axis_labels='freq') bc.blocks.detect(mode='scalar') bc.blocks.transpose(['time', 'pol', 'freq'])#$\tikzmark{gpu-end}$ bc.blocks.copy(space='system') bc.blocks.quantize('i8') bc.blocks.write_sigproc() pipeline = bf.get_default_pipeline()# $\tikzmark{pipeline-start}$ pipeline.shutdown_on_signals() pipeline.run()#$\tikzmark{pipeline-end}$
[ 6738, 4866, 1330, 2769, 30073, 198, 220, 198, 11748, 275, 361, 23341, 355, 275, 69, 198, 6738, 275, 361, 23341, 13, 79, 541, 4470, 1330, 26981, 12235, 198, 6738, 275, 361, 23341, 13, 358, 18747, 1330, 4866, 62, 18747, 198, 220, 628, ...
2.222222
333
# (C) Copyright 2016-2017 Hewlett Packard Enterprise Development LP # Copyright 2017 FUJITSU LIMITED # # 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 oslo_config import cfg influxdb_opts = [ cfg.StrOpt('database_name', help='database name where metrics are stored', default='mon'), cfg.HostAddressOpt('ip_address', help='Valid IP address or hostname ' 'to InfluxDB instance'), cfg.PortOpt('port', help='port to influxdb', default=8086), cfg.StrOpt('user', help='influxdb user ', default='mon_persister'), cfg.StrOpt('password', secret=True, help='influxdb password')] influxdb_group = cfg.OptGroup(name='influxdb', title='influxdb')
[ 2, 357, 34, 8, 15069, 1584, 12, 5539, 30446, 15503, 6400, 446, 14973, 7712, 18470, 198, 2, 15069, 2177, 376, 52, 41, 2043, 12564, 40880, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, ...
2.483577
548
import json your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]' parsed = json.loads(your_json) print(type(your_json)) print(type(parsed)) #print(json.dumps(parsed, indent=4, sort_keys=True))
[ 11748, 33918, 198, 198, 14108, 62, 17752, 796, 705, 14692, 21943, 1600, 19779, 5657, 26358, 65, 1031, 1600, 9242, 11, 352, 13, 15, 11, 362, 48999, 49946, 198, 79, 945, 276, 796, 33918, 13, 46030, 7, 14108, 62, 17752, 8, 198, 4798, 7...
2.37037
81
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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. # # @@license_version:1.7@@ import cloudstorage import logging from babel.dates import format_datetime from datetime import datetime from google.appengine.ext import ndb, deferred, db from typing import List from xlwt import Worksheet, Workbook, XFStyle from mcfw.cache import invalidate_cache from mcfw.consts import REST_TYPE_TO from mcfw.exceptions import HttpBadRequestException, HttpForbiddenException, HttpNotFoundException from mcfw.restapi import rest from mcfw.rpc import returns, arguments from rogerthat.bizz.gcs import get_serving_url from rogerthat.bizz.service import re_index_map_only from rogerthat.consts import FAST_QUEUE from rogerthat.models import ServiceIdentity from rogerthat.models.settings import ServiceInfo from rogerthat.rpc import users from rogerthat.rpc.users import get_current_session from rogerthat.utils import parse_date from rogerthat.utils.service import create_service_identity_user from shop.models import Customer from solutions import translate from solutions.common.bizz import SolutionModule, broadcast_updates_pending from solutions.common.bizz.campaignmonitor import send_smart_email_without_check from solutions.common.consts import OCA_FILES_BUCKET from solutions.common.dal import get_solution_settings from solutions.common.integrations.cirklo.cirklo import get_city_id_by_service_email, whitelist_merchant, \ list_whitelisted_merchants, list_cirklo_cities from solutions.common.integrations.cirklo.models import CirkloCity, CirkloMerchant, SignupLanguageProperty, \ SignupMails, CirkloAppInfo from solutions.common.integrations.cirklo.to import CirkloCityTO, CirkloVoucherListTO, CirkloVoucherServiceTO, \ WhitelistVoucherServiceTO from solutions.common.restapi.services import _check_is_city
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 12131, 3469, 6916, 15664, 23973, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, ...
3.38604
702
import matplotlib matplotlib.use('Agg') import numpy as np from astropy.tests.helper import pytest from .. import FITSFigure
[ 11748, 2603, 29487, 8019, 198, 6759, 29487, 8019, 13, 1904, 10786, 46384, 11537, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 6468, 28338, 13, 41989, 13, 2978, 525, 1330, 12972, 9288, 198, 198, 6738, 11485, 1330, 376, 29722, 11337,...
3.045455
44
import os, sys Project( title='ViZual language environment', about=''' * object (hyper)graph interpreter ''' ).sync()
[ 11748, 28686, 11, 25064, 198, 16775, 7, 198, 220, 220, 220, 3670, 11639, 38432, 57, 723, 3303, 2858, 3256, 198, 220, 220, 220, 546, 28, 7061, 6, 198, 9, 2134, 357, 49229, 8, 34960, 28846, 198, 7061, 6, 198, 737, 27261, 3419, 198 ]
2.930233
43
import asyncio import logging import aiohttp import uvicorn from fastai.vision import * from starlette.applications import Starlette from starlette.middleware.cors import CORSMiddleware from starlette.responses import JSONResponse # put your url here here model_file_url = 'https://www.dropbox.com/s/...?raw=1' model_file_name = 'model' path = Path(__file__).parent logging.basicConfig(format="%(levelname)s: %(message)s", level=logging.INFO) logger = logging.getLogger() logger.setLevel(logging.INFO) app = Starlette() app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_headers=['X-Requested-With', 'Content-Type']) loop = asyncio.get_event_loop() tasks = [asyncio.ensure_future(setup_learner())] model, classes = loop.run_until_complete(asyncio.gather(*tasks))[0] loop.close() if __name__ == '__main__': if 'serve' in sys.argv: uvicorn.run(app, host='0.0.0.0' port=4000)
[ 11748, 30351, 952, 198, 11748, 18931, 198, 198, 11748, 257, 952, 4023, 198, 11748, 334, 25531, 1211, 198, 6738, 3049, 1872, 13, 10178, 1330, 1635, 198, 6738, 3491, 21348, 13, 1324, 677, 602, 1330, 2907, 21348, 198, 6738, 3491, 21348, 13...
2.717718
333
from socket import * serverPort = 12001 serverSocket = socket(AF_INET, SOCK_STREAM) serverSocket.bind(('', serverPort)) serverSocket.listen(1) print("the server is ready to receive") while True: connectionSocket,addr = serverSocket.accept() sentence = connectionSocket.recv(1024).decode() sentence = sentence.upper() connectionSocket.send(sentence.encode()) connectionSocket.close()
[ 6738, 17802, 1330, 1635, 198, 15388, 13924, 796, 1105, 8298, 198, 15388, 39105, 796, 17802, 7, 8579, 62, 1268, 2767, 11, 311, 11290, 62, 2257, 32235, 8, 198, 15388, 39105, 13, 21653, 7, 10786, 3256, 4382, 13924, 4008, 198, 15388, 39105,...
3.190476
126
"""This module contains the GeneFlow LocalWorkflow class."""
[ 37811, 1212, 8265, 4909, 262, 13005, 37535, 10714, 12468, 11125, 1398, 526, 15931, 198 ]
4.357143
14
from torch.optim.lr_scheduler import StepLR, ReduceLROnPlateau, OneCycleLR def step_lr(optimizer, step_size, gamma=0.1, last_epoch=-1): """Create LR step scheduler. Args: optimizer (torch.optim): Model optimizer. step_size (int): Frequency for changing learning rate. gamma (float): Factor for changing learning rate. (default: 0.1) last_epoch (int): The index of last epoch. (default: -1) Returns: StepLR: Learning rate scheduler. """ return StepLR(optimizer, step_size=step_size, gamma=gamma, last_epoch=last_epoch) def reduce_lr_on_plateau(optimizer, factor=0.1, patience=10, verbose=False, min_lr=0): """Create LR plateau reduction scheduler. Args: optimizer (torch.optim): Model optimizer. factor (float, optional): Factor by which the learning rate will be reduced. (default: 0.1) patience (int, optional): Number of epoch with no improvement after which learning rate will be will be reduced. (default: 10) verbose (bool, optional): If True, prints a message to stdout for each update. (default: False) min_lr (float, optional): A scalar or a list of scalars. A lower bound on the learning rate of all param groups or each group respectively. (default: 0) Returns: ReduceLROnPlateau instance. """ return ReduceLROnPlateau( optimizer, factor=factor, patience=patience, verbose=verbose, min_lr=min_lr ) def one_cycle_lr( optimizer, max_lr, epochs, steps_per_epoch, pct_start=0.5, div_factor=10.0, final_div_factor=10000 ): """Create One Cycle Policy for Learning Rate. Args: optimizer (torch.optim): Model optimizer. max_lr (float): Upper learning rate boundary in the cycle. epochs (int): The number of epochs to train for. This is used along with steps_per_epoch in order to infer the total number of steps in the cycle. steps_per_epoch (int): The number of steps per epoch to train for. This is used along with epochs in order to infer the total number of steps in the cycle. pct_start (float, optional): The percentage of the cycle (in number of steps) spent increasing the learning rate. (default: 0.5) div_factor (float, optional): Determines the initial learning rate via initial_lr = max_lr / div_factor. (default: 10.0) final_div_factor (float, optional): Determines the minimum learning rate via min_lr = initial_lr / final_div_factor. (default: 1e4) Returns: OneCycleLR instance. """ return OneCycleLR( optimizer, max_lr, epochs=epochs, steps_per_epoch=steps_per_epoch, pct_start=pct_start, div_factor=div_factor, final_div_factor=final_div_factor )
[ 6738, 28034, 13, 40085, 13, 14050, 62, 1416, 704, 18173, 1330, 5012, 35972, 11, 44048, 35972, 2202, 3646, 378, 559, 11, 1881, 20418, 2375, 35972, 628, 198, 4299, 2239, 62, 14050, 7, 40085, 7509, 11, 2239, 62, 7857, 11, 34236, 28, 15, ...
2.59
1,100
# Copyright 2019 TerraPower, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test for Zones""" import copy import unittest import armi from armi import settings from armi.reactor import assemblies from armi.reactor import blueprints from armi.reactor import geometry from armi.reactor import grids from armi.reactor import reactors from armi.reactor import zones from armi.reactor.flags import Flags from armi.reactor.tests import test_reactors from armi.utils import pathTools from armi.settings.fwSettings import globalSettings THIS_DIR = pathTools.armiAbsDirFromName(__name__) if __name__ == "__main__": # import sys;sys.argv = ['', 'Zones_InReactor.test_buildRingZones'] unittest.main()
[ 2, 15069, 13130, 24118, 13434, 11, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 9...
3.443182
352
# Generated by Django 3.1.12 on 2021-07-12 19:32 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 1065, 319, 33448, 12, 2998, 12, 1065, 678, 25, 2624, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.875
32
import aspose.email.mapi.msg as msg from aspose.email.mapi import MapiNote, NoteSaveFormat, NoteColor if __name__ == '__main__': run()
[ 11748, 355, 3455, 13, 12888, 13, 8899, 72, 13, 19662, 355, 31456, 198, 6738, 355, 3455, 13, 12888, 13, 8899, 72, 1330, 9347, 72, 6425, 11, 5740, 16928, 26227, 11, 5740, 10258, 198, 197, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12...
2.711538
52
import functools from string import Formatter from typing import ( TYPE_CHECKING, Any, Set, Dict, List, Type, Tuple, Union, Generic, Mapping, TypeVar, Callable, Optional, Sequence, cast, overload, ) if TYPE_CHECKING: from .message import Message, MessageSegment TM = TypeVar("TM", bound="Message") TF = TypeVar("TF", str, "Message") FormatSpecFunc = Callable[[Any], str] FormatSpecFunc_T = TypeVar("FormatSpecFunc_T", bound=FormatSpecFunc) def format(self, *args, **kwargs): """""" return self._format(args, kwargs) def format_map(self, mapping: Mapping[str, Any]) -> TF: """, """ return self._format([], mapping)
[ 11748, 1257, 310, 10141, 198, 6738, 4731, 1330, 5178, 1436, 198, 6738, 19720, 1330, 357, 198, 220, 220, 220, 41876, 62, 50084, 2751, 11, 198, 220, 220, 220, 4377, 11, 198, 220, 220, 220, 5345, 11, 198, 220, 220, 220, 360, 713, 11, ...
2.386885
305
# -*- coding: utf-8 -*- if __name__ == '__main__': main()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 201, 198, 201, 198, 201, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 201, 198, 220, 220, 220, 1388, 3419, 201, 198 ]
1.775
40
""" """ names = ['', '', '', '', ''] courses = ['', '', ''] # scores = [[None] * len(courses) for _ in range(len(names))] for row, name in enumerate(names): for col, course in enumerate(courses): scores[row][col] = float(input(f'{name}{course}:')) print(scores)
[ 37811, 198, 198, 37811, 628, 198, 14933, 796, 37250, 3256, 705, 3256, 705, 3256, 705, 3256, 10148, 60, 198, 66, 39975, 796, 37250, 3256, 705, 3256, 10148, 60, 198, 2, 220, 198, 1416, 2850, 796, 16410, 14202, 60, 1635, 18896, 7, 66, ...
2.355372
121
import logging import random import numpy as np import pypinyin import tensorflow as tf from augmentations.augments import Augmentation from utils.speech_featurizers import SpeechFeaturizer from utils.text_featurizers import TextFeaturizer logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') import time
[ 11748, 18931, 198, 11748, 4738, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 279, 4464, 3541, 259, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 198, 6738, 35016, 602, 13, 7493, 902, 1330, 2447, 14374, 198, 6738, 3384, 4487, 1...
3.140351
114
"""empty message Revision ID: 2018_04_20_data_src_refactor Revises: 2018_04_11_add_sandbox_topic Create Date: 2018-04-20 13:03:32.478880 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. from sqlalchemy.dialects.postgresql import ARRAY revision = '2018_04_20_data_src_refactor' down_revision = '2018_04_11_add_sandbox_topic' branch_labels = None depends_on = None
[ 37811, 28920, 3275, 198, 198, 18009, 1166, 4522, 25, 2864, 62, 3023, 62, 1238, 62, 7890, 62, 10677, 62, 5420, 11218, 198, 18009, 2696, 25, 2864, 62, 3023, 62, 1157, 62, 2860, 62, 38142, 3524, 62, 26652, 198, 16447, 7536, 25, 2864, 1...
2.647436
156
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # coded by Vikas Kundu https://github.com/vikas-kundu # ------------------------------------------- import sys import getopt import time import config from lib.core.parse import banner from lib.core import util from lib.core import installer
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 201, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 201, 198, 2, 30817, 416, 10447, 292, 45099, 84, 3740, 1378, 12567, 13, 785, 14, 28930, 292, 12, 74, 917, 84, 201, ...
3.091837
98
# Copyright 2013 - Mirantis, Inc. # Copyright 2015 - StackStorm, Inc. # Copyright 2015 - Huawei Technologies Co. Ltd # # 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 mistral import exceptions as exc from mistral.tests.unit import base from mistral.utils import ssh_utils from mistral_lib import utils
[ 2, 15069, 2211, 532, 7381, 20836, 11, 3457, 13, 198, 2, 15069, 1853, 532, 23881, 32173, 11, 3457, 13, 198, 2, 15069, 1853, 532, 43208, 21852, 1766, 13, 12052, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, ...
3.510549
237
import xmltodict import json from .models import Tunein from .utils import _init_session from .Exceptions import APIException base_url = 'http://api.shoutcast.com' tunein_url = 'http://yp.shoutcast.com/{base}?id={id}' tuneins = [Tunein('/sbin/tunein-station.pls'), Tunein('/sbin/tunein-station.m3u'), Tunein('/sbin/tunein-station.xspf')]
[ 11748, 2124, 76, 2528, 375, 713, 198, 11748, 33918, 198, 6738, 764, 27530, 1330, 42587, 259, 198, 6738, 764, 26791, 1330, 4808, 15003, 62, 29891, 198, 6738, 764, 3109, 11755, 1330, 7824, 16922, 198, 198, 8692, 62, 6371, 796, 705, 4023, ...
2.47482
139
from django.core.management.base import BaseCommand, no_translations from django.contrib.auth.models import Group from django.conf import settings import sys
[ 6738, 42625, 14208, 13, 7295, 13, 27604, 13, 8692, 1330, 7308, 21575, 11, 645, 62, 7645, 49905, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 4912, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 1...
3.636364
44
# Copyright (c) 2010-2012 OpenStack 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. """ Database code for Swift """ from contextlib import contextmanager, closing import hashlib import logging import os from uuid import uuid4 import sys import time import errno import six.moves.cPickle as pickle from swift import gettext_ as _ from tempfile import mkstemp from eventlet import sleep, Timeout import sqlite3 from swift.common.constraints import MAX_META_COUNT, MAX_META_OVERALL_SIZE from swift.common.utils import json, Timestamp, renamer, \ mkdirs, lock_parent_directory, fallocate from swift.common.exceptions import LockTimeout from swift.common.swob import HTTPBadRequest #: Whether calls will be made to preallocate disk space for database files. DB_PREALLOCATION = False #: Timeout for trying to connect to a DB BROKER_TIMEOUT = 25 #: Pickle protocol to use PICKLE_PROTOCOL = 2 #: Max number of pending entries PENDING_CAP = 131072 def dict_factory(crs, row): """ This should only be used when you need a real dict, i.e. when you're going to serialize the results. """ return dict( ((col[0], row[idx]) for idx, col in enumerate(crs.description))) def chexor(old, name, timestamp): """ Each entry in the account and container databases is XORed by the 128-bit hash on insert or delete. This serves as a rolling, order-independent hash of the contents. (check + XOR) :param old: hex representation of the current DB hash :param name: name of the object or container being inserted :param timestamp: internalized timestamp of the new record :returns: a hex representation of the new hash value """ if name is None: raise Exception('name is None!') new = hashlib.md5(('%s-%s' % (name, timestamp)).encode('utf8')).hexdigest() return '%032x' % (int(old, 16) ^ int(new, 16)) def get_db_connection(path, timeout=30, okay_to_create=False): """ Returns a properly configured SQLite database connection. :param path: path to DB :param timeout: timeout for connection :param okay_to_create: if True, create the DB if it doesn't exist :returns: DB connection object """ try: connect_time = time.time() conn = sqlite3.connect(path, check_same_thread=False, factory=GreenDBConnection, timeout=timeout) if path != ':memory:' and not okay_to_create: # attempt to detect and fail when connect creates the db file stat = os.stat(path) if stat.st_size == 0 and stat.st_ctime >= connect_time: os.unlink(path) raise DatabaseConnectionError(path, 'DB file created by connect?') conn.row_factory = sqlite3.Row conn.text_factory = str with closing(conn.cursor()) as cur: cur.execute('PRAGMA synchronous = NORMAL') cur.execute('PRAGMA count_changes = OFF') cur.execute('PRAGMA temp_store = MEMORY') cur.execute('PRAGMA journal_mode = DELETE') conn.create_function('chexor', 3, chexor) except sqlite3.DatabaseError: import traceback raise DatabaseConnectionError(path, traceback.format_exc(), timeout=timeout) return conn def _is_deleted(self, conn): """ Check if the database is considered deleted :param conn: database conn :returns: True if the DB is considered to be deleted, False otherwise """ raise NotImplementedError() def is_deleted(self): """ Check if the DB is considered to be deleted. :returns: True if the DB is considered to be deleted, False otherwise """ if self.db_file != ':memory:' and not os.path.exists(self.db_file): return True self._commit_puts_stale_ok() with self.get() as conn: return self._is_deleted(conn) def merge_timestamps(self, created_at, put_timestamp, delete_timestamp): """ Used in replication to handle updating timestamps. :param created_at: create timestamp :param put_timestamp: put timestamp :param delete_timestamp: delete timestamp """ with self.get() as conn: old_status = self._is_deleted(conn) conn.execute(''' UPDATE %s_stat SET created_at=MIN(?, created_at), put_timestamp=MAX(?, put_timestamp), delete_timestamp=MAX(?, delete_timestamp) ''' % self.db_type, (created_at, put_timestamp, delete_timestamp)) if old_status != self._is_deleted(conn): timestamp = Timestamp(time.time()) self._update_status_changed_at(conn, timestamp.internal) conn.commit() def get_items_since(self, start, count): """ Get a list of objects in the database between start and end. :param start: start ROWID :param count: number to get :returns: list of objects between start and end """ self._commit_puts_stale_ok() with self.get() as conn: curs = conn.execute(''' SELECT * FROM %s WHERE ROWID > ? ORDER BY ROWID ASC LIMIT ? ''' % self.db_contains_type, (start, count)) curs.row_factory = dict_factory return [r for r in curs] def get_sync(self, id, incoming=True): """ Gets the most recent sync point for a server from the sync table. :param id: remote ID to get the sync_point for :param incoming: if True, get the last incoming sync, otherwise get the last outgoing sync :returns: the sync point, or -1 if the id doesn't exist. """ with self.get() as conn: row = conn.execute( "SELECT sync_point FROM %s_sync WHERE remote_id=?" % ('incoming' if incoming else 'outgoing'), (id,)).fetchone() if not row: return -1 return row['sync_point'] def get_syncs(self, incoming=True): """ Get a serialized copy of the sync table. :param incoming: if True, get the last incoming sync, otherwise get the last outgoing sync :returns: list of {'remote_id', 'sync_point'} """ with self.get() as conn: curs = conn.execute(''' SELECT remote_id, sync_point FROM %s_sync ''' % ('incoming' if incoming else 'outgoing')) result = [] for row in curs: result.append({'remote_id': row[0], 'sync_point': row[1]}) return result def get_replication_info(self): """ Get information about the DB required for replication. :returns: dict containing keys from get_info plus max_row and metadata Note:: get_info's <db_contains_type>_count is translated to just "count" and metadata is the raw string. """ info = self.get_info() info['count'] = info.pop('%s_count' % self.db_contains_type) info['metadata'] = self.get_raw_metadata() info['max_row'] = self.get_max_row() return info # def _commit_puts(self, item_list=None): """ Scan for .pending files and commit the found records by feeding them to merge_items(). Assume that lock_parent_directory has already been called. :param item_list: A list of items to commit in addition to .pending """ if self.db_file == ':memory:' or not os.path.exists(self.pending_file): return if item_list is None: item_list = [] self._preallocate() if not os.path.getsize(self.pending_file): if item_list: self.merge_items(item_list) return with open(self.pending_file, 'r+b') as fp: for entry in fp.read().split(':'): if entry: try: self._commit_puts_load(item_list, entry) except Exception: self.logger.exception( _('Invalid pending entry %(file)s: %(entry)s'), {'file': self.pending_file, 'entry': entry}) if item_list: self.merge_items(item_list) try: os.ftruncate(fp.fileno(), 0) except OSError as err: if err.errno != errno.ENOENT: raise def _commit_puts_stale_ok(self): """ Catch failures of _commit_puts() if broker is intended for reading of stats, and thus does not care for pending updates. """ if self.db_file == ':memory:' or not os.path.exists(self.pending_file): return try: with lock_parent_directory(self.pending_file, self.pending_timeout): self._commit_puts() except LockTimeout: if not self.stale_reads_ok: raise def _commit_puts_load(self, item_list, entry): """ Unmarshall the :param:entry and append it to :param:item_list. This is implemented by a particular broker to be compatible with its :func:`merge_items`. """ raise NotImplementedError def make_tuple_for_pickle(self, record): """ Turn this db record dict into the format this service uses for pending pickles. """ raise NotImplementedError def merge_syncs(self, sync_points, incoming=True): """ Merge a list of sync points with the incoming sync table. :param sync_points: list of sync points where a sync point is a dict of {'sync_point', 'remote_id'} :param incoming: if True, get the last incoming sync, otherwise get the last outgoing sync """ with self.get() as conn: for rec in sync_points: try: conn.execute(''' INSERT INTO %s_sync (sync_point, remote_id) VALUES (?, ?) ''' % ('incoming' if incoming else 'outgoing'), (rec['sync_point'], rec['remote_id'])) except sqlite3.IntegrityError: conn.execute(''' UPDATE %s_sync SET sync_point=max(?, sync_point) WHERE remote_id=? ''' % ('incoming' if incoming else 'outgoing'), (rec['sync_point'], rec['remote_id'])) conn.commit() def update_metadata(self, metadata_updates, validate_metadata=False): """ Updates the metadata dict for the database. The metadata dict values are tuples of (value, timestamp) where the timestamp indicates when that key was set to that value. Key/values will only be overwritten if the timestamp is newer. To delete a key, set its value to ('', timestamp). These empty keys will eventually be removed by :func:`reclaim` """ #old_metadata old_metadata = self.metadata # if set(metadata_updates).issubset(set(old_metadata)): # for key, (value, timestamp) in metadata_updates.items(): if timestamp > old_metadata[key][1]: break else: # return # with self.get() as conn: try: md = conn.execute('SELECT metadata FROM %s_stat' % self.db_type).fetchone()[0] md = json.loads(md) if md else {} utf8encodekeys(md) except sqlite3.OperationalError as err: if 'no such column: metadata' not in str(err): raise conn.execute(""" ALTER TABLE %s_stat ADD COLUMN metadata TEXT DEFAULT '' """ % self.db_type) md = {} # for key, value_timestamp in metadata_updates.items(): value, timestamp = value_timestamp if key not in md or timestamp > md[key][1]: md[key] = value_timestamp if validate_metadata: DatabaseBroker.validate_metadata(md) conn.execute('UPDATE %s_stat SET metadata = ?' % self.db_type, (json.dumps(md),)) conn.commit() def reclaim(self, age_timestamp, sync_timestamp): """ Delete rows from the db_contains_type table that are marked deleted and whose created_at timestamp is < age_timestamp. Also deletes rows from incoming_sync and outgoing_sync where the updated_at timestamp is < sync_timestamp. In addition, this calls the DatabaseBroker's :func:`_reclaim` method. :param age_timestamp: max created_at timestamp of object rows to delete :param sync_timestamp: max update_at timestamp of sync rows to delete """ if self.db_file != ':memory:' and os.path.exists(self.pending_file): with lock_parent_directory(self.pending_file, self.pending_timeout): self._commit_puts() with self.get() as conn: conn.execute(''' DELETE FROM %s WHERE deleted = 1 AND %s < ? ''' % (self.db_contains_type, self.db_reclaim_timestamp), (age_timestamp,)) try: conn.execute(''' DELETE FROM outgoing_sync WHERE updated_at < ? ''', (sync_timestamp,)) conn.execute(''' DELETE FROM incoming_sync WHERE updated_at < ? ''', (sync_timestamp,)) except sqlite3.OperationalError as err: # Old dbs didn't have updated_at in the _sync tables. if 'no such column: updated_at' not in str(err): raise DatabaseBroker._reclaim(self, conn, age_timestamp) conn.commit() def _reclaim(self, conn, timestamp): """ Removes any empty metadata values older than the timestamp using the given database connection. This function will not call commit on the conn, but will instead return True if the database needs committing. This function was created as a worker to limit transactions and commits from other related functions. :param conn: Database connection to reclaim metadata within. :param timestamp: Empty metadata items last updated before this timestamp will be removed. :returns: True if conn.commit() should be called """ try: md = conn.execute('SELECT metadata FROM %s_stat' % self.db_type).fetchone()[0] if md: md = json.loads(md) keys_to_delete = [] for key, (value, value_timestamp) in md.items(): if value == '' and value_timestamp < timestamp: keys_to_delete.append(key) if keys_to_delete: for key in keys_to_delete: del md[key] conn.execute('UPDATE %s_stat SET metadata = ?' % self.db_type, (json.dumps(md),)) return True except sqlite3.OperationalError as err: if 'no such column: metadata' not in str(err): raise return False def update_put_timestamp(self, timestamp): """ Update the put_timestamp. Only modifies it if it is greater than the current timestamp. :param timestamp: internalized put timestamp """ with self.get() as conn: conn.execute( 'UPDATE %s_stat SET put_timestamp = ?' ' WHERE put_timestamp < ?' % self.db_type, (timestamp, timestamp)) conn.commit() def update_status_changed_at(self, timestamp): """ Update the status_changed_at field in the stat table. Only modifies status_changed_at if the timestamp is greater than the current status_changed_at timestamp. :param timestamp: internalized timestamp """ with self.get() as conn: self._update_status_changed_at(conn, timestamp) conn.commit() def _update_status_changed_at(self, conn, timestamp): conn.execute( 'UPDATE %s_stat SET status_changed_at = ?' ' WHERE status_changed_at < ?' % self.db_type, (timestamp, timestamp))
[ 2, 15069, 357, 66, 8, 3050, 12, 6999, 4946, 25896, 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...
2.190524
8,020
"""Prop limits are used to validate the input given to xdl elements. For example, a volume property should be a positive number, optionally followed by volume units. The prop limit is used to check that input supplied is valid for that property. """ import re from typing import List, Optional ################## # Regex patterns # ################## #: Pattern to match a positive or negative float, #: e.g. '0', '-1', '1', '-10.3', '10.3', '0.0' would all be matched by this #: pattern. FLOAT_PATTERN: str = r'([-]?[0-9]+(?:[.][0-9]+)?)' #: Pattern to match a positive float, #: e.g. '0', 1', '10.3', '0.0' would all be matched by this pattern, but not #: '-10.3' or '-1'. POSITIVE_FLOAT_PATTERN: str = r'([0-9]+(?:[.][0-9]+)?)' #: Pattern to match boolean strings, specifically matching 'true' and 'false' #: case insensitvely. BOOL_PATTERN: str = r'(false|False|true|True)' #: Pattern to match all accepted volumes units case insensitvely, or empty string. VOLUME_UNITS_PATTERN: str = r'(l|L|litre|litres|liter|liters|ml|mL|cm3|cc|milliltre|millilitres|milliliter|milliliters|cl|cL|centiltre|centilitres|centiliter|centiliters|dl|dL|deciltre|decilitres|deciliter|deciliters|ul|uL|l|L|microlitre|microlitres|microliter|microliters)?' #: Pattern to match all accepted mass units, or empty string. MASS_UNITS_PATTERN: str = r'(g|gram|grams|kg|kilogram|kilograms|mg|milligram|milligrams|ug|g|microgram|micrograms)?' #: Pattern to match all accepted temperature units, or empty string. TEMP_UNITS_PATTERN: str = r'(C|K|F)?' #: Pattern to match all accepted time units, or empty string. TIME_UNITS_PATTERN = r'(days|day|h|hr|hrs|hour|hours|m|min|mins|minute|minutes|s|sec|secs|second|seconds)?' #: Pattern to match all accepted pressure units, or empty string. PRESSURE_UNITS_PATTERN = r'(mbar|bar|torr|Torr|mmhg|mmHg|atm|Pa|pa)?' #: Pattern to match all accepted rotation speed units, or empty string. ROTATION_SPEED_UNITS_PATTERN = r'(rpm|RPM)?' #: Pattern to match all accepted length units, or empty string. DISTANCE_UNITS_PATTERN = r'(nm|m|mm|cm|m|km)?' #: Pattern to match all accepted mol units, or empty string. MOL_UNITS_PATTERN = r'(mmol|mol)?' ############### # Prop limits # ############### def generate_quantity_units_pattern( quantity_pattern: str, units_pattern: str, hint: Optional[str] = '', default: Optional[str] = '' ) -> PropLimit: """ Convenience function to generate PropLimit object for different quantity types, i.e. for variations on the number followed by unit pattern. Args: quantity_pattern (str): Pattern to match the number expected. This will typically be ``POSITIVE_FLOAT_PATTERN`` or ``FLOAT_PATTERN``. units_pattern (str): Pattern to match the units expected or empty string. Empty string is matched as not including units is allowed as in this case standard units are used. hint (str): Hint for the prop limit to tell the user what correct input should look like in the case of an errror. default (str): Default value for the prop limit, should use standard units for the prop involved. """ return PropLimit( regex=r'^((' + quantity_pattern + r'[ ]?'\ + units_pattern + r'$)|(^' + quantity_pattern + r'))$', hint=hint, default=default ) # NOTE: It is important here that defaults use the standard unit for that # quantity type as XDL app uses this to add in default units. #: Prop limit for volume props. VOLUME_PROP_LIMIT: PropLimit = PropLimit( regex=r'^(all|(' + POSITIVE_FLOAT_PATTERN + r'[ ]?'\ + VOLUME_UNITS_PATTERN + r')|(' + POSITIVE_FLOAT_PATTERN + r'))$', hint='Expecting number followed by standard volume units, e.g. "5.5 mL"', default='0 mL', ) #: Prop limit for mass props. MASS_PROP_LIMIT: PropLimit = generate_quantity_units_pattern( POSITIVE_FLOAT_PATTERN, MASS_UNITS_PATTERN, hint='Expecting number followed by standard mass units, e.g. "2.3 g"', default='0 g' ) #: Prop limit for mol props. MOL_PROP_LIMIT: PropLimit = generate_quantity_units_pattern( POSITIVE_FLOAT_PATTERN, MOL_UNITS_PATTERN, hint='Expecting number followed by mol or mmol, e.g. "2.3 mol".', default='0 mol', ) #: Prop limit for temp props. TEMP_PROP_LIMIT: PropLimit = generate_quantity_units_pattern( FLOAT_PATTERN, TEMP_UNITS_PATTERN, hint='Expecting number in degrees celsius or number followed by standard temperature units, e.g. "25", "25C", "298 K".', default='25C', ) #: Prop limit for time props. TIME_PROP_LIMIT: PropLimit = generate_quantity_units_pattern( POSITIVE_FLOAT_PATTERN, TIME_UNITS_PATTERN, hint='Expecting number followed by standard time units, e.g. "15 mins", "3 hrs".', default='0 secs' ) #: Prop limit for pressure props. PRESSURE_PROP_LIMIT: PropLimit = generate_quantity_units_pattern( POSITIVE_FLOAT_PATTERN, PRESSURE_UNITS_PATTERN, hint='Expecting number followed by standard pressure units, e.g. "50 mbar", "1 atm".', default='1013.25 mbar' ) #: Prop limit for rotation speed props. ROTATION_SPEED_PROP_LIMIT: PropLimit = generate_quantity_units_pattern( POSITIVE_FLOAT_PATTERN, ROTATION_SPEED_UNITS_PATTERN, hint='Expecting RPM value, e.g. "400 RPM".', default='400 RPM', ) #: Prop limit for wavelength props. WAVELENGTH_PROP_LIMIT: PropLimit = generate_quantity_units_pattern( POSITIVE_FLOAT_PATTERN, DISTANCE_UNITS_PATTERN, hint='Expecting wavelength, e.g. "400 nm".', default='400 nm' ) #: Prop limit for any props requiring a positive integer such as ``repeats``. #: Used if no explicit property is given and prop type is ``int``. POSITIVE_INT_PROP_LIMIT: PropLimit = PropLimit( r'[0-9]+', hint='Expecting positive integer value, e.g. "3"', default='1', ) #: Prop limit for any props requiring a positive float. Used if no explicit #: prop type is given and prop type is ``float``. POSITIVE_FLOAT_PROP_LIMIT: PropLimit = PropLimit( regex=POSITIVE_FLOAT_PATTERN, hint='Expecting positive float value, e.g. "3", "3.5"', default='0', ) #: Prop limit for any props requiring a boolean value. Used if no explicit prop #: type is given and prop type is ``bool``. BOOL_PROP_LIMIT: PropLimit = PropLimit( BOOL_PATTERN, hint='Expecting one of "false" or "true".', default='false', ) #: Prop limit for ``WashSolid`` ``stir`` prop. This is a special case as the #: value can be ``True``, ``False`` or ``'solvent'``. WASH_SOLID_STIR_PROP_LIMIT: PropLimit = PropLimit( r'(' + BOOL_PATTERN + r'|solvent)', enum=['true', 'solvent', 'false'], hint='Expecting one of "true", "false" or "solvent".', default='True' ) #: Prop limit for ``Separate`` ``purpose`` prop. One of 'extract' or 'wash'. SEPARATION_PURPOSE_PROP_LIMIT: PropLimit = PropLimit(enum=['extract', 'wash']) #: Prop limit for ``Separate`` ``product_phase`` prop. One of 'top' or 'bottom'. SEPARATION_PRODUCT_PHASE_PROP_LIMIT: PropLimit = PropLimit(enum=['top', 'bottom']) #: Prop limit for ``Add`` ``purpose`` prop. One of 'neutralize', 'precipitate', #: 'dissolve', 'basify', 'acidify' or 'dilute'. ADD_PURPOSE_PROP_LIMIT = PropLimit( enum=[ 'neutralize', 'precipitate', 'dissolve', 'basify', 'acidify', 'dilute', ] ) #: Prop limit for ``HeatChill`` ``purpose`` prop. One of 'control-exotherm', #: 'reaction' or 'unstable-reagent'. HEATCHILL_PURPOSE_PROP_LIMIT = PropLimit( enum=['control-exotherm', 'reaction', 'unstable-reagent'] ) #: Prop limit for ``Stir`` ``purpose`` prop. 'dissolve' is only option. STIR_PURPOSE_PROP_LIMIT = PropLimit( enum=['dissolve'] ) #: Prop limit for ``Reagent`` ``role`` prop. One of 'solvent', 'reagent', #: 'catalyst', 'substrate', 'acid', 'base' or 'activating-agent'. REAGENT_ROLE_PROP_LIMIT = PropLimit( enum=[ 'solvent', 'reagent', 'catalyst', 'substrate', 'acid', 'base', 'activating-agent' ] ) #: Prop limit for ``Component`` ``component_type`` prop. One of 'reactor', #: 'filter', 'separator', 'rotavap' or 'flask'. COMPONENT_TYPE_PROP_LIMIT: PropLimit = PropLimit( enum=['reactor', 'filter', 'separator', 'rotavap', 'flask'] ) #: Pattern matching a float of value 100, e.g. '100', '100.0', '100.000' would #: all be matched. _hundred_float: str = r'(100(?:[.][0]+)?)' #: Pattern matching any float between 10.000 and 99.999. _ten_to_ninety_nine_float: str = r'([0-9][0-9](?:[.][0-9]+)?)' #: Pattern matching any float between 0 and 9.999. _zero_to_ten_float: str = r'([0-9](?:[.][0-9]+)?)' #: Pattern matching float between 0 and 100. Used for percentages. PERCENT_RANGE_PROP_LIMIT: PropLimit = PropLimit( r'^(' + _hundred_float + '|'\ + _ten_to_ninety_nine_float + '|' + _zero_to_ten_float + ')$', hint='Expecting number from 0-100 representing a percentage, e.g. "50", "8.5".', default='0', )
[ 37811, 24331, 7095, 389, 973, 284, 26571, 262, 5128, 1813, 284, 2124, 25404, 4847, 13, 1114, 198, 20688, 11, 257, 6115, 3119, 815, 307, 257, 3967, 1271, 11, 42976, 3940, 416, 198, 29048, 4991, 13, 383, 2632, 4179, 318, 973, 284, 2198,...
2.540395
3,540
""" Provides usable args and kwargs from inspect.getcallargs. For Python 3.3 and above, this module is unnecessary and can be achieved using features from PEP 362: http://www.python.org/dev/peps/pep-0362/ For example, to override a parameter of some function: >>> import inspect >>> def func(a, b=1, c=2, d=3): ... return a, b, c, d ... >>> def override_c(*args, **kwargs): ... sig = inspect.signature(override) ... ba = sig.bind(*args, **kwargs) ... ba['c'] = 10 ... return func(*ba.args, *ba.kwargs) ... >>> override_c(0, c=3) (0, 1, 10, 3) Also useful: http://www.python.org/dev/peps/pep-3102/ """ import sys import inspect from inspect import getcallargs try: from inspect import getfullargspec except ImportError: # Python 2.X from collections import namedtuple from inspect import getargspec FullArgSpec = namedtuple('FullArgSpec', 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations') def bindcallargs_leq32(_fUnCtIoN_, *args, **kwargs): """Binds arguments and keyword arguments to a function or method. Returns a tuple (bargs, bkwargs) suitable for manipulation and passing to the specified function. `bargs` consists of the bound args, varargs, and kwonlyargs from getfullargspec. `bkwargs` consists of the bound varkw from getfullargspec. Both can be used in a call to the specified function. Any default parameter values are included in the output. Examples -------- >>> def func(a, b=3, *args, **kwargs): ... pass >>> bindcallargs(func, 5) ((5, 3), {}) >>> bindcallargs(func, 5, 4, 3, 2, 1, hello='there') ((5, 4, 3, 2, 1), {'hello': 'there'}) >>> args, kwargs = bindcallargs(func, 5) >>> kwargs['b'] = 5 # overwrite default value for b >>> func(*args, **kwargs) """ # It is necessary to choose an unlikely variable name for the function. # The reason is that any kwarg by the same name will cause a TypeError # due to multiple values being passed for that argument name. func = _fUnCtIoN_ callargs = getcallargs(func, *args, **kwargs) spec = getfullargspec(func) # Construct all args and varargs and use them in bargs bargs = [callargs[arg] for arg in spec.args] if spec.varargs is not None: bargs.extend(callargs[spec.varargs]) bargs = tuple(bargs) # Start with kwonlyargs. bkwargs = {kwonlyarg: callargs[kwonlyarg] for kwonlyarg in spec.kwonlyargs} # Add in kwonlydefaults for unspecified kwonlyargs only. # Since keyword only arguements aren't allowed in python2, and we # don't support python 3.0, 3.1, 3.2, this should never be executed: if spec.kwonlydefaults is not None: # pragma: no cover bkwargs.update({k: v for k, v in spec.kwonlydefaults.items() if k not in bkwargs}) # Add in varkw. if spec.varkw is not None: bkwargs.update(callargs[spec.varkw]) return bargs, bkwargs if sys.version_info[0:2] < (3,3): bindcallargs = bindcallargs_leq32 else: bindcallargs = bindcallargs_geq33
[ 37811, 198, 15946, 1460, 24284, 26498, 290, 479, 86, 22046, 422, 10104, 13, 1136, 13345, 22046, 13, 198, 198, 1890, 11361, 513, 13, 18, 290, 2029, 11, 428, 8265, 318, 13114, 290, 460, 307, 8793, 1262, 198, 40890, 422, 350, 8905, 4570,...
2.609233
1,213
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import json import os import sys import time from marionette import MarionetteTestCase from marionette.by import By from marionette.errors import NoSuchElementException from marionette.errors import ElementNotVisibleException from marionette.errors import TimeoutException from marionette.errors import StaleElementException from marionette.errors import InvalidResponseException import mozdevice def remove_all_contacts(self, default_script_timeout=60000): self.marionette.switch_to_frame() self.marionette.set_script_timeout(max(default_script_timeout, 1000 * len(self.all_contacts))) result = self.marionette.execute_async_script('return GaiaDataLayer.removeAllContacts();', special_powers=True) assert result, 'Unable to remove all contacts' self.marionette.set_script_timeout(default_script_timeout) def get_setting(self, name): return self.marionette.execute_async_script('return GaiaDataLayer.getSetting("%s")' % name, special_powers=True) def get_bool_pref(self, name): """Returns the value of a Gecko boolean pref, which is different from a Gaia setting.""" return self._get_pref('Bool', name) def set_bool_pref(self, name, value): """Sets the value of a Gecko boolean pref, which is different from a Gaia setting.""" return self._set_pref('Bool', name, value) def get_int_pref(self, name): """Returns the value of a Gecko integer pref, which is different from a Gaia setting.""" return self._get_pref('Int', name) def set_int_pref(self, name, value): """Sets the value of a Gecko integer pref, which is different from a Gaia setting.""" return self._set_pref('Int', name, value) def get_char_pref(self, name): """Returns the value of a Gecko string pref, which is different from a Gaia setting.""" return self._get_pref('Char', name) def set_char_pref(self, name, value): """Sets the value of a Gecko string pref, which is different from a Gaia setting.""" return self._set_pref('Char', name, value) def connect_to_cell_data(self): self.marionette.switch_to_frame() result = self.marionette.execute_async_script("return GaiaDataLayer.connectToCellData()", special_powers=True) assert result, 'Unable to connect to cell data' def disable_cell_data(self): self.marionette.switch_to_frame() result = self.marionette.execute_async_script("return GaiaDataLayer.disableCellData()", special_powers=True) assert result, 'Unable to disable cell data' def delete_all_sms(self): self.marionette.switch_to_frame() return self.marionette.execute_async_script("return GaiaDataLayer.deleteAllSms();", special_powers=True) def delete_all_call_log_entries(self): """The call log needs to be open and focused in order for this to work.""" self.marionette.execute_script('window.wrappedJSObject.RecentsDBManager.deleteAll();') def kill_active_call(self): self.marionette.execute_script("var telephony = window.navigator.mozTelephony; " + "if(telephony.active) telephony.active.hangUp();") def sdcard_files(self, extension=''): files = self.marionette.execute_async_script( 'return GaiaDataLayer.getAllSDCardFiles();') if len(extension): return [filename for filename in files if filename.endswith(extension)] return files def send_sms(self, number, message): import json number = json.dumps(number) message = json.dumps(message) result = self.marionette.execute_async_script('return GaiaDataLayer.sendSMS(%s, %s)' % (number, message), special_powers=True) assert result, 'Unable to send SMS to recipient %s with text %s' % (number, message) class GaiaDevice(object): def push_file(self, source, count=1, destination='', progress=None): if not destination.count('.') > 0: destination = '/'.join([destination, source.rpartition(os.path.sep)[-1]]) self.manager.mkDirs(destination) self.manager.pushFile(source, destination) if count > 1: for i in range(1, count + 1): remote_copy = '_%s.'.join(iter(destination.split('.'))) % i self.manager._checkCmd(['shell', 'dd', 'if=%s' % destination, 'of=%s' % remote_copy]) if progress: progress.update(i) self.manager.removeFile(destination) class GaiaTestCase(MarionetteTestCase): _script_timeout = 60000 _search_timeout = 10000 # deafult timeout in seconds for the wait_for methods _default_timeout = 30 def change_orientation(self, orientation): """ There are 4 orientation states which the phone can be passed in: portrait-primary(which is the default orientation), landscape-primary, portrait-secondary and landscape-secondary """ self.marionette.execute_async_script(""" if (arguments[0] === arguments[1]) { marionetteScriptFinished(); } else { var expected = arguments[1]; window.screen.onmozorientationchange = function(e) { console.log("Received 'onmozorientationchange' event."); waitFor( function() { window.screen.onmozorientationchange = null; marionetteScriptFinished(); }, function() { return window.screen.mozOrientation === expected; } ); }; console.log("Changing orientation to '" + arguments[1] + "'."); window.screen.mozLockOrientation(arguments[1]); };""", script_args=[self.screen_orientation, orientation]) def wait_for_element_present(self, by, locator, timeout=_default_timeout): timeout = float(timeout) + time.time() while time.time() < timeout: time.sleep(0.5) try: return self.marionette.find_element(by, locator) except NoSuchElementException: pass else: raise TimeoutException( 'Element %s not present before timeout' % locator) def wait_for_element_not_present(self, by, locator, timeout=_default_timeout): timeout = float(timeout) + time.time() while time.time() < timeout: time.sleep(0.5) try: self.marionette.find_element(by, locator) except NoSuchElementException: break else: raise TimeoutException( 'Element %s still present after timeout' % locator) def wait_for_element_displayed(self, by, locator, timeout=_default_timeout): timeout = float(timeout) + time.time() e = None while time.time() < timeout: time.sleep(0.5) try: if self.marionette.find_element(by, locator).is_displayed(): break except (NoSuchElementException, StaleElementException) as e: pass else: # This is an effortless way to give extra debugging information if isinstance(e, NoSuchElementException): raise TimeoutException('Element %s not present before timeout' % locator) else: raise TimeoutException('Element %s present but not displayed before timeout' % locator) def wait_for_element_not_displayed(self, by, locator, timeout=_default_timeout): timeout = float(timeout) + time.time() while time.time() < timeout: time.sleep(0.5) try: if not self.marionette.find_element(by, locator).is_displayed(): break except StaleElementException: pass except NoSuchElementException: break else: raise TimeoutException( 'Element %s still visible after timeout' % locator) def wait_for_condition(self, method, timeout=_default_timeout, message="Condition timed out"): """Calls the method provided with the driver as an argument until the \ return value is not False.""" end_time = time.time() + timeout while time.time() < end_time: try: value = method(self.marionette) if value: return value except (NoSuchElementException, StaleElementException): pass time.sleep(0.5) else: raise TimeoutException(message) def is_element_present(self, by, locator): try: self.marionette.find_element(by, locator) return True except: return False def is_element_displayed(self, by, locator): try: return self.marionette.find_element(by, locator).is_displayed() except (NoSuchElementException, ElementNotVisibleException): return False
[ 2, 770, 8090, 6127, 5178, 318, 2426, 284, 262, 2846, 286, 262, 29258, 5094, 198, 2, 13789, 11, 410, 13, 362, 13, 15, 13, 1002, 257, 4866, 286, 262, 4904, 43, 373, 407, 9387, 351, 428, 198, 2, 2393, 11, 921, 460, 7330, 530, 379, ...
2.357465
3,992
# This is what is in GWT 1.5 for getAbsoluteLeft. err... #""" # // We cannot use DOMImpl here because offsetLeft/Top return erroneous # // values when overflow is not visible. We have to difference screenX # // here due to a change in getBoxObjectFor which causes inconsistencies # // on whether the calculations are inside or outside of the element's # // border. # try { # return $doc.getBoxObjectFor(elem).screenX # - $doc.getBoxObjectFor($doc.documentElement).screenX; # } catch (e) { # // This works around a bug in the FF3 betas. The bug # // should be fixed before they release, so this can # // be removed at a later date. # // https://bugzilla.mozilla.org/show_bug.cgi?id=409111 # // DOMException.WRONG_DOCUMENT_ERR == 4 # if (e.code == 4) { # return 0; # } # throw e; # } #""" # This is what is in GWT 1.5 for getAbsoluteTop. err... #""" # // We cannot use DOMImpl here because offsetLeft/Top return erroneous # // values when overflow is not visible. We have to difference screenY # // here due to a change in getBoxObjectFor which causes inconsistencies # // on whether the calculations are inside or outside of the element's # // border. # try { # return $doc.getBoxObjectFor(elem).screenY # - $doc.getBoxObjectFor($doc.documentElement).screenY; # } catch (e) { # // This works around a bug in the FF3 betas. The bug # // should be fixed before they release, so this can # // be removed at a later date. # // https://bugzilla.mozilla.org/show_bug.cgi?id=409111 # // DOMException.WRONG_DOCUMENT_ERR == 4 # if (e.code == 4) { # return 0; # } # throw e; # } #"""
[ 198, 2, 770, 318, 644, 318, 287, 27164, 51, 352, 13, 20, 329, 651, 24849, 3552, 18819, 13, 220, 11454, 986, 198, 2, 37811, 198, 2, 220, 220, 220, 3373, 775, 2314, 779, 24121, 29710, 994, 780, 11677, 18819, 14, 9126, 1441, 35366, 1...
2.603269
673
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-06-10 21:25 from __future__ import unicode_literals from django.db import migrations, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 24, 13, 21, 319, 1584, 12, 3312, 12, 940, 2310, 25, 1495, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 19...
2.719298
57
from depth_first_search import DFS
[ 6738, 6795, 62, 11085, 62, 12947, 1330, 360, 10652, 628 ]
3.6
10
import pymongo from conf import Configuracoes
[ 11748, 279, 4948, 25162, 198, 6738, 1013, 1330, 17056, 333, 330, 3028, 198 ]
3.538462
13
import machine import pycom import utime from exceptions import Exceptions
[ 11748, 4572, 201, 198, 11748, 12972, 785, 201, 198, 11748, 3384, 524, 201, 198, 201, 198, 6738, 13269, 1330, 1475, 11755, 201, 198 ]
3.521739
23
import torch import argparse from collections import defaultdict import os import json if __name__ == '__main__': main()
[ 198, 11748, 28034, 198, 11748, 1822, 29572, 198, 6738, 17268, 1330, 4277, 11600, 198, 11748, 28686, 198, 11748, 33918, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 197, 12417, 3419, 198 ]
3.432432
37
casa = int(input('Qual o valor da casa? ')) sal = int(input('Qual seu salario? ')) prazo = int(input('Quantos meses deseja pagar ? ')) parcela = casa/prazo margem = sal* (30/100) if parcela > margem: print('Este negocio no foi aprovado, aumente o prazo .') else: print("Negocio aprovado pois a parcela de R$ {} e voce pode pagar R$ {} mensais".format(parcela,margem))
[ 66, 15462, 796, 493, 7, 15414, 10786, 46181, 267, 1188, 273, 12379, 6124, 64, 30, 705, 4008, 201, 198, 21680, 796, 493, 7, 15414, 10786, 46181, 384, 84, 3664, 4982, 30, 705, 4008, 201, 198, 79, 3247, 78, 796, 493, 7, 15414, 10786, ...
2.270588
170
# Generated by Django 3.1.7 on 2021-03-27 18:22 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 22, 319, 33448, 12, 3070, 12, 1983, 1248, 25, 1828, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
# -*- coding: utf-8 -*- """ Created on Wed Jul 22 14:36:48 2020 @author: matth """ import autograd.numpy as np #%% Kernel operations # Returns the norm of the pairwise difference # Returns the pairwise inner product if __name__ == '__main__': print('This is the matrix operations file')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 3300, 5979, 2534, 1478, 25, 2623, 25, 2780, 12131, 198, 198, 31, 9800, 25, 2603, 400, 198, 37811, 198, 198, 11748, 1960, 519, 6335, 13, 77, 321...
3.051546
97
import json from wptserve.utils import isomorphic_decode
[ 11748, 33918, 198, 198, 6738, 266, 457, 2655, 303, 13, 26791, 1330, 318, 46374, 62, 12501, 1098, 198 ]
3.222222
18
#!/usr/bin/env python3 from pythonosc import osc_bundle_builder from pythonosc import osc_message_builder from pythonosc import udp_client from .device import DeviceObj # OSC Grid Object
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 6738, 21015, 17500, 1330, 267, 1416, 62, 65, 31249, 62, 38272, 198, 6738, 21015, 17500, 1330, 267, 1416, 62, 20500, 62, 38272, 198, 6738, 21015, 17500, 1330, 334, 26059, 62, 1...
3.275862
58
from .app import db
[ 6738, 764, 1324, 1330, 20613, 628 ]
3.5
6
from iron_cache import * import unittest import requests if __name__ == '__main__': unittest.main()
[ 6738, 6953, 62, 23870, 1330, 1635, 198, 11748, 555, 715, 395, 198, 11748, 7007, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 198 ]
2.837838
37
#!/usr/bin/env python # -*- coding: utf-8 -*- # __BEGIN_LICENSE__ # Copyright (c) 2009-2013, United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The NGT platform is 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. # __END_LICENSE__ """ Basic functions for working with images on disk. """ import sys, os, re, subprocess, string, time, errno import asp_string_utils def stripRgbImageAlphaChannel(inputPath, outputPath): """Makes an RGB copy of an RBGA image""" cmd = 'gdal_translate ' + inputPath + ' ' + outputPath + ' -b 1 -b 2 -b 3 -co "COMPRESS=LZW" -co "TILED=YES" -co "BLOCKXSIZE=256" -co "BLOCKYSIZE=256"' print cmd os.system(cmd) def getImageSize(imagePath): """Returns the size [samples, lines] in an image""" # Make sure the input file exists if not os.path.exists(imagePath): raise Exception('Image file ' + imagePath + ' not found!') # Use subprocess to suppress the command output cmd = ['gdalinfo', imagePath] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) textOutput, err = p.communicate() # Extract the size from the text sizePos = textOutput.find('Size is') endPos = textOutput.find('\n', sizePos+7) sizeStr = textOutput[sizePos+7:endPos] sizeStrs = sizeStr.strip().split(',') numSamples = int(sizeStrs[0]) numLines = int(sizeStrs[1]) size = [numSamples, numLines] return size def isIsisFile(filePath): """Returns True if the file is an ISIS file, False otherwise.""" # Currently we treat all files with .cub extension as ISIS files extension = os.path.splitext(filePath)[1] return (extension == '.cub') def getImageStats(imagePath): """Obtains some image statistics from gdalinfo""" if not os.path.exists(imagePath): raise Exception('Image file ' + imagePath + ' not found!') # Call command line tool silently cmd = ['gdalinfo', imagePath, '-stats'] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) textOutput, err = p.communicate() # Statistics are computed seperately for each band bandStats = [] band = 0 while (True): # Loop until we run out of bands # Look for the stats line for this band bandString = 'Band ' + str(band+1) + ' Block=' bandLoc = textOutput.find(bandString) if bandLoc < 0: return bandStats # Quit if we did not find it # Now parse out the statistics for this band bandMaxStart = textOutput.find('STATISTICS_MAXIMUM=', bandLoc) bandMeanStart = textOutput.find('STATISTICS_MEAN=', bandLoc) bandMinStart = textOutput.find('STATISTICS_MINIMUM=', bandLoc) bandStdStart = textOutput.find('STATISTICS_STDDEV=', bandLoc) bandMax = asp_string_utils.getNumberAfterEqualSign(textOutput, bandMaxStart) bandMean = asp_string_utils.getNumberAfterEqualSign(textOutput, bandMeanStart) bandMin = asp_string_utils.getNumberAfterEqualSign(textOutput, bandMinStart) bandStd = asp_string_utils.getNumberAfterEqualSign(textOutput, bandStdStart) # Add results to the output list bandStats.append( (bandMin, bandMax, bandMean, bandStd) ) band = band + 1 # Move to the next band
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 11593, 33, 43312, 62, 43, 2149, 24290, 834, 198, 2, 220, 15069, 357, 66, 8, 3717, 12, 6390, 11, 1578, 1829, 5070...
2.666213
1,468
#!/usr/bin/env python import argparse DELIMITER = "\t" if __name__ == '__main__': parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('genotypes') parser.add_argument('GQ') parser.add_argument('fout') args = parser.parse_args() merge(args.genotypes, args.GQ, args.fout)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 1822, 29572, 628, 198, 35, 3698, 3955, 2043, 1137, 796, 37082, 83, 1, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 30751, ...
2.477987
159
from .api.server import run_app
[ 6738, 764, 15042, 13, 15388, 1330, 1057, 62, 1324, 198 ]
3.2
10
import tweepy import traceback import time import pymongo from tweepy import OAuthHandler from pymongo import MongoClient from pymongo.cursor import CursorType twitter_consumer_key = "" twitter_consumer_secret = "" twitter_access_token = "" twitter_access_secret = "" auth = OAuthHandler(twitter_consumer_key, twitter_consumer_secret) auth.set_access_token(twitter_access_token, twitter_access_secret) api = tweepy.API(auth) conn_str = "" my_client = pymongo.MongoClient(conn_str) if __name__ == '__main__': while True: print("cycles start") mydb = my_client['TwoRolless'] mycol = mydb['sns'] mycol.remove({}) crawllTwit("@m_thelastman", "") crawllTwit("@Musical_NarGold", "_") crawllTwit("@rndworks", "") crawllTwit("@ninestory9", "") crawllTwit("@companyrang", "") crawllTwit("@companyrang", "") crawllTwit("@page1company", "") crawllTwit("@HONGcompany", "") crawllTwit("@orchardmusical", "") crawllTwit("@livecorp2011", "") crawllTwit("@shownote", "") crawllTwit("@od_musical", "") crawllTwit("@kontentz", "") crawllTwit("@i_seensee", "") crawllTwit("@doublek_ent", "") crawllTwit("@Insight_Since96", "") print("cycle end") print("sleep 30 seconds") time.sleep(30) print("sleep end")
[ 11748, 4184, 538, 88, 198, 11748, 12854, 1891, 198, 11748, 640, 198, 11748, 279, 4948, 25162, 198, 6738, 4184, 538, 88, 1330, 440, 30515, 25060, 198, 6738, 279, 4948, 25162, 1330, 42591, 11792, 198, 6738, 279, 4948, 25162, 13, 66, 21471...
2.235105
621
#!/usr/bin/env python """Handles Earth Engine service account configuration.""" import ee # The service account email address authorized by your Google contact. # Set up a service account as described in the README. EE_ACCOUNT = 'your-service-account-id@developer.gserviceaccount.com' # The private key associated with your service account in Privacy Enhanced # Email format (.pem suffix). To convert a private key from the RSA format # (.p12 suffix) to .pem, run the openssl command like this: # openssl pkcs12 -in downloaded-privatekey.p12 -nodes -nocerts > privatekey.pem EE_PRIVATE_KEY_FILE = 'privatekey.pem' EE_CREDENTIALS = ee.ServiceAccountCredentials(EE_ACCOUNT, EE_PRIVATE_KEY_FILE)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 12885, 829, 3668, 7117, 2139, 1848, 8398, 526, 15931, 198, 198, 11748, 304, 68, 198, 198, 2, 383, 2139, 1848, 3053, 2209, 10435, 416, 534, 3012, 2800, 13, 198, 2, 5345, 510, 2...
3.276995
213
""" Demonstration of numbers in Python """ # Python has an integer type called int print("int") print("---") print(0) print(1) print(-3) print(70383028364830) print("") # Python has a real number type called float print("float") print("-----") print(0.0) print(7.35) print(-43.2) print("") # Limited precision print("Precision") print("---------") print(4.56372883832331773) print(1.23456789012345678) print("") # Scientific/exponential notation print("Scientific notation") print("-------------------") print(5e32) print(999999999999999999999999999999999999999.9) print("") # Infinity print("Infinity") print("--------") print(1e500) print(-1e500) print("") # Conversions print("Conversions between numeric types") print("---------------------------------") print(float(3)) print(float(99999999999999999999999999999999999999)) print(int(3.0)) print(int(3.7)) print(int(-3.7)) """ Demonstration of simple arithmetic expressions in Python """ # Unary + and - print("Unary operators") print(+3) print(-5) print(+7.86) print(-3348.63) print("") # Simple arithmetic print("Addition and Subtraction") print(1 + 2) print(48 - 89) print(3.45 + 2.7) print(87.3384 - 12.35) print(3 + 6.7) print(9.8 - 4) print("") print("Multiplication") print(3 * 2) print(7.8 * 27.54) print(7 * 8.2) print("") print("Division") print(8 / 2) print(3 / 2) print(7.538 / 14.3) print(8 // 2) print(3 // 2) print(7.538 // 14.3) print("") print("Exponentiation") print(3 ** 2) print(5 ** 4) print(32.6 ** 7) print(9 ** 0.5) """ Demonstration of compound arithmetic expressions in Python """ # Expressions can include multiple operations print("Compound expressions") print(3 + 5 + 7 + 27) #Operator with same precedence are evaluated from left to right print(18 - 6 + 4) print("") # Operator precedence defines how expressions are evaluated print("Operator precedence") print(7 + 3 * 5) print(5.5 * 6 // 2 + 8) print(-3 ** 2) print("") # Use parentheses to change evaluation order print("Grouping with parentheses") print((7 + 3) * 5) print(5.5 * ((6 // 2) + 8)) print((-3) ** 2) """ Demonstration of the use of variables and how to assign values to them. """ # The = operator can be used to assign values to variables bakers_dozen = 12 + 1 temperature = 93 # Variables can be used as values and in expressions print(temperature, bakers_dozen) print("celsius:", (temperature - 32) * 5 / 9) print("fahrenheit:", float(temperature)) # You can assign a different value to an existing variable temperature = 26 print("new value:", temperature) # Multiple variables can be used in arbitrary expressions offset = 32 multiplier = 5.0 / 9.0 celsius = (temperature - offset) * multiplier print("celsius value:", celsius)
[ 37811, 198, 35477, 12401, 286, 3146, 287, 11361, 198, 37811, 198, 198, 2, 11361, 468, 281, 18253, 2099, 1444, 493, 198, 4798, 7203, 600, 4943, 198, 4798, 7203, 6329, 4943, 198, 4798, 7, 15, 8, 198, 4798, 7, 16, 8, 198, 4798, 32590, ...
2.883227
942
from source.solving_strategies.strategies.solver import Solver
[ 6738, 2723, 13, 82, 10890, 62, 2536, 2397, 444, 13, 2536, 2397, 444, 13, 82, 14375, 1330, 4294, 332, 628 ]
3.2
20
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-24 16:22 from __future__ import unicode_literals import datetime from django.db import migrations, models from django.utils.timezone import utc
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 22, 319, 2177, 12, 1157, 12, 1731, 1467, 25, 1828, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.876712
73
"""Implementation of Rule L024.""" from sqlfluff.core.rules.doc_decorators import document_fix_compatible from sqlfluff.rules.L023 import Rule_L023
[ 37811, 3546, 32851, 286, 14330, 406, 40839, 526, 15931, 628, 198, 6738, 19862, 1652, 75, 1648, 13, 7295, 13, 38785, 13, 15390, 62, 12501, 273, 2024, 1330, 3188, 62, 13049, 62, 38532, 198, 6738, 19862, 1652, 75, 1648, 13, 38785, 13, 43...
3.081633
49
""" Plot CMDs for each component. """ import numpy as np from astropy.table import Table import matplotlib.pyplot as plt import matplotlib.cm as cm plt.ion() # Pretty plots from fig_settings import * ############################################ # Some things are the same for all the plotting scripts and we put # this into a single library to avoid confusion. import scocenlib as lib data_filename = lib.data_filename comps_filename = lib.comps_filename compnames = lib.compnames colors = lib.colors ############################################ # Minimal probability required for membership pmin_membership = 0.5 ############################################ # how to split subplots grid = [5, 5] # CMD limits xlim = [-1, 5] ylim = [17, -3] ############################################ # Read data try: tab = tab0 comps = comps0 except: tab0 = Table.read(data_filename) Gmag = tab0['phot_g_mean_mag'] - 5 * np.log10(1.0 / (tab0['parallax'] * 1e-3) / 10) # tab['parallax'] in micro arcsec tab0['Gmag'] = Gmag comps0 = Table.read(comps_filename) tab = tab0 comps = comps0 # Main sequence parametrization # fitpar for pmag, rpmag fitpar = [0.17954163, -2.48748376, 12.9279348, -31.35434182, 38.31330583, -12.25864507] poly = np.poly1d(fitpar) x = np.linspace(1, 4, 100) y = poly(x) m = y > 4 yms = y[m] xms = x[m] print('Plotting %d components.'%len(comps)) fig=plt.figure() for i, c in enumerate(comps): ax = fig.add_subplot(grid[0], grid[1], i+1) # TODO: adjust this if needed comp_ID = c['comp_ID'] col=tab['membership%s'%comp_ID] mask = col > pmin_membership t=tab[mask] if len(t)>100: alpha=0.5 else: alpha=1 t.sort('membership%s'%comp_ID) #~ t.reverse() #~ ax.scatter(t['bp_rp'], t['Gmag'], s=1, c='k', alpha=alpha) ax.scatter(t['bp_rp'], t['Gmag'], s=1, c=t['membership%s'%comp_ID], alpha=1, vmin=0.5, vmax=1, cmap=cm.jet) ax=plot_MS_parametrisation_and_spectral_types(ax, xlim, ylim) age=c['Age'] ax.set_title('%s (%.2f$\pm$%.2f Myr %s) %d'%(comp_ID, age, c['Crossing_time'], c['Age_reliable'], len(t))) #~ plt.tight_layout() plt.show()
[ 37811, 198, 43328, 327, 12740, 82, 329, 1123, 7515, 13, 198, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 6468, 28338, 13, 11487, 1330, 8655, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 2603, ...
2.370811
925
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2012-2018 Snowflake Computing Inc. All right reserved. # import pytest from snowflake.connector.errors import (ProgrammingError) def test_binding_security(conn_cnx, db_parameters): """ SQL Injection Tests """ try: with conn_cnx() as cnx: cnx.cursor().execute( "CREATE OR REPLACE TABLE {name} " "(aa INT, bb STRING)".format( name=db_parameters['name'])) cnx.cursor().execute( "INSERT INTO {name} VALUES(%s, %s)".format( name=db_parameters['name']), (1, 'test1')) cnx.cursor().execute( "INSERT INTO {name} VALUES(%(aa)s, %(bb)s)".format( name=db_parameters['name']), {'aa': 2, 'bb': 'test2'}) for rec in cnx.cursor().execute( "SELECT * FROM {name} ORDER BY 1 DESC".format( name=db_parameters['name'])): break assert rec[0] == 2, 'First column' assert rec[1] == 'test2', 'Second column' for rec in cnx.cursor().execute( "SELECT * FROM {name} WHERE aa=%s".format( name=db_parameters['name']), (1,)): break assert rec[0] == 1, 'First column' assert rec[1] == 'test1', 'Second column' # SQL injection safe test # Good Example with pytest.raises(ProgrammingError): cnx.cursor().execute( "SELECT * FROM {name} WHERE aa=%s".format( name=db_parameters['name']), ("1 or aa>0",)) with pytest.raises(ProgrammingError): cnx.cursor().execute( "SELECT * FROM {name} WHERE aa=%(aa)s".format( name=db_parameters['name']), {"aa": "1 or aa>0"}) # Bad Example in application. DON'T DO THIS c = cnx.cursor() c.execute("SELECT * FROM {name} WHERE aa=%s".format( name=db_parameters['name']) % ("1 or aa>0",)) rec = c.fetchall() assert len(rec) == 2, "not raising error unlike the previous one." finally: with conn_cnx() as cnx: cnx.cursor().execute( "drop table if exists {name}".format( name=db_parameters['name'])) def test_binding_list(conn_cnx, db_parameters): """ SQL binding list type for IN """ try: with conn_cnx() as cnx: cnx.cursor().execute( "CREATE OR REPLACE TABLE {name} " "(aa INT, bb STRING)".format( name=db_parameters['name'])) cnx.cursor().execute( "INSERT INTO {name} VALUES(%s, %s)".format( name=db_parameters['name']), (1, 'test1')) cnx.cursor().execute( "INSERT INTO {name} VALUES(%(aa)s, %(bb)s)".format( name=db_parameters['name']), {'aa': 2, 'bb': 'test2'}) cnx.cursor().execute( "INSERT INTO {name} VALUES(3, 'test3')".format( name=db_parameters['name'])) for rec in cnx.cursor().execute(""" SELECT * FROM {name} WHERE aa IN (%s) ORDER BY 1 DESC """.format(name=db_parameters['name']), ([1, 3],)): break assert rec[0] == 3, 'First column' assert rec[1] == 'test3', 'Second column' for rec in cnx.cursor().execute( "SELECT * FROM {name} WHERE aa=%s".format( name=db_parameters['name']), (1,)): break assert rec[0] == 1, 'First column' assert rec[1] == 'test1', 'Second column' rec = cnx.cursor().execute(""" SELECT * FROM {name} WHERE aa IN (%s) ORDER BY 1 DESC """.format(name=db_parameters['name']), ((1,),)) finally: with conn_cnx() as cnx: cnx.cursor().execute( "drop table if exists {name}".format( name=db_parameters['name'])) def test_unsupported_binding(conn_cnx, db_parameters): """ Unsupported data binding """ try: with conn_cnx() as cnx: cnx.cursor().execute( "CREATE OR REPLACE TABLE {name} " "(aa INT, bb STRING)".format( name=db_parameters['name'])) cnx.cursor().execute( "INSERT INTO {name} VALUES(%s, %s)".format( name=db_parameters['name']), (1, 'test1')) sql = 'select count(*) from {name} where aa=%s'.format( name=db_parameters['name']) with cnx.cursor() as cur: rec = cur.execute(sql, (1,)).fetchone() assert rec[0] is not None, 'no value is returned' # dict with pytest.raises(ProgrammingError): cnx.cursor().execute(sql, ({'value': 1},)) finally: with conn_cnx() as cnx: cnx.cursor().execute( "drop table if exists {name}".format( name=db_parameters['name']))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 357, 66, 8, 2321, 12, 7908, 7967, 47597, 38589, 3457, 13, 1439, 826, 10395, 13, 198, 2, 198, 198,...
1.814651
2,935
# Natural Language Toolkit: Language Models # # Copyright (C) 2001-2008 University of Pennsylvania # Author: Steven Bird <sb@csse.unimelb.edu.au> # URL: <http://nltk.sf.net> # For license information, see LICENSE.TXT
[ 2, 12068, 15417, 16984, 15813, 25, 15417, 32329, 198, 2, 198, 2, 15069, 357, 34, 8, 5878, 12, 11528, 2059, 286, 9589, 198, 2, 6434, 25, 8239, 14506, 1279, 36299, 31, 6359, 325, 13, 403, 320, 417, 65, 13, 15532, 13, 559, 29, 198, ...
3.070423
71
import os from graphene_sqlalchemy import SQLAlchemyObjectType from sqlalchemy import Column, Integer, String, create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base POSTGRES_CONNECTION_STRING = ( os.environ.get("POSTGRES_CONNECTION_STRING") or "postgres://postgres:password@localhost:6432/postgres" ) engine = create_engine(POSTGRES_CONNECTION_STRING, convert_unicode=True) db_session = scoped_session( sessionmaker(autocommit=False, autoflush=False, bind=engine) ) Base = declarative_base() Base.query = db_session.query_property()
[ 11748, 28686, 198, 6738, 42463, 62, 25410, 282, 26599, 1330, 16363, 2348, 26599, 10267, 6030, 198, 6738, 44161, 282, 26599, 1330, 29201, 11, 34142, 11, 10903, 11, 2251, 62, 18392, 198, 6738, 44161, 282, 26599, 13, 579, 1330, 629, 19458, ...
2.966667
210
# microsig """ Author: Maximilliano Rossi More detail about the MicroSIG can be found at: Website: https://gitlab.com/defocustracking/microsig-python Publication: Rossi M, Synthetic image generator for defocusing and astigmatic PIV/PTV, Meas. Sci. Technol., 31, 017003 (2020) DOI:10.1088/1361-6501/ab42bb. """ import numpy as np import imageio import tkinter as tk import os from os import listdir from os.path import isfile, basename, join, isdir import sys import glob # import time as tm from tkinter import filedialog # ----- code adapted by Sean MacKenzie ------ # 2.0 define class # %% # %% # %% # %% # %% # %% if __name__ == '__main__': run()
[ 2, 4580, 82, 328, 198, 198, 37811, 198, 13838, 25, 38962, 359, 10115, 40696, 198, 5167, 3703, 546, 262, 4527, 50, 3528, 460, 307, 1043, 379, 25, 198, 33420, 25, 198, 220, 220, 220, 3740, 1378, 18300, 23912, 13, 785, 14, 4299, 420, ...
2.763052
249
# Copyright 2020 Tier IV, 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. # !/usr/bin/env python # -*- coding: utf-8 -*- # TODO(kosuke murakami): write ros2 visualizer # import rospy # from autoware_planning_msgs.msg import Trajectory # from autoware_planning_msgs.msg import TrajectoryPoint # import matplotlib.pyplot as plt # import numpy as np # import tf # from geometry_msgs.msg import Vector3 # def quaternion_to_euler(quaternion): # """Convert Quaternion to Euler Angles # quaternion: geometry_msgs/Quaternion # euler: geometry_msgs/Vector3 # """ # e = tf.transformations.euler_from_quaternion( # (quaternion.x, quaternion.y, quaternion.z, quaternion.w)) # return Vector3(x=e[0], y=e[1], z=e[2]) # class TrajectoryVisualizer(): # def __init__(self): # self.in_trajectory = Trajectory() # self.debug_trajectory = Trajectory() # self.debug_fixed_trajectory = Trajectory() # self.plot_done1 = True # self.plot_done2 = True # self.plot_done3 = True # self.length = 50 # self.substatus1 = rospy.Subscriber( # "/planning/scenario_planning/lane_driving/motion_planning/obstacle_avoidance_planner/trajectory", # Trajectory, self.CallBackTraj, queue_size=1, tcp_nodelay=True) # rospy.Timer(rospy.Duration(0.3), self.timerCallback) # def CallBackTraj(self, cmd): # if (self.plot_done1): # self.in_trajectory = cmd # self.plot_done1 = False # def CallBackDebugTraj(self, cmd): # if (self.plot_done2): # self.debug_trajectory = cmd # self.plot_done2 = False # def CallBackDebugFixedTraj(self, cmd): # if (self.plot_done3): # self.debug_fixed_trajectory = cmd # self.plot_done3 = False # def timerCallback(self, event): # self.plotTrajectory() # self.plot_done1 = True # self.plot_done2 = True # self.plot_done3 = True # def CalcArcLength(self, traj): # s_arr = [] # ds = 0.0 # s_sum = 0.0 # if len(traj.points) > 0: # s_arr.append(s_sum) # for i in range(1, len(traj.points)): # p0 = traj.points[i-1] # p1 = traj.points[i] # dx = p1.pose.position.x - p0.pose.position.x # dy = p1.pose.position.y - p0.pose.position.y # ds = np.sqrt(dx**2 + dy**2) # s_sum += ds # if(s_sum > self.length): # break # s_arr.append(s_sum) # return s_arr # def CalcX(self, traj): # v_list = [] # for p in traj.points: # v_list.append(p.pose.position.x) # return v_list # def CalcY(self, traj): # v_list = [] # for p in traj.points: # v_list.append(p.pose.position.y) # return v_list # def CalcYaw(self, traj, s_arr): # v_list = [] # for p in traj.points: # v_list.append(quaternion_to_euler(p.pose.orientation).z) # return v_list[0: len(s_arr)] # def plotTrajectory(self): # plt.clf() # ax3 = plt.subplot(1, 1, 1) # x = self.CalcArcLength(self.in_trajectory) # y = self.CalcYaw(self.in_trajectory, x) # if len(x) == len(y): # ax3.plot(x, y, label="final", marker="*") # ax3.set_xlabel("arclength [m]") # ax3.set_ylabel("yaw") # plt.pause(0.01) # def main(): # rospy.init_node("trajectory_visualizer") # TrajectoryVisualizer() # rospy.spin() # if __name__ == "__main__": # main()
[ 2, 15069, 12131, 15917, 8363, 11, 3457, 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, 198, 2,...
2.017518
2,055
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.contrib.auth.models import User from django import forms # If you don't do this you cannot use Bootstrap CSS
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 23914, 1330, 48191, 8479, 11, 11787, 12443, 341, 8479, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 42625, 14208, 1330, 5107, 628, 198, 198, 2, ...
3.703704
54
import pandas as pd from pandas import DataFrame df = pd.read_csv('sp500_ohlc.csv', index_col = 'Date', parse_dates=True) df['H-L'] = df.High - df.Low # Giving us count (rows), mean (avg), std (standard deviation for the entire # set), minimum for the set, maximum for the set, and some %s in that range. print( df.describe()) x = input('enter to cont') # gives us correlation data. Remember the 3d chart we plotted? # now you can see if correlation of H-L and Volume also is correlated # with price swings. Correlations for your correlations print( df.corr()) x = input('enter to cont') # covariance... now plenty of people know what correlation is, but what in the # heck is covariance. # Let's defined the two. # covariance is the measure of how two variables change together. # correlation is the measure of how two variables move in relation to eachother. # so covariance is a more direct assessment of the relationship between two variables. # Maybe a better way to put it is that covariance is the measure of the strength of correlation. print( df.cov()) x = input('enter to cont') print( df[['Volume','H-L']].corr()) x = input('enter to cont') # see how it makes a table? # so now, we can actually perform a service that some people actually pay for # I once had a short freelance gig doing this # so a popular form of analysis within especially forex is to compare correlations between # the currencies. The idea here is that you pace one currency with another. # import datetime import pandas.io.data C = pd.io.data.get_data_yahoo('C', start=datetime.datetime(2011, 10, 1), end=datetime.datetime(2014, 1, 1)) AAPL = pd.io.data.get_data_yahoo('AAPL', start=datetime.datetime(2011, 10, 1), end=datetime.datetime(2014, 1, 1)) MSFT = pd.io.data.get_data_yahoo('MSFT', start=datetime.datetime(2011, 10, 1), end=datetime.datetime(2014, 1, 1)) TSLA = pd.io.data.get_data_yahoo('TSLA', start=datetime.datetime(2011, 10, 1), end=datetime.datetime(2014, 1, 1)) print( C.head()) x = input('enter to cont') del C['Open'] # , 'high', 'low', 'close', 'volume' del C['High'] del C['Low'] del C['Close'] del C['Volume'] corComp = C corComp.rename(columns={'Adj Close': 'C'}, inplace=True) corComp['AAPL'] = AAPL['Adj Close'] corComp['MSFT'] = MSFT['Adj Close'] corComp['TSLA'] = TSLA['Adj Close'] print( corComp.head()) x = input('enter to cont') print( corComp.corr()) x = input('enter to cont') C = pd.io.data.get_data_yahoo('C', start=datetime.datetime(2011, 10, 1), end=datetime.datetime(2014, 1, 1)) AAPL = pd.io.data.get_data_yahoo('AAPL', start=datetime.datetime(2011, 10, 1), end=datetime.datetime(2014, 1, 1)) MSFT = pd.io.data.get_data_yahoo('MSFT', start=datetime.datetime(2011, 10, 1), end=datetime.datetime(2014, 1, 1)) TSLA = pd.io.data.get_data_yahoo('TSLA', start=datetime.datetime(2011, 10, 1), end=datetime.datetime(2014, 1, 1)) BAC = pd.io.data.get_data_yahoo('BAC', start=datetime.datetime(2011, 10, 1), end=datetime.datetime(2014, 1, 1)) BBRY = pd.io.data.get_data_yahoo('BBRY', start=datetime.datetime(2011, 10, 1), end=datetime.datetime(2014, 1, 1)) CMG = pd.io.data.get_data_yahoo('CMG', start=datetime.datetime(2011, 10, 1), end=datetime.datetime(2014, 1, 1)) EBAY = pd.io.data.get_data_yahoo('EBAY', start=datetime.datetime(2011, 10, 1), end=datetime.datetime(2014, 1, 1)) JPM = pd.io.data.get_data_yahoo('JPM', start=datetime.datetime(2011, 10, 1), end=datetime.datetime(2014, 1, 1)) SBUX = pd.io.data.get_data_yahoo('SBUX', start=datetime.datetime(2011, 10, 1), end=datetime.datetime(2014, 1, 1)) TGT = pd.io.data.get_data_yahoo('TGT', start=datetime.datetime(2011, 10, 1), end=datetime.datetime(2014, 1, 1)) WFC = pd.io.data.get_data_yahoo('WFC', start=datetime.datetime(2011, 10, 1), end=datetime.datetime(2014, 1, 1)) x = input('enter to cont') print( C.head()) del C['Open'] # , 'high', 'low', 'close', 'volume' del C['High'] del C['Low'] del C['Close'] del C['Volume'] corComp = C corComp.rename(columns={'Adj Close': 'C'}, inplace=True) corComp['BAC'] = BAC['Adj Close'] corComp['MSFT'] = MSFT['Adj Close'] corComp['TSLA'] = TSLA['Adj Close'] corComp['AAPL'] = AAPL['Adj Close'] corComp['BBRY'] = BBRY['Adj Close'] corComp['CMG'] = CMG['Adj Close'] corComp['EBAY'] = EBAY['Adj Close'] corComp['JPM'] = JPM['Adj Close'] corComp['SBUX'] = SBUX['Adj Close'] corComp['TGT'] = TGT['Adj Close'] corComp['WFC'] = WFC['Adj Close'] print( corComp.head()) x = input('enter to cont') print( corComp.corr()) x = input('enter to cont') fancy = corComp.corr() fancy.to_csv('bigmoney.csv')
[ 11748, 19798, 292, 355, 279, 67, 198, 6738, 19798, 292, 1330, 6060, 19778, 198, 198, 7568, 796, 279, 67, 13, 961, 62, 40664, 10786, 2777, 4059, 62, 1219, 44601, 13, 40664, 3256, 6376, 62, 4033, 796, 705, 10430, 3256, 21136, 62, 19581,...
2.016083
2,798
import cv2 import numpy as np import threading t1 = threading.Thread(target=test) t1.start()
[ 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 4704, 278, 198, 198, 83, 16, 796, 4704, 278, 13, 16818, 7, 16793, 28, 9288, 8, 198, 83, 16, 13, 9688, 3419, 628 ]
2.714286
35
# Copyright 2013 Cloudbase Solutions Srl # # Author: Claudiu Belu <cbelu@cloudbasesolutions.com> # Alessandro Pilotti <apilotti@cloudbasesolutions.com> # # 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. """ Utility class for VM related operations. Based on the "root/virtualization/v2" namespace available starting with Hyper-V Server / Windows Server 2012. """ import sys if sys.platform == 'win32': import wmi from oslo.config import cfg from ceilometer.compute.virt import inspector from ceilometer.openstack.common.gettextutils import _ from ceilometer.openstack.common import log as logging CONF = cfg.CONF LOG = logging.getLogger(__name__)
[ 2, 15069, 2211, 10130, 8692, 23555, 21714, 75, 198, 2, 198, 2, 6434, 25, 36303, 16115, 3944, 84, 1279, 66, 6667, 84, 31, 17721, 65, 1386, 14191, 13, 785, 29, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 47319, 28092, 12693, 263...
3.424779
339
# system from io import IOBase, StringIO import os # 3rd party import click # internal from days import DayFactory # import logging # logger = logging.getLogger(__name__) # logger.setLevel(logging.DEBUG) # ch = logging.StreamHandler() # logger.addHandler(ch) if __name__ == "__main__": # pylint: disable=no-value-for-parameter cli()
[ 2, 1080, 198, 6738, 33245, 1330, 314, 9864, 589, 11, 10903, 9399, 198, 11748, 28686, 628, 198, 2, 513, 4372, 2151, 198, 11748, 3904, 198, 198, 2, 5387, 198, 6738, 1528, 1330, 3596, 22810, 198, 198, 2, 1330, 18931, 198, 2, 49706, 796...
2.890756
119
from matplotlib.colors import LinearSegmentedColormap from numpy import nan, inf # Used to reconstruct the colormap in viscm parameters = {'xp': [-5.4895292543686764, 14.790571669586654, 82.5546687431056, 29.15531114139253, -4.1316769886951761, -13.002076438907238], 'yp': [-35.948168839230306, -42.273376159885785, -28.845467523197698, 52.03426124197, 36.832712600868973, 40.792291220556734], 'min_JK': 16.8314150305, 'max_JK': 95} cm_data = [[ 5.03832136e-02, 2.98028976e-02, 5.27974883e-01], [ 6.35363639e-02, 2.84259729e-02, 5.33123681e-01], [ 7.53531234e-02, 2.72063728e-02, 5.38007001e-01], [ 8.62217979e-02, 2.61253206e-02, 5.42657691e-01], [ 9.63786097e-02, 2.51650976e-02, 5.47103487e-01], [ 1.05979704e-01, 2.43092436e-02, 5.51367851e-01], [ 1.15123641e-01, 2.35562500e-02, 5.55467728e-01], [ 1.23902903e-01, 2.28781011e-02, 5.59423480e-01], [ 1.32380720e-01, 2.22583774e-02, 5.63250116e-01], [ 1.40603076e-01, 2.16866674e-02, 5.66959485e-01], [ 1.48606527e-01, 2.11535876e-02, 5.70561711e-01], [ 1.56420649e-01, 2.06507174e-02, 5.74065446e-01], [ 1.64069722e-01, 2.01705326e-02, 5.77478074e-01], [ 1.71573925e-01, 1.97063415e-02, 5.80805890e-01], [ 1.78950212e-01, 1.92522243e-02, 5.84054243e-01], [ 1.86212958e-01, 1.88029767e-02, 5.87227661e-01], [ 1.93374449e-01, 1.83540593e-02, 5.90329954e-01], [ 2.00445260e-01, 1.79015512e-02, 5.93364304e-01], [ 2.07434551e-01, 1.74421086e-02, 5.96333341e-01], [ 2.14350298e-01, 1.69729276e-02, 5.99239207e-01], [ 2.21196750e-01, 1.64970484e-02, 6.02083323e-01], [ 2.27982971e-01, 1.60071509e-02, 6.04867403e-01], [ 2.34714537e-01, 1.55015065e-02, 6.07592438e-01], [ 2.41396253e-01, 1.49791041e-02, 6.10259089e-01], [ 2.48032377e-01, 1.44393586e-02, 6.12867743e-01], [ 2.54626690e-01, 1.38820918e-02, 6.15418537e-01], [ 2.61182562e-01, 1.33075156e-02, 6.17911385e-01], [ 2.67702993e-01, 1.27162163e-02, 6.20345997e-01], [ 2.74190665e-01, 1.21091423e-02, 6.22721903e-01], [ 2.80647969e-01, 1.14875915e-02, 6.25038468e-01], [ 2.87076059e-01, 1.08554862e-02, 6.27294975e-01], [ 2.93477695e-01, 1.02128849e-02, 6.29490490e-01], [ 2.99855122e-01, 9.56079551e-03, 6.31623923e-01], [ 3.06209825e-01, 8.90185346e-03, 6.33694102e-01], [ 3.12543124e-01, 8.23900704e-03, 6.35699759e-01], [ 3.18856183e-01, 7.57551051e-03, 6.37639537e-01], [ 3.25150025e-01, 6.91491734e-03, 6.39512001e-01], [ 3.31425547e-01, 6.26107379e-03, 6.41315649e-01], [ 3.37683446e-01, 5.61830889e-03, 6.43048936e-01], [ 3.43924591e-01, 4.99053080e-03, 6.44710195e-01], [ 3.50149699e-01, 4.38202557e-03, 6.46297711e-01], [ 3.56359209e-01, 3.79781761e-03, 6.47809772e-01], [ 3.62553473e-01, 3.24319591e-03, 6.49244641e-01], [ 3.68732762e-01, 2.72370721e-03, 6.50600561e-01], [ 3.74897270e-01, 2.24514897e-03, 6.51875762e-01], [ 3.81047116e-01, 1.81356205e-03, 6.53068467e-01], [ 3.87182639e-01, 1.43446923e-03, 6.54176761e-01], [ 3.93304010e-01, 1.11388259e-03, 6.55198755e-01], [ 3.99410821e-01, 8.59420809e-04, 6.56132835e-01], [ 4.05502914e-01, 6.78091517e-04, 6.56977276e-01], [ 4.11580082e-01, 5.77101735e-04, 6.57730380e-01], [ 4.17642063e-01, 5.63847476e-04, 6.58390492e-01], [ 4.23688549e-01, 6.45902780e-04, 6.58956004e-01], [ 4.29719186e-01, 8.31008207e-04, 6.59425363e-01], [ 4.35733575e-01, 1.12705875e-03, 6.59797077e-01], [ 4.41732123e-01, 1.53984779e-03, 6.60069009e-01], [ 4.47713600e-01, 2.07954744e-03, 6.60240367e-01], [ 4.53677394e-01, 2.75470302e-03, 6.60309966e-01], [ 4.59622938e-01, 3.57374415e-03, 6.60276655e-01], [ 4.65549631e-01, 4.54518084e-03, 6.60139383e-01], [ 4.71456847e-01, 5.67758762e-03, 6.59897210e-01], [ 4.77343929e-01, 6.97958743e-03, 6.59549311e-01], [ 4.83210198e-01, 8.45983494e-03, 6.59094989e-01], [ 4.89054951e-01, 1.01269996e-02, 6.58533677e-01], [ 4.94877466e-01, 1.19897486e-02, 6.57864946e-01], [ 5.00677687e-01, 1.40550640e-02, 6.57087561e-01], [ 5.06454143e-01, 1.63333443e-02, 6.56202294e-01], [ 5.12206035e-01, 1.88332232e-02, 6.55209222e-01], [ 5.17932580e-01, 2.15631918e-02, 6.54108545e-01], [ 5.23632990e-01, 2.45316468e-02, 6.52900629e-01], [ 5.29306474e-01, 2.77468735e-02, 6.51586010e-01], [ 5.34952244e-01, 3.12170300e-02, 6.50165396e-01], [ 5.40569510e-01, 3.49501310e-02, 6.48639668e-01], [ 5.46157494e-01, 3.89540334e-02, 6.47009884e-01], [ 5.51715423e-01, 4.31364795e-02, 6.45277275e-01], [ 5.57242538e-01, 4.73307585e-02, 6.43443250e-01], [ 5.62738096e-01, 5.15448092e-02, 6.41509389e-01], [ 5.68201372e-01, 5.57776706e-02, 6.39477440e-01], [ 5.73631859e-01, 6.00281369e-02, 6.37348841e-01], [ 5.79028682e-01, 6.42955547e-02, 6.35126108e-01], [ 5.84391137e-01, 6.85790261e-02, 6.32811608e-01], [ 5.89718606e-01, 7.28775875e-02, 6.30407727e-01], [ 5.95010505e-01, 7.71902878e-02, 6.27916992e-01], [ 6.00266283e-01, 8.15161895e-02, 6.25342058e-01], [ 6.05485428e-01, 8.58543713e-02, 6.22685703e-01], [ 6.10667469e-01, 9.02039303e-02, 6.19950811e-01], [ 6.15811974e-01, 9.45639838e-02, 6.17140367e-01], [ 6.20918555e-01, 9.89336721e-02, 6.14257440e-01], [ 6.25986869e-01, 1.03312160e-01, 6.11305174e-01], [ 6.31016615e-01, 1.07698641e-01, 6.08286774e-01], [ 6.36007543e-01, 1.12092335e-01, 6.05205491e-01], [ 6.40959444e-01, 1.16492495e-01, 6.02064611e-01], [ 6.45872158e-01, 1.20898405e-01, 5.98867442e-01], [ 6.50745571e-01, 1.25309384e-01, 5.95617300e-01], [ 6.55579615e-01, 1.29724785e-01, 5.92317494e-01], [ 6.60374266e-01, 1.34143997e-01, 5.88971318e-01], [ 6.65129493e-01, 1.38566428e-01, 5.85582301e-01], [ 6.69845385e-01, 1.42991540e-01, 5.82153572e-01], [ 6.74522060e-01, 1.47418835e-01, 5.78688247e-01], [ 6.79159664e-01, 1.51847851e-01, 5.75189431e-01], [ 6.83758384e-01, 1.56278163e-01, 5.71660158e-01], [ 6.88318440e-01, 1.60709387e-01, 5.68103380e-01], [ 6.92840088e-01, 1.65141174e-01, 5.64521958e-01], [ 6.97323615e-01, 1.69573215e-01, 5.60918659e-01], [ 7.01769334e-01, 1.74005236e-01, 5.57296144e-01], [ 7.06177590e-01, 1.78437000e-01, 5.53656970e-01], [ 7.10548747e-01, 1.82868306e-01, 5.50003579e-01], [ 7.14883195e-01, 1.87298986e-01, 5.46338299e-01], [ 7.19181339e-01, 1.91728906e-01, 5.42663338e-01], [ 7.23443604e-01, 1.96157962e-01, 5.38980786e-01], [ 7.27670428e-01, 2.00586086e-01, 5.35292612e-01], [ 7.31862231e-01, 2.05013174e-01, 5.31600995e-01], [ 7.36019424e-01, 2.09439071e-01, 5.27908434e-01], [ 7.40142557e-01, 2.13863965e-01, 5.24215533e-01], [ 7.44232102e-01, 2.18287899e-01, 5.20523766e-01], [ 7.48288533e-01, 2.22710942e-01, 5.16834495e-01], [ 7.52312321e-01, 2.27133187e-01, 5.13148963e-01], [ 7.56303937e-01, 2.31554749e-01, 5.09468305e-01], [ 7.60263849e-01, 2.35975765e-01, 5.05793543e-01], [ 7.64192516e-01, 2.40396394e-01, 5.02125599e-01], [ 7.68090391e-01, 2.44816813e-01, 4.98465290e-01], [ 7.71957916e-01, 2.49237220e-01, 4.94813338e-01], [ 7.75795522e-01, 2.53657797e-01, 4.91170517e-01], [ 7.79603614e-01, 2.58078397e-01, 4.87539124e-01], [ 7.83382636e-01, 2.62499662e-01, 4.83917732e-01], [ 7.87132978e-01, 2.66921859e-01, 4.80306702e-01], [ 7.90855015e-01, 2.71345267e-01, 4.76706319e-01], [ 7.94549101e-01, 2.75770179e-01, 4.73116798e-01], [ 7.98215577e-01, 2.80196901e-01, 4.69538286e-01], [ 8.01854758e-01, 2.84625750e-01, 4.65970871e-01], [ 8.05466945e-01, 2.89057057e-01, 4.62414580e-01], [ 8.09052419e-01, 2.93491117e-01, 4.58869577e-01], [ 8.12611506e-01, 2.97927865e-01, 4.55337565e-01], [ 8.16144382e-01, 3.02368130e-01, 4.51816385e-01], [ 8.19651255e-01, 3.06812282e-01, 4.48305861e-01], [ 8.23132309e-01, 3.11260703e-01, 4.44805781e-01], [ 8.26587706e-01, 3.15713782e-01, 4.41315901e-01], [ 8.30017584e-01, 3.20171913e-01, 4.37835947e-01], [ 8.33422053e-01, 3.24635499e-01, 4.34365616e-01], [ 8.36801237e-01, 3.29104836e-01, 4.30905052e-01], [ 8.40155276e-01, 3.33580106e-01, 4.27454836e-01], [ 8.43484103e-01, 3.38062109e-01, 4.24013059e-01], [ 8.46787726e-01, 3.42551272e-01, 4.20579333e-01], [ 8.50066132e-01, 3.47048028e-01, 4.17153264e-01], [ 8.53319279e-01, 3.51552815e-01, 4.13734445e-01], [ 8.56547103e-01, 3.56066072e-01, 4.10322469e-01], [ 8.59749520e-01, 3.60588229e-01, 4.06916975e-01], [ 8.62926559e-01, 3.65119408e-01, 4.03518809e-01], [ 8.66077920e-01, 3.69660446e-01, 4.00126027e-01], [ 8.69203436e-01, 3.74211795e-01, 3.96738211e-01], [ 8.72302917e-01, 3.78773910e-01, 3.93354947e-01], [ 8.75376149e-01, 3.83347243e-01, 3.89975832e-01], [ 8.78422895e-01, 3.87932249e-01, 3.86600468e-01], [ 8.81442916e-01, 3.92529339e-01, 3.83228622e-01], [ 8.84435982e-01, 3.97138877e-01, 3.79860246e-01], [ 8.87401682e-01, 4.01761511e-01, 3.76494232e-01], [ 8.90339687e-01, 4.06397694e-01, 3.73130228e-01], [ 8.93249647e-01, 4.11047871e-01, 3.69767893e-01], [ 8.96131191e-01, 4.15712489e-01, 3.66406907e-01], [ 8.98983931e-01, 4.20391986e-01, 3.63046965e-01], [ 9.01807455e-01, 4.25086807e-01, 3.59687758e-01], [ 9.04601295e-01, 4.29797442e-01, 3.56328796e-01], [ 9.07364995e-01, 4.34524335e-01, 3.52969777e-01], [ 9.10098088e-01, 4.39267908e-01, 3.49610469e-01], [ 9.12800095e-01, 4.44028574e-01, 3.46250656e-01], [ 9.15470518e-01, 4.48806744e-01, 3.42890148e-01], [ 9.18108848e-01, 4.53602818e-01, 3.39528771e-01], [ 9.20714383e-01, 4.58417420e-01, 3.36165582e-01], [ 9.23286660e-01, 4.63250828e-01, 3.32800827e-01], [ 9.25825146e-01, 4.68103387e-01, 3.29434512e-01], [ 9.28329275e-01, 4.72975465e-01, 3.26066550e-01], [ 9.30798469e-01, 4.77867420e-01, 3.22696876e-01], [ 9.33232140e-01, 4.82779603e-01, 3.19325444e-01], [ 9.35629684e-01, 4.87712357e-01, 3.15952211e-01], [ 9.37990034e-01, 4.92666544e-01, 3.12575440e-01], [ 9.40312939e-01, 4.97642038e-01, 3.09196628e-01], [ 9.42597771e-01, 5.02639147e-01, 3.05815824e-01], [ 9.44843893e-01, 5.07658169e-01, 3.02433101e-01], [ 9.47050662e-01, 5.12699390e-01, 2.99048555e-01], [ 9.49217427e-01, 5.17763087e-01, 2.95662308e-01], [ 9.51343530e-01, 5.22849522e-01, 2.92274506e-01], [ 9.53427725e-01, 5.27959550e-01, 2.88883445e-01], [ 9.55469640e-01, 5.33093083e-01, 2.85490391e-01], [ 9.57468770e-01, 5.38250172e-01, 2.82096149e-01], [ 9.59424430e-01, 5.43431038e-01, 2.78700990e-01], [ 9.61335930e-01, 5.48635890e-01, 2.75305214e-01], [ 9.63202573e-01, 5.53864931e-01, 2.71909159e-01], [ 9.65023656e-01, 5.59118349e-01, 2.68513200e-01], [ 9.66798470e-01, 5.64396327e-01, 2.65117752e-01], [ 9.68525639e-01, 5.69699633e-01, 2.61721488e-01], [ 9.70204593e-01, 5.75028270e-01, 2.58325424e-01], [ 9.71835007e-01, 5.80382015e-01, 2.54931256e-01], [ 9.73416145e-01, 5.85761012e-01, 2.51539615e-01], [ 9.74947262e-01, 5.91165394e-01, 2.48151200e-01], [ 9.76427606e-01, 5.96595287e-01, 2.44766775e-01], [ 9.77856416e-01, 6.02050811e-01, 2.41387186e-01], [ 9.79232922e-01, 6.07532077e-01, 2.38013359e-01], [ 9.80556344e-01, 6.13039190e-01, 2.34646316e-01], [ 9.81825890e-01, 6.18572250e-01, 2.31287178e-01], [ 9.83040742e-01, 6.24131362e-01, 2.27937141e-01], [ 9.84198924e-01, 6.29717516e-01, 2.24595006e-01], [ 9.85300760e-01, 6.35329876e-01, 2.21264889e-01], [ 9.86345421e-01, 6.40968508e-01, 2.17948456e-01], [ 9.87332067e-01, 6.46633475e-01, 2.14647532e-01], [ 9.88259846e-01, 6.52324832e-01, 2.11364122e-01], [ 9.89127893e-01, 6.58042630e-01, 2.08100426e-01], [ 9.89935328e-01, 6.63786914e-01, 2.04858855e-01], [ 9.90681261e-01, 6.69557720e-01, 2.01642049e-01], [ 9.91364787e-01, 6.75355082e-01, 1.98452900e-01], [ 9.91984990e-01, 6.81179025e-01, 1.95294567e-01], [ 9.92540939e-01, 6.87029567e-01, 1.92170500e-01], [ 9.93031693e-01, 6.92906719e-01, 1.89084459e-01], [ 9.93456302e-01, 6.98810484e-01, 1.86040537e-01], [ 9.93813802e-01, 7.04740854e-01, 1.83043180e-01], [ 9.94103226e-01, 7.10697814e-01, 1.80097207e-01], [ 9.94323596e-01, 7.16681336e-01, 1.77207826e-01], [ 9.94473934e-01, 7.22691379e-01, 1.74380656e-01], [ 9.94553260e-01, 7.28727890e-01, 1.71621733e-01], [ 9.94560594e-01, 7.34790799e-01, 1.68937522e-01], [ 9.94494964e-01, 7.40880020e-01, 1.66334918e-01], [ 9.94355411e-01, 7.46995448e-01, 1.63821243e-01], [ 9.94140989e-01, 7.53136955e-01, 1.61404226e-01], [ 9.93850778e-01, 7.59304390e-01, 1.59091984e-01], [ 9.93482190e-01, 7.65498551e-01, 1.56890625e-01], [ 9.93033251e-01, 7.71719833e-01, 1.54807583e-01], [ 9.92505214e-01, 7.77966775e-01, 1.52854862e-01], [ 9.91897270e-01, 7.84239120e-01, 1.51041581e-01], [ 9.91208680e-01, 7.90536569e-01, 1.49376885e-01], [ 9.90438793e-01, 7.96858775e-01, 1.47869810e-01], [ 9.89587065e-01, 8.03205337e-01, 1.46529128e-01], [ 9.88647741e-01, 8.09578605e-01, 1.45357284e-01], [ 9.87620557e-01, 8.15977942e-01, 1.44362644e-01], [ 9.86509366e-01, 8.22400620e-01, 1.43556679e-01], [ 9.85314198e-01, 8.28845980e-01, 1.42945116e-01], [ 9.84031139e-01, 8.35315360e-01, 1.42528388e-01], [ 9.82652820e-01, 8.41811730e-01, 1.42302653e-01], [ 9.81190389e-01, 8.48328902e-01, 1.42278607e-01], [ 9.79643637e-01, 8.54866468e-01, 1.42453425e-01], [ 9.77994918e-01, 8.61432314e-01, 1.42808191e-01], [ 9.76264977e-01, 8.68015998e-01, 1.43350944e-01], [ 9.74443038e-01, 8.74622194e-01, 1.44061156e-01], [ 9.72530009e-01, 8.81250063e-01, 1.44922913e-01], [ 9.70532932e-01, 8.87896125e-01, 1.45918663e-01], [ 9.68443477e-01, 8.94563989e-01, 1.47014438e-01], [ 9.66271225e-01, 9.01249365e-01, 1.48179639e-01], [ 9.64021057e-01, 9.07950379e-01, 1.49370428e-01], [ 9.61681481e-01, 9.14672479e-01, 1.50520343e-01], [ 9.59275646e-01, 9.21406537e-01, 1.51566019e-01], [ 9.56808068e-01, 9.28152065e-01, 1.52409489e-01], [ 9.54286813e-01, 9.34907730e-01, 1.52921158e-01], [ 9.51726083e-01, 9.41670605e-01, 1.52925363e-01], [ 9.49150533e-01, 9.48434900e-01, 1.52177604e-01], [ 9.46602270e-01, 9.55189860e-01, 1.50327944e-01], [ 9.44151742e-01, 9.61916487e-01, 1.46860789e-01], [ 9.41896120e-01, 9.68589814e-01, 1.40955606e-01], [ 9.40015097e-01, 9.75158357e-01, 1.31325517e-01]] test_cm = LinearSegmentedColormap.from_list(__file__, cm_data) if __name__ == "__main__": import matplotlib.pyplot as plt import numpy as np try: from viscm import viscm viscm(test_cm) except ImportError: print("viscm not found, falling back on simple display") plt.imshow(np.linspace(0, 100, 256)[None, :], aspect='auto', cmap=test_cm) plt.show()
[ 198, 6738, 2603, 29487, 8019, 13, 4033, 669, 1330, 44800, 41030, 12061, 5216, 579, 499, 198, 6738, 299, 32152, 1330, 15709, 11, 1167, 198, 198, 2, 16718, 284, 31081, 262, 951, 579, 499, 287, 1490, 11215, 198, 17143, 7307, 796, 1391, 6...
1.543683
11,034
import matplotlib.pyplot as plt import numpy as np import math from algorithm.planner.utils.car_utils import Car_C PI = np.pi def draw_car(x, y, yaw, steer, color='black', extended_car=True): if extended_car: car = np.array([[-Car_C.RB, -Car_C.RB, Car_C.RF, Car_C.RF, -Car_C.RB, Car_C.ACTUAL_RF, Car_C.ACTUAL_RF, -Car_C.ACTUAL_RB, -Car_C.ACTUAL_RB], [Car_C.W / 2, -Car_C.W / 2, -Car_C.W / 2, Car_C.W / 2, Car_C.W / 2, Car_C.W/2, -Car_C.W/2, -Car_C.W/2, Car_C.W/2]]) else: car = np.array([[-Car_C.RB, -Car_C.RB, Car_C.RF, Car_C.RF, -Car_C.RB], [Car_C.W / 2, -Car_C.W / 2, -Car_C.W / 2, Car_C.W / 2, Car_C.W / 2]]) wheel = np.array([[-Car_C.TR, -Car_C.TR, Car_C.TR, Car_C.TR, -Car_C.TR], [Car_C.TW / 4, -Car_C.TW / 4, -Car_C.TW / 4, Car_C.TW / 4, Car_C.TW / 4]]) rlWheel = wheel.copy() rrWheel = wheel.copy() frWheel = wheel.copy() flWheel = wheel.copy() Rot1 = np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]]) Rot2 = np.array([[math.cos(steer), math.sin(steer)], [-math.sin(steer), math.cos(steer)]]) frWheel = np.dot(Rot2, frWheel) flWheel = np.dot(Rot2, flWheel) frWheel += np.array([[Car_C.WB], [-Car_C.WD / 2]]) flWheel += np.array([[Car_C.WB], [Car_C.WD / 2]]) rrWheel[1, :] -= Car_C.WD / 2 rlWheel[1, :] += Car_C.WD / 2 frWheel = np.dot(Rot1, frWheel) flWheel = np.dot(Rot1, flWheel) rrWheel = np.dot(Rot1, rrWheel) rlWheel = np.dot(Rot1, rlWheel) car = np.dot(Rot1, car) frWheel += np.array([[x], [y]]) flWheel += np.array([[x], [y]]) rrWheel += np.array([[x], [y]]) rlWheel += np.array([[x], [y]]) car += np.array([[x], [y]]) plt.plot(car[0, :], car[1, :], color) plt.plot(frWheel[0, :], frWheel[1, :], color) plt.plot(rrWheel[0, :], rrWheel[1, :], color) plt.plot(flWheel[0, :], flWheel[1, :], color) plt.plot(rlWheel[0, :], rlWheel[1, :], color) Arrow(x, y, yaw, Car_C.WB * 0.8, color)
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 10688, 198, 6738, 11862, 13, 11578, 1008, 13, 26791, 13, 7718, 62, 26791, 1330, 1879, 62, 34, 198, 198, 11901, 796, 45941, 13, 14...
1.849911
1,126
from sqlalchemy import Integer, Text, DateTime, func, Boolean, text from models.database_models import Base, Column
[ 6738, 44161, 282, 26599, 1330, 34142, 11, 8255, 11, 7536, 7575, 11, 25439, 11, 41146, 11, 2420, 198, 198, 6738, 4981, 13, 48806, 62, 27530, 1330, 7308, 11, 29201, 628 ]
3.933333
30
import json import re from datetime import datetime from json.decoder import JSONDecodeError import click from boto3.session import Session from boto3_type_annotations.ecs import Client from botocore.exceptions import ClientError, NoCredentialsError from dateutil.tz.tz import tzlocal from dictdiffer import diff JSON_LIST_REGEX = re.compile(r'^\[.*\]$') LAUNCH_TYPE_EC2 = 'EC2' LAUNCH_TYPE_FARGATE = 'FARGATE' class EcsTaskDefinition(object): def show_diff(self, show_diff: bool = False): if show_diff: click.secho('Task definition modified:') for d in self._diff: click.secho(f' {str(d)}', fg='blue') click.secho('') def get_tag(self, key): for tag in self.tags: if tag['key'] == key: return tag['value'] return None def set_tag(self, key: str, value: str): if key and value: done = False for tag in self.tags: if tag['key'] == key: if tag['value'] != value: diff = EcsTaskDefinitionDiff( container=None, field=f"tags['{key}']", value=value, old_value=tag['value'] ) self._diff.append(diff) tag['value'] = value done = True break if not done: diff = EcsTaskDefinitionDiff(container=None, field=f"tags['{key}']", value=value, old_value=None) self._diff.append(diff) self.tags.append({'key': key, 'value': value}) class EcsTaskDefinitionDiff(object):
[ 11748, 33918, 198, 11748, 302, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 33918, 13, 12501, 12342, 1330, 19449, 10707, 1098, 12331, 198, 198, 11748, 3904, 198, 6738, 275, 2069, 18, 13, 29891, 1330, 23575, 198, 6738, 275, 2069, ...
1.925081
921
import networkx as nx from scipy.special import comb import attr
[ 11748, 3127, 87, 355, 299, 87, 198, 6738, 629, 541, 88, 13, 20887, 1330, 1974, 198, 11748, 708, 81, 628 ]
3.3
20
from typing import Callable, Collection, Iterable, List, Union from data.anagram import anagram_iter from data.graph import _op_mixin, bloom_mask, bloom_node, bloom_node_reducer Transformer = Callable[['bloom_node.BloomNode'], 'bloom_node.BloomNode'] _SPACE_MASK = bloom_mask.for_alpha(' ') def _normalize_state( exit_node: 'bloom_node.BloomNode', index: Union[Iterable, anagram_iter.AnagramIter]) -> _AnagramState: if isinstance(index, _AnagramState): return index # `index` is an iterable list of ???, one-by-one these will be taken as a # route to the `exit_node`. initial_anagrams = anagram_iter.from_choices(index) index = _AnagramTransformIndex(exit_node, initial_anagrams) return _AnagramState(index, initial_anagrams)
[ 6738, 19720, 1330, 4889, 540, 11, 12251, 11, 40806, 540, 11, 7343, 11, 4479, 198, 198, 6738, 1366, 13, 272, 6713, 1330, 281, 6713, 62, 2676, 198, 6738, 1366, 13, 34960, 1330, 4808, 404, 62, 19816, 259, 11, 29955, 62, 27932, 11, 2995...
2.885496
262
import json import re import logging import html.parser import zlib import requests from gogapi import urls from gogapi.base import NotAuthorizedError, logger from gogapi.product import Product, Series from gogapi.search import SearchResult DEBUG_JSON = False GOGDATA_RE = re.compile(r"gogData\.?(.*?) = (.+);") CLIENT_VERSION = "1.2.17.9" # Just for their statistics USER_AGENT = "GOGGalaxyClient/{} pygogapi/0.1".format(CLIENT_VERSION) REQUEST_RETRIES = 3 PRODUCT_EXPANDABLE = [ "downloads", "expanded_dlcs", "description", "screenshots", "videos", "related_products", "changelog" ] USER_EXPANDABLE = ["friendStatus", "wishlistStatus", "blockedStatus"] LOCALE_CODES = ["de-DE", "en-US", "fr-FR", "pt-BR", "pl-PL", "ru-RU", "zh-Hans"] CURRENCY_CODES = [ "USD", "EUR", "GBP", "AUD", "RUB", "PLN", "CAD", "CHF", "NOK", "SEK", "DKK" ]
[ 11748, 33918, 198, 11748, 302, 198, 11748, 18931, 198, 11748, 27711, 13, 48610, 198, 11748, 1976, 8019, 198, 198, 11748, 7007, 198, 198, 6738, 467, 70, 15042, 1330, 2956, 7278, 198, 6738, 467, 70, 15042, 13, 8692, 1330, 1892, 13838, 114...
2.510264
341
import pathlib import os from setuptools import setup # The directory containing this file HERE = pathlib.Path(__file__).parent # The text of the README file README = (HERE / "README.md").read_text() # specify requirements of your package here REQUIREMENTS = ['biopython', 'numpy', 'pandas'] setup(name='stacksPairwise', version='0.0.0', description='Calculate pairwise divergence (pairwise pi) from Stacks `samples.fa` output fle', long_description=README, long_description_content_type="text/markdown", url='https://github.com/gibsonmatt/stacks-pairwise', author='Matt Gibson', author_email='matthewjsgibson@gmail.com', license='MIT', packages=['stacksPairwise'], install_requires=REQUIREMENTS, entry_points={ "console_scripts": [ "stacksPairwise=stacksPairwise.__main__:main" ] }, keywords='genetics genotyping sequencing Stacks' )
[ 11748, 3108, 8019, 198, 11748, 28686, 198, 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 2, 383, 8619, 7268, 428, 2393, 198, 39, 9338, 796, 3108, 8019, 13, 15235, 7, 834, 7753, 834, 737, 8000, 198, 198, 2, 383, 2420, 286, 262, 2083...
2.5625
368
#! /usr/bin/env python import os import sys args = sys.argv[1:] os.system('python -O -m spanningtree.csv_experiment_statistics ' + ' '.join(args))
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 22046, 796, 25064, 13, 853, 85, 58, 16, 47715, 198, 418, 13, 10057, 10786, 29412, 532, 46, 532, 76, 32557, 21048, 13, 40664, 62, 23100, 3...
2.47619
63