content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
""" Message context. """ from typing import Dict from microcosm.api import defaults, typed from microcosm.config.types import boolean from microcosm_logging.decorators import logger from microcosm_pubsub.constants import TTL_KEY, URI_KEY from microcosm_pubsub.message import SQSMessage
[ 37811, 198, 12837, 4732, 13, 198, 198, 37811, 198, 6738, 19720, 1330, 360, 713, 198, 198, 6738, 4580, 6966, 76, 13, 15042, 1330, 26235, 11, 25683, 198, 6738, 4580, 6966, 76, 13, 11250, 13, 19199, 1330, 25131, 198, 6738, 4580, 6966, 76...
3.372093
86
import os import argparse import torch import torch.optim as optim import torchvision import torchvision.transforms as transforms from model import Net from azureml.core import Run run = Run.get_context() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( '--data_path', type=str, help='Path to the training data' ) parser.add_argument( '--learning_rate', type=float, default=0.001, help='Learning rate for SGD' ) parser.add_argument( '--momentum', type=float, default=0.9, help='Momentum for SGD' ) args = parser.parse_args() print("===== DATA =====") print("DATA PATH: " + args.data_path) print("LIST FILES IN DATA PATH...") print(os.listdir(args.data_path)) print("================") # prepare DataLoader for CIFAR10 data transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ]) trainset = torchvision.datasets.CIFAR10( root=args.data_path, train=True, download=False, transform=transform, ) trainloader = torch.utils.data.DataLoader( trainset, batch_size=4, shuffle=True, num_workers=2 ) # define convolutional network net = Net() # set up pytorch loss / optimizer criterion = torch.nn.CrossEntropyLoss() optimizer = optim.SGD( net.parameters(), lr=args.learning_rate, momentum=args.momentum, ) # train the network for epoch in range(2): running_loss = 0.0 for i, data in enumerate(trainloader, 0): # unpack the data inputs, labels = data # zero the parameter gradients optimizer.zero_grad() # forward + backward + optimize outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() # print statistics running_loss += loss.item() if i % 2000 == 1999: loss = running_loss / 2000 run.log('loss', loss) # log loss metric to AML print(f'epoch={epoch + 1}, batch={i + 1:5}: loss {loss:.2f}') running_loss = 0.0 print('Finished Training')
[ 11748, 28686, 198, 11748, 1822, 29572, 198, 11748, 28034, 198, 11748, 28034, 13, 40085, 355, 6436, 198, 11748, 28034, 10178, 198, 11748, 28034, 10178, 13, 7645, 23914, 355, 31408, 198, 198, 6738, 2746, 1330, 3433, 198, 6738, 35560, 495, 4...
2.46614
886
import pytest from app.db import session_scope pytestmark = pytest.mark.asyncio
[ 11748, 12972, 9288, 198, 198, 6738, 598, 13, 9945, 1330, 6246, 62, 29982, 198, 198, 9078, 9288, 4102, 796, 12972, 9288, 13, 4102, 13, 292, 13361, 952, 628 ]
2.964286
28
from abc import ABC, abstractmethod from datetime import datetime import json import logging from catalyst import utils from catalyst.core import _State __all__ = ["MetricsFormatter", "TxtMetricsFormatter", "JsonMetricsFormatter"]
[ 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 33918, 198, 11748, 18931, 198, 198, 6738, 31357, 1330, 3384, 4487, 198, 6738, 31357, 13, 7295, 1330, 4808, 9012, 628, 628, 198, 198, 834, ...
3.537313
67
#!/usr/bin/env python3 """ Description: Python script to append the common columns in one sheet from another sheet using fuzzy matching. """ import pip import os import sys import argparse import_or_install('numpy') import_or_install('pandas') import_or_install('fuzzywuzzy') import numpy as np import pandas as pd from fuzzywuzzy import process, fuzz def parse_args(parser): """ Parsing and configuration of the command line arguments. """ parser = argparse.ArgumentParser() parser.add_argument('--firstcsv', type=str, required=True, help='CSV file for first table.') parser.add_argument('--secondcsv', type=str, required=True, help='CSV file for second table.') parser.add_argument('--destination', type=str, default='output.csv', help='Destination filename.') parser.add_argument('--commoncolumns1', type=str, required=True, help='Common columns for first table.') parser.add_argument('--commoncolumns2', type=str, required=True, help='Common columns for second table in the same order.') parser.add_argument("--in", dest="_in", default='second', choices=['second', 'first'], help='Table to append the columns. ') return check_args(parser.parse_args()) def check_args(args): """ Checking the arguments if they are entered properly. Validations performed: 1. Compulsory arguments are entered. 2. The entered filenames are present in the current folder. 3. The entered column names are present in the corresponding files. 4. If the destination filename is already present in the directory, ask the user if it can be overwritten. """ # for --firstcsv and --secondcsv for filename in [args.firstcsv, args.secondcsv]: if not os.path.isfile(filename): raise Exception("File {} is not present in the currrent folder.".format(filename)) # --commoncolumns1 commoncolumns1 = [i.strip().lower() for i in args.commoncolumns1.split(',')] temp = set(commoncolumns1) - set(pd.read_csv(args.firstcsv, nrows=1).columns.str.lower().str.strip()) if temp: raise Exception("The following columns are not present in the file, {}:\n{}".format(args.firstcsv, temp)) # --commoncolumns2 commoncolumns2 = [i.strip().lower() for i in args.commoncolumns2.split(',')] temp = set(commoncolumns2) - set(pd.read_csv(args.secondcsv, nrows=1).columns.str.lower().str.strip()) if temp: raise Exception("The following columns are not present in the file, {}:\n{}".format(args.secondcsv, temp)) # --destination if os.path.isfile(args.destination): print("The file {} already exists. Do you want to overwrite it? y/n".format(args.destination)) ans = input().strip().lower() if ans == 'n': print("Please enter different destination filename and run the script again.") sys.exit() return args if __name__ == "__main__": # instantiate the ArgumentParser class and parse the arguments parser = argparse.ArgumentParser() arguments = parse_args(parser) # save the arguments as some variables which later would be passed to FuzzyMatcher class filename_1 = arguments.firstcsv filename_2 = arguments.secondcsv result_filename = arguments.destination # clean and lowercase-ize the columns names common_columns_1 = [i.strip().lower() for i in arguments.commoncolumns1.split(',')] common_columns_2 = [i.strip().lower() for i in arguments.commoncolumns2.split(',')] # instantiate the FuzzyMatcher object, perform the fuzzy match, and save the result to the destination CSV file fuzzy_matcher = FuzzyMatcher(filename_1, filename_2, common_columns_1, common_columns_2, append_in=arguments._in) fuzzy_matcher.fuzzy_match fuzzy_matcher.save(result_filename)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 37811, 198, 11828, 25, 11361, 4226, 284, 24443, 262, 2219, 15180, 287, 530, 9629, 422, 1194, 9629, 1262, 34669, 12336, 13, 198, 37811, 198, 11748, 7347, 198, 220, 220, 220, 22...
2.852639
1,364
from .Panel import * __all__ = ['BubblePanel'] default_size = plt.matplotlib.rcParams['lines.markersize']**2
[ 6738, 764, 26639, 1330, 1635, 198, 198, 834, 439, 834, 796, 37250, 33, 549, 903, 26639, 20520, 198, 198, 12286, 62, 7857, 796, 458, 83, 13, 6759, 29487, 8019, 13, 6015, 10044, 4105, 17816, 6615, 13, 4102, 364, 1096, 20520, 1174, 17, ...
2.581395
43
import os from twisted.internet.defer import succeed
[ 11748, 28686, 198, 198, 6738, 19074, 13, 37675, 13, 4299, 263, 1330, 6758, 628 ]
3.928571
14
from rest_framework import viewsets from boh import models from . import serializers
[ 6738, 1334, 62, 30604, 1330, 5009, 1039, 198, 198, 6738, 275, 1219, 1330, 4981, 198, 198, 6738, 764, 1330, 11389, 11341, 628, 628, 198 ]
3.791667
24
import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot import agentframework import csv import matplotlib.animation #create environment in which agents will operate environment=[] #read csv downloaded file f = open('in.txt', newline='') reader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC) for row in reader: rowlist=[] # A list of rows environment.append(rowlist) for value in row: # A list of value #print(value) # Floats rowlist.append(value) f.close() # Don't close until you are done with the reader; # the data is read on request. #def distance_between(agents_row_a, agents_row_b): # return (((agents_row_a.x - agents_row_b.x)**2) + # ((agents_row_a.y - agents_row_b.y)**2))**0.5 num_of_agents = 10 num_of_iterations = 10 neighbourhood = 20 fig = matplotlib.pyplot.figure(figsize=(7, 7)) ax = fig.add_axes([0, 0, 1, 1]) # Make the agents and connecting with the environment. agents = [] animation = matplotlib.animation.FuncAnimation(fig, update, interval=1) matplotlib.pyplot.show()
[ 11748, 2603, 29487, 8019, 198, 6759, 29487, 8019, 13, 1904, 10786, 51, 74, 46384, 11537, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 198, 11748, 5797, 30604, 198, 11748, 269, 21370, 198, 11748, 2603, 29487, 8019, 13, 11227, 341, 220, ...
2.518605
430
# Copyright (C) 2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # try: import e2e.fixtures from e2e.conftest_utils import * # noqa from e2e.conftest_utils import pytest_addoption as _e2e_pytest_addoption # noqa from e2e import config # noqa from e2e.utils import get_plugins_from_packages pytest_plugins = get_plugins_from_packages([e2e]) except ImportError: _e2e_pytest_addoption = None pass import config import pytest from ote_sdk.test_suite.pytest_insertions import * from ote_sdk.test_suite.training_tests_common import REALLIFE_USECASE_CONSTANT pytest_plugins = get_pytest_plugins_from_ote() ote_conftest_insertion(default_repository_name='ote/training_extensions/external/model-preparation-algorithm') # pytest magic def pytest_generate_tests(metafunc): ote_pytest_generate_tests_insertion(metafunc) def pytest_addoption(parser): ote_pytest_addoption_insertion(parser)
[ 2, 15069, 357, 34, 8, 33160, 8180, 10501, 201, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 201, 198, 2, 201, 198, 201, 198, 28311, 25, 201, 198, 220, 220, 220, 1330, 304, 17, 68, 13, 69, 25506, 20...
2.5
386
"""Validation for UDFs. Warning: This is an experimental module and API here can change without notice. DO NOT USE DIRECTLY. """ from inspect import Parameter, Signature, signature from typing import Any, Callable, List import ibis.common.exceptions as com from ibis.expr.datatypes import DataType def _parameter_count(funcsig: Signature) -> int: """Get the number of positional-or-keyword or position-only parameters in a function signature. Parameters ---------- funcsig : inspect.Signature A UDF signature Returns ------- int The number of parameters """ return sum( param.kind in {param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY} for param in funcsig.parameters.values() if param.default is Parameter.empty ) def validate_input_type( input_type: List[DataType], func: Callable ) -> Signature: """Check that the declared number of inputs (the length of `input_type`) and the number of inputs to `func` are equal. If the signature of `func` uses *args, then no check is done (since no check can be done). Parameters ---------- input_type : List[DataType] func : callable Returns ------- inspect.Signature """ funcsig = signature(func) params = funcsig.parameters.values() # We can only do validation if all the positional arguments are explicit # (i.e. no *args) if not any(param.kind is Parameter.VAR_POSITIONAL for param in params): declared_parameter_count = len(input_type) function_parameter_count = _parameter_count(funcsig) if declared_parameter_count != function_parameter_count: raise TypeError( 'Function signature {!r} has {:d} parameters, ' 'input_type has {:d}. These must match. Non-column ' 'parameters must be defined as keyword only, i.e., ' 'def foo(col, *, function_param).'.format( func.__name__, function_parameter_count, declared_parameter_count, ) ) return funcsig def validate_output_type(output_type: Any) -> None: """Check that the output type is a single datatype.""" if isinstance(output_type, list): raise com.IbisTypeError( 'The output type of a UDF must be a single datatype.' )
[ 37811, 7762, 24765, 329, 471, 8068, 82, 13, 198, 198, 20361, 25, 770, 318, 281, 11992, 8265, 290, 7824, 994, 460, 1487, 1231, 4003, 13, 198, 198, 18227, 5626, 23210, 42242, 11319, 13, 198, 37811, 198, 198, 6738, 10104, 1330, 25139, 23...
2.547945
949
import inspect from ariadne import make_executable_schema, QueryType, MutationType, SubscriptionType from .resolver import * # # Schema # keywords = ['query', 'mutation', 'subscription', 'source'] # This is for testing or in case you don't want a database as the root schema
[ 11748, 10104, 198, 198, 6738, 257, 21244, 710, 1330, 787, 62, 18558, 18187, 62, 15952, 2611, 11, 43301, 6030, 11, 337, 7094, 6030, 11, 3834, 33584, 6030, 198, 198, 6738, 764, 411, 14375, 1330, 1635, 198, 198, 2, 198, 2, 10011, 2611, ...
3.361446
83
import random from otp.ai.AIBase import * from direct.distributed.ClockDelta import * from toontown.battle.BattleBase import * from toontown.battle.BattleCalculatorAI import * from toontown.toonbase.ToontownBattleGlobals import * from toontown.battle.SuitBattleGlobals import * from pandac.PandaModules import * from toontown.battle import BattleExperienceAI from direct.distributed import DistributedObjectAI from direct.fsm import ClassicFSM, State from direct.fsm import State from direct.task import Task from direct.directnotify import DirectNotifyGlobal from toontown.ai import DatabaseObject from toontown.toon import DistributedToonAI from toontown.toon import InventoryBase from toontown.toonbase import ToontownGlobals from toontown.toon import NPCToons from otp.ai.MagicWordGlobal import * from toontown.pets import DistributedPetProxyAI
[ 11748, 4738, 198, 6738, 30972, 79, 13, 1872, 13, 32, 9865, 589, 1330, 1635, 198, 6738, 1277, 13, 17080, 6169, 13, 44758, 42430, 1330, 1635, 198, 6738, 284, 756, 593, 13, 38471, 13, 24064, 14881, 1330, 1635, 198, 6738, 284, 756, 593, ...
3.409639
249
# Copyright (c) Group Three-Forest SJTU. All Rights Reserved. from tracking.tracking import * # a = tracking_video_rectangle("video/","1.mp4",[[273,352],[266,616],[412,620],[416,369]]) a = tracking_video_rectangle_tovideo("video/","1.mp4", "1.png", [[273,352],[266,616],[412,620],[416,369]], result = 'result__.avi', method_num = 5, edge = 4, middle_halt = 250)
[ 2, 15069, 357, 66, 8, 4912, 7683, 12, 34605, 31766, 51, 52, 13, 1439, 6923, 33876, 13, 220, 201, 198, 201, 198, 6738, 9646, 13, 36280, 1330, 1635, 201, 198, 201, 198, 2, 257, 796, 9646, 62, 15588, 62, 2554, 9248, 7203, 15588, 14, ...
2.631206
141
import gym from gym import spaces, error, utils from gym.utils import seeding import numpy as np from scipy.spatial.distance import pdist, squareform import configparser from os import path import matplotlib.pyplot as plt from matplotlib.pyplot import gca font = {'family' : 'sans-serif', 'weight' : 'bold', 'size' : 14}
[ 11748, 11550, 198, 6738, 11550, 1330, 9029, 11, 4049, 11, 3384, 4487, 198, 6738, 11550, 13, 26791, 1330, 384, 8228, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 629, 541, 88, 13, 2777, 34961, 13, 30246, 1330, 279, 17080, 11, 6616, 6...
2.818182
121
# -*-coding:utf-8-*- # from functools import reduce from functools import reduce SANCAI_jixiang = [1, 3, 5, 7, 8, 11, 13, 15, 16, 18, 21, 23, 24, 25, 31, 32, 33, 35, 37, 39, 41, 45, 47, 48, 52, 57, 61, 63, 65, 67, 68, 81] # ,, SANCAI_xiaoji = [6, 17, 26, 27, 29, 30, 38, 49, 51, 55, 58, 71, 73, 75] # SANCAI_xiong = [2, 4, 9, 10, 12, 14, 19, 20, 22, 28, 34, 36, 40, 42, 43, 44, 46, 50, 53, 54, 56, 59, 60, 62, 64, 66, 69, 70, 72, 74, 76, 77, 78, 79, 80] # ,,,,, SANCAI_wise = [3, 13, 16, 21, 23, 29, 31, 37, 39, 41, 45, 47] # ,, SANCAI_wealth = [15, 16, 24, 29, 32, 33, 41, 52] # ,, SANCAI_artist = [13, 14, 18, 26, 29, 33, 35, 38, 48] # ,,, SANCAI_goodwife = [5, 6, 11, 13, 15, 16, 24, 32, 35] # SANCAI_death = [21, 23, 26, 28, 29, 33, 39] # SANCAI_alone = [4, 10, 12, 14, 22, 28, 34] # SANCAI_merry = [5, 6, 15, 16, 32, 39, 41] # SANCAI_stubbon = [7, 17, 18, 25, 27, 28, 37, 47] # , SANCAI_gentle = [5, 6, 11, 15, 16, 24, 31, 32, 35] # , # # refer_good_num_list = [SANCAI_jixiang, SANCAI_xiaoji, SANCAI_wise, SANCAI_wealth, SANCAI_artist, SANCAI_goodwife, SANCAI_merry, SANCAI_gentle] # good_num_list = [SANCAI_jixiang, SANCAI_xiaoji, SANCAI_wise, SANCAI_wealth, SANCAI_artist, SANCAI_goodwife, SANCAI_merry, SANCAI_gentle] # refer_bad_num_list = [SANCAI_xiong, SANCAI_death, SANCAI_alone, SANCAI_stubbon] # bad_num_list = [SANCAI_xiong, SANCAI_death, SANCAI_alone] good_num_set = set(reduce((lambda x, y: x + y), good_num_list, [])) bad_num_set = set(reduce((lambda x, y: x + y), bad_num_list, [])) print(':', good_num_set) print(':', bad_num_set) # best_num_set = [x for x in good_num_set if x not in bad_num_set] print(':', best_num_set) RESULT_UNKNOWN = ''
[ 2, 532, 9, 12, 66, 7656, 25, 40477, 12, 23, 12, 9, 12, 198, 2, 422, 1257, 310, 10141, 1330, 4646, 198, 6738, 1257, 310, 10141, 1330, 4646, 198, 36753, 8141, 40, 62, 73, 844, 15483, 796, 685, 16, 11, 513, 11, 642, 11, 767, 11, ...
1.90572
944
# Generated by Django 3.1.2 on 2020-10-18 16:07 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 17, 319, 12131, 12, 940, 12, 1507, 1467, 25, 2998, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
""" Module for reporting into http://www.blazemeter.com/ service Copyright 2015 BlazeMeter 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 copy import logging import os import platform import sys import time import traceback import zipfile from collections import defaultdict, OrderedDict from io import BytesIO from urllib.error import HTTPError import requests from bzt import TaurusInternalException, TaurusConfigError, TaurusNetworkError from bzt.bza import User, Session, Test from bzt.engine import Reporter, Singletone from bzt.utils import b, humanize_bytes, iteritems, open_browser, BetterDict, to_json, dehumanize_time from bzt.modules.aggregator import AggregatorListener, DataPoint, KPISet, ResultsProvider, ConsolidatingAggregator from bzt.modules.monitoring import Monitoring, MonitoringListener from bzt.modules.blazemeter.project_finder import ProjectFinder from bzt.modules.blazemeter.const import NOTE_SIZE_LIMIT
[ 37811, 198, 26796, 329, 6447, 656, 2638, 1378, 2503, 13, 2436, 1031, 368, 2357, 13, 785, 14, 2139, 198, 198, 15269, 1853, 33965, 44, 2357, 3457, 13, 198, 198, 26656, 15385, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, ...
3.645408
392
""" Losses that assume an underlying spatial organization (gradients, curvature, etc.) """ import torch import torch.nn as tnn from nitorch.core.pyutils import make_list, prod from nitorch.core.utils import slice_tensor from nitorch.spatial import diff1d from ._base import Loss
[ 37811, 198, 43, 793, 274, 326, 7048, 281, 10238, 21739, 4009, 198, 7, 9744, 2334, 11, 46171, 1300, 11, 3503, 2014, 198, 37811, 198, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 256, 20471, 198, 6738, 299, 2072, 354, 13, 7295,...
3.287356
87
from django.db import models from django.utils import timezone
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 26791, 1330, 640, 11340, 628, 198 ]
3.611111
18
from app.services.console import Console from app.services.server import Server __main__ = ["server", "console"]
[ 6738, 598, 13, 30416, 13, 41947, 1330, 24371, 198, 6738, 598, 13, 30416, 13, 15388, 1330, 9652, 198, 198, 834, 12417, 834, 796, 14631, 15388, 1600, 366, 41947, 8973, 198 ]
3.8
30
#!/usr/bin/env python3 # Copyright 2020 Gaitech Korea 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. # Author: Brighten Lee import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import DeclareLaunchArgument from launch.substitutions import LaunchConfiguration from launch_ros.actions import Node
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 15069, 12131, 12822, 45396, 4969, 1766, 1539, 12052, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743,...
3.865217
230
import sys import unittest import requests_mock from mock import patch sys.path.append('services/LiveService') from LiveService import LiveService L = LiveService() baseURL = "https://yanexx65s8e1.live.elementalclouddev.com/api" if __name__ == '__main__': unittest.main()
[ 11748, 25064, 198, 11748, 555, 715, 395, 198, 11748, 7007, 62, 76, 735, 198, 6738, 15290, 1330, 8529, 198, 17597, 13, 6978, 13, 33295, 10786, 30416, 14, 18947, 16177, 11537, 198, 6738, 7547, 16177, 1330, 7547, 16177, 628, 198, 198, 43, ...
2.887755
98
# -*- coding: utf-8 -*- """ Created on Fri Sep 14 11:49:10 2018 @author: Lionel Massoulard """ import pytest import numpy as np import pandas as pd from sklearn.base import is_regressor, is_classifier from sklearn.exceptions import NotFittedError from sklearn.model_selection import KFold from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import RandomForestRegressor from sklearn.linear_model import LogisticRegression, Ridge from sklearn.dummy import DummyRegressor from aikit.models.stacking import OutSamplerTransformer, StackerClassifier, StackerRegressor
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 19480, 8621, 1478, 1367, 25, 2920, 25, 940, 2864, 198, 198, 31, 9800, 25, 44286, 5674, 2852, 446, 198, 37811, 198, 198, 11748, 12972, 9288, 198, ...
3.282609
184
from django import forms from django.conf import settings from django.http import HttpResponse, HttpResponseRedirect, Http404 from manager import models as pmod from . import templater from django.conf import settings import decimal, datetime # This view will display all users and then on a new page display all the current rentals for a given user
[ 6738, 42625, 14208, 1330, 5107, 201, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 201, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 31077, 11, 367, 29281, 31077, 7738, 1060, 11, 367, 29281, 26429, 201, 198, 6738, 4706, 1330, ...
3.778947
95
import pandas as pd import numpy as np import os import logging # suppress warnings import warnings; warnings.filterwarnings('ignore'); from tqdm.autonotebook import tqdm # register `pandas.progress_apply` and `pandas.Series.map_apply` with `tqdm` tqdm.pandas() # https://pandas.pydata.org/pandas-docs/stable/user_guide/options.html#available-options # adjust pandas display pd.options.display.max_columns = 30 # default 20 pd.options.display.max_rows = 200 # default 60 pd.options.display.float_format = '{:.2f}'.format # pd.options.display.precision = 2 pd.options.display.max_colwidth = 200 # default 50; None = all # Number of array items in summary at beginning and end of each dimension # np.set_printoptions(edgeitems=3) # default 3 np.set_printoptions(suppress=True) # no scientific notation for small numbers # IPython (Jupyter) setting: # Print out every value instead of just "last_expr" (default) from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" import matplotlib as mpl from matplotlib import pyplot as plt # defaults: mpl.rcParamsDefault rc_params = {'figure.figsize': (8, 4), 'axes.labelsize': 'large', 'axes.titlesize': 'large', 'xtick.labelsize': 'large', 'ytick.labelsize': 'large', 'savefig.dpi': 100, 'figure.dpi': 100 } # adjust matplotlib defaults mpl.rcParams.update(rc_params) import seaborn as sns sns.set_style("darkgrid") # sns.set()
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 11748, 18931, 628, 198, 2, 18175, 14601, 198, 11748, 14601, 26, 198, 40539, 654, 13, 24455, 40539, 654, 10786, 46430, 24036, 198, 198, 6738, 25...
2.626943
579
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack.package import *
[ 2, 15069, 2211, 12, 1238, 1828, 13914, 45036, 3549, 2351, 4765, 11, 11419, 290, 584, 198, 2, 1338, 441, 4935, 34152, 13, 4091, 262, 1353, 12, 5715, 27975, 38162, 9947, 2393, 329, 3307, 13, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, ...
3.439394
66
""" GPA Calculator """ # Write a function called "simple_gpa" to find GPA when student enters a letter grade as a string. Assign the result to a variable called "gpa". """ Use these conversions: A+ --> 4.0 A --> 4.0 A- --> 3.7 B+ --> 3.3 B --> 3.0 B- --> 2.7 C+ --> 2.3 C --> 2.0 C- --> 1.7 D+ --> 1.3 D --> 1.0 D- --> 0.7 F --> 0.0 """
[ 37811, 198, 38, 4537, 43597, 198, 37811, 198, 198, 2, 19430, 257, 2163, 1444, 366, 36439, 62, 70, 8957, 1, 284, 1064, 45283, 618, 3710, 14170, 257, 3850, 9559, 355, 257, 4731, 13, 2195, 570, 262, 1255, 284, 257, 7885, 1444, 366, 70,...
2.394366
142
import sys import soundcard import numpy import pytest ones = numpy.ones(1024) signal = numpy.concatenate([[ones], [-ones]]).T def test_loopback_playback(loopback_player, loopback_recorder): loopback_player.play(signal) recording = loopback_recorder.record(1024*10) assert recording.shape[1] == 2 left, right = recording.T assert left.mean() > 0 assert right.mean() < 0 assert (left > 0.5).sum() == len(signal) assert (right < -0.5).sum() == len(signal) def test_loopback_reverse_recorder_channelmap(loopback_player, loopback_microphone): with loopback_microphone.recorder(48000, channels=[1, 0], blocksize=512) as loopback_recorder: loopback_player.play(signal) recording = loopback_recorder.record(1024*12) assert recording.shape[1] == 2 left, right = recording.T assert right.mean() > 0 assert left.mean() < 0 assert (right > 0.5).sum() == len(signal) assert (left < -0.5).sum() == len(signal) def test_loopback_reverse_player_channelmap(loopback_speaker, loopback_recorder): with loopback_speaker.player(48000, channels=[1, 0], blocksize=512) as loopback_player: loopback_player.play(signal) recording = loopback_recorder.record(1024*12) assert recording.shape[1] == 2 left, right = recording.T assert right.mean() > 0 assert left.mean() < 0 assert (right > 0.5).sum() == len(signal) assert (left < -0.5).sum() == len(signal) def test_loopback_mono_player_channelmap(loopback_speaker, loopback_recorder): with loopback_speaker.player(48000, channels=[0], blocksize=512) as loopback_player: loopback_player.play(signal[:,0]) recording = loopback_recorder.record(1024*12) assert recording.shape[1] == 2 left, right = recording.T assert left.mean() > 0 if sys.platform == 'linux': # unmapped channels on linux are filled with the mean of other channels assert right.mean() < left.mean() else: assert abs(right.mean()) < 0.01 # something like zero assert (left > 0.5).sum() == len(signal) def test_loopback_mono_recorder_channelmap(loopback_player, loopback_microphone): with loopback_microphone.recorder(48000, channels=[0], blocksize=512) as loopback_recorder: loopback_player.play(signal) recording = loopback_recorder.record(1024*12) assert len(recording.shape) == 1 or recording.shape[1] == 1 assert recording.mean() > 0 assert (recording > 0.5).sum() == len(signal) def test_loopback_multichannel_channelmap(loopback_speaker, loopback_microphone): with loopback_speaker.player(48000, channels=[2, 0], blocksize=512) as loopback_player: with loopback_microphone.recorder(48000, channels=[2, 0], blocksize=512) as loopback_recorder: loopback_player.play(signal) recording = loopback_recorder.record(1024*12) assert len(recording.shape) == 2 left, right = recording.T assert left.mean() > 0 assert right.mean() < 0 assert (left > 0.5).sum() == len(signal) assert (right < -0.5).sum() == len(signal)
[ 11748, 25064, 198, 11748, 2128, 9517, 198, 11748, 299, 32152, 198, 11748, 12972, 9288, 198, 198, 1952, 796, 299, 32152, 13, 1952, 7, 35500, 8, 198, 12683, 282, 796, 299, 32152, 13, 1102, 9246, 268, 378, 26933, 58, 1952, 4357, 25915, 1...
2.591443
1,192
# This is a simple program to find the last three digits of 11 raised to any given number. # The main algorithm that does the work is on line 10 # To use it, simply copy the code and run the function
[ 2, 770, 318, 257, 2829, 1430, 284, 1064, 262, 938, 1115, 19561, 286, 1367, 4376, 284, 597, 1813, 1271, 13, 198, 2, 383, 1388, 11862, 326, 857, 262, 670, 318, 319, 1627, 838, 198, 198, 2, 1675, 779, 340, 11, 2391, 4866, 262, 2438, ...
4.102041
49
#!/usr/bin/env python import time from osr_msgs.msg import Joystick, Commands, Encoder, RunStop from nav_msgs.msg import Odometry from geometry_msgs.msg import Point, Pose, Quaternion, Twist, Vector3 import rospy import tf import math import numpy if __name__ == '__main__': rospy.init_node('osr_odometry2') rospy.loginfo("Starting the osr odometry2 node") baseFrame = rospy.get_param("/odometry/base_frame_id", "base_link") # mpt = rospy.get_param("/odometry/mpt", 0.000026322) mpt = rospy.get_param("/odometry/mpt", 0.000100708) wheelTrack = rospy.get_param("/odometry/wheel_track", 0.455) d4 = rospy.get_param("/odometry/d4", 0.2559) maxTickPerSec = rospy.get_param("/odometry/maxTickPerSec", 8000) publishTF = rospy.get_param("~publishTF", False) odom = Odometry2(baseFrame, wheelTrack, mpt, d4, maxTickPerSec, pubTF=publishTF) encSub = rospy.Subscriber("/encoder", Encoder, odom.onEncoderMessage) rate = rospy.Rate(20) while not rospy.is_shutdown(): rate.sleep()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 640, 198, 6738, 267, 27891, 62, 907, 14542, 13, 19662, 1330, 14087, 13915, 11, 49505, 11, 14711, 12342, 11, 5660, 19485, 198, 6738, 6812, 62, 907, 14542, 13, 19662, 1330, 10529, ...
2.303226
465
import numpy as np import h5py import os from devito.logger import info from devito import TimeFunction, clear_cache from examples.seismic.acoustic import AcousticWaveSolver from examples.seismic import Model, RickerSource, Receiver, TimeAxis from math import floor from scipy.interpolate import griddata import argparse parser = argparse.ArgumentParser(description='') parser.add_argument('--data_path', dest='data_path', type=str, default='/home/ec2-user/data', help='raw data path') parser.add_argument('--save_dir', dest='save_dir', type=str, default='/home/ec2-user/data', help='saving directory') args = parser.parse_args() data_path = args.data_path save_dir = args.save_dir origin = (0., 0.) spacing=(7.5, 7.5) tn=1100. nbpml=40 # Define your vp in km/sec (x, z) vp = np.fromfile(os.path.join(data_path, 'vp_marmousi_bi'), dtype='float32', sep="") vp = np.reshape(vp, (1601, 401)) # vp = vp[400:1401, 0:401] shape=[401, 301] values = np.zeros([vp.shape[0]*vp.shape[1], ]) points = np.zeros([vp.shape[0]*vp.shape[1], 2]) k = 0 for indx in range(0, vp.shape[0]): for indy in range(0, vp.shape[1]): values[k] = vp[indx, indy] points[k, 0] = indx points[k, 1] = indy k = k + 1 # nx, ny = shape[0], shape[1] X, Y = np.meshgrid(np.array(np.linspace(1000, 1287, shape[0])), np.array(np.linspace(120, 232, shape[1]))) int_vp = griddata(points, values, (X, Y), method='cubic') int_vp = np.transpose(int_vp) vp = int_vp # create model model = Model(origin, spacing, shape, 2, vp, nbpml=nbpml) # Derive timestepping from model spacing dt = model.critical_dt t0 = 0.0 nt = int(1 + (tn-t0) / dt) # Number of timesteps time = np.linspace(t0, tn, nt) # Discretized time axis datasize0 = int(np.shape(range(0, shape[0], 4))[0]) datasize1 = int(np.shape(range(100, nt, 20))[0]) datasize = datasize0*datasize1 strTrainA = os.path.join(save_dir, 'Wavefield_Marmousi_pml_401x301_1000-1287_120-232_4k_20kp100_A_train.hdf5') strTrainB = os.path.join(save_dir, 'Wavefield_Marmousi_pml_401x301_1000-1287_120-232_4k_20kp100_B_train.hdf5') dataset_train = "train_dataset" file_trainA = h5py.File(strTrainA, 'w-') datasetA = file_trainA.create_dataset(dataset_train, (datasize, shape[0]+2*nbpml, shape[1]+2*nbpml)) file_trainB = h5py.File(strTrainB, 'w-') datasetB = file_trainB.create_dataset(dataset_train, (datasize, shape[0]+2*nbpml, shape[1]+2*nbpml)) num_rec = 601 rec_samp = np.linspace(0., model.domain_size[0], num=num_rec); rec_samp = rec_samp[1]-rec_samp[0] time_range = TimeAxis(start=t0, stop=tn, step=dt) src = RickerSource(name='src', grid=model.grid, f0=0.025, time_range=time_range, space_order=1, npoint=1) src.coordinates.data[0, :] = np.array([1*spacing[0], 2*spacing[1]]).astype(np.float32) rec = Receiver(name='rec', grid=model.grid, time_range=time_range, npoint=num_rec) rec.coordinates.data[:, 0] = np.linspace(0., model.domain_size[0], num=num_rec) rec.coordinates.data[:, 1:] = src.coordinates.data[0, 1:] solverbad = AcousticWaveSolver(model, source=src, receiver=rec, kernel='OT2', isic=True, space_order=2, freesurface=False) solvergood = AcousticWaveSolver(model, source=src, receiver=rec, kernel='OT2', isic=True, space_order=20, freesurface=False) ulocgood = TimeFunction(name="u", grid=model.grid, time_order=2, space_order=20, save=nt) ulocbad = TimeFunction(name="u", grid=model.grid, time_order=2, space_order=2, save=nt) kk = 0 for xsrc in range(0, shape[0], 4): clear_cache() ulocgood.data.fill(0.) ulocbad.data.fill(0.) src.coordinates.data[0, :] = np.array([xsrc*spacing[0], 2*spacing[1]]).astype(np.float32) rec.coordinates.data[:, 0] = np.linspace(0., model.domain_size[0], num=num_rec) rec.coordinates.data[:, 1:] = src.coordinates.data[0, 1:] _, ulocgood, _ = solvergood.forward(m=model.m, src=src, time=nt-1, save=True) _, ulocbad, _ = solverbad.forward(m=model.m, src=src, time=nt-1, save=True) datasetA[kk:(kk+datasize1), :, :] = np.array(ulocgood.data[range(100, nt, 20), :, :]) datasetB[kk:(kk+datasize1), :, :] = np.array(ulocbad.data[range(100, nt, 20), :, :]) kk = kk + datasize1 file_trainA.close() file_trainB.close()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 289, 20, 9078, 198, 11748, 28686, 198, 6738, 1614, 10094, 13, 6404, 1362, 1330, 7508, 198, 6738, 1614, 10094, 1330, 3862, 22203, 11, 1598, 62, 23870, 198, 6738, 6096, 13, 325, 1042, 291, 13, ...
2.29579
1,829
import math if __name__=='__main__': n=(int)(input()) for abc in range(n): t=(int)(input()) print math.factorial(t)
[ 11748, 10688, 198, 361, 11593, 3672, 834, 855, 6, 834, 12417, 834, 10354, 198, 220, 220, 220, 299, 16193, 600, 5769, 15414, 28955, 198, 220, 220, 220, 329, 450, 66, 287, 2837, 7, 77, 2599, 198, 220, 220, 220, 220, 220, 220, 220, 2...
1.925
80
from setuptools import setup setup(name="pykinematicskineticstoolbox", version="0.0", description="Installable python package which collects useful kinematics and kinetics functions", author="John Martin K. God", author_email="john.martin.kleven.godo@gmail.com", license="MIT", packages=["pykinematicskineticstoolbox"], install_requires=["numpy"], )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 40406, 7, 3672, 2625, 9078, 5116, 368, 23372, 5116, 5139, 301, 970, 3524, 1600, 198, 197, 220, 2196, 2625, 15, 13, 15, 1600, 198, 197, 220, 6764, 2625, 15798, 540, 21015, 5301, 543, 26609...
3.04918
122
from datetime import datetime # ensure an rpc peer is added # exponetially smooth online/offline states of peers
[ 6738, 4818, 8079, 1330, 4818, 8079, 628, 198, 2, 4155, 281, 374, 14751, 12720, 318, 2087, 628, 198, 2, 1033, 36823, 1927, 7209, 2691, 14, 2364, 1370, 2585, 286, 14495, 198 ]
3.774194
31
# terrascript/dns/r.py import terrascript
[ 2, 8812, 15961, 14, 67, 5907, 14, 81, 13, 9078, 198, 11748, 8812, 15961, 628, 628, 628, 628, 198 ]
2.631579
19
from Jumpscale import j from .TCPRouterClient import TCPRouterClient JSConfigs = j.baseclasses.object_config_collection
[ 6738, 449, 8142, 38765, 1330, 474, 198, 6738, 764, 4825, 4805, 39605, 11792, 1330, 17283, 4805, 39605, 11792, 198, 198, 20120, 16934, 82, 796, 474, 13, 8692, 37724, 13, 15252, 62, 11250, 62, 43681, 628 ]
3.485714
35
""" Functions for reading Magritek Spinsolve binary (dx/1d) files and parameter (acqu.par/proc.par) files. """ import os from warnings import warn import numpy as np from . import fileiobase from . import jcampdx __developer_info__ = """ Spinsolve is the software used on the Magritek benchtop NMR devices. A spectrum is saved in a folder with several files. The spectral data is stored in these files: 'data.1d' (FID), 'spectrum.1d' (Fourier transformed) and 'spectrum_processed.1d' (FT + processed by spinsolve) Optional spectral data (System->Prefs->Setup->Global data storage): 'nmr_fid.dx' (FID stored in `JCAMP-DX standard <http://www.jcamp-dx.org/>`), 'spectrum.csv' and 'spectrum_processed.csv' (FT + processed by Spinsovle with ppm for each point and intensity delimited by ';') Other files: 'acqu.par' - all parameters that are used for acquisition 'Protocol.par' - text file used to reload data back into the Spinsolve software 'processing.script' - text file to transfer Spinsolve software protocol settings into MNOVA The Spinsolve Expert software has a slightly different output: [Needs to be double checked as I do not have access to this software -LCageman] - Output into JCAMP-DX is not possible - 'spectrum_processed.1d' is not generated - (new) 'fid.1d' - seems to be the same as 'data.1d' - (new) 'proc.par' - contains processing parameters in the same style as 'acqu.par' - (new) .pt1 files - seem to be plot files specific for the expert software, cannot be read by NMRglue """ def read(dir='.', specfile=None, acqupar="acqu.par", procpar="proc.par"): """ Reads spinsolve files from a directory When no spectrum filename is given (specfile), the following list is tried, in that specific order ["nmr_fid.dx", "data.1d", "fid.1d", "spectrum.1d", "spectrum_processed.1d"] To use the resolution enhanced spectrum use the './Enhanced' folder as input. Note that spectrum.1d and spectrum_processed.1d contain only data in the frequency domain, so no Fourier transformation is needed. Also, use dic["spectrum"]["xaxis"] to plot the x-axis Parameters ---------- dir : str Directory to read from specfile : str, optional Filename to import spectral data from. None uses standard filename from: ["nmr_fid.dx", "data.1d", "fid.1d", "spectrum.1d", "spectrum_processed.1d"] acqupar : str, optional Filename for acquisition parameters. None uses standard name. procpar : str, optional Filename for processing parameters. None uses standard name. Returns ------- dic : dict All parameters that can be present in the data folder: dic["spectrum"] - First bytes of spectrum(_processed).1d dic["acqu"] - Parameters present in acqu.par dic["proc"] - Parameters present in proc.par dic["dx"] - - Parameters present in the header of nmr_fid.dx data : ndarray Array of NMR data """ if os.path.isdir(dir) is not True: raise IOError("directory %s does not exist" % (dir)) # Create empty dic dic = {"spectrum": {}, "acqu": {}, "proc":{}, "dx":{}} # Read in acqu.par and write to dic acqupar = os.path.join(dir, acqupar) if os.path.isfile(acqupar): with open(acqupar, "r") as f: info = f.readlines() for line in info: line = line.replace("\n", "") k, v = line.split("=") dic["acqu"][k.strip()] = v.strip() # Read in proc.par and write to dic procpar = os.path.join(dir,procpar) if os.path.isfile(procpar): with open(procpar, "r") as f: info = f.readlines() for line in info: line = line.replace("\n", "") k, v = line.split("=") dic["proc"][k.strip()] = v.strip() # Define which spectrumfile to take, using 'specfile' when defined, otherwise # the files in 'priority_list' are tried, in that particular order priority_list = ["nmr_fid.dx", "data.1d", "fid.1d", "spectrum.1d", "spectrum_processed.1d", None] if specfile: inputfile = os.path.join(dir, specfile) if not os.path.isfile(inputfile): raise IOError("File %s does not exist" % (inputfile)) else: for priority in priority_list: if priority == None: raise IOError("directory %s does not contain spectral data" % (dir)) inputfile = os.path.join(dir, priority) if os.path.isfile(inputfile): break # Detect which file we are dealing with from the extension and read in the spectral data # Reading .dx file using existing nmrglue.fileio.jcampdx module if inputfile.split('.')[-1] == "dx": dic["dx"], raw_data = jcampdx.read(inputfile) data = np.empty((int(dic["dx"]["$TD"][0]), ), dtype='complex128') data = raw_data[0][:] + 1j * raw_data[1][:] # Reading .1d files elif inputfile.split('.')[-1] == "1d": with open(inputfile, "rb") as f: raw_data = f.read() # Write out parameters from the first 32 bytes into dic["spectrum"] keys = ["owner", "format", "version", "dataType", "xDim", "yDim", "zDim", "qDim"] for i, k in enumerate(keys): start = i * 4 end = start + 4 value = int.from_bytes( raw_data[start:end], "little") dic["spectrum"][k] = value data = np.frombuffer(raw_data[end:], "<f") # The first 1/3 of the file is xaxis data (s or ppm) split = data.shape[-1] // 3 xscale = data[0 : split] dic["spectrum"]["xaxis"] = xscale # The rest is real and imaginary data points interleaved data = data[split : : 2] + 1j * data[split + 1 : : 2] else: raise IOError("File %s cannot be interpreted, use .dx or .1d instead" % (inputfile)) return dic,data def guess_udic(dic,data): """ Guess parameters of universal dictionary from dic, data pair. Parameters ---------- dic : dict Dictionary of JCAMP-DX, acqu, proc and spectrum parameters. data : ndarray Array of NMR data. Returns ------- udic : dict Universal dictionary of spectral parameters. """ # Create an empty universal dictionary udic = fileiobase.create_blank_udic(1) # Update defalt parameters, first acqu.par parameters in dic are tried, then JCAMP-DX header parameters # size if data is not None: udic[0]["size"] = len(data) else: warn('No data, cannot set udic size') # sw try: udic[0]['sw'] = float(dic['acqu']['bandwidth']) * 1000 except KeyError: try: udic[0]['sw'] = float(dic['dx']['$SW'][0]) * float(dic['dx']['$BF1'][0]) except KeyError: try: if dic["spectrum"]["freqdata"]: udic[0]['sw'] = dic["spectrum"]["xaxis"][-1] - dic["spectrum"]["xaxis"][0] elif data is not None: udic[0]['sw'] = len(data) / dic["spectrum"]["xaxis"][-1] else: warn("Cannot set spectral width - set manually using: 'udic[0]['sw'] = x' where x is the spectral width in Hz") except KeyError: warn("Cannot set spectral width - set manually using: 'udic[0]['sw'] = x' where x is the spectral width in Hz") # obs try: udic[0]['obs'] = float(dic['acqu']['b1Freq']) except KeyError: try: udic[0]['obs'] = float(dic['dx']['$BF1'][0]) except KeyError: warn("Cannot set observe frequency - set manually using: 'udic[0]['obs'] = x' where x is magnetic field in MHz") # car try: udic[0]['car'] = float(dic['acqu']['lowestFrequency']) + (float(dic['acqu']['bandwidth']) * 1000 / 2) except KeyError: try: udic[0]['car'] = (float(dic['dx']['$REFERENCEPOINT'][0]) * -1 ) + (float(dic['dx']['$SW'][0]) * udic[0]['obs'] / 2) except KeyError: try: udic[0]['car'] = (float(dic['dx']['$BF1'][0]) - float(dic['dx']['$SF'][0])) * 1000000 except KeyError: warn("Cannot set carrier - try: 'udic[0]['car'] = x * udic[0]['obs']' where x is the center of the spectrum in ppm") # label try: udic[0]['label'] = dic['acqu']['rxChannel'] except KeyError: try: label_value = dic['dx'][".OBSERVENUCLEUS"][0].replace("^", "") udic[0]["label"] = label_value except KeyError: warn("Cannot set observed nucleus label") #keys left to default # udic[0]['complex'] # udic[0]['encoding'] # udic[0]['time'] = True # udic[0]['freq'] = False return udic
[ 37811, 198, 24629, 2733, 329, 3555, 2944, 6525, 74, 1338, 1040, 6442, 13934, 357, 34350, 14, 16, 67, 8, 3696, 290, 220, 198, 17143, 2357, 357, 43561, 13, 1845, 14, 36942, 13, 1845, 8, 3696, 13, 198, 37811, 198, 198, 11748, 28686, 19...
2.32247
3,805
import logging import copy import pickle import pandas as pd
[ 11748, 18931, 198, 11748, 4866, 198, 11748, 2298, 293, 198, 11748, 19798, 292, 355, 279, 67, 628, 628, 198 ]
3.421053
19
import sys import scipy.stats normal = scipy.stats.norm(0, 1)
[ 11748, 25064, 198, 198, 11748, 629, 541, 88, 13, 34242, 198, 198, 11265, 796, 629, 541, 88, 13, 34242, 13, 27237, 7, 15, 11, 352, 8, 628, 628, 628, 198 ]
2.333333
30
# -*- coding: utf-8 -*- # # Graph : graph package # # Copyright or Copr. 2006 INRIA - CIRAD - INRA # # File author(s): Jerome Chopard <jerome.chopard@sophia.inria.fr> # # Distributed under the Cecill-C License. # See accompanying file LICENSE.txt or copy at # http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.html # # VPlants WebSite : https://gforge.inria.fr/projects/vplants/ # """This module provide a simple pure python implementation for a graph interface does not implement copy concept """ from id_dict import IdDict
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 220, 220, 220, 220, 220, 220, 29681, 1058, 4823, 5301, 198, 2, 198, 2, 220, 220, 220, 220, 220, 220, 15069, 393, 6955, 81, 13, 4793, 3268, 49, 3539, 532...
2.466102
236
import paddle.fluid as fluid from paddle.fluid.initializer import MSRA from paddle.fluid.param_attr import ParamAttr if __name__ == '__main__': data = fluid.data(name='data', shape=[None, 3, 300, 300]) build_ssd(data, 21, img_shape=[3, 300, 300])
[ 11748, 39517, 13, 35522, 312, 355, 11711, 198, 6738, 39517, 13, 35522, 312, 13, 36733, 7509, 1330, 6579, 3861, 198, 6738, 39517, 13, 35522, 312, 13, 17143, 62, 35226, 1330, 25139, 8086, 81, 628, 628, 198, 361, 11593, 3672, 834, 6624, ...
2.755319
94
""" Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import unittest import os import random import cv2 import numpy as np import oneflow as flow import oneflow.typing as oft if __name__ == "__main__": unittest.main()
[ 37811, 198, 15269, 12131, 383, 1881, 37535, 46665, 13, 1439, 2489, 10395, 13, 198, 198, 26656, 15385, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 5832, 743, 407, 779, 428, 2393, 2845, 287, 11846, ...
3.610329
213
#! /usr/bin/env python3 import json import os.path import jinja2 DEFAULT_PARAMS = { "ansible_user": "vagrant" } if __name__ == "__main__": # Reading configuration here = os.path.dirname(os.path.realpath(__file__ + "/../")) with open(here + "/config.json", "r") as rf: config = json.load(rf) print(json.dumps(config, sort_keys=True, indent=4)) # Generating an inventory file with open(here + "/playbook/inventory/hosts", "w") as inventory: inventory.write("[kafka]\n") for host in config["hosts"]: # Setting default values and updating them when more specific. params = dict() params.update(DEFAULT_PARAMS) params.update(config["params"]) params.update(config["hosts"][host]) # Setting some extra ansible paramters. params["ansible_ssh_host"] = params["ip"] inventory.write("%s\t%s\n" % (host, " ".join(("%s=%s" % (k,v) for k,v in params.items())))) # Generating the Vagrantfile env = jinja2.Environment(loader=jinja2.FileSystemLoader(here + "/templates/")) template = env.get_template('Vagrantfile.j2') template.stream(**config).dump(here + '/vagrant/Vagrantfile') # Generating group vars for kafka with open(here + "/playbook/group_vars/kafka.yml", "w") as gv: gv.write("---\n") gv.write("hosts:\n") for (host, params) in config["hosts"].items(): gv.write(" %s: '%s.%s'\n" % (params["ip"], params["hostname"], config["params"]["domain" ])) gv.write("kafka:\n") gv.write(" hosts:\n") for (host, params) in config["hosts"].items(): gv.write(" - %s.%s\n" % (params["hostname"], config["params"]["domain" ]))
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 18, 628, 198, 11748, 33918, 198, 11748, 28686, 13, 6978, 198, 198, 11748, 474, 259, 6592, 17, 628, 198, 7206, 38865, 62, 27082, 40834, 796, 1391, 198, 220, 220, 220, 366, 504, 856, 62, ...
2.242386
788
import os import harvest.dataframe from harvest.models.simulator import Simulator
[ 11748, 28686, 198, 198, 11748, 13222, 13, 7890, 14535, 198, 6738, 13222, 13, 27530, 13, 14323, 8927, 1330, 13942, 198 ]
4.15
20
# pylint: skip-file import os from assimilator import * from Boinc import boinc_project_path if __name__ == "__main__": SlimeClustersAssimilator().run()
[ 2, 279, 2645, 600, 25, 14267, 12, 7753, 198, 198, 11748, 28686, 198, 6738, 36659, 1352, 1330, 1635, 198, 6738, 3248, 1939, 1330, 1489, 1939, 62, 16302, 62, 6978, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, ...
2.925926
54
# Licensed to Modin Development Team under one or more contributor license agreements. # See the NOTICE file distributed with this work for additional information regarding # copyright ownership. The Modin Development Team licenses this file to you 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. """Module houses class that implements ``PandasOnRayDataframe`` class using cuDF.""" import numpy as np import ray from ..partitioning.partition import cuDFOnRayDataframePartition from ..partitioning.partition_manager import cuDFOnRayDataframePartitionManager from modin.core.execution.ray.implementations.pandas_on_ray.dataframe.dataframe import ( PandasOnRayDataframe, ) from modin.error_message import ErrorMessage
[ 2, 49962, 284, 3401, 259, 7712, 4816, 739, 530, 393, 517, 18920, 5964, 11704, 13, 198, 2, 4091, 262, 28536, 2393, 9387, 351, 428, 670, 329, 3224, 1321, 5115, 198, 2, 6634, 9238, 13, 220, 383, 3401, 259, 7712, 4816, 16625, 428, 2393,...
3.9
310
from astropy.table import Table, Column import matplotlib.pyplot as plt #url = "https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI?table=exoplanets&select=pl_hostname,ra,dec&order=dec&format=csv" url = "https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI?table=exoplanets" # This API returns Hostname, RA and Dec t = Table.read(url, format="csv") t_b = t[t["pl_letter"] == "b"] t_c = t[t["pl_letter"] == "c"] t_d = t[t["pl_letter"] == "d"] t_e = t[t["pl_letter"] == "e"] t_f = t[t["pl_letter"] == "f"] t_g = t[t["pl_letter"] == "g"] t_h = t[t["pl_letter"] == "h"] t_i = t[t["pl_letter"] == "i"] fig = plt.figure() ax = fig.add_subplot(1,1,1,aspect="equal") ax.scatter(t_b["ra"],t_b["dec"],color="Black",label = "2 Planets") ax.scatter(t_c["ra"],t_c["dec"],color="red", label = "3 Planets") ax.scatter(t_d["ra"],t_d["dec"],color="blue", label = "4 Planets") ax.scatter(t_e["ra"],t_e["dec"],color="green", label = "5 Planets") ax.scatter(t_f["ra"],t_f["dec"],color="yellow", label = "6 Planets") ax.scatter(t_g["ra"],t_g["dec"],color="purple", label = "7 Planets") ax.scatter(t_h["ra"],t_h["dec"],color="orange", label = "8 Planets") ax.scatter(t_i["ra"],t_i["dec"],color="cyan", label = "9 Planets") ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) ax.set_xlim(360,0) ax.set_ylim(-90,90) ax.set_ylabel("DEC") ax.set_xlabel("RA") ax.set_title("Positions of Explanets by number of planets in system") plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.show()
[ 6738, 6468, 28338, 13, 11487, 1330, 8655, 11, 29201, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 2, 6371, 796, 366, 5450, 1378, 1069, 46853, 316, 17474, 13, 541, 330, 13, 9948, 13670, 13, 15532, 14, 37157, 12, ...
2.248895
679
from tools import factorial if __name__ == '__main__': solve()
[ 6738, 4899, 1330, 1109, 5132, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 8494, 3419, 198 ]
2.8
25
# Copyright 2022. ThingsBoard # # 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 threading import Thread from time import sleep, time from queue import Queue from random import choice from string import ascii_lowercase from thingsboard_gateway.tb_utility.tb_utility import TBUtility # Try import Pymodbus library or install it and import try: from pymodbus.constants import Defaults except ImportError: print("Modbus library not found - installing...") TBUtility.install_package("pymodbus", ">=2.3.0") TBUtility.install_package('pyserial') from pymodbus.constants import Defaults try: from twisted.internet import reactor except ImportError: TBUtility.install_package('twisted') from twisted.internet import reactor from twisted.internet import reactor from pymodbus.bit_write_message import WriteSingleCoilResponse, WriteMultipleCoilsResponse from pymodbus.register_write_message import WriteMultipleRegistersResponse, WriteSingleRegisterResponse from pymodbus.register_read_message import ReadRegistersResponseBase from pymodbus.bit_read_message import ReadBitsResponseBase from pymodbus.client.sync import ModbusTcpClient, ModbusUdpClient, ModbusSerialClient from pymodbus.client.sync import ModbusRtuFramer, ModbusSocketFramer, ModbusAsciiFramer from pymodbus.exceptions import ConnectionException from pymodbus.server.asynchronous import StartTcpServer, StartUdpServer, StartSerialServer, StopServer from pymodbus.device import ModbusDeviceIdentification from pymodbus.version import version from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext from pymodbus.datastore import ModbusSparseDataBlock from thingsboard_gateway.connectors.connector import Connector, log from thingsboard_gateway.connectors.modbus.constants import * from thingsboard_gateway.connectors.modbus.slave import Slave from thingsboard_gateway.connectors.modbus.backward_compability_adapter import BackwardCompatibilityAdapter from thingsboard_gateway.connectors.modbus.bytes_modbus_downlink_converter import BytesModbusDownlinkConverter CONVERTED_DATA_SECTIONS = [ATTRIBUTES_PARAMETER, TELEMETRY_PARAMETER] FRAMER_TYPE = { 'rtu': ModbusRtuFramer, 'socket': ModbusSocketFramer, 'ascii': ModbusAsciiFramer } SLAVE_TYPE = { 'tcp': StartTcpServer, 'udp': StartUdpServer, 'serial': StartSerialServer } FUNCTION_TYPE = { 'coils_initializer': 'co', 'holding_registers': 'hr', 'input_registers': 'ir', 'discrete_inputs': 'di' } FUNCTION_CODE_WRITE = { 'holding_registers': (6, 16), 'coils_initializer': (5, 15) } FUNCTION_CODE_READ = { 'holding_registers': 3, 'coils_initializer': 1, 'input_registers': 4, 'discrete_inputs': 2 }
[ 2, 220, 220, 220, 220, 15069, 33160, 13, 11597, 29828, 198, 2, 198, 2, 220, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 220, 220, 220, 220, 345, 743, 407, 779, 428, ...
3.078376
1,059
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. ### CONTROLS (non-tunable) ### # general TYPE_OF_RUN = test_episodes # train, test, test_episodes, render NUM_EPISODES_TO_TEST = 1000 MIN_FINAL_REWARD_FOR_SUCCESS = 1.0 LOAD_MODEL_FROM = models/gru_flat_babyai.pth SAVE_MODELS_TO = None # worker.py ENV = BabyAI_Env ENV_RANDOM_SEED = 1 AGENT_RANDOM_SEED = 1 REPORTING_INTERVAL = 1 TOTAL_STEPS = 1 ANNEAL_LR = False # A3cAgent AGENT_NET = GRU_Network # BabyAI_Env BABYAI_ENV_LEVEL = BabyAI-GoToLocal-v0 USE_SUCCESS_RATE = True SUCCESS_RATE_THRESHOLD = 0.99 HELDOUT_TESTING = False NUM_TEST_EPISODES = 10000 OBS_ENCODER = Flat BINARY_REWARD = True ### HYPERPARAMETERS (tunable) ### # A3cAgent A3C_T_MAX = 4 LEARNING_RATE = 4e-05 DISCOUNT_FACTOR = 0.9 GRADIENT_CLIP = 512.0 ENTROPY_TERM_STRENGTH = 0.02 ADAM_EPS = 1e-12 REWARD_SCALE = 2.0 WEIGHT_DECAY = 0. # RNNs NUM_RNN_UNITS = 96 OBS_EMBED_SIZE = 512 AC_HIDDEN_LAYER_SIZE = 4096
[ 2, 15069, 357, 66, 8, 5413, 10501, 13, 198, 2, 49962, 739, 262, 17168, 5964, 13, 198, 198, 21017, 220, 49833, 50, 220, 357, 13159, 12, 28286, 540, 8, 220, 44386, 198, 198, 2, 2276, 198, 25216, 62, 19238, 62, 49, 4944, 796, 1332, ...
2.13245
453
"""runghc support""" load(":private/context.bzl", "render_env") load(":private/packages.bzl", "expose_packages", "pkg_info_to_compile_flags") load( ":private/path_utils.bzl", "link_libraries", "ln", "target_unique_name", ) load( ":private/set.bzl", "set", ) load(":providers.bzl", "get_ghci_extra_libs") load("@bazel_skylib//lib:shell.bzl", "shell") def build_haskell_runghc( hs, runghc_wrapper, user_compile_flags, extra_args, hs_info, cc_info, output, package_databases, version, lib_info = None): """Build runghc script. Args: hs: Haskell context. hs_info: HaskellInfo. package_databases: package caches excluding the cache file of the package we're creating a runghc for. lib_info: If we're building runghc for a library target, pass HaskellLibraryInfo here, otherwise it should be None. Returns: None. """ (pkg_info_inputs, args) = pkg_info_to_compile_flags( hs, pkg_info = expose_packages( package_ids = hs.package_ids, package_databases = package_databases, version = version, ), prefix = "runghc-", ) if lib_info != None: for idir in set.to_list(hs_info.import_dirs): args += ["-i{0}".format(idir)] (ghci_extra_libs, ghc_env) = get_ghci_extra_libs( hs, cc_info, path_prefix = "$RULES_HASKELL_EXEC_ROOT", ) link_libraries(ghci_extra_libs, args) runghc_file = hs.actions.declare_file(target_unique_name(hs, "runghc")) # Extra arguments. # `compiler flags` is the default set of arguments for runghc, # augmented by `extra_args`. # The ordering is important, first compiler flags (from toolchain # and local rule), then from `extra_args`. This way the more # specific arguments are listed last, and then have more priority in # GHC. # Note that most flags for GHCI do have their negative value, so a # negative flag in `extra_args` can disable a positive flag set # in `user_compile_flags`, such as `-XNoOverloadedStrings` will disable # `-XOverloadedStrings`. args += hs.toolchain.compiler_flags + user_compile_flags + hs.toolchain.repl_ghci_args # ghc args need to be wrapped up in "--ghc-arg=" when passing to runghc runcompile_flags = ["--ghc-arg=%s" % a for a in args] runcompile_flags += extra_args hs.actions.expand_template( template = runghc_wrapper, output = runghc_file, substitutions = { "{ENV}": render_env(ghc_env), "{TOOL}": hs.tools.runghc.path, "{CC}": hs.toolchain.cc_wrapper.executable.path, "{ARGS}": " ".join([shell.quote(a) for a in runcompile_flags]), }, is_executable = True, ) # XXX We create a symlink here because we need to force # hs.tools.runghc and the best way to do that is # to use hs.actions.run. That action, in turn must produce # a result, so using ln seems to be the only sane choice. extra_inputs = depset(transitive = [ depset([ hs.tools.runghc, runghc_file, ]), package_databases, pkg_info_inputs, ghci_extra_libs, hs_info.source_files, hs.toolchain.cc_wrapper.runfiles.files, ]) ln(hs, runghc_file, output, extra_inputs)
[ 37811, 5143, 456, 66, 1104, 37811, 198, 198, 2220, 7, 1298, 19734, 14, 22866, 13, 65, 48274, 1600, 366, 13287, 62, 24330, 4943, 198, 2220, 7, 1298, 19734, 14, 43789, 13, 65, 48274, 1600, 366, 1069, 3455, 62, 43789, 1600, 366, 35339, ...
2.204315
1,576
# Copyright (C) 2019 Cancer Care Associates # 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 os import subprocess import uuid import numpy as np import pydicom from pymedphys._dicom.create import dicom_dataset_from_dict from pymedphys._dicom.header import ( RED_adjustment_map_from_structure_names, adjust_machine_name, adjust_RED_by_structure_name, adjust_rel_elec_density, ) from pymedphys._dicom.utilities import remove_file HERE = os.path.dirname(__file__) ORIGINAL_DICOM_FILENAME = os.path.join( HERE, "scratch", "original-{}.dcm".format(str(uuid.uuid4())) ) ADJUSTED_DICOM_FILENAME = os.path.join( HERE, "scratch", "adjusted-{}.dcm".format(str(uuid.uuid4())) )
[ 2, 15069, 357, 34, 8, 13130, 15523, 7276, 29306, 198, 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.963054
406
"""Test data validator decorator.""" from unittest.mock import Mock from aiohttp import web import voluptuous as vol from homeassistant.components.http import HomeAssistantView from homeassistant.components.http.data_validator import RequestDataValidator
[ 37811, 14402, 1366, 4938, 1352, 11705, 1352, 526, 15931, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 44123, 198, 198, 6738, 257, 952, 4023, 1330, 3992, 198, 11748, 2322, 37623, 5623, 355, 2322, 198, 198, 6738, 1363, 562, 10167, 13, 5...
3.661972
71
import days STAGE_INIT = 0 STAGE_CHALLENGE_INIT = 1 STAGE_BOOKED = 2 messages = [ "Hey {{first_name}}, thankyou for your enquiry to be one of our Transformation Challengers", "We have 2 Challenges available for you:\n\nThe 8 Week Bikini Challenge which helps you shed 3-9kg of unwanted body fat, flattens your tummy and tones your arms, abs, legs and butt.\n\nOr our 9in6 Challenge which helps you drop 9+kgs of pure fat in just 6 Weeks.", "Please choose which challenge information you would like below..." ] callbacks = { "INIT_8WBC" : [ { "type": "message", "text" : "Thank you {{first_name}},\n\ The FREE 8 Week Bikini Challenge is a done for you - step by step PROVEN program that helps you lose the 3-7kg of unwanted body fat, flatten your tummy and tone your arms, legs and butt.\n\ \n\ This is your chance to transform your body in just 8 weeks for FREE" }, { "type" : "message", "text" : "In exchange for the program being FREE....we ask that you allow us to share your transformation story on our Facebook fan page for marketing purposes to help motivate and inspire the ladies of Perth. \n\ (Please note, a small refundable deposit applies to keep you motivated throughout the 8 weeks)" }, { "type": "message", "text": "The challenge is starting Monday 12th of June and to start your 8 Week Bikini Challenge, we just require you to attend the upcoming information meeting at the facility to quickly go over the program in person. \n\ \n\ There is absolutely no high pressure sales or obligation to join. Simply a meet and chat.\n\ \n\ To RSVP to the meeting click a suitable date below" }, { "type" : "json", "template" : "init_8wbc" } ], "INIT_9IN6" : [ { "type" : "message", "text" : "Thank you {{first_name}},\n\ The 9in6 Transformation Challenge is a done for you - step by step PROVEN program that helps you lose 9kg kilos of unwanted body fat, flatten your tummy and tone your arms, legs and butt in just 6 weeks.\n\ \ \nThis is your chance to transform your body in just 6 weeks for FREE!" }, { "type" : "message", "text" : "In exchange for the program, we ask that you allow us to showcase your transformation story on our Facebook fan page for marketing purposes to help motivate and inspire the ladies of Perth. When you complete the program its FREE. \n\ Please note, a small refundable \"incentive deposit\" applies to keep you motivated throughout the 6 weeks." }, { "type" : "message", "text" : "The challenge is starting Monday 12th of June and to start your 9kg 6-week challenge, we require you to attend the upcoming information meeting where we explain the program in person. \n\ \n\ There is absolutely no high pressure sales or obligation to join at the end, just an opportunity for you learn about the program and how you can lose 9kg in 6 weeks for FREE\n\ \n\ To RSVP to the meeting click a suitable date below" }, { "type" : "json", "template" : "init_9in6" } ], "TIME_TABLE_8WBC" : [ { "type" : "message", "text" : "Sure here's our lesson time table.." }, { "type" : "file", "url" : "http://thetransformationcentre.com.au/img/timetable.pdf" }, { "type" : "json", "template" : "init_8wbc" } ] }
[ 11748, 1528, 198, 198, 2257, 11879, 62, 1268, 2043, 796, 657, 198, 2257, 11879, 62, 3398, 7036, 1677, 8264, 62, 1268, 2043, 796, 352, 198, 2257, 11879, 62, 39453, 1961, 796, 362, 198, 198, 37348, 1095, 796, 685, 198, 220, 220, 220, ...
2.591292
1,424
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack.package import *
[ 2, 15069, 2211, 12, 1238, 1828, 13914, 45036, 3549, 2351, 4765, 11, 11419, 290, 584, 198, 2, 1338, 441, 4935, 34152, 13, 4091, 262, 1353, 12, 5715, 27975, 38162, 9947, 2393, 329, 3307, 13, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, ...
3.439394
66
#!/usr/bin/env python3 import os, sys, re, json, requests, datetime, tarfile, argparse from pprint import pprint import numpy as np from utils.UrlUtils import UrlUtils server = 'https://qc.sentinel1.eo.esa.int/' cal_re = re.compile(r'S1\w_AUX_CAL') def cmdLineParse(): ''' Command line parser. ''' parser = argparse.ArgumentParser(description='Fetch calibration auxiliary files ingested into HySDS') parser.add_argument('-o', '--output', dest='outdir', type=str, default='.', help='Path to output directory') parser.add_argument('-d', '--dry-run', dest='dry_run', action='store_true', help="Don't download anything; just output the URLs") return parser.parse_args() def download_file(url, outdir='.', session=None): ''' Download file to specified directory. ''' if session is None: session = requests.session() path = "%s.tgz" % os.path.join(outdir, os.path.basename(url)) print('Downloading URL: ', url) request = session.get(url, stream=True, verify=False) request.raise_for_status() with open(path,'wb') as f: for chunk in request.iter_content(chunk_size=1024): if chunk: f.write(chunk) f.flush() return path def untar_file(path, outdir): ''' Extract aux cal files. ''' if not tarfile.is_tarfile(path): raise RuntimeError("%s is not a tarfile." % path) with tarfile.open(path) as f: f.extractall(outdir) def get_active_ids(es_url): """Query for the active calibration IDs.""" query = { "query":{ "bool":{ "must":[ {"term":{"_id": "S1_AUX_CAL_ACTIVE"}}, ] } }, "sort":[ { "starttime": { "order": "desc" } } ] } es_index = "grq_*_s1-aux_cal_active" if es_url.endswith('/'): search_url = '%s%s/_search' % (es_url, es_index) else: search_url = '%s/%s/_search' % (es_url, es_index) r = requests.post(search_url, data=json.dumps(query)) if r.status_code == 200: result = r.json() #pprint(result) total = result['hits']['total'] if total == 0: raise RuntimeError("Failed to find S1_AUX_CAL_ACTIVE at %s." % search_url) return result['hits']['hits'][0]['_source']['metadata']['active_ids'] else: print("Failed to query %s:\n%s" % (es_url, r.text), file=sys.stderr) print("query: %s" % json.dumps(query, indent=2), file=sys.stderr) print("returned: %s" % r.text, file=sys.stderr) r.raise_for_status() def get_cal_url(id, es_url): """Query for the active calibration url.""" query = { "query":{ "bool":{ "must":[ {"term":{"_id": id}}, ] } }, "fields": ["urls", "metadata.archive_filename"] } es_index = "grq_*_s1-aux_cal" if es_url.endswith('/'): search_url = '%s%s/_search' % (es_url, es_index) else: search_url = '%s/%s/_search' % (es_url, es_index) r = requests.post(search_url, data=json.dumps(query)) if r.status_code == 200: result = r.json() pprint(result) total = result['hits']['total'] if total == 0: raise RuntimeError("Failed to find %s at %s." % (id, search_url)) urls = result['hits']['hits'][0]['fields']['urls'] archive_fname = result['hits']['hits'][0]['fields']['metadata.archive_filename'][0] url = [x for x in urls if x.startswith('http')][0] #print(urls) #print(url) #print(archive_fname) return os.path.join(url, archive_fname) else: print("Failed to query %s:\n%s" % (es_url, r.text), file=sys.stderr) print("query: %s" % json.dumps(query, indent=2), file=sys.stderr) print("returned: %s" % r.text, file=sys.stderr) r.raise_for_status() if __name__ == '__main__': inps = cmdLineParse() fetch(inps.outdir, inps.dry_run)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 28686, 11, 25064, 11, 302, 11, 33918, 11, 7007, 11, 4818, 8079, 11, 13422, 7753, 11, 1822, 29572, 198, 6738, 279, 4798, 1330, 279, 4798, 198, 11748, 299, 32152, 355, 45941, ...
2.083845
1,956
# Copyright 2005-2008, James Garrison # Copyright 2010, 2012 Bradley M. Kuhn # This software's license gives you freedom; you can copy, convey, # propagate, redistribute, modify and/or redistribute modified versions of # this program under the terms of the GNU Affero General Public License # (AGPL) as published by the Free Software Foundation (FSF), either # version 3 of the License, or (at your option) any later version of the # AGPL published by the FSF. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero # General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program in a file in the toplevel directory called # "AGPLv3". If not, see <http://www.gnu.org/licenses/>. from django.conf.urls import url, include from django.contrib import admin, admindocs from conservancy import feeds, frontpage, sponsors import conservancy.apps.fundgoal.views as fundgoal_views import conservancy.static.views as static_views admin.autodiscover() urlpatterns = [ url(r'^$', frontpage.view), url(r'^sponsors$', frontpage.view), url(r'^sponsors/$', sponsors.view), url(r'^sponsors/index.html$', sponsors.view), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', admin.site.urls), url(r'^feeds/blog/?$', feeds.BlogFeed()), url(r'^feeds/news/?$', feeds.PressReleaseFeed()), url(r'^feeds/omnibus/?$', feeds.OmnibusFeed()), url(r'^feeds/?$', feeds.view), url(r'^news(/|$)', include('conservancy.apps.news.urls')), url(r'^blog(/|$)', include('conservancy.apps.blog.urls')), # formerly static templated things... (dirs with templates) url(r'^error/(40[134]|500)(?:/index\.html|/|)$', static_views.handler), url(r'^error', static_views.index), url(r'^about', static_views.index), url(r'^donate', static_views.index), url(r'^copyleft-compliance', static_views.index, {'fundraiser_sought' : 'vmware-match-0'}), url(r'^projects', static_views.index), url(r'^npoacct', static_views.index, {'fundraiser_sought' : 'npoacct'}), url(r'^contractpatch', include('conservancy.apps.contractpatch.urls')), url(r'^overview', static_views.index), url(r'^privacy-policy', static_views.index), url(r'^supporter', include('conservancy.apps.supporter.urls')), url(r'^fundraiser_data', fundgoal_views.view), ]
[ 2, 15069, 5075, 12, 11528, 11, 3700, 39233, 198, 2, 15069, 3050, 11, 2321, 16182, 337, 13, 46035, 77, 198, 198, 2, 770, 3788, 338, 5964, 3607, 345, 4925, 26, 345, 460, 4866, 11, 13878, 11, 198, 2, 47933, 11, 17678, 4163, 11, 13096...
2.734952
947
import unittest from unittest.mock import Mock from graphene import Schema from graphene.test import Client from graphene_spike.query import Query
[ 11748, 555, 715, 395, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 44123, 198, 198, 6738, 42463, 1330, 10011, 2611, 198, 6738, 42463, 13, 9288, 1330, 20985, 198, 198, 6738, 42463, 62, 2777, 522, 13, 22766, 1330, 43301, 628 ]
3.75
40
from rich import print from rich.console import Console from rich.table import Table import click from click_default_group import DefaultGroup import yaml import os ##from terminaltables import SingleTable import sys from textwrap import wrap import collections import datetime import configparser import pkg_resources # part of setuptools VERSION = pkg_resources.require("clikan")[0].version pass_config = click.make_pass_decorator(Config, ensure=True) def read_config(ctx, param, value): """Callback that is used whenever --config is passed. We use this to always load the correct config. This means that the config is loaded even if the group itself never executes so our aliases stay always available. """ cfg = ctx.ensure_object(Config) if value is None: value = os.path.join(os.path.dirname(__file__), 'aliases.ini') cfg.read_config(value) return value def read_data(config): """Read the existing data from the config datasource""" try: with open(config["clikan_data"], 'r') as stream: try: return yaml.load(stream, Loader=yaml.FullLoader) except yaml.YAMLError as exc: print("Ensure %s exists, as you specified it " "as the clikan data file." % config['clikan_data']) print(exc) except IOError: click.echo("No data, initializing data file.") write_data(config, {"data": {}, "deleted": {}}) with open(config["clikan_data"], 'r') as stream: return yaml.load(stream, Loader=yaml.FullLoader) def write_data(config, data): """Write the data to the config datasource""" with open(config["clikan_data"], 'w') as outfile: yaml.dump(data, outfile, default_flow_style=False) def read_config_yaml(): """Read the app config from ~/.clikan.yaml""" try: home = get_clikan_home() with open(home + "/.clikan.yaml", 'r') as stream: try: return yaml.load(stream, Loader=yaml.FullLoader) except yaml.YAMLError: print("Ensure %s/.clikan.yaml is valid, expected YAML." % home) sys.exit() except IOError: print("Ensure %s/.clikan.yaml exists and is valid." % home) sys.exit()
[ 6738, 5527, 1330, 3601, 198, 6738, 5527, 13, 41947, 1330, 24371, 198, 6738, 5527, 13, 11487, 1330, 8655, 198, 11748, 3904, 198, 6738, 3904, 62, 12286, 62, 8094, 1330, 15161, 13247, 198, 11748, 331, 43695, 198, 11748, 28686, 198, 2235, 6...
2.487097
930
from social_core.backends.oauth import BaseOAuth2
[ 6738, 1919, 62, 7295, 13, 1891, 2412, 13, 12162, 1071, 1330, 7308, 23621, 1071, 17, 628 ]
3.1875
16
from django.db import models from django.contrib import admin
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 628, 198 ]
3.555556
18
#!/usr/bin/env python # license removed for brevity import rospy from std_msgs.msg import String from gazebo_msgs.msg import LinkState if __name__ == '__main__': try: talker() except rospy.ROSInterruptException: pass
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 5964, 4615, 329, 1449, 21319, 198, 198, 11748, 686, 2777, 88, 198, 6738, 14367, 62, 907, 14542, 13, 19662, 1330, 10903, 198, 6738, 308, 1031, 1765, 78, 62, 907, 14542, 13, 19662, ...
2.464646
99
import torch from os import listdir, path from PIL import Image import torchvision
[ 11748, 28034, 198, 6738, 28686, 1330, 1351, 15908, 11, 3108, 198, 6738, 350, 4146, 1330, 7412, 198, 11748, 28034, 10178, 628 ]
4
21
from django.core.mail.message import EmailMessage, EmailMultiAlternatives from django.utils.translation import ugettext_lazy as _ from django.template.loader import render_to_string from django.utils.safestring import mark_safe
[ 6738, 42625, 14208, 13, 7295, 13, 4529, 13, 20500, 1330, 9570, 12837, 11, 9570, 29800, 23081, 2929, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 334, 1136, 5239, 62, 75, 12582, 355, 4808, 198, 6738, 42625, 14208, 13, 28243, 13, ...
3.59375
64
"""Tests for the HAPServer.""" from socket import timeout from unittest.mock import Mock, MagicMock, patch import pytest from pyhap import hap_server
[ 37811, 51, 3558, 329, 262, 367, 2969, 10697, 526, 15931, 198, 6738, 17802, 1330, 26827, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 44123, 11, 6139, 44, 735, 11, 8529, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 12972, 45897, 1330,...
3.255319
47
from flask import render_template, Blueprint, request from app.utils.search import MySQLClient from app.utils.preprocessor import TextPreprocessor mainbp = Blueprint("main", __name__)
[ 6738, 42903, 1330, 8543, 62, 28243, 11, 39932, 11, 2581, 198, 198, 6738, 598, 13, 26791, 13, 12947, 1330, 33476, 11792, 198, 6738, 598, 13, 26791, 13, 3866, 41341, 1330, 8255, 6719, 41341, 628, 198, 12417, 46583, 796, 39932, 7203, 12417...
3.897959
49
# -*- coding: utf-8 -*- """This module contains design algorithm for a traditional two stage operational amplifier.""" from typing import TYPE_CHECKING, List, Optional, Dict, Any, Tuple, Sequence from copy import deepcopy import numpy as np import scipy.optimize as sciopt from bag.math import gcd from bag.data.lti import LTICircuit, get_stability_margins, get_w_crossings, get_w_3db from bag.util.search import FloatBinaryIterator, BinaryIterator, minimize_cost_golden from bag.simulation.core import MeasurementManager from verification.mos.query import MOSDBDiscrete from .components import LoadDiodePFB, InputGm if TYPE_CHECKING: from verification.ac.core import ACTB
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 1212, 8265, 4909, 1486, 11862, 329, 257, 4569, 734, 3800, 13919, 33382, 526, 15931, 198, 198, 6738, 19720, 1330, 41876, 62, 50084, 2751, 11, 7343, 11, 32233, ...
3.280952
210
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import *
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 33918, 198, 198, 6738, 435, 541, 323, 13, 64, 404, 13, 15042, 13, 9979, 415, 13, 22973, 34184, 1187, 1330, 163...
2.446809
47
import torch from torchaudio_unittest.common_utils import PytorchTestCase from torchaudio_unittest.models.emformer.emformer_test_impl import EmformerTestImpl
[ 11748, 28034, 198, 6738, 28034, 24051, 62, 403, 715, 395, 13, 11321, 62, 26791, 1330, 9485, 13165, 354, 14402, 20448, 198, 6738, 28034, 24051, 62, 403, 715, 395, 13, 27530, 13, 368, 16354, 13, 368, 16354, 62, 9288, 62, 23928, 1330, 22...
3.404255
47
""" Two pipelines: * full history * update latest season * Only updates latest season year """ from functools import partial import itertools from kedro.pipeline import Pipeline, node from nba_analysis.pipelines.data_processing import basketball_reference from . import nodes
[ 37811, 198, 7571, 31108, 25, 198, 9, 1336, 2106, 198, 9, 4296, 3452, 1622, 198, 220, 220, 220, 1635, 5514, 5992, 3452, 1622, 614, 198, 37811, 628, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 11748, 340, 861, 10141, 198, 6738, 479, ...
3.653846
78
# Created by BaiJiFeiLong@gmail.com at 2022/1/21 17:13 import typing from IceSpringRealOptional.typingUtils import gg from PySide2 import QtWidgets, QtCore from IceSpringMusicPlayer import tt from IceSpringMusicPlayer.common.pluginMixin import PluginMixin from IceSpringMusicPlayer.common.pluginWidgetMixin import PluginWidgetMixin from IceSpringMusicPlayer.tt import Text
[ 2, 15622, 416, 40750, 41, 72, 14304, 72, 14617, 31, 14816, 13, 785, 379, 33160, 14, 16, 14, 2481, 1596, 25, 1485, 198, 198, 11748, 19720, 198, 198, 6738, 6663, 30387, 15633, 30719, 13, 774, 13886, 18274, 4487, 1330, 308, 70, 198, 67...
3.458716
109
""" An implementation on spherical harmonics in python becasue scipy.special.sph_harm in scipy<=0.13 is very slow Originally written by Jozef Vesely https://github.com/scipy/scipy/issues/1280 """ import numpy as np if __name__ == "__main__": from scipy.special import sph_harm from scipy.misc import factorial2, factorial from timeit import Timer print "Time: xfact(10)", Timer("xfact(10)", "from __main__ import xfact, ref_xfact").timeit(100) print "Time: ref_xfact(10)", Timer("ref_xfact(10)", "from __main__ import xfact, ref_xfact").timeit(100) print "Time: xfact(80)", Timer("xfact(80)", "from __main__ import xfact, ref_xfact").timeit(100) print "Time: ref_xfact(80)", Timer("ref_xfact(80)", "from __main__ import xfact, ref_xfact").timeit(100) print "m", "xfact", "ref_xfact" for m in range(10) + range(80,90): a = xfact(m) b = ref_xfact(m) print m, a, b phi, theta = np.ogrid[0:2*np.pi:10j,-np.pi/2:np.pi/2:10j] print "Time: Ylm(1,1,phi,theta)", Timer("Ylm(1,1,phi,theta)", "from __main__ import Ylm, sph_harm, phi, theta").timeit(10) print "Time: sph_harm(1,1,phi,theta)", Timer("sph_harm(1,1,phi,theta)", "from __main__ import Ylm, sph_harm, phi, theta").timeit(10) print "l", "m", "max|Ylm-sph_harm|" for l in xrange(0,10): for m in xrange(-l,l+1): a = Ylm(l,m,phi,theta) b = sph_harm(m,l,phi,theta) print l,m, np.amax(np.abs(a-b))
[ 37811, 198, 2025, 7822, 319, 43180, 25625, 873, 287, 21015, 639, 292, 518, 629, 541, 88, 13, 20887, 13, 82, 746, 62, 29155, 287, 629, 541, 88, 27, 28, 15, 13, 1485, 318, 845, 3105, 198, 198, 22731, 3194, 416, 5302, 89, 891, 569, ...
2.037086
755
#!/usr/bin/env python # coding: utf-8 # In[9]: import requests import pandas as pd from lxml import etree from bs4 import BeautifulSoup import datetime import io import numpy as np from alphacast import Alphacast from dotenv import dotenv_values API_KEY = dotenv_values(".env").get("API_KEY") alphacast = Alphacast(API_KEY) # In[10]: url1 = "https://www.estadisticaciudad.gob.ar/eyc/wp-content/uploads/2020/11/Eoh_PnoA_0811.xlsx" df1 = pd.read_excel(url1) df1[:2] = df1[:2].ffill(1) df1.columns = "Personal No Asalariado - " + df1.iloc[1] + " - " + df1.iloc[2] df1 = df1.drop(df1.columns[[1]], axis = 1) df1 = df1.drop(index=1) df1 = df1.drop(index=0) df1 = df1.drop(index=2) df1 = df1.dropna(subset = [df1.columns[3]]) #df1 = df1.iloc[2: , 3:-2] #df1 = df1[~df1.iloc[:, 0].astype(str).str.isdigit()] df1 = df1[df1.columns.dropna()] df1.index = pd.date_range(start='1/1/2008', periods=len(df1), freq = "QS") df1.index.name = "Date" #df1 = df1[df1.columns.drop(list(df1.filter(regex='Participacin')))] df1 # In[11]: url2 = "https://www.estadisticaciudad.gob.ar/eyc/wp-content/uploads/2018/05/Eoh_PA_0811.xlsx" df2 = pd.read_excel(url2) df2[:2] = df2[:2].ffill(1) df2.columns = "Personal Asalariado - " + df2.iloc[1] + " - " + df2.iloc[2] df2 = df2.drop(df2.columns[[1]], axis = 1) df2 = df2.drop(index=1) df2 = df2.drop(index=0) df2 = df2.drop(index=2) df2 = df2.dropna(subset = [df2.columns[3]]) #df2 = df2.iloc[2: , 3:-2] #df2 = df2[~df2.iloc[:, 0].astype(str).str.isdigit()] df2 = df2[df2.columns.dropna()] df2.index = pd.date_range(start='1/1/2008', periods=len(df2), freq = "QS") df2.index.name = "Date" df3 = df1.merge(df2, right_index=True, left_index=True) alphacast.datasets.dataset(7432).upload_data_from_df(df3, deleteMissingFromDB = True, onConflictUpdateDB = True, uploadIndex=True)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 554, 58, 24, 5974, 628, 198, 11748, 7007, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 300, 19875, 1330, 2123, 631, 198, 6738, 275,...
2.078857
875
# import the GED using the munkres algorithm import gmatch4py as gm import networkx as nx import collections import csv import pickle from collections import OrderedDict import json import concurrent.futures as cf import time iter = 0 ''' def runParallelCode(pairList): with cf.ProcessPoolExecutor(max_workers =2) as executor: try: for future in cf.as_completed((executor.map(getGraphDiff, pairList, timeout=5000000)), timeout=5000000): print(str(type(future.result()))) if str(type(future.result())) == "<class 'NoneType'>": pass else: print(future.result(timeout=5000000)) except cf._base.TimeoutError: print("Time limit exceeded") pass ''' if __name__ == '__main__': start_time = time.time() main() print("--- %s seconds ---" % (time.time() - start_time))
[ 198, 2, 1330, 262, 402, 1961, 1262, 262, 285, 2954, 411, 11862, 198, 11748, 308, 15699, 19, 9078, 355, 308, 76, 198, 11748, 3127, 87, 355, 299, 87, 220, 198, 11748, 17268, 198, 11748, 269, 21370, 198, 11748, 2298, 293, 198, 6738, 17...
2.358779
393
# -*- coding: utf-8 -*- # Copyright 2011 Takeshi KOMIYA # # 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 os from hashlib import sha1 from docutils import nodes import blockdiag.parser import blockdiag.builder import blockdiag.drawer
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 220, 15069, 2813, 33687, 5303, 509, 2662, 40, 44947, 198, 2, 198, 2, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, ...
3.467593
216
# -*- coding: utf-8 -*- """ Created on Thu Dec 19 20:00:00 2019 @author: Emilia Chojak @e-mail: emilia.chojak@gmail.com """ tax_dict = { 'Pan troglodytes' : 'Hominoidea', 'Pongo abelii' : 'Hominoidea', 'Hominoidea' : 'Simiiformes', 'Simiiformes' : 'Haplorrhini', 'Tarsius tarsier' : 'Tarsiiformes', 'Haplorrhini' : 'Primates', 'Tarsiiformes' : 'Haplorrhini', 'Loris tardigradus' : 'Lorisidae', 'Lorisidae' : 'Strepsirrhini', 'Strepsirrhini' : 'Primates', 'Allocebus trichotis' : 'Lemuriformes', 'Lemuriformes' : 'Strepsirrhini', 'Galago alleni' : 'Lorisiformes', 'Lorisiformes' : 'Strepsirrhini', 'Galago moholi' : 'Lorisiformes' } print(last_common_ancestor(find_ancestors_for_many(["Galago alleni", "Galago moholi"])))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 26223, 4280, 678, 1160, 25, 405, 25, 405, 13130, 198, 198, 31, 9800, 25, 2295, 17517, 10031, 73, 461, 198, 31, 68, 12, 4529, 25, 795, 17517, ...
2.216463
328
import csv # with open('./1.csv', newline='', encoding='utf-8') as f: # reader = csv.reader(f) # for row in reader: # print(row) with open('./1.csv', 'a', encoding='utf-8') as f: writer = csv.writer(f) writer.writerow(['4', '', '25', '1022', '886']) writer.writerow(['5', '', '18', '2234', '3121'])
[ 11748, 269, 21370, 198, 198, 2, 351, 1280, 7, 4458, 14, 16, 13, 40664, 3256, 649, 1370, 11639, 3256, 21004, 11639, 40477, 12, 23, 11537, 355, 277, 25, 198, 2, 220, 220, 220, 220, 9173, 796, 269, 21370, 13, 46862, 7, 69, 8, 198, ...
2.108974
156
"""This module contains code for parsing RPC responses.""" from dataclasses import dataclass, field from typing import Union, Tuple, Any, Dict, List, Optional, Literal from apischema import alias from apischema.conversions import as_str from solana.publickey import PublicKey from solana.transaction import TransactionSignature as_str(PublicKey) TransactionErrorResult = Optional[dict] SlotsUpdatesItem = Union[FirstShredReceived, Completed, CreatedBank, Frozen, Dead, OptimisticConfirmation, Root] SubscriptionNotification = Union[ AccountNotification, LogsNotification, ProgramNotification, SignatureNotification, SlotNotification, RootNotification, SlotsUpdatesNotification, VoteNotification, ]
[ 37811, 1212, 8265, 4909, 2438, 329, 32096, 39400, 9109, 526, 15931, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 11, 2214, 198, 6738, 19720, 1330, 4479, 11, 309, 29291, 11, 4377, 11, 360, 713, 11, 7343, 11, 32233, 11, 25659, 1...
3.333333
231
"""Build a binary min heap object.""" from math import floor
[ 37811, 15580, 257, 13934, 949, 24575, 2134, 526, 15931, 198, 6738, 10688, 1330, 4314, 628 ]
4.133333
15
""" Vesper archive settings. The Vesper server serves the Vesper archive that is in the directory in which the server starts. The archive settings are the composition of a set of default settings (hard-coded in this module) and settings (optionally) specified in the file "Archive Settings.yaml" in the archive directory. """ from pathlib import Path import os import sys from vesper.util.settings import Settings from vesper.util.settings_type import SettingsType import vesper.archive_paths as archive_paths _DEFAULT_SETTINGS = Settings.create_from_yaml(''' database: engine: SQLite ''') _SETTINGS_TYPE = SettingsType('Archive Settings', _DEFAULT_SETTINGS) _SETTINGS_FILE_NAME = 'Archive Settings.yaml' archive_settings = _create_settings()
[ 37811, 198, 53, 274, 525, 15424, 6460, 13, 198, 198, 464, 36448, 525, 4382, 9179, 262, 36448, 525, 15424, 326, 318, 287, 262, 8619, 198, 259, 543, 262, 4382, 4940, 13, 383, 15424, 6460, 389, 262, 11742, 198, 1659, 257, 900, 286, 427...
3.300429
233
#-*- coding=utf-8 -*- from __future__ import division, print_function, absolute_import from base_model import BaseModel from helper import * import tensorflow as tf import pickle import numpy as np import time
[ 2, 12, 9, 12, 19617, 28, 40477, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 7297, 11, 3601, 62, 8818, 11, 4112, 62, 11748, 198, 198, 6738, 2779, 62, 19849, 1330, 7308, 17633, 198, 6738, 31904, 1330, 1635, 198, 11748, 1...
3.419355
62
import subprocess from LEGEND import tbot as bot from LEGEND import tbot as borg from LEGEND.events import register from LEGEND import OWNER_ID, SUDO_USERS import asyncio import traceback import io import os import sys import time from telethon.tl import functions from telethon.tl import types from telethon.tl.types import * from telethon.errors import *
[ 11748, 850, 14681, 198, 6738, 20978, 10619, 1330, 256, 13645, 355, 10214, 198, 6738, 20978, 10619, 1330, 256, 13645, 355, 275, 2398, 198, 6738, 20978, 10619, 13, 31534, 1330, 7881, 198, 6738, 20978, 10619, 1330, 47210, 21479, 62, 2389, 11...
3.386792
106
# Status: Being ported by Steven Watanabe # Base revision: 47077 # # Copyright (c) 2005 Reece H. Dunn. # Copyright 2006 Ilya Sokolov # Copyright (c) 2008 Steven Watanabe # # Use, modification and distribution is subject to the Boost Software # License Version 1.0. (See accompanying file LICENSE_1_0.txt or # http://www.boost.org/LICENSE_1_0.txt) ##### Using Precompiled Headers (Quick Guide) ##### # # Make precompiled mypch.hpp: # # import pch ; # # cpp-pch mypch # : # sources # mypch.hpp # : # requiremnts # <toolset>msvc:<source>mypch.cpp # ; # # Add cpp-pch to sources: # # exe hello # : main.cpp hello.cpp mypch # ; from b2.build import type, feature, generators from b2.tools import builtin type.register('PCH', ['pch']) type.register('C_PCH', [], 'PCH') type.register('CPP_PCH', [], 'PCH') # Control precompiled header (PCH) generation. feature.feature('pch', ['on', 'off'], ['propagated']) feature.feature('pch-header', [], ['free', 'dependency']) feature.feature('pch-file', [], ['free', 'dependency']) # NOTE: requirements are empty, default pch generator can be applied when # pch=off. generators.register(builtin.DummyGenerator( "pch.default-c-pch-generator", False, [], ['C_PCH'], [])) generators.register(builtin.DummyGenerator( "pch.default-cpp-pch-generator", False, [], ['CPP_PCH'], []))
[ 2, 12678, 25, 11204, 49702, 416, 8239, 12242, 272, 11231, 198, 2, 7308, 18440, 25, 38634, 3324, 198, 2, 198, 2, 15069, 357, 66, 8, 5075, 29030, 344, 367, 13, 30833, 13, 198, 2, 15069, 4793, 49804, 64, 37641, 349, 709, 198, 2, 1506...
2.436522
575
import re from typing import Dict from aiohttp import web from yarl import URL from simcore_service_webserver.db_models import UserRole, UserStatus from simcore_service_webserver.login.cfg import cfg, get_storage from simcore_service_webserver.login.registration import create_invitation from simcore_service_webserver.login.utils import encrypt_password, get_random_string from .utils_assert import assert_status TEST_MARKS = re.compile(r"TEST (\w+):(.*)") def parse_test_marks(text): """Checs for marks as TEST name:123123 TEST link:some-value """ marks = {} for m in TEST_MARKS.finditer(text): key, value = m.groups() marks[key] = value.strip() return marks class NewUser: def __init__(self, params=None, app: web.Application = None): self.params = params self.user = None self.db = get_storage(app) if app else cfg.STORAGE # FIXME:
[ 11748, 302, 198, 6738, 19720, 1330, 360, 713, 198, 198, 6738, 257, 952, 4023, 1330, 3992, 198, 6738, 331, 7063, 1330, 10289, 198, 198, 6738, 985, 7295, 62, 15271, 62, 732, 1443, 18497, 13, 9945, 62, 27530, 1330, 11787, 47445, 11, 1178...
2.66763
346
from indra import sparser xml_str1 = ''' <article pmid="54321"> <interpretation> <sentence-text>MEK1 phosphorylates ERK1</sentence-text> <sem> <ref category="phosphorylate"> <var name="agent"> <ref category="protein"> <var name="name">MP2K1_HUMAN</var> <var name="uid">UP:MP2K1_HUMAN</var> </ref> </var> <var name="substrate"> <ref category="protein"> <var name="name">MK03_HUMAN</var> <var name="uid">UP:MK03_HUMAN</var> </ref> </var> <var name="present"><ref category="present"></ref></var> </ref> </sem> </interpretation> </article> ''' xml_str2 = ''' <article pmid="12345"> <interpretation> <sentence-text>Hence ASPP2 can be phosphorylated at serine 827 by MAPK1 in vitro</sentence-text> <sem> <ref category="phosphorylate"> <var name="subordinate-conjunction"> <ref category="subordinate-conjunction"><var name="word">hence</var></ref></var> <var name="substrate"> <ref category="protein"> <var name="name">ASPP2_HUMAN</var> <var name="uid">UP:ASPP2_HUMAN</var> </ref> </var> <var name="agent"> <ref category="protein"> <var name="context"> <ref category="in-vitro"></ref> </var> <var name="uid">UP:MK01_HUMAN</var> <var name="name">MK01_HUMAN</var> </ref> </var> <var name="site"> <ref category="residue-on-protein"> <var name="amino-acid"> <ref category="amino-acid"><var name="name">serine</var></ref> </var> <var name="position"> 827</var> </ref> </var> <var name="modal"><ref category="can"></ref></var> </ref> </sem> </interpretation> </article> '''
[ 6738, 773, 430, 1330, 599, 28198, 198, 198, 19875, 62, 2536, 16, 796, 705, 7061, 198, 27, 20205, 9114, 312, 2625, 20, 3559, 2481, 5320, 198, 1279, 27381, 341, 29, 198, 1279, 34086, 594, 12, 5239, 29, 11682, 42, 16, 18431, 652, 75, ...
1.998929
934
""" Simple Example using coreali to access a register model. Needs no h^ardware""" # Import dependencies and compile register model with systemrdl-compiler from systemrdl import RDLCompiler import coreali import numpy as np import os from coreali import RegisterModel rdlc = RDLCompiler() rdlc.compile_file(os.path.dirname(__file__)+"/../systemrdl/logger.rdl") root = rdlc.elaborate() # Generate hierarchical register model rio = coreali.registerio.RegIoNoHW(np.zeros([256], np.uint8())) logger = RegisterModel(root, rio) # Use the generated register model logger.Ctrl.read() logger.LogMem.write(0,[1,2,3]) logger.LogMem.read() logger.LogMem[1].write(0,[11,12,13]) print(logger)
[ 37811, 17427, 17934, 1262, 4755, 7344, 284, 1895, 257, 7881, 2746, 13, 36557, 645, 289, 61, 446, 1574, 37811, 198, 198, 2, 17267, 20086, 290, 17632, 7881, 2746, 351, 1080, 4372, 75, 12, 5589, 5329, 198, 6738, 1080, 4372, 75, 1330, 314...
2.878151
238
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import os import re from abc import ABC, ABCMeta, abstractmethod from dataclasses import dataclass from typing import ( TYPE_CHECKING, Dict, Iterable, Iterator, List, Optional, Sequence, Tuple, Union, cast, ) from pants.engine.fs import PathGlobs from pants.engine.objects import Collection from pants.option.custom_types import GlobExpansionConjunction from pants.option.global_options import GlobMatchErrorBehavior from pants.util.collections import assert_single_element from pants.util.dirutil import fast_relpath_optional, recursive_dirname from pants.util.filtering import create_filters, wrap_filters from pants.util.memo import memoized_property from pants.util.meta import frozen_after_init if TYPE_CHECKING: from pants.engine.mapper import AddressFamily, AddressMapper _specificity = { SingleAddress: 0, SiblingAddresses: 1, AscendantAddresses: 2, DescendantAddresses: 3, type(None): 99 } def more_specific( address_spec1: Optional[AddressSpec], address_spec2: Optional[AddressSpec] ) -> AddressSpec: """Returns which of the two specs is more specific. This is useful when a target matches multiple specs, and we want to associate it with the "most specific" one, which will make the most intuitive sense to the user. """ # Note that if either of spec1 or spec2 is None, the other will be returned. if address_spec1 is None and address_spec2 is None: raise ValueError('internal error: both specs provided to more_specific() were None') return cast( AddressSpec, address_spec1 if _specificity[type(address_spec1)] < _specificity[type(address_spec2)] else address_spec2 ) class FilesystemSpec(Spec, metaclass=ABCMeta): pass class FilesystemSpecs(Collection[FilesystemSpec]): def path_globs_for_spec( self, spec: Union[FilesystemLiteralSpec, FilesystemGlobSpec] ) -> PathGlobs: """Generate PathGlobs for the specific spec, automatically including the instance's FilesystemIgnoreSpecs. """ return self._generate_path_globs(specs=(spec, *self.ignores)) def to_path_globs(self) -> PathGlobs: """Generate a single PathGlobs for the instance.""" return self._generate_path_globs(specs=(*self.includes, *self.ignores)) class AmbiguousSpecs(Exception): pass
[ 2, 15069, 1946, 41689, 1628, 20420, 357, 3826, 27342, 9865, 3843, 20673, 13, 9132, 737, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 3826, 38559, 24290, 737, 198, 198, 11748, 28686, 198, 11748, 302, 198, 6738, 4...
3.25
744
import json import requests from enum import Enum from typing import Dict from ..exceptions import JsonDecodeError, UnexpectedResponse, RequestError, BaseApiRequestError # - # - - # , GET/POST def _handle_errors(self, token): """ , """ token = self.get_mine_error_part(token) if token == self.ERRORS.ERROR_TOKEN.value: raise BaseApiRequestError() elif token == self.ERRORS.BAD_CODE_400_TOKEN.value: self.raise_coded_error(400) elif token == self.ERRORS.BAD_CODE_401_TOKEN.value: self.raise_coded_error(401) elif token == self.ERRORS.BAD_CODE_403_TOKEN.value: self.raise_coded_error(403) elif token == self.ERRORS.BAD_CODE_404_TOKEN.value: self.raise_coded_error(404) def _mock_token_handler(self, token: str, list_object=False): """ """ self._handle_errors(token) if list_object: return requests.Response(), self.get_list_object_on_success(token) else: return requests.Response(), self.get_object_on_success(token)
[ 11748, 33918, 198, 11748, 7007, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 19720, 1330, 360, 713, 198, 6738, 11485, 1069, 11755, 1330, 449, 1559, 10707, 1098, 12331, 11, 471, 42072, 31077, 11, 19390, 12331, 11, 7308, 32, 14415, 18453, ...
2.099822
561
# -*- coding: utf-8 -*- # The MIT License (MIT) - Copyright (c) 2016-2021 Dave Vandenbout. import pytest from skidl import netlist_to_skidl from .setup_teardown import get_filename, setup_function, teardown_function
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 383, 17168, 13789, 357, 36393, 8, 532, 15069, 357, 66, 8, 1584, 12, 1238, 2481, 9935, 35464, 268, 65, 448, 13, 198, 198, 11748, 12972, 9288, 198, 198, 6738, ...
2.728395
81
#!/usr/bin/env python3 import ST7735 import sys st7735 = ST7735.ST7735( port=0, cs=1, dc=9, backlight=12, rotation=270, spi_speed_hz=10000000 ) # Reset the display st7735.begin() st7735.reset() st7735.set_backlight(0) print "\nDone." # Exit cleanly sys.exit(0)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 3563, 3324, 2327, 198, 11748, 25064, 198, 198, 301, 3324, 2327, 796, 3563, 3324, 2327, 13, 2257, 3324, 2327, 7, 198, 220, 220, 220, 2493, 28, 15, 11, 198, 220, 220, ...
2.049296
142
from geopy.geocoders import Nominatim from requests.models import LocationParseError geolocator = Nominatim(user_agent="geoapiExercises") Latitude = 25.594095 Longitude = 85.137566 location(Latitude, Longitude) # Display
[ 198, 6738, 4903, 11081, 13, 469, 420, 375, 364, 1330, 399, 6351, 265, 320, 198, 6738, 7007, 13, 27530, 1330, 13397, 10044, 325, 12331, 198, 198, 469, 349, 420, 1352, 796, 399, 6351, 265, 320, 7, 7220, 62, 25781, 2625, 469, 78, 15042...
2.825
80
import random from tkinter import PhotoImage """ Esse arquivo define os estados do game """ def ia_chocer(): """IA faz a escolha de um numero aleatrio""" posibility = ['rock', 'paper', 'scissor'] value = posibility[random.randint(0, 2)] return value
[ 11748, 4738, 198, 6738, 256, 74, 3849, 1330, 5555, 5159, 628, 198, 37811, 198, 23041, 325, 610, 421, 23593, 8160, 28686, 1556, 22484, 466, 983, 198, 198, 37811, 628, 198, 4299, 220, 544, 62, 354, 420, 263, 33529, 198, 220, 220, 220, ...
2.660377
106
from filelock import FileLock, Timeout import os import time
[ 6738, 2393, 5354, 1330, 9220, 25392, 11, 3862, 448, 201, 198, 11748, 28686, 201, 198, 11748, 640, 201, 198, 201, 198, 201, 198 ]
2.956522
23
#from . import context #from . import test_NNModels #from . import test_data_extract #from . import test_speedcom #from . import test_utilities
[ 2, 6738, 764, 1330, 4732, 198, 2, 6738, 764, 1330, 1332, 62, 6144, 5841, 1424, 198, 2, 6738, 764, 1330, 1332, 62, 7890, 62, 2302, 974, 198, 2, 6738, 764, 1330, 1332, 62, 12287, 785, 198, 2, 6738, 764, 1330, 1332, 62, 315, 2410, ...
3.2
45
# Django REST Framework from rest_framework import serializers # Model from todo.management.models import Task # Utils from todo.utils.tasks import TaskMetrics from todo.utils.serializer_fields import CompleteNameUser
[ 2, 37770, 30617, 25161, 198, 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 198, 2, 9104, 198, 6738, 284, 4598, 13, 27604, 13, 27530, 1330, 15941, 198, 198, 2, 7273, 4487, 198, 6738, 284, 4598, 13, 26791, 13, 83, 6791, 1330, 15941, ...
3.683333
60
import numpy as np import pandas as pd from sklearn.decomposition import PCA ''' A function that detects outliers, where k is a tandard deviation threshold hyperparameter preferablly (2, 2.5, 3). The algo could handle multivariable data frames with any number of features d. For that manner, it first reduces the dimensionality to 2 using PCA, makes sure that the matrix is positive definite and calculates the Mahalanobis Distance with a threshold value. Returns a series of n rows back. ''' # https://www.youtube.com/watch?v=spNpfmWZBmg&t=0s # Check that matrix is positive definite
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 1341, 35720, 13, 12501, 296, 9150, 1330, 4217, 32, 198, 198, 7061, 6, 198, 32, 2163, 326, 39382, 41528, 3183, 11, 810, 479, 318, 257, 256, 392, 446, 288...
3.575758
165
# included from snippets/main.py # tests T1 = """ 4 3 2 """ TEST_T1 = """ >>> as_input(T1) >>> main() 4 """ T2 = """ 1 2 3 """ TEST_T2 = """ >>> as_input(T2) >>> main() 1 """ T3 = """ 3141592 6535897 9323846 """ TEST_T3 = """ >>> as_input(T3) >>> main() 2 """ T4 = """ 2 10 1 """ TEST_T4 = """ >>> as_input(T4) >>> main() 4 """ T5 = """ 2 20 1 """ TEST_T5 = """ >>> as_input(T5) >>> main() 6 """ def as_input(s): "use in test, use given string as input file" import io f = io.StringIO(s.strip()) g = globals() g["input"] = lambda: bytes(f.readline(), "ascii") g["read"] = lambda: bytes(f.read(), "ascii") if __name__ == "__main__": import sys input = sys.stdin.buffer.readline read = sys.stdin.buffer.read sys.setrecursionlimit(10 ** 6) if sys.argv[-1] == "-t": print("testing") _test() sys.exit() main() sys.exit() # end of snippets/main.py
[ 2, 3017, 422, 45114, 14, 12417, 13, 9078, 628, 628, 198, 2, 5254, 198, 51, 16, 796, 37227, 198, 19, 513, 362, 198, 37811, 198, 51, 6465, 62, 51, 16, 796, 37227, 198, 33409, 355, 62, 15414, 7, 51, 16, 8, 198, 33409, 1388, 3419, ...
2.106576
441
ezan = { 'name': 'ezan', 'age': 18, 'hair': 'brown', 'cool': True , } print(ezan) ezan = Person( name = "ezan", age = 18, hair = "black", cool = True, hungry = False) print(ezan.name) print('I am hungry') Austin = Person(name = 'austin', age = 18, hair = "Shrek", cool = False, hungry = True)
[ 8471, 272, 796, 1391, 198, 220, 220, 220, 705, 3672, 10354, 705, 8471, 272, 3256, 198, 220, 220, 220, 705, 496, 10354, 1248, 11, 628, 220, 220, 220, 705, 27108, 10354, 705, 33282, 3256, 198, 220, 220, 220, 705, 24494, 10354, 6407, 8...
2.415385
130
# 62. # yanghui = [[0 for i in range(202)] for j in range(202)]
[ 2, 8190, 13, 220, 198, 2, 220, 198, 198, 4121, 456, 9019, 796, 16410, 15, 329, 1312, 287, 2837, 7, 19004, 15437, 329, 474, 287, 2837, 7, 19004, 15437, 198 ]
2.233333
30