text string | size int64 | token_count int64 |
|---|---|---|
__all__ = ['Token', 'Scanner', 'getscanner']
import types
class Token:
def __init__(self, type, attr=None, pattr=None, offset=-1):
self.type = intern(type)
self.attr = attr
self.pattr = pattr
self.offset = offset
def __cmp__(self, o):
if isinstance(o, Token):
... | 5,057 | 1,583 |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
import unittest
class FcntlModuleTest(unittest.TestCase):
def test_it_imports(self):
import fcntl
self.assertEqual(fcntl.__name__, "fcntl")
if __name__ == "__main__":
unittest.main()
| 312 | 113 |
#!/usr/bin/env python
#title :main.py
#description :Tensorflow implementation of CapsNet.
#author :Jose Chavez
#date :2019/04/30
#version :1.0
#usage :python3 main.py
#python_version :3.6.7
#============================================================================... | 7,576 | 2,794 |
import os
import sys
import time
import decimal
import sqlite3
import multiprocessing
from secret import rpc_user, rpc_password
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
import cluster_db_query as cdq
import db_query as dq
rpc_ip = '127.0.0.1'
rpc_port = '8332'
timeout = 300
def get_rpc():
... | 7,707 | 2,848 |
from typing import Optional, List
from pydantic import Field
from pydantic.main import BaseModel
from inoft_vocal_framework.utils.formatters import normalize_intent_name
class Intent(BaseModel):
name: str
displayName: str
class User(BaseModel):
_VERIFICATION_NAME_GUEST = "GUEST"
_VERIFICATION_NAME_... | 6,240 | 1,725 |
# -*- encoding: utf-8 -*-
from django.contrib import admin
from emailtemplates.models import EmailTemplate
from emailtemplates.models import MailServerFailure
class EmailTemplateAdmin(admin.ModelAdmin):
list_display = ['desc', 'subject']
readonly_fields = ['uid']
pass
admin.site.register(Ema... | 589 | 180 |
class Package(object):
def __init__(self, name):
self._name = name
@classmethod
def root(cls): # type: () -> Package
return Package("_root_")
@property
def __str__(self):
return self._name
def __eq__(self, other):
return str(other == self._name)
def __re... | 380 | 118 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#--------------------------------#
"""
File name: TPEX_STOCKBOT/main.py
Author: WEI-TA KUAN
Date created: 12/9/2021
Date last modified: 9/10/2021
Version: 1.0
Python Version: 3.8.8
Status: Developing
"""
#--------------------------------#
from scraping_data import stock_da... | 1,073 | 400 |
"""
list twikis:
List all L1 Trigger Offline Twikis
Usage:
list twikis [check=1]
Parameters:
check: force a check of the twiki URL before printing.
Useful when adding new entries. Default: 0
"""
import logging
import urllib
import hepshell
LOG = log... | 3,959 | 1,368 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""IAAFT surrogates for correlated noise.
The properties of linearly correlated noise can be captured quite
accurately by IAAFT surrogates. Thus, they cannot easily fool
a dimension estimator (here we use Takens's maximum likelihood estimator
for the correlation dimensio... | 1,528 | 690 |
import time
from unittest import TestCase
from app.pubmed.source_entrez import *
class TestEntrez(TestCase):
def test_do_rate_limit(self):
# Serial Test
start = time.time()
do_rate_limit()
do_rate_limit()
do_rate_limit()
do_rate_limit()
elapsed = time.time()... | 1,853 | 625 |
import nltk
import numpy as np
from nltk.stem.porter import PorterStemmer
nltk.download('punkt')
stemmer = PorterStemmer()
# splitting a string into words, punctuation and numbers
def tokenize(sentence):
return nltk.word_tokenize(sentence)
# generating the root form the words ex: universe - univers, universi... | 776 | 257 |
#!/usr/bin/env python3
import os
import click
from bank_api import create_app, db, models, utils
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
@app.shell_context_processor
def make_shell_context():
return {
'db': db,
'Account': models.Account,
'Customer': models.Customer,
... | 1,799 | 592 |
import sys
if sys.version_info[:2] >= (3, 8):
# TODO: Import directly (no need for conditional) when `python_requires = >= 3.8`
from importlib.metadata import PackageNotFoundError, version # pragma: no cover
else:
from importlib_metadata import PackageNotFoundError, version # pragma: no cover
try:
#... | 742 | 212 |
import os
import sys
rootpath=str("D:/_1work/pycharmcode/pycharmproject/resrep")
syspath=sys.path
sys.path=[]
sys.path.append(rootpath)#将工程根目录加入到python搜索路径中
sys.path.extend([rootpath+i for i in os.listdir(rootpath) if i[0]!="."])#将工程目录下的一级目录添加到python搜索路径中
sys.path.extend(syspath)
print(sys.path) | 296 | 149 |
import argparse
import os
import shutil
import time
import sys
import sklearn
import sklearn.metrics
import torch
torch.cuda.init()
import torch.nn as nn
import torch.nn.parallel
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.... | 18,554 | 6,397 |
import sys
from .. import api
import pysam
description = """
Index a VCF file.
This command will create an index file (.tbi) for the input VCF.
"""
epilog = f"""
[Example] Index a compressed VCF file:
$ fuc {api.common._script_name()} in.vcf.gz
[Example] Index an uncompressed VCF file (will create a compressed ... | 1,093 | 351 |
import logging
import os
import sys
from peewee import SqliteDatabase, PostgresqlDatabase
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)
if not os.getenv('POSTGRES_DB_NAME'):
logger.warning('[DB] u... | 1,174 | 462 |
from scuttlecrab.classes.bot import CustomBot
bot = CustomBot()
| 65 | 24 |
# Copyright (c) 2021 PaddlePaddle 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 appli... | 1,384 | 437 |
from captcha.image import ImageCaptcha
import random
def create_captcha():
captcha_text = str(hex(random.randint(3000, 5999) * random.randint(100, 199)))
image = ImageCaptcha(width=280, height=90)
data = image.generate(captcha_text)
image.write(captcha_text, 'cImg.png')
return captcha_tex... | 640 | 235 |
from openstates.utils import LXMLMixin
import datetime as dt
import re
from billy.scrape.events import Event, EventScraper
import lxml.html
import pytz
mi_events = "http://legislature.mi.gov/doc.aspx?CommitteeMeetings"
class MIEventScraper(EventScraper, LXMLMixin):
jurisdiction = 'mi'
_tz = pytz.timezone('... | 4,045 | 1,230 |
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
ret, power = 0, 31
while n:
ret += (n & 1) << power # n & 1 means: 末位是1则是1, 0则是0 向右移位
n = n >> 1 # n 左移移位
power -= 1 # 位数-1
return ret
if "__main__... | 418 | 172 |
"""Some preloads of database content."""
tables = list()
roles = list()
roles.append({"id": 1, "name": "administrator"})
roles.append({"id": 2, "name": "contributor"})
roles.append({"id": 3, "name": "staff"})
roles.append({"id": 4, "name": "parent"})
roles.append({"id": 5, "name": "caretaker"})
roles.append... | 1,018 | 442 |
#
# MIT License
#
# Copyright (c) 2020 Andrew Robinson
#
# 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,... | 6,689 | 1,840 |
from os import getcwd
def rdfile():
data = list()
# 顯示這個程式碼檔案是在哪裡被執行
print(getcwd())
with open("pm25.txt", 'r') as fd:
for line in fd:
try:
data.append(float(line.replace('\n', '')))
except:
pass
print('Max =', max(data))
print('M... | 651 | 267 |
####################################################################################################
# File: plotter.py
# Purpose: Plotting module.
#
# Author: Luke Poeppel
#
# Location: Kent, 2021
####################################################################################################
import logging... | 5,534 | 2,049 |
from flask import current_app, Flask, redirect, url_for
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
import config
from flask_login import LoginManager
app = Flask(__name__)
app.config.from_object(config) # load config.py
app.secret_key = 'super duper mega secret key'
login_manager = LoginManag... | 638 | 181 |
#!/usr/bin/env python
import logging
from threading import Thread, Event
from Queue import Queue, Empty as QueueEmpty
import codecs
class FileWriter(Thread):
"""
This thread reads log lines from a queue and writes these to a file passed as log_file_path.
The log line queue is filled with new log lines b... | 3,814 | 1,006 |
#Dados dos números, mostrar la suma, resta, división y multiplicación de ambos.
a = int(input("Dime el primer número: "))
b = int(input("Dime el segundo número: "))
print("La suma de los dos números es: ",a+b)
print("La resta de los dos números es: ",a-b)
print("La multiplicación de los dos números es: ",a*b)
print("L... | 361 | 129 |
from core.advbase import *
def module():
return Pipple
class Pipple(Adv):
conf = {}
conf['slots.a'] = ['Proper_Maintenance', 'Brothers_in_Arms']
conf['slots.frostbite.a'] = conf['slots.a']
conf['slots.d'] = 'Gaibhne_and_Creidhne'
conf['acl'] = """
`dragon(c3-s-end),x=5
`s2, (x=... | 610 | 256 |
class AutoRepresentation:
def __init__(self, adopt_configuration_threshold=None):
self.adoptConfigurationThreshold = adopt_configuration_threshold
| 159 | 40 |
import unittest
import logging
import nzmath.factor.methods as mthd
try:
_log = logging.getLogger('test.testFactorMethod')
except:
try:
_log = logging.getLogger('nzmath.test.testFactorMethod')
except:
_log = logging.getLogger('testFactorMethod')
_log.setLevel(logging.INFO)
class FactorTest... | 3,799 | 1,653 |
import collections
class Solution01:
"""
使用内置API
"""
def reverseWords(self, s: str) -> str:
return ' '.join(reversed(s.split()))
class Solution02:
"""
自己实现对应的功能
"""
def trim_space(self, s: str) -> list:
left, right = 0, len(s) - 1
# 去除首尾空格
while s[le... | 2,057 | 780 |
# Copyright (c) 2021, Serum Studio
# 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, mer... | 3,154 | 976 |
import sklearn
from sklearn import datasets
def generate(n_samples, features):
n_features = len(features)
data = sklearn.datasets.make_blobs(n_samples=n_samples, n_features=n_features, centers=10, cluster_std=1.0, center_box=(-10.0, 10.0), shuffle=True, random_state=None)
return (data, features) | 300 | 111 |
if __name__ == '__main__':
import Recommender_System.utility.gpu_memory_growth
from Recommender_System.algorithm.KGCN.tool import construct_undirected_kg, get_adj_list
from Recommender_System.algorithm.KGCN.model import KGCN_model
from Recommender_System.algorithm.KGCN.train import train
from R... | 947 | 356 |
import os
import setuptools
CUR_DIR = os.path.abspath(os.path.dirname(__file__))
about = {}
with open(os.path.join(CUR_DIR, "data_spec_validator", "__version__.py"), "r") as f:
exec(f.read(), about)
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name... | 1,133 | 390 |
"""
A component which allows you to send data to an Influx database.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/influxdb/
"""
from datetime import timedelta
import functools
import logging
import itertools
import json
from persistent_queue import P... | 9,204 | 2,804 |
import numpy as np
import os
from ..helpers import save_json
def callback_weather_fn(sensor_data, custom_args):
## note that in this function, sensor data comes from the
## 'weather' custom arg
## the sensor is used just to trigger the callback at the correct timestamp
weather = custom_args['weather']... | 587 | 186 |
Import("env")
# original Makefile builds into dapboot.bin/elf, let's do the same
env.Replace(PROGNAME="dapboot")
| 114 | 41 |
#drawing a line using DDA
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import sys
import math
def init():
glClearColor(1.0,2.0,1.0,1.0)
gluOrtho2D(-100.0,100.0,-100.0,100.0)
x1 = 0
x2 = 0
y1 = 0
y2 = 0
def plotpoints():
global x1, y1, x2, y2
glClear(G... | 1,393 | 624 |
import pathlib
import numpy as np
import xarray as xr
def to_netcdf(
grid, path, include="*", exclude=None, time=None, format="NETCDF4", mode="w"
):
"""Write landlab a grid to a netcdf file.
Write the data and grid information for *grid* to *path* as NetCDF.
If the *append* keyword argument in True,... | 4,884 | 1,570 |
from flask import request, url_for, g
from flask_api import FlaskAPI, status, exceptions
from flask_sqlalchemy import SQLAlchemy
import arrow
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_cors import CORS
app = FlaskAPI(__name__)
cors = CORS(app, resources={r"/*": {"origins... | 4,053 | 1,418 |
"""
Your object will be instantiated and called as such:
ty = ToyFactory()
toy = ty.getToy(type)
toy.talk()
"""
class Toy:
def talk(self):
raise NotImplementedError('This method should have implemented.')
class Dog(Toy):
def talk(self):
print('Wow')
class Cat(Toy):
def talk(self):
... | 592 | 191 |
from enum import IntEnum, unique
@unique
class Dimension(IntEnum):
InChan = 0
OutChan = 1
Height = 2
Width = 3
Batch = 4
| 143 | 57 |
from autohandshake.src.Pages.Page import Page
from autohandshake.src.HandshakeBrowser import HandshakeBrowser
from autohandshake.src.exceptions import InvalidURLError, NoSuchElementError, \
InvalidEmailError, InvalidPasswordError
import re
class LoginPage(Page):
"""
The old Handshake login page
"""
... | 4,746 | 1,329 |
from omegaconf import DictConfig
import pytorch_lightning as pl
import numpy as np
import torch
import wandb
from simsiam.models import get_resnet
from simsiam.metrics import get_accuracy
from simsiam.optimizer import get_optimizer, get_scheduler
class SupervisedEngine(pl.LightningModule):
def __init__(self, co... | 2,649 | 882 |
from flask import render_template, redirect, url_for, flash
from flask_login import current_user, login_user, logout_user
from sqlalchemy import func
import stripe
from app import db
from app.auth import bp
from app.auth.forms import LoginForm, RegistrationForm, ResetPasswordRequestForm, ResetPasswordForm
from app.mode... | 5,568 | 1,601 |
from nilearn import plotting
from IPython import display
def display_input(nifti, i, fig, ax, cut_coords=None):
if cut_coords is None:
cut_coords = [-9]
plotting.plot_img(nifti, title="In {}".format(i), axes=ax,
display_mode="z", cut_coords=cut_coords)
display.clear_output(wa... | 607 | 221 |
#!/usr/bin/env python3
import config
import rsys_api
import secrets
import json
import logging
import sys
def main():
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt="%Y/%m/%d %H:%M:%S",
filename="demo.log"
)
... | 2,420 | 755 |
from utils import save_params, load_params
from importlib import import_module
from environments.env import Env
def run(algorithm_name, exp_name, env_name, agent_params, train_params, use_ray, use_gpu, is_train,
num_runs=None, test_run_id=None, test_model_id=None):
"""
Runner for training or t... | 4,377 | 1,370 |
from decouple import config
from peewee import SqliteDatabase
from playhouse.pool import PooledSqliteExtDatabase, PooledPostgresqlExtDatabase
# db = SqliteDatabase(config('DATABASE_PATH', default='sentiment_analysis.db'))
db = PooledSqliteExtDatabase(
config('DATABASE_PATH', default='sentiment_analysis.db'),
... | 679 | 229 |
#!/usr/bin/env python
import webapp2
from pkg.controllers.transactionctrl import TransactionCtrl
from pkg.controllers.appctrl import AppCtrl
from pkg.controllers.debug import Debug
app = webapp2.WSGIApplication([
('/transaction', TransactionCtrl),
('/transaction/([0-9]+)', TransactionCtrl),
('/', AppCtrl),
('/deb... | 347 | 111 |
import re
from django.conf import settings
from django.shortcuts import redirect
from django.http import HttpResponseRedirect
EXEMPT_URLS=[]
if hasattr(settings,'LOGIN_EXEMPT_URLS'):
EXEMPT_URLS+=[re.compile(url) for url in settings.LOGIN_EXEMPT_URLS]
class AuthenticationMiddleware(object):
def __init__(self, get_... | 875 | 304 |
from datetime import datetime, timedelta, timezone
import freezegun
from autifycli.domain.entities.metadata import Metadata
JST = timezone(timedelta(hours=+9), "JST")
@freezegun.freeze_time("2021-08-12")
def test_metadata():
site = "https://example.com"
num_links = 0
num_images = 0
last_fetch = dat... | 579 | 204 |
# -*- coding: utf-8 -*-
"""
demeter database
name:__load__.py
"""
from demeter.model import *
from demeter.core import * | 128 | 48 |
import abc
class Visitor(metaclass=abc.ABCMeta):
@abc.abstractmethod
def visit_node(self, node, udf, orientation, last_iter):
pass | 148 | 49 |
# TIE Methods
import utils
from dxltieclient import TieClient
from dxltieclient.constants import HashType, ReputationProp, FileProvider, FileEnterpriseAttrib, \
CertProvider, CertEnterpriseAttrib, TrustLevel
# TIE Reputation Average Map
tiescoreMap = {0: 'Not Set', 1: 'Known Malicious', 15: 'Most Likely Malicious'... | 8,217 | 2,551 |
import hashlib
import json
import numpy as np
import pandas as pd
from pymemcache import serde
from pymemcache.client import base
from keepthis.MemcachedConnection import MemcachedConnection
from keepthis.exceptions import KeepThisValueError
class KeepThis:
def __init__(
self,
memcached_... | 3,720 | 1,046 |
import json
from pathlib import Path
from sbx_bgsvc_starterpack.sbx_json_default import json_default
def load(default_cfg: dict = {}, file: str = './cfg/cfg.json', encoding: str = 'utf-8-sig') -> dict:
# 1. 설정 파일이 없는경우 생성
cfg_file1 = Path(file)
if not cfg_file1.is_file():
save(default_cfg, file, ... | 1,016 | 520 |
#!/usr/bin/python
#
# ============================================================================
# Copyright (c) 2011 Marvell International, Ltd. All Rights Reserved
#
# Marvell Confidential
# ============================================================================
#
# Run a random sca... | 7,804 | 2,865 |
# --------------------------------------------------------------------------
# Copyright 2014 Digital Sapphire Development Team
#
# 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://... | 10,880 | 2,989 |
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField
from wtforms.validators import DataRequired, Length
def range_to_select_choices(items):
choices = [(0, '0 star')]
for item in items:
choices.append((item, str(item) + ' stars'))
return choices
class AddReco... | 649 | 197 |
from __future__ import annotations
import ast
import os
import re
import sys
from itertools import product
from pathlib import Path
import attr
from hypothesis import given, settings
from hypothesis.strategies import sampled_from
from absort.__main__ import (
CommentStrategy,
FormatOption,
NameRedefiniti... | 3,090 | 1,003 |
import pygame
from BrickBreaker import *
from BrickBreaker.Scenes import *
from BrickBreaker.Shared import *
class BrickBreaker:
def __init__(self):
self._lives = 5
self._score = 0
self._bonus = 1
self._level = Level(self)
self._level.load_random()
self._pad = P... | 4,593 | 1,520 |
from .visualization import plot_mean, plot_mean_interval
| 57 | 16 |
'''
###################################
Modified from Mike's predict_acc.py
###################################
'''
import os
import sys
import random
import pickle
import numpy as np
import pandas as pd
from keras.utils import to_categorical
from keras.models import load_model
from sklearn.metrics import accuracy_s... | 2,188 | 945 |
"""Tests for date utils"""
from datetime import time, datetime
import pytz
from jetblack_fixengine.utils.date_utils import (
is_dow_in_range,
is_time_in_range,
delay_for_time_period
)
MONDAY = 0
TUESDAY = 1
WEDNESDAY = 2
THURSDAY = 3
FRIDAY = 4
SATURDAY = 5
SUNDAY = 6
def test_dow_range():
"""Test... | 4,408 | 2,142 |
'''
xScratch exceptions
'''
class XSSyntaxError(Exception):
'''
Error raised when there is a syntax error in the script
'''
pass
class XSSemanticError(Exception):
'''
Error raised when there is a semantic error in the script
'''
pass
class XSArduinoError(Exception):
'''
Err... | 400 | 113 |
import os
import pybullet_data
from environments.locomotion.scene_abstract import Scene
import pybullet as p
class StadiumScene(Scene):
zero_at_running_strip_start_line = True # if False, center of coordinates (0,0,0) will be at the middle of the stadium
stadium_halflen = 105 * 0.25 # FOOBALL_FIELD_HALFLEN
... | 2,267 | 779 |
from defs import *
from utilities import warnings
def move_to(creep: Creep, target: RoomPosition) -> int:
result = creep.moveTo(target, {
'ignoreCreeps': True,
})
if result == ERR_NO_PATH:
result = creep.moveTo(target, {
'ignoreCreeps': False,
})
if result != OK an... | 522 | 166 |
from typing import Dict, Sequence, Union
from .typing_annotations import DataFrameOrSeries
import pandas as pd
import numpy as np
def create_constant_time_series(value:Union[int,float], start:pd.Timestamp) -> pd.Series:
return pd.Series([value], index=[start])
def remove_consecutive_duplicates(df:DataFrameOrSeri... | 4,817 | 1,415 |
# -*- coding: utf-8 -*-
""" Class definitions for the HLSCLT Command Line Tool.
Copyright (c) 2017 Ben Marshall
"""
# Generic error class
class Error(Exception):
"""Base class for exceptions in this module."""
pass
# Specific error class for local config file errors
class ConfigError(Error):
"""Exception... | 841 | 236 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class BasePage(object):
"""
BasePage封装所有页面都公用的方法,例如driver, url
"""
#初始化driver、url、等
def __init__(self, selenium_driver, base_url, pagetitle):
self.base_url = base_url
self.pagetitle = pagetitle
self.driver = selenium_driver
def _iopen(self, url, pagetitle):
... | 718 | 388 |
import logging
from collections import deque
from ..tokens import BuiltToken
from ..utils import LogicError
from ..router import NoSuchControlSequence
from ..constants.instructions import Instructions
logger = logging.getLogger(__name__)
# Stuff specific to *my parsing*.
letter_to_non_active_uncased_type_map = {
... | 9,740 | 3,010 |
# Generated by Django 2.1.4 on 2019-10-17 00:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('carnival', '0010_auto_20191013_1246'),
]
operations = [
migrations.AlterField(
model_name='register',
name='prime_on... | 719 | 225 |
#!/usr/bin/env python3
#
# Copyright (c) 2020 Google LLC.
# 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.... | 2,787 | 935 |
# -*- coding:utf-8 -*-
"""
events.py
~~~~~~~~
自定义信号, 事件
:author: Fufu, 2019/12/20
"""
from blinker import signal
# 用户登录成功
event_user_logined = signal('event_user_logined')
# 系统管理操作(用户授权/权限组管理等)
event_sys_admin = signal('event_sys_admin')
# app 上下文环境示例
event_async_with_app_demo = signal('event_async_... | 336 | 180 |
import datetime
import click
from oura import OuraClient
def download(db, token):
client = OuraClient(personal_access_token=token)
click.echo("User: ")
click.echo(client.user_info())
# FIXME get start_date from database (last day downloaded - 1day)
start_date = "2015-01-01"
end_date = str(da... | 1,181 | 396 |
import cv2
import os
import time
import advancedcv.hand_tracking as htm
import numpy as np
import itertools
patterns = np.array(list(itertools.product([0, 1], repeat=5)))
p_time = 0
cap = cv2.VideoCapture(0)
# w_cam, h_cam = 648, 480
# cap.set(3, w_cam)
# cap.set(4, h_cam)
folder_path = "finger_images"
my_list = os... | 1,635 | 690 |
import paddle
import paddlefsl
from paddlefsl.model_zoo import maml
# Set computing device
paddle.set_device('gpu:0')
# """ ---------------------------------------------------------------------------------
# Config: MAML, Omniglot, MLP, 5 Ways, 1 Shot
TRAIN_DATASET = paddlefsl.datasets.Omniglot(mode='train', image_s... | 12,852 | 5,329 |
import numpy as np
import collections, numpy
import glob
from PIL import Image
from matplotlib.pyplot import cm
nrImages = 1
imageSize = 449
finalImageSize = 449
ImageNumber = 0
sourceFolder = 'images'
# sourceFolder = "testInput"
destinationFolder = 'final_text_files_2'
# destinationFolder = "testOutpu... | 3,085 | 1,249 |
from ravager.database.tasks import Tasks
import logging
from ravager.database.helpers import setup_db
from ravager.config import DATABASE_URL, LOGS_DIR
from ravager.helpers.check_process import Process
from subprocess import check_call
logger = logging.getLogger(__file__)
setup_db.create_tables()
logger.info("Databas... | 1,857 | 652 |
from PyDAQmx import *
from ctypes import byref, c_ulong,c_int32
import numpy as np
class DAQSimpleDOTask(Task):
'''
a simple task that set one digital output line to high or low
'''
def __init__(self,chan= 'Dev2/port0/line5'):
'''
chan: name of the chanel, in the format of Dev2/por... | 4,623 | 1,451 |
#//
#// -------------------------------------------------------------
#// Copyright 2011 Synopsys, Inc.
#// Copyright 2010-2011 Mentor Graphics Corporation
#// Copyright 2019-2020 Tuomas Poikela (tpoikela)
#// All Rights Reserved Worldwide
#//
#// Licensed under the Apache License, Version 2.0 (the
#//... | 1,603 | 528 |
from math import inf
nums = list(map(int, input().split()))
signs = { '+': 1, '-': 2, '*': 3, '/': 4, '%': 5, '=': 0 }
anss = []
def comb(nums, exp, wasEq):
if not nums:
try:
res = eval(exp)
except:
res = 0
if type(res) == bool and eval(exp):
anss.append(exp)
return
return
cur, nrest = str(n... | 1,110 | 539 |
#
# Copyright 2021 by Tatsuya Hasebe, Hitachi, Ltd.
# All rights reserved.
#
# This file is part of the KEMPNN package,
# and is released under the "BSD 3-Clause License". Please see the LICENSE
# file that should have been included as part of this package.
#
import datetime
import json
import os
import pickle
import ... | 15,291 | 4,723 |
num = int (input ('Digite um número inteiro: '))
if num % 2 != 0 and num % 3 != 0 and num % 5 != 0 and num % 7 != 0:
print ('{} é um número primo'.format(num))
else:
print ('{} não é um número primo.'.format(num))
| 222 | 84 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 Graz University of Technology.
#
# invenio-records-lom is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Provider for LOM PID-fields."""
from invenio_drafts_resources.records.api import ... | 659 | 231 |
# -*- coding: utf-8 -*-
# Part of Ygen. See LICENSE file for full copyright and licensing details.
{
'name': 'Discord - Base module for discord',
'summary': """
This module is a base module to provide foudation for building discord modules for Odoo.""",
'description': """
This module is a b... | 1,127 | 386 |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
import os
basePath = os.path.abspath(os.path.dirname(__file__))
template_dir = os.path.join(basePath, 'templates')... | 696 | 247 |
x = int(input())
for i in range(12):
if (i+x) % 2 ==1:
print(i+x)
| 78 | 39 |
from ..constants import JSON_PROP_TYPE
from .base_blueprint import BaseProcedureBlueprint
from ..steps import placeholders
from ..reagents import Reagent
DEFAULT_VESSEL: str = 'reactor'
DEFAULT_SEPARATION_VESSEL: str = 'separator'
DEFAULT_EVAPORATION_VESSEL: str = 'rotavap'
class Chasm2(BaseProcedureBlueprint):
... | 6,167 | 2,022 |
class Admin(object):
def __init__(self):
self.rpc_host = None
self._abci_info_url = None
self._abci_query_url = None
self._block_url = None
self._block_result_url = None
self._block_chain_url = None
self._broadcast_tx_async_url = None
self._broadcast... | 1,487 | 501 |
from future.utils import iteritems
from pandaharvester.harvestercore import core_utils
class PluginBase(object):
def __init__(self, **kwarg):
for tmpKey, tmpVal in iteritems(kwarg):
setattr(self, tmpKey, tmpVal)
# make logger
def make_logger(self, base_log, token=None, method_name=Non... | 570 | 175 |
"""
Filtering of MEG data
Created on 13.9.2017
@author: Anja Thiede <anja.thiede@helsinki.fi>
"""
import os
from os import walk
import datetime
import numpy as np
import mne
now = datetime.datetime.now()
def processedcount(file_list):
n = 0
for item in file_list:
if item[-8:-4] == 'filt':
... | 1,762 | 618 |
x = int(input())
if (-15 < x <= 12) or (14 < x < 17) or x >= 19:
print("True")
else:
print("False")
| 108 | 53 |
#
# Copyright 2020–21, by the California Institute of Technology. ALL RIGHTS
# RESERVED. United States Government Sponsorship acknowledged. Any commercial
# use must be negotiated with the Office of Technology Transfer at the
# California Institute of Technology.
#
"""
===============
doi_database.py
=============... | 22,972 | 6,471 |
# -*- coding: utf-8 -*-
# pylint: disable=E1101
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPNotFound
from amnesia.modules.tag import Tag
from amnesia.modules.search import SearchResource
def includeme(config):
''' Pyramid includeme func'''
config.scan(__name__)
@view_confi... | 786 | 268 |