content stringlengths 5 1.05M |
|---|
# Generated by Django 2.0.9 on 2018-12-10 06:11
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('images', '0017_imageset_zip_state'),
]
operations = [
migrations.AddField(
model_name='im... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: xiaoya li
# file: count_length_autotokenizer.py
import os
import sys
repo_path = "/".join(os.path.realpath(__file__).split("/")[:-2])
print(repo_path)
if repo_path not in sys.path:
sys.path.insert(0, repo_path)
from transformers import AutoTokenizer
from... |
import pytest
from pydantic import ValidationError
from kaiba.models.iterator import Iterator
def test_validates(): # noqa: WPS218
"""Test that dict is marshalled to pydantic object."""
test = Iterator(
alias='test',
path=['data'],
)
assert test.alias == 'test'
assert test.path =... |
#!/usr/bin/env python
import sys
import pyautogui
def main():
width, height = pyautogui.size()
pyautogui.moveTo(width / 2, height / 2, 0.5, pyautogui.easeInQuad)
if __name__ == '__main__':
sys.exit(main())
|
from peewee import SQL, CharField, IntegerField
from ...db import db
from ..fields import UIntForeignKeyField
class ProductCategory(db.Model):
name = CharField(column_name="label", null=True)
parent = UIntForeignKeyField(
column_name="parent_id",
field="id",
model="self",
null... |
"""update reptiles, field type_inventaire values
Revision ID: e2d0f0d7bc9f
Revises: f4ed33963a7b
Create Date: 2018-03-30 11:49:23.021509
"""
# revision identifiers, used by Alembic.
revision = 'e2d0f0d7bc9f'
down_revision = 'f4ed33963a7b'
from alembic import op
import sqlalchemy as sa
from alembic import context... |
"""
MIT License
Copyright (c) 2020 Andy Zhou
"""
from flask import Blueprint
user_bp = Blueprint("user", __name__)
from . import views
|
import pandas as pd
import pytest
from pts.dataset import ProcessStartField
@pytest.mark.parametrize(
"freq, expected",
[
("B", "2019-11-01"),
("W", "2019-11-03"),
("M", "2019-11-30"),
("12M", "2019-11-30"),
("A-DEC", "2019-12-31"),
],
)
def test_process_start_fiel... |
import os
import pytest
from robocorp_ls_core.protocols import IConfigProvider
from robocorp_ls_core.robotframework_log import get_logger
from robocorp_ls_core.unittest_tools.cases_fixture import CasesFixture
from robocorp_code.protocols import IRcc
log = get_logger(__name__)
@pytest.fixture
def language_server_c... |
"""This XBlock provides syntax highlighting via the PrismJS library"""
import pkg_resources
from web_fragments.fragment import Fragment
from xblock.core import XBlock
from xblock.fields import Scope, String, Integer
from xblockutils.resources import ResourceLoader
class PrismXBlock(XBlock):
"""
Provide syntax... |
from scipy.stats import expon
from numpy import exp, ceil
from scipy.optimize import root_scalar
class ExponMixture:
def __init__(self, ps, scales):
self.ps = ps
self.scales = scales
self.expons = []
for scale in scales:
self.expons.append(expon(scale=scale))
def ... |
"""Module contains API to operate details route view model."""
from typing import Optional
from pyramid.request import Request
from billtracker.data import repository
from billtracker.data.models.bill import Bill
from billtracker.data.models.users import User
from billtracker.models.base import ViewModel
class BillDe... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: Olivier Noguès
import ares.Lib.AresSql
class AresPostGres(ares.Lib.AresSql.AresSqlConn):
"""
:category: Connector
:rubric: PY
:type: Class
:dsc:
Connector to Access databases. This connector will allow you to create, store and retri... |
from configparser import ConfigParser
from emails.EmailSnailPro import EmailSnailPro
from sites.AgentJbzd import AgentJbzd
from utils import BrowserManager
from utils import Logger
if __name__ == '__main__' and __package__ is None:
Logger.setup_logger()
# Read config.ini
config = ConfigParser()
confi... |
#!/usr/bin/python3
from pwncli import *
cli_script()
p:tube = gift['io']
elf:ELF = gift['elf']
libc: ELF = gift['libc']
def add(size:int):
p.sendlineafter("Choice: \n", "1")
p.sendlineafter("Size: ", str(size))
def edit(idx:int, data:(str, bytes)):
p.sendlineafter("Choice: \n", "2")
p.sendlineafter... |
"""Test cases for dual bytes/str APIs"""
import unittest
"""
The Python 2 str type conveniently permitted the creation of APIs that
could be used as either binary APIs (8-bit str in, 8-bit str out) or as
text APIs (unicode in, unicode out).
The critical enabler for this feature was the ability to define any
*consta... |
from functools import partial
from pathlib import Path
from typing import List
import numpy as np
import pandas as pd
import petab_select
import pytest
from more_itertools import one
from petab_select import ESTIMATE, Criterion, Method, Model
import pypesto.select
import pypesto.visualize.select
from pypesto.select i... |
# Copyright The PyTorch Lightning 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 agreed to i... |
import os
import re
import argparse
import torch
from PIL import Image
from torchvision import transforms
from mmcv import Config
from mmcv.runner import load_checkpoint, save_checkpoint
from model import Model
def get_parameter():
parser = argparse.ArgumentParser()
parser.add_argument("--con... |
#Class used for transfering lines to the write classes. Ex var assignments go to class Var
import Variable
import Objects
def init():
Objects.init()
def process(string):
if string[0] == "@":
Variable.process(string)
elif string[0] != "" or string[0] != "\n":
Objects.process(string)
|
#ATIVIDADE PEDIDA: (Prof.Ronaldo)####################################################################################################################################################{
#CT0111 – Décima primeira da primeira etapa ... |
from django.apps import apps
from django.test import TestCase
from django.core.management import call_command
class PopulateDbtTests(TestCase):
"""Test Module for commands that populate db for prototype"""
def setUp(self):
call_command('populate_db')
def test_populate_institute(self):
""... |
import os
import cv2
import glob
import torch
import pathlib
import argparse
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
matplotlib.use('Agg')
from utils.dataset import create_images_dict
labels... |
# -*- coding: utf-8 -*-
import os
import errno
import logging
import time
default_logger = logging.getLogger(__name__)
class Timer(object):
def __init__(self, name='-', logger=None):
self.name = name
self.logger = logger or default_logger
def __enter__(self):
self.start = time.time()... |
from typing import List
from urllib.request import urlopen
import altair as alt
from .chart import Chart, LayerChart
import json
def get_chart_spec_from_url(url: str) -> List[str]:
"""
For extracting chart specs produced by the research sites framework
"""
response = urlopen(url)
content = respons... |
from ipaddress import IPv4Network, IPv6Network
from .roa_trie import ROATrie
class IPv4ROATrie(ROATrie):
"""Trie of IPv4 CIDRs for ROAs"""
prefix_class = IPv4Network
class IPv6ROATrie(ROATrie):
"""Trie of IPv6 CIDRs for ROAs"""
prefix_class = IPv6Network
|
# Module 3 Assignment
# Amir Ahsan
myfile = open ("question.txt", "r+")
myquestion = myfile.read()
myresponse = input(myquestion)
myfile.write(myresponse)
myfile.close()
|
import bs4, requests
from urllib.parse import unquote
def searchRecipe(text, page):
result = {
'recipes': []
}
icook_search_url = 'https://icook.tw/search/'
if page == 0:
url = icook_search_url + text
else:
url = icook_search_url + text + '?page=' + str(page)
agent... |
from typing import List, NamedTuple
# TODO MCS-813 Use MaterialTuple throughout this file
class MaterialTuple(NamedTuple):
material: str
color: List[str]
UNTRAINED_COLOR_LIST = [
# Won't be used in Eval 3
]
AZURE = ("Custom/Materials/Azure", ["azure", "blue"])
BLACK = ("Custom/Materials/B... |
from unittest import TestCase
import pytest
from persiantools import characters, digits
class TestDigits(TestCase):
def test_ar_to_fa(self):
self.assertEqual(characters.ar_to_fa("السلام عليكم"), "السلام علیکم")
self.assertEqual(characters.ar_to_fa("HI ي"), "HI ی")
self.assertEqual(charac... |
# Set up the paths.
import os
import sys
sys.path.append(os.path.abspath('.'))
import themodule
def test_hallo():
assert themodule.hallo() == "hallo"
def test_nohallo():
assert themodule.hallo() != "blaat"
|
from models.model_plain import ModelPlain
class ModelPlain2(ModelPlain):
"""Train with two inputs (L, C) and with pixel loss"""
# ----------------------------------------
# feed L/H data
# ----------------------------------------
def feed_data(self, data, need_H=True):
self.L = data['L'].t... |
from random import randint
numeros = (randint(0,10),randint(0,10),
randint(0, 10),randint(0,10),
randint(0, 10))
for n in numeros:
print(f'{n} ', end='')
print('\nO maior numero sorteado e {}.'.format(max(numeros)))
print('O menor numero sorteado e {}.'.format(min(numeros)))
|
import sys
import os
from sklearn.linear_model import LinearRegression
from sklearn.grid_search import GridSearchCV
from utils.CSVHandler import CSVHandler
from utils.Preprocessor import Preprocessor
# from utils.Visualizer import Visualizer
from utils.Logger import Logger
"""
File paths
"""
data_dir = '../data/'
t... |
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional
__NAMESPACE__ = "NISTSchema-SV-IV-atomic-unsignedShort-enumeration-4-NS"
class NistschemaSvIvAtomicUnsignedShortEnumeration4Type(Enum):
VALUE_3331 = 3331
VALUE_794 = 794
VALUE_91 = 91
VALUE_5792 = 5792
VALU... |
# Binance
# https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md
# By Lari Taskula <lari@taskula.fi>
from exchange import Exchange, CURRENCY
class Binance(Exchange):
name = "Binance"
code = "binance"
ticker = "https://www.binance.com/api/v1/ticker/24hr"
discovery = "... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from stw import SupervisedTermWeightingWTransformer
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.svm import LinearSVC
from sklearn.metrics import accuracy_score, recall_score, f1_score
train = pd.rea... |
# 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 V1KubeVi... |
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
urlpatterns = [
url(r"^l(?P<line_pk>\d+)/p(?P<part_pk>\d+)/modifications/add/$", views.CreateStoryPart.as_view(view_mode="mod"), name="story_detail_line_part_modification_add"),
url(r"^l(?P<line_pk>\d+... |
#-*- coding: utf8 -*-
from flask import Flask, render_template, make_response, session, redirect, url_for, escape, request,jsonify,Response
import __builtin__, datetime
from dateutil import parser
import time as T, networkx as x, json # json.dumps
import cPickle as pickle, string
from SPARQLWrapper import SPARQLWrap... |
# -*- coding: utf-8 -*-
"""Parts-of-speech tagger implementations."""
from __future__ import absolute_import
import nltk
import textblob.compat
import textblob as tb
from textblob.en import tag as pattern_tag
from textblob.decorators import requires_nltk_corpus
from textblob.base import BaseTagger
class PatternTagg... |
# Generated by Django 2.1.5 on 2019-01-10 21:18
from django.db import migrations
import os
import csv
#Locate csv file to import
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CAT_FILE = os.path.join(BASE_DIR, 'art_data.csv')
def insert_categories(apps, schema_editor):
Category = apps.get_model('core', 'C... |
"""CFNgin hook for cleaning up resources prior to CFN stack deletion."""
# pylint: disable=unused-argument
# TODO move to runway.cfngin.hooks on next major release
import logging
LOGGER = logging.getLogger(__name__)
def delete_param(context, provider, **kwargs):
"""Delete SSM parameter."""
parameter_name = k... |
import numpy as np
from imantics import Polygons, Mask
import cv2
from csv import reader
import os
import json
image_folder = "C:\\Users\\Admin\\Documents\\open-images-1\\train_resized"
coco_dict = {}
coco_dict['images'] = []
coco_dict['annotations'] = []
coco_dict['categories'] = []
with open('C:\\Users\\Admin\\Docu... |
from typing import Tuple
import numpy as np
from shapely.geometry import LineString, Polygon
def _get_boundingbox(centroid: np.ndarray, yaw: float, extent: np.ndarray) -> Polygon:
x, y = centroid[0], centroid[1]
sin, cos = np.sin(yaw), np.cos(yaw)
width, length = extent[0] / 2, extent[1] / 2
x1, y1 ... |
valorhora= 20000
horastrabajadas=120
horasextra=10
valorhoraextra=((valorhora*0.25)+valorhora)
recibidoporhoraextra=(valorhoraextra*horasextra)
sueldobase=(valorhora*horastrabajadas)
print("El sueldo base del empleado es de:", str(sueldobase),"pesos.")
deducciones=(sueldobase*0.14)
Sueldomenosdeducciones=(sueldobase-de... |
"""Support for Alexa skill service end point."""
import logging
import voluptuous as vol
from homeassistant.const import CONF_NAME
from homeassistant.core import callback
from homeassistant.helpers import config_validation as cv, entityfilter
from . import flash_briefings, intent, smart_home_http
from .const import ... |
"""
This solver implements the double spike equations from the
double-spike toolbox. Other places too, but that's the most popular
reference. Code by Alex Tennant.
Questions to alexpattennant@gmail.com
"""
import numpy as np
from numpy import warnings
from scipy.optimize import fsolve
from scipy.optimize import least_s... |
import numpy as np
import pytest
from ..flag import (
slice_full_edge_masked,
slice_has_flags,
compute_masked_fraction)
@pytest.mark.parametrize(
'inds',
[(range(10), 0), # left
(range(10), -1), # right
(0, range(10)), # top
(-1, range(10)) # bottom
])
def test_slice_full... |
# Copyright 2019, OpenTelemetry Authors
#
# 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 i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import unittest
from py_privatekonomi.utilities.common import format_time_struct, is_unicode
from py_privatekonomi.utilities import helper
from py_privatekonomi.core import loader
from py_privat... |
import yaml
from fed_exchange_weight_bias.client import Clients
from fed_exchange_weight_bias.server import Server
from fed_exchange_weight_bias.utils.logger import initialize_logging, create_federated_logger
with open("parameters.yaml", mode='r', encoding="utf-8") as f:
params = yaml.load(f, Loader=yaml.FullLoad... |
"""Defines MeltanoInvoker."""
import os
import subprocess
import sys
from pathlib import Path
from .project import Project
from .project_settings_service import ProjectSettingsService, SettingValueStore
MELTANO_COMMAND = "meltano"
class MeltanoInvoker:
def __init__(self, project, settings_service: ProjectSettin... |
import logging
import uuid
from abc import ABCMeta, abstractmethod
from typing import Optional
from great_expectations.exceptions import InvalidKeyError, StoreBackendError, StoreError
logger = logging.getLogger(__name__)
class StoreBackend(metaclass=ABCMeta):
"""A store backend acts as a key-value store that ca... |
import logging
import uuid
import psutil
from datetime import datetime
import os
from flask import signals
from pythonapm.metrics.gauge import Gauge
from pythonapm.metrics.histogram import Histogram
from pythonapm.surfacers import Surfacers
from pythonapm.surfacers.log import LogSurfacer
logger = logging.getLogger(... |
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
if root is None:
return False
if root.left is None and root.ri... |
from testcases import (
TestServerTestCase,
get_client
)
from django.core.management import call_command
class OrderByTestCase(TestServerTestCase):
def setUp(self):
self.start_test_server()
self.client = get_client()
call_command('loaddata', 'small_data.json')
def tearDown(se... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
__author__ = "Thomas Kaulke"
__email__ = "kaulketh@gmail.com"
__maintainer__ = "Thomas Kaulke"
__status__ = "Production"
import datetime
from rpi_ws281x import *
from config import LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_BRIGHTNESS, \
LED_INVERT, LED_NIGHT_CUT_OF... |
# -*- coding: utf-8 -*-
# (c) 2017 Andreas Motl <andreas@ip-tools.org>
import celery
from uspto.peds.client import UsptoPatentExaminationDataSystemClient
from uspto.util.tasks import GenericDownloadTask, AsynchronousDownloader
class UsptoPatentExaminationDataSystemDownloadTask(GenericDownloadTask):
name = 'uspto.p... |
import argparse
import textwrap
from datetime import date
version = '1.0.11'
today = date.today()
class CustomHelpFormatter(argparse.HelpFormatter):
"""
This class changes the way the help output is displayed
"""
def _format_action_invocation(self, action):
# This removes metvar after short... |
import numpy as np
from scipy.signal import butter, lfilter, filtfilt, lfilter_zi
import copy
from P_extend import k_extend
def compare(A,B):
return np.sum(A-B)
def filter_highk(k,P_in,start,end):
P_out=copy.deepcopy(P_in)
# start = k where you want to start cross fad
# end = k where you want to end the cross ... |
import sys
if __name__ == "__main__":
def plus_one(s):
ss = s.strip()
sp1 = str(1 + int(ss))
print(
"(+1) {} => {}".format(ss, sp1),
file=sys.stderr
)
return sp1
while True:
x = input()
if x:
print(plus_one(x))
|
from flask import Flask
import tensorflow as tf
import pandas as pd
import numpy as np
import os
import json
import sys
from tensorflow.keras.models import model_from_json
#path = os.path.join(sys.path[0], "log\DA_dnn_10-4.json")
#print(path)
# inputData = np.array([4,9,5,9.5,2.3,3.4,0,45])
def runDaylightPrediction... |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import time
from msal.application import PublicClientApplication
from azure.core.credentials import AccessToken
from azure.core.exceptions import ClientAuthenticationE... |
# Copyright The PyTorch Lightning 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 agreed to i... |
from __future__ import annotations
from aiohttp import web, ClientSession
from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType
from homeassistant.components.http import KEY_AUTHENTICATED, HomeAssistantView
import logging
_LOGGER = logging.getLogger(__name__)
DOMAIN = "image... |
"""The mqtt_json component."""
|
# -*- coding: utf-8 -*-
class CCSDKException(Exception):
pass
class CCSDKInvalidParamException(CCSDKException):
pass
class CCServerException(CCSDKException):
pass
|
from abc import ABC
from pycurb.time_rule import TimeRule
from pycurb.utils import to_camelcase
class PyCurbObject(ABC):
fields = []
@classmethod
def from_dict(cls, d):
kwargs = {}
for a in cls.fields:
kwargs[a] = d.get(to_camelcase(a))
return cls(**kwargs)
def... |
# CacheIntervals: Memoization with interval parameters
#
# Copyright (C) Cyril Godart
#
# This file is part of CacheIntervals.
#
# @author = 'Cyril Godart'
# @email = 'cyril.godart@gmail.com'
name = 'CacheIntervals'
import sys
sys.path.append('.')
from .MemoizationIntervals import MemoizationWithIntervals |
import logging
logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S')
|
# -*- encoding: UTF-8
from __future__ import unicode_literals
import os
import sys
import tempfile
import unittest
import zipfile
import six
from fs import zipfs
from fs.compress import write_zip
from fs.opener import open_fs
from fs.opener.errors import NotWriteable
from fs.test import FSTestCases
from fs.enums imp... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 3 10:07:36 2020
This script is for detection IDH and TERTp mutation in gliomas.
1D-CNN is the approach that we use in this study.
This study was submitted to ISMRM 2021
Abdullah BAS
abdullah.bas@boun.edu.tr
BME Bogazici University
Istanbul / Usk... |
import numpy as np
import torch
import torch.nn as nn
from scipy import linalg
from tqdm import tqdm
from basicsr.archs.inception import InceptionV3
def load_patched_inception_v3(device='cuda',
resize_input=True,
normalize_input=False):
# we may not res... |
import unittest
from brainpy import IsotopicDistribution, isotopic_variants, calculate_mass, neutral_mass, _has_c, Peak
if _has_c:
from brainpy.brainpy import _IsotopicDistribution
class TestIsotopicDistribution(unittest.TestCase):
def test_neutral_mass(self):
hexnac = {'H': 13, 'C': 8, 'O': 5, 'N':... |
# Remove() -> Remove o primeiro elemento encontrado pelo valor específicado.
lista_4 = [10,9,8,7,5,6,4,2,3,1,2,3]
print(lista_4)
lista_4.remove(2)
print(lista_4)
|
from django.contrib import admin
from .models import WhatsappChatMessages, WhatsappMediaMessages
admin.site.register(WhatsappChatMessages)
admin.site.register(WhatsappMediaMessages) |
#!/usr/bin/python
from __future__ import print_function
import roslib; roslib.load_manifest('faa_data_processing')
import rospy
import argparse
import os
import numpy
import numpy.lib.recfunctions as recfunctions
import csv
from faa_utilities import FindData
from faa_utilities import FileTools
FILE_TOOLS = FileTools(... |
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013,2016 Contributor
#
# 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... |
class Model(object):
'''
Subclasses must specify id_field and base_uri as class variables
'''
id_field = None
base_uri = None
def __init__(self, raw_json, client):
if not self.__class__.id_field:
raise ValueError('Cannot construct Model subclass without id_field set')
... |
import multiprocessing
from .recursive_merge_sort import copy_merge as merge
from .recursive_merge_sort import recursive_merge_sort as merge_sort
def parallel_merge_sort(vector, count_slice=0, self_id=1, return_dict=None):
if return_dict == None:
manager = multiprocessing.Manager()
return_dict = m... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
if os.path.exists('.env'):
# print('reading .env..')
for line in open('.env'):
var = line.strip().split('=')
if len(var) == 2:
os.environ[var[0]] = var[1]
from app import create_app, db
from flask_script import Manager
from fla... |
# Return the number of open edges on a sphere.
#
import pyvista
sphere = pyvista.Sphere()
sphere.n_open_edges
# Expected:
## 0
#
# Return the number of open edges on a plane.
#
plane = pyvista.Plane(i_resolution=1, j_resolution=1)
plane.n_open_edges
# Expected:
## 4
|
import datetime
from flask.ext.bcrypt import generate_password_hash
from flask.ext.login import UserMixin
from peewee import *
DATABASE = SqliteDatabase('journal.db')
class User(UserMixin, Model):
username = CharField(unique=True)
email = CharField(unique=True)
password = CharField(max_length=100)
jo... |
import sys
import logging
import getpass
import time
from irida_staramr_results import util
def user_credentials(username, password):
"""
Validates username and password inputted as arguments.
If either of the two are not specified the user will be prompted.
:param username: username of the IRIDA acc... |
# ---------------------------------------------------------------------
# Ericsson.MINI_LINK.get_interfaces
# ---------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
... |
from civicboom.model.meta import Base, CacheChangeListener
from sqlalchemy import Column, ForeignKey
from sqlalchemy import String, Unicode, UnicodeText
from sqlalchemy import Integer, DateTime, Boolean
from sqlalchemy import func
from sqlalchemy.orm import relationship, backref
from sqlalchemy.schema import DDL
from ... |
"""
Command handler module for GMC
"""
import sys
import importlib
import os
from gmc.conf import ENVIRONMENT_VARIABLE
from gmc.conf import settings
def execute_from_command_line(argv=None, quiet=False):
"""
try to load a module specified in the given path.
Set GMC_SETTINGS_MODULE environment variable
... |
from setuptools import setup, find_packages
setup(
name="rotten_tomatoes_client",
packages=find_packages(exclude=['tests*']),
install_requires=["requests"],
version="0.0.3",
description="Rotten Tomatoes Client",
author="Jae Bradley",
author_email="jae.b.bradley@gmail.com",
url="https://github.com/jaebra... |
#
# PySNMP MIB module CISCO-ST-TC (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ST-TC
# Produced by pysmi-0.3.4 at Mon Apr 29 17:36:22 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, 0... |
import matplotlib.pyplot as plt
plots_path = "./plots/"
def plot_points(x,y,xlabel,ylabel,filename):
plt.plot(x, y)
plt.ylabel(ylabel)
plt.xlabel(xlabel)
plt.savefig(plots_path+filename)
plt.close()
def cluster_purity(clusterer,data,classes,debug=False):
l = len(list(data))
no_of_c... |
# coding: utf8
from __future__ import unicode_literals
from .cli.info import info as cli_info
from .glossary import explain
from .about import __version__
from . import util
def load(name, **overrides):
depr_path = overrides.get('path')
if depr_path not in (True, False, None):
util.deprecated(
... |
import os
from datetime import datetime
def list_sub_dirs(dir_path):
if not os.path.exists(dir_path):
raise RuntimeError("invalid dir path.")
if not os.path.isdir(dir_path):
raise RuntimeError("invalid dir path.")
sub_dirs = []
sub_files = os.listdir(dir_path)
for sub_file_name i... |
# https://blog.csdn.net/a19990412/article/details/85139058
# LSTM实现股票预测--pytorch版本【120+行代码】
'''
模型假设
我这里认为每天的沪深300的最高价格,是依赖于当天的前n天的沪深300的最高价。
然后用RNN的LSTM模型来估计(捕捉到时序信息)。
让模型学会用前n天的最高价,来判断当天的最高价。
'''
# depends
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import torch
import torch.nn as nn
import... |
import requests
from nose.plugins.attrib import attr
@attr('webservice')
def test_rest_api_responsive():
stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "FPLX": "MEK"}, "name": "ME... |
# Copyright (c) 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.
{
'includes': [
'auto_login_parser.gypi',
'components_tests.gypi',
'navigation_interception.gypi',
'visitedlink.gypi',
'web_content... |
"""Game Entities.
"""
class GamePlayer(object):
def __init__(self, symbol="", name="", team=0, loyalty=0, energy=0, score=0, active="ACTIVE", coord=(0, 0), speed=[]):
self.symbol = symbol
self.name = name
self.team = team
self.loyalty = loyalty
self.energy = energy
... |
from flask_restful import Resource
from appcode.models.mall import MallModel
class Mall(Resource):
def get(self, name):
mall = MallModel.find_by_name(name)
if mall:
return mall.json()
return {"message": "Mall not found..."}, 404
def post(self, name):
if MallModel.f... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'FeedPage'
db.delete_table('rss_feeds_feedpage')
# Deleting model 'FeedXML'
... |
# Author: Agyeya Mishra
# Institute: Delhi Technological University (formerly, Delhi College of Engineering)
# Language: Python
# Version: 3.x
# Environment: PyCharm
# This script plots Mohr's Circle when given the two-dimensional state of stress.
#Importing libraries
#
# Numpy is a general-purpose array-processing... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.