content stringlengths 5 1.05M |
|---|
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
print(device)
class SimpleAE(nn.Module):
def __init__(self):
super(SimpleAE, self).__init__()
self.encoder = nn.Sequential(
nn.Conv2d(3, 32... |
#!/usr/bin/env python3
import sys
import argparse
from time import sleep
from p3lib.uio import UIO
from p3lib.helper import logTraceBack
from smotor.smotor_ctrl import SMotor
class StepItError(Exception):
pass
class StepIt(object):
def __init__(self, uio, options):
"""@brief Constructor
... |
import datetime
from datetime import datetime
class Storage(object):
def __init__(self):
self.__data = {} # { 'default': {"key1":[ exp1, value1]}, 'domain2': {"key1":[ exp1, value1] }
def set(self, name, value, datatype, expiration=None, domain="default"):
try:
if domain not in s... |
import argparse
from copy import copy
try:
import ujson as json
except ModuleNotFoundError:
import json
import kaggle_environments
import numpy as np
import os
from pathlib import Path
import pandas as pd
from scipy import stats
import tqdm
from typing import *
from hungry_geese.utils import STATE_TYPE, read_j... |
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from fitness.accounts.managers import FitnessUserManager
class FitnessUser(AbstractBaseUser, PermissionsMixin):
is_staff = models.BooleanField(
default=False,
)
email = models.EmailField(
... |
"""Image utils."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import io
import matplotlib.pyplot as plt
import numpy as np
import PIL
import PIL.ExifTags
import scipy.ndimage as ndimage
import tensorflow as tf
face_cascade = cv2.CascadeCla... |
import cv2
import random
class RandomHorizontallyFlip(object):
def __init__(self, p=0.5):
self.p = p
def __call__(self, image, label):
if random.random() < self.p:
image = cv2.flip(image, 1)
label = cv2.flip(label, 1)
return image, label
class RandomVerticallyFlip(object):
def __ini... |
'''Additional CFG algorithms.'''
from util.digraph import Digraph
from table import first_sets
def has_empty_rules(grammar):
'''Return whether a grammar has e-productions.'''
for rule in grammar.productions:
if not rule.right_side:
return True
return False
def is_left_recursive(gramma... |
import socketserver
from video_reader import base_server
from video_reader import net_sock_handler
def video_net_socket_reader_server(data_pipe_w, ack_pipe_r, semaphore, port=9526):
return VideoPacketNetSocketReaderServer(
"video packet net socket reading server", data_pipe_w, ack_pipe_r, semaphore, port... |
# coding: utf-8
from caty import UNDEFINED
from caty.core.schema import *
from caty.core.script.builder import CommandCombinator
from caty.core.script.interpreter import BaseInterpreter
from caty.core.script.node import *
from caty.core.std.command.builtin import Void
from caty.core.typeinterface import TreeCursor
from... |
from django.contrib import admin
from .forms import TagLayoutAdminForm
from .models import TagLayout
# Register your models here.
@admin.register(TagLayout)
class TagLayoutAdmin(admin.ModelAdmin):
form = TagLayoutAdminForm
|
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
from nav_msgs.msg import Odometry
from tf2_msgs.msg import TFMessage
from geometry_msgs.msg import TransformStamped
pub = None
tf_static_list = TFMessage()
def callback(datas):
for data in datas.transforms:
tf_static_list.transforms.append... |
from ecomplexity.ecomplexity import ecomplexity
from ecomplexity.proximity import proximity
name = "ecomplexity"
|
class Solution(object):
def maximalRectangle(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
if matrix == []: return 0
a = [0 for i in xrange(len(matrix[0]))]; maxArea = 0
for i in xrange(len(matrix)):
for j in xrange(len(matrix[0]... |
from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
@app.route('/products/all')
def get_all_products():
print("Listing all the products")
response = requests.get('http://database-service:9090/products')
return jsonify(response.json())
@app.route('/products/')
def get_matching... |
def extended_gcd(a, b):
if a == 0:
return (b, 0, 1)
g, y, x = extended_gcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = extended_gcd(a % m, m)
if g != 1:
raise Exception('Element has no inverse')
return x % m
|
from __future__ import absolute_import # No implicit relative imports
from __future__ import print_function
from __future__ import division
from builtins import range
from rain.module_two import function_two
GLOBAL_VARIABLE_THREE = 3
def function_three():
return function_two(1)
|
import wx
from vistas.ui.project import SceneNode
class FlythroughSceneSelector(wx.Dialog):
""" A Dialog for choosing a Scene to create a Flythrough for. """
def __init__(self, scene_list: [SceneNode], parent, id):
super().__init__(parent, id, "Select Flythrough Scene", style=wx.CAPTION | wx.STAY_ON... |
import wx
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, parent=None, title="Panel Example")
self.panel = wx.Panel(self)
self.panel.SetBackgroundColour (wx.BLACK)
self.button1 = wx.Button(self.panel, label="50, 50)")
self.button1.SetPosition((50, 50))
self.button2 = wx.Button(self... |
class Utils(object):
''' This class contains helpers to use in tests '''
def __init__(self):
pass
ADMIN = {
'firstname': 'Luda',
'lastname': 'one',
'othername': 'politic',
'email': 'politician@app.com',
'phone_number': '254726094972',
'passportUrl' : '... |
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix or not matrix[0]:
return []
left, right, top, down = 0, len(matrix[0])-1, 0, len(matrix)-1
rst = []
while right > left and down > top:
for col in range(left, right+1, 1)... |
import numpy as np
from Utilities.ComputeSimilarityPython import ComputeSimilarityPython
class ItemBasedCollaborativeFilteringRecommender(object):
def __init__(self, URM):
self.URM = URM
def fit(self, topK=150, shrink=8, normalize=True):
similarity_object = ComputeSimilarityPython(self.URM, ... |
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from unittest import skip
from .base import FunctionalTest
import sys
class NewVisitorTest(FunctionalTest):
def test_can_start_a_list_and_retrieve_it_later(self... |
from pyrunner import tasks
from pyrunner.misc.types import TaskMetadata
TASKS = (
TaskMetadata(name="task reloader", interval=5, task_type=tasks.TaskReloaderTask),
TaskMetadata(name="ynet downloader", interval=10, task_type=tasks.URLDownloaderTask,
execute_kwargs={"url": "http://ynet.co.il", ... |
#to run
from pyvision.misc.NeuralStyleTransfer import NeuralStyle
__PREFIX__ = "pyvision/misc/NeuralStyleTransfer/Examples/"
#provide the paths to the two images
style_img, content_img = (__PREFIX__+'images/style1.jpg', __PREFIX__+'images/content2.jpg')
#if you do not wish to use gpu, pass use_gpu=False as a p... |
from autorecon.plugins import PortScan
from autorecon.config import config
import re
class AllTCPPortScan(PortScan):
def __init__(self):
super().__init__()
self.name = 'All TCP Ports'
self.description = 'Performs an Nmap scan of all TCP ports.'
self.type = 'tcp'
self.specific_ports = True
self.tags = ['d... |
import math
import time
import torch
from tqdm import tqdm as tqdm_wrap
from marshmallow.exceptions import ValidationError
from torch.utils.data import DataLoader
from patter.config import EvaluatorConfiguration
from patter.data import audio_seq_collate_fn
from patter.decoder import DecoderFactory, GreedyCTCDecoder
fr... |
class Product:
def __init__(self, name="", price=0.0, discountPercent=0):
self.name = name
self.price = price
self.discountPercent = discountPercent
def getDiscountAmount(self):
return self.price * self.discountPercent / 100
def getDiscountPrice(self):
return self.p... |
"""
This assumes data is generated by format_tercom.py
"""
import sys
import parse_pra_xml
import codecs
def read_file(file_path):
with codecs.open(file_path, 'r', "utf-8") as fid:
return [line.rstrip().split() for line in fid.readlines()]
assert len(sys.argv[:1]) == 1, "Expected one argument"
(
in_... |
from django.db import models
class Student(models.Model):
"""Database model for students"""
name = models.CharField(max_length=100)
roll_number = models.IntegerField(unique=True)
date_of_birth = models.DateField()
class Mark(models.Model):
"""Database model for marks"""
mark = m... |
# Generated by Django 3.2.4 on 2021-06-26 19:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('survey', '0004_survey_name_pl'),
]
operations = [
migrations.AddField(
model_name='answer',
name='text_en',
... |
class BasicEqualityMixin(object):
"""
Provides equals and not-equals methods based on the
member variables of the object being equal. Can be
inherited by any class where only those variables
are considered for equality
"""
def __eq__(self, other):
#note: I'm not checking for the cla... |
#------------------------------------------------------------------------------
#
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions d... |
"""
Represents an invitation message for establishing connection.
"""
from datetime import datetime, timezone
from typing import Union
from marshmallow import fields
from ...agent_message import AgentMessage, AgentMessageSchema
from ..message_types import BASIC_MESSAGE
HANDLER_CLASS = (
"indy_catalyst_agent.mes... |
import argparse
from deimos import __version__
from multiprocessing import cpu_count
from pkg_resources import resource_filename
from snakemake import snakemake
def main():
parser = argparse.ArgumentParser(description='DEIMoS: Data Extraction for Integrated Multidimensional Spectrometry')
parser.add_argument(... |
from utils.api import UsernameSerializer, serializers
from .models import Course, Practice
from account.models import User
from problem.serializers import ProblemSerializer
class CourseSerializer(serializers.ModelSerializer):
created_by = UsernameSerializer()
problems = ProblemSerializer(many=True)
clas... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from sciplot.skeleton import fib
__author__ = "Simon Wehle"
__copyright__ = "Simon Wehle"
__license__ = "mit"
def test_fib():
assert fib(1) == 1
assert fib(2) == 1
assert fib(7) == 13
with pytest.raises(AssertionError):
fib(-10)
|
"""Run offline learning experiments."""
import functools
import os
from typing import Iterator, Tuple
from absl import app
from absl import flags
from absl import logging
from acme import types
from acme import wrappers
import gym
import jax
from ml_collections import config_flags
import numpy as np
import wandb
impo... |
#!/usr/bin/env python
# Get the segments by calling GCProfile
#
# Author: Bingxin Lu
# Affiliation : National University of Singapore
# E-mail : bingxin@comp.nus.edu.sg
#
# Input:
# The genome sequence in FASTA format
#
# Output:
# The positions for a set of intervals
#
import os
import optparse
import subprocess
... |
from datetime import datetime, timezone
from typing import Optional
from pydantic import BaseModel
class Schedule(BaseModel):
"""名前と時間を含んだスケジュール"""
id: Optional[int]
name: str
datetime_start: datetime
datetime_end: datetime
createdAt: Optional[datetime]
def createdAtToLocal(self) -> Opt... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
import numpy as np
from collections import deque
from PIL import Image
import gym
from gym import spaces
import sys
import time
import cv2
from copy import copy
cv2.ocl.setUseOpenCL(False)
class NoopResetEnv(gym.Wrapper):
def __init__(self, env, noop_max=30):
"""Sample initial states by taking random numb... |
__all__ = ["encoder", "mldecoder", "rltrain", "crf"]
|
# %%
import numpy as np
from rrt_planner.manipulation_station_collision_checker import \
ManipulationStationCollisionChecker
from rrt_planner.robot import Range, ConfigurationSpace
from rrt_planner.rrt_planning import Problem
class IiwaProblem(Problem):
def __init__(self,
q_start: np.array,
... |
from time import strftime
from datetime import datetime, timezone
import os
# this class logs everything that happens - detections, coordinates (if supplied) and nozzle
# will also log errors and framerates
class Logger:
def __init__(self, name, saveDir):
self.name = strftime("%Y%m%d-%H%M%S_") + name
... |
import discord
import ast
from discord.ext import commands
def insert_returns(body):
if isinstance(body[-1], ast.Expr):
body[-1] = ast.Return(body[-1].value)
ast.fix_missing_locations(body[-1])
if isinstance(body[-1], ast.If):
insert_returns(body[-1].body)
insert_returns(body[... |
"""Move to well command request, result, and implementation models."""
from __future__ import annotations
from pydantic import BaseModel
from typing import TYPE_CHECKING, Optional, Type
from typing_extensions import Literal
from .pipetting_common import PipetteIdMixin, WellLocationMixin
from .command import AbstractCo... |
import json
import os
from django.apps import apps
from django.conf import settings
from django.core.management.base import BaseCommand
from rest_auth.utils import import_callable
from zconnect.models import Product
_Device = apps.get_model(settings.ZCONNECT_DEVICE_MODEL)
class Command(BaseCommand):
help = 'Pro... |
import argparse
from sys import stdout
import json5
from numpy.random import normal
from numpy import round
def create_circle(size, b_mean, b_dev, c_mean, c_dev):
def create_vertex():
values = round([normal(b_mean, b_dev), normal(-b_mean, b_dev)]).astype(int).tolist()
return {
'low': m... |
"""
Management utility to create users on Auth0 backend and as superusers locally.
"""
from __future__ import unicode_literals
import getpass
import sys
from auth0plus.management import Auth0
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.password_validation i... |
# usage: make_locale_dirs.py locale_dir [...]
#
# This script is intended to create empty locale directories (.lproj) in a
# Cocoa .app bundle. The presence of these empty directories is sufficient to
# convince Cocoa that the application supports the named localization, even if
# an InfoPlist.strings file is not provi... |
# coding: utf-8
"""
Implementation of convert_to_schema(data, previous_schema, new_schema)
"""
import typing
from .generate_placeholder import generate_placeholder
from .utils import get_dimensionality_for_units
def convert_to_schema(data: dict, previous_schema: dict, new_schema: dict) -> typing.Tuple[typing.Any, ty... |
import threading
import time
n = 100000
m = 10000
def process():
for _ in range(m):
time.sleep(0)
def main():
for _ in range(n):
t1 = threading.Thread(target=process)
t1.start()
if __name__ == '__main__':
main() |
# Copyright 2016 Intel
#
# 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, softwar... |
"""add workflow.source_metadata column
Revision ID: b182f655505f
Revises: e7b6dcb09efd
Create Date: 2022-03-14 12:56:57.067748
"""
from alembic import op
from sqlalchemy import Column
from galaxy.model.custom_types import JSONType
from galaxy.model.migrations.util import (
drop_column,
ignore_add_column_erro... |
from __future__ import annotations
from prettyqt import core, gui
from prettyqt.qt import QtGui
QtGui.QLinearGradient.__bases__ = (gui.Gradient,)
class LinearGradient(QtGui.QLinearGradient):
def __repr__(self):
return f"{type(self).__name__}({self.get_start()}, {self.get_final_stop()})"
def serial... |
from lxml import etree
from .. import style as main_style
class StylizedElement:
def __init__(self, *args, **kwargs):
self._built = False
self.x = self.y = 0
self.kwargs = kwargs
def do_build(self, style=None, **kwargs):
if not style:
style = main_style.STYLE
... |
"""Test /feature_association."""
from fastapi.testclient import TestClient
import pytest
from icees_api.app import APP
from ..util import load_data, do_verify_feature_matrix_response
testclient = TestClient(APP)
table = "patient"
year = 2010
age_levels = [
'0-2',
'3-17',
'18-34',
'35-50',
'51-69'... |
# -*- coding: utf-8 -*-
"""Main running script.
This script is the main chipsnet training script. Given the input
configuration it carries out the specified task, either create, train
or study.
Example:
The example below runs the example training configuration
$ python run.py ./config/train.yml
"""
import a... |
DATASET_TYPE_INVALID = -1
DATASET_TYPE_TRAIN = 0
DATASET_TYPE_VAL = 1
DATASET_TYPE_TEST = 2
DATASET_TYPE_ALL = [DATASET_TYPE_TRAIN, DATASET_TYPE_VAL, DATASET_TYPE_TEST]
DATASET_STR_TRAIN = 'train'
DATASET_STR_VAL = 'val'
DATASET_STR_TEST = 'test'
def dataset_type2str(ds_type: int) -> str:
"""convert dataset type... |
# Modify the previous program such that only the users Alice and Bob are greeted with their names.
while 1:
a = input("nhap vao ten cua ban: ")
if(a=="Alice" or a =="Bod"):
print("xin chao " + a)
break
else:
print("ban nhap sai ten, vui long nhap lai ten") |
# Lesson 5b: Packages need to be imported into Thonny using Tools | Manage Packages.
# Plot multiple stations, centred on the United Downs Deep Geothermal Project
import folium
# Set up a list of stations. This is a list of lists, a 2 dimensional list.
STATIONS = [
['RB30C','Falmouth',50.149,-5.095],
['RB5E8','Penzance... |
import unittest
import cloudwatch.modules.collectd as collectd
class collectdTest(unittest.TestCase):
def test_stub_logging_methods_are_not_throwing_exceptions(self):
collectd.debug("msg")
collectd.info("msg")
collectd.warning("msg")
collectd.error("msg")
... |
from typing import Set
import pytest
from transformers import AutoTokenizer
from gdmtl.datasets import mask_difference, mask_whole_word
@pytest.mark.parametrize( # type:ignore
"""arch,seq,prob,expected""",
[
("bert-base-uncased", "binsheng", 1.0, {"[MASK] [MASK] [MASK]"}),
(
"be... |
import sys
import logging
import hypercane.errors
module_logger = logging.getLogger("hypercane.order.memento_datetime")
def order_by_memento_datetime(urims, cache_storage):
from ..utils import get_memento_http_metadata
from datetime import datetime
import concurrent.futures
import traceback
meme... |
# from pizza_maker.dough import Dough
# from pizza_maker.pizza import Pizza
# from pizza_maker.topping import Topping
#
#
# tomato_topping = Topping("Tomato", 60)
# print(tomato_topping.topping_type)
# print(tomato_topping.weight)
#
# mushrooms_topping = Topping("Mushroom", 75)
# print(mushrooms_topping.topping_type)
#... |
import os
import glob
import pickle
import re
# Our numerical workhorses
import numpy as np
import pandas as pd
# Import the project utils
import sys
sys.path.insert(0, '../')
import NB_sortseq_utils as utils
# Import matplotlib stuff for plotting
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.c... |
import time
import machine
# reboot the board after some delay (in seconds)
def reboot(delay=5):
print('rebooting ...')
time.sleep(delay)
machine.reset()
# convert time specified in a string to milliseconds
# the format is `Xd Yh Zm Ws` where
# X is a number of days
# Y is a number of hours
# ... |
# Copyright 2014-2020 Chris Cummins <chrisc.101@gmail.com>.
#
# 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... |
# this file is present to add this folder to sys.path so tests work
# https://stackoverflow.com/questions/50155464/using-pytest-with-a-src-layer
|
import pandas as pd
import matplotlib.pyplot as plt
xco = []
for i in range(1147):
xco.append(i*382/1147)
df1 = pd.read_csv("Density_Values_Baseline_Dynamic.csv")
df2 = pd.read_csv("Density_Values_M5.csv")
plt.plot(xco, df1["Density Values"])
plt.plot(xco, df2["Density Values"]*20)
plt.xlabel("Time (in seconds)")
... |
from flask import Blueprint, request
from .AuthController import find_user, check_user, signup, check_token, get_home
auth = Blueprint('auth', __name__, template_folder='auth_templates', url_prefix='/auth')
@auth.route('/<path:path>', methods=["POST"])
def validate(path):
if path in ['username', 'email']:
... |
from datetime import datetime
from lxml import etree
from django.urls import reverse
from share.oaipmh.util import format_datetime, SubEl, ns, nsmap
class OAIRenderer:
def __init__(self, repository, request):
self.repository = repository
self.request = request
self.kwargs = {}
def ... |
# -*- coding: utf-8 -*-
"""
----
-----------
- Level 314 -
-----------
----
@author: Alexander Williams
date: Sun May 3 10:16:03 2020
"""
import numpy as np
import matplotlib.pyplot as plt
def map_orientation(cur_orientation, cur_count):
""" . . . . . x
. . . . . x
... |
import requests
import datetime as dt
from src.typeDefs.rawVoltageCreationResp import RawVoltageCreationResp
class RawVoltageCreationHandler():
rawVoltageCreationUrl = ''
def __init__(self, rawVoltageCreationUrl):
self.rawVoltageCreationUrl = rawVoltageCreationUrl
def createRawVoltage(self, star... |
from spider.LogInit import log
from bs4 import BeautifulSoup
from spider import Item
import re
from urllib.parse import urlparse
# 对于指定的HTML页面进行解析,抽取出要抓取图片的url和name
# 保存在Item对象中,Item对象保存在一个“线程安全”队列中
# 生产者-消费者模型
class HtmlParser(object):
'''
每一个HtmlParser对象中保存了要解析的HTML页面
parser = HtmlParser(html, taskMana... |
import cv2
import time
import glob
import os.path
import numpy as np
from matplotlib import pyplot as plt
import skimage
import skimage.measure
import skimage.morphology
def img_to_map(img):
map = img.copy().astype(np.float)
map[img == 128] = -1.0
map[img == 0] = 1.0
map[img == 200] = 0.0
return ma... |
import unittest
from datetime import timedelta, datetime
from time import sleep
from src.utils.datetime import strfdelta
from src.utils.timing import TimedTaskLimiter, TimedOccurrenceTracker
class TestTimedTaskLimiter(unittest.TestCase):
def setUp(self) -> None:
self.interval_seconds = 2
self.in... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
# -*- coding: utf-8 -*-
"""
# @Time : 2019/5/24
# @Author : Jiaqi&Zecheng
# @File : data_process.py
# @Software: PyCharm
"""
import json
import argparse
import nltk
import os
import pickle
try:
from irnet_utils import symbol_filter, re... |
import gym
import numpy as np
# Types
Program = [str]
Population = [Program]
class Agent:
def __init__(self):
# Agent structure parameters
self._T_values = ["pa", 'pv', '0.0', '0.025']
self._T_actions = ['L', 'R']
self._F = ["IFLTE"]
self._program_depth = 2
self._actions = {'L': 0, 'R': 1}
# GP exp... |
import re
import sys
class Token:
def __init__(self, type, val, pos):
self.val = val
self.type = type
self.pos = pos
def __str__(self):
return '%s [%s] at pos %s' %(self.val, self.type, self.pos)
class LexExeption(Exception):
def __init__(self, sign,pos):
self.pos ... |
from .clotho_data_loader import get_clotho_loader
from pathlib import Path
def get_dataloaders(path_to_clotho, input_modal='features', output_modal='words_ind', num_workers=1, shuffle_train=True, batch_size=20):
train_dataloader = get_clotho_loader(Path(path_to_clotho+'/data'), 'development', input_modal,
... |
from ase.io import read
from flosic_os import calculate_flosic, flosic,xyz_to_nuclei_fod,ase2pyscf,get_multiplicity
from pyscf import dft,gto
# This example shows how FLO-SIC calculations can be done in the one-shot mode.
# The necessary input is a .xyz file with the molecular geometry and the FOD positions.
# The ea... |
import json
import math
import string
from ast import literal_eval
from pathlib import Path
import ftfy
import jsonlines
import plac
import validators
from preshed.counter import PreshCounter
from spacy.lang.en import stop_words as en_stop_words
from spacy.lang.zh import stop_words as zh_stop_words
from tqdm import tq... |
from urllib.request import urlopen
import json
url = "https://raw.githubusercontent.com/pokemongo-dev-contrib/pokemongo-json-pokedex/master/output/pokemon.json"
response = urlopen(url)
final_data = []
json_data = json.loads(response.read())
for p in json_data:
final_data.append({
'dex': p['dex'],
... |
from shared import Blob
from typing import List
from ._base import _Base
def _blob_with_header(count: int) -> Blob():
output = Blob()
output.append_char4("W3do")
output.append_int(8) # major version
output.append_int(0xB) # minor version (often set to [0B 00 00 00]h)
output.append_int(count)
... |
#!/usr/bin/env python
from stile.hsc.base_tasks import CCDSingleEpochStileTask
CCDSingleEpochStileTask.parseAndRun()
|
help_txt = "Give admin power to user"
isadmin = True
syntax = "/admin [nick]"
def execute(caller, args, ex):
if len(args) < 1:
return ex.SHOW_USAGE
user = ex.server.nick2user(args[0])
if user is ex.server.userNotFound:
return ex.INVALID_ARG
user.admin = True
|
from datetime import timedelta
from rest_framework.status import HTTP_200_OK, HTTP_201_CREATED, HTTP_204_NO_CONTENT, HTTP_401_UNAUTHORIZED, \
HTTP_403_FORBIDDEN, HTTP_400_BAD_REQUEST
from rest_framework.test import APITestCase
from rest_framework_... |
from flask.views import MethodView
from flask import request, session
from flask import jsonify
from orm.fields import HasField
from orm.exceptions import FieldNotValidError, ObjectNotFoundError
from .login import api_login_required
'''
These two classes implements basic JSON REST-api
'''
class APIListView(MethodVie... |
# coding=utf-8
import ccxt
import sys
import time
verbose = False
try:
from config import markets as markets
except ImportError:
markets = { # defaults
'_1broker': { 'verbose': verbose, 'apiKey': '' },
'_1btcxe': { 'verbose': verbose, 'apiKey': '', 'secret': '' },
'bit2c': { 'verbose': verbo... |
from alembic_utils.experimental._collect_instances import collect_instances
__all__ = ["collect_instances"]
|
import random
from typing import List
from discord import Embed, Color, Member, VoiceState, VoiceChannel
from discord.ext import commands
from discord.ext.commands import Context as CommandContext, Bot
class VCRandomCog(object):
def __init__(self, bot: commands.Bot):
self.bot: commands.Bot = bot
@co... |
#!/usr/bin/env python
# Copyright 2019 The Vitess 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 required by applic... |
"""Session wide fixtures."""
from __future__ import annotations
import asyncio
from pathlib import Path
from typing import TYPE_CHECKING, Generator, Optional
import numpy as np
import pytest
from fastapi.testclient import TestClient
from PIL import Image
if TYPE_CHECKING:
from _pytest.monkeypatch import MonkeyPa... |
import numpy as np
def predict(x, w):
a = np.sum(x * w)
return step_function(a)
def step_function(a):
return np.array(a >= 0, dtype=np.int)
x_data = np.array([[-1, 0, 0], [-1, 0, 1], [-1, 1, 0], [-1, 1, 1]])
y_data = np.array([0, 0, 0, 1])
w = np.array([0.3, 0.4, 0.1])
learning_rate = 0.05
while True:
... |
# Generated by Django 3.0.4 on 2020-11-27 11:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0002_auto_20201127_1236'),
]
operations = [
migrations.AddField(
model_name='category',
na... |
import logging
import requests
from django.conf import settings
logger = logging.getLogger('ppwa.api')
# Users of api should't import requests to catch exceptions.
HTTPError = requests.HTTPError
def product_list():
'''Product listing.
:return: list of {id, uuid, slug, name}
:raise ValueError: JSON pars... |
from app import db
class Team(db.Model):
__tablename__ = "teams"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(200))
country = db.Column(db.String(100))
brand = db.Column(db.String(800))
... |
from .settings import Settings
from .COCO_classes_tag import *
name = 'core'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.