content stringlengths 5 1.05M |
|---|
from Model.Direction.CardinalDirection.XDirection.xdirection import XDirection
class EAST (XDirection):
def __str__ (self): return 'l' |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/2/20 下午1:38
# @Author : sws
# @Site : 使用 ForkingMixin
# @File : forking_mixin_socket_server.py
# @Software: PyCharm
import os
import socket
import threading
import SocketServer
SERVER_HOST = 'localhost'
SERVER_PORT = 0 # 动态是设置端口
BUF_SIZE = 10
ECH... |
from scipy.signal import find_peaks , find_peaks_cwt
import scipy.stats as stats
import matplotlib.pyplot as plt
import numpy as np
def plot_peaks(time_series):
peak_indexes, _ = find_peaks(record["time_series"])
plt.plot(record["time_series"])
plt.plot(peak_indexes, record["time_series"][peak_indexes], "... |
import math
import heapq
def allocate(desire, reputation, output=None):
if output is None:
output = [0]*len(reputation)
desire = desire[:]
desire_sum = sum(desire)
if desire_sum < 0:
desire = [-d for d in desire]
reputation = [-r for r in reputation]
elif desire_sum ==... |
#!python3
"""
Demonstration of the PO+PROP1 algorithm.
Programmer: Tom Latinn
Since: 2021-02
"""
import networkx as nx
from fairpy.agents import AdditiveAgent
from fairpy.items.allocations_fractional import FractionalAllocation
from fairpy.items.po_and_prop1_allocation import find_po_and_prop1_allocation
agent1 = ... |
# Purpose: entity space
# Created: 13.03.2011
# Copyright (C) 2011, Manfred Moitzi
# License: MIT License
from __future__ import unicode_literals
__author__ = "mozman <mozman@gmx.at>"
from .lldxf.const import DXFStructureError
class EntitySpace(list):
"""An EntitySpace is a collection of drawing entities.
T... |
from configparser import NoSectionError
from pyrogram import CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
from ..TG_AutoConfigurator import AutoConfigurator
from ..utils import tools, messages
@AutoConfigurator.on_callback_query()
def callback(bot: AutoConfigurator, callback_query: CallbackQuery):
... |
try:
import pybullet_envs # pytype: disable=import-error
except ImportError:
pybullet_envs = None
try:
import highway_env # pytype: disable=import-error
except ImportError:
highway_env = None
try:
import mocca_envs # pytype: disable=import-error
except ImportError:
mocca_envs = None
|
from tool import *
from xgb_classifier import xgb_classifier
import numpy as np
import pickle
from scipy import sparse
def xgb_meta_predict(data_base_dir,data_meta_part1_dir,submission_dir):
test_id=pickle.load(open(data_base_dir+"test_id.p","rb"))
y_all=pickle.load(open(data_base_dir+"y.p","rb"))
X_all=pic... |
# Licensed under a 3-clause BSD style license - see PYDL_LICENSE.rst
# -*- coding: utf-8 -*-
# Also cite https://doi.org/10.5281/zenodo.1095150 when referencing PYDL
"""
Implements pure python support methods for
:class:`pypeit.bspline.bspline.bspline`.
.. include:: ../links.rst
"""
import warnings
from IPython impor... |
"""
Tests for @timeout decorator
Date created: 8th June 2014
"""
from timeout import timeout, TimeoutError
import time
from nose.tools import assert_raises, assert_equals
class TestTimeout:
def setup(self):
pass
def teardown(self):
pass
def test_timeout_with_timeout_error(self):
... |
from ..utility.expr_wrap_util import symbolic
from ..expr import BVV, BVS
from ..utility.models_util import get_arg_k
from ..sym_state import State
MAX_READ = 100
def read_handler(state: State, view):
fd = get_arg_k(state, 1, 4, view)
buf = get_arg_k(state, 2, state.arch.bits() // 8, view)
count = get_ar... |
import sys
import os.path
def parse_inputs(fastq_file):
root,ext = os.path.splitext(fastq_file)
return root + ".removed" + ext, root + ".kept" + ext
def remove_reads(fastq_file, removed_reads_file, kept_reads_file):
f = open(fastq_file, "r")
g = open(removed_reads_file, "w+")
h = open(kept_reads_f... |
import heapq
class Solution:
def kSmallestPairs(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[List[int]]
"""
rls = []
if len(nums1) <= 0 or len(nums2) <= 0:
return rls
pq = [(nu... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: mibandDevice.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _sym... |
# Importing the packages required
from bs4 import BeautifulSoup
import requests
# create a function to extract only text from <p> tags
def get_only_text(url):
''' return the title and text from the headline of
the spesfied url'''
page = requests.get(url)
soup = BeautifulSoup(page.content, "lxml")
... |
# Copyright 2012 OpenStack Foundation
# 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 requ... |
from flask import Flask, render_template, flash
from form import SetTotp
import onetimepass
import pyqrcode
import base64
app = Flask(__name__, static_url_path='/static')
app.config['SECRET_KEY'] = '5791628bb0b13ce0c676dfde280ba245'
@app.route("/", methods=['GET','POST'])
@app.route("/index", methods=['GET','POST'... |
import pandas as pd, numpy as np
def get_matches_from_list(filenames,sheetnames,column_keys,skiprows,shift=0):
matches=[]
if type(filenames)!=list:
filenames=[filenames]
if type(sheetnames)!=list:
sheetnames=[sheetnames]
for filename in filenames:
for sheetname in sheetnames:
... |
#!/usr/bin/env python
import ROOT
ROOT.gROOT.SetBatch(True)
ROOT.PyConfig.IgnoreCommandLineOptions = True
import math
# Run NVtxDistribution selector on some DY and DoubleMuon to derive scale factor
f = ROOT.TFile.Open('NVtxDistribution-DYandData.root')
hmc = f.Get('DYJetsToLL_M-50_TuneCUETP8M1_13TeV-madgraphMLM-pythi... |
from colorama import Fore, Style
import os
import pandas as pd
def clear_screen():
os.system('cls' if os.name == 'nt' else 'clear')
def to_int(s):
try:
return int(s)
except:
return float("INF")
def print_menu():
clear_screen()
print(f"Olá, {NAME}! Escolha uma opção\n\n")
print("1. Trocar nome")
print("2.... |
from fatalattractors import attractors
import buchi as buchi
import copy
from graph import Graph
def buchi_inter_safety_player(g, u, s, j):
"""
Solves a Buchi inter safety game where player j has that objective. U is the set to be visited infinitely often
and s is to be avoided.
:param g: a game grap... |
# Copyright 2017 Cisco Systems, 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... |
import brambox as bb
import os
from os.path import join, basename
from pathflowai.utils import load_sql_df, npy2da
import skimage
import dask, dask.array as da, pandas as pd, numpy as np
import argparse
from scipy import ndimage
from scipy.ndimage.measurements import label
import pickle
from dask.distributed import Cli... |
# -*- coding: utf-8 -*-
from puremvc.patterns.mediator import Mediator
class MainWindowMediator(Mediator):
"""
"""
NAME = 'MainWindowMediator'
def __init__(self, mediatorName=None, viewComponent=None):
super(MainWindowMediator, self).__init__(mediatorName, viewComponent)
|
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 31 22:20:24 2020
@author: dykua
helpler functions for onnx face detection
"""
import numpy as np
import cv2
def area_of(left_top, right_bottom):
"""
Compute the areas of rectangles given two corners.
Args:
left_top (N, 2): left top corner.
ri... |
print('''
The task here is to remove all the white-spaces
from the string. For this purpose, we need to
traverse the string and check if any character
of the string is matched with a white-space
character or not. If so, Use any built-in method
like replace() with a blank.
''')
string=input('Enter string he... |
#!/usr/local/bin/python
#
# Copyright (c) 2013 University of Pennsylvania
#
# 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... |
import sys
import os
import time
import imp
import re
import subprocess
from util.hook import *
from util import output
def reload_all_modules(code):
code.variables = None
code.commands = None
code.setup()
output.info('Reloaded all modules')
def reload_module(code, name):
name = name.replace('.p... |
# updated SQLA schema display to work with pydot 1.0.2
from sqlalchemy.orm.properties import RelationshipProperty
from sqlalchemy.orm import sync
import pydot
import types
__all__ = [
'create_uml_graph', 'create_schema_graph', 'show_uml_graph',
'show_schema_graph'
]
def _mk_label(mapper, show_operations, sh... |
#
# PySNMP MIB module Wellfleet-MODULE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-MODULE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:40:57 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
# ------------------------------------------------------------------------------
# Copyright 2020 Forschungszentrum Jülich GmbH and Aix-Marseille Université
# "Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements; and to You under the Apache License,
# Version 2.0. "
#
# ... |
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
These pipelines are developed by the Poldrack lab at Stanford University
(https://poldracklab.stanford.edu/) for use at
the Center for Reproducible Neuroscience (http://reproduci... |
# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
from benchexec.tools.template import BaseTool2
class T... |
# MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptio... |
import os
import shutil
import numpy as np
old_model_path = '/home/guoran/git-repo/yolo_test_1218/yolov3_model'
new_model_path = "yolov3_model_python/"
os.mkdir(new_model_path)
layers = os.listdir(old_model_path)
print(layers)
for layer in layers:
models=os.listdir(os.path.join(old_model_path, layer))
for model... |
r"""
Utils to play with PyTorch.
"""
import torch.distributed as dist
# pylint: disable=broad-except
# pylint: disable=protected-access
def get_torch_default_comm():
r"""
The NCCL communicator is needed so that Fast MoE can perform customized
communication operators in the C code. However, it is not a pub... |
import os
import sys
import glob
import yaml
import simplejson
def makedirs(output_folder):
if not os.path.isdir(output_folder):
os.makedirs(output_folder)
def read_yaml_file(file_path, is_convert_dict_to_class=True):
with open(file_path, 'r') as stream:
data = yaml.safe_load(stream)
i... |
"""Test accessing and manipulating attributes of a little endian image."""
import binascii
import os
import textwrap
import pytest
from baseline import Baseline
from exif import Image
from .little_endian_baselines import LITTLE_ENDIAN_MODIFY_BASELINE
from ._utils import check_value
# pylint: disable=pointless-stat... |
import json
import logging
import random
import smtplib
import string
import threading
import time
from email.mime.text import MIMEText
from email.utils import formatdate
import requests
import websocket
from Crypto.Hash import SHA256
API_VERSION_1 = '1.0.0'
AUTH_PATH = 'cvpservice/login/authenticate.do'
DATE_FORMAT ... |
import pandas as pd
from ..constants import PART_B_STUB, PART_B_STUB_SUM
from ..download.medicare import (list_part_b_files, list_part_d_files,
list_part_d_opi_files)
from ..utils.utils import isid
from . import PARTB_COLNAMES
def part_d_files(summary=False, usecols=None, years=range... |
from os.path import realpath, join, dirname
class Config:
DEBUG = False
TESTING = False
SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db'
SQLALCHEMY_TRACK_MODIFICATIONS = False
@staticmethod
def init_app(app):
pass
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = 'mysql:... |
"""
Given an array of n elements and an integer m.
The task is to find the maximum value of the
sum of its subarray modulo m i.e find the
sum of each subarray mod m and print
the maximum value of this modulo operation.
"""
from icecream import ic
def MaxSumMod(a, n, m):
maxi = 0
for i in range(1, n):
... |
import uuid
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser, PermissionsMixin
)
from django.db import models
from django.utils.translation import gettext_lazy as _
class UserManager(BaseUserManager):
def create_user(self, username, password, email=None, contact_number='', location=N... |
import pandas as pd
from tqdm import tqdm
from question_recommend import QuestionRecommendation, TfIdfSearch, MinHashSearch
from semantic_sim import SimServer
TEST_QUESTIONS = 'data/test_questions.txt'
TEST_DATASET = 'data/test_dataset.txt'
def save_test_questions():
df = pd.read_csv('data/quora-question-pair... |
# Performs the G-test to estimate the goodness-of-fit of the GSD and QNormal models to real data.
#
# This script requires two parameters:
# (i) the number of chunks to cut the input data into and
# (ii) a zero-based chunk index of a chunk you want to process
#
# Author: Jakub Nawała <jnawala@agh.edu.pl>
# Date: Ma... |
"""
Sieve of Eratosthenes
implementation
"""
def sieve(number: int) -> list:
"""
The Sieve of Eratosthenes is an algorithm for
finding all prime numbers up to any given limit
"""
num1: int = (number - 1) // 2
num2: int = 0
num3: int = 3
arr: list = [True] * num1
result: list = [2]
... |
from flask import Blueprint, render_template, url_for, redirect
from flask_login import login_user, logout_user, login_required, current_user
from app.form import SearchForm, LoginForm, RegisterForm, WatchForm, UnWatchForm, DelPackageForm
from app.model import Express, Package, User
from config import INTERNAL_CODE
... |
import matplotlib
matplotlib.use('Agg')
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import sys
sys.path.insert(0, '../')
import utils.trajectory_utils
reload(utils.trajectory_utils)
from utils.trajectory_utils import TrajectoryLoader
from nets.net import *
from envs.env... |
#!/bin/env python2.7
##
## Copyright (c) 2010-2017 Intel Corporation
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless req... |
"""
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node)
self.data (the value of the node)"""
def _topLeft(root):
if root is not None:
_topLeft(root.left)
print root.data,
def _topRight(root):
if root is not None:
print root.data,
_... |
import torch
import torch.nn as nn
import math
from kobert.pytorch_kobert import get_pytorch_kobert_model
def _gen_attention_mask(token_ids, valid_length):
attention_mask = torch.zeros_like(token_ids)
for i, v in enumerate(valid_length):
attention_mask[i][:v] = 1
return attention_mask.float()
cl... |
# -*- coding: utf-8 -*-
import asyncio
from aiorpc.log import rootLogger
from aiorpc.constants import SOCKET_RECV_SIZE
__all__ = ['Connection']
_logger = rootLogger.getChild(__name__)
class Connection:
def __init__(self, reader, writer, unpacker):
self.reader = reader
self.writer = writer
... |
from geosquizzy.validation.messages import MESSAGES
class FeatureSyntaxError(SyntaxError):
def __init__(self):
super(FeatureSyntaxError, self).__init__(MESSAGES['1'])
class FeatureStructureError(Exception):
def __init__(self):
super(FeatureStructureError, self).__init__(MESSAGES['2'])
clas... |
def mymethod(self):
return self.x > 100
class_name = "MyClass"
base_classes = tuple()
params= {"x": 10, "check_greater": mymethod}
MyClass = type("MyClass", base_classes, params)
obj = MyClass()
print(obj.check_greater()) |
import asyncio
import functools
import pathlib
import threading
from http import server
import pytest
from digslash import sites
def get_dir(dirname):
return pathlib.os.path.join(
pathlib.os.path.dirname(__file__),
dirname
)
@pytest.fixture
def website1():
web_dir = get_dir('website-1'... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-06-05 14:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user_migration', '0003_auto_20180531_1052'),
]
operations = [
migrations.A... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
# Standard imports
from future import standard_library
standard_library.install_aliases()
from builtins import *
import json
import requests
import logging
import urllib.r... |
import json
from django.contrib import messages
from crispy_forms import layout
from django import forms
from django.template import defaultfilters
from django.http import Http404
from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy
from django_cradmin import crapp
from django_crad... |
"""
Find Duplicate Subtrees
Given the root of a binary tree, return all duplicate subtrees.
For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with the same node values.
Example 1:
Input: root = [1,2,3,4,null,2... |
#!/usr/bin/env python3
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# task from the https://www.hackerrank.com/challenges/swap-case/problem
def swap_case(s):
result=''.join(map(lambda x: x.lower() if x.isupper() == True else x.upper() ,s))
return result
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(res... |
from .account_activity import AccountActivity
from .account import Account
from .amount_owing import AmountOwing
from .contact import Contact
from .current_account import CurrentAccount
from .skipthedishes_order import SkipTheDishesOrder
__all__ = [
'AccountActivity',
'Account',
'AmountOwing',
'Contact... |
from keris.callbacks import Callback
from time import time
class ModelCheckpoint(Callback):
def __init__(self, filepath, monitor='val_loss', save_best_only=False):
if monitor not in ['train_loss', 'train_acc', 'val_loss', 'val_acc']:
raise ValueError('metric to monitor is not available')
... |
from io import BytesIO
from typing import Any, Dict, Type, TypeVar, Union
import attr
from ..types import UNSET, File, Unset
T = TypeVar("T", bound="BodyUploadFileTestsUploadPost")
@attr.s(auto_attribs=True)
class BodyUploadFileTestsUploadPost:
""" """
some_file: File
some_string: Union[Unset, str] = ... |
import tm1637
from machine import Pin
tm = tm1637.TM1637(clk=Pin(0), dio=Pin(1))
tm.numbers(12, 59)
tm.number(-123)
# tm.temperature(24) 不建议使用显示温度
# all LEDS on "88:88"
tm.write([127, 255, 127, 127])
# all LEDS off
tm.write([0, 0, 0, 0])
#一个列表每个代表一个led晶体管
# 数字8 由7个led管组成
# 8: 由8个led管组成 |
from aenum import Enum
from peewee import CharField
class NodeState(Enum):
ONLINE = "online"
OFFLINE = "offline"
SUSPENDED = "suspended"
class NodeStateField(CharField):
def db_value(self, value):
return value.value
def python_value(self, value):
return NodeState(value)
|
from gym_minigrid.minigrid import Cell, Grid, MiniGridEnv
from gym_minigrid.entities import Ball, Box, Door, Key, COLORS, make
def _reject_next_to(env, pos):
"""
Function to filter out object positions that are right next to
the agent's starting point
"""
si, sj = env.agent.pos
i, j = pos
... |
from scipy import signal
import os
import cv2
import numpy as np
import math
class Compare():
def correlation(self, img1, img2):
return signal.correlate2d (img1, img2)
def meanSquareError(self, img1, img2):
error = np.sum((img1.astype('float') - img2.astype('float')) ** 2)
error /= float... |
from rucio.client.rseclient import RSEClient
import uuid
c = RSEClient(account="ivm")
for rse in c.list_rses():
u = uuid.UUID(rse["id"])
print rse["rse"], u.hex
|
def get_parents(o):
parents = []
while orbits[o] != "":
o = orbits[o]
parents.append(o)
return parents
def create_orbits(orbit_map):
pairs = [pair.split(")") for pair in orbit_map.split("\n")]
objects = set(i for p in pairs for i in p)
orbits = {o: "" for o in objects}
for ... |
from multiprocessing import Queue, Value
from access_face_vision import access_logger
from time import sleep
from access_face_vision.face_detector import FaceDetector
from access_face_vision.face_encoder import FaceEncoder
from access_face_vision.source.image_reader import ImageReader
from access_face_vision.embeddin... |
"""Workflow module logic"""
import os
import logging
import contextlib
from abc import ABC, abstractmethod
from pathlib import Path
from haddock.core.defaults import MODULE_PATH_NAME, MODULE_IO_FILE
from haddock.core.exceptions import StepError
from haddock.gear.config_reader import read_config
from haddock.libs.libon... |
# Generated by Django 2.0 on 2018-02-14 13:24
from django.db import migrations
def forwards(apps, schema_editor):
"""
Change Events with kind 'movie' to 'cinema'
and Events with kind 'play' to 'theatre'.
Purely for more consistency.
"""
Event = apps.get_model("spectator_events", "Event")
... |
from beluga.visualization import BelugaPlot
from beluga.visualization.datasources import Dill
# plots = BelugaPlot('./data.dill',default_sol=-1,default_step=-1)
ds = Dill('./data.dill')
# ds2 = Dill('./phu_2k5_eps4.dill')
plots = BelugaPlot(datasource=ds,default_sol=-1,default_step=-1, renderer='matplotlib')
# plots =... |
#
# PySNMP MIB module CISCO-LWAPP-SI-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LWAPP-SI-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:06:24 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
import numpy as np
np.set_printoptions(legacy='1.13')
n,m = map(int,input().split())
arr = np.array([input().split() for _ in range(n)],int)
print(np.mean(arr,axis=1))
print(np.var(arr,axis=0))
print(np.std(arr,axis=None)) |
from selenium import webdriver
browser=webdriver.Firefox()
browser.get('http://inventwithpython.com')
linkElem=browser.find_element_by_link_text('Read Online for Free')
linkElem.click() |
#!/usr/bin/env python
import unittest
from flosrv import FlorinCoinSrv
import flosrv
from metachains import Florincoin, Synchronizer
from decimal import Decimal
import os
class MockCoin(object):
@property
def MaxPayloadSize(self): return 16
def block_count(self):
return 128
def blocks(self,... |
import attr
from viberio.types.base import ViberBaseObject
@attr.s
class Message(ViberBaseObject):
tracking_data: str = attr.ib(default=None)
keyboard: str = attr.ib(default=None)
min_api_version: str = attr.ib(default=None)
alt_text: str = attr.ib(default=None)
@attr.s
class TypedMessage(Message):... |
import Bboard
import Wboard
import board
import Bboardbak
import Wboardbak
import Bboardbak2
import Wboardbak2
import Wkiki1
import Wkiki2
import Bkiki1
import Bkiki2
import Bkikimoves1
import gc
def torare():
torare=0
torare2=0
for j in range(80):
b = 0
w = 0
b = Bkiki2.kikilist1[j... |
"""
"""
from masterstudent.tensorflowstudent import TensorFlowStudent
from args import get_parser
# make this contextmanager
def load_config(config_path):
"""
"""
from yaml import load
with open(config_path, 'r') as f:
return load(f)
def run_masters_student(backend_type, config):
"""
... |
from lib.utils import *
from collections import defaultdict
def loadSegmentsIndex(segFile, DExons):
segRanges = defaultdict(lambda : defaultdict(set))
segTxs = {}
segLens = {}
with open(segFile) as sFile:
for lc, line in enumerate(sFile):
if lc == 0: #skip header
... |
# pytorch
import pinocchio
from data.data_config import DataGenConfig
import torch
from torch import nn
import numpy as np
from os.path import dirname, abspath, join
from model import ConstrainedCVAE
def inference(pose, z = None):
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
cva... |
from keras.models import Model
from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint
from keras import backend as K
smooth = 1.
def dice_coef(y_true, y_pred):
y_true_f = K.flatten(y_true)
y_pred_f = K.fl... |
import os
import pickle
from src.configuration.constants import INTERIM_DATA_DIRECTORY, PROCESSED_DATA_DIRECTORY, RAW_DATA_DIRECTORY, INTERIM, \
PROCESSED, RAW
DIRNAME_TO_DIRECTORY = {
INTERIM: INTERIM_DATA_DIRECTORY,
PROCESSED: PROCESSED_DATA_DIRECTORY,
RAW: RAW_DATA_DIRECTORY,
}
def load_dataset(d... |
class Solution:
def numSubmatrixSumTarget(self, A: List[List[int]], target: int) -> int:
m, n = len(A), len(A[0])
for row in A:
for i in range(1, n):
row[i] += row[i - 1]
cnt = 0
for left in range(n):
for right in range(left, n):
... |
import logging
from project.settings import DEBUG
logger = logging.getLogger(name='project')
logger.setLevel(logging.DEBUG)
format = '%(asctime)s [%(levelname)s] %(filename)s: %(message)s'
formatter = logging.Formatter(format, datefmt='%d.%m.%Y %H:%M:%S')
if DEBUG:
level = logging.DEBUG
else:
level = logging... |
from tempfile import NamedTemporaryFile
import uuid
import time
import pytest
import requests
from labelbox import DataRow
def test_get_data_row(datarow, client):
assert client.get_data_row(datarow.uid)
def test_lookup_data_rows(client, dataset):
uid = str(uuid.uuid4())
# 1 external id : 1 uid
dr ... |
import requests,json,os,subprocess
# 发post请求,获取5条内容(title、author、下载url)
def getContent(music_name,type):
print('正在获取'+type+'资源...')
url = 'http://music.ifkdy.com/'
data = {'input': music_name,
'filter': 'name',#kuwo netease
'type': type,
'page': '1'}
headers = {... |
from django.db import models
from django.utils.translation import activate
# Create your models here.
class Movie(models.Model):
name = models.CharField(max_length=50, unique=True)
description = models.CharField(max_length=250, null=False)
active = models.BooleanField(default=True)
|
import csv
import os
from os.path import join, dirname
import pickle
import numpy as np
from plotly.offline import plot
import plotly.graph_objs as go
from collections import Counter
import json
import writeToS3 as s3
import argparse
import deleteDir as d
import notification as n
class Classification:
def __init_... |
from django import forms
from django.forms.widgets import PasswordInput, TextInput
class LoginForm(forms.Form):
username = forms.CharField(widget=TextInput(attrs={'class': 'nes-input'}), max_length=150)
password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'nes-input'}))
class EmployeeForm(fo... |
import os
import random
import hashlib
import string
import kopf
import kubernetes
import kubernetes.client
notebook_startup = """#!/bin/bash
conda init
source $HOME/.bashrc
if [ ! -f $HOME/.condarc ]; then
cat > $HOME/.condarc << EOF
envs_dirs:
- $HOME/.conda/envs
EOF
fi
if [ -d $HOME/.conda/envs/workspace ... |
from django.utils.cache import add_never_cache_headers
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from django.contrib.auth.middleware import RemoteUserMiddleware
class NoReferral(MiddlewareMixin):
def process_response(self, request, response):
response['X-Conten... |
##### Implementation of SCAFFOLOD #####
##### importing libraries #####
import copy
import random, argparse
from numpy.core import records
import torch
import numpy as np
from tqdm import tqdm
from solvers import create_solver
from utils import util
from data import create_dataloader, create_dataset
from options impor... |
from btchip.btchip import btchip
from btchip.bitcoinTransaction import bitcoinTransaction
from struct import unpack
from btchip.bitcoinVarint import readVarint, writeVarint
from btchip.bitcoinTransaction import bitcoinInput, bitcoinOutput
class btchip_xsh(btchip):
def getTrustedInput(self, transaction, index):
... |
from django.apps import AppConfig
class CustomEmailUserConfig(AppConfig):
name = 'custom_email_user'
|
# -*- coding:utf-8 -*-
import pandas as pd
path = 'dataSet//'
result_one = pd.read_csv(path + 'result_b_20180706181411.csv', encoding='utf-8', sep='\t')
result_two = pd.read_csv(path + 'result_b_20180706093641.csv', encoding='utf-8', sep='\t')
# print(result_one[result_one['RST'] > 0.1])
# print(result_tw... |
import pytest
from beatx.utils import import_string
class TestImportString:
def test_import_module(self):
mod = import_string('os.path')
assert hasattr(mod, 'abspath')
def test_import_function(self):
pow = import_string('math.pow')
assert pow(2, 3) == 8
def test_import_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.