content stringlengths 5 1.05M |
|---|
from flask import *
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.schema import Sequence
app = Flask(__name__, static_url_path='/static') #referencing this while
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///App.sqlite3'
app.config['SECRET_KEY'] = "secret key"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import scriptcontext as sc
import compas_rhino
from compas_ags.rhino import SettingsForm
from compas_ags.rhino import FormObject
from compas_ags.rhino import ForceObject
__commandname__ = "AGS_toolbar_displa... |
class DianpingConfig:
def __init__(self):
self.instance_name = "BERTModel.pt"
self.model_name = self.instance_name
self.BERT_MODEL = "bert-base-chinese"
self.max_sent_lens = 64
class SSTConfig:
def __init__(self):
self.instance_name = "BERTModel.pt"
self.model_na... |
from __future__ import unicode_literals
from djangobmf.apps import ContribTemplate
class EmployeeConfig(ContribTemplate):
name = 'djangobmf.contrib.employee'
label = "djangobmf_employee"
|
import eel
try:
from pyfirmata import Arduino, util
except:
from pip._internal import main as pipmain
pipmain(['install','pyfirmata'])
from pyfirmata import Arduino, util
#Get Operating System Type
import platform
currentOs = platform.system()
if "linux" in currentOs.lower():
curr... |
from sys import argv
script, filename=argv
print(f"We're going to erase{filename}.")
print("If you don't want that,hit CTRL-C(^C).")
print("If you do want that,hit RETURN.")
input("?")
print("Opening the file..")
target=open(filename,'w')
print("Truncating the file,Goodbye!")
target.truncate()
print("Now I'm goin... |
# =============================================================================== #
# #
# This file has been generated automatically!! Do not change this manually! #
# ... |
#MenuTitle: Check glyphsets match across open fonts
'''
Find missing glyphs across fonts
'''
def main():
fonts = Glyphs.fonts
glyphsets = {}
try:
for font in fonts:
if font.instances[0].name not in glyphsets:
glyphsets[font.instances[0].name] = set()
... |
initial = """\
.|||.#..|##.#||..#.|..|..||||..#|##.##..#...|.....
.|#.|#..##...|#.........#.#..#..|#.|#|##..#.#|..#.
#....#|.#|.###||..#.|...|.|.#........#.|.#.#|..#..
|..|#....|#|...#.#..||.#..||......#.........|....|
.|.|..#|...#.|.###.|...||.|.|..|...|#|.#..|.|..|.|
#.....||.#..|..|..||#.||#..|.||..||##.......#........ |
from group import GroupTestCases
from user import UserTestCases
from permission import PermissionTestCases
from core import *
|
'''
Defines the training step.
'''
import sys
sys.path.append('tfutils')
import tensorflow as tf
from tfutils.base import get_optimizer, get_learning_rate
import numpy as np
import cv2
from curiosity.interaction import models
import h5py
import json
class RawDepthDiscreteActionUpdater:
'''
Provides the training s... |
'''
Given an array of integers, there is a sliding window of size k which is moving from the left side of the array to the right, one element at a time. You can only interact with the k numbers in the window. Return an array consisting of the maximum value of each window of elements.
'''
def sliding_window_max(arr, k)... |
# terrascript/provider/chanzuckerberg/snowflake.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:27:17 UTC)
import terrascript
class snowflake(terrascript.Provider):
"""Terraform provider for managing Snowflake accounts"""
__description__ = "Terraform provider for managing Snowflake account... |
def move_tower(height, from_pole, middle_pole, to_pole):
if height >= 1:
move_tower(height-1, from_pole, to_pole, middle_pole)
print "move disk from {} to {}".format(from_pole, to_pole)
move_tower(height-1, middle_pole, from_pole, to_pole)
|
from getratings.models.ratings import Ratings
class NA_Karthus_Mid_Aatrox(Ratings):
pass
class NA_Karthus_Mid_Ahri(Ratings):
pass
class NA_Karthus_Mid_Akali(Ratings):
pass
class NA_Karthus_Mid_Alistar(Ratings):
pass
class NA_Karthus_Mid_Amumu(Ratings):
pass
class NA_Karthus_Mid_Anivia(Rating... |
# WARNING: you are on the master branch; please refer to examples on the branch corresponding to your `cortex version` (e.g. for version 0.24.*, run `git checkout -b 0.24` or switch to the `0.24` branch on GitHub)
import mlflow.sklearn
import numpy as np
class PythonPredictor:
def __init__(self, config, python_c... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""PyVoiceChanger."""
import sys
from datetime import datetime
from subprocess import call
from time import sleep
from PyQt5.QtCore import QProcess, Qt, QTimer
from PyQt5.QtGui import QColor, QCursor, QIcon
from PyQt5.QtWidgets import (QApplication, QDial, QGraphicsDropSh... |
from setuptools import setup
setup(
name='ctab',
version='0.1',
author='Thomas Hunger',
author_email='tehunger@gmail.com',
packages=[
'ctab',
]
)
|
""" Methods to setup the logging """
import os
import yaml
import platform
import logging
import coloredlogs
import logging.config
from funscript_editor.definitions import WINDOWS_LOG_CONFIG_FILE, LINUX_LOG_CONFIG_FILE
from funscript_editor.utils.config import SETTINGS
def create_log_directories(config: dict) -> No... |
#####################################################
# Read active and reactive power from the atm90e32 then
# store within mongodb.
#
# copyright Margaret Johnson, 2020.
# Please credit when evolving your code with this code.
########################################################
from FHmonitor.error_handling imp... |
import torch
import numpy as np
from torch import Tensor
from torch.utils.data import Dataset, DataLoader
from torchvision import io
from pathlib import Path
from typing import Tuple
class Wound(Dataset):
"""
num_classes: 18
"""
# explain the purpose of the model
# where is it, how big it is,
... |
#!/usr/bin/python3
def best_score(a_dictionary):
if a_dictionary:
return max(a_dictionary, key=a_dictionary.get)
|
print("before loop")
for count in range(10):
if count > 5:
continue
print(count)
print("after loop")
|
"""Application management util tests"""
# pylint: disable=redefined-outer-name
from types import SimpleNamespace
import pytest
import factory
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from mitol.common.utils import now_in_utc
from applications.api... |
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020. Huawei Technologies Co.,Ltd.ALL rights reserved.
This program is licensed under Mulan PSL v2.
You can use it according to the terms and conditions of the Mulan PSL v2.
http://license.coscl.org.cn/MulanPSL2
THIS PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHO... |
# -*- coding: utf-8 -*-
# @Time : 2022/2/20
# @Author : Zhelong Huang
# @File : client2.py
# @Description: client2
_POS = 2
import os, sys
sys.path.append(os.path.abspath('.'))
from coach import LoadCoach
import argparse
arg = argparse.ArgumentParser()
arg.add_argument('-r', '--render', default=True... |
# A non-empty zero-indexed array A consisting of N integers is given.
#
# A permutation is a sequence containing each element from 1 to N once, and
# only once.
#
# For example, array A such that:
# A = [4, 1, 3, 2]
# is a permutation, but array A such that:
# A = [4, 1, 3]
# is not a permutation, because value... |
"""Flexmock public API."""
# pylint: disable=no-self-use,too-many-lines
import inspect
import re
import sys
import types
from types import BuiltinMethodType, TracebackType
from typing import Any, Callable, Dict, Iterator, List, NoReturn, Optional, Tuple, Type
from flexmock.exceptions import (
CallOrderError,
E... |
import bs4
import re
from common import config
# Regular expresion definitions
is_well_former_link = re.compile(r'^https?://.+$')
is_root_path = re.compile(r'^/.+$')
def _build_link(host, link):
if is_well_former_link.match(link):
return link
elif is_root_path.match(link):
return '{}{}'.form... |
'''
Created on Apr 4, 2016
@author: Noe
'''
class MyClass(object):
'''
classdocs
'''
def __init__(self, params):
'''
Constructor
'''
|
#!/usr/bin/python
from __future__ import absolute_import, division, print_function, unicode_literals
import pi3d
import ConfigParser
from PIL import Image
import sys
#read config
Config = ConfigParser.ConfigParser()
Config.read("config.ini")
xloc = int(Config.get("client",'x_offset'))
yloc = int(Config.get("client"... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
def solve(s):
open_p = ('[', '{', '(')
close_p = (']', '}', ')')
pair = dict(zip(close_p, open_p)) # key: close_p
stack = list()
for c in s:
if c in open_p:
stack.append(c)
if c in close_p:
if len(stack... |
import aiohttp
import os
import pytest
from tokki.travis import TravisClient
from tokki.enums import Status
TOKEN = os.environ["TRAVISCI_TOKEN"]
AGENT = "Tests for Tokki +(https://github.com/ChomusukeBot/Tokki)"
@pytest.mark.asyncio
async def test_no_login():
with pytest.raises(TypeError, match=r": 'token'"):
... |
import argparse
parse = argparse.ArgumentParser(description="test")
parse.add_argument('count' , action='store' , type = int)
parse.add_argument('units',action='store')
parse.add_argument('priseperunit' , action= 'store')
print(parse.parse_args()) |
#!/usr/bin/env python3
import numpy
import cv2
import math
from entities.image import Image
from entities.interfaces.scene_interface import SceneInterface
from entities.aligned.aligned_band import AlignedBand
from entities.aligned.aligned_image import AlignedImage
from entities.aligned.aligned_true_color import Aligne... |
import os
import json
import scipy.io
import pandas
import itertools
import numpy as np
from PIL import Image
from collections import OrderedDict
info = OrderedDict(description = "Testset extracted from put-in-context paper (experiment H)")
licenses = OrderedDict()
catgs = ['airplane','apple','backpack','banana',... |
# See https://michaelgoerz.net/notes/extending-sphinx-napoleon-docstring-sections.html
# # -- Fixing bug with google docs showing attributes-------------
from sphinx.ext.napoleon.docstring import GoogleDocstring
# first, we define new methods for any new sections and add them to the class
def parse_keys_section(self,... |
import re
import random
import string
from django import template
from django.template import Context
from django.template.loader import get_template
from django.contrib.auth.models import Group
from django.core.exceptions import PermissionDenied
from crm.models import Person
from cedar_settings.models import General... |
import os
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse, HttpResponseForbidden, Http404
from django.core.urlresolvers import reverse
from django.conf import settings
from django.core.exceptions im... |
'''
Do a parcel analysis of the sounding and plot the parcel temperature
'''
from __future__ import print_function, division
from SkewTplus.skewT import figure
from SkewTplus.sounding import sounding
from SkewTplus.thermodynamics import parcelAnalysis, liftParcel
#Load the sounding data
mySounding = sounding("./exa... |
from cmath import exp, pi, sin
from re import I
import matplotlib.pyplot as mplt
def FFT(P):
n = len(P)
if n == 1:
return P
else:
w = exp((2.0 * pi * 1.0j) / n)
Pe = []
Po = []
for i in range(0, n, 2):
Pe.append(P[ i ])
for i in range(1, n, 2... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-04-15 18:21
# @Author : erwin
import pandas as pd
import numpy as np
from common.util_function import *
'''
缺失值处理
1. 采用均值/出现次数设置missing值。对于一列数字,要获取平均值。
2. 对于一列非数字,例如字符,要找到出现频率最高的字符赋值给missing值
3. 删除缺失值
http://pandas.pydata.org/pandas-docs/stable/generate... |
"""
The sys command to manage the cmd5 distribution
"""
import glob
import os
import shutil
from cloudmesh.common.util import path_expand
from cloudmesh.shell.command import PluginCommand
from cloudmesh.shell.command import command
from cloudmesh.sys.manage import Command, Git, Version
class SysCommand(PluginCommand... |
import numpy as np
from pypadre.pod.app import PadreApp
from sklearn.datasets import load_iris
from pypadre.examples.base_example import example_app
# create example app
padre_app = example_app()
def create_experiment1(app: PadreApp, name="", project="", auto_main=True):
@app.dataset(name="iris",
... |
import socket
import pickle
import struct
import argparse
def send_msg(sock, msg):
msg_pickle = pickle.dumps(msg)
sock.sendall(struct.pack(">I", len(msg_pickle)))
sock.sendall(msg_pickle)
print(msg[0], 'sent to', sock.getpeername())
def recv_msg(sock, expect_msg_type = None):
msg_len = struct.un... |
"""
NetCDF Builder
This is currently a test script and will eventuall be made into a module
"""
#==============================================================================
__title__ = "netCDF maker"
__author__ = "Arden Burrell (Manon's original code modified)"
__version__ = "v1.0(02.03.2018)"
__email__ ... |
lista = enumerate('zero um dois três quatro cinco seis sete oito nove'.split())
numero_string=dict(lista)
string_numero={valor:chave for chave,valor in numero_string.items()}
print (numero_string)
print(string_numero)
def para_numeral(n):
numeros=[]
for digito in str(n):
numeros.append(numero_... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 20 00:59:05 2020
@author: Leonardo Saccotelli
"""
import numpy as np
import AlgoritmiAlgebraLineare as al
#------------------- TEST MEDOTO DI ELIMINAZIONE DI GAUSS
#Dimensione della matrice
n = 5000
#Matrice dei coefficienti
matrix = np.random.random((n, n)).astype(f... |
"""Lists out the inbuilt plugins in Example"""
from src.example_reporter import ExampleReporter
from src.example_tool import ExampleTool
def get_reporters() -> dict:
"""Return the reporters in plugin"""
return {
"example-reporter": ExampleReporter,
}
def get_tools() -> dict:
"""Return the to... |
"""
stanCode Breakout Project
Adapted from Eric Roberts's Breakout by
Sonja Johnson-Yu, Kylie Jue, Nick Bowman,
and Jerry Liao.
YOUR DESCRIPTION HERE
Click mouse to start the game.
When no live is remained or all bricks are cleared, game is over.
"""
from campy.gui.events.timer import pause
from breakoutgraphics impo... |
#!/usr/bin/env python
'''
jRAT Rat Config Decoder
'''
__description__ = 'jRAT Rat Config Extractor'
__author__ = 'Kevin Breen http://techanarchy.net http://malwareconfig.com'
__version__ = '0.3'
__date__ = '2015/04/03'
#Standard Imports Go Here
import os
import sys
from base64 import b64decode
import string
from zip... |
import json
import uuid
from datetime import datetime
from sqlalchemy.dialects.postgresql import UUID
from app import db
# person_team = db.Table(
# "person_team",
# db.Column(
# "person_id",
# UUID,
# db.ForeignKey("person.id", ondelete="CASCADE"),
# primary_key=True,
# )... |
#!/usr/bin/env python
#
# Code to build the catalogue cache
#
# Usage: python build_cache.py
#
from __future__ import print_function
from sys import stdout
__author__ = "Yu Feng and Martin White"
__version__ = "1.0"
__email__ = "yfeng1@berkeley.edu or mjwhite@lbl.gov"
from imaginglss import DECALS
import numpy
from... |
#Summe der Zahlen von 1 bis 5
summe=0
for i in [1,2,3,4,5]:
summe=summe+i #Beginn eines Blocks
print("Summe von 1 bis ", i,":",summe) #Ende eines Blocks
print("Ende der Rechnung")
|
# -*- coding: utf-8 -*-
"""
Miscellaneous utilities and tools
"""
import errno
import functools
import keyword
import logging
import os
import re
import shutil
import sys
import traceback
from contextlib import contextmanager
from pathlib import Path
from pkg_resources import parse_version
from . import __version__
... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from odahuflow.sdk.models.base_model_ import Model
from odahuflow.sdk.models import util
class ExternalUrl(Model):
"""NOTE: This class is auto generated by the sw... |
from bs4 import BeautifulSoup, SoupStrainer
import re
import requests
import json
strained = SoupStrainer('a', href=re.compile('saskatchewan.kijiji.ca/f.*QQ'))
soup = BeautifulSoup(requests.get('http://saskatchewan.kijiji.ca').text)
category_dict = {}
for a in soup.findAll(strained):
category_id = None
category =... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import datetime
from django.conf import settings
from django.db import connection, DatabaseError, transaction
import djang... |
# src/chara/character.py
import enum
class C_type(enum.Enum):
PLAYER = 0
NPC = 1
OPPONENT = 2
BOSS = 3
class Character():
def __init__(self,name,c_type):
types = Character.__ty()
self.name = name
self.c_type = types[c_type]
# temporary function
def identity(self):... |
from peewee import IntegerField, Model, CompositeKey, ForeignKeyField
from data.db import database
from data.user import User
class Buddies(Model):
buddy1 = ForeignKeyField(User, to_field="id")
buddy2 = ForeignKeyField(User, to_field="id")
class Meta:
database = database
primary_key = Com... |
# Copyright 2019 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
""" Financial Modeling Prep Model """
__docformat__ = "numpy"
import pandas as pd
import FundamentalAnalysis as fa
from gamestonk_terminal import config_terminal as cfg
def get_rating(ticker: str) -> pd.DataFrame:
"""Get ratings for a given ticker. [Source: Financial Modeling Prep]
Parameters
----------... |
#!/usr/bin/env python
"""tests for :mod:`online_pomdp_planning.mcts`"""
from functools import partial
from math import log, sqrt
from typing import Dict
import pytest
from online_pomdp_planning.mcts import (
ActionNode,
DeterministicNode,
MuzeroInferenceOutput,
ObservationNode,
backprop_running_q... |
from itertools import product
import torch
import dgl
from dgl.data import citation_graph
from dgl.contrib.data import load_data
from dgl import DGLGraph
from runtime.dgl.gcn import GCN, GCNSPMV
from runtime.dgl.gat import GAT, GATSPMV
from runtime.dgl.rgcn import RGCN, RGCNSPMV
from runtime.dgl.train import train_ru... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import threading
from datetime import date, datetime, timedelta
from psycopg2 import sql
from odoo import api, fields, models, tools, SUPERUSER_ID
from odoo.osv import expression
from odoo.tools.translate... |
import sys
from schemas.input_conf import personal_info
from settings.base_conf import KOBO_PERSONAL_INFO_CSV_MAP
'''
json_structure - the json attributes that are to be extracted from the source json
mapping_format - see oldcuris_elastic_map for an example. import it here
input_format - default input of source json... |
""" Test Metadata Tool """
from __future__ import unicode_literals, absolute_import
from tmt.base import Tree
__all__ = ["Tree"]
|
import os
import matplotlib.pyplot as plt
from typing import List, Union, Tuple, Dict
import torch
import pickle
current_dir = os.path.dirname(os.path.realpath(__file__))
CATEGORY = List[Union[int, float]]
RUN_STATS = Dict[str, Union[int, float]]
def plot_score_and_acc_over_docs(
dir_name: str,
stats: List[Tu... |
from molsysmt._private_tools.exceptions import *
from molsysmt.forms.common_gets import *
import numpy as np
from molsysmt.molecular_system import molecular_system_components
from molsysmt._private_tools.files_and_directories import tmp_filename
form_name='file:dcd'
is_form = {
'file:dcd':form_name
}
inf... |
import mongolib
class a():
def aa(self):
a=mongolib.mongodb()
a.log_collect(msg='1gaejiusfuadaifuagusuifhiau afdu gaudf uisg uagsi gaug asyaigasydg aug iug ')
a.log_collect(msg='2')
a.log_input()
a.log_output()
aaaa=a()
aaaa.aa() |
import inspect
import operator
import re
from datetime import datetime
from decimal import Decimal
from enum import Enum
from functools import reduce
import pymongo
from bson import ObjectId
from pymongo.collection import Collection, ReturnDocument
from pymongo.errors import CollectionInvalid
from appkernel.configura... |
# Generated by Django 3.0.11 on 2021-01-22 10:13
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('cars', '0001_initial'),
('users', '0002_auto_20210122_0713'),
... |
import math
N = int(input())
sqN = math.floor(math.sqrt(N))
yaku1 = 1
yaku2 = 1
for i in range(sqN, 0, -1):
if N % i == 0:
yaku1 = i
yaku2 = N // i
break
print(yaku1+yaku2-2)
|
import asyncio
import pytest
import unittest
from unittest.mock import MagicMock, patch
from app import Application
@pytest.mark.asyncio
async def test_func1():
app = Application()
func2_stub = MagicMock(return_value='future result!')
func2_coro = asyncio.coroutine(func2_stub)
async with patch.object... |
#先引入后面分析、可视化等可能用到的库
import tushare as ts
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sqlalchemy import create_engine
import psycopg2
#正常显示画图时出现的中文和负号
from pylab import mpl
mpl.rcParams['font.sans-serif']=['SimHei']
mpl.rcParams['axes.unicode_minus']=False
#设置token
token = '7dc39867da... |
# Copyright (c) 2019 leosocy. All rights reserved.
# Use of this source code is governed by a MIT-style license
# that can be found in the LICENSE file.
import io
import os
from setuptools import setup
import edcc
# Package meta-data.
NAME = "edcc"
DESCRIPTION = "EDCC: An efficient and accurate algorithm for palmpr... |
from toolkit.modules.make_follow_sets import follow_sets
from toolkit.modules.make_first_sets import first_sets
from toolkit.modules.grammar import is_terminal
from tabulate import tabulate
def parsing_table(pgrammar, fs, fls, error_recovery=True):
"""
Input:
pgrammar: parsed grammar
fs: first... |
class MemcacheError(Exception):
pass
class MemcacheServerError(Exception):
def __init__(self, server: str, message: str) -> None:
self.server = server
super().__init__(message)
|
watchdog_config = """
# SDSLabs Watchdog configuration START
UsePAM yes
PasswordAuthentication no
AuthorizedKeysCommand /opt/watchdog/bin/watchdog auth -u %u -t %t -p %k
AuthorizedKeysCommandUser root
# SDSLabs Watchdog configuration END
"""
modified_options = [
'AuthorizedKeysCommand',
'AuthorizedKeysCommandUser... |
#!/usr/bin/env python
#author mark_purcell@ie.ibm.com
#NOTE: FOR GOFLEX OPERATIONS DONT CHANGE THE CONTENTS OF THIS FILE
#REQUEST BUG FIXES OR ENHANCEMENTS AS NECESSARY
class GoFlexMessageFormatter():
def __init__(self):
pass
def request_meter_data(self, meter, from_date, to_date):
return {... |
from .gradient_penalty import *
from .wasserstain_div import *
|
# -*- coding: utf-8 -*-
import sys
from formalchemy import templates
__doc__ = """
There is two configuration settings available in a global config object.
- encoding: the global encoding used by FormAlchemy to deal with unicode. Default: utf-8
- engine: A valide :class:`~formalchemy.templates.TemplateEngine`
- dat... |
'''
Copyright (c) 2021-2022 OVGU LIA
Author: Harish Kumar Pakala
This source code is licensed under the Apache License 2.0 (see LICENSE.txt).
This source code may use other Open Source software components (see LICENSE.txt).
'''
try:
import queue as Queue
except ImportError:
import Queue as Queue
class DataMan... |
# Последовательность треугольных чисел образуется путем сложения натуральных чисел. К примеру, 7-ое треугольное число
# равно 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. Первые десять треугольных чисел:
#
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
#
# Перечислим делители первых семи треугольных чисел:
#
# 1: 1
# 3: 1, 3
# 6: 1,... |
from django.conf import settings
if settings.WITH_WQDB:
from wq.db import rest
from wq.db.patterns import serializers as patterns
from .models import Note
rest.router.register_model(
Note,
serializer=patterns.NaturalKeyModelSerializer,
fields="__all__",
)
|
# Introduction to Python
# Structure of if statements
"""
if condition:
Statements
elif condition:
Statements
else:
Statements
"""
#Grade of a student
marks = 90
# No braces in Python, Indectation does the job
if marks > 90:
print("Grade O")
elif marks > 80:
print("Grade E")
elif marks > 70:
... |
class DeprecatedEnv(ImportError):
pass
|
#!/usr/bin/env python
# coding: utf-8
# ## Case Challenge Part I (Individual Assignment 1)
# After three years serving customers across the San Francisco Bay Area, the executives at
# Apprentice Chef have decided to take on an analytics project to better understand how much
# revenue to expect from each customer withi... |
from flocx_ui.api import schema
from flocx_ui.api.utils import generic_provider_request as generic_request
from flocx_ui.api.utils import validate_data_with
def post(path, **kwargs):
"""An alias for generic_request with the type set to 'POST'
:param path: A url path
:param **kwargs: The keyword arguments ... |
import bluesky.plan_stubs as bps
import bluesky.plans as bp
import bluesky.preprocessors as bpp
import numpy as np
import pytest
from ophyd.sim import SynAxis, hw
import nabs.plans as nbp
from nabs.simulators import validate_plan
hw = hw()
class LimitedMotor(SynAxis):
def check_value(self, value, **kwargs):
... |
def test_list_devices(client):
devices = client.devices()
assert len(devices) > 0
assert any(map(lambda device: device.serial == "emulator-5554", devices))
def test_version(client):
version = client.version()
assert type(version) == int
assert version != 0
|
import numpy as np
from gutfit import model, parameterlist
def matrix_diag3(d1,d2,d3):
return np.array([[d1, 0.0, 0.0], [0.0, d2, 0.0], [0.0, 0.0, d3]])
# Generic Rotations #
def matrix_rot23(th23):
return np.array([[1.0, 0.0 , 0.0],
[0.0, np.cos(th23), np.sin(th23)],
... |
import argparse
import json
import logging
import random
import numpy as np
import torch
from decouple import config
from tqdm import tqdm
from GPT2.config import GPT2Config
from GPT2.encoder import get_encoder
from GPT2.model import GPT2LMHeadModel
from GPT2.utils import load_weight
# import os
# import torch.nn.... |
#
# PySNMP MIB module SUN-T300-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SUN-T300-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:04:28 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... |
# ******************************************************************************
# Copyright 2017-2018 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.apa... |
def foo():
print "hello every body" |
from relevanceai.base import _Base
from relevanceai.api.endpoints.centroids import CentroidsClient
class ClusterClient(_Base):
def __init__(self, project, api_key):
self.project = project
self.api_key = api_key
self.centroids = CentroidsClient(project=project, api_key=api_key)
supe... |
import requests
import urllib
from bs4 import BeautifulSoup
from os import path, makedirs
import wget
class Crawler:
"""
Class for crawl by page ulr-like 'http(s)://page_path/page_name_{number}/ and download pictures
"""
def __init__(self, url_pattern, page_number, css_alt=None):
self.url_patt... |
# Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/)
#
# 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 appli... |
#!/usr/bin/env python3
# Povolene knihovny: copy, math
# Import jakekoli jine knihovny neprojde vyhodnocovaci sluzbou.
# To, ze jsou nejake knihovny povolene, neznamena, ze je nutne je pouzit.
# IB002 Domaci uloha 9.
#
# V teto uloze se budeme zabyvat binarnimi vyhledavacimi stromy.
#
# V prvni casti bude Vasi uloho... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.