content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 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.apach... | python |
from baseline.train import create_trainer, register_trainer, register_training_func, Trainer
from baseline.embeddings import register_embeddings
from baseline.reporting import register_reporting, ReportingHook
from baseline.tf.embeddings import TensorFlowEmbeddings
from baseline.tf.optz import optimizer
from baseline.c... | python |
"""Super class of contextual bandit algorithm agent class"""
import numpy as np
class ContextualBanditAlgorithm(object):
"""
Args:
n_features : 特徴量の次元数
Attributes:
iter_num(int) : 現在の反復回数
"""
def __init__(self, n_features:int):
self.n_features = n_features
self.ite... | python |
# Generated by Django 2.1.8 on 2019-08-08 23:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wagtailnhsukfrontendsettings', '0003_footersettings'),
]
operations = [
migrations.AddField(
model_name='footersettings',
... | python |
# --------------
# Import packages
import numpy as np
import pandas as pd
from scipy.stats import mode
# code starts here
bank = pd.read_csv(path)
categorical_var = bank.select_dtypes(include = 'object')
print(categorical_var)
numerical_var = bank.select_dtypes(include = 'number')
print(numerical_var)
# code e... | python |
# Copyright © 2018 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: BSD-2-Clause OR GPL-3.0-only
# !/usr/bin/python
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: vcd_vapp_netcommit
short_description: Ansibl... | python |
# Copyright 2018 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, ... | python |
import asyncio
import unittest
from unittest.mock import ANY
from aiobeanstalk.proto import Client
from aiobeanstalk.packets import Using, Inserted
def btalk_test(fun):
fun = asyncio.coroutine(fun)
def wrapper(self):
@asyncio.coroutine
def full_test():
cli = yield from Client.c... | python |
import os.path
charmap = []
charmapDescription = []
if os.path.isfile('charmap.mif'):
charmapFile = open('charmap.mif', 'r+')
lines = charmapFile.readlines()
cont = 0
character = []
for line in lines:
if line[0] == " ":
newLine = line[-10:-2]
if cont % 8 == 0 and cont... | python |
'''
Copyright 2017, Fujitsu Network Communications, 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 w... | python |
from flask import Blueprint, request, jsonify
from werkzeug import check_password_hash
from flask.ext.login import login_user, logout_user
from app.core import db
from app.api_decorators import requires_login, requires_keys
from app.models.user import User
blueprint = Blueprint('api_slash', __name__, url_prefix='/api'... | python |
# Copyright (c) 2019, NVIDIA CORPORATION. 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... | python |
# Copyright 2019 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
class FaceSearchUserInfo(object):
def __init__(self):
self._customuserid = None
self._merchantid = None
self._merchantuid = None
self._score = None
@p... | python |
import torch
import torch.nn as nn
class SLAF(nn.Module):
def __init__(self, k=2):
super().__init__()
self.k = k
self.coeff = nn.ParameterList(
[nn.Parameter(torch.tensor(1.0)) for i in range(k)])
def forward(self, x):
out = sum([self.coeff[k] * torch.pow(x, k) for... | python |
#from keras.models import Sequential, Model
#from keras.layers import Dense, Dropout, Flatten, Input
#from keras.layers import Conv2D, MaxPooling2D, Reshape, Concatenate
from keras.optimizers import Adam
#import tensorflow as tf
import numpy as np
import sys
import os
import cv2
import keras.backend as K
imp... | python |
import torch
import torchvision
def get_loader(root='.', batch_size=512):
transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
train_dataset = torchvision.datasets.CIFAR10(root, train=True,
... | python |
# -*- coding: utf-8 -*-
from guillotina.factory import serialize # noqa
from guillotina.factory.app import make_app # noqa
from guillotina.factory.content import ApplicationRoot # noqa
from guillotina.factory.content import Database # noqa
from guillotina.factory import security # noqa
| python |
import typing
from kubernetes import client
from kubernetes import config
from kubernetes.client.rest import ApiException
from kuber import definitions
from kuber import versioning
def load_access_config(in_cluster: bool = False, **kwargs):
"""
Initializes the kubernetes library from either a kube configura... | python |
# coding: utf-8
from abc import ABCMeta
from config.config_loader import logger
from mall_spider.spiders.actions.action import Action
from mall_spider.spiders.actions.context import Context
class DefaultAction(Action):
__metaclass__ = ABCMeta
def on_error(self, context, exp):
task = context.get(Cont... | python |
import pygame
from Player import PlayerBase
class Player2():
def __init__(self, image, speed = [0,0], pos = [0,0]):
self.image = pygame.image.load(image)
| python |
import theano.tensor as T
class Regularizer(object):
def __call__(self, **kwargs):
raise NotImplementedError
class L2Regularizer(Regularizer):
def __call__(self, alpha, params):
return alpha * l2_sqr(params) / 2.
def l2_sqr(params):
sqr = 0.0
for p in params:
sqr += T.sum((... | python |
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring
from __future__ import absolute_import, unicode_literals
# 3rd party imports
import pytest
from six import string_types
# project imports
from restible.url_params import from_string
@pytest.mark.parametrize('value,expected_type', (
('123', int),
('... | python |
from frangiclave.bot.templates.base import make_section, DIVIDER, URL_FORMAT
from frangiclave.compendium.deck import Deck
def make_deck(deck: Deck):
draw_messages = '\n'.join(f'• <https://www.frangiclave.net/element/{dm.element.element_id}/|{dm.element.element_id}>: {dm.message}' for dm in deck.draw_messages)
... | python |
import collections
import logging
import re
import socket
import subprocess
def json_update(d, u):
for k, v in u.items():
if isinstance(v, collections.abc.Mapping):
d[k] = json_update(d.get(k, {}), v)
else:
d[k] = v
return d
def remove_dict_null(d: dict):
"""Remov... | python |
# -*- coding: utf-8 -*-
import re
import scrapy
from locations.items import GeojsonPointItem
class GuzmanyGomezSpider(scrapy.Spider):
name = "guzmany_gomez"
item_attributes = {"brand": "Guzman Y Gomez"}
allowed_domains = ["guzmanygomez.com.au"]
start_urls = [
"https://www.guzmanygomez.com.au... | python |
import os
import lab_test
def mean(list_a):
return sum(list_a) / len(list_a)
def create_md_file(path, bpp_mine, psnr_mine, ssim_mine, bpp_jpg, psnr_jpg, ssim_jpg):
os.system('mkdir -p {}'.format(path))
file_p = os.path.join(path,'res.md')
mdfile = open(file_p, 'w')
res = []
res.append('MyMode... | python |
#! /usr/bin/env python
#coding: utf-8
######################################################################################
#Script for download and convert to fastq SRA datasets serially. #
#Authors: David Peris UW-Madison, Dept Genetics #
#Usage: python downl... | python |
#==========================================================================
#
# Copyright Insight Software Consortium
#
# 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
#
# ... | python |
from typing import Callable
def test_hello_default(hello: Callable[..., str]) -> None:
assert hello() == "Hello !"
def test_hello_name(hello: Callable[..., str], name: str) -> None:
assert hello(name) == "Hello {0}!".format(name)
| python |
# -*- coding: utf-8 -*-
"""
equip.analysis.python
~~~~~~~~~~~~~~~~~~~~~
Python related information for analysis.
:copyright: (c) 2014 by Romain Gaucher (@rgaucher)
:license: Apache 2, see LICENSE for more details.
"""
| python |
""" XVM (c) www.modxvm.com 2013-2017 """
#####################################################################
# MOD INFO
XFW_MOD_INFO = {
# mandatory
'VERSION': '0.9.19.0.1',
'URL': 'http://www.modxvm.com/',
'UPDATE_URL': 'http://www.modxvm.com/en/download-xvm/',
'GAME_VERSION... | python |
import numpy as np
import pandas as pd
import pytest
from dku_timeseries import WindowAggregator
from recipe_config_loading import get_windowing_params
@pytest.fixture
def columns():
class COLUMNS:
date = "Date"
category = "country"
aggregation = "value1_avg"
return COLUMNS
@pytest.f... | python |
#!/usr/bin/env python
import pyinotify
import os, sys
import logging
import json
import thread, threading
import time, datetime
import hashlib
import mimetypes
import traceback
# google stuff
from ServiceProviders.Google import GoogleServiceProvider
from apiclient.http import BatchHttpRequest
from apiclient import err... | python |
# CS4120 NLP, Northeastern University 2020
import spacy
from tqdm import tqdm
from spacy.analysis import Token, Doc, Span
from data_management import output_filepath, input_filepath
def main():
nlp = spacy.load("en_core_web_sm")
docs = []
with open(input_filepath("samplesentences.txt")) as f:
f... | python |
# -*- coding: utf-8 -*-
"""Tests for CommandChainDispatcher."""
from __future__ import absolute_import
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import nose.tools as nt
from IPython.core.erro... | python |
from datetime import date
import uuid
from typing import Optional, List
from pydantic import BaseModel, Field
def generate_invoice_id():
return str(uuid.uuid4())
class InvoiceInfo(BaseModel):
invoice_id: str = Field(default_factory=generate_invoice_id)
issuer_name: str
issuer_address: Optional[str]... | python |
# Generated by Django 3.0.7 on 2020-07-17 15:52
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('judge', '0010_auto_20200717_1735'),
]
operations = [
migrations.AlterField(
model_name='problem',
... | python |
import sys
import numpy as np
import matplotlib.pyplot as plt
# Load data
#bf = np.loadtxt('data/times/brute_force.txt')
#cp = np.loadtxt('data/times/closest_pair.txt')
bf = np.loadtxt(sys.argv[1])
cp = np.loadtxt(sys.argv[2])
# Reshape data
bf = bf.reshape(6, len(bf) // 6)
cp = cp.reshape(6, len(cp) // 6)
# Average... | python |
from core.testing import APITestCase
class TestAPITestCase(APITestCase):
def test_tests(self):
self.assertTrue(hasattr(self, 'pytestmark'))
self.assertTrue(hasattr(self, 'mixer'))
| python |
# NOT FINISHED, barely started
import copy
import time
import random
import math
from typing import List
import jax.numpy as np
from pomdp_py.framework.basics import Action, Agent, POMDP, State, Observation,\
ObservationModel, TransitionModel, GenerativeDistribution, PolicyModel
from pomdp_py.framework.planner ... | python |
# Generated by Django 3.2.3 on 2021-11-11 14:04
from django.db import migrations, models
import django.db.models.deletion
def copy_funding_instruments_from_calls_to_projects(apps, schema_editor):
Project = apps.get_model('project_core', 'Project')
for project in Project.objects.all():
project.fundin... | python |
import json
import argparse
def contains(splits):
# Returns 1D binary map of images to take such that access is O(1)
MAX, MIN = max([int(x.split('-')[-1]) for x in splits]), min([int(x.split('-')[0]) for x in splits])
A = [0 for _ in range(MAX-MIN+1)]
for sp in splits:
if '-' in sp:
beg... | python |
from sklearn.base import BaseEstimator
import numpy as np
from sklearn.base import clone
from .logs.loggers import get_logger
import math
class DeepModel(BaseEstimator):
def __init__(self, estimator, depths, n_estimators=100,
learning_rate=0.01, verbose=True, logging=None, logging_params={}):
... | python |
################################################################################
# COPYRIGHT(c) 2018 STMicroelectronics #
# #
# Redistribution and use in source and binary forms, with or without ... | python |
from django.core.mail import send_mail
from django.shortcuts import render,redirect,reverse
from django.http import HttpResponse
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import generic
from .models import AgentModel, LeadModel,CategoryModel
from .forms import (
Lea... | python |
# Copyright 2016 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
#
# Unless required by... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import logging
logger = logging.getLogger(__name__)
class RestartHandler:
def __init__(self, observer, command):
self.observer = observer
self.command = command
def run(self):
logger.info("Running restart handler")
... | python |
# 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
from... | python |
import numpy as np
from scipy.constants import mu_0
# TODO: make this to take a vector rather than a single frequency
def rTEfunfwd(nlay, f, lamda, sig, chi, depth, HalfSwitch):
"""
Compute reflection coefficients for Transverse Electric (TE) mode.
Only one for loop for multiple layers. Do not use... | python |
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseForbidden
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView
from rest_framework.renderers import JSONRenderer
from rest_framework... | python |
import cv2 as cv
import numpy as np
import math
import time
beg=time.time()
def readimg (xmin,xmax,ymin,ymax):
ymins=ymin
n=(xmax-xmin+1)*(ymax-ymin+1)*21.25
target=0
while xmin<xmax :
while ymin<ymax :
target = target+img[xmin,ymin]
ymin += 1
xmin +=... | python |
#!/usr/local/bin/python
import ogr, osr
import datetime
print "Start: ", datetime.datetime.now()
for i in range(10000):
pointX = -84
pointY = 38
inputESPG = 4267
outputEPSG = 2246
point = ogr.Geometry(ogr.wkbPoint)
point.AddPoint(pointX, pointY)
inSpatialRef = osr.SpatialReference()
... | python |
#!/usr/local/bin/python3
from MPL3115A2 import MPL3115A2
from si7021 import Si7021
from pms5003 import PMS5003
from smbus import SMBus
import influxdb_client
from influxdb_client import InfluxDBClient
import time
import logging
hostname="indoors"
logging.basicConfig(level=logging.DEBUG)
mpl = MPL3115A2(1, fetchPr... | python |
#! /usr/bin/env python
#coding=utf8
import os
import sys
if __name__ == '__main__':
if len(sys.argv) < 2:
print 'USAGE: commit message'
sys.exit()
commit_msg = sys.argv[1]
os.system('git pull origin master')
os.system('git status')
os.system('git add ./')
os.system('git commit ... | python |
#!/usr/bin/env python
from csv import DictReader
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from wordcloud import WordCloud
from snli_cooccur import mkdirp_parent
DEFAULT_COLOR_NAME = '#1f497d'
DEFAULT_RELATIVE_SCALING = 1.
DEFAULT_WIDTH = 800
DEFAULT_HEIGHT = 400
DEFAULT_MAX_WORDS =... | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import os
from unittest import TestCase
from flaky import flaky
from polyaxon_schemas.ops.build_job import BuildConfig
from polyaxon_schemas.ops.environments.pods import EnvironmentConfig
from polyaxon_schemas.ops.environments.... | python |
#!/usr/bin/env python
from typing import NamedTuple
from hummingbot.market.market_base import MarketBase
class ArbitrageMarketPair(NamedTuple):
"""
Specifies a pair of markets for arbitrage
"""
market_1: MarketBase
market_1_trading_pair: str
market_1_base_asset: str
market_1_quote_asset:... | python |
param_names = [\
'Kon_IL13Rec',
'Rec_phosphorylation',
'pRec_intern',
'pRec_degradation',
'Rec_intern',
'Rec_recycle',
'JAK2_phosphorylation',
'pJAK2_dephosphorylation',
'STAT5_phosphorylation',
'pSTAT5_dephosphorylation',
'SOCS3mRNA_production',
'DecoyR_binding',
'J... | python |
import datetime
import genshin
async def test_diary(lclient: genshin.Client, genshin_uid: int):
diary = await lclient.get_diary()
assert diary.uid == genshin_uid == lclient.uids[genshin.Game.GENSHIN]
assert diary.nickname == "sadru"
assert diary.month == datetime.datetime.now().month
assert diary... | python |
"""
A :class:`~miso.data.dataset_readers.dataset_reader.DatasetReader`
reads a file and converts it to a collection of
:class:`~miso.data.instance.Instance` s.
The various subclasses know how to read specific filetypes
and produce datasets in the formats required by specific models.
"""
# pylint: disable=line-too-long... | python |
import numpy as np
from napari.components import Camera
def test_camera():
"""Test camera."""
camera = Camera()
assert camera.center == (0, 0, 0)
assert camera.zoom == 1
assert camera.angles == (0, 0, 90)
center = (10, 20, 30)
camera.center = center
assert camera.center == center
... | python |
class APIError(Exception):
"""
Simple error handling
"""
codes = {
204: 'No Results',
400: 'Bad Request',
401: 'Unauthorized',
402: 'Unauthorized (Payment Required)',
403: 'Forbidden',
404: 'Not Found',
413: 'Too Much Data Given',
429: 'To... | python |
ta=[1,2,3]
tb=[9,8,7]
# cluster
zipped=zip(ta,tb)
print('zip(ta,tb)=',zip(ta,tb))
#decompose
na,nb=zip(*zipped)
print(na,nb)
| python |
import os, logging, math
import numpy as np
import torch
import torch.nn as nn
from volsim.base_models import *
from volsim.simulation_dataset import *
from volsim.params import *
class DistanceModel(nn.Module):
def __init__(self, modelParams:Params, useGPU:bool=True):
super(DistanceModel, self).__init_... | python |
"""Add hostname column to the resources table
Revision ID: 58a12e45663e
Revises: 06ce06e9bb85
Create Date: 2020-10-20 18:24:40.267394
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '58a12e45663e'
down_revision = '06ce06e9bb85'
branch_labels = None
depends_on =... | python |
from cantoolz.module import *
from cantoolz.uds import *
import json
class control_ecu_doors(CANModule):
name = "Doors trigger for vircar"
help = """
This module emulating lock control.
Init params (example):
{
'id_report': {0x91:'Left', 0x92:'Right'},
'id_command': 0x81,
... | python |
# Under MIT licence, see LICENCE.txt
import random
from typing import List
from Util import Pose, Position
from Util.ai_command import MoveTo
from Util.constant import BALL_RADIUS, ROBOT_RADIUS, POSITION_DEADZONE, ANGLE_TO_HALT
from Util.geometry import compare_angle
from ai.GameDomainObjects.player import Player
from... | python |
import factory
import json
from django.test import TestCase, Client
from django.urls import reverse
from django.test import RequestFactory
from django.contrib.auth.models import AnonymousUser
from movies.models import Movie
from movies.views import home
from movies.forms import SearchMovieForm
from movie_database.use... | python |
import spatialfacet
import numpy as np
from matplotlib import pyplot as plt
from shapely.geometry import Polygon, Point
U = Polygon([[-1,-1],
[-1,1],
[0,1],
[0,-1],
[-1,-1]])
V = Polygon([[0,-1],
[0,1],
[1,1],
[1,-1],
... | python |
import numpy
def diff(features1, features2):
pixelMap1 = numpy.asarray(features1)
pixelMap2 = numpy.asarray(features2)
return numpy.linalg.norm(pixelMap1-pixelMap2)
def highOrSober(soberFeatures, highFeatures, queryFeatures):
if(diff(soberFeatures, queryFeatures) < diff(highFeatures, queryFeatures)):
... | python |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'A tiny Python/C library for loading MIAS images from file.',
'author': 'Samuel Jackson',
'url': 'http://github.com/samueljackson92/mias-loader',
'download_url': 'http://github.com/s... | python |
from PIL import Image
import gym
import gym_pacman
import time
env = gym.make('BerkeleyPacmanPO-v0')
env.seed(1)
done = False
while True:
done = False
env.reset()
i = 0
while i < 100:
i += 1
s_, r, done, info = env.step(env.action_space.sample())
env.render()
print("It... | python |
from asyncio import sleep
from requests import get
from main import bot, reg_handler, des_handler, par_handler
async def diss(message, args, origin_text):
await message.edit("获取中 . . .")
status = False
for _ in range(20):
req = get("https://nmsl.shadiao.app/api.php?level=min&from=tntcrafthim")
... | python |
# Generated by Django 2.1 on 2018-10-03 01:54
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('unlabel_backend', '0021_auto_20180625_1904'),
]
operations = [
migrations.DeleteModel(
name='Article',
),
migrations.Delet... | python |
#!/usr/bin/env python
# vim:set ts=2 sw=2 expandtab:
#
# the pre.py script permits the reconstruction to specify the server, user
# name, and password used for connection. This is achieved by setting
# the parameters in a dictionary named jobArgs.
#
# Optional output variable : jobArgs
#
# Default dictionary; only thos... | python |
class Solution(object):
def findLongestWord(self, s, d):
"""
:type s: str
:type d: List[str]
:rtype: str
"""
newD = sorted(d, key=len, reverse=True)
tempList = []
for word in newD:
if len(tempList) != 0 and len(word) != len(tempList[-1]):
... | python |
"""
@author: Andrea Domenico Giuliano
@contact: andreadomenico.giuliano@studenti.unipd.it
@organization: University of Padua
"""
import datetime
import math
from collections import defaultdict
#File contenente le funzioni riguardanti la creazione dei dict rigurandanti i gruppi degli items e degli users
... | python |
import logging
import os
import shutil
import numpy as np
import torch
from pytorch_metric_learning.utils import common_functions as pml_cf
from sklearn.model_selection import train_test_split
from torchmetrics.functional import accuracy as tmf_accuracy
from ..adapters import Finetuner
from ..containers import Models... | python |
#!/usr/bin/env python
# $Id$
""" Abstract base class for driver classes"""
import exceptions
class DriverError(exceptions.Exception):
def __init__(self, arg):
exceptions.Exception.__init__(self,arg)
class Driver:
mount_delay = 0
def fileno(self):
raise NotImplementedError
de... | python |
#
# Copyright (c) 2015-2016 Erik Derr [derr@cs.uni-saarland.de]
#
# 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... | python |
def train_interupter():
with open('train_interupter.ini', 'r', encoding='utf-8') as f:
flag = f.read().strip()
if flag == '0':
return False
elif flag == '1':
with open('train_interupter.ini', 'w', encoding='utf-8') as f:
f.write('0')
return True
else:
... | python |
# The MIT License (MIT)
# Copyright (c) 2021 Jonah Yolles-Murphy (TG-Techie)
# 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
# t... | python |
import argparse
import logging
from sqlalchemy.orm import Session
from ...db import yield_connection_from_env_ctx
from ..indices import update_installation_default_indices
from ..models import SlackOAuthEvent
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def upgrade_one(
db_sess... | python |
from extractors.blockextractor import BlockExtractor
from extractors.characterfactory import CharacterFactory
from extractors.emojiextractor import EmojiExtractor
from extractors.mathcollectionextractor import MathExtractor
from extractors.nerdextractor import NerdExtractor
if __name__ == "__main__":
character_fac... | python |
"""AnimeSuki Media models"""
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.utils.text import slugify
from animesuki.core.models import ArtworkModel
from animesuki.core.utils import DatePrecision
from animesuki.history.models import HistoryModel
class Medi... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2019-06-12 07:41
from __future__ import unicode_literals
import bluebottle.files.fields
import bluebottle.utils.fields
from decimal import Decimal
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import d... | python |
from __future__ import annotations
import subprocess
import sys
def test_same_version():
""" Test the the version in setup.py matches the version in __init__.py """
res = subprocess.run(
[sys.executable, '-m', 'pip', 'show', 'cptk'],
stdout=subprocess.PIPE,
check=True,
encodi... | python |
# coding=utf-8 ##以utf-8编码储存中文字符
import jieba.analyse
import codecs,sys
import itertools
from work import match
from io import BufferedReader
from work import simplyParticiple
def Synonym(): #同义词函数
seperate_word = {}
dict1={}
i=0
file = codecs.open("same_word.txt","r","utf-8") # 这是同义词库
lines = fi... | python |
from .common import (
AskHandler,
CommonHandler,
AskCommutativeHandler,
TautologicalHandler,
test_closed_group,
)
__all__ = [
"AskHandler",
"CommonHandler",
"AskCommutativeHandler",
"TautologicalHandler",
"test_closed_group",
]
| python |
from matching_algorithm import matching_algorithm
import json
import copy
class top_trading_cycle(matching_algorithm):
def group_1_optimal(self):
return self.match(copy.deepcopy(self.group_1), copy.deepcopy(self.group_2), 'top_trading_cycle', False)
def group_2_optimal(self):
return self.matc... | python |
from setuptools import find_packages, setup
setup(
name="Skaak",
packages=find_packages(include=["skaak"]),
version="0.12.5",
description="A Python Chess Library",
author="George Munyoro",
license="MIT",
install_requires=[],
setup_requires=["pytest-runner"],
tests_require=["pytest==... | python |
"""
Ticket numbers usually consist of an even number of digits. A ticket number is considered lucky if the sum of the first
half of the digits is equal to the sum of the second half.
Given a ticket number n, determine if it's lucky or not.
Example
For n = 1230, the output should be
solution(n) = true;
Fo... | python |
import graphene
from ipam import filtersets, models
from netbox.graphql.scalars import BigInt
from netbox.graphql.types import BaseObjectType, OrganizationalObjectType, PrimaryObjectType
__all__ = (
'ASNType',
'AggregateType',
'FHRPGroupType',
'FHRPGroupAssignmentType',
'IPAddressType',
'IPRan... | python |
from utils import *
import matplotlib.pyplot as plt
# import matplotlib.colors
from sklearn.preprocessing import StandardScaler
from skimage.transform import resize
from PIL import Image
path_save = "./results/face_glasses_separation2/"
if not os.path.exists(path_save):
os.makedirs(path_save)
# color_map = mat... | python |
from flask_apscheduler import APScheduler
from actions import *
from context import *
from config import Config
class Executor:
"""
An Executor drives a pipeline which composed by a sequence of actions with a context
"""
def __init__(self, config: Config, pipeline_name, pipeline):
self.co... | python |
#!/usr/bin/env python
import os
try:
import cplex
except ImportError:
cplex = None
import numpy as np
from mapel.voting.metrics.inner_distances import hamming
# FOR SUBELECTIONS
def solve_lp_voter_subelection(election_1, election_2, metric_name='0'):
""" LP solver for voter subelection problem """
... | python |
# -*- coding: utf-8 -*-
# Author : Jesse Wei
# LastUpdate : 2020/10/04
# Impact : Jobs generated by SQLG
# Message : Humanity towards others, we live by sharing. Fear can hold you prisoner, only hope can set you free.
# from __future__ import print_function
import logging
import re
import airfl... | python |
from segmentTree import SumSegmentTree, MinSegmentTree
import numpy as np
import matplotlib.pyplot as plt
class RingBuffer(object):
def __init__(self, maxlen, shape, dtype='int32'):
self.maxlen = maxlen
self.data = np.zeros((maxlen,) + shape).astype(dtype)
self.next_idx = 0
def append(... | python |
from .plots import Plot,PlotError,PlotState
from .. import context
from .. import items
from .. import maps
from .. import randmaps
from .. import waypoints
from .. import monsters
from .. import dialogue
from .. import services
from .. import teams
from .. import characters
from .. import namegen
import random
from ..... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.