content stringlengths 5 1.05M |
|---|
import logging
import random as _random
def set_random():
try:
random = _random.SystemRandom()
except NotImplementedError: # pragma: no cover
log.warn("random.SystemRandom() is not available. Using random.Random() " "instead, this means that things will be less random.")
random = _ran... |
import logging
import os
from resources import Resources
LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO')
logging.basicConfig(level=LOG_LEVEL)
logger = logging.getLogger(__name__)
def discovery_apply():
resources = Resources()
#resources.apply_tags_instances()
resources.apply_tags_volumes()
resources.sh... |
import json
fileName = "collections.json"
collection = {}
try:
f = open(fileName)
collection = json.load(f)
except IOError:
collection = {}
finally:
f.close()
headers = {}
for website in collection:
if 'headers' in collection[website]:
for header in collection[website]['headers']:
if header in headers:
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Quantum Bit Core and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from restaurant_management.setup import install
from erpnext.stock.get_item_details import g... |
# -*- encoding: utf8 -*-
import os, io, sys
from glob import glob
from setuptools import setup, find_packages
def read(*names, **kwargs):
return io.open(
os.path.join(os.path.dirname(__file__), *names),
encoding=kwargs.get('encoding', 'utf8')
).read()
data_files = [
('/opt/simmetrica/confi... |
#!/usr/bin/env python
"""
Manage a single PaSD station - control and monitor the hardware via Modbus commands to the specified IP
address, and update the relevant tables in the PaSD database. Monitor the port state tables in that database, and
send updated information as needed to the hardware in the field.
"""
impor... |
"""
Bayesian Hierarchical Clustering
Author: Sam Voisin
July 2020
test_cluster.py
test methods for Cluster class
"""
import pytest
import numpy as np
from scipy.stats import multivariate_normal
from bhc.bayesian_hierarchical_clustering import BHC
class TestBHCHelpers:
"""
set of tests for bhc helper functio... |
import os
__version__ = open(
os.path.join(os.path.dirname(__file__), 'VERSION')).read().strip()
|
#!/usr/bin/env python
"""Unit test for ..."""
import requests
import unittest
from sagas.ofbiz.services import OfService, MetaService
from sagas.ofbiz.entities import MetaEntity
class TestServices(unittest.TestCase):
"""Class to execute unit tests for api.py."""
@classmethod
def setUpClass(self):
... |
from shelf.error_code import ErrorCode
class CloudStorageException(Exception):
def __init__(self, message, error_code):
super(CloudStorageException, self).__init__(message)
self.error_code = error_code
class ArtifactNotFoundError(CloudStorageException):
def __init__(self, artifact_name):
... |
def test_two_runs_clean():
"""
>>> report_fixture = getfixture('allure_report_with_params')
>>> allure_report_first_run = report_fixture('--clean-alluredir', cache=False)
>>> allure_report_second_run = report_fixture('--clean-alluredir', cache=False)
>>> assert_that(allure_report_second_run,
...... |
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
# no-op class for Django < 1.10
class MiddlewareMixin(object):
pass
class DisableCSRF(MiddlewareMixin):
def process_request(self, request):
setattr(request, '_dont_enforce_csrf_checks', True) |
class Solution:
firstLine = set('qwertyuiop')
secondLine = set('asdfghjkl')
thirdLine = set('zxcvbnm')
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
r = []
for word in words:
lowerWord = word.lower()
... |
file = open("clean2_dataproduct.txt", "r")
data = file.read().split("\n")
header = data[0]
products = data[1:]
hang = ["Apple", "Huawei", "Lenovo", "MSI", "HP", "Asus", "Acer", "Dell", "Surface", "LG", "Khác"]
count_daban = [0,0,0,0,0,0,0,0,0,0,0]
for x in range(len(products)):
products[x] = products[x].split(",... |
# Stupid python path shit.
# Instead just add darknet.py to somewhere in your python path
# OK actually that might not be a great idea, idk, work in progress
# Use at your own risk. or don't, i don't care
from scipy.misc import imread
import cv2
def array_to_image(arr):
arr = arr.transpose(2,0,1)
c ... |
#
# @lc app=leetcode.cn id=523 lang=python3
#
# [523] 连续的子数组和
#
# https://leetcode-cn.com/problems/continuous-subarray-sum/description/
#
# algorithms
# Medium (22.76%)
# Likes: 300
# Dislikes: 0
# Total Accepted: 48K
# Total Submissions: 188.2K
# Testcase Example: '[23,2,4,6,7]\n6'
#
# 给你一个整数数组 nums 和一个整数 k ,编写... |
_PCVER_HIGH_ = 0
_PCVER_LOW0_ = 1
_PCVER_LOW1_ = 6
|
from django.db.models import Sum, Avg, Max, Min
from TimeTracker.models import Sites
from datetime import datetime
from .dataFunc import DataInstruct
class Aggregators():
def __init__(self, user_id):
self.now = datetime.now()
self.date = self.now.strftime("%Y-%m-%d")
self.userSites = Site... |
import streamlit as st
import streamlit.components.v1 as components
import numpy as np
import mne
import os
from os import walk
from simpl_eeg import (
eeg_objects,
raw_voltage,
connectivity,
topomap_2d,
topomap_3d_brain,
topomap_3d_head
)
import matplotlib.pyplot as plt
import re
import dat... |
import asynctest
import asynctest.mock as amock
from opsdroid.cli.start import configure_lang
from opsdroid.core import OpsDroid
from opsdroid.matchers import match_event
from opsdroid import events
from opsdroid.parsers.event_type import parse_event_type
class TestParserEvent(asynctest.TestCase):
"""Test the op... |
import matplotlib.pyplot as plt
import sounddevice as sd
sd._initialize() #no idea if this is needed
fs = 44100 # Sample rates
#Selecting device is needed on windows????
sd.query_devices()
sd.default.device = 10 #specific personal setting
seconds = 5
myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels... |
# import word_search_creator.py via the execfile function
execfile("word_search_creator.py")
# test createWordSearch function with 8 randomly generated words
returnedWordSearch = createWordSearch(["seemly", "exotic", "obese", "disagreeable", "earn", "spark", "strengthen", "colossal"])
print stringifyWordSearch(returne... |
'''OpenGL extension APPLE.vertex_array_object
Overview (from the spec)
This extension introduces named vertex array objects which encapsulate
vertex array state on the client side. The main purpose of these
objects is to keep pointers to static vertex data and provide a name
for different sets of static vertex... |
from examples.auth import authorization
from socrata import Socrata
import gntp.notifier
socrata = Socrata(authorization)
with open('files/Permits.csv', 'rb') as file:
# Let's make a socrata view, open a revision on it, and then
# upload and validate our data
(revision, output_schema) = socrata.create(
... |
import asyncio
import hashlib
import hmac
import logging
from fastapi import HTTPException, Request
from gitops_server import settings
from gitops_server.app import app
from gitops_server.logging_config import * # noqa
from gitops_server.workers import DeploymentStatusWorker, DeployQueueWorker
logging.basicConfig(l... |
import json
import random
from typing import List, Optional
from redbot.core import commands
from redbot.core.utils.chat_formatting import box
from redbot.core.data_manager import bundled_data_path
from .cows import cowsay
class Moo:
@classmethod
async def convert(cls, ctx, arg):
if arg[:3].lower() ... |
a = 1
b = 2
# def func():
# global a
# a = 2
# return 3
# c = func()
env()
# a = 1
# def f():
# a = 7
# def g():
# nonlocal a
# a = 5
# def e():
# nonlocal a
# a = 3
# e()
# g()
# return a
# f()
# c = 3
# def... |
# (c) 2012-2018, Ansible by Red Hat
#
# This file is part of Ansible Galaxy
#
# Ansible Galaxy is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by
# the Apache Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
... |
from django.conf.urls import url
from .views import home, base_files
from rest_framework_swagger.views import get_swagger_view
app_name = 'base'
urlpatterns = [
url(r'^$', home, name='home'),
url(r'^(?P<filename>(robots.txt)|(humans.txt))$', base_files, name='base_files'),
url(r'^docs$', get_swagger_view(... |
#!/usr/local/bin/python
# coding: utf-8
import ConfigParser
from sensors import *
from actors import *
class Room:
name = "Room-with-no-name"
insideSensor = None
outsideSensor = None
actor = None
minInsideTemp = 0.0
minHumidDiff = 0.0
ventilationDuration = 0.0
ventilationQuietTime = 0.... |
def f(*args):
print "f(",
for a in args:
print a,
print ")"
s = -1
try:
s = sum(args)
except:
pass
return s
print map(f, range(10))
print map(f, range(9), range(20, 31), range(30, 40), range(40, 50), range(60, 70))
|
# Generated by Django 2.0.4 on 2018-04-09 20:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('siem', '0016_auto_20180326_1743'),
]
operations = [
migrations.AddField(
model_name='limitrule',
name='match_field',... |
# coding: utf-8
# In[1]:
# Load dependencies
import pandas as pd
import numpy as np
from scipy.stats import gmean
from scipy.optimize import curve_fit
import sys
sys.path.insert(0, '../../../statistics_helper')
from CI_helper import *
# # Estimating the total biomass of bacteria and archaea in the terrestrial dee... |
import time
import pytest
vmprof = pytest.importorskip('vmprof')
greenlet = pytest.importorskip('greenlet')
def count_samples(filename):
stats = vmprof.read_profile(filename)
return len(stats.profiles)
def cpuburn(duration):
end = time.time() + duration
while time.time() < end:
pass
def test_... |
# -*- coding: utf-8 -*-
# Calc Version: 1.00
import numpy as np
from project.zone_model_1.CTS import CTS
from project.zone_model_1.CTS import FireCurves
from project.zone_model_1.CTS import FireDynamics
from project.zone_model_1.CTS.FireDynamics import gaseous_chamber_ambient_pressure
from scipy.interpolate import int... |
"""Async functions for interacting with the MongoDB Atlas cluster.
!!None of the stuff below is final and it probably sucks so I'll change the structures later!!
The cluster structure is as follows:
-stk-cluster
-test
-test_data: use for anything
-matches_and_scores
-scores: collectio... |
import os
bot_config_pairs = [
('Primitive spot bot', 'log_primitive_spot_bot.txt')
]
for index in range(len(bot_config_pairs)):
print(f'{index} --> {bot_config_pairs[index][0]}')
LOG_FILE = bot_config_pairs[int(input('Select the config: '))][1]
# Read the log file
log_file_exact_path = os.path.join(os.p... |
#!/usr/bin/python
#Victor del Pino
from pyspark import SparkConf, SparkContext
import string
import sys
def users_average(RDDrating):
ratingsData = RDDrating.filter(lambda line: "userId" not in line).map(
lambda line: (int(line.split(',')[0]), float(line.split(',')[2])))
numRatings = RDDrating.filte... |
# =============================================================================
# Copyright (c) 2016, Cisco Systems, Inc
# 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 sour... |
# Another app modules.
import pytest
# !Triplinker modules:
from accounts.models.TLAccount_frequest import TLAccount
@pytest.mark.django_db
@pytest.fixture
def user_obj():
new_acc = TLAccount.objects.create_user('Robin', 'Long',
'robin@example.com', "M", "1992-09-13", "BY", "secret")
return ... |
import sys
from operator import itemgetter
from Model import Model
import random
import math
import pandas as pd
def find_initial_score(n):
i = 0
sums = 0
scores = []
scoring_sum = 0
if n > 5:
for k in range(2):
remain = n - k
sums = remain + sums
else:
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 18 08:55:28 2020
@author: sopmathieu
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.utils import resample
from sklearn.svm import SVR
from sklearn import svm
from kneed import KneeLocator
from scipy.stats import halfnorm
from sklearn.m... |
# A simplified root dns server
# Nicolas Gundersen neg62
# Anthony Tiongson ast119
import threading
import time
import random
import socket
import sys
def server():
port = int(sys.argv[1])
# This reads the PROJI - DNSTS.txt file
TSFiles = open("PROJI-DNSTS.txt", 'r')
# Create an empty Dictionary
t... |
from app.objects.secondclass.c_fact import Fact
from app.objects.secondclass.c_rule import Rule
from app.utility.rule_set import RuleAction
from app.utility.rule_set import RuleSet
class TestIPRule:
host1 = '127.0.0.1'
host2 = '127.0.1.0'
host3 = '128.0.0.1'
host4 = '127.0.0.0/23'
host5 = '127.0.0... |
# Copyright 2018, Oracle Corporation and/or its affiliates. All rights reserved.
# Licensed under the Universal Permissive License v 1.0 as shown at http://oss.oracle.com/licenses/upl.
connect(sys.argv[1],sys.argv[2],sys.argv[3])
deploy(sys.argv[4],sys.argv[5],sys.argv[6],upload='false',remote='false') |
from pytocl.driver import Driver
from pytocl.car import State, Command
import numpy as np
from Normalize_clean import Normalize
import tensorflow as tf
Ndata = Normalize()
# Initialize accbrk model and session
with tf.Graph().as_default() as accbrk_graph:
saver1 = tf.train.import_meta_graph("./model_accbrk/model_ac... |
import os.path as p
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
self_path = p.dirname(p.abspath(__file__))
root_path = p.dirname(self_path)
import aronnax.driver as drv
from aronnax.utils import working_directory
def Yang_et_al_spin_up():
nx = 200
ny = 200
... |
# -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""Primary container for radio interferometer calibration solutions."""
import copy
import numpy as np
import threading
import warnings
from ..uvbase import UVBase
from .. import paramet... |
import json
def jslint():
predef = ''
first = True
with open('globals') as f:
for line in f:
if not first:
predef += ","
first = False
predef += line.strip()
print(predef)
def jshint():
with open('globals') as f:
L = []
... |
from django.contrib import admin
from blog.models import Blog, Category
from django import forms
from ckeditor.widgets import CKEditorWidget
class BlogAdminForm(forms.ModelForm):
#Set the editor to a WYSIWYG or Markdown
#NOTE: Be sure to edit the template to reflect a change.
body = forms.CharField(widget=... |
import numpy as np
def noppa():
return np.random.randint(1, 7)
pelaajat = [0, 1, 2, 3]
vuorot = 0
lauta = np.zeros((len(pelaajat), 50))
alussa = [4, 4, 4, 4]
maalissa = [0, 0, 0, 0]
# aloitus
# syönti -> uusi -> liike
while (vuorot < 50):
# käy läpi pelaajat
for pelaaja in pelaajat:
# Käytettävi... |
# -*- coding: utf-8 -*-
"""
***********************************
tests.test_model_generation
***********************************
Tests for functions which programmatically generate declarative models.
"""
from datetime import datetime
import pytest
import simplejson as json
import yaml
from sqlalchemy.types import... |
from config import db
from time import time
from datetime import timedelta
from sys import version_info as py_version
from nextcord.ext.commands import Cog
from nextcord import *
from nextcord import slash_command as jeanne_slash, __version__ as discord_version
format = "%a, %d %b %Y | %H:%M:%S"
start_time = time()
c... |
#!/usr/bin/env python3
# Copyright 2019 SchedMD 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 applicable law o... |
from lizardanalysis.utils import auxiliaryfunctions
from lizardanalysis.utils import animal_settings
def body_speed(**kwargs):
"""
calculates the framewise body speed of the spider in mm/s
:param kwargs:
:return:
"""
import numpy as np
from pathlib import Path
data = kwargs.get("data")... |
import logging
from mist.api.rules.plugins import base
from mist.api.rules.plugins import methods
from mist.api.monitoring.victoriametrics import methods as victoria_methods
log = logging.getLogger(__name__)
class VictoriaMetricsBackendPlugin(base.BaseBackendPlugin):
def execute(self, query, rid=None):
... |
from django.test import TestCase
from eth_account import Account
from hexbytes import HexBytes
from gnosis.eth.constants import NULL_ADDRESS
from gnosis.eth.contracts import get_paying_proxy_contract
from gnosis.eth.utils import get_eth_address_with_key
from gnosis.safe import Safe, SafeOperation
from safe_relay_ser... |
import datetime
import logging
import traceback
import boto3
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.core import mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django_cron imp... |
import logging
from helper import utils
from helper.exception import NotPartOfFeatureError, TestFailed, DisabledBy
logger = logging.getLogger(__name__)
class TestUsers():
"""Class containing the tests based on /etc/passwd file"""
failed_before = False
def __new__(cls, client, features):
"""The a... |
"""
Word count topology (in memory)
"""
from bolts import WordCountBolt
from spouts import WordSpout
from streamparse import Grouping, Topology
class WordCount(Topology):
word_spout = WordSpout.spec()
count_bolt = WordCountBolt.spec(inputs={word_spout: Grouping.fields("word")}, par=2)
|
from abc import ABC, abstractmethod
from random import random, randint, choice
from collections import deque
import math
from utils import FormulaAdjacencyList, FormulaClauseCounter, State, StoppingCriterion
class SimulatedAnnealing(ABC):
""" Abstract class of simulated annealing. """
def __init__(
s... |
"""
server.py
revision 11.05.2014
Multi threaded RPC server for selected TF class listening on port 9876
"""
import sys
sys.path.append(r'C:\CROW\ATE')
import os
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
import inspect
import traceback
import tendo.singleton
import xmlrpclib
impor... |
import abc
from collections import OrderedDict
import numpy as np
from gym.spaces import Box
from rlkit.core.eval_util import create_stats_ordered_dict
from rlkit.envs.wrappers import ProxyEnv
from rlkit.core.serializable import Serializable
from rlkit.core import logger as default_logger
class MultitaskEnv(object,... |
#!/usr/bin/python
# Driver for the ADAM-5000
# Made by Bart Garcia on 23/07/2015
import sys, os, serial, threading, getopt , time
import termios, sys, os , fcntl
import datetime
#import command library
def acq_display():
print 'Acquiring \r',
for x in range(10000000):
x=x+1
print 'Acquiring... |
#!/usr/bin/env python
import unittest
from day02 import get_next_button, part1_buttons, part2_buttons
class TestFollowsInstructionsForPart1(unittest.TestCase):
buttons = part1_buttons
cases = (
("5", "ULL", "1"),
("1", "RRDDD", "9"),
("9", "LURDL", "8"),
("8", "UUUUD", "5"),
... |
import random
import quaternion
import habitat_sim
import matplotlib.pyplot as plt
import json
import numpy as np
from habitat_sim.utils.common import quat_to_magnum
import magnum as mn
import habitat
class ContinuousPathFollower(object):
def __init__(self, sim, path, waypoint_threshold):
self._sim = sim... |
# -*- coding: utf-8 -*-
from .oid import OID
from .types.reference import Reference
from .types.enumerations import DataType, StateAction, Icon
__all__ = ['OID', 'Reference', 'DataType', 'StateAction', 'Icon']
|
from .base import BaseState
class ChoiceState(BaseState):
kind = 'choice'
_shape = 'diamond'
_dict_fields = BaseState._dict_fields + ['choices', 'default']
def __init__(self, name=None, choices=None, default=None):
super().__init__(name, next)
self._choices = choices or []
sel... |
from dataclasses import dataclass
@dataclass
class Coordinate:
lat: float
long: float
def __str__(self):
ns = 'NS'[self.lat < 0]
we = 'WE'[self.long < 0]
return f'{abs(self.lat):.1f}°{ns}, {abs(self.long):.1f}°{we}'
sp = Coordinate(-23, 46)
print(sp)
sp.lat = 40
print(sp) |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( str ) :
n = len ( str )
L = [ [ 0 for x in range ( n ) ] for x in range ( n ) ]
for i in range ( n ) :
... |
from or_suite.agents.ambulance.median import *
from or_suite.agents.ambulance.median_graph import *
from or_suite.agents.ambulance.mode_graph import *
from or_suite.agents.ambulance.stable import *
from or_suite.agents.ambulance.median_sklearn import *
from or_suite.agents.ambulance.command_line_metric import * |
import json
import uuid
STORY_INDEX = {}
def space_indenting(lines):
indents = 0
for i in lines:
if len(i) > 0:
if i[0] == '\t':
indents = 0
break
if i[0] == ' ':
for j in i:
if j == ' ':
... |
"""
Legacy Graph types used in Galois.
"""
|
from typing import Generator, Any, Union
def get_inner_dict(source_dict, path_as_list):
result = source_dict
for index in path_as_list:
result = result[index]
return result
def merge_dicts(*dicts):
"""
Merges two or more dicts. If there are duplicate keys, later dict arguments take prece... |
1()
"string"()
|
from .adder import adder
from .printer import printer
from .runner import runner
|
# Copyright (C) 2018 Garth N. Wells
#
# SPDX-License-Identifier: MIT
"""This module contains a collection of functions related to
geographical data.
"""
from haversine import haversine
from .utils import sorted_by_key # noqa
def stations_by_distance(stations, p):
""" Returns the stations in order from closest t... |
from copy import deepcopy
from django.conf import settings as django_settings
from django.core.exceptions import ImproperlyConfigured
from django.test import override_settings
import pytest
from django_guid.config import Settings
def test_missing_identifier(monkeypatch):
"""
Tests that an exception is rais... |
from flask import Blueprint
alert_blueprint = Blueprint('alerts', __name__)
@alert_blueprint.route('/')
def index():
return "This is the alerts index."
@alert_blueprint.route('/new', methods=['POST'])
def create_alert():
pass
@alert_blueprint.route('/deactivate/<string:alert_id>')
def deactivate_alert(alert... |
import math
import torch.nn.functional as F
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch
import numpy as np
from torch.utils import data
from torchvision import transforms as T
model_urls = {
'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
'vgg13': 'https://dow... |
import sys
from PySide2 import QtWidgets
import logging
import os
import re
from textureimporter import importer_dialog
from .. import importer
from .. import setup
import pymxs
rt = pymxs.runtime
def run():
top_level_windows = QtWidgets.QApplication.topLevelWidgets()
no_parent_windows = list()
for wid... |
#!/usr/bin/python
# defining.py
class Some:
@staticmethod
def f():
print ("f() method")
def f():
print ("f() function")
def g():
def f():
print ("f() inner function")
f()
Some.f()
f()
g()
|
# Generated by Django 3.0.7 on 2021-03-15 23:22
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUT... |
# 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
# distributed under t... |
# -*- coding: utf-8 -*-
# coding=utf-8
# Copyright 2019 The SGNMT 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 requir... |
#corbin.mc96@gmail.com
#passed small and large
lines = [line.strip() for line in open('input.in')];
output = open('output.out','w')
for case in range(1,int(lines.pop(0))+1):
print case
r, t = map(int,lines.pop(0).split());
t = int(t)
first_ring = (r+1)**2 - r**2;
hi = t
lo = 0
while hi... |
from .imports import *
from .encoders import AWDLSTMEncoder, QRNNEncoder
from .tricks.dropout import LockedDropout
from .text import SequentialRNN
class LinearDecoder(nn.Module):
initrange = 0.1
def __init__(self, no, nh, dropout, tie_encoder=None, bias=False):
super().__init__()
self.decoder =... |
from threading import Thread
import numpy as np
import cv2
import os
import errno
from os import path
from ndu_gate_camera.api.ndu_camera_runner import NDUCameraRunner
from ndu_gate_camera.utility import constants, image_helper, onnx_helper
class EmotionRunner(Thread, NDUCameraRunner):
def __init__(self, config... |
'''
This script shows 3 examples of plotting the json data generated:
- Plotting a stacked bar graph of the exclusive max percents of functions for multiple runs.
- Plotting the profiling data of a union of the top n expensive functions for multiple runs.
- Plotting the profiling data of a specified collection of funct... |
import requests
# enter the API key got from Cuttly
API_key = "insert your API key here"
# get the URL you want to shorten
URL = input('Enter The URL: ')
# preferred name in the URL
API_URL = f"https://cutt.ly/api/api.php?key={API_key}&short={URL}"
# make the request
data = requests.get(API_URL).json()[... |
def register(config):
return MockReader(config)
class MockReader:
def __init__(self, config):
self.config = config
|
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.dispatch import receiver
from djasync.signals import async_receiver
from django.db.models import signals
class Profile(models.Model):
GENDER_NA = 0
GENDER_FEMALE = 1
... |
"""
Access to relabelling from templates.
"""
import logging
from django import template
from django.template import Context
from CreeDictionary.CreeDictionary.relabelling import LABELS
from CreeDictionary.utils.types import FSTTag
from crkeng.app.preferences import ParadigmLabel
logger = logging.getLogger(__name__... |
"""Module interpolating mathematical functions out of support points"""
from scipy.interpolate import interp1d, lagrange, CubicSpline
def interpolator(x_sup, y_sup, method):
"""Interpolates a mathematical function from a given set of
points using either linear, polynomial or cubic spline for the
interpol... |
from __future__ import print_function, division
import os
import sys
sys.path.append("..") # Adds higher directory to python modules path.
import torch
import numpy as np
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
from core.point_cloud.point_cloud_ops im... |
from lib.slack.accessory.button import Button, ButtonStyle
class ReadyButton(Button):
def __init__(self, ready_text: str, not_ready_text: str, prefix: str, ready=False):
super().__init__(text=ready_text if ready else not_ready_text,
style=ButtonStyle.PRIMARY if ready else ButtonSt... |
from datetime import datetime
class GormanianDatetime:
_MONTHS = ['March', 'April', 'May', 'June', 'Quintilis', 'Sextilis', 'September', 'October', 'November', 'December',
'January', 'February', 'Gormanuary']
_DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']... |
from django.core.mail import send_mail
from homepage.models import User
import decimal
AUCTION_POSTED="""
\n
Your auction has been accepted.
\n
Thank you for using Alpha Auctions and good luck!
\n
You can view the status of your auction at http://alpha-auctions.herokuapp.com/accounts/login
\n
\n
Alpha Auctions Team... |
from tkinter import *
from tkinter import colorchooser
def clique():
color = colorchooser.askcolor()
janela.config(background=color[1])
janela = Tk()
botao = Button(text="Clica aqui", command=clique)
botao.pack()
janela.geometry("500x500")
janela.mainloop() |
import numpy as np
from nltk.corpus import brown
# Split a text into chunks
def splitter(data, num_words):
words = data.split(' ')
output = []
cur_count = 0
cur_words = []
for word in words:
cur_words.append(word)
cur_count += 1
if cur_count == num_words:
output... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.