content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
# Switches workers between queues based on queue load and worker activity
import argparse
import logging
import traceback
import requests
import json
import time
import datetime
import sys
import threading
import worker_functions.constants as constants
# zookeeper
from kazoo.client import Kaz... |
# -*- coding: utf-8 -*-
"""
Utilities to use nilearn.image from nipype
"""
def ni2file(**presuffixes):
from functools import wraps
""" Pick the nibabel image container output from `f` and stores it in a file.
If the shape attribute of the container is True, will save it into a file, otherwise
will di... |
from .Specification import Specification, TypedProperty
__all__ = ['RelationshipSpecification', 'ParentGroupingRelationship',
'WorkflowRelationship']
class RelationshipSpecification(Specification):
"""
RelationshipSpecifications are used mainly with \ref
python.implementation.ManagerInterfaceBase.ManagerIn... |
from .shield import Shield |
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from future.builtins import (ascii, bytes, chr, dict, filter, hex, input,
int, map, next, oct, open, pow, range, round,
str, super, zip)
from subproces... |
#!/usr/bin/env python3
from sys import argv, stderr, stdout
from bakery import render_path
if len(argv) != 2:
stderr.write("Usage: render.py NAME\n")
exit(1)
stdout.write(render_path(argv[1]))
|
#!/usr/bin/python3
# Convert a binary to a fake "standard" assembler file
import sys
import struct
with open(sys.argv[1], "rb") as f:
code = f.read()
for i in range(0, len(code), 2):
print(" data $%04x" %struct.unpack(">H", code[i:i+2]))
|
# 旋转数组的最小数字
# 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
# 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
# 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
# NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
class Solution:
def minNumberInRotateArray(self, rotateArray):
minNum = 0
# 第一种方法,就是遍历所以的元素,找出最小的
for i in range(0, len(rotateArray)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from redis import ConnectionPool, StrictRedis
class RedisQ(object):
redis_client = StrictRedis
def __init__(self, connection_pool=None, url=None, **connection_params):
if url:
connection_pool = ConnectionPool.from_url(
url, de... |
from importlib import import_module
import logging
import os
import subprocess
import sys
from typing import Any, Sequence
from alembic import script
from alembic.migration import MigrationContext
from flogging import flogging
from mako.template import Template
from sqlalchemy import any_, create_engine
from sqlalchem... |
from common import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django_mongodb_engine', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'intranet_test', # Or path to database file if using sql... |
import logging
import os
import sys
import time
from typing import Union
from io import IOBase
from .base import Client
from tftpy.shared import TIMEOUT_RETRIES
from tftpy.packet import types
from tftpy.exceptions import TftpException,TftpTimeout,TftpFileNotFoundError
from tftpy.states import SentReadRQ,S... |
# Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
import os
import sys
import third_party
from util import run_output, build_path
out_filename = sys.argv[1]
args_list = run_output([
third_party.gn_path, "args",
build_path(), "--list", "--short", "--overrides-only"
],
... |
# Copyright (c) 2019 Nikita Tsarev
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# dis... |
from django.test import TestCase
from _apis.models import Telegram
from _setup.models import Config
from random import randint
class TelegramTestCase(TestCase):
def test_message(self):
if Telegram().setup_done:
messages = Config('UNITTESTS.TELEGRAM_TEST_MESSAGES').value
selected_me... |
Labels = (
('help_wanted', 'Help Wanted'),
('idea', 'Idea'),
('something_interesting', 'Something Interesting'),
)
|
from celery import Celery # noqa
"""
app = Celery('tasks', broker='pyamqp://guest@localhost//')
@app.task
def add(x, y):
return x + y
"""
|
from django.core.exceptions import ValidationError
from django.test import TestCase
from model_bakery import baker
from game_hub.accounts.models import GameHubUser
from game_hub.games.models import Game, Comment, LikeGame
class TestGameCreateModel(TestCase):
def test_game_title_validator_only_letters_numbers_an... |
from collections import defaultdict
from random import randint
from linked_list import LinkedList
import numpy as np
class Generator(object):
demand_bound = None
dmin = None
dmax = None
omin = None
omax = None
options = None
time_span = None
demand = None
number_of_different_so... |
from math import gcd
def lcm(*num):
num = list(num)
if str(type(num[0])) == "<class 'list'>":
num = num[0]
len_num = len(num)
if len_num < 2:
return None
elif len_num == 2:
a = num[0]
b = num[1]
return int(a * b / gcd(a, b))
else:
num[0] = lcm(nu... |
import pandas as pd
#날짜 형식의 문자열로 구성되는 리스트 정의
dates = ['2019-01-01','2020-03-01','2021-06-01']
#문자열 배열을 판다스 Timestamp로 변환
ts_dates = pd.to_datetime(dates)
print(ts_dates)
#Timestamp를 Period 로 변환
pr_day = ts_dates.to_period(freq='D')
print(pr_day)
pr_month = ts_dates.to_period(freq='M')
print(pr_month)
pr_year = ts_d... |
__id__ = "$Id: orthogonality.py 155 2007-08-31 20:11:54Z jlconlin $"
__author__ = "$Author: jlconlin $"
__version__ = " $Revision: 155 $"
__date__ = "$Date: 2007-08-31 14:11:54 -0600 (Fri, 31 Aug 2007) $"
"""This script will investigate how orthogonal my basis vectors really are. """
import random
import ... |
x = 13
print(x.bit_length())
print(x.__doc__)
print(x.__int__())
|
from ibai_exceptions import ExistingAuctionException, AuctionException, CategoryException
class Category:
def __init__(self, name):
"""Initialize a new category
:param name: name of the category
"""
if len(name) < 1:
raise Exception("Invalid Name")
self.name = ... |
import connexion
from flask_cors import CORS
from os import environ
from nova_api import create_api_files
debug = environ.get('DEBUG') or '0'
if debug == '0':
debug = False
elif debug == '1':
debug = True
port = int(environ.get('PORT')) if environ.get('PORT') else 80
ENTITIES = environ.get('ENTITIES') or ''
... |
import subprocess
for i in range(87,119):
for j in range(1,4):
i = i%100
url = f"https://stepdatabase.maths.org/database/db/{i:02}/{i:02}-S{j}.pdf"
subprocess.run(["wget", url])
for i in range(87,119):
for j in range(1,4):
i = i%100
url = f"https://stepdatabase.maths.or... |
from guizero import App, Box, Text, PushButton, Combo, Slider
def switch_screen(switch_to):
hide_all()
switch_to.show()
def hide_all():
for screen in all_screens:
screen.hide()
app = App("Multi box app", layout="grid")
# Create a blank list to hold all the different screens
all_screens = []
# ... |
import os
import os.path
import copy
import botocore.exceptions
from boto import cloudformation, sts
from troposphere import Parameter
from .template import Template
from . import cli
from . import resources as res
from fnmatch import fnmatch
from . import utility
from . import monitor
import json
TIMEOUT = 60
class... |
'''
경로 압축 알고리즘이면
union에서 그냥 Parent 찾아도 될 거 같긴한데,
그래도 root를 찾는 함수를 쓰도록 하자! (헷갈리지 않게)
7 8
0 1 3
1 1 7
0 7 6
1 7 1
0 3 7
0 4 2
0 1 1
1 1 1
>>
NO
NO
YES
'''
N, M = map(int, input().split())
data = []
for _ in range(M):
data.append(list(map(int, input().split())))
# debug
# print(N, M)
# print(data)
def find_parent(... |
# coding: utf-8
#Tom G.
from PIL import Image
import time
#Constantes
_DEBUTCHAINE = bytearray([0,129])
_FINCHAINE = bytearray([129,0])
def steganographie_ecrire(cheminImage, texteACacher):
image = ouvrir_fichier(cheminImage)
if(image != 0):
tailleImage = taille_image(image)
tab... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
################################################################################
# Copyright (c) 2019 University of Utah Student Computing Labs.
# All Rights Reserved.
#
# Author: Thackery Archuletta
# Creation Date: Oct 2018
# Last Updated: March 2019
#
# Permission to use, c... |
#https://nordvpn.com/
import os
import requests
from db.db import Database
class nordvpn:
def __init__(self,):
self.db = Database()
url = 'https://nordvpn.com/wp-admin/admin-ajax.php?searchParameters[0][name]=proxy-country&searchParameters[0][value]=&searchParameters[1][name]=proxy-ports&searchPar... |
# -*- coding: utf-8 -*-
"""
movies related genres component module.
"""
from pyrin.application.decorators import component
from pyrin.application.structs import Component
from charma.movies.related_genres import RelatedGenresPackage
from charma.movies.related_genres.manager import RelatedGenresManager
@component(Re... |
import unittest
from .door2 import solve, solve2
class ExampleTestsPartOne(unittest.TestCase):
def test_example(self):
self.assertEqual(solve('5 1 9 5\n7 5 3\n2 4 6 8'), 18)
def test_1(self):
self.assertEqual(solve('5 2 9 5\n7 5 3 12\n1 4 6 8'), 23)
def test_2(self):
self.assertE... |
# -*- coding: UTF-8 -*-
"""Client CLI entrypoint"""
import argparse
import sys
import requests
import six
from scriptd.app import util
from scriptd.app.exceptions import AuthenticationError
import scriptd.app.protocol
from scriptd.app.protocol import ScriptdProtocol
def main():
argparser = argparse.ArgumentPar... |
# -*- coding: utf-8 -*-
#
# Copyright 2015 Thomas Amland
#
# 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 l... |
from .base import SkeletonType
from .openpose_base import (
BODY_25,
BODY_25_JOINTS,
BODY_25_LINES,
FACE_LINES,
HAND_LINES,
UPPER_BODY_25_LINES,
)
from .reducer import SkeletonReducer
from .utils import incr, root_0_at
def compose_body(body=None, left_hand=None, right_hand=None, face=None):
... |
import numpy as np
import torch
from torch.autograd import Variable
'''
Sample a random unit vector in d dimensions by normalizing i.i.d gaussian vector
Input: d - dimensions
'''
def sample_random_unit(d):
gaussian = np.random.normal(size=d)
unit = gaussian / np.linalg.norm(gaussian)
return torch.tensor(unit)
'''... |
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
import sys
import unittest
class IsInstanceTest(unittest.TestCase):
def test_isinstance_metaclass(self):
... |
# base_trainer.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
class BaseTrainer(object):
def __init__(self, config, data, logger, model, session):
self.config = config
self.data = data
self.logger = ... |
# ------------------------------------------------------------
# Copyright (c) 2017-present, SeetaTech, Co.,Ltd.
#
# Licensed under the BSD 2-Clause License.
# You should have received a copy of the BSD 2-Clause License
# along with the software. If not, See,
#
# <https://opensource.org/licenses/BSD-2-Clause>
#
# ... |
import torch
import torch.nn.functional as F
import horovod.torch as hvd
def accuracy(output, target):
# get the index of the max log-probability
pred = output.max(1, keepdim=True)[1]
return pred.eq(target.view_as(pred)).cpu().float().mean()
def save_checkpoint(model, optimizer, checkpoint_format, epoch):... |
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
RESTART: C:\Users\Akshat\AppData\Local\Programs\Python\Python35\mergesort.py
[1, 2, 3, 4, 6, 71, 123]
>>>
RESTART: C:\Users\Akshat\AppData\Local\Progra... |
#!/usr/bin/env python
print "Content-type: text/plain\n\n"
import psycopg2
conn = psycopg2.connect("host=localhost dbname=siki user=siki password=qwerty")
cur = conn.cursor()
cur.execute("SELECT * FROM pdata")
for row in cur:
print row
cur.close()
conn.close()
|
"""Test cases for the document module."""
import pytest
from pytest_mock import MockFixture
from rdflib import Graph
from skolemizer.testutils import skolemization
from modelldcatnotordf.document import FoafDocument
from tests.testutils import assert_isomorphic
def test_instantiate_document() -> None:
"""It doe... |
"""Module to create, remove, and manage trades currently in play in running strategies"""
import logging
logger = logging.getLogger(__name__)
class Position:
def __init__(self, market, amount, price):
self.market = market
self.amount = amount
self.price = price
def update(self):
... |
# coding: utf-8
import time
from nose.tools import ok_
from mockidp.saml.response import saml_timestamp
def test_saml_timestamp():
t = time.time()
x = saml_timestamp(t)
ok_(len(x) > 1)
|
import test_support
import time
import unittest
class TimeTestCase(unittest.TestCase):
def setUp(self):
self.t = time.time()
def test_data_attributes(self):
time.altzone
time.daylight
time.timezone
time.tzname
def test_clock(self):
time.clock()
def t... |
import math
from functools import reduce
import torch
import torch.nn as nn
import pytorch_acdc as dct
from torch.utils.checkpoint import checkpoint
class ACDC(nn.Module):
"""
A structured efficient layer, consisting of four steps:
1. Scale by diagonal matrix
2. Discrete Cosine Transform
... |
import random
from cpu.cpu import Cpu
from game.transforms import Board
from .services import find_winning_position
# Author: Xavier
class Experimental(Cpu):
def name(self):
return 'Xavier''s AI 1.0'
def play(self, board: Board, player_side, opposing_side):
winning_position = find_winning_p... |
# -*- coding:utf-8 -*-
# https://leetcode.com/problems/minimum-window-substring/description/
class Solution(object):
def minWindow(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
wi, wj = None, None
ds, dt = {}, {}
for c in t:
d... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.account_login, name="account_login"),
path('register/', views.account_register, name="account_register"),
path('logout/', views.account_logout, name="account_logout"),
]
|
import unittest
import random
from LinkedList import SinglyLinkedList
RANDMAX = 100
'''
ATTRIBUTES:-
self.test_list -> A python list which contains the elements in order
self.test_SinglyLinkedList -> The actual Singly Linked List Object to do operations
test_insert -> A random test element to insert in the List
test_i... |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 ... |
from RNA_describe import *
from ORF_eliminator import *
from RNA_gen import *
class Simulator:
def get_random_sequence(self):
'''
This is Professor Miller's class that generates a RNA sequence
without any restriction.
'''
generator = Collection_Generator()
sequence_l... |
import re
import time
import praw
from prawcore.exceptions import PrawcoreException
from database import TaskerNetDatabase
from utils import TASKERNET_RE, PRAW_SITE_NAME, MONITORED_SUBREDDITS
reddit = praw.Reddit(PRAW_SITE_NAME)
subreddit = reddit.subreddit(MONITORED_SUBREDDITS)
db = TaskerNetDatabase()
running = ... |
import json
import scipy.io as scio
def pa_out(name_data, label_data, attributes_dict):
# 筛选列表
stander_list_upper_wear = ["ShortSleeve", "LongSleeve", "LongCoat"]
stander_list_lower_wear = ["Trousers", "Shorts", "Skirt&Dress"]
stander_list_upperbodycolor = []
stander_list_lowerbodycolor = []
s... |
"""
Convert RUSA Perms report CSV to
the CSV format we'll use for mapping.
Besides selecting and renaming columns, the
transformations are:
* Inactive routes are omitted
* If a route is reversible AND point-to-point,
it is duplicated with from and two locations
reversed
"""
import csv
import sys
import schemata... |
# kytten/dialog.py
# Copyrighted (C) 2009 by Conrad "Lynx" Wong
import pyglet
from pyglet import gl
from widgets import Widget, Control, Label
from button import Button
from frame import Wrapper, Frame
from layout import GetRelativePoint, ANCHOR_CENTER
from layout import VerticalLayout, HorizontalLayout
... |
import os
import sys
import getopt
import lxml.html
import tqdm
from datetime import datetime
from urllib.request import Request
from urllib.request import urlopen
# Helper function to print srcipt usage command
def print_usage():
print('Usage:')
print('\t1. python %s' % __file__)
print('\t2. python %s -s ... |
from enum import Enum
import numpy as np
import math
import lib.config as C
import lib.utils as U
import time
from strategy.agent import Agent as A
from unit.units import Army
import unit.protoss_unit as P
class ProtossAction(Enum):
Do_nothing = 0
Build_worker = 1
Build_zealot = 2
Build_pylon = 3
... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime
# Function to plot diurnal variaiton for given dataframe as input
# Plot mean diurnal variation PM2.5
def plot(dfmod, dfobs, mod, obs, mod_stdev=None, obs_stdev=None):
"""
Python function to plot the diurnal variation for... |
# this will generate suppl fig 4 A - D (4 matrices of covariance analysis)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
# need ana_rd and ana_all_rd from analysis.py
ana = ana_all_rd
conn_data = ana.conn_data['glom_kc_in_claw_unit']
ob_conn, glom_prob, glom_idx_ids... |
# ------------------------------------------
# Copyright (c) Rygor. 2021.
# ------------------------------------------
from .api import (
Sap_system,
TasksException,
add,
run,
delete,
update,
pw,
start_sap_db,
stop_sap_db,
list_systems,
query_param,
database
)
__ver... |
# File: chaos.py
# A simple program illustating chaotic behavior.
"""Modify the chaos program from section 1.6 so it prints out 20 values instead
of 10."""
def main():
print("This program illustates a chaotic function")
x = eval(input("Enter a number between 0 and 1: "))
for i in range(20):
x = 3.9... |
default_port = {
'mongo': 27017,
'mysql': 3306,
'postgres': 5432,
'redis': 6379,
'hbase': 9090,
'elasticsearch':9200
}
|
import bpy
from bpy.props import *
from ...nodes.BASE.node_base import RenderNodeBase
def update_node(self, context):
self.execute_tree()
class RSNodeLuxcoreRenderSettingsNode(RenderNodeBase):
"""A simple input node"""
bl_idname = 'RSNodeLuxcoreRenderSettingsNode'
bl_label = 'Luxcore Settings'
... |
'''
Exercício Python 093: Crie um programa que gerencie o aproveitamento
de um jogador de futebol. O programa vai ler o nome do jogador e quantas
partidas ele jogou. Depois vai ler a quantidade de gols feitos em cada partida.
No final, tudo isso será guardado em um dicionário, incluindo o total de gols
feitos durante o... |
import metadata
import xml.etree.ElementTree as etree
import os
def read_file(file_name):
obj = []
levels = []
level = -1
word = ''
with open(file_name, 'r', encoding='utf-8-sig') as f:
for line in f:
for c in line[:-1]:
if c in ',{}':
if wo... |
import pymysql
import sqlalchemy
from sqlalchemy import Column, DateTime, Integer, create_engine, func
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy.orm import sessionmaker
from settings import DB_LINK
pymysql.install_as_MySQLdb()
class BaseModelClass:
@declared_attr
... |
# Copyright 2017 Google Inc. 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 a... |
from .fetcher import Fetcher
name = "reference_sequence_fetcher"
|
import subprocess
import json
import sqlite3
from .fixtures import *
def test_depth_flag_is_accepted(process, disable_extractors_dict):
arg_process = subprocess.run(["archivebox", "add", "http://127.0.0.1:8080/static/example.com.html", "--depth=0"],
capture_output=True, env=disab... |
import hyperchamber as hc
from shared.ops import *
from shared.util import *
import os
import time
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import ops
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
learning... |
'''
Manage Azure Cosmos DB Cassandra tables.
'''
from .... pyaz_utils import _call_az
from . import throughput
def create(account_name, keyspace_name, name, resource_group, schema, analytical_storage_ttl=None, max_throughput=None, throughput=None, ttl=None):
'''
Create an Cassandra table under an Azure Cosmos... |
"""
whodunit.py
Computer Science 50 in Python
Problem Set 5
Decypher message hidden in BMP.
Run without arguments for usage.
"""
from sys import argv, exit
import struct
import Image
if __name__ == "__main__":
# Ensure proper usage
if not len(argv) == 3:
print "Usage: copy infile outfile"
exi... |
import torch
from torch import nn as nn
from basicsr.archs.buildingblocks import DoubleConv, ExtResNetBlock, create_encoders, create_decoders
from basicsr.utils.registry import ARCH_REGISTRY
def number_of_features_per_level(init_channel_number, num_levels):
return [init_channel_number * 2 ** k for k in range(num... |
import bilevel_solver
bilevel_solver.all_pivots_dot(
[
[0.000000, 0.000000, 1.00000, 1.00000, 6.000000, 1.000000, 2.000000, 0.000000, 0.000000, 510.000000],
[0.000000, 6.000000, 5.000000, 5.000000, 0.000000, -1.00000, 4.000000, 0.000000, 0.000000, 90.000000],
[0.000000, 0.000000, -5.00000, -5.00000, 0.000000, 1.0... |
import numpy as np
def griewank(P):
return (
1
+ (P**2).sum(axis=1) / 4000
- np.prod(
np.cos(
P/np.sqrt(
np.arange(1, P.shape[-1] + 1)
)
),
axis=1
)
)
def rast(P):
n = P.shape[-1]
... |
import re, subprocess
from smsgateway.sources.sms import command_list
from smsgateway.config import *
from smsgateway.sources.utils import *
service_commands = ['start', 'restart', 'stop', 'enable', 'disable', 'status']
service_regex = re.compile('^(?P<command>[a-zA-Z]+) (?P<service>.+)$')
def run_cmd(args):
ret... |
import argparse
import sys
from ledger import classproperty
from ledger.command import Command
from ledger.command.output import chunks
from ledger.transaction import Transaction
class Delete(Command):
names = ("delete", "del")
def __call__(self, args):
args = self.parser.parse_args(args)
if n... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '0'
from numpy.random import randn, randint
from decimal import Decimal
from tqdm import tqdm
import pickle
from tensorflow.keras.utils import plot_model
from cDCGAN.Discriminator import make_discriminator
from cDCGAN.Generator import make_generator
import tensorf... |
import os
import random
import torch
from PIL import Image
from torch.utils import data
from torchvision import transforms as T
class CelebA_withname(data.Dataset):
"""Dataset class for the CelebA dataset."""
def __init__(self,
image_dir,
attr_path,
selected... |
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
import argparse
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import StratifiedKFold
def RF_Classifier(X, y, indep=None, fold=5, n_trees=100, out='RF_output'):
"""
Parameters:
----------
:... |
import subprocess
import sys
import setup_util
import os
from zipfile import ZipFile
def start(args, logfile, errfile):
setup_util.replace_text("play-scala-mongodb/conf/application.conf", "jdbc:mysql:\/\/.*:3306", "jdbc:mysql://" + args.database_host + ":3306")
subprocess.check_call("play clean dist", shell=True... |
__version_info__ = ('1', '10', '12')
__version__ = '.'.join(__version_info__)
from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper,
BoundFunctionWrapper, WeakFunctionProxy, resolve_path, apply_patch,
wrap_object, wrap_object_attribute, function_wrapper,
wrap_function_wrapper... |
#!/usr/bin/env python
# -------------------------------------------------
# This script is for changing names of .png images.
# Written by Xiaoming Zhao
# -------------------------------------------------
import os
import sys
import glob
import argparse
def parse_args():
parser = argparse.ArgumentParser(
... |
import datetime
import functools
import logging
import os
import time
import gobject
import gtk
from tornado import ioloop
from tornado.log import gen_log
class GtkIOLoop(ioloop.IOLoop):
READ = gobject.IO_IN
WRITE = gobject.IO_OUT
ERROR = gobject.IO_ERR | gobject.IO_HUP
def initialize(self, time_f... |
from typing import Dict
import gym
import numpy as np
from ding.envs import ObsNormWrapper, RewardNormWrapper, DelayRewardWrapper, FinalEvalRewardEnv
def wrap_mujoco(
env_id,
norm_obs: Dict = dict(use_norm=False, ),
norm_reward: Dict = dict(use_norm=False, ),
delay_reward_step: int = ... |
import sys
from io import StringIO
from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QObject
from PyQt5.QtGui import QCloseEvent, QShowEvent, QTextCursor, QTextOption
from PyQt5.QtWidgets import qApp, QDialog, QDialogButtonBox, QStyleFactory, QTextEdit, QVBoxLayout
# documentation from vidcutter... let's see ... |
''' Distutils / setuptools helpers '''
import os
from os.path import join as pjoin, split as psplit, splitext
try:
from ConfigParser import ConfigParser
except ImportError:
from configparser import ConfigParser
from distutils.version import LooseVersion
from distutils.command.build_py import build_py
from dis... |
import numpy as np
mu = 0.1
nu = 0.2
lam = 0.3
G = np.array([[1,0,0],[0,1,0],[mu,nu,lam]])
G_inv_T = np.linalg.inv(G.T)
print (G,"G")
print (G_inv_T,"G_inv_T")
# print(G.dot(G_inv_T.T),"G.dot(G_inv_T)") |
"""Host built-in actions."""
from __future__ import annotations
import random
from typing import TYPE_CHECKING, List, Union
from voiceassistant.skills.create import action
if TYPE_CHECKING:
from voiceassistant.core import VoiceAssistant
@action("say")
def say(vass: VoiceAssistant, text: Union[str, List[str]])... |
import os, sys, importlib
from csalt.synthesize import make_template, make_data
from csalt.utils import cubestats, img_cube
sys.path.append('configs/')
cfg = 'FITStest'
# only need to do this **one time**.
make_template(cfg)
# impose a model onto the synthetic tracks
make_data(cfg, mtype='FITS', new_template=False... |
# TODO can we use explicit imports?
from bigchaindb.db.utils import *
|
from xml.etree import cElementTree as ElementTree
from casexml.apps.case.mock import CaseBlock
from dimagi.utils.chunked import chunked
from corehq.apps.hqcase.utils import submit_case_blocks
from corehq.form_processor.interfaces.dbaccessors import CaseAccessors
from corehq.apps.locations.models import SQLLocation
fr... |
#! /usr/bin/env python3
import os
import numpy as np
from scipy.io import loadmat
from sklearn import linear_model
from sklearn import svm
from sklearn.neural_network import MLPRegressor as nnr
import cPickle
from scipy import misc
import glob
import sys
import random
from computeOrupdateERD import ... |
# Most lines' ref-ID are refer back to the same original ID,
# which means those lines' User and Resource are the same. For this
# reason, we can exculde User and Resource in transaction. When node
# queries User and Resource, the baseline4 first get its original
# Node+ID, and use Node+RID to query additional resu... |
#!/usr/bin/env python
import sys
import os
import subprocess
import time
import argparse
import tempfile
import shutil
import glob
import multiprocessing
def ingest(ns):
procs = dict()
def spawn(afile):
print "Ingest %s" % afile
proc = subprocess.Popen([ns.script, afile])
procs[proc.p... |
import os
import json
import pytest
import tempfile
from pathlib import Path
from jina.hubble import helper
@pytest.fixture
def dummy_zip_file():
return Path(__file__).parent / 'dummy_executor.zip'
def test_parse_hub_uri():
result = helper.parse_hub_uri('jinahub://hello')
assert result == ('jinahub', '... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.