content stringlengths 5 1.05M |
|---|
def get_smaller_right(arr):
smaller_right_arr = list()
for i in range(len(arr)):
smaller_count = 0
for j in range(i + 1, len(arr)):
if arr[j] < arr[i]:
smaller_count += 1
smaller_right_arr.append(smaller_count)
return smaller_right_arr
# Tests
assert g... |
from typing import List
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
def binarySearch(l: int, r: int, first: bool) -> int:
nonlocal target
while l <= r:
mid = l + (r - l) // 2
if nums[mid] < target:
... |
"""
The Narrator for the screenplay, who informs the audience what the actors are
doing. The Narrator's microphone is modular, allowing for any number of
adapters to be applied. Adapters must follow the Adapter protocol outlined in
screenpy.protocols.
"""
from contextlib import contextmanager
from copy import deepcopy... |
from __future__ import annotations
from ctc.protocols import uniswap_v2_utils
from ctc import spec
async def async_get_pool_swaps(
pool_address: spec.Address,
start_block: spec.BlockNumberReference | None = None,
end_block: spec.BlockNumberReference | None = None,
replace_symbols: bool = False,
n... |
from flask import Flask
import os
app = Flask(__name__)
import testsite.views |
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
import psycopg2
import datetime
from database import database
def keep_alive(request):
"""
keep_alive process the keep alive route /keep_alive
:param request:
:return:
""... |
import numpy as np
from scipy.optimize import fsolve
def Force(E_interp_B1,E_interp_B2,R_B1,R_B2,M,N,delta,n):
'''
Computes the normal force between two contacting, elastically anisotropic bodies
Parameters:
E_interp_B1: interpolant of values of the plane strain modulus for the material
... |
from __future__ import print_function
import os, boto3, json, logging
lambda_client = boto3.client('lambda')
#logging configuration
logger = logging.getLogger()
logger.setLevel(logging.INFO)
#Read environment Variables
gatewayqueue = os.environ.get("GatewayQueue")
vpcid_hub = os.environ.get("HubVPC")
gwsize_spoke = ... |
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 7)
import numpy as np
n, w = map(int, readline().split())
vw = [list(map(int, readline().split())) for i in range(n)]
if n <= 30:
dp = [0]
check = [0]
for vv, ww in vw:
for j ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import hashlib
import re
import os
import json
bdir = "/Users/yuanliqiang/workspace/youtube-dl/"
sdir = "/Users/yuanliqiang/youtube/"
ddir = "/Users/yuanliqiang/tmp/"
lx = 1350
ly = 1010
logo = "/Users/yuanliqiang/workspace/youtube-dl/mengmadianjing.png"... |
import pytest
from src.get_minimum_cost import get_minimum_cost
cases = [
(3, [2, 5, 6], 13),
(2, [2, 5, 6], 15),
(3, [1, 3, 5, 7, 9], 29),
(2, [1, 3, 5, 7, 9], 35),
]
@pytest.mark.parametrize("friends, flowers, expected", cases)
def test_get_minimum_cost(friends, flowers, expected):
result = ge... |
import numpy as np
a1 = np.ndarray(shape=(2, 2)) # 랜덤 값으로 초기화
print(a1)
print(a1[0])
print(a1[1])
print(a1[0][1])
a2 = np.ndarray(shape=(2, 2, 3)) # 랜덤 값으로 초기화
# 3개의 값을 갖는 열을 2개 갖는 행렬을 2개 갖는다.
print(a2)
print(a2[0]) # 제일 바깥 쪽에 접근한다.
a2[0][0] = [1, 2, 3]
print(a2[0][1]) # 제일 바깥 쪽에 접근한다.
a3 = a2.reshape(2, 6) ... |
#!/usr/bin/env python
"""
Updates ug and ug-GRADYEAR groups based on the members table.
"""
import argparse
from datetime import date
from donut.pymysql_connection import make_db
today = date.today()
# Compute the start of the current academic year.
# This is the next calendar year if the script is run between July ... |
from django.db import models
class RawCPU(models.Model):
percent = models.FloatField()
class CPU(models.Model):
percent = models.FloatField()
class ArchiveCPU(models.Model):
percent = models.FloatField()
|
from django.contrib import admin
from django.urls import path
from admin_wizard.admin import UpdateAction, UpdateDialog
from testproject.testapp import models, forms
@admin.register(models.MyModel)
class MyModelAdmin(admin.ModelAdmin):
actions = [UpdateAction(form_class=forms.RenameForm)]
def get_urls(self)... |
from random import randint
from types import ListType, StringType
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag(takes_context=True)
def dfp_footer(context):
result = """
<script type="text/javascript">
var googletag = googletag ... |
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2016 Mag. Christian Tanzer All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. tanzer@swing.co.at
# #*** <License> ************************************************************#
# This module is part of the package GTW.RST.TOP.MOM.
#
# This module is licensed under... |
name = "openEPhys_DACQ"
|
import enum
import json
import unittest
from typing import List, Optional, Dict
from pynlp.utils.config import ConfigDict, _type_check, ConfigDictParser
from pynlp.utils.type_inspection import get_contained_type
class ConfigA(ConfigDict):
# def __init__(self, **kwargs):
# super().__init__(**kwargs)
f... |
sc.addPyFile('magichour.zip')
from magichour.api.dist.templates.templateGen import gen_tamplate_from_logs, read_logs_from_uri
transforms_URI = 'hdfs://namenode/magichour/simpleTrans'
raw_log_URI = 'hdfs://namenode/magichour/tbird.500k.gz'
template_output_URI = 'hdfs://namenode/magichour/templates'
support = 1000
# ... |
import asyncio
import contextlib
from unittest import mock
import datetime
import base64
import pytest
from ircd import IRC, Server
from ircd.irc import SERVER_NAME, SERVER_VERSION
pytestmark = pytest.mark.asyncio
HOST = "localhost"
ADDRESS = "127.0.0.1"
PORT = 9001
@contextlib.asynccontextmanager
async def conne... |
"""REST endpoint for the OpenAPI specification YAML file."""
from marshmallow import Schema, fields
import yaml
from .base import BaseResource
from .. import db
class OpenApiSchema(Schema):
info = fields.Dict()
paths = fields.Dict()
tags = fields.List(fields.Str())
openapi = fields.Str(... |
# Step 1: Import packages, functions, and classes
import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression, Lasso
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import matplotlib.... |
class Vehicle:
DEFAULT_FUEL_CONSUMPTION = 1.25
def __init__(self, fuel, horse_power):
self.fuel = fuel
self.horse_power = horse_power
self.fuel_consumption = self.set_default_fuel_consumption()
@classmethod
def set_default_fuel_consumption(cls):
return cls.DEFAULT_FUEL_... |
import os
import tempfile
from unittest import TestCase
from sampleProcess import SampleProcess
"""
This a integration test
"""
class ITTestSampleProcess(TestCase):
def test_run(self):
# Arrange
sut = SampleProcess()
tmpout = tempfile.mkdtemp()
# Act
actual = sut.run(ou... |
from django.apps import AppConfig
class ValidationcwappConfig(AppConfig):
name = 'validationcwApp'
|
#!/usr/bin/env python
# Copyright (c) 2014 Pier Carlo Chiodi - http://www.pierky.com
# Licensed under The MIT License (MIT) - http://opensource.org/licenses/MIT
import json
import datetime
import smtplib
from core import *
from config import *
# returns None or failure reason
def DoesScheduleMatch( DateTime, Schedul... |
from DAPI import *
from ctypes import *
import LAPI
import sys
rcmap = dict(zip("ACGTacgtNn-","TGCATGCANN-"))
def rc(seq):
return "".join([rcmap[c] for c in seq[::-1]])
ovl_data = LAPI.get_ovl_data(sys.argv[1])
db = DAZZ_DB()
open_DB(sys.argv[2], db)
trim_DB(db)
aln = LAPI.Alignment()
aln.aseq = LAPI.new_read_b... |
my_a = np.array([2, 3, 5, 7, 10])
my_sigma_a = np.array([0.2, 0.3, 0.4, 0.7, 0.9])
my_b = np.array([2, 3, 6, 4, 8])
my_sigma_b = np.array([0.3, 0.3, 0.5, 0.5, 0.5])
# errors propagated using custom functions
my_sum_ab_l, my_sigma_sum_ab_l = sum_ab(a=my_a, b=my_b, sigma_a=my_sigma_a, sigma_b=my_sigma_b)
my_division_... |
"""
[2016-04-29] Challenge #264 [Hard] Detecting Poetry Forms
https://www.reddit.com/r/dailyprogrammer/comments/4gzeze/20160429_challenge_264_hard_detecting_poetry_forms/
# Description
This is a variant of last week's intermediate challenge and was inspired by a comment from /u/Agent_Epsilon. In short,
given a piece ... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
def get_loss_function(loss_name):
if loss_name == 'ce':
return nn.CrossEntropyLoss()
elif loss_name == 'bce':
return nn.BCEWithLogitsLoss()
else:
raise ValueError
def per... |
from functools import reduce
from parsy import string, regex, generate, fail
from chr.ast import *
'''
integer ::= [0-9]+
string ::= '"' .* '"'
key_value ::= term ':' term
dict ::= '{' key_value { ',' key_value }* '}'
list ::= '[' term { ',' term }* ']'
symbol ::= [a-z][a-zA-Z0-9_-]*
variable ::= [A-Z_]... |
from eth_keys import keys
from eth_utils import decode_hex
from tests.core.integration_test_helpers import FUNDED_ACCT, load_mining_chain
from .churn_state.builder import (
delete_churn,
deploy_storage_churn_contract,
update_churn,
)
RECEIVER = keys.PrivateKey(
decode_hex("b71c71a67e1177ad4e901695e1b... |
# To Create dummy date (use in case of inavilability of data)
import random
start = [11, 5 ,2006]
end = [4, 12, 2010]
interval = [20, 26, 23, 19, 29]
def giveDate(previous):
inter = random.choice(interval)
previous[0] = previous[0] + inter
if previous[0] > 30:
previous[0] = previous[0] - 30
... |
'''
Module specific config
'''
import configparser
import os.path
import json
from simplesensor.shared import ThreadsafeLogger
def load(loggingQueue, name):
""" Load module specific config into dictionary, return it"""
logger = ThreadsafeLogger(loggingQueue, '{0}-{1}'.format(name, 'ConfigLoader'))
this... |
#!/usr/bin/env python
# -*- noplot -*-
from __future__ import print_function
import os
import matplotlib.pyplot as plt
import numpy as np
files = []
fig, ax = plt.subplots(figsize=(5, 5))
for i in range(50): # 50 frames
plt.cla()
plt.imshow(np.random.rand(5, 5), interpolation='nearest')
fname = '_tmp%0... |
'''
Pychecko is a microframework to compose
the methods in an instance in real time.
'''
import collections
import inspect
import types
from abc import (
ABCMeta,
abstractmethod,
)
class PyCheckoException(Exception):
'''Most genetic exception in Pychecko.'''
pass
class InvalidRuleError(PyCheckoExce... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 3 21:56:51 2021
@author: giuseppeperonato
"""
import csv
import json
class Recipe():
def __init__(self, name):
self.name = name
self.ingredients = {}
self.content = {}
self.cooking_steps = []
self.db... |
# -*- coding: utf-8 -*-
from functools import wraps
from .error import (UnknowResponse, LoginRequired, AuthenticationFailed,
DetailedHTTPError, UnknownShow, UnknownEpisode)
from .httpclient import HTTPClient, HTTPClientBase
from .models import Show, ShowDetails, EpisodeDetails
from .constants impor... |
"""Basic serializer."""
import re
from rest_framework import serializers
class MessageSerializer(serializers.Serializer):
"""Message serializer."""
message = serializers.CharField(required=True)
class ErrorSerializer(MessageSerializer):
"""Error serializer."""
errors = serializers.ListField(chil... |
import argparse
import json
import os
import os.path as osp
import pickle
import math
from datetime import datetime
from pdb import set_trace as st
import numpy as np
import torch
from PIL import Image
from torch.utils.data import Dataset
from torch import optim
from torchvision.datasets.folder import ImageFolder, IMG... |
from __future__ import print_function
import itertools
import numpy as np
import sys
sys.path.append('..')
from lib_inhomogeneous_gutzwiller import Gutzwiller
def test_lattice_definition_2D():
xy = np.empty(2, dtype=np.int32)
for L in [2, 3, 10, 11]:
G = Gutzwiller(D=2, L=L)
for i_site in ran... |
import math
num = float(input("Digite um número:"))
print("\n")
raiz = int ((num) ** 0.5)
raiz2 = float((num) ** 0.5)
print("O numero inteiro que mais se aproxima da raiz quadrada de", num,"é", raiz + 1)
print("A raiz quadrada de", num, "é {} ".format(round(raiz2 , 2))) |
# Copyright (c) 2019 CommerceBlock Team
# Use of this source code is governed by an MIT
# license that can be found in the LICENSE file.
import sys
import json
import argparse
import binascii
import io
import logging
import appdirs
import os
import time
import requests
import threading
import hashlib
import math
impor... |
from API import SolvedAPI
from make_table import Table
import json
import argparse
import os
config = dict()
solution_list = dict()
changeLevel_list = list()
api = None
table = None
def getFolder(path, EXCEPT=list()):
return [ folder for folder in os.listdir(path) \
... |
from __future__ import print_function
import sys
class ErrorLog(object):
NOTE = "notice"
WARN = "warning"
FAIL = "error"
REPORT_FILE = "docsgen_report.json"
def __init__(self):
self.errlist = []
self.has_errors = False
self.badfiles = {}
def add_entry(self, file, lin... |
from unittest import TestCase
import pandas as pd
from pytz import UTC
from test_trading_calendar import ExchangeCalendarTestBase
from trading_calendars.exchange_calendar_xwbo import XWBOExchangeCalendar
class XWBOCalendarTestCase(ExchangeCalendarTestBase, TestCase):
answer_key_filename = 'xwbo'
calendar_cl... |
{"akina saegusa": "nijisanji", "ange katrina": "nijisanji", "ars almal": "nijisanji", "debidebi debiru": "nijisanji", "dola": "nijisanji", "fuwa minato": "nijisanji", "fuyuki hakase": "nijisanji", "haru kaida": "nijisanji", "hayato kagami": "nijisanji", "kai mayuzumi": "nijisanji", "kana sukoya": "nijisanji", "kanae": ... |
import os
import requests
import json
import csv
import pandas as pd
from dotenv import load_dotenv
load_dotenv()
apikey = os.environ.get("API_KEY")
def get_zipcode(csv_file_path):
with open(csv_file_path,'r') as csv_file:
reader = csv.DictReader(csv_file)
for row in reader:
str... |
import sys
from _functools import reduce
import configurations as conf
import pagerank_utils as pru
import topic_specific_pagerank as tspr
import WebIR_HW_2_part_2 as part2
def _print_usage():
usage='''
Usage:
python WebIR_HW_2_part_4.py <graph_path> <user_ratings> <user_group_weights> [--verbose]
Example:
pytho... |
# Generated by Django 2.2.1 on 2020-03-25 13:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Kabupaten',
fields=[
... |
"""
Filename / URL patterns.
"""
import inspect
from dataclasses import dataclass, field, replace
from enum import Enum
from itertools import product
from typing import (
Any,
Callable,
ClassVar,
Dict,
Iterable,
Iterator,
List,
Optional,
Sequence,
Tuple,
Union,
)
class Com... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""This module contains class MRT_Metadata_Parser
The purpose of this class is to prepare MRT files for extrapolator.
This is done through a series of steps.
Read README for in depth explanation.
"""
__authors__ = ["Justin Furuness"]
__credits__ = ["Justin Furuness"]
_... |
"""
Template App - costum class template to efficiently handle objects
"""
# general imports
import numpy as np
# bokeh imports
from bokeh.models import ColumnDataSource
# internal imports
from TA_constants import xsl, ysl, xsr, ysr
# latex integration
#--------------------------------------------------------------... |
############################################################
# -*- coding: utf-8 -*-
#
# # # # # # #
# ## ## # ## # #
# # # # # # # # # # #
# # ## # ## ## ######
# # # # # # #
#
# Python-based Tool for interaction with the 10micron mounts
# GUI with PyQT5 fo... |
# Copyright 2019-2020 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" fil... |
from .wrapper import TransitionRecorderWrapper
|
#
# Download wix from http://wix.sourceforge.net/
# Install it to a path that DOES NOT have spaces or use a subst drive
# Set windows environment variable DEVBIN
#
import os, sys, shutil, hashlib, socket, time, tempfile
import random, re
from xml.dom import minidom
from os.path import join
import getopt
packageFiles ... |
from . import views
from flamingo.url.conf import path
routers = [
path(url="/aaaa", view_func_or_module=views.test, name="test_aaaa"),
path(url="/params/<int:id>/", view_func_or_module=views.params_test)
]
|
from urllib.parse import urlencode
import pytest
from django.contrib.auth import get_user_model
from django.http import HttpRequest
from django.urls import reverse
from tahoe_idp.tests.magiclink_fixtures import magic_link, user # NOQA: F401
User = get_user_model()
@pytest.mark.django_db
def test_login_verify(cli... |
import csv, os, json, argparse, sys
"""
Print tree of proper chemclasses
"""
# Initiate the parser
parser = argparse.ArgumentParser()
parser.add_argument("-q", "--query", help="perform SPARQL query",
action="store_true")
# Read arguments from the command line
args = parser.parse_args()
#print(args)
# Check ... |
# Copyright (c) 2016-2019, Broad Institute, 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 source code must retain the above copyright notice,
# this list of co... |
import pytest
import datetime as dt
from unittest import mock
from django.urls import reverse
from genie.models import NotebookRunLogs, NOTEBOOK_STATUS_RUNNING, NOTEBOOK_STATUS_SUCCESS, NOTEBOOK_STATUS_ERROR
from workflows.models import WorkflowRunLogs, STATUS_RUNNING, STATUS_SUCCESS, STATUS_ERROR
from mixer.backend.dj... |
from cms.utils.plugins import get_plugins
from django import template
register = template.Library()
@register.simple_tag(name='media_plugins', takes_context=True)
def media_plugins(context, post):
"""
Extract :py:class:`djangocms_blog.media.base.MediaAttachmentPluginMixin`
plugins from the ``media`` plac... |
#!/usr/bin/env python
"""Use numpy array."""
import sys
import numpy as np
A = np.array([4, 6, 8])
print(type(A))
A[0] = 7
print(A)
sys.exit()
|
__all__ = ["search"]
# standard library
from logging import getLogger
from typing import List, Sequence
# dependencies
from arxiv import Search
from dateparser import parse
# submodules
from .article import Article
from .consts import CATEGORIES, KEYWORDS, START_DATE, END_DATE
# constants
ARXIV_DATE_FORMAT = "%... |
from data import Database, ScrapeWSB
import streamlit as st
st.title('**Labeling Interface**')
st.markdown(""" #### Interface to assist in hand labeling posts and comments """)
st.text("IMPORTANT: You must set sentiment to 'select sentiment' when choosing 'POSTS' or 'COMMENTS'")
st.text("")
st.text("")
st.text("")
s... |
import sys
import re
import logging
import nbformat as nbf
from nbconvert.preprocessors import Preprocessor
import traitlets
from box import Box
DEBUG = 1
if DEBUG:
logging.basicConfig(level=logging.DEBUG)
def load_lessons(lesson_dicts):
res = [Lesson(d, i) for i, d in enumerate(lesson_dicts)]
for i, le... |
"""
Python Markdown
A Python implementation of John Gruber's Markdown.
Documentation: https://python-markdown.github.io/
GitHub: https://github.com/Python-Markdown/markdown/
PyPI: https://pypi.org/project/Markdown/
Started by Manfred Stienstra (http://www.dwerg.net/).
Maintained for a few years by Yuri Takhteyev (ht... |
grau = float(input())
min = float(input())
seg = float(input())
conversor = seg / 60
min = min + conversor
conversor = min / 60
grau = grau + conversor
print('graus = {:.4f}'.format(grau))
|
try:
import unittest2 as unittest
except ImportError:
import unittest
import rope.base.history
from rope.base import exceptions
import rope.base.change
from ropetest import testutils
class HistoryTest(unittest.TestCase):
def setUp(self):
super(HistoryTest, self).setUp()
self.project = te... |
# Copyright 2021 GraphRepo
#
# 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, so... |
from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.http import HttpResponse, JsonResponse
from django.core.exceptions import ValidationError
try:
from django.utils import simplejson as json
except ImportError:
import json
import logging
from braces.views import ... |
"""Hive Alarm Module."""
class HiveHomeShield:
"""Hive homeshield alarm.
Returns:
object: Hive homeshield
"""
alarmType = "Alarm"
async def getMode(self):
"""Get current mode of the alarm.
Returns:
str: Mode if the alarm [armed_home, armed_away, armed_night]... |
from models.quartznet import ASRModel
from utils import config
import torch
import os
import soundfile as sf
from datasets.librispeech import image_val_transform
from transforms import *
from torchvision.transforms import *
from utils.model_utils import get_most_probable
from collections import OrderedDict
from utils.l... |
"""Tests for dicomtrolley"""
|
"""Generate Gradcam maps for man/woman given the predicted captions"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import os
import glob
import sys
import json
import os.path as osp
import tensorflow as tf
import PIL.Image
import numpy as n... |
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
import buggy.urls
import buggy_accounts.urls
urlpatterns = [
url(r'^', include(buggy.urls)),
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include(... |
#!/usr/bin/env python
r'''
https://www.hackerrank.com/challenges/designer-pdf-viewer/problem
'''
import math
import os
import random
import re
import sys
# Complete the designerPdfViewer function below.
def designerPdfViewer(h, word):
maxHeight = 0
for i in range(len(word)):
ch = h[ord(word[i]) - 97]
... |
from copy import deepcopy
def is_negative_literal(n):
if n[0] == "neg":
return True
return False
def is_positive_literal(n):
if n[0] != "neg":
return True
return False
def get_premises(formula):
# TODO
#return []
return [get_args(n)[0] for n in get_args(formula) if is_neg... |
import os
import numpy as np
import pandas as pd
import xarray as xr
import ESMF
USER = os.environ['USER']
os.environ['CESMDATAROOT'] = f'/glade/scratch/{USER}/inputdata'
import pop_tools
path_to_here = os.path.dirname(os.path.realpath(__file__))
regrid_dir = f'/glade/work/{USER}/adhoc-regridding'
os.makedirs(re... |
import wpilib
from wpilib.interfaces import SpeedController
from wpilib import VictorSP
from magicbot import will_reset_to
class Intake:
intake_motor: VictorSP
speed = will_reset_to(0)
def spin(self, speed: float):
self.speed = speed
def execute(self):
self.intake_motor.set(self.spee... |
import pandas
s = pandas.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 5, 3])
print(s)
mean = s.mean()
print("Mean: " + str(mean))
sd = s.std()
print("Standard Deviation: " + str(sd))
|
import random
class Character:
name = ""
attack = 0
defense = 0
maxhealth = 0
currenthealth = 0
def getName(self):
return self.name
def getCurrentHealth(self):
return self.currenthealth
def getMaxHealth(self):
return self.maxhealth
def getAtta... |
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring
import json
import pytest
@pytest.mark.parametrize(
'http_method,http_path',
(
('GET', '/api/v1/auth/clients'),
('POST', '/api/v1/auth/clients'),
),
)
def test_unauthorized_access(http_method, http_path, flask_app_client):
re... |
from django.shortcuts import render
# Create your views here.
def home_view(request, *args, **kwargs):
return render(request, "home/home_view.html", {})
def chat_room_view(request, *args, **kwargs):
return render(request, "home/chat_room_view.html", {})
|
# -*- coding: utf-8 -*-
from contextlib import contextmanager
import os
import tempfile
import json
def _tempfile(filename):
"""
Create a NamedTemporaryFile instance to be passed to atomic_writer
"""
return tempfile.NamedTemporaryFile(mode='w',
dir=os.path.dirna... |
"""
Simple text plugin forms
"""
from html import unescape
from unicodedata import normalize
from django import forms
from django.utils.html import strip_spaces_between_tags
from djangocms_text_ckeditor.widgets import TextEditorWidget
from .models import SimpleText
class CKEditorPluginForm(forms.ModelForm):
""... |
#!/usr/bin/python
import networkx as nx
import pprint
import sys
pp = pprint.PrettyPrinter(indent=2)
def write_dfg(dfgfile, dfg):
nx.drawing.nx_agraph.write_dot(dfg, 'ldst.'+dfgfile)
def add_edges(a,b, sorted_memops,dfg):
for val in sorted_memops[a+1:b+1]:
# print "adding edges : val_a= " + str(... |
from flask import Flask, render_template, send_from_directory, redirect, url_for, request, flash,Blueprint,jsonify, current_app
from portfolio.forms import LoginForm, Testimoni_form, SkillForm, ProjectForm, JobForm,changepictureForm
import os
from PIL import Image
from datetime import datetime
from flask_login import l... |
from flask import Flask,request,jsonify
import requests
import json
def main():
file=open("sensor_registration.json","r")
data=json.load(file)
d = {'username':'test1234','config_file':data}
r=requests.post(url="http://13.68.206.239:5051/sensorregistration",json=d)
# r=requests.post(url="http://127.0.0.1:9000/t... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 entro <entropy1208@yahoo.co.in>
#
# Distributed under terms of the MIT license.
import numpy as np
from sklearn import neighbors, svm
from sklearn.model_selection import cross_validate
from sklearn.naive_bayes import GaussianNB
import... |
###
### Copyright (C) 2018-2019 Intel Corporation
###
### SPDX-License-Identifier: BSD-3-Clause
###
from ....lib import *
from ..util import *
spec = load_test_spec("mpeg2", "encode")
def check_psnr(params):
call(
"ffmpeg -hwaccel qsv -hwaccel_device /dev/dri/renderD128 -v verbose"
" -c:v mpeg2_qsv -i {enc... |
# -*- coding: utf-8 -*-
from flask import Flask, request, render_template, jsonify
import summarizer_machovec_modified
app = Flask(__name__)
app.config['DEBUG'] = True
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
text = request.form.get('text') or ''
s... |
"""Programa 7_4.py
Descrição: Escrever um programa que leia uma string e imprima quantas vezes cada caracter aparece.
Autor:Cláudio Schefer
Data:
Versão: 001
"""
# Declaração de variáveis
s = ""
d = {}
# Entrada de dados
s = input("Digite a string:")
d = {}
# Processamento
for letra in s:
if letra in d:
... |
import tensorflow as tf
def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):
"""
Freezes the state of a session into a pruned computation graph.
Creates a new computation graph where variable nodes are replaced by
constants taking their current value in the s... |
"""Unit tests for stem.py"""
from sbws.util.stem import parse_user_torrc_config
def test_parse_user_torrc_config_new_keyvalue_options_success():
config_torrc_extra_lines = """
Log debug file /tmp/tor-debug.log
NumCPUs 1
"""
torrc_dict = parse_user_torrc_config({}, config_torrc_extra_lines)
as... |
import tensorflow as tf
import sagemaker
from tensorflow.keras.datasets import fashion_mnist
from tensorflow.keras import utils
import os, json, logging
import numpy as np
import boto3
from botocore.exceptions import ClientError
from tqdm import tqdm
def uploadFile(file_name, bucket, object_name=None):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pylint: disable=C0103,W0703,R1711
'''
TTS service modules
GoogleTTS - TTS from google
XunfeiTTS - TTS from Xunfei (TBD)
AmazonPollyTTS - TTS from Amazon(TBD)
'''
import os
import logging
import html
from google.cloud import texttospeech
TTS_CONFIG = {
"GOOGLE_TTS... |
if 'INSTALLED_APPS' not in locals()["__builtins__"]:
INSTALLED_APPS = []
INSTALLED_APPS += (
'bootstrap3',
'django_admin_bootstrapped',
'jquery',
'pinax.eventlog', # Not mandatory
'bootstrapform',
'django.contrib.staticfiles',
'django_tables2',
'background_task',
'django_tables... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.