content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# Copyright (c) 2009-2014 Denis Bilenko and gevent contributors. See LICENSE for details.
from __future__ import absolute_import
# standard functions and classes that this module re-implements in a gevent-aware way:
_implements = ['create_connection',
'socket',
'SocketType',
... | python |
from pathlib import Path
import numpy as np
from scipy import ndimage
from self_supervised_3d_tasks.data.generator_base import DataGeneratorBase
import os
class SegmentationGenerator3D(DataGeneratorBase):
def __init__(
self,
data_path,
file_list,
batch_size=8,
... | python |
from django.contrib import admin
# Register your models here.
from .models import CarOwner
admin.site.register(CarOwner)
from .models import DrivingLicense
admin.site.register(DrivingLicense)
from .models import Owning
admin.site.register(Owning)
from .models import Car
admin.site.register(Car)
from .models import... | python |
import logging
import plistlib
from django.db import transaction
from django.http import HttpResponse
from django.views.generic import View
from zentral.contrib.inventory.models import MetaBusinessUnit
from zentral.contrib.inventory.utils import commit_machine_snapshot_and_trigger_events
from zentral.contrib.mdm.events... | python |
'''
Kattis - browniepoints
Annoying problem description which needs to be read closely. The line drawn passes through
the point in the center of the input sequence.
Time: O(n), Space: O(n)
'''
class point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "(" + ... | python |
class FakeDeserializer:
def __init__(self, output):
self.output = output
self.input = None
def serialize(self, obj):
return ""
def deserialize(self, body):
self.input = body
return self.output
| python |
# -*- coding: utf-8 -*-
from pkg_resources import resource_filename
import pandas
def load_example_data():
"""
Loads example data for pyexample.
Parameters
----------
None
Returns
-------
example : pandas.DataFrame
The example data for pyexample
Example
-------
... | python |
### ----------------- IMPORTS ----------------- ###
import pandas as pd
import numpy as np
### ------------------------------------------- ###
# Create dropdown column elements
dropdown_cols = ['Source', 'Search Function']
drop_options =[{'total_channels', 'file_name', 'channel_name', 'comment_text'},
{'contains', 'st... | python |
import os
import time
import logging
import datetime
from copy import deepcopy
from smartmicro.Helper.basicThreadHelper.threadHelper import ThreadHelper
class canReceive(ThreadHelper):
"""
This is an internal class and should not be used by the user
The user should use the communicationModule... | python |
from exatrkx.src.processing.feature_construction import FeatureStore
from exatrkx.src.embedding.layerless_embedding import LayerlessEmbedding
from exatrkx.src.embedding.layerless_embedding import EmbeddingInferenceCallback
from exatrkx.src.filter.vanilla_filter import VanillaFilter
from exatrkx.src.filter.vanilla_fil... | python |
from .consts import FEISHU as FEISHU
from .consts import ONEBOT as ONEBOT
from .consts import QQGUILD as QQGUILD
from .consts import TELEGRAM as TELEGRAM
from .deps import AdapterName as AdapterName
from .deps import EventName as EventName
from .deps import ImageSegmentMethod as ImageSegmentMethod
from .deps import Mes... | python |
#!/usr/bin/env python
"""
Page getter for Fanfiction.net and ao3
"""
import sys
import argparse
import logging
from dyrm import ffmonthly, do_you_read_ao3
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"-n", "--nomonth",
help="no monthly",
action="... | python |
# ==== Versions
# --pre
# constraints
# ==== Specific files
# hashes
# ==== Tag stuff
# --platform
# --python-version
# --implementation
# --abi
# ==== Wheels or sdists
# --no-binary (all, none, package...)
# --only-binary (all, none, package...)
# ==== Python version
# data-requires-python
# Normalized project na... | python |
# Time: O(2^n)
# Space: O(1)
# The gray code is a binary numeral system where two successive values differ in only one bit.
#
# Given a non-negative integer n representing the total number of bits in the code,
# print the sequence of gray code. A gray code sequence must begin with 0.
#
# For example, given n = 2, ... | python |
from typing import Dict, Optional
from datasets import datasets
import torch
from torch.utils.data import DataLoader
from catalyst.contrib import nn
from catalyst.contrib.models.cv.encoders import ResnetEncoder
from catalyst.data.dataset.self_supervised import SelfSupervisedDatasetWrapper
def add_arguments(parser) ... | python |
# Solution of;
# Project Euler Problem 199: Iterative Circle Packing
# https://projecteuler.net/problem=199
#
# Three circles of equal radius are placed inside a larger circle such that
# each pair of circles is tangent to one another and the inner circles do not
# overlap. There are four uncovered "gaps" which are ... | python |
class Solution:
"""
@param: num: a positive number
@return: true if it's a palindrome or false
"""
def isPalindrome(self, num):
# write your code here
string = str(num)
l = list(string)
length = len(l)
i = 1
while i < length / 2 + 1:
if l[... | python |
from kusto_tool.database import KustoDatabase
from kusto_tool.expression import Limit, TableExpr
def test_limit():
"""limit prints."""
assert str(Limit(1000)) == "| limit 1000"
def test_limit_tbl():
"""limit works on a tbl."""
assert (
str(TableExpr("tbl", KustoDatabase("c", "db")).limit(100... | python |
import argparse
from frontend import FrontEnd
def run():
f = FrontEnd()
parser = argparse.ArgumentParser(
prog='hoard',
epilog="See '%(prog)s <command> --help' for more help on a specific command."
)
sub_parsers = parser.add_subparsers(title='Commands')
get_parser = sub_parsers... | python |
# SPDX-License-Identifier: MIT
import contextlib
import os
import pathlib
import pytest
package_dir = pathlib.Path(__file__).parent / 'packages'
@contextlib.contextmanager
def cd_package(package):
cur_dir = os.getcwd()
package_path = package_dir / package
os.chdir(package_path)
try:
yield ... | python |
"""
Copyright 2013 The Trustees of Princeton University
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 applicab... | python |
"""
You can define these configurations and call using environment variable
`ENVIRONMENT`. For example: `export ENVIRONMENT=ProductionConfig`
"""
import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
class Config():
"""Base configuration with default flags"""
DEBUG = False
TESTING = False
... | python |
from .enums import Reagent, Temperature
def get_transcriptic_inventory(include_lowercase=True):
inventory = {
Reagent.dmem_fbs_ps: 'rs197gzgq2fufr',
Reagent.mem: 'rs196bbjnnayuk',
Reagent.methanol: 'rs196bbr78dppk',
Reagent.fbs: 'rs196baqxcecxs',
Reagent.pennstrep: 'rs196b... | python |
""":mod:`MainShopInventory` -- Represents an item in a user shop
.. module:: MainShopInventory
:synopsis: Represents an item in a user shop
.. moduleauthor:: Joshua Gilman <joshuagilman@gmail.com>
"""
from neolib.item.Item import Item
import logging
class UserShopFrontItem(Item):
"""Represents an item in... | python |
from math import prod
class Package:
def __init__(self, binary_input):
self.bin = binary_input
self.version = int(self.bin[:3], 2)
self.type = int(self.bin[3:6], 2)
if self.type == 4: # Literal value
groups = []
index = 6
while True:
... | python |
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from .models import Book
from django.contrib.auth.models import User
# Create your tests here.
class ShoppingCartFeatureTests(APITestCase):
book1 = Book.objects.get(id=1).__dict__
del book1['_state']... | python |
#
# Copyright (c) 2021, 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 appl... | python |
fig = plt.figure(figsize=(3, 3))
h = Hodograph()
h.plot_colormapped(u[mask], v[mask], windspeed[mask]) # Plot a line colored by wind speed
h.add_grid(increment=20) | python |
from collections import namedtuple
from datetime import datetime
from os import environ
import asyncio
import discord
import re
client = discord.Client()
trailhead = discord.Game("%help", start=datetime(1970, 1, 1, 0, 0, 0))
Command = namedtuple("Command", ["name", "desc", "usage", "regex", "action"])
commands = {}... | python |
import threading
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.conf import settings
from django.core.mail import EmailMessage
from django.http import JsonResponse
import os
import subprocess
from . import models
from project.settings import BASE_DIR
# index.html file a... | python |
"""
Task:MaxNonoverlappingSegments
Find a maximal set of non-overlapping segments.
Located on a line are N segments, numbered from 0 to N − 1, whose positions are given in arrays A and B. For each I (0 ≤ I < N) the position of segment I is from A[I] to B[I] (inclusive). The segments are sorted by their ends, which mea... | python |
import numpy as np
from pynwb.testing import TestCase
from ndx_csd import CSD
class TestCSDConstructor(TestCase):
def test_constructor_1d_probe(self):
"""Test that the constructor for CSD sets values as expected."""
num_times = 101
num_channels = 32
data = np.random.rand(num_tim... | python |
from setuptools import setup
setup(
name="pymold",
version="0.1.3",
description="A simple, fast template engine for Python.",
long_description="https://github.com/Bogdanp/mold",
packages=["mold"],
install_requires=[],
author="Bogdan Popa",
author_email="popa.bogdanp@gmail.com",
url=... | python |
import argparse
import json
import os
import time
import requests
import tqdm
from pexels_api import API
PEXELS_API_KEY = os.environ['PEXELS_KEY']
MAX_IMAGES_PER_QUERY = 100
RESULTS_PER_PAGE = 10
PAGE_LIMIT = MAX_IMAGES_PER_QUERY / RESULTS_PER_PAGE
def get_sleep(t):
def sleep():
time.sleep(t)
return... | python |
import math
import unittest
from xnmt.eval import metrics
from xnmt import events
from xnmt.utils import has_cython
from xnmt.vocabs import Vocab
class TestBLEU(unittest.TestCase):
def setUp(self):
events.clear()
self.hyp = ["the taro met the hanako".split()]
self.ref = ["taro met hanako".split()]
... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import os
import time
import warnings
import pandas as pd
import sys
import numpy as np
warnings.simplefilter(action='ignore', category=FutureWarning)
'''this section is to label junction starts/ends as main (a.k.a. canonical) and not main'''
def gene_counter(... | python |
import os
import fire
from commander import CommanderImpl, Response
class CLI(object):
def __init__(self):
self.sub_process = CommanderImpl()
def CaptureProcess(self, command: str, capture_name):
response: Response = self.sub_process.call(command)
os.makedirs('./tests/{}'.format(ca... | python |
"""Constants that define languages"""
CZECH = 'cs'
ENGLISH = 'en'
FRENCH = 'fr'
GERMAN = 'de'
POLISH = 'pl'
SPANISH = 'es'
| python |
from django.apps import AppConfig
class StufbgConfig(AppConfig):
name = "openpersonen.contrib.stufbg"
verbose_name = "StUF-BG backend"
| python |
#!/usr/bin/env python3
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import logging
from importlib import util
if util.find_spec('neo4j') is None:
print('[-] Neo4j library is not installed, please execute the following before: pip3 install --upgrade neo4j')
exit()
from neo4j import Auth,... | python |
from typing import Dict, List, Optional, Set, Type, TypeVar, cast
from black import FileMode, format_str
from blockkit.components import Component
from blockkit.elements import Image, MarkdownOption, OptionGroup, PlainOption
from blockkit.objects import (
Confirm,
DispatchActionConfig,
Filter,
Markdow... | python |
# Modules normally used
#import numpy as np
import cv2
# Load an image in grayscale
img = cv2.imread('img_name.jpg', 0)
print(type(img))
print(img.shape[0])
print(img.shape[1])
print(img.shape[2])
height, width, depth = img.shape
k = cv2.waitKey(0)
if k == 27:
# Wait for ESC key to exit
cv2.destroyAllWindow... | python |
import os
import joblib
import xgboost
import argparse
import numpy as np
import pandas as pd
from azureml.core.run import Run
from xgboost import XGBClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from azureml.data... | python |
import threading
from queue import Queue
from spider import Spider
from domain import *
from general import *
ALL_OF_MY_CATEGORYS = read_file('category.txt')
i = read_file('category.txt')[0]
PROJECT_NAME = ALL_OF_MY_CATEGORYS[0].split('\n')[0]
DOMAIN_NAME = get_domain_name('https://w3techs.com/sites/')
NUMBER_OF_THREA... | python |
from timeit import default_timer as timer
import logging
from scipy.spatial.distance import cosine
import numpy as np
import json
from nltk.tokenize import sent_tokenize
from typing import List, Union
from .objects import (
Phrase,
Keyphrase,
Request,
GraphQueryRequest,
GraphSegmentResponse,
Co... | python |
"""
"id" (https://docs.python.org/3/library/functions.html#id):
Return the “identity” of an object.
This is an integer which is guaranteed to be unique and constant for this object during its lifetime.
Two objects with non-overlapping lifetimes may have the same "id()" value.
CPython implementation detail: This is the... | python |
import unittest
from pyfinder import Crawler
class TestCrawler(unittest.TestCase):
def setUp(self):
self.crawler = Crawler()
self.n = 10
def test_crawl(self):
self.crawler.run()
@unittest.skip("Skipping test_build")
def test_build_test(self):
images = self.crawler.bui... | python |
import logging
log = logging.getLogger(__name__)
from collections import deque, namedtuple
from copy import copy
from functools import partial
from queue import Empty, Queue
import numpy as np
from scipy import signal
from atom.api import (Unicode, Float, Typed, Int, Property, Enum, Bool,
Calla... | python |
from django.views.generic import list_detail
from debugged.stream.models import StreamEntry
def entries(request, paginate_by=10, page=None, template_name=None,
extra_context=None, template_object_name='entry'):
return list_detail.object_list(request,
queryset=StreamEntry.objects.order_by('-pub... | python |
from manim import *
from manim_ml.image import GrayscaleImageMobject
from manim_ml.neural_network.layers.parent_layers import NeuralNetworkLayer
from PIL import Image
class ImageLayer(NeuralNetworkLayer):
"""Single Image Layer for Neural Network"""
def __init__(self, numpy_image, height=1.5, show_image_on_cr... | python |
"""
config tests.
"""
import os
import sys
import numpy as np
import pickle
import platform
import pytest
from unittest import mock
import wandb
from wandb import wandb_sdk
from wandb.errors import LogMultiprocessError, UsageError
from wandb.proto.wandb_internal_pb2 import RunPreemptingRecord
def test_run_step_prop... | python |
#!/usr/bin/env python
import h5py
import numpy as np
def Kanamori_interaction(l, U_int, J_hund):
norb = 2*l + 1
U = np.zeros((norb,norb,norb,norb), dtype=float)
for i in range(norb):
U[i][i][i][i] = U_int
for j in range(norb):
if(i != j):
U[i][j][i][j] = U_int... | python |
import numpy as np
import time
import faiss
from source import eval_cluster
import preprocess
def run_kmeans(x, nmb_clusters, verbose=False):
"""Runs kmeans on 1 GPU.
Args:
x: data
nmb_clusters (int): number of clusters
Returns:
list: ids of data in each cluster
"""
n_data, ... | python |
from django.db import models
from django.contrib.auth import models as auth_models
class Person(models.Model):
user = models.OneToOneField(auth_models.User, on_delete=models.CASCADE)
| python |
#!/usr/bin/python3
# encoding: utf-8
import socketserver
import threading
import time
import re
import ArmController as controller #舵机转动
import LeConf #偏差
from ArmCmd import LeError
import ArmCmd
import ArmWebServer as web
class ServoServer(socketserver.BaseRequestHandler):
def handle(self):
print("已连接")... | python |
import time
import unittest
import uuid
from decimal import Decimal
from typing import List, cast
import grpc
import petlib.bn
import petlib.ec
from common.constants import (
CURRENCY_PRECISIONS,
SECP256K1_ALTERNATIVE_GENERATOR,
SECP256K1_GENERATOR,
SECP256K1_GROUP,
Blockchain,
Currency,
)
from... | python |
import fastjsonschema # type: ignore
from ...models.meeting import Meeting
from ...shared.permissions.meeting import MEETING_CAN_MANAGE
from ...shared.schema import schema_version
from ..actions import register_action
from ..generics import CreateAction
create_meeting_schema = fastjsonschema.compile(
{
"... | python |
from django.shortcuts import render
from django.core import serializers
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.conf import settings
import json
import datetime
from registrar.models import Student
from regist... | python |
import csv
import json
from airflow.models import DAG
from airflow.operators.dummy import DummyOperator
from airflow.operators.python import PythonOperator
from airflow.providers.postgres.hooks.postgres import PostgresHook
from airflow.utils import timezone
import pandas as pd
DAGS_FOLDER = '/opt/airflow/dags'
de... | python |
import asyncio
import contextlib
import inspect
import io
import platform
import re
import sys
import textwrap
import traceback
from datetime import datetime, timezone
from random import randint
import math
import hikari
import lightbulb
from lightbulb import commands, plugins, checks
from lightbulb.context import Cont... | python |
# -*- coding: utf-8 -*-
"""
Created on July 11, 2016
@author: bwawok@gmail.com
"""
from __future__ import absolute_import
from django.core.paginator import Paginator
from django.test import TestCase
from djcompoundqueryset import CompoundQueryset
from .testapp.models import FirstModel, SecondModel
class LoginLogout... | python |
# emailer.py
#
# Copyright (c) 2022 John Fritz
# MIT License, see license.md for full license text
import json
import smtplib
import ssl
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
from email.utils impor... | python |
#
# Import Django
from django.urls import path
#
# Import views
from .api import api_start_timer, api_stop_timer, api_discard_timer, api_get_tasks
from .views import projects, project, edit_project, task, edit_task, edit_entry, delete_entry, delete_untracked_entry, track_entry
#
# Url pattern
app_name = 'project... | python |
#!/usr/bin/env python
#
# Wrapper on pyinotify for running commands
# (c) 2009 Peter Bengtsson, peter@fry-it.com
#
# TODO: Ok, now it does not start a command while another is runnnig
# But! then what if you actually wanted to test a modification you
# saved while running another test
# Yes, we... | python |
import torch
import torch.nn as nn
import torchvision
class AlexNet(nn.Module):
def __init__(self,num_classes=1000):
super(AlexNet,self).__init__()
self.feature_extraction = nn.Sequential(
nn.Conv2d(in_channels=3,out_channels=96,kernel_size=11,stride=4,padding=2,bias=False),
... | python |
# SPDX-License-Identifier: BSD-3-Clause
# Andrew Piroli 2022
import argparse
import time
import tracemac_parser
from getpass import getpass
from netmiko import ConnectHandler
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Union
etherchannel_cache_current_device_id: str = ""
etherchann... | python |
import sys
import os
from functools import reduce
from datetime import datetime
from time import strftime
from warnings import warn
import numpy as np
import pandas as pd
from scipy.sparse import issparse, csr_matrix
import scanpy as sc
import h5py
from natsort import natsorted
from anndata import AnnData
from mudata... | python |
import yaml
import os
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
@classmethod
def from_nested_dicts(cls, data):
""" Construct nested AttrDicts from nested dictionaries. """
if not isinstan... | python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017-2019 KuraLabs S.R.L
#
# 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 appl... | python |
flag_bits = 2
int_bits = 32
frac_bits = 30
internal_frac_bits = 60
internal_int_bits = 4
| python |
from django.conf.urls import url
from . import views
from django.contrib.auth.views import (
login,
logout,
# These built in views are for password reset
password_reset,
password_reset_done,
password_reset_confirm,
password_reset_complete
)
urlpatterns = [
url(r'^register/$', views.reg... | python |
def test_music_genre_object(fake):
test_genre_obj = fake.music_genre_object()
assert isinstance(test_genre_obj, dict)
assert "genre" in test_genre_obj.keys()
assert "subgenres" in test_genre_obj.keys()
def test_music_genre(fake):
test_genre = fake.music_genre()
assert isinstance(test_genre, st... | python |
# -*- coding: utf-8 -*-
import vim
from orgmode._vim import echo, echom, echoe, ORGMODE, apply_count, repeat, insert_at_cursor, indent_orgmode
from orgmode.menu import Submenu, Separator, ActionEntry, add_cmd_mapping_menu
from orgmode.keybinding import Keybinding, Plug, Command
from orgmode.liborgmode.checkboxes impor... | python |
"""
Counts number of occurrences of keywords and groups by word.
"""
from operator import add
from defoe import query_utils
def do_query(archives, config_file=None, logger=None, context=None):
"""
Counts number of occurrences of keywords and groups by word.
config_file must be the path to a configurati... | python |
#!/usr/bin/env python3
"""
BSD 3-Clause License
Copyright (c) 2017, SafeBreach Labs
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 above copyright noti... | python |
import unittest
from parameterized import parameterized_class
import gilded_rose_oop
import gilded_rose_functional
from items.aged_brie import AgedBrie
@parameterized_class([
{"gilded_rose_factory": gilded_rose_oop.GildedRose, "name": "OOP"},
{"gilded_rose_factory": gilded_rose_functional.GildedRose, "name"... | python |
"""
Usage:
plot_per_epoch.py (--model-names=MN)... [--algos=ALGO]... [options]
Options:
-h --help Show this screen.
--algos ALGO Which algorithms to load {BFS, parallel_coloring}.
Repeatable parameter. [default: BFS]
--has-GRU Does the pro... | python |
import csv
import re
def getCsv(txtFileName='ninteenth.txt'):
with open(txtFileName) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=' ')
return list(csv_reader)
def parseRules(csvFile):
rulesDict = {}
codes = []
rules = True
for row in csvFile:
if not row:
... | python |
# Generated by Django 2.0 on 2018-02-21 08:22
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
import web.managers
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0009_alter_user_last_name_max_len... | python |
#! /usr/bin/env python3
#
# Copyright 2019 Rolf Michelsen
#
# 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 |
from __future__ import annotations
import os
import pathlib
import typing
import services
from NeonOcean.S4.Main import Debug, Language, Paths, This
from NeonOcean.S4.Main.Saving import Save
from NeonOcean.S4.Main.UI import Dialogs
from ui import ui_dialog, ui_dialog_picker
SelectSaveDialogTitle = Language.String(Th... | python |
import time
from robot.utils import timestr_to_secs
class Wait:
@staticmethod
def until_true(condition, timeout, error_msg):
"""Helper to wait until given condition is met."""
timeout = timestr_to_secs(timeout)
max_wait = time.time() + timeout
while True:
if conditi... | python |
__author__ = 'mnowotka'
import datetime
from django.db import models
from chembl_core_model.models import *
from chembl_core_db.db.models.abstractModel import ChemblCoreAbstractModel
from chembl_core_db.db.models.abstractModel import ChemblModelMetaClass
from django.utils import six
# --------------------------------... | python |
'''LINEイベントのハンドラ'''
import sys
import linebot
from django.db.utils import OperationalError
from . import line_utilities as line_util
from . import line_settings
from .. import message_commands as mess_cmd
from .. import utilities as util
from ..exceptions import GroupNotFoundError, UserNotFoundError
CO... | python |
#!/usr/bin/env python
import time
from pylibftdi import Device, USB_PID_LIST, USB_VID_LIST
from ctypes import *
import struct
from slip import slip, unslip_from
STYX_VID = 0x2a19
STYX_PID = 0x1007
USB_VID_LIST.clear()
USB_VID_LIST.append(STYX_VID)
USB_PID_LIST.clear()
USB_PID_LIST.append(STYX_PID)
R1 = 21660.0
R2 =... | python |
import sys
import copy
from parseipl import parseIplInst, parseIplPath
def wxyzConjugate(q):
return q[0], -q[1], -q[2], -q[3]
def quatMultiply(q, p):
return q[0]*p[0] - q[1]*p[1] - q[2]*p[2] - q[3]*p[3], \
q[0]*p[1] + q[1]*p[0] + q[2]*p[3] - q[3]*p[2], \
q[0]*p[2] + q[2]*p[0] + q[3]*p[1] - q[1]*p[3], \
q[0]*p[3]... | python |
import logging
import logging.handlers
import sys
def getLogger(logger_name, use_syslog):
logger = logging.getLogger(logger_name)
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
cf = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(mess... | python |
import numpy as np
import pandas as pd
class ElanPortal():
def __init__(self):
self.data = {}
def add_tier(self, tier_name, type, tier_data):
'''
This function add data to portal
:param tier_name:
:param tier_data:
:return:
'''
self.data.setdefa... | python |
import numpy as np
import pandas as pd
from keras.utils import to_categorical
from keras import layers, Input, regularizers
from keras.models import Model
from sklearn import metrics
from keras.optimizers import SGD, Adam
from keras.callbacks import EarlyStopping
import STRING
from resources.sampling import un... | python |
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.shortcuts import render, redirect
from user_access.forms import SignUpForm
# Sign Up Functionality
def SignUpView(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_v... | python |
import shutil
import os
import crequests
from pathlib import Path
cacheDir = "tests/cachedir"
def test_cacheDirCreation():
shutil.rmtree(
cacheDir, ignore_errors=True
) # Remove the cache dir if it exists... We want to start from fresh
crs = crequests.Session(cacheDir) # Create an instance of ... | python |
# Generated by Django 3.1.2 on 2020-11-05 16:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("opcalendar", "0009_auto_20201105_0859"),
]
operations = [
migrations.AlterField(
model_name="event",
name="visibilit... | python |
"""
Script to compute partial correlations of various factors with flexibility.
"""
import numpy as np
import pandas as pd
from scipy import stats
import src.corpus
import src.partial
LANGS = "en fr zh es de ja la nl ar he id sl ro it pl da".split()
for LANG in LANGS:
data_file = "data/wiki/processed/%s.pkl" % LA... | python |
from flask import Flask
from flask import request
from flask import render_template
import sys, os
sys.path.append('/home/ec2-user/python-image-gallery/gallery/ui')
from db_functions import *
import secrets
app = Flask(__name__)
@app.route('/admin')
def admin_list():
data = listUsers2()
return render_template... | python |
#!/usr/bin/env python2
import sys
sys.path.append('../fml/')
import os
import numpy as np
import fml
import time
import random
t_width = np.pi / 4.0 # 0.7853981633974483
d_width = 0.2
cut_distance = 6.0
r_width = 1.0
c_width = 0.5
PTP = {\
1 :[1,1] ,2: [1,8]#Row1
,3 :[2,1] ,4: [2,2]#Row... | python |
import gennav
import sensor_msgs
from gennav_ros import conversions
def transform_polygons(polygons, position):
"""Transforms polygons with respect to some position
Args:
polygons (list[list[tuple[float, float, float]]]): polygon
to be transformed
position (gennav.utils.RobotState... | python |
from __future__ import unicode_literals
import logging
import unittest
from six import StringIO
class LoggerSetupTest(unittest.TestCase):
def _stream(self):
return StringIO()
def _logger(self, logger_name, stream):
logging.getLogger().addHandler(logging.StreamHandler(stream))
return ... | python |
#!/usr/bin/env python
# Script to extract "hashes" from Monero databases.
#
# + Tested with monero-gui-v0.11.1.0 on Fedora 27.
# + Tested with monero.linux.x64.v0-9-0-0.tar.bz2 (from Jan, 2016) on Fedora 27.
#
# This software is Copyright (c) 2017, Dhiru Kholia <dhiru at openwall.com> and
# it is hereby released to th... | python |
from typing import Callable, Optional
from ._utils.frame_model import FrameType, FrameModel
_hook = Callable[[FrameModel], Optional[bool]]
class Events:
def __init__(self, ws_client):
self.__WebSocketClient = ws_client
self.__ready_executed = False
def on_any(self, func: _hook = None, frame_... | python |
import logging
from typing import Any, Dict, Type
from uuid import UUID
from slack_bolt import App, BoltContext, Ack
from teamiclink.slack.middleware import SlackMiddleware
from teamiclink.slack.store_goal import GoalStore
from slack_sdk import WebClient
LOG = logging.getLogger(__name__)
def delete_goal(
contex... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.