text stringlengths 2 999k |
|---|
import unittest
import finvizlite as fl
class TestFinvizlite(unittest.TestCase):
def test_rows_to_pages(self):
self.assertEqual(fl.rows_to_pages(115), 6)
self.assertEqual(fl.rows_to_pages(15), 1)
self.assertEqual(fl.rows_to_pages(20), 1)
self.assertEqual(fl.rows_to_pages(21), 2)
... |
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../"))
import unittest
import shutil
import numpy as np
from ml.model import NumberRecognizeNN
from ml.data_processor import DataProcessor
from ml.trainer import Trainer
from ml.resource import Resource
class TestTrainer(unittest.TestCase):
... |
from django.conf.urls import patterns, url
urlpatterns = patterns('craneui.views',
url(r'^$', 'index', name='craneui.index'),
url(r'^create_container/$', 'create_container',
name='craneui.create_container'),
url(r'^buildos/$', 'build_os',
name='craneui.build_os'),
url(r'^buildinterprete... |
import pytest
from docarray import DocumentArray, Document
from docarray.array.qdrant import DocumentArrayQdrant
from docarray.array.sqlite import DocumentArraySqlite
from docarray.array.pqlite import DocumentArrayPqlite, PqliteConfig
from docarray.array.storage.qdrant import QdrantConfig
from docarray.array.storage.w... |
import argparse
from LightheadRCNN_Learner import LightHeadRCNN_Learner
def parse_args():
parser = argparse.ArgumentParser(description="Train CornerNet")
parser.add_argument("-r", "--resume", help="whether resume from the latest saved model",action="store_true")
parser.add_argument("-save", "--from_save_f... |
#!/usr/bin/env python
import json
import boto3
# Can also use an ~/.aws/credentials file
client = boto3.client(
'route53',
aws_access_key_id = '<access_key>',
aws_secret_access_key = '<secret_key>',
)
response = client.list_hosted_zones(
MaxItems='100',
)
for zone in response["HostedZones"]:
rec... |
# https://www.hackerrank.com/challenges/collections-counter/problem
from collections import Counter
"""
s = "daaababcc"
# result is same with
# s = ['d','a','a','a','b','a','b','c','c']
print(Counter(s))
# Counter({'a': 4, 'b': 2, 'c': 2, 'd': 1})
print(Counter(s).items())
# dict_items([('d', 1), ('a', 4), ('b', 2... |
# -*- coding: utf-8 -*-
import os
import pytest
from tempfile import gettempdir
from ansible_runner.config.ansible_cfg import AnsibleCfgConfig
from ansible_runner.config._base import BaseExecutionMode
from ansible_runner.exceptions import ConfigurationError
from ansible_runner.utils import get_executable_path
def ... |
CDNX_INVOICING_PERMISSIONS = {}
CDNX_INVOICING_PERMISSIONS['customer'] = [
'list_region',
'list_salesalbaran',
'list_salesbasket',
'list_salesinvoice',
'list_salesinvoicerectification',
'list_salesorder',
'list_salesticket',
'list_salesticketrectification',
'list_timezone',
'list... |
def three_things():
print("What's three most important things in your life")
things = []
for i in range(3):
thing = input("Thing number {}: ".format(i + 1))
things.append(thing)
print(things)
print("That's what you named")
for thing2 in things:
print(thing2)
if __name... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the windows services analysis plugin."""
from __future__ import unicode_literals
import unittest
from dfvfs.path import fake_path_spec
from plaso.analysis import windows_services
from plaso.lib import definitions
from plaso.parsers import winreg
from test... |
#!/usr/bin/python
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"... |
"""
FactSet Ownership API
FactSet’s Fund Ownership API gives access to both **Holdings** and **Holders** data.<p> Factset's Holdings endpoints gives access to all the underlying securities and their position detils held within a given fund. Fund Types supported include Open-End Mutual Funds, Closed-end Mutual ... |
# Exercise 7.24
# Author: Noah Waterfield Price
import numpy as np
import matplotlib.pyplot as plt
import operator
class PiecewiseConstant:
def __init__(self, data, xmax):
self.data = data + [(None, xmax)]
def __call__(self, x):
if isinstance(x, (float, int)):
return self.piecew... |
"""
DeepLesion database
"""
import cPickle
import cv2
import os
import numpy as np
# from scipy.io import loadmat
import csv
import sys
from ..logger import logger
from imdb import IMDB
from rcnn.config import config, default
DEBUG = False
class DeepLesion(IMDB):
def __init__(self, image_se... |
"""
Flask-GFM
-------------
GitHub Flavored Markdown jinja2 extension for Flask
"""
from setuptools import setup
__version__ = '0.1.1'
setup(
name='Flask-GFM',
version=__version__,
url='https://github.com/jckdotim/flask-gfm/',
license='MIT',
author='JC Kim',
author_email='jckdotim@gmail.com'... |
from blogapi import db
def is_user_exists(email):
cur = db.connection.cursor()
cur.execute("SELECT email FROM users WHERE email=%s", [email])
res = cur.rowcount
cur.close()
if res == 0:
return False
return True
def is_post_exists(post_id):
cur = db.connection.cursor()
cur... |
load("//scala:compile.bzl", "scala_proto_compile", "scala_grpc_compile")
load("@io_bazel_rules_scala//scala:scala.bzl", "scala_library")
def scala_proto_library(**kwargs):
name = kwargs.get("name")
deps = kwargs.get("deps")
visibility = kwargs.get("visibility")
name_pb = name + "_pb"
scala_proto_c... |
#!/usr/bin/env python2.7
from __future__ import print_function
import yaml
# Try to use the C parser.
try:
from yaml import CLoader as Loader
except ImportError:
print("For faster parsing, you may want to install libYAML for PyYAML")
from yaml import Loader
import cgi
from collections import defaultdict
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#####################################
### CIS SLOT FILLING SYSTEM ####
### 2014-2015 ####
### Author: Heike Adel ####
#####################################
import codecs, sys
reload(sys)
sys.setdefaultencoding('utf-8')
sys.stdout = codecs.get... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# this is to generate a config file when the --config flag is passed
from configparser import ConfigParser
import logging
from pathlib import Path
from .input_utils import choice, yes_or_no
log = logging.getLogger('pfg.config')
log.addHandler(logging.NullHandler())
hom... |
# Major package imports.
from setuptools import setup, find_packages
setup(
name = 'acme.motd.software_quotes',
version = '0.1a1',
author = 'Enthought, Inc',
author_email = 'info@enthought.com',
license = 'BSD',
zip_safe ... |
# -*- coding: utf-8 -*-
# (C) Datadog, Inc. 2016-present
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
import copy
import io
import logging
import math
import os
import mock
import pytest
import requests
from prometheus_client.core import CounterMetricFamily, GaugeMetricFamily, Histogram... |
try:
from collections import Sequence
except ImportError:
from collections.abc import Sequence
from io import BytesIO
import zipfile
class DocumentCollection(Sequence):
def __init__(
self,
sumo_client,
query,
mapper_function=None
):
self.sumo = sumo_client
... |
#!/usr/bin/python3
#
# pican_fd_tx_test.py
#
# For use with PiCAN FD board
# http://skpang.co.uk/catalog/canbus-fd-board-with-real-time-clock-for-raspberry-pi-3-p-1545.html
#
import RPi.GPIO as GPIO
import os
import can
import time
led = 22
count = 0
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(led,GPIO.O... |
# Copyright 2013 Red Hat, 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 agre... |
from PyQt5 import QtWidgets
from PyQt5 import QtCore
from PyQt5 import QtGui
class Canvas(QtWidgets.QWidget):
wheeled = QtCore.pyqtSignal(int)
def __init__(self, graphicsView):
super().__init__()
self.graphicsView = graphicsView
self.graphicsView.setMinimumSize(QtCore.QSize(512, 512))... |
import json
import os
import random
import string
import time
import sys
try:
import Crypto
except ImportError:
if sys.platform == 'win32':
from thirdparty.win.Crypto import Random
from thirdparty.win.Crypto.PublicKey import RSA
from thirdparty.win.Crypto.Cipher import AES, PKCS1_OAEP
... |
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import plotly.graph_objs as go
import pandas as pd
from .dash import Dash
df = pd.read_csv("app/data/indicators.csv")
available_indicators = df["Indicator Name"].u... |
from onyx.extensions import db
class Tokens(db.Model):
__tablename__ = 'tokens'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(), nullable=False, unique=True)
token = db.Column(db.String(), nullable=False, unique=True)
|
# Copyright 2017 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.
"""Shared setup and configuration code for Predator scripts."""
from datetime import date
from datetime import timedelta
import os
from analysis.type_enums... |
# coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.
import numpy as np
import os
from subprocess import Popen, PIPE
from pyiron.vasp.outcar import Outcar
from pyiron.vasp.... |
#!/usr/bin/env python
# coding: utf-8
SERVER = "127.0.0.1"
USER = "user"
PORT = 35601
PASSWORD = "user@123"
INTERVAL = 1
PROBEPORT = 80
PROBE_PROTOCOL_PREFER = "ipv4" # ipv4, ipv6
PING_PACKET_HISTORY_LEN = 100
CU = "cu.tz.cloudcpp.com"
CT = "ct.tz.cloudcpp.com"
CM = "cm.tz.cloudcpp.com"
import socket
import time
imp... |
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 2.1.4.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# ... |
import unittest
from unittest import mock
import shutil
import tempfile
from typing import Sequence
import asyncio
from electrum import storage, bitcoin, keystore, bip32, wallet
from electrum import Transaction
from electrum import SimpleConfig
from electrum.address_synchronizer import TX_HEIGHT_UNCONFIRMED, TX_HEIGHT... |
# -*- coding: utf-8 -*-
from mtpylon.contextvars import auth_key_var
def test_import_vars():
assert auth_key_var is not None
|
#!/usr/bin/env python
#
# Copyright 2013 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 all types of tests from one unified interface."""
import argparse
import collections
import logging
import os
import shutil
... |
import networkx as nx
def create_nxgraph(net, only_in_service=True):
"""
Convert a given network into a NetworkX MultiGraph
:param net: the given network
:param only_in_service: if True, convert only the pipes that are in service (default: True)
:return: a MultiGraph
"""
g = nx.OrderedDi... |
"""
Copyright (C) 2019 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable.
"""
from ibapi.contract import * # @UnusedWildImport
class ContractSamples:
""" Usually, the easiest way to... |
# -*- coding: utf-8 -*-
import json
from django.db import connection
from themis.rule_analysis.libs.mysql_plan_stat.json_plan_parse import json_plan_item
class MysqlPlanOrStat(object):
"""
mysql 执行计划和统计信息的解析类
"""
def __init__(self, db_client, mongo_client, rule_type):
self.db_client = db_c... |
#!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'locallibrary.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django.... |
import sys
import os
import time
import asyncio
import discord
import requests
import json
from config import *
import logger_wrap
logger = logger_wrap.logger(__name__)
def full_commands(_commands2):
if type(_commands2) == str:
_commands2 = [_commands2]
elif type(_commands2) == int or type(_commands2) == flo... |
"""Takes filename as input, creates a Markdown table of contents from its Markdown
headers, and prints TOC to stdout.
"""
import re
def get_headers(s):
"""Returns header tuples with text and indentation level.
"""
PATTERN = '###* (?=\w)'
matches = []
for line in s.splitlines():
m = re.matc... |
# Copyright 2008-2015 Nokia Solutions and Networks
#
# 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 l... |
from gettext import gettext as _
from django.db import models
from cyder.cydns.domain.models import Domain
from cyder.cydns.validation import (
validate_srv_label, validate_srv_port, validate_srv_priority,
validate_srv_weight, validate_srv_name, validate_srv_target
)
from cyder.cydns.models import CydnsRecord... |
import hashlib
import os
import urllib
import warnings
from typing import Any, Union, List
from pkg_resources import packaging
import torch
from PIL import Image
from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
from tqdm import tqdm
from .model import build_model
from .simple_tokeni... |
from django.apps import AppConfig
class KittenConfig(AppConfig):
name = 'kitten'
|
# Copyright 2016 Google Inc. 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 applicable law or ag... |
#
# PySNMP MIB module NETSCREEN-USER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NETSCREEN-USER-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:20:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
# Generated by Django 2.1.15 on 2020-06-09 02:49
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0009_alter_user_last_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
... |
# define a function
def flow_control(k):
# define a string based on the value of k
if(k==0):
s = "Variable k = %d equals 0." % k
elif(k==1):
s = "Variable k = %d equals 1." % k
else:
s = "Variable k = %d does not eequal 0 or 1." % k
# print the variable
print(s)
# define a main function
def mai... |
#!/usr/bin/env python
import os
from optparse import OptionParser
from jinja2 import Template
HEADER = '!!AUTO-GENERATED!! Edit bin/crontab/crontab.tpl instead.'
TEMPLATE = open(os.path.join(os.path.dirname(__file__), 'crontab.tpl')).read()
def main():
parser = OptionParser()
parser.add_option('-w', '--web... |
"""
1.Question 1
The file (SCC.txt) contains the edges of a directed graph. Vertices are labeled as positive integers from 1 to 875714. Every row indicates an edge, the vertex label in first column is the tail and the vertex label in second column is the head (recall the graph is directed, and the edges are directed ... |
import time
import struct
from banyan_ch_find import banyan_ch_find
import numpy
import datetime
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), "../submodules/FEED/src/python"))
# Grab the start time early, so things like
# python get_raw_adcs.py | tee `date "+%Y%m%d_%H%M%S"`.log
# will ... |
from crypto.aes import AESdecryptCBC, AESencryptCBC
from hfs.emf import cprotect_xattr, EMFVolume
from hfs.hfs import HFSVolume, hfs_date, HFSFile
from hfs.journal import carveBtreeNode, isDecryptedCorrectly
from hfs.structs import *
from util import sizeof_fmt, makedirs, hexdump
import hashlib
import os
import... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: owefsad@huoxian.cn
# datetime: 2021/7/16 下午12:17
# project: dongtai-engine
from dongtai.utils import const
class Replay:
"""
封装重放操作为单独的类
"""
def __init__(self, replay):
self.replay = replay
self.vul = None
@staticmethod
d... |
import os
import boto3
import json
import urllib.request
gsheets_url = "https://sheets.googleapis.com/v4/spreadsheets/"
def handler(event, context):
#remove credentials from event
accesstoken = event['accesstoken']
event['accesstoken'] = '***'
print("event")
print(event)
sheetid = event['sheetid']
req... |
def load_parameters():
"""
Loads the defined hyperparameters
:return parameters: Dictionary of loaded parameters
"""
# Input data params
TASK_NAME = 'qe-2016' # Task name
DATASET_NAME = TASK_NAME # Dataset name
SRC_LAN = 'src' ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-05-22 13:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pfb_analysis', '0027_remove_states_from_labels'),
]
operations = [
migratio... |
# Copyright 2012-2017 The Meson development team
# 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 agree... |
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.md')).read()
NEWS = open(os.path.join(here, 'CHANGELOG.rst')).read()
version = '0.4.0'
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
zip_sa... |
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
import argparse
import sys
import yaml
import multiprocessing
sys.path.append('..')
import models
class YAMLNamespace(argparse.Namespace):
def __init__(self, config_dict):
for key, value in config_dict.items():
setattr(self, key, value)
... |
import numpy as np
import csv
import sys
import os
##################################
# Setup
#
print("NetBench python analysis tool v0.01")
# Usage print
def print_usage():
print("Usage: python analyze.py /path/to/run/folder")
# Check length of arguments
if len(sys.argv) != 2:
print("Number of arguments m... |
# -*- encoding: utf-8 -*-
from django.conf.urls import include, patterns, url
from django.views.generic import TemplateView
from filebrowser.sites import site
from .feed.feed import RssLatestPostsFeed, AtomLatestPostsFeed
urlpatterns = patterns(
'',
# filebrowser
url(r'^admin/filebrowser/', include(sit... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
# -----------------------------------------------------------------------------
try... |
import sys
import unittest
import subprocess
import json
from packaging import version
import numpy as np
from optimum.intel.openvino import (
OVAutoModel,
)
import transformers
from transformers import AutoConfig
class NNCFTests(unittest.TestCase):
def test_bert_base_ner(self):
subprocess.run(
... |
from flask import request, abort, redirect, url_for
from app.controllers import comment
from app.server import server
from app.tasks import markdown
from app.helpers.render import render_json
from app.session.csrf import csrf_protected
@server.route("/post/comment/<int:post_id>", methods=["POST"])
@csrf_protected
def... |
import os
import sys
import re
import time
from aip import AipOcr
sms_code = ""
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
class BaiduOCR(object):
"""
百度ocr识别类,用于帮助ios设备识别投屏后的短信验证码
"""
def __init__(self, _config, debug=False):
from utils.logger import Log
... |
import socket
import urllib, urllib2
class Downloader:
def __init__(self, uri, qparams):
self.uri = uri
self.qparams = qparams
qstr = urllib.urlencode(self.qparams)
self.req = urllib2.Request('?'.join([uri, qstr]))
def download(self):
try:
f = urllib2.urlopen(self.req)
return f.read()
except urlli... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'demosite.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise Impor... |
import unittest
import atomic_neu.atomic as atomic
import numpy as np
class TestElectronCooling(unittest.TestCase):
def setUp(self):
ad = atomic.element('li')
eq = atomic.CollRadEquilibrium(ad)
self.temperature = np.logspace(0, 3, 50)
self.electron_density = 1e19
# y is a F... |
#
# Copyright (c) Pret-a-3D/Paolo Ciccone. All rights reserved.
# Modified by Fuzzy70/Lee Furssedonn with kind permission from Paolo Ciccone
#
from Reality_services import *
from Reality import *
# To customize this script all you need to do is to
# change the following variable
Re_sIBL_Map = ":Runtime:Text... |
from .helpers import deprecated_alias
@deprecated_alias('set_iscsi_options')
def iscsi_set_options(
client,
auth_file=None,
node_base=None,
nop_timeout=None,
nop_in_interval=None,
disable_chap=None,
require_chap=None,
mutual_chap=None,
chap_group... |
#-*- coding: utf-8 -*-
""" Crashlog module (without vendor lock-in) """
# std
import json
import os
import platform
import socket
# 3rd party
import requests
# local
from voiceplay import __version__
from voiceplay.logger import logger
from .piphelper import PIP
def exc2encode(exc_info, fname):
"""
Excepti... |
from PreprocessData.all_class_files.InformAction import InformAction
import global_data
class ConfirmAction(InformAction):
def __init__(self, additionalType=None, alternateName=None, description=None, disambiguatingDescription=None, identifier=None, image=None, mainEntityOfPage=None, name=None, potentialActi... |
#coding:utf-8
#
# id: bugs.core_4675
# title: Conditions like WHERE <field> = <cursor>.<field> do not use existing index
# decription:
# tracker_id: CORE-4675
# min_versions: ['3.0']
# versions: 3.0
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
# ver... |
import logging
import threading
import time
# Credits to https://gist.github.com/cypreess/5481681
class PeriodicThread(object):
"""
Python periodic Thread using Timer with instant cancellation
"""
def __init__(self, callback=None, period=1, name=None, *args, **kwargs):
self.name = name
... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
#
# PySNMP MIB module RH-ATT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RH-ATT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:48:48 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, 09:... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Clinton Cario 9/11/2015
# 02/08/2016
# Rewritten based on SSM_populator for memsql, no dependency on peewee and cleaner more efficient tables
# 02/09/2016
# Fixed bug where single quotes ruin syntax by incorperating a strip_invalid function that sanitizes ... |
print('Insert values for a, b, c')
#Quadratic formula
a=float(input())
b=float(input())
c=float(input())
d=(b**2)-(4*a*c) #The discriminant
if (d<0):
print('No solution') #There is no solution if d is less than 0
if (d==0):
print('1 solution') #There is one solution if d is equal to 0
if (d>0):
p... |
import numpy as np
import os
import sys
sys.path.append("../src")
import localmodule
# Define constants
dataset_name = localmodule.get_dataset_name()
aug_kinds = ["all", "all-but-noise", "none"]
folds = localmodule.fold_units()
units = localmodule.get_units()
n_trials = 10
script_name = "044_predict-add-convnet-full... |
# marin tvpb example data processing
# Ben Stabler, ben.stabler@rsginc.com, 09/17/20
import pandas as pd
import openmatrix as omx
# command to run the underdevelopment example
# python simulation.py -c configs_3_zone_marin -d data_3_marin -o output_3_marin
# data processing at c:\projects\activitysim\marin
# 1 - f... |
"""
Django settings for cloud_library project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
imp... |
import logging
import random
import numpy as np
import pickle
# disable gpu training for this example
import os
os.environ['CUDA_VISIBLE_DEVICES'] = ''
import paddle
import paddle.fluid as fluid
from config import parse_args
from reader import CriteoDataset
from network import DCN
from collections import OrderedDict... |
import pytest
import requests_mock
from app.integrations.clickmeeting import ClickMeetingClient
pytestmark = [pytest.mark.django_db]
@pytest.fixture(autouse=True)
def set_api_key(settings):
settings.CLICKMEETING_API_KEY = 's3c3r37'
@pytest.fixture
def client():
client = ClickMeetingClient()
with requ... |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.2.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Dataset Visualizer
# +
import sys
# Yeah darkside... |
# Example of a LinkedList
class Node:
def __init__(self, value, next):
self.value = value
self.next = next
def printNode(self):
print(self.value, '-', self.next)
class LinkedList:
def __init__(self, a):
self.head = None
tail = None
for i in a:
... |
import pyaf.Bench.TS_datasets as tsds
import pyaf.tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 7, transform = "Fisher", sigma = 0.0, exog_count = 100, ar_order = 0); |
from olympia.amo.install import addons
from olympia.amo.tests import TestCase
from olympia.amo.urlresolvers import reverse
from olympia.amo.utils import urlparams
class InstallTests(TestCase):
def test_generic(self):
url = reverse('api.install')
r = self.client.get(urlparams(url,
... |
from django import forms
from .models import Supplier,RawOrder,RawMaterial
class SupplierForm(forms.ModelForm):
class Meta:
model = Supplier
fields = ("",)
class RawOrderForm(forms.ModelForm):
class Meta:
model = RawOrder
fields = ("",)
class RawMaterailForm(forms... |
#!/usr/bin/python3
#-*- coding: utf-8 -*-
from db_connector import DBConnector
import time
import datetime
import subprocess
try:
from bmp280 import BMP280
except:
pass
class Main():
def __init__(self):
self.db = DBConnector()
self.termostats = []
self._add_termostat(50, 49, "В хо... |
# Copyright 2015 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... |
import torch
import torch.nn as nn
import os
import random
from third_party.midi_processor.processor import decode_midi, encode_midi
from utilities.argument_funcs import parse_generate_args, print_generate_args
from model.music_transformer import MusicTransformer
from model.music_lstm import MusicLSTM
from dataset.e_... |
import unittest
import time
from datetime import datetime
from app import create_app, db
from app.models import User, AnonymousUser, Role, Permission, Follow
class UserModelTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
... |
# MIT License
# Copyright (c) 2022 [FacuFalcone]
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, ... |
import IECore
import GafferUI
import GafferScene
import GafferSceneUI
import os
for nodeName in ['CustomAttributes']:
script.selection().add( script.descendant( nodeName ) )
script.context()["ui:scene:expandedPaths"] = GafferScene.PathMatcherData( GafferScene.PathMatcher( ['/', '/group', '/group/ballA', '/group/ballB... |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... |
from pyspark import SparkContext, SparkConf
import re
class Utils():
COMMA_DELIMITER = re.compile(''',(?=(?:[^"]*"[^"]*")*[^"]*$)''')
if __name__ == "__main__":
conf = SparkConf().setAppName('StackOverFlowSurvey').setMaster("local[*]")
sc = SparkContext(conf = conf)
total = sc.accumulator(0)
miss... |
'''
Training script for CIFAR-10/100
Copyright (c) Wei YANG, 2017
'''
from __future__ import print_function
import argparse
import os
import shutil
import time
import random
from dataloader import my_dataset
from ngd import NGD
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.