content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
""" Press run above to start """ from exercises.question_runner import run from question_directory import ( boolean_operators, boolean_review, changing_lists, dictionaries, equality_and_booleans, for_loops, functions, functions_quick_review, greater_than_less_than_and_booleans, inbuilt_functions_and_operators, indexing_lists, variables_equality_and_booleans, while_loops, ) from unit_tests.test_instructor_code import * # noqa if input("\n\nPress enter to start\n") != "test": # LESSON ONE # https://kathrinschuler.github.io/slide-python-intro/#/10/3 run(equality_and_booleans.TASKS, equality_and_booleans.BLURB) run(greater_than_less_than_and_booleans.TASKS, greater_than_less_than_and_booleans.BLURB) # https://kathrinschuler.github.io/slide-python-intro/#/11/4 run(variables_equality_and_booleans.TASKS, variables_equality_and_booleans.BLURB) run(boolean_operators.TASKS, boolean_operators.BLURB) # LESSON TWO run(inbuilt_functions_and_operators.TASKS, inbuilt_functions_and_operators.BLURB) # LESSON THREE # https://kathrinschuler.github.io/slide-python-intro/#/25/4 run(boolean_review.TASKS, boolean_review.BLURB) run(while_loops.TASKS, while_loops.BLURB) run(for_loops.TASKS, for_loops.BLURB) run(functions.TASKS, functions.BLURB) # LESSON FOUR run(indexing_lists.TASKS, indexing_lists.BLURB) run(functions_quick_review.TASKS, functions_quick_review.BLURB) run(changing_lists.TASKS, changing_lists.BLURB) run(dictionaries.TASKS, dictionaries.BLURB) else: if __name__ == "__main__": unittest.main() # noqa
[ 37811, 198, 13800, 1057, 2029, 284, 923, 198, 37811, 198, 198, 6738, 13565, 13, 25652, 62, 16737, 1330, 1057, 198, 6738, 1808, 62, 34945, 1330, 357, 198, 220, 220, 220, 25131, 62, 3575, 2024, 11, 198, 220, 220, 220, 25131, 62, 19023, ...
2.320334
718
import os
[ 11748, 28686, 198 ]
3.333333
3
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- import os for path, subdirs, files in os.walk('.'): for name in files: file_path = os.path.join(path, name) if file_path.endswith(".py") and "devops_sdk" in file_path: print('removing comments from ' + file_path) remove_comment_from_file(file_path)
[ 2, 16529, 1783, 10541, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 5964, 1321, 13, 198, 2, 16529, 1783, 10541, 198,...
3.621469
177
""" .. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from __future__ import print_function import ast import sys import xml.etree.ElementTree as ET from datetime import datetime import requests from sqlalchemy import create_engine, Table, MetaData, func, or_ from sqlalchemy.orm import sessionmaker from base import * # setup config config_path = sys.argv[1] with open(config_path) as configfile: config = ast.literal_eval(configfile.read()) tony_assembly = config["tony_assembly"] results_dir = config ["results_dir"] udocker_root = config["udocker_root"] toil_dir = config["toil_dir"] workflow_dir = config["workflow_dir"] log_dir = config["log_dir"] registry = config["registry"] def xml_download(ena_accession): """ pulling xml record from ENA :param ena_accession: :return: """ try: xml = ET.fromstring(requests.get("https://www.ebi.ac.uk/ena/data/view/{}&display=xml".format(ena_accession), stream=True, timeout=60).content) return xml except requests.exceptions.ReadTimeout: stderr.write("Could not download XML file with accession {}\n".format(ena_accession)) return None def xml_download_retry(ena_accession): """ pulling xml record from ENA, some of the records take a longer time to connect, this retry set timeout to be 5 mins :param ena_accession: :return: """ try: xml = ET.fromstring(requests.get("https://www.ebi.ac.uk/ena/data/view/{}&display=xml".format(ena_accession), stream=True, timeout=300).content) return xml except requests.exceptions.ReadTimeout: stderr.write("Could not download XML file with accession {}\n".format(ena_accession)) return None def chromosome_number(xml): """ find the number of chromosomes within the assembly. If the assembly is assembled to scaffold level, returns 0 :param xml: :return: """ try: chroms_number = len(xml.find("ASSEMBLY").find("CHROMOSOMES").findall("CHROMOSOME")) return chroms_number except AttributeError: return 0 def chromosome_data(xml): """ extract md5 and length of the chromosome from the chromosome's xml record :param xml: :return: """ for xref in xml.find("entry").findall("xref"): if xref.attrib["db"] == "MD5": md5 = xref.attrib["id"] break length = xml.find("entry").attrib["sequenceLength"] return md5, int(length) stderr = open("{log_dir}/log_update_tables.txt".format(log_dir=log_dir), "a") stderr.write(str(datetime.now()) + "\n") stderr.write("====\n") registry_engine = create_engine(registry) assembly = Table("assembly", MetaData(), autoload=True, autoload_with=registry_engine) engine = create_engine(tony_assembly) session = sessionmaker(bind=engine) s = session() old_accessions = s.query(GCA.accession).all() r_session = sessionmaker(bind=registry_engine) rs = r_session() sub_concat = func.concat(assembly.c.chain, ".", assembly.c.version) new_accessions = rs.query(sub_concat).filter(sub_concat.notin_(old_accessions)).all() rs.close() s = session() for entry in new_accessions: gca = GCA() gca.accession = entry[0] # print(gca.accession) gca_xml = xml_download(gca.accession) if gca_xml is not None: # only add to GCA table if the xml record of the assembly exists try: gca.assembly_level = gca_xml.find("ASSEMBLY").find("ASSEMBLY_LEVEL").text except AttributeError: gca.assembly_level = "No Level" stderr.write("{} has no assembly_level attribute, not added to database\n".format(gca.accession)) if gca.assembly_level in ["chromosome", "complete genome"]: gca.records = chromosome_number(gca_xml) s.add(gca) # print(gca.accession, gca.assembly_level, gca.records) for chrom_record in get_chromosomes(gca_xml): chromosome = Chromosome() chromosome.GCA_accession = gca.accession chromosome.accession = chrom_record.attrib["accession"] # print(chromosome.accession) chromosome.name = chrom_record.find("NAME").text chromosome.status = 1 chrom_xml = xml_download(chromosome.accession) if chrom_xml is not None: try: chromosome.md5, chromosome.length = chromosome_data(chrom_xml) except AttributeError: stderr.write("Chromosome {} doesn't exit or has corrupted xml file. Chromosome was added " "without md5 and length.\n".format(chromosome.accession)) s.add(chromosome) # print(chromosome.accession, chromosome.GCA_accession, # chromosome.name, chromosome.length, chromosome.md5) if not s.query(Jobs).filter(Jobs.chromosome_accession == chromosome.accession).all(): for job in ["get_fasta", "GC", "trf", "CpG"]: s.add(Jobs(chromosome_accession=chromosome.accession, job_name=job)) # print(chromosome.accession, job) elif gca.assembly_level in ["scaffold", "contig"]: gca.records = get_scaffold_number(gca_xml) s.add(gca) for job in ["get_fasta", "GC", "trf", "CpG"]: s.add(Jobs(chromosome_accession=gca.accession, job_name=job)) # print(gca.accession, gca.assembly_level, gca.records) s.commit() else: stderr.write("{} was not added because XML record is unavailable\n".format(gca.accession)) stderr.flush() # retry download chromosome xml record with a longer timeout for chromosome in s.query(Chromosome).filter(or_(Chromosome.md5 == None, Chromosome.length == None)).all(): chrom_xml = xml_download_retry(chromosome.accession) if chrom_xml is not None: try: chromosome.md5, chromosome.length = chromosome_data(chrom_xml) except AttributeError: stderr.write("Chromosome {} doesn't exit or has corrupted xml file. Chromosome data was not added\n" .format(chromosome.accession)) s.commit() stderr.flush() s.close() stderr.close()
[ 37811, 198, 492, 4091, 262, 28536, 2393, 9387, 351, 428, 670, 329, 3224, 1321, 198, 220, 220, 5115, 6634, 9238, 13, 198, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 220, 220, 3...
2.36642
2,972
# Copyright (C) 2014 Alex Wilson # Copyright (C) 2012-14 Abram Hindle # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import json, os from config import Config from databases import BulkOps, ElasticSearch from topics_controller import * import lda import common, project, task_queue # tasks for task_queue if __name__ == '__main__': import argparse parser = argparse.ArgumentParser('LDA analyser') parser.add_argument('project', help='project name') parser.add_argument('--topics', type=int, default=100, help='number of topics to generate (no effect on incremental)') parser.add_argument('--incremental', help='do an incremental analysis') Config.add_args(parser) args = parser.parse_args() config = Config.build(args) if args.incremental: LDAIncrementalTask(args.project).run() else: print 'running LDA analysis on {} with {} topics'.format( args.project, args.topics) LDATask(args.project, args.topics).run()
[ 2, 220, 15069, 357, 34, 8, 1946, 4422, 8127, 198, 2, 220, 15069, 357, 34, 8, 2321, 12, 1415, 39631, 17099, 293, 198, 2, 220, 220, 198, 2, 220, 770, 1430, 318, 1479, 3788, 26, 345, 460, 17678, 4163, 340, 290, 14, 273, 198, 2, 2...
3.177903
534
from flask_mail import Message from mailer import mailer from middleware.error_handling import write_log
[ 6738, 42903, 62, 4529, 1330, 16000, 198, 6738, 6920, 263, 1330, 6920, 263, 198, 6738, 3504, 1574, 13, 18224, 62, 4993, 1359, 1330, 3551, 62, 6404, 628 ]
3.925926
27
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from google import showcase metadata = (("showcase-trailer", "hello world"),)
[ 2, 15069, 2864, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 7330...
3.820809
173
INPUT_FILE_NAME = 'input.txt' puzzle_input = None with open(INPUT_FILE_NAME) as input_file: puzzle_input = list(map(lambda val: int(val), input_file.readline().rstrip('\n').split(','))) memory_solution_part1 = puzzle_input.copy() memory_solution_part1[1] = 12 memory_solution_part1[2] = 2 solution_part_1 = run_program(memory_solution_part1) print('Solution to part 1: %i' % (solution_part_1[0],)) (noun, verb) = find_noun_verb(19690720, puzzle_input) solution_part_2 = 100 * noun + verb print('Solution to part 2: %i' % (solution_part_2,))
[ 1268, 30076, 62, 25664, 62, 20608, 796, 705, 15414, 13, 14116, 6, 198, 198, 79, 9625, 62, 15414, 796, 6045, 198, 4480, 1280, 7, 1268, 30076, 62, 25664, 62, 20608, 8, 355, 5128, 62, 7753, 25, 198, 220, 220, 220, 15027, 62, 15414, 7...
2.536697
218
from pymongo import MongoClient import pymongo import datetime import sqlite3 as sql import os import signal from signal import SIGABRT, SIGILL, SIGINT, SIGSEGV, SIGTERM, SIGHUP import traceback from anonymizer.utils import logger_manager import sys ROOT_DIR = os.path.abspath(os.path.dirname(__file__)) ATEXIT_SINGLETON = None for sig in (SIGABRT, SIGILL, SIGINT, SIGSEGV, SIGTERM, SIGHUP): signal.signal(sig, store_last_processed_timestamp)
[ 6738, 279, 4948, 25162, 1330, 42591, 11792, 198, 11748, 279, 4948, 25162, 198, 11748, 4818, 8079, 198, 11748, 44161, 578, 18, 355, 44161, 198, 11748, 28686, 198, 11748, 6737, 198, 6738, 6737, 1330, 33993, 6242, 14181, 11, 33993, 8267, 11,...
2.796296
162
from django.db import models from django.contrib.auth.models import User from django.conf import settings # from polls import models as pmod # questions = pmod.Question.objects.all() # pmod.Question.objects.filter(question_text='This is the third question') # q1 = pmod.Question.objects.get(id=2) # .exclude() you can chain them together
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 628, 220, 220, 220, 220, 198, 220, 220, 198, 220, 220, 198, 2, 422, ...
3.106195
113
import cyanodbc import dbapi20 from distro import linux_distribution import pytest
[ 11748, 36818, 375, 15630, 198, 11748, 20613, 15042, 1238, 198, 6738, 1233, 305, 1330, 32639, 62, 17080, 3890, 198, 11748, 12972, 9288, 198 ]
3.608696
23
from problem import Problem from utils.primes import sieve_of_eratosthenes, simple_is_prime
[ 6738, 1917, 1330, 20647, 198, 6738, 3384, 4487, 13, 1050, 999, 1330, 264, 12311, 62, 1659, 62, 263, 265, 455, 831, 274, 11, 2829, 62, 271, 62, 35505, 628 ]
3.206897
29
from typing import Any, Dict, List, Type, TypeVar, Union import attr from ..types import UNSET, Unset T = TypeVar("T", bound="IndyPresAttrSpec")
[ 6738, 19720, 1330, 4377, 11, 360, 713, 11, 7343, 11, 5994, 11, 5994, 19852, 11, 4479, 198, 198, 11748, 708, 81, 198, 198, 6738, 11485, 19199, 1330, 4725, 28480, 11, 791, 2617, 198, 198, 51, 796, 5994, 19852, 7203, 51, 1600, 5421, 26...
2.921569
51
from helpers import cd_to_datetime, datetime_to_str
[ 6738, 49385, 1330, 22927, 62, 1462, 62, 19608, 8079, 11, 4818, 8079, 62, 1462, 62, 2536, 628 ]
3.117647
17
#!/usr/bin/env python # -*- coding: utf-8 -*- import asyncio import logging import json import ssl import uuid from terncy.version import __version__ import terncy.event as event import ipaddress from datetime import datetime from enum import Enum from zeroconf import ServiceBrowser, Zeroconf import aiohttp import websockets _LOGGER = logging.getLogger(__name__) TERNCY_HUB_SVC_NAME = "_websocket._tcp.local." WAIT_RESP_TIMEOUT_SEC = 5 _discovery_engine = None _discovery_browser = None discovered_homecenters = {} class Terncy: def __init__(self, client_id, dev_id, ip, port=443, username="", token=""): self.client_id = client_id self.dev_id = dev_id self.ip = ip self.port = port self.username = username self.token = token self.token_id = -1 self.token_state = TokenState.INVALID self._connection = None self._pending_requests = {} self._event_handler = None
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 30351, 952, 198, 11748, 18931, 198, 11748, 33918, 198, 11748, 264, 6649, 198, 11748, 334, 27112, 198, 6738, 1059, ...
2.493573
389
if sm.getSlotsLeftToAddByInvType(2) < 8: sm.dispose() sm.addInventorySlotsByInvType(8, 2) sm.consumeItem()
[ 361, 895, 13, 1136, 11122, 1747, 18819, 2514, 4550, 3886, 19904, 6030, 7, 17, 8, 1279, 807, 25, 198, 220, 220, 220, 895, 13, 6381, 3455, 3419, 198, 5796, 13, 2860, 818, 17158, 11122, 1747, 3886, 19904, 6030, 7, 23, 11, 362, 8, 198...
2.2
50
import vispy vispy.use(app='egl') from moviepy.editor import VideoClip import numpy as np from vispy import scene, io, visuals from vispy.color import * import cv2 # Check the application correctly picked up egl assert vispy.app.use_app().backend_name == 'egl', 'Not using EGL' if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='Test plotting voxels') parser.add_argument('gt_file', type=str, help='Path to gt file') parser.add_argument('--animate', action='store_true', help='Yield GIF instead of PNG') args = parser.parse_args() from ssc.data.suncg_mapping import SUNCGMapping import os labels = SUNCGMapping() gt_npz = np.load(args.gt_file) scatter_plot_voxels(gt_npz['voxels'], labels.get_classes(), gt_npz['vox_min'], gt_npz['vox_unit'], save_path = os.getcwd() , animate = args.animate)
[ 11748, 1490, 9078, 198, 4703, 9078, 13, 1904, 7, 1324, 11639, 1533, 75, 11537, 198, 198, 6738, 3807, 9078, 13, 35352, 1330, 7623, 2601, 541, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1490, 9078, 1330, 3715, 11, 33245, 11, 27329, ...
2.701538
325
bl_info = { 'name': 'BlendNet - distributed cloud render', 'author': 'www.state-of-the-art.io', 'version': (0, 4, 0), 'warning': 'development version', 'blender': (2, 80, 0), 'location': 'Properties --> Render --> BlendNet Render', 'description': 'Allows to easy allocate resources in cloud and ' 'run the cycles rendering with getting preview ' 'and results', 'wiki_url': 'https://github.com/state-of-the-art/BlendNet/wiki', 'tracker_url': 'https://github.com/state-of-the-art/BlendNet/issues', 'category': 'Render', } if 'bpy' in locals(): import importlib importlib.reload(BlendNet) importlib.reload(blend_file) else: from . import ( BlendNet, ) from .BlendNet import blend_file import os import time import tempfile from datetime import datetime import bpy from bpy.props import ( BoolProperty, IntProperty, StringProperty, EnumProperty, PointerProperty, CollectionProperty, ) def loadProvidersSettings(): '''Get the available providers settings to set and load them during registration of the class''' all_settings = BlendNet.addon.getProvidersSettings() for provider, provider_settings in all_settings.items(): for key, data in provider_settings.items(): path = 'provider_' + provider + '_' + key print('DEBUG: registering provider config:', path) if data.get('type') in ('string', 'path'): BlendNetAddonPreferences.__annotations__[path] = StringProperty( name = data.get('name'), description = data.get('description'), subtype = 'FILE_PATH' if data['type'] == 'path' else 'NONE', update = BlendNet.addon.updateProviderSettings, ) elif data.get('type') == 'choice': BlendNetAddonPreferences.__annotations__[path] = EnumProperty( name = data.get('name'), description = data.get('description'), items = data.get('values'), update = BlendNet.addon.updateProviderSettings, ) # Additional field to store string value (otherwise it's hard on init when # value of enum is integer and has no items to choose from) BlendNetAddonPreferences.__annotations__[path+'_value'] = StringProperty( name = data.get('name'), description = data.get('description'), ) else: print('ERROR: Unknown provider "%s" setting "%s" type: %s' % (provider, key, data.get('type'))) def initPreferences(): '''Will init the preferences with defaults''' prefs = bpy.context.preferences.addons[__package__].preferences # Set defaults for preferences # Update resource_provider anyway to set the addon var prefs.resource_provider = prefs.resource_provider or BlendNet.addon.getAddonDefaultProvider() # Since default for property will be regenerated every restart # we generate new session id if the current one is empty if prefs.session_id == '': prefs.session_id = '' if prefs.manager_password_hidden == '': prefs.manager_password_hidden = '' if prefs.agent_password_hidden == '': prefs.agent_password_hidden = '' BlendNet.addon.fillAvailableBlenderDists() # Getting provider info to make sure all the settings are ok # for current provider configuration BlendNet.addon.getProviderInfo() if __name__ == '__main__': register()
[ 2436, 62, 10951, 796, 1391, 198, 220, 220, 220, 705, 3672, 10354, 705, 3629, 437, 7934, 532, 9387, 6279, 8543, 3256, 198, 220, 220, 220, 705, 9800, 10354, 705, 2503, 13, 5219, 12, 1659, 12, 1169, 12, 433, 13, 952, 3256, 198, 220, ...
2.470867
1,476
"""Main module.""" from collections import defaultdict from functools import cache from itertools import product from operator import itemgetter from typing import List import numpy as np from Bio.Data.CodonTable import unambiguous_dna_by_id
[ 37811, 13383, 8265, 526, 15931, 198, 6738, 17268, 1330, 4277, 11600, 198, 6738, 1257, 310, 10141, 1330, 12940, 198, 6738, 340, 861, 10141, 1330, 1720, 198, 6738, 10088, 1330, 2378, 1136, 353, 198, 6738, 19720, 1330, 7343, 198, 198, 11748,...
3.769231
65
# -*- coding: utf-8 -*- """ Created on Sun Dec 15 01:37:59 2019 @author: kfmah """ stuff = list() stuff.append('python') stuff.append('chuck') stuff.sort() print (stuff[0]) print (stuff.__getitem__(0)) print (list.__getitem__(stuff,0))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 3825, 4280, 1315, 5534, 25, 2718, 25, 3270, 13130, 198, 198, 31, 9800, 25, 479, 38353, 993, 198, 37811, 198, 198, 41094, 796, 1351, 3419, 198, ...
2.382353
102
import tarfile with tarfile.open('archive.zip') as tar: #BAD : This could write any file on the filesystem. for entry in tar: tar.extract(entry, "/tmp/unpack/")
[ 198, 11748, 13422, 7753, 198, 198, 4480, 13422, 7753, 13, 9654, 10786, 17474, 13, 13344, 11537, 355, 13422, 25, 198, 220, 220, 220, 1303, 33, 2885, 1058, 770, 714, 3551, 597, 2393, 319, 262, 29905, 13, 198, 220, 220, 220, 329, 5726, ...
2.632353
68
# Author: Richard Correro from sklearn.base import ClusterMixin from .transformer_socket import TransformerSocket
[ 2, 6434, 25, 6219, 2744, 34785, 198, 198, 6738, 1341, 35720, 13, 8692, 1330, 38279, 35608, 259, 198, 198, 6738, 764, 7645, 16354, 62, 44971, 1330, 3602, 16354, 39105, 198 ]
3.866667
30
# coding: utf-8 """ Telstra Messaging API # Introduction <table><tbody><tr><td class = 'into_api' style='border:none;padding:0 0 0 0'><p>Send and receive SMS and MMS messages globally using Telstra's enterprise grade Messaging API. It also allows your application to track the delivery status of both sent and received messages. Get your dedicated Australian number, and start sending and receiving messages today.</p></td><td class = 'into_api_logo' style='width: 20%;border:none'><img class = 'api_logo' style='margin: -26px 0 0 0' src = 'https://test-telstra-retail-tdev.devportal.apigee.io/sites/default/files/messagingapi-icon.png'></td></tr></tbody></table> # Features The Telstra Messaging API provides the features below. | Feature | Description | | --- | --- | | `Dedicated Number` | Provision a mobile number for your account to be used as `from` address in the API | | `Send Messages` | Sending SMS or MMS messages | | `Receive Messages` | Telstra will deliver messages sent to a dedicated number or to the `notifyURL` defined by you | | `Broadcast Messages` | Invoke a single API call to send a message to a list of numbers provided in `to` | | `Delivery Status` | Query the delivery status of your messages | | `Callbacks` | Provide a notification URL and Telstra will notify your app when a message status changes | | `Alphanumeric Identifier` | Differentiate yourself by providing an alphanumeric string in `from`. This feature is only available on paid plans | | `Concatenation` | Send messages up to 1900 characters long and Telstra will automaticaly segment and reassemble them | | `Reply Request` | Create a chat session by associating `messageId` and `to` number to track responses received from a mobile number. We will store this association for 8 days | | `Character set` | Accepts all Unicode characters as part of UTF-8 | | `Bounce-back response` | See if your SMS hits an unreachable or unallocated number (Australia Only) | | `Queuing` | Messaging API will automatically queue and deliver each message at a compliant rate. | | `Emoji Encoding` | The API supports the encoding of the full range of emojis. Emojis in the reply messages will be in their UTF-8 format. | ## Delivery Notification or Callbacks The API provides several methods for notifying when a message has been delivered to the destination. 1. When you send a message there is an opportunity to specify a `notifyURL`. Once the message has been delivered the API will make a call to this URL to advise of the message status. 2. If you do not specify a URL you can always call the `GET /status` API to get the status of the message. # Getting Access to the API 1. Register at [https://dev.telstra.com](https://dev.telstra.com). 2. After registration, login to [https://dev.telstra.com](https://dev.telstra.com) and navigate to the **My apps** page. 3. Create your application by clicking the **Add new app** button 4. Select **API Free Trial** Product when configuring your application. This Product includes the Telstra Messaging API as well as other free trial APIs. Your application will be approved automatically. 5. There is a maximum of 1000 free messages per developer. Additional messages and features can be purchased from [https://dev.telstra.com](https://dev.telstra.com). 6. Note your `Client key` and `Client secret` as these will be needed to provision a number for your application and for authentication. Now head over to **Getting Started** where you can find a postman collection as well as some links to sample apps and SDKs to get you started. Happy Messaging! # Frequently Asked Questions **Q: Is creating a subscription via the Provisioning call a required step?** A. Yes. You will only be able to start sending messages if you have a provisioned dedicated number. Use Provisioning to create a dedicated number subscription, or renew your dedicated number if it has expired. **Q: When trying to send an SMS I receive a `400 Bad Request` response. How can I fix this?** A. You need to make sure you have a provisioned dedicated number before you can send an SMS. If you do not have a provisioned dedicated number and you try to send a message via the API, you will get the error below in the response: <pre><code class=\"language-sh\">{ \"status\":\"400\", \"code\":\"DELIVERY-IMPOSSIBLE\", \"message\":\"Invalid \\'from\\' address specified\" }</code></pre> Use Provisioning to create a dedicated number subscription, or renew your dedicated number if it has expired. **Q: How long does my dedicated number stay active for?** A. When you provision a dedicated number, by default it will be active for 30 days. You can use the `activeDays` parameter during the provisioning call to increment or decrement the number of days your dedicated number will remain active. Note that Free Trial apps will have 30 days as the maximum `activeDays` they can add to their provisioned number. If the Provisioning call is made several times within that 30-Day period, it will return the `expiryDate` in the Unix format and will not add any activeDays until after that `expiryDate`. **Q: Can I send a broadcast message using the Telstra Messaging API?** A. Yes. Recipient numbers can be in the form of an array of strings if a broadcast message needs to be sent, allowing you to send to multiple mobile numbers in one API call. A sample request body for this will be: `{\"to\":[\"+61412345678\",\"+61487654321\"],\"body\":\"Test Message\"}` **Q: Can I send SMS and MMS to all countries?** A. You can send SMS and MMS to all countries EXCEPT to countries which are subject to global sanctions namely: Burma, Cte d'Ivoire, Cuba, Iran, North Korea, Syria. **Q: Can I use `Alphanumeric Identifier` from my paid plan via credit card?** A. `Alphanumeric Identifier` is only available on Telstra Account paid plans, not through credit card paid plans. **Q: What is the maximum sized MMS that I can send?** A. This will depend on the carrier that will receive the MMS. For Telstra it's up to 2MB, Optus up to 1.5MB and Vodafone only allows up to 500kB. You will need to check with international carriers for thier MMS size limits. **Q: How is the size of an MMS calculated?** A. Images are scaled up to approximately 4/3 when base64 encoded. Additionally, there is approximately 200 bytes of overhead on each MMS. Assuming the maximum MMS that can be sent on Telstras network is 2MB, then the maximum image size that can be sent will be approximately 1.378MB (1.378 x 1.34 + 200, without SOAP encapsulation). **Q: How is an MMS classified as Small or Large?** A. MMSes with size below 600kB are classed as Small whereas those that are bigger than 600kB are classed as Large. They will be charged accordingly. **Q: Are SMILs supported by the Messaging API?** A. While there will be no error if you send an MMS with a SMIL presentation, the actual layout or sequence defined in the SMIL may not display as expected because most of the new smartphone devices ignore the SMIL presentation layer. SMIL was used in feature phones which had limited capability and SMIL allowed a *powerpoint type* presentation to be provided. Smartphones now have the capability to display video which is the better option for presentations. It is recommended that MMS messages should just drop the SMIL. **Q: How do I assign a delivery notification or callback URL?** A. You can assign a delivery notification or callback URL by adding the `notifyURL` parameter in the body of the request when you send a message. Once the message has been delivered, a notification will then be posted to this callback URL. **Q: What is the difference between the `notifyURL` parameter in the Provisoning call versus the `notifyURL` parameter in the Send Message call?** A. The `notifyURL` in the Provisoning call will be the URL where replies to the provisioned number will be posted. On the other hand, the `notifyURL` in the Send Message call will be the URL where the delivery notification will be posted, e.g. when an SMS has already been delivered to the recipient. # Getting Started Below are the steps to get started with the Telstra Messaging API. 1. Generate an OAuth2 token using your `Client key` and `Client secret`. 2. Use the Provisioning call to create a subscription and receive a dedicated number. 3. Send a message to a specific mobile number. ## Run in Postman <a href=\"https://app.getpostman.com/run-collection/ded00578f69a9deba256#?env%5BMessaging%20API%20Environments%5D=W3siZW5hYmxlZCI6dHJ1ZSwia2V5IjoiY2xpZW50X2lkIiwidmFsdWUiOiIiLCJ0eXBlIjoidGV4dCJ9LHsiZW5hYmxlZCI6dHJ1ZSwia2V5IjoiY2xpZW50X3NlY3JldCIsInZhbHVlIjoiIiwidHlwZSI6InRleHQifSx7ImVuYWJsZWQiOnRydWUsImtleSI6ImFjY2Vzc190b2tlbiIsInZhbHVlIjoiIiwidHlwZSI6InRleHQifSx7ImVuYWJsZWQiOnRydWUsImtleSI6Imhvc3QiLCJ2YWx1ZSI6InRhcGkudGVsc3RyYS5jb20iLCJ0eXBlIjoidGV4dCJ9LHsiZW5hYmxlZCI6dHJ1ZSwia2V5IjoiQXV0aG9yaXphdGlvbiIsInZhbHVlIjoiIiwidHlwZSI6InRleHQifSx7ImVuYWJsZWQiOnRydWUsImtleSI6Im9hdXRoX2hvc3QiLCJ2YWx1ZSI6InNhcGkudGVsc3RyYS5jb20iLCJ0eXBlIjoidGV4dCJ9LHsiZW5hYmxlZCI6dHJ1ZSwia2V5IjoibWVzc2FnZV9pZCIsInZhbHVlIjoiIiwidHlwZSI6InRleHQifV0=\"><img src=\"https://run.pstmn.io/button.svg\" alt=\"Run in Postman\"/></a> ## Sample Apps - [Perl Sample App](https://github.com/telstra/MessagingAPI-perl-sample-app) - [Happy Chat App](https://github.com/telstra/messaging-sample-code-happy-chat) - [PHP Sample App](https://github.com/developersteve/telstra-messaging-php) ## SDK Repos - [Messaging API - PHP SDK](https://github.com/telstra/MessagingAPI-SDK-php) - [Messaging API - Python SDK](https://github.com/telstra/MessagingAPI-SDK-python) - [Messaging API - Ruby SDK](https://github.com/telstra/MessagingAPI-SDK-ruby) - [Messaging API - NodeJS SDK](https://github.com/telstra/MessagingAPI-SDK-node) - [Messaging API - .Net2 SDK](https://github.com/telstra/MessagingAPI-SDK-dotnet) - [Messaging API - Java SDK](https://github.com/telstra/MessagingAPI-SDK-Java) ## Blog Posts For more information on the Messaging API, you can read these blog posts: - [Callbacks Part 1](https://dev.telstra.com/content/understanding-messaging-api-callbacks-part-1) - [Callbacks Part 2](https://dev.telstra.com/content/understanding-messaging-api-callbacks-part-2) # noqa: E501 OpenAPI spec version: 2.2.9 Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import copy import logging import multiprocessing import sys import urllib3 import six from six.moves import http_client as httplib def get_basic_auth_token(self): """Gets HTTP basic authentication header (string). :return: The token for basic HTTP authentication. """ return urllib3.util.make_headers( basic_auth=self.username + ':' + self.password ).get('authorization') def auth_settings(self): """Gets Auth Settings dict for api client. :return: The Auth Settings information dict. """ return { 'auth': { 'type': 'oauth2', 'in': 'header', 'key': 'Authorization', 'value': 'Bearer ' + self.access_token }, } def to_debug_report(self): """Gets the essential information for debugging. :return: The report for debugging. """ return "Python SDK Debug Report:\n"\ "OS: {env}\n"\ "Python Version: {pyversion}\n"\ "Version of the API: 2.2.9\n"\ "SDK Package Version: 1.0.6".\ format(env=sys.platform, pyversion=sys.version)
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 220, 220, 220, 12088, 12044, 10626, 3039, 7824, 628, 220, 220, 220, 220, 1303, 22395, 220, 1279, 11487, 6927, 83, 2618, 6927, 2213, 6927, 8671, 1398, 796, 705, 20424, 62, 15042, ...
3.200219
3,646
from gym_minigrid.minigrid import * from gym_minigrid.register import register
[ 6738, 11550, 62, 1084, 3692, 312, 13, 1084, 3692, 312, 1330, 1635, 198, 6738, 11550, 62, 1084, 3692, 312, 13, 30238, 1330, 7881, 628, 198, 220, 220, 220, 220, 628 ]
2.9
30
# n=7 # G=[[] for _ in range(n)] G[0]=[1,2] G[1]=[0,3] G[2]=[0,4,5] #etc.
[ 2, 198, 77, 28, 22, 198, 2, 198, 38, 41888, 21737, 329, 4808, 287, 2837, 7, 77, 15437, 198, 198, 38, 58, 15, 22241, 58, 16, 11, 17, 60, 198, 38, 58, 16, 22241, 58, 15, 11, 18, 60, 198, 38, 58, 17, 22241, 58, 15, 11, 19, ...
1.357143
56
#!/usr/bin/env python # coding=utf-8 # @Time : 2019-06-04 # @Author : hongshu import sys import asyncio from tawsocks import common
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 28, 40477, 12, 23, 198, 198, 2, 2488, 7575, 220, 220, 220, 1058, 13130, 12, 3312, 12, 3023, 198, 2, 2488, 13838, 220, 1058, 289, 506, 1477, 84, 198, 198, 11748, 25064, 19...
2.5
56
# -*- coding: utf-8 -*- import requests import json import logging
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 7007, 198, 11748, 33918, 198, 11748, 18931, 628 ]
2.956522
23
""" Vertical: Adds movement functions along the vertical (Y) axis to a game object """
[ 37811, 198, 42369, 605, 25, 198, 46245, 3356, 5499, 1863, 262, 11723, 357, 56, 8, 16488, 284, 257, 983, 2134, 198, 37811, 628 ]
3.826087
23
# -*- coding: utf-8 -*- import datetime from typing import Optional, List, Any from pip_services3_commons.config import ConfigParams from pip_services3_commons.convert import StringConverter from pip_services3_commons.errors import ConfigException from pip_services3_commons.refer import IReferences from pip_services3_components.auth import CredentialResolver from pip_services3_rpc.clients import RestClient from pip_services3_datadog.clients.DataDogLogMessage import DataDogLogMessage
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 4818, 8079, 198, 6738, 19720, 1330, 32233, 11, 7343, 11, 4377, 198, 198, 6738, 7347, 62, 30416, 18, 62, 9503, 684, 13, 11250, 1330, 17056, 10044, 4105, 198, 6738,...
3.386207
145
import logging import os from functools import partial from PIL.Image import Image from PyQt5.QtCore import QObject, pyqtSignal, QThread from PyQt5.QtWidgets import QProgressDialog from .threading import QThreadedWorkerDebug as QThreadedWorker from analyze.composition import Composition, Spectrogram from analyze.media.sound import Sound, SoundResampled from utils import ProgressProxy SAMPLERATE = 1024 * 16 log = logging.getLogger(__name__)
[ 11748, 18931, 198, 11748, 28686, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 198, 6738, 350, 4146, 13, 5159, 1330, 7412, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 14055, 1330, 1195, 10267, 11, 12972, 39568, 11712, 282, 11, 1195, 168...
3.330882
136
""" Node module =========== The ``node`` module contains the ``MetalNode`` class, which is the foundation for MetalPipe. """ import time import datetime import uuid import importlib import logging import os import threading import pprint import sys import copy import random import functools import csv import MySQLdb import re import io import yaml import types import inspect import prettytable import requests import graphviz from timed_dict.timed_dict import TimedDict from metalpipe.message.batch import BatchStart, BatchEnd from metalpipe.message.message import MetalPipeMessage from metalpipe.node_queue.queue import MetalPipeQueue from metalpipe.message.canary import Canary from metalpipe.utils.set_attributes import set_kwarg_attributes from metalpipe.utils.data_structures import Row, MySQLTypeSystem from metalpipe.utils import data_structures as ds # from metalpipe.metalpipe_recorder import RedisFixturizer from metalpipe.utils.helpers import ( load_function, replace_by_path, remap_dictionary, set_value, get_value, to_bool, aggregate_values, ) DEFAULT_MAX_QUEUE_SIZE = int(os.environ.get("DEFAULT_MAX_QUEUE_SIZE", 128)) MONITOR_INTERVAL = 1 STATS_COUNTER_MODULO = 4 LOGJAM_THRESHOLD = 0.25 SHORT_DELAY = 0.1 PROMETHEUS = False def no_op(*args, **kwargs): """ No-op function to serve as default ``get_runtime_attrs``. """ return None def _get_message_content(self, one_item): # Get the content of a specific keypath, if one has # been defined in the ``MetalNode`` initialization. message_content = ( get_value(one_item.message_content, self.input_message_keypath) if len(self.input_message_keypath) > 0 else one_item.message_content ) if ( isinstance(message_content, (dict,)) and len(message_content) == 1 and "__value__" in message_content ): message_content = message_content["__value__"] return message_content def wait_for_pipeline_finish(self): while not self.pipeline_finished: time.sleep(SHORT_DELAY) def input_queues_empty(self): """ Tests whether there are any messages on any of the node's input queues. Returns: bool: ``True`` if input queues are all empty. """ return all(queue.empty for queue in self.input_queue_list) def cleanup(self): """ If there is any cleanup (closing files, shutting down database connections), necessary when the node is stopped, then the node's class should provide a ``cleanup`` method. By default, the method is just a logging statement. """ self.log_info("in null cleanup") yield NothingToSeeHere() def _cleanup(self): self.log_info("Cleanup called after shutdown.") for i in self.cleanup(): yield i # Send termination message here if self.send_termination_message: yield Terminated(self) for q in self.output_queue_list: while not q.empty: pass self.log_info("setting cleanup_called to True") self.cleanup_called = True def log_info(self, message=""): logging.info( "{node_name}: {message}".format(node_name=self.name, message=message) ) def terminate_pipeline(self, error=False): """ This method can be called on any node in a pipeline, and it will cause all of the nodes to terminate if they haven't stopped already. Args: error (bool): Not yet implemented. """ self.log_info("terminate_pipeline called..." + str(self.name)) for node in self.all_connected(): node.terminate = True for q in node.output_queue_list: q.drain() # if not node.finished: # node.stopped_at = datetime.datetime.now() # print('setting node.terminate') # node.terminate = True def process_item(self, *args, **kwargs): """ Default no-op for nodes. """ pass def stream(self): """ Called in each ``MetalNode`` thread. """ self.status = "running" if getattr(self, "_import_pydatalog", False): from pyDatalog import pyDatalog, Logic Logic(self.logic_engine) try: for output, previous_message in self.start(): logging.debug("In MetalNode.stream.stream() --> " + str(output)) for output_queue in self.output_queue_list: self.messages_sent_counter += 1 output_queue.put( output, block=True, timeout=None, queue_event=self.queue_event, previous_message=previous_message, ) # if 1 or not isinstance(output, (NothingToSeeHere,)) and output is not None: except Exception as error: self.status = "error" self.stopped_at = datetime.datetime.now() raise error self.status = "success" self.stopped_at = datetime.datetime.now() def all_connected(self, seen=None): """ Returns all the nodes connected (directly or indirectly) to ``self``. This allows us to loop over all the nodes in a pipeline even if we have a handle on only one. This is used by ``global_start``, for example. Args: seen (set): A set of all the nodes that have been identified as connected to ``self``. Returns: (set of ``MetalNode``): All the nodes connected to ``self``. This includes ``self``. """ seen = seen or set() if isinstance(self, (DynamicClassMediator,)): for node_name, node_dict in self.node_dict.items(): node_obj = node_dict["obj"] seen = seen | node_obj.all_connected(seen=seen) else: if self not in seen: seen.add(self) for node in self.input_node_list + self.output_node_list: if node in seen: continue seen.add(node) seen = seen | node.all_connected(seen=seen) return seen def broadcast(self, broadcast_message): """ Puts the message into all the input queues for all connected nodes. """ for node in self.all_connected(): for input_queue in node.input_queue_list: input_queue.put(broadcast_message) def global_start( self, prometheus=False, pipeline_name=None, max_time=None, fixturize=False, ): """ Starts every node connected to ``self``. Mainly, it: 1. calls ``start()`` on each node #. sets some global variables #. optionally starts some experimental code for monitoring """ def prometheus_init(): """ Experimental code for enabling Prometheus monitoring. """ from prometheus_client import ( start_http_server, Summary, Gauge, Histogram, Counter, ) for node in self.all_connected(): node.prometheus_objects = {} summary = Summary( node.name + "_incoming", "Summary of incoming messages" ) node.prometheus_objects["incoming_message_summary"] = summary node.prometheus_objects["outgoing_message_summary"] = Gauge( node.name + "_outgoing", "Summary of outgoing messages" ) start_http_server(8000) if PROMETHEUS: prometheus_init() # thread_dict = self.thread_dict global_dict = {} run_id = uuid.uuid4().hex for node in self.all_connected(): # Set the pipeline name on the attribute of each node node.pipeline_name = pipeline_name or uuid.uuid4().hex # Set a unique run_id node.run_id = run_id node.fixturize = fixturize node.global_dict = global_dict # Establishing shared globals logging.debug("global_start:" + str(self)) # Create thread event here? thread = threading.Thread( target=MetalNode.stream, args=(node,), daemon=False ) thread.start() node.thread_dict = self.thread_dict self.thread_dict[node.name] = thread node.status = "running" monitor_thread = threading.Thread( target=MetalNode.thread_monitor, args=(self,), kwargs={"max_time": max_time}, daemon=True, ) monitor_thread.start() def draw_pipeline(self): """ Draw the pipeline structure using graphviz. """ dot = graphviz.Digraph() for node in self.all_connected(): dot.node(node.name, node.name, shape="box") for node in self.all_connected(): for target_node in node.output_node_list: dot.edge(node.name, target_node.name) dot.render("pipeline_drawing.gv", view=True) def thread_monitor(self, max_time=None): """ This function loops over all of the threads in the pipeline, checking that they are either ``finished`` or ``running``. If any have had an abnormal exit, terminate the entire pipeline. """ counter = 0 error = False time_started = time.time() while not self.pipeline_finished: logging.debug("MONITOR THREAD") time.sleep(MONITOR_INTERVAL) counter += 1 if max_time is not None: print("checking max_time...") if time.time() - time_started >= max_time: self.pipeline_finished = True print("finished because of max_time") for node in self.all_connected(): node.finished = True continue # Check whether all the workers have ``.finished`` # self.pipeline_finished = all( # node.finished for node in self.all_connected()) if counter % STATS_COUNTER_MODULO == 0: table = prettytable.PrettyTable( ["Node", "Class", "Received", "Sent", "Queued", "Status", "Time",] ) for node in sorted(list(self.all_connected()), key=lambda x: x.name): if node.status == "running": status_color = bcolors.WARNING elif node.status == "stopped": status_color = "" elif node.status == "error": status_color = bcolors.FAIL error = True elif node.status == "success": status_color = bcolors.OKGREEN else: assert False if node.logjam >= LOGJAM_THRESHOLD: logjam_color = bcolors.FAIL else: logjam_color = "" table.add_row( [ logjam_color + node.name + bcolors.ENDC, node.__class__.__name__, node.messages_received_counter, node.messages_sent_counter, node.input_queue_size, status_color + node.status + bcolors.ENDC, node.time_running, ] ) self.log_info("\n" + str(table)) if error: logging.error("Terminating due to error.") self.terminate_pipeline(error=True) # self.pipeline_finished = True break # Check for blocked nodes for node in self.all_connected(): input_queue_full = [ input_queue.approximately_full() for input_queue in node.input_queue_list ] output_queue_full = [ output_queue.approximately_full() for output_queue in node.output_queue_list ] logjam = ( not node.is_source and all(input_queue_full) and not any(output_queue_full) ) node.logjam_score["polled"] += 1 logging.debug("LOGJAM SCORE: {logjam}".format(logjam=str(node.logjam))) if logjam: node.logjam_score["logjam"] += 1 logging.debug( "LOGJAM {logjam} {name}".format(logjam=logjam, name=node.name) ) self.log_info("Pipeline finished.") self.log_info("Sending terminate signal to nodes.") self.log_info("Messages that are being processed will complete.") # HERE if error: self.log_info("Abnormal exit") sys.exit(1) else: self.log_info("Normal exit.") sys.exit(0) class CounterOfThings(MetalNode): class FunctionOfMessage(MetalNode): class MockNode(MetalNode): """ This is only intended for doing unit tests, etc. """ class InsertData(MetalNode): class RandomSample(MetalNode): """ Lets through only a random sample of incoming messages. Might be useful for testing, or when only approximate results are necessary. """ class SubstituteRegex(MetalNode): class CSVToDictionaryList(MetalNode): class SequenceEmitter(MetalNode): """ Emits ``sequence`` ``max_sequences`` times, or forever if ``max_sequences`` is ``None``. """ class GetEnvironmentVariables(MetalNode): """ This node reads environment variables and stores them in the message. The required keyword argument for this node is ``environment_variables``, which is a list of -- you guessed it! -- environment variables. By default, they will be read and stored in the outgoing message under keys with the same names as the environment variables. E.g. ``FOO_VAR`` will be stored in the message ``{"FOO_BAR": whatever}``. Optionally, you can provide a dictionary to the ``mappings`` keyword argument, which maps environment variable names to new names. E.g. if ``mappings = {"FOO_VAR": "bar_var"}``, then the value of ``FOO_VAR`` will be stored in the message ``{"bar_var": whatever}``. If the environment variable is not defined, then its value will be set to ``None``. Args: mappings (dict): An optional dictionary mapping environment variable names to new names. environment_variables (list): A list of environment variable names. """ class SimpleTransforms(MetalNode): class Serializer(MetalNode): """ Takes an iterable thing as input, and successively yields its items. """ class AggregateValues(MetalNode): """ Does that. """ class Filter(MetalNode): """ Applies tests to each message and filters out messages that don't pass Built-in tests: key_exists value_is_true value_is_not_none Example: {'test': 'key_exists', 'key': mykey} """ def process_item(self): if self.test in ["key_exists", "value_is_not_none", "value_is_true"]: result = ( getattr(self, "_" + self.test)(self.__message__, self.test_keypath) == self.value ) else: raise Exception("Unknown test: {test_name}".format(test_name=test)) if result: logging.debug("Sending message through") yield self.message else: logging.debug("Blocking message: " + str(self.__message__)) yield NothingToSeeHere() class StreamMySQLTable(MetalNode): # def get_schema(self): # self.cursor.execute(self.table_schema_query) # table_schema = self.cursor.fetchall() # return table_schema class PrinterOfThings(MetalNode): class ConstantEmitter(MetalNode): """ Send a thing every n seconds """ class TimeWindowAccumulator(MetalNode): """ Every N seconds, put the latest M seconds data on the queue. """ def get_node_dict(node_config): node_dict = {} for node_config in node_config["nodes"]: node_class = globals()[node_config["class"]] node_name = node_config["name"] node_dict[node_name] = {} node_dict[node_name]["class"] = node_class frozen_arguments = node_config.get("frozen_arguments", {}) node_dict[node_name]["frozen_arguments"] = frozen_arguments node_obj = node_class(**frozen_arguments) node_dict[node_name]["remapping"] = node_config.get("arg_mapping", {}) return node_dict def kwarg_remapper(f, **kwarg_mapping): reverse_mapping = {value: key for key, value in kwarg_mapping.items()} logging.debug("kwarg_mapping:" + str(kwarg_mapping)) parameters = [i for i, _ in list(inspect.signature(f).parameters.items())] for kwarg in parameters: if kwarg not in kwarg_mapping: reverse_mapping[kwarg] = kwarg return remapped_function def template_class( class_name, parent_class, kwargs_remapping, frozen_arguments_mapping ): kwargs_remapping = kwargs_remapping or {} frozen_init = functools.partial(parent_class.__init__, **frozen_arguments_mapping) if isinstance(parent_class, (str,)): parent_class = globals()[parent_class] cls = type(class_name, (parent_class,), {}) setattr(cls, "__init__", kwarg_remapper(frozen_init, **kwargs_remapping)) return cls def class_factory(raw_config): new_class = type(raw_config["name"], (DynamicClassMediator,), {}) new_class.node_dict = get_node_dict(raw_config) new_class.class_name = raw_config["name"] new_class.edge_list_dict = raw_config.get("edges", []) new_class.raw_config = raw_config for node_name, node_config in new_class.node_dict.items(): _class = node_config["class"] cls = template_class( node_name, _class, node_config["remapping"], node_config["frozen_arguments"], ) setattr(cls, "raw_config", raw_config) node_config["cls_obj"] = cls # Inject? globals()[new_class.__name__] = new_class return new_class if __name__ == "__main__": pass
[ 37811, 198, 19667, 8265, 198, 2559, 18604, 198, 198, 464, 7559, 17440, 15506, 8265, 4909, 262, 7559, 36790, 19667, 15506, 1398, 11, 543, 318, 262, 8489, 198, 1640, 12136, 47, 3757, 13, 198, 37811, 198, 198, 11748, 640, 198, 11748, 4818,...
2.169517
8,772
import random numeroPc = random.randint(1, 5) numeroUsuario = int(input('Digite um nmero: ')) print('Parabns vc acertou!' if numeroPc == numeroUsuario else 'O Computador venceu')
[ 11748, 4738, 198, 198, 22510, 3529, 47, 66, 796, 4738, 13, 25192, 600, 7, 16, 11, 642, 8, 198, 22510, 3529, 52, 2385, 4982, 796, 493, 7, 15414, 10786, 19511, 578, 23781, 299, 647, 78, 25, 705, 4008, 628, 198, 4798, 10786, 10044, 3...
2.527778
72
import pyipmi import pyipmi.interfaces import os import re import datetime import os.path import time import math import numpy import mmap import array import getopt import sys #Inmport path sys.path.append('../src') from aardvark_initial import * #Inmport path sys.path.append('../') from os_parameters_define import * from utility_function import * from nm_ipmi_raw_to_str import * from error_messages_define import * from nm_functions import * from config import * ## Define Delay Time check function ## Define Delay Time check function ## Define Input parameters lenth check ## _Main_ ## # Initial aardvark #ipmi = aardvark_ipmi_init(target_me_addr, target_me_bridge_channel) # Check delay time parameter sts = parameter_check(sys.argv) if(sts == PASS): print 'Check Delay Time parameter setting' sts, delay_time = delay_check(str(sys.argv[1])) print ( "delay time = %d " %(delay_time) ) sts, loop_number = loop_check(str(sys.argv[2])) print ("loop_number = " , loop_number) else: sts = ERROR if(sts == PASS): print 'Start to Send Get Device ID..' while loop_number : sts, sps_version, platform, dcmi, nm, image = get_device_id_py(ipmi) # Add delay time 5 secs to make sure me go back to stable mode time.sleep(delay_time) # Show Result print('SPS Version = '+ sps_version) print('platform = %d' %platform ) print('dcmi =%d' %dcmi) print('nm = %d' %nm) print('image = %d' %(image)) if( loop_number == 'loop' ): loop_number = True else: loop_number = loop_number -1 if(sts == ERROR ): loop_number = False break else: print' Done! '
[ 11748, 12972, 541, 11632, 198, 11748, 12972, 541, 11632, 13, 3849, 32186, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 4818, 8079, 198, 11748, 28686, 13, 6978, 198, 11748, 640, 198, 11748, 10688, 198, 11748, 299, 32152, 198, 11748, 808...
2.472779
698
import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines sys.setrecursionlimit(10 ** 7) from collections import Counter n, *a = map(int, read().split()) counter = Counter(a).values() ans = len(counter) if (sum(counter) - ans) % 2 == 1: ans -= 1 print(ans)
[ 11748, 25064, 198, 961, 796, 25064, 13, 19282, 259, 13, 22252, 13, 961, 198, 961, 1370, 796, 25064, 13, 19282, 259, 13, 22252, 13, 961, 1370, 198, 961, 6615, 796, 25064, 13, 19282, 259, 13, 22252, 13, 961, 6615, 198, 17597, 13, 2617...
2.767241
116
import json from plato import db from plato.model.user import User from plato.test.base import BaseTestCase from plato.test.utils import add_user, add_domain
[ 11748, 33918, 198, 198, 6738, 458, 5549, 1330, 20613, 198, 6738, 458, 5549, 13, 19849, 13, 7220, 1330, 11787, 198, 6738, 458, 5549, 13, 9288, 13, 8692, 1330, 7308, 14402, 20448, 198, 6738, 458, 5549, 13, 9288, 13, 26791, 1330, 751, 62...
3.333333
48
import sqlite3 import datetime conn = sqlite3.connect('database.db') print("Opened database successfully") # NOTE: ID is DEPRECATED conn.execute('CREATE TABLE simulated (id TEXT, lat NUMERIC, lon NUMERIC, alt NUMERIC, time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)') conn.execute('CREATE TABLE locations (id TEXT, lat NUMERIC, lon NUMERIC, alt NUMERIC, time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)') print("Table created successfully") conn.close()
[ 11748, 44161, 578, 18, 198, 11748, 4818, 8079, 198, 198, 37043, 796, 44161, 578, 18, 13, 8443, 10786, 48806, 13, 9945, 11537, 198, 4798, 7203, 18257, 2945, 6831, 7675, 4943, 198, 198, 2, 24550, 25, 4522, 318, 5550, 47, 38827, 11617, 1...
3.134752
141
# A bit of duplication of the component system tests to ensure # typescript components are transpiled properly to Python. # Types are tested in test_mypy. import json import re import pytest from . import ts_components as tsc def test_tsc_enum_docstring(): assert ":param enumeration: (Possible values: 'foo', 'bar')" \ in tsc.TypedComponent.__init__.__doc__ assert ":param defined_enum: (Possible values: 'foo', 'bar')" \ in tsc.TypedComponent.__init__.__doc__
[ 2, 317, 1643, 286, 50124, 286, 262, 7515, 1080, 5254, 284, 4155, 198, 2, 2170, 3798, 1968, 6805, 389, 1007, 79, 3902, 6105, 284, 11361, 13, 198, 2, 24897, 389, 6789, 287, 1332, 62, 1820, 9078, 13, 198, 11748, 33918, 198, 11748, 302,...
2.830508
177
# -*- coding: utf-8 -*- import random import numpy as np import colorama from colorama import Fore, Back import copy colorama.init() LEFT = 'lft' RIGHT = 'rgt' UP = 'up' DOWN = 'dwn' HORIZONTAL = 'horizontal' VERTICAL = 'vertical' print("beginning...") level = [] for x in range(50): level.append([]) for y in range(50): level[x].append(".") rooms = [] corridors = [] for a in range(0,1000): generateLevel() print("finished generation !") print(len(rooms)) count = 1 for room in rooms: for x in range(room.x, room.x + room.w): level[x][room.y] = str(count)#"" level[x][room.y + room.h] = str(count) for y in range(room.y, room.y + room.h): level[room.x][y] = str(count) level[room.x + room.w][y] = str(count) count += 1 print("nombre de corridors : ", len(corridors)) for corridor in corridors: print("nombre de corridors : ", len(corridor.straights)) for straight in corridor.straights: print("origine", straight.x, ', ',straight.y,"oritentation : ",straight.orientation, "length : ", straight.length) if straight.orientation == VERTICAL: for y in range(straight.y,straight.y + straight.length, np.sign(straight.length)): for x in range(straight.x -1,straight.x + 1 + 1,2): #level[x][y] = "" pass level[straight.x][y]=Fore.RED + "." + Fore.WHITE elif straight.orientation == HORIZONTAL: print("horizontal") for x in range(straight.x,straight.x + straight.length, np.sign(straight.length)): for y in range(straight.y -1,straight.y + 1 + 1,2): #level[x][y] = "" pass level[x][straight.y]= Fore.RED + "." + Fore.WHITE for line in level: lineC = " " print(lineC.join(line)) rooms = [] corridors = [] level = [] for x in range(50): level.append([]) for y in range(50): level[x].append(".") print("loop position : ",a) input()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 4738, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 3124, 1689, 198, 6738, 3124, 1689, 1330, 4558, 11, 5157, 198, 11748, 4866, 198, 198, 8043, 1689, 13, 15...
2.037511
1,093
#!/usr/bin/env python3 import wx import vmwizard as vmw if __name__ == '__main__': app = wx.App(False) frame = wx.Frame(None, wx.ID_ANY, "Variant Matrix") wiz = vmw.Wizard(frame) frame.Show(True) frame.Centre() app.MainLoop()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 266, 87, 198, 198, 11748, 45887, 86, 8669, 355, 45887, 86, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 598, 796, 266, 87, ...
2.179487
117
import os import string import textwrap import unittest import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import * import logging # # DMRIInstall #
[ 11748, 28686, 198, 11748, 4731, 198, 11748, 2420, 37150, 198, 11748, 555, 715, 395, 198, 11748, 410, 30488, 11, 10662, 83, 11, 269, 30488, 11, 14369, 263, 198, 6738, 14369, 263, 13, 7391, 276, 8912, 540, 26796, 1330, 1635, 198, 11748, ...
3.056604
53
import requests import json from typing import Tuple from datetime import timedelta, datetime from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django.utils.html import strip_tags from django.contrib.auth.models import Group from esi.errors import TokenExpiredError, TokenInvalidError from esi.models import Token from allianceauth.authentication.models import CharacterOwnership from allianceauth.eveonline.models import EveCharacter, EveCorporationInfo from allianceauth.services.hooks import get_extension_logger from allianceauth.authentication.models import State from .providers import esi from .decorators import fetch_token_for_owner logger = get_extension_logger(__name__) class Owner(models.Model): """A corporation that holds the calendars""" ERROR_NONE = 0 ERROR_TOKEN_INVALID = 1 ERROR_TOKEN_EXPIRED = 2 ERROR_INSUFFICIENT_PERMISSIONS = 3 ERROR_NO_CHARACTER = 4 ERROR_ESI_UNAVAILABLE = 5 ERROR_OPERATION_MODE_MISMATCH = 6 ERROR_UNKNOWN = 99 ERRORS_LIST = [ (ERROR_NONE, "No error"), (ERROR_TOKEN_INVALID, "Invalid token"), (ERROR_TOKEN_EXPIRED, "Expired token"), (ERROR_INSUFFICIENT_PERMISSIONS, "Insufficient permissions"), (ERROR_NO_CHARACTER, "No character set for fetching data from ESI"), (ERROR_ESI_UNAVAILABLE, "ESI API is currently unavailable"), ( ERROR_OPERATION_MODE_MISMATCH, "Operaton mode does not match with current setting", ), (ERROR_UNKNOWN, "Unknown error"), ] corporation = models.OneToOneField( EveCorporationInfo, default=None, null=True, blank=True, on_delete=models.CASCADE, help_text="Corporation owning the calendar", related_name="+", ) character = models.ForeignKey( CharacterOwnership, on_delete=models.SET_DEFAULT, default=None, null=True, blank=True, help_text="Character used for syncing the calendar", related_name="+", ) event_visibility = models.ForeignKey( EventVisibility, on_delete=models.CASCADE, null=True, blank=True, help_text=_("Visibility filter that dictates who is able to see this event"), ) operation_type = models.ForeignKey( EventCategory, null=True, blank=True, on_delete=models.CASCADE, help_text=_( "Event category that will be assigned for all of the events from this owner." ), ) is_active = models.BooleanField( default=True, help_text=("whether this owner is currently included in the sync process"), ) def token(self, scopes=None) -> Tuple[Token, int]: """returns a valid Token for the owner""" token = None error = None # abort if character is not configured if self.character is None: logger.error("%s: No character configured to sync", self) error = self.ERROR_NO_CHARACTER # abort if character does not have sufficient permissions elif self.corporation and not self.character.user.has_perm( "opcalendar.add_ingame_calendar_owner" ): logger.error( "%s: This character does not have sufficient permission to sync corporation calendars", self, ) error = self.ERROR_INSUFFICIENT_PERMISSIONS # abort if character does not have sufficient permissions elif not self.character.user.has_perm("opcalendar.add_ingame_calendar_owner"): logger.error( "%s: This character does not have sufficient permission to sync personal calendars", self, ) error = self.ERROR_INSUFFICIENT_PERMISSIONS else: try: # get token token = ( Token.objects.filter( user=self.character.user, character_id=self.character.character.character_id, ) .require_scopes(scopes) .require_valid() .first() ) except TokenInvalidError: logger.error("%s: Invalid token for fetching calendars", self) error = self.ERROR_TOKEN_INVALID except TokenExpiredError: logger.error("%s: Token expired for fetching calendars", self) error = self.ERROR_TOKEN_EXPIRED else: if not token: logger.error("%s: No token found with sufficient scopes", self) error = self.ERROR_TOKEN_INVALID return token, error class IngameEvents(models.Model): event_id = models.PositiveBigIntegerField( primary_key=True, help_text="The EVE ID of the event" ) owner = models.ForeignKey( Owner, on_delete=models.CASCADE, help_text="Event holder", ) event_start_date = models.DateTimeField() event_end_date = models.DateTimeField(blank=True, null=True) title = models.CharField(max_length=128) text = models.TextField() event_owner_id = models.IntegerField(null=True) owner_type = models.CharField(max_length=128) owner_name = models.CharField(max_length=128) host = models.ForeignKey( EventHost, on_delete=models.CASCADE, default=1, help_text=_("Host entity for the event"), ) importance = models.CharField(max_length=128) duration = models.CharField(max_length=128)
[ 11748, 7007, 198, 11748, 33918, 198, 198, 6738, 19720, 1330, 309, 29291, 198, 6738, 4818, 8079, 1330, 28805, 12514, 11, 4818, 8079, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 1...
2.3212
2,500
import sacred from sacred import Experiment import os.path as osp import pandas as pd import scipy.io as sio import numpy as np from sacred import SETTINGS SETTINGS.CONFIG.READ_ONLY_CONFIG=False
[ 11748, 13626, 198, 6738, 13626, 1330, 29544, 198, 198, 11748, 28686, 13, 6978, 355, 267, 2777, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 629, 541, 88, 13, 952, 355, 264, 952, 198, 11748, 299, 32152, 355, 45941, 198, 198, ...
3
66
import numpy as np arrs = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(arrs[[0,2]])
[ 198, 11748, 299, 32152, 355, 45941, 198, 198, 3258, 82, 796, 45941, 13, 18747, 26933, 58, 16, 11, 362, 11, 513, 4357, 685, 19, 11, 642, 11, 718, 4357, 685, 22, 11, 807, 11, 860, 11907, 8, 198, 4798, 7, 3258, 82, 30109, 15, 11, ...
1.875
48
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- from ....proto import onnx_proto from ...common._registration import register_converter register_converter('arrayFeatureExtractor', convert_array_feature_extractor)
[ 2, 16529, 45537, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 198, 2, 5964, 1321, 13, 198, 2, 16529, 35937, 198, 1...
5.206522
92
# one identifier for one types of dict # for instance, DK_SOME_KEY means this is a key for a data_dict DK_BATCH_SIZE = "batch_size" DK_PAD = "pad" # DK: general purpose data_dict DK_SRC_WID = "src_wid" # src = msg + ctx DK_SRC_WID_MASK = "src_wid_mask" DK_SRC_SEQ_MASK = "src_seq_mask" DK_MSG_WID = "msg_wid" # msg is usually shorter than ctx DK_MSG_WID_MASK = "msg_wid_mask" DK_CTX_WID = "ctx_wid" # msg is usually shorter than ctx DK_CTX_WID_MASK = "ctx_wid_mask" DK_SRC_POS = "src_pos" DK_SRC_NER = "src_ner" DK_SRC_SEG_LISTS = "src_seg_lists" DK_TGT_GEN_WID = "tgt_gen_wid" DK_TGT_CPY_WID = "tgt_cpy_wid" DK_TGT_CPY_GATE = "tgt_cpy_gate" DK_TGT_N_TOKEN = "tgt_n_token" DK_TGT_SEG_LISTS = "tgt_seg_lists" DK_SRC_IOB = "src_iob" # iob: SQuAD QG specific DK_DOC_WID = "doc_wid" DK_DOC_SEG_LISTS = "doc_seg_lists" DK_DOC_WID_MASK = "doc_wid_mask" DK_DOC_SENTS_WID = "doc_sents_wid" DK_DOC_SENTS_WID_MASK = "doc_sents_wid_mask" DK_TITLE_WID = "title_wid" DK_TQ_SEG_LISTS = "title_seg_lists" DK_TITLE_WID_MASK = "title_wid_mask" DK_CONCEPT_SEG_LISTS = "concept_seg_lists" DK_TGT_CONCEPT_GEN_WID = "tgt_concept_gen_wid" # concept gen specific DK_TGT_CONCEPT_CPY_WID = "tgt_concept_cpy_wid" DK_TGT_CONCEPT_CPY_GATE = "tgt_concept_cpy_gate" DK_TGT_CONCEPT_N_TOKEN = "tgt_concept_n_token" DK_TGT_TITLE_GEN_WID = "tgt_title_gen_wid" # title gen specific DK_TGT_TITLE_CPY_WID = "tgt_title_cpy_wid" DK_TGT_TITLE_CPY_GATE = "tgt_title_cpy_gate" DK_TGT_TITLE_N_TOKEN = "tgt_title_n_token" DK_SENT_DEPEND_GRAPH_LIST = "sent_depend_graph_list" DK_DOC_KW_DIST_GRAPH = "doc_kw_dist_graph" DK_DOC_SENT_MEAN_TFIDF_SIM_GRAPH = "doc_sent_mean_tfidf_sim_graph" DK_DOC_SENT_PAIR_TFIDF_SIM_GRAPH = "doc_sent_pair_tfidf_sim_graph" DK_DOC_SENT_WORD_OVERLAP_GRAPH = "doc_sent_word_overlap_graph" DK_G2S_WID_GRAPH = "graph2seq_wid_graph" SQGK_SRC_W_LIST = "src_word_list" # SQGK: SQuAD data reader keys SQGK_SRC_IOB_LIST = "src_iob_list" SQGK_SRC_POS_LIST = "src_pos_list" SQGK_SRC_NER_LIST = "src_ner_list" SQGK_TGT_W_LIST = "tgt_word_list" SQGK_DATA_LIST = "data_list" SQGK_IOB_T2I = "iob_t2i" SQGK_POS_T2I = "pos_t2i" SQGK_NER_T2I = "ner_t2i" CHKPT_COMPLETED_EPOCHS = "completed_epochs" # CHKPT: checkpoint dict keys CHKPT_MODEL = "model" CHKPT_OPTIMIZER = "optimizer" CHKPT_METADATA = "metadata" CHKPT_PARAMS = "params" CHKPT_BEST_EVAL_RESULT = "best_eval_result" CHKPT_BEST_EVAL_EPOCH = "best_eval_epoch" CHKPT_PAST_EVAL_RESULTS = "past_eval_results" GK_EDGE_WEIGHT = "edge_weight" # GK: graph keys GK_EDGE_WORD_PAIR = "edge_word_pair" GK_EDGE_GV_IDX_PAIR = "edge_v_idx_pair" GK_EDGE_TYPE = "edge_type" GK_EDGE_DIR = "edge_directed" GK_EDGE_UNDIR = "edge_undirected" GK_SENT_DEP = "sentence_depends"
[ 2, 530, 27421, 329, 530, 3858, 286, 8633, 198, 2, 329, 4554, 11, 32975, 62, 50, 13649, 62, 20373, 1724, 428, 318, 257, 1994, 329, 257, 1366, 62, 11600, 198, 48510, 62, 33, 11417, 62, 33489, 796, 366, 43501, 62, 7857, 1, 198, 48510...
1.943478
1,380
# -*- coding: utf-8 -*- """ .. module:: register.views.list :synopsis: View to list all registered users .. moduleauthor:: Chris Bartlett """ from django.urls import reverse from django.views.generic import TemplateView from register.api.utils.make_request import make_request
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 492, 8265, 3712, 7881, 13, 33571, 13, 4868, 198, 220, 220, 1058, 28869, 24608, 25, 3582, 284, 1351, 477, 6823, 2985, 198, 198, 492, 8265, 9800, 3712, 5180, ...
3.329412
85
import unittest from prymate import evaluator, objects from prymate.lexer import Lexer from prymate.parser import Parser if __name__ == "__main__": unittest.main()
[ 11748, 555, 715, 395, 198, 198, 6738, 279, 563, 9830, 1330, 5418, 84, 1352, 11, 5563, 198, 6738, 279, 563, 9830, 13, 2588, 263, 1330, 17210, 263, 198, 6738, 279, 563, 9830, 13, 48610, 1330, 23042, 263, 628, 198, 198, 361, 11593, 367...
2.819672
61
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # A simple native client in python. # All this client does is echo the text it receives back at the extension. import sys import struct if __name__ == '__main__': Main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 15069, 357, 66, 8, 2321, 383, 18255, 1505, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, ...
3.524272
103
from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. from django.dispatch import receiver # ( , ) # @receiver(post_save, sender=AppUser) # def create_profile(sender, instance, **kwargs): # print(' ') # if not Profile.objects.filter(user=instance).exists(): # Profile.objects.create(user=instance)
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 27741, 12982, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 13, 12683, 874, 1330, 1281, 62, 21928, 198, 6738, 42625, 14208, 13...
2.924528
159
# -*- coding: utf-8 -*- # Copyright 2017 Edoardo Pasca # # 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. """ Created on Wed Jun 7 09:57:13 2017 @author: ofn77899 """ from distutils.core import setup #from setuptools import setup, find_packages import os import sys cil_version = "20.07.4" setup( name="ccpi-viewer", version=cil_version, packages=['ccpi','ccpi.viewer', 'ccpi.viewer.utils'], install_requires=['numpy','vtk'], # Project uses reStructuredText, so ensure that the docutils get # installed or upgraded on the target machine #install_requires=['docutils>=0.3'], # package_data={ # # If any package contains *.txt or *.rst files, include them: # '': ['*.txt', '*.rst'], # # And include any *.msg files found in the 'hello' package, too: # 'hello': ['*.msg'], # }, zip_safe = False, # metadata for upload to PyPI author="Edoardo Pasca", author_email="edo.paskino@gmail.com", description='CCPi Core Imaging Library - VTK Viewer Module', license="Apache v2.0", keywords="3D data viewer", url="http://www.ccpi.ac.uk", # project home page, if any # could also include long_description, download_url, classifiers, etc. )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 220, 220, 15069, 2177, 1717, 11953, 78, 350, 42688, 198, 2, 198, 2, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, ...
2.842276
615
""" Defines the dataclass for holding training related arguments. """ import json import math import sys from dataclasses import asdict, dataclass, field from enum import Enum from typing import Any, Dict, List, Optional, Union from das.models.model_args import ModelArguments from das.utils.basic_utils import create_logger logger = create_logger(__name__) SUPPORTED_MODEL_ARGUMENTS = { "generate_metrics": GenerateMetricsTaskArguments, "generate_robustness_metrics": GenerateRobustnessMetricsTaskArguments, "generate_shap_values": GenerateShapValuesTaskArguments, "generate_shap_visualizations": GenerateShapVisualizationsTaskArguments, "feature_perturbation": FeaturePerturbationTaskArguments, "similar_images_clustering": SimilarImagesClusteringTaskArguments, "feature_perturbation_analysis": FeaturePerturbationAnalysisTaskArguments, }
[ 37811, 198, 7469, 1127, 262, 4818, 330, 31172, 329, 4769, 3047, 3519, 7159, 13, 198, 37811, 198, 198, 11748, 33918, 198, 11748, 10688, 198, 11748, 25064, 198, 6738, 4818, 330, 28958, 1330, 355, 11600, 11, 4818, 330, 31172, 11, 2214, 198...
3.116197
284
""" Perform sanitization check prior of releasing the app as ready. """ def main(): "Perform sanitization checks" pass
[ 37811, 198, 5990, 687, 5336, 270, 1634, 2198, 3161, 286, 13011, 262, 598, 355, 3492, 13, 198, 37811, 198, 198, 4299, 1388, 33529, 198, 220, 220, 220, 366, 5990, 687, 5336, 270, 1634, 8794, 1, 198, 220, 220, 220, 1208, 198 ]
3.121951
41
import asyncio import traceback from asyncio import StreamWriter, StreamReader, Task from .BaseClientHandler import BaseClientHandler from data import Message
[ 11748, 30351, 952, 198, 11748, 12854, 1891, 198, 6738, 30351, 952, 1330, 13860, 34379, 11, 13860, 33634, 11, 15941, 198, 198, 6738, 764, 14881, 11792, 25060, 1330, 7308, 11792, 25060, 198, 6738, 1366, 1330, 16000, 628 ]
4.472222
36
# chat/consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from .models import RoomControl from channels.db import database_sync_to_async
[ 2, 8537, 14, 5936, 31260, 13, 9078, 198, 11748, 33918, 198, 6738, 9619, 13, 41357, 13, 732, 1443, 5459, 1330, 1081, 13361, 1135, 1443, 5459, 49106, 198, 6738, 764, 27530, 1330, 10096, 15988, 198, 6738, 9619, 13, 9945, 1330, 6831, 62, ...
3.659574
47
import numpy as np from cnnclustering._primitive_types import P_AINDEX, P_AVALUE from cnnclustering import _types, _fit COMPONENT_ALT_KW_MAP = { "input": "input_data", "data": "input_data", "n": "neighbours", "na": "neighbours", "nb": "neighbour_neighbours", "getter": "neighbours_getter", "ogetter": "neighbours_getter_other", "ngetter": "neighbours_getter", "ongetter": "neighbours_getter_other", "dgetter": "distance_getter", "checker": "similarity_checker", "q": "queue", } COMPONENT_KW_TYPE_ALIAS_MAP = { "neighbour_neighbours": "neighbours", "neighbour_getter_other": "neighbours_getter", } COMPONENT_NAME_TYPE_MAP = { "input_data": { "components_mview": _types.InputDataExtComponentsMemoryview, "neighbourhoods_mview": _types.InputDataExtNeighbourhoodsMemoryview }, "neighbours_getter": { "brute_force": _types.NeighboursGetterExtBruteForce, "lookup": _types.NeighboursGetterExtLookup, }, "distance_getter": { "metric": _types.DistanceGetterExtMetric, "lookup": _types.DistanceGetterExtLookup, }, "neighbours": { "vector": _types.NeighboursExtVector, "uset": _types.NeighboursExtCPPUnorderedSet, "vuset": _types.NeighboursExtVectorCPPUnorderedSet, }, "metric": { "dummy": _types.MetricExtDummy, "precomputed": _types.MetricExtPrecomputed, "euclidean": _types.MetricExtEuclidean, "euclidean_r": _types.MetricExtEuclideanReduced, "euclidean_periodic_r": _types.MetricExtEuclideanPeriodicReduced, "euclidean_reduced": _types.MetricExtEuclideanReduced, "euclidean_periodic_reduced": _types.MetricExtEuclideanPeriodicReduced, }, "similarity_checker": { "contains": _types.SimilarityCheckerExtContains, "switch": _types.SimilarityCheckerExtSwitchContains, "screen": _types.SimilarityCheckerExtScreensorted, }, "queue": { "fifo": _types.QueueExtFIFOQueue }, "fitter": { "bfs": _fit.FitterExtBFS, "bfs_debug": _fit.FitterExtBFSDebug } } def prepare_pass(data): """Dummy preparation hook Use if no preparation of input data is desired. Args: data: Input data that should be prepared. Returns: (data,), {} """ return (data,), {} def prepare_points_from_parts(data): r"""Prepare input data points Use when point components are passed as sequence of parts, e.g. as >>> input_data, meta = prepare_points_parts([[[0, 0], ... [1, 1]], ... [[2, 2], ... [3,3]]]) >>> input_data array([[0, 0], [1, 1], [2, 2], [3, 3]]) >>> meta {"edges": [2, 2]} Recognised data formats are: * Sequence of length *d*: interpreted as 1 point with *d* components. * 2D Sequence (sequence of sequences all of same length) with length *n* (rows) and width *d* (columns): interpreted as *n* points with *d* components. * Sequence of 2D sequences all of same width: interpreted as parts (groups) of points. The returned input data format is compatible with: * `cnnclustering._types.InputDataExtPointsMemoryview` Args: data: Input data that should be prepared. Returns: * Formatted input data (NumPy array of shape :math:`\sum n_\mathrm{part}, d`) * Dictionary of meta-information Notes: Does not catch deeper nested formats. """ try: d1 = len(data) except TypeError as error: raise error finished = False if d1 == 0: # Empty sequence data = [np.array([[]])] finished = True if not finished: try: d2 = [len(x) for x in data] all_d2_equal = (len(set(d2)) == 1) except TypeError: # 1D Sequence data = [np.array([data])] finished = True if not finished: try: d3 = [len(y) for x in data for y in x] all_d3_equal = (len(set(d3)) == 1) except TypeError: if not all_d2_equal: raise ValueError( "Dimension mismatch" ) # 2D Sequence of sequences of same length data = [np.asarray(data)] finished = True if not finished: if not all_d3_equal: raise ValueError( "Dimension mismatch" ) # Sequence of 2D sequences of same width data = [np.asarray(x) for x in data] finished = True meta = {} meta["edges"] = [x.shape[0] for x in data] data_args = (np.asarray(np.vstack(data), order="C", dtype=P_AVALUE),) data_kwargs = {"meta": meta} return data_args, data_kwargs def prepare_neighbourhoods(data): """Prepare neighbourhood information by padding Args: data: Expects a sequence of sequences with neighbour indices. Returns: Data as a 2D NumPy array of shape (#points, max. number of neighbours) and a 1D array with the actual number of neighbours for each point (data args). Also returns meta information (data kwargs). """ n_neighbours = [len(s) for s in data] pad_to = max(n_neighbours) data = [ np.pad(a, (0, pad_to - n_neighbours[i]), mode="constant", constant_values=0) for i, a in enumerate(data) ] meta = {} data_args = ( np.asarray(data, order="C", dtype=P_AINDEX), np.asarray(n_neighbours, dtype=P_AINDEX) ) data_kwargs = {"meta": meta} return data_args, data_kwargs
[ 11748, 299, 32152, 355, 45941, 198, 198, 6738, 269, 20471, 565, 436, 1586, 13557, 19795, 1800, 62, 19199, 1330, 350, 62, 32, 12115, 6369, 11, 350, 62, 10116, 1847, 8924, 198, 6738, 269, 20471, 565, 436, 1586, 1330, 4808, 19199, 11, 48...
2.105714
2,800
#!/usr/bin/env python from __future__ import print_function from ipywidgets import * from IPython.display import display from getpass import getpass import glob import os import stat import paramiko from string import Template from os.path import expanduser from pkg_resources import resource_string from IPython.core.magic import (register_line_magic, register_cell_magic,register_line_cell_magic) import hashlib from itertools import izip,cycle from IPython.display import IFrame USERNAME = os.environ['USER'] CONF_DIR='.rg_conf' CONF_MOD=int('700', 8) # exclusive access CONF_FILE='%s/%s'%(CONF_DIR, USERNAME) #ROGER_PRJ='/projects/class/jhub/users' #JUPYTER_HOME='/mnt/jhub/users' ROGER_PRJ='/projects/jupyter' JUPYTER_HOME='/home' #@register_line_magic #def roger(line): # Roger() #del roger
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 20966, 88, 28029, 11407, 1330, 1635, 198, 6738, 6101, 7535, 13, 13812, 1330, 3359, 198, 6738, 651, 6603, 1330, 651, 6603, 198, ...
2.814035
285
import subprocess import os import shutil import time import yaml import sys import logging logger = logging.getLogger(__name__) if __name__ == '__main__': compile()
[ 11748, 850, 14681, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 11748, 640, 198, 11748, 331, 43695, 198, 11748, 25064, 198, 11748, 18931, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 198, 198, 361, 11593, ...
3.092593
54
# Generated by Django 2.1.11 on 2019-08-14 03:10 from django.db import migrations
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 1157, 319, 13130, 12, 2919, 12, 1415, 7643, 25, 940, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
2.8
30
"""A CSV annotation writer that reads the bbox in x, y, w, h format.""" from discolight.annotations import BoundingBox from .types import CSVRow, CSVAnnotationLoader
[ 37811, 32, 44189, 23025, 6260, 326, 9743, 262, 275, 3524, 287, 2124, 11, 331, 11, 266, 11, 289, 5794, 526, 15931, 198, 6738, 1221, 349, 432, 13, 34574, 602, 1330, 347, 9969, 14253, 198, 6738, 764, 19199, 1330, 9429, 13024, 322, 11, ...
3.553191
47
from days import day09 from ddt import ddt, data, unpack import unittest import util
[ 6738, 1528, 1330, 1110, 2931, 201, 198, 6738, 288, 28664, 1330, 288, 28664, 11, 1366, 11, 555, 8002, 201, 198, 11748, 555, 715, 395, 201, 198, 11748, 7736, 201, 198, 201, 198 ]
2.84375
32
"""A utility module which has FD-related functions. This module mostly exists for L{clean_fds}, so it can be imported without accidentally getting a reactor or something else that might create a critical file descriptor. """ import os import resource def clean_fds(): """Close all non-stdio file descriptors. This should be called at the beginning of a program to avoid inheriting any unwanted file descriptors from the invoking process. Unfortunately, this is really common in unix! """ rlimit_nofile = resource.getrlimit(resource.RLIMIT_NOFILE)[1] total_descriptors = min(4096, rlimit_nofile) for fd in range(3, total_descriptors): try: os.close(fd) except OSError: pass
[ 37811, 32, 10361, 8265, 543, 468, 30002, 12, 5363, 5499, 13, 198, 198, 1212, 8265, 4632, 7160, 329, 406, 90, 27773, 62, 69, 9310, 5512, 523, 340, 460, 307, 17392, 1231, 198, 4134, 23961, 1972, 257, 21905, 393, 1223, 2073, 326, 1244, ...
2.922179
257
""" This script creates users in a JAMF Pro Server instance from an LDAP query. """ # Copyright 2020 Dalton Durst # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. import sys from collections import namedtuple from multiprocessing.pool import ThreadPool from typing import List from json.decoder import JSONDecodeError import ldap import requests from ldap.controls import SimplePagedResultsControl from conf import ( JAMF_PASSWORD, JAMF_URL, JAMF_USERNAME, LDAP_BIND_PASSWORD, LDAP_BIND_URI, LDAP_BIND_USERNAME, LDAP_FILTER, LDAP_INSECURE, LDAP_SEARCH_DN_LIST, ) JAMF_AUTH = requests.auth.HTTPBasicAuth(JAMF_USERNAME, JAMF_PASSWORD) SESSION = requests.Session() User = namedtuple("User", ["sAMAccountName", "email", "last_name", "first_name"]) def eprint(*args, **kwargs): """Like print, but outputs to stderr.""" print(*args, file=sys.stderr, **kwargs) def results_for_dn(directory: ldap.ldapobject, base_dn: str, filter: str) -> List[User]: """Returns a list of User objects found in the directory object for filter :param directory: A ldap.LDAPObject that has already been bound to a directory. :param base_dn: The base of the directory tree to run the search filter against. :param filter: The LDAP search filter to run on base_dn using directory. """ req_ctrl = SimplePagedResultsControl(True, size=5000, cookie="") known_ldap_resp_ctrls = { SimplePagedResultsControl.controlType: SimplePagedResultsControl, } # Send search request msgid = directory.search_ext( base_dn, ldap.SCOPE_SUBTREE, filterstr=LDAP_FILTER, serverctrls=[req_ctrl] ) results = [] while True: __, result_data, __, serverctrls = directory.result3( msgid, resp_ctrl_classes=known_ldap_resp_ctrls ) results.extend( [ User( ldap_entry["sAMAccountName"][0].decode(), ldap_entry["mail"][0].decode(), ldap_entry["sn"][0].decode(), ldap_entry["givenName"][0].decode(), ) for __, ldap_entry in result_data ] ) page_controls = [ control for control in serverctrls if control.controlType == SimplePagedResultsControl.controlType ] if page_controls: if page_controls[0].cookie: # Copy cookie from response control to request control req_ctrl.cookie = page_controls[0].cookie msgid = directory.search_ext( base_dn, ldap.SCOPE_SUBTREE, filterstr=LDAP_FILTER, serverctrls=[req_ctrl], ) else: break else: eprint("Warning: Server ignores RFC 2696 control.") break return results def create_user_in_jamf(user: User): """ Creates a user in the JPS :param user: A User object which will be used to create the JPS user. This function uses the following module variables: * SESSION must be a requests.Session instance * JAMF_AUTH must be a requests.auth interface instance * JAMF_URL must be the full base URL of a JAMF instance. """ eprint("Attempting to create", user.sAMAccountName) xml = """ <user> <name>{name}</name> <full_name>{last_name}, {first_name}</full_name> <email>{email}</email> </user> """.format( name=user.sAMAccountName, last_name=user.last_name, first_name=user.first_name, email=user.email, ).encode() r = SESSION.post( JAMF_URL + "/JSSResource/users/id/-1", data=xml, headers={"Content-Type": "application/xml", "Accept": "application/xml"}, auth=JAMF_AUTH, ) try: r.raise_for_status() except requests.exceptions.RequestException as e: eprint("Failed to create user with username", user.sAMAccountName) eprint(e) eprint(r.text) else: print(user.sAMAccountName) if __name__ == "__main__": main()
[ 37811, 198, 1212, 4226, 8075, 2985, 287, 257, 449, 2390, 37, 1041, 9652, 4554, 422, 281, 27178, 2969, 12405, 13, 198, 37811, 198, 198, 2, 15069, 12131, 33261, 11164, 301, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, ...
2.410304
2,174
# coding:utf-8 ''' from http://www.pythonchallenge.com/pc/def/integrity.html ''' un = 'BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M\x07<]\xc9\x14\xe1BA\x06\xbe\x084' pw = 'BZh91AY&SY\x94$|\x0e\x00\x00\x00\x81\x00\x03$ \x00!\x9ah3M\x13<]\xc9\x14\xe1BBP\x91\xf08' if __name__ == '__main__': print bz2_un() print bz2_pw()
[ 2, 19617, 25, 40477, 12, 23, 198, 198, 7061, 6, 198, 6738, 2638, 1378, 2503, 13, 29412, 36747, 3540, 13, 785, 14, 14751, 14, 4299, 14, 18908, 10138, 13, 6494, 198, 7061, 6, 198, 198, 403, 796, 705, 33, 57, 71, 6420, 4792, 5, 230...
1.575221
226
from flask import Flask, jsonify, request from flask_cors import CORS from twilio.twiml.messaging_response import MessagingResponse, Message from twilio.rest import Client import sqlconnector as sql from datetime import datetime import os # configuration DEBUG = True twilio_sid = os.environ.get('TWILIO_SID') twilio_secret = os.environ.get('TWILIO_SECRET') client = Client(twilio_sid, twilio_secret) # instantiate the app app = Flask(__name__) app.config.from_object(__name__) # enable CORS CORS(app, resources={r'/*': {'origins': '*'}}) if __name__ == '__main__': app.run(host="192.168.0.21")
[ 6738, 42903, 1330, 46947, 11, 33918, 1958, 11, 2581, 198, 6738, 42903, 62, 66, 669, 1330, 327, 20673, 198, 6738, 665, 346, 952, 13, 4246, 320, 75, 13, 37348, 3039, 62, 26209, 1330, 10626, 3039, 31077, 11, 16000, 198, 6738, 665, 346, ...
2.761468
218
#!/usr/bin/env python from scapy.all import * import dpkt import argparse import sys if __name__ == '__main__': sys.exit(main())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 6738, 629, 12826, 13, 439, 1330, 1635, 198, 11748, 288, 79, 21841, 198, 11748, 1822, 29572, 198, 11748, 25064, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, ...
2.627451
51
#!/usr/bin/env python3 # coding=utf-8 from __future__ import print_function from jsonrpcclient.http_client import HTTPClient from url_util import endpoint import argparse import simplejson if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 19617, 28, 40477, 12, 23, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 33918, 81, 79, 535, 75, 1153, 13, 4023, 62, 16366, 1330, 14626, 11792, 198, 6738,...
3.038961
77
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
[ 6738, 42903, 62, 25410, 282, 26599, 1330, 16363, 2348, 26599, 198, 198, 9945, 796, 16363, 2348, 26599, 3419, 628 ]
3.157895
19
__version__ = "0.0.1" from .revx_output_siip import SIIPTimeSeriesMetadata, concat, max_fiber_size, match_points
[ 834, 9641, 834, 796, 366, 15, 13, 15, 13, 16, 1, 198, 198, 6738, 764, 18218, 87, 62, 22915, 62, 13396, 541, 1330, 311, 3978, 47, 7575, 27996, 9171, 14706, 11, 1673, 265, 11, 3509, 62, 69, 1856, 62, 7857, 11, 2872, 62, 13033, 198...
2.533333
45
# -*- coding: utf-8 -*- """ Created on Sun Jan 07 07:52:52 2018 @author: MVGrigoriev @task: kNN method """ import pandas import numpy as np from sklearn.neighbors import KNeighborsClassifier # Import class from scikit-learn from sklearn.model_selection import KFold # Import KFold function from sklearn.model_selection import cross_val_score # Import metrics for cross validation from sklearn.preprocessing import scale # Import Scale function data = pandas.read_csv('wine.data', header=None) # Import data target = data[0] # Extract target features = data.drop(0, axis=1) # Extract features kf = KFold(n_splits=5, shuffle=True, random_state=42) # At what k is the maximum quality obtained without normalization of characteristics? # # What is the maximum quality without the normalization of characteristics (the number in the scale from 0 to 1)? # listOfAccuracy = [] for i in range(1, 51): neigh = KNeighborsClassifier(n_neighbors=i) neigh.fit(features, target) cvs = cross_val_score(neigh, features, target, cv=kf, scoring='accuracy') cvsValue = np.mean(cvs) listOfAccuracy.append(cvsValue) optValue = max(listOfAccuracy) optIndex = listOfAccuracy.index(optValue) with open('2_1.txt', 'w') as f1: print(optIndex+1, file=f1, end='') with open('2_2.txt', 'w') as f2: print(round(optValue, 2), file=f2, end='') # Which optimal K is obtained after the normalization of the characteristics? # # What is the maximum quality after the normalization of characteristics (a number in the range from 0 to 1)? # features = scale(features) listOfAccuracy = [] for i in range(1, 51): neigh = KNeighborsClassifier(n_neighbors=i) neigh.fit(features, target) cvs = cross_val_score(neigh, features, target, cv=kf, scoring='accuracy') cvsValue = np.mean(cvs) listOfAccuracy.append(cvsValue) optValue = max(listOfAccuracy) optIndex = listOfAccuracy.index(optValue) with open('2_3.txt', 'w') as f3: print(optIndex+1, file=f3, end='') with open('2_4.txt', 'w') as f4: print(round(optValue, 2), file=f4, end='')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 3825, 2365, 8753, 8753, 25, 4309, 25, 4309, 2864, 198, 198, 31, 9800, 25, 32947, 38, 4359, 273, 11203, 198, 198, 31, 35943, 25, 479, 6144, 2446...
2.742147
764
# ipython utils import os import sys import time import yaml import datetime from pathlib import Path from IPython import get_ipython from IPython.core.magic import (register_line_magic, register_cell_magic, register_line_cell_magic) import warnings; warnings.simplefilter('ignore') start = time.time() os.environ.update({ "GROUP": "tutorial", "VERSION": "v1", "KOPFLOG": "false", "DOCKER_TLS_VERIFY": "1", "DOCKER_HOST": "tcp://127.0.0.1:32770", "DOCKER_CERT_PATH": str(Path(os.environ["HOME"], ".minikube/certs")), "MINIKUBE_ACTIVE_DOCKERD": "minikube", "IMAGEPULL": "Never", "REPO": "tutorial", }) workdir = (Path(os.environ["GOPATH"], "src", "digi.dev", "tutorial", "workdir")) os.environ["WORKDIR"] = str(workdir)
[ 2, 20966, 7535, 3384, 4487, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 331, 43695, 198, 11748, 4818, 8079, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 6738, 6101, 7535, 1330, 651, 62, 541, 7535, 220, 198, 6738,...
2.199468
376
#!/usr/bin/python3 # Run the camera with a 180 degree rotation. from qt_gl_preview import * from picamera2 import * import time picam2 = Picamera2() preview = QtGlPreview(picam2) preview_config = picam2.preview_configuration() preview_config["transform"] = libcamera.Transform(hflip=1, vflip=1) picam2.configure(preview_config) picam2.start() time.sleep(5)
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 2, 5660, 262, 4676, 351, 257, 11546, 4922, 13179, 13, 198, 198, 6738, 10662, 83, 62, 4743, 62, 3866, 1177, 1330, 1635, 198, 6738, 8301, 18144, 17, 1330, 1635, 198, 11748, 640, 198,...
2.661765
136
#!/usr/bin/env python from __future__ import unicode_literals from prompt_toolkit import prompt if __name__ == '__main__': print('If you press meta-! or esc-! at the following prompt, you can enter system commands.') answer = prompt('Give me some input: ', enable_system_bindings=True) print('You said: %s' % answer)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 6738, 6152, 62, 25981, 15813, 1330, 6152, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, ...
3.122642
106
import unittest import searcheval.metrics as sm if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 198, 11748, 9622, 2395, 2100, 13, 4164, 10466, 355, 895, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 198 ]
2.538462
39
# # 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. # # flake8: noqa from six import ( add_metaclass, iteritems, raise_from, string_types, text_type, ) from six.moves import configparser from six.moves.reprlib import Repr from six.moves.urllib.parse import parse_qs, urlsplit, urlunsplit from six.moves.urllib.parse import urlparse, urlencode from six.moves.urllib.request import urlopen, urlretrieve from six.moves.urllib.error import HTTPError try: maketrans = str.maketrans except AttributeError: from string import maketrans
[ 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 7330, 257, 4866, 286, 262, 13789, 379,...
3.109145
339
from collections import OrderedDict from dataclasses import dataclass from datetime import datetime from enum import Enum from typing import Optional, Set import discord import functools from .gameflags import GameFlagsManager from .playerdict import PlayerDict from .repoman import GameRepoManager from constants import colors, emoji, info, strings import utils VOTE_ALIASES = { '+': 'for', '-': 'against', 'abstain': 'abstain', 'against': 'against', 'del': 'remove', 'delete': 'remove', 'for': 'for', 'remove': 'remove', 'rm': 'remove', } VOTE_TYPES = ('for', 'against', 'abstain') class ProposalManager(GameRepoManager): def has_proposal(self, n: int) -> bool: return isinstance(n, int) and 1 <= n <= len(self.proposals) def get_proposal(self, n: int) -> Optional[Proposal]: if self.has_proposal(n): return self.proposals[n - 1]
[ 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 19720, 1330, 32233, 11, 5345, 198, 11748, 36446, 198, 1...
2.691176
340
# -*- coding: utf-8 -*- from ..stanzas import Stanza from ..errors import makeStanzaError from ..protocols.stream_mgmt import NS_URI
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11485, 14192, 89, 292, 1330, 7299, 4496, 198, 6738, 11485, 48277, 1330, 787, 32140, 4496, 12331, 198, 6738, 11485, 11235, 4668, 82, 13, 5532, 62, 11296, 16762, 1330,...
2.851064
47
from dataclasses import dataclass
[ 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 628 ]
3.888889
9
from unittest import TestCase import pandas as pd from feature_extraction.pattern.pattern import Pattern from preprocessing.corpus import build_corpus
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 3895, 62, 2302, 7861, 13, 33279, 13, 33279, 1330, 23939, 198, 6738, 662, 36948, 13, 10215, 79, 385, 1330, 1382, 62, 10215, 79, 385, 628 ]
3.642857
42
from starlette.responses import Response from passlib.hash import pbkdf2_sha256 from starlette.websockets import WebSocketDisconnect from blockchain import Blockchain # from wallet import Wallet from fastapi import FastAPI, WebSocket import uvicorn import socket import requests as r from pydantic import BaseModel from fastapi.templating import Jinja2Templates import json import asyncio # from Utilities.algorithims import Algs import time as t import random import base64 from sys import getsizeof # from Utilities.cryptography_testing import Make_Keys # from Utilities.cryptography_testing import primary_addresses # from Utilities.cryptography_testing import Check_Wallet_Balance # from Utilities.cryptography_testing import Ring_CT # from Utilities.cryptography_testing import Decoy_addresses from Utilities.cryptography_testing import * from fastapi_signals import * ring_ct = Ring_CT() checkbalance = Check_Wallet_Balance() create_keys = Make_Keys() primary_addr = primary_addresses() decoy_addresses = Decoy_addresses() #imported templates #from fastapi.staticfiles import StaticFiles #imported staticfiles # { # "node": [ # "http://127.0.0.1:8000", "http://127.0.0.1:8001" # ] #} tags_metadata = [ {'name':'information', 'description': 'This will allow you to get info about the blockchain', 'name':'wallet', 'description': 'this will allow you to access your wallet and make wallets', 'name': 'transaction', 'description': 'transactions', 'name': 'mining', 'description': 'mining', 'name': 'nodes', 'description': 'adding nodes and replacing the chain', 'name': 'contracts', 'description': 'smart contracts on the blockchain' }] # CONSTANTS SERVER_NAME = 'Token Network' SERVER_HOST = '0.0.0.0' SERVER_PORT = 8000 SERVER_RELOAD = False DESCRIPTION = "Welcome to The Token Network, a blockchain network with a cryptocurrency called Token, it's like Dogecoin and Bitcoin but faster than Bitcoin and harder to mine than Dogecoin, welcome to the Future of the world." algs = Algs() S = socket.socket(socket.AF_INET, socket.SOCK_STREAM) hostname = socket.gethostname() IP = socket.gethostbyname(hostname) # wallet = Wallet() # class Phrase(BaseModel): # phrase: str app = FastAPI(title=SERVER_NAME, openapi_tags=tags_metadata, description=DESCRIPTION) templates = Jinja2Templates(directory="templates/") blockchain = Blockchain() """ Wallets should be made offline. """ # @app.post('/recover_wallet', tags=['wallet']) # async def recover_wallet(recover:Recover): # """ recover wallet with passphrase and publickey """ # is_valid = wallets.recover_wallet_with_passphrase(recover.passphrase) # if is_valid == True: # return {'message': 'Wallet recovery is successful!', 'private key': wallets.privatekey, 'public key': wallets.publickey, 'passphrase': recover.passphrase} # else: # return 'invalid publickey or passphrase!' if __name__ == '__main__': # hostname = socket.gethostname() # IP = socket.gethostbyname(hostname) # blockchain.replace_chain() uvicorn.run('main:app', host=SERVER_HOST, port=SERVER_PORT, reload=SERVER_RELOAD) # ran = run # while run == ran: # update = blockchain.replace_chain() # t.sleep(60.0)
[ 6738, 3491, 21348, 13, 16733, 274, 1330, 18261, 198, 6738, 1208, 8019, 13, 17831, 1330, 279, 65, 74, 7568, 17, 62, 26270, 11645, 198, 6738, 3491, 21348, 13, 732, 1443, 11603, 1330, 5313, 39105, 7279, 8443, 198, 6738, 11779, 1330, 29724,...
3.056933
1,089
import json from bunch import Bunch import os def get_config_from_json(json_file): """ Get the config from a json file :param json_file: :return: config(namespace) or config(dictionary) """ # parse the configurations from the config json file provided with open(json_file, 'r') as config_file: config_dict = json.load(config_file) # convert the dictionary to a namespace using bunch lib config = Bunch(config_dict) config = default_values(config) return config, config_dict
[ 11748, 33918, 198, 6738, 7684, 1330, 347, 3316, 198, 11748, 28686, 628, 198, 4299, 651, 62, 11250, 62, 6738, 62, 17752, 7, 17752, 62, 7753, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 3497, 262, 4566, 422, 257, 33918, 2393, ...
2.983146
178
import json from django.views import View from django.shortcuts import redirect, render from django.core.exceptions import ObjectDoesNotExist from django.contrib import messages from django.http.response import HttpResponseRedirect from rest_framework.renderers import TemplateHTMLRenderer from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authtoken.models import Token from user.services.user_service import UserService, TokenService from user.services.cookies_service import CookiesService from user.forms.user_forms import LoginForm, MagicLinkForm, RegisterUserForm from helpers.cache_adapter import CacheAdapter from user.serializers import RegisterUserSerializer, LoginUserSerializer, \ GenerateMagicLinkSerializer from user.services.magic_link_service import MagicLinkService from worker.send_email import send_email
[ 11748, 33918, 198, 198, 6738, 42625, 14208, 13, 33571, 1330, 3582, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 18941, 11, 8543, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 9515, 13921, 3673, 3109, 396, 198, 6738, 42625,...
3.991379
232
from apps.vadmin.system.models.celery_log import CeleryLog from apps.vadmin.system.models.config_settings import ConfigSettings from apps.vadmin.system.models.dict_data import DictData from apps.vadmin.system.models.dict_details import DictDetails from apps.vadmin.system.models.logininfor import LoginInfor from apps.vadmin.system.models.message_push import MessagePush from apps.vadmin.system.models.message_push import MessagePushUser from apps.vadmin.system.models.operation_log import OperationLog from apps.vadmin.system.models.save_file import SaveFile
[ 6738, 6725, 13, 85, 28482, 13, 10057, 13, 27530, 13, 7015, 88, 62, 6404, 1330, 15248, 1924, 11187, 198, 6738, 6725, 13, 85, 28482, 13, 10057, 13, 27530, 13, 11250, 62, 33692, 1330, 17056, 26232, 198, 6738, 6725, 13, 85, 28482, 13, 1...
3.522013
159
from django.conf.urls import url from .views import profile, hunterList, changePass urlpatterns = [ url(r'^$', profile, name='hunter_profile'), url(r'^password', changePass, name='hunter_password'), url(r'^list', hunterList, name='hunter_list') ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 6738, 764, 33571, 1330, 7034, 11, 19177, 8053, 11, 1487, 14478, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 19016, 7, 81, 6, 61, 3, 3256, 7034, 11, 1438, ...
2.857143
91
from scipy.sparse import dok_matrix import pandas as pd from cytoolz import itemmap
[ 6738, 629, 541, 88, 13, 82, 29572, 1330, 466, 74, 62, 6759, 8609, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 3075, 25981, 89, 1330, 2378, 8899, 628, 198 ]
2.866667
30
from django.db import migrations from backent.api import enums
[ 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 198, 198, 6738, 736, 298, 13, 15042, 1330, 551, 5700, 628, 628 ]
3.35
20
from .test_uk_base import TestUkBase ################################
[ 6738, 764, 9288, 62, 2724, 62, 8692, 1330, 6208, 28425, 14881, 628, 198, 29113, 198 ]
4.8
15
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2019-2020 European Commission (JRC); # Licensed under the EUPL (the 'Licence'); # You may not use this work except in compliance with the Licence. # You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl """ Harvest functions & annotate their :term:`dependencies <dependency>` to build :term:`pipeline`\\s. >>> from wltp.autograph import * >>> __name__ = "wltp.autograph" """ import functools as fnt import inspect import logging import re import sys from collections import ChainMap from inspect import Parameter from pathlib import Path from types import ModuleType from typing import ( Any, Callable, Collection, Iterable, List, Mapping, Pattern, Set, Tuple, Union, cast, ) from boltons.iterutils import first from boltons.setutils import IndexedSet as iset from graphtik import keyword, optional, sfx, sfxed from graphtik.base import Operation, func_name from graphtik.fnop import FnOp, reparse_operation_data from graphtik.modifier import is_sfx from .utils import Literal, Token, asdict, aslist, astuple try: from re import Pattern as RegexPattern except ImportError: # PY3.6 from typing import Pattern as RegexPattern log = logging.getLogger(__name__) _my_project_dir = Path(__file__).parent _FnKey = Union[Union[str, Pattern], Iterable[Union[str, Pattern]]] def camel_2_snake_case(word): """ >>> camel_2_snake_case("HTTPResponseCodeXYZ") 'http_response_code_xyz' From https://stackoverflow.com/a/1176023/548792 """ return re.sub(r"((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))", r"_\1", word).lower() def _is_in_my_project(item) -> bool: """UNUSED""" in_my_project = False try: path = inspect.getfile(item) except TypeError: pass # raised for builtins e.g.`sys` else: try: Path(path).relative_to(_my_project_dir) in_my_project = True except ValueError: pass # raised when unrelated return in_my_project _unset = Token("unset") # TODO: replace `_unset` with ... def autographed( fn=_unset, *, name=None, needs=_unset, provides=_unset, renames=_unset, returns_dict=_unset, aliases=_unset, inp_sideffects=_unset, out_sideffects=_unset, domain: Union[str, int, Collection] = None, **kws, ): """ Decorator adding ``_autograph`` func-attribute with overrides for :class:`Autograph`. :param name: the name of the operation. - If the same `name` has already been defined for the same `domain`, it is overwritten; otherwise, a new decoration is appended, so that :meth:`.Autograph.yield_wrapped_ops()` will produce more than one operations. - if not given, it will be derrived from the `fn` on wrap-time. :param domain: one or more list-ified domains to assign decors into (instead of the "default" domain); it allows to reuse the same function to build different operation, when later wrapped into an operation by :class:`.Autograph`. :param renames: mappings to rename both any matching the final `needs` & `provides` :param inp_sideffects: appended into `needs`; if a tuple, makes it a :class:`.sfxed` :param out_sideffects: appended into `provides`; if a tuple, makes it a :class:`.sfxed` :param kws: the rest arguments of :class:`graphtik.operation`, such as:: endured, parallel, marshalled, node_props The rest arguments (e.g. `needs`, etc) are coming from :class:`graphtik.operation`. """ kws.update( { k: v for k, v in locals().items() if v is not _unset and k not in "kws fn name domain".split() } ) if fn is _unset: return decorator return decorator(fn) def get_autograph_decors( fn, default=None, domain: Union[str, int, Collection] = None ) -> dict: """ Get the 1st match in `domain` of the `fn` :func:`autographed` special attribute. :param default: return this if `fn` non-autographed, or domain don't match :param domain: list-ified if a single str :return: the decors that will override :class:`Autograph` attributes, as found from the given `fn`, and for the 1st matching domain in `domain`:: <fn>(): _autograph (function-attribute) <domain> (dict) <name> (dict) <decors> (dict) """ for dmn in astuple(domain, "domain"): if hasattr(fn, "_autograph"): if dmn in fn._autograph: return fn._autograph[dmn] return default """ Example code hidden from Sphinx: >>> from graphtik import compose >>> aug = Autograph(['calc_', 'upd_'], { ... 'calc_p_available':{'provides': 'p_avail'}, ... 'calc_p_resist': {'provides': 'p_resist'}, ... 'calc_inertial_power': {'provides': 'p_inert'}, ... }) >>> ops = [aug.wrap_funcs(funcs.items()] >>> netop = compose('wltp', *(op for op in ops if op.provides)) """
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 13130, 12, 42334, 3427, 4513, 357, 41, 7397, 1776, 198, 2, 49962, 739, 262, 4576, 6489, 357, 1169, ...
2.405517
2,175
import pandas as pd import os import torch import numpy as np import argparse from trojai_utils import * # Get args parser = argparse.ArgumentParser(description="Generate embeddings") parser.add_argument('--embedding-type', type=str, help='Model architecture (one of "BERT", "DistilBERT", "GPT-2")') parser.add_argument('--n', type=int, default=1000, help='Number of embeddings of each sentiment to generate') parser.add_argument('--batch-size', type=int, default=50, help='Size of batches to feed into the language model for embedding generation') args = parser.parse_args() # Load in the data base_huggingface_path = "your path with the huggingface transformer files" base_data_path = "your file path with the reviews datasets" sentiment_data = pd.read_csv(os.path.join(base_data_path, "train_datasets.csv")) # Split by sentiment pos_data = sentiment_data[sentiment_data.sentiment==True].sample(args.n) neg_data = sentiment_data[sentiment_data.sentiment==False].sample(args.n) # Get random samples pos_reviews = list(np.asarray(pos_data.reviewText, dtype=str)) pos_labels = torch.ones(args.n) neg_reviews = list(np.asarray(neg_data.reviewText, dtype=str)) neg_labels = torch.zeros(args.n) # Make embeddings cls_first = (args.embedding_type == "DistilBERT") or (args.embedding_type == "BERT") tokenizer, embedding = get_LM(args.embedding_type, base_huggingface_path) pos_embeddings = batch_embeddings(pos_reviews, args.n, args.batch_size, tokenizer, embedding, cls_first) neg_embeddings = batch_embeddings(neg_reviews, args.n, args.batch_size, tokenizer, embedding, cls_first) # Save results base_embedding_path = "your path to save embeddings to" torch.save(pos_embeddings, os.path.join(base_embedding_path, args.embedding_type, "pos_embeddings{}.pt".format(args.n))) torch.save(neg_embeddings, os.path.join(base_embedding_path, args.embedding_type, "neg_embeddings{}.pt".format(args.n))) torch.save(pos_labels, os.path.join(base_embedding_path, args.embedding_type, "pos_labels{}.pt".format(args.n))) torch.save(neg_labels, os.path.join(base_embedding_path, args.embedding_type, "neg_labels{}.pt".format(args.n)))
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 28686, 198, 11748, 28034, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 1822, 29572, 198, 6738, 4161, 73, 1872, 62, 26791, 1330, 1635, 198, 198, 2, 3497, 26498, 198, 48610, 796, 1822, 29572...
2.70632
807
""" test pretrained models """ from __future__ import print_function import mxnet as mx from common import find_mxnet, modelzoo from common.util import download_file, get_gpus from score import score if __name__ == '__main__': gpus = get_gpus() assert len(gpus) > 0 batch_size = 16 * len(gpus) gpus = ','.join([str(i) for i in gpus]) download_data() test_imagenet1k_resnet(gpus=gpus, batch_size=batch_size) test_imagenet1k_inception_bn(gpus=gpus, batch_size=batch_size)
[ 37811, 198, 9288, 2181, 13363, 4981, 198, 37811, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 285, 87, 3262, 355, 285, 87, 198, 6738, 2219, 1330, 1064, 62, 36802, 3262, 11, 2746, 89, 2238, 198, 6738, 2219, 13, 22602...
2.525253
198
""" Provides Siren rendering support. """ from __future__ import unicode_literals from rest_framework.renderers import JSONRenderer
[ 37811, 198, 15946, 1460, 43904, 14837, 1104, 13, 198, 37811, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 1334, 62, 30604, 13, 10920, 19288, 1330, 19449, 49, 437, 11882, 628 ]
3.722222
36
import numpy as np __all__ = ( "standard_bipolar_sine", "double_bipolar_sine", "standard_bipolar", "double_bipolar", "semicircle", "double_semicircle", "gaussian", "double_gaussian", ) def semicircle(a, T): """Return semicircle bipolar wave with amplitude a (units of V) and period T (units of ms) args: a (float): Amplitude in Volts T (float): Period in ms """ if T < 0.01: raise ValueError("limit of Ferroelectric Tester") count = int(T * 1000) int_amp = int(2047 * a / 10) wf = [] for i in range(count): if i <= count / 2: wf.append(np.sqrt(1 - ((i - count / 4) / (count / 4)) ** 2)) else: wf.append( -1 * np.sqrt(1 - ((i - count / 2 - count / 4) / (count / 4)) ** 2) ) wf = np.array([int_amp * i + 2047 for i in wf]) return wf def double_semicircle(a, T): """Return double semicircle bipolar wave with amplitude a (units of V) and period T (units of ms) args: a (float): Amplitude in Volts T (float): Period in ms """ wf = np.concatenate((semicircle(a, T / 2), semicircle(a, T / 2))) return wf def standard_bipolar(a, T): """Return standard bipolar triangle wave with amplitude a (units of V) and period T (units of ms) args: a (float): Amplitude in Volts T (float): Period in ms """ if T < 0.01: raise ValueError("limit of Ferroelectric Tester") count = int(T * 1000) int_amp = int(2047 * a / 10) step = 4 / (count) wf = [] for i in range(count): if i <= count / 4: wf.append(i * step) elif i > count / 4 and i <= 3 * count / 4: wf.append(wf[i - 1] - step) else: wf.append(wf[i - 1] + step) wf = np.array([int_amp * i + 2047 for i in wf]) return wf def double_bipolar(a, T): """Return double bipolar triangle wave with amplitude a (units of V) and period T (units of ms) args: a (float): Amplitude in Volts T (float): Period in ms """ wf = np.concatenate((standard_bipolar(a, T / 2), standard_bipolar(a, T / 2))) return wf def standard_bipolar_sine(a, T): """Return standard bipolar sine wave with amplitude a (units of V) and period T (units of ms) args: a (float): Amplitude in Volts T (float): Period in ms """ if T < 0.01: raise ValueError("limit of Ferroelectric Tester") count = int(T * 1000) int_amp = int(2047 * a / 10) wf = np.array( [int_amp * np.sin(2 * np.pi * i / (count)) + 2047 for i in range(count)] ) return wf def double_bipolar_sine(a, T): """Return standard bipolar sine wave with amplitude a (units of V) and period T (units of ms) args: a (float): Amplitude in Volts T (float): Period in ms """ if T < 0.01: raise ValueError("limit of Ferroelectric Tester") count = int(T * 1000) int_amp = int(2047 * a / 10) wf = np.array( [int_amp * np.sin(4 * np.pi * i / (count)) + 2047 for i in range(count)] ) return wf
[ 11748, 299, 32152, 355, 45941, 198, 198, 834, 439, 834, 796, 357, 198, 220, 220, 220, 366, 20307, 62, 65, 49133, 62, 82, 500, 1600, 198, 220, 220, 220, 366, 23352, 62, 65, 49133, 62, 82, 500, 1600, 198, 220, 220, 220, 366, 20307, ...
2.192804
1,473
from keras import layers import tensorflow as tf from Resnet import ResNet50 import keras from keras.models import Input,Model
[ 6738, 41927, 292, 1330, 11685, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 1874, 3262, 1330, 1874, 7934, 1120, 198, 11748, 41927, 292, 198, 6738, 41927, 292, 13, 27530, 1330, 23412, 11, 17633, 198 ]
3.628571
35
"""Visualizations for NLP analysis""" import pandas as pd import numpy as np from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt import seaborn as sns
[ 37811, 36259, 4582, 329, 399, 19930, 3781, 37811, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 1341, 35720, 13, 4164, 10466, 1330, 17923, 62, 13116, 198, 6738, 1341, 35720, 13, 4164, 10466, 1330, ...
3.53125
64
from sqlpuzzle._common import Object from sqlpuzzle._queries.options import Options __all__ = ()
[ 6738, 44161, 79, 9625, 13557, 11321, 1330, 9515, 198, 6738, 44161, 79, 9625, 13557, 421, 10640, 13, 25811, 1330, 18634, 198, 198, 834, 439, 834, 796, 7499, 628, 198 ]
3.448276
29
from Code.utility_functions import get_excel_row_index
[ 6738, 6127, 13, 315, 879, 62, 12543, 2733, 1330, 651, 62, 1069, 5276, 62, 808, 62, 9630, 628 ]
3.111111
18
import logging from datetime import datetime from datetime import timedelta from cvprac.cvp_client_errors import CvpApiError
[ 11748, 18931, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 4818, 8079, 1330, 28805, 12514, 198, 6738, 269, 85, 1050, 330, 13, 33967, 79, 62, 16366, 62, 48277, 1330, 327, 36133, 32, 14415, 12331, 628 ]
3.5
36
from flask import current_app, request from http import HTTPStatus from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.orm import Session from app.models.stores.store_model import StoreModel from app.decorators import verify_payload, validator
[ 6738, 42903, 1330, 1459, 62, 1324, 11, 2581, 198, 6738, 2638, 1330, 14626, 19580, 198, 198, 6738, 44161, 282, 26599, 13, 579, 13, 41194, 1330, 1400, 23004, 21077, 198, 6738, 44161, 282, 26599, 13, 579, 1330, 23575, 198, 198, 6738, 598, ...
3.764706
68
#!/usr/bin/env python import argparse import boto from boto.s3 import connection as s3_connection from cinderclient.v1 import client as cinder_v1 import code from novaclient.v1_1 import client as nova_v1 from novaclient.shell import OpenStackComputeShell as open_shell from glanceclient import Client as glance_client from keystoneclient.v2_0 import client as key_v2 from neutronclient.v2_0 import client as neutron_v2 import os import swiftclient import sys from urlparse import urlparse if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 1822, 29572, 198, 11748, 275, 2069, 198, 6738, 275, 2069, 13, 82, 18, 1330, 4637, 355, 264, 18, 62, 38659, 198, 6738, 269, 5540, 16366, 13, 85, 16, 1330, 5456, 355, 269, 5540,...
3.2
165
import inspect from .descriptors import Descriptor from .arguments import ArgsDescriptor
[ 11748, 10104, 198, 198, 6738, 764, 20147, 1968, 669, 1330, 2935, 6519, 273, 198, 6738, 764, 853, 2886, 1330, 943, 14542, 24564, 1968, 273 ]
3.708333
24
# -*- coding:utf-8 -*- """ Created on 2017/10/01 @author: Jimmy Liu @group : waditu @contact: jimmysoa@sina.cn """ if __name__ == '__main__': pass
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 220, 198, 37811, 198, 220, 198, 41972, 319, 2177, 14, 940, 14, 486, 198, 31, 9800, 25, 12963, 18258, 198, 31, 8094, 1058, 266, 324, 34272, 198, 31, 32057, 25, 474, 320, 1820, ...
2.180556
72