content
stringlengths
0
894k
type
stringclasses
2 values
""" Custom terminal color scheme. """ from django.core.management import color from django.utils import termcolors def color_style(): style = color.color_style() style.BOLD = termcolors.make_style(opts = ('bold',)) style.GREEN = termcolors.make_style(fg = 'green', opts = ('bold',)) style.YELLOW = termcolors.make...
python
#!/usr/bin/env python3 from pathlib import Path import shutil import subprocess import sys import zipapp script_dir = Path(__file__).parent ficdl_path = script_dir.joinpath('ficdl') dist = script_dir.joinpath('dist') shutil.rmtree(dist, ignore_errors=True) dist.mkdir() shutil.copytree(ficdl_path, dist.joinpath('pk...
python
from __future__ import unicode_literals import datetime import json import logging from urllib import urlencode from django.core.urlresolvers import reverse from django.http.response import JsonResponse, Http404 from django.shortcuts import render, redirect from django.template import loader from django.utils import ...
python
import re str = "Edureka" m = re.match('(..)+',str) print m.group(1) print m.group(0)
python
#! /usr/bin/env python import json import argparse from typing import Tuple, List import os import sys sys.path.insert( 0, os.path.dirname(os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir)))) ) from allennlp.common.util import JsonDict from allennlp.semparse.domain_languages import NlvrLanguage fr...
python
import sigvisa_util from sigvisa.database import db import numpy as np import sigvisa.utils.geog dbconn = db.connect() cursor = dbconn.cursor() sql_query = "select distinct fit.arid, lebo.lon, lebo.lat, sid.lon, sid.lat, leba.seaz, fit.azi from leb_origin lebo, leb_assoc leba, leb_arrival l, sigvisa_coda_fits fit, st...
python
#--------------------------------------------------------------------------- # # Evolution.py: basics of evolutionary dynamics, Evolution chapter # # see Quasispecies.py and Tournament.py for application examples # # by Lidia Yamamoto, Belgium, July 2013 # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -...
python
__version__ = '0.1.0' from .registry_client import RegistryClient
python
#encoding: utf-8 """ Following Python and Django’s “batteries included” philosophy, Philo includes a number of optional packages that simplify common website structures: * :mod:`~philo.contrib.penfield` — Basic blog and newsletter management. * :mod:`~philo.contrib.shipherd` — Powerful site navigation. * :mod:`~philo....
python
import requests from django.conf import settings from django.http import ( Http404, HttpResponse, HttpResponseServerError, JsonResponse, StreamingHttpResponse, ) from django.utils.translation import ugettext_lazy as _ from requests import Session from requests.auth import HTTPBasicAuth from rest_fra...
python
from random import choice def random_placement(board, node): """ Chooses a placement at random """ available_placements = list(board.get_available_placements()) return choice(available_placements) def check_for_win_placement(board, node): """ Checks if a placement can be made that leads ...
python
""" Module for managing a sensor via KNX. It provides functionality for * reading the current state from KNX bus. * watching for state updates from KNX bus. """ from xknx.remote_value import RemoteValueControl, RemoteValueSensor from .device import Device class Sensor(Device): """Class for managing a sensor.""...
python
""" Workflow class that splits the prior into a gold standard and new prior """ import pandas as pd import numpy as np from inferelator_ng.utils import Validator as check from inferelator_ng import default def split_for_cv(all_data, split_ratio, split_axis=default.DEFAULT_CV_AXIS, seed=default.DEFAULT_CV_RANDOM_SEED...
python
from Crypto.Cipher import AES obj = AES.new('hackgt{oracle_arena_sux_go_cavs}', AES.MODE_CBC, '0000000000000000') message = "hello world" padding = 16 - len(message) print len( ciphertext = obj.encrypt(message + '/x00' * 16) print ciphertext
python
import os from scipy.io import loadmat class DATA: def __init__(self, image_name, bboxes): self.image_name = image_name self.bboxes = bboxes class WIDER(object): def __init__(self, file_to_label, path_to_image=None): self.file_to_label = file_to_label self.path_to_image = path...
python
# See http://cookiecutter.readthedocs.io/en/latest/advanced/hooks.html from datetime import datetime import io import pathlib import shlex import shutil import sys def is_trueish(expression: str) -> bool: """True if string and "True", "Yes", "On" (ignorecase), False otherwise""" expression = str(expression)....
python
from typing import Any, Dict, Optional import redis from datastore.shared.di import service_as_singleton from datastore.shared.services import EnvironmentService, ShutdownService # TODO: Test this. Add something like a @ensure_connection decorator, that wraps a # function that uses redis. It should ensure, that the...
python
from setuptools import setup CLASSIFIERS = [ 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Operating System :: OS Independent', 'Topic :: Documentation', ] setup( name = "sphinx-autodoc-pywps", version = "0.1", #url = "h...
python
from django.test import TestCase from booking.models import Material, RateClass from booking.tests.factories import MaterialFactory, RateClassFactory class RateClassModelTest(TestCase): def test_delete_rateclass_keeps_materials(self): rateclass = RateClassFactory() material = MaterialFactory(rate...
python
import os import time from PIL import Image, ImageChops import progressbar import argparse import utils_image ##### MAIN ############ def main(): ''' Parse command line arguments and execute the code ''' parser = argparse.ArgumentParser() parser.add_argument('--dataset_path', required=True, type=...
python
''' * Copyright (C) 2019-2020 Intel Corporation. * * SPDX-License-Identifier: MIT License * ***** * * MIT License * * Copyright (c) Microsoft Corporation. * * 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...
python
# Based on # https://github.com/tensorflow/docs/blob/master/site/en/tutorials/keras/basic_classification.ipynb # (MIT License) from __future__ import absolute_import, division, print_function from tensorflow import keras import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import os figdir = "....
python
from TASSELpy.utils.helper import make_sig from TASSELpy.utils.Overloading import javaConstructorOverload, javaOverload from TASSELpy.net.maizegenetics.dna.snp.score.SiteScore import SiteScore from TASSELpy.net.maizegenetics.dna.snp.byte2d.Byte2D import Byte2D from TASSELpy.java.lang.Integer import metaInteger import n...
python
from .draw_chessboard import draw_chessboard from .draw_chessboard import draw_tuples
python
# Software License Agreement (BSD License) # # Copyright (c) 2012, Fraunhofer FKIE/US, Alexander Tiderko # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code mus...
python
""" Question: Remove Nth Node From End of List Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given ...
python
"""OAuth 2.0 WSGI server middleware implements support for basic bearer tokens and also X.509 certificates as access tokens OAuth 2.0 Authorisation Server """ __author__ = "R B Wilkinson" __date__ = "12/12/11" __copyright__ = "(C) 2011 Science and Technology Facilities Council" __license__ = "BSD - see LICENSE file i...
python
"""A milestone is a set of parameters used to add a label on a time period. A milestone can then be used as a time's and timezone's filter.""" from .utils._internal import instance_builder from .model import SourceModel class Milestone(SourceModel): """This object stores all information about a milestone. Data s...
python
import RPi.GPIO as GPIO import time # Class to manage the LEDs on the breakout board class LedArray: def __init__(_self): # Set board numbering scheme and warnings GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) # Set the pins to be outputs GPIO.setup(11, GPIO.OUT) GPIO.setup(13, GPIO.OUT) GPIO.setu...
python
# -*- coding: utf-8 -*- "IMPORTED" def foo(): """imported module""" return "FOO" print __name__
python
# Este es un ejemplo de un for for n in range(10) print(n)
python
import asyncio import asyncws clients = [] clients_lock = asyncio.Lock() def chat(websocket): client_copy = None with (yield from clients_lock): client_copy = list(clients) clients.append(websocket) peer = str(websocket.writer.get_extra_info('peername')) for client in client_copy: ...
python
from deepflash2.learner import EnsembleLearner, get_files, Path from app import crud import pathlib import numpy as np from app.api import classes, utils_transformations import app.fileserver_requests as fsr from app.api import utils_paths import zarr def predict_image_list(classifier_id, image_id_list, use_tta, chan...
python
import os class OccupEyeConstants(): """ A function-less class that defines cache and URL constants for the OccupEye API. These are used to try and avoid typos and repeated typing of long strings. Each {} is a format string container that is replaced by an appropriate string from...
python
#! /usr/bin/env python from socket import * host = 'localhost' port = 10000 sock = socket(AF_INET,SOCK_DGRAM) sock.bind((host,port)) while 1: data = sock.recvfrom(1024) print data sock.close()
python
import os import torch as T import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np class OUActionNoise(object): def __init__(self, mu, sigma=0.15, theta=.2, dt=1e-2, x0=None): self.theta = theta self.mu = mu self.sigma = sigma self.dt = ...
python
import wandb import torch import numpy as np import sklearn.gaussian_process as skgp import sklearn.utils.validation as skval import scipy.stats as stat import utils import constants kernels = { "rbf": skgp.kernels.RBF, "matern": skgp.kernels.Matern, "rat_quad": skgp.kernels.RationalQuadratic, "period...
python
# -*- coding: utf-8 -*- from django.db import models from django.core.urlresolvers import reverse from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, UserManager as BaseUserManager from recipi.core.tasks.mail import send_mai...
python
# A logarithmic solution to the Knight's Dialer problem mentioned here: # https://medium.com/@alexgolec/google-interview-questions-deconstructed-the-knights-dialer-f780d516f029 import numpy as np import sys from timeit import default_timer as timer # Uses a fibonacci sequence approach to compute matrices that "add" u...
python
"""I don't like how the error messages are shown in attrs""" import attr import numpy as np from attr._make import attrib, attrs @attrs(repr=False, slots=True, hash=True) class _InstanceOfValidator(object): type = attrib() def __call__(self, inst, attr, value): """ We use a callable class to...
python
def fibo(n): flist = [1,1] if n <= 0 : return 0 if n == 1 or n == 2: return n else : while n >= 3: temp = flist[1] flist[1] += flist[0] flist[0] = temp n -= 1 return flist[1] print(fibo(45))
python
import json import datetime from uuid import UUID from django.test import TestCase from django.utils import six from model_mommy import mommy from rest_framework.fields import empty from rest_framework.test import APIClient from django.contrib.auth import get_user_model from .compat import resolve from dynamic_rest.me...
python
############################################################################## # Copyright 2018 Rigetti Computing # # 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://ww...
python
from django.test import TestCase from ..models import Meal from authentication.models import CustomUser class TestMeal(TestCase): def setUp(self): self.user = CustomUser.objects.create_user( email="zoran@zoran.com", password="123456") Meal.objects.create( text="breakfast", ...
python
import unittest import operator import pytest from loris import transforms from loris.loris_exception import ConfigError from loris.webapp import get_debug_config from tests import loris_t class ColorConversionMixin: """ Adds a helper method for testing that a transformer can edit the embedded color pro...
python
from sklearn.datasets import load_breast_cancer from sklearn.metrics import calinski_harabasz_score from sklearn.metrics import adjusted_mutual_info_score, adjusted_rand_score from gama import GamaCluster if __name__ == "__main__": X, y = load_breast_cancer(return_X_y=True) automl = GamaCluster(max_total_tim...
python
import math import itertools flatten_iter = itertools.chain.from_iterable # https://stackoverflow.com/a/6909532/5538273 def factors(n): return set(flatten_iter((i, n//i) for i in range(1, int(math.sqrt(n)+1)) if n % i == 0)) def prime_factors(n): dividend = n prime_nums = primes(n) prime_factors =...
python
# SPDX-License-Identifier: Apache-2.0 # Copyright 2016 Eotvos Lorand University, Budapest, Hungary from utils.codegen import format_expr, make_const import utils.codegen from compiler_log_warnings_errors import addError, addWarning from compiler_common import generate_var_name, prepend_statement #[ #include "dataplan...
python
""" The tests exercise the casting machinery in a more low-level manner. The reason is mostly to test a new implementation of the casting machinery. Unlike most tests in NumPy, these are closer to unit-tests rather than integration tests. """ import pytest import textwrap import enum import itertools import random i...
python
import numpy as np from core.region.region import Region from random import randint import warnings from intervals import IntInterval import numbers class Chunk(object): """ Each tracklet has 2 track id sets. P - ids are surely present N - ids are surely not present A - set of all animal ids. ...
python
import configparser import typing class BaseConfig: default = { "copy_ignores": [ "venv", "logs", ".git", ".idea", ".vscode", "__pycache__", ], "clean_py": True, "build_dir": "build", } @property d...
python
from django.db import models # Create your models here. class Order(models.Model): is_payed = models.BooleanField(default=False, blank=True, null=True) amount = models.DecimalField(max_digits=50, decimal_places=2, blank=True, null=True) amount_for_payme = models.DecimalField(max_digits=50, decimal_places...
python
from .core import * # noqa __version__ = '1.0.0'
python
from celestial_bodies.celestial_body import Celestial_Body from celestial_bodies.trajectories.stationary import Stationary from celestial_bodies.trajectories.ellipse_approx import Ellipse_Mock from celestial_bodies.trajectories.rotation import Rotation from vector3 import Vector3 # the kepler model is practically the...
python
#! /usr/bin/env python # # # Brute-force dump of single row from WKT Raster table as GeoTIFF. # This utility is handy for debugging purposes. # # WARNING: Tha main purpose of this program is to test and # debug WKT Raster implementation. It is NOT supposed to be an # efficient performance killer, by no means. # #######...
python
text = input() upper_cases_count, lower_cases_count = 0, 0 for character in text: if character.isupper(): upper_cases_count += 1 elif character.islower(): lower_cases_count += 1 if upper_cases_count > lower_cases_count: print(text.upper()) else: print(text.lower())
python
import unittest from unittest import mock from tinydb import TinyDB, Query from motey.repositories import capability_repository class TestCapabilityRepository(unittest.TestCase): @classmethod def setUp(self): self.test_capability = 'test capability' self.test_capability_type = 'test capabili...
python
tasks = [ { 'name': 'A simple command', 'function': 'scrapli_command.scrapli_command', 'kwargs': { 'command' : 'show version | i uptime'} }, ] tasks = [tasks[0]] taskbook = {} taskbook['name'] = "Testing with Scrapli Async!" taskbook['run_mode'...
python
import pytest from mlflow.exceptions import MlflowException from mlflow.store.dbmodels.db_types import DATABASE_ENGINES from mlflow.utils import get_unique_resource_id, extract_db_type_from_uri, get_uri_scheme def test_get_unique_resource_id_respects_max_length(): for max_length in range(5, 30, 5): for _...
python
__author__ = 'fran'
python
import argparse from nuts.testhandling.evaluator import Evaluator from nuts.testhandling.network_test_builder import TestBuilder from nuts.testhandling.network_test_runner import TestRunner from nuts.testhandling.reporter import Reporter from nuts.utilities.ui_handler import UIHandler class TestController: """ ...
python
import tkinter as tk SQUARE_DIM = 120 BOARD_DIM = SQUARE_DIM*8 TEXT_SIZE = 28 HAVE_DRAWN = False global images images = {} def ranges(val): return range(val - SQUARE_DIM//2, val + SQUARE_DIM//2) def move_piece(piece_x, piece_y, piece_name, x, y): if x <= 0: x = 1 if x>= BOARD_DIM + 4*SQUARE_DI...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ """ import click import json import pickle import math import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn.svm import SVC from sklearn.decomposition import PCA from numpy import linalg as LA from scipy.optimize imp...
python
from __future__ import print_function from PIL import Image import torchvision.datasets as datasets import torch.utils.data as data class CIFAR10Instance(datasets.CIFAR10): """CIFAR10Instance Dataset. """ def __init__(self, root='./data/cifar10', train=True, download=True, transform=None, two_imgs=False, ...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Grabs brain volumes for Freesurfer and SIENAX segmentations with follow up scans and plots them """ import os from glob import glob import re import itertools import numpy as np import matplotlib.pyplot as plt import nibabel as nib from scipy import stats sienax_mas...
python
from src.utilities.geometry import dist_between_points def cost_to_go(a: tuple, b: tuple) -> float: """ :param a: current location :param b: next location :return: estimated segment_cost-to-go from a to b """ return dist_between_points(a, b) def path_cost(E, a, b): """ Cost of the un...
python
"""Extensions module - Set up for additional libraries can go in here.""" import logging # logging logger = logging.getLogger("flask.general")
python
from config import config from packettest.packets import make_packet # from packettest.test_context import make_context from packettest.test_context import TestContext from packettest.predicates import received_packet from packettest.predicates import saw_packet_equals_sent from simple_switch.simple_switch_runner imp...
python
# -*- coding: utf-8 -*- """ Profile: http://hl7.org/fhir/StructureDefinition/Condition Release: R4 Version: 4.0.1 Build ID: 9346c8cc45 Last updated: 2019-11-01T09:29:23.356+11:00 """ import io import json import os import unittest import pytest from .. import condition from ..fhirdate import FHIRDate from .fixtures ...
python
class Parser: site_url = "" required_path_elements = [] @staticmethod def parse_thread(soup_obj, url): pass @staticmethod def parse_title(soup_obj): pass
python
#!/usr/bin/env python """ Horn Concerto - Evaluation for inference. Author: Tommaso Soru <tsoru@informatik.uni-leipzig.de> Version: 0.1.0 Usage: Use test endpoint (DBpedia) > python evaluation.py <TEST_SET> <INFERRED_TRIPLES> """ import sys from joblib import Parallel, delayed import numpy as np import multipro...
python
"""Tokenization utilities.""" import pyonmttok _ALLOWED_TOKENIZER_ARGS = set( [ "bpe_dropout", "bpe_model_path", "case_feature", "case_markup", "joiner", "joiner_annotate", "joiner_new", "lang", "mode", "no_substitution", "pre...
python
""" nvo This module contains a collection of YANG definitions for Cisco VxLAN feature configuration. Copyright (c) 2013\-2014 by Cisco Systems, Inc. All rights reserved. """ from collections import OrderedDict from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, B...
python
# -*- coding=utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the ...
python
import json from collections import namedtuple, defaultdict, deque try: from collections import Mapping except ImportError: from collections.abc import Mapping from glypy.io import glycoct from glypy.structure.glycan_composition import HashableGlycanComposition EnzymeEdge = namedtuple("EnzymeEdge", ("parent"...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import find_packages from setuptools import setup setup( name='blueprint-webapp-flask-graphql', version='1.0.0', packages=find_packages(exclude=["*_tests"]), license='MIT', long_description=open('README.md').read(), install_requires=...
python
#!/usr/bin/env python import setuptools setuptools.setup( name='loops', description='Convenience classes and functions for looping threads', author='Fenhl', author_email='fenhl@fenhl.net', packages=['loops'], use_scm_version={ 'write_to': 'loops/_version.py' }, setup_requires=[...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # @copyright &copy; 2010 - 2021, Fraunhofer-Gesellschaft zur Foerderung der # angewandten Forschung e.V. All rights reserved. # # BSD 3-Clause License # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the fol...
python
import argparse def get_options(args): parser = argparse.ArgumentParser(description="Parses command.") parser.add_argument("-i", "--input", help="Your input file.", required=True) parser.add_argument("-o", "--output", help="Your destination output file.", default='/data/adversarial_image.png') parser....
python
# Pyrogram - Telegram MTProto API Client Library for Python # Copyright (C) 2017-2018 Dan Tès <https://github.com/delivrance> # # This file is part of Pyrogram. # # Pyrogram 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 S...
python
#!/usr/bin/env python3 """ SPDX-License-Identifier: BSD-3-Clause Copyright (c) 2020 Deutsches Elektronen-Synchrotron DESY. See LICENSE.txt for license details. """ import setuptools from pathlib import Path as path from frugy import __version__ readme_contents = path('./README.md').read_text() requirements = path('./...
python
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "YaraGuardian.settings") from django.core.wsgi import get_wsgi_application from whitenoise import WhiteNoise from django.conf import settings application = get_wsgi_application() if settings.SERVE_STATIC: application = WhiteNoise(application)
python
''' Objectives : 1. Input a JSON file from user. (here, Employees.json) 2. Read the JSON file and print the data on console 3. Create methods (units) for each field of an employee and check the fields values using regular expression. 4. Perform unit testing for each unit using Python module unittest. ''' import json i...
python
#!/usr/bin/env python """This script compiles multiple instances of a program trying out different heuristics, and storing in the database the best one that is found""" import sys import os import shutil import sqlite3 import random import xml.dom.minidom import re import pbutil import tunerwarnings import maximaparser...
python
#!/home/joan/Documents/Myproject/mynewenv/bin/python3 from django.core import management if __name__ == "__main__": management.execute_from_command_line()
python
from Lexer import * # Keywords can execute outside main function kw_exe_outside_main = {KW_main, KW_def, KW_import1} variables = [] functions = [] current_line = 0 class Token: def __init__(self, tokens): self.t_values = [] self.last_kw = '' for tok in tokens: ...
python
from __future__ import division import os from flask import Flask, url_for, request, redirect, render_template from flask_sqlalchemy import SQLAlchemy from sqlalchemy import func import math import sqlite3 app = Flask(__name__) app.config['SERVER_NAME'] = 'the-gpa-calculator-noay.herokuapp.com' app.secret_key = 'Secre...
python
from src.DataReader.CNN_Data.ReadData_CNN import * import time from src.Params import branchName ############################################################################################## ## Rule of thumb: don't call any other function to reduce lines of code with the img data in np. ## Otherwise, it could c...
python
import os import re import sys try: from Cython.Distutils import build_ext except ImportError: from setuptools.command.build_ext import build_ext from distutils.extension import Extension from distutils.sysconfig import get_config_vars, get_python_lib, get_python_version from pkg_resources import Distribution...
python
from sqlalchemy import Column, Integer from sqlalchemy.ext.declarative import declared_attr, declarative_base from backend import Backend Base = declarative_base() class DjangoLikeModelMixin(object): id = Column(Integer, primary_key=True) @declared_attr def __tablename__(cls): return cls.__name...
python
import datetime, send_data cefmapping = {"ip-src": "src", "ip-dst": "dst", "hostname": "dhost", "domain": "dhost", "md5": "fileHash", "sha1": "fileHash", "sha256": "fileHash", "url": "request"} mispattributes = {'input': list(cefmapping.keys())} outputFileExtension = "cef" responseType = "...
python
#! /usr/local/bin/stackless2.6 # by pts@fazekas.hu at Thu Apr 29 19:20:58 CEST 2010 """Demo for hosting a Concurrence application within a Syncless process.""" __author__ = 'pts@fazekas.hu (Peter Szabo)' # It would work even with and without these imports, regardless of the import # order. #from syncless.best_stackl...
python
# Multiple Linear Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd from pathlib import Path # Importing the dataset path = Path(__file__).parent / '50_Startups.csv' dataset = pd.read_csv(path) X = dataset.iloc[:, :-1].values y = dataset.iloc[:, -1].values # ...
python
#encoding:utf-8 import xml.etree.ElementTree as ET import requests KEY = '7931e48c2618c58d14fc11634f2867db' TRANSFER_URL = u'http://openapi.aibang.com/bus/transfer?app_key=%s&city=武汉&start_addr=%s&end_addr=%s' LINES_URL = u'http://openapi.aibang.com/bus/lines?app_key=%s&city=武汉&q=%s' STATUS_URL = u'http://openapi.aib...
python
from app import app, db from app.models import User, Listing @app.shell_context_processor def make_shell_context(): with app.app_context(): return {'db': db, 'User': User, 'Listing': Listing}
python
# -*- coding: utf-8 -*- # Copyright 2019 Cohesity Inc. import cohesity_management_sdk.models.netapp_cluster_info import cohesity_management_sdk.models.netapp_volume_info import cohesity_management_sdk.models.netapp_vserver_info class NetappProtectionSource(object): """Implementation of the 'NetappProtectionSourc...
python
#!/usr/bin/env python #-*- coding: utf-8 -*- #Importações e tratamento de exceções #try: import kivy from kivy.app import App as app from kivy.uix.boxlayout import BoxLayout as bl from kivy.uix.button import Button as btn from kivy.uix.label import Label as lb # except: # import kivy # kivy.require('1.0.1') # fr...
python
""" AudioFile class Load audio files (wav or mp3) into ndarray subclass Last updated: 15 December 2012 """ import os from subprocess import Popen, PIPE import numpy from numpy import * import scipy.io.wavfile from pymir import Frame import pyaudio class AudioFile(Frame.Frame): def __new__(subtype, shape, dtyp...
python
from keras.layers import Flatten, Dense, Dropout, Input from keras.models import Sequential, Model import tensorflow as tf import pickle flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_string('dataset', 'cifar10', "Make bottleneck features this for dataset, one of 'cifar10', or 'traffic'") flags.DEFINE_string('...
python
# -*- coding: utf-8 -*- import csv,serial arduino = serial.Serial('/dev/cu.usbmodem30',9600) print(""" ______________________________________________________ Proyecto Programación Estructurada Integrantes: Ing. Juan Manuel Corza Hermosillo ...
python