content stringlengths 5 1.05M |
|---|
import webapp2.api as API
API.menuItems = [
{ 'caption': 'Dashboard',
'icon': 'dashboard',
'route': '/dashboard'
},
{ 'caption': 'Administration',
'icon': 'settings',
'children': []
},
{ 'caption': 'Feedback',
'icon': 'feedback',
'route': '/feedback'
}
] |
import functools
import os
import struct
import typing
from collections import UserList
def to_bytearray_deco(func):
@functools.wraps(func)
def wrap(datatype):
packed = func(datatype)
array = ByteArray(packed)
return array
return wrap
def to_bytearray(data, little_endian=False, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2021-01-07 13:10:57
# @Author : Joe Gao (jeusgao@163.com)
from backend import keras, V_TF
from keras_bert.layers import MaskedGlobalMaxPool1D
from .graph_attention_layer import GraphAttention
from .models import base_embed, bert_base, get_model, nonmask_embe... |
import json
import sys
from ..exceptions import JSONRPCInvalidRequestException, JSONRPCInvalidResponseException
from ..jsonrpc2 import (
JSONRPC20Request,
JSONRPC20BatchRequest,
JSONRPC20Response,
JSONRPC20BatchResponse,
)
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import... |
from pyspark.sql.types import StructType, StructField, IntegerType, StringType
spark = SparkSession.builder.getOrCreate()
# For escuelasPR.csv file
school_schema = StructType([
StructField("school_region", StringType(), True),
StructField("school_district", StringType(), True),
StructField("city", StringT... |
import requests
from config import bot_url, api_secret
from typing import List
_bot_headers = {
'authorization': f"Bearer srv.{api_secret}"
}
def _build_bot_url(path: str):
return f"{bot_url}{path}"
def bot_add_roles(user_id: str, guild_id: str, role_ids: List[str]):
r = requests.post(_build_bot_url("/ad... |
default_app_config = 'dcodex_carlson.apps.DcodexCarlsonConfig'
|
#!/usr/bin/env python
import sys
import requests
from cattle import from_env
url = sys.argv[1]
r = requests.get(url)
if r.status_code == 200 and r.text.startswith('#!/bin/sh'):
print url
sys.exit(0)
r = requests.get(sys.argv[1])
try:
url = r.headers['X-API-Schemas']
except KeyError:
url = sys.argv[... |
from __future__ import (
absolute_import,
print_function,
unicode_literals,
)
import argparse
import io
def main(argv=None):
args = parse_args(argv)
dirtiness_results = {
check_and_report_file_blocktrans_dirtiness(filename)
for filename in args.filenames
}
return 0 if dirt... |
from .caveat import Caveat
from .macaroon import Macaroon
from .macaroon import MACAROON_V1
from .macaroon import MACAROON_V2
from .verifier import Verifier
__all__ = [
'Macaroon',
'Caveat',
'Verifier',
'MACAROON_V1',
'MACAROON_V2'
]
__author__ = 'Evan Cordell'
__version__ = "0.13.0"
__version_... |
TEST = [(
"""
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
""",
198,
)]
TEST2 = [(
"""
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
""",
230,
)]
import sys
from pathlib import Path
from collections import defaultdict, Counter
import math
# import... |
# -*- coding: utf-8 -*-
from setuptools import setup, Extension
packages = [
"swig_ex2",
]
ext_modules = [
Extension(
name="_swig_ex2",
sources=["ex2.c", "ex2_wrap.c"],
),
]
setup(
name="swig_ex2",
version="1.0.0",
description="SWIG Example2",
ext_modules=ext_modules,
packages=packages,
package_dir={"sw... |
import logging
import json
from typing import Dict, Any, Optional, List
from allennlp.common.file_utils import cached_path
from allennlp.common.checks import ConfigurationError
from allennlp.data.dataset_readers.dataset_reader import DatasetReader
from allennlp.data.token_indexers import TokenIndexer, SingleIdTokenInd... |
from conans import ConanFile
import os
from conans.tools import download, unzip, check_sha256
from conans import CMake
class ArbitraryName(ConanFile):
name = "sso-23"
version = "2015.1.29"
branch = "master"
generators = "cmake"
license = "Boost"
url="http://github.com/TyRoXx/conan-sso-23"
Z... |
_SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"]
# sample doc at: https://docs.google.com/spreadsheets/d/1X0wsfpb5-sm2PE4_dJDliBOrXIOzvVrYrA1JYeyS06c/edit?usp=sharing
_SPREADSHEET_ID = "1X0wsfpb5-sm2PE4_dJDliBOrXIOzvVrYrA1JYeyS06c"
_SHEET_NAME = "Sheet1"
_TEMPLATE_NAME = "template.pdf"
|
import csv
import io
import json
import random
import re
from django import http
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core i... |
from .reply_server import Server
|
# Generated by Django 2.0.7 on 2018-07-30 06:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('question', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='attachment',
name='detail_id',
... |
import asyncio # for concurrency
from poke_env.player.random_player import RandomPlayer
from poke_env.player.utils import cross_evaluate
from tabulate import tabulate
async def main():
"""Create a 3 random pokemon trainer bot to to fight against each other with random actions"""
# We create three random play... |
# infer Encoder via pre-trained models, before use this code, set args from line 171 carefully (parameters for model type, path, image size and so on).
import os
import math
import torch
import torch.nn as nn
import torchvision
import model.E.E as BE
#import model.E.E_blur as BE # if use case 2 change above line
impor... |
"""
LeetCode Problem: 22. Generate Parentheses
Link: https://leetcode.com/problems/generate-parentheses/submissions/
Language: Python
Written by: Mostofa Adib Shakib
Time complexity: Bounded by a catalan number
"""
"""
Conditions that makes parenthesis balanced:
1) An empty string is a string in which parenthesis are... |
# This package contains all the files for those advent days starting with a zero ('01' for day 1, et cetera).
|
# -*- coding: UTF-8 -*-
__author__ = "Liu Fei"
__github__ = "http://github.com/lfblogs"
__all__ = [
"logger_factory",
"data_factory",
"response_factory",
]
"""
"""
import asyncio
import json
try:
from aiohttp import web
except ImportError:
from aio2py.required.aiohttp import web
import logging
... |
# -*- coding: utf-8 -*-
from werkzeug.wrappers import Response, Request
@Request.application
def application(request):
return Response('Hello world')
if __name__ == '__main__':
from werkzeug.serving import run_simple
run_simple('0.0.0.0', 4000, application) |
# coding: utf-8
"""
Finnhub API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
fro... |
# Take 2 input sets A and B
input()
A = set(map(int, input().split()))
input()
B = set(map(int, input().split()))
# Print difference by symmetric_difference
print(len(A.symmetric_difference(B)))
|
import re
import time
import datetime
import requests
import execjs
import json
import rsa
import base64
import os
from lib.mp.base import Base
from lib.yundama import verify_captcha
from lib.tools.custom_exception import CustomException
from lib.tools import toutiao_login_js
class BaiJia(Base):
mp_id = 3
zh... |
#!/usr/bin/env python3
# xlattice_py/testTimestamp.py
""" Test timestamp-related functions. """
import calendar
import os
import time
import unittest
from xlutil import(mk_epoch_from_utc, get_utc_timestamp,
parse_timestamp, timestamp, timestamp_now)
from rnglib import SimpleRNG
class TestTimest... |
# Generated by Django 3.2.11 on 2022-02-28 14:32
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django_extensions.db.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(setti... |
"""Copyright (c) 2021, Nadun De Silva. 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 applicable law or agreed... |
import os
import numpy as np
from libcity.data.dataset import TrafficStateCPTDataset, TrafficStateGridDataset
from libcity.utils.dataset import timestamp2array, timestamp2vec_origin
class STResNetDataset(TrafficStateGridDataset, TrafficStateCPTDataset):
"""
STResNetๅค้จๆฐๆฎๆบไปฃ็ ๅช็จไบext_y, ๆฒกๆ็จๅฐext_x!
"""
def... |
from random import *
def rockPaperScissors(user,npc):
if user == 1 and npc == 1:
print("Tie")
elif user == 1 and npc == 2:
print("NPC Wins")
elif user == 1 and npc == 3:
print("User Wins!")
elif user == 2 and npc == 1:
print("User Wins")
elif user == 2 and npc == 2:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Filter for escaping unsafe XML characters: <, >, &
@author Sergey Chikuyonok (serge.che@gmail.com)
@link http://chikuyonok.ru
'''
import re
alias = 'e'
"Filter name alias (if not defined, ZC will use module name)"
char_map = {
'<': '<',
'>': '>',
'&': '&... |
#!/usr/bin/env python3
import shutil
import sys
import os
import ntpath
targetFiles = ["source/au/audiounitconfig.h", "source/au/Info.plist", "resource/llllpluginnamellll.rc", "source/version.h",
"source/pluginProcessor.cpp", "source/pluginProcessor.h", "source/pluginController.cpp", "source/pluginController.h",
"s... |
#!/usr/bin/python3
'''
print following Pattern
1
22
333
4444
if input = 5
'''
#code
for i in range(1, int(input())):
print ((10**(i)//9)*i)
|
# -*- coding: utf-8 -*-
# @Time : 2019/4/23 14:01
# @Author : hyy
# @Email : 1554148540@qq.com
# @File : water_quality_data.py
# @Software: PyCharm
import requests
import time
import os
import random
import smtplib
from email.mime.text import MIMEText
from email.header import Header
def get_data(url, value, ... |
from datetime import datetime
def convert_dt(year: int, month: int, day: int) -> str:
return datetime(year, month, day).strftime('%Y-%m-%d %H:%M:%S')
|
import csv
import os
# csvๆไปถ่ทฏๅพ
path = './csv/'
# ๅฎไนๆฐๆฎๆธ
ๆดๅฝๆฐdata_wash, ๆฅๆถfilename[ๆไปถๅ], la_max[ๆๅคง็บฌๅบฆ], ln_max[ๆๅคง็ฒพๅบฆ]ๅๆฐ,
def data_wash(filename, la_max, ln_max):
# ๅฎไนcsvๆไปถๅๅๅ
ฅๅจ,็จไบไฟๅญ็ๆ็csvๆไปถ,ไฟๅญ็ๆไปถๅไธบ:ๅๆไปถๆไปถๅ+_output
csv_out_file = open(path + filename + '_output', 'w')
csv_writer = csv.writer(csv_out_file)
# ... |
"""empty message
Revision ID: d55a3395296c
Revises: 19d023a4f56c
Create Date: 2017-03-16 15:24:42.688425
"""
# revision identifiers, used by Alembic.
revision = 'd55a3395296c'
down_revision = '19d023a4f56c'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - ... |
from __future__ import print_function
import os
import ast
import json
import demisto_client
from threading import Thread, Lock
from demisto_sdk.commands.common.tools import print_color, LOG_COLORS, run_threads_list, print_error
from Tests.Marketplace.marketplace_services import PACKS_FULL_PATH, IGNORED_FILES
PACK_ME... |
import json
import requests
def test_files_get_all(regtest, db, url, file):
r = requests.get(url + '/files')
f = r.json()
f['data']['files'][0]['timestamp'] = None
regtest.write(str(json.dumps(f, sort_keys=True)))
def test_files_get_filter(regtest, db, url, file):
r = requests.get(url + '/files?... |
import numpy as np
import matplotlib.pyplot as plt
from gwpy.timeseries import TimeSeriesDict
from gwpy.time import tconvert
import re
import warnings
warnings.filterwarnings('ignore')
#start = tconvert('Jul 20 2019 19:00:00 JST')
end = tconvert('Jul 20 2019 21:25:00 JST')
start = end - 2**11
channels = ['K1:P... |
# Copyright 2021 Red Hat, 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... |
import unittest
class FileUtilsTestCase(unittest.TestCase):
def test1(self):
print("test1")
self.assertEqual(1, 1)
if __name__ == '__main__':
unittest.main() |
#๋น
๋ฐ์ดํฐ ๋ถ์, ๋ฅ๋ฌ๋, ๋จธ์ ๋ฌ๋
import random
#seed : ์ฃผ์ด์ง ์ซ์๋ฅผ ๋ฐํ์ผ๋ก ๋์ ์์ฑ(๋ฐ์ํ ๋์๋ ๋ฐ๋์ง ์๋๋ค.)
random.seed(999)
#๋์ ๋ฐ์ 5๋ฅผ ์ง์ ํ์๊ธฐ์ 0~4๊น์ง ๋์๋ฐ์
a=[random.randrange(100) for _ in range(10)]
print(a)
#๋ฐ์ดํฐ -> ํ๋ จ๋ฐ์ดํฐ(์ฃผ์ด์ง ๋ฐ์ดํฐ์ 70% ์ ๋)/ํ
์คํธ๋ฐ์ดํฐ(30%) -> ๋ชจ๋ธ -> ํ
์คํธ๋ฐ์ดํฐ์
๋ ฅ -> ๋ชจ๋ธํ๊ฐ -> ํ๊ฐ ๊ฒฐ๊ณผ์ ๋ฐ๋ฅธ feedback
#์๊ณ ๋ฆฌ์ฆ์ ๋ฐ๊ฟ ๋ชจ๋ธ์ ๋ฐ๊ฟจ์ ๋ ํ์ต ๋ฐ ํ
์คํธ ๋ฐ์ดํฐ๊ฐ ๋ฐ๋๋ฉด ๋น๊ตํ ์ ์์ผ๋ฏ๋ก... |
import cv2 as cv
import numpy as np
import os
import sys
os.chdir(sys.path[0])
coeff = 2
target = cv.imread('resources/angel.jpg')
tgt_shape = np.flip(np.shape(target)[0:2])
target = cv.resize(target, (int(tgt_shape[0]/coeff), int(tgt_shape[1]/coeff)))
replacement = cv.imread('resources/book_template.jpg')
replacemen... |
from django.urls import reverse
from .base import AuthenticatedAPITestCase
from ..models import OffTopicChannelName
class UnauthenticatedTests(AuthenticatedAPITestCase):
def setUp(self):
super().setUp()
self.client.force_authenticate(user=None)
def test_cannot_read_off_topic_channel_name_lis... |
from pandac.PandaModules import *
from direct.task.Task import Task
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import StateData
from direct.fsm import ClassicFSM, State
from direct.fsm import State
class Walk(StateData.StateData):
notify = DirectNotifyGlobal.directNotify.newCategory('Walk')... |
# Copyright 2016 The Bazel 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 applicable la... |
"""
Hello World
------------
This simple workflow calls a task that returns "Hello World" and then just sets that as the final output of the workflow.
"""
import typing
# %%
# All imports at the root flytekit level are stable and we maintain backwards
# compatibility for them.
from flytekit import task, workflow
# %... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from conan_clang_update.conan_clang_update import Command
import platform
def is_macos():
return 'Darwin' in platform.system()
def test_update_clang_remote_project():
""" Clone dummy project and update it.
"""
args = ['--remote', 'uilianries/conan-base6... |
class Account:
"""
Account for a bank client.
"""
prefix = 'GIRO'
def __init__(self, newname, balance=0):
self.name = newname
self.balance = balance
def deposit(self, amt):
self.balance += amt
def withdraw(self, amt):
self.balance -= amt
... |
import datetime
import json
import os
import time
import sys
import pickle
import jsonpickle
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
from data.WebOrderLine import WebOrderLine
from tools.CNMWebOrdersScrapper import C... |
"""
@author: liyao
@contact: liyao2598330@126.com
@software: pycharm
@time: 2020/3/30 11:41 ไธๅ
@desc:
"""
import json
import datetime
import functools
from django.http import HttpResponse
from echidna.settings import HttpResponseMessage
# Json ๆ ๆณ่งฃๆ datatime ็ฑปๅ็ๆฐๆฎ๏ผๆๅปบ DateEncoder ็ฑป่งฃๅณ datatime ่งฃๆ้ฎ้ข
class DateEncoder(js... |
import torch
from torch import distributions as D
import dgl
import numpy as np
class embedding(torch.nn.Module):
'''in_dim, out_dim'''
def __init__(self, in_dim, out_dim, in_num_channels):
super(embedding, self).__init__()
self.conv1d_1 = torch.nn.Conv1d(in_num_channels, 8, 3, stride=1, paddi... |
import numpy as np
from tqdm.auto import tqdm
import matplotlib.pyplot as plt
import pandas as pd
from argent.live_plot import LivePlot
class Sweep:
def __init__(self, client, x, start, stop, steps, averages=1, sweeps=1, plot=None, legend=None):
''' Run a sweep across one or more variables.
Arg... |
# resource constants
# some minor setup required to run in record mode
# - actual subsid to be used
# - rg must exist
# - vnet must exist
TEST_RG='sdk-py-tests-rg'
TEST_ACC_1='sdk-py-tests-acc-1'
TEST_ACC_2='sdk-py-tests-acc-2'
TEST_POOL_1='sdk-py-tests-pool-1'
TEST_POOL_2='sdk-py-tests-pool-2'
TEST_VOL_1='sdk-py-t... |
# helper_module.py
# -*- coding: utf8 -*-
# vim:fileencoding=utf8 ai ts=4 sts=4 et sw=4
# Copyright 2016 National Research Foundation (South African Radio Astronomy Observatory)
# BSD license - see LICENSE for details
from __future__ import absolute_import, division, print_function
from future import standard_library
... |
from urllib.parse import urlparse
#get domain name (example.com)
def get_domain_name(url):
try:
results = get_sub_domain_name(url).split('.')
return results[-2] + '.' + results[-1]
except:
return ''
#get sub domain name (name.example.com)
def get_sub_domain_name(url):
try :
... |
class Solution:
# @param matrix, a list of lists of integers
# RETURN NOTHING, MODIFY matrix IN PLACE.
def setZeroes(self, matrix):
x = len(matrix)
if x > 0:
y = len(matrix[0])
else:
y = 0
rows = [1]*x
cols = [1]*y
for i in range(x):
... |
import bayesnewton
import objax
from bayesnewton.utils import inv
import numpy as np
from jax.config import config
config.update("jax_enable_x64", True)
import pytest
import tensorflow as tf
import gpflow
import scipy as sp
import pickle
gpflow.config.set_default_jitter(1e-20)
train_data = pickle.load(open(f'../exper... |
#!/usr/bin/env python3
import atexit
import requests
from pact import Consumer, Provider
pact = Consumer('sandwich-maker').has_pact_with(Provider('Butterer'))
pact.start_service()
atexit.register(pact.stop_service)
PACT_BASE_URL = 'http://localhost:1234'
BREAD_AND_BUTTER = 'bread and butter'
def test_buttering():... |
import os
import torch
import torch.nn.functional as F
import torch.distributed as dist
from torch.autograd import Variable
import numpy as np
import json
import cv2
CONFIG_PATH = os.getcwd()+'/../assets/config.ymal'
def within_bound(p,shape,r=0):
""" check if point p [y;x] or [y;x;theta] with radius r is inside ... |
from plotly.offline import plot
from plotly.graph_objs import Figure, Scatter, Marker, Line
import plotly.graph_objs as go
all_ranks = []
frequent_ranks = [] # for elements occurring at least twice
frequencies = []
rankfrequ = []
words = []
rank = 1
with open('frequencies.dat', "r") as ins:
for line in ins: #... |
import os, frontmatter, markdown, configparser
from jinja2 import Environment, FileSystemLoader, contextfilter, Markup
def markdownfilter(val):
return Markup(markdown.markdown(val))
env = Environment(loader=FileSystemLoader("./templates/"))
env.filters["markdown"]=markdownfilter
config = configparser.ConfigParser()... |
"""
Define the modelseed variable.
"""
import os
import sys
"""
This has now been abstracted into PyFBA.__init__.py to avoid redundancy
MODELSEED_DIR = ""
if os.path.exists('Biochemistry/ModelSEEDDatabase'):
MODELSEED_DIR = 'Biochemistry/ModelSEEDDatabase'
elif 'ModelSEEDDatabase' in os.environ:
MODELSE... |
import argparse
from collections import OrderedDict
from pathlib import Path
from typing import List, Dict, Any
import apex
import numpy as np
import pytorch_lightning as pl
import torch
import torch.nn.functional as F
import yaml
from albumentations.core.serialization import from_dict
from iglovikov_helper_functions.... |
from .models import Song, User
from rest_framework import serializers
class SongSerializer(serializers.ModelSerializer):
class Meta:
model = Song
fields = ('id', 'title', 'artist', 'album')
class UserSerializer(serializers.ModelSerializer):
song_count = serializers.ReadOnlyField(source='song... |
import pystache
from redwind.models import Post
from sqlalchemy import desc
import isodate
FEED_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{{title}}}</title>
<style>
body {
font-family: sans-serif;
max-width:800px;
}
h1,h2,h3,h4 {
font-size: 1em;
}
li {
list-st... |
from dataclasses import dataclass
from datetime import datetime
from . import RepoLanguages
@dataclass
class RepoStats(RepoLanguages):
created_at: datetime
stars: int
forks: int
score: float
def __hash__(self):
return super.__hash__(self)
def __eq__(self, other):
return super... |
#-------------------------------------------------------------------------
# The Azure Batch Apps Python Client
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated docu... |
# For plotting
import numpy as np
import matplotlib.pyplot as plt
#%matplotlib inline
# For conversion
from skimage.color import lab2rgb, rgb2lab, rgb2gray
from skimage import io
# For everything
import torch
import torch.nn as nn
import torch.nn.functional as F
# For our model
import torchvision.models as models
from ... |
#!/usr/bin/python
# Copyright (c) 2013 The Chromium OS 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 module tests the cros flash command."""
import mock
import os
import sys
sys.path.insert(0, os.path.abspath('%s/../../..' ... |
# Generated by Django 3.0.8 on 2020-12-28 13:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0010_invoice_pdf_document'),
]
operations = [
migrations.AlterField(
model_name='invoice',
name='pdf_doc... |
#
# Copyright (c) 2009-2020 Tom Keffer <tkeffer@gmail.com>
#
# See the file LICENSE.txt for your full rights.
#
"""Main engine for the weewx weather system."""
# Python imports
from __future__ import absolute_import
from __future__ import print_function
import gc
import logging
import socket
import sys
import ... |
from flask import jsonify, current_app
from dmapiclient.audit import AuditTypes
from dmutils.email.helpers import hash_string
from app import db
from app.callbacks import callbacks
from app.utils import get_json_from_request
from app.models import User, AuditEvent
@callbacks.route('/')
@callbacks.route('')
def call... |
'''
Storage helper class
MIT License
Copyright (c) 2019 Daniel Marchasin (daniel@vt77.com)
See LICENSE file
'''
import os.path
import sqlite3
import logging
logger = logging.getLogger(__name__)
dbfilename = 'data/.gamedata.db'
if not os.path.isfile(dbfilename):
with sqlite3.connect(dbfilename) as conn:
... |
"""
Module that provides access to the Proctor registry
or conditions.
The utility functions here could conceivably be wrapped
and exposed via a web endpoint.
All output from these utils should be json format.
"""
import logging
import serializers
from filter_set import FilterSet
from . import Proctor, ContextualCon... |
class Base():
def __init__(self, filename, byte_content, entries, option_map):
raise 'Not implemented!'
def parse(self):
pass
|
import tensorflow as tf
from tensorflow import keras
ops_module = tf.load_op_library('ops/ops.so')
class BinarizeLayer(keras.layers.Layer):
"""Binarize input probabilities via graph-cut algorithm."""
def __init__(self, gc_lambda, name=None):
super().__init__(trainable=False, name=name)
assert... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from quixote.errors import TraversalError
from vilya.models.project import CodeDoubanProject
from vilya.models.comment import Comment, latest
from vilya.views.util import http_method
_q_exports = []
class CommentUI:
''' project commit comment ui '... |
import cv2
class Rescale(object):
"""Rescale the image in a sample to a given size.
Args:
output_size (tuple or int): Desired output size. If tuple, output is
matched to output_size. If int, smaller of image edges is matched
to output_size keeping aspect ratio the same.
""... |
try:
from flask import Flask, render_template, url_for, request, redirect, make_response
import random
import json
import os
from time import time
from random import random
from flask import Flask, render_template, make_response
from flask_dance.contrib.github import make_github_blueprin... |
"""
This file writes all of the materials data (multi-group nuclear
cross-sections) for the LRA diffusion
benchmark problem to an HDF5 file. The script uses the h5py Python package
to interact with the HDF5 file format. This may be a good example for those
wishing ot write their nuclear data to an HDF5 file to import ... |
"""Test DNA/RNA folding."""
from os import path
from time import time
import unittest
from seqfold import dg, dg_cache, fold, Cache, Struct
from seqfold.dna import DNA_ENERGIES
from seqfold.rna import RNA_ENERGIES
from seqfold.fold import (
STRUCT_DEFAULT,
_traceback,
_bulge,
_stack,
_hairpin,
... |
load("@rules_proto//proto:defs.bzl", "ProtoInfo")
load(
"@io_bazel_rules_scala//scala_proto/private:scala_proto_aspect_provider.bzl",
"ScalaProtoAspectInfo",
)
load(
"@io_bazel_rules_scala//scala/private:phases/api.bzl",
"extras_phases",
"run_phases",
)
load("@bazel_skylib//lib:dicts.bzl", "dicts")
... |
from .data_augment import PairRandomCrop, PairCompose, PairRandomHorizontalFilp, PairToTensor
from .data_load import train_dataloader, test_dataloader, valid_dataloader
|
import argparse
from yaaf import Timestep
from openmdp.agents import QMDPAgent, MLSAgent, OptimalMDPPolicyAgent
from openmdp.scenarios import DuoNavigationPOMDP
def run(agent, pomdp, horizon, render=False):
fully_observable = agent.name == "Optimal MDP Policy"
state = pomdp.reset()
if not fully_observabl... |
"""
The MIT License (MIT)
Copyright (c) 2017 Marvin Teichmann
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import numpy as np
import scipy as scp
import logging
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)... |
class WellGrid:
"""Square grid class with regular spacing and well at grid center.
The default WellGrid object has radius gr=100 defining the square's
extent and grid density gd=21. An exception occurs if the grid radius is
not positive. Grid density defines the numbers of rows and columns
comprisi... |
"""Tests for VM actions called via WebTest
$ ~/eoscloud-venv/bin/python3 -m unittest eos_db.test.test_vm_actions_http
"""
import os
import unittest
from eos_db import server
from webtest import TestApp
from pyramid.paster import get_app
from http.cookiejar import DefaultCookiePolicy
# These states should be settab... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#__author__ = 'pyphrb'
def assign(service, arg):
if service == "joomla":
return True, arg
def audit(arg):
url = arg
_, head, body, _, _ = curl.curl(url + '/index.php?option=com_jobprofile&Itemid=61&task=profilesview&id=-1+union+all+select+1,concat_ws(0... |
import logging
from unittest import mock
from .common import generate_msg
from pypeman.message import Message
from pypeman.test import TearDownProjectTestCase as TestCase
class MessageTests(TestCase):
def test_message_dict_conversion(self):
m = generate_msg(message_content={'answer': 42}, with_context... |
# Factory test suit
from silhouette.factory import *
def test_render_file_paths():
src_paths = ["/home/ubuntu/project/$name$/$module$/readme.md", "/home/ubuntu/project/$name$/$module$/jenkinsfile"]
vars = {"name": "flask", "module": "example"}
result = render_file_paths(src_paths, vars)
assert('/home/u... |
from unittest import TestCase
from scripts.helpers import hash_password
class TestExample(TestCase):
def test_mytest(self):
self.assertTrue(True)
|
"""
python file object library
"""
# imports python
import json
import imp
import cPickle
# imports local
from . import _generic
# PYTHON FILE OBJECTS #
class JsonFile(_generic.File):
"""file object that manipulate a ``.json`` file on the file system
"""
# ATTRIBUTES #
_extension = 'json'
#... |
def main():
from pyperclip import copy as cpy
import pyautogui
from time import sleep
def gg():
sleep(3)
cpy('!p gooba earrape')
pyautogui.hotkey('ctrl', 'v')
pyautogui.press('enter')
cpy('-p gooba earrape')
pyautogui.hotkey('ctrl', 'v')
... |
def alphabet_war(fight):
|
import hy
import main
def run():
parts = {"head": "O", "torso": "|", "l_arm": "-", "r_arm": "-", "l_leg": "/", "r_leg": "\\"}
print(main.game_loop({"lives": 6, "word": "hangman".lower(), "guess": [], "body": {}, "parts": parts, "letters": []}))
if __name__ == '__main__':
run()
while input('Replay? Y/N... |
# Import numpy as np
import numpy as np
# Calculate the portfolio standard deviation
portfolio_volatility = np.sqrt(np.dot(portfolio_weights.T, np.dot(cov_mat_annual, portfolio_weights)))
print(portfolio_volatility)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.