content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#In this assignment you will write two functions. Your functions should not make any print statements.
#Any printing should be done by driver code outside the functions.
#Problem 1:
#Write a function tha will take two parameters: city and country. You can name it whatever you want.
#The function should return a forma... | python |
from infi.clickhouse_orm import migrations # type: ignore
from ee.clickhouse.sql.events import (
EVENTS_WITH_PROPS_TABLE_SQL,
MAT_EVENT_PROP_TABLE_SQL,
MAT_EVENTS_WITH_PROPS_TABLE_SQL,
)
operations = [
migrations.RunSQL(EVENTS_WITH_PROPS_TABLE_SQL),
migrations.RunSQL(MAT_EVENTS_WITH_PROPS_TABLE_S... | python |
#!/usr/bin/env python
# coding=utf-8
# This file is copied from torchvision.models
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import tensorboardX as tbx
import libs.c... | python |
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
import json
import os
import random
import requests
import src.services.providers.python.fetch_git_data
import src.services.providers.python.fetch_lingo_data
import src.services.providers.python.fetch_lab_data
def create_app():
ap... | python |
import StockAnalysisSystem.core.api as sasApi
from StockAnalysisSystem.core.SubServiceManager import SubServiceContext
from StockAnalysisSystem.core.Utility.relative_import import RelativeImport
from StockAnalysisSystem.core.Utility.event_queue import Event, EventDispatcher
with RelativeImport(__file__):
from WebS... | python |
"""'On-fly' avatar changer.
This script allows to change avatar of bot while it's running.
Script gets randomly choosen avatar data to replace current avatar.
This file can also be imported as a module and contains the following functions:
* get_avatar_bytes - gets bytes from avatar picture
"""
import pathlib
im... | python |
import queue
from typing import Tuple
from agents.abstract_agent import AbstractAgent
from games.game import Game
from utils import print_turn
from utils import print_board
from utils import print_move
from utils import print_visit_count
from utils import print_winner
from games.game_types import UIEvent
class CUI:
... | python |
import numpy as np
import threading
#from federatedml.ftl.encryption import mulmatOT
import mulmatOT
import sys,getopt
import socket
import pickle
from time import *
BITS_LEN=16
ROW_A=6
COL_A=6
ROW_B=6
COL_B=6
# a=np.array([[ 0.00514600],
# [ 0.02252000],
# [-0.01941000],
# [ 0.04263000],
# [-0.01234000],
# [ 0.... | python |
import poplib
import getpass
import sys
import mailconfig
# Configuramos o servidor
mailserver = mailconfig.servidor_pop
# O nome do usuário
mailuser = mailconfig.usuário_pop
# Pedimos por uma senha
mailpasswd = getpass.getpass('Senha para %s?' % mailserver)
# Iniciamos o processo de conexão com o servidor
print('C... | python |
import os
import pathlib
# Clone the tensorflow models repository if it doesn't already exist
if "models" in pathlib.Path.cwd().parts:
while "models" in pathlib.Path.cwd().parts:
os.chdir('..')
elif not pathlib.Path('models').exists():
!git clone --depth 1 https://github.com/tensorflow/models
import matplotli... | python |
# -*- coding: utf-8 -*-
"""
Author: Keurfon Luu <keurfon.luu@mines-paristech.fr>
License: MIT
"""
__all__ = [ "progress_bar", "progress_perc", "progress" ]
def progress_bar(i, imax, n = 50):
bar = list("[" + n * " " + "]")
perc = (i+1) / imax
bar[1:int(perc*n)+1] = int(perc*n) * "="
imid = (n+2) // ... | python |
import pytz
from pytz import timezone, common_timezones
from datetime import datetime
def local_to_utc(local_time, local_tz, aware=True):
if local_tz not in common_timezones:
raise ValueError('Timezone: %s is not in common list' % (local_tz))
utc = pytz.utc
tz = timezone(local_tz)
if aware:
... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @uthor: Makram Jandar
# ____ __ ___ __ ______ ___ ___
# | | | | \| | | | / _] \
# |__ | | | o ) | | |/ [_| D )
# __| | | | _/| ~ |_| |_| _] /
# / | | : | | |___, | | | | [_| \
# \ ` | |... | python |
import sys, re
try:
from Bio import Entrez
except ImportError as exc:
print(f"### Error: {exc}", file=sys.stderr)
print(f"### This program requires biopython", file=sys.stderr)
print(f"### Install: conda install -y biopython>=1.79", file=sys.stderr)
sys.exit(-1)
from biorun.libs import placlib as ... | python |
'''
Agilent 33220A
Created on October 11, 2009
@author: bennett
'''
# Future functions GetLoad and SetLoad, GetUnits and SetUnits
import gpib_instrument
class Agilent33220A(gpib_instrument.Gpib_Instrument):
'''
The Agilent 33220A Arbitrary Function Generator GPIB communication class (Incomplete)
'''
... | python |
from collections import Counter
import json
import math
from pprint import pprint
import re
import sys
import urllib.request
import glob
files = glob.glob(
"/Users/nakamura/git/d_umesao/umesao_images/docs/iiif/item/*/manifest.json")
files = sorted(files)
selections = []
prefix = "https://nakamura196.github.io/vi... | python |
# Generated by Django 2.0.6 on 2018-06-29 16:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('grafik', '0004_auto_20180629_2115'),
]
operations = [
migrations.RemoveField(
model_name='passenger',
name='kecamata... | python |
# Generates simulation data for time-series count data with decoupled mean and variance
import numpy as np
import pandas as pd
from scipy.stats import norm
import statsmodels.api as sm
from datetime import datetime as dt
from dateutil.relativedelta import relativedelta
from dataclasses import dataclass
def generate_d... | python |
import machine
import utime
class KitronikPicoMotor:
#Pins 4 and 5 motor 1
#Pins 9 and 10 motor 2
#'Forward' is P5 or P9 driven high, with P4 or P10 held low.
#'Reverse' is P4 or P10 driven high, with P5 or P9 held low
#Driving the motor is simpler than the servo - just convert 0-100% ... | python |
from django import test
import actrack
from actrack.managers.inst import get_user_model
from actrack.actions import save_queue
__test__ = False
__unittest = True
class TestCase(test.TestCase):
@property
def user_model(self):
return get_user_model()
def log(self, *args, **kwargs... | python |
# DmrSmashTools by Dreamer
# Github Link: https://github.com/Dreamer13sq/DmrSmashTools/tree/main/DmrSmashTools_Blender
bl_info = {
"name": "Dmr Smash Tools",
"description": 'Some tools used to make modelling more efficient.',
"author": "Dreamer",
"version": (1, 0),
"blender": (2, 90, 0),
"categ... | python |
# -*- coding: utf-8 -*-
from nose import tools as nose
from tests.integration.resource import ResourceTestCase
class AlbumResourceTestCase(ResourceTestCase):
"""
GET /albums/ [artist=<int>]
200 OK
401 Unauthorized
POST /albums/ name=<str> [year=<int>] [cover_url=<str>]
201 Created... | python |
"""
train.py
Entry point for training Hasse diagrams.
"""
from ehreact.train import calculate_diagram
def train(args):
"""
Computes a Hasse diagram based on the inputted arguments
Parameters
----------
args: Namespace
Namespace of arguments.
"""
if not args.quiet:
print(... | python |
# grid relative
from .fl_controller import FLController
processes = FLController()
| python |
'''
Nome: Andre Devay Torres Gomes
NUSP: 10770089
'''
# Função principal que roda a interface e chama as outras funções
def main():
global solucao
n = int(input('Digite o número N (entre 4 e 26) de rainhas que deseja no tabuleiro NxN :'))
matriz = []
solucao = []
for i in range(n):
... | python |
# Copyright 2012 Red Hat, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | python |
from blackbox_mpc.policies.model_free_base_policy import ModelFreeBasePolicy
import tensorflow as tf
class RandomPolicy(ModelFreeBasePolicy):
def __init__(self, number_of_agents, env_action_space):
"""
This is the random policy for controlling the agent
Parameters
---------
... | python |
import ROOT
import Analysis
import AnalysisHelpers as AH
import Constants
#======================================================================
class ZAnalysis(Analysis.Analysis):
"""Analysis searching for events where Z bosons decay to two leptons of same flavour and opposite charge.
"""
def __init__(self, ... | python |
import uuid
import os
import shutil
def create_tmp_dir() -> str:
tmp_dir = f"/tmp/gitopscli/{uuid.uuid4()}"
os.makedirs(tmp_dir)
return tmp_dir
def delete_tmp_dir(tmp_dir: str) -> None:
shutil.rmtree(tmp_dir, ignore_errors=True)
| python |
"""
BeWilder - a *wild* text adventure game :: Main game module
# Make a new player object that is currently in the 'outside' room.
Write a loop that:
- Prints the current room name
- Prints the current description (the textwrap module might be useful here).
- Waits for user input and decides what to do.
- If th... | python |
import inspect
import re
import sys
from builtins import object
from operator import attrgetter
from os import sep, path, mkdir
try:
from os import scandir
except ImportError:
from scandir import scandir
from n_utils.git_utils import Git
from n_utils.aws_infra_util import load_parameters
class Component(obje... | python |
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
# from abc import ABCMeta, abstractmethod
import numpy as np
from pytest import approx
import torch
from implicitresnet.utils.spectral import spectral_norm
import implicitresnet.utils.calc as utils
#############... | python |
# -*- coding: utf-8 -*-
import logging
from .api import PrivoxyAdapter, RetryPrivoxyAdapter # noqa: F401
from .version import __version__ # noqa: F401
logging.getLogger("urllib3").setLevel(logging.ERROR)
__author__ = "Alexey Shevchenko"
__email__ = 'otetz@me.com'
__copyright__ = "Copyright 2017, Alexey Shevchenko... | python |
import os
import unittest
from pathlib import Path
import pytest
from paramak import RotateStraightShape, SweepSplineShape
class TestSweepSplineShape(unittest.TestCase):
def setUp(self):
self.test_shape = SweepSplineShape(
points=[(-10, 10), (10, 10), (10, -10), (-10, -10)],
pat... | python |
""" TF sandbox for testing new stuff """
import math
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_boolean('fake_data', False, 'If true, uses fake data '
'for unit testing.')
flags.DEFIN... | python |
"""
Example showing how to set up a semi-discretization with the spectral difference method and advect it.
"""
# Import libraries
##################
from nodepy import semidisc
from nodepy import *
import numpy as np
import matplotlib.pyplot as pl
# Create spatial operator L (i.e. u' = L u)
########################... | python |
class pos:
def __init__(self, r, c, is_blocked):
self.r = r
self.c = c
self.is_blocked = is_blocked
def robot_find_path(matrix, cur_pos, end):
''' Start at 0,0'''
memo_path = dict
memo_path[ (0,0) ] = (0,0)
if (cur_pos == end):
return pos
if cur_pos.is_blocked:
... | python |
import maya.cmds as cmds
#### XGEN DESCRIPTIONS - RENDER ONLY #####
def main():
xGen = getXgen()
setVisibility(xGen)
def getXgen():
node = cmds.ls(selection = True)
children_nodes = cmds.listRelatives(allDescendents=True, type='xgmSplineDescription')
if not children_nodes:
print("No XGEN")
... | python |
from src.domain.interaction.interaction_phase_state import InteractionPhaseState
class ExitPhase(InteractionPhaseState):
def fetch_next_interaction_phase(self, input_text):
return self
def process_input_text(self, input_text, input_text_processor):
return input_text_processor.process_exit_st... | python |
# ---------------------------------------------------------------------
# Angtel.Topaz.get_vlans
# ---------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# Python m... | python |
"""
makeblastdb -dbtype nucl -in nanoTRF_0.1M.fasta -out nanoTRF_0.1M.fasta
blastn -query merged_TR_rank_all.fasta -outfmt 6 -db nanoTRF_0.1M.fasta -out merged_TR_rank_all_vs_nanoTRF_0.1M.out -window_size 22 -num_threads 100 -evalue 10
"""
from bin.helpers.help_functions import getLog
import os
class run_BLAST():
... | python |
import argparse
import csv
import itertools as it
from operator import itemgetter
import csv2xml as c2x
def find_targeting(from_char, to_char):
lineset, opponent_meta = c2x.load_character(from_char)
rows = []
line_to_row = {}
for stageset, case in c2x.iter_lineset(lineset):
targeted_... | python |
# Copyright (c) 2015 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... | python |
# -*- coding: utf-8 -*-
'''
Easy and basic configure for print log
'''
__author__ = 'lujiaying@baidu.com'
import logging
from logging.handlers import RotatingFileHandler
import os
################################
# Conf to edit
################################
# To print into screen if DebugConf is True
DebugConf = ... | python |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Common system settings
# ---------------------------------------------------------------------
# Copyright (C) 2007-2015 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------... | python |
import numpy as np
from scipy.optimize import minimize
import dadapy.utils_.utils as ut
def ML_fun_gPAk(params, args):
"""
The function returns the log-Likelihood expression to be minimized.
Requirements:
* **params**: array of initial values for ''a'', ''b''
* **args**: additional parameters '... | python |
class StockSpanner:
def __init__(self):
self.stack = [] # (price, span)
def next(self, price: int) -> int:
span = 1
while self.stack and self.stack[-1][0] <= price:
span += self.stack.pop()[1]
self.stack.append((price, span))
return span
| python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This allows easy testing of the `projects` service of the
application server. It can be run interactively or in 'simulation'
mode.
"""
from __future__ import unicode_literals, division, print_function #Py2
import argparse
import random
import time
import requests
... | python |
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","root","","zambia_weather")
# prepare a cursor object using cursor() method
cursor = db.cursor()
insert = """INSERT INTO test (name, region) VALUES (%s, %s)"""
sql = cursor.execute(insert, ("Hello", "World"))
db.commit()
#curs... | python |
import numpy as np
from numpy import log, exp, sqrt
from numpy.lib.shape_base import _expand_dims_dispatcher
# import yahoo finance to pull stock and crypto data from
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
import scipy.optimize as optimization
# bringing in these libraries in order to... | python |
# Copyright (C) 2019 LYNX B.V. All rights reserved.
# Import ibapi deps
from ibapi import wrapper
from ibapi.client import EClient
from ibapi.contract import *
from threading import Thread
from time import sleep
CONTRACT_ID = 4001
class Wrapper(wrapper.EWrapper):
def __init__(self):
wrapper.EWrapper.__... | python |
import re
# print(re.split(r'\s*', 'here are some words'))
# print(re.split(r'(\s*)', 'here are some words'))
# print(re.split(r'(s*)', 'here are some words'))
# [a-z] find a range of characters
# print(re.split(r'[a-hA-F0-9]', 'saldkfjeilksjdLKJSAEIAL;SDF', re.I | re.M))
'''
\d = digits
\D = non-digits
\s = Space
... | python |
## AUTHOR: Vamsi Krishna Reddy Satti
##################################################################################
# Data loader
##################################################################################
import numpy as np
class DataLoader:
def __init__(self, dataset, batch_size=1, shuffle=False):... | python |
import PHPTraceTokenizer
import PHPProfileParser
import PHPTraceParser
import os
traceDir = "test-data"
def trace_and_profile_from_timestamp(traceDir, timestamp):
return (
os.path.join(traceDir, "{}.xt".format(timestamp)),
os.path.join(traceDir, "{}.xp".format(timestamp))
)
def create_trace(... | python |
"""
EVM Instruction Encoding (Opcodes)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. contents:: Table of Contents
:backlinks: none
:local:
Introduction
------------
Machine readable representations of EVM instructions, and a mapping to their
implementations.
"""
import enum
from typing import Callable, Dict
from .... | python |
import tensorflow as tf
import sys
def get_id_feature(features, key, len_key, max_len):
ids = features[key]
ids_len = tf.squeeze(features[len_key], [1])
ids_len = tf.minimum(ids_len, tf.constant(max_len, dtype=tf.int64))
return ids, ids_len
def create_train_op(loss, hparams):
train_op = tf.contrib.layers.op... | python |
from __future__ import unicode_literals
from celery import shared_task
from isisdata.models import *
from isisdata.tasks import _get_filtered_object_queryset
from django.apps import apps
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User
from django.db import models
imp... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import time
import functools
import random
from multiprocessing import Pool
import cProfile
import pstats
try:
import networkx as nx
except ImportError:
print('This script requires NetworkX to be installed.')
exit(1)
try:
import vkontakte... | python |
#!/env/bin/python
import hashlib
import json
import random
import string
import sys
import time
import zmq
from termcolor import colored
import fnode
# def check_files_node(node, my_id):
# files_my_id = {}
# delete = {}
# for i in node['file']:
# print i[0:7] + '-->>' + node['lower_bound']
# ... | python |
from django import forms
from django.forms import SelectDateWidget
from mopga.modules.project.models import Project
class NewProject(forms.Form):
title = forms.CharField(max_length=200)
donationGoal = forms.IntegerField(label='Donation goal', min_value=0)
description = forms.CharField(max_length=5000, wi... | python |
from ..systems import ContinuousSys
from ..tools import nd_rand_init, sigmoid
import numpy as np
class JansenRit(ContinuousSys):
def __init__(self, A=3.25, B=22, a_inv=10, b_inv=20, C=135, Crep=[1., 0.8, 0.25, 0.25], vmax=5, v0=6, r=0.56, n_points=5000, t_min=0, t_max=30):
self.A = A
self.B = B
... | python |
__all__ = ['Design', 'DesignTools', 'DesignSep2Phase', 'DesignSep3Phase']
| python |
def kfilter(ar,kf):
nx=shape(ar)[0];kx=fftshift(fftfreq(nx))*nx
ny=shape(ar)[1];ky=fftshift(fftfreq(ny))*ny
nz=shape(ar)[2];kz=fftshift(fftfreq(nz))*nz
km=np.zeros((nx,ny,nz))
for x in range(nx):
for y in range(ny):
for z in range(nz):
km[x,y,z]=sqrt(kx[x]**2+ky[y]**2+kz[z]**2)... | python |
# -*- coding: utf-8 -*-
import yaml
from pymodm import connect, fields, MongoModel, EmbeddedMongoModel
def setup_db(environment):
config = parse_db_config(environment)
connect("mongodb://{0}/{1}".format(config['clients']['default']['hosts'][0], config['clients']['default']['database']))
def parse_db_config(... | python |
import psutil
import gc
# check if memory usage is over limit
def check_memory_limit(limit: float = 90.):
return psutil.virtual_memory()[2] > limit
def memory_circuit_breaker(limit: float = 90.):
# if over limit, garbage collect
if check_memory_limit(limit):
gc.collect()
# if still above limi... | python |
# Boilerplate stuff:
from pyspark import SparkConf, SparkContext
conf = SparkConf().setMaster('local').setAppName('DegreesOfSeparation')
sc = SparkContext(conf=conf)
# The characters we wish to find the degree of separation between:
START_CHARACTER_ID = 5306 # SpiderMan
TARGET_CHARACTER_ID = 14 # ADAM 3,031 (who?)... | python |
from aiogram.types import Message, ReplyKeyboardRemove
from aiogram.dispatcher.filters import ChatTypeFilter
from app.loader import dp
from app.keyboards import reply_bot_menu
@dp.message_handler(ChatTypeFilter("private"), commands='menu')
async def show_menu_command(msg: Message):
return await msg.answer(
... | python |
from __future__ import print_function
from __future__ import unicode_literals
import errno
import os
from . import config
def _get_address(instance_ip):
username = config.get('ssh.username_prefix', '') + config.get('ssh.username', '')
# Don't add the username to the address when it is the current user,
... | python |
import unittest
from unittest import mock
from betfairlightweight.streaming.stream import BaseStream, MarketStream, OrderStream
from tests.unit.tools import create_mock_json
class BaseStreamTest(unittest.TestCase):
def setUp(self):
self.listener = mock.Mock()
self.listener.max_latency = 0.5
... | python |
#! /usr/bin/env python3
# Copyright 2018 Red Book Connect LLC. operating as HotSchedules
#
# 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
#
... | python |
#!/usr/bin/env python3
from baselines.common import tf_util as U
from baselines import logger
from env.LaneChangeEnv import LaneChangeEnv
from ppo_new import ppo_sgd
import random, sys, os
import numpy as np
import tensorflow as tf
if 'SUMO_HOME' in os.environ:
tools = os.path.join(os.environ['SUMO_HOME'], 'tools')... | python |
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import LineCollection
# In order to efficiently plot many lines in a single set of axes,
# Matplotlib has the ability to add the lines all at once. Here is a
# simple example showing how it is done.
N = 50
x = np.arange(N)
# Here are many ... | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import configparser
import os
class ConfigParser:
def __init__(this, filePath = os.getcwd() + os.sep + 'config' + os.sep + 'config.ini'):
this.fp = filePath
this.conf = configparser.ConfigParser()
this.conf.read(this.fp, encoding="utf-8-sig")
... | python |
## This file is part of Scapy
## See http://www.secdev.org/projects/scapy for more informations
## Copyright (C) Philippe Biondi <phil@secdev.org>
## This program is published under a GPLv2 license
"""
Clone of Nmap's first generation OS fingerprinting.
"""
import os
from scapy.data import KnowledgeBase
from scapy.c... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 Ben Lindsay <benjlindsay@gmail.com>
from distutils.core import setup
desc = 'A module for automating flat or hierarchical job creation and submission'
with open('README.rst', 'r') as f:
long_desc = f.read()
setup(
name = 'job_tree',
packag... | python |
#-------------------------------------#
# Python script for BEST address #
# Author: Marc Bruyland (FOD BOSA) #
# Contact: marc.bruyland@bosa.fgov.be #
# June 2019 #
#-------------------------------------#
from BEST_Lib import *
def createTestFile(inputFile, outputFile):
fi... | python |
import logging
import re
from string import punctuation
import unicodedata
from nltk.corpus import stopwords
import contractions
from spellchecker import SpellChecker
from .article import get_article
from .dictionary import get_extended_dictionary, valid_one_letter_words
logger = logging.getLogger('django')
def... | python |
import logging; log = logging.getLogger(__name__)
import OpenGL.GL as gl
from OpenGL.raw.GL.ARB.vertex_array_object import glGenVertexArrays, \
glBindVertexArray
class VertexArray:
"""GL vertex array object."""
class _Binding:
"""Object returned by VertexArray.bound()."""
def __init__(self, a... | python |
REDIS_URL = 'redis://redis:6379'
| python |
# This program is public domain.
"""
Support for rarely varying instrument configuration parameters.
Instrument configuration parameters will change throughout the
lifetime of an instrument. For example, the properties of the
beam such as wavelength and wavelength divergence will change
when a new monochromator is i... | python |
import cv2
import glob, os
import numpy as np
import pandas as pd
import tensorflow as tf
from preprocessing import Preprocess
import Model
from matplotlib import pyplot as plt
df_train = []
df_test = []
df_val = []
if os.path.exists("./dataset/train.npy"):
df_train = np.load("./dataset/train.npy")
df_test = ... | python |
import sys
import numpy as np
import h5py
import random
import os
from subprocess import check_output
# 1. h5 i/o
def readh5(filename, datasetname):
data=np.array(h5py.File(filename,'r')[datasetname])
return data
def writeh5(filename, datasetname, dtarray):
# reduce redundant
fid=h5py.File(filename,... | python |
# シェルソート
n = int(input())
lst = [int(input()) for _ in range(n)]
def insertionSort(A, n, g):
global cnt
for i in range(g, n):
v = A[i]
j = i - g
while j >= 0 and A[j] > v:
A[j+g] = A[j]
j = j - g
cnt += 1
A[j+g] = v
def shellSort(A, n):
... | python |
import json
from flask import request, make_response, jsonify, session as loginSession
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm.exc import NoResultFound
from config.flask_config import app
from model.entities import Category
from model.repository import CategoryRepo
from exception.exception_help... | python |
s = input()
index_A = float('inf')
index_Z = float('inf')
for i in range(len(s)):
if s[i] == 'A':
index_A = i
break
for i in range(len(s) - 1, -1, -1):
if s[i] == 'Z':
index_Z = i
break
print(len(s[index_A:index_Z + 1]))
| python |
def evaluate_policy(env, model, render, turns = 3):
scores = 0
for j in range(turns):
s, done, ep_r, steps = env.reset(), False, 0, 0
while not done:
# Take deterministic actions at test time
a = model.select_action(s, deterministic=True)
s_prime, r, done, inf... | python |
import os,sys
import re
import sympy
import math
import cmath
from math import factorial as fact
from sympy import factorial as symb_fact
from sympy import factorial2 as symb_fact2
from scipy.special import binom as binomial
from sympy import exp as symb_exp
from sympy import I as symb_I
def generate_cartesian_ls( L )... | python |
#Embedded file name: cmstop_inj.py
import re
if 0:
i11iIiiIii
def assign(service, arg):
if service != '''cmstop''':
return
else:
return (True, arg)
if 0:
O0 / iIii1I11I1II1 % OoooooooOO - i1IIi
def audit(arg):
o0OO00 = arg + decode('\xc5Y\x05K\xc5\xa8\x80\xac\x13\xc3=\r\x9... | python |
# encoding: utf-8
"""
@author: liaoxingyu
@contact: sherlockliao01@gmail.com
"""
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
import numpy as np
import math
import random
from .backbones import *
from .loss... | python |
# Confidential, Copyright 2020, Sony Corporation of America, All rights reserved.
from .person_routines import DefaultPersonRoutineAssignment
from ..environment import Home, GroceryStore, Office, School, Hospital, RetailStore, HairSalon, Restaurant, Bar, \
PandemicSimConfig, LocationConfig
__all__ = ['town_config... | python |
from django.urls import path, include
from .views import registration_view, login_view, logout_view
urlpatterns = [
path("registration/", registration_view, name="registration_view"),
path("login/", login_view),
path("logout/", logout_view)
] | python |
from holdings.position import Position
from collections import OrderedDict
from holdings.transaction import Transaction
class PositionHandler:
"""
Helper class to handle position operations in a Portfolio object.
"""
def __init__(self):
self.positions = OrderedDict()
def transact_positio... | python |
# Copyright 2016 gRPC authors.
#
# 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... | python |
''' Handling the data io '''
import argparse
import torch
import sys
def read_vocab_idx(vocab_path):
''' build vocab '''
word2idx = {"_PAD" : 0}
with open(vocab_path) as f:
for line in f:
tokens = line.strip("\n").split("\t")
no = int(tokens[1])
word2idx[toke... | python |
class Serie:
__slots__ = ("__weakref__", "_state", "_rooms", "id", "code", "name", "description", "difficulty", )
def __init__(self, state, data):
self._state = state
self._from_data(data)
def _from_data(self, data):
self.id = data.get("_id")
self.code = data.... | python |
import pathlib
#import numpy as np
test_data = 0
points = set()
folds = []
path = str(pathlib.Path(__file__).parent.resolve())
with open(path+"/data{}.csv".format("_test" if test_data else ""), 'r') as file:
for line in file.read().splitlines():
if line.startswith("fold"):
folds.append((line[... | python |
class Attr(object):
def __init__(self, name, type_):
self.name = name
self.type_ = type_
def __get__(self, instance, cls):
return instance.__dict__[self.name]
def __set__(self, instance, value):
if not isinstance(value, self.type_):
raise TypeError('expected an... | python |
from django.urls import path, include
from django.contrib import admin
from django.views.decorators.csrf import csrf_exempt
from rest_framework import routers, urlpatterns
from .views import *
urlpatterns = [
path("register/", Register.as_view(), name="register-user"),
]
| python |
import re
import storage
import args
import requests
import concurrent.futures
from bs4 import BeautifulSoup
from urllib.parse import urlparse, urljoin
class NaiveCrawler:
def __init__(self, initial_url, allowed_domains, depth, database, init=True):
self.init = init
self.initial_url = initial_url
... | python |
from django.urls import path
from .views import DocumentAPIView, DocumentDetails
urlpatterns = [
path('document/', DocumentAPIView.as_view()),
path('document/<int:id>/', DocumentDetails.as_view()),
]
| python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.