filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_25329 | import os
from pathlib import Path
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
from keras.optimizers import Adam
from keras.applications.vgg16 import VGG16
from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Flatten
from keras.callbacks import ModelCheckp... |
the-stack_106_25331 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.application.app} and L{twisted.scripts.twistd}.
"""
from __future__ import absolute_import, division
import errno
import inspect
import signal
import os
import sys
try:
import pwd
import grp
except ImportError:
... |
the-stack_106_25335 | #!/usr/local/autopkg/python
# pylint: disable = invalid-name
'''
Copyright (c) 2022, dataJAR Ltd. 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 m... |
the-stack_106_25336 | """Word/Symbol level next step prediction using Recurrent Highway Networks - Theano implementation.
To run:
$ python theano_rhn_train.py
References:
[1] Zilly, J, Srivastava, R, Koutnik, J, Schmidhuber, J., "Recurrent Highway Networks", 2016
[2] Gal, Y, "A Theoretically Grounded Application of Dropout in Recurrent Ne... |
the-stack_106_25341 | """Segment objects are used by the human module. A segment has a position, and
an orientation. All constituent solids of a segment have the same orientation.
That is to say that the base of the segment is at a joint in the human. The
user does not interact with this module.
"""
# Use Python3 integer division rules.
fr... |
the-stack_106_25342 | from csv import DictReader
from functools import partial
from typing import Dict
from vnpy.event import Event, EventEngine
from vnpy.trader.engine import MainEngine
from vnpy.trader.ui import QtCore, QtWidgets
from ..engine import (APP_NAME, EVENT_RADAR_LOG, EVENT_RADAR_RULE,
EVENT_RADAR_UPDATE, ... |
the-stack_106_25343 | import copy
import hashlib
import json
import os
import tempfile
import time
import logging
import sys
import click
import random
import yaml
try: # py3
from shlex import quote
except ImportError: # py2
from pipes import quote
from ray.autoscaler.autoscaler import validate_config, hash_runtime_conf, \
h... |
the-stack_106_25345 | """
LC 504
Given an integer num, return a string of its base 7 representation.
Example 1:
Input: num = 100
Output: "202"
Example 2:
Input: num = -7
Output: "-10"
"""
class Solution:
def convertToBase7(self, num: int) -> str:
if num == 0:
return '0'
base = 7
sign = ""
... |
the-stack_106_25346 | import bisect
import copy
import itertools
import logging
import numpy as np
import operator
import pickle
import torch.utils.data
from fvcore.common.file_io import PathManager
from tabulate import tabulate
from termcolor import colored
from detectron2.structures import BoxMode
from detectron2.utils.comm import get_wo... |
the-stack_106_25347 | from sqllineage.models import Table
from sqllineage.runner import LineageRunner
def helper(sql, source_tables=None, target_tables=None):
lp = LineageRunner(sql)
assert set(lp.source_tables) == (
set() if source_tables is None else {Table(t) for t in source_tables}
)
assert set(lp.target_tables... |
the-stack_106_25348 | #!/usr/bin/env python
#
# (C) Copyright 2012-2013 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its ... |
the-stack_106_25349 | import csv
import os
import sys
import django
def read_apply_csv():
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CSV_PATH = os.path.join(BASE_DIR, 'recruitment/total.csv')
with open(CSV_PATH, 'r', encoding='utf-8') as reader:
lines = reader.readlines()
rcsv = csv.rea... |
the-stack_106_25350 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import cstr, cint, getdate, get_first_day, get_last_day, date_diff, add_days
from frappe import msgprint, _
from calenda... |
the-stack_106_25351 | #!C:\Python279\python.exe
# See http://cens.ioc.ee/projects/f2py2e/
import os, sys
for mode in ["g3-numpy", "2e-numeric", "2e-numarray", "2e-numpy"]:
try:
i=sys.argv.index("--"+mode)
del sys.argv[i]
break
except ValueError: pass
os.environ["NO_SCIPY_IMPORT"]="f2py"
if mode=="g3-numpy":
... |
the-stack_106_25355 | #!/usr/bin/env python
from github3 import login
from time import sleep
from random import randint
print("go to https://github.com/settings/tokens/new to get an access token")
gh_token = raw_input("what's your access token? ")
owner = raw_input("what user owns the repo? ")
reponame = raw_input("what's the repo called?... |
the-stack_106_25356 | import csv
from collections import defaultdict
import json
def _process_post_codes():
d = defaultdict(lambda: defaultdict(dict))
with open('./scripts/oz_postcodes.csv') as csvfile:
reader = csv.reader(csvfile)
next(reader, None) # skip the headers
for row in reader:
state =... |
the-stack_106_25357 | try:
import sys
import os
sys.path.append(
os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'../'
# '../src'
)
)
)
except:
raise
import unittest
from src.calculadora import soma
print('a',soma(1,2))
... |
the-stack_106_25359 | import pytest
import layabase
import layabase.mongo
@pytest.fixture
def controller() -> layabase.CRUDController:
class TestCollection:
__collection_name__ = "test"
int_value = layabase.mongo.Column(
int, allow_comparison_signs=True, default_value=3
)
controller = layabas... |
the-stack_106_25360 | """CAP-6619 Deep Learning Fall 2018 term project
MNIST with standard deep neural network and batch normalization
Create shell scripts with all tests we need to execute.
Batch normalization paper: https://arxiv.org/pdf/1502.03167.pdf
Some default values from Keras to keep in mind:
* Learning rate: SGD=0.01, RMSprop=... |
the-stack_106_25361 | """Tests of the material components"""
# pylint: disable=redefined-outer-name,protected-access
# pylint: disable=missing-function-docstring,missing-module-docstring,missing-class-docstring
import param
import pytest
from awesome_panel_extensions.frameworks.material import Select
class ParameterizedMock(param.Paramet... |
the-stack_106_25362 | # MIT License
#
# (C) Copyright [2020-2021] Hewlett Packard Enterprise Development LP
#
# 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-stack_106_25363 | import copy
import datetime as dt
import os
import shutil
import typing
from argparse import Namespace
from pathlib import Path
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
import optuna
import optuna.visualization as optv
import pandas as pd
import pytorch_lightning as pl
impor... |
the-stack_106_25364 | from django.core.management.base import BaseCommand
from iplookup.rbl import RBLSearch
from coredata.models import Ip, Rbl
import ipaddress
class Command(BaseCommand):
help = 'Check ip address agaist RBLs'
def add_arguments(self, parser):
parser.add_argument('--ips',
nargs... |
the-stack_106_25365 | ''''
An example of how to by pass NRP. Solution to this problem is dynamic infernce as discussed in the paper.
Dynamic inference is achieved by perturbing the incoming sample with random noise.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
import tor... |
the-stack_106_25369 | import os
import jinja2
import helpers.javatype as javatype
import datetime
import pymajorme_config
import hashlib
from helpers.pack import pack
from helpers.constraints import *
TEMPLATE_NAME = 'sql.template'
def filter_sql_type(attribute_type):
sql_types = { 'Integer' : 'INT',
'String' : 'VA... |
the-stack_106_25370 | # Load/combine extracted feature sets, remove highly correlated features, and build models
from collections import OrderedDict
import warnings
import argparse
import pandas as pd
import numpy as np
from sklearn import ensemble, pipeline, model_selection, metrics
import xgboost
from skopt import BayesSearchCV, space
i... |
the-stack_106_25371 |
def test_tags(client):
client.session.get.return_value.json.return_value.update({'tags': [1, ]})
client.tags()
client.session.get.assert_called_once_with('tags')
def test_apply_tag(client):
client.session.post.return_value.status_code = 204
expected_payload = {
'tags': [
{
... |
the-stack_106_25372 | import json
import os
import requests
import time
from requests.auth import AuthBase
from pprint import pprint
from dotenv import load_dotenv
load_dotenv(verbose=True) # Throws error if it can't find .env file
# Retrieves and stores credential information from the '.env' file
#BEARER_TOKEN = os.getenv("TWITTER_BEARE... |
the-stack_106_25373 | import logging
import neptune
from validate_utils import validate
LOG = logging.getLogger(__name__)
max_epochs = 1
def main():
# load dataset.
test_data = neptune.load_test_dataset(data_format='txt', with_image=False)
# read parameters from deployment config.
class_names = neptune.context.get_param... |
the-stack_106_25377 | #!/usr/bin/env python3
from datetime import datetime, timedelta
## TODO: just scrape, https://www.timeanddate.com/countdown/generic?iso=20170411T070001&p0=1440&msg=DO+SFO2+DOWNTIME&ud=1&font=cursive
bad_format = "Please use correct format: .countdown 2012 12 21 You can also try: '.nye -5'"
## 2036 02 07
def get_outp... |
the-stack_106_25379 | from pyspark import SparkConf, SparkContext
conf = SparkConf().setMaster("local").setAppName("WordCount")
sc = SparkContext(conf=conf)
input = sc.textFile("../data/Book.txt")
words = input.flatMap(lambda x: x.split())
wordCounts = words.countByValue()
for word, count in wordCounts.items():
cleanWord = word.encod... |
the-stack_106_25380 | from html import HTML
from visualizer import Visualizer
visualizer = Visualizer()
# create website
web_dir = "path_of_webpage"
webpage = HTML(web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (
opt.name, opt.phase, opt.which_epoch))
# test
for i, data in enumerate(dataset):
visuals = model.get_current_visuals(... |
the-stack_106_25381 | # Copyright (c) 2013 Mirantis, 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... |
the-stack_106_25382 | #!/usr/bin/env python
# coding: utf-8
import torch
import graphgallery
import torch_geometric
print("GraphGallery version: ", graphgallery.__version__)
print("Torch version: ", torch.__version__)
print("Torch_Geometric version: ", torch_geometric.__version__)
'''
Load Datasets
- cora/citeseer/pubmed
''... |
the-stack_106_25384 | from django.urls import path
from .views import (PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
UserPostListView
)
from . import views
urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('user/<str:username>', UserPostListView.as_view(), name='user-posts'... |
the-stack_106_25388 | # coding=utf-8
# Copyright 2020-present the HuggingFace Inc. team.
#
# 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 ap... |
the-stack_106_25389 | from rpython.rtyper.annlowlevel import llstr
from rpython.rtyper.lltypesystem import lltype, rffi
from rpython.rtyper.lltypesystem.rstr import copy_string_to_raw
from rpython.rlib.objectmodel import keepalive_until_here, we_are_translated
from rpython.rlib import jit
from pypy.interpreter.error import OperationError, ... |
the-stack_106_25390 | import mock
from django.test import TestCase
from morango.sync.utils import SyncSignal
from morango.sync.utils import SyncSignalGroup
class SyncSignalTestCase(TestCase):
def test_defaults(self):
signaler = SyncSignal(this_is_a_default=True)
handler = mock.Mock()
signaler.connect(handler)
... |
the-stack_106_25391 | from __future__ import absolute_import
from rest_framework.response import Response
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.serializers import serialize
from sentry.models import EnvironmentProject
environment_visibility_filter_options = {
'all': lambda queryset: queryset,
'hidd... |
the-stack_106_25393 | from src.scenario.scenario import Scenario
from src.grid.electrical_vehicle import EV
import numpy as np
def create_scenario_evs_locations(grid, scenario, t_current_ind, observe_ev_locations='full'):
t_current_hr = scenario.timesteps_hr[t_current_ind]
if observe_ev_locations == 'full':
new_to_old_evs_... |
the-stack_106_25394 | import _plotly_utils.basevalidators
class ColorsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="colorsrc", parent_name="surface.hoverlabel.font", **kwargs
):
super(ColorsrcValidator, self).__init__(
plotly_name=plotly_name,
paren... |
the-stack_106_25395 | # -*- coding: utf-8 -*-
from __future__ import print_function, division
"""
.. note::
These are the database functions for SPLAT
"""
# imports: internal
import base64
import copy
import csv
import glob
import os
import re
import requests
from shutil import copyfile
import time
# imports: external
import as... |
the-stack_106_25399 | from torch import nn
from torch.nn import functional as F
import torch
class CBOW(nn.Module):
def __init__(self, hidden_dim, embeddings, keep_rate):
super(CBOW, self).__init__()
self.__name__ = 'CBOW'
## Define hyperparameters
self.embedding_dim = embeddings.shape[1]
self.d... |
the-stack_106_25401 | #!/usr/local/bin/python3.4
# ------------------------------------------------
# Copyright 2014 AT&T Intellectual Property
# 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:/... |
the-stack_106_25403 | # encoding: utf8
#
# spyne - Copyright (C) Spyne contributors.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version... |
the-stack_106_25404 | # 1. Found a nice solution from 'Discuss'
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return len(nums) != len(set(nums))
# 2. Solution using "Dictionary" which is the implementation of "Hash Table" in Python.
# NOTE it only works in P... |
the-stack_106_25405 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import common
class TestMoveExplode(common.TransactionCase):
def setUp(self):
super(TestMoveExplode, self).setUp()
# Usefull models
self.SaleOrderLine = self.env['sale.order... |
the-stack_106_25406 | def test_parse_json_urls_file(
json_urls_provider, expected_urls_in_json_file, expected_regexp_in_json_file
):
parsed_urls = set()
parsed_regexp_list = set()
for url_data in json_urls_provider:
parsed_urls.add(str(url_data.url))
parsed_regexp_list.add(url_data.regexp)
assert parsed_... |
the-stack_106_25408 | from faker import Faker
class User:
def __init__(self, email: str, first_name: str, last_name: str,
age: int, address: str, gender: str, job: str, has_children_under_sixteen: bool):
self.email = email
self.first_name = first_name
self.last_name = last_name
self.age... |
the-stack_106_25409 | #!/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.
"""
Base script for running TOD model-model chats.
For example, to extract gold ground truth data from the holdout versi... |
the-stack_106_25411 | from django.shortcuts import render, redirect
from hoax.models import Corpus
from django.db import connection
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import csv
from django.http import HttpResponse
from nltk.book import *
from c... |
the-stack_106_25414 | from easydict import EasyDict
from ding.entry import serial_pipeline
nstep = 3
lunarlander_dqn_default_config = dict(
exp_name='lunarlander_dqn_priority',
env=dict(
# Whether to use shared memory. Only effective if "env_manager_type" is 'subprocess'
manager=dict(shared_memory=True, ),
#... |
the-stack_106_25415 | # coding=utf-8
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distr... |
the-stack_106_25416 | #!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import argparse
import onnx
import os
import pathlib
import sys
from .onnx_model_utils import make_dim_param_fixed, make_input_shape_fixed, fix_output_shapes
def make_dynamic_shape_fixed_helper():
... |
the-stack_106_25417 | """
Functions for applying functions that act on arrays to xarray's labeled data.
"""
import functools
import itertools
import operator
from collections import Counter
from typing import (
TYPE_CHECKING,
AbstractSet,
Any,
Callable,
Dict,
Hashable,
Iterable,
List,
Mapping,
Optiona... |
the-stack_106_25419 | import sys
import time
import sqlite3 as sql
import Adafruit_DHT
DB_NAME = "db/data.db"
SLEEP_TIME = 2 # in seconds
FREQUENCY = 1 # in seconds (every 1 minute)
DHT11_SENSOR = Adafruit_DHT.DHT11
DHT11_SENSOR_PIN = 4
def get_data():
humidity, temperature = Adafruit_DHT.read_retry(DHT11_SENSOR, DHT11_SENSOR_PIN)
if h... |
the-stack_106_25420 | def funny_division(anumber):
try:
if anumber == 13:
raise ValueError("13 is an unlucky")
return 100 / anumber
except ZeroDivisionError:
return "Enter a number other than zero"
except TypeError:
return "Enter a numerical value"
except ValueError:
print(... |
the-stack_106_25422 | import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.preprocessing import MinMaxScaler
# We use display so that we can do multiple nice renderings of dataframes
# in Jupyter
from IPython.display import display
# Exercise 1
data = pd.re... |
the-stack_106_25425 | #!/usr/bin/env python
"""
Python class wrapper for data fitting.
Includes the following external methods:
getFunctions returns the list of function names (dictionary keys)
FitRegion performs the fitting
Note that FitRegion no longer attempts to plot.
"""
# January, 2009
# Paul B. Manis, Ph.D.
# UNC Chapel Hill
# Depa... |
the-stack_106_25426 | # django imports
from django import forms
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.template.loader import render_to_string
# portlets imports
from portlets.models import Portlet
# lfs imports
from lfs.catalog.models import Product
from lfs.caching.utils i... |
the-stack_106_25427 | # -*- coding:utf-8 -*-
# @author xupingmao
# @since 2022/02/04 22:45:35
# @modified 2022/02/13 18:11:19
# @filename 006_class.py
import time
import random
try:
randint_wrap = random.randint
except:
# micropython
def randint_wrap(a, b):
return a + random.getrandbits(32) % (b-a)
class TestClass:
... |
the-stack_106_25429 | import os
import random
from locust import task, between
from locust.contrib.fasthttp import FastHttpUser
from random import choice
from random import randint
class UserBehavior(FastHttpUser):
connection_timeout = 300.0
wait_time = between(2, 10)
# source: https://tools.tracemyip.org/search--ip/list
... |
the-stack_106_25431 | # emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil; coding: utf-8 -*-
# ex: set sts=4 ts=4 sw=4 et:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license te... |
the-stack_106_25432 | # Importing the necessary libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pickle
from sklearn.linear_model import LinearRegression
# Reading the dataset
dataset = pd.read_csv(r"C:\Users\olutu\ML_SALARY_PRED\model_files\hiring.csv", encoding = "utf-8")
# Filling missing value... |
the-stack_106_25433 | # coding: utf-8
import sys, os
sys.path.append(os.pardir) # 親ディレクトリのファイルをインポートするための設定
import numpy as np
import matplotlib.pyplot as plt
from simple_convnet import SimpleConvNet
from matplotlib.image import imread
from common.layers import Convolution
def filter_show(filters, nx=4, show_num=16):
"""
c.f. http... |
the-stack_106_25434 | from setuptools import setup, find_packages
from setuptools.command.test import test as test_command
import sys
class Tox(test_command):
user_options = [('tox-args=', 'a', "Arguments to pass to tox")]
def initialize_options(self):
test_command.initialize_options(self)
self.tox_args = None
... |
the-stack_106_25437 | from collections import namedtuple
import vispy
from vispy.color import Color
from vispy.scene import Node
from vispy.scene.visuals import Polygon, Ellipse, Rectangle, RegularPolygon
from vispy import app, scene
from vispy.app import use_app
from vispy.visuals.shaders import Function
from vispy.visuals.collections im... |
the-stack_106_25438 | #!/usr/bin/env python
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# ---------------------------------------------... |
the-stack_106_25440 | """
Helper functions for coordinate operations
"""
import numpy as np
from scipy.spatial import cKDTree, SphericalVoronoi
def sph2cart(r, theta, phi):
"""Transforms from spherical to Cartesian coordinates.
Spherical coordinates follow the common convention in Physics/Mathematics
Theta denotes the elevati... |
the-stack_106_25442 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
import sys
import os
import subprocess
import argparse
import signal
from multiprocessing import Pool
from Bio import SeqIO
from Bio.SeqIO.FastaIO import SimpleFast... |
the-stack_106_25443 | import matplotlib.pyplot as plt
from xlrd import open_workbook
import xlsxwriter
import numpy as np
file_name = '../result_draw/data_rate_waiting.xlsx'
workbook = xlsxwriter.Workbook(file_name)
worksheet = workbook.add_worksheet()
X = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
book1 = open_workbook('../results/res... |
the-stack_106_25444 | """Service for creating pull requests."""
from typing import Dict, List, NamedTuple, Optional
import inject
from emm.clients.evg_service import EvgService
from emm.clients.git_proxy import LOGGER, GitProxy
from emm.clients.github_service import GithubService
from emm.models.repository import Repository
from emm.optio... |
the-stack_106_25445 | import subprocess
from subprocess import CalledProcessError
import sys
import psutil
import platform
from timeit import default_timer as timer
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def measure(cmd, proc_name):
try:
start = timer()
cmdp = subprocess.Popen(cmd.spli... |
the-stack_106_25447 | import random
import numpy as np
import os
from collections import Counter
import logging
import torch
import dadmatools.models.common.seq2seq_constant as constant
from dadmatools.models.common.data import map_to_ids, get_long_tensor, get_float_tensor, sort_all
from dadmatools.models.lemma.vocab import Vocab, MultiVoc... |
the-stack_106_25448 | # -*- coding: utf-8 -*-
'''Applications' windows module
'''
from __future__ import with_statement, division, absolute_import, print_function
import sys
from PyQt4 import (QtGui, uic)
#from PyQt4.QtCore import QEvent
__import__('resources')
from backend import DayLogger, get_label_slug
def get_call_info(obj, args... |
the-stack_106_25449 | import numpy as np
import numpy.random as rnd
from ..common.utils import *
from ..common.data_plotter import *
from ..common.gen_samples import *
from .aad_support import *
"""
To run:
pythonw -m ad_examples.aad.test_tree_detectors
"""
def compute_n_found(scores, labels, budget=-1):
if budget < 0:
budge... |
the-stack_106_25450 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
the-stack_106_25452 | """
Implements the DIAL-protocol to communicate with the Chromecast
"""
from collections import namedtuple
from uuid import UUID
import logging
import requests
from .const import CAST_TYPE_CHROMECAST
from .discovery import get_info_from_service, get_host_from_service_info
XML_NS_UPNP_DEVICE = "{urn:schemas-upnp-org:... |
the-stack_106_25454 | from os import makedirs, path
from typing import List
from .common import (
Author, BoolValue, Category, Created, Deprecated, Description, EnumValue, Keywords, Name, Position, Rotation,
StringValue, UUIDValue, Version
)
from .helper import indent_entities
class DefaultValue(StringValue):
def __init__(se... |
the-stack_106_25455 | import os
import urllib
import platform
import warnings
from functools import wraps
import matplotlib.pyplot as plt
import numpy.distutils.system_info as sysinfo
import pkg_resources
import pytest
from matplotlib.testing import compare
from astropy.wcs.wcs import FITSFixedWarning
import sunpy.map
from sunpy.tests im... |
the-stack_106_25456 | '''
Copyright 2015 Planet Labs, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
... |
the-stack_106_25457 | import os
import numpy as np
from PIL import Image
from gym_pcgrl.envs.probs.problem import Problem
from gym_pcgrl.envs.helper import get_range_reward, get_tile_locations, calc_num_regions, calc_certain_tile, run_dikjstra
"""
Generate a fully connected GVGAI zelda level where the player can reach key then the door.
A... |
the-stack_106_25458 | import keras # work around segfault
import sys
import numpy as np
import random
import torch
import torch.nn as nn
from torch.autograd import Variable
sys.path.append('../pytorch2keras')
from converter import pytorch_to_keras
class TestLeakyReLU(nn.Module):
"""Module for PReLu conversion testing
"""
d... |
the-stack_106_25461 | # 13. Roman to Integer
# Time: O(len(s))
# Space: O(1)
class Solution:
def romanToInt(self, s: str) -> int:
roman_map = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,
'IV':4,'IX':9,
'XL':40,'XC':90,
'CD':400,'CM':900}
num = 0
... |
the-stack_106_25462 | import json
import os
import urllib
from maccli.helper.exception import InstanceNotReadyException, InstanceDoesNotExistException, BashException, \
MacParameterNotFound, MacJsonException, MacParseParamException
import maccli.service.instance
__author__ = 'tk421'
import re
import maccli
import maccli.helper.cmd
impor... |
the-stack_106_25463 | # -*- coding: utf-8 -*-
"""The app module, containing the app factory function."""
import math
import logging
from slugify import slugify
from flask import Flask, render_template
from liar import commands, public
from liar.assets import assets
from liar.extensions import cache, csrf_protect, debug_toolbar, mongo, sc... |
the-stack_106_25465 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: dorefa.py
# Author: Yuxin Wu <ppwwyyxxc@gmail.com>
import tensorflow as tf
from tensorpack.utils.argtools import graph_memoized
@graph_memoized
def get_dorefa(bitW, bitA, bitG):
"""
return the three quantization functions fw, fa, fg, for weights, activati... |
the-stack_106_25466 | # ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# Copyright (c) 2008-2021 pyglet contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the follo... |
the-stack_106_25468 | import os
import sys
from argparse import ArgumentParser
import cv2
import numpy as np
from svd import sklearn_svd_implementation, numpy_svd_implementation, custom_svd_implementation
def compress_image(img, k, svd_implementation=custom_svd_implementation):
def compress_channel(data, k, implementation):
... |
the-stack_106_25469 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright 2015 Pascual Martinez-Gomez
#
# 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
#
... |
the-stack_106_25471 | import tempfile
import os
from django.test import TestCase
from ambition_utils.tests.models import FakeModel
from ambition_utils.sql import StringSQL, FileSQL
class SQL(TestCase):
def setUp(self):
self.simple_query = 'SELECT * FROM tests_fakemodel;'
self.param_query = 'SELECT * FROM tests_fakemode... |
the-stack_106_25472 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2019 the HERA Project
# Licensed under the MIT License
"""Command-line drive script for redundant calibration (firstcal, logcal, omnical, remove_degen).
Includes solar flagging and iterative antenna exclusion based on chi^2."""
import argparse
from hera_cal.re... |
the-stack_106_25473 | import argparse
import os
from util import util
import torch
import models
import data
class BaseOptions():
"""This class defines options used during both training and test time.
It also implements several helper functions such as parsing, printing, and saving the options.
It also gathers additional opti... |
the-stack_106_25476 | import json
import logging
import uuid
from typing import Dict
from localstack.services.awslambda.lambda_executors import InvocationException, InvocationResult
from localstack.utils.aws.aws_models import LambdaFunction
from localstack.utils.aws.aws_stack import connect_to_service, firehose_name, get_sqs_queue_url
from... |
the-stack_106_25477 | # Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
the-stack_106_25478 | import tensorflow as tf
from active_learning_ts.experiments.experiment_runner import ExperimentRunner
from tests.experiments.blueprints.data_set_blueprint import DataSetBlueprint
def test_basic_functionality():
er = ExperimentRunner([DataSetBlueprint])
er.run()
test = [tf.random.uniform(shape=(3,), minv... |
the-stack_106_25479 | import torch
from torch.utils.data import Dataset
import os
from torchvision.io import read_image
import matplotlib.pyplot as plt
import numpy as np
#-------------------------------------------------------------------------------------------------------------------------------------------------------
## Update the fo... |
the-stack_106_25480 | from packaging.version import Version
import os
import warnings
import yaml
import mxnet as mx
import numpy as np
import pandas as pd
import pytest
from mxnet import context as ctx
from mxnet.gluon import Trainer
from mxnet.gluon.data import DataLoader
from mxnet.gluon.nn import HybridSequential, Dense
import mlflow
... |
the-stack_106_25482 | """Resamples a GeoTIFF file to make a KML and a PNG browse image for ASF"""
import argparse
import logging
import os
import sys
from osgeo import gdal
from hyp3lib.resample_geotiff import resample_geotiff
def makeAsfBrowse(geotiff: str, base_name: str, use_nn=False, width: int = 2048):
"""
Make a KML and P... |
the-stack_106_25483 | # -*- coding: utf-8 -*-
from __future__ import print_function
from warnings import catch_warnings
from datetime import datetime
import itertools
import pytest
from numpy.random import randn
from numpy import nan
import numpy as np
from pandas.compat import u
from pandas import (DataFrame, Index, Series, MultiIndex... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.