id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9966235 | import FWCore.ParameterSet.Config as cms
ecalPnGraphs = cms.EDAnalyzer("EcalPnGraphs",
# requested EBs
requestedEbs = cms.untracked.vstring('none'),
# length of the line centered on listPns containing the Pns you want to see
# needs to be an odd number
numPn = cms.untracked.int32(9),
fileName ... |
9966263 | class Controllable(object):
def __init__(self):
self._controller = None
@property
def controller(self):
return self._controller
@controller.setter
def controller(self, value):
self._controller = value
def reset(self):
if self._controller is not None:
... |
9966281 | import argparse
import daemon
import daemon.pidfile
import http.server
import json
import logging
import os
import pkg_resources
import socketserver
CONFIG = {}
class RequestHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path.endswith('ptg.json'):
with open(CONFIG['d... |
9966283 | import pathlib
from setuptools import find_packages, setup
CONFIGDIR = pathlib.Path.home() / ".config" / "spfy"
CONFIGDIR.mkdir(parents=True, exist_ok=True)
with open("spfy/__init__.py", "r") as f:
for line in f:
if line.startswith("__version__"):
version = line.strip().split("=")[1].strip(" '... |
9966336 | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from apostello import models
@admin.register(models.SmsOutbound)
class SmsOutboundAdmin(admin.ModelAdmin):
"""Admin class for apostello.models.SmsOutbound."""
list_display = ("content... |
9966373 | from rest_framework import serializers
from testapp.models import MySingleSignalModel
class MySingleSignalModelSerializer(serializers.ModelSerializer):
class Meta:
model = MySingleSignalModel
fields = [
'id',
'value',
]
|
9966390 | from typing import Callable, Dict, List, Tuple, Union
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.signals import setting_changed
from django.dispatch import receiver
from django.http import HttpRequest, HttpResponse
from django.utils.functional import cache... |
9966415 | class Solution:
def minCost(self, costs):
"""
:type costs: List[List[int]]
:rtype: int
"""
prev = [0] * 3
for cost in costs:
prev = [cost[i] + min(prev[:i] + prev[i + 1 :]) for i in range(3)]
return min(prev)
|
9966499 | from distutils.dir_util import copy_tree
from subprocess import call
from tempfile import mkstemp
import os
import shutil
import sys
import urllib
from firebase import firebase
# Get all of the new apks from firebase
# Run through them all
# Upload to server
def write_keys():
print 'Using production k... |
9966526 | from ._b2d import b2AABB
from .extend_math import vec2
Aabb = b2AABB
def aabb(lower_bound=None, upper_bound=None, p=None, r=None):
if lower_bound is not None and upper_bound is not None:
lb = vec2(lower_bound)
ub = vec2(upper_bound)
elif r is not None and p is not None:
p = vec2(p)
... |
9966532 | import requests
import json
from typing import Optional
token = ""
def initiate_payment(tx_ref: str, amount: float, redirect_url: str, customer_name: str,
customer_email: str, currency: Optional[str] = None, payment_options: Optional[str] = None,
title: Optional[str] = None,... |
9966538 | from fireo.fields import TextField, IDField, DateTime
from fireo.models import Model
from datetime import datetime
def test_fix_issue_63():
class UserIssue63(Model):
user_id = IDField()
name = TextField()
date_added = DateTime()
u = UserIssue63.collection.create(user_id='1',name='<NAM... |
9966545 | from django.conf import settings
from django.shortcuts import resolve_url
from django.test import TestCase
class TestHealthCheck(TestCase):
def test_status(self):
resp = self.client.get(resolve_url('healthcheck'))
self.assertEqual(200, resp.status_code)
|
9966621 | from typing import NamedTuple, Union
import numpy as np
from scipy.sparse import coo_matrix, csr_matrix
# import numpy.typing as npt
FloatDType = np.float64
IntDType = np.intp
# Requires numpy 1.21, not on conda yet...
# FloatArray = np.ndarray[FloatDType]
# IntArray = np.ndarray[IntDType]
# BoolArray = np.ndarray[... |
9966633 | class RefreshDeviceKeyOutDTO(object):
def __init__(self):
self.verifyCode = None
self.timeout = None
def getVerifyCode(self):
return self.verifyCode
def setVerifyCode(self, verifyCode):
self.verifyCode = verifyCode
def getTimeout(self):
return self.timeout
... |
9966646 | from elasticsearch import Elasticsearch, RequestsHttpConnection
from chalicelib.core import log_tools
import base64
import logging
logging.getLogger('elasticsearch').level = logging.ERROR
IN_TY = "elasticsearch"
def get_all(tenant_id):
return log_tools.get_all_by_tenant(tenant_id=tenant_id, integration=IN_TY)
... |
9966676 | import logging
import xml.dom.minidom as minidom
import hashlib, binascii
from content import read_chunked, query_params, compress, decompress
import qxml
def is_signed(req):
return 'X-ADP-Request-Digest' in req.headers
def get_query_params(req):
_, _, query = req.path.partition('?')
if query:
return query_par... |
9966690 | from allennlp.nn.module import Module
from allennlp.nn.activations import Activation
from allennlp.nn.initializers import Initializer, InitializerApplicator
from allennlp.nn.regularizers import RegularizerApplicator
|
9966729 | def compute_performance(dictionary, corpus, texts, limit, start=2, step=1, lda_type=None, mallet_path=None):
"""
Compute c_v coherence and perplexity (if applicable) for various number of topics
Parameters:
----------
dictionary : Gensim dictionary
corpus : Gensim corpus
texts : List of inp... |
9966731 | from functools import partial
from typing import Optional, Tuple, List
import numpy
from numpy.typing import ArrayLike
from scipy.ndimage import gaussian_filter
from aydin.it.classic_denoisers import _defaults
from aydin.util.crop.rep_crop import representative_crop
from aydin.util.j_invariance.j_invariance import ca... |
9966733 | from command import Command
from subcommand import Subcommand
from insulaudit.core import Link
from insulaudit.core import Session
import utils
from insulaudit import scan
from pprint import pprint
class FlowCommand(Subcommand):
"""I'm a sub command"""
name = None
def __init__(self, flow, handler, **kwds):
... |
9966747 | from .defaults import *
ALLOWED_HOSTS = ['*']
STATIC_ROOT = os.path.join(BASE_DIR, '_static')
MEDIA_ROOT = os.path.join(BASE_DIR, '_media')
DEBUG = True
EMAIL_HOST = "localhost"
EMAIL_PORT = 1025
CELERY_TASK_ALWAYS_EAGER = True
CELERY_TASK_EAGER_PROPAGATES = True
|
9966775 | class Sorts:
#This will ony work when the array has 0 to (n-1) elements
def cyclicSort(self, arr: list[int]):
i = 0
while i<len(arr):
correct = arr[i]-1
if arr[i] != arr[correct]:
arr[i], arr[correct] = arr[correct], arr[i]
else:
i += 1
if __name__ == '__main__':
s = Sorts()
# taking array inp... |
9966777 | import paddlehub as hub
senta_test = hub.Module(directory="senta_test")
print(senta_test.sentiment_classify(["这部电影太糟糕了", "这部电影太棒了"]))
|
9966788 | from threading import Thread, Event
import importlib
import atexit
from time import sleep
import Queue
from helpers import read_config
listener = None
class CallbackException(Exception):
def __init__(self, code=0, message=""):
self.code = code
self.message = message
class InputListener():
"""... |
9966805 | import numpy as np
from anonymizer.obfuscation import Obfuscator
from anonymizer.utils import Box
class TestObfuscator:
@staticmethod
def test_it_obfuscates_regions():
obfuscator = Obfuscator()
np.random.seed(42) # to avoid flaky tests
image = np.random.rand(128, 64, 3) # height, wi... |
9966806 | from webargs.flaskparser import use_args
from crime_data.extensions import DEFAULT_MAX_AGE
from flask.ext.cachecontrol import cache
from sqlalchemy import func
from crime_data.common import cdemodels, marshmallow_schemas
from crime_data.common.base import CdeResource, tuning_page
from crime_data.common.marshmallow_sch... |
9966847 | import os
os.environ['CUDA_VISIBLE_DEVICES'] = '2'
import bert
from bert import optimization
from bert import tokenization
from bert import modeling
import numpy as np
import json
import tensorflow as tf
import itertools
import collections
import re
import random
import sentencepiece as spm
from unidecode import unid... |
9966848 | import Soros
import sys
import codecs
out = sys.stdout
state = ""
output = ""
prefix = ""
params = []
for i in sys.argv:
if state != "":
if state == "prefix":
prefix = i + " "
elif state == "output":
output = i
state = ""
continue
if i == "-p":
s... |
9966872 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.salinity import salinity
def test_salinity():
"""Test module salinity.py by downloading
salinity.csv and testing shape of
extracted data h... |
9966887 | import sys, os, time
# <NAME>, <NAME> - Eurecat (c) 2019
class bcolors:
PURPLE = '\033[95m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
CYAN = '\033[96m'
ENDC = '\033[0m'
BOLD = '\033[1m'
CYAN = '\033[96m'
class AverageMeter(object):
... |
9966913 | from collections import defaultdict
import numpy as np
import skimage
import torchvision as vision
import torch
import torch.nn as nn
import torch.nn.functional as F
import multiprocessing.dummy as mp
import multiprocessing
from gym import spaces
from evkit.sensors import SensorPack
def blind(output_size, dtype=np.f... |
9966972 | import http.cookiejar, urllib.request
# 实例化cookiejar对象
cookie = http.cookiejar.CookieJar()
# 使用 HTTPCookieProcessor 构建一个 handler
handler = urllib.request.HTTPCookieProcessor(cookie)
# 构建Opener
opener = urllib.request.build_opener(handler)
# 发起请求
response = opener.open('https://www.baidu.com/')
print(cookie)
... |
9966978 | name = "redshift"
version = '2.6.49'
description = \
"""
Redshift3D Deployment Recipe
This is separated into its own 'recipe' package
so that the common files can be distributed as
a single platform package. As opposed to having
to copy over *all* binary files each time per
Houdini o... |
9966990 | from tir import Webapp
import unittest
class OGA430F(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup('SIGAADV',"15/07/2020",'T1','D MG 01 ','67')
inst.oHelper.Program('OGA450')
def test_OGA430F_CT001(self):
... |
9966991 | from talon import Module, Context, actions
from typing import Union
import re
mod = Module()
ctx_vscode = Context()
ctx_vscode.matches = r"""
app: vscode
"""
@mod.action_class
class Actions:
# Default implementation inserts snippets as normal text
def insert_snippet(snippet: Union[str, list[str]]):
... |
9966992 | import subprocess
import os
from tempfile import NamedTemporaryFile
from colorama import Fore, Back, Style
class Utility(object):
log_file = "error_log.txt"
@staticmethod
def write_exception_to_log(project_name, exception):
with open(Utility.log_file, 'a') as log:
log.write("Project ::... |
9966998 | import argparse
import dill as pickle
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.ticker import FormatStrFormatter
from nes.ensemble_selection.config import BUDGET, PLOT_EVERY
matplotlib.use("Agg")
import os
from pathlib import Path
import numpy as np
import pandas as pd
plt.rcParams['axes.grid... |
9967021 | import os
DB_HOST_PATH = "sqlite:///data/db.sqlite3"
OSRM_HOSTPORT = os.getenv("OSRM_HOSTPORT", "localhost:5000")
DEFAULT_LOG_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../logs/tmp")
DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../data")
CENTER_LATITUDE = 40.75
CENTE... |
9967037 | from abc import ABC, abstractmethod
class InputTextProcessor(ABC):
@abstractmethod
def process_initialization_statement(self, initialization_statement):
pass
@abstractmethod
def process_context_statement(self, context_statement):
pass
@abstractmethod
def process_phase_transi... |
9967043 | from jsgf import PublicRule, OptionalGrouping, Grammar, Sequence
def print_matching(grammar, speech):
matching = grammar.find_matching_rules(speech)
if not matching:
print("No rules matched '%s'." % speech)
else:
print("Rules matching '%s':" % speech)
for r in matching:
... |
9967100 | from curlylint import ast
from curlylint.check_node import CheckNode, build_tree
from curlylint.issue import Issue
NO_AUTOFOCUS = "no_autofocus"
RULE = {
"id": "no_autofocus",
"type": "accessibility",
"docs": {
"description": "Enforce autofocus is not used on inputs. Autofocusing elements can cau... |
9967157 | from typing import Any
from typing import Dict
from unittest import mock
import pytest
from task_processing.interfaces.event import Event
from task_processing.plugins.kubernetes.task_config import KubernetesTaskConfig
from tron.config.schema import ConfigSecretSource
from tron.config.schema import ConfigVolume
from t... |
9967171 | from typing import List
from guet.committers import Committers2 as Committers
from guet.committers.committer import Committer
from guet.files import FileSystem
from guet.util import project_root
from ._initials_for_project import initials_for_project
from ._set_current_committers import set_current_committers
class... |
9967203 | import rest_framework
from rest_framework.response import Response
from rest_framework import viewsets, status, generics
from rest_framework.decorators import detail_route, list_route
from yak.rest_core.utils import get_package_version
from yak.rest_social_network.models import Tag, Comment, Follow, Flag, Share, Like
f... |
9967219 | from ad_api.base import Client, sp_endpoint, fill_query_params, ApiResponse
class Profiles(Client):
"""
Profiles AD-API Client
:link:
With the Profiles.
"""
@sp_endpoint('/v2/profiles', method='GET')
def list_profiles(self, **kwargs) -> ApiResponse:
r"""
list_profiles(self... |
9967260 | from .data import load_data_from_directory
from decimal import Decimal
def test_empty() -> None:
group, cache, account, open_orders = load_data_from_directory("tests/testdata/empty")
frame = account.to_dataframe(group, open_orders, cache)
# Typescript says: 0
assert account.init_health(frame) == Dec... |
9967264 | import pandas as pd # type: ignore
from datetime import datetime
from typing import cast, Dict, List, Optional, Tuple, Union, TYPE_CHECKING
from aat.core import Event, Trade, Instrument, ExchangeType, Position
from ..base import ManagerBase
from .portfolio import Portfolio
if TYPE_CHECKING:
from aat.strategy i... |
9967299 | import logging
import sys
import json
from argparse import Namespace
from dgllife.utils import smiles_to_bigraph
from functools import partial
import pandas as pd
from utils import load_model, init_featurizers, model_saved_path, model_params_saved_path
import torch
from dgllife.data.csv_dataset import MoleculeCSVData... |
9967318 | from amadeus.client.decorator import Decorator
class GeneratedPhotos(Decorator, object):
def get(self, **params):
'''
Returns a link with a rendered image of a landscape
.. code-block:: python
amadeus.media.files.generated_photos.get(category='MOUNTAIN')
:param category:... |
9967356 | from yoyo import utils
class TestChangeParamStyle:
def test_changes_to_qmark(self):
sql = "SELECT :a, :b, :a"
assert utils.change_param_style("qmark", sql, {"a": 1, "b": 2}) == (
"SELECT ?, ?, ?",
(1, 2, 1),
)
def test_changes_to_numeric(self):
sql = "S... |
9967364 | import socket, threading, sys, ipaddress, time, os
from optparse import OptionParser
from scapy.all import *
class Port_Scanner:
def __init__(self, ip, ports):
self.ip = str(ip)
self.logfile = "squidmap.txt"
file = open(self.logfile,"w")
file.close()
self.isnetwork =... |
9967366 | import numpy as np
#Credit score range 300-850 on the basis of which you will get a loan
g = np.array([500,720,690,300,370,632,820,425,740,430,421,323,620,519,620,530,422,616])
#random initialization whether loan will be sanctioned
h = np.array([0,1,1,0,0,1,1,0,1,0,1,0,1,1,1,0,0,1])
def sigmoid(g):
return... |
9967469 | import os
from unittest import mock
from django.test import TestCase
from django_datajsonar.models import Distribution, Catalog, Node, ReadDataJsonTask
from django_datajsonar.tasks import read_datajson
from series_tiempo_ar_api.libs.indexing.indexer.distribution_indexer import DistributionIndexer
SAMPLES_DIR = os.pa... |
9967475 | from django.db import models
from django.conf import settings
from ara.db.models import MetaDataModel
class NotificationReadLog(MetaDataModel):
class Meta(MetaDataModel.Meta):
verbose_name = '알림 조회 기록'
verbose_name_plural = '알림 조회 기록 목록'
unique_together = (
('read_by', 'notifi... |
9967570 | import time
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.server_settings import ServerSettings
from tests import test_site_url, test_client_credentials
def print_server_settings(context):
"""
:type context: ClientContext
"""
is_online = ServerSettings.is_shar... |
9967652 | from django.http import HttpResponse, Http404
from django.shortcuts import render
import datetime
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.contrib.auth.views import login as loginview
from registration.backends.simple import views
from django.contrib.auth import au... |
9967670 | from django.db.models import signals
from django.dispatch import receiver
from . import models
def subscribable_changed(sender, instance, created, **kwargs):
""" handle publishing a new, or updated subscribable model.
"""
if created:
publish = sender.PUBLISH_ON_CREATE
else:
publish = ... |
9967678 | import featuretools as ft
from category_encoders import TargetEncoder as Target
from categorical_encoding.primitives import TargetEnc
class TargetEncoder():
"""Maps each categorical value to one column using target encoding.
Parameters:
cols: [str]
list of column names to encode.
"""... |
9967686 | from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_raises
from mrec.evaluation import metrics
def test_sort_metrics_by_name():
names = ['recall@10','z-score','auc','recall@5']
expected = ['auc','recall@5','recall@10','z-score']
assert_equal(expected,metrics.sort_metric... |
9967695 | from setuptools import setup, find_packages
setup(name='caimcaim',
version='0.3',
description='CAIM',
long_description='CAIM Discretization Algorithm',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language ... |
9967724 | from selenium.webdriver.support.event_firing_webdriver import EventFiringWebDriver
class WebDriverExtended(EventFiringWebDriver):
def __init__(self, driver, event_listener, config):
super().__init__(driver, event_listener)
self.base_url = config["base_url"]
def open(self):
self.get(se... |
9967728 | from __future__ import absolute_import
import rospy
from hopper_msgs.msg import ServoTelemetry, HexapodTelemetry
from dynamixel import DynamixelDriver, search_usb_2_ax_port
class HexapodBodyController(object):
def __init__(self):
super(HexapodBodyController, self).__init__()
self.telementrics_publ... |
9967729 | from storybro.models.manager import ModelManager
from storybro.models.registry import ModelRegistry
from storybro.stories.manager import StoryManager
class Config:
models_path: str = None
stories_path: str = None
grammars_path: str = None
model_registry: ModelRegistry = None
model_manager: ModelM... |
9967742 | from __future__ import absolute_import, unicode_literals
import json
import six
from django.http import HttpResponse, Http404
from django.conf import settings
from django.views import generic
from django.shortcuts import render
from .. import api, constants, matrix, settings as local_settings
class ShowTestMatrixV... |
9967748 | import psycopg2
import MySQLdb
from _mysql_exceptions import ProgrammingError as MySQLProgrammingError, OperationalError as MySQLOperationalError
from django.core.cache import cache
from .helpers import run_as_site
from raven.contrib.django.raven_compat.models import client
def create_postgres_database(database):
... |
9967758 | import tweepy
import environ
env = environ.Env()
environ.Env.read_env()
def main():
twitter_auth_keys = {
"consumer_key": env('SECRET_KEY'),
"consumer_secret": env('SECRET_KEY'),
"access_token": env('SECRET_KEY'),
"access_token_secret": env('SECRET_KEY')
}
auth = tweepy.... |
9967804 | from terra_sdk.core import Tx
# def test_deserializes_tx(load_json_examples):
# data = load_json_examples("./Tx.data.json")
# example = data["tx"]
# parsed = Tx.from_data(example).to_data()
# for key in parsed.keys():
# assert parsed[key] == example[key]
|
9967810 | import os
import json
import torch
from torchreid.models.proxyless.utils import download_url, load_url
from .nas_modules import ProxylessNASNets
from torchreid.utils.load_weights import load_weights
def proxyless_base(num_classes, loss, pretrained=True, net_config=None, net_weight=None):
assert net_config is no... |
9967815 | import discord
from discord.ext.commands import Converter
from PIL import ImageDraw, ImageFont, Image
import io, os, math
class ScoreboardFlags:
BOARD = ["--board", "-b"]
ALL = ["--all", "-a"]
class ScoreboardFlag(Converter):
async def convert(self, ctx, argument):
if argument in ScoreboardFlags.A... |
9967827 | import pandas as pd
# read input species list
species_list_file = 'data/precompiled/gl_data/aves_gl.txt'
species_list = pd.read_csv(species_list_file,sep='\t',header=None)
# define reference group
reference_group = "Aves"
reference_rank = "class"
iucn_key='01524b67f4972521acd1ded2d8b3858e7fedc7da5fd75b8bb2c5456ea18b01... |
9967844 | from gdsctools.tissues import TCGA, TCGA_GDSC1000, TCGA_2_GDSC, Tissues
def test_TCGA():
t = TCGA()
assert t['ACC'] == 'Adrenocortical Carcinoma'
def test_tcga_gdsc1000():
assert 'BLCA' in TCGA_GDSC1000
def test_TCGA_2_GDSC():
assert TCGA_2_GDSC['MB'] == 'nervous_system'
def test_Tissues():
t ... |
9967858 | from dependency_injector.wiring import inject, Provide
from loguru import logger
from nextcord.ext import commands
from novelsave.containers import Application
from novelsave.core.services.source import BaseSourceService
from .. import checks, mfmt
from ..bot import bot
@bot.command()
async def dm(ctx: commands.Cont... |
9967859 | import pytest
from django.contrib.auth.models import User
from django.contrib.messages import get_messages
from graphapi.tests.utils import populate_db
from openstates.data.models import Person
from profiles.models import Subscription, Notification
from profiles.views import PermissionException
from profiles.utils impo... |
9967863 | import marshmallow
import pytest
from aiosnow import fields
from aiosnow.query.utils import select
def test_fields_datetime_deserialize_plain_valid():
dt = fields.DateTime()
dt.name = "test_dt"
result = dt.deserialize("2020-08-26 21:01:07")
result_tz = dt.deserialize("2020-08-26T21:01:07+00:00")
... |
9967867 | name, age = "jishnu", 18
username = "jishnu2512"
print ('Hello!')
print("Name: {}\nAge: {}\nUsername: {}".format(name, age, username))
|
9967868 | import math
import time
from pprint import pprint
import pandas as pd
import hyperopt
from hyperopt import fmin, hp
from hyperopt.mongoexp import MongoTrials
from pymongo import MongoClient
from sacred_wrapper import hyperopt_objective
from hopt_sacred import hyperopt_grid, to_exp_space, objective_wrapper
import war... |
9967901 | from pathlib import Path
from typing import Dict, Optional
from snowddl.parser.abc_parser import AbstractParser
placeholder_json_schema = {
"type": "object",
"additionalProperties": {
"type": ["boolean", "number", "string"]
}
}
class PlaceholderParser(AbstractParser):
def load_blueprints(se... |
9967906 | from src import view
from model.structure import earthquake
from model.utils import plot
import cherrypy
class Earthquake:
def index(self):
pass
def response_spectrum(self, **var):
# Prepare view & model object
template = view.lookup.get_template('structure/earthquake_respon... |
9967929 | import torch
import torch.nn as nn
from utils.prep_utils import MODEL_NEURONS
class ConvBlock(nn.Module):
def __init__(self, in_depth, out_depth):
super().__init__()
self.double_conv = nn.Sequential(
nn.BatchNorm2d(in_depth),
nn.Conv2d(in_depth, out_depth, kernel_size=3, p... |
9967966 | import warnings
from typing import Optional
import numpy as np
import pandas as pd
from anndata import AnnData
from natsort import natsorted
from spatialtis_core import comb_bootstrap
from spatialtis.abc import AnalysisBase
from spatialtis.utils import NeighborsNotFoundError
from spatialtis.typing import Array
from s... |
9967969 | import cv2
import yaml
from tqdm import tqdm
import os
from dotmap import DotMap
import numpy as np
# Change the options below for each of the new submissions.
config = yaml.safe_load('''
##########################################################################
# This is the main config file for your method. Please f... |
9967983 | import os
rootdir = os.path.dirname(os.path.dirname(__file__))
os.sys.path.insert(0, rootdir)
# this brings in most of the relevant parts. It requires numpy, scipy and pybullet
import math
import random
from roman import *
def rand(max):
return (random.random()-0.5)*max
if __name__ == '__main__':
# connect t... |
9967992 | from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from users.views import finished_signup_flow
def home(request):
current_user = request.user
if not current_user.is_authenticated:
return render(request, 'login.html')
# TODO: Initiate the Twitter initial... |
9968003 | from Firefly import logging
from Firefly.const import (IS_DARK, IS_LIGHT, IS_MODE, IS_NOT_MODE, IS_NOT_TIME_RANGE, IS_TIME_RANGE)
class Conditions(object):
def __init__(self, is_dark: bool=None, is_light: bool=None, is_mode: list=None, is_not_mode: list=None, last_mode: list=None, before_time=None, after_time=None, ... |
9968059 | from rfeed import *
from .description_builder import description_builder, dict_to_html_list
def generate_rss(listing, uri):
items = []
for offer in listing.offers:
items.append(
Item(
title=offer.name, link=offer.url, description=description_builder(offer),
... |
9968070 | import numpy as np
from keras.callbacks import ModelCheckpoint
import cv2
from keras.preprocessing.image import ImageDataGenerator
from keras.layers import Dense, Conv2D, Flatten, MaxPooling2D, Dropout, Input, Activation
from keras.layers.normalization import BatchNormalization
from keras.optimizers import Adam
from ke... |
9968091 | import tensorflow as tf
# Default hyper-parameters:
serving_params = tf.contrib.training.HParams(
# Directory to load the exported model from.
export_dir='/tmp/export/ljspeech',
# Version number of the exported model to be loaded.
export_version=1,
)
|
9968126 | from EXOSIMS.Prototypes.PlanetPopulation import PlanetPopulation
import numpy as np
import astropy.units as u
class JupiterTwin(PlanetPopulation):
"""
Population of Jupiter twins (11.209 R_Earth, 317.83 M_Eearth, 1 p_Earth)
On eccentric orbits (0.7 to 1.5 AU)*5.204.
Numbers pulled from nssdc.gsfc.nasa.... |
9968130 | import setuptools
version = "0.1.29"
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="TableauScraper",
version=version,
author="<NAME>",
author_email="<EMAIL>",
description="Python library to scrape data from Tableau viz",
long_description_content_ty... |
9968146 | class Solution:
def isValid(self, S: str) -> bool:
St = []
for c in S:
if c == 'c':
if St[-2:] != ['a', 'b']:
return False
St.pop()
St.pop()
else:
St.append(c)
return not St
|
9968190 | from typing import Dict, Tuple, Type
import attr
from sqlalchemy import Column
from sqlalchemy.orm import relationship
@attr.s(auto_attribs=True)
class RawModel:
name: str
bases: Tuple[Type, ...]
namespace: Dict
def append_column(self, name: str, column: Column) -> None:
self.namespace[name]... |
9968199 | import json
from datetime import datetime
import nose.tools as nt
from mock import patch, ANY, Mock
import logging
import botocore
from xflow import utils
from xflow.aws import CloudWatchLogs, CloudWatchLogDoesNotExist, \
CloudWatchStreamDoesNotExist, \
Kinesis, KinesisStreamDoesNotExi... |
9968205 | from django.contrib.auth import get_user_model
from django.db import models
# Taken from django-fitbit, many thanks to them! Package is good, just wanted CBVs
# https://github.com/orcasgit/django-fitbit/blob/master/fitapp/models.py
USER_MODEL = get_user_model()
class UserFitbit(models.Model):
""" A user's fitb... |
9968207 | from functools import partial
from pathlib import Path
from typing import Union, Dict, Any
from .base import Source, OcvFrame
from .image import Image
from ..backend import cv
from ..exceptions import SourceError
from ..frame import AnyFrame
class Property:
"""Represents a capture video property with restriction... |
9968215 | import pytest
from odin import datastructures
class TestCaseLessStringList(object):
@pytest.mark.parametrize('needle haystack'.split(), (
('foo', ['foo']),
('FOO', ['foo']),
('foo', ['FOO']),
('Foo', ['fOO']),
('Foo', ['foo', 'bar']),
))
def test_contains__true(sel... |
9968217 | import os
import pickle
import torch
from tqdm import tqdm
import pandas as pd
from PIL import Image
from torchvision import transforms
from torchvision.datasets import ImageFolder
from torch.utils.data import DataLoader, Dataset
from padim import PaDiM, PaDiMShared
from padim.datasets import LimitedDataset
class T... |
9968220 | import bpy
import nodeitems_utils
from . import nodes
class ElementsNodeCategory(nodeitems_utils.NodeCategory):
@classmethod
def poll(cls, context):
return context.space_data.tree_type == 'elements_node_tree'
# get categories data
def get_categs_data():
# node categories data
data = {}
... |
9968225 | from apprentice.explain.explanation import Explanation
from apprentice.working_memory.skills_test import AdditionEngine, EmptyAdditionEngine
from apprentice.working_memory.representation import Sai
from apprentice.working_memory import ExpertaWorkingMemory
import inspect
from experta import Fact
def old_test_compile_... |
9968226 | from ploomber.io import serializer, unserializer
@serializer(fallback='joblib', defaults=['.json', '.txt'], unpack=True)
def my_serializer(obj, product):
pass
@unserializer(fallback='joblib', defaults=['.json', '.txt'], unpack=True)
def my_unserializer(product):
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.