content stringlengths 5 1.05M |
|---|
#
# Copyright 2020 XEBIALABS
#
# 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, distribute, subli... |
# coding: utf-8
import warnings
from traitlets.config.application import catch_config_error
from .releaseassignmentapp import ReleaseAssignmentApp
class ReleaseApp(ReleaseAssignmentApp):
@catch_config_error
def initialize(self, argv=None):
super(ReleaseApp, self).initialize(argv=argv)
msg = ... |
def hw1p3b():
from sklearn.datasets import load_boston
import numpy as np
from numpy import linalg as linalg
boston = load_boston()
b_data = boston.data
b_target = boston.target
t0 = np.median(b_target)
divider = 406
x_train = b_data[:divider,:] # N*D
bDataTestS = b_data[divid... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `nameko_structlog` package."""
from unittest.mock import MagicMock, call
from nameko.testing.services import entrypoint_hook
import structlog
class TestingStructlogProcessor:
"""
Testing StuctlogProcessor that make use of `ReturnLogger`.
"""
... |
from .clean import clean_json |
"Unit tests of array functions."
import unittest
import numpy as np
from numpy.testing import assert_almost_equal, assert_equal, assert_raises
nan = np.nan
from la import larry
from la.missing import nans, missing_marker, ismissing
class Test_nans(unittest.TestCase):
"Tes... |
#! /usr/bin/python3
# (c) Copyright 2019-2022, James Stevens ... see LICENSE for details
# Alternative license arrangements possible, contact me for more information
""" module to resolve DNS queries into DoH JSON objects """
from syslog import syslog
import socket
import select
import argparse
import os
import json
i... |
import os
import re
import csv
import argparse
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence
class Lang(object):
""" creates word-index mappings
"""
def __init__(self, name):
self.name = name
self.word2... |
import os, sys, string, re, time
import marshal
from log import *
import time,hashlib
import neo_cgi, neo_util
from clearsilver import odb, hdfhelp, odb_sqlite3
class WhichReadDB(odb.Database):
def __init__ (self, conn):
odb.Database.__init__(self, conn)
self.addTable("whichread", "wr_whichread", Whic... |
# Copyright (c) 2015, the Fletch project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE.md file.
{
'target_defaults': {
'include_dirs': [
'../../',
],
},
'targets': [
{
... |
Version = "3.56.0"
|
from slot import Slot
class Recipient:
def __init__(self, recipient_id:str, email:str, first_name:str, last_name:str, age:int):
self.__recipient_id = recipient_id
self.__email = email
self.__first_name = first_name
self.__last_name = last_name
self.__age = age
self._... |
from bean import RuleBuilder
bot_host = "127.0.0.1" # 机器人host
bot_port = "8080" # 机器人port
qq_group = [123456, 987654] # 生效群
compress_kb = 500 # 压缩图片大小, 单位为kb
bot_img_file_dir = r"C:\酷Q Pro\data\image" # 酷q机器人接收图片位置, 如图位置
APP_ID = 123456 # 从tx云获取的api
APP_KEY = 'jlKkjKOWtEogd'
# 规则
rules = RuleBuilder()\
.ad... |
import sys
import random
import datetime
import time
class utils:
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
__version__ = '0.1'
@staticmethod
def num_to_short_alphanumeric(i):
chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXY'
length = len(chars)
result = ''
while i:
res... |
"""Preprocessing mainly cares about constructing a DAG before we start processing.
The shared layers and models are also duplicated duing this procedue.
"""
import logging
import onnx as O
import keras as K
from keras.models import Sequential
from . import helper
from .exceptions import FeatureNotImplemented, OnnxNotS... |
# ###########################################################################
#
# CLOUDERA APPLIED MACHINE LEARNING PROTOTYPE (AMP)
# (C) Cloudera, Inc. 2021
# All rights reserved.
#
# Applicable Open Source License: Apache 2.0
#
# NOTE: Cloudera open source products are modular software products
# made up of hun... |
class Game:
def __init__(self, players) -> None:
super().__init__()
self.players = list()
self.num_players = players
for i in range(players):
self.players.append(Player(i + 1))
self.circle = Circle()
def play_until(self, last_marble):
for i in range(... |
#xorshift method https://en.wikipedia.org/wiki/Xorshift
class fastrand:
def __init__(self, seed=0x956126898):
self.rctr = seed
def rand(self):
self.rctr %= 0xFFFFFFFF
self.rctr ^= (self.rctr << 13)
self.rctr %= 0xFFFFFFFF
self.rctr ^= (self.rctr >> 7)
self.rctr ... |
from typing import List
class Solution:
def trap(self, height: List[int]) -> int:
before = 0
sum = 0
for i in range(1, len(height)):
if height[i] >= height[before]:
for j in range(before + 1, i):
sum += height[before] - height[j]
... |
"""Dialog State Tracker Interface"""
from abc import abstractmethod
from tatk.util.module import Module
class Tracker(Module):
"""Base class for dialog state tracker models."""
# @abstractmethod
def update(self, action):
""" Update the internal dialog state variable.
Args:
ac... |
#!/usr/bin/env python
import sys
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
setup(name='treetagger',
version='1.1.1',
description='A Pytho... |
"""
PyDelphin contains modules for working with the (in)formalisms of the
DELPH-IN ecosystem.
"""
|
from typing import Any
import tensorflow as tf
import numpy as np
from teal import RandomGain
from tests.utils import get_audio_examples
from tests.common import TealTest
class TestRandomGain(TealTest.TealTestCase):
def setUp(self):
self.power = 2
self.setup_layer(
layer=RandomGain(1.0... |
import easyocr
import os
import pandas as pd
from PIL import Image
import numpy as np
import time
import spacy
from spacy_langdetect import LanguageDetector
import streamlit as st
import de_core_news_sm
import en_core_web_sm
from langdetect import detect, DetectorFactory
DetectorFactory.seed = 0
im... |
from __future__ import annotations
from typing import Any, TYPE_CHECKING
from pathmagic.helper import PathLike
from .format import Format
if TYPE_CHECKING:
from pathmagic.file import File
class Serialized(Format):
extensions = {"pkl"}
def __init__(self, file: File) -> None:
from iotools impo... |
'''
Picks a subset of the validation set for grid_search
Script arguments:
1: directory containing validation ppm images
2: output directory
3: how many images will be picked
'''
import random
import os
import sys
from shutil import copyfile
all_files = os.listdir(sys.argv[1])
all_file... |
# An element in linked list
class Node:
def __init__(self, value):
self.value = value
self.prev = None
self.next = None
class CircularDoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
self.index = self.head
se... |
# Angus Dempster, Francois Petitjean, Geoff Webb
# Dempster A, Petitjean F, Webb GI (2019) ROCKET: Exceptionally fast and
# accurate time series classification using random convolutional kernels.
# arXiv:1910.13051
import argparse
import numpy as np
import pandas as pd
import time
from numba import njit, prange
fro... |
import argparse
import os
import numpy as np
import random
import imagegen
import matplotlib.pyplot as plt
import cv2
from PIL import Image
import matplotlib.colors as color
#import matplotlib.image as mpimg
import matplotlib
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-n... |
from setuptools import setup
from os import path
here = path.abspath(path.dirname(__file__))
setup(
name='bokchoy',
version='1.0.0',
description='Simple distributed task queue using NSQ',
url='https://github.com/ulule/bokchoy',
author='Ulule',
author_email='tech@ulule.com',
license='MIT',
... |
from asyncpg.exceptions import PostgresError
from bot.exceptions import (NotEnoughPrefixes, PrefixExists,
PrefixDoesntExist)
class GuildCache:
def __init__(self, bot):
self._bot = bot
self.guilds = {}
@property
def bot(self):
return self._bot
def ... |
import typing
import tempfile
class FileHelper:
'''Context manager to use files in pulzar
'''
def __init__(self) -> None:
pass
def __enter__(self):
pass
def __exit__(self, *args):
pass |
# file1=open('text.txt','w')
# print(file1.write('\n'+'test append'))
"""
ТЗ:
По данным введенным пользователем вычислить, сможет он купить выбранный им товар или нет.
Если товар в списке отсутствует - NOT OK
__________
Входные данные: название товара,кол-во товара, наличные
Реализовать 2+ функциями
Выходные данные: с... |
"""This module contains the GeneFlow DataManager class."""
import inspect
from geneflow.uri_parser import URIParser
from geneflow.log import Log
from geneflow.extend import data_manager_contexts
class DataManager:
"""
Copy/move, list, delete data for various contexts.
Currently, these contexts include... |
from rest_framework import serializers
from .models import ExternalLink
class ExternalLinkSerializer(serializers.ModelSerializer):
class Meta:
model = ExternalLink
fields = '__all__'
|
# Copyright (C) 2018 lukerm
#
# 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 writ... |
import asyncio
import sys
import threading
import time
from concurrent.futures import CancelledError
from contextlib import suppress
import pytest
from anyio import (
create_blocking_portal, create_capacity_limiter, create_event, create_task_group,
run_async_from_thread, run_sync_in_worker_thread, sleep, star... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
import regex
from jsonpath_rw import parse
from .constants import EdgeConstants
class CreateOptionParser(object):
def __init__(self, create_option):
self.create_option = create_option
def parse_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from test.common import test_dict
from box import Box, ConfigBox
class TestConfigBox:
def test_config_box(self):
g = {
"b0": "no",
"b1": "yes",
"b2": "True",
"b3": "false",
"b4": True,
"... |
def dev_only(func, *args, **kwargs):
def inner(*args, **kwargs):
request = kwargs.get("request", args[0])
# Check host
host = request.get_host()
if env_from_host(host) != "DEV":
raise Http404
else:
return func(*args, **kwargs)
return inner
def n... |
#!/usr/bin/env python
import argparse
import os
import shutil
import sys
def validate(srcdir):
"""
Check if `srcdir` has an index.html in it.
"""
indexpath = os.path.join(srcdir, "index.html")
if not os.path.exists(indexpath):
print("Missing index.html file in", srcdir)
return Fals... |
# Generated by Django 3.0.6 on 2020-06-18 08:59
from django.conf import settings
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
("posthog", "0060_au... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import signal
import logging
import urllib2
import json
import time
import ble_codes
import util
import multiprocessing as mp
from util import current_milli_time
# ----------------------------------------
# BLE state machine definitions
# ------------------... |
from bs4 import BeautifulSoup
from ..occurrences.occurrences import Occurrences
from ..occurrences.occurrence_interface import OccurrenceInterface
class Recommendation16:
"""
Recomendação 16 – Identificar o idioma principal da página
"""
def __init__(self, sourcecode):
self.rec = 16
... |
from . import device
class USF5P(device.Device):
def __init__(self, site, data):
super(USF5P, self).__init__(site, data)
self.port = {}
self.parse_stat(data['stat'])
self.parse_uplink(data.get('uplink'))
self.parse_port_table(data['port_table'])
self.general_temper... |
import random
import numpy as np
from numpy import array, mod, floor, ceil, sin, cos, dot
from OpenGL.GL import *
from PyEngine3D.Utilities import normalize
from PyEngine3D.OpenGLContext import CreateTexture, Texture2D, Texture2DArray, Texture3D, TextureCube
def generate_3d_data(size):
value = 255.0 / float(si... |
#!/usr/bin/env python3
"""
A simple caching layer on top of a TANGO database.
"""
from collections import OrderedDict
from tango import Database, DeviceProxy, GreenMode
from tangogql.ttldict import TTLDict
class CachedMethod(object):
"""A cached wrapper for a DB method."""
def __init__(self, method, ttl=... |
""" This scripts uploads location database to sdd-db """
import os
import re
import pandas as pd
from datetime import datetime
# compatibility with ipython
try:
__IPYTHON__
os.chdir(os.path.dirname(__file__))
except: pass
import json
import boto3
from pathlib import Path
from shapely.geometry import Point
import... |
def tensor_out_in_axis(tensor):
nndct_layouts = {2: 'OI', 4: 'OHWI'}
data_format = nndct_layouts[tensor.ndim]
out_axis = data_format.index('O')
in_axis = data_format.index('I')
return out_axis, in_axis
|
import sys
from . import system_tools
TEST_CON = 'test_constants'
test_constants = {'tri_a_T':1, 'tri_b_T': 1,
'tim_a_T':1,'fil_a_T':1.,'cons_T':1,
'tri_a_S':1,'cons_S':1}
# These constants come from the Major Variables script that ran on
# tornado in serial
system_constants = {'... |
from . import transformation
import copy
import collections
import operator
import logging
logger = logging.getLogger(__name__)
class Grid:
def __init__( self):
"""
grid is a list of pairs: the grid coord and associated attributes (e.g., width, color)
"""
self.grid = []
sel... |
from paddle.trainer_config_helpers import *
settings(
batch_size=1000,
learning_rate=1e-5
)
din = data_layer(name='data', size=30)
data_seq = data_layer(name='data_seq', size=30)
outputs(expand_layer(input=din, expand_as=data_seq,
expand_level=ExpandLevel.FROM_SEQUENCE),
expand_l... |
# -*- coding: UTF-8 -*-
from collections import *
import heapq
class Priority_Queue(object):
"""
by XRH
date: 2020-05-01
利用堆实现 优先队列
提供以下功能:
1.根据主键直接访问 堆中的元素,包括读取和更新
2.选择 比较大小 进而做相应的堆调整 的键
3.当前最小键 从堆中 弹出
4.元素插入,并调整堆
"""
def __init__(self, initial=None, ke... |
#!/usr/bin/env python3
'''
This is a simple control application for the servos on the box.
The application itself writes the control ommands for the servoblaster on stdout so it
can be directly forwarded by netcat.
The servo IDs (Channel IDs of servoblaster are hardcoded here)
'''
import sys
from time import sleep
... |
"""
"Genyal" (c) by Ignacio Slater M.
"Genyal" is licensed under a
Creative Commons Attribution 4.0 International License.
You should have received a copy of the license along with this
work. If not, see <http://creativecommons.org/licenses/by/4.0/>.
"""
from random import Random
from typing import Any, Callable, List,... |
__version_info__ = (1, 1, 3)
__version__ = ".".join("{0}".format(x) for x in __version_info__)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
__title__ = 'yorktown'
__author__ = 'Jonathan Kelley'
__version__ = '0.0.1'
__license__ = 'FreeBSD'
__copyright__ = 'Copyright 2018 BoomTown LLC'
MODULES = [
'demo',
'gitexec',
'jenkins',
]
|
import os
import jax
from jax import numpy as jnp
def run_cmd(x):
os.system(x)
def test_platform_allocator():
os.environ["XLA_PYTHON_CLIENT_ALLOCATOR"] = "platform"
#os.environ["XLA_PYTHON_CLIENT_PREALLOCATE"] = "false"
a = jnp.ones(1 << 30)
run_cmd("nvidia-smi")
a = None
run_cmd("nvi... |
'''
Web sederhana pemetaan kecelakaan
mirip first news app
'''
# app.py >> konfigurasi untuk server & route ada di sini
import csv
from flask import Flask
from flask import abort
from flask import render_template
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
def get_csv():
csv_path = './... |
#!/usr/bin/env python3
import argparse
from blockchain_fundamentals import *
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Perform the SHA256 function on input string. Can be hex or ascii.')
parser.add_argument('value', metavar='value')
args = parser.parse_args()
result = s... |
import logging
import redis
import os
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from mapofinnovation.lib.base import BaseController, render
log = logging.getLogger(__name__)
class WikiapiController(BaseController):
def getWikiLink... |
# -*- python -*-
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis <michael.aivazis@para-sim.com>
#
# (c) 2013-2018 parasim inc
# (c) 2010-2018 california institute of technology
# all rights reserved
#
# the package
import altar
# my protocol
from .Monitor import Monitor as monitor
# an implementation of the monito... |
# -*- coding: utf-8 -*-
"""save_princess_peach.__init__.py
Initialize file.
"""
|
from fastapi import APIRouter
from .allocations import router as allocation_router
from .portfolios import router as portfolio_router
from .assets import router as asset_router
from .transactions import router as transaction_router
from .incomes import router as income_router
from .stats import router as dashboard_rou... |
import os
# Configure Test Environment
def get_env(variable_name: str) -> str:
"""Returns a environment variable"""
try:
var = os.environ[variable_name]
if not var:
raise RuntimeError(f"Variable is null, Check {variable_name}.")
return var
except KeyError:
raise... |
import time
import multiprocessing as mp
from tqdm import trange
import torch.nn as nn
from torch.utils.data import DataLoader
from torchio import ImagesDataset, Queue, DATA
from torchio.data.sampler import ImageSampler
from torchio.utils import create_dummy_dataset
from torchio.transforms import (
ZNormalizatio... |
import unittest
from malcolm.modules.builtin.vmetas import BooleanArrayMeta
class TestValidate(unittest.TestCase):
def setUp(self):
self.meta = BooleanArrayMeta("test description")
def test_init(self):
assert "test description" == self.meta.description
assert self.meta.label == ""
... |
"""empty message
Revision ID: 0148_add_letters_as_pdf_svc_perm
Revises: 0147_drop_mapping_tables
Create Date: 2017-12-01 13:33:18.581320
"""
# revision identifiers, used by Alembic.
revision = "0148_add_letters_as_pdf_svc_perm"
down_revision = "0147_drop_mapping_tables"
from alembic import op
def upgrade():
o... |
# html helpers
from lxml import html
def make_source_link(kind: str, stage: str, name: str) -> html.Element:
d = html.Element("span")
if kind != stage and kind != "source":
a = html.Element("a")
# "http://covid19-api.exemplartech.com/github-data/raw/AZ.html
a.attrib["href"] = f"../{stag... |
from aiohttp import web
from src.combinators import AmountCombinator, CurrencyCombinator, ReferenceDateCombinator, validate_payload
from src.prices_service import PricesServiceImpl
from src.utils import catch_exceptions
from src.vo_service import MicroCurrencyConverterVOServiceImpl
routes = web.RouteTableDef()
prices... |
# -*- coding: utf-8 -*-
"""
@author: dong.lu
@contact: ludong@cetccity.com
@software: PyCharm
@file: phrase.py
@time: 2018/11/15 14:18
@desc: 从大量语料中统计预选短语的
`
"""
import math
from collections import Counter
import numpy as np
from src.linefile import persistence
class PhraseMine(object):
def __init__(self,... |
# note: qt and kivy use different i18n methods
# FIXME all these messages *cannot* be localized currently!
def to_rtf(msg):
return '\n'.join(['<p>' + x + '</p>' for x in msg.split('\n\n')])
MSG_CAPITAL_GAINS = """
This summary covers only on-chain transactions (no lightning!). Capital gains are computed by attac... |
import os
from instaloader import Instaloader, Post, Profile
from zipfile import ZipFile
class IGDownloader:
"""IGDownloader Class - takes login username and password as argument"""
def __init__(self, login_username, login_password):
self.loader = Instaloader()
self.loader.login(login_username... |
# flake8: noqa
# import all models into this package
# if you have many models here with many references from one model to another this may
# raise a RecursionError
# to avoid this, import only the models that you directly need like:
# from from fds.sdk.SPAREngine.model.pet import Pet
# or import this package, but bef... |
from kombu import Connection
from .resolver_types import RESOVLER_TYPE_MAP
from .resolver_types import DnsService
import toml
import os
import socketserver
import logging
class ClownFactory(object):
REQUIRED_BLOCKS = ['dnstap', 'dnsproviders']
REQUIRED_DNSTAP = ['dns_host', 'dns_port']
@classmethod
... |
import string
LOWERCASE_OFFSET = ord("a")
ALPHABET = string.ascii_lowercase[:16]
def b16_encode(plain):
enc = ""
for c in plain:
binary = "{0:08b}".format(ord(c))
enc += ALPHABET[int(binary[:4], 2)]
enc += ALPHABET[int(binary[4:], 2)]
return enc
def shift(c, k):
t1 = ord(c) ... |
#!/usr/bin/env python
'''
This file makes an docx (Office 2007) file from scratch, showing off most of python-docx's features.
If you need to make documents from scratch, use this file as a basis for your work.
Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing informat... |
"""
The ordinal directions.
A collection of normalized vectors to be referenced by name.
Best used for the positions or facings of :class:`Sprites <ppb.Sprite>`.
"""
from ppb_vector import Vector
Up = Vector(0, 1).normalize() #: Unit vector to the top of the screen from center.
Down = Vector(0, -1).normalize() #: ... |
import json
import random
WEEKDAYS = {
"mon": 'Понедельник',
"tue": 'Вторник',
"wed": 'Среда',
"thu": 'Четверг',
"fri": 'Пятница',
"sat": 'Суббота',
"sun": 'Воскресенье'
}
ICONS = {
"travel": "⛱",
"study": "🏫",
"work": "🏢",
"relocate": "🚜",
"programming": "🎮"
}
de... |
# -*- coding: utf-8 -*-
"""
Various utilities for processing physiological data. These should not be called
directly but should support wrapper functions stored in `peakdet.operations`.
"""
from functools import wraps
import inspect
import numpy as np
from peakdet import physio
def make_operation(*, exclude=None):
... |
# 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... |
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred')
app.logger.error('An error occurrd')
return "Hello Workd"
if __name__ == '__main__':
app.run(debug=True)
|
#!/usr/bin/env python
#
# Map weather service icon codes to my limited set held on the e-ink device
#
def interpret_icons(service,id):
if service == "openweathermap":
icons = {
"200": {
"label": "thunderstorm with light rain",
"icon": "RAIN"
},
"201": {
"labe... |
from django.contrib import admin
from .models import Acta, Grupo, Lote, Rodado, Subasta, Tipo
class ActaAdmin(admin.ModelAdmin):
filter_horizontal = ('profesionales', )
class GrupoAdmin(admin.ModelAdmin):
list_display = ['subasta',
'numero',
'martillero']
class Rod... |
# Copyright (c) Facebook, Inc. and its affiliates.
import numpy as np
import torch
from tools.utils import Timer
from torch.utils.data.sampler import Sampler
from torch._six import int_classes as _int_classes
class SceneBatchSampler(Sampler):
def __init__(self, sampler, batch_size, drop_last, \
train=True,... |
import unittest, time, sys
sys.path.extend(['.','..','py'])
import h2o
import h2o_hosts
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def setUpClass(cls):
global localhost
localhost = h2o.decide_if_localhost()
if (localhost)... |
import fnmatch
from functools import partial
import click
import storefact
import yaml
from kartothek.api.discover import discover_cube
__all__ = ("filter_items", "get_cube", "get_store", "to_bold", "to_header")
def get_cube(store, uuid_prefix):
"""
Get cube from store.
Parameters
----------
u... |
import os
import csv
import pandas
from sklearn.svm import LinearSVC
from sklearn import linear_model, metrics
from sklearn.model_selection import train_test_split
from scipy.sparse import csr_matrix
from questionparser import QuestionParser
CORPUS_DIR = os.path.join(os.path.dirname(__file__), 'corpus')
def compare_mo... |
import requests,subprocess,copy,time
import boto3, json
import sys,os
from netaddr import *
from requests.packages.urllib3 import Retry
from kubernetes.client.rest import ApiException
from kubernetes import client, config
from pprint import pprint
from ipassignhelper import *
### Class, representing a worker... |
# -*- coding:utf-8 -*-
"""
A tensorflow implementation for text matching
model in paper MV-LSTM.
author: Bin Zhong
data: 2018-11-12
"""
import tensorflow as tf
class MVLSTM(object):
def __init__(
self, max_len_left, max_len_right, vocab_size,
embedding_size, num_hidden, num_k, l2_reg_lambda=0.0):
... |
"""Revelation root module with package info"""
from .app import Revelation
__author__ = "Humberto Rocha"
__email__ = "humrochagf@gmail.com"
__version__ = "2.0.0"
__all__ = ["Revelation"]
|
#!/usr/bin/env python3
rules = {}
tickets = []
with open('input.txt', 'r') as input:
l = input.readline().strip()
while l != "":
idx = l.index(':')
name = l[:idx]
rules_str = l[idx + 1:].split(' or ')
ranges = []
for r in rules_str:
idx = r.index('-')
... |
#!/usr/bin/env python
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (t... |
from tkinter import *
from .internals import *
import os
import importlib
class MainOS(Tk):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.app_path = os.path.join('os_main', 'apps')
self.wm_attributes('-fullscreen', True)
self.config(bg="orange")
... |
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
import time
# Initial shapes.
class Gaussian:
def __init__(self, a, b, c, k):
self.a = a
self.b = b
self.c = c
self.k = k
def r_at(self, x):
return self.a * np.exp(-(0.5... |
import sys
import re
from .anjuke import community as anjuke_community
from .juejin import posts as juejin_posts
from .juejin import books as juejin_books
from . import __version__
def _print_welcom():
print('=========================================\nHi, guy! Welcome to use kcrwaler v{} !\nhttps://github.com/kenb... |
import pytest
pytestmark = [
pytest.mark.django_db,
pytest.mark.usefixtures('ten_percent_promocode'),
]
@pytest.fixture(autouse=True)
def _freeze_stripe_course(mocker):
mocker.patch('stripebank.bank.StripeBank.ue', 70) # let it be forever :'(
@pytest.mark.parametrize('code', [
'TESTCODE',
'tes... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
# 测试是否成功连接MySQL数据库,每隔3秒中检查一次
import time
import MySQLdb
def sleeptime(hour,min,sec):
return hour*3600 + min*60 + sec;
second = sleeptime(0,0,3)
# 打开数据库连接
conn = MySQLdb.connect("localhost","root","123456","crm" )
while 1==1:
print "do action"
# 使用cursor()... |
import numpy as np
import csv
import datetime as dt
def split_csv(in_file_path, out_dir_path):
"""
Splits csv data file into smaller pieces using ticker names. It saves
split data as numpy arrays.
:param in_file_path: path to csv file
:param out_dir_path: path to output directory
:return: -
... |
import sys
from lib2to3 import refactor
# The original set of these fixes comes from lib3to2 (https://bitbucket.org/amentajo/lib3to2):
fix_names = set([
'libpasteurize.fixes.fix_add_all__future__imports', # from __future__ import absolute_import etc. on separate lines
'libpasteurize.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.