content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
ar = [float(i) for i in input().split()]
ar_sq = []
for i in range(len(ar)):
ar_sq.append(ar[i]**2)
ar_sq = sorted(ar_sq)
print(ar_sq[0], end = ' ')
for i in range(1, len(ar_sq)):
if ar_sq[i] != ar_sq[i-1]:
print(ar_sq[i], end = ' ')
| python |
from chroniclr import window
if __name__ == '__main__':
window = window.AppWindow() | python |
import atexit
import sys
import inspect
import json
import time
from .Autocomplete import Autocomplete
from .Connection import Connection, ConnectionError
from .Controller import Controller, ControllerError, parse_key
from .Device import (Device, DeviceError, parse_hex, parse_hsv,
parse_hsv_normal... | python |
# pylint: disable=redefined-outer-name
""" py.test dynamic configuration.
For details needed to understand these tests, refer to:
https://pytest.org/
http://pythontesting.net/start-here/
"""
# Copyright © {{ cookiecutter.year }} {{ cookiecutter.full_name }} <{{ cookiecutter.email }}>
#
# ## LICENS... | python |
import subprocess
import codecs
goal_goals = []
#txt_dirs = ['ted_originals/', 'ted_transcripts/']
#txt_dirs = ['orig_lower/']
txt_dirs = ['trans_preprocessed/', 'orig_preprocessed/']
for txt_dir in txt_dirs:
with codecs.open('goal_goals.txt') as goal_goals_in:
for line in goal_goals_in:
if li... | python |
import unittest
import os
NOT_FATAL = 0
iverilog = "iverilog -y./tb -y./main_unit/ -o ./tb/main_unit__adc_capture__tb.vvp ./tb/main_unit__adc_capture__tb.v"
vvp = "vvp ./tb/main_unit__adc_capture__tb.vvp"
class adc_capture(unittest.TestCase):
def test_adc_capture(self):
self.assertEqual(os.system(iverilog), NOT... | python |
import random
import math
import sys
import copy
# import os
class Bracket:
def __init__(self, teams):
self.numTeams = 1
# self.numTeams = len(teams)
self.teams = list(teams)
self.maxScore = len(max(["Round "]+teams, key=len))
self.numRounds = int(math.ceil(math.log(self.nu... | python |
import re
import numpy
import os
import pdb
### INPUT FILES
rd_folder = "../raw_data/"
traits_file = rd_folder+"data_dental_master.csv"
bio_file_all = rd_folder+"data_sites_IUCN_narrowA.csv"
occurence_file = rd_folder+"occurence_IUCN_%s.csv"
bio_legend_file = rd_folder+"bio_legend.txt"
### OUTPUT FILES
pr_folder = ".... | python |
# -*- coding: utf-8 -*-
#
# Copyright 2017-2020 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in c... | python |
# -*- coding: utf-8 -*-
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import torch
from torchvision.models import resnet
class BasicBlock1d(nn.Module):
def __init__(self, inplanes, planes, stride, size,downsample):
super(BasicBlock1d, self).__init__()
self... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from sqlalchemy import MetaData
from py_privatekonomi.utilities import common
class ModelContext(object):
def __init__(self, context = {}):
self.__context = common.as_obj(context)
self.__context._metadata = MetaData... | python |
from setuptools import setup
setup(
name = 'json2html',
packages = ['json2html'],
version = '1.3.0',
description = 'JSON to HTML Table Representation',
long_description=open('README.rst').read(),
author = 'Varun Malhotra',
author_email = 'varun2902@gmail.com',
url = 'https://github.com... | python |
class Solution:
# @param {integer} A
# @param {integer} B
# @param {integer} C
# @param {integer} D
# @param {integer} E
# @param {integer} F
# @param {integer} G
# @param {integer} H
# @return {integer}
def computeArea(self, A, B, C, D, E, F, G, H):
def area(x, y):
... | python |
def roll_new(name, gender):
pass
def describe(character):
pass | python |
"""Integrate with NamecheapDNS."""
import asyncio
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.const import CONF_HOST, CONF_ACCESS_TOKEN, CONF_DOMAIN
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import async_track_time_interval
from... | python |
celsius = float(input('Insira a temperatura em °C:'))
fahrenheit = celsius * 1.8 + 32
kelvin = celsius + 273.15
print(f'{celsius}°C vale {fahrenheit}°F e {kelvin}K.')
| python |
"""
A Python package module for simulating falling objects with simple aerodynamic drag.
Developed by FIRST Robotics Competition Team 6343 - Steel Ridge Robotics
Strong
Trustworthy
Empowering
Effective
Leadership
"""
__VERSION__ = "1.0.0b1"
| python |
"""
pluginName = dashcam
Senario Continuous Video Series like a Dashcam
----------------------------------------------
You want to take a series of videos like a dash cam.
You can manage disk space and delete oldest videos when disk
is close to full or run video session for a set number of minutes.
Edit the settings ... | python |
load_dotenv('.env.txt') | python |
import discord
from discord.ext import commands
from cogs.utils import checks
from .utils.dataIO import dataIO, fileIO
from __main__ import send_cmd_help
import os
import io
import requests
import json
import asyncio
import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
creditIcon = "htt... | python |
"""
Module to implement a plugin that looks for hard tabs in the files.
"""
from pymarkdown.plugin_manager import Plugin, PluginDetails
class RuleMd040(Plugin):
"""
Class to implement a plugin that looks for hard tabs in the files.
"""
def get_details(self):
"""
Get the details for th... | python |
from django.dispatch import Signal
# providing_args: "orderId", "recipientAmount"
result_received = Signal()
| python |
"""
Generic module for managing manual data transfer jobs using Galaxy's built-in file browser.
This module can be used by various external services that are configured to transfer data manually.
"""
import logging, urllib2, re, shutil
from data_transfer import *
log = logging.getLogger( __name__ )
__all__ = [ 'Manua... | python |
# coding: utf-8
# In[36]:
# In[39]:
import numpy as np
import powerlaw
edges= np.array([[1,2],[0,2],[0,3],[2,3],[3,4],[4,1]])
class karpatiGraphSolution:
def __init__(self,edges):
assert type(edges)==np.ndarray, "input is not an edge list"
self.edgeList=edges
self.numNodes=np.amax(edg... | python |
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectAI import DistributedObjectAI
class GuildManagerAI(DistributedObjectAI):
notify = DirectNotifyGlobal.directNotify.newCategory('GuildManagerAI')
| python |
from xviz.builder.base_builder import XVIZBaseBuilder, CATEGORY
from xviz.v2.core_pb2 import Pose, MapOrigin
class XVIZPoseBuilder(XVIZBaseBuilder):
"""
# Reference
[@xviz/builder/xviz-pose-builder]/(https://github.com/uber/xviz/blob/master/modules/builder/src/builders/xviz-pose-builder.js)
"""
def... | python |
# SPDX-FileCopyrightText: 2022 Cedar Grove Maker Studios
# SPDX-License-Identifier: MIT
"""
touch_calibrator_built_in.py 2022-01-21 v2.1
Author(s): JG for Cedar Grove Maker Studios
On-screen touchscreen calibrator for built-in displays.
When the test screen appears, use a stylus to swipe to the four edges
of the v... | python |
from spaceone.inventory.libs.schema.dynamic_field import TextDyField, ListDyField, \
DateTimeDyField, EnumDyField, SearchField
from spaceone.inventory.libs.schema.resource import CloudServiceTypeResource, CloudServiceTypeResponse, \
CloudServiceTypeMeta
cst_elb = CloudServiceTypeResource()
cst_elb.name = 'Load... | python |
import csv
import matplotlib.pyplot as plt
import numpy as np
CTEs = list()
error = list()
labels = list()
with open('results.csv', 'r') as file:
reader = csv.DictReader(file)
for line in reader:
labels.append(line['permutation'].replace(",","\n"))
CTEs.append(float(line['accuracy']))
... | python |
import numpy as np
import uncertainties.unumpy as unp
def center():
return None # or the arg-number of the center.
def getCenter(args):
# return the average
return (args[1] + args[4])/2
def args():
return ('Amp1', 'Center1', 'Sigma1', 'Amp2', 'Center2', 'Sigma2', 'Offset')
def f(x, A1, x01, sig1... | python |
# check file encoding format
# import chardet
# f = open('test-1000.txt', 'rb')
# result = chardet.detect(f.read())
# print(result)
import codecs
f = codecs.open("dev-1000.txt", 'r', 'GB18030')
ff = f.read()
file_object = codecs.open('dev-1000-new.txt', 'w', 'utf-8')
file_object.write(ff)
# with open("test-1000.txt",... | python |
from newGui import Ui_MainWindow
import sys
from pyqtgraph import PlotWidget ,PlotItem
import os
import pathlib
import pyqtgraph as pg
import pandas as pd
import numpy as np
from PyQt5 import QtCore, QtGui, QtWidgets ,QtPrintSupport
#--------- to save as pdf ------------#
def print_widget(widget, filename):
pr... | python |
# vim: set encoding=utf-8
# Copyright (c) 2016 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 require... | python |
# Generated by Django 2.1 on 2019-06-19 12:32
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('articles', '0004_merge_20190618_0923'),
('articles', '0004_merge_20190618_1311'),
]
operations = [
]
| python |
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include
from django.conf.urls.static import static
urlpatterns = [
path('', include('frontend.urls')),
path('api/', include('backend.urls')),
path('api/auth/', include(... | python |
import logging
import matplotlib.pyplot as plt
import mrcfile
import numpy as np
from scipy.linalg import lstsq
import aspire.volume
from aspire.nufft import anufft
from aspire.numeric import fft, xp
from aspire.utils import crop_pad_2d, grid_2d
from aspire.utils.matrix import anorm
logger = logging.getLogger(__name... | python |
# -*- coding:utf-8 -*-
# Copyright 2015 NEC Corporation. #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License... | python |
#!/usr/bin/env python
import argparse
import astropy.io.fits as pyfits
if __name__=="__main__":
parser = argparse.ArgumentParser(
prog='show_gti.py',
usage='show_gti.py input.fits',
description='Show GTI information',
epilog='',
add_help=True,
)
parser.add_argument(
'input_fits',metavar='input_fits'... | python |
#!/usr/bin/env python3
import os.path
import json
dir_path = os.path.normpath(os.path.join(__file__, '..' , '..' , 'data'))
file_path = os.path.join(dir_path, 'config_file.json')
## get user input-----------------------------------------
ssid = input("Enter wifi ssid: ")
pswd = input("Enter wifi password: ")
name = i... | python |
from abc import ABCMeta
from discord.ext.commands import CogMeta
from bot.utils.redis_cache import RedisCache
__all__ = ['RedisCache', 'CogABCMeta']
class CogABCMeta(CogMeta, ABCMeta):
"""Metaclass for ABCs meant to be implemented as Cogs."""
pass
def pad_base64(data: str) -> str:
"""Return base64 `... | python |
# First
# Hello World
import developer skill
import resilience skill
import persistence skill
pythonapprentice = str('Johnny')
print(f'welcome to the python world {pythonapprentice}')
print('Learning...') | python |
from tweets.models import Comment
from django.db import router
# from posts.views import my_view
from rest_framework import routers
from django.urls.conf import include
from django.urls import path
from tweets.views import TweetViewSet, LikeViewSet, RetweetviewSet, CommentviewSet, index
router = routers.DefaultRouter... | python |
from Repository.eventTriggerOutputGroupingSetupValueRepo import eventTriggerOutputGroupingSetupValueRepo
from sqlalchemy import Table
from sqlalchemy.engine.base import Connection
from sqlalchemy.sql.expression import BinaryExpression
class eventTriggerOutputGroupingSetupValueServices():
__eventTriggerOutputGroupi... | python |
'''
Version and license information.
'''
__all__ = ['__version__', '__versiondate__', '__license__']
__version__ = '1.3.3'
__versiondate__ = '2022-01-16'
__license__ = f'Sciris {__version__} ({__versiondate__}) – © 2014-2022 by the Sciris Development Team'
| python |
# Copyright 2017 The Bazel 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 applicable la... | python |
from __future__ import absolute_import
import os
import sys
import traceback
from webob.exc import HTTPNotFound, HTTPInternalServerError
from .config import Config
from .config import get_config
from .request import Request
from .response import Response
from .exceptions import PageNotFound
from .tools import import_mo... | python |
"""
Clean up & organize outputs from processing workflow batch.
"""
import logging
import os
import re
import zipfile
import shutil
logger = logging.getLogger(__name__)
class OutputCleaner(object):
"""
Moves, renames, and deletes individual output files from a workflow
processing batch for a selected pro... | python |
# Copyright 2018 Comcast Cable Communications Management, LLC
#
# 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... | python |
import sftoolbox
class Variable(object):
"""variable
"""
def __init__(self, project):
"""construct"""
project.add(self)
self.project = project
self.idname = None
def _apply_json(self, data):
"""apply the json data
"""
self.label = data.get('lab... | python |
# Generated by Django 3.2.7 on 2021-12-07 12:54
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('insta', '0002_auto_20211... | python |
# Copyright 2021 Sony Corporation.
# Copyright 2021 Sony Group 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 requi... | python |
#! /usr/bin/env python
'''
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will... | python |
import cv2
from collections import defaultdict
from utils.timer import Timer
_GRAY = [218, 227, 218]
_RED = [0, 0, 255]
_GREEN = [18, 127, 15]
_BULE = [255, 144, 30]
_WHITE = [255, 255, 255]
_BLACK = [0, 0, 0]
colors = [_RED, _GREEN, _BULE, _WHITE]
def get_class_string(class_index, score, dataset):
class_text =... | python |
# The parsing logic is heavily borrowed from the python-nubia project, available at:
# https://github.com/facebookincubator/python-nubia
#
# In compliance with python-nubia's BSD-style license, its copyright and license terms
# are included below:
#
# BSD License
#
# For python-nubia software
#
# Copyright (c) Facebook... | python |
import re
f = open('Dockerfile')
data = f.read()
f.close()
resp = re.sub('RUN','sudo',data)
resp = re.sub('WORKDIR','cd',resp)
resp = re.sub('FROM.*','',resp)
cmd = re.findall('ENTRYPOINT\s+\[(.*?)].*?CMD\s+\[(.*?)\]',resp,re.DOTALL)
if cmd:
cmd = cmd[0]
cmd = cmd[0].strip() + ' ' + cmd[1].strip()
cmd = cm... | python |
# flush
import time
import yaqc
from .._pump import *
def run():
# Flush
# (all volumes in mL unless specified differently)
if True:
print("flush")
for i in range(65):
print(i)
return
# pall_flow_rates is the flow rate of one DSP
# FILL IN PUMP FLOW RATE BE... | python |
from bs4 import BeautifulSoup as bs
from splinter import Browser
import time
import pandas as pd
import lxml
# full "scrape" function, comprised of the four subfunctions
# defined below
def scrape():
# create the overall dictionary to hold all the results
# which will be returned by this function to the flask... | python |
# -*- coding: utf-8 -*-
from shuup_workbench.settings.utils import get_disabled_migrations
from shuup_workbench.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'myapp.sqlite3'
}
}
| python |
#!/usr/bin/env python
import ConfigParser
import log
import obslog
import os
from pyraf import iraf
import shutil
import utils
# ----------------------------------------------------------------------------------------------------------------------
def start(configfile):
"""
Parameters are loaded from gnirs-p... | python |
def jackpot():
if 10*"@" in first_half and 10*"@" in second_half:
return ["True", "@", 10]
elif 10*"#" in first_half and 10*"#" in second_half:
return ["True", "#", 10]
elif 10*"$" in first_half and 10*"$" in second_half:
return ["True", "$", 10]
elif 10*"^" in first_half and 10*... | python |
from ...language.base import parse
from ...utils.ast_to_code import ast_to_code
from ..compiled import GraphQLCompiledDocument
from .schema import schema
def test_compileddocument_from_module_dict():
# type: () -> None
document_string = "{ hello }"
document_ast = parse(document_string)
document = Grap... | python |
import argparse
from random import seed
from yaml import dump
from utils.experiment import test
from utils.utils import *
if __name__ == "__main__":
seed(0)
parser = argparse.ArgumentParser(
description='Test error for a combination of ensembler and weak learner.')
parser.add_argument('dataset', ... | python |
# Copyright (c) 2009-2013, Monoidics ltd.
# Copyright (c) 2013-present, Facebook, Inc.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_functi... | python |
import unittest
from rating.processing import rates
from rating.processing.utils import ConfigurationException
class TestConversion(unittest.TestCase):
def test_conversion_byte_second_to_hour_harder(self):
rating_unit = 'GiB-hours'
metric_unit = 'byte-seconds'
qty = 7e12
converted... | python |
from django.contrib import admin
from users.models import Profile, ConfirmedMail
# Represents Profile and ConfirmedMail models at admin site.
admin.site.register(Profile)
admin.site.register(ConfirmedMail)
| python |
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número '))
r = n1 + n2
print('O resultado da soma é {}'.format(r))
r = n1 - n2
print('O resultado da subtração é {}'.format(r))
r = n1 * n2
print('O resultado da multiplicação é {}'.format(r))
r = n1 / n2
print('O resultado da divisão é {}'.format(... | python |
import pdb, traceback, sys
try:
1/0
except:
extype, value, tb = sys.exc_info()
traceback.print_exc()
pdb.post_mortem(tb)
| python |
# Open3D: www.open3d.org
# The MIT License (MIT)
# See license file or visit www.open3d.org for details
import importlib
import platform
if platform.architecture()[0] == '32bit':
globals().update(importlib.import_module('open3d.win32.32b.open3d').__dict__)
elif platform.architecture()[0] == '64bit':
globals()... | python |
from copy import copy
from contextlib import contextmanager
from logging import getLogger
import tensorflow as tf
from rl.utils.tf_utils import (purge_orphaned_summaries
as _purge_orphaned_summaries)
USE_DEFAULT = object()
logger = getLogger("rl")
class SummaryManager(object):
def ... | python |
num1 = 11
num2 =222
num3 =3333 | python |
""""
Copyright © Krypton 2021 - https://github.com/kkrypt0nn (https://krypt0n.co.uk)
Description:
This is a template to create your own discord bot in python.
Version: 4.1
"""
class UserBlacklisted(Exception):
"""
Thrown when a user is attempting something, but is blacklisted.
"""
def __init__(self,... | python |
a = [0, 0, 0, 1, 1, 1, 3, 3, 6, 6, 9, 9]
print(len(a))
def root(x):
while x != a[x]:
a[x] = a[a[x]]
print(x, a[x])
x = a[x]
return x
def root2(x):
if x != a[x]:
a[x] = root2(a[x])
return a[x]
root2(9)
print(a)
| python |
"""
@Note: Implementation of Knowledge Distillation Algorithms
@Author: LucasX
"""
import copy
import os
import sys
import time
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from sklearn.metrics import confusion_matrix
from torch.o... | python |
import tensorflow as tf
import numpy as np
import os
# from sklearn.manifold._utils import _binary_search_perplexity
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
config = tf.ConfigProto()
config.gpu_options.allow_growth=True
class TSNE:
def __init__(self,n_components=2, perplexity=30, early_exaggeration=12, learning_... | python |
n = int(input())
print(pow(2, n+1)-2)
| python |
import unittest
from typing import Generator, List
from common import open_fixture
BASE_PATTERN = (0, 1, 0, -1)
def decode(s: str) -> List[int]:
return [int(c) for c in s.strip()]
def pattern(position: int) -> Generator[int, None, None]:
skip = True
while True:
for i in range(len(BASE_PATTER... | python |
class newNode:
# Construct to create a newNode
def __init__(self, key):
self.data = key
self.left = None
self.right = None
self.hd = 0
# function should print the topView
# of the binary tree
def topview(root) :
if(root == None) :
return
q = []
mp = dict()
head = 0
root.head = head
# push no... | python |
import tensorflow as tf
import dnnlib.tflib as tflib
from training import dataset
from training import misc
from metrics import metric_base
class ACC(metric_base.MetricBase):
def __init__(self, num_images, minibatch_per_gpu, test_data_dir, test_dataset, **kwargs):
super().__init__(**kwargs)
self.n... | python |
#! /usr/bin/env python
"""
GaussLaguerre_doughnut.py
Calculates the intensity- and phase distributions of
Laguerre-Gauss doughnut laser modes.
cc Fred van Goor, May 2020.
"""
from LightPipes import *
import matplotlib.pyplot as plt
if LPversion < "2.0.0":
print(r'You need to upgrade LightPipes... | python |
from layers import *
class CNN(object):
"""
Implements Convolutional Neural Network
Input shape: [8, 3, 32, 32]---------->[batch size, channels, height, width]
Model Architecture:
----------------------------------------------------------------
Layer (type) Output Shape ... | python |
from collections import Counter
occurrence_list = [item.lower() for item in input().split()]
odd_occurrence = [key for key, value in Counter(occurrence_list).items() if value % 2 != 0]
print(', '.join(list(odd_occurrence)))
| python |
import requests
import wget
import time
r = requests.post("http://10.42.0.255:8000/start")
time.sleep(4)
r = requests.post("http://10.42.0.255:8000/stop")
file_url = 'http://10.42.0.100/get/10'
file_name = wget.download(file_url)
file_name.save(/'pictures/10_picture.png') | python |
#
# Get the language breakdown for a repo
# Usage: ghb langs USER/REPO
#
import operator
import sys
import requests
from .helpers import credentials
URL = "https://api.github.com/repos/%s/languages"
def average(total, number):
return round((number / float(total)) * 100, 2)
def main(args):
username, passw... | python |
# import all necessarily modules
import os.path
import subprocess
import sys
from configparser import ConfigParser
# working dir and extension types will be passed through CLI
try:
workDir = sys.argv[1]
extType = sys.argv[2]
newExtType = sys.argv[3]
except IndexError:
raise Exception("Usage: python3... | python |
import logging
from riffdog.data_structures import FoundItem
from riffdog.resource import register, ResourceDirectory
from ...aws_resource import AWSRegionalResource
logger = logging.getLogger(__name__)
@register("aws_lambda_function")
class AWSLambdaFunction(AWSRegionalResource):
"""
This is aws Lambda fu... | python |
# using: encoding-utf8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import time
import os
from six.moves import cPickle
import utils.opts as opts
import models
from util... | python |
# pylint: disable=C0103
import json
class CampaignObject():
def __init__(self, json_def):
if type(json_def) is str:
json_def = json.loads(json_def)
s = json_def
self.campaignTp = None if 'campaignTp' not in s else s['campaignTp']
self.customerId = None if 'custom... | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2017 bily Huazhong University of Science and Technology
#
# Distributed under terms of the MIT license.
"""Save the paths of crops from the ImageNet VID 2015 dataset in pickle format"""
from __future__ import absolute_import
from __future__ import divi... | python |
import argparse
import datetime as dt
import os
from gpsynth.synthesizer import big_sweep, all_kernels
parser = argparse.ArgumentParser(description='Generate wavetables with Gaussian Processes')
parser.add_argument('path', metavar='path', type=str, nargs='?', default=None,
help='the parent directo... | python |
# coding=utf-8
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.utils
from torch.autograd import Variable
from torch.nn import Parameter, init
from torch.nn._functions.rnn import variable_recurrent_factory, StackedRNN
from torch.nn.modules.rnn import RNNCellBase
from torch... | python |
from flask import Flask, send_from_directory, request
from flask_restful import Api, Resource, reqparse
import json
import numpy as np
import datetime
import csv
import click
from dlw import DLWSubject
STATICS_LOCATION = 'dist'
app = Flask(__name__, static_url_path='', static_folder=STATICS_LOCATION)
api = Api(app)
... | python |
#!/usr/bin/env python
from strip import Strip
import random
import time
import signal
import logging
logger = logging.getLogger(__name__)
def init_logging(log_level):
logging.basicConfig(level=log_level)
# catch signals for tidy exit
_exiting = False
def signal_handler(signal, frame):
global _exiting
_... | python |
from flask_appbuilder import Model
from flask_appbuilder.models.mixins import AuditMixin, FileColumn, ImageColumn
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
"""
You can use the extra Flask-AppBuilder fields and Mixin's
AuditMixin will add automatic timestamp of... | python |
import pytest
from ergaleia import Mini
@pytest.fixture
def mini():
return Mini('foo value=bar')
def test_default(mini):
assert mini.foo == 'bar'
with pytest.raises(TypeError):
mini['foo']
def test_set_attribute(mini):
mini.foo = 'whatever'
assert mini.foo == 'whatever'
with pytest... | python |
import itertools
import pickle
import time
import tarfile
import sys
import uuid
import warnings
from collections import OrderedDict
from pathlib import Path
import hawkeslib as hl
import numpy as np
from joblib import Parallel, delayed
from sklearn.decomposition import NMF
from sklearn.cluster import KMeans, Spectral... | python |
# Copyright (c) Ye Liu. All rights reserved.
from .dynamic_bce import DynamicBCELoss
from .focal import (FocalLoss, FocalLossStar, GaussianFocalLoss, focal_loss,
focal_loss_star, gaussian_focal_loss)
from .ghm import GHMCLoss
from .lasso import (BalancedL1Loss, L1Loss, SmoothL1Loss, balanced_l1_los... | python |
import pandas as pd
t1 = pd.read_csv("lgb_pyst.csv")
t2 = pd.read_csv("lgb_pyst_Keras_4_0.967189916545.csv")
t2['click'] = t2['click']*0.8 +t1['click']*0.2
t2.to_csv('avg_lgb_pyst_Keras_4_2_8.csv', index=False) | python |
# Sum of Polygon Angles
print("Given an n-sided regular polygon n, return the total sum of internal angles (in degrees).")
n_sided = int(input("Enter your n-sided polygon : "))
angles = 2(n_sided)−4×90(n_sided)
print(angles) | python |
#Copyright ReportLab Europe Ltd. 2000-2008
#this test and associates functionality kinds donated by Ian Sparks.
#see license.txt for license details
"""
Tests for internal links and destinations
"""
__version__='''$Id: test_pdfgen_links.py 3288 2008-09-15 11:03:17Z rgbecker $'''
from reportlab.lib.testutils import setO... | python |
import os
from setuptools import setup
def pkg_dir(path):
return os.path.join(os.path.dirname(__file__), path)
with open(pkg_dir('VERSION'), 'r') as f:
version = f.read().strip()
with open(pkg_dir('README.md'), 'r') as f:
readme = f.read()
setup(
name='elasticsearch-collectd-plugin',
version... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.