content stringlengths 5 1.05M |
|---|
# Generated by Django 3.1 on 2020-12-02 19:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('extras', '0052_customfield_cleanup'),
]
operations = [
migrations.RenameField(
model_name='webhook',
old_name='obj_type',
... |
from copy import deepcopy
from time import time
import numpy as np
from Agents.randomAgent import RandomInvestor
from LightningSimulator import LightningSimulator, transfer_money_in_graph
from utils.common import human_format
from utils.graph_helpers import create_sub_graph_by_node_capacity
from routing.LND_routing im... |
class FitError(Exception):
def __init__(self, message, line=0):
self.message = message
self.line = line
def __str__(self):
return "FitError: {}".format(self.message) + \
(" the line {}!".format(self.line) if self.line > 0 else "!")
class FitNotExist(Exception):
def __i... |
import threading
import pyttsx3
import queue
class TTSThread(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
self.daemon = True
self.start()
def run(self):
global tts_engine
tts_engine = pyttsx3.init()
tt... |
from exopy.tasks.api import (InstrumentTask)
class ResumeProgramTask(InstrumentTask):
""" Resumes a paused program.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def perform(self):
self.driver.resume()
|
#!python3
"""
Article name : Optimal Envy-Free Cake Cutting
Authors : Yuga J. Cohler, John K. Lai, David C. Parkes and Ariel D. Procaccia
Algorithm #1 : opt_piecewise_constant
Algorithm #2 : opt_piecewise_linear
Programmer: Tom Goldenberg
Since: 2020-05
"""
from fairpy import Allocation
from fairpy.agents import *
i... |
#/*
# * Copyright (c) 2019,2020 Xilinx Inc. All rights reserved.
# *
# * Author:
# * Bruce Ashfield <bruce.ashfield@xilinx.com>
# *
# * SPDX-License-Identifier: BSD-3-Clause
# */
import copy
import struct
import sys
import types
import unittest
import os
import getopt
import re
import subprocess
import shutil
fr... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
# %load imports_default.py
#!/usr/bin/env python
# In[ ]:
import numpy as np
import math
import random as rn
import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd
import json
get_ipython().run_line_magic('matplotlib', 'inline')
get_ipython().ru... |
# -*- coding: utf-8 -*-
"""
@date: 2020/8/22 下午4:20
@file: demo.py
@author: zj
@description:
"""
import cv2
import glob
import os
import time
import torch
import argparse
import numpy as np
from PIL import Image
from zcls.config import cfg
from zcls.config.key_word import KEY_OUTPUT
from rotnet.rotnet import rot... |
# Generated by Django 3.1.2 on 2020-10-15 03:49
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('survey', '0002_auto_20201010_0524'),
]
operations = [
migrations.RenameField(
model_name='survey',
old_name='survey_type_par... |
from decouple import config
import time
import json
from cross_traffic import run
conf = config("TASK_PARAMS")
def f(data):
return json.dumps(run(data))
with open("/file.txt", "w") as writer:
writer.write(f(json.loads(conf)))
|
# coding=utf-8
from __future__ import absolute_import, division, print_function
from astwro.exttools import Runner
class WCSUtilsRunner(Runner):
def __init__(self, translator=None):
# base implementation of __init__ calls `_reset` also
self.translator = translator
super(WCSUtilsRunner, self... |
"""
entradas
temperatura-->float-->a
Salidas
deporte-->str-->d
"""
a = float(input("Digite su temperatura :"))
if(a > 85):
print("Natacion")
elif(a > 71 and a <= 85):
print("Tenis")
elif(a > 32 and a <= 70):
print("Golf")
elif(a > 10 and a <= 32):
print("Esqui")
elif(a <= 10):
print("Marcha")
else:
print("N... |
from LaplaceWSAPIClient import *
from MLQueries import *
import pandas as pd
from io import StringIO
from ClientConfig import client_config
ut = UserTokenSerde(client_config["user"],client_config["token"])
target_column = "variety"
test = pd.read_csv('test.csv')
train = pd.read_csv('train.csv')
uri = client_config["ws... |
import sys
sys.path.append("..")
from connections import connections
from aux_functions import aux_functions
from datetime import datetime
import psycopg2
################################################################# INSERT FACT ACESSO #################################################################
def inse... |
from api.helper import is_me_query
from db.models import Student, ProfileState, ProfileType
def privacy_protection(match_only=False):
def decorator(func):
def wrapper(self: Student, info):
if is_me_query(info):
return func(self, info)
# check for possible matches... |
import os
import sys
sys.path.insert(0, os.path.abspath('../../'))
from moredata.utils.osm_downloader import OSM_util
import csv
import pandas as pd
if __name__ == "__main__":
osm = OSM_util()
place_id = osm.get_place_ID("Brasil")
print(place_id)
key = "tourism"
value = "museum"
query = """
... |
# internal
from src.translation import _
from src.ui.components import BaseDialog, SMButton, SMEdit, SaveSMButton, CancelSMButton
# pyqt
from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtWidgets import QHBoxLayout, QFormLayout, QLabel
class RegisterFormSignals(QObject):
"""Register Form Signals"""
sho... |
from pathlib import Path
import yaml
__all__ = (
'mask_match', 'msg_join', 'msg_split',
'userhost_split', 'validate_hostname',
)
DATA_DIR = Path(__file__).resolve().parent / 'data'
def load_data(name):
with (DATA_DIR / '{}.yaml'.format(name)).open(encoding='utf-8') as f:
data = yaml.safe_load(f... |
"""
Exception handler hook for RQ (http://python-rq.org/)
How to use:
1. Instead of using the default "rqworker" script to run the worker, write your own short script
as shown in this example:
https://github.com/nvie/rq/blob/master/examples/run_worker.py
2. In this script, initialize rollbar with `handler='blockin... |
"""
@author: Viet Nguyen <nhviet1009@gmail.com>
"""
import argparse
import cv2
import numpy as np
def get_args():
parser = argparse.ArgumentParser("Image to ASCII")
parser.add_argument("--input", type=str, default="data/input.jpg", help="Path to input image")
parser.add_argument("--output", type=str, def... |
"""
For example, consider just the first seven characters of FBFBBFFRLR:
Start by considering the whole range, rows 0 through 127.
F means to take the lower half, keeping rows 0 through 63.
B means to take the upper half, keeping rows 32 through 63.
F means to take the lower half, keeping rows 32 through 47.
B means to... |
import os
import time
import requests
import telebot
from dotenv import load_dotenv
load_dotenv()
TELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN')
OPENWEATHER_TOKEN = os.getenv('OPENWEATHER_TOKEN')
bot = telebot.TeleBot(TELEGRAM_TOKEN)
@bot.message_handler(commands=['start'])
def start(message):
username = messa... |
#!/usr/bin/env python
#
# Copyright 2017 the original author or authors.
#
# 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 require... |
import mock
import pytest
from framework.auth import Auth
from osf.models import RegistrationSchema, Registration
from osf_tests.factories import (
AuthUserFactory,
ProjectFactory,
RegionFactory
)
@pytest.mark.django_db
class TestRegion:
@pytest.fixture()
def user(self):
return AuthUser... |
from sardana.tango.macroserver import main
if __name__ == "__main__":
main()
|
# https://app.codesignal.com/challenge/Cg7JueyPBNPfycb7x
def find_value(string, i, end, k):
if k < 0:
return False
if i == end:
return True
while string[i] == string[end]:
i += 1
end -= 1
if abs(end - i) <= 1:
return True
if find_value(string,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Define the *Z order* of drawn objects
See http://matplotlib.org/examples/pylab_examples/zorder_demo.html
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.lines as mlines
# Plot data #################
fi... |
from copy import copy, deepcopy
import pytest
from returns.maybe import Nothing, Some, _Nothing
from returns.primitives.exceptions import ImmutableStateError
from returns.primitives.interfaces import (
Bindable,
Instanceable,
Mappable,
Unwrapable,
)
@pytest.mark.parametrize('container', [
Nothin... |
import numpy as np
import rospy
import gym # https://github.com/openai/gym/blob/master/gym/core.py
from gym.utils import seeding
from .gazebo_connection import GazeboConnection
class GymGazeboEnv(gym.Env):
def __init__(self, start_init_physics_parameters=True, reset_world_or_sim="WORLD"):
# To reset Simulations... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import SimpleTestCase, TestCase
from social_hashtags.api import (
parse_hashtags_from_text, parse_hashtags
)
from social_hashtags.tests.models import Post
from social_hashtags.settings import TAGS_MANAGER_NAME
text_with_hashtags = ... |
## A standard exception to indicate a type error in a function call.
class IntTypeError(Exception):
def __init__(self, desc):
self.desc = desc
def __str__(self):
return self.desc
## A standard Descriptor class to simplify and encapsulate class attributes.
class Descriptor(object):
def __init__(self, get_func,... |
import pandas as pd
import os
from dateutil import parser
def get_match_history(gr_df, date, team1, team2):
previous_games = gr_df[(((gr_df['home'] == team1) | (gr_df['home'] == team2)) & ((gr_df['away'] == team1) | (gr_df['away'] == team2))) & (gr_df['date'] < date)]
team1_wins = 0
team1_win_differential... |
import os
from libqtile import widget
def test_thermal_zone_getting_value():
# Create temporary zone file
tmp = "/var/tmp/qtile/test/widgets/thermal_zone"
zone_file = tmp + "/sys/class/thermal/thermal_zone0/temp"
os.makedirs(os.path.dirname(zone_file), exist_ok=True)
class FakeLayout:
pa... |
###################################################################################################
# Copyright © 2021 Neal Meswania
# Lisence: MIT
###################################################################################################
import json
import logging
import queue
from jsonschema import validat... |
from django.db import models
from rest_framework import authentication, permissions, filters
class ManagerMainMixin(models.Manager):
def get_queryset(self):
return super(ManagerMainMixin, self).get_queryset().filter(deleted_at__isnull=True)
class TimeStampedMixin(models.Model):
created_at = models.D... |
"""
Tests for BASIL module
FIXME need more multi-step tests
FIXME need to test more error conditions
"""
import pytest
import numpy as np
from fsl.data.image import Image
from oxasl import AslImage, Workspace
import oxasl.basil as basil
pytest.skip("skipping basil tests as neeed rewrite", allow_module_level=True)
... |
from django.contrib.auth.models import User
from django.db import models
import binascii
import os
class Media(models.Model):
name = models.CharField(
max_length=10,
verbose_name='이름'
)
rss_list = models.TextField(
verbose_name='RSS 리스트'
)
political_view = models.FloatField... |
import ustruct
from eoslib import *
import db
g_scope = N('cache')
g_code = N('cache')
payer = N('cache')
class CList(object):
def __init__(self,table_id):
self._list = []
self._dirty_keys = {}
self.table_id = N('list'+str(table_id))
def load(self):
itr = db.end_i64(g_code, g_... |
#!/usr/bin/env python3
import shutil
import os
os.chdir('/home/student/2022-01-04-Python/')
shutil.move('raynor.obj', 'Lab_21/')
xname = input('What is the new name for kerrigan.obj? ')
shutil.move('Lab_21/kerrigan.obj', 'Lab_21/' + xname)
|
import sys
import os
import time
from sklearn import metrics
import numpy as np
import pickle
from ensemble import Stacking
import warnings
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from xgboost i... |
from django.contrib import admin
from authority_list.models import OrganisationForm
class OrganisationFormAdmin(admin.ModelAdmin):
pass
admin.site.register(OrganisationForm, OrganisationFormAdmin)
|
import time
from sqlalchemy import String, Integer, Column, Text, UnicodeText, Unicode
from models.base_model import SQLMixin, db
from models.user import User
from models.reply import Reply
class Topic(SQLMixin, db.Model):
views = Column(Integer, nullable=False, default=0)
title = Column(Unicode(50), nullab... |
import twitter
import speedtest
text_file = input("Put the name of your text file here")
codes = open(text_file, "r")
ACCESS_TOKEN = codes.readline().rstrip()
ACCESS_SECRET = codes.readline().rstrip()
KEY = codes.readline().rstrip()
KEY_SECRET = codes.readline().rstrip()
UPLOAD_SPEED = float(codes.readline(... |
#!/usr/bin/python3
from pyrob.api import *
@task(delay=0.05)
def task_6_6():
i = 0
while (not wall_is_on_the_right()):
move_right()
i += 1
while (not wall_is_above()):
move_up()
fill_cell()
while (not wall_is_beneath()):
move_down()
move... |
import sys
import urllib
import color
from color import *
def sql():
fullurl = input(''+T+'' + color.UNDERLINE + 'Full URL> ' + color.END)
errormsg = "You have an error in your SQL syntax"
payloads = ["'admin'or 1=1 or ''='", "'=1\' or \'1\' = \'1\'", "'or 1=1", "'1 'or' 1 '=' 1", "'or 1=1#", "'0 '... |
def isPalindrome(n):
reverse = 0
reminder = 0
while(n != 0):
remainder = n % 10
reverse = reverse * 10 + remainder
n = int(n / 10)
return reverse
num = int(input('Enter The Number'))
reverse = isPalindrome(num)
if(num == reverse):
print(num,'is a Palindrome')
else... |
from .formats import ssh_certificate_formats, ssh_pubkey_formats
from .cert import SSHCertificate
from .pubkey import SSHPublicKeyFile
from .request import SSHCSR
|
import torch
from collections.abc import Iterable
def _get_layers(model, all_layers=None, all_names=None, top_name=None, fn=None, sep='_'):
"""Auxiliar function. Recursive method for getting all in the model for which `fn(layer)=True`."""
if all_names is None:
all_names = []
if all_layers is None:... |
import numpy as np
import tensorflow as tf
import gpflow
import tensorflow_probability as tfp
from src.models.initialization import *
from src.models.base_kernel import BaseKernel
class ARD(BaseKernel, gpflow.kernels.Kernel):
"""
Own implementation of the squared exponential kernel with ard
property... |
# -*- coding: utf-8 -*-
# pylint: disable=invalid-name
""" Test/example for the BindingEnergyWorkChain"""
import os
import click
import ase.io
from aiida.engine import run
from aiida.orm import Code, Dict, StructureData, Str
from aiida.plugins import WorkflowFactory
BindingEnergyWorkChain = WorkflowFactory('lsmo.cp2... |
import unittest
from rankum.models import Doc
from rankum.exceptions import MissingDocIdException, EmptyDocListException
from rankum import JsonDocReader
class JsonDocReaderTest(unittest.TestCase):
def test_should_json_list(self):
input_json = '[{"id": 1, "category": 1}, {"id": "2", "category": 2}]'
... |
# Create a program that reads the name and two notes of several students and stores everything in a compound list.
# At the end, show a bulletin containing the average of each one and allow the user to show the grades of each student
# individually.
sheet = list()
while True:
name = str(input('Name: '))
note1 ... |
# -*- coding: utf-8 -*-
# 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... |
fname = input("Enter file name: ")
if len(fname) < 1 :
fname = "mbox-short.txt"
fh = open(fname)
counts = dict()
for line in fh:
line = line.rstrip()
lst = line.split()
if len(lst)>1 and lst[0] == "From":
counts[lst[1]] = counts.get(lst[1],0)+1
bigWord = None
bigCount = None
for word, count in c... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-22 08:59
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
... |
import import_watch._cyclic_import_package.b # noqa: F401
|
# TASK:
# Вхідні дані: рядок, що складається з відкриваючих та закриваючих круглих дужок -
# аргумент командного рядка. Для передачі в якості рядка послідовність береться в подвійні
# лапки.
# Результат роботи: рядок "YES", якщо вхідний рядок містить правильну дужкову
# послідовність; або рядок "NO", якщо послідовність... |
import re
import toml
def toml_break_line(line):
m = re.match(r"^other = \"(.+?)\"$", line)
if not m:
return [line]
splits = m.group(1).replace(r"\n", "\n").splitlines()
if len(splits) == 1:
return [line]
lines = []
lines.append('other = """' + splits[0])
lines.extend(spl... |
import cv2
lena = cv2.imread(r"..\lena.jpg")
rgb = cv2.cvtColor(lena, cv2.COLOR_BGR2RGB)
cv2.imshow("lena", lena)
cv2.imshow("rgb", rgb)
cv2.waitKey()
cv2.destroyAllWindows()
|
import logging
import subprocess
import sys
import time
from tempfile import TemporaryDirectory
from typing import Dict, List
import requests
from common.models import BoundingBox as BoundingBoxModel
from common.models import setup_database_connections
from common.types import (BoundingBox, CitationData, CitationLocat... |
import math
from typing import Any, Callable, Dict, List, Optional, TYPE_CHECKING, Tuple, Union, cast
from cache import volatile_cache
from constants import SQUAD_DISMANTLE_RANGED, rmem_key_dismantler_squad_opts, role_squad_dismantle, role_squad_heal, \
role_squad_ranged
from creeps.roles.squads import SquadDrone
... |
"""
Copyright 2020 The OneFlow 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 applicable law or agr... |
from __future__ import annotations
from datetime import datetime
class Issue:
cursor: str
closed: bool
participantTotalCount: str
def __init__(self, data: dict) -> None:
self.cursor = data.get('cursor')
self.closed = data['closed']
self.participantTotalCount = data.get('total... |
##################
##Script for the AI Financial Forecaster's Main Code and Trading Strategy Component from Team 1(CE903)
##################
#!pip install nasdaq-data-link
import Core_Infrastructure_1stHalf ##Also forms the Project Directory
from Core_Infrastructure_1stHalf import historical_data_recorder
f... |
import argparse
import collections
import os
from collections import OrderedDict
from collections import defaultdict
from PIL import ImageOps, Image
from pandas import DataFrame
def get_image(input_file):
im = Image.open(input_file).convert('RGB') # Can be many different formats.
im = ImageOps.mirror(im)
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def migrate_profile_pics(apps, schema_editor):
from events.tasks import firebase_get, firebase_put
from events.handlers.events.profile import UpdateProfilePicHandler
User = apps.get_model("gatekeeper... |
# proxy module
from pyface.workbench.debug.debug_view import *
|
"""
Tested with Python 3.4
This program uses Tsorter by Terrill Dent, licensed under the MIT licence:
http://terrill.ca/sorting/tsorter/LICENSE
This is a very early draft of a program. Use more as food for though rather than
as a production tool. Please excuse the lengthy code. I am only a beginner
programmer :)
"""
... |
from ircclient.const import NOTICE, PRIVMSG
crontable = []
outputs = []
relay_outs = []
def catch_all(data):
ignore = ['CONNECTED', 'PING', 'MODE', 'JOIN', 'PART', 'QUIT', 'INVITE', 'KICK', 'BAN']
if data.type == PRIVMSG or data.type == NOTICE:
channel = data.args[1]
if channel.startswith('#... |
#
# @lc app=leetcode id=297 lang=python3
#
# [297] Serialize and Deserialize Binary Tree
#
# @lc code=start
# Definition for a binary tree node.
import collections
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
de... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.MangaListView.as_view(), name='index'),
path('manga/<int:id>/', views.MangaDetailView.as_view(), name='manga-details-page'),
path('readlists/<int:userid>/', views.ReadlistView.as_view(), name='user-readlist-page'),
] |
# Generated by Django 2.1.5 on 2019-04-13 22:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('server', '0003_auto_20190413_1553'),
]
operations = [
migrations.AlterField(
model_name='company',
name='company_add... |
from copy import deepcopy
import logging
from typing import Any, Callable, Coroutine, List, Union, Dict
log = logging.getLogger(__name__)
Comparable = Any
SortedList = List
DictSortedByKeys = Dict
def producer(
inp: Any,
trash_transformation: Coroutine,
transformations: DictSortedByKeys[Comparable, Cor... |
import collections
import numpy as np
import os
import time
from tqdm import tqdm
from apex import amp
import torch
import torch.nn.functional as F
from pycocotools.cocoeval import COCOeval
from simpleAICV.classification.common import ClassificationDataPrefetcher, AverageMeter, accuracy
from simpleAICV.detection.comm... |
import matplotlib.pyplot as plt
import numpy as np
from environment.corridor_gridworld import ShortCorridor
class LogisticalFunc:
def __call__(self, w):
return np.exp(w) / (1. + np.exp(w)) * 0.9 + 0.05
def derivative(self, w):
return np.exp(w) / ((1. + np.exp(w)) ** 2) * 0.9
class MyPolicy:... |
"""
在终端中录入一个内容,循环打印每个文字的编码值。
效果:
请输入文字:qtx
113
116
120
"""
#
# num=input("请输入文字:")
# for item in num:
# print(ord(item))
"""
循环录入编码值打印文字,直到输入空字符串停止。
效果:
请输入数字:113
q
请输入数字:116
t
请输入数字:
Process finished with exit code 0
"""
while True:
num=input("请输入数字:")
if num=="":
break
print(chr(int(num))... |
n = int(input())
m = int(input())
s = float(0)
for i in range(1,n+1):
for j in range (1,m+1):
s = s + (i**2) * j/((3**i) * (j * (3**i) + i * (3**j)))
print("%.4f"%s) |
#!/bin/env/python
'''
test boss_sbi.galaxies
'''
import os, time
import numpy as np
from boss_sbi.halos import Quijote_LHC_HR
from boss_sbi import galaxies as Galaxies
from boss_sbi import forwardmodel as FM
# --- plotting ---
import matplotlib as mpl
mpl.use('pdf')
import matplotlib.pyplot as plt
mpl.rcParams['te... |
#!/usr/bin/env python3
import argparse
import sys
from glob import glob
from matplotlib import pyplot as plt
from spectra import ConvSpectrum
from spectra.plot import plotter
def main(argv=None) -> None:
parser = argparse.ArgumentParser(description="Plot the spectra from csv file(s).")
parser.add_argument("... |
from support.c import *
class CppSupport(CSupport):
def generateotransform(self, info, index):
"""Generates the code to transform values"""
k = "override/#" + str(index) + "/transform/cpp"
if k in info:
f = info.get(k)
return f;
return "return value"
def generateftransform(self, info, index):
"""Gen... |
#importing modules
from sklearn.model_selection import train_test_split
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.linear_model import SGDClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import BaggingClassifier
from sklearn... |
from enum import Enum
from common import mace_check, ModuleName
class SkelMode(Enum):
NON_DOMAINS = 0
DOMAINS = 1
class Skel(Enum):
V60 = 'V60'
V65 = 'V65'
V66 = 'V66'
class DspType(Enum):
ADSP = 'ADSP'
CDSP = 'CDSP'
class SocSkelTable:
def __init__(self, soc_id, mode, skel, d... |
# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
import sys
import re
import json
def read_json_file(file_path):
data = None
with open(file_path, "r") as f:
data = json.load(f)
return data[0:10]
def write_json_file(terms, file_path):
f... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Test Restaurant Module
"""
import unittest
from app import db
from app.modules.restaurant.models import Restaurant, Table, Booking
class TestRestaurantModule(unittest.TestCase):
""" Test restaurant module and methods """
def test_create_restaurant(self):
... |
import os
import json
from multiprocessing import cpu_count
import numpy as np
import pandas as pd
from linora.utils._logger import Logger
from linora.sample_splits import kfold, train_test_split
from linora.param_search._HyperParameters import HyperParametersRandom
from linora.param_search._config import __xgboost_ve... |
import os
ROOTDIR = "./after_modify/no_stop_noun/"
TRAIN_DIR = "./after_modify/train/"
TEST_DIR = "./after_modify/test/"
change_path = {"07", "08", "10", "13", "14", "16", "20", "22", "23", "24"}
for i in change_path:
for parent, dirnames, filenames in os.walk(ROOTDIR + i):
for filename in filenames:
... |
from abc import ABCMeta, abstractmethod
from tempfile import NamedTemporaryFile
from unittest import TestCase
from mock import Mock, patch
class BaseTestCase(TestCase):
def patch(self, target, mock_=None):
if not mock_:
mock_ = Mock()
patcher = patch(target, mock_)
self.addClea... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 25 20:48:39 2017
@author: ratnadeepb
@License: MIT
"""
# System Import
import numpy as np
import sys
# Local Import
from InnerProductSpaces.norm import unit_vec
from InnerProductSpaces.projection import proj
'''
Gram Schmidt process of creating o... |
"""Auth0 OAuth 2.0 Provider.
Implementation of an Auth0 OAuth 2.0 Provier.
"""
import requests
import json
from jose import jwt
from functools import wraps, partial
from flask import request
from brighthive_authlib.providers import OAuth2Provider, OAuth2ProviderError
class AuthZeroProvider(OAuth2Provider):
"""... |
"""
Distributed under the terms of the BSD 3-Clause License.
The full license is in the file LICENSE, distributed with this software.
Author: Jun Zhu <jun.zhu@xfel.eu>
Copyright (C) European X-Ray Free-Electron Laser Facility GmbH.
All rights reserved.
"""
import unittest
from unittest.mock import patch, MagicMock
f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `pytsp` package."""
import unittest
from pytsp import pytsp
class TestPytsp(unittest.TestCase):
"""Tests for `pytsp` package."""
def setUp(self):
"""Set up test fixtures, if any."""
def tearDown(self):
"""Tear down test fixtu... |
#!env/bin/python
import sys
import os
import json
from werkzeug import generate_password_hash
from app.controller import Controller
from app.models import DB
basedir = os.getcwd()
db = DB()
def main():
print '\n'
print 'STACK'
print '----------'
print '\n'
print 'Welcome to the STACK setup too... |
import sys
if sys.version_info < (3,):
sys.exit("triku requires Python >= 3.7")
from pathlib import Path
from setuptools import setup, find_packages
__author__ = ", ".join(["Alex M. Ascensión"])
__email__ = ", ".join(
[
"alexmascension@gmail.com",
# We don’t need all, the main authors are su... |
"""
Ledger output
Supports both `Ledger <https://www.ledger-cli.org/>`_ and
`hledger <https://hledger.org/>`_ plain text accounting formats.
By default the output should be valid for Ledger, but can be customized for
hledger or other variants via formatting options. Invalid variants are
possible, so the user should b... |
# coding=utf-8
import time
from selenium import webdriver
browser = webdriver.Chrome()
browser.maximize_window() # 窗口最大化
browser.get('https://www.baidu.com') # 在当前浏览器中访问百度
browser.find_element_by_id("kw").send_keys("selenium")
browser.find_element_by_id("su").click()
time.sleep(3)
browser.find_element_by_xpath("/ht... |
'''
Author: liziwei01
Date: 2022-02-18 18:35:53
LastEditors: liziwei01
LastEditTime: 2022-03-17 15:47:49
Description: 加载数据
'''
from array import array
from sklearn.cluster import KMeans
from collections import defaultdict
import scipy.io as sio
import numpy as np
import os
class MatLoader:
__filenames = ['testX', ... |
##################################################################
## (c) Copyright 2015- by Jaron T. Krogel ##
##################################################################
#====================================================================#
# hdfreader.py ... |
from Tree import *
# create new list of random features in root original length
def generate_features(features_list):
new_random_features = features_list.to_numpy()
np.random.shuffle(new_random_features)
return new_random_features[0:int(np.sqrt(len(features_list)))]
# create a new sub data... |
from kivy.app import App
from kivy.lang import Builder
from kivy.clock import Clock
from kivy.core.window import Window
from kivy.config import Config
from components.LayoutManager import LayoutManager
Config.set('kivy', 'log_level', 'info')
# Config.set('kivy', 'log_level', 'critical')
Config.set('graphics', 'border... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.