content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import stiefo
#stiefo.render_screen(["2-", "aus", "bei", "bei t a g", "pro", "pro z e nt"])
#stiefo.render_screen(["2- t", "2- z", "aus", "mit g e b", "der", "trans p o t", "die"])
#stiefo.render_screen(["der", "man", "ist", "nicht", "3b e0", "w e@ lich", "f a", "f... | python |
import logging
from dht.node import SelfNode
from dht.settings import BUCKET_SIZE, BUCKET_REPLACEMENT_CACHE_SIZE
class BucketHasSelfException(Exception):
pass
class NodeNotFoundException(Exception):
pass
class NodeAlreadyAddedException(Exception):
pass
class BucketIsFullException(Exception):
pa... | python |
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import argparse
import urllib.parse as urlparse
from osim.env import RunEnv
import numpy as np
from utils import Scaler
import multiprocessing
import pickle
PORT_NUMBER = 8018
def mp_test(s):
p = multiprocessing.Pool(2)
tras = p.map(run_... | python |
#!/usr/bin/env python
# coding: utf-8
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
s = pd.Series(np.random.normal(10, 8, 20))
s.plot(style='ko-', alpha=0.4, label='Series plotting')
plt.legend()
plt.savefig('pandasplot.png')
| python |
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
import numpy as np
import popart
import popart._internal.ir as _ir
import pytest
def test_tensor_type_creation():
""" Test that we can create a popart._internal.ir.TensorType enum. """
_ir.TensorType.ActGrad
_ir.TensorType.Const
_ir.TensorType.S... | python |
SPOTIFY_USERS = {
'<user_name_1>': {
'client_id': '<client_id>',
'client_secret': '<client_secret>',
'redirect_uri': '<redirect_uri>',
'user_name': '<user_name>',
},
'<user_name_2>': {
'client_id': '<client_id>',
'client_secret': '<client_secret>',
're... | python |
from sisense.resource import Resource
class Folder(Resource):
def get(self, oid: str) -> Resource:
"""
Get a specific folder.
:param oid: (str) Folder's ID.
:return: (Folder)
"""
content = self._api.get(f'folders/{oid}')
return Folder(self._api, content)
... | python |
from clearskies.secrets.additional_configs import MySQLConnectionDynamicProducerViaSSHCertBastion as Base
from pathlib import Path
import socket
import subprocess
import os
import time
class MySQLConnectionDynamicProducerViaSSHCertBastion(Base):
_config = None
_boto3 = None
def __init__(
self,
... | python |
"""
Functions and classes for aligning two lists using dynamic programming.
The algorithm is based on on a slight variation of the method given at:
http://www.avatar.se/molbioinfo2001/dynprog/adv_dynamic.html. By default NIST
insertion, deletion and substitution penalties are used.
Author: Herman Kamper
Contact: kamp... | python |
from __future__ import absolute_import, division, print_function
import pkgutil
import numpy as np
import glue
def test_histogram_data():
data = glue.core.data.Data(label="Test Data")
comp_a = glue.core.data.Component(np.random.uniform(size=500))
comp_b = glue.core.data.Component(np.random.normal(size=... | python |
import jax.numpy as jnp
from matplotlib import pyplot as plt
from numpy.linalg import inv
from jsl.sent.run import train
from jsl.sent.agents.kalman_filter import KalmanFilterReg
from jsl.sent.environments.base import make_matlab_demo_environment
def posterior_lreg(X, y, R, mu0, Sigma0):
Sn_bayes_inv = inv(Sigm... | python |
import os
from datetime import datetime
import tensorflow as tf
from feature_extractor import MobileNet, Resnet, Vgg16
from modules import atrous_spatial_pyramid_pooling
class DeepLab(object):
def __init__(self, base_architecture, training=True, num_classes=21, ignore_label=255, batch_norm_momentum=0.9997, pre... | python |
import zmq
from threading import Thread
import queue
from client_login import LoginClient
from enums import Host, Intervals
import time
class Client:
def __init__(self, target):
self.context = zmq.Context.instance()
self.username = None
self.queue = queue.Queue()
self.message = Non... | python |
import serial
import bk169X.sim as _bksim
class PSCommError(Exception):
pass
class PowerSupply(object):
def __init__(
self,
device,
baud=9600,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
... | python |
#!/home/sunnymarkliu/software/miniconda2/bin/python
# _*_ coding: utf-8 _*_
"""
VGG net implementation example using TensorFlow library.
This example is using the MNIST database of handwritten digits
VGG net Paper: https://arxiv.org/pdf/1409.1556.pdf
Mnist Dataset: http://yann.lecun.com/exdb/mnist/
@author: MarkLiu
... | python |
from __future__ import absolute_import
HORIZON_CONFIG = {
# Allow for ordering dashboards; list or tuple if provided.
'dashboards': ["module", "portal"],
# Name of a default dashboard; defaults to first alphabetically if None
'default_dashboard': "portal",
# Default redirect url for users' home
... | python |
#Team Zephyr
#necessary libraries to be imported
import nmap
import netifaces
from nmap import PortScanner
import socket
import multiprocessing
import subprocess
import os
import threading
import time
import re
import pdb
import numpy
HOST_IP = [] #contains the ip addresses of the devices connected onto the netw... | python |
#!/usr/bin/python
# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Test the lint module."""
import collections
import os
import sys
sys.path.insert(0, os.path.abspath('%s/../../..' % os.path.dir... | python |
from yunionclient.common import base
class Federatedrolebinding(base.ResourceBase):
pass
class FederatedrolebindingManager(base.StandaloneManager):
resource_class = Federatedrolebinding
keyword = 'federatedrolebinding'
keyword_plural = 'federatedrolebindings'
_columns = ["Federatednamespace_Id"]
... | python |
"""Main module."""
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import pandas as pd
from sentimentbot.feeds import FinvizNewsFeed
class SentimentAnalyzer(object):
""" wrapper for the sentiment analyzer """
_analyzer = SentimentIntensityAnalyzer()
def __init__(self, ticker):
se... | python |
from __future__ import absolute_import
import os, sys
import imp
class docs(object):
def __init__(self, show=True, update=False):
"""
Class for viewing and building documentation
Parameters
----------
show : bool
If True, show docs after rebuilding (default: T... | python |
import time
from datetime import timedelta, datetime, timezone
from decimal import Decimal, localcontext, DefaultContext
import aiohttp
import asyncio
import signal
from aiokraken.model.asset import Asset
from aiokraken import markets, balance, ohlc, OHLC
from aiokraken.utils import get_kraken_logger, get_nonce
fro... | python |
from django.http.response import JsonResponse
from core.apps.basket.basket import Basket
from .models import Order, OrderItem
def add(request):
basket = Basket(request)
if request.POST.get('action') == 'post':
order_key = request.POST.get('order_key')
user_id = request.user.id
baske... | python |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
heap, res, j = [], [], 0
while head:
res.append(0)
while heap and hea... | python |
import psutil
import schedule
import time
from userClass import *
class LeagueScheduler:
#Setters
def set_processName(self, processName):
self.__processName = processName
def __set_inGame(self, inGame):
self.__inGame = inGame
#Getters
def get_processName(self):
return self.__processName
def get_inGam... | python |
"""Backend agnostic array operations.
"""
import itertools
import numpy
from autoray import do, reshape, transpose, dag, infer_backend, get_dtype_name
from ..core import njit, qarray
from ..utils import compose
from ..linalg.base_linalg import norm_fro_dense
def asarray(array):
"""Maybe convert data for a tenso... | python |
"""
The wntr.network package contains methods to define a water network model,
network controls, and graph representation of the network.
"""
from wntr.network.model import WaterNetworkModel, Node, Link, Junction, Reservoir, Tank, Pipe, Pump, Energy, Valve, Curve, LinkStatus, WaterNetworkOptions, LinkType, NodeType
fro... | python |
import cv2
img = cv2.imread("dog.jpg")
cv2.imshow("dog", img)
cv2.waitKey()
cv2.destroyAllWindows()
| python |
#-*- coding: utf-8 -*-
# https://github.com/Kodi-vStream/venom-xbmc-addons
#test film strem vk 1er page dark higlands & tous ces enfants m'appartiennent
from resources.hosters.hoster import iHoster
from resources.lib.handler.requestHandler import cRequestHandler
from resources.lib.parser import cParser
import re
UA = ... | python |
__author__ = 'Richard Lincoln, r.w.lincoln@gmail.com'
""" This example demonstrates how to use the discrete Roth-Erev reinforcement
learning algorithms to learn the n-armed bandit task. """
import pylab
import scipy
from pybrain.rl.agents import LearningAgent
from pybrain.rl.explorers import BoltzmannExplorer #@Unus... | python |
import abc
from enum import Enum as EnumCLS
from typing import Any, List, Optional, Tuple, Type
import pendulum
from starlette.requests import Request
from mongoengine import Document
from mongoengine import QuerySet
from fastapi_admin import constants
from fastapi_admin.widgets.inputs import Input
class Filter(Inp... | python |
from itertools import chain
from functools import lru_cache
import abc
import collections
from schema import Schema
from experta.pattern import Bindable
from experta.utils import freeze, unfreeze
from experta.conditionalelement import OperableCE
from experta.conditionalelement import ConditionalElement
class BaseFi... | python |
from tensorflow.keras.models import Sequential
import tensorflow.keras.layers as layers
import numpy as np
from os.path import join
import os
from invoke.context import Context
import unittest
import templates
import ennclave_inference as ennclave
import config as cfg
def common(backend: str):
target_dir = join(... | python |
import numpy as np
import os
import time
from . import util
from tensorboardX import SummaryWriter
import torch
class TBVisualizer:
def __init__(self, opt):
self._opt = opt
self._save_path = os.path.join(opt.checkpoints_dir, opt.name)
self._log_path = os.path.join(self._save_path, 'loss_l... | python |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
import pandas as pd
from funcs import shortpath
def print_inp(inp_file_name):
inp_file_full = pd.read_csv(inp_file_name, sep='\t', header=1, dtype=str)
for j in range(len(inp_file_full)):
inp_file = inp_file_full.loc[[j], :]
... | python |
format = "%(asctime)s - %(levelname)s - %(name)s - %(message)s"
minimal_format = "%(message)s"
def _get_formatter_and_handler(use_minimal_format: bool = False):
logging_dict = {
"version": 1,
"disable_existing_loggers": True,
"formatters": {
"colored": {
"()": "... | python |
import argparse
import json
import os
import shutil
import logging
from weed_annotator.semantic_segmentation import utils
from weed_annotator.semantic_segmentation.train import train
from weed_annotator.semantic_segmentation.inference import inference
from weed_annotator.post_processing.post_process_masks import post... | python |
"""
This module contains helper functions.
The main purpose is to remove clutter in the main
file
"""
from __future__ import print_function
import argparse
import sys
import os
import logging
import copy
import subprocess
from operator import attrgetter
from string import Formatter
try:
# Python 3
import _str... | python |
"""
Use to populate:
from crs.populate_crs_table import CrsFromApi
crs_api = CrsFromApi()
crs_api.populate()
"""
import re
import math
from bills.models import Bill
from crs.scrapers.everycrsreport_com import EveryCrsReport
# Bill's types {'sres', 'hjres', 'hconres', 's', 'hres', 'sjres', 'hr', 'sconres'}
BILL_NUMBER... | python |
import os
import numpy as np
import pandas as pd
from trackml.dataset import load_event
from trackml.score import score_event
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import DBSCAN
class Clusterer(object):
def __init__(self, eps):
self.eps = eps
def _preprocess(self, h... | python |
"""
This module encapsulates QCoDeS database: its schema, structure, convenient
and relevant queries, wrapping around :mod:`sqlite3`, etc.
The dependency structure of the sub-modules is the following:
::
.connection .settings
/ | \ |
/ | \ |
/ |... | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# vim: fenc=utf-8
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
#
"""
File name: constants.py
Author: dhilipsiva <dhilipsiva@gmail.com>
Date created: 2016-11-20
"""
class QuestionType(object):
UNKNOWN = -1
MULTIPLE_CHOICE = 0
CHOICE = 1
BOOLE... | python |
"""
author:xing xiangrui
test os.system()
"""
import os
os.chdir("mAP/")
#os.system("cd mAP/")
os.system("python main.py -na") | python |
'''
Author : ZHP
Date : 2022-04-12 16:00:40
LastEditors : ZHP
LastEditTime : 2022-04-12 17:01:01
FilePath : /models/PointFormer/similarity.py
Description :
Copyright 2022 ZHP, All Rights Reserved.
2022-04-12 16:00:40
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
import sys... | python |
import re
import pytest
from perl.translator import translate_string
from perl.utils import re_match, reset_vars
@pytest.fixture
def _globals():
return {"re": re, "__perl__re_match": re_match, "__perl__reset_vars": reset_vars}
def test_match__value_present__returns_true(_globals):
ldict = {"var": "one foo... | python |
# Authors: Stephane Gaiffas <stephane.gaiffas@gmail.com>
# License: BSD 3 clause
"""This modules introduces the Dataset class allowing to store a binned features matrix.
It uses internally a bitarray to save the values of the features in a memory efficient
fashion. It exploits the fact that any columns j of the featu... | python |
import numpy as np
from sklearn.metrics.pairwise import pairwise_distances
try:
from bottleneck import argpartsort
except ImportError:
try:
# Added in version 1.8, which is pretty new.
# Sadly, it's still slower than bottleneck's version.
argpartsort = np.argpartition
except AttributeError:
argpa... | python |
#!/usr/bin/env python3
#-----------------------------------------------------------------------------
# This file is part of the rogue_example software. It is subject to
# the license terms in the LICENSE.txt file found in the top-level directory
# of this distribution and at:
# https://confluence.slac.stanford.e... | python |
# Generated by Django 2.2 on 2019-05-18 19:06
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="CIPRSRecord",
fields=[... | python |
retrieve = [
{"scenario":"Patient Exists","patient":"9000000009", "response":{"address":[{"extension":[{"extension":[{"url":"type","valueCoding":{"code":"PAF","system":"https://fhir.nhs.uk/R4/CodeSystem/UKCore-AddressKeyType"}},{"url":"value","valueString":"12345678"}],"url":"https://fhir.nhs.uk/R4/StructureDefinit... | python |
from django.contrib import admin
from . models import Ads
class AdsAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
admin.site.register(Ads, AdsAdmin)
| python |
#write import statement for Die class
from src.homework.homework9.die import Die
'''
Create a Player class.
'''
class Player:
def __init__(self):
'''
Constructor method creates two Die attributes die1 and die2
'''
self.die1 = Die()
self.die2 = Die()
def roll_doubles... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This is needed as multiprocessing shouldn't include nsz
# as it won't be able to optain __main__.__file__ and so crash inside Keys.py
if __name__ == '__main__':
import sys
if sys.hexversion < 0x03060000:
raise ImportError("NSZ requires at least Python 3.6!\nCurrent ... | python |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# 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 ... | python |
from datetime import datetime
from unittest import mock
import dateutil.relativedelta
from carbonserver.api.infra.repositories.repository_projects import SqlAlchemyRepository
from carbonserver.api.usecases.project.project_sum import ProjectSumsUsecase
PROJECT_ID = "e60afa92-17b7-4720-91a0-1ae91e409ba1"
END_DATE = da... | python |
# -*- coding: utf-8 -*-
'''
Created on 2017-6-22
@author: hshl.ltd
'''
from __future__ import absolute_import, unicode_literals
import warnings
from sqlalchemy import orm
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from django.conf import settings
fr... | python |
import os
import requests
from dotenv import load_dotenv
dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
load_dotenv(dotenv_path)
# how to generate URL https://www.youtube.com/watch?v=lEQ68HhpO4g
INCOMING_WEBHOOKS_ACCESS_URL=os.getenv("INCOMING_WEBHOOKS_ACCESS_URL")
def send_message(post_data, api_u... | python |
import os
import sys
import random
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn.functional as F
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torchvision.utils
import imgaug as ia
from torch.utils.data import DataLoader,Dataset
from torch.... | python |
from django.http import Http404
from django.test.testcases import TestCase
from corehq.apps.app_manager.models import (
AdvancedModule,
Application,
BuildProfile,
GlobalAppConfig,
LatestEnabledBuildProfiles,
Module,
)
from corehq.apps.app_manager.views.utils import get_default_followup_form_xml... | python |
# Gradient Norm Scaling/Clipping
from keras import optimizers
# configure sgd with gradient norm scaling
# i.e. changing the derivatives of the loss function to have a given vector norm when
# the L2 vector norm (sum of the squared values) of the gradient vector exceeds
# a threshold value.
opt = optimizers.SGD(lr=0.0... | python |
class DEQue:
__slots__ = '_length', '_data'
def __init__(self):
self._length = 0
self._data = []
def __len__(self):
return self._length
def is_empty(self):
return len(self) == 0
def first(self):
if self.is_empty():
print('DEQue is em... | python |
from tcprecord import TCPRecord, TCPRecordStream
from httprecord import HTTPRecordStream
from tcpsession import TCPSession, tcp_flags, SeqException
from httpsession import parse_http_streams, HTTPParsingError, HTTPResponse, HTTPRequest
from errors import *
import sys
import printing
from printing import print_tcp_sess... | python |
from .fid import FIDScore
| python |
# Copyright 2016 Ifwe 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 writing, so... | python |
"""
A file just to hold the version number, allows automated version increasing.
"""
SEMANTIC = '0.1.4-SNAPSHOT'
BUILD_TIME = 'UNKNOWN'
try:
with open('build-time.txt') as f:
CONTENTS = f.readline().rstrip()
if CONTENTS:
BUILD_TIME = CONTENTS
except IOError:
pass
| python |
import unittest
from iterable_collections import collect
class TestMap(unittest.TestCase):
def test_list(self):
c = collect(list(range(10))).map(lambda x: x + 1)
self.assertEqual(c.list(), list(map(lambda x: x + 1, list(range(10)))))
def test_lists(self):
c = collect(list(range(10))... | python |
# Copyright 2016 Joel Dunham
#
# 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 writi... | python |
# Software License Agreement (BSD License)
#
# Copyright (c) 2018, Fraunhofer FKIE/CMS, Alexander Tiderko
# 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 mu... | python |
# Generated by Django 3.0.2 on 2021-05-11 11:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('banks', '0002_bankcode_otp_enabled'),
('loans', '0021_loanrequests'),
]
operations = [
migrations.C... | python |
#!/usr/bin/env python3
from argparse import ArgumentParser, FileType
from collections import OrderedDict
from datetime import datetime
import logging
from json import dumps
from sys import stdout
from time import sleep
from coloredlogs import install as coloredlogs_install
from ssnapshot.ssnapshot import (
creat... | python |
import itk
import numpy as np
from segmantic.prepro import core
from segmantic.prepro.core import make_image
def test_extract_slices(labelfield: core.Image3) -> None:
slices_xy = core.extract_slices(labelfield, axis=2)
assert slices_xy[0].GetSpacing()[0] == labelfield.GetSpacing()[0]
assert slices_xy[0... | python |
"""
Fetch dependencies and build a Windows wheel
============================================
This script depends on pycairo being installed to provide cairo.dll; cairo.dll
must have been built with FreeType support.
The cairo headers (and their dependencies) are fetched from the Arch Linux
repositories (the official... | python |
#!/usr/bin/env python3
# encoding: utf-8
"""
This module contains unit tests for the arc.main module
"""
import os
import shutil
import unittest
from arc.common import ARC_PATH
from arc.exceptions import InputError
from arc.imports import settings
from arc.main import ARC, StatmechEnum, process_adaptive_levels
from ... | python |
b = 1
for i in range(100000):
b += i * b
print(b)
| python |
import sys, os, math, random, time, zlib, secrets, threading, time, asyncio
async def say_after(delay, what):
await asyncio.sleep(delay)
return what
async def main():
taskvec=[]
for i in range(10):
taskvec.append(asyncio.create_task(say_after(i,str(i))))
print(f"started at {time.strftim... | python |
# Copyright 2021 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... | python |
from django.urls import reverse
from rest_framework import status
from django.test import TestCase
from .models import CustomUser
from .serializers import UserDetailsSerializer
from rest_framework.test import APIClient
REGISTRATION_URL = reverse('rest_register')
LOGIN_URL = reverse('rest_login')
PASSWORD_CHANGE_URL = ... | python |
print("Please give termination parameter as zero to proceed with number of iterations.")
x = list()
x1, d, e = map(float, input(
"Enter initial point, delta and termination parameter: ").split())
expr = input("Enter expression for x: ")
print("Please give no. of iterations as considerably a high number to check wit... | python |
from bs4 import BeautifulSoup
from faker import Faker
import requests
class faceFarm():
def __init__(self) -> None:
super(faceFarm, self).__init__()
self.requests = requests.Session()
pass
def request(self, method, url, **kwargs):
try:
return self.requests.request(... | python |
var1 = int(input('Digite um número: '))
print('Analizando o valor {}, seu antecessor é o {} e o seu sucessor é {}'.format(var1, var1-1, var1+1))
| python |
import pathlib
import aiosql
queries = aiosql.from_path(pathlib.Path(__file__).parent / "sql", "asyncpg")
| python |
dollars=eval(input("Enter in a value of Dollars:"))
def main():
euros=dollars*0.8007
euros=round(euros,2)
print("That is exactly",euros,"euros.")
main() | python |
import logging
from functools import partial
from typing import TYPE_CHECKING, Optional
from magicgui.widgets import create_widget
from napari.qt.threading import thread_worker
from napari_plugin_engine import napari_hook_implementation
from qtpy.QtCore import QEvent, Qt
from qtpy.QtWidgets import (
QCheckBox,
... | python |
"""Methods for projecting a feature space to lower dimensionality."""
from .factory import create_projector, IDENTIFIERS, DEFAULT_IDENTIFIER # noqa: F401
from .projector import Projector # noqa: F401
| python |
import numpy as np
from sklearn.metrics import pairwise_distances
from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances, haversine_distances, chi2_kernel, \
manhattan_distances
class Similarity(object):
"""
Simple kNN class
"""
def __init__(self, data, user_profile_matrix, ... | python |
from enum import Enum
from typing import Optional, Sequence
from PyQt5 import QtCore, QtWidgets
from electroncash.address import Address, AddressError
from electroncash.consolidate import (
MAX_STANDARD_TX_SIZE,
MAX_TX_SIZE,
AddressConsolidator,
)
from electroncash.constants import PROJECT_NAME, XEC
from ... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# データセットの交差検証
import pandas as pd
import numpy as np
import dataclasses
from collections import defaultdict
from .utils.folder import folder_create
from tqdm import tqdm
@dataclasses.dataclass
class Stratified_group_k_fold:
"""
データをグループ層化K分割すると... | python |
import numpy as np
from tqdm import tqdm
class PaddingInputExample(object):
"""Fake example so the num input examples is a multiple of the batch size.
When running eval/predict on the TPU, we need to pad the number of examples
to be a multiple of the batch size, because the TPU requires a fixed batch
size. T... | python |
from typing import List
import metagrad.module as nn
from examples.feedforward import load_dataset
from metagrad.dataloader import DataLoader
from metagrad.dataset import TensorDataset
from metagrad.functions import sigmoid
from metagrad.loss import BCELoss
from metagrad.optim import SGD
from metagrad.paramater import... | python |
from functools import wraps
from ..exceptions import BeeSQLError
def primary_keyword(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
if not self.table:
raise BeeSQLError('No table selected. Use Query.on to select a table first')
statement = func(self, *args, **kwargs)
... | python |
"""
Relationship pseudo-model.
"""
class Relationship:
def __init__(self, start_id, end_id, type, properties):
"""
A relationship (edge) in a property graph view of data.
:param {str} start_id: unique id of the 'from' node in the graph this relationship is associated with
:param... | python |
# Number of Islands
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if not any(grid): return 0
m, n = len(grid), len(grid[0])
count = 0
for i in range(m):
for j in range(n):
... | python |
from parameterized import parameterized
from combinatrix.testintegration import load_parameter_sets
from doajtest.helpers import DoajTestCase
from doajtest.fixtures import JournalFixtureFactory, ArticleFixtureFactory
from doajtest.mocks.store import StoreMockFactory
from doajtest.mocks.model_Cache import ModelCacheMoc... | python |
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/', methods=['GET'])
def hello_world():
#return 'Hello, World!'
response = ""
term = request.args['term']
if term:
items = [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby", "perl", "ocaml", "haskell", "... | python |
"""Flsqls module."""
from pineboolib.core import decorators
from pineboolib.core.utils import utils_base
from pineboolib.application.metadata import pntablemetadata
from pineboolib import logging
from pineboolib.fllegacy import flutil
from pineboolib.interfaces import isqldriver
from sqlalchemy.orm import sessionm... | python |
"""
Copyright 2021 Gabriele Pisciotta - ga.pisciotta@gmail.com
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTH... | python |
import re
from .models import Profile, Link
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.utils.module_loading import import_string
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.models import User
from django.contrib.auth impo... | python |
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
import os
from pathlib import Path
from subprocess import run
import nltk
def rebuild_custom_ops():
"""The objective of this script is to:
1.) Delete the existing custom ops if it exists
2.) Perform the make command
3.) Validate a custom_ops.s... | python |
from tortoise import Tortoise
from tortoise.contrib import test
from tortoise.exceptions import OperationalError, ParamsError
from tortoise.tests.testmodels import Event, EventTwo, TeamTwo, Tournament
from tortoise.transactions import in_transaction, start_transaction
class TestTwoDatabases(test.SimpleTestCase):
... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.