content stringlengths 5 1.05M |
|---|
l=0
k=1
n=int(input("Enter number of terms"))
while(k<=n):
l=k**3+2*k
k+=1
print(l, end =" ")
|
import json
class Location(object):
def __init__(self, d):
self.id = d.get('Id', None) # bosses do not have Ids
self.room = d['Room']
self.name = d['Name']
self.area = d['Area']
self.visited = False
class Locations(object):
def __init__(self, raw_locations):
self.locations = [ Location(loc... |
import tensorflow as tf
# construct nodes
NODE1 = tf.constant(3.0, dtype=tf.float32)
NODE2 = tf.constant(4.0)
print('NODE1, NODE2:', NODE1, NODE2)
# run nodes in session
SESS = tf.Session()
print('SESS.run(NODE1, NODE2):', SESS.run([NODE1, NODE2]))
# add combo node
NODE3 = tf.add(NODE1, NODE2)
print('NODE3:', NODE3)... |
from django.forms import ModelForm
from .models import Case
class CaseForm(ModelForm):
class Meta:
model = Case
fields = '__all__'
labels = {
'title': '标题',
'description': '故障描述',
'projects': '影响项目'
}
|
# Copyright 2017 Google 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... |
import os
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Renames a Django project'
def add_arguments(self, parser):
parser.add_argument('current', type=str, nargs='+',
help='The current Django project folder name')
parser.ad... |
"""
Drop-in replacement RPC Client for REST over XML-RPC.
Usage is to just change a usual import like this:
from xmlrpc.client import ServerProxy
To this:
from restxrpc.rpcclient import ServerProxy
Additionally, set the URL for XML-RPC specs download, e.g.:
ServerProxy.set_specs_url("http://myhost:80... |
#In[]
# coding=utf-8
import numpy as np
import Putil.base.logger as plog
plog.PutilLogConfig.config_handler(plog.stream_method)
plog.PutilLogConfig.config_log_level(stream=plog.DEBUG)
plog.PutilLogConfig.config_format(plog.Format)
logger = plog.PutilLogConfig('TestCOCODataUnit').logger()
logger.setLevel(plog.DEBUG)
... |
import pytest
import itertools
from functools import partial
import flax
import jax
import numpy as np
from numpy import testing
import jax.numpy as jnp
import jax.flatten_util
from jax.scipy.sparse.linalg import cg
import netket as nk
from netket.optimizer import qgt
from netket.optimizer.qgt import qgt_onthefly... |
#!/usr/bin/env python
# * DS-Explorer is being developed for the TANGO Project: http://tango-project.eu
# * Copyright 2018 CETIC www.cetic.be
# * DS-Explorer is a free software: you can redistribute it and/or modify
# * it under the terms of the BSD 3-Clause License
# * Please see the License file for more information... |
# coding: spec
from photons_messages_generator import test_helpers as thp
from photons_messages_generator import errors
from delfick_project.errors_pytest import assertRaises
describe "Multiple":
it "does not allow broken bytes":
src = """
packets:
one:
OnePacket... |
from jsonrpcbase import InvalidParamsError
from JobBrowserBFF.schemas.Schema import Schema, SchemaError
class Validation(object):
def __init__(self, schema_dir=None, load_schemas=None):
self.schema = Schema(schema_dir=schema_dir, load_schemas=load_schemas)
def validate_params(self, method_name, data)... |
from collections import deque
class DigraphCycle(object):
def __init__(self, graph):
indegrees = [graph.get_indegree(v) for v in range(graph.v)]
queue = deque([v for v, indegree in enumerate(indegrees) if indegree==0])
while queue:
v = queue.popleft()
for w in grap... |
# **********************************************************************************************************************
# FileName:
# bp_test.py
#
# Description:
# Boilerplate generator for LLD testing files
#
# Usage Examples:
# N/A
#
# 2020 | Brandon Braun | brandonbraun653@gmail.com
# ****... |
from google.appengine.ext import ndb
from . import models
class Site(models.Model):
root_folder_id = ndb.StringProperty()
site_title = ndb.StringProperty()
logo_url = ndb.StringProperty()
email_footer = ndb.TextProperty()
sidebar = ndb.StringProperty()
path = ndb.StringProperty()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 29 11:37:07 2019
@author: deborahkhider
"""
import xarray as xr
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import imageio
import os... |
from redis import Redis
from rq import Queue, Worker
redis = Redis(host='redis', port=6379)
queue = Queue('model_prediction', connection=redis)
if __name__ == '__main__':
print('Starting Worker')
worker = Worker([queue], connection=redis, name='model_prediction')
worker.work()
print('Ending Worker')
|
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
setup(
name='negative-cycles',
# Versions should com... |
#!/usr/bin/python
import sys
result= {}
for line in sys.stdin:
line = line.strip()
trimmedNucleotide,seqIds = line.split('#', 1)
try:
result[trimmedNucleotide] = 0
except ValueError:
pass
for word in result:
print '%s' % (word)
|
import asyncio
import unittest
from slixmpp import JID
from slixmpp.test.integration import SlixIntegration
class TestUserAvatar(SlixIntegration):
async def asyncSetUp(self):
await super().asyncSetUp()
self.add_client(
self.envjid('CI_ACCOUNT1'),
self.envstr('CI_ACCOUNT1_PA... |
import random
import pyfiglet
import MyColors
import os
lbiu = MyColors.lightColorsBIU()
nbiu = MyColors.NormalBIUColors()
lbold = MyColors.lightColorsBold()
def game():
os.system("clear")
name = input(lbold.LIGHT_greenBold("\n\n\nYour name: "))
print("\nWelcome")
print(pyfiglet.figlet_... |
# Create your awesome net!!
import pickle
f = open('deep_convnet_params.pkl','rb')
data = pickle.load(f)
print (data) |
NAMES = [
'k5z',
'k5ta',
'k5ma',
'k5tb2',
'k5mb2',
'k5tb3',
'k5mb3',
'k6t',
'k6m',
'k1ta',
'k1ma',
'k1tb',
'k1mb',
'k2ta',
'k2ma',
'k2tb',
'k2mb',
'k2tc',
'k2mc',
'k3t',
'k3m',
'k4t',
'k4m',
#signal
'sinput',
'sbase'... |
import argparse
import subprocess
from pathlib import Path
import pickle
import numpy as np
from ...Data import pipeline
from alphafold.Model import AlphaFold, AlphaFoldFeatures, model_config
import torch
import numpy as np
import matplotlib.pylab as plt
def string_plot(af2, thist, field):
af2t = torch.from_numpy(af2... |
import sys
input = sys.stdin.readline
index = 0
while True:
unit_usable, unit_period, vacation = map(int, input().split())
if unit_usable == 0 or unit_period == 0 or vacation == 0:
break
index += 1
can_use = 0
while unit_period < vacation:
can_use += unit_usable
vacatio... |
from .utils import list_categories, create_simple_message
|
"""
Overview
========
Create an anonymous gist on github.
"""
from websnake import Post, ResponseHandle, core, die, JSon, TokenAuth
def handle_done(con, response):
print('Headers:', response.headers.headers)
print('Code:', response.code)
print('Version:', response.version)
print('Reason:', response.... |
# Generated by Django 3.1.2 on 2021-08-03 00:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('characters', '0007_auto_20210802_2046'),
]
operations = [
migrations.RemoveField(
model_name='character',
name='numb... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.transforms import SIGN
from torch.utils.data import DataLoader
import math
from typing import Optional
from torch import Tensor
eps=1e-5
from Precomputing.base import PrecomputingBase
class SAGN(PrecomputingBase):
def __init... |
from speechrecproj.data import *
signals = tf.placeholder(tf.float32, [None, 16000])
def main():
sample_manager = SamplesManager('data')
print(len(sample_manager.files_labels))
print(sample_manager.files_labels[0])
print(Label.all_labels)
sample_manager.files_labels[0].get_wav()
tfreader = ... |
#-*- coding: utf-8 -*-
import os.path
from .base_filter import BaseFilter
class StopwordsFilter(BaseFilter):
def __init__(self, country):
super(StopwordsFilter, self).__init__()
self.country = country
stopword_fname = '%s.txt' % self.country
folder_name = os.path.dirname(__file__)... |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from endorsement.services import endorsement_services
from endorsement.dao.uwnetid_supported import get_supported_resources_for_netid
from endorsement.dao.user import get_endorser_model
from endorsement.test.dao import TestDao
clas... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def get_res_net_18(ensemble, **kwargs):
if ensemble is None:
return ResNet18(**kwargs)
elif ensemble == "early_exit":
return ResNet18EarlyExit(**kwargs)
elif ensemble == "mc_dropout":
return Re... |
##############################################################################
# Copyright by The HDF Group. #
# All rights reserved. #
# #
# Th... |
from bokeh.io import show, export_png
from bokeh.plotting import figure
from bokeh.layouts import row
import numpy as np
A = np.array([[1,.8],[.8,1]])
B = np.array([[1,.4],[.4,1]])
C = np.array([[1,-.8],[-.8,1]])
a = np.random.multivariate_normal([1,3],cov=A,size=100)
b = np.random.multivariate_normal([-1,2],cov=B,... |
num=[]
nam=[]
while True:
print("-"*30)
print("1.请您任意输入两个数字")
print("2.退出系统")
try:
key=int(input("请选择功能(输入序号1到2):"))
except:
print("您的输入有误,请输入序号1到2")
continue
if key==1:#输入并比较数字。
try:
num=int(input("请输入您猜的第一个数字:"))
nam=int(input("请输入您猜的第二个数... |
import tensorflow as tf
from tensorflow.contrib import slim
from .base_model import BaseModel, Mode
from .backbones import resnet_v1 as resnet
from .layers import delf_attention, image_normalization, dimensionality_reduction
class Delf(BaseModel):
input_spec = {
'image': {'shape': [None, None, None, ... |
"""
stuff for testing Phenny modules
example:
if __name__ == '__main__':
import sys
sys.path.extend(('.','..')) # so we can find phennytest
from phennytest import PhennyFake, CommandInputFake
PHENNYFAKE = PhennyFake()
CMDFAKE = CommandInputFake('.wub a dub dub')
wub(PHENNYFAKE, CMDFAKE)
"""
import sys, r... |
from .models import Slot, Service, Booking
from django.contrib import admin
# Register your models here.
@admin.register(Booking)
class BookingAdmin(admin.ModelAdmin):
list_display = ["user", "slot", "start", "end"]
search_fields = ["user", "slot", "service", "school"]
|
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
setup(
name='pythontabcmd2',
url='https://github.com/tableau/tabcmd2',
packages=find_packages(),
entry_points={
'console_scripts': [
'tabcmd2 = pythontabcmd2.tabcmd2:main'
... |
# mira.py
# -------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attrib... |
import json
import os
from datetime import datetime
from .config import config
class Entry():
"""Loads entry json file, and presents a simple api to access and
save fields"""
def __init__(self):
d = datetime.now()
self.datetime = {
"year": d.year,
"month": d.month,
"day": d.day,
"hour": d.hour,... |
from django.conf.urls import patterns, include, url
from store_search import views
urlpatterns = (
url(r'^search$', views.search_page, name='store_search'),
)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
class Command(BaseCommand):
help = _("Collect information about all customers which accessed this shop.")
... |
# coding=utf-8
# Copyright 2022 The Google Research 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 applicab... |
"""
"regex_classifier" categorises the label based on keyword occurrences.
- keywords are chosen from the most frequent and symbolic words from each category (doc/feature/bug/other)
- word frequency analysis is done both holistically and individually on each repo
- it turns out that individual repo analysis gives us... |
from sawyer.ros.envs.sawyer.pick_and_place_env import PickAndPlaceEnv
from sawyer.ros.envs.sawyer.push_env import PushEnv
from sawyer.ros.envs.sawyer.reacher_env import ReacherEnv
from sawyer.ros.envs.sawyer.toy_env import ToyEnv
from sawyer.ros.envs.sawyer.transition_env import TransitionEnv, TransitionPickEnv, Transi... |
import os
import abc
import json
import torch
from torch import nn
import utils
class GenericLayer(abc.ABC, nn.Module):
def __init__(self, previous_layer=None, input_dim=None, output_dim=None, samedim: bool = False,
**kwargs):
super().__init__()
self.model_name = 'Gene... |
class Solution:
def addDigits(self, num):
while num >= 10:
digits = [int(x) for x in str(num)]
num = sum(digits)
return num
|
#!/usr/bin/env python
"""
"""
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import ctypes
import pyglet
from pyglet.window.xlib import xlib
import lib_xrandr as xrandr
def _check_extension(display):
major_opcode = ctypes.c_int()
first_event = ctypes.c_int()
first_error = ctypes.c_int()
... |
import logging
from typing import Any, Dict, List
import numpy as np
from overrides import overrides
import torch
import torch.nn.functional as F
from torch.nn.functional import nll_loss
from torch.nn.functional import cross_entropy
from torch.nn import CrossEntropyLoss
from pytorch_pretrained_bert.modeling import Bert... |
import csv_utilities
from collections import namedtuple
class Data( object ):
def __init__( self, filename, reader_fun, converter_fun=lambda x: x ):
Row = namedtuple( 'Row', [ 'X', 'Y' ] )
reader_data = converter_fun( reader_fun( filename ) )
self.attributes = reader_data[ 0 ][ :-1 ] # Remove 'class' attribu... |
from numbers import Real
class Site:
"""This is a class for create an object of sites.
:param index: The index of each site of the system
:type index: int
:param position: The position of each site of the system
:type position: float
:param type: The type of each site in the system
:type ... |
#!/usr/bin/env python
# SPDX-License-Identifier: GPL-2.0-only
#
# wad-shuffle-dir - Shuffle lumps in WAD files
#
# Shuffle lumps of a given type in order to produce a randomized WAD. This
# more of a novelty than a useful tool.
from __future__ import print_function
# Imports
import argparse
import atexit
import os
... |
import math
pi = 3.14
x = 1
y = 2
z = 3
#print(round(pi))
#print(math.ceil(pi))
#print(math.floor(pi))
#print(abs(pi)) # if pi = -3.14 -> abs(pi) = 3.14
#print(pow(pi,2)) # potencia de 2
#print(math.sqrt(420))
print(max(x,y,z))
print(min(x,y,z)) |
from tkinter import *
class Application(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.msg = Label(self, text = "Hello World")
self.msg.pack()
self.bye = Button (self, text = "Bye", command = self.quit)
self.bye.pack()
self.pack
app = Application()
mainloop()
|
import subprocess
import signal
import string
import random
import re
import json
import time
import os
import socket
import requests
import logging
import sys
import base64
import yaml
from flask import Flask, request, send_from_directory, jsonify, render_template, redirect
app = Flask(__name__, static_url_path='')
... |
todo_api_path: str = "https://jsonplaceholder.typicode.com/todos/"
|
import os
from typing import List, Tuple
import cv2
import numpy as np
import pickle5 as pickle
from tqdm import tqdm
from mmhuman3d.core.conventions.keypoints_mapping import convert_kps
from mmhuman3d.data.data_structures.human_data import HumanData
from .base_converter import BaseModeConverter
from .builder import ... |
from app import db
from models import User
u = User(username='admin', email='admin@example.com',
password_hash='b3282a2f2a28757b3a18ab833de16a9c54518c0b0cf493e3f0a7cf09386f326a')
db.session.add(u)
db.session.commit()
|
##################################################################
# R E A D M E
##################################################################
'''
Methods to launch this script:
- from command line
- three main parameters: -i, -o, -l
-i specifies the input file
- if -i is not used, all files in t... |
from os import listdir, makedirs
from os.path import isfile, isdir, join, exists, dirname
def file_listing(dir, extension=None):
'''
List all files (exclude dirs) in specified directory with (optional) given extension
Args:
dir (string): Director full path
extension (string): (optional) E... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 21 07:16:35 2018
@author: MiguelArturo
"""
__author__ = "Miguel Barreto Sanz"
__copyright__ = "Copyright 2018, Miguel Barreto Sanz"
__credits__ = ["Miguel Barreto Sanz"]
__license__ = "MIT"
__version__ = "0.0.1"
__maintainer__ = "Miguel Barreto Sanz... |
import tensorflow as tf
import numpy as np
from functools import partial
from keras.models import Model
from .. import layers
from ..base import K
from .module import conv2d, deconv2d, conv2dt, vae_sampling
def HGResiduleModule(inputs, out_channel, add_residule=True, kernel_initializer='glorot_uniform', **kwargs):
... |
"""GeoNet NZ Volcanic Alert Level feed."""
import logging
from datetime import datetime
from typing import Optional
import pytz
from aio_geojson_client.feed import GeoJsonFeed
from aiohttp import ClientSession
from aio_geojson_geonetnz_volcano.consts import URL
from .feed_entry import GeonetnzVolcanoFeedEntry
_LOGG... |
from enum import Enum
class SharingType(Enum):
UNLIMITED = "UNLIMITED"
PERMISSIONS_LIMITED = "PERMISSIONS_LIMITED"
DISABLED = "DISABLED"
class ObjectType(Enum):
ARTIFACT = "ARTIFACT"
FILE = "FILE"
FOLDER = "FOLDER"
class FolderType(Enum):
STANDARD = "STANDARD"
SHARES = "SHARES"
... |
from django.db import models
from django.urls import reverse
from django.utils.safestring import mark_safe
from django.utils.functional import cached_property
from .choices import (
AB_CHOICES,
APPLICATION_TYPE_CHOICES,
APP_SUBMISSION_TYPE_CHOICES,
BOOL_CHOICES,
CFDA_CHOICES,
FED_ID_REGION_CHOI... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# nnutil2 - Tensorflow utilities for training neural networks
# Copyright (c) 2019, Abdó Roig-Maranges <abdo.roig@gmail.com>
#
# This file is part of 'nnutil2'.
#
# This file may be modified and distributed under the terms of the 3-clause BSD
# license. See the LICENSE fi... |
import logging
import unittest
import time
from datetime import datetime
import string
import random
from kafka import * # noqa
from kafka.common import * # noqa
from kafka.codec import has_gzip, has_snappy
from kafka.consumer import MAX_FETCH_BUFFER_SIZE_BYTES
from .fixtures import ZookeeperFixture, KafkaFixture
... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("WRITE")
process.source = cms.Source("EmptySource", numberEventsInLuminosityBlock = cms.untracked.uint32(4))
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(20))
process.out = cms.OutputModule("PoolOutputModule", fileName = cms.untra... |
import os
import subprocess
import time
import boardom as bd
from .gitignore import IGNORE, IGNORE_FIRST
# TODO: (SOS) Guard git calls to ignore CTRL-C and SIGINTS until finished
# TODO: (SOS) Make it only master process
# TODO: Add logging
# TODO: Manage gitignore (e.g. .pth files, boardom files etc)
# TODO: Smart ad... |
import os
import sys
sys.path.append('../../')
from dependencies import *
from settings import *
from reproducibility import *
from models.TGS_salt.Unet34_scSE_hyper import Unet_scSE_hyper as Net
import pickle
prediction0=pickle.load(open("../../../liao_checkpoints/OHEM_5fold.p","rb"))
prediction1=pickle.load(open("5... |
# Generated by Django 2.1 on 2019-05-11 13:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('comments', '0006_historicalcomment'),
]
operations = [
migrations.AddField(
model_name='comment',
name='first_index',
... |
"""
This module defines functions for extracting/defining version information for
packages. Functions for retrieving version/branch info from SVN, as well as
those for formatting version strings and finding packages with predefined
version info are defined in this module.
"""
# author: Rick Ratzel
# created: 8/9/05
... |
# @oncall
"""This is a module."""
def f():
pass
|
"""Tests NotificationData."""
import os
from pathlib import Path
import email
from circuit_maintenance_parser.data import NotificationData
dir_path = os.path.dirname(os.path.realpath(__file__))
def test_init_from_raw():
"""Test the init_data_raw function."""
data = NotificationData.init_from_raw("my_type",... |
import logging
import re
from types import TracebackType
from typing import (
Any,
Callable,
Dict,
Generic,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
from urllib.parse import urlencode, urlunparse
from selenium.webdriver import Chrome
from selenium.webdriver.remote.webdrive... |
from django.shortcuts import render
from django.shortcuts import HttpResponse
def index(request):
return HttpResponse("hi")
# Create your views here.
|
import multi_cavity_base
import states
from util import isiter, sort_eigenstates
import numpy as np
import qutip
import copy
class CavityArray(multi_cavity_base.CavityArray):
def __init__(self, num_cavities, num_photons, model_params, periodic=False):
"""Create new CavityArray object
Args:
... |
#-*-coding:utf-8-*-
from .PyTorch_AlexNet import *
from .PyTorch_ResNet import * |
# Welcome to the third lesson in the Yesselman Group's Python series
# Topics covered: Lists
########################################################################################################################
# Part I: List basics
# As you have seen so far, variables are a great way to store information. That bein... |
# pragma pylint: disable=missing-docstring,C0103
import datetime
from pathlib import Path
from unittest.mock import MagicMock
from freqtrade.data.converter import parse_ticker_dataframe
from freqtrade.data.history import pair_data_filename
from freqtrade.misc import (datesarray_to_datetimearray, file_dump_json,
... |
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_html_components as html
import dash_table
import plotly.express as px
import pandas as pd
import pkg_resources
from callbacks import register_callbacks
meta_viewport = {"name": "viewport", "cont... |
from functools import reduce
from typing import Set
from unittest import TestCase, main
from program_graphs.adg.parser.java.parser import parse # type: ignore
from slicing.block.block import gen_block_slices
from slicing.block.block import get_entry_candidates, get_node_lines, mk_declared_variables_table
from slicin... |
from __future__ import absolute_import
import os
import pytest
import shutil
import subprocess
import importlib
import inspect
import compas
def get_names_in_module(module_name):
exceptions = ['absolute_import', 'division', 'print_function']
module = importlib.import_module(module_name)
all_names = modul... |
#
# PySNMP MIB module RADLAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:59:59 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... |
from aws_cdk import (
aws_lambda as lambda_,
aws_s3 as s3,
App, Duration, Stack
)
# Creates reference to already existing s3 bucket and lambda code
class LambdaS3Code(Stack):
def __init__(self, app: App, id: str) -> None:
super().__init__(app, id)
lambda_code_bucket = s3.Bucket.from_b... |
import json, re
def addAlarm(textToSpeech, phrases, text):
textString = "";
for index, string in enumerate(text):
textString += string + (index == len(text) - 1 and "" or " ");
textString = textString.replace("a.m.", "AM").replace("p.m.", "PM");
alarmTime = textString.split(" at ")[1].upper()... |
#Legacy Grammar Learner testL fill in ULL Project Plan Parses spreadshit
#language-learning/src/grammar_learner/pqa_table.py 80725, renamed pqa05 #80802
import os
import sys
import time
from ..common.cliutils import handle_path_string
from ..grammar_tester.grammartester import test_grammar
from ..grammar_tester.optcons... |
import tkinter as tk
# Event handler function
def doorbell(event):
print("You rang the doorbell!!")
window = tk.Tk()
window.geometry("300x200")
alabel = tk.Label(text="Banana")
alabel.grid(column=0, row=0)
blabel = tk.Label(text="Apple")
blabel.grid(column=1, row=0)
button = tk.Button(window, text="Doorbell"... |
from operator import itemgetter
from datetime import date
import calendar
def print_header(name, account_no, balance):
print("\nname:", name, " account:", account_no, " original balance:", "$" + str(balance))
def get_date(date_string):
year = int(date_string[:4])
month = int(date_st... |
from typing import Dict
from gym.spaces import space
from malib.utils.episode import EpisodeKey
from tests.algorithm import AlgorithmTestMixin
from gym import spaces
import numpy as np
from malib.algorithm.mappo import CONFIG, MAPPO, MAPPOLoss, MAPPOTrainer
import os
import shutil
import pytest
custom_config = CONFIG[... |
from django.db import models
from uuid import uuid4
from supersaver.constants import *
from country.models import Country
from source.models import DataSource
from common.models import Property
class Retailer (models.Model):
# Normalised name in lower case
id = models.UUIDField(primary_key=True, default=uuid... |
import argparse
import bottle
import logging
import os
import random
import re
import urllib
import urllib2
import pyhelix.spectator as spectator
class CodeRunner(object):
"""
A class that will find nodes that run code and dispatch work
"""
def __init__(self, cluster, resource, host, port, zk_svr):
... |
import logging
from aiohttp import web
from cen_uiu import assets
Logger = logging.getLogger(__name__)
STATIC_FOLDER = assets.__path__[0]
INDEX_HTML = assets.__path__[0] + "/index.html"
async def index(request):
return web.FileResponse(INDEX_HTML)
def create_app() -> web.Application:
Logger.debug("creating ... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sb
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report, confusion_matrix
def m... |
#restart
print('')
def introduc():
print('Is this a restart?')
print('or a load')
def menu():
print('(0)to quit(1)Restart (2)Load')
def loopy():
pl = input()
while pl !=None:
pl = input()
if pl == "":
print("Quit trying to break things")
i... |
from flask import request
from flask.ext.restful import Resource, Api, marshal_with, fields, abort
from flask_restful_swagger import swagger
from jira import JIRA
from .models import DummyResult
from .models import HelloResult
from .models import IssueResult
from .errors import JsonRequiredError
from .errors import Js... |
#!/usr/bin/env python
import argparse,textwrap
from igf_data.utils.singularity_run_wrapper import singularity_run
description = textwrap.dedent(
"""
A script for running commands within a singularity container in HPC
USAGE:
python run_singularity_container.py
-i /path/SINGULARITY_IMAGE
-b /path/CONTAIN... |
"""
(4) Modifique a função acima de maneira que ela receba mais um parâmetro, a extrem-
idade que se deseja juntar.
Exemplo:
>> l = [0,1,2,2,4,0]
>> funcao_auxiliar2(l, ’dir’) #nome generico nao use esse nome
[0,0,1,2,2,4]
>> funcao_auxiliar2(l, ’esq’)
[1,2,2,4,0,0] """
def mover_zeros(numeros, direcao):
if dire... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.