content
stringlengths
5
1.05M
"""Implementation of Valve learning layer 2/3 switch.""" # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation. # Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer. # Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd. # Copyright (C) 2015--2018 The Contributors # # L...
import sys from cpu import CPU from assembler import assemble from cpu.pipeline import fetch_unit, decode_unit, execute_unit, writeback_unit from Benchmarks.memory_initialisation import INITIALISATION from cpu.Memory import MEMORY if len(sys.argv) < 2: sys.exit() else: debug = False if len(sys.argv) > 2: ...
# # @lc app=leetcode id=238 lang=python3 # # [238] Product of Array Except Self # # @lc code=start from typing import List class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: """Calculate an array of the products for every element in the array except the one at the same ind...
""" This example shows how to use RegEX to collect information in the logfile, in particular it shows how to get the modulethe number of CE for each events and add this information to all systems ending their evolution as binary of compact objects The output files are stored in ../sevn_outputs_example/sevn_output_singl...
''' For the masked peptides, see if we can find them in the MS data; ''' import glob, sys, os, numpy from glbase3 import * import matplotlib.pyplot as plot sys.path.append('../') import shared res = {} all_matches = glload('results_gene.glb') all_te_transcripts = glload('../te_discovery/te_transcripts/transcript_t...
import spacy nlp = spacy.load("de_core_news_sm") text = "Apple wurde 1976 von Steve Wozniak, Steve Jobs und Ron Wayne gegründet." # Verarbeite den Text doc = ____ for token in doc: # Greife auf den Text, die Wortart und die Dependenzrelation des Tokens zu token_text = ____.____ token_pos = ____.____ ...
from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Informe(object): def setupUi(self, Informe): Informe.setObjectName("Informe") Informe.resize(840, 485) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("images/Qt.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off) Informe.setWind...
import os from decouple import config class Config: SECRET_KEY = 'example' class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = 'mysql+mysqlconnector://root:@localhost/project_web2' SQLALCHEMY_TRACK_MODIFICATIONS = False MAIL_SERVER = 'smpt.googlemail.com' MAIL_PORT = 587 ...
from jina.drivers.rank import Chunk2DocRankDriver from jina.executors.rankers import Chunk2DocRanker, MaxRanker, MinRanker from jina.proto import jina_pb2 from tests import JinaTestCase class MockLengthRanker(Chunk2DocRanker): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ...
from blob import Context from handlers.decorators import OsuEvent from packets.OsuPacketID import OsuPacketID from packets.Reader.PacketResolver import PacketResolver from packets.Builder.index import PacketBuilder from typing import TYPE_CHECKING if TYPE_CHECKING: from objects.Player import Player # client pac...
from django.db import models from django.utils import timezone from bs4 import BeautifulSoup class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() _snippet = models.TextField(blank=True) _date_posted = models.DateTimeField(default=timezone.now) def __str_...
import matplotlib.pyplot as plt from matplotlib import style style.use('ggplot') import pandas as pd import numpy as np import math import random a1=[] a2=[] for i in range(100): a1.append(random.randint(5,60)) a1.append(random.randint(-56,-1)) a2.append(random.randint(0,40)) a2.append(random.randint(-...
#!coding:utf-8 from sys import path as sys_path from os import path as os_path sys_path.append(os_path.abspath(os_path.join(os_path.dirname(__file__), "../"))) import autoargparse cmd = autoargparse.cmd("cmd deco mark test.") @cmd.mark(run_order=4) @cmd.args("-a") def a(x): print(x) @cmd.mark(run_order=1) @...
import json import yaml def test_metrics_diff_simple(tmp_dir, scm, dvc): def _gen(val): tmp_dir.gen({"m.yaml": str(val)}) dvc.run(cmd="", metrics=["m.yaml"], single_stage=True) dvc.scm.add(["m.yaml.dvc"]) dvc.scm.commit(str(val)) _gen(1) _gen(2) _gen(3) expected ...
# -*- coding: utf-8 -*- '''Common classes module ''' from __future__ import ( absolute_import, division, print_function, unicode_literals, with_statement, ) import importlib import inspect import logging import sys import threading import time import dateutil.parser as du_parser LOG = logging....
from itertools import product def linear_evaluation_imagenet_experiments(): dataset = "imagenet" dataset_dir = "<YOUR DATASET DIR HERE>" arg_pool = "ssp_linear_evaluation" model = "SSLResNet50" round_budget = 10000 rounds = 8 init_pool_size = 30000 subset_labeled = 50000 subset_unla...
# # PySNMP MIB module ASCEND-CHASSIS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-CHASSIS-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:26:06 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
#!/usr/bin/env python3 __author__ = "Mert Erol" #import os # This signature is required for the automated grading to work. # Do not rename the function or change its list of parameters! def absolute_value(a): # implement this function return abs(a) # This signature is required for the automated grading to wo...
import ctypes import os from multi_tools import config, common, functional from types import FunctionType if not os.path.exists(config.Cpp.APPDATA): try: os.mkdir(config.Cpp.APPDATA) except FileNotFoundError: pass def search_dll(name: str) -> ctypes.CDLL: """ Utility for searching .d...
# Test plotting functions so that we know they'll run without crashing. # Does not check the actual contents of the plots, because it'd be too fiddly and fragile. import os import random from autumn.tools.db import Database from autumn.tools.db.uncertainty import calculate_mcmc_uncertainty from autumn.tools.plots.cali...
from __future__ import division import numpy as np from scipy.constants import mu_0, pi, epsilon_0 from scipy.special import erf from SimPEG import utils import warnings def hzAnalyticDipoleF(r, freq, sigma, secondary=True, mu=mu_0): """ The analytical expression is given in Equation 4.56 in Ward and Hohmann,...
import django.contrib.auth.views from django.urls import path, include from . import views urlpatterns = [ path('', views.index, name='index'), path('vehicles/', views.vehicles, name='vehicles'), path('vehicles/<int:vehicle_id>', views.vehicle, name='vehicle'), path('search_vehicles', views.search_vehi...
from __future__ import unicode_literals from django.apps import AppConfig class SponsorshipConfig(AppConfig): name = "conf_site.sponsorship"
import json import os from custom.openlmis.api import OpenLMISEndpoint, RequisitionDetails class MockOpenLMISEndpoint(OpenLMISEndpoint): def create_virtual_facility(self, facility_data): return True def update_virtual_facility(self, id, facility_data): return True def submit_requisition...
from dataclasses import dataclass from datetime import date, datetime from typing import List from marshmallow import Schema, fields @dataclass class DataclassObject(): str_field: str int_field: int float_field: float boolean_field: bool list_field: List date_field: date datetime_field: d...
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseNotFound, HttpResponseRedirect from django.template import RequestContext, loader from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from dogs.models import * from...
# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries # SPDX-License-Identifier: MIT from adafruit_crickit import crickit # crickit setup ss = crickit.seesaw # pin for photo interrupter photo = crickit.SIGNAL1 ss.pin_mode(photo, ss.INPUT_PULLUP) # dc motor setup motor = crickit.dc_motor_1 # party par...
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from ...
import os import keras import numpy as np from keras import regularizers from keras.models import Model, Input, load_model from keras.losses import categorical_crossentropy, mean_squared_error from keras.layers import ( Add, Dense, Conv2D, Reshape, Flatten, BatchNormalization, Activation ) from config import ( ...
"""The |pydwf.core.dwf_library| module implements a single class: |DwfLibrary|.""" import sys import ctypes from pydwf.core.auxiliary.dwf_function_signatures import dwf_function_signatures, dwf_version as expected_dwf_version from pydwf.core.auxiliary.exceptions import PyDwfError, DwfLibraryError from pydwf.core.auxi...
#!/usr/bin/python # -------------------------- IMPORTS -------------------------- # import numpy as np import augment as ag import parallel_augment as pa # -------------------------- LOAD DATASET -------------------------- # ''' Here we load the dataset. The functions we provide receive as in...
from app import db from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship class Stock(db.Model): __tablename__ = 'stocks' id = db.Column(db.Integer, primary_key=True) symbol = db.Column(db.String(5), index=True, unique=True) name = db.Column(db.String(35), index=True, unique=True) exchange = ...
from .element import Element class TableRow(Element): """ Element class to represent HTML tr """ def __iter__(self): """ Return all cells in row as an iterable """ return iter(self.cell_elements({'css': 'th,td'})) def get_cells(self, identifier, operation=None): ...
class temp_disconnect_signal(): """ Temporarily disconnect a model from a signal """ def __init__(self, signal, receiver, sender, dispatch_uid=None): self.signal = signal self.receiver = receiver self.sender = sender self.dispatch_uid = dispatch_uid def __enter__(self): ...
""" Testronyx Flask app factory """ __author__ = 'kkennedy' import flask from injector import Module, singleton, provides from . import api, rpc class FlaskAppModule(Module): @singleton @provides(flask.Flask) def create_app(self): """ Testronyx Flask App Factory :return: flask.F...
from typing import Protocol, Optional class IBinanceSpotMarketDataChannelCreator(Protocol): """Binance spot market data socket channel creator.""" def create_agg_trades_channel(self, symbol: str) -> str: """Creates agg trade channel. Args: symbol (str) Returns: ...
import mysql.connector db = mysql.connector.connect( host="localhost", user="root", passwd="tvbtvb123", database="recipes" ) mycursor = db.cursor() # mycursor.execute("CREATE DATABASE recipes") # mycursor.execute("SHOW DATABASES") # mycursor.execute("CREATE TABLE entries (Name VARCHAR(255)...
# Nested Lists and Dictionaries def run(): my_list = [1, "Hello", True, 4.5] my_dict = { "firstname": "Mauricio", "lastname": "Valadez" } super_list = [ {"firstname": "Mauricio", "lastname": "Valadez"}, {"firstname": "Carlos", "lastname": "García"}, {"firstname":...
# Copyright (C) 2020 FireEye, Inc. All Rights Reserved. import abc class FeatureExtractor(object): """ FeatureExtractor defines the interface for fetching features from a sample. There may be multiple backends that support fetching features for capa. For example, we use vivisect by default, but also...
#!/usr/bin/python # -*- coding: utf-8 -*- import os import unittest from mock import patch, call from modules.data import get_models from modules.links import helpers from testing import TrottoTestCase ShortLink = get_models('links').ShortLink class TestUtilityFunctions(TrottoTestCase): def test__encode_ascii...
import urllib.request import zipfile import os url = 'https://syncandshare.lrz.de/dl/fiVRr3EeLiGxcoHXmW5yoWHq/models.zip' print('Dlownloaing models (This might take time)') urllib.request.urlretrieve(url, 'models.zip') with zipfile.ZipFile('models.zip', 'r') as zip_ref: print("extracting models") zip_ref.extra...
# coding: utf-8 from __future__ import division from __future__ import print_function from __future__ import unicode_literals import sys import os import numpy as np import time import random import torch import torch.nn.functional as F try: import cPickle as pickle except ImportError: import pickle from modifi...
from requests.adapters import HTTPAdapter from requests.packages.urllib3.poolmanager import PoolManager import ssl class TransportAdapter(HTTPAdapter): def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager(num_pools=connections, ...
'''create_rg.py - Create an Azure resource group''' import json import sys import azurerm # Load Azure app defaults try: with open('azurermconfig.json') as config_file: CONFIG_DATA = json.load(config_file) except FileNotFoundError: print("Error: Expecting azurermconfig.json in current folder") sys...
import os from nose.plugins.skip import SkipTest if os.name == "nt": raise SkipTest("Skipped on Windows.") import libmproxy.console.help as help class DummyLoop: def __init__(self): self.widget = None class DummyMaster: def __init__(self): self.loop = DummyLoop() def make_view(self...
from aws_cdk import aws_ec2 from aws_cdk import core import random import string class GlobalArgs(): """ Helper to define global statics """ OWNER = "Redshift POC SSA team" ENVIRONMENT = "development" REPO_NAME = "redshift-demo" VERSION = "2021_03_15" class VpcStack(core.Stack): def...
import networkx as nx from ditto.network.network import Network from ditto.models.power_source import PowerSource from ditto.models.load import Load """ This uses the DiTTo Network functionality to check that there is a path from a load to the source node. Considers switch states. Transformer consistency checked else...
import graphene from flask_graphql_auth import mutation_jwt_required, get_jwt_identity from app.models import User, Idea from app.schema.unions import ResponseUnion from app.schema.fields import ResponseMessageField from app.schema.utils import idea_activity_logger class VoteIdeaMutation(graphene.Mutation): cla...
## @ingroup Attributes-Propellants # Liquid H2 # # Created: Unk 2013, SUAVE TEAM # Modified: Apr 2015, SUAVE TEAM # Feb 2016, M. Vegh # Jan 2018, W. Maier # ---------------------------------------------------------------------- # Imports # -----------------------------------------------------...
import os, time import azure.cognitiveservices.speech as speechsdk from msrest.authentication import CognitiveServicesCredentials from azure.cognitiveservices.vision.computervision import ComputerVisionClient ''' This sample uses the Computer Vision and Speech Service SDKs from Cognitive Services. With local images o...
#!/usr/bin/env python3 # Disable 'Module name "X4FProjector" doesn't conform to snake_case naming # style (invalid-name)' # pylint: disable=invalid-name """Main function for the project. See the help message.""" import argparse import logging import os import sys import exporters import file_loaders import lang imp...
from modules.exceptions import ValidationException from modules.exceptions import NoArgsException class Validator: def __init__(self, args): self.args = args def validate(self): self._check_at_least_one_arg_provided() self._check_number_is_positive() self._check_only_one_hash_...
r""" Cluster wave breaking events in time and space. This script can use the results of naive_wave_breaking_detector directly but this is not recommended. It is recommended that you narrow down the candidates for clustering using predict_active_wave_breaking or another tool. For help: python cluster_wave_break...
# Copyright (c) 2019, NVIDIA CORPORATION. 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 applic...
""" Salt compatibility code """ # pylint: disable=unused-import import sys # The ipaddress module included in Salt is from Python 3.9.5. # When running from Py3.9.5+ use the standard library module, use ours otherwise if sys.version_info >= (3, 9, 5): import ipaddress else: import salt.ext.ipaddress as ipaddre...
#!/usr/bin/python ''' Ansible module to transfer files to Cisco IOS devices. ''' from ansible.module_utils.basic import * from netmiko import ConnectHandler, FileTransfer def main(): ''' Ansible module to transfer files to Cisco IOS devices. ''' module = AnsibleModule( argument_spec=dict( ...
class Solution: def XXX(self, digits: List[int]) -> List[int]: a = -1 for b in digits: a += 1 digits[a] += 1 while True: for c in digits: if c == 10: d = digits.index(10) digits[d] = 0 ...
# -*- coding: utf-8 -*- import os import time from threading import Lock, Thread from .packet import EmotivExtraPacket from .python_queue import Queue from .sensors import sensors_mapping from .util import get_quality_scale_level, system_platform class EmotivOutput(object): """ Write output to console. ...
print("Hello DecisionTree!") import graphviz with open('tree.dot') as f: dot_graph = f.read() graph = graphviz.Source(dot_graph) graph.render(view=True)
# Copyright (C) 2019-2020, Therapixel SA. # All rights reserved. # This file is subject to the terms and conditions described in the # LICENSE file distributed in this package. """Test that the config functionalities of the pacsanini package can be correctly accessed from the command line. """ import json import os im...
""" Physical or chemical model-based analysis of data Submodules ---------- .. autosummary:: :toctree: _autosummary """ from . import utils from .utils import * __all__ = utils.__all__
import os import sys from setuptools import find_packages, setup from djangobot import __version__ # README.md is long description readme = os.path.join(os.path.dirname(__file__), 'README.md') setup( name='djangobot', version=__version__, url='https://github.com/djangobot/djangobot', author='Scott Bur...
#!/usr/bin/env python #import peewee as pw #from peewee import * #from ifc.ta import get_series import ifc.ta as ta print dir(ta) x = ta.get_series("TGT", "2016-04-17", "2017-04-17") x.run_calculations() x.trim_fat() print x.df
"""Main application.""" import os from flask import Flask, render_template, request app = Flask(__name__) ### # Routing ### @app.route('/') def home(): """Render the actual cv page.""" return render_template('home.html') ### # General functions ### @app.errorhandler(404) def page_not_found(error): "...
from .strategy import * from .acc_variance import *
from __future__ import absolute_import from clims.legacy.service.dilution.service import DilutionService from clims.legacy import UnitConversion from clims.legacy.repository import LegacyRepository, FileRepository from clims.legacy.utils import lazyprop from clims.legacy import LegacySession from clims.legacy.service i...
from flask import Flask app = Flask(__name__) app.secret_key="secret key"
def fcomb(n, k): ''' Compute the number of ways to choose k elements out of a pile of n. Use an iterative approach with the multiplicative formula: \frac{n!}{k!(n - k)!} = \frac{n(n - 1)\dots(n - k + 1)}{k(k-1)\dots(1)} = \prod{i = 1}{k}\frac{n + 1 - i}{i} Also rely on the symmetry: C_n^k ...
# vim:ts=4:sw=4:et: # Copyright (c) Facebook, Inc. and its affiliates. # # 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 b...
import scipy.optimize import torch import torch.nn.functional as F import neuralnet_pytorch as nnt def hungarian_loss(predictions, targets, thread_pool): # predictions and targets shape :: (n, c, s) predictions, targets = outer(predictions, targets) # squared_error shape :: (n, s, s) squared_error = F...
# TCopyright 2013 Big Switch Networks, 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 # # Unles...
from django import template from accounts.queries import get_child_eligibility_for_study register = template.Library() @register.simple_tag def child_is_valid_for_study(child, study): return get_child_eligibility_for_study(child, study)
# coding: utf-8 from .admin_objects import * from . import cmdline
from kirby.experiment import Experiment from kirby.qa_model import QAModel from kirby.run_params import RunParams data_file = "data/augmented_datasets/pickle/description_qa_knowledge.pkl" run_params = RunParams( run_name="description_qa_knowledge_20", debug=False, pretrained=True, data_files=data_file,...
# Classes to read and write CMIF video files. # (For a description of the CMIF video format, see cmif-file.ms.) # Layers of functionality: # # VideoParams: maintain essential parameters of a video file # Displayer: display a frame in a window (with some extra parameters) # BasicVinFile: read a CMIF video file # Basic...
#!/usr/bin/env python # -*- coding: utf-8 -*- # $Id: IEMAllInstructionsPython.py 67072 2017-05-25 08:26:51Z vboxsync $ """ IEM instruction extractor. This script/module parses the IEMAllInstruction*.cpp.h files next to it and collects information about the instructions. It can then be used to generate disassembler t...
import urllib.parse import requests import discord import os import time from discord.ext import commands class other(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def shop(self, ctx): embed = discord.Embed(title="Fortnite Item...
import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import unittest from engine import model from engine import utils from engine import crypto as cry from engine import pwd_utils class TestEngine(unittest.TestCase): def setUpClass(): TestEngine.netrcfile ...
import os from string import whitespace as WHITESPACE def try_remove_file(path: str) -> None: try: os.unlink(path) except OSError: if os.path.exists(path): # TODO - use the logger print(f'Error: could not unlink file at path {path}') def remove_whitespace(string: str) -...
# -*- encoding:utf-8 -*- # Copyright (c) Alibaba, Inc. and its affiliates. import logging import tensorflow as tf from google.protobuf import text_format from easy_rec.python.utils import config_util from easy_rec.python.utils import fg_util from easy_rec.python.utils import test_utils if tf.__version__ >= '2.0': ...
import logging import colander from cornice.validators import colander_validator from pyramid import httpexceptions from pyramid.security import NO_PERMISSION_REQUIRED from kinto.core import Service, errors from kinto.core.errors import ErrorSchema from kinto.core.resource.viewset import CONTENT_TYPES from kinto.core...
'''Repository''' import json from domain.mining import Miner class MinerRepository(object): """repository for miners""" def readminers(self, file_name): with open(file_name, encoding='utf-8-sig') as config_file: jsonarray = json.loads(config_file.read()) miners = [Miner(**k) for k ...
import time import numpy as np import pytest from ocs.ocs_twisted import Pacemaker def test_quantized(): """ Tests that Pacemaker forces regular sampling rate when quantize=True. """ sample_freq = 5 pm = Pacemaker(sample_freq, quantize=True) times = [] for i in range(10): pm.sleep(...
import json import datetime from sqlalchemy.ext.declarative import DeclarativeMeta class AlchemyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj.__class__, DeclarativeMeta): # an SQLAlchemy class return obj.__json__() elif isinstance(obj, (datetime.date...
import pickle import numpy as np from scipy import stats import os import matplotlib.pyplot as plt import random import edges_and_nodes_creation indice_de_confiance_1 = 10 indice_de_confiance_2 = 3 indice_de_confiance_3 = 0.1 indice_de_confiance_4 = 4 indice_de_confiance_5 = 0.2 indice_de_confiance_7 = ...
# -*- coding: utf-8 -*- # # Copyright (C) 2014 Mika Mäenpää <mika.j.maenpaa@tut.fi>, # Tampere University of Technology # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation...
from Tests.test_variables import * from Tests.tests_arithmetic import *
import tempfile from unittest.mock import MagicMock from unittest.mock import patch from cauldron import environ from cauldron import writer @patch('time.sleep') @patch('cauldron.writer.attempt_file_write') def test_write_file(attempt_file_write: MagicMock, sleep: MagicMock): """Should successfully write without...
# Generated by Django 2.1.7 on 2019-03-18 22:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('molecules', '0002_auto_20190228_1107'), ] operations = [ migrations.AddField( model_name='ligand', name='pdb_id', ...
from distutils.command.build_scripts import first_line_re from pprint import pp from tensorflow.keras.layers import * from tensorflow.keras.models import * from tensorflow.keras import backend as K from tensorflow.keras.optimizers import * from tensorflow.keras import backend as K import tensorflow as tf import h5py as...
#!/usr/bin/env python3 # # Copyright 2021 Graviti. Licensed under MIT License. # """Transform3D. :class:`Transform3D` contains the rotation and translation of a 3D transform. :attr:`Transform3D.translation` is stored as :class:`.Vector3D`, and :attr:`Transform3D.rotation` is stored as `numpy quaternion`_. .. _numpy ...
from flask import Flask, render_template, request, url_for, redirect, session, jsonify, Response, g from flask_cors import CORS from app import app import makedata import os @app.route('/',methods=['GET']) def index(): return render_template('index.html') @app.route('/',methods=['POST']) def run(): inputPath ...
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-09-25 12:18 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('contenttypes', '0002_remove_content_type...
from itertools import islice from pathlib import Path import PyPDF2 import requests from bs4 import BeautifulSoup from logzero import logger import settings from rcheatsheets.contents.cheatsheet import CheatSheet from rcheatsheets.contents.cover import Cover from rcheatsheets.contents.toc import TOC class Handler: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import shutil import sys from io import open from setuptools import find_packages, setup if sys.argv[-1] == "publish": os.system("python setup.py sdist bdist_wheel") os.system("twine upload dist/*") shutil.rmtree("dist") shutil.rmtree("build") ...
import unittest from fortosto.commons.sqlTemplates import getCreateTableQuery class TestSqlTemplates(unittest.TestCase): def test_sql1(self): expected = """CREATE TABLE "theSchema"."theTable" ( "c1" character varying, "c2" character varying, "c3" character varying ); """ ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from frappe import _ def get_data(): return [ # { # "module_name": "Senergy", # "color": "grey", # "icon": "octicon octicon-file-directory", # "type": "module", # "label": _("Senergy") # }, { "module_name": "Item Master", "cate...
import os c.NotebookApp.extra_template_paths.append('/etc/jupyter/binder_templates') c.NotebookApp.jinja_template_vars.update({'binder_url': os.environ.get('BINDER_URL', 'https://mybinder.org')})
import os import unittest import shutil from doppel import mkdir, makedirs this_dir = os.path.abspath(os.path.dirname(__file__)) test_stage_dir = os.path.join(this_dir, '..', 'stage') class TestMkdir(unittest.TestCase): def setUp(self): os.chdir(this_dir) stage = os.path.join(test_stage_dir, 'mk...
# -*- encoding: utf-8 -*- # ! python3 import glob import logging import os import shutil import sys from invoke import run, task logger = logging.getLogger(__name__) @task def worker(ctx): """ Run Celery Worker """ ctx.run("celery worker --pidfile=../data/celery/celery-worker.pid --workdir=src/ --app=main ...