content stringlengths 5 1.05M |
|---|
from django.utils import timezone
from django.conf import settings
from django.db.utils import ProgrammingError
from django.contrib.contenttypes.models import (
ContentType,
)
from django.db.models import (
Model,
CharField,
DateTimeField,
ForeignKey,
CASCADE,
TextField,
DateField,
P... |
import sys
sys.path.append('..')
import traceback
import genericBotBase.botbase as BotBase
log = BotBase.log
config = BotBase.config
bot = BotBase.bot
extensions = [
'genericBotBase.cogs.admin',
'genericBotBase.cogs.common',
'genericBotBase.cogs.basic',
'cogs.QueueCommands'
]
def main()... |
from tensorflow.keras import backend as K
from tensorflow.keras.layers import (
Input,
Conv2D,
BatchNormalization,
Layer,
PReLU,
SeparableConv2D,
DepthwiseConv2D,
add,
Flatten,
Dense,
Dropout,
GlobalAveragePooling2D,
Reshape,
Multiply,
)
from tensorflow.keras.mode... |
# -*- coding: utf-8 -*-
import os
import pytest
from gaas_sample import *
def test_local_input(create_gaas_calc, configure_with_daemon, assert_finished):
from aiida.work.run import run
process, inputs = create_gaas_calc()
output, pid = run(process, _return_pid=True, **inputs)
assert all(key in outp... |
#!/usr/bin/env python
# ryan g. coleman, ryangc@mail.med.upenn.edu
# kim sharp lab
# phi.py enables read/write of binary phi-maps from delphi
# usage is import, then pass in filename to object creation
# extensions written in bks lab, 2012, and by extensions i mean reading
# phimap files written by a pgf, 32-bit versio... |
from django.contrib.admin.models import LogEntry
from django.core.exceptions import PermissionDenied
from django.views import generic
class AdminActionsHistory(generic.ListView):
template_name = 'admin/actions_history.html'
model = LogEntry
context_object_name = "actions_history_list"
paginate_by = 25... |
import os
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
#Update system
print(" ")
print(bcolors.OKGREEN + "Updating your system as sudo" + bcolors.ENDC)
print("... |
from app import app, models
from datetime import datetime
task1 = models.Todoitem('Finish Flask App', 'Use a great mix of latest py.tech to finish To-Do app.', datetime.now().date(), True)
task2 = models.Todoitem('Remember the milk', 'Buy low-fat and fresh milk', datetime.now().date(), False)
print('Addding a few sam... |
import pdb
import numpy
import bag_records.records
import copy
class Bool(bag_records.records.RecordBase):
"""Record for std_msgs/Bool types
"""
def __init__(self, has_msg_time=False):
"""Constructor
Arguments:
has_msg_time: optional bool indicating if this record should hav... |
from django.conf.urls import patterns, url
from things.views import ThingDetailView, ThingListView
from .models import Post, PostPhoto
urlpatterns = patterns(
'',
url(r'^posts/$',
ThingListView.as_view(model=Post),
name='post_list'),
url(r'^posts/(?P<slug>[\w\-\/]+)/$',
ThingDetai... |
# Generated by Django 3.1.7 on 2021-04-09 14:18
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('rest_api', '0007_auto_20210409_1717'),
]
operations = [
migrations.RemoveField(
model_name='extremesport',
name='country',
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Illustration of Theiler window using an AR(1) series.
An AR(1) time series is temporally correlated. Thus, if a judicious
(nonzero) value of the Theiler window is not used, the estimated
dimension converges to the fractal dimension of the trajectory formed by
the time... |
__version__ = "2.0.1"
# __version__ has to be defined in the first line
from .classifiers import (Box_Plot, Equal_Interval, Fisher_Jenks,
Fisher_Jenks_Sampled, HeadTail_Breaks, Jenks_Caspall,
Jenks_Caspall_Forced, Jenks_Caspall_Sampled,
Max_... |
#!/usr/bin/env python3
import cv2
import depthai as dai
import numpy as np
# Start defining a pipeline
pipeline = dai.Pipeline()
# Define a source - two mono (grayscale) cameras
cam_left = pipeline.createMonoCamera()
cam_left.setCamId(1)
cam_left.setResolution(dai.MonoCameraProperties.SensorResolution.THE_720_P)
ca... |
from floodsystem.stationdata import build_station_list, update_water_levels
from floodsystem.station import MonitoringStation
from floodsystem.datafetcher import fetch_measure_levels
from floodsystem.analysis import polyfit
import numpy as np
import datetime
# Defining parameters for risk levels globally
global high, ... |
from validator.decorator import version_range
from validator.constants import (FIREFOX_GUID, FENNEC_GUID,
THUNDERBIRD_GUID as TB_GUID, ANDROID_GUID)
# Compatibility app/version ranges:
def _build_definition(maj_version_num, firefox=True, fennec=True,
thunderbird... |
"""
Implementation of the config class, which manages the config of different bittensor modules.
"""
# The MIT License (MIT)
# Copyright © 2021 Yuma Rao
# 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 the... |
from dataclasses import dataclass
from pathlib import Path
from dataclasses import dataclass, field
from loguru import logger
from libraries.crowdin import UECrowdinClient
from libraries.utilities import LocTask
@dataclass
class AddSourceFiles(LocTask):
# Declare Crowdin parameters to load them from config
... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import hashlib
import time
import math
import matplotlib.pyplot as plt
from random import SystemRandom, randint
"""
generate a number of length
"""
def generate_number(k):
random = SystemRandom()
p = random.getrandbits(k)
binary = bin(p)
new_binary = ... |
# Generated by Django 3.1 on 2020-09-09 00:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('resources', '0003_auto_20200819_1748'),
]
operations = [
migrations.AddField(
model_name='job',
name='description',
... |
from fabric.api import local
from jinja2 import Environment, FileSystemLoader
template_env = Environment(loader=FileSystemLoader('.'))
def build():
#template = template_env.get_template('source/index.html')
# Template to generate the presentation
template = template_env.get_template('mobile_test_automat... |
# -*- coding: utf-8 -*-
"""
convert from 16bit tiff to 16bit png.
======================================
"""
# import standard libraries
import os
# import third-party libraries
import numpy as np
import cv2
# import my libraries
# information
__author__ = 'Toru Yoshihara'
__copyright__ = 'Copyright (C) 2020 - Tor... |
from django_filters import rest_framework as filter
from .models import Usuario, Classificacao, LogAutenticacao
from empresa.filters import lookup_types_empresa
lookup_types_usuario = {
'uuid': ['exact', 'in', ],
#'codigo': ['exact', 'contains', 'gt', 'gte', 'lt', 'lte', 'in', 'range'],
'username': ['exact... |
from scipy.io import wavfile
import soundfile as sf
from pesq import pesq
def cal_pesq(f1,f2):
ref,rate = sf.read(f1)
deg,rate = sf.read(f2)
print(f1,f2)
print('wb', pesq(rate, ref, deg, 'wb'))
print('nb', pesq(rate, ref, deg, 'nb'))
cal_pesq('./nearspeech.wav', './output.wav')
cal_pesq('./nearspe... |
import telnetlib
from routersploit import (
exploits,
print_status,
print_success,
print_error,
mute,
validators,
)
class Exploit(exploits.Exploit):
"""
Exploit implementation for ZTE F6XX default root password.
If the target is vulnerable it is possible to authenticate to the dev... |
"""
server_status.py
Copyright 2006 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is distributed in the hope th... |
#!/usr/bin/env python3
from sys import argv
from math import cos, sin
from math import radians as toR
data = [x.strip() for x in open(argv[1]).readlines()]
x = 0
y = 0
wp = [10, 1] # x, y / EW, NS
for s in data:
dir = s[0]
amnt = int(s[1:])
if dir == "N":
wp[1] += amnt
elif dir == "E":
... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 3
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import isi_sdk_8_0
from isi... |
import csv
import statistics
durations = []
with open('fast_a_better_vB_100.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
with open('../api-tests/resources/bpmn/fast_a_better/fast_a_better_vB_100.json', 'w+') as txt_file:
txt_file.write("{\n")
txt_file.write('"durations":... |
# Use modern Python
from __future__ import absolute_import, print_function, unicode_literals
# Django imports
from django.test import TestCase, SimpleTestCase
# External imports
from django_prbac.models import Grant, Role
# CCHQ imports
from corehq.apps.hqadmin.management.commands import cchq_prbac_bootstrap
from fa... |
# coding=utf-8
import re
import os
import platform
import subprocess
import signal
import time
class Util(object):
def __init__(self, sn):
self.sn = sn
self.debug = False
if sn is None:
self.sn = self.__get_sn()
def __get_sn(self):
out = self.cmd('adb devices').str... |
"""
Utilities for the :mod:`dicom_parser.utils.siemens.csa` module.
"""
# DICOM VR code to Python type
VR_TO_TYPE = {
"FL": float, # float
"FD": float, # double
"DS": float, # decimal string
"SS": int, # signed short
"US": int, # unsigned short
"SL": int, # signed long
"UL": int, # u... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2021 Johannes Reiff
# SPDX-License-Identifier: MIT
"""
Implementation of the LiCN ⇌ LiNC isomerization potential surface.
This code is based on:
* R. Essers, J. Tennyson, and P. E. S. Wormer,
“An SCF potential energy surface for lithium cyanide,”
Ch... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
import csv
from django.contrib import messages
import time
import os
# forms
from analysis.forms import homeForm
from analysis.forms import selectForm
# backend file
from analysis.result_analysis import analysis_fun
# Create your view... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_mysql.models import JSONField, Model
from django.db import models
from cuestionarios.models import Preguntas_test, Grupo_edad
from alumnos.models import Alumno
class Respuesta(Model):
alumno = models.ForeignKey(Alumno,
... |
# -*- encoding: utf-8 -*-
"""Testing Unittest facilities offered.
This doesn't test 'wrap' command, but the 'self.w' provided to
tests inheriting BaseShTest.
"""
from .. import ShellError, BaseShTest
class WrapSimpleTest(BaseShTest):
def test_shell_call(self):
out = self.w("true")
self.asser... |
from contextlib import closing
from mysql.connector import connect
import random
def create_journal_group_name_lookup(filepath, encoding, delimiter):
data = load_delimited_data(filepath, encoding, delimiter)
lookup = {}
for row in data:
nlm_id = row[0]
group = row[1]
lookup[nlm_id]... |
def linha():
print('-=' * 30)
def area(a, b):
ar = a * b
print(f'A área de um terreno {a:.2f} x {b:.2f} é de {ar:.2f}m² ')
#Função Main
linha()
print(' Controle de Terrenos')
linha()
larg = float(input('Largura (m): '))
comp = float(input('Comprimento (m): '))
area(larg, comp)
|
import pytest
from my_package import process
@pytest.mark.parametrize(
'name, expected',
[
['Hemingway, Ernest', 'Ernest Hemingway'],
['virginia woolf', 'Virginia Woolf'],
['charles dickens ', 'Charles Dickens'],
],
)
def test_clean_name(name, expected):
assert process.clean_... |
import scrapy
import os
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
try:
from lyrics_crawler_single.constants import (
BASE_URL,
TOP_N,
MOST_ACCESSED,
OUTPUT_FILE,
)
except:
from constants import BASE_URL, TOP_N, ... |
#!/usr/bin/python3
# knowing cipher-text and plain-text
# we can obtain key of vigenere-ciper
# then use https://www.dcode.fr/vigenere-cipher
plaintext = "OrestisHackingforfunandprofit"
ciphertext = "PieagnmJkoijegnbwzwxmlegrwsnn"
key = ""
for i in range(len(plaintext)):
num_key = ((ord(ciphertext[i]) - ord(plai... |
import pandas as pd
import dataconfig as cfg
import csv
from os import listdir
from os.path import isfile, join
def main():
root_folder=cfg.data['watch_event_out_folder']
filenames = [f for f in listdir(root_folder) if isfile(join(root_folder, f))]
filenames=[root_folder+f for f in filenames]
#Ref:htt... |
#!/usr/bin/env python3
# coding:utf-8
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, duplication):
table = set()
for num in numbers:
if num not in table:
table.add(num)
else:
duplic... |
import os
from setuptools import setup
f = open(os.path.join(os.path.dirname(__file__), 'README.md'))
readme = f.read()
f.close()
VERSION = "0.2.2"
setup(
name = "paizaio-api"
, version = VERSION
, author = "Takazumi Shirayanagi"
, author_email = "zumix.cpp@gmail.com"
, url = "https://github.com/srz-zumix/paiza... |
import os.path
import sys
sys.path = [os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')] + sys.path
from amqpsfw import amqp_spec, ioloop
from amqpsfw.server.server import Server, ServerClient
from amqpsfw.client.client import Client
from amqpsfw.client.configuration import ClientConfiguration
fro... |
# -*- coding: utf-8 -*-
import json
from flask_restful import Resource
from dashboard import r_kv
from ..utils import build_response
class KeyList(Resource):
"""
Get the keys in database.
Return all the keys exist in database which are used to
store data for build table and visualization. i.e, thos... |
import urllib
import zipfile
import csv
from django import test
from localground.apps.site.tests import Client, ModelMixin
from rest_framework import status
from StringIO import StringIO
from django.contrib.gis.geos import Point
from localground.apps.site.api.tests.renderer_tests import mixins
from localground.apps.sit... |
from __future__ import division
from __future__ import print_function
import argparse
import time
import numpy as np
import scipy.sparse as sp
import torch
import pickle
from torch import optim
from load_graph_embedding import load_embedding
from graph_embedding_config import *
from vgae_model import GCNMode... |
from collections import defaultdict
from copy import deepcopy
import os
import re
dx = [-1, 0, 1]
dy = [-1, 0, 1]
dz = [-1, 0, 1]
dw = [-1, 0, 1]
def process(x, y, z, w, system):
current_value, neighbours = system[(x, y, z, w)], ""
for x2 in dx:
for y2 in dy:
for z2 in dz:
... |
from sandbox.rocky.tf.q_functions.base import QFunction
import sandbox.rocky.tf.core.layers as L
import tensorflow as tf
import numpy as np
from rllab.core.serializable import Serializable
from sandbox.rocky.tf.core.layers_powered import LayersPowered
from sandbox.rocky.tf.misc import tensor_utils
from sandbox.rocky.tf... |
from galaxy import exceptions
from abc import ABCMeta
from abc import abstractmethod
from galaxy import model
import logging
log = logging.getLogger( __name__ )
class DatasetCollectionType(object):
__metaclass__ = ABCMeta
@abstractmethod
def generate_elements( self, dataset_instances ):
""" Gen... |
'''
Created on 12.07.2018
@author: yvo
Sample script showing polymorphistic approach to retrieve attribute
data of glaciers from the database.
'''
import configparser
import inspect
import sys
from dataflow.DataReaders.DatabaseReaders.GlacierReader import GlacierReader
from dataflow.DataReaders.DatabaseReaders.Vol... |
# -*- coding: utf-8 -*-
'''
Utility routines, classes, etc. A catch-all.
BUGS / WARNINGS / FIXME:
* This module keeps references to the config and logger objects it returns,
and then uses them, so the caller should take care to not somehow acquire
different ones.'''
# Copyright (c) Los Alamos National Security,... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(
regex=r'^$',
view=views.TypeListView.as_view(),
name='type-list'
),
url(r'^delivery/$', view=views.LetterFormView.as_view(), name='delivery'),
]
|
default_app_config = 'baserow.contrib.database.config.DatabaseConfig'
|
DESCRIPTIONS = {
400: {
"title": "400 Bad Request",
"description": "The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).",
"fix": "Please your... |
#!/usr/bin/python3
import aiohttp
import asyncio
import threading
import time
import os
import sys
import random
import binascii
import csv
import requests
# import dotenv
# from dotenv import load_dotenv
# load_dotenv()
# MY_ENV_VAR = os.getenv('NODES')
nodes = int(sys.argv[1])
count = int(sys.argv[2])
with open(... |
# Copyright 2021 Northern.tech AS
#
# 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 ag... |
from .job import Job
from .manager import Manager
from .scheduler import Scheduler
__author__ = 'Timur Faradzhov'
__copyright__ = 'Copyright 2019, The Pypyrus Runner Project'
__credits__ = ['Timur Faradzhov']
__license__ = 'MIT'
__version__ = '0.0.1'
__maintainer__ = 'Timur Faradzhov'
__email__ = 'timurfaradzhov@gmai... |
import random, string, urllib.request, json, getpass
#Generate root password
password = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(20))
#Download ngrok
! wget -q -c -nc https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
! unzip -qq -n ngrok-stable-linux-amd64.zip
#Se... |
import bjoern
from app import app
bjoern.run(
wsgi_app=app,
host='0.0.0.0',
port=5000,
reuse_port=True
)
|
# -*- coding: utf-8 -*-
__author__ = 'ffuentes'
from datetime import datetime
from django.conf import settings
from django.contrib.auth.middleware import get_user
from django.contrib.auth.models import User
from django.contrib.sessions.models import Session
from django.contrib.sessions.backends.base import UpdateError... |
import os
import shutil
import pickle
import numpy as np
import dnnlib
import dnnlib.tflib as tflib
import config
from encoder.generator_model import Generator
import sys
from moviepy.editor import *
if __name__ == "__main__":
if len(sys.argv)>1:
ENC_DIR = sys.argv[1]
else:
ENC_DIR = 'enc'
... |
print('Estamos probando conectar repositorio local con el de la nube') |
import discord
import threading
import os
import random
from re import search
from flask import Flask, request, jsonify
from bot.models.intent import Intent
from bot.models.question_intent import QuestionIntent
from bot.constants.game_players import LeaguePlayers
from concurrent.futures import ThreadPoolExecutor
fr... |
from os import (getcwd, path as osp)
from unittest.mock import (patch, MagicMock)
from click.testing import CliRunner
import pytest
from thug.cli import (meme, thug_meme, _form_result_path)
from .conftest import IMG_1_FACE
@pytest.fixture
def cli_runner():
return CliRunner()
@patch('thug.cli.Meme')
class Test... |
from a10sdk.common.A10BaseClass import A10BaseClass
class AuthSamlIdp(A10BaseClass):
""" :param remote_file: {"optional": true, "type": "string", "description": "Profile name for remote url", "format": "url"}
:param use_mgmt_port: {"default": 0, "optional": true, "type": "number", "description": "Use ... |
import optunity
import optunity.metrics
# comment this line if you are running the notebook
import sklearn.svm
import numpy as np
decision_values = np.array([-0.69354811, -0.69354743, -0.69354744, -0.69354754, -0.69354715, -0.69354866, -0.69354775, -0.69355032, -0.69355325])
y_test = [0, 0, 0, 0, 0, 0, 0, 0, 0]
auc ... |
# Solution of;
# Project Euler Problem 119: Digit power sum
# https://projecteuler.net/problem=119
#
# The number 512 is interesting because it is equal to the sum of its digits
# raised to some power: 5 + 1 + 2 = 8, and 83 = 512. Another example of a
# number with this property is 614656 = 284. We shall define an t... |
from odoo import api, fields, models
class SaleOrderInfo(models.Model):
_inherit = 'sale.order'
order_day_info = fields.Char('Order Day')
Discount_code = fields.Char('Discount Code')
customer_email = fields.Char(related='partner_id.email', string='Customer Email')
def copy(self, default={}):
... |
import sys
import argparse
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer
from transformers import BertForSequenceClassification
sys.stdin.reconfigure(encoding='utf-8')
sys.stdout.reconfigure(encoding='utf-8')
def define_argparser():
p = argparse.ArgumentParser()
p.add_a... |
import sys
import os
import numpy as np
import torch
from tqdm import tqdm
from tabulate import tabulate
from torch.utils.data import DataLoader
from data.lmdb_dataset import LMDBDataset
from data.meta_dataset_reader import TRAIN_METADATASET_NAMES, ALL_METADATASET_NAMES
from models.model_utils import CheckPointer, sig... |
import os
import sys
from requests import post
# A stupid fix for a stupid problem caused by PyCharm's inability to not overwrite
# the PYTHONPATH set in the Dockerfile
sys.path.append('/opt/api')
from core.blockchain.projectpai.paicoin.transaction import Transaction
CRYPTO_HOST = os.environ['CRYPTO_HOST']
CRYPTO_PO... |
# -*- coding: utf-8 -*-
# @Author : William
# @Project : TextGAN-william
# @FileName : instructor.py
# @Time : Created at 2019-04-25
# @Blog : http://zhiweil.ml/
# @Description :
# Copyrights (C) 2018. All Rights Reserved.
import numpy as np
import torch
import torch.nn as n... |
#!/usr/bin/env python
from splunklib.searchcommands import dispatch, GeneratingCommand, Configuration, Option, validators
import sys
import os
try:
# python2
import ConfigParser as configparser
from StringIO import StringIO as BytesIO
import urllib2 as urllib_functions
except:
# python3
import ... |
#!/usr/bin/python
import sys
import json
import os
import fnmatch
import collections
import fileinput
import re
# Settings loaded from cluster.properties file
brokers = []
brokers_target = []
zookeepers = []
zookeepers_target = []
producers = []
consumers = []
consumers_target = []... |
import numpy as np
import matplotlib.pylab as plt
def getErrors(fname):
errors = np.loadtxt(fname)
test_len = int(errors.shape[1]/2)
ite = errors.shape[0]
L= np.arange(test_len)
x_real = errors[:,:test_len]
x_pred = errors[:,test_len:]
rmse = np.sqrt(np.mean((x_real-x_pred)**2,axis=0))
... |
# -*- coding: utf-8 -*-
# Name: GdbToDWG.py
# Description: Export vers un beau DWG
# Author: mav
# To Do : remplacer la gdb temporaire par in_memory
# Import system modules
import arcpy, os, datetime
# from arcpy import env
# Début du minutage, hors import des modules
now = datetime.datetime.now()
# ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 10 13:14:38 2015
@author: djc@thinksysinc.com
A collection of test functions used to check some basic math in the Python
interface
"""
import math
# A square root function
def sqrt(a):
retval = -1.0;
if a >= 0:
retval = math.sqrt(a);
... |
expected_output = {'interfaces': {'Ethernet1/33': {'in_bcast_pkts': 0,
'in_mcast_pkts': 64,
'in_octets': 1162614,
'in_ucast_pkts': 14178,
... |
# Copyright 2020 Google 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 writing, soft... |
from django.urls import path
from . import views
# from doobi.users.views import (
# user_detail_view,
# user_redirect_view,
# user_update_view,
# )
app_name = "users"
urlpatterns = [
# path("~redirect/", view=user_redirect_view, name="redirect"),
# path("~update/", view=user_update_view, name="up... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy.loader.processors import TakeFirst
def remove_star_text(input_string):
"""
Simple preprocess custom method
"""
if "star-ra... |
import cv2
alpha = 0.5
beta = 1 - alpha
src1 = cv2.imread('./Media/sample.jpeg')
src2 = cv2.imread('./Media/sample2.jpeg')
# Check for image loading or not
if src1 is None:
print("Error loading Src1")
exit(-1)
elif src2 is None:
print("Error loading src2")
exit(-1)
# cretae addWeighted method
dst = ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import settings
from server.domain.models import *
from core_backend.database import con, connect
from sqlalchemy import create_engine
from core_backend.database.base import DomainBase
if __name__ == "__main__":
print settings.DB_URL
engine = create_engine(settings.DB... |
# Django settings for test_project project.
import os
import sys
DEBUG = True
TESTING = sys.argv[1:2] == ['test']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(os.path.dirname(__file__), 'test_project.db'),
}
}
USE_I18N = True
USE_L10N = True
SECRET_K... |
# Copyright © 2020, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All rights reserved.
#
# The DELTA (Deep Earth Learning, Tools, and Analysis) platform is
# licensed under the Apache License, Version 2.0 (the "License");
# you may not use this f... |
from qt import *
from qtcanvas import *
import math
def dxdy(w, x1, y1, x2, y2):
if x1 > x2:
x1, x2 = x2, x1
y1, y2 = y2, y1
a = x2-x1
b = y2-y1
c = math.sqrt(a*a + b*b)
if c == 0:
dx = dy = 0
else:
dx = b * w / c / 2.0
dy = a * w / c / 2.0
return d... |
import torch
import torch.nn as nn
import torch.optim as optim
import math
import cv2
import torchvision.transforms as transforms
from dataset.dataset import ImageFolder
from config import config
from models.model_resnet import ResNet, FaceQuality
from models.metrics import GaussianFace
from models.focal import Focal... |
# import boto3
# s3 = boto3.client('s3')
# def handler(event, context):
# response = s3.get_object(
# Bucket='gtfs-bussim-347664766527',
# Key='config.sh',
# )
# print(str(response.get("Body").read()))
import pandas as pd
def handler(event, context):
print("hi")
df = pd.DataFr... |
# Generated by Django 2.0.1 on 2018-01-21 08:57
from django.db import migrations, models
import django_jalali.db.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Bar',
fields=[
... |
import os
import requests
import json
import time
from sachima.log import logger
from sachima import conf
from io import BytesIO
BAIDU_GEO_TOKEN = conf.get("BAIDU_GEO_TOKEN")
QQ_GEO_TOKEN = conf.get("QQ_GEO_TOKEN")
AMAP_GEO_TOKEN = conf.get("AMAP_GEO_TOKEN")
def poi_compound_dict(
dim={"K001": "subway", "K002"... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.action import ActionBase
try:
from ansible_collections.ansible.utils.plugins.module_utils.common.argspec_validate import (
AnsibleArgSpecValidator,
)
except ImportError:
ANSIBLE_UTILS_IS_INST... |
# Copyright 2019:
# Marcelo Lerendegui <marcelo@lerendegui.com>
# WeiHsien Lee <weihsien.lee@duke.edu>
# Yihang Xin <yihang.xin@duke.edu>
# This file is part of BME547_Final_Project.
#
# BME547_Final_Project is free software: you can redistribute it and/or
# modify it under the terms of the GNU Gener... |
import warnings
from keras import backend as K
from keras.models import Model
from keras.layers import Convolution2D, MaxPooling2D, Input, AtrousConvolution2D
from keras.layers import Dropout, UpSampling2D, ZeroPadding2D
from keras.utils.layer_utils import convert_all_kernels_in_model
from keras.utils.data_utils impo... |
from random import randrange
# Split a dataset into k folds
def cross_validation_split(dataset, n_folds):
dataset_split = list()
dataset_copy = list(dataset)
fold_size = int(len(dataset) / n_folds)
for _ in range(n_folds):
fold = list()
while len(fold) < fold_size:
index = r... |
"""Unit test for pydrip modules."""
|
from quex.frs_py.file_in import *
import quex.lexer_mode as lexer_mode
from quex.token_id_maker import TokenInfo
from quex.input.setup import setup as Setup
from quex.input.ucs_db_parser import ucs_property_db
from quex.core_engine.utf8 import __read_one_utf8_code_from_stream
from quex.core_engi... |
# Mode: -*- python -*-
# Copyright (c) 2015-2019 by Rocky Bernstein <rb@dustyfeet.com>
#
# Note: we can't start with #! because setup.py bdist_wheel will look for that
# and change that into something that's not portable. Thank you, Python!
#
#
from __future__ import print_function
import sys, os
import click
import os... |
def n_last_char(a,b,n):
if (a == 1):
s = b + 1
else: s = (pow(a,b+1) - 1)//(a-1)
s %= pow(10,n)
res = str(s)
while (len(res)<n):
res = '0' + res
return res
# print(n_last_char(1,1,4)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.