content stringlengths 5 1.05M |
|---|
import pathlib
import numpy
import pandas as pd
from libs.datasets.population import PopulationDataset
from libs.datasets import dataset_utils
from libs.datasets import data_source
from libs.us_state_abbrev import US_STATE_ABBREV, ABBREV_US_FIPS
from libs import enums
from libs.datasets.dataset_utils import Aggregation... |
names = ['Michael_', 'Bob_', 'Tracy_']
for name in names:
print(name, end="")
print("---------------------------------")
# python内置id()函数,这个函数用于返回对象的唯一标识(identity)。对象实际内存地址为hex(id(obj)),本文我将id()和内存地址划等号。
# 内置函数is(),用于比较两个对象的identity是否一样,举例:
classmates = ['Michael', 'Bob', 'Tracy']
a = ['Michael', 'Bob', 'Tracy']
... |
# 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,... |
from django.contrib import admin
from .models import Proxy
@admin.register(Proxy)
class ProxyAdmin(admin.ModelAdmin):
...
|
import discord
from redbot.core import commands, checks, Config, modlog
from redbot.core.utils.chat_formatting import humanize_list
from redbot.core.i18n import Translator, cog_i18n
from .eventmixin import EventMixin, CommandPrivs
inv_settings = {
"message_edit": {"enabled": False, "channel": None, "bots": False... |
import time
import unittest
import sys
from utils import xbridge_utils
from interface import xbridge_client
""" *** COMMENT ***
- Here, the length of the garbage data is very high and increased.
The "j" parameter in the "generate_garbage_input" function is the length of the... |
#!/usr/bin/env python2
# Own config parser based on ConfigParser. Defines default values.
import ConfigParser
import utils
import time
confn = "main.ini"
#confn = "test.ini"
#caln = "calib_data.txt"
#ttyn = "/dev/ttyUSB0"
#mainpos = (180, 0)
#addr = ('192.168.1.29', 12345)
#az_step = 0.5
#el_step = 0.5
# Earth radiu... |
# -*- coding: utf-8 -*-
def slugify_persian(str):
# self.slug = slugify(self.title)
str = str.replace(u'،', "-")
str = str.replace(u'، ', "-")
str = str.replace("(", "-")
str = str.replace(")", "")
str = str.replace( u'؟', "")
str = str.replace( u'?', "")
str = str.replace( u'!', "")
str = '-'.join(str.lower(... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google 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 or... |
import math
# log e tan
tan = math.tan(3.14/6)
log = math.log(1000,10)
print("O tangente é: ", tan)
print("O log é: ", log)
# arredondamento
a = 3.8
print(math.ceil(a))
print(math.floor(a))
# raiz e potencia
raiz = math.sqrt(36)
potencia = math.pow(2,3)
# seno e cosseno
seno = math.sin(3.14/6) # 30 graus
cosseno ... |
default_app_config = 'parsing.apps.ParsingConfig' |
from flask_restful import Resource, reqparse
import psycopg2
import pandas as pd
from pandas.io.json import json_normalize
import cx_Oracle
from sqlalchemy import create_engine
import datetime
import numpy as np
import json
import re
from flask_jwt_extended import (create_access_token, create_refresh_token, j... |
import unittest
from unittest import TestCase
from escnn.gspaces import *
from escnn.nn import *
class TestRestriction(TestCase):
def test_restrict_rotations(self):
space = rot2dOnR2(-1, maximum_frequency=10)
cls = FieldType(space, list(space.representations.values()))
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# cryptographically secure pseudorandom number generators
def mcg(alpha, beta, m, n):
"""
Multiplicative congruential generator (MCG)
"""
for i in range(n):
alpha = (beta * alpha) % m
yield alpha / m
def mmg(b, c, k, n):
"""
MacLa... |
from django.urls import path, include
from .views.project_view import *
from .views.column_view import *
from .views.task_view import *
from .views.subtask_view import *
from .views.comment_view import *
from .views.attachments_view import *
urlpatterns = [
path('project/detail/<int:pk>/', ProjectDetailView.as_view(... |
from django import forms
from accounts.models import GovDepartment
class SCDForm(forms.Form):
department = forms.ModelChoiceField(
queryset=GovDepartment.objects.all(),
empty_label="Select department",
widget=forms.Select(
attrs={
"class": "govuk-select",
... |
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
di = {}
for line in handle:
if line.startswith('From '): #I forgot the space while the first trial
line = line.rstrip()
words = line.split()
email = list()
# it should use list to store the em... |
"""
1:9 binding system solved using Lagrange multiplier approach
Modified Factory example utilising Lagrane multiplier to solve complex
concentration in a 1:9 protein:ligand binding system
"""
from timeit import default_timer as timer
from scipy.optimize import fsolve
import autograd.numpy as np
from autograd import g... |
#!/usr/bin/env python
#
# Copyright 2012 cloudysunny14.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
#!/bin/python
#
import os
import time
import sys
import random
import math
import shutil
#appion
from appionlib import appionScript
from appionlib import apDisplay
from appionlib import apFile
from appionlib import apTemplate
from appionlib import apStack
from appionlib import apEMAN
from appionlib import apProject
fro... |
import webview
import time
"""
This example demonstrates how a webview window is created and URL is changed
after 10 seconds.
"""
def change_url(window):
# wait a few seconds before changing url:
time.sleep(10)
# change url:
window.load_url('https://pywebview.flowrl.com/hello')
if __name__ == '__m... |
# COLLISION AVOIDANCE MECHANISM
import numpy as np
import matplotlib.pyplot as plt
import logging
from arm import Arm
from velocity_control import linear_interpolation, find_intersection, update_velocity, adjust_arm_velocity
from arm import Arm
logger = logging.getLogger(__name__)
logging.basicConfig()
logger.setLev... |
"""Platform for sensor integration."""
from datetime import timedelta
import logging
import voluptuous as vol
from oru import Meter
from oru import MeterError
from homeassistant.components.sensor import PLATFORM_SCHEMA
import homeassistant.helpers.config_validation as cv
from homeassistant.const import ENERGY_KILO_W... |
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime, timedelta, timezone
from tnnt import settings
from tnnt import dumplog_utils
# If adding any more models to this file, be sure to add a deletion for them in
# wipe_db.py.
class Trophy(models.Model):
# The "perm... |
def define(hub):
'''
Return the definition used by the runtime to insert the conditions of the
given requisite
'''
return {
'result': [True, None],
}
|
'''
* Copyright (C) 2019-2020 Intel Corporation.
*
* SPDX-License-Identifier: BSD-3-Clause
'''
import sys
import json
from os import path
import gi
gi.require_version('Gst', '1.0') # pylint: disable=wrong-import-position
from gi.repository import Gst
from gstgva import VideoFrame
DETECT_THRESHOLD = 0
Gst.init(sys.ar... |
V = float(input('Qual é a velocidade atual do carro?'))
if V > 80:
print('Multado! você excedeu o limite que é de 80km/h')
print(f'Você deve pagar uma multa de R${(V - 80)*7:.2f}!')
print('Tenha um bom dia! Dirija com segurança!')
|
import logging
import traceback
from functools import partial, wraps, update_wrapper
from multiprocessing import Process
from threading import Thread
from celery import shared_task as celery_shared_task
from celery import states
from celery.decorators import periodic_task as celery_periodic_task
from django.core.mail ... |
from django.contrib.auth import authenticate, login, get_user_model
from django.http import HttpResponse
from django.shortcuts import render, redirect
from .forms import ContactForm
def home_page(request):
context = {
"title": "رستوران خوشخور",
"content": request.user.username,
}
return r... |
from asgard.models.base import BaseModel
class ScheduleSpec(BaseModel):
value: str
tz: str = "UTC"
|
"""All the input and responses that the chatbot can receive and give"""
pairs = [
[
r"my name is (.*)",
["Hello %1, How are you feeling today?", ]
],
[
r"i am a bit concerned about this recent stock market fiasco",
["Do not be alarmed sir, I've handled your investmen... |
# pylint: disable=unused-import,missing-docstring
from deepr.optimizers.base import Optimizer
from deepr.optimizers.core import TensorflowOptimizer
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2019 Snowflake Computing Inc. All right reserved.
#
import pytest
import time
from datetime import datetime
from snowflake.connector.compat import IS_WINDOWS
from snowflake.connector.sfdatetime import (
SnowflakeDateTimeFormat,
SnowflakeDateTi... |
# voltage is channel 0
# current is channel 1
from crownstone_core.util.Conversion import Conversion
class AdcChannelPacket:
packetSize = 6
def __init__(self, payload, channelIndex):
if len(payload) < self.packetSize:
print("ERROR: INVALID PAYLOAD LENGTH", len(payload), payload)
... |
# ---
# jupyter:
# jupytext:
# cell_metadata_filter: -all
# comment_magics: true
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.13.8
# kernelspec:
# display_name: Python 3.8.0 ('mapp... |
#!/usr/bin/env python
import mlxtk
from mlxtk.systems.single_species.harmonic_trap import HarmonicTrap
if __name__ == "__main__":
x = mlxtk.dvr.add_harmdvr(512, 0.0, 1.0)
parameters = HarmonicTrap.create_parameters()
parameters.m = 19
parameters_quenched = parameters.copy()
parameters_quenched.om... |
#!/usr/bin/env python3
import io
import os
import shutil
import sys
import urllib.parse
import xml.etree.ElementTree as etree # cElementTree has no _namespace_map?
import zipfile
class LinkResolver(object):
"""Holds context relevant to resolving links."""
def __init__(self, zfile, directory):
self.zf... |
import platform
import sys
import aiohttp
import pytest
from pytest_toolbox import mktree
from aiohttp_devtools.exceptions import AiohttpDevConfigError
from aiohttp_devtools.runserver.config import Config
from aiohttp_devtools.runserver.serve import modify_main_app
from aiohttp_devtools.start import StartProject
IS_... |
from __future__ import absolute_import
import pytest
import base64
import mock
from exam import fixture
from six.moves.urllib.parse import urlencode, urlparse, parse_qs
from django.conf import settings
from django.core.urlresolvers import reverse
from sentry.auth.providers.saml2 import SAML2Provider, Attributes, HAS... |
import shutil
from pathlib import Path
import pytest
from quick_zip.schema.backup_job import BackupJob, BackupResults
from quick_zip.services import zipper
def test_validate_job_store(job_store):
assert all(isinstance(x, BackupJob) for x in job_store)
for _ in job_store:
pass
def test_replace_varia... |
import os
import sys
import torch
from torch.autograd import Variable
import torch.nn as nn
from qpth.qp import QPFunction
def computeGramMatrix(A, B):
"""
Constructs a linear kernel matrix between A and B.
We assume that each row in A and B represents a d-dimensional feature vector.
Parameters:... |
"""Implementation of Adversarial Attack
1. Fast Gradient Method
2. Optimization Method
"""
import os
import tensorflow as tf
import numpy as np
import utils.data_prepare as data
import utils.CNN as CNN
import IPython
from tensorflow.python import debug as tf_debug
import h5py as h5
from skimage import ... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2020, Exa Analytics Development Team
# Distributed under the terms of the Apache License 2.0
from exa import DataFrame
import numpy as np
#import pandas as pd
class Gradient(DataFrame):
"""
The gradient dataframe
"""
# simple function that will have to be s... |
# https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
# Related Topics: Array, Binary Search
# Difficulty: Medium
# Initial thoughts:
# A naive approach is to look at every element of nums to find the beginning
# and end of target. This approach's Time complexity is O(n).
# To redu... |
from flask import Flask
application = Flask(__name__)
application.config.from_object('config')
from app import views
|
import json
class Bch_sim:
def List_Terminals(self, file_name):
with open(file_name) as ofile:
self.terminals = json.loads(ofile.read())
sys = Bch_sim()
sys.List_Terminals("terminals.json")
print(sys.terminals) |
while True:
try:
s = input()
except:
break
def cal(n, k):
if n == 1:
return k
return cal(3*n+1, k+1) if n % 2 else cal(n/2, k+1)
[i, j] = list(map(int, s.split()))
print(i, j, end=' ')
if i > j:
i, j = j, i
data = list()
for x in range... |
# mqtt_log.py Demo/test program for MicroPython asyncio low power operation
# Author: Peter Hinch
# Copyright Peter Hinch 2019 Released under the MIT license
# MQTT Demo publishes an incremental count and the RTC time periodically.
# On my SF_2W board consumption while paused was 170μA.
# Test reception e.g. with:
# ... |
# -*- coding=utf-8 -*-
'''
有两个容量分别为 x升 和 y升 的水壶以及无限多的水。请判断能否通过使用这两个水壶,从而可以得到恰好 z升 的水?
如果可以,最后请用以上水壶中的一或两个来盛放取得的 z升 水。
你允许:
装满任意一个水壶
清空任意一个水壶
从一个水壶向另外一个水壶倒水,直到装满或者倒空
示例1: (From the famous "Die Hard" example)
输入: x = 3, y = 5, z = 4
输出: True
'''
import copy
class Solution(object):
def canMeasureWater(self, x, y,... |
from trame.internal import (
change, Controller, flush_state, get_cli_parser, get_state, get_version,
is_dirty, is_dirty_all, port, start, State, stop, trigger, update_state
)
from trame.layouts import update_layout
__version__ = get_version()
state = State()
"""This object provides pythonic access to the state
... |
# ----------------------------- #
# Collection of functions I use #
# ----------------------------- #
import numpy as np
from numba import njit
# @njit
def gini(x, w=None):
'''Compute the gini coefficient for array x'''
# The rest of the code requires numpy arrays.
x = np.asarray(x)
if w is not None:... |
from typing import Union, List
class InputExample:
"""
Structure for one input example with texts, the label and a unique id
"""
def __init__(self, guid: str, texts: List[str], label: Union[int, float]):
"""
Creates one InputExample with the given texts, guid and label
str.str... |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... |
from spacy.lang.ja import Japanese
from spacy.tokens import Token
nlp = Japanese()
# デフォルト値がFalseである拡張属性「is_country」をトークンに追加
____.____(____, ____=____)
# テキストを処理し、「スペイン」のトークンについてis_country属性をTrueにする
doc = nlp("私はスペインに住んでいます。")
____ = True
# すべてのトークンについて、文字列とis_country属性を表示
print([(____, ____) for token in doc])
|
display(bikeshare[(bikeshare['temp']>30) & (bikeshare['atemp']<10)])
|
"""WSGI config for grpc_python_example.apis.http.
Exposes the WSGI callable as a module-level variable named `app`.
"""
import os
from grpc_python_example.apis.http import create_app
# pylint: disable=invalid-name
env = os.environ.get('ENV', 'development')
app = create_app('grpc_python_example.apis.http.settings.%sCo... |
import csv
from datetime import datetime
import json
import os
import pickle
import psutil
import random
import re
import socket
import subprocess
from job import Job
from job_table import JobTable
from policies import allox, fifo, finish_time_fairness, gandiva, isolated, \
max_min_fairness, max_min_fairness_water... |
# -*- coding: utf-8 -*-
import json
from collections import OrderedDict
from typing import List
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import pandas as pd
from dash import dash
from dash.dependencies import Input, Output, State
from zvdata import IntervalLevel
from zv... |
import logging
from collections import Counter
from operator import itemgetter
from django.contrib import messages
from django.db import transaction
from django.shortcuts import render, get_object_or_404, redirect
from vcweb.core.decorators import group_required
from vcweb.core.forms import SingleIntegerDecisionForm
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable la... |
from os import path, mkdir
import app.functions as functions
from datetime import datetime
functions.current_datetime = datetime.now().strftime("%Y-%m-%d %H-%M-%S")
output_dir = "output/"
if not path.exists(output_dir):
mkdir(output_dir)
functions.video_output_dir = output_dir + functions.current_datetime + "/"... |
import os
from setuptools import setup, find_packages
DESCRIPTION = "Toolkit for genome-wide analysis of STRs"
LONG_DESCRIPTION = DESCRIPTION
NAME = "trtools"
AUTHOR = "Melissa Gymrek"
AUTHOR_EMAIL = "mgymrek@ucsd.edu"
MAINTAINER = "Melissa Gymrek"
MAINTAINER_EMAIL = "mgymrek@ucsd.edu"
DOWNLOAD_URL = 'http://github.co... |
#!/usr/bin/env Python
from __future__ import print_function
from collections import OrderedDict
import pprint
def getcpuname():
CPUinfo=OrderedDict()
procinfo=OrderedDict()
nprocs = 0
with open('/proc/cpuinfo') as f:
for line in f:
if not line.strip():
CPUinfo['pro... |
# 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 __future__ import print_function
import codecs
import errno
import multiprocessing.pool
import os
import os.path
imp... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Evaluate ball detection and forecast - Deeplearning Exercice 1 - Part 1
.. moduleauthor:: Paul-Emmanuel Sotir
.. See https://perso.liris.cnrs.fr/christian.wolf/teaching/deeplearning/tp.html and https://github.com/PaulEmmanuelSotir/BallDetectionAndForecasting
""... |
import matplotlib.pyplot as plt
import numpy as np
def parse_result(f):
return [float(a) / 1000 for a in f.read().split("\n")[:-1]]
with open("../data/python_bench.txt") as f:
pandas = parse_result(f)
with open("../data/python_bench_str.txt") as f:
pandas_str = parse_result(f)
with open("../data/pypola... |
import json
import logging
import os
import random
import time
from emoji import emojize
from telegram import Bot, Update
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
RESPONSE = {
"OK": {
'statusCode': 200,
'headers': {'Content-type':... |
#
# Python Testing: Covering Your Bases
# Python Techdegree
#
# Created by Dulio Denis on 1/13/19.
# Copyright (c) 2019 ddApps. All rights reserved.
# ------------------------------------------------
# `coverage.py` is an amazing library for
# determining how much of your code is covered
# by your tests and how... |
class MyClass:
"""
This class does... stuff
"""
def do_something(self):
#jupman-raise
print("Doing something")
#/jupman-raise
def do_something_else(self):
#jupman-raise
print("Doing something else")
helper(5)
#/jupman-raise
... |
n = int(input('Digite um numero'))
if(n % 2 == 0):
print('Número é Par!')
else:
print('Número é Impar!') |
import os
import sys
import csv
import argparse
import logging
import datetime
import itertools
from os.path import join, dirname, abspath, relpath
from cached_property import cached_property
from pyclarity_lims.entities import Step, Queue
from egcg_core import clarity, util
from egcg_core.app_logging import AppLogger,... |
import os
import sys
import subprocess
from pathlib import Path
from dotenv import load_dotenv
ROOT_DIR = Path(__file__).parent.parent
EXAMPLE_AGENT_DIR = ROOT_DIR / "example_agents"
# Agent directories
ACME_R2D2_AGENT_DIR = EXAMPLE_AGENT_DIR / "acme_r2d2"
ACME_DQN_AGENT_DIR = EXAMPLE_AGENT_DIR / "acme_dqn... |
import math
class Quat:
def __init__(self, *args, **kwargs):
if len(args) == 0:
if all(k in kwargs.keys() for k in "wxyz"):
self.q = [kwargs['x'], kwargs['y'], kwargs['z'], kwargs['w']]
elif len(kwargs)==0:
self.q = [0, 0, 0, 1]
elif len(args)... |
#from sklearn.datasets import load_digits
import os
import json
# Dirty, but it needs to load all models
from sklearn import *
from sklearn.externals import joblib
import sklearn
import argparse
import functools
import numpy as np
import logging
class Scikitjson:
def __init__(self):
self.jsonmodel = Non... |
import torch
import torch.nn as nn
import torch.nn.functional as F
'''
modules
'''
class EqualizedLR(nn.Module):
'''
equalized learning rate
'''
def __init__(self, layer, gain=2):
super(EqualizedLR, self).__init__()
self.wscale = (gain / layer.weight[0].numel()) ** 0.5
self.l... |
#
# @lc app=leetcode id=473 lang=python3
#
# [473] Matchsticks to Square
#
# @lc code=start
class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
matchsticks.sort(reverse = True)
sumLen = 0
for i in matchsticks: sumLen += i
if sumLen % 4 != 0:
return Fals... |
from server_delta_app import view_sets, models, serializers, services
from rest_framework import viewsets as viewsets_rest_framework, mixins
from rest_framework.permissions import AllowAny
from server_delta_app import services
from django.http import HttpResponse
class CustomerDossierViewSet(view_sets.BaseViewSet):
... |
#!/usr/bin/env python
import sys
from contextlib import closing
import lxml.html as html # pip install 'lxml>=2.3.1'
from lxml.html.clean import Cleaner
from selenium.webdriver import Firefox # pip install selenium
from werkzeug.contrib.cache import FileSystemCache # pip install werkzeug
url = sys.... |
import xlrd
from collections import Counter
def removeDashes(arr):
'''
Some 0 values appear as '--' in excel
Return:
- list with '--' replaced by 0.0
'''
for idx, item in enumerate(arr):
if item == '--':
arr[idx] = 0.0
return arr
def containsNegative(arr):
'''Preprocessing data step
Check if features ... |
#
# Copyright (c) 2017 Louie Lu. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
from .. import gate
from ..bitarray import BitArray
def And(a: bool, b: bool) -> bool:
return gate.Not(gate.Nand(a, b))
def And16(a: BitArray, b: BitArra... |
import json
import discord
import textwrap
import asyncio
#from .cogs.utils.utils import Utils
from .AudioNode import AudioNode
from .AudioPlayer import AudioPlayer
from .Events import TrackStart
class AudioManager:
"""
Class of the AudioManager section.
This is main class and controls all stuff like joini... |
import json
import os
from api import get_location_top_players
def get_country_top_players(country):
response = get_location_top_players(country['id'])
return {
country['name']: [player['tag'].replace('#', '%') for player in response['items']]
}
def get_global_top_players_api():
try:
... |
import torch
import torch.nn.functional as F
from agent.td3 import TD3
class TD3MT(TD3):
def __init__(self,
state_dim,
action_dim,
max_action,
num_env,
discount=0.99,
tau=0.005,
policy_noise=0.2... |
#!/usr/bin/env python3
# Copyright 2020 Google 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 or... |
from django.db import models
# Create your models here.
class Evaluation(models.Model):
comment = models.TextField()
score = models.IntegerField()
class Meta:
abstract = True
class StoreEveluation(Evaluation):
evaluation = models.ForeignKey('stores.Store', related_name = 'store_eveluations', ... |
from flopz.arch.register import Register
import enum
class VleRegisterType(enum.IntEnum):
# see E200Z0.pdf
GENERAL_PURPOSE = 0
EXCEPTION_HANDLING_AND_CONTROL = 1
PROCESSOR_CONTROL = 2
DEBUG = 3
MEMORY_MANAGEMENT = 4
CACHE = 5
class VleGpRegister(Register):
def __init__(self, name: st... |
from solutions import input_list # you can adjust the file name from solutions(.py) to something else
import unittest
import random
class TestInputList(unittest.TestCase):
def test_simple_one_digit(self):
input_string = "1,2,3,4,5"
delimiter = ","
actual = input_list(input_string, delimit... |
from flask import Flask, render_template, flash, request, session,redirect
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
from werkzeug.utils import secure_filename
import time
import os
import json
json_path = os.path.join(os.path.dirname("./"), 'webapp.json')
json_path_setti... |
from . import client as raw
from .sorting import sort_by_name
from .cache import cache
from .helpers import normalize_model_parameter
from .shot import get_sequence
default = raw.default_client
def new_scene(project, sequence, name, client=default):
"""
Create a scene for given sequence.
"""
project... |
from .core import *
from . import heroku
from . import local
|
# Uncomment the next two lines if you want to save the animation
#import matplotlib
#matplotlib.use("Agg")
import numpy
from matplotlib.pylab import *
from mpl_toolkits.axes_grid1 import host_subplot
import matplotlib.animation as animation
from matplotlib import style
import time
import random
from datetime import... |
import unittest
from app.data_model.answer_store import Answer, AnswerStore
from app.helpers.schema_helper import SchemaHelper
from app.questionnaire.path_finder import PathFinder
from app.schema_loader.schema_loader import load_schema_file
class TestConfirmationPage(unittest.TestCase):
def test_get_next_locati... |
# vim: set encoding=utf-8
# Copyright (c) 2016 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... |
# Generated by Django 2.2.5 on 2020-07-18 11:19
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Language',
fields=[
('id', models.AutoField... |
# -*- coding: utf-8 -*-
from stix_shifter_utils.stix_translation.src.utils.transformers import ValueTransformer
from stix_shifter_utils.utils import logger
LOGGER = logger.set_logger(__name__)
WINDOWS_KEY_MAPPING = {
"HKCC": "HKEY_CURRENT_CONFIG",
"HKCR": "HKEY_CLASSES_ROOT",
"HKCU": "HKEY_CURRENT_USER",
... |
import matplotlib.pyplot as plt
import re
import json
infile = open("out.txt", "r")
values = infile.read()
infile.close()
popCount = []
happiness = []
crimes = []
gunCrimes = []
avgConnectedness = []
gunPossession = []
values = map(lambda x: x.split(", "), values[2:-2].split("), ("))
for val in values:
popCount.appe... |
# Crie um programa que leia as notas do ano letivo de um aluno e faça a média entre elas.
n = float(input('\033[31mNota do 1° bimestre: \033[m'))
q = float(input('\033[32mNota do 2° bimestre: \033[m'))
r = float(input('\033[36mNota do 3° bimestre: \033[m'))
s = float(input('\033[34mNota do 4° bimestre: \033[m'))
res = ... |
"""
Author: Andreas Finkler
Created: 23.12.2020
"""
|
#region Imports
from Base.EnforceTypes import EnforceTypes;
from Base.ValidParameters import ValidSportsBooks, ValidSports;
from Base.CustomExceptions import SportError;
#endregion Imports
class RequestBase:
@classmethod
def GetArgString(cls):
#Get the list of attributes of the given subclass
... |
from collections import deque
def solve(number):
pumps = deque()
for _ in range(number):
fuel, distance = input().split()
fuel = int(fuel)
distance = int(distance)
pumps.append([fuel, distance])
for i in range(number):
is_success = True
total_fuel = 0
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.