filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_0_11204 | # included code for NAF/KAF
from span_data import *
from external_references_data import *
from term_sentiment_data import *
from lxml import etree
class Cterm:
def __init__(self,node=None,type='NAF'):
self.type = type
if node is None:
self.node = etree.Element('term')
else:
... |
the-stack_0_11206 |
class Jet:
def __init__(
self,
progenitor=None,
constituents=None,
mass=None,
pt=None,
eta=None,
phi=None,
y=None,
tree=None,
root_id=None,
tree_content=None,
**kwargs
... |
the-stack_0_11208 | # USAGE
# python match_histograms.py --source empire_state_cloudy.png --reference empire_state_sunset.png
# import the necessary packages
from skimage import exposure
import matplotlib.pyplot as plt
import argparse
import cv2
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.ad... |
the-stack_0_11211 | """About Dialog for IDLE
"""
import os
import sys
from platform import python_version, architecture
from tkinter import Toplevel, Frame, Label, Button, PhotoImage
from tkinter import SUNKEN, TOP, BOTTOM, LEFT, X, BOTH, W, EW, NSEW, E
from idlelib import textview
def build_bits():
"Return bits for... |
the-stack_0_11212 | import os
import unittest
import six
from conans.paths import BUILD_INFO, CONANFILE
from conans.test.utils.tools import TestClient
from conans.util.files import mkdir
class SourceTest(unittest.TestCase):
def test_local_flow_patch(self):
# https://github.com/conan-io/conan/issues/2327
conanfile ... |
the-stack_0_11213 | # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RS4vectors(RPackage):
"""The S4Vectors package defines the Vector and List virtual classes... |
the-stack_0_11214 | import requests
headers = {"OCS-APIRequest": "true"}
# The API is implemented as documented here: https://deck.readthedocs.io/en/latest/API/
class DeckAPI:
def __init__(self, url, auth):
self.url = url
self.auth = auth
def get(self, route):
response = requests.get(
f"{self... |
the-stack_0_11216 | """Decorators are higher order functions that accept functions and return another function that executes the original"""
import datetime
import functools
def check_value(func):
"""checking value parameter decorator - function that returns a function."""
def do_checking(name, value):
print("decorate: w... |
the-stack_0_11217 | # -*- coding: utf-8 -*-
'''
Manage Grafana v4.0 users
.. versionadded:: 2017.7.0
:configuration: This state requires a configuration profile to be configured
in the minion config, minion pillar, or master config. The module will use
the 'grafana' key by default, if defined.
Example configuration using ba... |
the-stack_0_11218 | # Natural Language Toolkit: Dependency Corpus Reader
#
# Copyright (C) 2001-2015 NLTK Project
# Author: Kepa Sarasola <kepa.sarasola@ehu.es>
# Iker Manterola <returntothehangar@hotmail.com>
#
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
import codecs
from cnltk.parse import DependencyG... |
the-stack_0_11222 | """
Print command.
Print information about the wily cache and what is in the index.
"""
import tabulate
from wily import logger, format_date, format_revision, MAX_MESSAGE_WIDTH
from wily.config import DEFAULT_GRID_STYLE
from wily.state import State
def index(config, include_message=False):
"""
Show informat... |
the-stack_0_11223 | """
Test the pre-trained autoencoder model with test trajectory data.
"""
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import ae_utilities as aeu
import dataset_defines as dd
import numpy as np
import os
abspath = os.path.abspath(__file__)
dir_name = os.path.dirname(abspath)
dataset... |
the-stack_0_11225 | import requests
import random
from time import sleep
from urllib.parse import urlparse as parsy
bad = '\033[91m[-]\033[0m'
user_agents = ['Mozilla/5.0 (X11; Linux i686; rv:60.0) Gecko/20100101 Firefox/60.0',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/... |
the-stack_0_11226 | # importing important librarires
import itertools
import numpy as np
import torch
import pydicom
from PIL import Image
from torch.utils.data import DataLoader
import pandas as pd
def load_scan(path):
"""
This function is used to load the MRI scans. It converts the scan into a numpy array
Parameters:... |
the-stack_0_11227 | #!/usr/bin/env python
# Copyright 2016 99cloud 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 ... |
the-stack_0_11228 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from marionette.by import By
from gaiatest import GaiaTestCase
from gaiatest.apps.gallery.app import Gallery
class Tes... |
the-stack_0_11229 | import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self,
plotly_name="color",
parent_name="scatter3d.line.colorbar.title.font",
**kwargs
):
super(ColorValidator, self).__init__(
plotly_name=pl... |
the-stack_0_11230 | # EXAMPLES needs to add parent directory to path so we can import EZ:
import os, sys
sys.path.append(os.path.dirname(__file__) + '/..')
# Disable the creation of python bytecode to keep stuff clean:
sys.dont_write_bytecode = True
from scripts.EZpanda.EZ import EZ, config
config['window-title'] = "EZpanda Examples"
... |
the-stack_0_11232 | import bisect
from collections import defaultdict
class Solution:
def dailyTemperatures(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
n = len(temperatures)
if n == 0:
return []
elif n == 1:
return [0]
... |
the-stack_0_11233 | from contextlib import closing
from mysql.connector import connect
import random
def create_journal_group_name_lookup(filepath, encoding, delimiter):
data = load_delimited_data(filepath, encoding, delimiter)
lookup = {}
for row in data:
nlm_id = row[0]
group = row[1]
lookup[nlm_id]... |
the-stack_0_11235 | import asyncio
import functools
import inspect
import typing
from urllib.parse import urlencode
from starlette.exceptions import HTTPException
from starlette.requests import HTTPConnection, Request
from starlette.responses import RedirectResponse, Response
from starlette.websockets import WebSocket
def has_required_... |
the-stack_0_11236 | from expenses_tracker.expenses.models import Expense
from expenses_tracker.profiles.models import Profile
def get_profile():
profile = Profile.objects.first()
if profile:
expenses = Expense.objects.all()
profile.budget_left = profile.budget - sum(e.price for e in expenses)
return profil... |
the-stack_0_11238 | from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Recipe
from recipe.serializers import RecipeSerializer
RECIPES_URL = reverse('recipe:recipe-list')
de... |
the-stack_0_11239 | #! /usr/bin/env python
#
# 1440 files took about 38 mins
#
from __future__ import print_function
from tkinter import filedialog
from astride import Streak
import glob
import sys
import shutil
import os
import tkinter as tk
import matplotlib.pyplot as plt
from astropy.io import fits
import numpy as np
def get_arg(ar... |
the-stack_0_11240 | import json
import logging
from django.utils.functional import wraps
from morango.sync.context import LocalSessionContext
from kolibri.core.auth.constants.morango_sync import ScopeDefinitions
from kolibri.core.auth.hooks import FacilityDataSyncHook
logger = logging.getLogger(__name__)
def _get_our_cert(context):
... |
the-stack_0_11244 | import warnings
from . import DealFormat
from .. import dto
class BRIFormat(DealFormat):
number_warning = '.bri file format assumes consequent deal numbers from 1'
@property
def suffix(self):
return '.bri'
def parse_content(self, content):
warnings.warn(self.number_warning)
d... |
the-stack_0_11245 | import time
import cache
import vkapi
from log import datetime_format
def main(a, args):
dialogs = a.messages.getDialogs(unread=1)['items']
messages = {}
users = []
chats = []
for msg in dialogs:
def cb(req, resp):
messages[req['peer_id']] = resp['items'][::-1]
a.messa... |
the-stack_0_11246 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import warnings
import nevergrad.common.typing as tp
# import numpy as np
from nevergrad.parametrization import paramete... |
the-stack_0_11247 | from math import *
import random
### ------------------------------------- ###
# Below, is the robot class
#
# This robot lives in 2D, x-y space, and its motion is
# pointed in a random direction, initially.
# It moves in a straight line until it comes close to a wall
# at which point it stops.
#
# For measurements,... |
the-stack_0_11248 |
import unittest
import random
import threading
import System
from System.IO import Directory
from System.IO import Path
from System.Collections.Generic import Dictionary
from System.Collections.Generic import SortedDictionary
from System.Collections.Generic import SortedList
import clr
clr.AddReferenceB... |
the-stack_0_11252 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 23 17:38:24 2017
@author: Phoebe
"""
import os
import time
import numpy as np
import pandas as pd
# Download and install the Python COCO tools from https://github.com/waleedka/coco
# That's a fork from the original https://github.com/pdollar/coco with a bug... |
the-stack_0_11253 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 22 22:51:13 2021
@author: liujinli
"""
import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error,r2_score
from lightgbm import LGBMRegressor
from xgboost import XGBRegressor
from sklearn.ensemble import RandomForestRegressor,AdaBoostRegressor
... |
the-stack_0_11255 | import asyncio
import shutil
import subprocess
from pathlib import Path
from typing import Any, List
from jinja2 import Environment, PackageLoader
from . import logger
from .exceptions import FetchError, GenerateError, GenerateScriptError
from .fetcher import fetch
from .parser import Blueprint
_environment = Enviro... |
the-stack_0_11256 | # Copyright 2013-2018 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyBottleneck(PythonPackage):
"""A collection of fast NumPy array functions written in Cyth... |
the-stack_0_11258 | '''
Exercício Python 101: Crie um programa que tenha uma função chamada voto() que vai receber como parâmetro o ano de
nascimento de uma pessoa, retornando um valor literal indicando se uma pessoa tem voto NEGADO, OPCIONAL e OBRIGATÓRIO
nas eleições.
'''
def voto(ano):
from datetime import date
print('-='* 15)
... |
the-stack_0_11259 | """Environment to render templates"""
import json
from pathlib import Path
from sys import executable
from diot import Diot, OrderedDiot
from pyppl.template import DEFAULT_ENVS
__all__ = []
def rimport(*paths):
rimport_rfunc = f"""
if (!exists('..rimport..') || !is.function(..rimport..)) {{
reticulate::use_python... |
the-stack_0_11263 | """
选择枚举,用于对常量进行处理
"""
import collections
from enum import Enum
from typing import Dict, Tuple
__all__ = [
"ChoicesValue",
"ChoicesEnum",
]
ChoicesValue = collections.namedtuple("choices_value", ["id", "name"])
class ChoicesEnum(Enum):
@classmethod
def _get_members(cls):
return cls._member... |
the-stack_0_11266 | import socket
import sys
send_response = True
default_response_str = ''
default_response_bytes = default_response_str.encode('utf-8')
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(10)
# Bind the socket to the port
server_address = ('localhost', 8001)
print(f"{sys.st... |
the-stack_0_11267 | #!/usr/bin/env python
"""
Copyright (c) 2019 Intel Corporation
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 l... |
the-stack_0_11269 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module defines generic plotters.
"""
import collections
import importlib
from pymatgen.util.plotting import pretty_plot
class SpectrumPlotter:
"""
Class for plotting Spectrum objects and su... |
the-stack_0_11271 | # Exercise OLS (version without functions
# Load the data
x = [9.55, 9.36, 0.2, 2.06, 5.89, 9.3, 4.74, 2.43, 6.5, 4.77]
y = [15.28, 16.16, 1.2, 5.14, 9.82, 13.88, 6.3, 3.71, 9.96, 9]
# Let us compute the average of x
sum_x = 0
for i in x:
sum_x +=i
mean_x = sum_x/len(x)
# Let us compute the average of y
sum_y = ... |
the-stack_0_11272 | import torch
import torch.nn as nn
import numpy as np
from torchsummary import summary
def double_conv(in_c, out_c):
block = nn.Sequential(nn.Conv2d(in_c, out_c, kernel_size = 3, bias = False),
nn.BatchNorm2d(out_c),
nn.ReLU(inplace = True),
... |
the-stack_0_11276 | class Solution:
def trap(self, height: List[int]) -> int:
n = len(height)
l = [0] * n # l[i] := max(height[0..i])
r = [0] * n # r[i] := max(height[i..n))
for i, h in enumerate(height):
l[i] = h if i == 0 else max(h, l[i - 1])
for i, h in reversed(list(enumerate(height))):
r[i] = h ... |
the-stack_0_11277 | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.sodium as sodium
import specs.... |
the-stack_0_11278 | # Copyright (c) 2016, Neil Booth
#
# All rights reserved.
#
# See the file "LICENCE" for information about the copyright
# and warranty status of this software.
'''Class for handling environment configuration and defaults.'''
import re
from ipaddress import IPv4Address, IPv6Address
from typing import Type
from aior... |
the-stack_0_11279 | """
MIT License
Copyright (c) 2019-2021 naoTimesdev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publi... |
the-stack_0_11281 | import json
# Create a dictionary object
person_dict = {'first': 'Christopher', 'last':'Harrison'}
# Add additional key pairs to dictionary as needed
person_dict['City']='Seattle'
# Create a list object of programming languages
languages_list = ['CSharp','Python','JavaScript']
# Add list object to dictionary for th... |
the-stack_0_11282 |
import pandas as pd
import numpy as np
import torch
import torch.utils.data as Data
def get_params_length(layer_id):
'''
获取不同层参数向量长度
'''
get_params_length_dic = {
0:13,
1:19,
2:25,
3:14,
4:20,
5:26,
6:11,
7:17,
8:23,
9:9,... |
the-stack_0_11285 | import json
import tkinter
from alp.ml import Alp
class MainWindow(tkinter.Tk):
def __init__(self, filename):
super().__init__()
self.create_mf(filename)
def loop_mainframe(self):
self.mainloop()
def create_mf(self, filename):
f = open(f"{Alp.CONF_DIR}/{filename}", "r")
... |
the-stack_0_11287 | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
class CarouselGalleryUniteOptionsAdmin(admin.ModelAdmin):
'''
Carousel
Tiles - Columns
Tiles - Grid
Tiles - Justified
Tiles - Nested
'''
fieldsets = (
(_('Gallery options'), {
'... |
the-stack_0_11290 | #!/usr/bin/env python3
import os
import requests
import json
import sys
import psutil
import subprocess
import re
from colorama import Fore, Style, Back
from tqdm import tqdm
import urllib3
from troncli.constants import *
"""
Printing Messages
"""
def logo_simple():
print(Fore.RED + Style.BRIGHT + '')
print... |
the-stack_0_11291 | from django.contrib import admin
from django.db.models import TextField
from django.forms import Textarea
from .models import Job, Analysis, Project, Access, Data
@admin.register(Access)
class AccessAdmin(admin.ModelAdmin):
list_select_related = (
'user',
'project',
)
readonly_fields = (... |
the-stack_0_11292 | from denariusrpc.authproxy import AuthServiceProxy, JSONRPCException
import time
import sys
import datetime
import urllib
import json
from influxdb import InfluxDBClient
# rpc_user and rpc_password are set in the denarius.conf file
rpc_connection = AuthServiceProxy("http://%s:%s@127.0.0.1:32369"%("rpcuser", "rpcpassw... |
the-stack_0_11294 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.forms import widgets
from django.forms.util import ErrorList
from django.core.exceptions import ValidationError
class PartialFormField(object):
"""
Behave similar to django.forms.Field, encapsulating a partial dictionary, stored as
... |
the-stack_0_11295 | """Provide functionality to stream video source.
Components use create_stream with a stream source (e.g. an rtsp url) to create
a new Stream object. Stream manages:
- Background work to fetch and decode a stream
- Desired output formats
- Home Assistant URLs for viewing a stream
- Access tokens for URLs for vi... |
the-stack_0_11296 | from __future__ import print_function
import array
import os
import shutil
import tempfile
import uuid
from collections import defaultdict, namedtuple
from mozlog import structuredlog
from . import manifestupdate
from . import testloader
from . import wptmanifest
from . import wpttest
from .expected import expected_p... |
the-stack_0_11297 | # NEW COLORS 108.04.24
# output=gray colors
import numpy as np
import pygame
import time
# Define some colors
COLORS = 3 # 測試次數上限
# 模擬器上顏色設定
BLACK = np.array((0, 0, 0))
WHITE = np.array((255, 255, 255))
BLUE = np.array((60, 150, 255))
PURPLE = np.array((153, 47, 185))
RED_PROBE = np.array((230, 90, 80)... |
the-stack_0_11300 | import _pickle as pickle
from keras.models import load_model
class BaseModel(object):
def __init__(self, model_size):
self.model_size = model_size
self.model = None
def save(self, filename):
if self.model is not None:
self.model.save(filename + '.model')
d = dict(... |
the-stack_0_11302 | from numpy.distutils.core import setup
from numpy.distutils.misc_util import Configuration
def configuration(parent_package='', top_path=None):
config = Configuration('delaunay', parent_package, top_path)
config.add_extension("_delaunay",
sources=["_delaunay.cpp", "VoronoiDiagramGenerator.cpp",
... |
the-stack_0_11303 | """Provides a sensor to track various status aspects of a UPS."""
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
CONF_HOST, CONF_PORT, CONF_NAM... |
the-stack_0_11307 | from sstcam_sandbox import get_plot
from CHECLabPy.plotting.setup import Plotter
from CHECOnsky.utils.astri_database import ASTRISQLQuerier
import pandas as pd
import matplotlib.dates as mdates
import matplotlib.colors as mcolors
class Uptime(Plotter):
def plot(self, sql, start, end, title):
start_day = s... |
the-stack_0_11308 | agenda = dict()
td = list()
nomes = list()
cont = 0
print(' AGENDA TELEFONICA ')
while True:
menu = int(input('[0] Mostrar agenda\n'
'[1] Novo contato\n'
'[2] Pesquisar contato\n'
'[3] Remover ou fazer alteração do contato\n:'))
while menu no... |
the-stack_0_11310 | """A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from pathlib import Path
import subprocess
from setuptools import setup, find_packages
# io.open is needed for projects that support Pyt... |
the-stack_0_11311 | #%%
import os
# import warnings
# warnings.filterwarnings('ignore') # 注:放的位置也会影响效果,真是奇妙的代码
#
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import numpy as np
from matplotlib import pyplot as plt
import cv2
from detection.datasets import myDataset,data_generator
from dete... |
the-stack_0_11312 | class Solution(object):
def longestIncreasingPath(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: int
"""
if not matrix or len(matrix[0]) <= 0:
return 0
h = len(matrix)
w = len(matrix[0])
memo_arr = [[0 for _ in range(w)] for _ ... |
the-stack_0_11314 | # BSD 3-Clause License
#
# Copyright (c) 2019, Elasticsearch BV
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, t... |
the-stack_0_11317 | import randopt as ro
def loss(x):
return x**2
e = ro.Experiment('myexp', {
'alpha': ro.Gaussian(mean=0.0, std=1.0, dtype='float'),
})
# Sampling parameters
for i in range(100):
e.sample('alpha')
res = loss(e.alpha)
print('Result: ', res)
e.add_result(res)
# Manually setting parameter... |
the-stack_0_11318 | from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="pypodo",
version="3.0.3",
description="pypodo is a todolist tool which works with a .todo file at the root of the home directory. It has a mecanism of indexes and tags.",
long_description=long... |
the-stack_0_11322 | # -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. 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 requir... |
the-stack_0_11323 | from django.conf import settings
from django.contrib.postgres.fields import JSONField
from django.core.exceptions import ValidationError
from django.core.mail import EmailMultiAlternatives
from django.db import models
from django.template import (
Context,
Template,
TemplateDoesNotExist,
TemplateSyntaxE... |
the-stack_0_11324 | # Desafio 030 -> Crie um programa que leia um numero inteiro e diga se ele é par ou impar
import math
num = int(input('Digite um número inteiro: '))
numd = num % 2
print ('{} é par'.format(num) if numd == 0 else '{} é ímpar'.format(num))
# print('{} é par'.format(num))
#else:
# print('{} é ímpar'.format(num))
|
the-stack_0_11327 | from requests import Session
from m3u8 import loads
import os
from m3u8.model import SegmentList, Segment, find_key
class XET(object):
APPID = '' # APPid
XIAOEID = '' # Cookie XIAOEID
RESOURCEID = '' # ResourceID,这里的resourceid代表课程id
sessionid = '' # Cookie laravel_session
session = Session()
... |
the-stack_0_11330 | import logging
import os
import platform
import subprocess
import sys
import warnings
from unittest import skipIf
from pytest import raises, mark
from testfixtures import LogCapture
from twisted.internet import defer
from twisted.trial import unittest
import scrapy
from scrapy.crawler import Crawler, CrawlerRunner, C... |
the-stack_0_11332 | #!python
# coding=utf-8
import logging
from typing import List, Tuple
from itertools import zip_longest, filterfalse
from avro import schema
from confluent_kafka import Producer
from confluent_kafka.avro import AvroProducer, CachedSchemaRegistryClient
# Monkey patch to get hashable avro schemas
# https://issues.apac... |
the-stack_0_11334 | import asyncio
import logging
from aiohttp import ClientError, ClientSession
from gios import ApiError, InvalidSensorsData, Gios, NoStationError
GIOS_STATION_ID = 117
logging.basicConfig(level=logging.DEBUG)
async def main():
try:
async with ClientSession() as websession:
gios = Gios(GIOS_ST... |
the-stack_0_11335 | import os
import tensorflow as tf
def assign_to_gpu(gpu=0, ps_dev="/device:CPU:0"):
def _assign(op):
node_def = op if isinstance(op, tf.compat.v1.NodeDef) else op.node_def
if node_def.op == "Variable":
return ps_dev
else:
return "/gpu:%d" % gpu
return _assign
... |
the-stack_0_11337 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import asyncio
import signal
import sys
import functools
from aiotinder.controllers.tinder import Tinder
facebook_id = ""
facebook_token = ""
async def shutdown(loop: asyncio.events.AbstractEventLoop) -> None:
await asyncio.sleep(0.1)
loop.close()
async def ... |
the-stack_0_11338 | '''
Voice metadata definition.
Copyright (c) 2009, 2013 Peter Parente
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 THE... |
the-stack_0_11339 | from enum import IntEnum
import functools
import usb.core
import usb.util
from traffic_light.error import TrafficLightError, MultipleTrafficLightsError
CTRL_ENDPOINT = 0x02
ID_VENDOR = 0x0d50
ID_PRODUCT = 0x0008
INTERFACE = 0
class Color(IntEnum):
RED = 0x10
YELLOW = 0x11
GREEN = 0x12
class State(Int... |
the-stack_0_11340 | from aws_cdk.aws_lambda import Function, Code, Runtime
from aws_cdk.core import Stack
from b_elasticsearch_layer.layer import Layer as ElasticsearchLayer
class TestingInfrastructure(Stack):
def __init__(self, scope: Stack):
super().__init__(
scope=scope,
id=f'TestingStack',
... |
the-stack_0_11341 | import json
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--results", type=str, required=True)
parser.add_argument("--claims", type=str, required=True)
parser.add_argument("--t5_output_ids", type=str, required=True)
parser.add_argument("--t5_output", type=str, required=True)
args = parser.par... |
the-stack_0_11343 | #!/usr/bin/env python3
import uuid
import typing
import aiohttp
from aiohttp import web_exceptions
class MumbleException(Exception):
def __init__(self, message: str):
super().__init__()
self.message = message
def ApiSession(timeout: int) -> typing.AsyncContextManager[aiohttp.ClientSession]:
... |
the-stack_0_11344 | import argparse
import json
import os
import subprocess
from bids import BIDSLayout
import datetime
from collections import OrderedDict
from shutil import copy as fileCopy
from shutil import rmtree
def isTrue(arg):
return arg is not None and (arg == 'Y' or arg == '1' or arg == 'True')
def logtext(logfile, textstr... |
the-stack_0_11345 | import os
import requests
import json
import pandas as pd
from datetime import datetime, timedelta
ENV = "sandbox" #Use "sandbox" when testing, and "api" if you have an account at Tradier
API_TOKEN = "" #Fill in your Tradier API Token here
###
#Script starts here
###
def main():
#Get list of symbols from file
... |
the-stack_0_11346 | '''
# Functions
'''
import cv2
import numpy as np
import platform
import time
import sys
from rmracerlib import config as cfg
def contours_detection(mask, frame):
# find shapes
# contours detection
contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
... |
the-stack_0_11347 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
with open("README.rst") as readme_file:
readme = readme_file.read()
with open("HISTORY.rst") as history_file:
history = history_file.read()
requirements = ["Click>=6.0",
"watchd... |
the-stack_0_11350 | from .base import * # flake8: noqa
#env.bool('DJANGO_DEBUG', default=False)
DEBUG = env('DEBUG')
TEMPLATES[0]['OPTIONS']['debug'] = DEBUG
SECRET_KEY = env('DJANGO_SECRET_KEY')
# Compress static files offline
# http://django-compressor.readthedocs.org/en/latest/settings/#django.conf.settings.COMPRESS_OFFLINE
# Turn... |
the-stack_0_11352 | # -*- coding: utf-8 -*-
import os
import re
import time
from bs4 import BeautifulSoup
import requests
import httpx
def rrss(test_str):
regex = r"(@(\w+))"
subst = "<a rel='nofolow norefer' href=\"https://twitter.com/\\2\" target=\"_blank\">\\1</a>"
result = re.sub(regex, subst, test_str, 0, re.IGNORECASE |... |
the-stack_0_11353 | """
Python re-implementation of "Exploiting the Circulant Structure of
Tracking-by-detection with Kernels"
@book{Henriques2012Exploiting,
title={Exploiting the Circulant Structure of Tracking-by-Detection with Kernels},
author={Henriques, Jo?o F. and Rui, Caseiro and Martins, Pedro and Batista, Jorge},
year... |
the-stack_0_11354 | from io import BytesIO
from PIL import Image, ImageDraw
from flask import send_file
from utils.endpoint import Endpoint, setup
from utils.textutils import auto_text_size, render_text_with_emoji
@setup
class KnowYourLocation(Endpoint):
params = ['text']
def generate(self, avatars, text, usernames, kwargs):
... |
the-stack_0_11356 | # Copyright 2017 The Wallaroo Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
the-stack_0_11358 | #!/usr/bin/env python
#
# Copyright (C) 2015 The Android Open Source Project
#
# 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 req... |
the-stack_0_11364 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
CNN completely definable via command line arguments.
Provides create().
Author: Jan Schlüter
"""
import re
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from . import PickDictKey, PutDictKey, ReceptiveField
from .layers impor... |
the-stack_0_11367 |
# coding: utf-8
# In[1]:
import autograd.numpy as np
import autograd.numpy.random as npr
npr.seed(0)
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
from matplotlib.gridspec import GridSpec
import seaborn as sns
sns.set_style("white")
sns.set_context("talk")
color_names = ["... |
the-stack_0_11372 | #!/usr/bin/env python3
# Copyright (c) 2010 ArtForz -- public domain half-a-node
# Copyright (c) 2012 Jeff Garzik
# Copyright (c) 2010-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Bitcoin test... |
the-stack_0_11373 | import pytest
from datetime import time, timedelta
import numpy as np
import pandas as pd
import pandas.util.testing as tm
from pandas.util.testing import assert_series_equal
from pandas import (Series, Timedelta, to_timedelta, isna,
TimedeltaIndex)
from pandas._libs.tslib import iNaT
class Test... |
the-stack_0_11374 | # -*- coding: utf-8 -*-
"""Development settings and globals."""
from __future__ import absolute_import
from os.path import join, normpath
from .base import *
########## DEBUG CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = True
# See: https://docs.djangoproject.com/en/dev/re... |
the-stack_0_11375 | from django import forms
from django.db.models import Q
from common.models import User, Attachments, Comment
from contacts.models import Contact
from events.models import Event
from teams.models import Teams
class EventForm(forms.ModelForm):
WEEKDAYS = (('Monday', 'Monday'),
('Tuesday', 'Tuesday'... |
the-stack_0_11380 | #!/usr/bin/env python3
# Develop a program that finds all the genes in a bacterial genome.
# Program reads FASTA file of genome sequence
# Genes begin with ATG and end with stop codon
# Genes are at least X amino acids long (default 100)
# Genes may be on either strand
# Genes must be given unique names
# Genes must b... |
the-stack_0_11381 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import collections
import os
import re
import time
import numpy as np
import tensorflow as tf
from sklearn.utils import shuffle
# In[2]:
def build_dataset(words, n_words, atleast=1):
count = [["PAD", 0], ["GO", 1], ["EOS", 2], ["UNK", 3]]
counter = collectio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.