filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_26734 | # Based loosely on the code written by folks at Wheaton College, including:
# https://github.com/goodmanj/domecontrol
import time
from panoptes.pocs.dome import abstract_serial_dome
class Protocol:
# Status codes, produced when not responding to an input. They are oriented towards
# reporting whether the tw... |
the-stack_106_26737 | import os
import ycm_core
# These are the compilation flags that will be used in case there's no
# compilation database set (by default, one is not set).
# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR.
flags = [
'-Wall',
'-Wextra',
'-Werror',
'-Wno-long-long',
'-Wno-variadic-macros',
'-D... |
the-stack_106_26738 | #
# @lc app=leetcode id=79 lang=python3
#
# [79] Word Search
#
from typing import List
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
self.board = board
self.visted = set() # 记录已经检测过的点
# 遍历整个字母表
for i in range(len(board)):
for j in range(l... |
the-stack_106_26739 | #! /usr/bin/env python2
import numpy as np
from matplotlib import pyplot as plt
import lmeds
a1 = -5
a2 = 0.2
x_ = np.random.randn(100,1)*10
y_ = a1 * x_ + a2
x = x_ + np.random.rand(100,1) * 5 - 1
y = y_ + np.random.rand(100,1) * 5 - 1
A = np.c_[x, np.ones_like(x)]
b = y.copy()
b[-48:] *= -1
model_lstsq = np.li... |
the-stack_106_26740 | # Source: https://github.com/python/pyperformance
# License: MIT
# create chaosgame-like fractals
# Copyright (C) 2005 Carl Friedrich Bolz
import math
import random
class GVector(object):
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def Mag(self):
ret... |
the-stack_106_26743 | import asyncio
import logging
import io
import json
import pathlib
import shutil
import time
import unittest.mock as mock
import zipfile
import pytest
from asynctest import CoroutineMock
import api as service
import wqdss.processing
import wqdss.model_registry
import model_registry_api
logging.basicConfig(level=logg... |
the-stack_106_26744 | # set in mathematics is a collection of unique elements.
# set arrays should only be 1-d arrays.
import numpy as np
x1 = np.array([1, 1, 1, 3, 4, 4, 6, 6, 8, 4, 3, 5, 7, 3, 2, 5, 6])
x2 = np.unique(x1) # finding unique elements from set of array
print(x2)
x3 = np.array([1, 1, 1, 3, 4, 4, 6, 6])
x4 ... |
the-stack_106_26745 | #!/usr/bin/env python
import os
from setuptools import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(... |
the-stack_106_26746 | from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Selected(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "scattermapbox"
_path_str = "scattermapbox.selected"
_valid_props = {"marker"}
# marke... |
the-stack_106_26748 | import numpy as np
import gd
X = np.array([[2, 0], [0, 1], [0, 0]])
y = np.array([[3], [2], [2]])
def fp(w):
return 2 * X.T @ (X @ w - y)
stepsize = 0.1
maxiter = 1000000
w0 = np.array([[0.0], [0.0]])
w_traces = gd.gd_const_ss(fp, w0, stepsize=stepsize, maxiter=maxiter)
print(
f'stepsize={stepsize}, numb... |
the-stack_106_26752 | import numpy as np
import os
from mpi4py import MPI
from mpi4py.MPI import COMM_WORLD as comm
import h5py
import glob
import dolfin as df
from surfaise.common.io import makedirs_safe, remove_safe, load_parameters
from surfaise.common.cmd import (
info_warning, info_split, info_on_red, info,
mpi_is_root, mpi_ba... |
the-stack_106_26753 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# erode.py -- a script to simulate erosion of height fields
# (c) 2014 Michel J. Anders (varkenvarken)
# with some modifications by Ian Huish (nerk)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public Licen... |
the-stack_106_26755 | # Exercise 1 (week1) :: Somu :: 22-01-2018
# Adapted from: Ian McLoughlin 's Source code
# A program that displays Fibonacci numbers.
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
# Test t... |
the-stack_106_26756 | # Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the 'license' file acc... |
the-stack_106_26757 | # -*- coding: utf-8 -*-
# TensorFlow Production Example (Training)
#----------------------------------
#
# We pull together everything and create an example
# of best tensorflow production tips
#
# The example we will productionalize is the spam/ham RNN
# from
import os
import re
import io
import requests
impor... |
the-stack_106_26758 | #!/usr/bin/python3
import argparse
import os
import json
import shutil
def loadIOC(filename):
conf = {}
with open(filename) as f:
while True:
line = f.readline().strip()
if not line:
break
if line[0] == '#':
continue
vals ... |
the-stack_106_26760 | #!/usr/bin/env python
import matplotlib
import numpy as np
import wx
import copy
import os
import pmagpy.pmag as pmag
import pmagpy.ipmag as ipmag
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanvas
from matplotlib.backends.... |
the-stack_106_26762 | import os
import pytest
import sys
import ray
import pathlib
import json
import time
import subprocess
from dataclasses import asdict
from pathlib import Path
from jsonschema import validate
import ray._private.usage.usage_lib as ray_usage_lib
import ray._private.usage.usage_constants as usage_constants
from ray._pri... |
the-stack_106_26764 | from multiprocessing import cpu_count
SEED = 777
TEMP_DIRECTORY = "temp/data"
RESULT_FILE_DEV = "result_dev.tsv"
RESULT_FILE_TEST = "result_test.tsv"
SUBMISSION_FILE = "predictions.txt"
RESULT_IMAGE = "result.jpg"
GOOGLE_DRIVE = False
DRIVE_FILE_ID = None
MODEL_TYPE = "mt5"
MODEL_NAME = "google/mt5-base"
quest5_confi... |
the-stack_106_26766 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from pant... |
the-stack_106_26768 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Transformer decoder implementations.
"""
from __future__ import annotations
from typing import Dict, Optional, Tuple... |
the-stack_106_26769 | #!/usr/bin/env python
from __future__ import print_function
import sys
import os
import struct
try:
import usocket as socket
except ImportError:
import socket
import websocket_helper
# Define to 1 to use builtin "websocket" module of MicroPython
USE_BUILTIN_WEBSOCKET = 0
# Treat this remote directory as a root... |
the-stack_106_26770 | # -*- coding: utf-8 -*-
#
# Copyright 2020. Huawei Technologies Co., Ltd. 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.... |
the-stack_106_26771 | import cv2
import numpy as np
import time, imutils
import math
import pydirectinput
time_for_camera_warmup = 3
min_contour_area = 2000
cap = cv2.VideoCapture(0)
time.sleep(time_for_camera_warmup)
try:
while True:
counter = 0
try:
_, frame = cap.read()
# ROI where h... |
the-stack_106_26772 | """Core visualization operations."""
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Eric Larson <larson.eric.d@gmail.com>
# Joan Massich <mailsik@gmail.com>
# Guillaume Favelier <guillaume.favelier@gmail.com>
#
# License: Simplified BSD
import sys
import os
from contextlib im... |
the-stack_106_26773 | import requests
from pkg_resources import parse_version
def update_pypi_source(server: str) -> bool:
# Gets the latest version on PyPi accompanied by a source distribution
url = server + '/cvxpy/json'
r = requests.get(url)
if r.ok:
data = r.json()
releases = data["releases"]
ve... |
the-stack_106_26774 | #!/usr/bin/python
#
# Copyright 2010 Google Inc. 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 ... |
the-stack_106_26775 | # %%
# VScodeで入力をテキストから読み込んで標準入力に渡す
import sys
import os
f=open(r'.\chapter_2\C_input.txt', 'r', encoding="utf-8")
# inputをフルパスで指定
# win10でファイルを作るとs-jisで保存されるため、読み込みをutf-8へエンコードする必要あり
# VScodeでinput file開くとutf8になってるんだけど中身は結局s-jisになっているらしい
sys.stdin=f
#
# 入力スニペット
# num = int(input())
# num_list = [int(item) for item in... |
the-stack_106_26777 | # petname: library for generating human-readable, random names
# for objects (e.g. hostnames, containers, blobs)
#
# Copyright 2014 Dustin Kirkland <dustin.kirkland@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lice... |
the-stack_106_26778 | #!/usr/bin/env python
# -*- mode: python; encoding: utf-8 -*-
"""This modules contains tests for VFS API handlers."""
import StringIO
import zipfile
from grr.gui import api_test_lib
from grr.gui.api_plugins import vfs as vfs_plugin
from grr.lib import access_control
from grr.lib import action_mocks
from grr.lib im... |
the-stack_106_26779 | import torch
import torch.nn as nn
import torch.optim as optim
from random import random
import random
import numpy as np
import os, time, copy,sys
def pick_best_model_acc(model, best_model ,epoch, v_acc, best_acc, checkpoint_folder, model_name="a"):
if v_acc > best_acc:
best_acc = v_acc
best_mod... |
the-stack_106_26781 | # encoding: utf-8
"""
@author: xingyu liao
@contact: sherlockliao01@gmail.com
"""
import argparse
import glob
import os
import sys
import cv2
import numpy as np
# import tqdm
sys.path.append("/home/zsy/runtimelib-tensorrt-tiny/build")
import pytrt
def get_parser():
parser = argparse.ArgumentParser(description... |
the-stack_106_26782 | import argparse
import torch
import torch.optim as optim
from painter import *
# settings
parser = argparse.ArgumentParser(description="Neural Painter")
parser.add_argument(
"--renderer",
type=str,
default="oilpaintbrush",
metavar="str",
help="renderer: [watercolor, markerpen, oilpaintbrush, recta... |
the-stack_106_26784 | import socket
from typing import Any, Dict, List
from .abc import AbstractResolver
from .helpers import get_running_loop
__all__ = ('ThreadedResolver', 'AsyncResolver', 'DefaultResolver')
try:
import aiodns
# aiodns_default = hasattr(aiodns.DNSResolver, 'gethostbyname')
except ImportError: # pragma: no cove... |
the-stack_106_26786 | """
This module lets you practice correcting SYNTAX (notation) errors.
Authors: David Mutchler, Dave Fisher, Vibha Alangar, Amanda Stouder,
their colleagues and Myon McGee.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
###############################################################################
#
# DON... |
the-stack_106_26788 | ##############################################################################
##
# This file is part of Sardana
##
# http://www.sardana-controls.org/
##
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
# Sardana is free software: you can redistribute it and/or modify
# it under the terms of the GNU Less... |
the-stack_106_26790 | import torch
import transforms as T
class DetectionPresetTrain:
def __init__(self, data_augmentation, hflip_prob=0.5, mean=(123., 117., 104.)):
if data_augmentation == 'hflip':
self.transforms = T.Compose([
T.RandomHorizontalFlip(p=hflip_prob),
T.PILToTensor(),... |
the-stack_106_26791 | """Grid example."""
from flow.controllers import GridRouter, IDMController, RLController
from flow.controllers.routing_controllers import MinicityRouter
from flow.core.params import SumoParams, EnvParams, InitialConfig, NetParams
from flow.core.params import VehicleParams, PersonParams
from flow.core.params import Traf... |
the-stack_106_26792 | """
Post-processes the obiwan/, tractor/, data products. Joins the psql db,
input properties, and tractor catalogue measurements for easy anaylsis
later. Uses mpi4py to parallelize to a full production runs' outputs.
"""
import numpy as np
import os
from glob import glob
import pandas as pd
from collections import Cou... |
the-stack_106_26793 | """ Calculates quantities required in semi-visible jet models """
import math
def calc_alpha_d(n_c, n_f, Lambda_d):
b_param = calc_b_param(n_c, n_f)
alpha_d = -2.0*math.pi / (b_param * math.log(Lambda_d/1000.0))
return alpha_d
def calc_lambda_d(n_c, n_f, alpha_d):
b_param = calc_b_param(n_c, n_f)
... |
the-stack_106_26794 | """Support for the Automatic platform."""
import asyncio
from datetime import timedelta
import json
import logging
import os
from aiohttp import web
import voluptuous as vol
from homeassistant.components.device_tracker import (
ATTR_ATTRIBUTES, ATTR_DEV_ID, ATTR_GPS, ATTR_GPS_ACCURACY, ATTR_HOST_NAME,
ATTR_MA... |
the-stack_106_26796 | # -*- coding: utf-8 -*-
import nltk
from sklearn.feature_extraction.text import TfidfVectorizer
from nltk.corpus import stopwords
from nltk.stem.arlstem import ARLSTem
from sklearn.metrics.pairwise import cosine_similarity, linear_kernel
from nltk.tokenize import WordPunctTokenizer
import numpy as np
import pickle
from... |
the-stack_106_26798 | # Copyright (c) 2013, VHRS and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
import math
from datetime import datetime,timedelta
from frappe.utils import getdate, cint, add_months, date_diff, add_days, nowdate, \
get_dateti... |
the-stack_106_26799 | """
### BEGIN NODE INFO
[info]
name = Serial Server
version = 1.5.1
description = Gives access to serial devices via pyserial.
instancename = %LABRADNODE% Serial Server
[startup]
cmdline = %PYTHON% %FILE%
timeout = 20
[shutdown]
message = 987654321
timeout = 20
### END NODE INFO
"""
import os
import time
import colle... |
the-stack_106_26800 | """GUI frontend for atamaTracker
"""
import cv2
from . import graphics
from .geometry import Point
# constants
ESC = 27
LEFT_ARROW = 63234
class EventListener(object):
"""Listener for mouse events
Public properties:
clicked_points -- [list] List of Point instances
is_pressed -- [bool] Boolean whe... |
the-stack_106_26805 | #!/usr/bin/env python3
import os
import re
import sys
from setuptools import find_packages, setup
REQUIRED_MAJOR = 3
REQUIRED_MINOR = 6
# Check for python version
if sys.version_info < (REQUIRED_MAJOR, REQUIRED_MINOR):
error = (
"Your version of python ({major}.{minor}) is too old. You need "
"... |
the-stack_106_26806 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
the-stack_106_26808 | """
A jones calculus example.
You can use the package for simple normal incidence Jones calculus. In the
:mod:`dtmm.jones` you will find all the functionality to work with jones calculus.
For example, we can compute the transmittance properties of a simple Twisted
Nematic director profile. We compute wavelength-de... |
the-stack_106_26809 | '''
Created on May 30, 2019
@author: mohammedmostafa
'''
import numpy as np
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
import matplotlib.pyplot as plt
xs = np.random.choice(np.arange(-3,3,.01),500)
ys = xs**2
x_test=np.linspace(-3,3,1000)
y_test=x_test**2
model = Seque... |
the-stack_106_26810 | # XXX TO DO:
# - popup menu
# - support partial or total redisplay
# - key bindings (instead of quick-n-dirty bindings on Canvas):
# - up/down arrow keys to move focus around
# - ditto for page up/down, home/end
# - left/right arrows to expand/collapse & move out/in
# - more doc strings
# - add icons for "file", ... |
the-stack_106_26811 | #!/usr/bin/env python
from gppylib.gplog import *
from gppylib.gpcatalog import *
import re
class ForeignKeyCheck:
"""
PURPOSE: detect differences between foreign key and reference key values among catalogs
"""
def __init__(self, db_connection, logger, shared_option, autoCast):
self.db_connec... |
the-stack_106_26812 | from collections import OrderedDict
import dask.dataframe as dd
import pandas as pd
import pytest
from dask.dataframe.utils import tm
import ibis
import ibis.expr.datatypes as dt
from ... import connect, execute
@pytest.fixture(scope="module")
def value():
return OrderedDict([("fruit", "pear"), ("weight", 0)])... |
the-stack_106_26814 | #!/usr/bin/env python3
import sys
import subprocess
# Custom Enum for Operations
dmt_counter=0
def dmtCounter(reset=False):
global dmt_counter
if reset:
dmt_counter = 0
result = dmt_counter
dmt_counter += 1
return result
#Operations
OP_PUSH=dmtCounter(True)
OP_PLUS=dmtCounter()
OP_MINUS=d... |
the-stack_106_26815 | #!/usr/bin/python3 -u
import zlib
from random import randint
import os
from Crypto.Cipher import Salsa20
flag = open("./flag").read()
def compress(text):
return zlib.compress(bytes(text.encode("utf-8")))
def encrypt(plaintext):
secret = os.urandom(32)
cipher = Salsa20.new(key=secret)
return cipher.... |
the-stack_106_26816 | # -*- coding: utf-8 -*-
from bs4 import BeautifulSoup #网页解析
import re
import urllib.request
import xlwt #Excel操作
import sqlite3 #sqlite数据库操作
def main():
baseurl = 'https://movie.douban.com/top250?start='
datalist = getData(baseurl)
savepath = '豆瓣电影top250.xls'
saveData(datalist,savepath)
... |
the-stack_106_26818 | # Circuit Playground Express Hot Potato
#
# Author: Carter Nelson
# MIT License (https://opensource.org/licenses/MIT)
import time
import random
import math
import board
from analogio import AnalogIn
from adafruit_circuitplayground.express import cpx
# This brings in the song to play
import melody
number_of_notes = len... |
the-stack_106_26819 | import os
import cv2 as cv
import matplotlib.pylab as plt
import numpy as np
from console_progressbar import ProgressBar
from scipy.interpolate import interp1d
from scipy.signal import gaussian, convolve
from config import num_classes
def compute_class_prior(do_plot=False):
categories_folder = 'data/instance-le... |
the-stack_106_26820 | from zipfile import ZipFile
import io
from io import StringIO
from urllib import request
import csv
from .interface import ServiceInterface
from .logger import debug
class CsvZipServiceInterface(ServiceInterface):
TYPE = "csv-zip"
@classmethod
def key(cls):
return cls.TYPE.lower()
def __ini... |
the-stack_106_26821 | import logging
import queue
import traceback
from http.server import BaseHTTPRequestHandler, HTTPServer
from multiprocessing import Process, Queue
from .pact_request_handler import PactRequestHandler
_providers = {}
log = logging.getLogger(__name__)
def getMockServer(pact):
if pact.provider.name not in _provi... |
the-stack_106_26822 |
import os
import queue
import shlex
import select
import threading as mt
import subprocess as sp
from .constants import RUNNING, DONE, FAILED
from .misc import is_string
# ------------------------------------------------------------------------------
#
def sh_callout(cmd, stdout=True, stderr=True, shell=Fals... |
the-stack_106_26827 | import os
import sys
Plugins = []
debug = True
def default_params():
return {'method':'GET','page':1}
def LoadPlugins(destdir='plugins'):
ss = [ f for f in os.listdir(destdir) if os.path.isfile(os.path.join(destdir,f)) and f!='__init__.py' ]
sys.path.insert( 0, destdir)
for s in ss... |
the-stack_106_26828 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import io
import os
import argparse
import pandas as pd
from PIL import Image
def pil_loader(image_path):
with open(image_path, "rb") a... |
the-stack_106_26829 | import numpy as np
import networkx as nx
import opensfm.reconstruction
def test_triangulate_track_equirectangular():
graph = nx.Graph()
graph.add_node('im1', bipartite=0)
graph.add_node('im2', bipartite=0)
graph.add_node('1', bipartite=1)
graph.add_edge('im1', '1', feature=(0,0))
graph.add_edg... |
the-stack_106_26832 | import sys
import copy
import types
import inspect
__all__ = ['dataclass',
'field',
'Field',
'FrozenInstanceError',
'InitVar',
'MISSING',
# Helper functions.
'fields',
'asdict',
'astuple',
'make_dataclass',
... |
the-stack_106_26834 | import os
DIRNAME = os.path.dirname(__file__)
DEBUG = True
DATABASE_ENGINE = 'sqlite3'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(DIRNAME, 'example.sqlite').replace('\\','/'),
'USER': '',
'PASSWORD': '',
'HOST': '',
'PO... |
the-stack_106_26835 | import logging
from utils import Logger
import pandas as pd
from datetime import datetime
from typing import Any, Dict, IO, List, Tuple, Union
from pandas.io.parsers import TextFileReader
## import local files
from interfaces.src.DataInterface import DataInterface
class CSVInterface(DataInterface):
def __init__(se... |
the-stack_106_26836 | import torch
from torch.nn import functional as F
from linear_nets import MLP,fc_layer
from exemplars import ExemplarHandler
from continual_learner import ContinualLearner
from replayer import Replayer
import utils
class Classifier(ContinualLearner, Replayer, ExemplarHandler):
'''Model for classifying images, "en... |
the-stack_106_26838 | import pytest
from quart import Quart
@pytest.mark.asyncio
@pytest.mark.parametrize(
'debug, testing, present',
[(True, True, False), (True, False, True), (False, True, False), (False, False, False)],
)
async def test_debug(debug: bool, testing: bool, present: bool) -> None:
app = Quart(__name__)
app... |
the-stack_106_26840 | from setuptools import setup, find_packages, Command
from setuptools.command.build_py import build_py
from distutils import dir_util
from distutils.util import convert_path
from pathlib import Path
import os
import re
import string
import textwrap
from typing import Dict, NamedTuple, List, Sequence, Optional, TypeVar, ... |
the-stack_106_26845 | ################################# LICENSE ##################################
# Copyright (c) 2009, South African Astronomical Observatory (SAAO) #
# All rights reserved. #
# #
# Redistribu... |
the-stack_106_26846 | # Python test set -- built-in functions
import ast
import builtins
import collections
import decimal
import fractions
import io
import locale
import os
import pickle
import platform
import random
import re
import sys
import traceback
import types
import unittest
import warnings
from contextlib import ExitStack
from op... |
the-stack_106_26847 | import _plotly_utils.basevalidators
class YsideValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name='yside', parent_name='layout.grid', **kwargs
):
super(YsideValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent... |
the-stack_106_26851 | try:
import usocket as socket
except:
import socket
import ussl as ssl
CONTENT = b"""\
HTTP/1.0 200 OK
Hello #%d from MicroPython!
"""
def main(use_stream=True):
s = socket.socket()
# Binding to all interfaces - server will be accessible to other hosts!
ai = socket.getaddrinfo("0.0.0.0", 8443)
... |
the-stack_106_26853 | from setuptools import find_packages, setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="simpletransformers",
version="0.15.6",
author="Thilina Rajapakse",
author_email="chaturangarajapakshe@gmail.com",
description="An easy-to-use wrapper library for the Transf... |
the-stack_106_26854 | """
Knapsack problem.
Naive recursive implementation. Try all combinations (Bad idea)
Complexity is exponential (2^n) where n is number of items.
"""
# Uncomment the following lines if you want to play around with more than 2000 items
# import sys
# sys.setrecursionlimit(2500)
memo = {}
def ks(capacity_left, n, weig... |
the-stack_106_26855 | """Project models."""
import fnmatch
import logging
import os
import re
from urllib.parse import urlparse
from django.conf import settings
from django.contrib.auth.models import User
from django.core.files.storage import get_storage_class
from django.db import models
from django.db.models import Prefetch
from django.... |
the-stack_106_26856 | import torch
import numpy as np
import multiprocessing
import os
from torch import optim
import utils
from torch.autograd import Variable
from model import Dense_Net, ImgNet
class MHN(object):
def __init__(self, config, train_dataloader, view):
self.args = config
self.output_shape = config.output_... |
the-stack_106_26857 | # Copyright (C) 2013-2018 Internet Systems Consortium.
#
# Permission to use, copy, modify, and 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 INTERNET ... |
the-stack_106_26869 | from manim2.imports import *
from from_3b1b.old.hilbert.curves import *
class Intro(TransformOverIncreasingOrders):
@staticmethod
def args_to_string(*args):
return ""
@staticmethod
def string_to_args(string):
raise Exception("string_to_args Not Implemented!")
def construct... |
the-stack_106_26870 | """Making sure we are running the right version of python"""
import sys
if sys.version_info[0] >= 3:
raise Exception("Must be using Python 2")
"""Making sure soar library path environment is set
Remember to set the environment variable to point to where soar build is located, e.g.:
export LD_LIBRARY_PATH=~/Desktop... |
the-stack_106_26871 | import sys
N,M = map(int,sys.stdin.readline().split())
array = list(range(1,M+1))
while(1):
if N+1 in array: #N+1인 수가 존재할 때
index = array.index(N+1)
if index == 0: # N+1인 수가 첫번째 수 일때
sys.exit()
else: # N+1인 수가 첫번째 수가 아닐 때
array[index-1] += 1
for i in range(index,M):
array[i] = ... |
the-stack_106_26872 | if __name__ == '__main__':
def fac(n):
ans = 1
for i in range(1, n + 1):
ans *= i
ans = str(ans)
mysum = 0
for i in ans:
mysum += int(i)
return [ans, mysum]
n = int(input('Enter a number: '))
li = fac(n)
print(str(n) + '! = '... |
the-stack_106_26873 | import os
from pathlib import Path
from huey import SqliteHuey
from workoutizer.logger import get_logging_config
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
INITIAL_TRACE_DATA_DIR = os.path.join(BASE_DIR, "setup", "initial_trace_data")
if os.ge... |
the-stack_106_26874 | """
Experiment configuration for:
Model: Dhingra et al 2018 -- https://arxiv.org/abs/1804.00720
Benchmark: Tacred
"""
from reflex.qa_runner import QARunner
from reflex.utils import setup_experiment
import os
ex = setup_experiment('Dhingra Tacred')
@ex.config
def conf():
qa_path = os.path.join(os.environ['BASE_PAT... |
the-stack_106_26875 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# В списке, состоящем из вещественных элементов, вычислить:
# 1. количество элементов списка, больших С;
# 2. произведение элементов списка, расположенных после максимального по модулю
# элемента.
if __name__ == '__main__':
lst = [0] * 10
count = 0
d = 1
c ... |
the-stack_106_26876 | """Simple test script for 4.2" 400x300 black and white displays.
Supported products:
* WaveShare 4.2" Black and White
* https://www.waveshare.com/product/modules/oleds-lcds/e-paper/4.2inch-e-paper.htm
* https://www.waveshare.com/product/modules/oleds-lcds/e-paper/4.2inch-e-paper-module.htm
"""
import time... |
the-stack_106_26877 | from __future__ import print_function
from setuptools import Command
import sys
from os.path import realpath, join, exists, dirname, curdir, basename, split
from os import makedirs
from glob import glob
from shutil import rmtree, copyfile
def argv_contains(t):
for arg in sys.argv:
if arg.startswith(t):
... |
the-stack_106_26879 | #
# File:
# TRANS_read_ASCII.py
#
# Synopsis:
# Illustrates how to read an ASCII file
#
# Categories:
# I/O
#
# Author:
# Karin Meier-Fleischer, based on NCL example
#
# Date of initial publication:
# September 2018
#
# Description:
# This example shows how to read an ASCII file.
#
# Effects ... |
the-stack_106_26881 | import FWCore.ParameterSet.Config as cms
process = cms.Process("TEST")
process.maxEvents.input = 3
process.source = cms.Source("EmptySource",
firstLuminosityBlockForEachRun = cms.untracked.VLuminosityBlockID(
cms.LuminosityBlockID(10,1),
... |
the-stack_106_26883 | import sys
sys.path.append(".")
sys.path.append("../../.")
import os
import pathlib
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from src.models.models.cnn import Encoder, Decoder
from src.models.models.DenoisingAutoencoder import DenoisingAutoencoder
from src.data.datal... |
the-stack_106_26885 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Pytest configuration."""
from __future__ import absolute_import, print_function
... |
the-stack_106_26886 | """
This is an FSLeyes plugin script that integrates AxonDeepSeg tools into FSLeyes.
Author : Stoyan I. Asenov
"""
import wx
import wx.lib.agw.hyperlink as hl
import fsleyes.controls.controlpanel as ctrlpanel
import fsleyes.actions.loadoverlay as ovLoad
import numpy as np
import nibabel as nib
from PIL import Image... |
the-stack_106_26887 | # Copyright 2013 Evan Hazlett and contributors.
#
# 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 agree... |
the-stack_106_26888 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# CODE NAME HERE
# CODE DESCRIPTION HERE
Created on 2019-01-17 at 14:31
@author: cook
"""
from apero.science.velocity import general
__all__ = ['compute_ccf_fp', 'compute_ccf_science', 'locate_reference_file',
'measure_fp_peaks', 'remove_telluric_domain',... |
the-stack_106_26889 | # Good kraken and python resource:
# https://github.com/zertrin/clikraken/tree/master/clikraken
import base64
import hashlib
import hmac
import json
import logging
import time
from enum import Enum
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
from urllib.parse import urlencode
import geven... |
the-stack_106_26890 | """
Firmware de dispositivo de colecta de dados
y storage em SSD. Enviando a la nuve segun
jerarquia de filas definidas.
Autor: Eng. Francis Benjamin
Fecha: 09/03/2021
"""
import uasyncio
import btree
from time import sleep
from machine import Pin
import i2c
#Objetos i2c
adress_i2c = i2c.com_i2c().scan_i2c()
i2... |
the-stack_106_26891 | # Django Imports
from django.conf.urls import patterns, url
from django.views.generic import RedirectView
from django.views.generic.base import TemplateView
# WaW Imports
from wawmembers import views, interactions, news, policies, ajax
'''
Dispatches URL requests to functions.
'''
urlpatterns = patterns("",
url(... |
the-stack_106_26892 | from collections import Counter
class Solution:
def countElements(self, arr: List[int]) -> int:
c = Counter(arr)
res = 0
for n,n_count in c.items():
if n+1 in c:
res += n_count
return res
|
the-stack_106_26899 | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import pytest
import numpy as np
from utils_cv.classification.plot import (
plot_roc_curve,
plot_precision_recall_curve,
plot_pr_roc_curves,
plot_thresholds,
)
from utils_cv.classification.model import hamming... |
the-stack_106_26900 | """
=================
Wavelet denoising
=================
The discrete wavelet transform is not `shift-invariant`_. Shift invariance can
be achieved through an undecimated wavelet transform (also called stationary
wavelet transform), at cost of increased redundancy (i.e. more wavelet
coefficients than input image pix... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.