content stringlengths 5 1.05M |
|---|
import cimodel.data.simple.util.branch_filters as branch_filters
from cimodel.data.simple.util.docker_constants import (
DOCKER_IMAGE_NDK, DOCKER_REQUIREMENT_NDK
)
class AndroidJob:
def __init__(self,
variant,
template_name,
is_master_only=True):
sel... |
# Copyright 2019-2020 The ASReview 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 appl... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# GUI module generated by PAGE version 4.21
# in conjunction with Tcl version 8.6
# Apr 21, 2019 05:48:53 PM +0530 platform: Windows NT
import sys
import tkinter
from tkinter import messagebox
from tkinter import *
import mysql.connector
import dbConne... |
'''
Code to evaluate a particular trained network. Think about formatting results
here well to be tables in the paper.
'''
import sklearn.metrics as skmetrics
from collections import Counter
from util import get_window
class Eval:
'''
Methods to evaluate different models.
'''
def __init__(self, test... |
#!/usr/bin/env python
# coding=utf-8
"""
A sample application for cmd2.
This example is very similar to example.py, but had additional
code in main() that shows how to accept a command from
the command line at invocation:
$ python cmd_as_argument.py speak -p hello there
"""
import argparse
import random
import cm... |
from pynotifier import Notification
from .ims import IMS
from threading import Timer, Thread
import time
import pandas as pd
class Bot:
def __init__(self, id, pw, interval = 5 * 60, alert_types = ['new']):
self.ims = IMS(id, pw)
self.interval = interval
self.init_variables()
self.al... |
import random
from collections import defaultdict
import numpy as np
class Member:
def __init__(self, r_d, label=None, doc_id=None):
self._r_d = r_d
self._label = label
self._doc_id = doc_id
class Cluster:
def __init__(self):
self._centroid = None
self._members = []
... |
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... |
from app import db
class Position(db.Model):
id = db.Column(db.Integer, primary_key=True)
account_id = db.Column(db.Integer, db.ForeignKey('account.id'), nullable=False)
stock_id = db.Column(db.Integer, db.ForeignKey('stock.id'), nullable=False)
cost_basis = db.Column(db.Float(decimal_return_scale=2), ... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.HomePageView.as_view(), name='index'),
url(r'^good/$', views.GoodView.as_view(), name='good'),
url(r'^bad/$', views.BadView.as_view(), name='bad'),
]
|
import os
from . import minneapolis_park_board
from . import migrated
from . import mn_state
def _load_minneapolis_park_board(resource_path):
results = []
path = os.path.join(resource_path, 'minneapolis_park_board')
for year in range(2007, 2018):
filename = '{0}.csv'.format(year)
full_pat... |
import boto3
import base64
def decrypt(event, context):
encrypted = bytes(event['secret'], 'ascii')
decoded = base64.b64decode(encrypted)
kms = boto3.client('kms')
decrypted = kms.decrypt(CiphertextBlob=decoded)
return decrypted['Plaintext']
|
import os
import django
DEBUG = True
USE_TZ = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "uzbLoOIYlJnzGDYlUfynNyocjZH9NLSc3AAREwLDaugQkCzsQn"
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
'OPTIONS': {
... |
import sys
import os
import automl_data_processing as app
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
import os
import cv2
import numpy as np
def draw_output(all_matches, obs_matches, kp1, output):
""" Writes output image to file.
Params:
all_matches: All matches found from Orb matcher.
obs_matches: Matches after matches have been filtered.
kp1: Keypoints from image 1 (current image).... |
# netchat session object
import pexpect
import sys
from .exception import ParameterError
from .constant import status, spawn
from .script import Script
class Session():
"""connect to a listening TCP port and perform expect/send interaction
:param: address: (host, port) for TCP connection
:type: addres... |
import sys
import filetype
import magic
import shutil
import os
import xml.etree.ElementTree as ET
import base64
import filetype
import datetime
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
from pathlib import Path
from os.path import isfile, join, basename, dirname, getsize, abspath
from... |
import os
import pytest
from pytest_insta import SnapshotFixture
from beet.toolchain.config import load_config
@pytest.mark.parametrize("directory", os.listdir("tests/config_examples"))
def test_config_resolution(snapshot: SnapshotFixture, directory: str):
project_config = load_config(f"tests/config_examples/{d... |
# coding=utf-8
# @Time: 2022/1/12 15:42
# @Author: forevermessi@foxmail.com
|
"""Test cases for io.py."""
import json
from ..unittest.util import get_test_file
from .io import dump, group_and_sort, load, parse
from .typing import Frame
def test_parse() -> None:
"""Test parse label string."""
raw = json.loads(
'{"name": 1, "videoName": "a", "size": {"width": 10, "height": 20}, ... |
# Generated by Django 3.1 on 2020-09-29 05:34
import django.db.models.deletion
import django_extensions.db.fields
from django.conf import settings
from django.db import migrations, models
import library.django_utils.django_file_system_storage
class Migration(migrations.Migration):
initial = True
dependenc... |
# settings/local_pydanny.py
# to use this setting you must run:
# python manage.py runserver --settings=config.settings.local
from .local import *
# Set short cache timeout
CACHE_TIMEOUT = 30
|
#!/usr/bin/python3
EMPTY_SEQUNCE = 'ε'
class Rule:
def __init__(self, input_symbols, output_symbols):
if input_symbols is None or output_symbols is None:
raise ValueError("Invalid rule arguments")
self._input_symbols = input_symbols
self._output_symbols = output_symbols
@p... |
#
# PySNMP MIB module F3-ESM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/F3-ESM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:11:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... |
from django.forms import ModelForm
from .models import Post, Comment
class PostForm(ModelForm):
class Meta:
model = Post
fields = ['title', 'post_text', 'subreddit']
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ['text']
|
from importlib import reload
import argparse
import sys
import asyncio
import sc2
import bot
from bot import SimpleBot
from sc2 import Race, Difficulty
from sc2.player import Bot, Computer
import random
from sc2.constants import *
from sc2.position import Point2
class RampWallBot(sc2.BotAI):
async def on_step... |
def is_valid(checksum: int) -> bool:
return checksum % 11 == 0
def verify(isbn: str) -> bool:
isbn = isbn.replace("-", "")
check_sum = 0
if not len(isbn) == 10:
return False
for index, digit in enumerate(isbn):
if index == len(isbn) - 1 and digit == "X":
digit = "10"
... |
#########################
# 演示各种String的常用操作方法
#########################
from pkg.Tools import print_divider
str1 = "abcdefghijklmnopqrstuvwxyz"
str2 = 'life is short, i use python, i love python'
str3 = '演示各种 String 的常用操作方法'
str4 = 'python.py'
str5 = 'ad dsf \t sfdf \n sdfdf j sd l a\t dsf da r \t sdfa fd '
# find... |
import os
import shutil
import stat
import tempfile
from pathlib import Path
import pytest
from pyprojectx.wrapper import pw
@pytest.fixture
def tmp_dir():
path = tempfile.mkdtemp(prefix="build-env-")
yield Path(path)
shutil.rmtree(path)
@pytest.fixture(scope="session")
def tmp_project():
tmp = Pa... |
from __future__ import print_function
import csv, collections, os, sys
# args
# 1: cdr -- a3 or b3
# 2: stcr_data directory -- ...stcr_data/ -- should contain <cdr>/details/*.tsv
# 3: IMGT-renumbered structures directory -- ...all_structures/imgt/
# ex: python get_cdrs_stcr.py b3 ../datasets/stcr_data/ ~/Downloads/all... |
from flask import Flask, abort, request, jsonify
from datetime import date, datetime
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import func
import os, json, logging
import playerRankings as rank
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
db = SQLAlchemy(ap... |
#!/usr/bin/env python3
''' Creates Neo4j index and constraints for Canonicalized KG2
Usage: create_indexes_constraints_canonicalized.py [--passwordFile=<password-file-name>] <Neo4j Username> [<Neo4j Password>]
'''
import argparse
import neo4j
import getpass
import sys
import json
__author__ = 'Erica Wood'
__copyr... |
from plenum.common.roles import Roles
from plenum.common.transactions import PlenumTransactions
class Command:
def __init__(self, id, title, usage, note=None, examples=None):
self.id = id # unique command identifier
self.title = title # brief explanation about the command
self.usage = us... |
#
# Copyright (c) Microsoft Corporation. All Rights Reserved.
#
"""
This module is a wrapper around ivy2's logic representation for
copmpatibility with ivy1 code.
Ivy1 uses a sorted first-order logic.
Constants (both first and second-order) are represented by class
Symbol. Variables are represented by class Variable.... |
import pandas as pd
import numpy as np
import math
c_mean=2
k_mean=1
c_sig=2
k_sig=1
df = pd.read_csv('normal.csv')
lr=0.07/len(df)
nrounds=10000
def erf(x):
# save the sign of x
sign = np.sign(x)
x = abs(x)
# constants
a1 = 0.254829592
a2 = -0.284496736
a3 = 1.421413741
a4 ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'variable.ui'
#
# Created by: PyQt4 UI code generator 4.12.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
import FFT_Variable
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
... |
"""
This section covers functionality for computing predictions
with a [NERDA.models.NERDA][] model.
"""
from NERDA.preprocessing import create_dataloader
import torch
import numpy as np
from tqdm import tqdm
from nltk.tokenize import sent_tokenize, word_tokenize
from typing import List, Callable
import transformers
... |
from bs4 import BeautifulSoup
import urllib2
import cookielib
from getpass import getpass
import sys
import time
import click
def run():
cric=urllib2.urlopen("http://www.cricbuzz.com")
html=cric.read()
soup=BeautifulSoup(html)
scoreall=soup.find_all("div",class_="cb-ovr-flo")
list=[]
c=0
for li... |
import setuptools
import codecs
with codecs.open('README.rst', encoding='utf8') as fh:
long_description = fh.read()
setuptools.setup(name='xlogit',
version='0.2.0-beta1',
description='A Python package for GPU-accelerated ' +
'estimation of mixed logit models.',
... |
import subprocess
from subprocess import PIPE
import json
import cson as cson_lib
cson_lib.loads
def cson2json(cson):
if cson is None:
return None
result = cson_lib.loads(cson)
return result
|
from flaskeztest import RouteEZTestCase, expect_fixture
class IndexOneTestCase(RouteEZTestCase):
FIXTURE = 'oneuser'
def runTest(self):
RouteEZTestCase.runTest(self)
expectation = expect_fixture('oneuser')
self.assert_expectation_correct(expectation)
|
# Tek tırnak veya çift tırnak aynı şeyi yapar. Ancak noktlama işaretlerini kullanmak için her ikisini de kullanmamız gerekir
print("Neler neler yapıyorsun bensizken Ankara'da?")
# Üç tırnak ise fazla satırlı tanımlamalar için kullanılabilir.
print("""Neler neler yapıyorsun
bensizken Ankara'da?""")
##################... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Copyright (c) Merchise Autrement [~º/~] and Contributors
# All rights reserved.
#
# This is free software; you can do what the LICENCE file allows you to.
#
from xoeuf import fields, models, api
MIXI... |
import numpy
from datetime import datetime
import Files.FetchData as FD
dbName = 'market_data'
stockCollName = 'stock_data'
indexCollName= 'benchmark_data'
data = FD.findDataWithFilters_AllFields(dbName,stockCollName,{'Ticker':'AAPL'},[('Date',1)])
# for val in data:
# print(val.get('Close'))
# for data in FD.fin... |
from django.http import HttpResponse
import datetime
from django.template import Template, Context
from django.template.loader import get_template
from django.shortcuts import render
class Persona(object):
def __init__(self, name, last_name):
self.name=name
self.last_name=last_name
def saludo(request):
do... |
from peewee import *
from faker import Faker
# Para generar valores random en los rows
fake = Faker()
# Crea conexión con la DB
db = PostgresqlDatabase(
'random_cats',
user='the_cat',
password='secretcat123',
host='localhost',
port=5432
)
# ORM con una tabla
class MyCats(Model):
nombre = CharFie... |
#!/usr/bin/env python3
# Copyright © 2019-2020 Broadcom. All rights reserved.
# The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may also obtain a copy of th... |
import datetime
from django.db import models
class Trade(models.Model):
"""
A model to hold trade information - stored, per `symbol` per `time_stamp`.
"""
SYM_LFZ = "LFZ"
SYM_EURGBP = "EUR/GBP"
SYM_6A = "6A"
SYM_FDAX = "FDAX"
SYMBOL_CHOICES = (
(SYM_LFZ, "LFZ"),
(SYM... |
import unittest
from netengine import get_version, __version__
from netengine.backends import BaseBackend
from netengine.exceptions import NetEngineError
__all__ = ['TestBaseBackend']
class TestBaseBackend(unittest.TestCase):
def test_version(self):
get_version()
__version__
def t... |
# Picon Zero Servo Test
# Use arrow keys to move 2 servos on outputs 0 and 1 for Pan and Tilt
# Use G and H to open and close the Gripper arm
# Press Ctrl-C to stop
import tty
import termios
import sys
sys.path.insert(0, "../../lib/PiconZero/Python")
import piconzero as pz
#========================================... |
# -*- coding: utf-8 -*-
"""AG module containing base Asset class and associated enums
This module contains all of the necessary components for the proper
function of standard asset classes within AlphaGradient, as well as
the API.
Todo:
* Complete google style docstrings for all module components
* Complete f... |
from __future__ import unicode_literals
from django.apps import AppConfig
class PollsConfig(AppConfig):
name = 'polls'
|
import cherrypy, os, sys, json
import helpers
class Settings(object):
def __init__(self):
cherrypy.engine.subscribe('settings-broadcast', self.listen)
return
def listen(self, m):
if m['type'] == 'settings':
# print(m)
f = open('settings.json', 'r')
... |
# -*- coding: utf-8 -*-
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('common', '0002_address'),
]
operations = [
migrations.AddField(
model_name='address',
name='label',
field=models.CharField(defa... |
import types
try:
from .config import *
except ImportError:
from .config_example import *
DB_SQLITE_SQL_GETVAR = "SELECT data FROM `main` WHERE variable=? AND user=?"
DB_SQLITE_SQL_INSERTVAR = "INSERT INTO `main` (`user`, `variable`, `data`) VALUES (?, ?, ?)"
DB_SQLITE_SQL_UPDATEVAR = """
UPDATE main
SET ... |
import numpy as np
# Load data
data = np.loadtxt('challenges/01-sonar-sweep/input.txt', dtype=int)
# Perform a sliding window summation per 3 elements
data = np.convolve(data, np.ones(3, dtype=int), 'valid')
# Calculate the differences
diffs = np.diff(data)
# Get the ones that have positive difference
has_increased... |
import sys
# TODO: Investigate more precise timing libraries
import time
from contentcuration.models import ContentKind, ContentNode, File
def print_progress(text):
sys.stdout.write("\r" + text)
sys.stdout.flush()
class Objective:
"""
Objective is a class that provides tools for measuring and explor... |
# Copyright 2019 Mycroft AI 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 writin... |
import pandas as pd
import numpy as np
from uszipcode import SearchEngine
import sqlite3
search = SearchEngine(db_file_dir="/tmp/db")
conn = sqlite3.connect("/tmp/db/simple_db.sqlite")
pdf = pd.read_sql_query("select zipcode, lat, lng, radius_in_miles,
bounds_west, bounds_east, bounds_north,... |
"""Tests for selection functions."""
import numpy as np
import condense.optimizer.masking_functions as mf
from logging import info
def test_mask_min_value():
"""Testing default selection function."""
test_array = np.array([[1, 4, 3], [4, 2, 6]])
mask = mf.mask_min_value(test_array, 0.5)
assert (mas... |
import discord
ICE_BLUE = discord.Color.from_rgb(207, 242, 255)
|
import logging
import typing
from abc import ABC
from abc import abstractmethod
from vk.utils.mixins import MetaMixin
if typing.TYPE_CHECKING:
from vk.bot_framework.dispatcher.dispatcher import Dispatcher
T = typing.TypeVar("T")
logger = logging.getLogger(__name__)
class AbstractExtension(ABC, MetaMixin):
... |
from plot_events import *
from helper_functions import *
from random import randint
# TODO: Consider separating out all conversion functions into their own file
def test_convert_event_to_boxes(faker) -> None:
"""Test that an `Event` can be converted into a list of `EventBox`s on different days (one event can be ... |
#
# Copyright (c) 2021 Joe Todd
#
# 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, distribu... |
import os
import pytest
import mne
from meegpowreg.power_features import compute_features
data_path = mne.datasets.sample.data_path()
data_dir = os.path.join(data_path, 'MEG', 'sample')
raw_fname = os.path.join(data_dir, 'sample_audvis_raw.fif')
frequency_bands = {'alpha': (8.0, 15.0), 'beta': (15.0, 30.0)}
def t... |
import numpy as np, os, itertools
import pandas as pd
from rpy2 import robjects
import rpy2.robjects.numpy2ri
rpy2.robjects.numpy2ri.activate()
import rpy2.robjects.pandas2ri
from rpy2.robjects.packages import importr
from .comparison_metrics import (sim_xy,
glmnet_lasso,
... |
from pyxdameraulevenshtein import damerau_levenshtein_distance
from doublemetaphone import dm
import json
import sys
#---------------------------------------------------------------------------
# EDIT DISTANCE SEARCH
#---------------------------------------------------------------------------
def load_... |
#!/usr/bin/env python
# filename: pl.py
#
# Copyright (c) 2021 Bryan Briney
# License: The MIT license (http://opensource.org/licenses/MIT)
#
# 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 w... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from downward import suites
import common_setup
REVS = ["issue546-base", "issue546-v1"]
LIMITS = {"search_time": 1800}
SUITE = suites.suite_optimal_with_ipc11()
CONFIGS = {
"seq_opt_fdss_1": ["--alias", "seq-opt-fdss-1"],
"seq_opt_fdss_2": ["--alias", "seq-opt... |
from __future__ import absolute_import
from __future__ import unicode_literals
from datetime import datetime
from corehq.toggles import EMG_AND_REC_SMS_HANDLERS, NAMESPACE_DOMAIN
from custom.ilsgateway.tanzania.reminders import REC_HELP, REC_CONFIRMATION, REC_ERROR, INVALID_PRODUCT_CODE
from custom.ilsgateway.tests.ha... |
"""
TODO:
1) Move final data to a real object; needs better and named structure
2) Give all data on return; fix connections across project
3) Move plotting to a separate optional place
"""
import json
import statistics as s
from pathlib import Path
from copy import deepcopy
from datetime import datetime, ... |
import sys
from typing import List
sys.setrecursionlimit(10 ** 5)
def partition(array: List, start: int, end: int) -> int:
"""
Helper function for quick_sort
Partitions array around a pivot
such that elements to the right of pivot are > pivot
elements to the left of pivot < pivot
and pivot i... |
# coding: utf-8
import socketserver
import os
# Copyright 2013 Abram Hindle, Eddie Antonio Santos
#
# 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/L... |
from ftis.corpus import Corpus
from ftis.world import World
import argparse
parser = argparse.ArgumentParser(description="Process input and output location")
parser.add_argument(
"-i",
"--input",
default="~/corpus-folder/corpus1",
type=str,
help="Folder for input. This should contain some audio fi... |
import os
import pytz
settings = {}
settings["TIMEZONE"] = pytz.timezone("America/Chicago")
settings["FPS"] = 29.969664
settings["FRAME_INTERVAL"] = "0.03336707S"
settings["starttime_file"] = "../../dataset/Sense2StopSync/start_time.csv"
settings["starttime_train_file"] = "../../dataset/Sense2StopSync/start_time_trai... |
"""
Tests for Docking
"""
from __future__ import division
from __future__ import unicode_literals
__author__ = "Bharath Ramsundar"
__copyright__ = "Copyright 2016, Stanford University"
__license__ = "MIT"
import unittest
import os
from nose.plugins.attrib import attr
from nose.tools import nottest
import sys
import ... |
# -*- coding:utf-8 -*-
def application(environ,start_response):
start_response('200 OK', [('Content-Type','text/html')])
return [b'<h1>Hello world!</h1>'] |
from pythondjangoapp.settings.base import *
DEBUG = True
INSTALLED_APPS += (
# other apps for local development
)
|
import unittest
from queue import Queue
from threading import Thread
from time import sleep
from satella.coding import Monitor
class MonitorTest(unittest.TestCase):
def test_synchronize_on(self):
class TestedMasterClass(Monitor):
def __init__(self):
self.value = 0
... |
from distutils.util import strtobool
from typing import Dict
from ..common.config import AppConfigReader
from ..common.icons import Icon, Icons
from ..pull_requests import PullRequestSort, PullRequestStatus
class GitlabMrsConstants(object):
MODULE = "gitlab_mrs"
TIMEOUT_MESSAGE = "Timeout while trying to co... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask, request
import app_05_db
# -- 関数 -- #
def shutdown_server():
""" サーバー停止 """
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
# -- 初期... |
import math
import sys
from PyQt5 import QtGui
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class DrawPoints(QWidget):
def __init__(self):
super(DrawPoints, self).__init__()
self.init()
def init(self):
self.setGeometry(300, 300, 300, 300)
... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
import datetime
from seir.wrapper import MultiPopWrapper
from seir.utils import plot_solution
# read calibration data
actual_hospitalisations = pd.read_excel('data/calibration.xlsx', sheet_name='Hospitalisations')
actual_hospitalisa... |
### Dependent packages ###
import time
import sys, os
import numpy as np
import scipy as sp
from scipy import optimize
from ..util.div import formattime, len_none
from ..util.linalg import jitchol, try_jitchol, triang_solve, mulinv_solve, chol_inv, traceprod, nearestPD
from ..util.stats import norm_cdf_int, norm_cdf_i... |
from graper.spiders import *
from graper.utils import log
import js2py
import json
import datetime
import openpyxl
import tqdm
logger = log.get_logger(__file__)
class AppListSpider(Spider):
"""
采集指定行业下的APP列表
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
encrypt_j... |
"""
- What is Dogeon?
Dogeon is a simple, fast, complete, correct and extensible DSON <http://dogeon.org>
encoder and decoder for Python 2.5+ and Python 3.3+.
It is pure Python code with no dependencies.
The encoder can be specialized to provide serialization in any kind of situation,
without any special support by t... |
from six.moves import xrange
class Communicator(object):
def communicate(self, visualizer, solution, visualizer_cb, solution_cb):
visualizer_cb(visualizer.readline(), flush=False) # maxPercentage
line = visualizer.readline() # H
visualizer_cb(line, flush=False)
for i in xrange(in... |
# Python3 code to delete middle of a stack
# without using additional data structure.
# Deletes middle of stack of size
# n. Curr is current item number
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
d... |
"""
Helper methods to demangle an ILIAS date.
"""
import datetime
import locale
import logging
import re
from typing import Optional
from ..logging import PrettyLogger
LOGGER = logging.getLogger(__name__)
PRETTY = PrettyLogger(LOGGER)
def demangle_date(date: str) -> Optional[datetime.datetime]:
"""
Demangl... |
# Generated by Django 3.0.3 on 2020-02-25 07:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('datahub', '0006_auto_20200224_1212'),
]
operations = [
migrations.AddField(
model_name='train',
name='trainCategory'... |
# Generated by Django 2.2.1 on 2019-05-16 11:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('music', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='songs',
name='album',
field=m... |
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import decomposition
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
from scipy import linalg as LA
def run_pca_np(x):
#centering the data
... |
"""
.. currentmodule:: flytekitplugins.sqlalchemy
This package contains things that are useful when extending Flytekit.
.. autosummary::
:template: custom.rst
:toctree: generated/
SQLAlchemyConfig
SQLAlchemyDefaultImages
SQLAlchemyTask
"""
from .task import SQLAlchemyConfig, SQLAlchemyDefaultImages, ... |
'''
Created on 13.06.2016
@author: Fabian Reiber
@version: 1.0
'''
class NoSignedPartException(Exception):
def __str__(self, *args, **kwargs):
return Exception.__str__(self, *args, **kwargs) |
import matplotlib.pyplot as plt
import numpy as np
from ezmodel.models.mean import SimpleMean
from ezmodel.models.svr import SVR
from ezmodel.util.sample_from_func import sine_function
svm = SVR()
# create some data to test this model on
X, y, _X, _y = sine_function(20, 200)
# let the model fit the data
svm.fit(X,... |
from datetime import datetime
from rich import print
def time_now():
dt = datetime.now()
dtime = dt.strftime("%X")
return f"[italic white]{dtime}[/] |"
class console():
def nanostyle(text): print(f'[magenta]{text}[/magenta]')
def log(text): print(f'{time_now()} [[dim]INFO[/]]:\t{text}')
d... |
# Support Python 2 and 3 API calls without importing
# a 3rd party library
try:
from urllib.request import Request as HTTPRequest
from urllib.parse import urlencode
except ImportError: # pragma: no cover
from urllib2 import Request as HTTPRequest # pragma: no cover
from urllib import urlencode # prag... |
import random
import aiarena21.server.settings as settings
from aiarena21.server.item import Item1, Item2, Item3
from opensimplex import OpenSimplex
from aiarena21.server.logs import log, replay
class Game:
def __init__(self, players):
self.current_round = 0
self.total_rounds = settings.TOTAL_ROUN... |
/usr/lib/python3.6/encodings/cp866.py |
import torch
import numpy as np
import yaml
from collagen.data import FoldSplit
from collagen.core.utils import auto_detect_device
from collagen.strategies import Strategy
from collagen.data.utils.datasets import get_mnist
import random
from tensorboardX import SummaryWriter
from examples.autoencoder.utils import i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.