content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import math
import random
def print_n_whitespaces(n: int):
print(" " * n, end="")
def print_n_newlines(n: int):
for _ in range(n):
print()
def subroutine_1610():
B = 3 / A * random.random()
if B < 0.37:
C = 0.5
elif B < 0.5:
C = 0.4
elif B < 0.63:
C = 0.3
... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created by Chouayakh Mahdi
25/06/2010
The package contains functions to analyse all sentence of a utterance
Functions: ... | python |
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param head ListNode类
# @param k int整型
# @return ListNode类
#
class Solution:
def reverseKGroup(self , head , k ):
def reverse(a,b):
pre = None
cur = a
while cur != b... | python |
from .bignet import BigHouseModel
from .goal import BigGoalHouseModel, AuxiliaryBigGoalHouseModel | python |
from modules import util
from modules.util import Failed
logger = util.logger
builders = ["stevenlu_popular"]
base_url = "https://s3.amazonaws.com/popular-movies/movies.json"
class StevenLu:
def __init__(self, config):
self.config = config
def get_stevenlu_ids(self, method):
if method == "st... | python |
# used as reference version, for comparison/correctness
import numpy as np
from timecheck import inittime, timecheck
from neoncl.util import math_helper
def calcU(W):
Ci = W.shape[0]
kH = W.shape[1]
kW = W.shape[2]
Co = W.shape[3]
G = np.array([[1/4,0,0],
[-1/6,-1/6,-1/6],
[-1/6,... | python |
from nose.tools import eq_
from amo.tests import app_factory
class DynamicBoolFieldsTestMixin():
def setUp(self):
"""
Create an instance of the DynamicBoolFields model and call super
on the inheriting setUp.
(e.g. RatingDescriptors.objects.create(addon=self.app))
"""
... | python |
import sys, json, os
BOARD_ID='Os1ByyJc'
def read_auth_info():
script_path = os.path.dirname(os.path.realpath(__file__))
auth_file = script_path + "/trello-auth.json"
if not os.path.exists(auth_file):
sys.stderr.write("Cannot access Trello: Missing {}\n".format(auth_file))
sys.exit(1)
with open(auth_f... | python |
import os
'''
user = os.environ['POSTGRES_USER']
password = os.environ['POSTGRES_PASSWORD']
host = os.environ['POSTGRES_HOST']
database = os.environ['POSTGRES_DB']
port = os.environ['POSTGRES_PORT']
'''
user = 'test'
password = 'password'
host = 'localhost'
database = 'example'
port = '5432'
DATABASE_CONNECTION_URI =... | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import collections
from collections import OrderedDict
from datetime import timedelta
from itertools import chain
import datetime
from django.urls import reverse
from django.template.loader import render_to_st... | python |
from collections import namedtuple
import contextlib
import meshcat
import meshcat.geometry as meshcat_geom
import meshcat.transformations as meshcat_tf
import matplotlib.pyplot as plt
import logging
import numpy as np
import networkx as nx
import os
import yaml
import torch
import pydrake
from pydrake.common.cpp_para... | python |
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class TestModel(models.Model):
field1 = models.CharField(max_length=255)
field2 = models.IntegerField()
def __str__(self):
return '%s%d' % (self.field1, self.field2)
@python_2... | python |
# -*- coding: utf-8 -*-
import torch.nn as nn
import torchvision
def densenet(n_classes, pretrained=False, n_layers=121, **kwargs):
'''
Creates a DenseNet based on the parameters
Arguments:
n_layers: The number of hidden layers
n_classes: The number of classes/labels
pretrained: Bo... | python |
#hwIo.py
#A part of NonVisual Desktop Access (NVDA)
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
#Copyright (C) 2015-2018 NV Access Limited, Babbage B.V.
"""Raw input/output for braille displays via serial and HID.
See the L{Serial} and L{Hid} classes.
Braille displa... | python |
from finta import TA
import scipy as sp
from scipy.signal import argrelextrema
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import yfinance as yf
from collections import defaultdict
class Loss(object):
def __init__(self,method, sup, res):
self.method = method
self.sup = sup
sel... | python |
# This file is Copyright (c) 2010 by the GPSD project
# BSD terms apply: see the file COPYING in the distribution root for details.
#
# Creates build/lib.linux-${arch}-${pyvers}/gpspacket.so,
# where ${arch} is an architecture and ${pyvers} is a Python version.
from distutils.core import setup, Extension
import os
im... | python |
"""
The :class:`Signature` object and associated functionality. This
provides a way to represent rich callable objects and type check
calls.
"""
from collections import defaultdict
from .error_code import ErrorCode
from .stacked_scopes import (
AndConstraint,
Composite,
Constraint,
ConstraintType,
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015-2016 Telefónica Investigación y Desarrollo, S.A.U
#
# This file is part of FIWARE project.
#
# 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 t... | python |
import math, statistics, random, time, sys
import numpy as np
import pandas as pd
import ray
import time
import holoviews as hv
from holoviews import opts
from holoviews.streams import Counter, Tap
from bokeh_util import square_circle_plot, two_lines_plot, means_stddevs_plot
hv.extension('bokeh')
from bokeh.layouts i... | python |
# coding: utf-8
"""
OrderCloud
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 1.0
Contact: ordercloud@four51.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Ve... | python |
import calendar
import datetime as dt
import time
DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S.000Z'
DATE_FORMAT = '%Y-%m-%dT00:00:00.000Z'
DPLUS_FORMAT = '%Y-%m-%dT00:01:00.000Z'
def valid_rfcformat(potential):
try:
dt.datetime.strptime(potential, DATETIME_FORMAT)
return True
except:
return F... | python |
"""Test the cli module."""
| python |
import asyncio, re, json
from smsgateway.sources.sms import command_list
from smsgateway.config import *
from smsgateway.sources.utils import *
from smsgateway import sink_sms
from telethon import TelegramClient, utils
from telethon.tl.types import Chat, User, Channel, \
PeerUser, PeerChat, PeerChannel, \
Me... | python |
from environs import Env
from lektor.pluginsystem import Plugin
__version__ = "18.6.12.3"
DEFAULT_PREFIX = "LEKTOR_"
class LektorEnv:
def __init__(self, config=None):
self.env = Env()
if not config:
self.prefix = DEFAULT_PREFIX
else:
self.prefix = config.get("env... | python |
import sys
from PyQt5.QtWidgets import *
from PyQt5.QAxContainer import *
from PyQt5.QtCore import *
import logging.handlers
import time
from pandas import DataFrame
is_64bits = sys.maxsize > 2**32
if is_64bits:
print('64bit 환경입니다.')
else:
print('32bit 환경입니다.')
formatter = logging.Formatter('[%(levelname)s|%(... | python |
#!/usr/bin/env python
# Copyright 2021 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 ... | python |
""" Copyright (c) 2017-2020 ABBYY Production 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 agreed to in wr... | python |
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
# Set default settings for celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'stratahq.settings')
app = Celery('strathq')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
@ap... | python |
from flask import session
import csv, pymssql, datetime
import threading
table_lock = threading.Lock()
def create_csv_rep(orgid, filename):
table_lock.acquire()
host = "197.189.232.50"
username = "FE-User"
password = "Fourier.01"
database = "PGAluminium"
conn = pymssql.connect(host... | python |
from granule_ingester.processors.EmptyTileFilter import EmptyTileFilter
from granule_ingester.processors.GenerateTileId import GenerateTileId
from granule_ingester.processors.TileProcessor import TileProcessor
from granule_ingester.processors.TileSummarizingProcessor import TileSummarizingProcessor
from granule_ingeste... | python |
import sys
input = sys.stdin.readline
# import accumulate takes too much memory
def accumulate(A):
n = len(A)
P = [0] * (n + 1)
for k in range(1, n + 1):
P[k] = P[k - 1] + A[k - 1]
return P
count = 0
length = 0
lower_bound = 0
cups, fill = map(int, input().split())
cuplist = [0] * (cups + 2)... | python |
import PyPDF2
pdf1File = open('meetingminutes.pdf', 'rb')
pdf2File = open('meetingminutes2.pdf', 'rb')
pdf1Reader = PyPDF2.PdfFileReader(pdf1File)
pdf2Reader = PyPDF2.PdfFileReader(pdf2File)
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdf1Reader.numPages):
pageObj = pdf1Reader.getPage(pageNum)
p... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on Nov 7, 2015
Don't blink...
@author: Juan_Insuasti
'''
import sys
import datetime
import os.path
import json
class Logger:
def __init__(self, logName="Log", file="log.txt", enabled=True, printConsole=True, saveFile=False, saveCloud=False):
self.... | python |
from setuptools import setup
# Load in babel support, if available.
try:
from babel.messages import frontend as babel
cmdclass = {"compile_catalog": babel.compile_catalog,
"extract_messages": babel.extract_messages,
"init_catalog": babel.init_catalog,
"update_cat... | python |
from typing import Union
from notion.models.annotations import Annotations
class RichText():
"""
https://developers.notion.com/reference/rich-text
"""
TYPES = ["text", "mention", "equation"]
def __init__(self, plain_text: str = None, href: str = None, annotations: Union[dict, Annotations] = Non... | python |
"""
Handles running extensions inside a sandbox, which runs outside the primary
Petronia memory space with OS specific constraints.
"""
from .module_loader import create_sandbox_module_loader
| python |
# -*- coding: utf-8 -*-
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# You can only use this computer program if you have closed
# a license agreement with MPG or you get the right to use the computer
# program from someone who is... | python |
from fastai.conv_learner import *
from fastai.dataset import *
from tensorboard_cb_old import *
import cv2
import pandas as pd
import numpy as np
import os
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score
import scipy.optimize as opt
import torch
import torch.nn as nn
import t... | python |
"""Reverse-engineered client for the LG SmartThinQ API.
"""
from .core import * # noqa
from .client import * # noqa
from .ac import * # noqa
from .dishwasher import * # noqa
from .dryer import * # noqa
from .refrigerator import * # noqa
from .washer import * # noqa
__version__ = '1.3.0'
| python |
# dic = {'key': 'value', 'key2': 'value2'}
import json
#
# ret = json.dumps(dic) # 序列化
# print(dic, type(dic))
# print(ret, type(ret))
#
# res = json.loads(ret) # 反序列化
# print(res, type(res))
# 问题1
# dic = {1: 'value', 2: 'value2'}
# ret = json.dumps(dic) # 序列化
# print(dic, type(dic))
# print(ret, type(ret))
#
# r... | python |
__author__ = 'xubinggui'
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print(self.score)
bart = Student('Bart Simpson', 59)
bart.print_score() | python |
import unittest
from app.models import Pitch, User
from flask_login import current_user
from app import db
class TestPitch(unittest.TestCase):
def setUp(self):
self.user_joe = User(
username='jack', password='password', email='xyz@gmail.com')
self.new_pitch = Pitch(title="Test", pitch... | python |
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
from .unique_identifiable import CloudioUniqueIdentifiable
class CloudioObjectContainer(CloudioUniqueIdentifiable):
"""Interface to be implemented by all classes that can hold cloud.iO objects."""
__metaclass__ = ABCMeta
@abstractmethod
... | python |
import os, sys; sys.path.append(os.path.join("..", "..", ".."))
from pattern.en import parse, Text
# The easiest way to analyze the output of the parser is to create a Text.
# A Text is a "parse tree" of linked Python objects.
# A Text is essentially a list of Sentence objects.
# Each Sentence is a list of Word objec... | python |
import re
from enum import Enum
from operator import attrgetter
from re import RegexFlag
from typing import List, Union, Match, Dict, Optional
from annotation.models.models import Citation
from annotation.models.models_enums import CitationSource
from library.log_utils import report_message
from ontology.models import... | python |
import pprint
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/', methods=['POST'])
def hello_world():
content = request.get_json(silent=True)
pprint.pprint(content)
return content
| python |
#! /usr/bin/env python
from __future__ import print_function
import tensorflow as tf
import os, collections, sys, subprocess, io
from abc import abstractmethod
import numpy as np
def flattern(A):
'''
Flatten a list containing a combination of strings and lists.
Copied from https://stackoverflow.com/questions/1786... | python |
# -*- coding: utf-8 -*-
""" RandOm Convolutional KErnel Transform (ROCKET)
"""
__author__ = ["Matthew Middlehurst", "Oleksii Kachaiev"]
__all__ = ["ROCKETClassifier"]
import numpy as np
from joblib import delayed, Parallel
from sklearn.base import clone
from sklearn.ensemble._base import _set_random_states
from sklea... | python |
# Generated by Django 2.2.1 on 2019-05-29 20:37
import json
from django.db import migrations
def normalize_webhook_values(apps, schema_editor):
Channel = apps.get_model("api", "Channel")
for ch in Channel.objects.filter(kind="webhook").only("value"):
# The old format of url_down, url_up, post_data s... | python |
from easyidp.io.tests import test
import easyidp.io.metashape
import easyidp.io.pix4d
import easyidp.io.pcd | python |
#!/usr/bin/python
# (C) 2005 British Broadcasting Corporation and Kamaelia Contributors(1)
# All Rights Reserved.
#
# You may only modify and redistribute this under the terms of any of the
# following licenses(2): Mozilla Public License, V1.1, GNU General
# Public License, V2.0, GNU Lesser General Public Licens... | python |
import pytest
from channels.generic.websocket import (
AsyncJsonWebsocketConsumer, AsyncWebsocketConsumer, JsonWebsocketConsumer, WebsocketConsumer,
)
from channels.testing import WebsocketCommunicator
# @pytest.mark.asyncio
# async def test_websocket_consumer():
# """
# Tests that WebsocketConsumer is i... | python |
from PySide6.QtCore import QAbstractTableModel, Qt
class PandasModel(QAbstractTableModel):
def __init__(self, data):
super().__init__()
self._data = data
def rowCount(self, index):
return self._data.shape[0]
def columnCount(self, parnet=None):
return self._data.shape[1]
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2019 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
https://developer.cisco.com/docs/licenses
All use o... | python |
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import re
import logging
from rapidsms.apps.base import AppBase
from .models import Location
logger = logging.getLogger(__name__)
class App(AppBase):
PATTERN = re.compile(r"^(.+)\b(?:at)\b(.+?)$")
def __find_location(self, text):
try:
... | python |
class Weapon:
def __init__(self, name, damage, range):
self.name = name
self.damage = damage
self.range = range
def hit(self, actor, target):
if target.is_alive():
if (self.range >= (target.pos_x - actor.pos_x) +
(target.pos_y - actor.pos_y)):
... | python |
# flake8: noqa
#
# Root of the SAM package where we expose public classes & methods for other consumers of this SAM Translator to use.
# This is essentially our Public API
#
| python |
class Solution:
def trap(self, height: List[int]) -> int:
n = len(height)
if n<=2:return 0
stack = []
ans = 0
for i,num in enumerate(height):
while stack and height[stack[-1]]<num:
cur = stack.pop()
if stack:
ans... | python |
import random
def int_to_list(n):
n=str(n)
l=list(n)
return l
class CowsAndBulls:
def __init__(self):
self.number = ""
self.digits = 0
self.active = False
def makeRandom(self, digit):
digits = set(range(10))
first = random.randint(1, 9)
second_to_las... | python |
"""
Build a parse tree to evaluate a fully parenthesised mathematical expression, ((7+3)∗(5−2)) = ?
*
/ \
+ -
/ \ / \
... | python |
#! /usr/bin/env python
import re
import csv
import click
import numpy as np
from scipy.stats import spearmanr
from hivdbql import app
from hivdbql.utils import dbutils
from hivdbql.models.isolate import CRITERIA_SHORTCUTS
np.seterr(divide='raise', invalid='raise')
db = app.db
models = app.models
GENE2DRUGCLASS = {... | python |
""" Manages drawing of the game """
from typing import List, Tuple, Any
import colorsys
import random
import pygame
import settings
from game_state import GameState, Snake, Pizza
Color = Tuple[int, int, int]
class Colors:
""" Basic colors """
CLEAR_COLOR = (240, 240, 240)
BLACK = (0, 0, 0)
DARK_YELLO... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from re import findall
from string import printable
from struct import unpack
from src.capturePkt.networkProtocol import NetworkProtocol
class Telnet(NetworkProtocol):
IAC = 0xff
codeDict = {236: 'EOF',
237: 'SUSP',
238: 'ABORT',... | python |
#-*- coding: utf-8 -*-
'''
Created on 2017. 11. 06
Updated on 2017. 11. 06
'''
from __future__ import print_function
import os
import cgi
import re
import time
import codecs
import sys
import subprocess
import math
import dateutil.parser
from datetime import datetime
from commons import Subjects
from x... | python |
#!/usr/bin/env python3
#
# Copyright (c) 2018 Sébastien RAMAGE
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
#
import logging
import argparse
import time
from zigate import connect
logging.basicConfig(level=logging.INFO)
parser = argparse... | python |
import os
import sys
import argparse
from cuttsum.event import read_events_xml
from cuttsum.nuggets import read_nuggets_tsv
from cuttsum.util import gen_dates
import streamcorpus as sc
import numpy as np
from sklearn.feature_extraction import DictVectorizer
import codecs
def main():
event_file, rc_dir, event_title... | python |
# coding: utf-8
# 2020/1/3 @ tongshiwei
__all__ = ["get_net", "get_bp_loss"]
from mxnet import gluon
from .WCLSTM import WCLSTM
from .WCRLSTM import WCRLSTM
from .WRCLSTM import WRCLSTM
def get_net(model_type, class_num, embedding_dim, net_type="lstm", **kwargs):
if model_type == "wclstm":
return WCLST... | python |
"""LiteDRAM BankMachine (Rows/Columns management)."""
import math
from migen import *
from litex.soc.interconnect import stream
from litedram.common import *
from litedram.core.multiplexer import *
class _AddressSlicer:
def __init__(self, colbits, address_align):
self.colbits = colbits
self.ad... | python |
from django.contrib import admin
from mptt.admin import MPTTModelAdmin
from .models import Business, Category, Request
@admin.register(Business)
class BusinessAdmin(admin.ModelAdmin):
list_display = ('name', 'location', 'main_category')
ordering = ('name',)
filter_horizontal = ('other_categories', 'deliv... | python |
import uuid
from cinderclient import exceptions as cinder_exceptions
from ddt import ddt, data
from django.conf import settings
from django.test import override_settings
from novaclient import exceptions as nova_exceptions
from rest_framework import status, test
import mock
from six.moves import urllib
from waldur_op... | python |
##########################################################################
#
# Copyright (c) 2008-2010, Image Engine Design 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:
#
# * Redis... | python |
# -*- coding: utf-8 -*-
import codecs
import numpy as np
import tensorflow as tf
from Transformer.config.hyperparams import Hyperparams as pm
class Data_helper(object):
def __init__(self):
self.pointer = 0
def mini_batch(self):
X, Y = self.load_train_datasets()
num_batch ... | python |
import os
import glob
def delete_given_file(image_name):
file_name = image_name.split(".")[0]
IMG_PATH = "./annotated_dataset/img"
TXT_PATH = "./annotated_dataset/txt_label"
XML_PATH = "./annotated_dataset/xml_label"
img_file = f"{IMG_PATH}/{file_name}.jpg"
txt_file = f"{TXT_PATH}/{file_name... | python |
#!/usr/bin/env python
# Copyright (c) 2020 - for information on the respective copyright owner
# see the NOTICE file and/or the repository
# <https://github.com/boschresearch/amira-blender-rendering>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance w... | python |
"""
Transitions (Perturbation Kernels)
==================================
Perturbation strategies. The classes defined here transition the current
population to the next one. pyABC implements global and local transitions.
Proposals for the subsequent generation are generated from the current
generation density estimat... | python |
from test.ga.ga import GaTestCase
from test.ga.population import PopulationTestCase
from test.ga.individual import IndividualTestCase
__all__ = (
"GaTestCase", "PopulationTestCase",
"IndividualTestCase"
)
| python |
def get_key():
if isinstance(self.instance,
def clean():
pass
| python |
from screen.drawing.color import *
from screen.drawing.color import __all__ as _color__all__
from screen.drawing.colorinterpolationmethod import *
from screen.drawing.colorinterpolationmethod import __all__ as _colorinterpolationmethod__all__
from screen.drawing.style import *
from screen.drawing.style import __all__ a... | python |
from types import FunctionType
import backends
__storage = backends.default()
def set_storage(BackendInstance):
global __storage
__storage = BackendInstance
def make_cached(make_key, f):
def cached(*args, **kwargs):
cache_key = make_key(args=args, kwargs=kwargs)
if __storage... | python |
"""
Created on Wed Jan 15 11:17:10 2020
@author: mesch
"""
from colorama import init, Fore, Back
init(autoreset=True) #to convert termcolor to wins color
import copy
from pyqum.instrument.benchtop import RSA5 as MXA
from pyqum.instrument.benchtop import PSGA
from pyqum.instrument.modular import AWG
from pyqum.instrum... | python |
from datetime import datetime
import hashlib
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from markdown import markdown
import bleach
from flask import current_app, request, url_for
from flask_login import UserMixin, Ano... | python |
from typing import Any, Dict, Iterable, List
import pandas as pd
from fugue.dataframe import ArrayDataFrame
from fugue.exceptions import FugueInterfacelessError
from fugue.extensions.transformer import (
Transformer,
_to_transformer,
transformer,
register_transformer,
)
from pytest import raises
from t... | python |
from header_common import *
from header_dialogs import *
from header_operations import *
from module_constants import *
####################################################################################################################
# During a dialog, the dialog lines are scanned from top to bottom.
# If the dialo... | python |
#!/usr/bin/python
import sys
import h5py
if __name__ == "__main__":
files = sys.argv[1:]
files.extend(sys.stdin.readlines())
for file in files:
file = file.strip()
with h5py.File(file, 'r') as f:
f['/entry1/instrument/parameters/y_pixels_per_mm'][0] = 0.321
| python |
"""
Tests CoreML Scaler converter.
"""
import unittest
import numpy
import coremltools
from sklearn.preprocessing import StandardScaler
from onnxmltools.convert.coreml.convert import convert
from onnxmltools.utils import dump_data_and_model
class TestCoreMLScalerConverter(unittest.TestCase):
def test_scaler(self... | python |
total_bill = 124.56
procent_10 = 0.10
procent_12 = 0.12
procent_15 = 0.15
split_people = 7
tip = total_bill * procent_12 + total_bill
print(tip)
print(tip)
total = tip / float(split_people)
print(round(total, 2))
| python |
from guardian.core import ObjectPermissionChecker
class ObjectPermissionCheckerViewSetMixin:
"""add a ObjectPermissionChecker based on the accessing user to the serializer context."""
def get_serializer_context(self):
context = super().get_serializer_context()
if self.request:
per... | python |
# --------------------------------------------------------------------------
# Source file provided under Apache License, Version 2.0, January 2004,
# http://www.apache.org/licenses/
# (c) Copyright IBM Corp. 2015, 2016
# --------------------------------------------------------------------------
"""
This is a problem ... | python |
import os
from minicps.devices import PLC
from temperature_simulator import TemperatureSimulator
from Logger import hlog
import time
class EnipPLC1(PLC): #builds upon the tags of the swat example
# These constants are used mostly during setting up of topology
NAME = 'plc1'
IP = ' 10.0.2.110'
MAC = '... | python |
from setuptools import setup, find_packages
setup(name='donkeypart_keras_behavior_cloning',
version='0.1.3',
description='Library to control steering and throttle actuators.',
long_description="no long description given",
long_description_content_type="text/markdown",
url='https://github.... | python |
from trading_bot import app, create_app
def init_app():
# TODO add test config class
create_app()
def reset_managers():
create_app()
app.symbol_manager._symbols = []
app.exchange_manager._exchanges = []
app.exchange_manager._exchanges_by_name = {}
app.indicator_manager._indicators = []
... | python |
import cv2
import numpy as np
import math
import time
import testAAE
import testAAEWithClassifier
import region
def quantizeAngle(angle):
if angle >= 0:
if angle >= 90:
if angle >= 45:
quantized = 2
else:
quantized = 1
elif angle >= 135:
... | python |
def read_input():
# for puzzles where each input line is an object
with open('input.txt') as fh:
for line in fh.readlines():
if line.strip():
yield line.strip()
def read_input_objs():
# for puzzles with newline-separated objects as input
with open('input.txt') as fh... | python |
import PySimpleGUI as sg
use_custom_titlebar = False
def make_window(theme=None):
NAME_SIZE = 23
def name(name):
dots = NAME_SIZE - len(name) - 2
return sg.Text(
name + ' ' + '•' * dots,
size=(NAME_SIZE, 1),
justification='r',
pad=(0, 0),
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for :mod:`orion.algo.tpe`."""
import numpy
import pytest
from scipy.stats import norm
from orion.algo.space import Categorical, Fidelity, Integer, Real, Space
from orion.algo.tpe import (
TPE,
CategoricalSampler,
GMMSampler,
adaptive_parzen_estima... | python |
import pygame
import random
screen_size = [360, 600]
screen = pygame.display.set_mode(screen_size)
pygame.font.init()
background = pygame.image.load('background.png')
user = pygame.image.load('user.png')
chicken = pygame.image.load('chicken.png')
def display_score(score):
font = pygame.font.SysFont('Comic Sans ... | python |
from flask import request, jsonify, Blueprint
from flask_jwt_extended import (
create_access_token,
create_refresh_token,
jwt_refresh_token_required,
get_jwt_identity
)
from flasgger import swag_from
from myapi.models import User
from myapi.extensions import pwd_context, jwt
from myapi.api.doc.login_do... | python |
import psycopg2
import os
from dotenv import load_dotenv
import sqlite3
import pandas as pd
import datetime
from psycopg2.extras import execute_values
load_dotenv()
# connecting to our elephant sql rpg database
RPG_DB_NAME = os.getenv('RPG_DB_NAME', default='oops')
RPG_DB_USER = os.getenv('RPG_DB_USER', default='oop... | python |
import time
def time_training(fitter):
"""Print the time taken for a machine learning algorithm to train.
Parameters:
fitter(function): function used to train the model
Returns: None
"""
start = time.time()
fitter()
end = time.time()
diff = end - start
print(f'Traini... | python |
################################################################################
# Module: decision.py
# Description: Agent decision function templates
# Rafal Kucharski @ TU Delft, The Netherlands
################################################################################
from math import exp
import random
import... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.