content stringlengths 5 1.05M |
|---|
import discord
from discord.ext import commands
from json_functions import read_json,edit_json
bot=commands.Bot(command_prefix='!')
register_list=read_json('register_list')
@bot.event
async def on_ready():
print(bot.user.name)
print(bot.user.id)
for server in bot.servers:
print(server.name)
@bot.command(pass_c... |
class Monster:
name = "lizard"
attack = 0
defense = 0
speed = 0
awareness = 0
hitpoints = 10
attacks = {}
description = "Default monster"
bookDescription = "Default"
drops = []
X = 0
Y = 0
def __init__(self,nme,atk, defnse, spd, aware, hp, atks, desc, bookDesc,drops, x, y):
self.name = nme
self.attack... |
import numpy as np
import pandas as pd
def _UnionFatherSearch(idx, union_array):
if union_array[idx] == idx:
return idx
union_array[idx] = _UnionFatherSearch(union_array[idx], union_array)
return union_array[idx]
class BarcodeSearch():
'''
BarcodeSearch: Class for calculating zero sublev... |
import pytest
import respx
@pytest.fixture()
def httpx_mock():
"""respx mock object"""
with respx.mock(base_url='http://example.com') as _httpx_mock:
yield _httpx_mock
|
#!/usr/bin/env python
'''
==================
Git Commit Handler
==================
'''
import sys, subprocess as sp
from os import path, chdir, getcwd
import click
from pysrc import issues
from pysrc.qs import getAnswer, isExist
from pysrc.git import *
issues.version(3)
defaults = {}
defaultspath = path.join(".", ... |
from django.core.cache.backends.memcached import BaseMemcachedCache
import pickle
class GaeMemcachedCache(BaseMemcachedCache):
def __init__(self, server, params):
from google.appengine.api import memcache
BaseMemcachedCache.__init__(self, server, params,
library=memcache, value_not... |
import asyncio
from asyncio import CancelledError
from . import loggers, rpc
from .cm import CM
from .loggers import Adapter
from .timer import ElectionTimer, HeartbeatTimer
logs = loggers.get(__name__)
class Server(rpc.Server):
def __init__(
self,
id,
peers=None,
ask_peer_timeou... |
import logging
from os import path, environ
from pathlib import Path
import git
logger = logging.getLogger(__name__)
logger.setLevel(int(environ.get('LOG_LEVEL', 10)))
STAGE_PRD: str = "prd"
# Staging constant - production
STAGE_DEV: str = "dev"
# Staging constant - development
STAGE_LCL: str = "lcl"
# Staging c... |
"""art_app URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... |
from random import randint
from hud_library import *
pygame.mixer.init()
import time
class Sprite(UIElement):
def __init__(self, position, size):
UIElement.__init__(self, position, size)
brush = UIBrush(self._surface)
self._velocity = Vector()
self.should_delete = False
... |
from vector import Vector
class Translatable(object):
def __init__(self, position = (0, 0)):
self.__position = Vector(position[0], position[1])
def set_position(self, position):
self.__position = Vector(position[0], position[1])
def position(self):
return self.__position
def... |
"""
VIS Data Reduction Pipeline
===========================
This simple backbone can be used as a VIS data reduction pipeline.
The pipeline performs the following data reduction steps that can be controlled using a config file:
#. Nonlinearity correction
#. Bias subtraction
#. Charge transfer inefficienc... |
import logging
from collections import ChainMap
from typing import Dict, Tuple, Optional, Union, Iterable
import numpy as np
from autoconf import cached_property
from autofit import exc
from autofit.graphical.factor_graphs.abstract import AbstractNode
from autofit.graphical.factor_graphs.factor import Factor
from aut... |
# Libraries
import random
# Constants
values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
suits = ['hearts', 'clubs', 'spades', 'diamonds']
# Functions
def coin_toss(pick):
toss = random.choice(['Heads', 'Tails'])
if toss == pick:
return True
else:
return False
... |
#!/usr/bin/python
# now I wish I had done the first one the naive way
# this time we will build a matrix and step around it
# totalling the values
# there probably is a mathematical way to calculate the adjacency
# but I am quicker to program it this way!
import math
with open("input.txt") as fp:
value = int(fp... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from graph_nets import modules
from graph_nets import utils_tf
from graph_nets import blocks
import sonnet as snt
LATENT_SIZE = 64
NUM_LAYERS = 4
def make_mlp_model():
"""Instantiate... |
from urllib.request import urlopen
import hmac
import hashlib
from math import ceil
from io import BytesIO
from base64 import b64decode
from typing import Union
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
class Decryptor:
@... |
from django.apps import AppConfig
class WarriorsAppConfig(AppConfig):
name = 'warriors_app'
|
import os
import numpy as np
import torch
from PIL import Image
from skimage import io, transform, color
import cv2
from torch.utils.data import DataLoader, IterableDataset, Dataset
import scipy.io
import random
def generate_hm(self, height, width, landmarks, s=1.0, upsample=True):
""" Generate a full Heat Map for... |
from src.setting import DATA_ANALYST, ANALYST_PWD
from src.util import connect_mongo
conn = connect_mongo(db='quote', username=DATA_ANALYST, password=ANALYST_PWD)
from src.api.common import get_price, get_segments, get_blocks, get_peak_start_date
from src.api.futures import get_roll_yield
from src.api.cons import FRE... |
""" Custom errors thrown by the package"""
class pgError(Exception):
"""Base error raised by pyIsoFit-master"""
class ParameterError(pgError):
"""Raised when one of the parameters is unsuitable"""
class SaveError(pgError):
"""Raised when the .save method is called incorrectly"""
class HenryError(pgE... |
import csv
import json
import logging
from datetime import date, timedelta
from typing import Tuple, List
from enum import Enum
import requests
from Common import Status, SaveHtmlToTable
from ScraperBase import ScraperBase
class CostcoWrapper:
def __init__(self):
self.urlKeys = {}
self.urlFront... |
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
from pymemcache import __version__
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
readme = read('README.rst')
changelog = read('ChangeLog.rst')
setup(
name='pyelasticache_client',
version=__v... |
# VMware vSphere Python SDK
# Copyright (c) 2008-2014 VMware, 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
#
# ... |
# Copyright (C) 2010-2011 Richard Lincoln
#
# 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... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
#def is used to create a new function. The function below will be hello()
#hello() will now call whats executed into when calledS
def hello():
print('Howdy')
print('Howdy!!')
print('Hello there!')
hello()
#this case adds a parameter "name" into the def function hello
def hello(name):
print... |
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
import dill
X, y = make_classification(n_samples=1000, n_features=4,
n_informative=2, n_redundant=0,
random_state=0, n_classes=2, shuffle=False)
model = RandomFo... |
from dataclasses import dataclass
@dataclass
class TaskInfo:
task_name: str
display_name: str
@dataclass
class ModelInfo:
model_name: str
display_name: str
@dataclass
class MetricInfo:
metric_name: str
display_name: str
|
import unittest
from main import *
import config
class TestPathHelper(unittest.TestCase, TxtFile):
def setUp(self):
self.path = '/Coding/GitHub/todo'
self.test_for_expected_output = '/Coding/GitHub/pip-helper/pip-helper/path_helper.py'
self.line_example = 'TxtFile().requirements_maker()\n'
self.used_libs = ... |
import aiosip
import pytest
import asyncio
async def test_notify(test_server, protocol, loop, from_details, to_details, close_order):
notify_list = [0, 1, 2, 3, 4]
subscribe_future = loop.create_future()
class Dialplan(aiosip.BaseDialplan):
async def resolve(self, *args, **kwargs):
a... |
"""add new columns type meta containerId
Revision ID: 1e86c18af2dd
Revises: 13d127569afa
Create Date: 2014-06-04 09:53:27.116054
"""
# revision identifiers, used by Alembic.
revision = '1e86c18af2dd'
down_revision = '13d127569afa'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="dockter", # Replace with your own username
version="0.1.8",
author="Samuel Mignot",
description=
"A package to create dockerfiles for jupyter notebooks to ensure compatibility",
long_... |
"""Defines fixtures common to util module testing"""
CYTON_8BIT_FIRMWARE_STRING = b'''OpenBCI V3 8bit Board
Setting ADS1299 Channel Values
ADS1299 Device ID: 0x3E
LIS3DH Device ID: 0x33
$$$'''
CYTON_V1_FIRMWARE_STRING = b'''OpenBCI V3 16 channel
ADS1299 Device ID: 0x3E
LIS3DH Device ID: 0x33
$$$'''
CYTON_V2_FIRMWA... |
# -*- coding: utf-8 -*-
import csv
import time
from PIL import Image
from enum import Enum
HIST_LENGTH = 8
INDEX_COLOR = 6
filename_no_color = "book_spine_data_no_color.csv"
filename_result = "book_spine_data.csv"
path_result = "android_application/app/src/main/assets/"
path_images = "Spines/"
class HistColor(Enum):
... |
#!/usr/bin/env python
# Amazon FPGA Hardware Development Kit
#
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License"). You may not use
# this file except in compliance with the License. A copy of the License is
# located at
#
# http:/... |
# Volatility
# Copyright (c) 2008-2013 Volatility Foundation
#
# This file is part of Volatility.
#
# Volatility is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License Version 2 as
# published by the Free Software Foundation. You may not use, modify or
# distribu... |
from mysql_utils import cnx, cmd
import threading
from queue import Queue
## Also in C:\Users\Toshiba-PC\AppData\Local\Programs\Python\Python35\Lib\site-packages
## Base class for thread-safe mysql queries
class QueryThread:
def __init__(self):
self.queryqueue = Queue(maxsize=0)
self.querythread... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from cosinnus.models import CosinnusGroupMembership
class OrganiserRoleManager(models.Manager):
def for_user(self, user):
qs = self.filter(cosinnus_group_m... |
"""
pgoapi - Pokemon Go API
Copyright (c) 2016 tjado <https://github.com/tejado>
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... |
from typing import Any, Optional
__all__ = ["find_compatible_torch_version"]
class Version:
@classmethod
def from_str(cls, version: str) -> "Version":
parts = version.split(".")
major = int(parts[0])
minor = int(parts[1]) if len(parts) > 1 else None
patch = int(parts[2]) if le... |
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, BatchNormalization
#import keras
import numpy as np
import glob
from sklearn.model_selection import train_test_split
from sklearn.utils import class_weight
from scipy.io import savemat, loadmat
from sklearn.metrics import classific... |
import xadmin
from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html
from xadmin.layout import Fieldset,Row
from .models import Post, Category, Tag
from .adminforms import PostAdminForm
from typeidea.adminx import BaseOwnerAdmin
class PostAdimn(BaseOwnerAdmin):
... |
#!/usr/bin/env python
#coding=utf8
'''
Created on Mar 18, 2013
@author: yoyzhou
'''
try:
import os
import sys
import urllib
import urllib2
import cookielib
import base64
import re
import hashlib
import json
import rsa
import binascii
import logging
except ImportError:... |
from pyscenario import *
class Scenario(PyScenario):
def get_description(self):
return 'Force a leading car to break, with parametric deceleration and AEB'
def get_map(self):
return 'simple-straight'
def init(self):
# Init main car
self.car_1 = self.build_car().set_acceler... |
import conf
from note import Note
from category import Category
conf.init_db()
|
import numpy as np
from sympy import false, true
from hdf5_to_dict import load_tracer
import os, math
import pandas as pd
from copulas.multivariate import GaussianMultivariate
from copulas.univariate import UniformUnivariate, GaussianKDE, GaussianUnivariate, BetaUnivariate
class Stat:
def __init__(self, dims:list... |
"""
RocketLogger calibration tests.
Copyright (c) 2019-2020, ETH Zurich, Computer Engineering Group
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the abov... |
"""
-*- test-case-name: PyHouse.Modules.Lighting.test.test_lighting_buttons -*-
@name: PyHouse/src/Modules/Lighting/lighting_buttons.py
@author: D. Brian Kimmel
@contact: D.BrianKimmel@gmail.com
@copyright: (c) 2010-2016 by D. Brian Kimmel
@note: Created on Apr 2, 2010
@license: MIT License
@summary: ... |
#!/usr/bin/python
import cv2
#function to find image difference. We are taking 3 frames
def diff(x,y,z):
img1=cv2.absdiff(x,y)
img2=cv2.absdiff(y,z)
com_diff=cv2.bitwise_and(img1,img2)
return com_diff
#taking 3 consistent frames
cap=cv2.VideoCapture(0)
frame1=cap.read()[1]
frame2=cap.read()[1]
frame3=cap.read()[... |
import os
def find_folders(xpath):
result = []
listdir = os.listdir(xpath)
print('ListDIR', listdir)
'''
for filename in listdir: # loop through all the files and folders
if os.path.isdir(
os.path.join(os.path.abspath("."), filename)): # check whether the current object... |
from time import sleep
import sys
import os
from Trailer.sensors.tof_laser import tof_laser
from Trailer.bluetooth.bluetooth_server import bluetooth
#from Trailer.sensors.float import float
#from Trailer.sensors.button import button
#from Trailer.sensors.ir_sensor import ir_sensor
#from bluetooth.bluetooth_server impo... |
#!/usr/bin/env python3
"""Process raw input data for individual files and create analytes from individual runs"""
import os
import sys
import pickle
from ms2analyte.converters import waters, thermo, agilent
from ms2analyte.process import filters, peak_create, analyte_create, ms2_process
from ms2analyte.output import... |
import glob
import logging
import os
from PIL import Image
default_logger=logging.getLogger(__name__)
default_logger.setLevel(level=logging.INFO)
def format_images(
target_dir:str,
image_width:int,
image_height:int,
logger:logging.Logger=default_logger):
"""
format_images resizes images and co... |
import torch
import numpy as np
TINY_NUMBER = 1e-6
#######################################################################################################
# compute envmap from SG
#######################################################################################################
def compute_envmap(lgtSGs, H, W, ... |
# data helper code
import os
from collections import defaultdict
import PIL
import numpy as np
from PIL import Image
from numba import jit
from .logger import get_logger
test_jzazbz_array = np.load("jzazbz_array.npy")
@jit
def rgb_array_to_jzazbz_array(rgb_array):
"""
Converts rgb pixel values to JzAzBz p... |
from django.conf.urls import url
from bootcamp.follow import views
urlpatterns = [
url(r'^$', views.user_detail, name='user_detail'),
]
|
from functools import wraps
from .utils import partial_prepare
def partial_step(save_to_session):
"""Wraps func to behave like a partial pipeline step, any output
that's not None or {} will be considered a response object and
will be returned to user.
The pipeline function will receive a current_par... |
from flask import request
from lin.exception import ParameterException
from lin.forms import Form
from wtforms import Form as WTForm, FieldList
from wtforms import StringField, IntegerField
from wtforms.validators import DataRequired, NumberRange, Length, Regexp, Optional
class ProductContent(Form):
name = String... |
import urllib.request
import sys
import random
import time
import minimax
import board
from math import inf
import utils
import copy
import datetime
start = 0.0
end = 0.0
if len(sys.argv) == 1:
print("Voce deve especificar o numero do jogador (1 ou 2)\n\nExemplo: ./random_client.py 1")
quit()
# Alterar s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from itertools import chain
def to_tuple(s):
return tuple(tuple(c for c in row) for row in s.split('/'))
def rotator(sq):
# Rotations
for _ in range(3):
sq = tuple(zip(*sq[::-1]))
yield sq
yield tuple((tuple(row[::-1]) for row in sq))... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-07-30 10:35
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django_fsm
class Migration(migrations.Migration):
dependencies = [
migration... |
import smart_imports
smart_imports.all()
def noun(forms, properties):
if (len(forms) == 6):
forms = forms + forms[:6]
if (len(forms) == 12):
forms = forms + forms[6:]
properties = utg_words.Properties(*[utg_data.VERBOSE_TO_PROPERTIES[prop.strip()] for prop in properties.split(',')])
... |
import datetime
import uuid
import threading
import requests
import jwt
from django.conf import settings
habilitation_mock = {
"habilitations": [
{
"id": 9,
"groupe": {
"id": 28,
"profil": {
"code": "MO_PERS_MORALE",
... |
from jpype import *
import time
remote_pack="c:/tools/netbeean-remote-pack"
profiler_options = [
"-agentpath:%s/lib/deployed/jdk15/windows/profilerinterface.dll=%s/lib,5140" % (remote_pack, remote_pack)
]
options = [
'-verbose:gc',
'-Xmx16m',
] #+ profiler_options
startJVM(getDefaultJVMPath(... |
from openslides_backend.models.models import AgendaItem
from tests.system.action.base import BaseActionTestCase
class AgendaItemSystemTest(BaseActionTestCase):
def test_create(self) -> None:
self.create_model("meeting/2", {"name": "test"})
self.create_model("topic/1", {"meeting_id": 2})
re... |
import os
import numpy as np
import tensorflow as tf
from tensorflow.python.keras.datasets import fashion_mnist
from tensorflow.contrib.eager.python import tfe
# enable eager mode
tf.enable_eager_execution()
tf.set_random_seed(0)
np.random.seed(0)
if not os.path.exists('weights/'):
os.makedirs('weights/')
# con... |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from pandas import DataFrame, Series
from matplotlib.pyplot import MultipleLocator
# 这两行代码解决 plt 中文显示的问题
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# read file
datafile = '../data/s... |
import io
from django.contrib.auth.models import Permission
from django.urls import reverse
from openpyxl import load_workbook
from chartofaccountDIT.test.factories import (
NaturalCodeFactory,
ProgrammeCodeFactory,
ProjectCodeFactory,
)
from core.models import FinancialYear
from core.test.test_base imp... |
"""
Michael duPont - michael@mdupont.com
avwx_api.cache - Class for communicating with the report cache
"""
# stdlib
import asyncio as aio
from datetime import datetime, timedelta
from os import environ
# library
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo.errors import AutoReconnect, OperationFai... |
def addr(operation, before):
after = before.copy()
after[operation[2]] = before[operation[0]] + before[operation[1]]
return after
def addi(operation, before):
after = before.copy()
after[operation[2]] = before[operation[0]] + operation[1]
return after
def mulr(operation, before):
after = b... |
"""hrcompass URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-bas... |
"""Django admin for the example app."""
|
# run spam_data_download.py to download spam data
|
# coding=utf8
import unittest
import copy
from borax.datasets.join_ import (OnClause, OC, SelectClause, SC, join, join_one, deep_join, deep_join_one)
catalogs_dict = {
1: 'Python',
2: 'Java',
3: '软件工程'
}
catalog_choices = [(1, 'Python'), (2, 'Java'), (3, '软件工程')]
catalogs_list = [
{'id': 1, 'name': '... |
"""
Input: homolog trees
Output: individual orthologs trees
if a tip is longer than the LONG_TIP_CUTOFF
and also long than 10 times its sister, cut it off
This is to fix the leftover trees that frequently has some long tips in it
If not to output 1-to-1 orthologs, for example, already analysed these
set OUTPUT_1to1_O... |
import jwt
import datetime
from ns_portal.database.main_db import (
TInstance,
TApplications,
TAutorisations,
TUsers,
TRoles,
TSite
)
from ns_portal.utils.utils import (
my_get_authentication_policy
)
# we follow the RFC7519
# look at https://tools.ietf.org/html/rfc7519#section-4.1
# for al... |
from django import forms
from django.forms.widgets import TextInput
from . import models
class ProjectForm(forms.ModelForm):
class Meta:
model = models.Project
fields = '__all__'
widgets = {
'background_colour': TextInput(attrs={'type': 'color'}),
'text_colour': Te... |
# Copyright (C) 2021 ServiceNow, Inc.
""" Train a mittens model """
import csv
import numpy as np
import pickle
import argparse
from mittens import Mittens
def glove2dict(glove_filename):
with open(glove_filename) as f:
reader = csv.reader(f, delimiter=' ', quoting=csv.QUOTE_NONE)
embed = {line[0... |
#coding:utf-8
import re
with open("test.html","r") as c:
txt = c.read()
a = re.findall(">*[0-9]+-[0-9]+-[0-9]+<*",txt)
for i in a:
#print i
with open("chem_all.txt","a") as c:
c.write(i)
|
import altair as alt
from data import load_data
from app import cache
wind = load_data(index=True)
@cache.memoize(timeout=50)
def bar_chart(selector: str = None) -> str:
"""
Function returns a bar chart of model count in each province
Args:
Selector: province. Defaults to None.
Returns... |
import json
import subprocess
# Open the current library.json file
library_json = open(
"C:\\Users\\sdamiano\\Documents\\GitHub\\EnviroDIY\\ModularSensors\\library.json",
)
library_data = json.load(library_json)
# Open the current library.json file
dependency_json = open(
"C:\\Users\\sdamiano\\Documents\\GitH... |
# -*- coding: utf-8 -*-
# Import Python libs
from __future__ import absolute_import, unicode_literals
import os
import sys
import logging
import subprocess
import tempfile
# Import Salt Testing libs
from tests.support.unit import TestCase, skipIf
from tests.support.runtests import RUNTIME_VARS
import tests.support.he... |
"""This module handle client"""
import datetime
import io
import json
import logging
import os
import re
import socket
import subprocess
import time
from collections import OrderedDict
from collections.abc import Mapping, MutableMapping
from itertools import chain
from . import errors
LOGGER = logging.getLogger(__na... |
from tts_pipeline.pipelines.waterfall.models.UnifiedKeywordExtractor import UnifiedKeywordPairsExtractor
class UnifiedKeywordPairsExtractorV2(UnifiedKeywordPairsExtractor):
def predict(self, sentence):
"""
This class redefines the predict method in order to avoid an output empty keywords set.
... |
#python3
import os
import sys
import statistics as s
import pandas as pd
from find_loss import *
##########################
## statistics on orthogroups
##########################
"""if len(sys.argv) != 5:
print("Need 4 arguments: [Orthologous group input file] [LECA orthologous groups input list] [method name] [stat... |
# Scripts to extract keywords
from src.utils import data_connector
from gensim.summarization import keywords
from multi_rake import Rake
from nltk.corpus import stopwords
from textblob_de import TextBlobDE as TextBlob
class KeyPhraseExtractor:
def __init__(self, model_name, num_of_phrases):
self.model_name... |
def bubble_sort(array):
array_length = len(array)
temp = 0
for i in range(array_length - 1):
for j in range(array_length - i - 1):
if array[j] > array[j + 1]:
temp = array[j + 1]
array[j + 1] = array[j]
array[j] = temp
return array
|
"""
NOTE this strengthing optimization is only used in the vecopt.
It needs also the information about integral modifications
gathered with IntegralForwardModification
"""
from rpython.jit.metainterp.optimizeopt.renamer import Renamer
from rpython.jit.metainterp.optimizeopt.dependency import (DependencyGraph,
... |
from django.contrib.auth.models import User
from django.db import models
class Notification(models.Model):
MESSAGE = 'message'
APPLICATION = 'application'
CHOICES = (
(MESSAGE, 'Message'),
(APPLICATION, 'Application')
)
to_user = models.ForeignKey(User, related_name='notifications... |
import numpy as np
from aip import AipBodyAnalysis
import cv2
import base64
""" 你的 APPID AK SK """
APP_ID = '17363443'
API_KEY = 'cxAUPSbo7xCQlGIGsYDhSZ6C'
SECRET_KEY = 'XzaYnnD8qrf9cYwEWF4SdXvENiqNlUxk'
client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY)
""" 读取图片 """
def get_file_content(filePath):
with open(f... |
from flask_restplus import Resource
from werkzeug.exceptions import BadRequest, NotFound
from app.api.mines.status.models.mine_status_xref import MineStatusXref
from app.extensions import api
from app.api.utils.access_decorators import requires_role_view_all
from app.api.utils.resources_mixins import UserMixin
from ap... |
from .gaussian_target import gaussian_radius, draw_umich_gaussian
__all__ = ['gaussian_radius', 'draw_umich_gaussian'] |
"""Transforms for UNet.
Many methods are taken from https://www.kaggle.com/c/tgs-salt-identification-challenge/discussion/63974.
"""
__author__ = 'Erdene-Ochir Tuguldur, Yuan Xu'
import cv2
import random
import numpy as np
class PrepareImageAndMask(object):
"""Prepare images and masks like fixing channel numb... |
# -*- coding: utf-8 -*-
from django.db import models
from django_extensions.db.models import TimeStampedModel
STATUS_CHOICES = {
(0, 'ENABLED'),
(1, 'DISABLED'),
}
class Plugin(TimeStampedModel):
name = models.CharField(max_length=128, unique=True)
pythonpath = models.CharField(max_length=128, uniqu... |
import random
class Ages:
def __init__(self, age=None):
if not age:
age = random.choice(range(0, 99))
self.age = age
def __str__(self):
return str(self.age)
def __add__(self, other):
self.age += other
@staticmethod
def func():
print("THIS IF F... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_files/widgets/inv_row.ui'
#
# Created by: PyQt5 UI code generator 5.7
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_InvRow(object):
def setupUi(self, InvRow):
In... |
import mock
import time
import redis
from pyramid import testing
from kinto.core.utils import sqlalchemy
from kinto.core.storage import exceptions
from kinto.core.cache import (CacheBase, postgresql as postgresql_backend,
redis as redis_backend, memory as memory_backend,
... |
# -*- coding: utf-8 -*-
"""This code is not a bit production-ready, just a pimped imitation of uWSGI server behavior
"""
import logging
import time
from multiprocessing import Process
from wsgiref.simple_server import make_server
from ws4py.websocket import WebSocket
from ws4py.server.wsgirefserver import WSGIServer, W... |
import json
import unittest
import threading
from argparse import ArgumentParser, Namespace
from http.client import responses
from http.server import HTTPServer
from typing import Dict, Tuple, Any
from urllib.error import HTTPError
from urllib.request import Request, urlopen
from converter.app import *
from converter.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.