content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import torch import torch.nn as nn import torch.nn.functional as F def single_conv(in_channels, out_channels, ks=3): return nn.Sequential( nn.ReflectionPad2d(ks//2), nn.Conv2d(in_channels, out_channels, 3, bias=False), nn.ReLU(inplace=True) )
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 628, 198, 4299, 2060, 62, 42946, 7, 259, 62, 354, 8961, 11, 503, 62, 354, 8961, 11, 479, 82, 28, 18, 2599, 198, 220, 220,...
2.139535
129
import math from datetime import datetime AVAILABLE_ACTIONS = [{'action': 'add', 'admin_required': False, 'operator': '+'}, {'action': 'subtract', 'admin_required': False, 'operator': '-'}, {'action': 'multiply', 'admin_required': False, 'operator': '*'}, {'action': 'divide', 'admin_required': False, 'operator': '/'}, {'action': 'power', 'admin_required': True, 'operator': '**'}, {'action': 'sqrt', 'admin_required': True, 'operator': 'sqrt'}, ] def get_available_options(action): """ Go through the available options and find it, then return that object :param action: string :return: list """ return [obj for obj in AVAILABLE_ACTIONS if obj['action'] == action.lower()] def do_calculation(action, x, y): """ This function does all the calculation thig :param action: string :param x: int :param y: int :return: int ( the result ) """ operator = get_available_options((action))[0]['operator'] ops = { '+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '/': lambda x, y: x / y if y else 0, '**': lambda x, y: x ** y, 'sqrt': lambda x, y: math.sqrt(int(x)) } return ops[operator](int(x), int(y))
[ 11748, 10688, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 10116, 32, 4146, 17534, 62, 10659, 11053, 796, 685, 90, 6, 2673, 10354, 705, 2860, 3256, 705, 28482, 62, 35827, 10354, 10352, 11, 198, 220, 220, 220, 220, 220, 220, 220,...
1.994737
760
""" API v1 models. """ import logging from itertools import groupby from django.db import transaction from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey from common.djangoapps.course_modes.models import CourseMode from lms.djangoapps.verify_student.models import VerificationDeadline from openedx.core.djangoapps.content.course_overviews.models import CourseOverview log = logging.getLogger(__name__) UNDEFINED = object()
[ 37811, 7824, 410, 16, 4981, 13, 37227, 628, 198, 11748, 18931, 198, 6738, 340, 861, 10141, 1330, 1448, 1525, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 8611, 198, 6738, 32191, 62, 13083, 1330, 17665, 9218, 12331, 198, 6738, 32191, 62...
3.440299
134
import sys import pandas as pd import numpy as np import itertools from sklearn.preprocessing import RobustScaler from sklearn.tree import DecisionTreeClassifier from evaluate_model import evaluate_model dataset = sys.argv[1] pipeline_components = [RobustScaler, DecisionTreeClassifier] pipeline_parameters = {} min_impurity_decrease_values = np.arange(0., 0.005, 0.00025) max_features_values = [0.1, 0.25, 0.5, 0.75, 'sqrt', 'log2', None] criterion_values = ['gini', 'entropy'] random_state = [324089] all_param_combinations = itertools.product(min_impurity_decrease_values, max_features_values, criterion_values, random_state) pipeline_parameters[DecisionTreeClassifier] = \ [{'min_impurity_decrease': min_impurity_decrease, 'max_features': max_features, 'criterion': criterion, 'random_state': random_state} for (min_impurity_decrease, max_features, criterion, random_state) in all_param_combinations] evaluate_model(dataset, pipeline_components, pipeline_parameters)
[ 11748, 25064, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 340, 861, 10141, 198, 6738, 1341, 35720, 13, 3866, 36948, 1330, 3851, 436, 3351, 36213, 198, 6738, 1341, 35720, 13, 21048, 1330, 26423, ...
2.902655
339
''' Wrapper function to run PPO algorithm for training ''' import numpy as np import matplotlib.pyplot as plt import time import math import logging from scipy.optimize import minimize, LinearConstraint # custom libraries from training.PPO.run_helper import buyerPenaltiesCalculator, buyerUtilitiesCalculator, evaluation from training.PPO.run_helper import logger_handle, initialize_agent, get_ys, choose_prob, cumlativeBuyerExp, getPurchases
[ 7061, 6, 198, 36918, 2848, 2163, 284, 1057, 350, 16402, 11862, 329, 3047, 198, 7061, 6, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 640, 198, 11748, 10688, 198, 11...
3.393939
132
import pytest from scripts.custom import clean_dateTime
[ 11748, 12972, 9288, 198, 198, 6738, 14750, 13, 23144, 1330, 3424, 62, 4475, 7575, 628 ]
3.866667
15
import os import traceback from dataclasses import dataclass from typing import Any, Callable, List, Optional, Union import pytorch_pfn_extras as ppe import torch from pytorch_pfn_extras.training import extension, extensions from torch import nn from torch.utils.data import DataLoader from mlprogram import distributed, logging from mlprogram.builtins import Environment from mlprogram.pytorch_pfn_extras import SaveTopKModel, StopByThreshold from mlprogram.synthesizers import Synthesizer logger = logging.Logger(__name__) Length = Union[Epoch, Iteration] def create_extensions_manager(n_iter: int, evaluation_interval_iter: int, snapshot_interval_iter: int, iter_per_epoch: int, model: nn.Module, optimizer: torch.optim.Optimizer, evaluate: Optional[Callable[[], None]], metric: str, maximize: bool, threshold: Optional[float], output_dir: str, report_metrics: Optional[List[str]] = None): model_dir = os.path.join(output_dir, "model") logger.info("Prepare pytorch-pfn-extras") manager = ppe.training.ExtensionsManager( model, optimizer, n_iter / iter_per_epoch, out_dir=os.path.join(output_dir), extensions=[], iters_per_epoch=iter_per_epoch, ) manager.extend( extensions.FailOnNonNumber(), trigger=Trigger(evaluation_interval_iter, n_iter) ) if evaluate is not None: manager.extend( Call(evaluate), trigger=Trigger(evaluation_interval_iter, n_iter), ) if distributed.is_main_process(): manager.extend( extensions.LogReport( trigger=Trigger(100, n_iter), filename="log.json", ) ) manager.extend(extensions.ProgressBar()) manager.extend( SaveTopKModel(model_dir, 1, metric, model, maximize=maximize), trigger=Trigger(evaluation_interval_iter, n_iter), ) metrics = report_metrics or [] manager.extend( extensions.PrintReport(entries=[ "loss", *metrics, "iteration", "epoch", "time.iteration", "gpu.time.iteration", "elapsed_time" ]), trigger=Trigger(100, n_iter), ) if threshold is not None: manager.extend( StopByThreshold(metric, threshold, maximize=maximize), trigger=Trigger(evaluation_interval_iter, n_iter), ) if distributed.is_initialized(): snapshot = extensions.snapshot(autoload=True, n_retains=1, saver_rank=0) snapshot._rank = distributed.rank() snapshot._size = distributed.size() snapshot._local_rank = distributed.rank() else: snapshot = extensions.snapshot(autoload=True, n_retains=1) manager.extend(snapshot, trigger=Trigger(snapshot_interval_iter, n_iter)) return manager def create_dataloader(dataset: torch.utils.data.Dataset, batch_size: int, n_worker: int, collate_fn: Callable) \ -> torch.utils.data.DataLoader: if hasattr(dataset, "__len__"): is_iterable = False else: is_iterable = True if is_iterable: return DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=n_worker, collate_fn=collate_fn) else: return DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=n_worker, collate_fn=collate_fn) def get_world_process_group(device: torch.device) \ -> Optional[torch.distributed.group]: if not distributed.is_initialized(): return None else: if device.type == "cuda": return distributed.groups["world_nccl"] else: return distributed.groups["world_gloo"] def setup_distributed_training( model: nn.Module, loss: nn.Module, group: torch.distributed.group ): model = TrainModule(model, loss) if group is None: return model else: return ppe.nn.parallel.distributed.DistributedDataParallel( module=model, process_group=group, ) def save_results(output_dir: str, model: nn.Module, optimizer: torch.optim.Optimizer) -> None: if distributed.is_main_process(): logger.info("Dump the last model") torch.save(model.state_dict(), os.path.join(output_dir, "model.pt")) torch.save(optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
[ 11748, 28686, 198, 11748, 12854, 1891, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 6738, 19720, 1330, 4377, 11, 4889, 540, 11, 7343, 11, 32233, 11, 4479, 198, 198, 11748, 12972, 13165, 354, 62, 79, 22184, 62, 2302, 8847, ...
2.118808
2,281
import matplotlib.pyplot as plt import math import numpy as np
[ 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 201, 198, 11748, 10688, 201, 198, 11748, 299, 32152, 355, 45941, 201 ]
2.954545
22
from operator import add, itruediv, mul, sub ops = [add, sub, mul, itruediv] a = float(input("Inserisci un numero: ")) b = float(input("Inserisci un altro numero: ")) op = int( input("Inserisci un operatore (0 per addizione, 1 per sottrazione, 2 per moltiplicazione oppure 3 per divisione: ") ) print(ops[op](a, b))
[ 6738, 10088, 1330, 751, 11, 340, 21556, 452, 11, 35971, 11, 850, 198, 198, 2840, 796, 685, 2860, 11, 850, 11, 35971, 11, 340, 21556, 452, 60, 198, 198, 64, 796, 12178, 7, 15414, 7203, 818, 2655, 271, 979, 555, 997, 3529, 25, 366, ...
2.515625
128
from robot.api.parsing import ModelTransformer, get_model, ModelVisitor, Token import os, sys keywordlist = [] other_keywords = [] used_keywords = []
[ 6738, 9379, 13, 15042, 13, 79, 945, 278, 1330, 9104, 8291, 16354, 11, 651, 62, 19849, 11, 9104, 15854, 2072, 11, 29130, 198, 11748, 28686, 11, 25064, 198, 198, 2539, 4775, 4868, 796, 17635, 198, 847, 62, 2539, 10879, 796, 17635, 198, ...
3.081633
49
from typing import Tuple import pandas as pd import numpy as np import matplotlib.pyplot as plt from Common.Strategies.TechIndicators.AbstractTechStrategy import AbstractTechStrategy from Common.TechIndicators.MacdIndicator import MacdIndicator
[ 6738, 19720, 1330, 309, 29291, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 8070, 13, 13290, 2397, 444, 13, 17760, 5497, 44549, 13, ...
3.617647
68
#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################### # Author: Mu yanru # Date : 2018.5 # Email : muyanru345@163.com ################################################################### from collections import defaultdict import utils from qt import * from separator import DayuHSeparator from field_mixin import MFieldMixin if __name__ == '__main__': import sys app = QApplication(sys.argv) test = MWizard() test.register_field('formats', []) test.register_field('type_group', 'element') test.register_field('current_step', 'prep') test.set_title('Publish Element') page0 = MWizardPage('Select Publish Type') page1 = MWizardPage('Write Comment') page2 = MWizardPage('Upload Thumbnail') page3 = MWizardPage('Quality Check') test.add_page(page0) test.add_page(page3) test.add_page(page1) test.add_page(page2) test.go_to(0) test.show() sys.exit(app.exec_())
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 29113, 29113, 21017, 198, 2, 6434, 25, 8252, 331, 272, 622, 198, 2, 7536, 220, 1058, 2864, 13, 20, 198, 2, 9570, 10...
2.867816
348
from __future__ import division, print_function, generators import numpy as np pi = np.pi def techChange_sunny(p): """sunny constraint for techChangeModel""" return p[:, 0] > 0.325
[ 198, 198, 6738, 11593, 37443, 834, 1330, 7297, 11, 3601, 62, 8818, 11, 27298, 198, 198, 11748, 299, 32152, 355, 45941, 628, 198, 14415, 796, 45941, 13, 14415, 628, 198, 198, 4299, 7261, 19400, 62, 82, 16948, 7, 79, 2599, 198, 220, 2...
2.884058
69
# -*- coding: utf-8 -*- """ :Authors: cykooz :Date: 23.06.2019 """ from pathlib import Path import piexif import pytest from PIL import Image from cykooz.heif.errors import HeifError from cykooz.heif.image import RawHeifImage from cykooz.heif.pil import register_heif_opener def test_raw_heif_image_form_path(data_path): img = RawHeifImage.from_path(data_path / 'test.heic') assert img.width == 3024 assert img.height == 4032 assert img.mode == 'RGB' assert len(img.data) == 36578304 assert img.stride == 9072 assert len(img.exif) == 2026 def test_raw_heif_image_form_reader(data_path): img_path = data_path / 'test.heic' with img_path.open('rb') as f: img = RawHeifImage.from_stream(f) assert img.width == 3024 assert img.height == 4032 assert img.mode == 'RGB' assert len(img.data) == 36578304 assert img.stride == 9072 assert len(img.exif) == 2026 def test_raw_heif_image_form_reader_errors(data_path): img_path = data_path / 'test.heic' with img_path.open('rb') as f: img = RawHeifImage.from_stream(f) assert img.width == 3024 assert img.height == 4032 # File is closed with pytest.raises(HeifError): _ = img.data
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 25, 30515, 669, 25, 3075, 74, 2238, 89, 198, 25, 10430, 25, 2242, 13, 3312, 13, 23344, 198, 37811, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 250...
2.296564
553
#!/usr/bin/env python ''' Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' import os import signal import threading import logging import multiprocessing from ambari_agent.PythonReflectiveExecutor import PythonReflectiveExecutor from ambari_agent.RemoteDebugUtils import bind_debug_signal_handlers from ambari_agent.ExitHelper import ExitHelper logger = logging.getLogger(__name__)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 7061, 6, 198, 26656, 15385, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 198, 273, 517, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 198, 17080, 6169, 351, 428, ...
3.855634
284
import bpy from bpy.props import * from bpy.types import Operator, AddonPreferences
[ 11748, 275, 9078, 198, 6738, 275, 9078, 13, 1676, 862, 1330, 1635, 198, 6738, 275, 9078, 13, 19199, 1330, 35946, 11, 3060, 261, 36698, 4972, 628, 628, 628 ]
3.178571
28
""" Fabfile for deploying and setting up code that looks like the production environment. it also makes it easy to start up the servers If you want to run on the localhost you may need to first do:: rm -rf ~/.ssh/known_hosts """ from __future__ import with_statement import os import re from fabric.api import local, settings, abort, run , cd, env, lcd, sudo, prompt from fabric.contrib.console import confirm from fabric.contrib import files env.roledefs = {'local':['localhost']} env.use_ssh_config=True TAG_REGEX = re.compile('^[0-9]+\.[0-9]+\.[0-9]+') STABLE_MSG = '**stable**' LINK_CODE_DIR = os.path.split(os.path.abspath(__file__))[0] def dir_code_base(): """ If you are using any localhost then it will use the current directory. Otherwise you will use the code_dir """ if 'localhost' in env.host_string: return os.getcwd() return code_dir def dir_scripts(): """ The directory where you house all the scripts """ return '%s/scripts' % (dir_code_base()) config_dir = '~/.link' def configure(): """ Create the base configuration so that you can change it. Might want to include the configuration in a different repo """ if not files.exists(config_dir): run('mkdir %s' % config_dir) lnk_config = '%s/link.config' % config_dir if not files.exists(lnk_config): run('touch %s' % lnk_config) def script(script_name, command = 'python', **args): """ Will run the script that is in the scripts folder. you can pass in a dictionory of args and it will pass it through to the script as command line args in this format fab -R local script:example.py,arg1=value1,arg2=value2 that will result in running this command <command> <scripts_directory>/<scriptname> --arg1=value1 --arg2=value2 """ with cd(dir_scripts()): parameters = '' if args: parameters = ' '.join(['--%s=%s' % (key, value) for key,value in args.iteritems()]) run("%s %s %s" % (command , script_name, parameters)) def commit(msg=None): """ Commit your changes to git :msg: @todo :returns: @todo """ print '---Commiting---' print msg = msg or prompt('Commit message: ') commit = False commit = prompt('Confirm commit? [y/n]') == 'y' if commit: with settings(warn_only=True): _commit = not local('git commit -a -m "%s"' % msg).failed if not _commit: #nothing was committed commit = False print "Nothing to commit" else: abort('commit aborted') print print '---Done---' return commit def check_tag_format(tag): """ Checks the tag format and returns the component parts """ parsed = tag.split('.') try: #allow for at most 2 minor decimals...i mean comeon major = int(parsed[0]) minor = int(parsed[1]) build = int(parsed[2][0:2]) return (major, minor, build) except Exception as e: print e abort("""Must be of the form <major_version>.<minor>.<maintence>, like 0.0.1. Only integers allowed""") def write_version(version): """ Write out the version python file to the link directory before installing version needs to be a list or tuple of the form (<major>, <minor>, <build>) or a string in the format <major>.<minor>.<build> all ints """ file_name ='link/__init__.py' init = open(file_name) init_read = init.readlines() init.close() version_line = [idx for idx, x in enumerate(init_read) if '__version__ = ' in x] if len(version_line)>1: raise Exception('version is in there more than once') if isinstance(version, str): try: version_split = map(int, version.split('.')) except: raise Exception("Version string must be in the format <major>.<minor>.<build>") if not isinstance(version_split, (list, tuple)) or len(version_split)!=3: raise Exception('invalid version %s' % version) init_read[version_line[0]] = "__version__ = '%s'\n" % version init = open(file_name, 'w') try: init.write(''.join(init_read)) finally: init.close() def prompt_for_tag(default_offset=1, stable_only = False): """ Prompt for the tag you want to use, offset for the default by input """ tags = tag_names(10, stable_only) print "Showing latest tags for reference" default = '0.0.1' if tags: default = tags[0] (major, minor, build) = check_tag_format(default) build = build+default_offset new_default = '%s.%s.%s' % (major, minor, build) tag = prompt('Tag name [in format x.xx] (default: %s) ? ' % new_default) tag = tag or new_default return tag def push_to_pypi(): """ Will push the code to pypi """ if prompt('would you like to tag a new version first [y/n]') == 'y': tag() local('python setup.py sdist upload') def prompt_commit(): """ prompts if you would like to commit """ local('git status') print print _commit = prompt('Do you want to commit? [y/n]') == 'y' if _commit: msg = prompt('Commit message: ') return commit(msg) def tag(mark_stable=False): """ Tag a release, will prompt you for the tag version. You can mark it as stable here as well """ tag = prompt_for_tag() print "writing this tag version to version.py before commiting" write_version(tag) print _commit = prompt_commit() print if not _commit and not tag: print print "Nothing commited, using default tag %s" % default print tag = default else: msg = '' if mark_stable: msg = STABLE_MSG + ' ' msg += prompt("enter msg for tag: ") local('git tag %(ref)s -m "%(msg)s"' % { 'ref': tag, 'msg':msg}) local('git push --tags') return tag def merge(branch=None, merge_to = 'master'): """ Merge your changes and delete the old branch """ if not branch: print "no branch specified, using current" branch = current_branch() if prompt('confirm merge with of branch %s to %s [y/N]' % (branch, merge_to)) == 'y': prompt_commit() local('git checkout %s ' % merge_to) local('git merge %s ' % branch) if prompt('delete the old branch locally and remotely? [y/N]') == 'y': local('git branch -d %s' % branch) local('git push origin :%s' % branch) else: print "leaving branch where it is" if prompt('push results [y/N]' ) == 'y': local('git push') def tag_deploy(mark_stable=False): """ Asks you to tag this release and Figures out what branch you are on. It then calls the deploy function """ local('git fetch --tags') branch = local('git branch | grep "^*" | cut -d" " -f2', capture=True) _tag = tag(mark_stable=mark_stable) deploy(_tag, branch) def retag(tag, msg): """ Retag a tag with a new message """ local('git tag %s %s -f -m "%s"' % (tag, tag, msg)) local('git push --tags') def mark_stable(tag, msg = None): """ Mark a previous tag as stable """ retag(tag, '%s %s' % (STABLE_MSG, msg) ) def deploy(tag=None, branch=None, stable_only=False): """ This is only for deployment on a dev box where everything can be owned by this user. This is NOT for production deployment. Put's the code in code_dir """ if not tag: tag = prompt_for_tag(0, stable_only = stable_only) configure() setup_environment() #check out all the code in the right place with cd(code_dir): # i **THINK** you have to have the branch checked out before you can # checkout the tag if branch: #then you haven't even checkout this branch branches = run('git branch') if branch not in branches: run('git checkout -b %s' % branch) _current_branch = current_branch() if "* %s" % branch != _current_branch: run('git checkout %s' % branch) #pull the latest run('git pull origin %s' % branch) else: run("git pull origin master") #check out a specific tag if tag: run("git fetch --tags") run("git checkout %s" % tag) #hacky if env.user == 'root': #make sure everything is still owned by the deployer run('chown -R %s %s' % (deploy_user, code_dir)) ### # How to setup a fresh box. You probably have to run this as root for it to # work ### def install_easy_install(): """ Installs setup tool, this should also go into an RPM """ run('wget http://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11-py2.7.egg#md5=fe1f997bc722265116870bc7919059ea') run('sh setuptools-0.6c11-py2.7.egg') def install_python(): """ Installs python, I should be able to create an RPM eventually """ run('wget http://python.org/ftp/python/2.7.2/Python-2.7.2.tgz') run('tar -xvf Python-2.7.2.tgz') with cd('Python-2.7.2'): run('./configure') run('make') run('make install') ### # This isn't reall necessary but i'll keep it for now ### def install_python_dependancies(): """ Easy install all the packages we need """ run('easy_install requests') run('easy_install numpy') run('easy_install pandas') run('easy_install happybase') run('easy_install flask') run('easy_install ipython') run('easy_install gunicorn') run('easy_install link') run('easy_install pymongo') run('easy_install mysql-python') run('easy_install docutils') def install_box_libraries(): """ Installs the libs you need like readlines and libsqlite. This will only run on a ubuntu machine with apt-get """ with settings(warn_only=True): has_apt = run('which apt-get') if has_apt: run('apt-get install make') run('apt-get install libsqlite3-dev') run('apt-get install libreadline6 libreadline6-dev') run('apt-get install libmysqlclient-dev') else: print "this is not an ubuntu system...skipping" def setup_box(): """ Will install python and all libs needed to set up this box to run the examjam code. Eventually this needs to be more RPM based """ #place_pub_key() install_box_libraries() install_python() install_easy_install() install_python_dependancies()
[ 37811, 198, 43957, 7753, 329, 29682, 290, 4634, 510, 2438, 326, 3073, 588, 262, 3227, 198, 38986, 13, 220, 340, 635, 1838, 340, 2562, 284, 923, 510, 262, 9597, 220, 198, 198, 1532, 345, 765, 284, 1057, 319, 262, 1957, 4774, 345, 743...
2.431448
4,420
from channels.routing import ProtocolTypeRouter from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'/websocket', consumers.VNCConsumer) ]
[ 6738, 9619, 13, 81, 13660, 1330, 20497, 6030, 49, 39605, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 302, 62, 6978, 198, 6738, 764, 1330, 7008, 198, 198, 732, 1443, 5459, 62, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 302, 62, ...
2.951613
62
# Copyright (C) 2016 Intel Corporation # Released under the MIT license (see COPYING.MIT) from oeqa.core.case import OETestCase from oeqa.utils.package_manager import install_package, uninstall_package
[ 2, 15069, 357, 34, 8, 1584, 8180, 10501, 198, 2, 28728, 739, 262, 17168, 5964, 357, 3826, 27975, 45761, 13, 36393, 8, 198, 198, 6738, 267, 68, 20402, 13, 7295, 13, 7442, 1330, 440, 2767, 395, 20448, 198, 6738, 267, 68, 20402, 13, ...
3.561404
57
""" scaffoldgraph tests.analysis.test_general """ from scaffoldgraph.analysis import get_singleton_scaffolds, get_virtual_scaffolds from ..test_network import long_test_network
[ 37811, 198, 1416, 2001, 727, 34960, 5254, 13, 20930, 13, 9288, 62, 24622, 198, 37811, 198, 198, 6738, 41498, 727, 34960, 13, 20930, 1330, 651, 62, 12215, 10565, 62, 1416, 2001, 10119, 11, 651, 62, 32844, 62, 1416, 2001, 10119, 198, 67...
3.333333
54
import math import time t1 = time.time() N = 1000000 n = (N+1)//2 p = [True]*(n) i = 1 prime = [2] while i < n: if p[i]: t = 2*i+1 prime.append(t) j = i while j < n: p[j] = False j += t i += 1 # define a binary search target = prime[:] count = 0 while len(target) > 0: #print(target) #print (count) test = target[0] dig = math.floor(math.log10(test))+1 target.pop(0) if dig == 1: count += 1 continue if dig > 1: i = 1 counted = 0 tl = True while i < dig: test = test//10 + (test%10)*math.pow(10,dig-1) if isPrime(test): i += 1 ind = isInList(test,target) if ind >= 0: target.pop(ind) else: counted += 1 else: tl = False break if tl: count += dig - counted print (count) print("time:",time.time()-t1)
[ 11748, 10688, 198, 11748, 640, 198, 198, 83, 16, 796, 640, 13, 2435, 3419, 198, 198, 45, 796, 1802, 2388, 198, 198, 77, 796, 357, 45, 10, 16, 8, 1003, 17, 198, 198, 79, 796, 685, 17821, 60, 9, 7, 77, 8, 198, 198, 72, 796, 35...
1.651376
654
from django.apps import AppConfig
[ 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
3.888889
9
import torch import torch.nn as nn from collections import OrderedDict ### GPT NEO VERSION ###### ''' # couldn't get it to work with class inheritance def add_adapters(model, reduction_factor): n_layers = len(model.h) hidden_size = model.config.hidden_size for n in range(n_layers): model.h[n].mlp = nn.Sequential(OrderedDict([('MLP', model.h[n].mlp), ('Adapter', AdapterLayer(hidden_size, reduction_factor))])) return model ''' # couldn't get it to work with class inheritance
[ 11748, 28034, 201, 198, 11748, 28034, 13, 20471, 355, 299, 77, 201, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 201, 198, 201, 198, 21017, 402, 11571, 44106, 44156, 2849, 46424, 2, 201, 198, 7061, 6, 201, 198, 2, 3521, 470, 651, 3...
2.330612
245
import unittest import os import re import subprocess
[ 11748, 555, 715, 395, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 850, 14681, 628 ]
3.666667
15
import os import subprocess from typing import Optional from hydrus import hydrus_log_analyzer from hydrus.hydrus_deployer_interface import IHydrusDeployer from simulation.simulation_error import SimulationError from utils import path_formatter
[ 11748, 28686, 198, 11748, 850, 14681, 198, 6738, 19720, 1330, 32233, 198, 198, 6738, 2537, 7109, 385, 1330, 2537, 7109, 385, 62, 6404, 62, 38200, 9107, 198, 6738, 2537, 7109, 385, 13, 15511, 14932, 62, 2934, 1420, 263, 62, 39994, 1330, ...
3.686567
67
from openprocurement.api.utils import APIResource, json_view, context_unpack, get_now, generate_id from openprocurement.framework.core.utils import ( submissionsresource, apply_patch, save_qualification, ) from openprocurement.framework.core.validation import ( validate_patch_submission_data, validate_operation_submission_in_not_allowed_period, validate_submission_status, validate_update_submission_in_not_allowed_status, validate_activate_submission, validate_action_in_not_allowed_framework_status, ) from openprocurement.framework.electroniccatalogue.models import Qualification
[ 6738, 1280, 36942, 495, 434, 13, 15042, 13, 26791, 1330, 3486, 4663, 274, 1668, 11, 33918, 62, 1177, 11, 4732, 62, 403, 8002, 11, 651, 62, 2197, 11, 7716, 62, 312, 198, 6738, 1280, 36942, 495, 434, 13, 30604, 13, 7295, 13, 26791, ...
3.141414
198
from __future__ import division from torch.autograd import Variable import cv2 import numpy as np import torch
[ 6738, 11593, 37443, 834, 1330, 7297, 201, 198, 6738, 28034, 13, 2306, 519, 6335, 1330, 35748, 201, 198, 201, 198, 11748, 269, 85, 17, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 28034, 201, 198, 201, 198, 201, 198, 201, ...
2.653061
49
# ---------- 320ms, 15.9MB ---------- # # ---------- 320ms, 16.1MB ---------- #
[ 2, 24200, 438, 20959, 907, 11, 1315, 13, 24, 10744, 24200, 438, 1303, 198, 2, 24200, 438, 20959, 907, 11, 1467, 13, 16, 10744, 24200, 438, 1303 ]
2.925926
27
from rabbitConsumer import * from socketConsumer import SocketConsumer from dlx import * import threading import sys if __name__ == '__main__': work_with = sys.argv[1] r_k = ['*.jpg', '*.jpeg', '#'] threads = [] dlx = ReconnectingDlx() threads.append(threading.Thread(target=dlx.run)) for j in range(1, 4): if work_with == 'rabbit': # consumer = RabbitConsumer(_id_consumer=j, _exchange='exchange1', # _queue=f'queue{j}', _routing_key=r_k[j - 1], _exchange_type='topic', # _producer_to_dlx=dlx) consumer = RabbitReconnectingConsumer(_id_consumer=j, _exchange='exchange1', _queue=f'queue{j}', _routing_key=r_k[j - 1], _exchange_type='topic', _producer_to_dlx=dlx) elif work_with == 'socket': consumer = SocketConsumer(_id_consumer=j) else: print("the parameter in args must be 'rabbit' or 'socket'!") threads.append(threading.Thread(target=consumer.run)) for thread in threads: thread.start()
[ 6738, 22746, 49106, 1330, 1635, 198, 6738, 17802, 49106, 1330, 47068, 49106, 198, 6738, 288, 75, 87, 1330, 1635, 198, 198, 11748, 4704, 278, 198, 11748, 25064, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 628, 220...
1.976744
602
"""Mapeamento das tabelas para persistir os processos datajud Revision ID: 6fdbb9233bd6 Revises: 8d2eb6149b1d Create Date: 2020-10-18 09:22:06.650559 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '6fdbb9233bd6' down_revision = '8d2eb6149b1d' branch_labels = None depends_on = None
[ 37811, 44, 1758, 3263, 78, 288, 292, 7400, 417, 292, 31215, 21160, 343, 28686, 1429, 418, 1366, 10456, 198, 198, 18009, 1166, 4522, 25, 718, 69, 9945, 65, 24, 25429, 17457, 21, 198, 18009, 2696, 25, 807, 67, 17, 1765, 21, 19442, 65,...
2.47482
139
""" A set of CC412022, CC416168 were run back to back without blanks on 2019-11-12. Rough quantification is done by the below. """ __package__ = 'Z' from datetime import datetime from settings import CORE_DIR, DB_NAME from IO.db import connect_to_db, GcRun, Integration, Standard, SampleQuant from processing import blank_subtract from reporting import compile_quant_report engine, session = connect_to_db(DB_NAME, CORE_DIR) standard_to_quantify_with = session.query(Standard).filter(Standard.name == 'cc416168').one_or_none() # get standard cert values for the quantifier certified_values_of_sample = (session.query(Standard) .filter(Standard.name == 'cc412022_noaa_provided') .one().quantifications) # get standard cert values for the sample being quantified vocs = session.query(Standard).filter(Standard.name == 'vocs').one_or_none() vocs = [q.name for q in vocs.quantifications] samples = (session.query(GcRun).join(Integration, Integration.run_id == GcRun.id) .filter(GcRun.date > datetime(2019, 11, 12), GcRun.date < datetime(2019, 11, 13)) .filter(Integration.filename.like('%CC412022___.D')) .order_by(GcRun.date) .all()) standards = (session.query(GcRun).join(Integration, Integration.run_id == GcRun.id) .filter(GcRun.date > datetime(2019, 11, 12), GcRun.date < datetime(2019, 11, 13)) .filter(Integration.filename.like('%CC416168___.D')) .order_by(GcRun.date) .all()) quants = [] for sample, standard in zip(samples, standards): blank_subtract(sample, vocs, session, blank=None, force_no_blank=True) blank_subtract(standard, vocs, session, blank=None, force_no_blank=True) quant = SampleQuant(sample, standard, None, standard_to_quantify_with) quant.quantify() quants.append(quant) compile_quant_report(quants, 'CC412022', 'CC416168', certified_values_of_sample, date=datetime(2019, 11, 12))
[ 37811, 198, 32, 900, 286, 12624, 19, 10232, 1828, 11, 12624, 35218, 14656, 547, 1057, 736, 284, 736, 1231, 698, 2283, 319, 13130, 12, 1157, 12, 1065, 13, 198, 198, 49, 619, 5554, 2649, 318, 1760, 416, 262, 2174, 13, 198, 37811, 198,...
2.52986
787
import logging import sys from datacatalog_fileset_enricher import datacatalog_fileset_enricher_cli if __name__ == '__main__': logging.basicConfig(level=logging.INFO) argv = sys.argv datacatalog_fileset_enricher_cli.\ DatacatalogFilesetEnricherCLI.run(argv[1:] if len(argv) > 0 else argv)
[ 11748, 18931, 198, 11748, 25064, 198, 6738, 4818, 330, 10254, 519, 62, 16624, 316, 62, 268, 1173, 372, 1330, 4818, 330, 10254, 519, 62, 16624, 316, 62, 268, 1173, 372, 62, 44506, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417,...
2.384615
130
# Copyright (C) 2013 Peter Rowlands """csgo events module Contains event classes for CS:S and CS:GO events """ from __future__ import absolute_import, unicode_literals from future.utils import python_2_unicode_compatible from .generic import (BaseEvent, PlayerEvent, PlayerTargetEvent, KillEvent, AttackEvent) CSGO_EVENTS = [ SwitchTeamEvent, BuyEvent, ThrowEvent, CsgoAssistEvent, CsgoKillEvent, CsgoAttackEvent, ]
[ 2, 15069, 357, 34, 8, 2211, 5613, 11314, 4447, 198, 37811, 6359, 2188, 2995, 8265, 198, 198, 4264, 1299, 1785, 6097, 329, 9429, 25, 50, 290, 9429, 25, 11230, 2995, 198, 198, 37811, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, ...
2.693182
176
import re
[ 11748, 302, 628 ]
3.666667
3
# Listing_19-1.py # Copyright Warren & Carter Sande, 2013 # Released under MIT license http://www.opensource.org/licenses/mit-license.php # Version $version ---------------------------- # Trying out sounds in Pygame import pygame pygame.init() pygame.mixer.init() screen = pygame.display.set_mode([640,480]) pygame.time.delay(1000) # Wait a second for the mixer to finish initializing splat = pygame.mixer.Sound("splat.wav") # Create the Sound object splat.play() # Play the sound running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.quit()
[ 2, 7343, 278, 62, 1129, 12, 16, 13, 9078, 198, 2, 15069, 11328, 1222, 10831, 3837, 68, 11, 2211, 198, 2, 28728, 739, 17168, 5964, 220, 220, 2638, 1378, 2503, 13, 44813, 1668, 13, 2398, 14, 677, 4541, 14, 2781, 12, 43085, 13, 10121...
2.68
250
import six import docker_emperor.logger as logger from docker_emperor.nodes.context import Context
[ 11748, 2237, 198, 11748, 36253, 62, 368, 8723, 13, 6404, 1362, 355, 49706, 198, 6738, 36253, 62, 368, 8723, 13, 77, 4147, 13, 22866, 1330, 30532, 198 ]
3.666667
27
#!/usr/bin/env python from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import time from instance_lock import InstanceLock ################################################################################ ################################################################################ if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 25064, 198, 11748, 640...
5.025
80
import modelexp from modelexp.experiments.sas import Sans from modelexp.models.sas import Sphere from modelexp.data import XyeData from modelexp.fit import LevenbergMarquardt from modelexp.models.sas import InstrumentalResolution app = modelexp.App() app.setExperiment(Sans) dataRef = app.setData(XyeData) dataRef.loadFromFile('./sansSphereData_sa.xye', 'sa') dataRef.loadFromFile('./sansSphereData_la.xye', 'la') dataRef.plotData() modelRef = app.setModel(Sphere, InstrumentalResolution) modelRef.setParam("r", 50.115979438653525, minVal = 0, maxVal = 100, vary = True) modelRef.setParam("sldSphere", 4.5e-05, minVal = 0, maxVal = 0.00045000000000000004, vary = False) modelRef.setParam("sldSolvent", 1e-05, minVal = 0, maxVal = 0.0001, vary = False) modelRef.setParam("sigR", 0.0446, minVal = 0, maxVal = 0.2, vary = True) modelRef.setParam("i0", 1.0082741570299425, minVal = 0, maxVal = 10, vary = True) modelRef.setParam("bg", 0.0, minVal = 0, maxVal = 1, vary = False) modelRef.setParam("dTheta_sa", 0.000174, minVal = 0, maxVal = 0.001, vary = True) modelRef.setParam("dTheta_la", 0.000765, minVal = 0, maxVal = 0.001, vary = True) app.setFit(LevenbergMarquardt) app.show()
[ 11748, 4235, 2588, 79, 198, 6738, 4235, 2588, 79, 13, 23100, 6800, 13, 82, 292, 1330, 20845, 198, 6738, 4235, 2588, 79, 13, 27530, 13, 82, 292, 1330, 31798, 198, 6738, 4235, 2588, 79, 13, 7890, 1330, 1395, 5948, 6601, 198, 6738, 423...
2.540426
470
#!/usr/bin/python2.7 # -*- coding:utf-8 -*- # Author: NetworkRanger # Date: 2019/1/9 12:35 """ ProxyHandler """ import urllib2 proxy = urllib2.ProxyHandler({'http': '127.0.0.1:8087'}) opener = urllib2.build_opener([proxy]) urllib2.install_opener(opener) response = urllib2.urlopen('http://www.zhichu.com/') print response.read()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 17, 13, 22, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 198, 2, 6434, 25, 7311, 49, 2564, 198, 2, 7536, 25, 13130, 14, 16, 14, 24, 1105, 25, 2327, 198, 198, 37811, 198...
2.314685
143
#!/usr/bin/env python import argparse import logging from metasv.generate_final_vcf import convert_metasv_bed_to_vcf if __name__ == "__main__": FORMAT = '%(levelname)s %(asctime)-15s %(name)-20s %(message)s' logging.basicConfig(level=logging.INFO, format=FORMAT) logger = logging.getLogger(__name__) parser = argparse.ArgumentParser( description="Convert MetaSV final BED to VCF", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--sample", help="Sample name", required=True) parser.add_argument("--bed", help="MetaSV final BED", required=True) parser.add_argument("--vcf", help="Final VCF to output", required=True) parser.add_argument("--reference", help="Reference FASTA") parser.add_argument("--work", help="Work directory", default="work") parser.add_argument("--pass_only", action="store_true", help="Output only PASS calls") args = parser.parse_args() convert_metasv_bed_to_vcf(bedfile=args.bed, vcf_out=args.vcf, workdir=args.work, sample=args.sample, reference=args.reference, pass_calls=args.pass_only)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 1822, 29572, 198, 11748, 18931, 198, 6738, 1138, 292, 85, 13, 8612, 378, 62, 20311, 62, 85, 12993, 1330, 10385, 62, 4164, 292, 85, 62, 3077, 62, 1462, 62, 85, 12993, 198,...
2.288321
548
from __future__ import annotations from abc import ABC, abstractmethod, abstractproperty from typing import Any, Optional, Set from .page_path import PagePath, PagePathLike
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 11, 12531, 26745, 198, 6738, 19720, 1330, 4377, 11, 32233, 11, 5345, 198, 198, 6738, 764, 7700, 62, 6978, 1330, 7873, 15235, 11, 7873, 15235, ...
4.093023
43
from trame import state from trame.html import vuetify, vtk from trame.layouts import SinglePage from vtkmodules.vtkImagingCore import vtkRTAnalyticSource from vtkmodules.vtkFiltersGeometry import vtkGeometryFilter from vtkmodules.vtkRenderingCore import ( vtkRenderer, vtkRenderWindow, vtkRenderWindowInteractor, vtkDataSetMapper, vtkActor, ) # VTK factory initialization from vtkmodules.vtkInteractionStyle import vtkInteractorStyleSwitch # noqa import vtkmodules.vtkRenderingOpenGL2 # noqa # ----------------------------------------------------------------------------- # VTK pipeline # ----------------------------------------------------------------------------- DEFAULT_RESOLUTION = 10 renderer = vtkRenderer() renderWindow = vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera() source = vtkRTAnalyticSource() filter = vtkGeometryFilter() filter.SetInputConnection(source.GetOutputPort()) mapper = vtkDataSetMapper() actor = vtkActor() mapper.SetInputConnection(filter.GetOutputPort()) actor.SetMapper(mapper) renderer.AddActor(actor) renderer.ResetCamera() renderWindow.Render() filter.Update() _min, _max = filter.GetOutput().GetPointData().GetScalars().GetRange() mapper.SetScalarRange(_min, _max) actor.GetProperty().SetEdgeVisibility(1) actor.GetProperty().SetEdgeColor(1, 1, 1) # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # GUI # ----------------------------------------------------------------------------- # html_view = vtk.VtkLocalView(renderWindow) # html_view = vtk.VtkRemoteView(renderWindow) html_view = vtk.VtkRemoteLocalView(renderWindow, mode="local") layout = SinglePage("Geometry export", on_ready=html_view.update) layout.logo.click = html_view.reset_camera layout.title.set_text("Geometry export") with layout.toolbar as tb: vuetify.VSpacer() tb.add_child("{{ resolution }}") vuetify.VSlider( v_model=("resolution", DEFAULT_RESOLUTION), min=10, max=100, step=1, hide_details=True, dense=True, style="max-width: 300px", ) vuetify.VBtn("Update", click=html_view.update) with layout.content: vuetify.VContainer( fluid=True, classes="pa-0 fill-height", children=[html_view], ) # ----------------------------------------------------------------------------- # Main # ----------------------------------------------------------------------------- if __name__ == "__main__": layout.start()
[ 6738, 491, 480, 1330, 1181, 198, 6738, 491, 480, 13, 6494, 1330, 410, 84, 316, 1958, 11, 410, 30488, 198, 6738, 491, 480, 13, 10724, 5269, 1330, 14206, 9876, 198, 198, 6738, 410, 30488, 18170, 13, 85, 30488, 3546, 3039, 14055, 1330, ...
3.230409
855
# Generated by Django 3.2.9 on 2021-12-17 22:10 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 24, 319, 33448, 12, 1065, 12, 1558, 2534, 25, 940, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
from django.contrib import messages from django.contrib.auth.decorators import permission_required from django.shortcuts import get_object_or_404, redirect from django.template.response import TemplateResponse from django.utils.translation import pgettext_lazy from ....store.models import SpecialPage from ...views import staff_member_required from .forms import SpecialPageForm
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 6218, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 12501, 273, 2024, 1330, 7170, 62, 35827, 198, 6738, 42625, 14208, 13, 19509, 23779, 1330, 651, 62, 15252, 62, 273, 62, 26429, 11, 18...
3.918367
98
cidade = str(input('Qual cidade voce mora?')) print(cidade.strip().lower().startswith('santo'))
[ 66, 312, 671, 796, 965, 7, 15414, 10786, 46181, 269, 312, 671, 7608, 344, 2146, 64, 8348, 4008, 198, 4798, 7, 66, 312, 671, 13, 36311, 22446, 21037, 22446, 9688, 2032, 342, 10786, 82, 14723, 6, 4008, 198 ]
2.526316
38
from datetime import datetime, timedelta from typing import BinaryIO, Generator, Optional, Tuple import astropy.units as u import pytz from astropy.units import Quantity from salt_finder_charts.image import Survey, SurveyImageService from salt_finder_charts.mode import ( Mode, ModeDetails, ImagingModeDetails, LongslitModeDetails, SlotModeDetails, MOSModeDetails, ) from salt_finder_charts.output import output_pdf, output_png, output_svg, OutputFormat from salt_finder_charts.util import ( MagnitudeRange, MOSMask, julian_day_start, julian_day_end, ) from salt_finder_charts import finder_charts from salt_finder_charts.ephemerides import ( HorizonsEphemerisService, ConstantEphemerisService, EphemerisService, ) TimeInterval = Tuple[datetime, datetime] def standard_finder_charts( # arguments which are always required mode: Mode, output_format: OutputFormat, # time interval start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, # ephemerides ra: Optional[Quantity] = None, dec: Optional[Quantity] = None, min_magnitude: Optional[float] = None, max_magnitude: Optional[float] = None, bandpass: Optional[str] = None, horizons_id: Optional[str] = None, horizons_stepsize: Optional[Quantity] = None, # image survey: Survey = Survey.POSS2UKSTU_RED, # instrument mode details position_angle: Optional[Quantity] = None, slitwidth: Optional[Quantity] = None, mos_mask_rsmt: Optional[BinaryIO] = None, # miscellaneous basic_annotations: bool = False, title: Optional[str] = None, ) -> Generator[BinaryIO, None, None]: """ Create standard SALT finder charts. Some of the parameters are mutually exclusive. For example, it does mot make sense to specify a slit width if you generate finding charts for imaging mode. In some cases such combinations will raise an error, but in others some of the parameters may just be ignored. If no start time is given, the beginning of the current Julian day is assumed. If no end time is given, the end of the current Julian day is assumed. Parameters ---------- mode : Mode Observation mode (such as imaging or MOS). basic_annotations : bool Whether only basic annotations should be added to the finder chart. output_format : OutputFormat Output format (such as PDF) to use for the generated finder charts. start_time : datetime Start time from which to generate finder charts. end_time : datetime End time until which to generate finder charts. ra : Quantity Right ascension of the finder chart center. dec : Quantity Declination of the finder chart center. min_magnitude : float Minimum magnitude of the target. max_magnitude L: float Maximum magnitude of the target. bandpass : str Bandpass (such as V) for the magnitudes, horizons_id : str Identifier for a target in the Horizons database. horizons_stepsize : Quantity Time between ephemerides queried from the Horizons service. The default is 5 minutes. survey : Survey The image survey from which the finder chart image shall be taken. position_angle : Quantity The position angle. slitwidth : Quantity The width of the longslit, as an angle. mos_mask_rsmt : BinaryIO Input stream containing an RSMT file for a MOS setup. title : str Title for the finder chart. Returns ------- Generator of BinaryIO The finder charts as input streams. """ # time interval # get default start and end time if need be now = datetime.now(pytz.utc) if not start_time: start_time = julian_day_start(now) if not end_time: end_time = julian_day_end(now) # ensure there are timezones if start_time.tzinfo is None: raise ValueError("The start time must be timezone-aware.") if end_time.tzinfo is None: raise ValueError("The end time must be timezone aware.") # ephemerides mos_mask: Optional[MOSMask] = None if mode == Mode.MOS: if mos_mask_rsmt is None: raise ValueError( "A RSMT file must be supplied if a finding chart is generated for MOS mode." ) if ra or dec or position_angle: raise ValueError( "You must not supply a right ascension, declination or position angle in MOS mode, as they are taken from the MOS mask definition." ) mos_mask = MOSMask(mos_mask_rsmt) ra = mos_mask.right_ascension dec = mos_mask.declination position_angle = mos_mask.position_angle if horizons_id: # get ephemerides from Horizons if ra is not None or dec is not None: raise ValueError( "No right ascension or declination must be supplied if a Horizons identifier is supplied." ) if horizons_stepsize is None: horizons_stepsize = 5 * u.minute ephemeris_service: EphemerisService = HorizonsEphemerisService( object_id=horizons_id, start_time=start_time - timedelta(days=2), end_time=end_time + timedelta(days=2), stepsize=horizons_stepsize, ) else: # use ephemerides for a non-sidereal target if ra is None: raise ValueError("The right ascension is missing.") if dec is None: raise ValueError("The declination is missing.") if min_magnitude is not None and (max_magnitude is None or bandpass is None): raise ValueError( "You must supply a maximum magnitude and bandpass if you supply a minimum magnitude." ) if max_magnitude is not None and (min_magnitude is None or bandpass is None): raise ValueError( "You must supply a minimum magnitude and bandpass if you supply a maximum magnitude." ) if bandpass is not None and (min_magnitude is None or max_magnitude is None): raise ValueError( "You must supply a minimum and maximum magnitude if you supply a bandpass." ) magnitude_range: Optional[MagnitudeRange] = None if ( min_magnitude is not None and max_magnitude is not None and bandpass is not None ): magnitude_range = MagnitudeRange( min_magnitude=min_magnitude, max_magnitude=max_magnitude, bandpass=bandpass, ) ephemeris_service = ConstantEphemerisService( ra=ra, dec=dec, magnitude_range=magnitude_range ) # image image_service = SurveyImageService(survey=survey) # mode details if mode is None: raise ValueError("You must specify an instrument mode.") if mode == Mode.IMAGING or mode == Mode.HRS: mode_details: ModeDetails = ImagingModeDetails(position_angle) elif mode == Mode.SLOT: mode_details = SlotModeDetails(pa=position_angle) elif mode == Mode.LONGSLIT: if slitwidth is None: raise ValueError( "A slit width is required if a finding chart is generated for longslit mode." ) mode_details = LongslitModeDetails( slitwidth=slitwidth, pa=position_angle, center_ra=ra, center_dec=dec ) elif mode == Mode.MOS: if not mos_mask: raise ValueError("No MOS mask has been supplied.") mode_details = MOSModeDetails(mos_mask) else: raise ValueError(f"Mode unsupported: {mode.value}") # output if output_format == OutputFormat.PDF: output = output_pdf elif output_format == OutputFormat.PNG: output = output_png elif output_format == OutputFormat.SVG: output = output_svg else: raise ValueError(f"Output format unsupported: {output_format.value}") # generate the finder charts return finder_charts( mode_details=mode_details, start_time=start_time, end_time=end_time, ephemeris_service=ephemeris_service, image_service=image_service, title=title, basic_annotations=basic_annotations, output=output, )
[ 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 198, 6738, 19720, 1330, 45755, 9399, 11, 35986, 11, 32233, 11, 309, 29291, 198, 198, 11748, 6468, 28338, 13, 41667, 355, 334, 198, 11748, 12972, 22877, 198, 6738, 6468, 28338, 13, 41...
2.534478
3,321
import argparse import logging import sys from datetime import datetime import satstac from satstac import Catalog import satstac.landsat as landsat from .version import __version__ # quiet loggers logging.getLogger('urllib3').propagate = False logging.getLogger('requests').propagate = False logger = logging.getLogger(__name__) if __name__ == "__main__": cli()
[ 11748, 1822, 29572, 198, 11748, 18931, 198, 11748, 25064, 198, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 11748, 3332, 301, 330, 198, 6738, 3332, 301, 330, 1330, 44515, 198, 11748, 3332, 301, 330, 13, 4447, 265, 355, 8604, 265, ...
3.065574
122
import sqlite3 import random import string import re import sys # domain name args = sys.argv if len(args)==2: if args[1] == 'localhost': domain = "localhost:5000/" else: domain = "https://squez-url-shortener.herokuapp.com/" else: domain = "https://squez-url-shortener.herokuapp.com/" # URL verification regex regex = r"""(?i)\b((?:https?://|www\d{0,3}[.]{1}|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?]))""" # check_same_thread=False to disable thread sync conn = sqlite3.connect("url.db", check_same_thread=False) def check_if_exists(id: str, flag: bool): """ returns true if record exists params: id: data to check in db flag: True if shortened URL, else False returns: True if record exists else False """ if flag: query = f'''SELECT COUNT(*) FROM URLS WHERE ID="{id}";''' else: query = f'''SELECT COUNT(*) FROM URLS WHERE ORIGINAL="{id}";''' db_res = conn.execute(query) if [i[0] for i in db_res] == [0]: return False return True def insert_data(id: str, og: str, value: int): """ Insert data in db Params: id: short url(primary key) og: original url value: number of visit returns: True if successful else False """ query = f'''INSERT INTO URLS (ID, ORIGINAL, VISITS) VALUES ("{str(id)}", "{str(og)}", {int(value)});''' db_res = conn.execute(query) conn.commit() if not db_res: return False return True def get_original_url(id: str, flag: bool): """ returns record data if exists params: id: shortened or original url flag: True for shortened id else False returns: False if data doesn't exist else return data """ if flag: query = f'''SELECT ORIGINAL FROM URLS WHERE ID="{str(id)}";''' else: query = f'''SELECT ID FROM URLS WHERE ORIGINAL="{str(id)}";''' db_res = conn.execute(query) url = [i[0] for i in db_res] if url: return url[0] return False def get_valid_combination(url: str)-> str: """ finds and returns shortened URL params: url: original url returns: False if operation failed else return whole shortened link """ res = re.findall(regex, url) url = re.sub(r"^(http://|https://){0,1}(www.|ww.|w.){0,1}", "", url) data = False if res: if not check_if_exists(url, False): while 1: shrt = ''.join(random.choice(string.ascii_letters) for _ in range(8)) if not check_if_exists(shrt, True): if not insert_data(shrt, url, 0): return False data = "".join([domain, shrt]) break else: shrt = get_original_url(url, False) data = "".join([domain, shrt]) return data
[ 11748, 44161, 578, 18, 198, 11748, 4738, 198, 11748, 4731, 198, 11748, 302, 198, 11748, 25064, 198, 198, 2, 7386, 1438, 198, 22046, 796, 25064, 13, 853, 85, 198, 361, 18896, 7, 22046, 8, 855, 17, 25, 198, 220, 220, 220, 611, 26498, ...
2.156003
1,391
from turtle import Turtle from scoreboard import Scoreboard WIDTH = 800 HEIGHT = 600 START_SPEED = 0.1
[ 6738, 28699, 1330, 33137, 198, 198, 6738, 50198, 1330, 15178, 3526, 198, 198, 54, 2389, 4221, 796, 10460, 198, 13909, 9947, 796, 10053, 198, 2257, 7227, 62, 4303, 41841, 796, 657, 13, 16 ]
3.151515
33
from .validation import * from .preparation import * from .external import * from .core import * from .preprocessing import * from .transforms import * from .mixed_augmentation import *
[ 6738, 764, 12102, 341, 1330, 1635, 198, 6738, 764, 3866, 1845, 341, 1330, 1635, 198, 6738, 764, 22615, 1330, 1635, 198, 6738, 764, 7295, 1330, 1635, 198, 6738, 764, 3866, 36948, 1330, 1635, 198, 6738, 764, 7645, 23914, 1330, 1635, 198, ...
3.627451
51
# Generated by Django 2.0 on 2018-04-08 15:13 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 15, 319, 2864, 12, 3023, 12, 2919, 1315, 25, 1485, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.966667
30
jira_user_url = "" jira_email = "" jira_token = ""
[ 73, 8704, 62, 7220, 62, 6371, 796, 13538, 198, 73, 8704, 62, 12888, 796, 13538, 198, 73, 8704, 62, 30001, 796, 13538 ]
2.272727
22
import subprocess, re, os from baseq.utils.runcommand import run_it, run_generator import pandas as pd import random """ baseq dev bed ./bed """ import click, os, sys CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
[ 11748, 850, 14681, 11, 302, 11, 28686, 198, 6738, 2779, 80, 13, 26791, 13, 5143, 21812, 1330, 1057, 62, 270, 11, 1057, 62, 8612, 1352, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 4738, 198, 37811, 198, 8692, 80, 1614, 3996, 24...
2.873418
79
from io import UnsupportedOperation import pytest from xz.io import IOStatic
[ 6738, 33245, 1330, 791, 15999, 32180, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 2124, 89, 13, 952, 1330, 24418, 45442, 628, 628 ]
3.565217
23
# -*- coding: utf-8 -*- """ __init__.py """ import os import logging from logging.handlers import RotatingFileHandler from flask import Flask, request, jsonify, render_template, make_response from classes.database import db from config import DefaultConfig from classes import views #from classes import models from classes import oauth __all__ = ['create_app', 'getDBInstance'] DEFAULT_APP_NAME = __name__ DEFAULT_MODULES = ( (views.frontend, ''), (views.api, '/api'), (views.user, '/users'), (views.context, '/contexts'), (views.sweet, '/sweets'), (views.app, '/apps'), (views.Oauth, '/oauth') ) # return the current db instance # TODO: is this needed so much?
[ 2, 532, 9, 12, 220, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 220, 220, 220, 11593, 15003, 834, 13, 9078, 198, 37811, 198, 198, 11748, 28686, 198, 11748, 18931, 198, 6738, 18931, 13, 4993, 8116, 1330, 18481, 803, 8...
2.886179
246
#!/usr/bin/env python3 import pytest import fileinput import sys DAY=12 def test_answer(example_input, example_result): plants = Plants(example_input) print('Rules: ',plants.rules) for i in range(0, 20+1): if i > 0: plants.gen() print('Pots after {:2} generations: {}'.format(plants.generation, plants.print_pots())) assert '{:2}: {}'.format(i, plants.print_pots()) == example_result[2+i] assert plants.sum_pots() == 325 if __name__ == '__main__': in_lines = [l.strip() for l in fileinput.input(sys.argv[1:] or '{:02}.input'.format(DAY))] plants = Plants(in_lines) for i in range(0, 20+1): if i > 0: plants.gen() print('Pots after {:2} generations: {}'.format(plants.generation, plants.print_pots())) print('Answer: {}'.format(plants.sum_pots()))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 12972, 9288, 198, 11748, 2393, 15414, 198, 11748, 25064, 198, 26442, 28, 1065, 198, 198, 4299, 1332, 62, 41484, 7, 20688, 62, 15414, 11, 1672, 62, 20274, 2599, 198, 220, 613...
2.599349
307
# Databricks notebook source from pyspark.sql import SparkSession from pyspark.sql.functions import col, lit from pyspark.sql.functions import sum,avg,max,min,mean,count spark = SparkSession.builder.appName("Spark DataFrames").getOrCreate() # COMMAND ---------- df = spark.read.options(header='True', inferSchema='True').csv('/FileStore/tables/StudentData.csv') df.show() # COMMAND ---------- # 1 df.groupBy("course").count().show() df.groupBy("course").agg(count("*").alias("total_enrollment")).show() # COMMAND ---------- # 2 df.groupBy("course", "gender").agg(count("*").alias("total_enrollment")).show() # COMMAND ---------- # 3 df.groupBy("course", "gender").agg(sum("marks").alias("total_marks")).show() # COMMAND ---------- # 4 df.groupBy("course", "age").agg(min("marks"), max("marks"), avg("marks")).show()
[ 2, 16092, 397, 23706, 20922, 2723, 198, 6738, 279, 893, 20928, 13, 25410, 1330, 17732, 36044, 198, 6738, 279, 893, 20928, 13, 25410, 13, 12543, 2733, 1330, 951, 11, 6578, 198, 6738, 279, 893, 20928, 13, 25410, 13, 12543, 2733, 1330, 2...
2.929078
282
#!/usr/bin/python3 """ A queue is a first-in first-out type of data structure For this to work, you must be able to enqueue (add) items to the queue, dequeue (remove) items from the queue """
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 37811, 198, 198, 32, 16834, 318, 257, 717, 12, 259, 717, 12, 448, 2099, 286, 1366, 4645, 198, 1890, 428, 284, 670, 11, 345, 1276, 307, 1498, 284, 551, 36560, 357, 2860, 8, 3709, ...
2.928571
70
#!/usr/bin/env python3 import pandas as pd import json df = pd.read_excel("OPIMD Calc_checked_03Feb21AL.xlsx", sheet_name=None) obj = {} dz = df["OPIMD15ACCESSDATAZONERANK"] dz = dz.dropna(subset=["datazone"]) dz.datazone = dz.datazone.astype(int) dz.index = dz.datazone obj["dz"] = dz.OPIMDAccPopRank_AL.to_dict() hlth = df["HEALTHCALC"] hlth.index = hlth.HlthPattern obj["hlth"] = hlth.HlthRank.to_dict() inc = df["INCOMECALC"] inc.index = inc.IncPattern obj["inc"] = inc.IncRank.to_dict() house = df["HOUSECALC"] house.index = house.HouPattern obj["house"] = house.HouRank.to_dict() con = df["CONNECTCALC"] con = con.dropna(subset=["ConPattern"]) con.ConPattern = con.ConPattern.astype(int) con.index = con.ConPattern obj["con"] = con.ConRank.to_dict() assets = df["ASSETSCALC"] assets = assets.dropna(subset=["AsPattern"]) assets.AsPattern = assets.AsPattern.astype(int) assets.index = assets.AsPattern obj["assets"] = assets.AsRank.to_dict() breaks = df["OPIMDRankDecile"] breaks = breaks.iloc[3:13,0:3] breaks.columns = ["min", "max", "decile"] obj["breaks"] = breaks.to_dict(orient='records') with open("data.json", "w") as f: json.dump(obj, f) print("Saved")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 33918, 198, 198, 7568, 796, 279, 67, 13, 961, 62, 1069, 5276, 7203, 3185, 3955, 35, 2199, 66, 62, 26752, 62, 3070, 15146, 2481, ...
2.328094
509
import requests import urllib
[ 11748, 7007, 198, 11748, 2956, 297, 571, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 628, 628, 198 ]
2.043478
23
import re __all__ = ['register_table_name', 'sql_query'] batch_table_name_map = dict() stream_table_name_map = dict()
[ 11748, 302, 198, 198, 834, 439, 834, 796, 37250, 30238, 62, 11487, 62, 3672, 3256, 705, 25410, 62, 22766, 20520, 198, 198, 43501, 62, 11487, 62, 3672, 62, 8899, 796, 8633, 3419, 198, 5532, 62, 11487, 62, 3672, 62, 8899, 796, 8633, 3...
2.733333
45
""" Functions for working with the codepage on Windows systems """ import logging from contextlib import contextmanager from salt.exceptions import CodePageError log = logging.getLogger(__name__) try: import pywintypes import win32console HAS_WIN32 = True except ImportError: HAS_WIN32 = False # Although utils are often directly imported, it is also possible to use the loader. def __virtual__(): """ Only load if Win32 Libraries are installed """ if not HAS_WIN32: return False, "This utility requires pywin32" return "win_chcp" def get_codepage_id(raise_error=False): """ Get the currently set code page on windows Args: raise_error (bool): ``True`` will raise an error if the codepage fails to change. ``False`` will suppress the error Returns: int: A number representing the codepage Raises: CodePageError: On unsuccessful codepage change """ try: return win32console.GetConsoleCP() except pywintypes.error as exc: _, _, msg = exc.args error = "Failed to get the windows code page: {}".format(msg) if raise_error: raise CodePageError(error) else: log.error(error) return -1 def set_codepage_id(page_id, raise_error=False): """ Set the code page on windows Args: page_id (str, int): A number representing the codepage. raise_error (bool): ``True`` will raise an error if the codepage fails to change. ``False`` will suppress the error Returns: int: A number representing the codepage Raises: CodePageError: On unsuccessful codepage change """ if not isinstance(page_id, int): try: page_id = int(page_id) except ValueError: error = "The `page_id` needs to be an integer, not {}".format(type(page_id)) if raise_error: raise CodePageError(error) log.error(error) return -1 try: win32console.SetConsoleCP(page_id) return get_codepage_id(raise_error=raise_error) except pywintypes.error as exc: _, _, msg = exc.args error = "Failed to set the windows code page: {}".format(msg) if raise_error: raise CodePageError(error) else: log.error(error) return -1
[ 37811, 198, 24629, 2733, 329, 1762, 351, 262, 14873, 538, 496, 319, 3964, 3341, 198, 37811, 198, 198, 11748, 18931, 198, 6738, 4732, 8019, 1330, 4732, 37153, 198, 198, 6738, 8268, 13, 1069, 11755, 1330, 6127, 9876, 12331, 198, 198, 6404...
2.359691
1,037
from flask import Flask, render_template from application.settings import STATIC from application.storage import storage app = Flask(__name__, static_url_path=STATIC)
[ 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 198, 198, 6738, 3586, 13, 33692, 1330, 15486, 2149, 198, 6738, 3586, 13, 35350, 1330, 6143, 198, 198, 1324, 796, 46947, 7, 834, 3672, 834, 11, 9037, 62, 6371, 62, 6978, 28, 35744, 2149, ...
3.863636
44
"""Fun section of CLI command.""" import json import logging import time from pprint import pformat, pprint import click from fabric.colors import red
[ 37811, 24629, 2665, 286, 43749, 3141, 526, 15931, 198, 11748, 33918, 198, 11748, 18931, 198, 11748, 640, 198, 6738, 279, 4798, 1330, 279, 18982, 11, 279, 4798, 198, 198, 11748, 3904, 198, 6738, 9664, 13, 4033, 669, 1330, 2266, 628, 628,...
3.636364
44
import unittest import unittest.mock as mock import pytest from smqtk.algorithms.descriptor_generator import DescriptorGenerator from smqtk.algorithms.descriptor_generator.colordescriptor.colordescriptor \ import ColorDescriptor_Image_csift # arbitrary leaf class from smqtk.utils.configuration import configuration_test_helper
[ 11748, 555, 715, 395, 198, 198, 11748, 555, 715, 395, 13, 76, 735, 355, 15290, 198, 11748, 12972, 9288, 198, 198, 6738, 895, 80, 30488, 13, 282, 7727, 907, 13, 20147, 1968, 273, 62, 8612, 1352, 1330, 2935, 6519, 273, 8645, 1352, 198...
3.111111
108
# Generated by Django 2.1.7 on 2019-04-18 09:15 from django.db import migrations, models import django.db.models.deletion import django_fsm
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 22, 319, 13130, 12, 3023, 12, 1507, 7769, 25, 1314, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, ...
2.784314
51
# Generated by Django 3.1.5 on 2021-04-28 16:22 import ckeditor.fields from django.db import migrations, models import django_minio_backend.models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 20, 319, 33448, 12, 3023, 12, 2078, 1467, 25, 1828, 198, 198, 11748, 269, 9091, 2072, 13, 25747, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 62,...
2.921569
51
import socket from threading import Thread, Timer def get_real_ip(): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.connect(('1.1.1.1', 1)) return sock.getsockname()[0] def get_hostname(): return socket.gethostname()
[ 11748, 17802, 198, 6738, 4704, 278, 1330, 14122, 11, 5045, 263, 628, 198, 198, 4299, 651, 62, 5305, 62, 541, 33529, 198, 220, 220, 220, 32263, 796, 17802, 13, 44971, 7, 44971, 13, 8579, 62, 1268, 2767, 11, 17802, 13, 50, 11290, 62, ...
2.51
100
from . import db from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin from . import login_manager from datetime import datetime def __repr__(self): return f'User {self.husband_name} and {self.wife_name}' class Notice(db.Model): __tablename__ = 'notices' id = db.Column(db.Integer, primary_key = True) district = db.Column(db.String(255)) spouse = db.Column(db.String(255)) g_name = db.Column(db.String(255)) g_condition = db.Column(db.String(255)) g_occupation = db.Column(db.String(255)) g_age = db.Column(db.Integer) g_residence = db.Column(db.String(255)) g_consent = db.Column(db.String(255)) b_name = db.Column(db.String(255)) b_condition = db.Column(db.String(255)) b_occupation = db.Column(db.String(255)) b_age = db.Column(db.Integer) b_residence = db.Column(db.String(255)) b_consent = db.Column(db.String(255)) dd = db.Column(db.Integer) mm = db.Column(db.String(255)) yy = db.Column(db.Integer) signature = db.Column(db.String(255)) user_id = db.Column(db.Integer,db.ForeignKey("users.id")) class Certificate(db.Model): __tablename__ = 'certificates' id = db.Column(db.Integer, primary_key = True) g_date = db.Column(db.Date()) g_name = db.Column(db.String(255)) g_condition = db.Column(db.String(255)) g_occupation = db.Column(db.String(255)) g_age = db.Column(db.Integer) g_residence = db.Column(db.String(255)) g_fname = db.Column(db.String(255)) g_foccupation = db.Column(db.String(255)) b_date = db.Column(db.Date()) b_name = db.Column(db.String(255)) b_condition = db.Column(db.String(255)) b_occupation = db.Column(db.String(255)) b_age = db.Column(db.Integer) b_residence = db.Column(db.String(255)) g_fname = db.Column(db.String(255)) g_foccupation = db.Column(db.String(255)) groom = db.Column(db.String(255)) bride = db.Column(db.String(255)) witness1 = db.Column(db.String(255)) witness2 = db.Column(db.String(255)) date = db.Column(db.Date()) user_id = db.Column(db.Integer,db.ForeignKey("users.id")) class Impediment(db.Model): __tablename__ = 'impediments' id = db.Column(db.Integer, primary_key = True) spouse = db.Column(db.String(255)) at = db.Column(db.String(255)) in_input = db.Column(db.String(255)) surname = db.Column(db.String(255)) forename = db.Column(db.String(255)) country = db.Column(db.String(255)) date = db.Column(db.Date()) father = db.Column(db.String(255)) sex = db.Column(db.String(255)) race = db.Column(db.String(255)) religion = db.Column(db.String(255)) residence = db.Column(db.String(255)) condition = db.Column(db.String(255)) occupation = db.Column(db.String(255)) dd = db.Column(db.Integer) mm = db.Column(db.String(255)) yy = db.Column(db.Integer) signature = db.Column(db.String(255)) user_id = db.Column(db.Integer,db.ForeignKey("users.id")) class Agreement(db.Model): __tablename__ = 'agreements' id = db.Column(db.Integer, primary_key = True) husband_vows = db.Column(db.String(255)) wife_vows = db.Column(db.String(255)) dowry_agreement = db.Column(db.String(255)) other_agreements = db.Column(db.String(255)) user_id = db.Column(db.Integer,db.ForeignKey("users.id")) class Witness(db.Model): __tablename__ = 'witnesses' id = db.Column(db.Integer, primary_key = True) witness1_name = db.Column(db.String(255)) witness2_name = db.Column(db.String(255)) witness1_id = db.Column(db.String(255)) witness2_id = db.Column(db.String(255)) witness1_dob = db.Column(db.Date()) witness2_dob = db.Column(db.Date()) user_id = db.Column(db.Integer,db.ForeignKey("users.id"))
[ 6738, 764, 1330, 20613, 198, 6738, 266, 9587, 2736, 1018, 13, 12961, 1330, 7716, 62, 28712, 62, 17831, 11, 2198, 62, 28712, 62, 17831, 198, 6738, 42903, 62, 38235, 1330, 11787, 35608, 259, 198, 6738, 764, 1330, 17594, 62, 37153, 198, ...
2.410692
1,590
# coding=utf-8 # Copyright 2021-present, the Recognai S.L. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest from rubrix.server.commons.errors import ClosedDatasetError from rubrix.server.commons.es_wrapper import create_es_wrapper from rubrix.server.datasets.dao import DatasetsDAO from rubrix.server.datasets.model import DatasetDB from rubrix.server.tasks.commons import TaskType from rubrix.server.tasks.commons.dao.dao import dataset_records_dao from rubrix.server.tasks.text_classification.dao.es_config import ( text_classification_mappings, ) es_wrapper = create_es_wrapper() records = dataset_records_dao(es_wrapper) records.register_task_mappings( TaskType.text_classification, text_classification_mappings() ) dao = DatasetsDAO.get_instance(es_wrapper, records)
[ 2, 220, 19617, 28, 40477, 12, 23, 198, 2, 220, 15069, 33448, 12, 25579, 11, 262, 31517, 1872, 311, 13, 43, 13, 1074, 13, 198, 2, 198, 2, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 1...
3.171498
414
import unittest from solution.rotated_array_search import RotatedArraySearch
[ 11748, 555, 715, 395, 198, 6738, 4610, 13, 10599, 515, 62, 18747, 62, 12947, 1330, 18481, 515, 19182, 18243, 198 ]
3.85
20
############################################################### # pytest -v --capture=no tests/test_keygroup.py # pytest -v tests/test_keygroup.py ############################################################### #import pytest import os from cloudmesh.common.variables import Variables from cloudmesh.common.Benchmark import Benchmark from cloudmesh.compute.vm.Provider import Provider from cloudmesh.configuration.Config import Config from cloudmesh.mongo.CmDatabase import CmDatabase # import pytest import os from cloudmesh.common.Benchmark import Benchmark from cloudmesh.common.variables import Variables from cloudmesh.compute.vm.Provider import Provider from cloudmesh.configuration.Config import Config from cloudmesh.mongo.CmDatabase import CmDatabase Benchmark.debug() user = Config()["cloudmesh.profile.user"] variables = Variables() KEY = "test-keygroup" cloud = variables.parameter('cloud') print(f"Test run for {cloud} on key {KEY}") if cloud is None: raise ValueError("cloud is not not set") cm = CmDatabase() provider = Provider(name=cloud) #@pytest.mark.incremental
[ 29113, 14468, 7804, 4242, 21017, 198, 2, 12972, 9288, 532, 85, 1377, 27144, 495, 28, 3919, 5254, 14, 9288, 62, 2539, 8094, 13, 9078, 198, 2, 12972, 9288, 532, 85, 220, 5254, 14, 9288, 62, 2539, 8094, 13, 9078, 198, 29113, 14468, 780...
3.460568
317
import pytest import pandas as pd import numpy as np from blinpy import models data = pd.DataFrame( {'x': np.array( [0.0, 1.0, 1.0, 2.0, 1.8, 3.0, 4.0, 5.2, 6.5, 8.0, 10.0]), 'y': np.array([5.0, 5.0, 5.1, 5.3, 5.5, 5.7, 6.0, 6.3, 6.7, 7.1, 7.5])} )
[ 11748, 12972, 9288, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 698, 259, 9078, 1330, 4981, 198, 198, 7890, 796, 279, 67, 13, 6601, 19778, 7, 198, 220, 220, 220, 220, 220, 220, 220, 1391, 6, ...
1.643678
174
import pprint import time import json from gtmcore.dispatcher import Dispatcher, jobs from lmsrvlabbook.tests.fixtures import fixture_working_dir
[ 11748, 279, 4798, 198, 11748, 640, 198, 11748, 33918, 198, 198, 6738, 308, 17209, 7295, 13, 6381, 8071, 2044, 1330, 3167, 8071, 2044, 11, 3946, 198, 6738, 300, 907, 81, 19279, 397, 2070, 13, 41989, 13, 69, 25506, 1330, 29220, 62, 1609...
3.288889
45
import re n = int(input()) for i in range(n): print(verify(input()))
[ 11748, 302, 198, 77, 796, 493, 7, 15414, 28955, 198, 1640, 1312, 287, 2837, 7, 77, 2599, 198, 220, 220, 220, 3601, 7, 332, 1958, 7, 15414, 3419, 4008 ]
2.482759
29
from MAPLEAF.Motion import ForceMomentSystem, Inertia, Vector from MAPLEAF.Rocket import RocketComponent __all__ = [ "SampleStatefulComponent" ]
[ 6738, 34645, 2538, 8579, 13, 45740, 1330, 5221, 29252, 298, 11964, 11, 554, 861, 544, 11, 20650, 198, 6738, 34645, 2538, 8579, 13, 50218, 1330, 16920, 21950, 198, 198, 834, 439, 834, 796, 685, 366, 36674, 9012, 913, 21950, 1, 2361 ]
3.536585
41
from Utils.Array import input_array ZERO, ONE, TWO = 0, 1, 2 # Time -> O(n) # Space -> O(1) inplace if __name__ == "__main__": A = input_array() sort_by_counting(A) print(A) """ 2 1 0 1 2 0 0 0 1 2 2 2 1 1 1 1 1 1 2 1 0 2 1 0 2 1 0 """
[ 6738, 7273, 4487, 13, 19182, 1330, 5128, 62, 18747, 198, 198, 57, 34812, 11, 16329, 11, 35288, 796, 657, 11, 352, 11, 362, 628, 198, 2, 3862, 220, 4613, 440, 7, 77, 8, 198, 2, 4687, 4613, 440, 7, 16, 8, 220, 287, 5372, 628, 19...
2.064516
124
#!/usr/bin/python -t # 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 Library 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # Copyright 2005 Duke University """ Progress display callback classes for the yum command line. """ import rpm import os import sys import logging from yum import _ from yum.constants import *
[ 2, 48443, 14629, 14, 8800, 14, 29412, 532, 83, 198, 2, 770, 1430, 318, 1479, 3788, 26, 345, 460, 17678, 4163, 340, 290, 14, 273, 13096, 198, 2, 340, 739, 262, 2846, 286, 262, 22961, 3611, 5094, 13789, 355, 3199, 416, 198, 2, 262, ...
3.89916
238
#!/usr/bin/env python3 import rospy from miradar_node.msg import PPI, PPIData from visualization_msgs.msg import MarkerArray, Marker from geometry_msgs.msg import Point import dynamic_reconfigure.client if __name__ == "__main__": rospy.init_node("ppi_visualizer") ppiVisualizer = PPIVisualizer() rospy.spin()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 686, 2777, 88, 198, 6738, 5720, 324, 283, 62, 17440, 13, 19662, 1330, 350, 11901, 11, 21082, 2389, 1045, 198, 6738, 32704, 62, 907, 14542, 13, 19662, 1330, 2940, 263, ...
2.518797
133
import dash from dash.dependencies import Input, Output import dash_core_components as dcc import dash_html_components as html import psycopg2 import json import pandas as pd import time app = dash.Dash(__name__) #app.css.config.serve_locally=False #app.css.append_css( # {'external_url': 'https://codepen.io/amyoshino/pen/jzXypZ.css'}) conn = psycopg2.connect(host='ec2-18-232-24-132.compute-1.amazonaws.com',database='earthquake', user='postgres', password='********') cur = conn.cursor() location = pd.read_csv("data_file.csv") location=location.astype(str) app.layout = html.Div([ html.Div([ html.Div([ dcc.Graph(id='graph', style={'margin-top': '20'})], className="six columns"), html.Div([ dcc.Graph( id='bar-graph' ) ], className='twelve columns' ), dcc.Interval( id='interval-component', interval=5*1000, # in milliseconds n_intervals=0) ], className="row") ], className="ten columns offset-by-one") if __name__ == '__main__': app.run_server(debug=False)
[ 11748, 14470, 198, 6738, 14470, 13, 45841, 3976, 1330, 23412, 11, 25235, 198, 11748, 14470, 62, 7295, 62, 5589, 3906, 355, 288, 535, 198, 11748, 14470, 62, 6494, 62, 5589, 3906, 355, 27711, 198, 11748, 17331, 22163, 70, 17, 198, 11748, ...
2.268293
492
import pymongo from .config import DB_PASSWORD, DB_USER, CLUSTER_NAME, SUBDOMAIN, DB_NAME from .exceptions import CharacterNotFound, PoemAuthorNotFound DBService = DatabaseService()
[ 11748, 279, 4948, 25162, 198, 198, 6738, 764, 11250, 1330, 20137, 62, 47924, 54, 12532, 11, 20137, 62, 29904, 11, 7852, 7759, 1137, 62, 20608, 11, 28932, 39170, 29833, 11, 20137, 62, 20608, 198, 6738, 764, 1069, 11755, 1330, 15684, 3673...
3.1
60
# imports from collections import defaultdict import numpy as np import matplotlib.pyplot as pyplot # pycsep imports import csep from csep.utils import stats, plots # experiment imports from experiment_utilities import ( load_zechar_catalog, plot_consistency_test_comparison, read_zechar_csv_to_dict ) from experiment_config import config # runtime flags show_target_event_rates = True plot = False compute_evaluations = True # catalog from manuscript catalog = csep.load_catalog('./data/evaluation_catalog_zechar2013_merge.txt', loader=load_zechar_catalog) evaluation_results = defaultdict(list) # load results from zechar zechar_dict = read_zechar_csv_to_dict('./data/consistency_quantile_scores_from_zechar.csv') # main evaluation loop for name, path in config['forecasts'].items(): # load forecast fore = csep.load_gridded_forecast( config['forecasts'][name], start_date=config['start_date'], end_date=config['end_date'], name=name ) # assign region of forecast to catalog catalog.region = fore.region cat_filt = catalog.filter_spatial(in_place=False) # assign region to new catalog cat_filt.region = fore.region # compute likelihood and expected number of events spatial_magnitude_counts = cat_filt.spatial_magnitude_counts() ll = stats.poisson_log_likelihood(spatial_magnitude_counts, fore.data).sum() # print summary statistics print(f"{name}\n==========================") print(f"Nfore: {fore.sum()}\nNobs: {cat_filt.event_count}\nLL/Nobs: {ll / cat_filt.event_count}") print("") if show_target_event_rates: print("Target event rates") for lon, lat, mag in zip(cat_filt.get_longitudes(), cat_filt.get_latitudes(), cat_filt.get_magnitudes()): try: rate = fore.get_rates([lon], [lat], [mag]) print(lon, lat, mag, rate[0]) except ValueError: print(lon, lat, mag, "ERROR") print("") # n-test if compute_evaluations: n_test_result = csep.poisson_evaluations.number_test( fore, cat_filt ) evaluation_results['n-test'].append(n_test_result) print(f"N-test result: {n_test_result.quantile}") # m-test m_test_result = csep.poisson_evaluations.magnitude_test( fore, cat_filt, num_simulations=config['nsims'], seed=config['seed'] ) evaluation_results['m-test'].append(m_test_result) print(f"M-test result: {m_test_result.quantile}") # s-test s_test_result = csep.poisson_evaluations.spatial_test( fore, cat_filt, num_simulations=config['nsims'], seed=config['seed'], ) evaluation_results['s-test'].append(s_test_result) print(f"S-test result: {s_test_result.quantile}") # l-test l_test_result = csep.poisson_evaluations.likelihood_test( fore, cat_filt, num_simulations=config['nsims'], seed=config['seed'], ) evaluation_results['l-test'].append(l_test_result) print(f"L-test result: {l_test_result.quantile}") print("") # plot and save results ax = plot_consistency_test_comparison(evaluation_results, zechar_dict) ax.get_figure().savefig('./output/pycsep_zechar_comparison.pdf') # visualizations if plot: ax = plots.plot_poisson_consistency_test( evaluation_results['n-test'], plot_args={'xlabel': 'Observed earthquakes'} ) ax.set_xlim([0,100]) ax.get_figure().savefig('./output/number_test_pycsep.pdf') ax = plots.plot_poisson_consistency_test( evaluation_results['l-test'], plot_args={'xlabel': 'log-likelihood'}, one_sided_lower=True ) ax.set_xlim([-600,0]) ax.get_figure().savefig('./output/likelihood_test_pycsep.pdf') ax = plots.plot_poisson_consistency_test( evaluation_results['s-test'], plot_args={'xlabel': 'log-likelihood'}, one_sided_lower=True ) ax.set_xlim([-220, -100]) ax.get_figure().savefig('./output/spatial_test_pycsep.pdf') ax = plots.plot_poisson_consistency_test( evaluation_results['m-test'], plot_args={'xlabel': 'log-likelihood'}, one_sided_lower=True ) ax.set_xlim([-35, -10]) ax.get_figure().savefig('./output/magnitude_test_pycsep.pdf')
[ 2, 17944, 198, 6738, 17268, 1330, 4277, 11600, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 12972, 29487, 198, 198, 2, 12972, 66, 325, 79, 17944, 198, 11748, 269, 325, 79, 198, 6738, 26...
2.191283
2,065
import os import re import sys import time import puzzles from csp import * from search import * from utils import * if __name__ == "__main__": # Get all puzzles from puzzle.py kakuro_puzzles = [] for item in vars(puzzles).keys(): if not item.startswith("__"): kakuro_puzzles.append((item,vars(puzzles)[item])) for puzzle_name, puzzle in kakuro_puzzles: print("\n----------------------------- {} Kakuro puzzle -----------------------------".format(puzzle_name)) kakuro = Kakuro(puzzle) kakuro.display_grid(kakuro.puzzle) # BT algorithm print("\n> Solution using BT algorithm") kakuro.display_solution(kakuro.puzzle, *kakuro.BT(), kakuro.nassigns) # BT + MRV algorithm print("\n> Solution using BT and MRV algorithm") kakuro.display_solution(kakuro.puzzle, *kakuro.BT_MRV(), kakuro.nassigns) # FC algorithm print("\n> Solution using FC algorithm") kakuro.display_solution(kakuro.puzzle, *kakuro.FC(), kakuro.nassigns) # FC + MRV algorithm print("\n> Solution using FC and MRV algorithm") kakuro.display_solution(kakuro.puzzle, *kakuro.FC_MRV(), kakuro.nassigns) # MAC algorithm print("\n> Solution using MAC algorithm") kakuro.display_solution(kakuro.puzzle, *kakuro.MAC(), kakuro.nassigns) # print an empty line for better output print()
[ 11748, 28686, 198, 11748, 302, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 24367, 198, 198, 6738, 269, 2777, 1330, 1635, 198, 6738, 2989, 1330, 1635, 198, 6738, 3384, 4487, 1330, 1635, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366...
2.332253
617
C, N = map(int, input().split(' ')) print(C % N)
[ 34, 11, 399, 796, 3975, 7, 600, 11, 5128, 22446, 35312, 10786, 705, 4008, 198, 4798, 7, 34, 4064, 399, 8, 198 ]
2.227273
22
import csv import os import sys import matplotlib.pyplot as plt from metrics.index import metrics from plot_package.helpers import ascendence_label, descendence_label, with_sign if len(sys.argv) != 2: print(f"{__file__} sample_name.csv") sys.exit(1) sample_name = sys.argv[1] # set size plt.figure(figsize=(20.48, 10.24)) # draw heartbeats seconds = [] heartbeats = [] with open(sample_name) as f: read_csv = csv.reader(f, delimiter=",") for row in read_csv: seconds.append(int(row[0])) heartbeats.append(int(row[1])) plt.plot(seconds, heartbeats, color="blue", marker="D") # calcualte ctg metrics ctg_metrics = metrics(heartbeats) x_min = 0 x_max = seconds[-1] basic_channel_bottom = ctg_metrics.avg * 0.875 # - 12.5% basic_channel_top = ctg_metrics.avg * 1.125 # + 12.5% # draw ctg metrics # average # TODO: use a beeter way to draw line (plot(y)). See _axes.py plot method docs plt.plot( [x_min, x_max], [ctg_metrics.avg, ctg_metrics.avg], label=f"Average: {round(ctg_metrics.avg, 2)}", color="red", ) # basic channel plt.plot([x_min, x_max], [basic_channel_bottom, basic_channel_bottom], color="black") plt.plot( [x_min, x_max], [basic_channel_top, basic_channel_top], color="black", label=f"Basic channel from {round(basic_channel_bottom, 2)} to {round(basic_channel_top, 2)}. " f"Variance: {with_sign(ctg_metrics.variance)}", ) # ascendences for index, ascendence in enumerate(ctg_metrics.ascendences): plt.plot( # NOTE: We add + 1 to ascendence.end cause slice(, end) is exclusive seconds[slice(ascendence.start, ascendence.end + 1)], heartbeats[slice(ascendence.start, ascendence.end + 1)], color="green", marker="D", label=ascendence_label( heartbeats=heartbeats, ascendence=ascendence, index=index ), ) # descendences for index, descendence in enumerate(ctg_metrics.descendences): plt.plot( seconds[slice(descendence.start, descendence.end + 1)], heartbeats[slice(descendence.start, descendence.end + 1)], color="purple", marker="D", label=descendence_label( heartbeats=heartbeats, descendence=descendence, index=index ), ) # draw common plot elements # naming the x axis plt.xlabel("Second") # naming the y axis plt.ylabel("Heartbeat") # giving a title to my graph plt.title("CTG") # show a legend on the plot plt.legend() # function to show the plot plt.show() # save the plot # sample_basename, _sample_extname = os.path.splitext(sample_name) # figure_name = f"{sample_basename}.png" # plt.savefig(figure_name) # print(f"Saved to {figure_name}")
[ 11748, 269, 21370, 198, 11748, 28686, 198, 11748, 25064, 198, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 6738, 20731, 13, 9630, 1330, 20731, 198, 198, 6738, 7110, 62, 26495, 13, 16794, 364, 1330, 34800, 594,...
2.394643
1,120
#!/user/bin/env python # -*- coding:utf-8 -*- # zm6 # 2021-03-19 # 2021-03-19 # N import time # if __name__ == "__main__": n = int(input("please enter the number")) # n start = time.time() # num = list_prime(n) print(n, "", num) end = time.time() # print(str(end - start))
[ 2, 48443, 7220, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 2, 1976, 76, 21, 198, 2, 33448, 12, 3070, 12, 1129, 198, 2, 33448, 12, 3070, 12, 1129, 198, 2, 399, 628, 198, 11748, ...
2.166667
144
import glob import os from pkg_resources import resource_filename import mbuild as mb import parmed as pmd import pytest from foyer import Forcefield from foyer.tests.utils import get_fn FF_DIR = resource_filename('foyer', 'forcefields') FORCEFIELDS = glob.glob(os.path.join(FF_DIR, '*.xml'))
[ 11748, 15095, 198, 11748, 28686, 198, 6738, 279, 10025, 62, 37540, 1330, 8271, 62, 34345, 198, 198, 11748, 285, 11249, 355, 285, 65, 198, 11748, 1582, 1150, 355, 9114, 67, 198, 11748, 12972, 9288, 198, 198, 6738, 277, 35301, 1330, 5221,...
2.980198
101
from ns_portal.database.meta import ( Main_Db_Base ) from sqlalchemy import ( Column, Integer, String )
[ 6738, 36545, 62, 634, 282, 13, 48806, 13, 28961, 1330, 357, 198, 220, 220, 220, 8774, 62, 43832, 62, 14881, 198, 8, 198, 6738, 44161, 282, 26599, 1330, 357, 198, 220, 220, 220, 29201, 11, 198, 220, 220, 220, 34142, 11, 198, 220, 2...
2.469388
49
""" Form validators for authorization """ import re from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import DataRequired, Length, ValidationError, Email, EqualTo from cloudcourseproject.src.model import User def password_validator(password): """ Validate password should contain capital and small latin letters and numbers """ if re.search("[0-9]", password) is None: raise ValidationError("Password should have numbers") if re.search("[A-Z]", password) is None: raise ValidationError("Password should contain capital latin letters") if re.search("[a-z]", password) is None: raise ValidationError("Password should contain lower latin letters")
[ 37811, 5178, 4938, 2024, 329, 19601, 37227, 198, 11748, 302, 198, 6738, 42903, 62, 86, 27110, 1330, 46947, 8479, 198, 6738, 266, 83, 23914, 1330, 10903, 15878, 11, 30275, 15878, 11, 39900, 15878, 198, 6738, 266, 83, 23914, 13, 12102, 20...
3.481481
216
import pathlib from mara_pipelines.commands.sql import ExecuteSQL, Copy from mara_pipelines.pipelines import Pipeline, Task from mara_pipelines import config pipeline = Pipeline( id="load_marketing_data", description="Jobs related with loading marketing leads data from the backend database", max_number_of_parallel_tasks=5, base_path=pathlib.Path(__file__).parent, labels={"Schema": "m_data"}) pipeline.add_initial( Task(id="initialize_schemas", description="Recreates the marketing data schema", commands=[ ExecuteSQL(sql_file_name='../recreate_marketing_data_schema.sql', file_dependencies=[ pathlib.Path(__file__).parent.parent / 'recreate_marketing_data_schema.sql'])])) tables = [ 'closed_deal', 'marketing_qualified_lead' ] for table in tables: pipeline.add( Task(id=f"load_{table}", description=f'Loads the {table}s from the backend database', commands=[ ExecuteSQL(sql_file_name=f'{table}/create_{table}_table.sql'), Copy(sql_statement=f""" SELECT * FROM marketing.{table}s; """, source_db_alias='olist', target_db_alias='dwh', target_table=f'm_data.{table}', delimiter_char=';')] ) )
[ 11748, 3108, 8019, 198, 198, 6738, 1667, 64, 62, 79, 541, 20655, 13, 9503, 1746, 13, 25410, 1330, 8393, 1133, 17861, 11, 17393, 198, 6738, 1667, 64, 62, 79, 541, 20655, 13, 79, 541, 20655, 1330, 37709, 11, 15941, 198, 6738, 1667, 64...
2.085294
680
from django.urls import path,include from .views import menu, image, weixinFile urlpatterns = [ path('menu/list', menu.get_menu), path('menu/user', menu.UserMenu.as_view()), path('image', image.ImageView.as_view()), path('saveWX', weixinFile.saveWX), path('getRecentWX', weixinFile.getRecentWX), ]
[ 198, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 11, 17256, 198, 6738, 764, 33571, 1330, 6859, 11, 2939, 11, 356, 844, 259, 8979, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 3108, 10786, 26272, 14, 4868, 3256, 68...
2.5
128
from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from navigation import Link from .permissions import ( permission_key_delete, permission_key_receive, permission_key_view, permission_keyserver_query ) link_private_keys = Link( icon='fa fa-key', permissions=(permission_key_view,), text=_('Private keys'), view='django_gpg:key_private_list' ) link_public_keys = Link( icon='fa fa-key', permissions=(permission_key_view,), text=_('Public keys'), view='django_gpg:key_public_list' ) link_key_delete = Link( permissions=(permission_key_delete,), tags='dangerous', text=_('Delete'), view='django_gpg:key_delete', args=('object.fingerprint', 'object.type',) ) link_key_query = Link( permissions=(permission_keyserver_query,), text=_('Query keyservers'), view='django_gpg:key_query' ) link_key_receive = Link( keep_query=True, permissions=(permission_key_receive,), text=_('Import'), view='django_gpg:key_receive', args='object.key_id' ) link_key_setup = Link( icon='fa fa-key', permissions=(permission_key_view,), text=_('Key management'), view='django_gpg:key_public_list' )
[ 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 334, 1136, 5239, 62, 75, 12582, 355, 4808, 198, 198, 6738, 16408, 1330, 7502, 198, 198, 6738, 764, 525, 8481, 1330, ...
2.726852
432
""" Problem : RNA Splicing URL : http://rosalind.info/problems/splc/ Author : David P. Perkins """ import fasta if __name__ == "__main__": import sys FASTAs = fasta.FASTA.fromList(sys.stdin.readline()) cr = getCodingRegion(FASTAs[0].value, [x.value for x in FASTAs[1:]]) rna = cr.replace('T','U') prot = RNAtoProt(rna) print(prot)
[ 37811, 198, 40781, 220, 1058, 25897, 13341, 6345, 198, 21886, 220, 220, 220, 220, 220, 1058, 2638, 1378, 4951, 282, 521, 13, 10951, 14, 1676, 22143, 14, 22018, 66, 14, 198, 13838, 220, 220, 1058, 3271, 350, 13, 29618, 198, 37811, 198,...
2.228916
166
import os path_joiner = os.path.join path_basename = os.path.basename
[ 11748, 28686, 628, 198, 6978, 62, 7639, 7274, 796, 28686, 13, 6978, 13, 22179, 198, 6978, 62, 12093, 12453, 796, 28686, 13, 6978, 13, 12093, 12453 ]
2.730769
26
"""Interrupt field tests.""" from copy import deepcopy from unittest import TestCase from ..testbench import RegisterFileTestbench
[ 37811, 9492, 3622, 2214, 5254, 526, 15931, 198, 198, 6738, 4866, 1330, 2769, 30073, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 6738, 11485, 9288, 26968, 1330, 17296, 8979, 14402, 26968, 198 ]
4
33
import tornado.ioloop import tornado.web import tornado.options from tornado.log import gen_log ''' Alert Manager Documentation: https://prometheus.io/docs/alerting/configuration/ Sample alertmanager message: { "version": "4", "groupKey": <string>, // key identifying the group of alerts (e.g. to deduplicate) "status": "<resolved|firing>", "receiver": <string>, "groupLabels": <object>, "commonLabels": <object>, "commonAnnotations": <object>, "externalURL": <string>, // backlink to the Alertmanager. "alerts": [ { "status": "<resolved|firing>", "labels": <object>, "annotations": <object>, "startsAt": "<rfc3339>", "endsAt": "<rfc3339>", "generatorURL": <string> // identifies the entity that caused the alert }, ... ] } ''' def make_app(): return tornado.web.Application([ (r"/v1/webhooks/incoming/([^/]+)", MainHandler), (r"/", HealthHandler), ]) if __name__ == "__main__": tornado.options.parse_command_line() app = make_app() app.listen(8080) tornado.ioloop.IOLoop.current().start()
[ 11748, 33718, 13, 1669, 11224, 198, 11748, 33718, 13, 12384, 198, 11748, 33718, 13, 25811, 220, 198, 6738, 33718, 13, 6404, 1330, 2429, 62, 6404, 198, 198, 7061, 6, 198, 36420, 9142, 43925, 25, 3740, 1378, 16963, 36916, 13, 952, 14, 3...
2.558891
433
from rest_framework import serializers from backend.models import TodoItem, Note from django.contrib.auth import authenticate, get_user_model
[ 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 6738, 30203, 13, 27530, 1330, 309, 24313, 7449, 11, 5740, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 8323, 5344, 11, 651, 62, 7220, 62, 19849, 628, 628, 198 ]
3.74359
39
from rstem.led_matrix import FrameBuffer from rstem.mcpi import minecraft, control import time control.show() mc = minecraft.Minecraft.create() SCALE = 25 fb = FrameBuffer() count = 0 FLASH_COUNT = 3 flash_lit = True while True: pos = mc.player.getTilePos() x = round(pos.x/SCALE + (fb.width-1)/2) x_out_of_bounds = not 0 <= x < fb.width x = min(fb.width-1, max(0, x)) z = round(pos.z/SCALE + (fb.height-1)/2) z_out_of_bounds = not 0 <= z < fb.height z = min(fb.height-1, max(0, z)) fb.erase() count += 1 if count > FLASH_COUNT: flash_lit = not flash_lit count = 0 if not x_out_of_bounds and not z_out_of_bounds or flash_lit: fb.point(z, x) fb.show() time.sleep(0.01)
[ 6738, 374, 927, 13, 992, 62, 6759, 8609, 1330, 25184, 28632, 198, 6738, 374, 927, 13, 76, 13155, 72, 1330, 6164, 3323, 11, 1630, 198, 11748, 640, 198, 198, 13716, 13, 12860, 3419, 198, 198, 23209, 796, 6164, 3323, 13, 39194, 13, 179...
2.271242
306
import os from os.path import join as osp import numpy as np from tqdm import tqdm import wandb import torch import torch.nn as nn import torch.optim as optim from torch.cuda import amp import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP from torch import autograd from torch.optim import lr_scheduler # from torchinfo import summary from options.train_options import TrainOptions from utils import AverageMeter, reduce_loss, synchronize, cleanup, seed_everything, set_grads, log_imgs_wandb from data import CreateDataLoader from data.unaligned_dataset import UnAlignedDataset from models.custom_unet import Unet, NLayerDiscriminator, PatchSampleF, GANLoss, PatchNCELoss, get_norm_layer, init_weights if __name__ == '__main__': main()
[ 11748, 28686, 198, 6738, 28686, 13, 6978, 1330, 4654, 355, 267, 2777, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 198, 11748, 11569, 65, 198, 198, 11748, 28034, 198, 11748, 28034, 13, 20471,...
3.260331
242
from backend.common.consts.notification_type import NotificationType from backend.common.models.notifications.verification import ( VerificationNotification, )
[ 6738, 30203, 13, 11321, 13, 1102, 6448, 13, 1662, 2649, 62, 4906, 1330, 42808, 6030, 198, 6738, 30203, 13, 11321, 13, 27530, 13, 1662, 6637, 13, 332, 2649, 1330, 357, 198, 220, 220, 220, 4643, 2649, 3673, 2649, 11, 198, 8, 628, 628,...
3.818182
44