content stringlengths 5 1.05M |
|---|
# this will probably be used later. For now we are using dictionaries.
# class Vertice:
# """ These will be used as Node like objects in our Graph data structure.
# Each vertice is away of all the vertices it connects out to.
# """
# def __init__(self, val):
# self.val = val
# self.v... |
# -*- coding: utf-8 -*-
"""
.. module:: pytfa
:platform: Unix, Windows
:synopsis: Thermodynamics-based Flux Analysis
.. moduleauthor:: pyTFA team
Variability analysis
"""
from tqdm import tqdm
import pandas as pd
import numpy as np
from numpy.linalg import norm
from optlang.interface import Constraint
from pyt... |
A = float(30000)
B = float(100000)
Ano = int(0)
while A < B:
A = A + (A*(2.5/100))
B = B + (B*(1.8/100))
Ano = Ano + 1
print(f'Após {Ano} anos a cidade B, com {B:.1f} habitantes, ultrapssa a cidade A, com {A:.1f} habitantes')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*--
# Copyright (c) 2020, 2022 Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
from __future__ import print_function, absolute_import, division
import copy
from ads.common.model import A... |
class FooMany():
def __init__(self, *args):
pass
FooMany()
FooMany(1, 2, 3)
class FooMany2():
def __init__(self, **kwargs):
pass
foo = FooMany2(foo=1, bar=2, baz=3)
bar = FooMany2()
class Foo0():
def __init__(self):
pass
Foo0()
class FooOne():
def __init__(self, a):
self.a = a
def foo(self):
print(... |
import os
class Config:
"""
Stores configuration data
"""
SECRET_KEY = os.environ.get('SECRET_KEY', 'key')
SQLALCHEMY_DATABASE_URI = os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite:///site.db')
MAIL_SERVER = 'smtp.googlemail.com'
MAIL_USE_TLS = True
MAIL_USERNAME = os.environ.get('M... |
# Generated by Django 2.2 on 2019-09-01 23:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('moment', '0047_auto_20190603_2308'),
]
operations = [
migrations.AlterField(
model_name='story_file_status',
name='fil... |
# -*- coding: utf-8 -*-
#******************************************************************************************
# Copyright (c) 2019
# School of Electronics and Computer Science, University of Southampton and Hitachi, Ltd.
# All rights reserved. This program and the accompanying materials are made available under
#... |
#!/usr/bin/env python3
'''
genetribe - longestfasta.py
Copyright (C) Yongming Chen
Contact: chen_yongming@126.com
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, ... |
from django.forms import ModelForm
from .models import *
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class OrderForm(ModelForm):
class Meta:
model = Order
fields = '__all__'
# exclude = ['customer']
cl... |
#!/usr/bin/python
import scipy.stats as st
file = open("TScoreDist.csv", "w")
ls = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,35,40,60,120]
tail = [0.4,0.25,0.1,0.05,0.025,0.01,0.005,0.001,0.0005]
file.write("n, t, prob\n")
for n in ls:
for item in tail:
file.write(s... |
class Solution:
def threeSum(self, nums: [int]) -> [[int]]:
"""
O(N ** 2)
0 - Avoid searching duplicates for ALL THREE pointers i, low, and high.
0.0 - For i, use continue.
0.1 - For low and high, loop as below.
low += 1
while low < high and nu... |
import smart_imports
smart_imports.all()
class Clan(meta_relations_objects.MetaType):
__slots__ = ('caption', )
TYPE = 8
TYPE_CAPTION = 'Гильдия'
def __init__(self, caption, **kwargs):
super().__init__(**kwargs)
self.caption = caption
@property
def url(self):
return... |
from app.io import *
from app.formula import *
from app.gui import *
if __name__ == "__main__":
#(ves, vozrast, rost, pol) = input_paramerty()
#kalory = calculate(ves, vozrast, rost, pol)
#output_rezultat(kalory)
run_window() |
from __future__ import annotations
import splatlog as logging
from typing import Literal
from nansi.plugins.action.compose import ComposeAction
from nansi.plugins.action.args.all import Arg, ArgsBase, os_fact_formatter
from nansi.os_resolve import os_map_resolve
LOG = logging.getLogger(__name__)
class Args(ArgsBase... |
__version__ = '0.1.0'
import cowsay
def baz():
return cowsay.tux('hi')
|
import os
from utils import run
from celery import Celery, signals
from efficient_frontier import solve_ef
CELERY_BROKER_URL = (os.environ.get("CELERY_BROKER_URL", "redis://localhost:6379"),)
CELERY_RESULT_BACKEND = os.environ.get(
"CELERY_RESULT_BACKEND", "redis://localhost:6379"
)
celery = Celery("tasks", broke... |
# https://www.hackerrank.com/challenges/two-pluses
import re
def prepare_matcher(c, size):
if size == 0:
return 'G'
regex = ('G[\s\S]{%d}' * size) % tuple([c] * (size - 1) + [c - size])
regex += 'G{%d})G(?=G{%d}' % (size, size)
regex += ('[\s\S]{%d}G' * size) % tuple([c - size] + [c] * (size ... |
import pandas as pd
import numpy as np
from sklearn.preprocessing import PolynomialFeatures, StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.metrics import mean_squared_error, accuracy_score, classification_report, f1_score, roc_auc_score, roc_curve, plot_roc_curve, confusion_mat... |
"""
DialogueHandler
The DialogueHandler maintains a pool of dialogues.
"""
from muddery.server.utils import defines
from muddery.server.utils.game_settings import GAME_SETTINGS
from muddery.server.mappings.element_set import ELEMENT
class DialogueHandler(object):
"""
The DialogueHandler maintains a pool of... |
import wabtec_track
file_name = 'images/Caltrain_01-08-20_Page_2.jpg'
wtt = wabtec_track.WabTecTrack(file_name=file_name)
lines = wtt.get_lines() #gets list of line_track objects
for ln in lines:
print(ln.point_one(), ', ' , ln.point_two())
#print(ln.x1) #can also be accesseds
#only for testing
wtt.draw... |
#
# PySNMP MIB module RADIUS-AUTH-CLIENT-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/RADIUS-AUTH-CLIENT-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:25:31 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 201... |
import json
import os
import random
import time
import logging
import selenium.common
from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.... |
import requests
import json
import hashlib
link = "https://api.codenation.dev/v1/challenge/dev-ps/generate-data?token=e113855b46bddcc9761496f7dac26cb39d30c47a"
linkEnvio = "https://api.codenation.dev/v1/challenge/dev-ps/submit-solution?token=e113855b46bddcc9761496f7dac26cb39d30c47a"
# get requisição
req = requests.ge... |
import pytest
import yaml
from kalc.model.kubernetes import KubernetesCluster
from kalc.model.kinds.Pod import Pod
from kalc.model.kinds.Node import Node
from kalc.model.kinds.Service import Service
from kalc.model.kinds.Deployment import Deployment
from kalc.model.kinds.PriorityClass import PriorityClass
from kalc.mod... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-06-13 16:13
# @Author : liupan
# @Site :
# @File : demo13.py
# @Software: PyCharm
import time
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
browser = webdriver.Chrome()
url = 'http://www.runoob.com/t... |
import parslepy
import parslepy.base
import parslepy.selectors
import lxml.cssselect
from nose.tools import *
from .tools import *
class TestInvalidParseletInit(object):
init_parselets = (
#{ "title": ".test #"}, # this does not raise SyntaxError in lxml<3
{ "title": "/h1[@]"},
{ "title": "... |
import json
import os, re, sys, argparse
import CCEvents as Events
import CCUtils
from CCEvents import ChangeVarType
from enum import Enum
# ~ crosscode eventscript v1.5.0 parser, by EL ~
# to run:
# python cc-eventscript-parser.py <input text file>
# REQUIRES PYTHON 3.10 OR ABOVE!
# to make a text file:
# see rea... |
from rest_framework import permissions
class IsOwner(permissions.BasePermission):
def has_object_permission(self,request,view,obj):
return obj.owner == request.user |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
size= 0
vals = []
tmp = head
flag = True
while(tmp):
siz... |
#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*
#pylint: disable=missing-docstring, line-too-long, empty-docstring, too-many-locals, invalid-name, trailing-newlines
#-------------------------------------------------------------------------------
#
# Project: VirES-Aeolus
# Purpose: Aeolus -- watc... |
import unittest
import mock
import yaml
from configbutler.main import resolve_properties
class TestAWSInstanceMetadataResolver(unittest.TestCase):
def test_simple(self):
args = mock.Mock()
undertest = """
properties:
a: string|a
aa: string|${a}${a}
ab: string|${a}b
"""
prop... |
from django.conf.urls import url
from .views import (
OrderListView,
OrderDetailView,
LibraryView,
VerifyOwnership,
OrderDetailGeneratePDFView
)
urlpatterns = [
url(r'^$', OrderListView.as_view(), name='list'),
url(r'^library/$', LibraryView.as_view(), name='library'),
url(r'^(?P<order_id>[0-9A-Za-z]... |
import asyncio
from cowait.network import Server, HttpServer, get_local_ip
from cowait.utils import StreamCapturing
from .io_thread import IOThread
from .logger import Logger
from .parent_client import ParentClient
class WorkerNode(object):
def __init__(self, id: str, upstream: str, port: int = 80, logger: Logger... |
import sys
import ast
import os
import glob
import re
import stat
import time
from setuptools.command.egg_info import (
egg_info, manifest_maker, EggInfoDeprecationWarning, get_pkg_info_revision,
)
from setuptools.dist import Distribution
from setuptools.extern.six.moves import map
import pytest
from . import en... |
import logging
import requests
from django.conf import settings
from django.contrib.auth import authenticate, login
from django.shortcuts import redirect, render
from integrations.slack.models import SlackCommunity, SlackUser, SLACK_METHOD_ACTION
from integrations.slack.utils import get_slack_user_fields
from policyeng... |
# Copyright (c) 2020-2021 Matematyka dla Ciekawych Świata (http://ciekawi.icm.edu.pl/)
# Copyright (c) 2020-2021 Robert Ryszard Paciorek <rrp@opcode.eu.org>
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Soft... |
import os
import unittest
import shutil
import sys
sys.path.append(".")
from annogesiclib.paths import Paths
class TestPaths(unittest.TestCase):
def setUp(self):
self.test_folder = "test_folder"
if not os.path.exists(self.test_folder):
os.mkdir(self.test_folder)
self.paths = P... |
"""
Before trades can be sent for execution they need to pass
any defined compliance rules. These rules may include position
limits, restricted securities, ...
Here compliance rules have been arranged using a composite pattern
to check portfolio positions should the trade be fully executed.
"""
from abc import ABC, abs... |
# Copyright 2020 The TensorFlow Probability 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 o... |
fruits = ['apple', 'banana', 'kiwi', 'watermelon']
for fruit in fruits:
print(fruit + "가 있습니다.")
index = 0
while index <= 3:
print(fruits[index] + "를 꺼냈습니다.")
index = index + 1 |
import argparse
import datetime
import importlib
import importlib.resources
import logging
import logging.handlers
import os
import random
from shutil import copyfile
import time
import pendulum
# Plotman libraries
from plotman import analyzer, archive, configuration, interactive, manager, plot_util, reporting
from p... |
from pyecharts import options as opts
from pyecharts.charts import Pie
c = (
Pie()
.add_dataset(
source=[
["product", "2012", "2013", "2014", "2015", "2016", "2017"],
["Matcha Latte", 41.1, 30.4, 65.1, 53.3, 83.8, 98.7],
["Milk Tea", 86.5, 92.1, 85.7, 83.1, 73.4, 55.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 18 17:54:55 2020
@author: RredRrobin
"""
import os
import tkinter as tk
import tkinter.filedialog as filedialog
import tkinter.ttk as ttk
import pandas as pd
from datetime import datetime, timedelta
import numpy as np
class TextScrollCombo(tk.Fra... |
import torch
import torch.nn as nn
class EncoderRNN(nn.Module):
def __init__(self, input_size, hidden_size, device):
"""
:param input_size: 5 which is OHLC + trend
"""
super(EncoderRNN, self).__init__()
self.device = device
self.hidden_size = hidden_size
sel... |
from setuptools import setup
PACKAGES = [
'clumpy',
'clumpy.datasets',
'clumpy.datasets.data',
'clumpy.tests',
]
def setup_package():
setup(
name="ClumPy",
version='0.1.0',
description='Implementation of Various Clustering Algorithms',
author='Joshu... |
"""2018 - Day 8 Part 1: Memory Maneuver tests."""
from src.year2018.day08a import solve
def test_solve():
sample_task = "2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2"
assert solve(sample_task) == 138
|
"""
TODO
"""
import torch
import torch.nn.functional as F
def fgsm_attack(model: torch.nn.Module, image: torch.tensor, label: torch.tensor, epsilon: float, **kwargs) -> torch.tensor:
"""
Fast Gradient Sign Method Attack, no target class
"""
model.eval()
image.grad = None
image.requires_grad ... |
import matplotlib.pyplot as plt
import numpy as np
from statistics import mean, variance, stdev, pstdev
## HVAR Q
t1 = np.arange(4., 26., 1)
h1a = [0.000054,0.000060,0.000219,0.000121,0.000817,0.000420,0.001006,0.000320,0.000823,0.000409,0.005720,0.004519,0.035852,0.022784,0.172694,0.015400,0.946574,0.044666,9.2531... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from jinja2 import Environment, PackageLoader, select_autoescape
from networkx.readwrite import json_graph
import json
from .utils import *
from .settings import *
from .fmanager import FileManager
# set up jinja2
env = Environment(
loader=PackageLoader('dice.media', 'te... |
try:
from setuptools import setup, Extension
except:
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, Extension
name = 'pyjip'
version = '0.7'
description = 'JIP pipeline library'
author_email = "thasso.griebel@gmail.com"
url = ""
packages = ['jip', 'jip.cli', ... |
from datetime import datetime
print '''\
<html>
<body>
<p>Generated {0}</p>
</body>
</html>'''.format(datetime.now())
|
from shared import readAssets
def doExtract(args):
print("Larkstongue v0.0.1-alpha")
def readGfx():
readLine = line.strip("\n")
if len(readLine) > 0:
areaGfx.append(readLine)
def readGff():
readLine = line.strip("\n")
if len(readLine) > 0:
... |
import json
from configuration_file import ConfigurationDict
from pprint import pprint
class InterfaceConfiguration(ConfigurationDict):
'''
loads a single interface configuration file from the projects/project/config folder
flattens the interface to a
'''
def __init__(self, interface_name, folderna... |
import argparse
snp_id_index = 1
def to_dominance_bim(bim_path, out_path):
assert bim_path != out_path, 'out_path cannot be the same as the original bim file path'
print(f'=> converting {bim_path} to dominance bim out_path: {out_path}')
with open(bim_path, 'r') as file, open(out_path, 'w') as out:
... |
#pylint: skip-file
import mock
import re
from util import VigilanceTestCase
class ConfigurationParserTest(VigilanceTestCase):
def setUp(self):
super(ConfigurationParserTest, self).setUp()
global ConfigurationParsingError
from vigilance.error import ConfigurationParsingError
from vi... |
#!/usr/bin/python2
#Original Author: Zane J Cersovsky
#Original Date: Mar 8 2016
#Last Modified By: Zane J Cersovsky
#Last Modified On: Mar 23 2016
import random
import sys
import logging
#import sensor abstract
import abstractsensor
class LuxSensor(abstractsensor.Sensor):
def __init__(self, bus=1, addr=0x39, normValu... |
import unittest
from fastapi.testclient import TestClient
from backend.api.cpu_load import app
class TestCPULoad(unittest.TestCase):
def setUp(self):
self._client = TestClient(app)
def test_get_average_cpu_load(self):
response = self._client.get('/api/average-cpu-load')
self.assert... |
from django.contrib import admin
from .models import Userprofile
admin.site.register(Userprofile)
|
import sys
import maya.OpenMayaMPx as OpenMayaMPx
import maya.OpenMaya as OpenMaya
# -*- Plugin information -*-
plugin_node_name = 'pushDeformer'
plugin_node_id = OpenMaya.MTypeId(0x1C3B0475)
class PushDeformerNode(OpenMayaMPx.MPxDeformerNode):
# Amount to push the vertices by
inflation_attr = OpenMaya.MObject()
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 18 14:01:09 2021
@author: Peter Reynolds
"""
import numpy as np
import cv2
import matplotlib.pyplot as plt
import sys
from skimage.transform import rotate, resize
from skimage.util import crop
from skimage.color import rgb2gray
from skimage.feature import... |
from obj_dict_tools import *
from nose.tools import raises
@dict_fields(['name', 'size'])
class Simple:
def __init__(self, name=None, size=None):
self.name = name
self.size = size
@dict_fields(['first', 'second'])
class Pair:
def __init__(self, first=None, second=None):
self.first ... |
import re
import requests
from bs4 import BeautifulSoup
from helper.metadata import TERM_COLOR
term_color = ''
def _set_term_color(key):
global term_color
term_color = TERM_COLOR[key]
def _get_perk_name(perk):
perk_name_regex = re.compile(r'alt="[a-zA-Zㄱ-힇 ]*')
perk_name_reqex2 = re.compile(r'[ㄱ-힇... |
#!/usr/bin/env python
"""
:Author: Martin Kircher
:Contact: mkircher@uw.edu
:Date: *13.04.2015
"""
import sys, os
from optparse import OptionParser
import math
from sortedcontainers import SortedList
import numpy as np
parser = OptionParser()
parser.add_option("-s","--smoother", dest="smoother", help="Use smoother o... |
# Copyright (C) 2018 Julien Hartmann
# This program is distributed under the MIT license, a copy of which you should
# have receveived along with it. If not, see <https://opensource.org/licenses/MIT>.
#
import aiohttp
import asyncio
import pytest
from decimal import Decimal
from tests.aiohttp import http_redirect, Case... |
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label": _("Invoices"),
"icon": "fa fa-star",
"items": [
{
"type": "doctype",
"name": "Ticket Invoice",
"description": _("Ticket Invoice")
},
{
"type": "doctype",
"name": "Tour Invoi... |
def binary_search(list, target):
"""
Search a sorted list.
:param list: the input sorted list
:param target: the value that is to be found
:return: index of target in list, or -1 if not found
"""
# the initial left and right index
l = 0
r = len(list)
# while left is less t... |
#!/bin/python3
import sys
n, k, q = input().strip().split(' ')
n, k, q = [int(n), int(k), int(q)]
a = [int(a_temp) for a_temp in input().strip().split(' ')]
l = k % n
a = a[n - l:] + a[:n - l] if l != 0 else a
for a0 in range(q):
m = int(input().strip())
print(a[m])
|
from rest_framework.serializers import (
HyperlinkedIdentityField,
ModelSerializer,
SerializerMethodField
)
from .models import Chat,Message
from users.models import BeerBearCustomer
class ChatRoomSerializer(ModelSerializer):
class Meta:
model = Chat
fields = (
'__all__'
... |
import os
import ptf.testutils as testutils
import ptf.mask as mask
import ptf.packet as packet
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
DUT_TMP_DIR = os.path.join('tmp', os.path.basename(BASE_DIR))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
SUB_PORTS_TEMPLATE = 'sub_port_config.j2'
ACTION_FWD =... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 01 16:32:22 2017
@author: ag16225
"""
from collections import Counter
import numpy as np
#from wordcloud import WordCloud
import pandas as pd
import matplotlib.pyplot as plt
import operator
from nltk.stem.wordnet import WordNetLemmatizer
#For logging to console purposes... |
# -*- coding: utf-8 -*-
"""
@author: WellenWoo
"""
import torch
#from torch.autograd import Variable
from torch import optim
import torch.nn as nn
import torch.utils.data
import torchvision.utils as vutils
from nets import NetD, NetG, weights_init
from loss import l2_loss
from reporter import print_current_performance,... |
##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2020, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
from pgadmin.tool... |
class Solution:
def findGoodStrings(self, n, s1, s2, evil):
M = 10 ** 9 + 7
m = len(evil)
memo = {}
# KMP
dfa = self.failure(evil)
def dfs(i, x, bound):
if x == m:
return 0
if i == n:
return 1
... |
# Generated by Django 2.1.7 on 2019-04-10 14:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('PiGPIO', '0012_dashboard'),
]
operations = [
migrations.RenameField(
model_name='dashboard',
old_name='color',
... |
#!/usr/bin/env python
#
# Run 'sacct --format=ALL' on the given job and present
# the output in a row-based format instead of column-based
# so it's easier to read.
#
# Ross Dickson, ACENET, 2017-12-21
#
from __future__ import print_function
import sys
import subprocess
jobid = sys.argv[1]
# Get all accounting fields... |
from MIND_corpus import MIND_Corpus
import time
from config import Config
import torch.utils.data as data
from numpy.random import randint
from torch.utils.data import DataLoader
class MIND_Train_Dataset(data.Dataset):
def __init__(self, corpus: MIND_Corpus):
self.negative_sample_num = corpus.negative_sam... |
background_image_filename = 'sushiplate.jpg'
sprite_image_filename = 'fugu.png'
import pygame
from pygame.locals import *
from sys import exit
from gameobjects.vector2 import Vector2
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
background = pygame.image.load(background_image_filename).convert()... |
import os
import filecmp
from dvc.main import main
from dvc.utils import file_md5
from dvc.stage import Stage
from dvc.command.run import CmdRun
from tests.basic_env import TestDvc
class TestRun(TestDvc):
def test(self):
cmd = 'python {} {} {}'.format(self.CODE, self.FOO, 'out')
deps = [self.FOO... |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def VAppEntityConfigInfo(vim, *args, **kwargs):
'''This object type describes the behavio... |
from floodsystem.station import MonitoringStation
def stations_level_over_threshold(stations, tol):
'When given a list of MonitoringStation objects and a tolerance, returns a list of tuples of station objects with relative water levels over that tolerance, and their relative water levels'
from floodsystem.utils... |
A, B = map(int, input().split())
# A<=x<y<=B の時に最大公約数cが成り立つかBから見ていく
for c in range(B, 0, -1):
# A以上B以下のcの倍数の数が2個以上であるか
if (A+c-1)//c < B//c:
print(c)
exit(0)
|
from .base import (
HTTPClient,
ResourceData,
ErrorData,
)
from .intranet import Login as IntranetLogin
from .intranet import StudentPhoto as IntranetStudentPhoto
from .intranet import Chapel as IntranetChapel
from .intranet import Timetable as IntranetTimetable
from .intranet import Course as IntranetCours... |
import collections
class Node:
def __init__(self, data, parent):
self.parent = parent
self.data = data
self.children = {}
def __contains__(self, item):
return item in self.children
def __getitem__(self, item):
return self.children[item]
def __setitem__(self, ... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('dashboard', views.dashboard, name='dashboard'),
path('buildings', views.buildings, name='buildings'),
path('flats', views.flats, name='flats'),
path('rooms', views.rooms, name='rooms'),
... |
# Copyright 2013-2021 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 Gradle(Package):
"""Gradle is an open source build automation system that builds
upon ... |
class Company(object):
def __init__(self,employee_list):
self.employee = employee_list
def __getitem__(self, item):
return self.employee[item]
company = Company(['tom','bob','jane'])
# emploee = company.employee
#
# for em in emploee:
# print(em)
for em in company:
print(em) |
import scrapy
from itemloaders.processors import MapCompose
from exchanges.utils import ItemParser
class QuoteItem(scrapy.Item):
date = scrapy.Field(input_processor=MapCompose(str.strip, ItemParser.p_date)) # 資料日期
code = scrapy.Field() # 證券代號
name = scrapy.Field() # 證券名稱
shares = scrapy.Field(input... |
###################################################################################################
#
# chrome_extensions.py
# Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field
#
# Plugin Author: Ryan Benson (ryan@obsidianforensics.com)
#
###########################... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django_blog.sitemaps import BlogSitemap
from django_blog.sitemaps import StaticViewSitemap
admin.autodiscover()
sitemaps = {
'blog': BlogSitemap,
'static': StaticViewSitemap
}
urlpatterns = patterns('',
# Examples:... |
from gui import GUI
from tkinter import Tk
TEXT = {
"title": "RA3 Replay Auto Analysis Tool",
"info_1": "Choose a replay file first",
"browse_file": "Select file",
"export_1": "Export flowchart information",
"export_2": "Export all commands information",
"No Support": "Get AI info is not sup... |
"""
For processing downloaded CRS data into a more manageable format
"""
import io
import os
import zipfile
import pandas as pd
RAW_CRS_DELIMITER = '|'
RAW_CRS_NUM_COLUMNS = 80
MASTER_PICKLE_FILE_NAME = 'all_data.pkl'
def strip_additional_byte_order_marks(unicode_contents):
"""
Creditor Reporting System data... |
import os
from newspaper import Article
url = 'http://fox13now.com/2013/12/30/new-year-new-laws-obamacare-pot-guns-and-drones/'
article = Article(url)
article.download()
article.parse()
with open(os.path.join('testdata', 'article.txt'), 'w') as f:
f.write(article.text)
|
"""
Includes utilities to download and transform data.
"""
from abc import abstractmethod, ABCMeta
from difflib import SequenceMatcher
from datetime import datetime, timedelta
from itertools import product
import numpy as np
import pandas as pd
from sklearn.model_selection import ParameterGrid
from sklearn.utils impo... |
"""migrate_sources
Revision ID: 426b74e836df
Revises: 070ac78ddbcb
Create Date: 2019-11-25 11:26:47.059916
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = "426b74e836df"
down_revision = "070ac78ddbcb"
branch_labels = ... |
"""Module for generating algorithm and hyperparameter sequences.
This is a controller that jointly generates machine learning framework
pipelines and their associated hyperparameter settings. It does so via an RNN
that has a separate softmax classifier at each time step, where the classifier
has to predict either an a... |
# https://github.com/matheusfelipeog/fordev
from fordev.generators import people
import pandas as pd
df = pd.DataFrame(people(20, age=18))
pd.read_html()
df.to_excel("datas/test.xlsx")
|
import argparse
import importlib
import math
import os
import numpy as np
import tensorflow as tf
from tensorflow.python import debug as tf_debug
from tqdm import trange
from config import MovieQAPath
# from input import Input as In
# from input_v2 import Input as In2
from raw_input import Input
from utils import fun... |
from gpiozero import Device, Button, DigitalInputDevice, CompositeDevice
class RotaryEncoder(Device):
"""
Decode mechanical rotary encoder pulses.
Connect the extrems pins of the rotary encoder (left and right pins) to any GPIO
and the middle pin to a ground pin. Alternatively, connect the middle pin ... |
import toml, setuptools, pathlib, flit
flit = toml.load('pyproject.toml')['tool']['flit']
metadata = flit['metadata']
description, version = flit.common.get_docstring_and_version_via_import(flit.common.Module('poser'))
setuptools.setup(
name=metadata['module'],
version=version,
packages=setuptools.find_p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.