content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
__author__ = 'study_sun'
from spider_base.downloader import *
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class IndexDownloader(SBDownloader):
pass |
INPUT_IMAGE_WIDTH = 1024
|
##### Imports #####
from datetime import date, datetime
import json
import dateutil.parser
import babel
from flask import (
Flask,
render_template,
request,
Response,
flash,
redirect,
url_for)
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from flask_migrate ... |
#!/usr/bin/env python
""" a collection of functions for reading EEG signals and applying basic filtering operations
"""
import os
import scipy.io
import numpy as np
from scipy.signal import butter, lfilter
def butter_lowpass(cutoff, fs, order=5):
""" wrapper for calculating parameters of a lowpass filter
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import models, migrations
import orchestra.models.fields
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_... |
raise ValueError("test failed! wrapper did not ignore polluted PWD. either the wrapper is faulty, or ooni is still unpatched (Tor bug #13581)")
|
"""empty message
Revision ID: 879fe8a73df4
Revises: 8c3766231a8f
Create Date: 2018-06-07 19:56:40.800424
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '879fe8a73df4'
down_revision = '8c3766231a8f'
branch_labels = None
depends_on = None
def upgrade():
# ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('peacecorps', '0035_auto_20141202_2354'),
]
operations = [
migrations.AddField(
model_name='campaign',
... |
import time
from flask import request, jsonify, make_response
from app import app
from controllers.mock_data import request_method_list, get_mock_data
@app.route('/mock/<path:path>', methods=request_method_list)
def mock_call(path):
try:
if not path.startswith('/'):
path = "/" + path
... |
# Hyppopy - A Hyper-Parameter Optimization Toolbox
#
# Copyright (c) German Cancer Research Center,
# Division of Medical Image Computing.
# All rights reserved.
#
# This software is distributed WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.
#
# See L... |
"""Routines for performing spectral unmixing on earth engine images."""
import ee as _ee
from tqdm import tqdm as _tqdm
from .utils import selectSpectra as _selectSpectra
# this function must be run before any of the specific unmixing routines are set
def Initialize(sensor, n=30, bands=None):
"""Initializes sen... |
from builtins import *
import numpy as np
import scipy.linalg
from scipy.special import gammaln, digamma
from bnpy.suffstats import ParamBag, SuffStatBag
from bnpy.util import LOGTWO, LOGPI, LOGTWOPI, EPS
from bnpy.util import dotATA, dotATB, dotABT
from bnpy.util import as1D, as2D, as3D, toCArray
from bnpy.util impor... |
import networkx as nx
import operator
import matplotlib.pyplot as plt
g = nx.read_weighted_edgelist('data/edgelist24.csv')
degree = nx.degree(g)
numNodes = nx.number_of_nodes(g)
numEdges = nx.number_of_edges(g)
minDegree = min([item[1] for item in degree])
maxDegree = max([item[1] for item in degree])
print(degree)
... |
# Copyright 2019 Google LLC
#
# 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, ... |
import vcr
from .common import *
from keepassxc_pwned.cli import main_wrapper
from keepassxc_pwned.parser import Database
db_file_loc = os.path.join(db_files, "duplicate_entry.kdbx")
db_pw = "duplicate_entry"
@pytest.fixture()
def database():
db: Database = Database(pathlib.Path(db_file_loc))
db._password ... |
import sys
import logging
import random
import numpy as np
import os
# from nltk.corpus import wordnet as wn
import argparse
import torch
import pickle
from transformers import GPT2Tokenizer, TransfoXLTokenizer
from shutil import copyfile
import collections
from multiprocessing.pool import Pool
import multiprocessing
... |
from keras.models import load_model
import cv2
import numpy as np
from mtcnn.mtcnn import MTCNN
cap = cv2.VideoCapture(0)
model = load_model('../model/face-detector-model.h5')
size = (200, 200)
detector = MTCNN()
while True:
ret, frame = cap.read()
faces = detector.detect_faces(frame)
for face in fac... |
# Copyright 2018 The TensorFlow 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 applica... |
from mayan.apps.testing.tests.base import BaseTestCase
from ..events import event_otp_disabled, event_otp_enabled
from .mixins import AuthenticationOTPTestMixin
class UserOTPDataTestCase(AuthenticationOTPTestMixin, BaseTestCase):
create_test_case_superuser = True
def test_method_get_absolute_url(self):
... |
import xlwings as xw
import requests
from aruba import Config, switch
def vlans(data):
"""Enumera las VLANs del switch"""
# Obtengo el workbook, las coordenadas y la dirección IP del servidor API
wb, row, col, api_host = splitExcel(data)
# Y ahora, obtengo los datos del switch
with switch.sessio... |
"""
module(requirement) - Python依赖.
Main members:
# check_requirement - 检查依赖.
"""
from qytPython import logger
# 模块与pypi对应关系
module_pypi_config = {
'docx': 'python-docx',
'yaml': 'PyYAML'
}
def check_requirement(module_obj, module_name):
""" 检查依赖.
@params:
... |
import numpy as np
# See discussion around this question: https://stackoverflow.com/questions/2018178/finding-the-best-trade-off-point-on-a-curve/2022348#2022348
def index_of_elbow(points):
"""Returns the index of the "elbow" in ``points``.
Decently fast and pretty approximate. Performs worse with disproporti... |
from .abstract import *
from .. import schema
class Lead( ListableAPIResource, MutableAPIResource ):
"""
Attributes:
assessment_run_id (str): ID of the associated assessment run
confidence (mage.schema.Confidence): Confidence level of the lead
created_at (str): When the lead was created... |
# Generated by Django 3.1.4 on 2021-01-02 07:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
... |
import unittest
import numpy as np
from svreg.summation import Rho, FFG
from tests._testStructs import _all_test_structs, r0
class Test_Summation(unittest.TestCase):
def setUp(self):
self.ffg = FFG(
name='ffg',
allElements=['H', 'He'],
neighborElements=['H', 'He'],
... |
from .testing import Tester
from .training import Trainer
from .dataloader import multiview_dataloader
def get_trainer(cfg, net, optimizer, device=None):
return Trainer(cfg=cfg, net=net, optimizer=optimizer, device=device)
def get_tester(cfg, net, device=None):
return Tester(cfg=cfg, net=net, device=device)
... |
from datetime import timedelta, datetime
from django.conf import settings
from django.utils.timezone import make_aware
import pytz
from rest_framework import exceptions
from rest_framework.authentication import TokenAuthentication
import logging
logger = logging.getLogger(__name__)
class BearerAuthentication(TokenA... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" hdf5events.py
Description:
"""
# Package Header #
from ..__header__ import *
# Header #
__author__ = __author__
__credits__ = __credits__
__maintainer__ = __maintainer__
__email__ = __email__
# Imports #
# Standard Libraries #
import datetime
import time
import uuid
... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Module Level Imports
# -----------------------------------------------------------------------------
from .typings import (
missing,
snowflake,
nullable,
string,
optional,
snowflakearray,
... |
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
class Logger:
def __init__(self, cnf):
self.dat, self.acc, self.cnf = [], 0, cnf
self.path_out = cnf.path_out
self.path_out += '/{0}/'.format(self.cnf.log_name)
self.pa... |
import speech_recognition as sr
import subprocess
from subprocess import call
import os
import gnk
import time
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "//add_credentials"
def prepare_date(self):
self.response = self.response + self.result[2:18]
def prepare_time(self):
self.response = self.response + se... |
'''Checkout how many servers I'm used in!'''
import discord
from discord.ext import commands
from packages.utils import Embed, ImproperType
import textwrap
import lorem
import math
from mongoclient import DBClient
client = discord.Client
class Command(commands.Cog):
def __init__(self, client):
self.clien... |
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This script generates header/source files with C++ language bindings
# for the X11 protocol and its extensions. The protocol information
# is obtained fro... |
from math import sin, radians
#for i in range(100):
# r = radians(i)
# # print(f" sinus z {i} = {sin(i)}")
# print(f" sinus z {r} = {sin(r)}")
x = 0
i = 0
while x < 1:
i = i + 1
r = radians(i)
x = sin(r)
print(i,r,x)
x = 0
i = 0
while True:
i = i + 1
r = radians(i)
x = sin(r)
i... |
# Generated by Django 2.2.13 on 2020-06-18 21:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('oidc_provider', '0027_token_refresh_token_expire_at'),
]
operations = [
migrations.AddField(
model_name='client',
n... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayBossRelatedCompanyConsultModel(object):
def __init__(self):
self._biz_time_in_mills = None
self._is_whole_month_valid = None
self._type = None
self._value = ... |
from .cprint import aprint, printInfo
from .utils import Utils
|
#!/usr/bin/env python
# Copyright 2018 Criteo
#
# 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 agree... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
''' Script to check the correctness of the clustering.
'''
import unittest
import os
import numpy as np
from pixel_clusterizer.clusterizer import HitClusterizer, default_hits_dtype, default_clusters_dtype, default_clusters_descr, default_cluster_hits_dtype
def create_hits(n_hits, max_column, max_row, max_frame, ma... |
# -*- coding: utf-8 -*-
# Copyright CERN since 2022
#
# 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 ... |
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from tests.test_files import html_doc
def mocked_requests_get(*args, **kwargs):
"""this method will be used by the mock to replace requests.get"""
class MockResponse:
def __init__(self, html, status_code):
sel... |
from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck
from checkov.common.models.enums import CheckResult, CheckCategories
class GoogleComputeIPForward(BaseResourceCheck):
def __init__(self):
name = "Ensure that IP forwarding is not enabled on Instances"
id = "CKV_GCP... |
import pytest
from leapp.exceptions import InvalidTagDefinitionError
from leapp.tags import Tag, get_tags, ExperimentalTag, DisabledTag
class TestTag(Tag):
name = "test-tag"
def test_tag_members_correctly_set():
assert hasattr(TestTag, 'Common') and TestTag.Common.name == 'common-test-tag'
assert hasat... |
from django.contrib import admin
from .models import name_cat,items_cat
from django.db import models
from mdeditor.widgets import MDEditorWidget
# Register your models here.
@admin.register(name_cat)
class Name_admin(admin.ModelAdmin):
prepopulated_fields = { 'slug': ('name',)}
@admin.register(items_cat)
class Ite... |
import json
import os
from solc import compile_standard
from web3.contract import ConciseContract
from web3 import Web3, HTTPProvider
OUTPUT_DIR = os.environ['HOME'] + '/plasma-dex/plasma/root_chain/build/contracts'
class Deployer(object):
def __init__(self, eth_node_endpoint):
provider = HTTPProvider(et... |
# Unit test for bayesnet_inf_autodiff
import numpy as onp # original numpy
import jax.numpy as np
from jax import grad
import bayesnet_inf_autodiff as bn
# Example from fig 3 of Darwiche'03 paper
# Note that we assume 0=False, 1=True so we order the entries differently
thetaA = np.array([0.5, 0.5]) # thetaA[a] = P(A... |
#! /usr/bin/env python
#IDN
#This node subscribes to the topics which include motor RPM speeds published by arduino analog outputs
def wheels2twist(w1,w2,w3,w4):
l_x = 0.33
r = 0.0762*2
l_y = 0.33
d=1/(l_x+l_y)
I_J = np.array([[ 1, 1, 1, 1 ],
[ 1, -1, -1, ... |
import serial
import config
from time import sleep
config.x = 0
config.y = 0
config.PORT = '/dev/ttyACM0'
ser = None
def setup():
global ser
ser = serial.Serial(config.PORT, 9600, timeout=1)
st = serial_read()
print(st)
def serial_write(s):
t = s
global ser
if ser is None:
return "Er... |
from django.db import models
from django.contrib.auth.models import AbstractUser
from PIL import Image
class User(AbstractUser):
is_teacher = models.BooleanField(default=False)
is_student = models.BooleanField(default=False)
first_name = models.CharField(max_length=100)
last_name = models.CharField(ma... |
from django.urls import reverse
from rest_framework.test import APIClient
from django.test import TestCase
from people.models import Person
from owf_groups.models import OwfGroup, OwfGroupPeople
requests = APIClient()
class GroupsApiTests(TestCase):
fixtures = ['resources/fixtures/default_data.json', ]... |
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm, UserUpdateForm, UserTypeForm, UserDeleteForm
from django.contrib.auth.decorators import login_required
from functions import find_special_chars
# Form for registration page
def register(request):
... |
import os
import csv
import json
import glob
import gzip
import random
import tarfile
import zipfile
import pandas as pd
from .downloader_utils import get_corpora_dict
from .downloader_utils import get_resource_dir
def _extract_tarfile(filename, target_dir):
with tarfile.open(filename, 'r:*') as tar:
ta... |
import argparse
try:
from . import treedata_pb2 as proto
from . import utils
except (ValueError, ImportError):
import treedata_pb2 as proto
import utils
import represent_ast as ra
class Node:
def __init__(self, id, label, position):
self.id = id
self.label = labe... |
from setuptools import setup
def get_install_requires():
install_requires = [
'Django>=3,<4',
'django-jsoneditor>0.1,<0.2',
]
try:
import importlib
except ImportError:
install_requires.append('importlib')
try:
from collections import OrderedDict
except... |
"""
:py:class:`Model` is an abstract class representing
an AllenNLP model.
"""
import logging
import os
from typing import Dict, Union, List
import numpy
import torch
from allennlp.common.checks import ConfigurationError
from allennlp.common.params import Params
from allennlp.common.registrable import Registrable
fr... |
# Importing Specific Items
# Fill in the blanks so that the program below prints 90.0.
# Do you find this version easier to read than preceding ones?
# Why wouldn’t programmers always use this form of import?
____ math import ____, ____
angle = degrees(pi / 2)
print(angle) |
# coding=utf-8
# Copyright 2018 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... |
from .base import Widget
class PasswordInput(Widget):
""" This widgets behaves like a TextInput but does not reveal what text is entered.
Args:
id (str): An identifier for this widget.
style (:obj:`Style`): An optional style object. If no style is provided then
a new one will be c... |
import os
import alignfaces as af
expression = ["an", "ca", "di", "fe", "ha", "ne", "sa", "sp"]
mouth = ["o", "c"]
databases = []
for ex in expression:
for mo in mouth:
databases.append("NIM-" + ex + "-" + mo)
num_dirs = len(expression) * len(mouth)
file_postfixes = ["bmp"] * num_dirs
my_project_path = os.... |
import unittest
import json
from lambda_function import get_user, get_users
class TestTwitterUpdates(unittest.TestCase):
def test_get_users(self):
users_resp = get_users()
self.assertEqual(200, users_resp['statusCode'])
users = users_resp['body']
self.assertEqual(10, len(users))
self.assertEqua... |
# Copyright 2015 Google
# 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, software... |
import cv2
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from python_util.image_processing.image_stats import get_scaling_factor
def load_image_paths(image_list):
with open(image_list) as f:
image_paths = f.readlines()
return [image_path.rstrip() for image_path in image_pa... |
# Copyright (C) 2019 Intel Corporation. All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
#
import os
import subprocess
BIOS_INFO_KEY = ['BIOS Information', 'Vendor:', 'Version:', 'Release Date:', 'BIOS Revision:']
BASE_BOARD_KEY = ['Base Board Information', 'Manufacturer:', 'Product Name:', 'Version:']... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
# -*- coding: utf-8 -*-
#
# 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, softwa... |
from arekit.common.experiment.api.enums import BaseDocumentTag
from arekit.common.experiment.api.ops_doc import DocumentOperations
class CustomDocOperations(DocumentOperations):
def iter_tagget_doc_ids(self, tag):
assert(isinstance(tag, BaseDocumentTag))
assert(tag == BaseDocumentTag.Annotate)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup
"""
@author: Kirill Python
@contact: https://vk.com/python273
@license Apache License, Version 2.0, see LICENSE file
Copyright (C) 2017
"""
setup(
name='vk_api',
version='8.3.1',
author='python273',
author_email='whoami@p... |
import pytest
import torch
from src.defs import layers
def test_flatten():
x = torch.arange(12).view(2, 1, 3, 2)
print('Before flattening: ', x)
print('After flattening: ', layers.flatten(x))
|
#!/usr/bin/env python3
import unittest
from typing import Tuple, Union
import numpy as np
import torch
from torch import Tensor
from reagent.ope.estimators.types import TypeWrapper, Values
class TestTypes(unittest.TestCase):
TestType = Union[int, Tuple[int], float, Tuple[float], np.ndarray, Tensor]
TestCla... |
#!/usr/bin/python
#TODO Update the line below
#Date last updated: 27 Mar 2018
#NO7 Web logs
#Software: Microsoft Internet Information Services 7.0
#Version: 1.0
#Date: 2011-12-11 00:00:00
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) sc-status sc-substatus sc-win32-s... |
import os
import sys
import time
import argparse
import re
from tqdm import tqdm
from colorama import Fore, Back, Style
from google.cloud import translate
'''
* @desc load input file function
* @param string file_path - input file path and name
* @param string split_on - split each line with. Default: "\n"
*... |
# Generated by Django 3.2.3 on 2021-06-01 05:05
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('reviews', '0003_vote'),
]
operations = [
migrations.RemoveField(
model_name='project',
name='voters',
),
]
|
from flask import render_template, request, jsonify, make_response, url_for, redirect, Blueprint
from blueprints.hotdog.static.forms.hotdog_form import FileUploadForm
from blueprints.hotdog.model.pretrained_resnet import Hotdog_Model_Resnet
from PIL import Image
from torch.nn.functional import softmax
from torch import... |
""" Keeps track of configured datastore indexes. """
import json
import logging
import time
from kazoo.client import NoNodeError
from kazoo.protocol.states import KazooState
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.locks import Event as AsyncEvent
from appscale.common.async_retrying impo... |
from territory import Territory
from player import Player
from continent import Continent
class BoardUtils:
# @staticmethod
# def get_distance(self, source: Territory, target: Territory):
# if source.ruler == target.ruler:
# return float("inf")
@staticmethod
def get_continent_ratio... |
# coding: utf-8
# Copyright (c) Henniggroup.
# Distributed under the terms of the MIT License.
"""
This package contains modules to generate various input files for running VASP calculations and parse the relevant outputs which are required for our defect-related analysis.
Currently, only io interfacing with VASP is p... |
class Solution:
def largestOverlap(self, A: List[List[int]], B: List[List[int]]) -> int:
n = len(A)
A1 = set()
B1 = set()
for i in range(n):
for j in range(n):
if B[i][j] == 1:
B1.add((i, j))
if A[i][j] == 1:
... |
try:
import uarray as array
except ImportError:
try:
import array
except ImportError:
print("SKIP")
raise SystemExit
a = array.array('B', [1, 2, 3])
print(a, len(a))
i = array.array('I', [1, 2, 3])
print(i, len(i))
print(a[0])
print(i[-1])
a = array.array('l', [-1])
print(len(a), a[... |
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Michael A.G. Aivazis
# California Institute of Technology
# (C) 1998-2005 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~... |
import sys
import mariadb
import time
def export_to_db(dbconfig, temperature, weatherCode, windSpeed, windDirection):
# Connect to MariaDB Platform
try:
conn = mariadb.connect(
user=dbconfig['username'],
password=dbconfig['password'],
host=dbconfig['host'],
... |
# Modules
import discord
from json import loads, dumps
from discord.ext import commands
from assets.prism import Tools, Constants
# Main Command Class
class Warn(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.desc = "Warns a member on the server"
self.usage = "warn [user] [re... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile, CMake, tools
import os
class GlObjectsConan(ConanFile):
name = "globjects"
version = "2.0.0"
description = "Cross platform C++ wrapper for OpenGL API objects"
url = ""
homepage = "https://github.com/cginternals/globjects"... |
from .base import BaseCFObject
class Metadata(BaseCFObject):
top_level_key = 'Metadata'
|
from django.shortcuts import render, HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from tracker.models import Expense
from datetime import datetime, timedelta
import json
@login_re... |
# -*- coding: utf-8 -*-
from sbscraper import product
from sbscraper.transform import base
class RedMartProductTransformer(base.ProductTransformer):
"""Transforms RedMart data to :class:`~sbscraper.product.Product`."""
API_VERSION = 'v1.5.6'
def get_currency(self, datum):
# RedMart only deals i... |
# Counting Sundays
WEEKDAYS = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
"Sunday")
MONTHS = ("January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December")
month_dict = {}
for m in MONTHS:
if m in ("September", "April", "June", "... |
import sys
import os
import getopt
import pygame
pygame.init()
grass_tiles = pygame.image.load(os.path.join('sprite_art','Multi_Platformer_Tileset_v2','Grassland','Terrain','Grass_Tileset.png'))
ground_tiles = pygame.image.load(os.path.join('sprite_art','Multi_Platformer_Tileset_v2','Grassland','Background','GrassLan... |
import tkinter
from tkinter import *
from tkinter import messagebox
import dbhelper
def add():
if(len(addtask.get()) == 0):
messagebox.showerror(
"ERROR", "No data Available\nPlease Enter Some Task")
else:
dbhelper.insertdata(addtask.get())
addtask.delete(0, END)
po... |
# This file is part of the clacks framework.
#
# http://clacks-project.org
#
# Copyright:
# (C) 2010-2012 GONICUS GmbH, Germany, http://www.gonicus.de
#
# License:
# GPL-2: http://www.gnu.org/licenses/gpl-2.0.html
#
# See the LICENSE file in the project's top-level directory for details.
import string
import os
imp... |
import io
import os
import re
from setuptools import find_packages, setup
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
def read(filename):
filename = os.path.join(os.path.dirname(__file__), filename)
text_type = type(u"")
with io... |
from toontown.coghq.SpecImports import *
GlobalEntities = {1000: {'type': 'levelMgr',
'name': 'LevelMgr',
'comment': '',
'parentEntId': 0,
'cogLevel': 0,
'farPlaneDistance': 1500,
'modelFilename': 'phase_11/models/lawbotHQ/LB_Zone08a',
'wantDoors': 1},
1001: {'ty... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 17 16:17:25 2017
@author: jorgemauricio
"""
# librerias
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
# crear una serie
ser1 = Series([1,2,3,4,1,2,3,4])
# desplegar
ser1
# usando replace .replace(valor a ser rempla... |
from django.db import IntegrityError
from rest_framework.exceptions import ErrorDetail, ValidationError
from rest_framework import serializers
from ..models import Customer
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
field... |
# fetch mnist dataset
"""by GeoHotz"""
def fetch(url):
import requests
import hashlib
import os
import tempfile
fp = os.path.join(tempfile.gettempdir(), hashlib.md5(
url.encode('utf-8')).hexdigest())
if os.path.isfile(fp):
with open(fp, "rb") as f:
dat = f.read()
... |
import sys
from briefcase.platforms.linux.appimage import LinuxAppImageCreateCommand
def test_support_package_url(first_app_config, tmp_path):
command = LinuxAppImageCreateCommand(base_path=tmp_path)
# Set some properties of the host system for test purposes.
command.host_arch = 'wonky'
command.plat... |
import pymongo
import pandas as pd
class mongo:
'''
mongodb class through which we can perform most of the mongodb tasks using python
'''
def __init__(self):
'''
init function
'''
self.db = ""
def connect(self, connection_url,db):
'''
connect func... |
# Copyright 2019, The TensorFlow 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 appli... |
import json
import pathlib
import pytest
import laskea
import laskea.config as cfg
def test_generate_template_command():
json_string = cfg.generate_template()
assert '"markers": "[[[fill ]]] [[[end]]]"' in json_string
def test_process_spoc_no_file(capsys):
with pytest.raises(SystemExit):
cfg.p... |
from copy import *
import re
class TaggedWord:
def __init__(self, word='', tag=''):
self.word = word
self.tag = tag
def getWord(self):
return self.word
def getTag(self):
return self.tag
def replaceCharAt(str, pos, c):
return str[:pos]+c+str[pos+1:]
class CorpusReader... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.