content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
#/usr/bin/python import serial import time import matplotlib.pyplot as plt import numpy as np import os """"""""""""""""""""""""""""""""""" """""""NEVS BEER SCRIPT"""""""""""" """"""""""""""""""""""""""""""""""" ###need to add exception handler for serial disconnection ## SETUP SERIAL PORT try: ser = serial.Serial('COM3',9600) # open serial port print('Serial connection established!') except: print('ERR: Unable to connect to arduino...retrying') time.sleep(3) try: ser = serial.Serial('COM3',9600) except: raw_input('ERR: Unable to connect to arduino....check connections and press Enter to continue') try: ser = serial.Serial('COM3',9600) except: raw_input('ERR: Unable to connect to arduino...Press Enter to exit..') ## STRIKE WATER CALCULATOR ##strike water calculator ##volume of water is heated inside an insulated mash tun ##grain is added to mash tun ## Tw = (Tm((Sw*mw)+(Sg*mg))-(Sg*mg*Tg))/(Sw*mw) ## Tw = strike water temp. ## Tm = mash temp. Sw = 1; ##Specific heat water Sg = 0.4; ##Specific heat grain beername = raw_input("Please enter the name of the beer:") Tm = input("Mash Temp.(\xb0C)") Vw = input("Water Volume(L)") mw = Vw; ##mass water(kg) = volume water(L) mg = input("Grain mass(kg)") Tg = input("Grain temp.(\xb0C)") print("Calculating...") time.sleep(1) Tw = (Tm*((Sw*mw)+(Sg*mg))-(Sg*mg*Tg))/(Sw*mw) Tw = round(Tw,1) ##print "Strike temp.(\xb0C) = "+str(Tw) ## MASH INSTRUCTIONS print 'Set strike temperature to ' + str(Tw) + '\xb0C' raw_input('Press Enter to continue...') temperaturefloat = 0 ##measure temperature while True: try: temperaturefloat = round(float((ser.read(7))),1) #read except: ##handle all serial read errors try: ser = serial.Serial('COM3',9600) # open serial port except: ser.close() ser = serial.Serial('COM3',9600) # open serial port temperaturefloat = 0 time.sleep(0.1) print str(temperaturefloat) + '\xb0C' time.sleep(0.1) ## if temperaturefloat > Tm: #### check temperature 5 times ## dragon = np.ones(5) ## for i in range(0,4): ## try: ## temperaturefloat = round(float(ser.read(7)),1) ## except: ##handle all serial read errors ## temperaturefloat = 0 ## ## if temperaturefloat < 0: ## temperaturefloat = 0 ## ## print str(temperaturefloat) + '\xb0C' ## dragon[i] = temperaturefloat ## print str(dragon) ## time.sleep(0.1) ## if sum(dragon)/5 > Tm: ## print 'SUCCESS' ## break if temperaturefloat > Tm: print 'Stike temperature reached! Please stir the water and prepare grain for submersion...' mashtime1 = 60*input('Enter total mash time (min):') raw_input('Submerge grain and press enter to coninue...') print 'Mash in progress, please wait ' + str(mashtime1/60) + ' minutes...' break ## TEMPERATURE LOGGING ser.close() ## restart Com port ser = serial.Serial('COM3',9600) print 'Temp(\xb0C)\tTime(s)' nowtimefloat = 0 temperaturefloat = 0 #read from serial and exit when user wants while nowtimefloat < mashtime1: try: temperaturefloat = round(float((ser.read(7))),1) #read except: ##handle all serial read errors try: ser = serial.Serial('COM3',9600) # open serial port except: ser.close() ser = serial.Serial('COM3',9600) # open serial port temperaturefloat = 0 time.sleep(0.1) nowtimefloat = round(time.clock(),1) nowtimestring = str(nowtimefloat) temperaturesting = str(temperaturefloat) goblin = open('templog.txt','a') #open txt file datastring = temperaturesting + '\t' + nowtimestring + '\n' print(datastring) #print temp to console goblin.write(datastring) ## goblin.flush() ## ser.close() # close port else: print "Mash complete!" raw_input('Press Enter to save the data..') goblin.close() os.rename('templog.txt',beername + 'templog.txt') print 'Data saved!' raw_input('Press Enter to exit...') ## DATA ANALYSIS ##plt.axis([0,3600,55,75]) ###temperature lines ##plt.hlines(70,0,3600,colors='r') ##plt.hlines(60,0,3600,colors='r') ## ##dragon = np.loadtxt('templog.txt', delimiter="\t") ##x = dragon[:,1] ##y = dragon[:,0] ## ##plt.scatter(x,y) ####plt.draw() ##plt.show() ##plt.waitforbuttonpress() ####plt.pause(0.1) ## ##raw_input('Press Enter to exit...') ##
[ 2, 14, 14629, 14, 8800, 14, 29412, 201, 198, 11748, 11389, 220, 201, 198, 11748, 640, 201, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 28686, 201, 198, 201, ...
2.164238
2,265
from abc import ABC, abstractmethod from domain.errors.failure import Failure from domain.errors.image_failure import ImageFailure from domain.repositories.image_repository_abstraction import ImageRepositoryAbstraction
[ 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 198, 6738, 7386, 13, 48277, 13, 32165, 495, 1330, 25743, 198, 6738, 7386, 13, 48277, 13, 9060, 62, 32165, 495, 1330, 7412, 50015, 198, 6738, 7386, 13, 260, 1930, 270, 1749, 13, 9060, ...
3.762712
59
import pygame import math pygame.init() pi = ('Pi = ' + str(math.pi)) e = ('E = ' + str(math.e)) f = ('F = 0,1,1,2,3,5,8,13...') p = ('P = 1,2,5,12,29...') l = ('L = 2,1,3,4,7,11,18,29...') pl = ('P-L = 2,6,14,34,82...') display = pygame.display.set_mode((800,600)) pygame.display.set_caption('Nums') font = pygame.font.SysFont('None', 72) pitxt = font.render(pi, 0, (0,255,0)) etxt = font.render(e, 0, (0,255,0)) ftxt = font.render(f, 0, (0,255,0)) ptxt = font.render(p, 0, (0,255,0)) ltxt = font.render(l, 0, (0,255,0)) pltxt = font.render(pl, 0, (0,255,0)) run = True while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.display.update() display.blit(pitxt, (0,0)) display.blit(etxt, (0,40)) display.blit(ftxt, (0,80)) display.blit(ptxt, (0,120)) display.blit(ltxt, (0,160)) display.blit(pltxt, (0,200)) pygame.quit()
[ 11748, 12972, 6057, 201, 198, 11748, 10688, 201, 198, 9078, 6057, 13, 15003, 3419, 201, 198, 14415, 796, 19203, 38729, 796, 705, 1343, 965, 7, 11018, 13, 14415, 4008, 201, 198, 68, 796, 19203, 36, 796, 705, 1343, 965, 7, 11018, 13, ...
1.934426
488
import io import csv import logging from StringIO import StringIO from datetime import datetime from gzip import GzipFile import boto3 from celery import shared_task from flask import current_app from flask_mail import Attachment from invenio_mail.api import TemplatedMessage logger = logging.getLogger(__name__) def encode_element(element): """ Converts element to utf-8 string. None value will be converted to an empty string. """ if element is None: return "" if isinstance(element, basestring): return element.encode('utf-8') return element def to_csv(data): """ Serialize generated tool data to CSV. :param data: dictionary representing the data to be serialized. 'header' key has to contain a list of string, 'data' key has to contain a list of list of string. :return: (content_type, data) 2-tuple: corresponding MIME type as string and the serialized value as string. """ if not data or 'header' not in data or 'data' not in data: raise ValueError('Invalid parameter to be serialized.') result = StringIO() cw = csv.writer(result, delimiter=";", quoting=csv.QUOTE_ALL) cw.writerow(data['header']) for row in data['data']: cw.writerow([encode_element(element) for element in row]) return 'text/csv', result.getvalue() def send_result(result_data, content_type, recipients, tool_name): """ Sends the result via email to the user who requested it. :param result_data: generated data in a serialized form. :param content_type: MIME type of the attachment. :param recipients: recipients who will receive the email. :param tool_name: name of the tool, which will be used in the subject of the email. """ timestamp = datetime.now().strftime('%Y-%m-%dT%H:%M:%S') filename = 'scoap3_export_%s_%s.csv' % (tool_name, timestamp) # compress data if needed # try: # compress = current_app.config.get('TOOL_COMPRESS_ATTACHMENT', False) # if compress: # compressed_buffer = StringIO() # gzip_file = GzipFile(fileobj=compressed_buffer, mode="wt") # gzip_file.write(result_data) # gzip_file.close() # # result_data = compressed_buffer.getvalue() # content_type = 'application/gzip' # filename += '.gz' # except Exception as e: # logger.error('Error in csv compression: {}'.format(e.message)) # # attachment = Attachment(filename=filename, content_type=content_type, data=result_data) host = current_app.config.get('S3_HOSTNAME') bucket = current_app.config.get('S3_BUCKET') s3 = boto3.resource('s3', endpoint_url='http://s3.cern.ch/') s3.meta.client.upload_fileobj( io.BytesIO(result_data), bucket, filename, ExtraArgs={'ACL': 'public-read'} ) file_url = "{}/{}/{}".format(host, bucket, filename) msg = TemplatedMessage( template_html='scoap3_tools/email/result.html', ctx={'attachment_url': file_url}, subject='SCOAP3 - Export %s result' % tool_name, sender=current_app.config.get('MAIL_DEFAULT_SENDER'), recipients=recipients, # attachments=[attachment], ) current_app.extensions['mail'].send(msg) def send_failed_email(recipients, tool_name, task_id=None): """ Notifies the user about a failed generation. :param recipients: recipients who will receive the email. :param tool_name: name of the tool, which will be used in the subject of the email. :param task_id: celery task id, if available. """ msg = TemplatedMessage( template_html='scoap3_tools/email/failed.html', subject='SCOAP3 - Export %s result error' % tool_name, sender=current_app.config.get('MAIL_DEFAULT_SENDER'), recipients=recipients, ctx={'task_id': task_id} ) current_app.extensions['mail'].send(msg)
[ 11748, 33245, 198, 11748, 269, 21370, 198, 11748, 18931, 198, 6738, 10903, 9399, 1330, 10903, 9399, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 308, 13344, 1330, 402, 13344, 8979, 198, 198, 11748, 275, 2069, 18, 198, 6738, 18725, ...
2.61421
1,506
from system.db import db from telegram_bot.handlers.utils.decorators import remember_new_user, \ send_typing, write_logs from telegram_bot.handlers.utils.menu_entries import MenuEntry from telegram_bot.handlers.utils.reply_markup import create_main_reply_markup from telegram_bot.models import User
[ 6738, 1080, 13, 9945, 1330, 20613, 198, 6738, 573, 30536, 62, 13645, 13, 4993, 8116, 13, 26791, 13, 12501, 273, 2024, 1330, 3505, 62, 3605, 62, 7220, 11, 3467, 198, 220, 220, 220, 3758, 62, 774, 13886, 11, 3551, 62, 6404, 82, 198, ...
3.134021
97
# Generated by Django 3.2 on 2022-02-27 11:38 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 319, 33160, 12, 2999, 12, 1983, 1367, 25, 2548, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.966667
30
# -*- coding: utf-8-*- import os import base64 import tempfile import pypinyin from aip import AipSpeech from . import utils, config, constants from robot import logging from pathlib import Path from pypinyin import lazy_pinyin from pydub import AudioSegment from abc import ABCMeta, abstractmethod from .sdk import TencentSpeech, AliSpeech, XunfeiSpeech, atc logger = logging.getLogger(__name__) def get_engine_by_slug(slug=None): """ Returns: A TTS Engine implementation available on the current platform Raises: ValueError if no speaker implementation is supported on this platform """ if not slug or type(slug) is not str: raise TypeError(" TTS slug '%s'", slug) selected_engines = list(filter(lambda engine: hasattr(engine, "SLUG") and engine.SLUG == slug, get_engines())) if len(selected_engines) == 0: raise ValueError(" {} TTS ".format(slug)) else: if len(selected_engines) > 1: logger.warning(": TTS {} ").format(slug) engine = selected_engines[0] logger.info(" {} TTS ".format(engine.SLUG)) return engine.get_instance() def get_engines(): return [engine for engine in list(get_subclasses(AbstractTTS)) if hasattr(engine, 'SLUG') and engine.SLUG]
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 12, 9, 12, 198, 11748, 28686, 198, 11748, 2779, 2414, 198, 11748, 20218, 7753, 198, 11748, 279, 4464, 3541, 259, 198, 6738, 257, 541, 1330, 317, 541, 5248, 3055, 198, 6738, 764, 1330, 33...
2.487985
541
from channels.db import database_sync_to_async from .exceptions import ClientError from .models import Game
[ 6738, 9619, 13, 9945, 1330, 6831, 62, 27261, 62, 1462, 62, 292, 13361, 198, 6738, 764, 1069, 11755, 1330, 20985, 12331, 198, 6738, 764, 27530, 1330, 3776 ]
3.962963
27
import os import pytest from ddb.__main__ import load_registered_features from ddb.config import config from ddb.feature import features from ddb.feature.core import CoreFeature from ddb.utils import file from ddb.utils.file import FileWalker, FileUtils
[ 11748, 28686, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 288, 9945, 13, 834, 12417, 834, 1330, 3440, 62, 33736, 62, 40890, 198, 6738, 288, 9945, 13, 11250, 1330, 4566, 198, 6738, 288, 9945, 13, 30053, 1330, 3033, 198, 6738, 288, 99...
3.5
74
# Copyright (C) 2021, Pyronear contributors. # This program is licensed under the GNU Affero General Public License version 3. # See LICENSE or go to <https://www.gnu.org/licenses/agpl-3.0.txt> for full license details. import unittest import tempfile from pathlib import Path import json from PIL.Image import Image import pandas as pd import random import requests import torch from torch.utils.data import DataLoader from torchvision.transforms import transforms from torchvision.datasets import VisionDataset from pyrodataset.wildfire import WildFireDataset, WildFireSplitter, computeSubSet if __name__ == '__main__': unittest.main()
[ 2, 15069, 357, 34, 8, 33448, 11, 9485, 1313, 451, 20420, 13, 198, 198, 2, 770, 1430, 318, 11971, 739, 262, 22961, 6708, 3529, 3611, 5094, 13789, 2196, 513, 13, 198, 2, 4091, 38559, 24290, 393, 467, 284, 1279, 5450, 1378, 2503, 13, ...
3.418848
191
# -*- coding: utf-8 -*- # # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # # pylint: disable= no-member, arguments-differ, invalid-name # # Utilities for using pre-trained models. import torch from dgl.data.utils import _get_dgl_url, download from .moleculenet import * from .generative_models import * from .property_prediction import * from .reaction import * __all__ = ['load_pretrained'] url = {**moleculenet_url, **generative_url, **property_url, **reaction_url} def download_and_load_checkpoint(model_name, model, model_postfix, local_pretrained_path='pre_trained.pth', log=True): """Download pretrained model checkpoint The model will be loaded to CPU. Parameters ---------- model_name : str Name of the model model : nn.Module Instantiated model instance model_postfix : str Postfix for pretrained model checkpoint local_pretrained_path : str Local name for the downloaded model checkpoint log : bool Whether to print progress for model loading Returns ------- model : nn.Module Pretrained model """ url_to_pretrained = _get_dgl_url(model_postfix) local_pretrained_path = '_'.join([model_name, local_pretrained_path]) download(url_to_pretrained, path=local_pretrained_path, log=log) checkpoint = torch.load(local_pretrained_path, map_location='cpu') model.load_state_dict(checkpoint['model_state_dict']) if log: print('Pretrained model loaded') return model # pylint: disable=I1101 def load_pretrained(model_name, log=True): """Load a pretrained model Parameters ---------- model_name : str Currently supported options include * ``'GCN_Tox21'``: A GCN-based model for molecular property prediction on Tox21 * ``'GAT_Tox21'``: A GAT-based model for molecular property prediction on Tox21 * ``'Weave_Tox21'``: A Weave model for molecular property prediction on Tox21 * ``'AttentiveFP_Aromaticity'``: An AttentiveFP model for predicting number of aromatic atoms on a subset of Pubmed * ``'DGMG_ChEMBL_canonical'``: A DGMG model trained on ChEMBL with a canonical atom order * ``'DGMG_ChEMBL_random'``: A DGMG model trained on ChEMBL for molecule generation with a random atom order * ``'DGMG_ZINC_canonical'``: A DGMG model trained on ZINC for molecule generation with a canonical atom order * ``'DGMG_ZINC_random'``: A DGMG model pre-trained on ZINC for molecule generation with a random atom order * ``'JTNN_ZINC'``: A JTNN model pre-trained on ZINC for molecule generation * ``'wln_center_uspto'``: A WLN model pre-trained on USPTO for reaction prediction * ``'wln_rank_uspto'``: A WLN model pre-trained on USPTO for candidate product ranking * ``'gin_supervised_contextpred'``: A GIN model pre-trained with supervised learning and context prediction * ``'gin_supervised_infomax'``: A GIN model pre-trained with supervised learning and deep graph infomax * ``'gin_supervised_edgepred'``: A GIN model pre-trained with supervised learning and edge prediction * ``'gin_supervised_masking'``: A GIN model pre-trained with supervised learning and attribute masking * ``'GCN_canonical_BACE'``: A GCN model trained on BACE with canonical featurization for atoms * ``'GCN_attentivefp_BACE'``: A GCN model trained on BACE with attentivefp featurization for atoms * ``'GAT_canonical_BACE'``: A GAT model trained on BACE with canonical featurization for atoms * ``'GAT_attentivefp_BACE'``: A GAT model trained on BACE with attentivefp featurization for atoms * ``'Weave_canonical_BACE'``: A Weave model trained on BACE with canonical featurization for atoms and bonds * ``'Weave_attentivefp_BACE'``: A Weave model trained on BACE with attentivefp featurization for atoms and bonds * ``'MPNN_canonical_BACE'``: An MPNN model trained on BACE with canonical featurization for atoms and bonds * ``'MPNN_attentivefp_BACE'``: An MPNN model trained on BACE with attentivefp featurization for atoms and bonds * ``'AttentiveFP_canonical_BACE'``: An AttentiveFP model trained on BACE with canonical featurization for atoms and bonds * ``'AttentiveFP_attentivefp_BACE'``: An AttentiveFP model trained on BACE with attentivefp featurization for atoms and bonds * ``'gin_supervised_contextpred_BACE'``: A GIN model pre-trained with supervised learning and context prediction, and fine-tuned on BACE * ``'gin_supervised_infomax_BACE'``: A GIN model pre-trained with supervised learning and infomax, and fine-tuned on BACE * ``'gin_supervised_edgepred_BACE'``: A GIN model pre-trained with supervised learning and edge prediction, and fine-tuned on BACE * ``'gin_supervised_masking_BACE'``: A GIN model pre-trained with supervised learning and masking, and fine-tuned on BACE * ``'NF_canonical_BACE'``: An NF model trained on BACE with canonical featurization for atoms * ``'GCN_canonical_BBBP'``: A GCN model trained on BBBP with canonical featurization for atoms * ``'GCN_attentivefp_BBBP'``: A GCN model trained on BBBP with attentivefp featurization for atoms * ``'GAT_canonical_BBBP'``: A GAT model trained on BBBP with canonical featurization for atoms * ``'GAT_attentivefp_BBBP'``: A GAT model trained on BBBP with attentivefp featurization for atoms * ``'Weave_canonical_BBBP'``: A Weave model trained on BBBP with canonical featurization for atoms and bonds * ``'Weave_attentivefp_BBBP'``: A Weave model trained on BBBP with attentivefp featurization for atoms and bonds * ``'MPNN_canonical_BBBP'``: An MPNN model trained on BBBP with canonical featurization for atoms and bonds * ``'MPNN_attentivefp_BBBP'``: An MPNN model trained on BBBP with attentivefp featurization for atoms and bonds * ``'AttentiveFP_canonical_BBBP'``: An AttentiveFP model trained on BBBP with canonical featurization for atoms and bonds * ``'AttentiveFP_attentivefp_BBBP'``: An AttentiveFP model trained on BBBP with attentivefp featurization for atoms and bonds * ``'gin_supervised_contextpred_BBBP'``: A GIN model pre-trained with supervised learning and context prediction, and fine-tuned on BBBP * ``'gin_supervised_infomax_BBBP'``: A GIN model pre-trained with supervised learning and infomax, and fine-tuned on BBBP * ``'gin_supervised_edgepred_BBBP'``: A GIN model pre-trained with supervised learning and edge prediction, and fine-tuned on BBBP * ``'gin_supervised_masking_BBBP'``: A GIN model pre-trained with supervised learning and masking, and fine-tuned on BBBP * ``'NF_canonical_BBBP'``: An NF model pre-trained on BBBP with canonical featurization for atoms * ``'GCN_canonical_ClinTox'``: A GCN model trained on ClinTox with canonical featurization for atoms * ``'GCN_attentivefp_ClinTox'``: A GCN model trained on ClinTox with attentivefp featurization for atoms * ``'GAT_canonical_ClinTox'``: A GAT model trained on ClinTox with canonical featurization for atoms * ``'GAT_attentivefp_ClinTox'``: A GAT model trained on ClinTox with attentivefp featurization for atoms * ``'Weave_canonical_ClinTox'``: A Weave model trained on ClinTox with canonical featurization for atoms and bonds * ``'Weave_attentivefp_ClinTox'``: A Weave model trained on ClinTox with attentivefp featurization for atoms and bonds * ``'MPNN_canonical_ClinTox'``: An MPNN model trained on ClinTox with canonical featurization for atoms and bonds * ``'MPNN_attentivefp_ClinTox'``: An MPNN model trained on ClinTox with attentivefp featurization for atoms and bonds * ``'AttentiveFP_canonical_ClinTox'``: An AttentiveFP model trained on ClinTox with canonical featurization for atoms and bonds * ``'AttentiveFP_attentivefp_BACE'``: An AttentiveFP model trained on ClinTox with attentivefp featurization for atoms and bonds * ``'GCN_canonical_ESOL'``: A GCN model trained on ESOL with canonical featurization for atoms * ``'GCN_attentivefp_ESOL'``: A GCN model trained on ESOL with attentivefp featurization for atoms * ``'GAT_canonical_ESOL'``: A GAT model trained on ESOL with canonical featurization for atoms * ``'GAT_attentivefp_ESOL'``: A GAT model trained on ESOL with attentivefp featurization for atoms * ``'Weave_canonical_ESOL'``: A Weave model trained on ESOL with canonical featurization for atoms and bonds * ``'Weave_attentivefp_ESOL'``: A Weave model trained on ESOL with attentivefp featurization for atoms and bonds * ``'MPNN_canonical_ESOL'``: An MPNN model trained on ESOL with canonical featurization for atoms and bonds * ``'MPNN_attentivefp_ESOL'``: An MPNN model trained on ESOL with attentivefp featurization for atoms and bonds * ``'AttentiveFP_canonical_ESOL'``: An AttentiveFP model trained on ESOL with canonical featurization for atoms and bonds * ``'AttentiveFP_attentivefp_ESOL'``: An AttentiveFP model trained on ESOL with attentivefp featurization for atoms and bonds * ``'gin_supervised_contextpred_ESOL'``: A GIN model pre-trained with supervised learning and context prediction, and fine-tuned on ESOL * ``'gin_supervised_infomax_ESOL'``: A GIN model pre-trained with supervised learning and infomax, and fine-tuned on ESOL * ``'gin_supervised_edgepred_ESOL'``: A GIN model pre-trained with supervised learning and edge prediction, and fine-tuned on ESOL * ``'gin_supervised_masking_ESOL'``: A GIN model pre-trained with supervised learning and masking, and fine-tuned on ESOL * ``'GCN_canonical_FreeSolv'``: A GCN model trained on FreeSolv with canonical featurization for atoms * ``'GCN_attentivefp_FreeSolv'``: A GCN model trained on FreeSolv with attentivefp featurization for atoms * ``'GAT_canonical_FreeSolv'``: A GAT model trained on FreeSolv with canonical featurization for atoms * ``'GAT_attentivefp_FreeSolv'``: A GAT model trained on FreeSolv with attentivefp featurization for atoms * ``'Weave_canonical_FreeSolv'``: A Weave model trained on FreeSolv with canonical featurization for atoms and bonds * ``'Weave_attentivefp_FreeSolv'``: A Weave model trained on FreeSolv with attentivefp featurization for atoms and bonds * ``'MPNN_canonical_FreeSolv'``: An MPNN model trained on FreeSolv with canonical featurization for atoms and bonds * ``'MPNN_attentivefp_FreeSolv'``: An MPNN model trained on FreeSolv with attentivefp featurization for atoms and bonds * ``'AttentiveFP_canonical_FreeSolv'``: An AttentiveFP model trained on FreeSolv with canonical featurization for atoms and bonds * ``'AttentiveFP_attentivefp_FreeSolv'``: An AttentiveFP model trained on FreeSolv with attentivefp featurization for atoms and bonds * ``'gin_supervised_contextpred_FreeSolv'``: A GIN model pre-trained with supervised learning and context prediction, and fine-tuned on FreeSolv * ``'gin_supervised_infomax_FreeSolv'``: A GIN model pre-trained with supervised learning and infomax, and fine-tuned on FreeSolv * ``'gin_supervised_edgepred_FreeSolv'``: A GIN model pre-trained with supervised learning and edge prediction, and fine-tuned on FreeSolv * ``'gin_supervised_masking_FreeSolv'``: A GIN model pre-trained with supervised learning and masking, and fine-tuned on FreeSolv * ``'GCN_canonical_HIV'``: A GCN model trained on HIV with canonical featurization for atoms * ``'GCN_attentivefp_HIV'``: A GCN model trained on HIV with attentivefp featurization for atoms * ``'GAT_canonical_HIV'``: A GAT model trained on BACE with canonical featurization for atoms * ``'GAT_attentivefp_HIV'``: A GAT model trained on BACE with attentivefp featurization for atoms * ``'Weave_canonical_HIV'``: A Weave model trained on HIV with canonical featurization for atoms and bonds * ``'Weave_attentivefp_HIV'``: A Weave model trained on HIV with attentivefp featurization for atoms and bonds * ``'MPNN_canonical_HIV'``: An MPNN model trained on HIV with canonical featurization for atoms and bonds * ``'MPNN_attentivefp_HIV'``: An MPNN model trained on HIV with attentivefp featurization for atoms and bonds * ``'AttentiveFP_canonical_HIV'``: An AttentiveFP model trained on HIV with canonical featurization for atoms and bonds * ``'AttentiveFP_attentivefp_HIV'``: An AttentiveFP model trained on HIV with attentivefp featurization for atoms and bonds * ``'gin_supervised_contextpred_HIV'``: A GIN model pre-trained with supervised learning and context prediction, and fine-tuned on HIV * ``'gin_supervised_infomax_HIV'``: A GIN model pre-trained with supervised learning and infomax, and fine-tuned on HIV * ``'gin_supervised_edgepred_HIV'``: A GIN model pre-trained with supervised learning and edge prediction, and fine-tuned on HIV * ``'gin_supervised_masking_HIV'``: A GIN model pre-trained with supervised learning and masking, and fine-tuned on HIV * ``'NF_canonical_HIV'``: An NF model trained on HIV with canonical featurization for atoms * ``'GCN_canonical_Lipophilicity'``: A GCN model trained on Lipophilicity with canonical featurization for atoms * ``'GCN_attentivefp_Lipophilicity'``: A GCN model trained on Lipophilicity with attentivefp featurization for atoms * ``'GAT_canonical_Lipophilicity'``: A GAT model trained on Lipophilicity with canonical featurization for atoms * ``'GAT_attentivefp_Lipophilicity'``: A GAT model trained on Lipophilicity with attentivefp featurization for atoms * ``'Weave_canonical_Lipophilicity'``: A Weave model trained on Lipophilicity with canonical featurization for atoms and bonds * ``'Weave_attentivefp_Lipophilicity'``: A Weave model trained on Lipophilicity with attentivefp featurization for atoms and bonds * ``'MPNN_canonical_Lipophilicity'``: An MPNN model trained on Lipophilicity with canonical featurization for atoms and bonds * ``'MPNN_attentivefp_Lipophilicity'``: An MPNN model trained on Lipophilicity with attentivefp featurization for atoms and bonds * ``'AttentiveFP_canonical_Lipophilicity'``: An AttentiveFP model trained on Lipophilicity with canonical featurization for atoms and bonds * ``'AttentiveFP_attentivefp_Lipophilicity'``: An AttentiveFP model trained on Lipophilicity with attentivefp featurization for atoms and bonds * ``'gin_supervised_contextpred_Lipophilicity'``: A GIN model pre-trained with supervised learning and context prediction, and fine-tuned on Lipophilicity * ``'gin_supervised_infomax_Lipophilicity'``: A GIN model pre-trained with supervised learning and infomax, and fine-tuned on Lipophilicity * ``'gin_supervised_edgepred_Lipophilicity'``: A GIN model pre-trained with supervised learning and edge prediction, and fine-tuned on Lipophilicity * ``'gin_supervised_masking_Lipophilicity'``: A GIN model pre-trained with supervised learning and masking, and fine-tuned on Lipophilicity * ``'GCN_canonical_MUV'``: A GCN model trained on MUV with canonical featurization for atoms * ``'GCN_attentivefp_MUV'``: A GCN model trained on MUV with attentivefp featurization for atoms * ``'GAT_canonical_MUV'``: A GAT model trained on MUV with canonical featurization for atoms * ``'GAT_attentivefp_MUV'``: A GAT model trained on MUV with attentivefp featurization for atoms * ``'Weave_canonical_MUV'``: A Weave model trained on MUV with canonical featurization for atoms and bonds * ``'Weave_attentivefp_MUV'``: A Weave model trained on MUV with attentivefp featurization for atoms and bonds * ``'MPNN_canonical_MUV'``: An MPNN model trained on MUV with canonical featurization for atoms and bonds * ``'MPNN_attentivefp_MUV'``: An MPNN model trained on MUV with attentivefp featurization for atoms and bonds * ``'AttentiveFP_canonical_MUV'``: An AttentiveFP model trained on MUV with canonical featurization for atoms and bonds * ``'AttentiveFP_attentivefp_MUV'``: An AttentiveFP model trained on MUV with attentivefp featurization for atoms and bonds * ``'gin_supervised_contextpred_MUV'``: A GIN model pre-trained with supervised learning and context prediction, and fine-tuned on MUV * ``'gin_supervised_infomax_MUV'``: A GIN model pre-trained with supervised learning and infomax, and fine-tuned on MUV * ``'gin_supervised_edgepred_MUV'``: A GIN model pre-trained with supervised learning and edge prediction, and fine-tuned on MUV * ``'gin_supervised_masking_MUV'``: A GIN model pre-trained with supervised learning and masking, and fine-tuned on MUV * ``'GCN_canonical_PCBA'``: A GCN model trained on PCBA with canonical featurization for atoms * ``'GCN_attentivefp_PCBA'``: A GCN model trained on PCBA with attentivefp featurization for atoms * ``'GAT_canonical_PCBA'``: A GAT model trained on PCBA with canonical featurization for atoms * ``'GAT_attentivefp_PCBA'``: A GAT model trained on PCBA with attentivefp featurization for atoms * ``'Weave_canonical_PCBA'``: A Weave model trained on PCBA with canonical featurization for atoms and bonds * ``'Weave_attentivefp_PCBA'``: A Weave model trained on PCBA with attentivefp featurization for atoms and bonds * ``'MPNN_canonical_PCBA'``: An MPNN model trained on PCBA with canonical featurization for atoms and bonds * ``'MPNN_attentivefp_PCBA'``: An MPNN model trained on PCBA with attentivefp featurization for atoms and bonds * ``'AttentiveFP_canonical_PCBA'``: An AttentiveFP model trained on PCBA with canonical featurization for atoms and bonds * ``'AttentiveFP_attentivefp_PCBA'``: An AttentiveFP model trained on PCBA with attentivefp featurization for atoms and bonds * ``'GCN_canonical_SIDER'``: A GCN model trained on SIDER with canonical featurization for atoms * ``'GCN_attentivefp_SIDER'``: A GCN model trained on SIDER with attentivefp featurization for atoms * ``'GAT_canonical_SIDER'``: A GAT model trained on SIDER with canonical featurization for atoms * ``'GAT_attentivefp_SIDER'``: A GAT model trained on SIDER with attentivefp featurization for atoms * ``'Weave_canonical_SIDER'``: A Weave model trained on SIDER with canonical featurization for atoms and bonds * ``'Weave_attentivefp_SIDER'``: A Weave model trained on SIDER with attentivefp featurization for atoms and bonds * ``'MPNN_canonical_SIDER'``: An MPNN model trained on SIDER with canonical featurization for atoms and bonds * ``'MPNN_attentivefp_SIDER'``: An MPNN model trained on SIDER with attentivefp featurization for atoms and bonds * ``'AttentiveFP_canonical_SIDER'``: An AttentiveFP model trained on SIDER with canonical featurization for atoms and bonds * ``'AttentiveFP_attentivefp_SIDER'``: An AttentiveFP model trained on SIDER with attentivefp featurization for atoms and bonds * ``'gin_supervised_contextpred_SIDER'``: A GIN model pre-trained with supervised learning and context prediction, and fine-tuned on SIDER * ``'gin_supervised_infomax_SIDER'``: A GIN model pre-trained with supervised learning and infomax, and fine-tuned on SIDER * ``'gin_supervised_edgepred_SIDER'``: A GIN model pre-trained with supervised learning and edge prediction, and fine-tuned on SIDER * ``'gin_supervised_masking_SIDER'``: A GIN model pre-trained with supervised learning and masking, and fine-tuned on SIDER * ``'NF_canonical_SIDER'``: An NF model trained on SIDER with canonical featurization for atoms * ``'GCN_canonical_Tox21'``: A GCN model trained on Tox21 with canonical featurization for atoms * ``'GCN_attentivefp_Tox21'``: A GCN model trained on Tox21 with attentivefp featurization for atoms * ``'GAT_canonical_Tox21'``: A GAT model trained on Tox21 with canonical featurization for atoms * ``'GAT_attentivefp_Tox21'``: A GAT model trained on Tox21 with attentivefp featurization for atoms * ``'Weave_canonical_Tox21'``: A Weave model trained on Tox21 with canonical featurization for atoms and bonds * ``'Weave_attentivefp_Tox21'``: A Weave model trained on Tox21 with attentivefp featurization for atoms and bonds * ``'MPNN_canonical_Tox21'``: An MPNN model trained on Tox21 with canonical featurization for atoms and bonds * ``'MPNN_attentivefp_Tox21'``: An MPNN model trained on Tox21 with attentivefp featurization for atoms and bonds * ``'AttentiveFP_canonical_Tox21'``: An AttentiveFP model trained on Tox21 with canonical featurization for atoms and bonds * ``'AttentiveFP_attentivefp_Tox21'``: An AttentiveFP model trained on Tox21 with attentivefp featurization for atoms and bonds * ``'gin_supervised_contextpred_Tox21'``: A GIN model pre-trained with supervised learning and context prediction, and fine-tuned on Tox21 * ``'gin_supervised_infomax_Tox21'``: A GIN model pre-trained with supervised learning and infomax, and fine-tuned on Tox21 * ``'gin_supervised_edgepred_Tox21'``: A GIN model pre-trained with supervised learning and edge prediction, and fine-tuned on Tox21 * ``'gin_supervised_masking_Tox21'``: A GIN model pre-trained with supervised learning and masking, and fine-tuned on Tox21 * ``'NF_canonical_Tox21'``: An NF model trained on Tox21 with canonical featurization for atoms * ``'GCN_canonical_ToxCast'``: A GCN model trained on ToxCast with canonical featurization for atoms * ``'GCN_attentivefp_ToxCast'``: A GCN model trained on ToxCast with attentivefp featurization for atoms * ``'GAT_canonical_ToxCast'``: A GAT model trained on ToxCast with canonical featurization for atoms * ``'GAT_attentivefp_ToxCast'``: A GAT model trained on ToxCast with attentivefp featurization for atoms * ``'Weave_canonical_ToxCast'``: A Weave model trained on ToxCast with canonical featurization for atoms and bonds * ``'Weave_attentivefp_ToxCast'``: A Weave model trained on ToxCast with attentivefp featurization for atoms and bonds * ``'MPNN_canonical_ToxCast'``: An MPNN model trained on ToxCast with canonical featurization for atoms and bonds * ``'MPNN_attentivefp_ToxCast'``: An MPNN model trained on ToxCast with attentivefp featurization for atoms and bonds * ``'AttentiveFP_canonical_ToxCast'``: An AttentiveFP model trained on ToxCast with canonical featurization for atoms and bonds * ``'AttentiveFP_attentivefp_ToxCast'``: An AttentiveFP model trained on ToxCast with attentivefp featurization for atoms and bonds * ``'gin_supervised_contextpred_ToxCast'``: A GIN model pre-trained with supervised learning and context prediction, and fine-tuned on ToxCast * ``'gin_supervised_infomax_ToxCast'``: A GIN model pre-trained with supervised learning and infomax, and fine-tuned on ToxCast * ``'gin_supervised_edgepred_ToxCast'``: A GIN model pre-trained with supervised learning and edge prediction, and fine-tuned on ToxCast * ``'gin_supervised_masking_ToxCast'``: A GIN model pre-trained with supervised learning and masking, and fine-tuned on ToxCast * ``'NF_canonical_ToxCast'``: An NF model trained on ToxCast with canonical featurization for atoms and bonds log : bool Whether to print progress for model loading Returns ------- model """ if model_name not in url: raise RuntimeError("Cannot find a pretrained model with name {}".format(model_name)) for func in [create_moleculenet_model, create_generative_model, create_property_model, create_reaction_model]: model = func(model_name) if model is not None: break return download_and_load_checkpoint(model_name, model, url[model_name], log=log)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 6186, 13, 785, 11, 3457, 13, 393, 663, 29116, 13, 1439, 6923, 33876, 13, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15...
2.539479
10,284
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import numpy as np import pyrobot.utils.util as prutil from pyrobot.core import Camera from pyrobot.utils.util import try_cv2_import cv2 = try_cv2_import() from cv_bridge import CvBridge, CvBridgeError from pyrep.objects.vision_sensor import VisionSensor from pyrep.const import ObjectType, PerspectiveMode, RenderMode from pyrep.objects.joint import Joint
[ 2, 15069, 357, 66, 8, 3203, 11, 3457, 13, 290, 663, 29116, 13, 198, 198, 2, 770, 2723, 2438, 318, 11971, 739, 262, 17168, 5964, 1043, 287, 262, 198, 2, 38559, 24290, 2393, 287, 262, 6808, 8619, 286, 428, 2723, 5509, 13, 198, 198, ...
3.43949
157
import serial ser = serial.Serial('COM7',115200, timeout=1) while True: print("R: ", ser.readline())
[ 11748, 11389, 198, 198, 2655, 796, 11389, 13, 32634, 10786, 9858, 22, 3256, 15363, 2167, 11, 26827, 28, 16, 8, 198, 4514, 6407, 25, 198, 220, 220, 220, 3601, 7203, 49, 25, 33172, 1055, 13, 961, 1370, 28955 ]
2.763158
38
import sys import random import avro.schema from avro.datafile import DataFileWriter from avro.io import DatumWriter NAME_POOL = ['george', 'john', 'paul', 'ringo'] OFFICE_POOL = ['office-%d' % _ for _ in xrange(4)] COLOR_POOL = ['black', 'cyan', 'magenta', 'yellow'] if __name__ == '__main__': main(sys.argv)
[ 11748, 25064, 198, 11748, 4738, 198, 198, 11748, 1196, 305, 13, 15952, 2611, 198, 6738, 1196, 305, 13, 7890, 7753, 1330, 6060, 8979, 34379, 198, 6738, 1196, 305, 13, 952, 1330, 16092, 388, 34379, 198, 198, 20608, 62, 16402, 3535, 796, ...
2.572581
124
import numpy as np import unittest from chainer.dataset import DatasetMixin from chainer import testing from chainercv.utils import assert_is_bbox_dataset from chainercv.utils import generate_random_bbox testing.run_module(__name__, __file__)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 555, 715, 395, 198, 198, 6738, 6333, 263, 13, 19608, 292, 316, 1330, 16092, 292, 316, 35608, 259, 198, 6738, 6333, 263, 1330, 4856, 198, 198, 6738, 6333, 2798, 85, 13, 26791, 1330, 6818, 62, ...
2.988235
85
# Copyright (c) 2012-2016 Seafile Ltd. from __future__ import unicode_literals import unicodedata import urlparse import json from functools import wraps from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden JSON_CONTENT_TYPE = 'application/json; charset=utf-8' def is_safe_url(url, host=None): """ https://github.com/django/django/blob/fc6d147a63f89795dbcdecb0559256470fff4380/django/utils/http.py Return ``True`` if the url is a safe redirection (i.e. it doesn't point to a different host and uses a safe scheme). Always returns ``False`` on an empty url. """ if url is not None: url = url.strip() if not url: return False # Chrome treats \ completely as / in paths but it could be part of some # basic auth credentials so we need to check both URLs. return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host)
[ 2, 15069, 357, 66, 8, 2321, 12, 5304, 49967, 576, 12052, 13, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 11748, 28000, 9043, 1045, 198, 11748, 19016, 29572, 198, 11748, 33918, 198, 198, 6738, 1257, 310, ...
2.831804
327
"""Provide default settgins""" from pathlib import Path BIOPIPEN_DIR = Path(__file__).parent.parent.resolve() REPORT_DIR = BIOPIPEN_DIR / "reports" SCRIPT_DIR = BIOPIPEN_DIR / "scripts"
[ 37811, 15946, 485, 4277, 2970, 29878, 37811, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 3483, 3185, 4061, 1677, 62, 34720, 796, 10644, 7, 834, 7753, 834, 737, 8000, 13, 8000, 13, 411, 6442, 3419, 198, 2200, 15490, 62, 34720, 796, 2...
2.75
68
from flask_settings import GEOTIFF_FULL_PATH import sys import traceback sys.path.append('../') import numpy as np import json from datetime import timedelta from functools import update_wrapper from pextant.EnvironmentalModel import GDALMesh from pextant.explorers import Astronaut from pextant.analysis.loadWaypoints import JSONloader from pextant.lib.geoshapely import GeoPolygon, LAT_LONG from pextant.solvers.astarMesh import astarSolver from flask import Flask from flask import make_response, request, current_app app = Flask(__name__) # if __name__ == "__main__": main(sys.argv[1:]) #main(['../data/maps/dem/HI_air_imagery.tif'])
[ 6738, 42903, 62, 33692, 1330, 22319, 2394, 29267, 62, 37, 9994, 62, 34219, 198, 11748, 25064, 198, 11748, 12854, 1891, 198, 17597, 13, 6978, 13, 33295, 10786, 40720, 11537, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 33918, 198, 6738,...
3.131707
205
#!/usr/bin/python3 import shutil import os import base64 from time import sleep import flask import requests.exceptions import blueprint from flask_cors import CORS from confhttpproxy import ProxyRouter, ProxyRouterException from flask import Flask, jsonify import rest_routes from lmsrvcore.utilities.migrate import migrate_work_dir_structure_v2 from gtmcore.dispatcher import Dispatcher from gtmcore.dispatcher.jobs import update_environment_repositories from gtmcore.configuration import Configuration from gtmcore.logging import LMLogger from gtmcore.auth.identity import AuthenticationError, get_identity_manager_class from gtmcore.labbook.lock import reset_all_locks logger = LMLogger.get_logger() def configure_chp(proxy_dict: dict, is_hub_client: bool) -> str: """Set up the configurable HTTP proxy (CHP) Args: proxy_dict: obtained from the config dict inside the config instance is_hub_client: are we running on the hub? (also obtained from config instance) Returns: the final api_prefix used by the router We define this as a function mostly so we can optionally wrap it in a try block below """ # /api by default api_prefix = proxy_dict["labmanager_api_prefix"] proxy_router = ProxyRouter.get_proxy(proxy_dict) # Wait up to 10 seconds for the CHP to be available for _ in range(20): try: # This property raises an exception if the underlying request doesn't yield a status code of 200 proxy_router.routes # noqa except (requests.exceptions.ConnectionError, ProxyRouterException): sleep(0.5) continue # If there was no exception, the CHP is up and responding break else: # We exhausted our for-loop logger.error("Could not reach router after 20 tries (10 seconds), proxy_router.add() will likely fail") if is_hub_client: # Use full route prefix, including run/<client_id> if running in the Hub api_target = f"run/{os.environ['GIGANTUM_CLIENT_ID']}{api_prefix}" api_prefix = f"/{api_target}" # explicit routes for UI with full route prefix proxy_router.add("http://localhost:10002", f"run/{os.environ['GIGANTUM_CLIENT_ID']}") else: api_target = "api" proxy_router.add("http://localhost:10001", api_target) logger.info(f"Proxy routes ({type(proxy_router)}): {proxy_router.routes}") return api_prefix def configure_default_server(config_instance: Configuration) -> None: """Function to check if a server has been configured, and if not, configure and select the default server""" try: # Load the server configuration. If you get a FileNotFoundError there is no configured server config_instance.get_server_configuration() except FileNotFoundError: default_server = config_instance.config['core']['default_server'] logger.info(f"Configuring Client with default server via auto-discovery: {default_server}") try: server_id = config_instance.add_server(default_server) config_instance.set_current_server(server_id) # Migrate any user dirs if needed. Here we assume all projects belong to the default server, since # at the time it was the only available server. migrate_work_dir_structure_v2(server_id) except Exception as err: logger.exception(f"Failed to configure default server! Restart Client to try again: {err}") # Re-raise the exception so the API doesn't come up raise # Start Flask Server Initialization and app configuration app = Flask("lmsrvlabbook") random_bytes = os.urandom(32) app.config["SECRET_KEY"] = base64.b64encode(random_bytes).decode('utf-8') app.config["LABMGR_CONFIG"] = config = Configuration(wait_for_cache=10) configure_default_server(config) app.config["ID_MGR_CLS"] = get_identity_manager_class(config) # Set Debug mode app.config['DEBUG'] = config.config["flask"]["DEBUG"] app.register_blueprint(blueprint.complete_labbook_service) # Set starting flags # If flask is run in debug mode the service will restart when code is changed, and some tasks # we only want to happen once (ON_FIRST_START) # The WERKZEUG_RUN_MAIN environmental variable is set only when running under debugging mode ON_FIRST_START = app.config['DEBUG'] is False or os.environ.get('WERKZEUG_RUN_MAIN') != 'true' ON_RESTART = os.environ.get('WERKZEUG_RUN_MAIN') == 'true' if os.environ.get('CIRCLECI') == 'true': try: url_prefix = configure_chp(config.config['proxy'], config.is_hub_client) except requests.exceptions.ConnectionError: url_prefix = config.config['proxy']["labmanager_api_prefix"] else: url_prefix = configure_chp(config.config['proxy'], config.is_hub_client) # Add rest routes app.register_blueprint(rest_routes.rest_routes, url_prefix=url_prefix) if config.config["flask"]["allow_cors"]: # Allow CORS CORS(app, max_age=7200) if ON_FIRST_START: # Empty container-container share dir as it is ephemeral share_dir = os.path.join(os.path.sep, 'mnt', 'share') logger.info("Emptying container-container share folder: {}.".format(share_dir)) try: for item in os.listdir(share_dir): item_path = os.path.join(share_dir, item) if os.path.isfile(item_path): os.unlink(item_path) else: shutil.rmtree(item_path) except Exception as e: logger.error(f"Failed to empty share folder: {e}.") raise post_save_hook_code = """ import subprocess, os def post_save_hook(os_path, model, contents_manager, **kwargs): try: client_ip = os.environ.get('GIGANTUM_CLIENT_IP') if os.environ.get('HUB_CLIENT_ID'): # Running in the Hub service_route = "run/{}/api/savehook".format(os.environ.get('HUB_CLIENT_ID')) else: # Running locally service_route = "api/savehook" tokens = open('/home/giguser/jupyter_token').read().strip() username, owner, lbname, jupyter_token = tokens.split(',') url_args = "file={}&jupyter_token={}&email={}".format(os.path.basename(os_path), jupyter_token, os.environ['GIGANTUM_EMAIL']) url = "http://{}:10001/{}/{}/{}/{}?{}".format(client_ip,service_route,username,owner,lbname,url_args) subprocess.run(['wget', '--spider', url], cwd='/tmp') except Exception as e: print(e) """ os.makedirs(os.path.join(share_dir, 'jupyterhooks')) with open(os.path.join(share_dir, 'jupyterhooks', '__init__.py'), 'w') as initpy: initpy.write(post_save_hook_code) # Reset distributed lock, if desired if config.config["lock"]["reset_on_start"]: logger.info("Resetting ALL distributed locks") reset_all_locks(config.config['lock']) # Create local data (for local dataset types) dir if it doesn't exist local_data_dir = os.path.join(config.config['git']['working_directory'], 'local_data') if os.path.isdir(local_data_dir) is False: os.makedirs(local_data_dir, exist_ok=True) logger.info(f'Created `local_data` dir for Local Filesystem Dataset Type: {local_data_dir}') # Create certificates file directory for custom CA certificate support. certificate_dir = os.path.join(config.config['git']['working_directory'], 'certificates', 'ssl') if os.path.isdir(certificate_dir) is False: os.makedirs(certificate_dir, exist_ok=True) logger.info(f'Created `certificates` dir for SSL and custom CA certificates: {certificate_dir}') # make sure temporary upload directory exists and is empty tempdir = config.upload_dir if os.path.exists(tempdir): shutil.rmtree(tempdir) logger.info(f'Cleared upload temp dir: {tempdir}') os.makedirs(tempdir) # Start background startup tasks d = Dispatcher() # Make sure the queue is up before we start using RQ for _ in range(20): if d.ready_for_job(update_environment_repositories): break sleep(0.5) else: # We exhausted our for-loop err_message = "Worker queue not ready after 20 tries (10 seconds) - fatal error" logger.error(err_message) raise RuntimeError(err_message) # Run job to update Base images in the background d.dispatch_task(update_environment_repositories, persist=True) # Set auth error handler # TEMPORARY KLUDGE # Due to GitPython implementation, resources leak. This block deletes all GitPython instances at the end of the request # Future work will remove GitPython, at which point this block should be removed. # TEMPORARY KLUDGE def main(debug=False) -> None: try: # Run app on 0.0.0.0, assuming not an issue since it should be in a container # Please note: Debug mode must explicitly be set to False when running integration # tests, due to properties of Flask werkzeug dynamic package reloading. if debug: # This is to support integration tests, which will call main # with debug=False in order to avoid runtime reloading of Python code # which causes the interpreter to crash. app.run(host="0.0.0.0", port=10001, debug=debug) else: # If debug arg is not explicitly given then it is loaded from config app.run(host="0.0.0.0", port=10001) except Exception as err: logger.exception(err) raise if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 198, 198, 11748, 4423, 346, 198, 11748, 28686, 198, 11748, 2779, 2414, 198, 6738, 640, 1330, 3993, 198, 198, 11748, 42903, 198, 198, 11748, 7007, 13, 1069, 11755, 198, 11748, 30881, 198, 6738, ...
2.61589
3,650
# -*- coding: utf-8 -*- # # Copyright (C) 2005-2007 Christopher Lenz <cmlenz@gmx.de> # Copyright (C) 2007 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://bitten.edgewall.org/wiki/License. """Model classes for objects persisted in the database.""" from trac.attachment import Attachment from trac.db import Table, Column, Index from trac.resource import Resource from trac.util.text import to_unicode import codecs import os __docformat__ = 'restructuredtext en' schema = BuildConfig._schema + TargetPlatform._schema + Build._schema + \ BuildStep._schema + BuildLog._schema + Report._schema schema_version = 10
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 357, 34, 8, 5075, 12, 12726, 12803, 12592, 89, 1279, 66, 4029, 19471, 31, 70, 36802, 13, 2934, 29, 198, 2, 15069, 357, 34, 8, 4343, 1717, 39909, ...
3.255144
243
import numpy as np import pandas as pd from sklearn.linear_model import Ridge from sklearn.model_selection import cross_val_score, train_test_split from sklearn.model_selection import RepeatedKFold from sklearn.preprocessing import OneHotEncoder import pickle from flask import Flask, request np.random.seed(42) df = pd.read_csv('StudentsPerformance.csv') df.rename(columns={'race/ethnicity': 'race', 'parental level of education': 'parent_level_of_education', 'test preparation course': 'test_prep_course', 'math score': 'math_score', 'reading score': 'reading_score', 'writing score': 'writing_score'}, inplace=True) # creating a categorical boolean mask categorical_feature_mask = df.dtypes == object # filtering out the categorical columns categorical_cols = df.columns[categorical_feature_mask].tolist() # instantiate the OneHotEncoder Object one_hot = OneHotEncoder(handle_unknown='ignore', sparse=False) # applying data one_hot.fit(df[categorical_cols]) cat_one_hot = one_hot.transform(df[categorical_cols]) # creating Dataframe of the hot encoded columns hot_df = pd.DataFrame(cat_one_hot, columns=one_hot.get_feature_names(input_features=categorical_cols)) df_OneHotEncoder = pd.concat([df, hot_df], axis=1).drop(columns=categorical_cols, axis=1) X = df_OneHotEncoder.drop('math_score', axis=1) y = df_OneHotEncoder['math_score'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2) model = Ridge(alpha=.99).fit(X_train, y_train) model_scores = cross_val_score(estimator=model, X=X_test, y=y_test, cv=5) print('accuracy for ridge model: %.1f' % (model_scores.mean() * 100)) pickle.dump(model, open('model.pkl', 'wb')) row = ['male', 'group_a', 'some high school', 'standard', 'none', 80, 80] result = row_pred(row) print(result)
[ 11748, 299, 32152, 355, 45941, 201, 198, 11748, 19798, 292, 355, 279, 67, 201, 198, 6738, 1341, 35720, 13, 29127, 62, 19849, 1330, 20614, 201, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 3272, 62, 2100, 62, 26675, 11, 4512, 62...
2.596662
719
"""Enrollment event models context fields definitions""" from typing import Literal, Union from ...base import BaseContextField
[ 37811, 4834, 48108, 1785, 4981, 4732, 7032, 17336, 37811, 198, 198, 6738, 19720, 1330, 25659, 1691, 11, 4479, 198, 198, 6738, 2644, 8692, 1330, 7308, 21947, 15878, 628, 198 ]
4.551724
29
import os import pytest from fontbakery.utils import TEST_FILE from fontbakery.checkrunner import ERROR def test_check_fontvalidator(): """ MS Font Validator checks """ from fontbakery.profiles.fontval import com_google_fonts_check_fontvalidator as check font = TEST_FILE("mada/Mada-Regular.ttf") # we want to run all FValidator checks only once, # so here we cache all results: fval_results = list(check(font)) # Then we make sure that there wasn't an ERROR # which would mean FontValidator is not properly installed: for status, message in fval_results: assert status != ERROR # Simulate FontVal missing. old_path = os.environ["PATH"] os.environ["PATH"] = "" with pytest.raises(OSError) as _: status, message = list(check(font))[-1] assert status == ERROR os.environ["PATH"] = old_path
[ 11748, 28686, 198, 11748, 12972, 9288, 198, 198, 6738, 10369, 65, 33684, 13, 26791, 1330, 43001, 62, 25664, 198, 6738, 10369, 65, 33684, 13, 9122, 16737, 1330, 33854, 628, 198, 4299, 1332, 62, 9122, 62, 10331, 12102, 1352, 33529, 198, 2...
3.123596
267
from run import app from functools import wraps from flask import render_template,flash,redirect,logging,session,url_for,request from .models.database import user_register, user_login, get_feed, get_user_info, update_feed, change_password #kullanc giri decorator'u. bu yap tm decoratorlarda ayn.
[ 6738, 1057, 1330, 598, 201, 198, 6738, 1257, 310, 10141, 1330, 27521, 201, 198, 6738, 42903, 1330, 8543, 62, 28243, 11, 34167, 11, 445, 1060, 11, 6404, 2667, 11, 29891, 11, 6371, 62, 1640, 11, 25927, 201, 198, 6738, 764, 27530, 13, ...
2.80531
113
import click import logging import sys from typing import Tuple from kubails.commands import helpers from kubails.services.config_store import ConfigStore from kubails.services.service import Service from kubails.resources.templates import SERVICE_TEMPLATES from kubails.utils.command_helpers import log_command_args_factory logger = logging.getLogger(__name__) log_command_args = log_command_args_factory(logger, "Service '{}' args") config_store = None service_service = None ############################################################ # Images sub-group ############################################################
[ 11748, 3904, 198, 11748, 18931, 198, 11748, 25064, 198, 6738, 19720, 1330, 309, 29291, 198, 6738, 479, 549, 1768, 13, 9503, 1746, 1330, 49385, 198, 6738, 479, 549, 1768, 13, 30416, 13, 11250, 62, 8095, 1330, 17056, 22658, 198, 6738, 479...
3.831325
166
from __future__ import absolute_import from hashlib import sha256 import hmac import json import six from sentry import options from sentry.models import ApiToken, ProjectKey from sentry.testutils import TestCase UNSET = object()
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 6738, 12234, 8019, 1330, 427, 64, 11645, 198, 11748, 289, 20285, 198, 11748, 33918, 198, 11748, 2237, 198, 198, 6738, 1908, 563, 1330, 3689, 198, 6738, 1908, 563, 13, 27530, 1330...
3.537313
67
from math import exp,sqrt from random import randrange n = 100 X_app = [(randrange(-500,501)/1000,randrange(-500,501)/1000) for i in range(n)] Y_app = [1 if ((x[0]-0.3)+(x[1]-0.3))<0.2 else 0 for x in X_app] a=1 Y_pred,Y_score = [None for i in range(1001)], [None for i in range(1001)] for i in range(1001): b=i/1000*4-1 ne = neurone(a,b) Y_pred[i] = [ne.proceed(z) for z in X_app] Y_score[i] = sum([abs(Y_pred[i][j]-Y_app[j]) for j in range(n)]) opt = min(Y_score) print(Y_score)
[ 6738, 10688, 1330, 1033, 11, 31166, 17034, 198, 6738, 4738, 1330, 43720, 9521, 198, 198, 77, 796, 1802, 198, 55, 62, 1324, 796, 47527, 25192, 9521, 32590, 4059, 11, 33548, 20679, 12825, 11, 25192, 9521, 32590, 4059, 11, 33548, 20679, 12...
2.123404
235
import json import datetime import mimetypes from urllib.parse import urlparse from arcgis import env from arcgis.gis import GIS from arcgis.gis import Item from ._ref import reference def _add_webpage(self, title, url, content=None, actions=None, visible=True, alt_text="", display='stretch'): """ Adds a webpage to the storymap =============== ==================================================================== **Argument** **Description** --------------- -------------------------------------------------------------------- title Required string. The title of the section. --------------- -------------------------------------------------------------------- url Required string. The web address of the webpage --------------- -------------------------------------------------------------------- content Optional string. The content of the section. --------------- -------------------------------------------------------------------- actions Optional list. A collection of actions performed on the section --------------- -------------------------------------------------------------------- visible Optional boolean. If True, the section is visible on publish. If False, the section is not displayed. --------------- -------------------------------------------------------------------- alt_text Optional string. Specifies an alternate text for an image. --------------- -------------------------------------------------------------------- display Optional string. The image display properties. =============== ==================================================================== :return: Boolean """ if actions is None: actions = [] if visible: visible = "PUBLISHED" else: visible = "HIDDEN" self._properties['values']['story']['sections'].append( { "title": title, "content": content, "contentActions": actions, "creaDate": int(datetime.datetime.now().timestamp() * 1000), "pubDate": int(datetime.datetime.now().timestamp() * 1000), "status": visible, "media": { "type": "webpage", "webpage": { "url": url, "type": "webpage", "altText": alt_text, "display": display, "unload": True, "hash": "5" } } } ) return True #---------------------------------------------------------------------- def _add_video(self, url, title, content, actions=None, visible=True, alt_text="", display='stretch' ): """ Adds a video section to the StoryMap. =============== ==================================================================== **Argument** **Description** --------------- -------------------------------------------------------------------- title Required string. The title of the section. --------------- -------------------------------------------------------------------- url Required string. The web address of the image --------------- -------------------------------------------------------------------- content Optional string. The content of the section. --------------- -------------------------------------------------------------------- actions Optional list. A collection of actions performed on the section --------------- -------------------------------------------------------------------- visible Optional boolean. If True, the section is visible on publish. If False, the section is not displayed. --------------- -------------------------------------------------------------------- alt_text Optional string. Specifies an alternate text for an image. --------------- -------------------------------------------------------------------- display Optional string. The image display properties. =============== ==================================================================== :return: Boolean """ if actions is None: actions = [] if visible: visible = "PUBLISHED" else: visible = "HIDDEN" video = { "title": title, "content": content, "contentActions": actions, "creaDate": 1523450612336, "pubDate": 1523450580000, "status": visible, "media": { "type": "video", "video": { "url": url, "type": "video", "altText": alt_text, "display": display } } } self._properties['values']['story']['sections'].append(video) return True #---------------------------------------------------------------------- def _add_webmap(self, item, title, content, actions=None, visible=True, alt_text="", display='stretch', show_legend=False, show_default_legend=False, extent=None, layer_visibility=None, popup=None ): """ Adds a WebMap to the Section. =============== ==================================================================== **Argument** **Description** --------------- -------------------------------------------------------------------- item Required string/Item. The webmap Item Id or Item of a webmap. --------------- -------------------------------------------------------------------- title Required string. The title of the section. --------------- -------------------------------------------------------------------- url Required string. The web address of the image --------------- -------------------------------------------------------------------- content Optional string. The content of the section. --------------- -------------------------------------------------------------------- actions Optional list. A collection of actions performed on the section --------------- -------------------------------------------------------------------- visible Optional boolean. If True, the section is visible on publish. If False, the section is not displayed. --------------- -------------------------------------------------------------------- alt_text Optional string. Specifies an alternate text for an image. --------------- -------------------------------------------------------------------- display Optional string. The image display properties. =============== ==================================================================== :return: Boolean """ if isinstance(item, Item): item = item.itemid if actions is None: actions = [] if visible: visible = "PUBLISHED" else: visible = "HIDDEN" wm = { "title": title, "content": content, "contentActions": actions, "creaDate": int(datetime.datetime.now().timestamp() * 1000), "pubDate": int(datetime.datetime.now().timestamp() * 1000), "status": visible, "media": { "type": "webmap", "webmap": { "id": item, "extent": extent, "layers": layer_visibility, "popup": popup, "overview": { "enable": False, "openByDefault": True }, "legend": { "enable": show_legend, "openByDefault": show_default_legend }, "geocoder": { "enable": False }, "altText": alt_text } } } self._properties['values']['story']['sections'].append(wm) return True #---------------------------------------------------------------------- def _add_image(self, title, image, content=None, actions=None, visible=True, alt_text=None, display='fill'): """ Adds a new image section to the storymap =============== ==================================================================== **Argument** **Description** --------------- -------------------------------------------------------------------- title Required string. The title of the section. --------------- -------------------------------------------------------------------- url Required string. The web address of the image --------------- -------------------------------------------------------------------- content Optional string. The content of the section. --------------- -------------------------------------------------------------------- actions Optional list. A collection of actions performed on the section --------------- -------------------------------------------------------------------- visible Optional boolean. If True, the section is visible on publish. If False, the section is not displayed. --------------- -------------------------------------------------------------------- alt_text Optional string. Specifies an alternate text for an image. --------------- -------------------------------------------------------------------- display Optional string. The image display properties. =============== ==================================================================== :return: Boolean """ if actions is None: actions = [] if visible: visible = "PUBLISHED" else: visible = "HIDDEN" self._properties['values']['story']['sections'].append( { "title": title, "content": content, "contentActions": actions, "creaDate": int(datetime.datetime.now().timestamp() * 1000), "pubDate": int(datetime.datetime.now().timestamp() * 1000), "status": visible, "media": { "type": "image", "image": { "url": image, "type": "image", "altText": alt_text, "display": display } } } ) return True #---------------------------------------------------------------------- def remove(self, index): """ Removes a section by index. =============== ==================================================================== **Argument** **Description** --------------- -------------------------------------------------------------------- index Required integer. The position of the section to remove. =============== ==================================================================== :return: Boolean """ try: item = self._properties['values']['story']['sections'][index] self._properties['values']['story']['sections'].remove(item) return True except: return False #---------------------------------------------------------------------- def save(self, title=None, tags=None, description=None): """ Saves an Journal StoryMap to the GIS =============== ==================================================================== **Argument** **Description** --------------- -------------------------------------------------------------------- title Optional string. The title of the StoryMap. --------------- -------------------------------------------------------------------- tags Optional string. The tags of the StoryMap. --------------- -------------------------------------------------------------------- description Optional string. The description of the StoryMap =============== ==================================================================== :return: Boolean """ import uuid if self._item: p = { 'text' : json.dumps(self._properties) } if title: p['title'] = title if tags: p['tags'] = tags return self._item.update(item_properties=p) else: if title is None: title = "Map Journal, %s" % uuid.uuid4().hex[:10] if tags is None: tags = "Story Map,Map Journal" typeKeywords = ",".join(['JavaScript', 'layout-side', 'Map', 'MapJournal', 'Mapping Site', 'Online Map', 'Ready To Use', 'selfConfigured', 'Story Map', 'Story Maps', 'Web Map']) item = self._gis.content.add(item_properties={ 'title' : title, 'tags' : tags, 'text' : json.dumps(self._properties), 'typeKeywords' : typeKeywords, 'itemType' : 'text', 'type' : "Web Mapping Application", }) parse = urlparse(self._gis._con.baseurl) isinstance(self._gis, GIS) if self._gis._portal.is_arcgisonline: url = "%s://%s/apps/MapJournal/index.html?appid=%s" % (parse.scheme, parse.netloc, item.itemid) else: import os wa = os.path.dirname(parse.path[1:]) url = "%s://%s/%s/sharing/rest/apps/MapJournal/index.html?appid=%s" % (parse.scheme, parse.netloc, wa, item.itemid) return item.update(item_properties={ 'url' : url }) return False #---------------------------------------------------------------------- def delete(self): """Deletes the saved item on ArcGIS Online/Portal""" if self._item: return self._item.delete() return False #---------------------------------------------------------------------- #---------------------------------------------------------------------- #---------------------------------------------------------------------- #---------------------------------------------------------------------- #---------------------------------------------------------------------- #----------------------------------------------------------------------
[ 11748, 33918, 198, 11748, 4818, 8079, 198, 11748, 17007, 2963, 12272, 198, 6738, 2956, 297, 571, 13, 29572, 1330, 19016, 29572, 198, 6738, 10389, 70, 271, 1330, 17365, 198, 6738, 10389, 70, 271, 13, 70, 271, 1330, 402, 1797, 198, 6738, ...
2.358795
7,004
from aoc2015.core import dispatch def test_dispatch_fail(capsys): '''Dispatch fails properly when passed a bad day''' # capsys is a pytest fixture that allows asserts agains stdout/stderr # https://docs.pytest.org/en/stable/capture.html dispatch(['204']) captured = capsys.readouterr() assert 'No module named aoc2015.day204' in captured.out def test_dispatch_day0(capsys): '''Dispatch to "template" day0 module works''' # capsys is a pytest fixture that allows asserts agains stdout/stderr # https://docs.pytest.org/en/stable/capture.html dispatch(['0', 'arg1', 'arg2']) captured = capsys.readouterr() assert "day0: ['arg1', 'arg2']" in captured.out
[ 6738, 257, 420, 4626, 13, 7295, 1330, 27965, 628, 198, 4299, 1332, 62, 6381, 17147, 62, 32165, 7, 27979, 893, 2599, 198, 220, 220, 220, 705, 7061, 49354, 10143, 6105, 618, 3804, 257, 2089, 1110, 7061, 6, 198, 220, 220, 220, 1303, 11...
2.756863
255
from myoperator import BlockOperator import re
[ 6738, 616, 46616, 1330, 9726, 18843, 1352, 198, 11748, 302, 628 ]
4.363636
11
import os from StringIO import StringIO from zipfile import ZipFile import subprocess import shutil import fcntl import time import signal import imp import sys,traceback
[ 11748, 28686, 198, 6738, 10903, 9399, 1330, 10903, 9399, 198, 6738, 19974, 7753, 1330, 38636, 8979, 198, 11748, 850, 14681, 198, 11748, 4423, 346, 198, 11748, 277, 66, 429, 75, 198, 11748, 640, 198, 11748, 6737, 198, 11748, 848, 198, 11...
3.717391
46
from __future__ import absolute_import, unicode_literals try: from importlib import reload except ImportError: pass from django.conf.urls import url from django.test import TestCase from mock import patch try: import wagtail.core.urls as wagtail_core_urls except ImportError: # pragma: no cover; fallback for Wagtail <2.0 import wagtail.wagtailcore.urls as wagtail_core_urls import wagtailsharing.urls
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 28000, 1098, 62, 17201, 874, 198, 198, 28311, 25, 198, 220, 220, 220, 422, 1330, 8019, 1330, 18126, 198, 16341, 17267, 12331, 25, 198, 220, 220, 220, 1208, 198, 198, 6738, 42625, 142...
2.884354
147
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2011-2021, Nigel Small # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from monotonic import monotonic
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 15069, 2813, 12, 1238, 2481, 11, 28772, 10452, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362,...
3.561497
187
# check to strings that represent version numbers and finds the greatest, # 'equals' if they are the same version or 'Invalid Format' # example: 1.2 is greater than 1.1. # for reusability this function just returns the version number or the word equals # if a more elaborated answer is needed an interface would be usefull
[ 2, 2198, 284, 13042, 326, 2380, 2196, 3146, 290, 7228, 262, 6000, 11, 198, 2, 705, 4853, 874, 6, 611, 484, 389, 262, 976, 2196, 393, 705, 44651, 18980, 6, 220, 198, 2, 1672, 25, 352, 13, 17, 318, 3744, 621, 352, 13, 16, 13, 22...
4.153846
78
# This sample tests type narrowing of subject expressions for # match statements. from typing import Literal
[ 2, 770, 6291, 5254, 2099, 46426, 286, 2426, 14700, 329, 198, 2, 2872, 6299, 13, 198, 198, 6738, 19720, 1330, 25659, 1691, 628, 198 ]
4.666667
24
import sys import os sys.path.append(os.getcwd()) import argparse import numpy as np import pmdarima import torch import torch.nn.functional as F from torch import nn from fusions.common_fusions import Stack from unimodals.common_models import LSTMWithLinear from datasets.stocks.get_data import get_dataloader parser = argparse.ArgumentParser() parser.add_argument('--input-stocks', metavar='input', help='input stocks') parser.add_argument('--target-stock', metavar='target', help='target stock') args = parser.parse_args() print('Input: ' + args.input_stocks) print('Target: ' + args.target_stock) stocks = sorted(args.input_stocks.split(' ')) train_loader, val_loader, test_loader = get_dataloader(stocks, stocks, [args.target_stock], modality_first=True) baselines()
[ 11748, 25064, 198, 11748, 28686, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 1136, 66, 16993, 28955, 198, 198, 11748, 1822, 29572, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 9114, 27455, 8083, 198, 11748, 28034, 198, 11748, 28034, ...
3.158537
246
# -- Imports ------------------------------------------------------------------ from __future__ import print_function from __future__ import unicode_literals from Foundation import CFPreferencesAppSynchronize, CFPreferencesCopyAppValue from os import getenv # -- Class -------------------------------------------------------------------- if __name__ == '__main__': from doctest import testmod testmod()
[ 2, 1377, 1846, 3742, 16529, 438, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 5693, 1330, 327, 5837, 5420, 4972, 4677, 50, 24871, 1096, 11, 3...
4.582418
91
# parsetab.py # This file is automatically generated. Do not edit. # pylint: disable=W,C,R _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'leftIMPLIESSIMPLIESleftANDORleftRPARENLPARENrightNEGATIONALPHABET AND IMPLIES LPAREN NEGATION OR PREDICATE RPAREN SIMPLIESexpr : expr AND exprexpr : ALPHABETexpr : expr OR exprexpr : NEGATION exprexpr : expr IMPLIES exprexpr : expr SIMPLIES exprexpr : LPAREN expr RPAREN' _lr_action_items = {'ALPHABET':([0,3,4,5,6,7,8,],[2,2,2,2,2,2,2,]),'NEGATION':([0,3,4,5,6,7,8,],[3,3,3,3,3,3,3,]),'LPAREN':([0,3,4,5,6,7,8,],[4,4,4,4,4,4,4,]),'$end':([1,2,9,11,12,13,14,15,],[0,-2,-4,-1,-3,-5,-6,-7,]),'AND':([1,2,9,10,11,12,13,14,15,],[5,-2,-4,5,-1,-3,5,5,-7,]),'OR':([1,2,9,10,11,12,13,14,15,],[6,-2,-4,6,-1,-3,6,6,-7,]),'IMPLIES':([1,2,9,10,11,12,13,14,15,],[7,-2,-4,7,-1,-3,-5,-6,-7,]),'SIMPLIES':([1,2,9,10,11,12,13,14,15,],[8,-2,-4,8,-1,-3,-5,-6,-7,]),'RPAREN':([2,9,10,11,12,13,14,15,],[-2,-4,15,-1,-3,-5,-6,-7,]),} _lr_action = {} for _k, _v in _lr_action_items.items(): for _x,_y in zip(_v[0],_v[1]): if not _x in _lr_action: _lr_action[_x] = {} _lr_action[_x][_k] = _y del _lr_action_items _lr_goto_items = {'expr':([0,3,4,5,6,7,8,],[1,9,10,11,12,13,14,]),} _lr_goto = {} for _k, _v in _lr_goto_items.items(): for _x, _y in zip(_v[0], _v[1]): if not _x in _lr_goto: _lr_goto[_x] = {} _lr_goto[_x][_k] = _y del _lr_goto_items _lr_productions = [ ("S' -> expr","S'",1,None,None,None), ('expr -> expr AND expr','expr',3,'p_and','main.py',48), ('expr -> ALPHABET','expr',1,'p_expr','main.py',52), ('expr -> expr OR expr','expr',3,'p_or','main.py',56), ('expr -> NEGATION expr','expr',2,'p_negation','main.py',60), ('expr -> expr IMPLIES expr','expr',3,'p_implies','main.py',64), ('expr -> expr SIMPLIES expr','expr',3,'p_simplies','main.py',69), ('expr -> LPAREN expr RPAREN','expr',3,'p_parens','main.py',73), ]
[ 198, 2, 13544, 316, 397, 13, 9078, 198, 2, 770, 2393, 318, 6338, 7560, 13, 2141, 407, 4370, 13, 198, 2, 279, 2645, 600, 25, 15560, 28, 54, 11, 34, 11, 49, 198, 62, 8658, 9641, 796, 705, 18, 13, 940, 6, 198, 198, 62, 14050, 6...
1.925628
995
'''Please write a program to read the scan and print out The maximum voxel intensity The mean voxel intensity The coordinates of the centre of the image volume, in the scanner coordinate system. ''' import pydicom import numpy as np import matplotlib.pyplot as plt import cv2 import glob import os import image_slicer '''form a 3D array by stacking all CT scan slices''' # load the DICOM files src_path = r'C:\Users\GGPC\SegmentationTest\Image-Segmentation' DICOM_dir_path = src_path + '\DICOM data' # snapshot dicom file files = [] for fname in glob.glob(DICOM_dir_path+'\*', recursive=False): print("loading: {}".format(fname)) files.append(pydicom.read_file(fname)) print("file count: {}".format(len(files))) # skip files with no SliceLocation slices = [] skipcount = 0 for f in files: if hasattr(f, 'SliceLocation'): slices.append(f) else: skipcount = skipcount + 1 print("skipped, no SliceLocation: {}".format(skipcount)) # ensure they are in the correct order slices = sorted(slices, key=lambda s: s.SliceLocation) # create 3D array (assuming that each slice has the same pixel size) img_shape = list(slices[0].pixel_array.shape) img_shape.append(len(slices)) img3d = np.zeros(img_shape) # fill 3D array with the images from the files for i, s in enumerate(slices): img3d[:, :, i] = s.pixel_array input("Press Enter to continue showing Question 1 (a) results...") '''start solving Q1_a read and print''' # first two questions are straight-forward print() print('Question 1 (a)') print('i. The maximum voxel intensity is {}'.format(img3d.max())) print('ii. The mean voxel intensity is {}'.format(img3d.mean())) # centre of the image volume is at (256.5,256.5) pixel position between the 100th and 101st slices ImagePlanePosition_of_100th_slice = np.array(slices[99].ImagePositionPatient) RowChangeInX_of_100th_slice = np.array(slices[99].ImageOrientationPatient[0:3]) * slices[99].PixelSpacing[0] * 256.5 ColumnChangeInY_of_100th_slice = np.array(slices[99].ImageOrientationPatient[3:6]) * slices[99].PixelSpacing[1] * 256.5 coordinate_of_100th_slice = ImagePlanePosition_of_100th_slice + RowChangeInX_of_100th_slice + ColumnChangeInY_of_100th_slice ImagePlanePosition_of_101th_slice = np.array(slices[100].ImagePositionPatient) RowChangeInX_of_101th_slice = np.array(slices[100].ImageOrientationPatient[0:3]) * slices[100].PixelSpacing[0] * 256.5 ColumnChangeInY_of_101th_slice = np.array(slices[100].ImageOrientationPatient[3:6]) * slices[100].PixelSpacing[1] * 256.5 coordinate_of_101th_slice = ImagePlanePosition_of_101th_slice + RowChangeInX_of_101th_slice + ColumnChangeInY_of_101th_slice coordinate_of_ImageVolumeCentre = (coordinate_of_100th_slice+coordinate_of_101th_slice)/2 print('iii. coordinates of the centre of the image volume is {} mm'.format(list(coordinate_of_ImageVolumeCentre))) input("Press Enter to continue showing Question 1 (b) results...") '''start solving Q1_b''' # plot the maximum voxel intensity of each slice MaxVoxelList=[] MeanVoxelList=[] for s in slices: MaxVoxelList.append(s.pixel_array.max()) MeanVoxelList.append(s.pixel_array.mean()) print('Close plot to continue') plt.scatter(range(0,len(MaxVoxelList)), MaxVoxelList) plt.xlabel('slice index (1-200)') plt.ylabel('maximum voxel intensity') plt.title('Scatter of Max Voxel over Slice Index') plt.show() # selection voxel intensity threshold of 3000 Threshold = 3000 print('Close plot of an mask dection example to continue') a1 = plt.subplot(2, 2, 1) plt.imshow(img3d[:, :, 30]) a1 = plt.subplot(2, 2, 2) plt.imshow(img3d[:, :, 30]>Threshold) a1 = plt.subplot(2, 2, 3) plt.imshow(img3d[:, :, 176]) a1 = plt.subplot(2, 2, 4) plt.imshow(img3d[:, :, 176]>Threshold) plt.show() input("Press Enter to continue generating images and masks to Folders: SegmentationMask(metal mask) and Images(ct scan slices)...") # generate images and masks NameCount = 300 for s in slices: ImageName = '\SegmentationMask\IM00' + str(NameCount) + '.png' img = s.pixel_array>Threshold img = img.astype('uint8')*255 cv2.imwrite(src_path + ImageName, img) print(ImageName + ' has been saved') NameCount+=1 NameCount = 300 for s in slices: ImageName = '\Images\IM00' + str(NameCount) + '.png' img = (s.pixel_array - img3d.min())/(img3d.max()-img3d.min())*255 cv2.imwrite(src_path + ImageName, img) print(ImageName + ' has been saved') NameCount+=1 # NameCount = 300 # for s in slices: # ImageName = '\SegmentationBoneMask\IM00' + str(NameCount) + '.png' # img = s.pixel_array>0 # img = img.astype('uint8')*255 # cv2.imwrite(src_path + ImageName, img) # print(ImageName + ' has been saved') # NameCount+=1 # NameCount = 300 # for s in slices: # ImageName = '\Dataset_Slicer\masks\IM00' + str(NameCount) + '.png' # img = s.pixel_array>Threshold # img = img.astype('uint8')*255 # cv2.imwrite(src_path + ImageName, img) # image_slicer.slice(src_path + ImageName,14) # os.remove(src_path + ImageName) # print(ImageName + ' has been saved') # NameCount+=1 # # NameCount = 300 # for s in slices: # ImageName = '\Dataset_Slicer\images\IM00' + str(NameCount) + '.png' # img = (s.pixel_array - img3d.min())/(img3d.max()-img3d.min())*255 # cv2.imwrite(src_path + ImageName, img) # image_slicer.slice(src_path + ImageName, 14) # os.remove(src_path + ImageName) # print(ImageName + ' has been saved') # NameCount+=1 # # NameCount = 300 # for s in slices: # ImageName = '\Dataset_Slicer\masks\IM00' + str(NameCount) + '.png' # img = s.pixel_array>0 # img = img.astype('uint8')*255 # cv2.imwrite(src_path + ImageName, img) # print(ImageName + ' has been saved') # NameCount+=1 # os.mkdir(src_path + '\\Dataset') # for fname in glob.glob(DICOM_dir_path + '\*', recursive=False): # os.mkdir(src_path + '\\Dataset' + fname[-8:]) # os.mkdir(src_path + '\\Dataset' + fname[-8:] + '\\images') # os.mkdir(src_path + '\\Dataset' + fname[-8:] + '\\masks') # # NameCount = 300 # for s in slices: # ImageName = '\Dataset\IM00' + str(NameCount) + '\masks\MetalMask.png' # img = s.pixel_array>Threshold # img = img.astype('uint8')*255 # cv2.imwrite(src_path + ImageName, img) # print(ImageName + ' has been saved') # NameCount+=1 # # NameCount = 300 # for s in slices: # ImageName = '\Dataset\IM00' + str(NameCount) + '\images' + '\IM00' + str(NameCount) + '.png' # img = (s.pixel_array - img3d.min())/(img3d.max()-img3d.min())*255 # cv2.imwrite(src_path + ImageName, img) # print(ImageName + ' has been saved') # NameCount+=1 # # NameCount = 300 # for s in slices: # ImageName = '\Dataset\IM00' + str(NameCount) + '\masks\PositiveVoxelMask.png' # img = s.pixel_array>0 # img = img.astype('uint8')*255 # cv2.imwrite(src_path + ImageName, img) # print(ImageName + ' has been saved') # NameCount+=1
[ 7061, 6, 5492, 3551, 257, 1430, 284, 1100, 262, 9367, 290, 3601, 503, 198, 464, 5415, 410, 1140, 417, 12245, 198, 464, 1612, 410, 1140, 417, 12245, 198, 464, 22715, 286, 262, 7372, 286, 262, 2939, 6115, 11, 287, 262, 27474, 20435, 1...
2.478914
2,798
if __name__ == "__main__": main()
[ 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419, 198 ]
2.1
20
"""An unofficial Python wrapper for the Binance exchange API v3 .. moduleauthor:: Sam McHardy .. modified by Stephan Avenwedde for Pythonic """
[ 37811, 2025, 27220, 11361, 29908, 329, 262, 347, 14149, 5163, 7824, 410, 18, 198, 198, 492, 8265, 9800, 3712, 3409, 1982, 17309, 88, 198, 492, 9518, 416, 20800, 15053, 19103, 2934, 329, 11361, 291, 198, 198, 37811, 198 ]
3.842105
38
import os from tests import PMGTestCase from tests.fixtures import dbfixture, CommitteeQuestionData
[ 11748, 28686, 198, 6738, 5254, 1330, 3122, 38, 14402, 20448, 198, 6738, 5254, 13, 69, 25506, 1330, 288, 19881, 9602, 11, 4606, 24361, 6601, 628 ]
4.04
25
root = Tree(4, left = Tree(3), right=Tree(5, left= Tree(4))) #InOrderTraversal print("In order:", InOrderTraversal(root)) #PreOrderTraversal print("Pre order:", PreOrderTraversal(root)) #PostOrderTraversal print("Post order:", PostOrderTraversal(root)) print("Level order Traversal: ", LevelOrderTraversal(root))
[ 15763, 796, 12200, 7, 19, 11, 1364, 796, 12200, 7, 18, 828, 826, 28, 27660, 7, 20, 11, 1364, 28, 12200, 7, 19, 22305, 201, 198, 201, 198, 2, 818, 18743, 15721, 690, 282, 201, 198, 4798, 7203, 818, 1502, 25, 1600, 554, 18743, 157...
2.74359
117
from datetime import datetime # Rest framework from rest_framework import status from rest_framework.decorators import action from rest_framework.mixins import RetrieveModelMixin, ListModelMixin, UpdateModelMixin, CreateModelMixin from rest_framework.response import Response from rest_framework.viewsets import GenericViewSet from rest_framework.permissions import IsAuthenticated # Serializers from csv_analyzer.apps.dataset.serializers import ( DataSetModelSerializer, CreateDataSetModelSerializer, FileDataSetModelSerializer, ) # Models from csv_analyzer.apps.dataset.models import DataSet # Permissions from csv_analyzer.apps.dataset.permissions.dataset import IsDataSetOwner # Celery from csv_analyzer.apps.dataset.tasks import populate_dataset_file # MongoDB utils from csv_analyzer.apps.mongodb.utils import MongoDBConnection
[ 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 2, 8324, 9355, 198, 6738, 1334, 62, 30604, 1330, 3722, 198, 6738, 1334, 62, 30604, 13, 12501, 273, 2024, 1330, 2223, 198, 6738, 1334, 62, 30604, 13, 19816, 1040, 1330, 4990, 30227, 17633, ...
3.293436
259
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. """Tests for tfx_bsl.tfxio.tensor_to_arrow.""" import numpy as np import pyarrow as pa import tensorflow as tf from tfx_bsl.tfxio import tensor_adapter from tfx_bsl.tfxio import tensor_to_arrow from google.protobuf import text_format from absl.testing import absltest from absl.testing import parameterized from tensorflow_metadata.proto.v0 import schema_pb2 _TF_TYPE_TO_ARROW_TYPE = { tf.int8: pa.int8(), tf.int16: pa.int16(), tf.int32: pa.int32(), tf.int64: pa.int64(), tf.uint8: pa.uint8(), tf.uint16: pa.uint16(), tf.uint32: pa.uint32(), tf.uint64: pa.uint64(), tf.float32: pa.float32(), tf.float64: pa.float64(), tf.string: pa.binary(), } _ROW_PARTITION_DTYPES = { "INT64": np.int64, "INT32": np.int32 } _CONVERT_TEST_CASES = [ dict( testcase_name="multiple_tensors", type_specs={ "sp1": tf.SparseTensorSpec([None, None], tf.int32), "sp2": tf.SparseTensorSpec([None, None], tf.string), }, expected_schema={ "sp1": pa.list_(pa.int32()), "sp2": pa.list_(pa.binary()), }, expected_tensor_representations={ "sp1": """varlen_sparse_tensor { column_name: "sp1" }""", "sp2": """varlen_sparse_tensor { column_name: "sp2" }""", }, tensor_input={ "sp1": tf.SparseTensor( values=tf.constant([1, 2], dtype=tf.int32), indices=[[0, 0], [2, 0]], dense_shape=[4, 1]), "sp2": tf.SparseTensor( values=[b"aa", b"bb"], indices=[[2, 0], [2, 1]], dense_shape=[4, 2]) }, expected_record_batch={ "sp1": pa.array([[1], [], [2], []], type=pa.list_(pa.int32())), "sp2": pa.array([[], [], [b"aa", b"bb"], []], type=pa.list_(pa.binary())) }), dict( testcase_name="ragged_tensors", type_specs={ "sp1": tf.RaggedTensorSpec( tf.TensorShape([2, None]), tf.int64, ragged_rank=1, row_splits_dtype=tf.int64), "sp2": tf.RaggedTensorSpec( tf.TensorShape([2, None]), tf.string, ragged_rank=1, row_splits_dtype=tf.int64), }, expected_schema={ "sp1": pa.list_(pa.int64()), "sp2": pa.list_(pa.binary()), }, expected_tensor_representations={ "sp1": """ragged_tensor { feature_path { step: "sp1" } row_partition_dtype: INT64 }""", "sp2": """ragged_tensor { feature_path { step: "sp2" } row_partition_dtype: INT64 }""", }, tensor_input={ "sp1": tf.RaggedTensor.from_row_splits( values=np.asarray([1, 5, 9], dtype=np.int64), row_splits=np.asarray([0, 2, 3], dtype=np.int64)), "sp2": tf.RaggedTensor.from_row_splits( values=np.asarray([b"x", b"y", b"z"], dtype=np.str), row_splits=np.asarray([0, 2, 3], dtype=np.int64)) }, expected_record_batch={ "sp1": pa.array([[1, 5], [9]], type=pa.list_(pa.int32())), "sp2": pa.array([[b"x", b"y"], [b"z"]], type=pa.list_(pa.binary())), }) ] + _make_2d_varlen_sparse_tensor_test_cases( ) + _make_3d_ragged_tensor_test_cases() if __name__ == "__main__": # Do not run these tests under TF1.x -- TensorToArrow does not support TF 1.x. if tf.__version__ >= "2": absltest.main()
[ 2, 15069, 12131, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 733...
1.798522
2,571
""" Thornleigh Farm - VPN Watchdog Failure Email Module author: hugh@blinkybeach.com """ from th_watchdog.email import Email
[ 37811, 198, 817, 1211, 42342, 11272, 532, 21669, 6305, 9703, 198, 50015, 9570, 19937, 198, 9800, 25, 289, 6724, 31, 2436, 29246, 1350, 620, 13, 785, 198, 37811, 198, 6738, 294, 62, 8340, 9703, 13, 12888, 1330, 9570, 628 ]
3.230769
39
__all__ = ['TextDataLayer'] from functools import partial import torch from torch.utils.data import DataLoader, DistributedSampler from nemo.backends.pytorch.common.parts import TextDataset from nemo.backends.pytorch.nm import DataLayerNM from nemo.core import DeviceType from nemo.core.neural_types import * from nemo.utils.misc import pad_to
[ 834, 439, 834, 796, 37250, 8206, 6601, 49925, 20520, 198, 198, 6738, 1257, 310, 10141, 1330, 13027, 198, 198, 11748, 28034, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 6060, 17401, 11, 4307, 6169, 16305, 20053, 198, 198, 6738, 36945, 7...
3.192661
109
import logging from datetime import time, timedelta from functools import wraps # Telegram bot libraries from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler from telegram import KeyboardButton, ReplyKeyboardMarkup, ParseMode, Bot, InlineKeyboardButton, InlineKeyboardMarkup from telegram.error import TelegramError, Unauthorized, BadRequest, TimedOut, ChatMigrated, NetworkError # Local files from utils import * from orario import * import config from captions import Captions # Enable logging logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.WARNING) logger = logging.getLogger(__name__) # Captions class handles languages languages = Captions(config.supported_languages, config.captions_path) # Decorators # Update Handlers def callback_orario(update, context): data = update.callback_query.data[2:] ultima_data = update.callback_query.message.text.splitlines()[0][-11:-1] u_id = str(update.callback_query.from_user.id) chat_id = update.callback_query.message.chat_id lang_str = languages.get_reply('orario', lang=get_lang('', u_id=u_id)) reply, keyboard = orarioSaveSetting(chat_id, data, lang_str, last_date=ultima_data) reply_markup = InlineKeyboardMarkup(keyboard) context.bot.editMessageText(text=reply, chat_id=chat_id, message_id=update.callback_query.message.message_id, parse_mode=ParseMode.MARKDOWN, reply_markup=reply_markup) def callback_settings(update, context): data = update.callback_query.data[2:].split('-') u_id = str(update.callback_query.from_user.id) chat_id = update.callback_query.message.chat_id if data[0] == 'alarm': if data[1] == 'on': # Chiude il job unset_job_orario(str(chat_id), context.job_queue) set_alarm_value(u_id, None) elif data[1] == 'off': # Scelta timing orario lang_list = languages.get_reply('settings', lang=get_lang('', u_id=u_id)) markup = [] for hour in [5, 7, 9, 12, 18, 21]: markup.append([InlineKeyboardButton(str(hour)+':00', callback_data='2-alarm-set-'+str(hour)+':00'), InlineKeyboardButton(str(hour)+':30', callback_data='2-alarm-set-'+str(hour)+':30'), InlineKeyboardButton(str(hour+1)+':00', callback_data='2-alarm-set-'+str(hour+1)+':00'), InlineKeyboardButton(str(hour+1)+':30', callback_data='2-alarm-set-'+str(hour+1)+':30')]) markup = InlineKeyboardMarkup(markup) context.bot.editMessageText(text=lang_list[5], chat_id=chat_id, message_id=update.callback_query.message.message_id, parse_mode=ParseMode.MARKDOWN, reply_markup=markup) return elif data[1] == 'set': set_job_orario(str(chat_id), u_id, context.job_queue, orario=data[2]) set_alarm_value(u_id, data[2]) elif data[0] == 'mensa': if data[1] == 'enable': # Scelta mensa mense_list = languages.get_keyboard('mensa') lang_list = languages.get_reply('settings', lang=get_lang('', u_id=u_id)) markup = [] for row in mense_list: for mensa in row: if mensa != '/home': markup.append([InlineKeyboardButton(mensa.replace('/',''), callback_data='2-mensa-set-'+mensa.replace('/',''))]) markup = InlineKeyboardMarkup(markup) context.bot.editMessageText(text=lang_list[9], chat_id=chat_id, message_id=update.callback_query.message.message_id, parse_mode=ParseMode.MARKDOWN, reply_markup=markup) return elif data[1] == 'set': set_fav_mensa(u_id, data[2]) elif data[1] == 'disable': set_fav_mensa(u_id, None) elif data[0] == 'lang': changed = set_lang(u_id, data[1]) if not changed: return reply, keyboard = get_user_settings(update, languages.get_reply('settings', lang=get_lang('', u_id=u_id)), u_id=u_id) reply_markup = InlineKeyboardMarkup(keyboard) context.bot.editMessageText(text=reply, chat_id=chat_id, message_id=update.callback_query.message.message_id, parse_mode=ParseMode.MARKDOWN, reply_markup=reply_markup) def job_orario(context): chat_id = context.job.context[0] u_id = context.job.context[0] lang_str = languages.get_reply('orario', lang=get_lang('', u_id=u_id)) reply, keyboard = orarioSetup(chat_id, lang_str, resetDate=True) # Check if orario is empty if lang_str['text'][9] in reply: return reply_markup = InlineKeyboardMarkup(keyboard) context.bot.sendMessage(chat_id=chat_id, text=reply, parse_mode=ParseMode.MARKDOWN, disable_notification=True, reply_markup=reply_markup) def set_job_orario(chat_id, u_id, job_queue, orario): try: # 0: lun, 1: mar, 2: mer, 3: gio, 4: ven orario = orario.split(':') job_queue.run_daily(job_orario, time=time(int(orario[0]), int(orario[1]), 0), days=(0, 1, 2, 3, 4), context=[chat_id, u_id]) #job_queue.run_repeating(job_orario, timedelta(seconds=10), context=[chat_id, u_id]) # For testing except (IndexError, ValueError): pass def unset_job_orario(chat_id, job_queue): for job in job_queue.jobs(): try: if job.context[0] == chat_id: job.schedule_removal() except: pass def admin_forward(update, context): context.bot.forwardMessage(chat_id=config.botAdminID, from_chat_id=get_chat_id(update), message_id=update.message.message_id) text = '<code>/reply ' + str(update.message.chat.id) + '</code>' context.bot.sendMessage(chat_id=config.botAdminID, parse_mode=ParseMode.HTML, disable_notification=True, text=text) if __name__ == '__main__': main()
[ 11748, 18931, 198, 6738, 4818, 8079, 1330, 640, 11, 28805, 12514, 198, 6738, 1257, 310, 10141, 1330, 27521, 198, 198, 2, 50203, 10214, 12782, 198, 6738, 573, 30536, 13, 2302, 1330, 3205, 67, 729, 11, 9455, 25060, 11, 16000, 25060, 11, ...
2.103437
2,997
from server import db, auth, emolytics from server.models import Tweet from classifier import create_classifier from tweepy import Stream from tweepy.streaming import StreamListener from flask.ext.rq import job import json import random from multiprocessing import Process from sqlalchemy.exc import IntegrityError ''' def start_thread(track): global process if process != None and process.is_alive(): process.terminate() process = Process(target=start_streaming, kwargs={"track": track}) process.start() print "Started the thread" def start_classification(): global clf_process if clf_process != None and clf_process.is_alive(): clf_process.terminate() clf_process = Process(target=classify) clf_process.start() print "Started classification" '''
[ 6738, 4382, 1330, 20613, 11, 6284, 11, 795, 3366, 14094, 198, 6738, 4382, 13, 27530, 1330, 18752, 198, 6738, 1398, 7483, 1330, 2251, 62, 4871, 7483, 198, 198, 6738, 4184, 538, 88, 1330, 13860, 198, 6738, 4184, 538, 88, 13, 5532, 278, ...
3.033708
267
import csv import os import shutil from datetime import datetime from grid import * #from cluster import * from regions import * start_time = datetime.now() print("Allocating...") #grid2 #gridSystem = GridSystem(-74.04, -73.775, 5, 40.63, 40.835, 5) #gridname = "grid2" #grid3 #gridSystem = GridSystem(-74.02, -73.938, 4, 40.7, 40.815, 6) #gridname = "grid3" #cluster1 #gridSystem = ClusterSystem("cluster1/clusters.csv") #gridname = "cluster1" gridSystem = RegionSystem("4year_features") gridname = "region1" invalids = 0 for y in ["FOIL2010", "FOIL2011", "FOIL2012", "FOIL2013"]: for n in range(1,13): filename = "../../new_chron/" + y + "/trip_data_" + str(n) + ".csv" print("Reading file " + filename) r = csv.reader(open(filename, "r")) i = 0 header = True for line in r: if(header): Trip.initHeader(line) header = False else: trip = None try: trip = Trip(line) except ValueError: invalids += 1 if(trip!= None and (y!="FOIL" + str(trip.date.year) or n!= trip.date.month)): trip.has_other_error = True gridSystem.record(trip) i += 1 if(i%1000000==0): print("Read " + str(i) + " rows") gridSystem.close() end_time = datetime.now() program_duration = end_time - start_time print("Processing took " + str(program_duration))
[ 11748, 269, 21370, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 10706, 1330, 1635, 198, 2, 6738, 13946, 1330, 1635, 198, 6738, 7652, 1330, 1635, 628, 198, 9688, 62, 2435, 796, 4818, 8079,...
2.322357
577
# Lint as: python3 # Copyright 2019 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for haiku._src.stateful.""" from absl.testing import absltest from haiku._src import base from haiku._src import module from haiku._src import stateful from haiku._src import test_utils from haiku._src import transform import jax import jax.numpy as jnp import numpy as np def _callback_prim(forward, backward): prim = jax.core.Primitive("hk_callback") prim.def_impl(f_impl) prim.def_abstract_eval(f_impl) jax.ad.deflinear(prim, b_impl) return prim.bind class CountingModule(module.Module): class SquareModule(module.Module): if __name__ == "__main__": absltest.main()
[ 2, 406, 600, 355, 25, 21015, 18, 198, 2, 15069, 13130, 10766, 28478, 21852, 15302, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 4...
3.493369
377
# -*- coding: utf-8 -*- """ Wrapper for RoBO """ __descr__ = "TODO" __license__ = "BSD 3-Clause" __author__ = u"Epistmio" __author_short__ = u"Epistmio" __author_email__ = "xavier.bouthillier@umontreal.ca" __copyright__ = u"2021, Epistmio" __url__ = "https://github.com/Epistimio/orion.algo.robo" from ._version import get_versions __version__ = get_versions()["version"] del get_versions
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 36918, 2848, 329, 5564, 8202, 198, 37811, 198, 198, 834, 20147, 81, 834, 796, 366, 51, 3727, 46, 1, 198, 834, 43085, 834, 796, 366, 21800, 513, 12, 2601, ...
2.375758
165
""" Znale kt , przy ktrym zasig skoku z wahada bdzie maksymalny. Naley posuy si metod zotego podziau. Mateusz Ostrowski Index:216708 """ import matplotlib.pyplot as plt import numpy as np while True: h0 = input("podaj wysokosc:") line0 = input("podaj dugo liny:") a00 = input("podaj amplitude waha W stopniach:") if int(line0) > int(h0): print("Error: wysoko mniejsza od dugoci liny!!!") else: break fig = plt.figure() ax = fig.add_subplot(111) a = Zloty_podzial(h0, line0, a00) ax.plot(a.xw, a.f(a.xw, a.a0, a.h, a.line), "-b") plt.show()
[ 37811, 198, 57, 77, 1000, 479, 83, 837, 778, 7357, 479, 28311, 76, 1976, 292, 328, 1341, 11601, 1976, 266, 993, 4763, 275, 67, 49746, 285, 461, 1837, 7617, 3281, 13, 399, 16730, 198, 1930, 4669, 33721, 1138, 375, 1976, 1258, 2188, 2...
1.970968
310
from app.database import MOCK_PRODUCT_DATA import re from app.products.base_handler import BaseHandler
[ 6738, 598, 13, 48806, 1330, 337, 11290, 62, 4805, 28644, 62, 26947, 198, 11748, 302, 198, 6738, 598, 13, 29498, 13, 8692, 62, 30281, 1330, 7308, 25060, 198 ]
3.678571
28
import sys import copy import pprint pp = pprint.PrettyPrinter(width=120) import inspect import numpy as np from .. import __version__ from .. import qcvars from ..driver.driver_helpers import print_variables from ..exceptions import * from ..molecule import Molecule from ..pdict import PreservingDict from .worker import psi4_subprocess from .botanist import muster_inherited_options def psi4_harvest(jobrec, psi4rec): # jobrec@i, psi4rec@io -> jobrec@io """Processes raw results from read-only `psi4rec` into QCAspect fields in returned `jobrec`.""" psi4rec = psi4rec['json'] # TODO NOT how this should be done figure out 1-tier/2-tier try: pass #jobrec['molecule']['real'] #jobrec['do_gradient'] except KeyError as err: raise KeyError( 'Required fields missing from ({})'.format(jobrec.keys())) from err try: psi4rec['raw_output'] #if jobrec['do_gradient'] is True: # dftd3rec['dftd3_gradient'] except KeyError as err: raise KeyError('Required fields missing from ({})'.format( psi4rec.keys())) from err if psi4rec['error']: raise RuntimeError(psi4rec['error']) #c4files = {} for fl in psi4rec.keys(): if fl.startswith('outfile_'): jobrec[fl] = psi4rec[fl] #for fl in ['GRD', 'FCMFINAL', 'DIPOL']: # field = 'output_' + fl.lower() # if field in cfourrec: # text += ' Cfour scratch file {} has been read\n'.format(fl) # text += cfourrec[field] # c4files[fl] = cfourrec[field] # Absorb results into qcdb data structures progvars = PreservingDict(psi4rec['psivars']) import psi4 progarrs = {k: np.array(psi4.core.Matrix.from_serial(v)) for k, v in psi4rec['psiarrays'].items()} progvars.update(progarrs) qcvars.build_out(progvars) calcinfo = qcvars.certify(progvars) jobrec['raw_output'] = psi4rec['raw_output'] jobrec['qcvars'] = calcinfo #prov = {} #prov['creator'] = 'Psi4' #prov['routine'] = sys._getframe().f_code.co_name #prov['version'] = version jobrec['provenance'].append(psi4rec['provenance']) return jobrec """ Required Input Fields --------------------- Optional Input Fields --------------------- Output Fields ------------- """
[ 11748, 25064, 198, 11748, 4866, 198, 11748, 279, 4798, 198, 381, 796, 279, 4798, 13, 35700, 6836, 3849, 7, 10394, 28, 10232, 8, 198, 11748, 10104, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 11485, 1330, 11593, 9641, 834, ...
2.421268
978
from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 26791, 1330, 640, 11340, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 13, 12683, 874, 133...
3.537037
54
#Main Sedov Code Module #Ported to python from fortran code written by James R Kamm and F X Timmes #Original Paper and code found at http://cococubed.asu.edu/papers/la-ur-07-2849.pdf import numpy as np from globalvars import comvars as gv from sedov_1d import sed_1d from sedov_1d_time import sed_1d_time from matplotlib import pyplot as plt import pickle gv.its = 20 # define sedov_main as a function #define function to produce results at different points in time instead of sedov_1d #final graph plots scaled density, pressure and velocity one one plot. # plt.plot(zpos, den/max(den), 'b', label = 'Density') # plt.plot(zpos, pres/max(pres), 'g', label = 'Pressure') # plt.plot(zpos, vel/max(vel), 'r', label = 'Velocity') # plt.axis([0, zmax, 0, 1]) # plt.legend(loc = 'upper left') # plt.title('Scaled Density, Pressure, and Velocity') # plt.ylabel('Scaled Value (x/max(x))') # plt.xlabel('Position (m)') # plt.show()
[ 2, 13383, 22710, 709, 6127, 19937, 201, 201, 198, 2, 47, 9741, 284, 21015, 422, 329, 2213, 272, 2438, 3194, 416, 3700, 371, 509, 6475, 290, 376, 1395, 5045, 6880, 201, 201, 198, 2, 20556, 14962, 290, 2438, 1043, 379, 2638, 1378, 66,...
2.035088
570
from lib import action
[ 6738, 9195, 1330, 2223, 628 ]
4.8
5
import unittest from typing import Dict, List from src.math_challenge import Challenge, DEFAULT_EMPTY_ANS from src.student_info import StudentInfo if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 6738, 19720, 1330, 360, 713, 11, 7343, 198, 198, 6738, 12351, 13, 11018, 62, 36747, 3540, 1330, 13879, 11, 5550, 38865, 62, 39494, 9936, 62, 15037, 198, 6738, 12351, 13, 50139, 62, 10951, 1330, 13613, 12360, ...
3.046154
65
import hlt import logging from collections import OrderedDict # GAME START game = hlt.Game("Spoof_v7") logging.info('Starting my %s bot!', game._name) TURN = 0 while True: # TURN START TURN += 1 group_attack_limit = 3 attack_ship_modifier = .4 game_map = game.update_map() command_queue = [] me = game_map.get_me() enemies = [enemy for enemy in game_map.all_players() if enemy.id != me.id] my_ships = me.all_ships() my_docked_ships = [ship for ship in my_ships if ship.docking_status != ship.DockingStatus.UNDOCKED] #planet_docking_status = [] enemy_ships = [ship for ship in game_map._all_ships() if ship not in my_ships] docked_enemy_ships = [ship for ship in enemy_ships if ship.docking_status != ship.DockingStatus.UNDOCKED] unowned_planets = [planet for planet in game_map.all_planets() if not planet.is_owned()] my_planets = [planet for planet in game_map.all_planets() if planet.is_owned() and planet.owner.id == me.id] enemy_planets = [planet for planet in game_map.all_planets() if planet.is_owned() and planet.owner.id != me.id] targeted_planets = [] targeted_ships = [] # find center of enemy mass planet_x = [planet.x for planet in enemy_planets] ship_x = [ship.x for ship in enemy_ships] planet_y = [planet.y for planet in enemy_planets] ship_y = [ship.y for ship in enemy_ships] x = planet_x + ship_x y = planet_y + ship_y enemy_centroid = hlt.entity.Position(0,0) if len(x): enemy_centroid = hlt.entity.Position(sum(x) / len(x), sum(y) / len(y)) entities_by_distance_to_enemy_centroid = OrderedDict(sorted(game_map.nearby_entities_by_distance(enemy_centroid).items(), key=lambda t: t[0])) my_ships_by_distance_to_enemy_centroid = [entities_by_distance_to_enemy_centroid[distance][0] for distance in entities_by_distance_to_enemy_centroid if entities_by_distance_to_enemy_centroid[distance][0] in my_ships and entities_by_distance_to_enemy_centroid[distance][0] not in my_docked_ships] # adjust limits based on ship counts my_ship_count = len(my_ships) enemy_ship_count = len(enemy_ships) if my_ship_count > 0 and enemy_ship_count > 0: ratio = (my_ship_count / enemy_ship_count) if ratio > 1: group_attack_limit *= ratio # logging.info('group attack limit: %s', group_attack_limit) #logging.info(enemy_centroid) # find undocked ships that are closest to action and make them fighters first set the rest as miners attack_ships = my_ships_by_distance_to_enemy_centroid[0 : int(len(my_ships_by_distance_to_enemy_centroid) * attack_ship_modifier)] # logging.info('Number of attack ships: %s', len(attack_ships)) # For every ship that I control for ship in my_ships: # If the ship is docked if ship.docking_status != ship.DockingStatus.UNDOCKED: # Skip this ship continue entities_by_distance = OrderedDict(sorted(game_map.nearby_entities_by_distance(ship).items(), key=lambda t: t[0])) target_planets = [entities_by_distance[distance][0] for distance in entities_by_distance if entities_by_distance[distance][0] in game_map.all_planets() and entities_by_distance[distance][0] not in targeted_planets] target_unowned_planets = [entities_by_distance[distance][0] for distance in entities_by_distance if entities_by_distance[distance][0] in unowned_planets and entities_by_distance[distance][0] not in targeted_planets] target_enemy_planets = [entities_by_distance[distance][0] for distance in entities_by_distance if entities_by_distance[distance][0] in enemy_planets] target_ships = [entities_by_distance[distance][0] for distance in entities_by_distance if entities_by_distance[distance][0] in enemy_ships] target_docked_ships = [entities_by_distance[distance][0] for distance in entities_by_distance if entities_by_distance[distance][0] in docked_enemy_ships] # if ship in attack_ships attack if ship in attack_ships: for enemy_ship in target_ships: # if unowned planet is closer, then dock, otherwise attack # if target_unowned_planets[0]: # if ship.calculate_distance_between(target_unowned_planets[0]) < ship.calculate_distance_between(enemy_ship): # if ship.can_dock(target_unowned_planets[0]): # command_queue.append(ship.dock(target_unowned_planets[0])) # else: # navigate(ship, enemy_ship, 1) # else: # if enemy is targeted by n ships then get next closest ship if enemy_ship in targeted_ships: if targeted_ships.count(enemy_ship) >= group_attack_limit: # logging.info('group attack limit met, trying next ship') continue targeted_ships.append(enemy_ship) navigate(ship, enemy_ship, 1) break else: for planet in target_planets: # If we can dock, let's (try to) dock. If two ships try to dock at once, neither will be able to. if ship.can_dock(planet) and planet in unowned_planets: command_queue.append(ship.dock(planet)) elif ship.can_dock(planet) and planet in my_planets and not planet.is_full(): command_queue.append(ship.dock(planet)) # if planet is owned then attack elif planet.is_owned() and planet in enemy_planets: for enemy_ship in planet.all_docked_ships(): if enemy_ship: navigate(ship, enemy_ship) break else: targeted_planets.append(planet) navigate(ship, planet) break # Send our set of commands to the Halite engine for this turn game.send_command_queue(command_queue) # TURN END # GAME END
[ 11748, 289, 2528, 198, 11748, 18931, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 198, 2, 30517, 33303, 198, 6057, 796, 289, 2528, 13, 8777, 7203, 4561, 37711, 62, 85, 22, 4943, 198, 6404, 2667, 13, 10951, 10786, 22851, 616, 406...
2.294853
2,720
import pytest from eph.horizons import *
[ 11748, 12972, 9288, 198, 198, 6738, 304, 746, 13, 17899, 29457, 1330, 1635, 628, 628, 628, 628, 628, 628, 628, 628, 198 ]
2.636364
22
# -*- coding: utf-8 -*- import time import sqs_service """Usage: python demo.py Expected set environment variables: - AWS_ACCESS_KEY_ID - AWS_SECRET_ACCESS_KEY - AWS_DEFAULT_REGION - AWS_SESSION_TOKEN for IAM roles - AWS_SECURITY_TOKEN for IAM roles Send 'Hello World' to queue 'TEST', listen to the queue and print first message received """ if __name__ == '__main__': run()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 640, 198, 198, 11748, 19862, 82, 62, 15271, 198, 198, 37811, 28350, 25, 198, 29412, 13605, 13, 9078, 198, 198, 3109, 7254, 900, 2858, 9633, 25, 198, 12, 30...
2.713287
143
# Copyright 2020 The FedLearner Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding: utf-8 import json from google.protobuf.json_format import MessageToDict from fedlearner_webconsole.proto.workflow_definition_pb2 import ( WorkflowDefinition, JobDefinition, JobDependency ) from fedlearner_webconsole.proto.common_pb2 import ( Variable ) if __name__ == '__main__': print(json.dumps(MessageToDict( make_workflow_template(), preserving_proto_field_name=True, including_default_value_fields=True)))
[ 2, 15069, 12131, 383, 10169, 14961, 1008, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846...
3.25228
329
import os import shutil
[ 11748, 28686, 198, 11748, 4423, 346, 628, 198 ]
3.25
8
import os import bz2 import json import random import pickle from collections import defaultdict, Counter from tqdm import tqdm import torch from data.crosswoz.data_process.dst.trade_preprocess import ( EXPERIMENT_DOMAINS, Lang, get_seq, get_slot_information, ) def fix_general_label_error(belief_state): """ :param belief_state: "belief_state": [ { "slots": [ [ "-", " " ] ] }, { "slots": [ [ "-", "100 - 150 " ] ] } ] :return: """ belief_state_dict = { slot_value["slots"][0][0]: slot_value["slots"][0][1] for slot_value in belief_state } return belief_state_dict
[ 11748, 28686, 198, 11748, 275, 89, 17, 198, 11748, 33918, 198, 11748, 4738, 198, 11748, 2298, 293, 198, 6738, 17268, 1330, 4277, 11600, 11, 15034, 198, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 198, 11748, 28034, 198, 198, ...
1.779835
486
from django.conf.urls import url from django.views.generic import TemplateView from reports import views urlpatterns = [ url(r'balance/$', views.balance, name='report_balance'), url(r'performance/$', views.performance, name='report_performance'), url(r'last_activity/$', views.last_activity, name='last_activity'), url(r'collection/$', views.CollectionListView.as_view(), name='report_collection'), url(r'saleschart/$', TemplateView.as_view( template_name='reports/sales_chart.html'), name='chart_sales'), url(r'paymentchart/$', TemplateView.as_view( template_name='reports/payment_chart.html'), name='chart_payment'), url(r'callchart/$', TemplateView.as_view( template_name='reports/calls_chart.html'), name='chart_call'), ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 6738, 42625, 14208, 13, 33571, 13, 41357, 1330, 37350, 7680, 198, 198, 6738, 3136, 1330, 5009, 628, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 19016, 7, 81, 6, ...
2.848375
277
from pycam.Utils.events import get_event_handler, get_mainloop
[ 6738, 12972, 20991, 13, 18274, 4487, 13, 31534, 1330, 651, 62, 15596, 62, 30281, 11, 651, 62, 12417, 26268, 628 ]
3.2
20
#!/usr/bin/env python3 # This file is covered by the LICENSE file in the root of this project. import zipfile import argparse import os if __name__ == "__main__": parser = argparse.ArgumentParser( description="Validate a submission zip file needed to evaluate on CodaLab competitions.\n\nThe verification tool checks:\n 1. correct folder structure,\n 2. existence of label files for each scan,\n 3. count of labels for each scan.\nInvalid labels are ignored by the evaluation script, therefore we don't check\nfor invalid labels.", formatter_class=argparse.RawTextHelpFormatter) parser.add_argument( "zipfile", type=str, help='zip file that should be validated.', ) parser.add_argument( 'dataset', type=str, help='directory containing the folder "sequences" containing folders "11", ..., "21" with the "velodyne" files.' ) parser.add_argument( "--task", type=str, choices=["segmentation"], default="segmentation", help='task for which the zip file should be validated.' ) FLAGS, _ = parser.parse_known_args() checkmark = "\u2713" try: print('Validating zip archive "{}".\n'.format(FLAGS.zipfile)) print(" 1. Checking filename.............. ", end="", flush=True) if not FLAGS.zipfile.endswith('.zip'): raise ValidationException('Competition bundle must end with ".zip"') print(checkmark) with zipfile.ZipFile(FLAGS.zipfile) as zipfile: if FLAGS.task == "segmentation": print(" 2. Checking directory structure... ", end="", flush=True) directories = [folder.filename for folder in zipfile.infolist() if folder.filename.endswith("/")] if "sequences/" not in directories: raise ValidationException('Directory "sequences" missing inside zip file.') for sequence in range(11, 22): sequence_directory = "sequences/{}/".format(sequence) if sequence_directory not in directories: raise ValidationException('Directory "{}" missing inside zip file.'.format(sequence_directory)) predictions_directory = sequence_directory + "predictions/" if predictions_directory not in directories: raise ValidationException('Directory "{}" missing inside zip file.'.format(predictions_directory)) print(checkmark) print(' 3. Checking file sizes............ ', end='', flush=True) prediction_files = {info.filename: info for info in zipfile.infolist() if not info.filename.endswith("/")} for sequence in range(11, 22): sequence_directory = 'sequences/{}'.format(sequence) velodyne_directory = os.path.join(FLAGS.dataset, 'sequences/{}/velodyne/'.format(sequence)) velodyne_files = sorted([os.path.join(velodyne_directory, file) for file in os.listdir(velodyne_directory)]) label_files = sorted([os.path.join(sequence_directory, "predictions", os.path.splitext(filename)[0] + ".label") for filename in os.listdir(velodyne_directory)]) for velodyne_file, label_file in zip(velodyne_files, label_files): num_points = os.path.getsize(velodyne_file) / (4 * 4) if label_file not in prediction_files: raise ValidationException('"' + label_file + '" is missing inside zip.') num_labels = prediction_files[label_file].file_size / 4 if num_labels != num_points: raise ValidationException('label file "' + label_file + "' should have {} labels, but found {} labels!".format(int(num_points), int(num_labels))) print(checkmark) else: # TODO scene completion. raise NotImplementedError("Unknown task.") except ValidationException as ex: print("\n\n " + "\u001b[1;31m>>> Error: " + str(ex) + "\u001b[0m") exit(1) print("\n\u001b[1;32mEverything ready for submission!\u001b[0m \U0001F389")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 770, 2393, 318, 5017, 416, 262, 38559, 24290, 2393, 287, 262, 6808, 286, 428, 1628, 13, 198, 198, 11748, 19974, 7753, 198, 11748, 1822, 29572, 198, 11748, 28686, 628, 198, 198, ...
2.643663
1,507
#! /usr/bin/env python # License: Apache 2.0. See LICENSE file in root directory. # # For simple behaviors that can run syncronously, Python provides # a simple way to implement this. Add the work of your behavior # in the execute_cb callback # import rospy import actionlib import behavior_common.msg import time import random from std_msgs.msg import Float64 from std_msgs.msg import UInt16 from std_msgs.msg import UInt32 from std_msgs.msg import Bool from std_msgs.msg import Empty # for talking import actionlib import actionlib.action_client import audio_and_speech_common.msg # for servos #from sheldon_servos.head_servo_publishers import * #from sheldon_servos.right_arm_servo_publishers import * #from sheldon_servos.left_arm_servo_publishers import * from sheldon_servos.standard_servo_positions import * from sheldon_servos.set_servo_speed import * from sheldon_servos.set_servo_torque import * if __name__ == '__main__': rospy.init_node('ship_behavior') server = BehaviorAction(rospy.get_name()) rospy.spin()
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 13789, 25, 24843, 362, 13, 15, 13, 4091, 38559, 24290, 2393, 287, 6808, 8619, 13, 198, 2, 198, 2, 1114, 2829, 14301, 326, 460, 1057, 17510, 1313, 3481, 11, 11361, 3769, 198, 2...
2.930168
358
from collections import defaultdict, namedtuple import torch # When using the sliding window trick for long sequences, # we take the representation of each token with maximal context. # Take average of the BERT embeddings of these BPE sub-tokens # as the embedding for the word. # Take *weighted* average of the word embeddings through all layers. def _check_is_max_context(doc_spans, cur_span_index, position): """Check if this is the 'max context' doc span for the token.""" # Because of the sliding window approach taken to scoring documents, a single # token can appear in multiple documents. E.g. # Doc: the man went to the store and bought a gallon of milk # Span A: the man went to the # Span B: to the store and bought # Span C: and bought a gallon of # ... # # Now the word 'bought' will have two scores from spans B and C. We only # want to consider the score with "maximum context", which we define as # the *minimum* of its left and right context (the *sum* of left and # right context will always be the same, of course). # # In the example the maximum context for 'bought' would be span C since # it has 1 left context and 3 right context, while span B has 4 left context # and 0 right context. best_score = None best_span_index = None for (span_index, doc_span) in enumerate(doc_spans): end = doc_span.start + doc_span.length - 1 if position < doc_span.start: continue if position > end: continue num_left_context = position - doc_span.start num_right_context = end - position score = min(num_left_context, num_right_context) + 0.01 * doc_span.length if best_score is None or score > best_score: best_score = score best_span_index = span_index return cur_span_index == best_span_index
[ 6738, 17268, 1330, 4277, 11600, 11, 3706, 83, 29291, 198, 198, 11748, 28034, 628, 198, 2, 1649, 1262, 262, 22292, 4324, 6908, 329, 890, 16311, 11, 198, 2, 356, 1011, 262, 10552, 286, 1123, 11241, 351, 40708, 4732, 13, 198, 2, 7214, ...
3.24237
557
from rest_framework import serializers from .models import Lecture
[ 6738, 1334, 62, 30604, 1330, 11389, 11341, 198, 6738, 764, 27530, 1330, 31209, 495, 198 ]
4.466667
15
from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('', (r'^$', 'suggestions.views.list_all'), (r'^post/$', 'suggestions.views.add_suggestion'), (r'^vote/(?P<suggestion_id>.*)/$', 'suggestions.views.add_vote'), (r'^unvote/(?P<suggestion_id>.*)/$', 'suggestions.views.remove_vote'), (r'^close/(?P<suggestion_id>.*)/$', 'suggestions.views.close'), )
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 13, 12286, 82, 1330, 7572, 11, 2291, 11, 19016, 198, 198, 6371, 33279, 82, 796, 7572, 10786, 3256, 198, 220, 220, 357, 81, 6, 61, 3, 3256, 705, 47811, 507, 13, 33571, 13, 4868, 62, 439,...
2.459627
161
#Esse codigo utilizado para calcular a fronteira eficiente de um portfolio #Esse codigo tem como objetivo avaliar a eficiencia das de um portfolio import numpy as np import pandas as pd import matplotlib.pyplot as plt from pandas_datareader import data as wb assets = ['PG', '^GSPC'] pf_data = pd.DataFrame() for a in assets: pf_data[a] = wb.DataReader(a, data_source='yahoo', start='2010-1-1')['Adj Close'] pf_data.tail() (pf_data / pf_data.iloc[0] * 100).plot(figsize=(10, 5)) log_returns = np.log(pf_data / pf_data.shift(1)) log_returns.mean() * 250 log_returns['PG'].cov(log_returns['^GSPC']) * 250 #Correlacao superior a 30% indica que sao muito correlacionados, isso bom log_returns['PG'].corr(log_returns['^GSPC']) #Agora vamos aprtir pra uma otimizacao do portfolio por uma perspectiva mais tecnica #Vamos criar uma variavel que ira contar o numero de ativos na nossa carteira num_assets = len(assets) #Agora iremos criar dois pesos alatorios para esses ativos #O metodo random.random pode gerar dois numeros aleatorios entre o e 1 arr = np.random.random(2) #Vamos calcular a soma do valor dos dois pesos obtidos aleatoriamente arr[0] + arr[1] #A soma desses pesos aleatorios nem sempre sera igual a 1 #Para fazer com que a soma seja = 1, temos weights = np.random.random(num_assets) weights /= np.sum(weights) print(weights) #O codigo /= significa o peso, dividido pela soma dos pesos, como um loop #Lembrando, quando se usa o numpy estamos transformando esses valores em elementos da matriz #Por isso quando atribuimos esse codigo a soma dos pesos igual a 1 #Para escrever o retorno esperado de um portfolio: #Retorno = soma do produto da media dos retornos logaritmicos anualizados pelo seus respectivos pesos #Essa funcao .sun do numpy, funciona somando objetos em mais de uma dimensao, por isso difere do sum(nativo do python) np.sum(weights * log_returns.mean()) * 250 #Esse codigo como ja foi visto fornece a variancia np.dot(weights.T, np.dot(log_returns['PG'].cov(log_returns['^GSPC']) * 250, weights)) #Esse codigo como ja foi visto fornece a volatilidade np.sqrt(np.dot(weights.T, np.dot(log_returns['PG'].cov(log_returns['^GSPC']) * 250, weights))) #Usaremos esses 3 codigos para calcular o retorno e a volatilidade na simulacao dos portfolios de minima variancia #Agora iremos criar um grafico onde mil simulacoes de minima variancia serao plotadas #Nao estamos fazendo 1000 investimentos diferentes #estamos fazendo 1000 combinacoes dos mesmos ativos(pesos) #Esse loop, gerara uma repeticao de 1000 possibilidades para os pesos dos ativos pfolio_returns = [] pfolio_volatilities = [] for x in range (1000): weights = np.random.random(num_assets) weights /= np.sum(weights) pfolio_returns.append(np.sum(weights * log_returns.mean()) * 250) pfolio_volatilities.append(np.sqrt(np.dot(weights.T, np.dot(log_returns['PG'].cov(log_returns['^GSPC']) * 250, weights)))) #Fazemos isso para transformar os numeros dispersos, em arrays contidos numa matriz, fica mais pratico de trabalhar pfolio_returns = np.array(pfolio_returns) pfolio_volatilities = np.array(pfolio_volatilities) pfolio_volatilities,pfolio_returns #Agora iremos criar um objeto no dataframe com duas colunas, uma para os retornos e outra para as respectivas volatilidades portfolios = pd.DataFrame({'Return': pfolio_returns, 'Volatility': pfolio_volatilities}) portfolios.head() portfolios.tail() #Agora estamos plotando os valores do dataframe num grafico #O tipo de grafico que estamos inserindo to tipo scatter (grafico de dispersao) portfolios.plot(x='Volatility', y='Return', kind='scatter', figsize=(10, 6)) plt.xlabel('Expected Volatility') plt.ylabel('Expected Return') plt.show()
[ 2, 23041, 325, 14873, 14031, 220, 7736, 528, 4533, 31215, 2386, 10440, 257, 1216, 38599, 8704, 304, 69, 11373, 68, 390, 23781, 15320, 201, 198, 2, 23041, 325, 14873, 14031, 2169, 401, 78, 26181, 316, 23593, 1196, 7344, 283, 257, 304, ...
2.474903
1,554
""" Tests for the wily build command. All of the following tests will use a click CLI runner to fully simulate the CLI. Many of the tests will depend on a "builddir" fixture which is a compiled wily cache. TODO : Test build + build with extra operator """ import pathlib import pytest from click.testing import CliRunner from git import Repo, Actor from mock import patch import wily.__main__ as main from wily.archivers import ALL_ARCHIVERS def test_build_not_git_repo(tmpdir): """ Test that build defaults to filesystem in a non-git directory """ with patch("wily.logger") as logger: runner = CliRunner() result = runner.invoke(main.cli, ["--path", tmpdir, "build", "test.py"]) assert result.exit_code == 0, result.stdout cache_path = tmpdir / ".wily" assert cache_path.exists() index_path = tmpdir / ".wily" / "filesystem" / "index.json" assert index_path.exists() def test_build_invalid_path(tmpdir): """ Test that build fails with a garbage path """ with patch("wily.logger") as logger: runner = CliRunner() result = runner.invoke(main.cli, ["--path", "/fo/v/a", "build", "test.py"]) assert result.exit_code == 1, result.stdout def test_build_no_target(tmpdir): """ Test that build fails with no target """ with patch("wily.logger") as logger: runner = CliRunner() result = runner.invoke(main.cli, ["--path", tmpdir, "build"]) assert result.exit_code == 2, result.stdout def test_build_crash(tmpdir): """ Test that build works in a basic repository. """ repo = Repo.init(path=tmpdir) tmppath = pathlib.Path(tmpdir) # Write a test file to the repo with open(tmppath / "test.py", "w") as test_txt: test_txt.write("import abc") with open(tmppath / ".gitignore", "w") as test_txt: test_txt.write(".wily/") index = repo.index index.add(["test.py", ".gitignore"]) author = Actor("An author", "author@example.com") committer = Actor("A committer", "committer@example.com") index.commit("basic test", author=author, committer=committer) import wily.commands.build with patch.object( wily.commands.build.Bar, "finish", side_effect=RuntimeError("arggh") ) as bar_finish: runner = CliRunner() result = runner.invoke(main.cli, ["--path", tmpdir, "build", "test.py"]) assert bar_finish.called_once assert result.exit_code == 1, result.stdout with patch("wily.commands.build.logger") as logger: logger.level = "DEBUG" with patch.object( wily.commands.build.Bar, "finish", side_effect=RuntimeError("arggh") ) as bar_finish: runner = CliRunner() result = runner.invoke( main.cli, ["--debug", "--path", tmpdir, "build", "test.py"] ) assert bar_finish.called_once assert result.exit_code == 1, result.stdout def test_build(tmpdir): """ Test that build works in a basic repository. """ repo = Repo.init(path=tmpdir) tmppath = pathlib.Path(tmpdir) # Write a test file to the repo with open(tmppath / "test.py", "w") as test_txt: test_txt.write("import abc") with open(tmppath / ".gitignore", "w") as test_txt: test_txt.write(".wily/") index = repo.index index.add(["test.py", ".gitignore"]) author = Actor("An author", "author@example.com") committer = Actor("A committer", "committer@example.com") commit = index.commit("basic test", author=author, committer=committer) with patch("wily.logger") as logger: runner = CliRunner() result = runner.invoke( main.cli, ["--debug", "--path", tmpdir, "build", "test.py"] ) assert result.exit_code == 0, result.stdout cache_path = tmpdir / ".wily" assert cache_path.exists() index_path = tmpdir / ".wily" / "git" / "index.json" assert index_path.exists() rev_path = tmpdir / ".wily" / "git" / commit.name_rev.split(" ")[0] + ".json" assert rev_path.exists() def test_build_twice(tmpdir): """ Test that build works when run twice. """ repo = Repo.init(path=tmpdir) tmppath = pathlib.Path(tmpdir) # Write a test file to the repo with open(tmppath / "test.py", "w") as test_txt: test_txt.write("import abc") with open(tmppath / ".gitignore", "w") as test_txt: test_txt.write(".wily/") index = repo.index index.add(["test.py", ".gitignore"]) author = Actor("An author", "author@example.com") committer = Actor("A committer", "committer@example.com") commit = index.commit("basic test", author=author, committer=committer) runner = CliRunner() result = runner.invoke(main.cli, ["--debug", "--path", tmpdir, "build", "test.py"]) assert result.exit_code == 0, result.stdout cache_path = tmpdir / ".wily" assert cache_path.exists() index_path = tmpdir / ".wily" / "git" / "index.json" assert index_path.exists() rev_path = tmpdir / ".wily" / "git" / commit.name_rev.split(" ")[0] + ".json" assert rev_path.exists() # Write a test file to the repo with open(tmppath / "test.py", "w") as test_txt: test_txt.write("import abc\nfoo = 1") index.add(["test.py"]) commit2 = index.commit("basic test", author=author, committer=committer) result = runner.invoke(main.cli, ["--debug", "--path", tmpdir, "build", "test.py"]) assert result.exit_code == 0, result.stdout cache_path = tmpdir / ".wily" assert cache_path.exists() index_path = tmpdir / ".wily" / "git" / "index.json" assert index_path.exists() rev_path = tmpdir / ".wily" / "git" / commit.name_rev.split(" ")[0] + ".json" assert rev_path.exists() rev_path2 = tmpdir / ".wily" / "git" / commit2.name_rev.split(" ")[0] + ".json" assert rev_path2.exists() def test_build_no_commits(tmpdir): """ Test that build fails cleanly with no commits """ repo = Repo.init(path=tmpdir) runner = CliRunner() result = runner.invoke( main.cli, ["--debug", "--path", tmpdir, "build", tmpdir, "--skip-ignore-check"] ) assert result.exit_code == 1, result.stdout def test_build_dirty_repo(builddir): """ Test that build fails cleanly with a dirty repo """ tmppath = pathlib.Path(builddir) with open(tmppath / "test.py", "w") as test_txt: test_txt.write("import abc\nfoo = 1") runner = CliRunner() result = runner.invoke(main.cli, ["--debug", "--path", builddir, "build", builddir]) assert result.exit_code == 1, result.stdout archivers = {name for name in ALL_ARCHIVERS.keys()}
[ 37811, 198, 51, 3558, 329, 262, 266, 813, 1382, 3141, 13, 198, 198, 3237, 286, 262, 1708, 5254, 481, 779, 257, 3904, 43749, 17490, 284, 3938, 29308, 262, 43749, 13, 198, 7085, 286, 262, 5254, 481, 4745, 319, 257, 366, 11249, 15908, ...
2.474166
2,729
import unittest from zmq_integration_lib import RPCClient, RPCServer import unittest.mock as mock
[ 11748, 555, 715, 395, 198, 6738, 1976, 76, 80, 62, 18908, 1358, 62, 8019, 1330, 39400, 11792, 11, 39400, 10697, 198, 11748, 555, 715, 395, 13, 76, 735, 355, 15290, 628, 220, 220, 220, 220, 198 ]
2.888889
36
import os import numpy as np import tqdm as tqdm cvtData.cvt_Data() print('done')
[ 11748, 28686, 220, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 256, 80, 36020, 355, 256, 80, 36020, 201, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 2...
1.418803
117
############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Define runtime information view component for Application Control """ __docformat__ = 'restructuredtext' from zope.app.applicationcontrol.interfaces import IRuntimeInfo from zope.app.applicationcontrol.i18n import ZopeMessageFactory as _
[ 29113, 29113, 7804, 4242, 2235, 198, 2, 198, 2, 15069, 357, 66, 8, 5878, 11, 6244, 1168, 3008, 5693, 290, 25767, 669, 13, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 770, 3788, 318, 2426, 284, 262, 8617, 286, 262, 1168, 3008, ...
4.101852
216
import json import os.path
[ 11748, 33918, 198, 11748, 28686, 13, 6978, 628 ]
3.5
8
import ndex.client as nc from ndex.networkn import NdexGraph import io import json from IPython.display import HTML from time import sleep import os, time, tempfile import sys import time import logging import grpc import networkx as nx import cx_pb2 import cx_pb2_grpc import numpy as np import inspect from concurrent import futures from itertools import combinations from subprocess import Popen, PIPE, STDOUT import pandas as pd from ddot import Ontology, align_hierarchies from ddot.utils import update_nx_with_alignment from ddot.cx_services.cx_utils import yield_ndex, required_params, cast_params from ddot.config import default_params _ONE_DAY_IN_SECONDS = 60 * 60 * 24 verbose = True if __name__ == '__main__': logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s %(message)s') log_info("Listening for requests on '0.0.0.0:8081'") serve()
[ 11748, 299, 67, 1069, 13, 16366, 355, 299, 66, 198, 6738, 299, 67, 1069, 13, 27349, 77, 1330, 399, 67, 1069, 37065, 198, 198, 11748, 33245, 198, 11748, 33918, 198, 6738, 6101, 7535, 13, 13812, 1330, 11532, 198, 6738, 640, 1330, 3993, ...
2.940789
304
""" OPENSIGNALSFACTORY PACKAGE INITIALISATION FILE (WITH IMPORT STATEMENTS) The main purpose of biosignalsnotebooks package is to support the users of PLUX acquisition devices, such as biosgnalsplux or bitalino, in some processing tasks that can be applied to the acquired electrophysiological signals, namely ECG, EMG... This package had been developed as part of the "OpenSignals Tools" project, that offers a set of Jupyter Notebooks (tutorials) where it is explained step by step how the user can execute the previously mentioned processing tasks (such as detection of muscular activation from EMG signal, determination of each cardiac cycle duration from an ECG acquisition or monitoring fatigue by generating EMG median power frequency evolution time series). At the end of each Notebook is referred the correspondent biosignalsnotebooks function that synthesises the processing functionality presented step by step. In spite of being 'part' of an integrate solution for OpenSignals users, this package can be used independently. Package Documentation --------------------- The docstring presented as the initial statement of each module function will help the user to correctly and effectively use all biosignalsnotebooks functions. A full guide that collects all the function docstring is available for download at: ... OpenSignals Tools Project Repository ------------------------------------ More information's about the project and the respective files are available at: https://github.com/biosignalsplux/biosignalsnotebooks Available Modules ----------------- aux_functions Includes a set of auxiliary functions that are invoked in other biosignalsnotebooks modules. This module has a 'private' classification, i.e., it was not specially designed for users. __notebook_support__ Set of functions invoked in OpenSignals Tools Notebooks to present some graphical results. These function are only designed for a single end, but we made them available to the user if he want to explore graphical functionalities in an example format. conversion Module responsible for the definition of functions that convert Raw units (available in the acquisition files returned by OpenSignals) and sample units to physical units like mV, A, C, s,..., accordingly to the sensor under analysis. detect Contains functions intended to detect events on electrophysiological signals. extract Ensures to the user that he can extract multiple parameters from a specific electrophysiological signal at once. open Module dedicated to read/load data from .txt and .h5 files generated by OpenSignals. With the available functions the user can easily access data inside files (signal samples) together with the metadata in the file header. process Processing capabilities that are more general than the categories of the remaining modules. signal_samples A module that gives an easy access to the biosignalsnotebooks dataset/library of signals (used in OpenSignals Tools Notebooks). visualise Graphical data representation functions based on the application of Bokeh main functionalities. /\ """ from .conversion import * from .detect import * from .extract import * from .load import * from .process import * from .visualise import * from .signal_samples import * from .factory import * from .synchronisation import * from .train_and_classify import * from .__notebook_support__ import * from .synchronisation import * # 11/10/2018 16h45m :)
[ 37811, 198, 3185, 16938, 16284, 1847, 20802, 10659, 15513, 47035, 11879, 3268, 2043, 12576, 1797, 6234, 45811, 357, 54, 10554, 30023, 9863, 15486, 12529, 50, 8, 198, 198, 464, 1388, 4007, 286, 37140, 570, 874, 11295, 12106, 5301, 318, 284...
4.098131
856
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Base utilities for loading datasets.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import os import random import time import shutil from six.moves import urllib Dataset = collections.namedtuple('Dataset', ['data', 'target']) Datasets = collections.namedtuple('Datasets', ['train', 'validation', 'test']) _RETRIABLE_ERRNOS = { 110, # Connection timed out [socket.py] } def maybe_download(filename, work_directory, source_url): """Download the data from source url, unless it's already here. Args: filename: string, name of the file in the directory. work_directory: string, path to working directory. source_url: url to download from if file doesn't exist. Returns: Path to resulting file. """ if not os.path.exists(work_directory): os.makedirs(work_directory) filepath = os.path.join(work_directory, filename) if not os.path.exists(filepath): temp_file_name, _ = urlretrieve_with_retry(source_url) shutil.copy(temp_file_name, filepath) size = os.path.getsize(filepath) print('Successfully downloaded', filename, size, 'bytes.') return filepath
[ 2, 15069, 1584, 383, 309, 22854, 37535, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, ...
3.220199
604
from behave import given
[ 6738, 17438, 1330, 1813, 628 ]
5.2
5
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import sys import argparse import os import re import sqlite3 import requests import bs4 from termcolor import colored # Python2 compatibility if sys.version_info[0] == 2: reload(sys) sys.setdefaultencoding('utf-8') # Default database path is ~/.iSearch. DEFAULT_PATH = os.path.join(os.path.expanduser('~'), '.iSearch') CREATE_TABLE_WORD = ''' CREATE TABLE IF NOT EXISTS Word ( name TEXT PRIMARY KEY, expl TEXT, pr INT DEFAULT 1, aset CHAR[1], addtime TIMESTAMP NOT NULL DEFAULT (DATETIME('NOW', 'LOCALTIME')) ) ''' def colorful_print(raw): '''print colorful text in terminal.''' lines = raw.split('\n') colorful = True detail = False for line in lines: if line: if colorful: colorful = False print(colored(line, 'white', 'on_green') + '\n') continue elif line.startswith(''): print(line + '\n') continue elif line.startswith(''): print(colored(line, 'white', 'on_green') + '\n') detail = True continue if not detail: print(colored(line + '\n', 'yellow')) else: print(colored(line, 'cyan') + '\n') def normal_print(raw): ''' no colorful text, for output.''' lines = raw.split('\n') for line in lines: if line: print(line + '\n') def search_online(word, printer=True): '''search the word or phrase on http://dict.youdao.com.''' url = 'http://dict.youdao.com/w/ %s' % word expl = get_text(url) if printer: colorful_print(expl) return expl def search_database(word): '''offline search.''' conn = sqlite3.connect(os.path.join(DEFAULT_PATH, 'word.db')) curs = conn.cursor() curs.execute(r'SELECT expl, pr FROM Word WHERE name LIKE "%s%%"' % word) res = curs.fetchall() if res: print(colored(word + ' ', 'white', 'on_green')) print() print(colored(' ' * res[0][1], 'red'), colored(' ' * (5 - res[0][1]), 'yellow'), sep='') colorful_print(res[0][0]) else: print(colored(word + ' ', 'white', 'on_red')) search_online(word) input_msg = '(1~5) Enter \n>>> ' if sys.version_info[0] == 2: add_in_db_pr = raw_input(input_msg) else: add_in_db_pr = input(input_msg) if add_in_db_pr and add_in_db_pr.isdigit(): if(int(add_in_db_pr) >= 1 and int(add_in_db_pr) <= 5): add_word(word, int(add_in_db_pr)) print(colored(' {word} '.format(word=word), 'white', 'on_red')) curs.close() conn.close() def add_word(word, default_pr): '''add the word or phrase to database.''' conn = sqlite3.connect(os.path.join(DEFAULT_PATH, 'word.db')) curs = conn.cursor() curs.execute('SELECT expl, pr FROM Word WHERE name = "%s"' % word) res = curs.fetchall() if res: print(colored(word + ' ', 'white', 'on_red')) sys.exit() try: expl = search_online(word, printer=False) curs.execute('insert into word(name, expl, pr, aset) values ("%s", "%s", %d, "%s")' % ( word, expl, default_pr, word[0].upper())) except Exception as e: print(colored('something\'s wrong, you can\'t add the word', 'white', 'on_red')) print(e) else: conn.commit() print(colored('%s has been inserted into database' % word, 'green')) finally: curs.close() conn.close() def delete_word(word): '''delete the word or phrase from database.''' conn = sqlite3.connect(os.path.join(DEFAULT_PATH, 'word.db')) curs = conn.cursor() # search fisrt curs.execute('SELECT expl, pr FROM Word WHERE name = "%s"' % word) res = curs.fetchall() if res: try: curs.execute('DELETE FROM Word WHERE name = "%s"' % word) except Exception as e: print(e) else: print(colored('%s has been deleted from database' % word, 'green')) conn.commit() finally: curs.close() conn.close() else: print(colored('%s not exists in the database' % word, 'white', 'on_red')) def set_priority(word, pr): ''' set the priority of the word. priority(from 1 to 5) is the importance of the word. ''' conn = sqlite3.connect(os.path.join(DEFAULT_PATH, 'word.db')) curs = conn.cursor() curs.execute('SELECT expl, pr FROM Word WHERE name = "%s"' % word) res = curs.fetchall() if res: try: curs.execute('UPDATE Word SET pr= %d WHERE name = "%s"' % (pr, word)) except Exception as e: print(colored('something\'s wrong, you can\'t reset priority', 'white', 'on_red')) print(e) else: print(colored('the priority of %s has been reset to %s' % (word, pr), 'green')) conn.commit() finally: curs.close() conn.close() else: print(colored('%s not exists in the database' % word, 'white', 'on_red')) def list_letter(aset, vb=False, output=False): '''list words by letter, from a-z (ingore case).''' conn = sqlite3.connect(os.path.join(DEFAULT_PATH, 'word.db')) curs = conn.cursor() try: if not vb: curs.execute('SELECT name, pr FROM Word WHERE aset = "%s"' % aset) else: curs.execute('SELECT expl, pr FROM Word WHERE aset = "%s"' % aset) except Exception as e: print(colored('something\'s wrong, catlog is from A to Z', 'red')) print(e) else: if not output: print(colored(format(aset, '-^40s'), 'green')) else: print(format(aset, '-^40s')) for line in curs.fetchall(): expl = line[0] pr = line[1] print('\n' + '=' * 40 + '\n') if not output: print(colored(' ' * pr, 'red', ), colored(' ' * (5 - pr), 'yellow'), sep='') colorful_print(expl) else: print(' ' * pr + ' ' * (5 - pr)) normal_print(expl) finally: curs.close() conn.close() def list_priority(pr, vb=False, output=False): ''' list words by priority, like this: 1 : list words which the priority is 1, 2+ : list words which the priority is lager than 2, 3-4 : list words which the priority is from 3 to 4. ''' conn = sqlite3.connect(os.path.join(DEFAULT_PATH, 'word.db')) curs = conn.cursor() try: if not vb: if len(pr) == 1: curs.execute('SELECT name, pr FROM Word WHERE pr == %d ORDER by pr, name' % (int(pr[0]))) elif len(pr) == 2 and pr[1] == '+': curs.execute('SELECT name, pr FROM Word WHERE pr >= %d ORDER by pr, name' % (int(pr[0]))) elif len(pr) == 3 and pr[1] == '-': curs.execute('SELECT name, pr FROM Word WHERE pr >= %d AND pr<= % d ORDER by pr, name' % ( int(pr[0]), int(pr[2]))) else: if len(pr) == 1: curs.execute('SELECT expl, pr FROM Word WHERE pr == %d ORDER by pr, name' % (int(pr[0]))) elif len(pr) == 2 and pr[1] == '+': curs.execute('SELECT expl, pr FROM Word WHERE pr >= %d ORDER by pr, name' % (int(pr[0]))) elif len(pr) == 3 and pr[1] == '-': curs.execute('SELECT expl, pr FROM Word WHERE pr >= %d AND pr<= %d ORDER by pr, name' % ( int(pr[0]), int(pr[2]))) except Exception as e: print(colored('something\'s wrong, priority must be 1-5', 'red')) print(e) else: for line in curs.fetchall(): expl = line[0] pr = line[1] print('\n' + '=' * 40 + '\n') if not output: print(colored(' ' * pr, 'red', ), colored(' ' * (5 - pr), 'yellow'), sep='') colorful_print(expl) else: print(' ' * pr + ' ' * (5 - pr)) normal_print(expl) finally: curs.close() conn.close() def list_latest(limit, vb=False, output=False): '''list words by latest time you add to database.''' conn = sqlite3.connect(os.path.join(DEFAULT_PATH, 'word.db')) curs = conn.cursor() try: if not vb: curs.execute('SELECT name, pr, addtime FROM Word ORDER by datetime(addtime) DESC LIMIT %d' % limit) else: curs.execute('SELECT expl, pr, addtime FROM Word ORDER by datetime(addtime) DESC LIMIT %d' % limit) except Exception as e: print(e) print(colored('something\'s wrong, please set the limit', 'red')) else: for line in curs.fetchall(): expl = line[0] pr = line[1] print('\n' + '=' * 40 + '\n') if not output: print(colored(' ' * pr, 'red'), colored(' ' * (5 - pr), 'yellow'), sep='') colorful_print(expl) else: print(' ' * pr + ' ' * (5 - pr)) normal_print(expl) finally: curs.close() conn.close() def count_word(arg): '''count the number of words''' conn = sqlite3.connect(os.path.join(DEFAULT_PATH, 'word.db')) curs = conn.cursor() if arg[0].isdigit(): if len(arg) == 1: curs.execute('SELECT count(*) FROM Word WHERE pr == %d' % (int(arg[0]))) elif len(arg) == 2 and arg[1] == '+': curs.execute('SELECT count(*) FROM Word WHERE pr >= %d' % (int(arg[0]))) elif len(arg) == 3 and arg[1] == '-': curs.execute('SELECT count(*) FROM Word WHERE pr >= %d AND pr<= % d' % (int(arg[0]), int(arg[2]))) elif arg[0].isalpha(): if arg == 'all': curs.execute('SELECT count(*) FROM Word') elif len(arg) == 1: curs.execute('SELECT count(*) FROM Word WHERE aset == "%s"' % arg.upper()) res = curs.fetchall() print(res[0][0]) curs.close() conn.close() if __name__ == '__main__': main()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 11, 28000, 1098, 62, 17201, 874, 198, 11748, 25064, 198, 11748, 1822, 29572, 198, 11748, 28686, 198, 11748, 302, 198, 11748,...
2.098548
4,891
#!/usr/bin/env python # -*- coding: utf-8 -*- """Title: GCN models Description: The original Graph convolutional network model and GCN layer. Refer to: https://arxiv.org/abs/1609.02907 """ # ======================================= # @author Zhibin.Lu # @email zhibin.lu@umontreal.ca # ======================================= import collections import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.init as init
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 19160, 25, 20145, 45, 4981, 198, 198, 11828, 25, 220, 198, 464, 2656, 29681, 3063, 2122, 282, 3127, 2746, 290, ...
3.234899
149
SOLIDITY_TO_BQ_TYPES = { 'address': 'STRING', } table_description = ''
[ 50, 3535, 2389, 9050, 62, 10468, 62, 33, 48, 62, 9936, 47, 1546, 796, 1391, 198, 220, 220, 220, 705, 21975, 10354, 705, 18601, 2751, 3256, 198, 92, 198, 198, 11487, 62, 11213, 796, 10148, 628, 628, 628 ]
2.131579
38
#Method-1 guess the number game import random number = random.randint(1,10) guess = 0 count = 0 print("You can exit the game anytime. Just enter 'exit'.") while guess != number and guess != "exit": guess = input("Guess a number between 1 to 10 :- ") if guess == "exit": print("Closing the game...") break guess = int(guess) count += 1 if guess < number: print("Too low!") elif guess > number: print("Too high!") else: print("\nCongratulation, You got it!") print("You have tried ", count ," times")
[ 2, 17410, 12, 16, 4724, 262, 1271, 983, 198, 11748, 4738, 198, 198, 17618, 796, 4738, 13, 25192, 600, 7, 16, 11, 940, 8, 198, 5162, 408, 796, 657, 198, 9127, 796, 657, 198, 4798, 7203, 1639, 460, 8420, 262, 983, 17949, 13, 2329, ...
2.487288
236
"""Solvates a host, inserts guest(s) into solvated host, equilibrates """ import os import time import tempfile import numpy as np from rdkit import Chem from md import builders, minimizer from fe import pdb_writer, free_energy from ff import Forcefield from ff.handlers.deserialize import deserialize_handlers from timemachine.lib import custom_ops, LangevinIntegrator from docking import report def dock_and_equilibrate( host_pdbfile, guests_sdfile, max_lambda, insertion_steps, eq_steps, outdir, fewer_outfiles=False, constant_atoms=[], ): """Solvates a host, inserts guest(s) into solvated host, equilibrates Parameters ---------- host_pdbfile: path to host pdb file to dock into guests_sdfile: path to input sdf with guests to pose/dock max_lambda: lambda value the guest should insert from or delete to (recommended: 1.0 for work calulation, 0.25 to stay close to original pose) (must be =1 for work calculation to be applicable) insertion_steps: how many steps to insert the guest over (recommended: 501) eq_steps: how many steps of equilibration to do after insertion (recommended: 15001) outdir: where to write output (will be created if it does not already exist) fewer_outfiles: if True, will only write frames for the equilibration, not insertion constant_atoms: atom numbers from the host_pdbfile to hold mostly fixed across the simulation (1-indexed, like PDB files) Output ------ A pdb & sdf file for the last step of insertion (outdir/<guest_name>/<guest_name>_ins_<step>_[host.pdb/guest.sdf]) A pdb & sdf file every 1000 steps of equilibration (outdir/<guest_name>/<guest_name>_eq_<step>_[host.pdb/guest.sdf]) stdout corresponding to the files written noting the lambda value and energy stdout for each guest noting the work of transition, if applicable stdout for each guest noting how long it took to run Note ---- The work will not be calculated if the du_dl endpoints are not close to 0 or if any norm of force per atom exceeds 20000 kJ/(mol*nm) [MAX_NORM_FORCE defined in docking/report.py] """ if not os.path.exists(outdir): os.makedirs(outdir) print( f""" HOST_PDBFILE = {host_pdbfile} GUESTS_SDFILE = {guests_sdfile} OUTDIR = {outdir} MAX_LAMBDA = {max_lambda} INSERTION_STEPS = {insertion_steps} EQ_STEPS = {eq_steps} """ ) # Prepare host # TODO: handle extra (non-transitioning) guests? print("Solvating host...") ( solvated_host_system, solvated_host_coords, _, _, host_box, solvated_topology, ) = builders.build_protein_system(host_pdbfile) _, solvated_host_pdb = tempfile.mkstemp(suffix=".pdb", text=True) writer = pdb_writer.PDBWriter([solvated_topology], solvated_host_pdb) writer.write_frame(solvated_host_coords) writer.close() solvated_host_mol = Chem.MolFromPDBFile(solvated_host_pdb, removeHs=False) os.remove(solvated_host_pdb) guest_ff_handlers = deserialize_handlers( open( os.path.join( os.path.dirname(os.path.abspath(__file__)), "..", "ff/params/smirnoff_1_1_0_ccc.py", ) ).read() ) ff = Forcefield(guest_ff_handlers) # Run the procedure print("Getting guests...") suppl = Chem.SDMolSupplier(guests_sdfile, removeHs=False) for guest_mol in suppl: start_time = time.time() guest_name = guest_mol.GetProp("_Name") guest_conformer = guest_mol.GetConformer(0) orig_guest_coords = np.array(guest_conformer.GetPositions(), dtype=np.float64) orig_guest_coords = orig_guest_coords / 10 # convert to md_units minimized_coords = minimizer.minimize_host_4d( [guest_mol], solvated_host_system, solvated_host_coords, ff, host_box ) afe = free_energy.AbsoluteFreeEnergy(guest_mol, ff) ups, sys_params, combined_masses, _ = afe.prepare_host_edge( ff.get_ordered_params(), solvated_host_system, minimized_coords ) combined_bps = [] for up, sp in zip(ups, sys_params): combined_bps.append(up.bind(sp)) x0 = np.concatenate([minimized_coords, orig_guest_coords]) v0 = np.zeros_like(x0) print(f"SYSTEM", f"guest_name: {guest_name}", f"num_atoms: {len(x0)}") for atom_num in constant_atoms: combined_masses[atom_num - 1] += 50000 seed = 2021 intg = LangevinIntegrator(300.0, 1.5e-3, 1.0, combined_masses, seed).impl() u_impls = [] for bp in combined_bps: bp_impl = bp.bound_impl(precision=np.float32) u_impls.append(bp_impl) ctxt = custom_ops.Context(x0, v0, host_box, intg, u_impls) # insert guest insertion_lambda_schedule = np.linspace(max_lambda, 0.0, insertion_steps) calc_work = True # collect a du_dl calculation once every other step subsample_interval = 1 full_du_dls, _, _ = ctxt.multiple_steps(insertion_lambda_schedule, subsample_interval) step = len(insertion_lambda_schedule) - 1 lamb = insertion_lambda_schedule[-1] ctxt.step(lamb) report.report_step( ctxt, step, lamb, host_box, combined_bps, u_impls, guest_name, insertion_steps, "INSERTION", ) if not fewer_outfiles: host_coords = ctxt.get_x_t()[: len(solvated_host_coords)] * 10 guest_coords = ctxt.get_x_t()[len(solvated_host_coords) :] * 10 report.write_frame( host_coords, solvated_host_mol, guest_coords, guest_mol, guest_name, outdir, str(step).zfill(len(str(insertion_steps))), "ins", ) if report.too_much_force(ctxt, lamb, host_box, combined_bps, u_impls): print("Not calculating work (too much force)") calc_work = False continue # Note: this condition only applies for ABFE, not RBFE if abs(full_du_dls[0]) > 0.001 or abs(full_du_dls[-1]) > 0.001: print("Not calculating work (du_dl endpoints are not ~0)") calc_work = False if calc_work: work = np.trapz(full_du_dls, insertion_lambda_schedule[::subsample_interval]) print(f"guest_name: {guest_name}\tinsertion_work: {work:.2f}") # equilibrate for step in range(eq_steps): ctxt.step(0.00) if step % 1000 == 0: report.report_step( ctxt, step, 0.00, host_box, combined_bps, u_impls, guest_name, eq_steps, "EQUILIBRATION", ) if (not fewer_outfiles) or (step == eq_steps - 1): host_coords = ctxt.get_x_t()[: len(solvated_host_coords)] * 10 guest_coords = ctxt.get_x_t()[len(solvated_host_coords) :] * 10 report.write_frame( host_coords, solvated_host_mol, guest_coords, guest_mol, guest_name, outdir, str(step).zfill(len(str(eq_steps))), "eq", ) if step in (0, int(eq_steps / 2), eq_steps - 1): if report.too_much_force(ctxt, 0.00, host_box, combined_bps, u_impls): break end_time = time.time() print(f"{guest_name} took {(end_time - start_time):.2f} seconds") if __name__ == "__main__": main()
[ 37811, 36949, 85, 689, 257, 2583, 11, 42220, 8319, 7, 82, 8, 656, 1540, 85, 515, 2583, 11, 1602, 346, 2889, 689, 198, 37811, 198, 11748, 28686, 198, 11748, 640, 198, 11748, 20218, 7753, 198, 198, 11748, 299, 32152, 355, 45941, 198, ...
2.032315
3,961
#!python import string # Hint: Use these string constants to encode/decode hexadecimal digits and more # string.digits is '0123456789' # string.hexdigits is '0123456789abcdefABCDEF' # string.ascii_lowercase is 'abcdefghijklmnopqrstuvwxyz' # string.ascii_uppercase is 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # string.ascii_letters is ascii_lowercase + ascii_uppercase # string.printable is digits + ascii_letters + punctuation + whitespace digit_value = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15, 'g': 16, 'h': 17, 'i': 18, 'j': 19, 'k': 20, 'l': 21, 'm': 22, 'n': 23, 'o': 24, 'p': 25, 'q': 26, 'r': 27, 's': 28, 't': 29, 'u': 30, 'v': 31, 'w': 32, 'x': 33, 'y': 34, 'z': 35} value_digit = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f', 16: 'g', 17: 'h', 18: 'i', 19: 'j', 20: 'k', 21: 'l', 22: 'm', 23: 'n', 24: 'o', 25: 'p', 26: 'q', 27: 'r', 28: 's', 29: 't', 30: 'u', 31: 'v', 32: 'w', 33: 'x', 34: 'y', 35: 'z'} def decode(digits, base): """Decode given digits in given base to number in base 10. digits: str -- string representation of number (in given base) base: int -- base of given number return: int -- integer representation of number (in base 10)""" # Handle up to base 36 [0-9a-z] assert 2 <= base <= 36, 'base is out of range: {}'.format(base) # TODO: Decode digits from binary (base 2) digits_list = list(digits.lower()) digits_list.reverse() # print(digits_list) # go through the array and figure out what each 1 and 0 mean total = 0 for i, value in enumerate(digits_list): place_value = base ** i # print(place_value, value) total += digit_value[value] * place_value # print(place_value, digit_value[value], digit_value[value] * place_value, total) return total # ... # TODO: Decode digits from hexadecimal (base 16) # TODO: Decode digits from any base (2 up to 36) # ... def encode(number, base): """Encode given number in base 10 to digits in given base. number: int -- integer representation of number (in base 10) base: int -- base to convert to return: str -- string representation of number (in given base)""" # Handle up to base 36 [0-9a-z] assert 2 <= base <= 36, 'base is out of range: {}'.format(base) # Handle unsigned numbers only for now assert number >= 0, 'number is negative: {}'.format(number) # TODO: Encode number in binary (base 2) numbers = [] while number > 0: remainder = number % base if number < base: remainder = number number = number//base numbers.append(value_digit[remainder]) numbers.reverse() numbers_string = ''.join(numbers) return numbers_string # TODO: Encode number in hexadecimal (base 16) # ... # TODO: Encode number in any base (2 up to 36) # ... def convert(digits, base1, base2): """Convert given digits in base1 to digits in base2. digits: str -- string representation of number (in base1) base1: int -- base of given number base2: int -- base to convert to return: str -- string representation of number (in base2)""" # Handle up to base 36 [0-9a-z] assert 2 <= base1 <= 36, 'base1 is out of range: {}'.format(base1) assert 2 <= base2 <= 36, 'base2 is out of range: {}'.format(base2) decoded = decode(digits, base1) encoded = encode(decoded, base2) return encoded # TODO: Convert digits from base 2 to base 16 (and vice versa) # ... # TODO: Convert digits from base 2 to base 10 (and vice versa) # ... # TODO: Convert digits from base 10 to base 16 (and vice versa) # ... # TODO: Convert digits from any base to any base (2 up to 36) result = decode(digits, base1) return encode(result, base2) # ... def main(): """Read command-line arguments and convert given digits between bases.""" import sys args = sys.argv[1:] # Ignore script file name if len(args) == 3: digits = args[0] base1 = int(args[1]) base2 = int(args[2]) # Convert given digits between bases result = convert(digits, base1, base2) print('{} in base {} is {} in base {}'.format(digits, base1, result, base2)) else: print('Usage: {} digits base1 base2'.format(sys.argv[0])) print('Converts digits from base1 to base2') if __name__ == '__main__': # main() print(convert_fractional(".625", 10, 2))
[ 2, 0, 29412, 198, 198, 11748, 4731, 198, 2, 367, 600, 25, 5765, 777, 4731, 38491, 284, 37773, 14, 12501, 1098, 17910, 671, 66, 4402, 19561, 290, 517, 198, 2, 4731, 13, 12894, 896, 318, 705, 486, 1954, 2231, 3134, 4531, 6, 198, 2, ...
2.500542
1,844
# -*- coding: utf-8 -*- from ecl.provider_connectivity import provider_connectivity_service from ecl import resource2 from ecl.network.v2 import network from ecl.network.v2 import subnet import hashlib
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 304, 565, 13, 15234, 1304, 62, 8443, 3458, 1330, 10131, 62, 8443, 3458, 62, 15271, 198, 6738, 304, 565, 1330, 8271, 17, 198, 6738, 304, 565, 13, 27349, 13, ...
3.044118
68
import unittest from unittest import TestCase from src.gifGenerator import GifGenerator if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 6738, 12351, 13, 27908, 8645, 1352, 1330, 402, 361, 8645, 1352, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, ...
2.836735
49
""" TestCases for checking dbShelve objects. """ import sys, os, string import tempfile, random from pprint import pprint from types import * import unittest try: # For Pythons w/distutils pybsddb from bsddb3 import db, dbshelve except ImportError: # For Python 2.3 from bsddb import db, dbshelve from test_all import verbose #---------------------------------------------------------------------- # We want the objects to be comparable so we can test dbshelve.values # later on. #---------------------------------------------------------------------- #---------------------------------------------------------------------- #---------------------------------------------------------------------- # test cases for a DBShelf in a RECNO DB. #---------------------------------------------------------------------- def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(DBShelveTestCase)) suite.addTest(unittest.makeSuite(BTreeShelveTestCase)) suite.addTest(unittest.makeSuite(HashShelveTestCase)) suite.addTest(unittest.makeSuite(ThreadBTreeShelveTestCase)) suite.addTest(unittest.makeSuite(ThreadHashShelveTestCase)) suite.addTest(unittest.makeSuite(EnvBTreeShelveTestCase)) suite.addTest(unittest.makeSuite(EnvHashShelveTestCase)) suite.addTest(unittest.makeSuite(EnvThreadBTreeShelveTestCase)) suite.addTest(unittest.makeSuite(EnvThreadHashShelveTestCase)) suite.addTest(unittest.makeSuite(RecNoShelveTestCase)) return suite if __name__ == '__main__': unittest.main(defaultTest='test_suite')
[ 37811, 198, 14402, 34, 1386, 329, 10627, 20613, 50, 2978, 303, 5563, 13, 198, 37811, 198, 198, 11748, 25064, 11, 28686, 11, 4731, 198, 11748, 20218, 7753, 11, 4738, 198, 6738, 279, 4798, 1330, 279, 4798, 198, 6738, 3858, 1330, 1635, 1...
3.165029
509
""" pyexcel.sources.file ~~~~~~~~~~~~~~~~~~~ Representation of file sources :copyright: (c) 2015-2016 by Onni Software Ltd. :license: New BSD License """ from pyexcel import params from pyexcel.factory import FileSource from pyexcel.sources.rendererfactory import RendererFactory from pyexcel.sources import renderer RendererFactory.register_renderers(renderer.renderers) try: import pyexcel_text as text RendererFactory.register_renderers(text.renderers) except ImportError: pass file_types = tuple(RendererFactory.renderer_factories.keys()) sources = ( WriteOnlySheetSource, WriteOnlyBookSource, SheetSource, BookSource )
[ 37811, 201, 198, 220, 220, 220, 12972, 1069, 5276, 13, 82, 2203, 13, 7753, 201, 198, 220, 220, 220, 220, 27156, 4907, 93, 201, 198, 201, 198, 220, 220, 220, 10858, 341, 286, 2393, 4237, 201, 198, 201, 198, 220, 220, 220, 1058, 221...
2.565371
283
import pathlib from setuptools import setup, find_packages HERE = pathlib.Path(__file__).parent VERSION = '0.1.0' PACKAGE_NAME = 'MDF_DALEC_GRASS' AUTHOR = 'Vasilis Myrgiotis' AUTHOR_EMAIL = 'v.myrgioti@ed.ac.uk' URL = 'https://github.com/vmyrgiotis/MDF_DALEC_GRASS' LICENSE = 'MIT' DESCRIPTION = 'A Bayesian model-data fusion algorithm for simulating carbon dynamics in grassland ecosystems' LONG_DESCRIPTION = (HERE / "README.md").read_text() LONG_DESC_TYPE = "text/markdown" INSTALL_REQUIRES = ["numpy", "pandas","spotpy","sklearn","sentinelhub", "shapely", "datetime", "geopandas", "cdsapi"] PYTHON_REQUIRES = '>=3.8' setup(name=PACKAGE_NAME, version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, long_description_content_type=LONG_DESC_TYPE, author=AUTHOR, license=LICENSE, author_email=AUTHOR_EMAIL, url=URL, install_requires=INSTALL_REQUIRES, packages=find_packages() )
[ 11748, 3108, 8019, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 39, 9338, 796, 3108, 8019, 13, 15235, 7, 834, 7753, 834, 737, 8000, 198, 198, 43717, 796, 705, 15, 13, 16, 13, 15, 6, 198, 47, 8120, 11879...
2.459893
374
import setuptools from croo import croo_args with open('README.md', 'r') as fh: long_description = fh.read() setuptools.setup( name='croo', version=croo_args.__version__, scripts=['bin/croo'], python_requires='>3.4.1', author='Jin Lee', author_email='leepc12@gmail.com', description='CRomwell Output Organizer', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/ENCODE-DCC/croo', packages=setuptools.find_packages(exclude=['examples', 'docs']), classifiers=[ 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', ], install_requires=['caper'] )
[ 11748, 900, 37623, 10141, 198, 6738, 6763, 78, 1330, 6763, 78, 62, 22046, 198, 198, 4480, 1280, 10786, 15675, 11682, 13, 9132, 3256, 705, 81, 11537, 355, 277, 71, 25, 198, 220, 220, 220, 890, 62, 11213, 796, 277, 71, 13, 961, 3419, ...
2.52349
298
from typing import Dict import numpy as np from ..envs.env import StructuralModel from ..utils.lik_func import * from ..utils.useful_class import ParameterGrid if __name__ == "__main__": grid = { 'delta': [0.1, 0.2, 0.3], 'gamma': [1, 10] } pg = ParameterGrid(grid) for g in pg: print(g)
[ 6738, 19720, 1330, 360, 713, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 11485, 268, 14259, 13, 24330, 1330, 32112, 1523, 17633, 198, 6738, 11485, 26791, 13, 46965, 62, 20786, 1330, 1635, 198, 6738, 11485, 26791, 13, 1904, ...
2.248322
149
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from AlgorithmImports import * ### <summary> ### This algorithm is a regression test for issue #2018 and PR #2038. ### </summary>
[ 2, 19604, 1565, 4825, 1340, 48842, 13, 9858, 532, 9755, 2890, 15007, 11, 2295, 6477, 278, 34884, 13, 198, 2, 45661, 978, 7727, 9383, 25469, 7117, 410, 17, 13, 15, 13, 15069, 1946, 16972, 13313, 10501, 13, 198, 2, 198, 2, 49962, 739,...
3.9
210
from django.db import models from django.contrib.auth.models import User
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 628, 198 ]
3.409091
22
import torch import torch.nn.functional as F from typing import Optional from collections import namedtuple import hpc_rl_utils # hpc version only support cuda hpc_ppo_loss = namedtuple('hpc_ppo_loss', ['policy_loss', 'value_loss', 'entropy_loss']) hpc_ppo_info = namedtuple('hpc_ppo_info', ['approx_kl', 'clipfrac'])
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 19720, 1330, 32233, 198, 6738, 17268, 1330, 3706, 83, 29291, 198, 11748, 289, 14751, 62, 45895, 62, 26791, 198, 198, 2, 289, 14751, 2196, 691, 1104, 269, 15339,...
2.944954
109
from prometheus_client import Counter from raiden.utils.typing import TokenAmount from raiden_libs.metrics import ( # noqa: F401, pylint: disable=unused-import ERRORS_LOGGED, EVENTS_EXCEPTIONS_RAISED, EVENTS_PROCESSING_TIME, MESSAGES_EXCEPTIONS_RAISED, MESSAGES_PROCESSING_TIME, REGISTRY, ErrorCategory, MetricsEnum, collect_event_metrics, collect_message_metrics, get_metrics_for_label, ) REWARD_CLAIMS = Counter( "economics_reward_claims_successful_total", "The number of overall successful reward claims", labelnames=[Who.label_name()], registry=REGISTRY, ) REWARD_CLAIMS_TOKEN = Counter( "economics_reward_claims_token_total", "The amount of token earned by reward claims", labelnames=[Who.label_name()], registry=REGISTRY, )
[ 6738, 1552, 36916, 62, 16366, 1330, 15034, 198, 198, 6738, 9513, 268, 13, 26791, 13, 774, 13886, 1330, 29130, 31264, 198, 6738, 9513, 268, 62, 8019, 82, 13, 4164, 10466, 1330, 357, 220, 1303, 645, 20402, 25, 376, 21844, 11, 279, 2645,...
2.524845
322
# modified from TikNib/tiknib/ida/fetch_funcdata_v7.5.py import os import sys import string from hashlib import sha1 from collections import defaultdict import time import pprint as pp import idautils import idc import idaapi import ida_pro import ida_nalt import ida_bytes sys.path.append(os.path.abspath("./TikNib")) from tiknib.utils import demangle, get_arch, init_idc, parse_fname, store_func_data printset = set(string.printable) isprintable = lambda x: set(x).issubset(printset) # find consts # find strings # This function returns a caller map, and callee map for each function. # This function returns edges, and updates caller_map, and callee_map init_idc() try: func_data = main() except: import traceback traceback.print_exc() ida_pro.qexit(1) else: bin_path = get_bin_path() store_func_data(bin_path, func_data) ida_pro.qexit(0)
[ 2, 9518, 422, 46338, 45, 571, 14, 83, 1134, 77, 571, 14, 3755, 14, 69, 7569, 62, 20786, 7890, 62, 85, 22, 13, 20, 13, 9078, 201, 198, 11748, 28686, 201, 198, 11748, 25064, 201, 198, 11748, 4731, 201, 198, 201, 198, 6738, 12234, ...
2.401535
391