content stringlengths 5 1.05M |
|---|
# Ian McLoughlin
# A program that displays Fibonacci numbers using people's names.
# Modified by Emma Patton 2018-02-04
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i = j
i, j = j, i + j
n = n - 1
return i
name = "Patton"
first = nam... |
from django.contrib import admin
from favorites.models import *
# Register your models here.
@admin.register(WishList)
class WishList(admin.ModelAdmin):
list_display = ('user',"product",'created_at')
list_filter = ('user',"product")
search_fields = ('user',"product") |
import unittest
from rexmex.dataset import DatasetReader
from rexmex.metricset import ClassificationMetricSet, CoverageMetricSet, RatingMetricSet
from rexmex.scorecard import CoverageScoreCard, ScoreCard
class TestMetricAggregation(unittest.TestCase):
def setUp(self):
reader = DatasetReader()
sel... |
import uuid
import os
import requests
import logging
import zipfile
from obs.libs import gmt
from obs.libs import utils
from obs.libs import auth as auth_lib
def buckets(resource):
"""Return all available buckets object."""
all_buckets = []
for bucket in resource.buckets.all():
all_buckets.append... |
from unittest import TestCase
from src.prediction_format import validate_content, ValidationError
class TestPredictionFormatValidateContent(TestCase):
def test_ok(self):
content = b"""position,symbol
0.2,ETH
0.3,XRP
0.1,BTC"""
validate_content(content)
def test_decode_error(self):
con... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Runs a daemon to update git credentials from the GCE metadata server.
Only works inside a GCE with proper service accounts tagged.
Example invocation:
./... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
def run():
print("\033[0;30;47m ###### Ahora has decidido cambiar de aires...")
time.sleep(2)
print("\033[0;31;47m ###### Porque levantar una empresa de cero ya lo has tachado...")
time.sleep(2)
print("\033[0;33;47m ###... |
# Copyright 2016 The TensorFlow Authors. 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.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
"""Test for views of users' app."""
import jwt
from django.test import TestCase
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from rest_framework import status
from rest_framework.test import APIClient
from rest_framework_jwt.settings import api_settings
from main.settings... |
from .routes import get_group_children, get_group_by_name, get_all_groups, create_group
|
from __future__ import annotations
from typing import Any
from clovars.bio import Well
class WellLoader:
"""Class responsible for validating and creating the Well in the Simulation."""
default_well_radius = 1.0
def __init__(
self,
well_settings: dict[str, Any],
) -> None:
... |
import sys, os
import glob
sys.path.append(os.path.join(os.getenv('XChemExplorer_DIR'),'lib'))
import XChemDB
def parse_autofit_folder(sampleDir,compoundID):
filenames = ['best.pdb','ligand_fit_1.pdb']
pdbList = []
for files in glob.glob(os.path.join(sampleDir,'autofit_ligand',compoundID+'_*','*'... |
from flask import render_template
import pyexcel
import os
import ruamel.yaml as yaml
import json
from pathlib import Path
import csv
from . import app
@app.route('/')
def open_file():
filename_path = Path(os.environ.get('FILENAME', 'simplecel.xlsx'))
if filename_path.exists():
if filename_path.suff... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('wishlist', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Item',
fields=[
... |
import sys
import os
import logging
from logging import StreamHandler
import shutil
import json
run_directory = os.environ['RAFT_TOOL_RUN_DIRECTORY']
raft_libs_dir = os.path.join(run_directory, '..', '..', 'libs', 'python3')
sys.path.append(raft_libs_dir)
import raft
zap_dir = '/zap'
sys.path.append(zap_dir)
raftUti... |
class _DropdownItem():
@classmethod
def _create(cls):
return cls()
def __init__(self):
super(_DropdownItem, self).__init__()
self._name = ""
self._close_on_selected = True
self._selected = False
def _copy_values_deep(self, other):
self._name = other._na... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Copyright (c) Merchise Autrement [~º/~] and Contributors
# All rights reserved.
#
# This is free software; you can do what the LICENCE file allows you to.
#
from datetime import timedelta
from odoo.fi... |
# IMPORTATION STANDARD
# IMPORTATION THIRDPARTY
import pytest
# IMPORTATION INTERNAL
from openbb_terminal.stocks.dark_pool_shorts import quandl_model
@pytest.fixture(scope="module")
def vcr_config():
return {
"filter_headers": [("x-api-token", "MOCK_API_TOKEN")],
}
@pytest.mark.vcr
@pytest.mark.pa... |
import datetime
import functools
import json
import logging
import os
import shutil
import conbench.runner
import pyarrow
from benchmarks import _sources
logging.basicConfig(format="%(levelname)s: %(message)s")
def _now_formatted():
now = datetime.datetime.now(datetime.timezone.utc)
return now.isoformat()... |
from datetime import datetime, timedelta
import eisoil.core.pluginmanager as pm
import eisoil.core.log
logger=eisoil.core.log.getLogger('dhcpresourcemanager')
from ip import IP
from dhcpexceptions import *
worker = pm.getService('worker')
Schedule = pm.getService('schedule')
sex = pm.getService('scheduleexceptions')... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
import datetime
from floodsystem.stationdata import build_station_list
from floodsystem.stationdata import update_water_levels
from floodsystem.flood import stations_level_over_threshold
from floodsystem.plot import plot_water_levels
from floodsystem.datafetcher import fetch_measure_levels
def task2E():
stations =... |
"""
Decline Curve Models
Copyright © 2020 David S. Fulford
Author
------
David S. Fulford
Derrick W. Turk
Notes
-----
Created on August 5, 2019
"""
from math import exp, log, log1p, ceil as ceiling, floor
import warnings
import dataclasses as dc
from dataclasses import dataclass
from numpy import ndarray
import nu... |
'''
This file provides modules to do the conversion between Euler angles and Vectors on AFW & AFLW & BIWI datasets
It also include some util functions for visualization
Author: Zhiwen Cao
Version: V1.0
Last Update: Mar-05-2020
'''
import numpy as np
from scipy.optimize import minimize
import math
i... |
# -*- coding: utf-8 -*-
from tccli.services.tdcpg.tdcpg_client import action_caller
|
# -*- coding: utf-8 -*-
import os
import unittest
from flask import Flask
from coaster.utils import buid
from coaster.sqlalchemy import BaseMixin
from nodular.db import db
class User(BaseMixin, db.Model):
__tablename__ = 'user'
userid = db.Column(db.Unicode(22), nullable=False, default=buid, unique=True)
... |
import logging
# -- Rename this file to config.py! --
import os
## -- Main
# Enter discord token from https://discordapp.com/developers/applications/me/
# expected format: `token = 'supersecrettoken'`
token = os.environ['DISCORD_TOKEN']
# reacts to pastebin posts with pob info in these channels
active_channels = [... |
from opnsense_cli.facades.commands.plugin.haproxy.base import HaproxyFacade
from opnsense_cli.api.plugin.haproxy import Settings, Service
class HaproxyServerFacade(HaproxyFacade):
jsonpath_base = '$.haproxy.servers.server'
uuid_resolver_map = {
'linkedResolver': {'template': '$.haproxy.resolvers.resol... |
import paramiko
import pathlib
import glob
import termcolor
# Const variables for makes config file
DHCP = 'dhcp'
STATIC = 'static'
DEFAULT_IP_PLC = '192.168.1.10'
DEFAULT_IP = ('192.168.2.1', '192.168.1.1', '10.0.0.1')
DEFAULT_NETWORK = ('192.168.2.0', '192.168.1.0', '10.0.0.0')
DEFAULT_NETMASK = '255.255.255.0'
DHCP... |
"""
These are plotting functions that take either :py:class:`~uravu.relationship.Relationship` or :py:class:`~uravu.distribution.Distribution` class objects.
The aim is to produce *publication quality* plots. However, we recognise that taste exists, and ours may be different from yours. The colorscheme in this work wa... |
# -*- coding: utf-8 -*-
"""
obspy.io.zmap - ZMAP read and write support for ObsPy
=====================================================
This module provides read and write support for the ZMAP format.
:copyright:
The ObsPy Development Team (devs@obspy.org)
:license:
GNU Lesser General Public License, Version ... |
try:
from . import _broker
except ImportError:
import _broker
import broker
class Event(_broker.zeek.Event):
def __init__(self, *args):
if len(args) == 1 and not isinstance(args[0], str):
# Parse raw broker message as event.
_broker.zeek.Event.__init__(self, broker.Data.fr... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015-2018 by Exopy Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# ---------------... |
from click.testing import CliRunner
from onegov.people.cli import cli
from onegov.people.models import Person
from pathlib import Path
from transaction import commit
def test_cli(cfg_path, session_manager, temporary_directory):
runner = CliRunner()
# Clear
result = runner.invoke(cli, [
'--config'... |
#Create a function that takes a string and returns that string with the first half lowercased and the last half uppercased.
def sillycase(silly):
mid = (len(silly)+1) // 2 #add 1 to make divisible midpoint
return silly[:mid].lower() + silly[mid:].upper() |
from django.contrib.auth.models import Group
from ecs.utils.testcases import EcsTestCase
from ecs.tasks.models import TaskType, Task
from ecs.users.utils import create_user
class AuthorizationTest(EcsTestCase):
'''Test for the tasks module
Tests for user authorizations and task assignment.
'''
... |
import dataclasses
from typing import TYPE_CHECKING, Final, List, Optional
from django.conf import settings
__all__ = [
"NAMESPACE",
"Config",
"config",
]
NAMESPACE: Final = "STRAWBERRY_DJANGO"
@dataclasses.dataclass
class Config:
"""Settings for this extension.
The configs here are expected t... |
class Const(object):
guard_from_loop = False
class ConstError(Exception):
pass
def __setattr__(self, name, value):
if self.guard_from_loop:
self.guard_from_loop = False
return
if hasattr(self, name):
err = f"Can't rebind const variable: {name}"
... |
"""
This is really not a logging facility. For the CLI we only require a nice color
output on some interactions. Full logging is not needed.
"""
import sys
from ceph_installer.cli import util
def error(message):
line = "%s %s\n" % (util.red_arrow, message)
line = line.encode("utf-8")
sys.stderr.write(line... |
import math
from functools import partial
import torch
import torch.nn.functional as F
import numpy as np
from torch.autograd import Variable
from baseline.utils import Offsets, exporter
from eight_mile.pytorch.layers import repeat_batch, gnmt_length_penalty, BeamSearchBase, rnn_cell, WeightTieDense
from baseline.pytor... |
import sys
import vi.app.nonogram
import vi.csp
import vi.graph
import vi.search.graph
import vi.search.gac
with open(sys.argv[1], 'r') as f:
problem, dimensions = vi.app.nonogram.build_problem(f.read())
search = vi.search.graph.BestFirst(problem, vi.search.graph.BestFirst.Strategy.astar)
while not search.is_co... |
from sanic import response
def health(request):
return response.text('', status=200)
|
#!/usr/bin/env python
from nose.tools import *
from nose import SkipTest
import networkx
from nose.plugins.attrib import attr
from networkx import edge_current_flow_betweenness_centrality \
as edge_current_flow
from networkx import edge_current_flow_betweenness_centrality_subset \
as edge_current_flow_subset
... |
import cv2
import os
import torch
import model_
import numpy as np
import matplotlib.pyplot as plt
import torchvision.models
from utils import get_best_weight
from torch import nn
from torchvision import models, transforms
from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
from pytorch_grad_cam imp... |
from telethon import events
from __main__ import client
from constants import CMD_PREFIX
@client.on(events.NewMessage(outgoing=True, pattern=CMD_PREFIX + "abot"))
async def repo(event):
about_bot = f"""
**This userbot updates the biography of a telegram user according to their current spotify playback.**
**Update ... |
import torch
import torch.nn.functional as F
from DeepFaceRecognitron import MARGIN
class ContrastiveLoss(torch.nn.Module):
def __init__(self):
super(ContrastiveLoss, self).__init__()
self.margin = MARGIN
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
de... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'wood_detection.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_dialog(object):
def setupUi(self, dialog):
dialog.set... |
import pytest
from typedpy import ImmutableStructure, Integer, Map, Serializer, Structure, mappers, Pick
def build_default_dict():
return {"abc": 0}
class Blah(Structure):
i: int
d: Map[str, int] = build_default_dict
a: str
class Foo(Blah, ImmutableStructure):
s: set
b: Integer
_seri... |
# TODO test decorator
|
import json
import sys
import os
sys.path.append(os.path.abspath("."))
from Client import Client
def main():
client = Client()
# 部署evidence合约:交易标识string,合约名称string,合约版本int,合约代码类型string
# trans = client.create_trans_deploy("", "evidence", 1, "scala")
# 调用evidence合约:交易标识string,合约名称string,合约版本int,合约方法stri... |
from setuptools import setup
setup(name='cpp_wrapper',
version='0.1',
packages=['cpp_wrapper'],
scripts=['create_project.py'])
|
# coding: utf-8
"""
KubeVirt API
This is KubeVirt API an add-on for Kubernetes.
OpenAPI spec version: 1.0.0
Contact: kubevirt-dev@googlegroups.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class V1Virtua... |
# pylint: disable=duplicate-code
"""
Floor plan example
==================
.. Copyright:
Copyright Wirepas Ltd 2019 licensed under Apache License, Version 2.0
See file LICENSE for full license details.
"""
from utils import get_settings, setup_log
from connections import Connections
from fi... |
"""Functions to plot M/EEG data e.g. topographies
"""
# Author: Alexandre Gramfort <gramfort@nmr.mgh.harvard.edu>
#
# License: Simplified BSD
import numpy as np
import pylab as pl
from .fiff.pick import channel_type
def plot_topo(evoked, layout):
"""Plot 2D topographies
"""
ch_names = evoked.info['ch_n... |
#!/usr/bin/python3
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0, '/var/www/codexlab/')
sys.path.insert(1, '/var/www/codexlab/codexlab/')
from codexlab import app as application
application.secret_key = 'FHsWHwCb5dX9UJCUK1LPq8BSVnHKP6kA'
|
# Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# 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
... |
import os
from berglas import VERSION
CONTINUE_ON_ERROR = os.environ.get("BERGLAS_CONTINUE_ON_ERROR", "false").lower() == "true"
REFERENCE_PREFIX = "berglas://"
USER_AGENT = f"berglas/{VERSION} (https://github.com/maroux/berglas)"
METADATA_KMS_KEY = "berglas-kms-key"
|
from .entries import ResourceMapper
__all__ = ("LinksMapper",)
class LinksMapper(ResourceMapper):
ENDPOINT = "links"
@classmethod
def map_back(cls, doc: dict) -> dict:
"""Map properties from MongoDB to OPTiMaDe
:param doc: A resource object in MongoDB format
:type doc: dict
... |
# Las lineas que tienen el signo de gato son comentarios
# no pasa nada si los dejas o los eliminas!
# -----------------------------------
# Tienes que leer dos datos e imprimir algo
a = int(raw_input())
b = int(raw_input())
# Recuerda que puedes anidar condiciones con "and" "or"
if a == 1 and b == 1:
print"Despeg... |
import time
import webbrowser
totalBreaks = 3
print ("Break Time program has started on {}".format (time.ctime ()))
while totalBreaks > 0:
time.sleep (10)
webbrowser.open ("https://udacity.com/course/programming-foundations-with-python--ud036")
totalBreaks -= 1
|
"""
An example pikefile
"""
from functools import wraps
VARIABLE = "foo"
def do_thing(thing: str):
"""
Do a thing, and do it perfectly
:param thing: The thing to do
"""
print("Doing", thing)
def _private_task():
pass
def _task_wrapper(f):
@wraps(f)
def wrapper(*args, **kwargs):
... |
def write_file(filename, data, header):
with open(filename, 'r') as fr:
look_data = fr.read()
if look_data == "":
with open(filename, 'w') as fw:
fw.write('{header} \n{line}\n{data}'.format(
data=data,
line='='*12,
header=... |
#!/usr/bin/env python
##############################################################################
#
# xpdacq by Billinge Group
# Simon J. L. Billinge sb2896@columbia.edu
# (c) 2016 trustees of Columbia University in the City of
# New York.
# ... |
"""Extended core templates for the Lifecycle Management plugin."""
from abc import ABCMeta
from django.db.models import Q
from nautobot.extras.plugins import PluginTemplateExtension
from nautobot.dcim.models import InventoryItem
from .models import HardwareLCM
from .software import (
DeviceSoftware,
Inventory... |
# Docs and codes in python: https://www.askpython.com/
# Treasure Map
# Instructions
# You are going to write a program which will mark a spot with an X.
# In the starting code, you will find a variable called map.
# This map contains a nested list. When map is printed this is what the nested list looks like:
# ['... |
import justpy as jp
from .group import Group
class Row(Group):
def __init__(self):
'''Row Element
Provides a container which arranges its child in a row.
'''
view = jp.QDiv(classes='row items-start', style='gap: 1em', delete_flag=False)
super().__init__(view)
|
"""
This file should be your actual blueprint and can be a .ipynb, .js, whatever
"""
|
from sqlalchemy import Column, Integer, String
from Agent import Base, Session
class PlanApplicationAPI(Base):
"""description of class"""
__tablename__ = 'vw_planapplicationapis'
PlanId = Column(Integer, primary_key = True)
ApplicationName = Column(String, primary_key = True)
APIName = Colum... |
from flytekit.configuration import common as _config_common
GCS_PREFIX = _config_common.FlyteRequiredStringConfigurationEntry("gcp", "gcs_prefix")
GSUTIL_PARALLELISM = _config_common.FlyteBoolConfigurationEntry("gcp", "gsutil_parallelism", default=False)
|
import hashlib
from . import primitives
from . import exceptions
from . import mgf
from .defaults import default_crypto_random
def encrypt(public_key, message, label=b'', hash_class=hashlib.sha1,
mgf=mgf.mgf1, seed=None, rnd=default_crypto_random):
'''Encrypt a byte message using a RSA public key and... |
from django import forms
from .models import BookMaster, BlogPost
class BookForm(forms.ModelForm):
class Meta:
model = BookMaster
fields = [
"book_type",
"book_name",
"book_author",
"book_genre",
"book_year",
"book_publication... |
from setuptools import setup
setup(
name='pymeg',
version='0.0.1',
author='Jung Gyu Yoon',
author_email='yjg30737@gmail.com',
license='MIT',
packages=['pymeg'],
description='Python Mathematical Expression Generator',
url='https://github.com/yjg30737/pymeg.git'
) |
#This code shows Normalized Power Density(Energy/grid) on Cathode position
# it is normalized f(n, E)/grid
# this will not clip the cathode, rather draw a circle over the cathode
'''
Created on August 6, 2018
@author: Jyoti Biswas
Email:jbiswas@bnl.gov
'''
from matplotlib import cm
from matplotlib.colors ... |
import json
def analyze_all_searches(targets):
result = {}
for target_name, target in targets.items():
result[target_name] = {}
for entity_name, entity in target.items():
homologs_file = entity["homologs"]
homologs = json.load(open(homologs_file))
... |
import unittest
from tests import get_config_for_test
from binascii import Error
import client_encryption.session_key_params as to_test
from client_encryption.field_level_encryption_config import FieldLevelEncryptionConfig
from client_encryption.encryption_exception import KeyWrappingError
class SessionKeyParamsTest(... |
from abc import abstractmethod, ABC
from typing import Tuple, Sequence, List, Text, Callable, Union, Optional, Dict, NamedTuple, Type
import gin
import pysc2.lib.actions
import sonnet as snt
import tensorflow as tf
from sc2_imitation_learning.agents.common.spatial_decoder import SpatialDecoder
from sc2_imitation_lear... |
# Code generated by `typeddictgen`. DO NOT EDIT.
"""CoreV1EventSeriesDict generated type."""
import datetime
from typing import TypedDict
CoreV1EventSeriesDict = TypedDict(
"CoreV1EventSeriesDict",
{
"count": int,
"lastObservedTime": datetime.datetime,
},
total=False,
)
|
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
row = [set() for _ in range(9)]
col = [set() for _ in range(9)]
grid = [set() for _ in range(9)]
for i in range(9):
for j in range(9):
e = board[i][j]
if e == '.': c... |
#!/bin/python3
#initialize and scan for cards
# 1 Addr x XOR
#always use bcast addr
def setup(ser):
print("Setup: Emptying card buffers")
readanddiscard(ser)
command=1
addr=1
data =0
xor=command^addr^data
toSend= bytes([command, addr, data, xor])
ser.write(toSend)
return parseSetu... |
import os
from django.http import Http404
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.decorators import permission_required
from codereview.dashboard.models import Repository
from codereview.browser import vcs
def _repo(request, name):
try:
... |
import sys
import numpy as np
def character_to_index(c: str) -> int:
index = ord(c) - 97
if -1 < index < 26:
index = index
else:
index = 26
return index
def parse_file(filename: str) -> list:
results = [[0 for i in range(27)] for j in range(27)]
with open(filename) as f:
... |
"""Automatic calibration by associating peaks with energies."""
from itertools import combinations
import matplotlib.pyplot as plt
import numpy as np
from .peakfinder import PeakFinder
from .calibration import Calibration
MAJOR_BACKGROUND_LINES = [
1460.82,
2614.51,
1620.50,
911.20,
338.32,
2... |
def log(func):
print('loged')
return func()
@log()
def now():
print('now') |
import logging
import traceback
from collections import defaultdict
from consts.event_type import EventType
class EventInsightsHelper(object):
@classmethod
def calculate_event_insights(cls, matches, year):
INSIGHTS_MAP = {
2016: cls.calculate_event_insights_2016,
2017: cls.cal... |
"""
Problem 4 (Optional, 15%)
Description:
Write a class named “Cat” that can perform the following actions:
.name: print out capitalized name
.meow(): return the string: “(=^.^=) meow!”
print(): when print object, print out the string: “My name is [name], I am a cat.”
Example:
x = Cat(name=”t... |
import ot_file
# Several tests will use selawk.ttf, SourceHanSans-Regular.TTC
selawk_path = r"TestData\selawk.ttf"
sourceHansSans_path = r"TestData\SourceHanSans-Regular.TTC"
bungeeColor_path = r"TestData\BungeeColor-Regular_colr_Windows.ttf"
notoHW_COLR1_rev2_path = r"TestData\noto-handwriting-colr_1_rev2.ttf"
_a... |
# https://www.geeksforgeeks.org/python-build-a-rest-api-using-flask/
# https://stackoverflow.com/questions/48095713/accepting-multiple-parameters-in-flask-restful-add-resource
# using flask_restful
from flask import Flask, jsonify
from flask_restful import Resource, Api
import threading
import time
import socket
import... |
# robot.py 15/01/2021 D.J.Whale
# Simple simulation of a robot - replace with your own robot routines.
import turtle
# import thread
class VisualRobot():
STOP = "s"
FORWARD = "f"
BACKWARD = "b"
BOUNCE = 10
def __init__(self):
turtle.forward(0) # cause turtle canvas to display
... |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import traceback, logging, json
from typing import Tuple, List
import azlmbr.bus
from scene_api import scene_d... |
# from gensim.models.fasttext import FastText as FT_gensim
# from gensim.test.utils import datapath
from ..embeddings.base import Embeddings
from gensim.models.fasttext import load_facebook_vectors
import os
class FastTextEmbeddings(Embeddings):
def __init__(self, model_path, *args, **kwargs):
super(... |
#!/usr/bin/python
import sn
import os
import sys,string
import numpy as np
import math
try:
outfilename = sys.argv[1]
except:
print "Usage:",sys.argv[0], "dir_files_input outfile"; sys.exit(1)
def creat_map(output_file="output.map"):
"""Create the .map file"""
input_file=raw_input("\n-------fol... |
import argparse
import matplotlib.pyplot as plt
import numpy as np
from scipy.fftpack import fft
parser = argparse.ArgumentParser(description='Plot FFT transform of data file at path.')
parser.add_argument('data_path', help='data path (ex: /Dug/data/noise/1.txt')
args = parser.parse_args()
# Load data
stimulus_data ... |
import numpy as np
import scipy
import matcompat
# if available import pylab (from matlibplot)
try:
import matplotlib.pylab as plt
except ImportError:
pass
def prony(h, nb, na):
# Local Variables: a, c, b, h1, h, nb, H1, M, N, H2, H, na, H2_minus, K
# Function calls: max, length, prony, zeros, toepl... |
class Matrix:
def __init__(self, size, values=None):
self.size = size
if values == None:
self.a = []
for y in range(size):
self.a.append([])
for x in range(size):
self.a[y].append(0)
else:
self.a = [list(... |
import numpy as np
import pandas as pd
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
from .base import PlotView
MAX_DURATION = 60
class DurationPlot(PlotView):
def data(self):
pdf = pd.DataFrame()
pdf["duration"] = self.df["time_end"] - self.df["time_start"]
... |
# -*- coding: utf-8 -*-
l = int(input())
p = 1
n = 1
while l >= 2:
l /= 2
p = 4**n
n += 1
print(p) |
from django.shortcuts import render_to_response, render
from django.http import HttpResponse
import sys, os
# Create your views here.
def Guide(request):
locations = [
{'name':'Linkedinyou','slurl':'Linkedinyou','text':'Red\'s BBQ & Bait Shop'},
{'name':'OGP Island','slurl':'Linkedinyou Isle','text':'Lindens ... |
"""Auto-generated file, do not edit by hand. CN metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_CN = PhoneMetadata(id='CN', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='[19]\\d\\d(?:\\d{2,3})?', possible_leng... |
from nornir.core.exceptions import CommandError
from nornir.core.task import Result, Task
from paramiko.agent import AgentRequestHandler
def remote_command(task: Task, command: str) -> Result:
"""
Executes a command remotely on the host
Arguments:
command (``str``): command to execute
Retur... |
from django.forms import ModelForm
from coolbeans.app.models.question import MultipleChoiceModel, WordMatchingModel, WordScrambleQuestionModel, GapFillQuestionModel
from coolbeans.app.models.quiz import QuizModel
class MCForm(ModelForm):
"""
Multiple Choice Question Form made from the model
"""
class M... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.