text string | size int64 | token_count int64 |
|---|---|---|
from dulwich.repo import Repo
from dulwich.client import get_transport_and_path
import sys
def push(remote_url, repo_path='.'):
"""
Push to a remote repository
:param remote_url: <str> url of remote repository
:param repo_path: <str> path of local repository
:return refs: <dict> dictionary of ref-... | 1,159 | 357 |
import torch
from glasses.nn.regularization import DropBlock, StochasticDepth
def test_drop_block():
drop = DropBlock()
x = torch.ones((1, 3, 28, 28))
x_drop = drop(x)
assert not torch.equal(x, x_drop)
assert drop.training
drop = drop.eval()
x_drop = drop(x)
assert torch.equal(x, x_d... | 711 | 299 |
#! /Users/susorhc1/anaconda/bin/python
##
##
##
# Program: dD_plots_lon_runbin
# Author: Hannah C.M. Susorney
# Date Created: 2020-03-03
#
# Purpose: To compare depth/diameter measurements in overlapping longitude bins
# Used in study
#
# Required Inputs: .csv of data
#
# Updates: 2021-08-31 - Clean and document cod... | 27,200 | 11,648 |
from bs4 import BeautifulSoup as Soup
import re
import json
import sys
import shutil
import tempfile
import os
import subprocess
from pathlib import Path
from docassemble.base.util import log, path_and_mimetype, validation_error, DADict, DAList, Individual, value, force_ask, space_to_underscore
__all__ = ['run_automa... | 24,158 | 6,951 |
#! /usr/bin/env python3
import sys
import argparse
from graphenetools import gt
def create_parser():
parser = argparse.ArgumentParser(description="Plot graphene lattice and C1/3 phase corresponding to printed command line arguments for uniaxially strained graphene (for use with QMC software located at https://code... | 2,571 | 788 |
from django.contrib import admin
from .models import UserProfile
class ProfileAdmin(admin.ModelAdmin):
"""Display the user profiles created in the Admin panel."""
list_display = (
'user',
'default_full_name',
'default_email',
'default_country',
)
admin.site.register(UserPr... | 341 | 93 |
from django.db import models
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.utils import timezone
from django.utils.translation i... | 15,509 | 4,088 |
from .dataset import Dataset, Document
| 40 | 11 |
import psycopg2
import re
import json
from MedTAG_sket_dock_App.models import *
import os
import pandas as pd
import numpy
from psycopg2.extensions import register_adapter, AsIs
def addapt_numpy_float64(numpy_float64):
return AsIs(numpy_float64)
def addapt_numpy_int64(numpy_int64):
return AsIs(numpy_int64)
regi... | 29,332 | 6,560 |
import sys
sys.path.append("/home/ly/workspace/mmsa")
seed = 1938
import numpy as np
import torch
from torch import nn
from torch import optim
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
from models.bigru_rcnn_gate import *
from utils.train import *
from t... | 1,159 | 441 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
########################################################################
# GNU General Public License v3.0
# GNU GPLv3
# Copyright (c) 2019, Noureldien Hussein
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General ... | 2,113 | 792 |
#mostre quando a pessoa vai pagar com o desconto de 5%
preco = float(input('Digite o Preço do Produto R$: '))
desconto = preco * 0.05
print(f'O preço do Produto é de R${preco:.2f} com o Desconto de R${desconto:.2f} \nO Total vai ficar R$:{preco - desconto:.2f}') | 262 | 117 |
#!/usr/bin/env python
# coding: utf-8
# In[65]:
from sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer
from sklearn.naive_bayes import BernoulliNB, MultinomialNB
from sklearn import metrics
from sklearn.metrics import roc_auc_score, accuracy_score
import requests
from bs4 import BeautifulSoup
im... | 20,534 | 7,451 |
import json
import numpy as np
import os
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense, Dropout, Embedding, Flatten, Activation, BatchNormalization
from sklearn.model_selection import train_test_split
class SuggestionModeler(object):
"""
A collection of functions ... | 5,808 | 1,874 |
preço = float(input('Digite o preço do produto: R$'))
d = preço * 0.05
vD = preço - d
print('Valor original R${:.2f}, desconto de 5% é igual à R${:.2f}, seu novo preço é R${:.2f}'.format(preço, d, vD)) | 203 | 95 |
"""
Logic related to License, PatternMatch, etc. for atmosphere.
"""
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
from core.models.license import License, LicenseType
from core.models.match import PatternMatch, MatchType
from core.models.identity import Identit... | 3,282 | 941 |
import support
support.tune_all(pairs_to_tune=support.pairs, verbose=1)
| 73 | 30 |
import numpy as np
import tensorflow as tf
from encoder import Encoder
from decoder import Decoder, TreeDecoder
import bisect
from time import time
class PointerNet(object):
def __init__(self, vsize, esize, hsize, asize, buckets, **kwargs):
super(PointerNet, self).__init__()
self.name = kwargs.... | 11,524 | 4,096 |
import itertools
from typing import Sequence
import torch.nn as nn
import torch
from perceiver_io.io_processors.preprocessors import ImagePreprocessor
from perceiver_io.io_processors.processor_utils import patches_for_flow
from perceiver_io.output_queries import FlowQuery
from perceiver_io.perceiver import PerceiverI... | 7,695 | 2,315 |
load(":import_external.bzl", import_external = "import_external")
def dependencies():
import_external(
name = "commons_fileupload_commons_fileupload",
artifact = "commons-fileupload:commons-fileupload:1.4",
artifact_sha256 = "a4ec02336f49253ea50405698b79232b8c5cbf02cb60df3a674d77a749a1def7"... | 489 | 228 |
##################################################
#
# Tests for model.py
#
#
#
#
#
#
#
#
#
#
#
##################################################
from boole.core.model import *
from boole.core.language import clear_default_language
from nose.tools import *
def is_prime(x):
if x == 0 or x == 1:
return Fa... | 8,654 | 3,731 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Sniffs RF4CE packets. Supports encryption.
"""
from __future__ import (absolute_import,
print_function, unicode_literals)
from builtins import *
import argparse
from datetime import datetime
import binascii
from rf4ce import Dot15d4FCS, Dot15... | 3,739 | 1,522 |
# from electrum_stratis.i18n import _
# fullname = 'Plot History'
# description = _("Ability to plot transaction history in graphical mode.")
# requires = [('matplotlib', 'matplotlib')]
# available_for = ['qt']
| 213 | 67 |
#!/usr/bin/env python3
"""
Host the setup function.
"""
import pathlib
import setuptools
from cushead import info
def setup() -> None:
"""
Execute the setup.
"""
assets_path = pathlib.Path(info.PACKAGE_NAME) / "console" / "assets" / "images"
templates_path = pathlib.Path(info.PACKAGE_NAME) / "ge... | 2,600 | 778 |
#!~/bike-computer/.venv/bin python
import picamera
import datetime
path = '/home/pi/bike-computer/data/'
with picamera.PiCamera(resolution=(1640,1232),framerate=30) as camera:
try:
while True:
#start_time = datetime.datetime.now().timestamp()
for filename in camera.record_sequence(path+'%d.h264' % i for... | 414 | 169 |
#!/usr/bin/env python
import unittest
import pytest
import sys, os
import logging
import pdfplumber
from pdfplumber import table
from pdfplumber.utils import Decimal
logging.disable(logging.ERROR)
HERE = os.path.abspath(os.path.dirname(__file__))
class Test(unittest.TestCase):
@classmethod
def setup_clas... | 2,687 | 1,060 |
import torchvision.models as models
from torch.nn import Module, Sequential, Linear
class Model(Module):
def __init__(self, pretrained: bool = False, in_dim: int = 2048, out_dim: int = 256):
super(Model, self).__init__()
self.resnet = Sequential(*list(models.resnet50(pretrained=pretrained).childr... | 546 | 198 |
import os, sys
import re
import zipfile
import requests
import warnings
import logging
import pandas as pd
import numpy as np
from stat import S_IREAD, S_IRGRP, S_IROTH
import getpass
import pymysql
# Code by Jeff Levy (jlevy@urban.org), 2016-2017
class LoadData():
"""
This class is inherited by the Data clas... | 17,625 | 4,992 |
import boto3
import os
import json
from botocore.exceptions import ClientError
try:
POLLY_METADATA_STORE = os.environ['POLLY_METADATA_STORE']
except KeyError as e:
print(f"Missing env variable: {e}")
exit(1)
dynamo = boto3.resource("dynamodb")
polly_metadata_store = dynamo.Table(POLLY_METADATA_STORE)
def... | 2,737 | 973 |
import sys
import ctypes
class Encoding:
# Unknown - the default value
IR_ENCODING_UNKNOWN = 1
# Space encoding, or Pulse Distance Modulation
IR_ENCODING_SPACE = 2
# Pulse encoding, or Pulse Width Modulation
IR_ENCODING_PULSE = 3
# Bi-Phase, or Manchester encoding
IR_ENCODING_BIPHASE = 4
# RC5 - a type of Bi-P... | 888 | 416 |
from PedSimulation.scene import *
from PedSimulation.gui.ui.mainwindow_main import Ui_MainWindow_Main
from PedSimulation.gui.ui.mainwindow_setting import Ui_MainWindow_Setting, Dragebutton
from PedSimulation.gui.drawer.drawer_register import SceneDrawerRegister
from PyQt5 import QtCore
from PyQt5.QtWidgets import QDesk... | 13,525 | 4,140 |
#!/usr/bin/env python3
"""An instantiable component. See the docstring for the class."""
from __future__ import absolute_import, division, print_function
from future.utils import with_metaclass
import logging
import inspect
class NamedClass(type):
"""
A read-only name property for classes. See
http://sta... | 1,608 | 462 |
# Copyright (c) 2021 Binbin Zhang(binbzha@qq.com)
#
# 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 a... | 2,288 | 702 |
from maya import cmds
import copy
# TODO: Find a way to have different naming for different production.
# Maybe handle it in the rig directly?
class BaseName(object):
"""
This class handle the naming of object.
Store a name as a list of 'tokens'
When resolved, the tokens are joinned using a 'separator... | 5,711 | 1,830 |
# Copyright 2022 Tiernan8r
#
# 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 writing, so... | 2,185 | 598 |
import math
import numpy as np
import torch
from mock import patch
from core.train_utils import compute_angular_error, compute_angular_error_xyz_arr, spherical2cartesial
def test_spherical2cartesial():
spherical = torch.Tensor([
[0, 0],
[math.pi / 2, 0],
[-math.pi / 2, 0],
[0, ma... | 2,090 | 907 |
from rest_framework import serializers
from scripts.models import Manuscript
from scripts.models import Page
from scripts.models import Coordinates
class ManuscriptSerializer(serializers.ModelSerializer):
class Meta:
model = Manuscript
fields = ('id', 'slug', 'shelfmark', 'date', 'manifest')
cla... | 732 | 200 |
import csv
import re
from os import makedirs
from os.path import abspath, basename, dirname, isdir, join
def generate_csv(path, fields, rows, quote_empty=False):
path = abspath(path)
name = basename(path)
name = re.sub('py$', 'csv', name)
cases = join(dirname(dirname(path)), 'cases')
if not isdir(... | 750 | 265 |
from datetime import datetime
import traceback
import boto3
from botocore.exceptions import ClientError
from ...config import config
from ...log import log
class Submitter():
def __init__(self, event):
self.event = event
def find_instance(self, instance_id, mac_address): # pylint: disable=R0201
... | 8,196 | 2,230 |
import asyncio
import json
import os
import sys
import multiprocessing
import webbrowser
import requests
import requests.cookies
import logging as log
import subprocess
import time
from galaxy.api.consts import LocalGameState, Platform
from galaxy.api.plugin import Plugin, create_and_run_plugin
from galaxy.api.types ... | 19,754 | 5,472 |
import pytest
from buyer import serializers
@pytest.mark.django_db
def test_buyer_deserialization():
data = {
'email': 'jim@example.com',
'name': 'Jim Exampleson',
'sector': 'AEROSPACE',
'company_name': 'Example corp',
'country': 'China',
}
serializer = serializer... | 649 | 202 |
from moai.utils.arguments.common import (
assert_numeric,
assert_non_negative,
assert_negative,
)
from moai.utils.arguments.choices import (
assert_choices,
ensure_choices,
)
from moai.utils.arguments.list import (
ensure_numeric_list,
ensure_string_list,
assert_sequence_size,
)
from moa... | 637 | 216 |
##########################################################################
# Copyright (c) 2009, ETH Zurich.
# All rights reserved.
#
# This file is distributed under the terms in the attached LICENSE file.
# If you do not find this file, copies can be found by writing to:
# ETH Zurich D-INFK, Universitaetstrasse 6, CH... | 1,258 | 384 |
#1d_tests.py
import autograd.numpy as np
import autograd.scipy.stats.norm as norm
from copy import copy
import datetime as dt
from matplotlib import pyplot as plt
import seaborn as sns
import sys; sys.path.append('..')
from mcmc import langevin, MALA, RK_langevin, RWMH, HMC
def bimodal_logprob(z):
return (np.log(n... | 2,243 | 1,039 |
import qrcode
# data example
data = "www.google.com"
# file name
file_name = "qrcode.png"
# generate qr code
img = qrcode.make(data=data)
# save generated qr code as img
img.save(file_name)
| 195 | 78 |
import click
import inspect
import os
import requests
from onecodex.exceptions import OneCodexException, UnboundObject
def as_uri(uuid, base_class):
return base_class._resource._schema._uri.rstrip("#") + "/" + uuid
def coerce_search_value(search_value, field_name, base_class):
from onecodex.models import O... | 7,845 | 2,139 |
from itertools import count, product
import numpy as np
grid = np.genfromtxt("input.txt", delimiter=1, dtype=int)
def propagate_flash(grid, i, j, flash_mask):
flash_mask[i, j] = 1
for di, dj in product(range(-1, 2), range(-1, 2)):
if 0 <= i + di < grid.shape[0] and 0 <= j + dj < grid.shape[1]:
... | 932 | 360 |
# Calculate the intersection of the land use polygons with Muette
land_use_muette = land_use.geometry.intersection(muette) | 122 | 36 |
"""
Low level miscilanious calls
"""
import UserDict
import types
import random
import datetime
import pprint
import re
import unicodedata
import logging
log = logging.getLogger(__name__)
now_override = None
def now():
"""
A passthough to get now()
We can override this so that automated tests can fake ... | 7,754 | 2,587 |
class Node:
props = ()
def __init__(self, **kwargs):
for prop in kwargs:
if prop not in self.props:
raise Exception('Invalid property %r, allowed only: %s' %
(prop, self.props))
self.__dict__[prop] = kwargs[prop]
for prop... | 6,421 | 2,221 |
import os
import cv2
from ReceiptGenerator.draw_receipt import create_crnn_sample
NUM_OF_TRAINING_IMAGES = 3000
NUM_OF_TEST_IMAGES = 1000
TEXT_TYPES = ['word', 'word_column', 'word_bracket', 'int', 'float', 'price_left', 'price_right', 'percentage']
# TEXT_TYPES = ['word']
with open('./ReceiptProcessor/training_ima... | 1,381 | 483 |
import os
from pydantic import BaseSettings
class AppSettings(BaseSettings):
debug: bool = False
time_zone: str = "Asia/Shanghai"
logger_level: str = "INFO"
logger_formatter: str = "%(asctime)s [%(name)s] %(funcName)s[line:%(lineno)d] %(levelname)-7s: %(message)s"
secret_key: str = "1@3$5^7*9)"
... | 1,487 | 533 |
# coding: utf-8
"""
Layered Insight Assessment, Compliance, Witness & Control
LI Assessment & Compliance performs static vulnerability analysis, license and package compliance. LI Witness provides deep insight and analytics into containerized applications. Control provides dynamic runtime security and analyti... | 4,867 | 1,370 |
# configure debugging
import os
from .local import *
DEBUG=True
TEMPLATE_DEBUG = True
INTERNAL_IPS = ('127.0.0.1',)
MIDDLEWARE_CLASSES.extend([
#'debug_toolbar.middleware.DebugToolbarMiddleware',
])
DATABASES = {
'fctracker': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/var/htsworkflo... | 540 | 218 |
# Generated with SMOP 0.41-beta
try:
from smop.libsmop import *
except ImportError:
raise ImportError('File compiled with `smop3`, please install `smop3` to run it.') from None
# Script_DoubleBarrierOptions.m
##################################################################
### DOUBLE BARRIER OPT... | 4,343 | 1,507 |
# Generated by Django 2.2.10 on 2020-01-28 07:01
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('computes', '0001_initial'),
]
operations = [
migrations.CreateModel(
name=... | 870 | 267 |
'''
Different utils used by plotters.
'''
import mpl_toolkits.basemap as bm
import matplotlib.pyplot as pl
from matplotlib import colors, cm
import scipy as sp
# Make spectral plot
def my_psd(x):
P,f=pl.psd(x); pl.clf()
T=2./f; ind= T>=12.
pl.plot(T[ind]/12,P[ind]);
ax=pl.gca();
ax.set_xscale('lo... | 1,145 | 471 |
"""
These are various mehtods that can be used in the training process. Some
return values, some display images. Best used in Jupyter Notebooks.
"""
from __future__ import division, print_function, absolute_import
# Use one of these based on the version of skimage loaded
from skimage.util import montage
# from skima... | 23,708 | 6,897 |
#!/usr/bin/env python
"""
Lyrebird Voice Changer
Simple and powerful voice changer for Linux, written in GTK 3
(c) Charlotte 2020
"""
import sys
import re
from setuptools import setup
version_regex = r'__version__ = ["\']([^"\']*)["\']'
with open('app/__init__.py', 'r') as f:
text = f.read()
match = re.search... | 1,125 | 373 |
from .curve import ParametricCurve as _ParametricCurve
from sympy import Symbol as _Symbol
def curve_normalization(
other:_ParametricCurve,
new_var=_Symbol('s', real=True)):
from sympy import S, solveset, Eq
from sympy import integrate
from silkpy.sympy_utility import norm
drdt = norm(othe... | 1,617 | 583 |
from pyroute2.netlink import rtnl
from pyroute2.netlink import NETLINK_ROUTE
from pyroute2.netlink.nlsocket import NetlinkSocket
from pyroute2.netlink.rtnl.marshal import MarshalRtnl
class RawIPRSocketMixin(object):
def __init__(self, fileno=None):
super(RawIPRSocketMixin, self).__init__(NETLINK_ROUTE, f... | 556 | 210 |
from zhixuewang.urls import BASE_URL
class Url:
INFO_URL = f"{BASE_URL}/container/container/student/account/"
CHANGE_PASSWORD_URL = f"{BASE_URL}/portalcenter/home/updatePassword/"
TEST_URL = f"{BASE_URL}/container/container/teacher/teacherAccountNew"
GET_EXAM_URL = f"{BASE_URL}/classreport/class/cl... | 1,013 | 393 |
sort = lambda array: [sublist for sublist in sorted(array, key=lambda x: x[1])]
if __name__ == "__main__":
print(sort([
("English", 88),
("Social", 82),
("Science", 90),
("Math", 97)
]))
| 229 | 89 |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from helusers.models import AbstractUser
class User(AbstractUser):
is_official = models.BooleanField(verbose_name=_("official"), default=False)
class Meta:
verbose_name = _("user")
verbose_name_plural = _("us... | 451 | 139 |
import time
import traceback
from python_terraform import Terraform
from src.main.python.tranquilitybase.gcpdac.configuration.helpers.eaglehelper import EagleConfigHelper
from src.main.python.tranquilitybase.gcpdac.configuration.helpers.envhelper import EnvHelper
from src.main.python.tranquilitybase.gcpdac.main.core.t... | 3,904 | 1,217 |
import logging
import json
import os.path
LOG = logging.getLogger(__name__)
class JsonFile(object):
def __init__(self, path, default_data=None, ignore_errors=False,
header=None):
'''Construct a new JsonFile.
Parameters
----------
default_data : dict
... | 2,692 | 729 |
"""
Twitch API Module.
This module implements only those parts of the Twitch API needed for the
twitchalyze app to function. It is not a general purpose SDK.
This module is written against Version 5 of the Twitch API.
"""
import json
import requests
# Read in user configuration
with open('.twitchalyze') as data_fil... | 982 | 324 |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import pandas as pd
import glob,os,csv,re,math
import shutil, time
from astropy.io import ascii
import matplotlib.pyplot as plt
# Load all data files:
psdir ='/Users/maryumsayeed/Desktop/HuberNess/mlearning/powerspectrum/'
hrdir ='/Users/maryu... | 12,956 | 5,485 |
"""
See Ian P. Gent, Christopher Jefferson, Ian Miguel: Watched Literals for Constraint Propagation in Minion. CP 2006: 182-197
Examples of Execution:
python3 LangfordBin.py
python3 LangfordBin.py -data=10
"""
from pycsp3 import *
n = data or 8
# v[i] is the ith value of the Langford's sequence
v = VarArray(siz... | 646 | 287 |
# Authors: Michael Sander, Pierre Ablin
# License: MIT
"""
Original code from
Maclaurin, Dougal, David Duvenaud, and Ryan Adams.
"Gradient-based hyperparameter optimization through reversible learning."
International conference on machine learning. PMLR, 2015.
"""
import numpy as np
import torch
RADIX_SCALE = 2 ** 5... | 3,912 | 1,300 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/TechLaProvence/lp_mongodb
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 figarocms dhardy@figarocms.fr
from tornado.concurrent import return_future
from lp_mongodb.storag... | 531 | 181 |
import numpy as np
from tabulate import tabulate
import matplotlib.pyplot as plt
import Page_Rank_Utils as pru
def detectedConverged(y,x,epsilon):
C = set()
N = set()
for i in range(len(y)):
if abs(y[i] - x[i])/abs(x[i]) < epsilon:
C.add(i)
else:
N.add(i)
return... | 857 | 334 |
from troyka_led_matrix import TroykaLedMatrix
from urandom import getrandbits
import time
matrix = TroykaLedMatrix()
while True:
matrix.draw_pixel(getrandbits(3), getrandbits(3))
matrix.clear_pixel(getrandbits(3), getrandbits(3))
time.sleep_ms(50)
| 272 | 105 |
import json
import logging
from datetime import datetime, timezone
from ..enip_common.pg import get_ro_cursor
from .run import export_all_states, export_national
# Bulk-exports a range of ingests for testing purposes. Prints out a JSON
# blob describing the exports.
START_TIME = datetime(2020, 10, 15, 16, 0, 0, tzinf... | 1,560 | 546 |
''' show_chassis.py
Parser for the following show commands:
* show chassis fpc detail
* show chassis environment routing-engine
* show chassis firmware
* show chassis firmware no-forwarding
'''
# python
import re
from genie.metaparser import MetaParser
from genie.metaparser.util.schemaengine import (... | 11,032 | 3,334 |
import math
import itertools
class Vector:
"""
Generic vector operations.
"""
def _apply(self,op, other):
pairwise = None
if type(other) is Vector:
pairwise = zip(self.vals, other.vals)
else:
pairwise = zip(self.vals, [other for _ ... | 2,009 | 717 |
"""Module containing global playground constants and functions."""
import os
from google.appengine.api import app_identity
from google.appengine.api import backends
DEBUG = True
COMPUTE_IDLE_INSTANCES_TARGET = 0
COMPUTE_INSTANCE_TTL_MINUTES = 10
COMPUTE_PROJECT_ID = app_identity.get_application_id()
COMPUTE_ZON... | 1,230 | 500 |
import numpy as np
import os
os.environ['TF_FORCE_GPU_ALLOW_GROWTH']='true'
import datetime
from sacred import Experiment
from sacred.observers import FileStorageObserver
from datasets.ucf101 import UCF101Dataset
from algorithms.kerasvideoonenet import KerasVideoOneNet
from algorithms.kerasvideoonenet_admm import Keras... | 4,984 | 1,707 |
## This script requires "requests": http://docs.python-requests.org/
## To install: pip install requests
import requests
import json
FRESHDESK_ENDPOINT = "http://YOUR_DOMAIN.freshdesk.com" # check if you have configured https, modify accordingly
FRESHDESK_KEY = "YOUR_API_TOKEN"
user_info = {"user":{"name":"Example U... | 594 | 203 |
# Generated by Django 2.2.2 on 2020-03-07 03:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ordenes', '0002_auto_20200305_0056'),
]
operations = [
migrations.AddField(
model_name='orden',
name='guia_de_envio'... | 1,102 | 431 |
#tiersweekly.py
from fantasyfootball import tiers
from fantasyfootball import fantasypros as fp
from fantasyfootball import config
from fantasyfootball import ffcalculator
from fantasyfootball.config import FIGURE_DIR
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture
from matplotlib import... | 8,311 | 3,005 |
from makememe.generator.prompts.prompt import Prompt
import datetime
from PIL import Image
from makememe.generator.design.image_manager import Image_Manager
class Ineffective_Solution(Prompt):
name = "Ineffective_Solution"
description = "the solution was a poor way of doing it"
def __init__(self):
... | 2,629 | 850 |
"""Pauses the execution."""
import time
from dodo_commands.framework.decorator_utils import uses_decorator
class Decorator:
def is_used(self, config, command_name, decorator_name):
return uses_decorator(config, command_name, decorator_name)
def add_arguments(self, parser): # override
parser... | 665 | 216 |
class Solution:
def decompressRLElist(self, nums: List[int]) -> List[int]:
de = []
for i in range(0, len(nums), 2):
pair = []
pair.append(nums[i])
pair.append(nums[i + 1])
arr = [nums[i + 1]] * nums[i]
de += arr
return de
| 310 | 108 |
from marshmallow import (fields, post_load, Schema, validate, validates,
validates_schema, ValidationError)
from {{cookiecutter.project_slug}}.lib.hash import compare_plaintext_to_hash, hash_plaintext
from {{cookiecutter.project_slug}}.models.user import User, get_user_by_email_address
MIN_PA... | 4,060 | 1,094 |
class SubCommand:
def __init__(self, command, description="", arguments=[], mutually_exclusive_arguments=[]):
self._command = command
self._description = description
self._arguments = arguments
self._mutually_exclusive_arguments = mutually_exclusive_arguments
def getCommand(self)... | 568 | 144 |
import logging
from typing import List
from .AnaplanRequest import AnaplanRequest
from .User import User
from .ModelDetails import ModelDetails
logger = logging.getLogger(__name__)
class Model(User):
def get_models_url(self) -> AnaplanRequest:
"""Get list of all Anaplan model for the specified user.
:return: O... | 1,304 | 433 |
from unittest import mock
from lms.extensions.feature_flags.views._predicates import FeatureFlagViewPredicate
class TestFeatureFlagsViewPredicate:
def test_text(self):
assert (
FeatureFlagViewPredicate("test_feature", mock.sentinel.config).text()
== "feature_flag = test_feature"
... | 883 | 264 |
def read_file(filepath):
with open(filepath,'r') as i:
inst = [int(x) for x in i.read().replace(')','-1,').replace('(','1,').strip('\n').strip(',').split(',')]
return inst
def calculate(inst,floor=0):
for i,f in enumerate(inst):
floor += f
if floor < 0: break
... | 468 | 168 |
# Hangman game
#
# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)
import random
import string
WORDLIST_FILENAME = "/Users/deedeebanh/Documents/MITx_6.00.1.x/ProblemSet3/word... | 4,810 | 1,372 |
from database_creation.nyt_article import Article
from database_creation.utils import Tuple, Wikipedia, Query, Annotation
from numpy import split as np_split
from numpy.random import seed, choice
from time import time
from glob import glob
from collections import defaultdict
from pickle import dump, load, PicklingErro... | 39,909 | 11,001 |
#!/usr/bin/python3
import argparse
from datetime import datetime
import json
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5 import uic
import os
import sys
from weather import Weather
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
DISP_SIZE = (640, 384)
WHITE = 0xffffffff
BLACK = 0xff000... | 3,623 | 1,214 |
import os
from run_grtrans_test_problems import run_test_problems
from unit_tests import run_unit_tests
passed, max_passed, failed = run_test_problems(save=0)
nfailed, ufailed = run_unit_tests()
if passed < max_passed or nfailed > 0: print 'ERROR -- grtrans tests failed!'
else:
# os.chdir('..')
# os.system('cvs... | 677 | 255 |
"""Exceptions for the Luftdaten Wrapper."""
class LuftdatenError(Exception):
"""General LuftdatenError exception occurred."""
pass
class LuftdatenConnectionError(LuftdatenError):
"""When a connection error is encountered."""
pass
class LuftdatenNoDataAvailable(LuftdatenError):
"""When no dat... | 349 | 96 |
from sklearn.metrics import r2_score
y_true = [3, -0.5, 2, 7]
y_pred = [2.5, 0.0, 2, 8]
r2=r2_score(y_true, y_pred)
print(r2)
y_true = [5,6,7,8]
y_pred = [-100,524,-1,3]
r2=r2_score(y_true, y_pred)
print(r2)
r2_ | 215 | 138 |
import pytest
from ssz.sedes import Bitvector
def test_bitvector_instantiation_bound():
with pytest.raises(ValueError):
bit_count = 0
Bitvector(bit_count)
| 178 | 60 |
# Seguridad Informatica
# ejercicio de encriptacion
# Angelo Padron (42487)
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
with open('key.bin', 'rb') as k:
key = k.read()
with open('vector.bin', 'rb') as v:
init_vector = v.read()
cipher = AES.new(key, AES.MODE_CBC, ... | 613 | 233 |
"""
@Time: 2018/5/11 10:57
@Author: qingyaocui
"""
from course.src.service import admin_service
from course.src.models import Student
login_stu = None
def show_choice():
show = '''
1.菜单
2.登录
3.注册
4.查看成绩
Q|q.退出系统
'''
print(show)
def login():
s_name = input... | 1,597 | 650 |
import numpy as np
import os
from six.moves import cPickle as pickle
import neuralnetwork as nn
import inputdata
# ----------------------------------------------------------------------------- #
arser = argparse.ArgumentParser()
parser.add_argument('-valid_train', action='store', dest='valid_train', help='Valid/Trai... | 2,328 | 751 |
def test_check_left_panel(app):
app.login(username="admin", password="admin")
app.main_page.get_menu_items_list()
app.main_page.check_all_admin_panel_items()
| 184 | 76 |