text
string
size
int64
token_count
int64
from django.views.generic import DetailView, ListView, TemplateView from .models import Books class BooksListView(ListView): model = Books class BooksDeitalView(DetailView): model = Books class Home(TemplateView): template_name = './biblioteca/index.html' class TermsOfService(TemplateView): templat...
363
102
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from .evaluator import DatasetEvaluator, DatasetEvaluators, inference_context, inference_on_dataset from .testing import print_csv_format, verify_results from .hico_evaluation import HICOEvaluator from .swig_evaluation import SWIGEvaluator # from .d...
429
133
import datetime as dt from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator from django.core.exceptions import ValidationError from users.models import CustomUser def validate_year(value): """ Год выпуска произведения не может быть больше текущего. """ ...
4,092
1,294
### ### This file was automatically generated ### from archinfo.arch import register_arch, Endness, Register from .common import ArchPcode class ArchPcode_PowerPC_LE_32_QUICC(ArchPcode): name = 'PowerPC:LE:32:QUICC' pcode_arch = 'PowerPC:LE:32:QUICC' description = 'PowerQUICC-III 32-bit little endian fa...
127,462
67,497
# -*- coding: utf-8 -*- import json import pdb import os from os.path import join as pj import networkx as nx import pandas as pd from networkx.readwrite.json_graph import node_link_data def chain(): g = nx.Graph() # Horizontal for i in range(11, 15): g.add_edge(i, i + 1) for i in range(...
6,796
2,586
# auto_telnet.py - remote control via telnet import os, sys, string, telnetlib from getpass import getpass class AutoTelnet: def __init__(self, user_list, cmd_list, **kw): self.host = kw.get('host', 'localhost') self.timeout = kw.get('timeout', 600) self.command_prompt = kw.get('command_pro...
2,741
888
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 7 09:46:10 2018 @author: sungkyun FFTNet model using 2x1 dil-conv """ import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # Models with Preset (for convenience) ''' dim_input: dimension of input (256 for 8-bit mu-...
5,511
2,059
""" Copy - copy fields into other (possibly new) fields configuration: on: list of 'alert', 'revoke', 'report', 'reset' (optional: def 'alert' only) cp: ( (in,out), ... ) Field names take the form of dir1/dir2/dir3, which in the payload will be data[dir1][dir2][dir3] """ import logging from snewpdag.dag import N...
1,390
483
''' houses each team member's link to personal GitHub io or website or blog space RJProctor ''' # Imports from 3rd party libraries import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output from app import app ...
1,562
457
from importlib import _bootstrap from . import util import collections import imp import sys import unittest class PathHookTests(unittest.TestCase): """Test the path hook for extension modules.""" # XXX Should it only succeed for pre-existing directories? # XXX Should it only work for directories contai...
755
211
import os from glob import iglob from concurrent.futures import ThreadPoolExecutor def count_words_file(path): if not os.path.isfile(path): return 0 with open(path) as file: return sum(len(line.split()) for line in file) def count_words_sequential(pattern): return sum(map(count_words_fil...
480
151
#!/usr/bin/env python from livereload import Server, shell server = Server() server.watch('*.rst', shell('make html')) server.serve()
141
48
# -*- coding: UTF-8 -*- # !/usr/bin/python # @time :2019/6/5 21:04 # @author :Mo # @function :file of path import os import pathlib import sys # 项目的根目录 path_root = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) path_root = path_root.replace('\\', '/') path_top = str(pathlib.P...
3,008
1,304
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Created by Roberto Preste import pytest import asyncio from pandas.testing import assert_frame_equal from apyhgnc import apyhgnc # apyhgnc.info def test_info_searchableFields(searchable_fields): result = apyhgnc.info().searchableFields assert result == searchab...
2,617
1,021
import os.path import argparse from xml.etree import ElementTree as ET class ExtractedEnum(object): def __init__(self, tag_name, value_names): self.tag_name = tag_name self.value_names = value_names def write_pxd(self, file_): file_.write("\n ctypedef enum {}:\n".format(self.tag_n...
2,770
989
class Libro: def __init__(self, titulo, autor): """...""" self.titulo = titulo self.autor = autor def obtener_titulo(self): """...""" return str(self.titulo) def obtener_autor(self): """...""" return str(self.autor) class Biblioteca: def...
1,230
448
# -*- coding: utf-8 -*- import unittest from xml.etree import ElementTree as ET from parser_tool import tokenizer from parser_tool import htmlgenerator class TestHtmlGenerator(unittest.TestCase): def _maketokendict(self, **kwargs): token_text = kwargs.get("token", "") token_dict = { ...
5,540
1,864
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.core.files import File def update_gitlab_system_user_photo_to_v2(apps, schema_editor): # We get the model from the versioned app registry; # if we directly import it, it'll be the wrong version...
1,772
537
load("//tools/bzl:maven_jar.bzl", "maven_jar") def external_plugin_deps(omit_commons_codec = True): JACKSON_VERS = "2.10.2" maven_jar( name = "scribejava-core", artifact = "com.github.scribejava:scribejava-core:6.9.0", sha1 = "ed761f450d8382f75787e8fee9ae52e7ec768747", ) maven_j...
995
449
# Este programa muestra la suma de dos variables, de tipo int y float print("Este programa muestra la suma de dos variables, de tipo int y float") print("También muestra que la variable que realiza la operación es de tipo float") numero1 = 7 numero2 = 3.1416 sumadeambos = numero1 + numero2 print("El resultado d...
442
151
# -*- coding: utf-8 -*- from sklearn import preprocessing from torch.autograd import Variable from models_gat import GAT import os import torch import numpy as np import argparse import pickle import sklearn.metrics as metrics import cross_val import time import random torch.manual_seed(0) np.random.seed(0) random.s...
12,398
3,921
import copy import numbers import struct from ._common import * from ._exif import * TIFF_HEADER_LENGTH = 8 def dump(exif_dict_original): """ py:function:: piexif.load(data) Return exif as bytes. :param dict exif: Exif data({"0th":dict, "Exif":dict, "GPS":dict, "Interop":dict, "1st":dict, "thumbn...
12,752
4,460
import pygame import random from pygame import * pygame.init() width, height = 740, 500 screen = pygame.display.set_mode((width, height)) player = [pygame.transform.scale(pygame.image.load("Resources/Balljump-1(2).png"), (100,100)), pygame.t...
8,000
2,806
# (C) Datadog, Inc. 2021-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) from typing import Any, Dict from datadog_checks.base.stubs.aggregator import AggregatorStub from datadog_checks.datadog_cluster_agent import DatadogClusterAgentCheck from datadog_checks.dev.utils import ...
2,137
753
import pylab import numpy import sys if (len(sys.argv) < 2): fn = raw_input("Please enter data file to be plotted\n") else: fn = sys.argv[1] data = np.loadtxt(fn) # if the first line contains crap use skiprows=1 #data = np.loadtxt(fn, skiprows=1) fig = pylab.figure() ax = fig.add_subplot(111) # if you wan...
843
366
def load(h): return ({'abbr': 0, 'code': 0, 'title': 'There is no appended list'}, {'abbr': 1, 'code': 1, 'title': 'Numbers define number of points corresponding to full coordinate ' 'circles (i.e. parallels), coordinate values on each circle are ' ...
1,415
359
from __future__ import division from lib import env_config from lib.senior_env import BetterEnvironment from keras.optimizers import Adam from rl.agents.dqn import DQNAgent from rl.policy import LinearAnnealedPolicy, BoltzmannQPolicy, EpsGreedyQPolicy from rl.memory import SequentialMemory from lib import models impor...
2,691
868
# I'm just the one that executes the instructions! import sys, math, json, operator, time import mcpi.minecraft as minecraft from PIL import Image as pillow from blockid import get_block import mcpi.block as block import functions as pymc from tqdm import tqdm import tkinter as tk # Functions # Main code mc = minecra...
1,752
713
#!/usr/bin/python import optparse import os import re import sys import cairo from gaphas.painter import Context, ItemPainter from gaphas.view import View import gaphor.UML as UML from gaphor.application import Application from gaphor.storage import storage def pkg2dir(package): """ Return directory path f...
4,377
1,311
class InvalidSideException(Exception): """Invalid side""" class NotSupportedException(Exception): """Not supported by dummy wallet""" class InvalidProductException(Exception): """Invalid product type""" class OutOfBoundsException(Exception): """Attempt to access memory outside buffer bounds"""
317
80
# -*- coding: utf-8 -*- """ Created on Fri Apr 08 11:33:01 2016 @author: Leander Kotzur """ import tsib def test_get_ID(): # parameterize a building bdgcfg = tsib.BuildingConfiguration( { "refurbishment": False, "nightReduction": False, "occControl": False, ...
1,140
415
from abc import ABC, abstractmethod from collections import defaultdict from collections.abc import Sequence from functools import partial from itertools import product import numpy as np from pycompss.api.api import compss_wait_on from scipy.stats import rankdata from sklearn import clone from sklearn.model_selection...
25,791
7,116
import os from django.test import TestCase from mock import patch from ui.views import parse_search_results FIXTURES_ROOT = os.path.join(os.path.dirname(__file__), 'fixtures') FX = lambda *relpath: os.path.join(FIXTURES_ROOT, *relpath) @patch('ui.views.get_repo_type') @patch('ui.views.CODE_ROOT', '/opt/botanist/re...
1,407
426
""" Copyright (C) 2021 Clariteia SL This file is part of minos framework. Minos framework can not be copied and/or distributed without the express permission of Clariteia SL. """ from typing import ( Any, Type, ) class MinosException(Exception): """Exception class for import packages or modules""" ...
4,395
1,125
""" Extensions for pylearn2 training algorithms. Those are either reimplemented to suit the execution model of this package, or new ones for recording metrics. """ import os import cPickle as pkl import numpy as np from pylearn2.train_extensions import TrainExtension from .abcs import Buildable class BuildableTr...
4,598
1,294
import asyncio from io import BytesIO import logging import os import random import time from typing import List from urllib.parse import urlparse import aiohttp from aiohttp import ClientSession, TCPConnector import requests from requests import Response from tqdm import tqdm from nogi import REQUEST_HEADERS from no...
6,189
1,891
from Jumpscale import j import signal from .. import templates DNSMASQ = "/bin/dnsmasq --conf-file=/etc/dnsmasq.conf -d" class DHCP: def __init__(self, container, domain, networks): self.container = container self.domain = domain self.networks = networks def apply_config(self): ...
1,429
449
hensu_int = 17 #数字 hensu_float = 1.7 #小数点(浮動小数点) hensu_str = "HelloWorld" #文字列 hensu_bool = True #真偽 hensu_list = [] #リスト hensu_tuple = () #タプル hensu_dict = {} #辞書(ディクト)型 print(type(hensu_int)) print(type(hensu_float)) print(type(hensu_str)) print(type(hensu_bool)) print(type(hensu_list)) print(type(hensu_tuple)) prin...
340
175
#!/usr/bin/env python3 """UrsaLeo LEDdebug board LED demo Turn the LED's on one at a time, then all off""" import time ON = 1 OFF = 0 DELAY = 0.5 # seconds try: from LEDdebug import LEDdebug except ImportError: try: import sys import os sys.path.append("..") sys.path.appen...
888
294
#!/usr/bin/env python ################################################################################### ## ## Project: COVID -19 xDNN Classifier 2020 ## Version: 1.0.0 ## Module: Server ## Desription: The COVID -19 xDNN Classifier 2020 server. ## License: MIT ## Copyright: 2021, Asociacion De Investigac...
6,352
2,398
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 3.0.0.11832 on 2017-03-22. # 2017, SMART Health IT. import io import json import os import unittest from . import allergyintolerance from .fhirdate import FHIRDate class AllergyIntoleranceTests(unittest.TestCase): def instantiate_from(self...
4,382
1,605
import time import random import requests from lxml import etree import pymongo from .url_file import mjx_weibo, mjx_dy, mjx_ks, mjx_xhs class DBMongo: def __init__(self): self.my_client = pymongo.MongoClient("mongodb://localhost:27017/") # 连接数据库 self.db = self.my_client["mcn"] def i...
4,107
1,644
import numpy as np from keras.utils import np_utils import pandas as pd import sys from sklearn.preprocessing import LabelEncoder from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis as QDA from sklearn.decomposition import PCA import os from sklearn.externals import joblib from sklearn.metrics impor...
2,756
1,102
import struct import json from collections import OrderedDict file_path = "data0002.bin" show_offset = True show_hash = False loaded_data = 0 def unpack(upstream_data_set): global loaded_data loaded_data = loaded_data + 1 currentCursor = file.tell() print(hex(file.tell())) file.seek(...
2,850
1,023
## to change recursion limit import sys print(sys.getrecursionlimit()) #Return the current value of the recursion limit #1000 ## change the limit sys.setrecursionlimit(2000) # change value of the recursion limit #2000 i=0 def greet(): global i i+=1 print('hellow',i) greet() greet() # hellow...
342
129
from django.test import TestCase, override_settings from django.urls import reverse from pages.models import Article, HomePage @override_settings(USE_I18N=False) class PageViewTest(TestCase): @classmethod def setUpTestData(cls): print("\nTest page views") # Set up non-modified objects used by...
1,406
429
#!/usr/bin/env python import logging import sys sys.path.append("../../") sys.path.append("pylib") import time import datetime import pymongo import uuid import os import subprocess import os.path import settings from common.utils import getSiteDBCollection sys.path.insert(0, "../../") class LoggingManager: de...
26,030
8,374
from decimal import Decimal as D from django.test import TestCase from oscar.apps.basket.models import Basket from oscar.apps.partner import strategy from oscar.test import factories from oscar.apps.catalogue.models import Option class TestAddingAProductToABasket(TestCase): def setUp(self): self.basket...
4,488
1,441
import pytest import os import sqlalchemy import contextlib @pytest.fixture(scope="session") def engine_uri(test_dir): database_path = test_dir.joinpath("pytest_meltano.db") try: database_path.unlink() except FileNotFoundError: pass return f"sqlite:///{database_path}"
305
101
#!/usr/bin/env python3 import json import os from pathlib import Path import numpy as np from natsort import natsorted try: from docopt import docopt from marko.ext.gfm import gfm import pygal from pygal.style import Style, DefaultStyle except ImportError as e: raise Exception('Some external depe...
11,134
4,050
# # This file is part of LiteX. # # Copyright (c) 2014-2019 Florent Kermarrec <florent@enjoy-digital.fr> # Copyright (c) 2019 msloniewski <marcin.sloniewski@gmail.com> # Copyright (c) 2019 vytautasb <v.buitvydas@limemicro.com> # SPDX-License-Identifier: BSD-2-Clause import os import subprocess import sys import math f...
9,839
3,173
"""Various helpers and utilities that don't belong anywhere else.""" from typing import Dict, Generic, TypeVar KeyType = TypeVar('KeyType') ValueType = TypeVar('ValueType') class GenericMonoDict(Dict[KeyType, ValueType]): """A dict with specific key and value types.""" def __getitem__(self, key: KeyType) -...
336
104
from rest_framework.routers import DefaultRouter from records.views import RecordViewSet router = DefaultRouter() router.register('', RecordViewSet, basename='records') urlpatterns = router.urls
198
54
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import os from rhea import RheaError from rhea import parser as rhea_parser from azure.common import AzureHttpError from azure.storage.blob.models import BlobPrefix from polystores.clients.azure_client import get_blob_service_c...
10,831
2,946
""" Copyright (c) 2016 Jet Propulsion Laboratory, California Institute of Technology. All rights reserved """ import sys import numpy as np import logging import time import types from datetime import datetime from netCDF4 import Dataset from nexustiles.nexustiles import NexusTileService from webservice.webmodel impor...
22,217
6,265
import numpy as np from collections import defaultdict, Counter from .rbbox_np import rbbox_iou def get_ap(recall, precision): recall = [0] + list(recall) + [1] precision = [0] + list(precision) + [0] for i in range(len(precision) - 1, 0, -1): precision[i - 1] = max(precision[i - 1], precision[i...
2,602
949
import logging import pygame from app import * from pygame.locals import * from werkzeug.serving import run_simple from web import webapp as w import data_access as da logging.basicConfig(filename='setlistmanager.log', level=logging.DEBUG) SCREEN_WIDTH = 160 SCREEN_HEIGHT = 128 class Button: pass class Text()...
5,186
1,730
import json import pandas as pd import numpy as np from matplotlib import pyplot as plt import simulation from eval_functions import oks_score_multi import utils def alter_location(points, x_offset, y_offset): x, y = points.T return np.array([x + x_offset, y + y_offset]).T def alter_rotation(points, radians):...
4,488
1,575
import requests import time import os import sys import json import threading from getpass import getpass import schedule import event as e import configuration as c import RPi.GPIO as GPIO #SERVER_URL = "https://home-automation-289621.uc.r.appspot.com" #SERVER_URL = "http://127.0.0.1:4747" SERVER_URL = "http://192.16...
6,592
2,277
from typing import Dict, Union from graphql import ( GraphQLBoolean, GraphQLFloat, GraphQLInputField, GraphQLInt, GraphQLList, GraphQLNonNull, GraphQLScalarType, GraphQLString, ) from sqlalchemy import ARRAY, Boolean, Float, Integer from sqlalchemy.dialects.postgresql import ARRAY as PG...
1,640
520
import Crypto.Random.random as rand import itertools import math #for log import sys def decomposition(i): #from stack exchange, don't think it's uniform while i > 0: n = rand.randint(1, i) yield n i -= n def Decomposition(i): while True: l = list(decomposition(i)) i...
3,223
1,156
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from .shared import Conv_Block from ..utils.utils import zeros, mean_cube, last_frame, ENS class Residual(nn.Module): def __init__(self, fn): super().__init__() self.fn = fn def f...
14,601
4,872
# Copyright (C) 2017 O.S. Systems Software LTDA. # This software is released under the MIT License import unittest from hydra import Hydra, Client class ClientsTestCase(unittest.TestCase): def setUp(self): self.hydra = Hydra('http://localhost:4444', 'client', 'secret') self.client = Client( ...
2,325
801
# Copyright 2020 The FastEstimator 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 appl...
4,097
1,450
#!/usr/bin/env python from scTools import interval, primeForm from scTools.rowData import ats from scTools.scData import * count = 1 for w in ats: prime = primeForm(w[0:6]) print '%3d\t' % count, for x in w: print '%X' % x, print ' ', intervals = interval(w) for y in intervals: ...
619
237
import asyncio import click from precon.devices_handlers.distance_sensor import show_distance as show_distance_func from precon.remote_control import steer_vehicle, Screen try: import RPi.GPIO as GPIO except (RuntimeError, ModuleNotFoundError): import fake_rpi GPIO = fake_rpi.RPi.GPIO @click.command(n...
1,042
337
import csv import string import ftplib import math import time from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import sqlite...
57,607
17,959
# -*- coding: utf-8 -*- # # Copyright (c) 2015, Alcatel-Lucent Inc # 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 must retain the above copyright # no...
3,932
1,247
import atexit import sys if sys.version_info[0] == 2: from Queue import Empty else: from queue import Empty from multiprocessing import Process, Queue from rllab.sampler.utils import rollout import numpy as np __all__ = [ 'init_worker', 'init_plot', 'update_plot' ] process = None queue = None de...
1,787
531
''' Livro-Introdução-a-Visão-Computacional-com-Python-e-OpenCV-3 Repositório de imagens https://github.com/opencv/opencv/tree/master/samples/data ''' import cv2 import numpy as np from matplotlib import pyplot as plt #import mahotas VERMELHO = (0, 0, 255) VERDE = (0, 255, 0) AZUL = (255, 0, 0) AMARELO = (0, 255, ...
1,902
929
import base64 import json import jwt import requests from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend USER_MODEL = get_user_model() class ALBAuth(ModelBackend): def authenticate(self, request, **kwargs): if request: ...
1,949
637
import json import os import sys import re import copy import numpy as np from data_profiler.labelers.base_model import BaseModel from data_profiler.labelers.base_model import AutoSubRegistrationMeta _file_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(_file_dir) class RegexModel(BaseModel, metac...
11,306
2,944
# Desarrolle un un programa que reciba la fecha de nacimiento # de una persona, y como salida, indique el nombre del signo del # zodiaco correspondiente, ademas de su edad def zodiaco(DD, MM): if (((DD >= 22) and (MM == 11)) or ((DD <=21) and (MM == 12))): return("Sagitario") if (((DD >= 22) and (MM ==...
1,693
721
import re, scrapy from crawler.items import * class BenchmarkSpider(scrapy.Spider): drop_params = True # Spider name, for use with the scrapy crawl command name = "benchmarks" # Constants to get url parts FULL, PROTOCOL, USER, PASSWORD, SUBDOMAIN, DOMAIN, TOP_LEVEL_DOMAIN, PORT_NUM, PATH, PAGE, GE...
5,110
1,650
# Copyright 2017 GoDaddy # # 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 in ...
22,005
5,171
import re import logging import httplib import view_base from models import rt_proxy LOG = logging.getLogger('ryu.gui') class RtAddrDel(view_base.ViewBase): def __init__(self, host, port, dpid, address_id, status=None): super(RtAddrDel, self).__init__() self.host = host self.port = port ...
1,180
355
"""This module contains tests for the helper module. """ from pywrangler.util.helper import get_param_names def test_get_param_names(): def func(): pass assert get_param_names(func) == [] def func1(a, b=4, c=6): pass assert get_param_names(func1) == ["a", "b", "c"] assert get...
361
134
# ============================================================================= # Created By : Giannis Kostas Georgiou # Project : Machine Learning for Fish Recognition (Individual Project) # ============================================================================= # Description : File in order to convert save...
964
249
from .test_utils import PySparkTestCase from sparkts.datetimeindex import * import pandas as pd class DateTimeIndexTestCase(PySparkTestCase): def test_frequencies(self): bd = BusinessDayFrequency(1, 1, self.sc) self.assertEqual(bd.days(), 1) hf = HourFrequency(4, self.sc) s...
2,283
918
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: seen = set() curr = headA while curr: seen.add(curr) ...
492
140
import numpy as np import photon_stream as ps import photon_stream_production as psp import pkg_resources import os runinfo_path = pkg_resources.resource_filename( 'photon_stream_production', os.path.join('tests', 'resources', 'runinfo_20161115_to_20170103.csv') ) drs_fRunID_for_obs_run = psp.drs_run._drs_fRu...
1,214
506
# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-04-18 05:56 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('cmdb', '0001_initial'), ('appc...
2,444
704
import http import logging from typing import List, Tuple, MutableMapping from datetime import datetime import re from requests.packages.urllib3 import Retry import autoscaler.utils as utils from autoscaler.autoscaling_groups import AutoScalingGroup from autoscaler.azure_api import AzureApi, AzureScaleSet, AzureScale...
10,450
3,125
""" Insertion Sort Approach: Loop Complexity: O(n2) """ def sort_insertion(input_arr): print("""""""""""""""""""""""""") print("input " + str(input_arr)) print("""""""""""""""""""""""""") ln = len(input_arr) i = 1 # Assuming first element is sorted while i < ln: # n times c = inpu...
772
334
""" NAME tarea_7.py VERSION [1.0] AUTHOR Ignacio Emmanuel Ramirez Bernabe CONTACT iramirez@lcg.unam.mx GITHUB https://github.com/eveiramirez/python_class/blob/master/Python2/tareas/tarea_7.py DESCRIPTION Este programa contiene arrays estructurados para los arrays ...
1,780
624
""" Base pipeline class. Main rule generator classes inherit from this one. """ from copy import deepcopy from typing import List, Tuple, Union, Dict from iguanas.pipeline.class_accessor import ClassAccessor from iguanas.utils.typing import PandasDataFrameType, PandasSeriesType import iguanas.utils.utils as utils from ...
11,857
2,940
import unittest import datetime from parameterized import parameterized from activity_merger import Interval from aw_core.models import Event from typing import List, Tuple def _build_datetime(seed: int) -> datetime.datetime: return datetime.datetime(2000, 1, seed, seed, 0, 0).astimezone(datetime.timezone.utc) ...
6,306
1,856
""" NOTE: There are a few minor complications to fluid human control which make this code a little more involved than trivial. 1. Key press-release cycles can be, and often are, faster than one tick of the game/simulation, but the player still wants that cycle to count, i.e. to lay a bomb! 2. When holding down ...
4,526
1,310
# Copyright 2015 Cisco Systems, 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 agreed to in ...
14,852
4,486
""" fixtures that return an sql statement with a list of values to be inserted.""" def load_language(): """ return the sql and values of the insert queuery.""" sql = """ INSERT INTO Spanglish_Test.Language ( `name`, `iso-639-1` ) VALUES (%s, %s) ...
555
170
import datetime as dt from os.path import dirname, join import numpy as np import pandas as pd import pyarrow as pa import pyarrow.parquet as pq from bokeh.io import curdoc from bokeh.layouts import column, gridplot, row from bokeh.models import ColumnDataSource, DataRange1d, Select, HoverTool, Panel, Tabs, LinearC...
9,693
3,363
""" ================ HTTPS Middleware ================ Change scheme for current request when aiohttp application deployed behind reverse proxy with HTTPS enabled. Usage ===== .. code-block:: python from aiohttp import web from aiohttp_middlewares import https_middleware # Basic usage app = web.App...
2,223
615
import cv2 import numpy as np class DrawingClass(object): def __init__(self): self.draw_command ='None' self.frame_count = 0 def drawing(self, frame, fps, num_egg, htc_egg, state): cv2.putText(frame, 'FPS: {:.2f}'.format(fps), (10, 30), cv2.FONT_HERSHEY_SIMP...
6,620
3,009
import pandas_datareader.data as pdr import yfinance as fix import numpy as np fix.pdr_override() def back_test(strategy, seq_len, ticker, start_date, end_date, dim): """ A simple back test for a given date period :param strategy: the chosen strategy. Note to have already formed the model, and fitted with...
1,452
476
# -*- coding: utf-8 """Module for custom component groups. It is possible to create subsystems of component groups in tespy. The subsystem class is the base class for custom subsystems. This file is part of project TESPy (github.com/oemof/tespy). It's copyrighted by the contributors recorded in the version control ...
2,278
667
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. import copy import logging from typing import TYPE_CHECKING, Any, Callable, List, Optional, Type import torch import tor...
7,940
2,195
from setuptools import setup, find_packages setup( name="raytracing-one-weekend", version="0.0.0", author="Andy Palmer", author_email="contactninezerozeronine@gmail.com", description="A raytracer achievable in a weekend.", url="https://github.com/ninezerozeronine/raytracing-one-weekend", in...
445
156
""" URLconf of the homepage """ from django.urls import path, include from . import views urlpatterns = [ path('', views.home, name='home'), path('auth', views.auth, name='auth'), path('auth/public', views.auth_public, name='auth-public'), path('auth/full', views.auth_full, name='auth-full'), p...
603
210
""" Notification email machinery, for tasks to send credentials and instructions to users. Email templates placed inside the `templates` directory of this module should: - extend from `layout` - provide `subject` and `body` blocks """ from enum import Enum import os.path from jinja2 import Environment, FileSystemLo...
3,058
879
from .operations import Multiply, Add, Substract class MyApp(object): def __init__(self): self.operations={'multiply': Multiply, 'add': Add, 'substract': Substract} def do(self, operation, number1, number2): return self.operations[operation.low...
348
102