content stringlengths 5 1.05M |
|---|
import click
from . import fio
from . import utils
from .config import column_default
from .fio import fio_client
DEFAULT_COLS = column_default(
"review_links", "id,name,item_count,view_count,short_url,expires_at"
)
@click.group()
def review_links():
"""Review link related commands"""
@review_links.command... |
from collections import namedtuple
from django.conf import settings
from django.core.mail import send_mail, EmailMultiAlternatives
from django.core.management.base import BaseCommand, CommandError
from django.http import HttpResponse
from django.template import loader, Context
import json
import requests
from weatherm... |
from setuptools import setup
setup(
name = 'bangla',
version = '1',
description = 'This is a package consist of bengali words, stop words, stemmer module, etc.',
packages = ['bangla'],
package_data={'bangla': ['data/*.pkl', 'lib/*.py']},
zip_safe = False,
include_package_data = Tru... |
# encoding: utf-8
# Copyright 2011 Tree.io Limited
# This file is part of Treeio.
# License www.tree.io/license
"""
Reporting module URLs
"""
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('treeio.reports.views',
# Index pages
url(r'^(\.(?P<response_format>\w+))?$'... |
import sys
from PyQt5.QtWidgets import (
QApplication, QVBoxLayout, QLabel, QLineEdit, QToolButton, QGroupBox, QMessageBox)
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QIcon
KEY_LIST = ['BID', 'BNAME', 'AUTHOR',
'PUBLICATION_DATE', 'PRESS', 'POSITION', 'SUM', 'CLASSIFICATION']
class B... |
# ---
# jupyter:
# kernel_info:
# name: python3
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% outputHidden=false inputHidden=false tags=["parameters"]
param = 4
# %% outputHidden=false inputHidden=false
import pandas as pd
# %% outputHidden=false inputHidden... |
#!/usr/bin/python3
import setuptools
from dataserve import __version__
#To create the pypi distribution do..
# python3 setup.py sdist bdist_wheel
with open('README.md', 'r') as fh:
readme = fh.read()
setuptools.setup(
name='dataserve',
version=__version__,
author='Brad Jascob',
author_email='bj... |
# Generated by Django 3.2.7 on 2021-10-01 20:08
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import kutub.fields
class Migration(migrations.Migration):
dependencies = [
('kutub', '0032_auto_20211001_1924'),
]
operations = [
migr... |
"""
Database handling code for fastloansearch using SQLAlchemy's declarative syntax
"""
__author__ = 'Doug Bromley'
__email__ = "doug@tintophat.com"
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from key import DBNA... |
from json import dumps
from flask import Blueprint, redirect, request
from .doc import auto
frontend = Blueprint('frontend', __name__, url_prefix='/blog')
users = []
posts = []
class User(object):
def __init__(self, username):
self.username = username
users.append(self)
self.id = use... |
'''
Created on 2015年12月1日
1. While there are still tokens to be read in,
1.1 Get the next token.
1.2 If the token is:
1.2.1 A number: push it onto the value stack.
1.2.2 A variable: get its value, and push onto the value stack.
1.2.3 A left parenthesis: push it onto the operator stack.
... |
from time import sleep
from typing import Any, List
import psycopg2
import psycopg2.extras
def error_handler(func):
def wrapper(*args, **kwargs):
self = args[0]
max_retries = self.max_retries
retry_delay = self.retry_delay
for i in range(1, max_retries + 1):
try:
... |
"""
Copyright 2019 Samsung SDS
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... |
# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
import numpy as np
class K1C1HCNN():
'''
this model have 1 convolution layer and 1 hid... |
import requests
from bs4 import BeautifulSoup
# 극작가 목록 api 추출
anc_list = requests.get("http://www.kopis.or.kr/openApi/restful/prfper?service=3dbea193a9e0445a9c80d813e9233d93&stdate=20210101&eddate=20211231&cpage=1&rows=7019".encode('utf-8'))
anc_soup = BeautifulSoup(anc_list.content, "html.parser")
anc_id = list(str(a... |
#!/usr/bin/env python
import logging
import os
import sys
from concurrent import futures
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(CURRENT_DIR))
from database import initialize_db
from src import scrapping_sites
logging.basicConfig(level=logging.INFO)
# True is used wh... |
# =================================================
# minso.jeong@daum.net
# 25. CLAHE
# Reference : samsjang@naver.com
# =================================================
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
def clahe():
img = cv.imread('../Images/31.light.jpg', cv.IMREAD_GRAYSCALE)
c... |
__author__ = "Nicholas Harding"
# This script takes a single zarr zipstore, and computes summary stats
# of the alignment from the AD and GT fields of calldata/
import zarr
import allel
import pandas as pd
import sys
import argparse
import numpy as np
def log(*msg):
print(*msg, file=sys.stderr)
sys.stderr.f... |
from shared.views import CURDViewSet
from systemconfig.models import *
from systemconfig.serializers import NationalitySerializer
from rest_framework.views import APIView
# from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
clas... |
import json
from rest_framework import fields
from api.experiments.serializers import ExperimentJobDetailSerializer
def get_job_definition(definition):
serializer = ExperimentJobDetailSerializer(data={
'definition': json.dumps(definition, default=fields.DateTimeField().to_representation)
})
seri... |
import unittest
from neo3 import storage
from neo3.core import types
class StorageKeyTest(unittest.TestCase):
def test_eq(self):
contract = types.UInt160.zero()
key_val = b'\0x01\x02\x03'
sk = storage.StorageKey(contract, key_val)
sk2 = storage.StorageKey(contract, key_val)
... |
#
# Copyright (c) 2020 Averbis GmbH.
#
# This file is part of Averbis Python API.
# See https://www.averbis.com for further info.
#
# 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:... |
from ev_core.config import Config
from ev_core.drivers.basedriver import BaseDriver
import os
import hashlib
from utils.langutils import *
#
# A simple noń virtual driver
# which allows to trigger another python script
# this can be used for macros or whatever comes your mind
#
class FEvalDriver(BaseDriver):
_ini... |
import time
import binascii
from struct import pack
from socket import socket, AF_PACKET, SOCK_RAW
try:
interval = float(input('Enter time interval(s): '))
# create a raw socket
raw_socket = socket(AF_PACKET, SOCK_RAW)
raw_socket.bind(('interface_name', 0))
# prepare the packet to be replayed
... |
from numpy import random
from matplotlib import pyplot
random.seed(12345)
sequence = random.normal(size=1000000, loc=30, scale=5)
pyplot.hist(sequence, bins=20)
pyplot.show()
|
from contextlib import (
contextmanager,
)
from decimal import (
Decimal,
)
import json
from time import (
monotonic,
sleep,
)
import urllib.request
import warnings
import zipfile
from splinter.driver import (
DriverAPI,
)
METAMASK_DOWNLOAD_URL = 'https://github.com/MetaMask/metamask-extension/' \... |
from baby_steps import given, then, when
from district42 import schema
from .._fixtures import * # noqa: F401, F403
def test_const_generation(*, generate, random_):
with given:
sch = schema.const
with when:
res = generate(sch)
with then:
assert res is None
def test_const_valu... |
import torch
import torch.nn as nn
import numpy as np
import time
import tensorflow as tf
from tensorflow.python.layers import core as layers_core
def data_type():
return tf.float32
class RNNModel(nn.Module):
"""Container module with an encoder, a recurrent module, and a decoder."""
def __init__(self, option):... |
from marshmallow import Schema, fields
class TaskInfoSchema(Schema):
"""Task metainfo schema"""
task_name = fields.String(attribute='task_name')
display_name = fields.String(attribute='display_name')
class ModelInfoSchema(Schema):
"""Model metainfo schema"""
model_name = fields.String(attribut... |
from pprint import pprint
import numpy as np
import cv2
import os
# CenterNet
import sys
CENTERNET_PATH = './CenterNet/src/lib'
sys.path.insert(0, CENTERNET_PATH)
from detectors.detector_factory import detector_factory
from opts import opts
MODEL_PATH = './CenterNet/models/ctdet_coco_dla_2x.pth'
ARCH = 'dla_34'
# M... |
from skimage import io, transform
import glob
import os
import json
import numpy as np
img_dir = 'data/images/'
image_shape = (320, 240, 3)
print(glob.glob(os.path.join(img_dir, '*.jpg')))
def preprocess(image) :
return transform.resize(image, image_shape)
def read_image(image_name, split, ifpreprocess=True) :... |
from talon import actions
input_raw = "why? and it's nice!"
input_raw_numbers = "why? and it's nice 123.0!"
fixtures_format = [
# Simple formatters
["NOOP", input_raw, input_raw],
["TRAILING_PADDING", input_raw, f"{input_raw} "],
["ALL_CAPS", input_raw, input_raw.upper()],
["ALL_LOWERCASE", input_... |
# -*- coding: utf-8 -*-
# @Time : 2021/6/19 11:30 上午
# @Author : Haonan Wang
# @File : Load_Dataset.py
# @Software: PyCharm
import numpy as np
import torch
import random
from scipy.ndimage.interpolation import zoom
from torch.utils.data import Dataset
from torchvision import transforms as T
from torchvision.tran... |
class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
k=0
x={}
for i in nums:
if i not in x:
x[i]=1
else:
x[i]+=1
for i,j in x.items():
if j==1:
k+=i
return k
|
from collections import namedtuple
from django.conf import settings
from django.http import HttpResponseRedirect, QueryDict
from django.utils.six.moves.urllib.parse import urlparse, urlunparse
from django.shortcuts import resolve_url
SSOUser = namedtuple('SSOUser', ['id', 'email', 'session_id'])
class SSOLoginRequ... |
from __future__ import unicode_literals
import logging
import sys
import os
import re
import shutil
from . import errors
from .tvdb import TVDB
log = logging.getLogger('Core')
def clean_name(filename, before=':', after=','):
"""
Cleans the string passed in.
A wrapper of Python's str.... |
import sys, json, os
import numpy as np
from scipy.spatial.transform import Rotation
import matplotlib.pyplot as plt
import cv2
import pdb
"""
- This script finds features in the TUMVI indoor sequences and records their
pixel locations and their X, Y, Z position in the camera frame.
- The position of the camera fr... |
"""
Tests the functionality of validate.py with several different recipes which should raise different errors
"""
import json
import sys
from unittest import mock
import pytest
import workflows
from workflows.recipe.validate import main, validate_recipe
def test_validate_returns_type_error_when_called_without_para... |
import random
char=input("Desired Characters (1.Uppercase 2.Lowercase 3.Numbers 4.Symbols ex:134)")
tmplt=char.replace("1", "ABCDEFGHIJKLMNOPQRSTUVWXYZ").replace("2", "abcdefghijklmnopqrstuvwxyz").replace("4", "!%&*()-_=+/?.>,<':;[]").replace("3", "0123456789")
print("Generationg password from", tmplt)
lgth=input("Des... |
from core.himesis import Himesis
import cPickle as pickle
from uuid import UUID
class HRule1_1(Himesis):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HRule1_1.
"""
# Flag this instance as compiled now
self.is_compiled = True
... |
"""
Some utility functions for the data analysis project.
"""
import numpy as np, healpy as hp, pylab as plt
from pixell import curvedsky
from pspy import pspy_utils, so_cov, so_spectra, so_mcm, so_map_preprocessing
from pspy.cov_fortran.cov_fortran import cov_compute as cov_fortran
from pspy.mcm_fortran.mcm_fortran im... |
"""All public configuration of application"""
import os
from dotenv import load_dotenv
base_dir = os.path.abspath(os.path.dirname(__name__))
load_dotenv(os.path.join(base_dir, '.env'))
class BaseConfig:
DEBUG = False
SECRET_KEY = '\xbf\xb0\x11\xb1\xcd\xf9\xba\x8bp\x0c...'
SQLALCHEMY_DATABASE_URI = 'sqli... |
def dutchFlag(arr):
r = 0
b = len(arr) - 1
i = 0
while i <= b:
if arr[i] == 'R':
arr[i], arr[r] = arr[r], arr[i]
i += 1
r += 1
elif arr[i] == 'G':
i += 1
else:
arr[i], arr[b] = arr[b], arr[i]
b -= 1
retur... |
def test_it(a, b):
sum_a=0
sum_b=0
for addDigit in str(a):
sum_a+=int(addDigit)
for addDigit2 in str(b):
sum_b+=int(addDigit2)
return sum_a*sum_b |
import torch
from torch import nn
from torch.nn import Module
from torchvision.transforms import transforms
import copy
from nn_interpretability.interpretation.backprop.backprop_base import BackPropBase
from nn_interpretability.interpretation.backprop.smooth_grad import add_noise
class GuidedBackprop(BackPropBase):
... |
import re
from itertools import chain
from django import forms
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext as _, ugettext_lazy, get_language
from django.utils.safestring import mark_safe
try: #Django 1.7+
from django.contrib.admin.options import TO_FIELD... |
import os
from time import time
from keras.models import Model
import keras
from keras.preprocessing.image import ImageDataGenerator
import numpy as np
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
from keras.models import load_model
from resnet152 import ResNet152
from keras.layers import Dense, Ac... |
# Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
import numpy as np
np.random.seed(1)
import time
import warnings
import sys
import os
if not sys.warnoptions:
warnings.simplefilter("ignore")
os.environ["PYTHONWARNINGS"] = 'ignore'
class GeneticAlgorithmFS:
'''
Machine Learning Parameters
----------
model : Model object. It should ha... |
import math
from discord.ext import commands
from discord import Embed, Color
levelExp = [100, 205, 315, 430, 550, 675, 805, 940, 1080, 1225, 1375, 1530, 1690, 1855, 2025, 2200, 2380, 2565, 2755, 2950, 3150, 3355, 3565, 3780, 4000, 4225, 4455, 4690, 4930, 5175, 5425, 5680, 5940, 6205, 6475, 6750, 7030, 7315, 7605, 790... |
MIDDLE_HIGH_GERMAN_CORPORA = [
{
'name': 'middle_high_german_models_cltk',
'origin': 'https://github.com/cltk/middle_high_german_models_cltk.git',
'location': 'remote',
'type': 'model'
},
]
|
"""
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。
示例 1:
输入:["h","e","l","l","o"]
输出:["o","l","l","e","h"]
示例 2:
输入:["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]
"""
class Solution(object):
def reverseString(self, s):
... |
from speedo_server.database.exceptions import EnumError, SpeedoServerError
from typing import Dict, List, Any, Optional
from datetime import datetime, timezone
from sqlalchemy.sql import select, desc, and_
from sqlalchemy.sql.functions import func
from .tables import (
Submission,
Project,
User,
TagRel... |
from dhtc import HC #从dhtc模块中导入HC类
import time #导入时间模块
hc = HC() #创建HC对象
test = 30 #计数
while test>0:
l = hc.read() #读取距离
print(l) #在终端上输出距离
time.sleep(1) #睡眠一秒
test-=1 #计数自减1 |
# 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 or agreed to in writing, ... |
import os
import shutil
from time import time
from datetime import datetime
class Utils(object):
''' Static Helpers.'''
@staticmethod
def rm_tree(path):
'''Removes all the files.'''
if os.path.isdir(path):
if os.name == 'nt':
#Hack for Windows. Shutil can't remo... |
import json
import uuid
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.schema import FetchedValue
from app.extensions import db
from app.api.utils.models_mixins import AuditMixin, Base
class ApplicationStatusCode(AuditMixin, Base):
__tablename__ = 'application_status_code'
application_statu... |
import unittest
from flapi.jwt.rules import JwtRule
class JwtRuleTest(unittest.TestCase):
def test_raises_not_implemented(self):
self.assertRaises(NotImplementedError, JwtRule(), "token")
|
locale = 'fr'
|
import argparse
import torch
from torch.utils.tensorboard import SummaryWriter
import config
from lib.dataset.codd import CODDAggDataset
from lib.dataset.kitti import KITTIOdometryDataset
from lib.dataset.datatransforms import Compose, VoxelSampling, RandomRotationTransform
from lib.models.fastreg import FastReg
from... |
# Copyright 2016 Bridgewater Associates
#
# 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... |
from luxon.core.handlers.cmd.application import Application as Cmd
|
"""
Module to build FFT -related arrays of 2D images
to be used in multiscale analysis or multi-operations
and reduce computation time
Created: Feb 19, 2019
Author: Cristina MT
"""
import numpy as np
class BuildFFT():
"""
Builds the 2D FFT of an image and the base grid matrix
to be used in convolution computatio... |
"""
VW Platform Application Package Constructor
"""
from flask import Flask
from flask_cors import CORS
from flask_mongoengine import MongoEngine
from config import config
db = MongoEngine()
# enable cross-origin resource sharing for the REST API
cors = CORS(resources={r'/api/*': {'origins': '*'}})
# enable cross... |
class Footer:
pass
|
"""Python based utilities for the registration system."""
import os
import json
from urllib.parse import quote_plus
from functools import lru_cache
import pymongo
CRED_DIR_PATH = os.path.expanduser('~/.datahack/')
CRED_FNAME = 'mongodb_credentials.json'
def _get_credentials():
fpath = os.path.join(CRED_DIR_PA... |
from .Sessions import Sessions
__version__='0.1.0' |
import numpy as np
from spn.structure.Base import Context
from spn.structure.StatisticalTypes import MetaType
from spn.algorithms.LearningWrappers import learn_mspn
from scipy.io import arff
import pandas as pd
from spn.algorithms.Inference import log_likelihood
data_name = "iris"
train_data_path = "../../data/continu... |
"""
UNet structure models,
mainly for ECG wave delineation
References:
-----------
[1] Moskalenko, Viktor, Nikolai Zolotykh, and Grigory Osipov. "Deep Learning for ECG Segmentation." International Conference on Neuroinformatics. Springer, Cham, 2019.
[2] https://github.com/milesial/Pytorch-UNet/
"""
import sys
from co... |
'''
/**
* This is the solution of No. 114 problem in the LeetCode,
* the website of the problem is as follow:
* https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list
* <p>
* The description of problem is as follow:
* ===================================================================================... |
# Generated by Django 2.0.5 on 2018-05-20 05:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('showme', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='showme',
name='image',
field... |
# -*- coding: utf-8 -*-
# Example package with a console entry point
"""Reads and formats data from the SWMM 5 output file."""
from __future__ import absolute_import, print_function
import copy
import datetime
import os
import struct
import sys
import warnings
from builtins import object, range, str, zip
import mand... |
# link: https://pytorch.org/docs/stable/nn.html#loss-functions
import torch.nn as nn
# some example of built-in loss functions in pytorch
L1 = nn.L1Loss()
MSE = nn.MSELoss()
CE = nn.CrossEntropyLoss()
BCE = nn.BCELoss()
BCE_L = nn.BCEWithLogitsLoss()
# in use:
def get_loss(pred, mask):
loss = L1(p... |
import argparse
import numpy as np
from keras import backend as K
import matplotlib.pyplot as plt
from keras.optimizers import RMSprop
from keras.models import Model, Sequential
from keras.layers import Input, Conv1D, MaxPooling1D, Lambda, LSTM, Dropout, BatchNormalization, Activation
def LoadData(path_Xtrain, path_Yt... |
# package
from .pidPS import *
|
import re
VERSION = '0.7.0'
def readlines(filename: str) -> list[str]:
with open(filename) as in_f:
return in_f.readlines()
def writelines(filename: str, lines: list[str]):
with open(filename, 'w') as out_f:
out_f.write(''.join(lines))
def update_version(filename: str, pattern: str, vers... |
# --------------------------------------------------------
# TensorFlow @ Dragon
# Copyright(c) 2017 SeetaTech
# Written by Ting Pan
# --------------------------------------------------------
from dragon.vm.tensorflow.ops import nn
from dragon.vm.tensorflow.layers import base, utils
class _Pooling2D(base.Layer):
... |
# Solfec-2.0 input command test: ARGV
import sys
output = ARGV()
print(output)
sys.stdout.flush()
|
import re
line = 'a sdf fjdk; afed, fjek,asdf, foo'
print(re.split(r'[;,\s]\s*', line)) |
# MIT License
#
# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020
#
# 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
# r... |
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.schema import FetchedValue
from sqlalchemy.ext.associationproxy import association_proxy
from app.api.utils.models_mixins import Base
from app.api.mines.documents.models.mine_document import MineDocument
from app.extensions import db
class ExplosivesPer... |
# coding=utf-8
from __future__ import absolute_import, division, print_function
from oct.cli.util.repository_options import Repository
from oct.tests.unit.playbook_runner_test_case import CLICK_RC_USAGE, PlaybookRunnerTestCase, TestCaseParameters, \
show_stack_trace, PlaybookRunCallSpecification
if not show_stack... |
"""
Handles all POST requests
"""
from controller import Controller
from utils import public
class PostController(Controller):
"""
Handles all POST requests
For details: see controller.py
"""
@public
def login(self, name, password):
"""Try to login user with name and passwor... |
import pandas as pd
def manual_agg_func(dg):
dg_cnt = dg["marker"].count()
dg_max = dg["marker"].max()
dg_min = dg["marker"].min()
dg_mean = dg["marker"].mean()
return pd.Series([dg_cnt, dg_max, dg_min, dg_mean], index=["marker_count",
... |
import asyncio
import requests
from python3_anticaptcha import NoCaptchaTaskProxyless, NoCaptchaTask
ANTICAPTCHA_KEY = "ae23fffcfaa29b170e3843e3a486ef19"
"""
Синхронный пример без прокси
Sync example without proxy
"""
result = NoCaptchaTaskProxyless.NoCaptchaTaskProxyless(anticaptcha_key=ANTICAPTCHA_KEY).captcha_ha... |
"""Re-export of numproto methods"""
from numproto.numproto import ndarray_to_proto, proto_to_ndarray
|
import copy
import os
import pprint
import numpy as np
import tensorflow as tf
from dfp import util as my_util
from dfp.agent_multimodal_advantage import AgentMultimodalAdvantage
from dfp.future_target_maker import FutureTargetMaker
from dfp.experience_memory import ExperienceMemory
from dfp.multi_simulator import Mu... |
import polars as pl
def test_sort_by_bools() -> None:
# tests dispatch
df = pl.DataFrame(
{
"foo": [1, 2, 3],
"bar": [6.0, 7.0, 8.0],
"ham": ["a", "b", "c"],
}
)
out = df.with_column((pl.col("foo") % 2 == 1).alias("foo_odd")).sort(
by=["foo",... |
from Constract.IPull import IPull
from HcServices.Http import Http
import logging
from Database.Db import Db
test_data = [
{
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"name": "string",
"hasTimer": True,
"startAt": "2021-07-19T06:50:26.470Z",
"endAt": "2021-07-19T06:50:26.470Z",
"hasRepeat... |
import concurrent.futures
import main
def main_multi():
executor: concurrent.futures.Executor
executor = concurrent.futures.ProcessPoolExecutor()
for i in range(0, 4):
executor.submit(main.main, False, '127.0.0.1', 8052, f'Human:{i}')
executor.shutdown()
if __name__ == '__main__':
main_m... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import render_template, redirect, url_for, flash
from app.exceptions import ValidationError
from app.form import form
from app.models.email_event import EmailEvent
from app.models.email_event_form import EmailEventForm
from app.models.email_group import EmailGr... |
import requests
omk = requests.get("https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data")
r = omk.text
sut = r.rstrip().split("\n")
print([[el] for el in sut])
import pickle
cars = sut
file = "picklefile2.pkl"
fileobj = open(file, 'wb')
pickle.dump(cars, fileobj)
fileobj.close()
file = "picklef... |
from uninstall import uninstall # noqa
from megdc.util import pkg_managers
# Allow to set some information about this distro
#
distro = None
release = None
codename = None
def choose_init(module):
"""
Select a init system
Returns the name of a init system (upstart, sysvinit ...).
"""
if distro.... |
from .SimpleNullStringRecordSchema import SimpleNullStringRecordSchema
from .AvroSchema import AvroSchema
from .ComplexAvroSchema import ComplexAvroSchema
|
import os
import time
import uuid
from django.db import models
from datetime import datetime
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
#Generate a uuid
def _createid():
unique_id = str(uuid.uuid4())
unique_id.replace("-", "_"... |
# coding=utf-8
class OmittedType(object):
"""
Omitted represents a Do Not Care value, useful when None won't work
because it's a valid value.
"""
__slots__ = tuple()
|
from tkinter import messagebox
global_funciones_extra = ""
funciones_extra = ""
def agregar_a_global_funciones_extra(entrada):
global global_funciones_extra
global_funciones_extra += '''
global %s''' % entrada
class GeneradorFileC3D:
def __init__(self):
self.path_archivo_c3d = '../interfaz/... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from numba import jit
import setup_bmss as lab
import BMSS.models.settings_handler as sh
import BMSS.models.setup_cf as sc
import BMSS.icanalysis as ac
import BMSS.curvefit... |
from shared_matrix import SharedMatrix
from custom_barrier import CustomBarrier
from threading import Thread, current_thread
from typing import Tuple, Union
from statistics import mean
class Worker(Thread):
def __init__(self, barrier: CustomBarrier, observer_barrier: Union[CustomBarrier, None], shared_matrix: Sha... |
import os
from pathlib import Path
import sys
from scipy.spatial import cKDTree
import time
import pickle
from Bio import SeqIO
import re
import subprocess
def miRNA_miRge_format(hpin, mir):
start, end = re.search(mir, hpin).span()
prefix = hpin[:start][-2:]
suffix = hpin[end:][:6]
new_mir = prefix + m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.