content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
class Config:
redis = {
'host': '127.0.0.1',
'port': '6379',
'password': None,
'db': 0
}
app = {
'name': 'laravel_database_gym',
'tag': 'swap'
}
conf = Config()
| python |
# Copyright 2018 ZTE Corporation.
#
# 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 ... | python |
#!/usr/bin/python
"""
Broker for MQTT communication of the agent.
Copyright (C) 2017-2022 Intel Corporation
SPDX-License-Identifier: Apache-2.0
"""
import logging
import json
from typing import Optional
from diagnostic.ibroker import IBroker
from diagnostic.diagnostic_checker import DiagnosticChecker
fro... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: https://github.com/monero-project/mininero
# Author: Dusan Klinec, ph4r05, 2018
# see https://eprint.iacr.org/2015/1098.pdf
import logging
from monero_glue.xmr import common, crypto
from monero_serialize import xmrtypes
logger = logging.getLogger(__name__)
de... | python |
import os
from dataclasses import dataclass, field
from di import Container, Dependant
@dataclass
class Config:
host: str = field(default_factory=lambda: os.getenv("HOST", "localhost"))
class DBConn:
def __init__(self, config: Config) -> None:
self.host = config.host
async def controller(conn: DB... | python |
from beaker._compat import pickle
import logging
from datetime import datetime
from beaker.container import OpenResourceNamespaceManager, Container
from beaker.exceptions import InvalidCacheBackendError
from beaker.synchronization import null_synchronizer
log = logging.getLogger(__name__)
db = None
class GoogleNa... | python |
# Generated by Django 3.1.5 on 2021-05-01 09:50
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_depende... | python |
parrot = "Norwegian Blue"
letter = input('Enter a char: ')
if letter in parrot:
print('it is in there')
else:
print('not there')
activity = input("What would you like to do today? ")
# I want to go to Cinema
if "cinema" not in activity.casefold(): # casefold handles some languages better
print("But I wa... | python |
from __future__ import absolute_import
from .node import Node
from .edge import Edge
from .domain import URI, Domain
from .file import File, FileOf
from .ip_address import IPAddress
from .process import Launched, Process
from .registry import RegistryKey
from .alert import Alert
__all__ = [
"Node",
"Edge",
... | python |
#!/usr/bin/env python3
# Advent of Code 2016 - Day 13, Part One & Two
import sys
from itertools import chain, combinations, product
# test set
# start = (1, 1)
# goal = (7, 4)
# magic = 10
# part one & two
start = (1, 1)
goal = (31, 39)
magic = 1352
def is_valid(coord):
x, y = coord
if x < 0 or y < 0:
... | python |
def extractWwwScribblehubCom(item):
'''
Parser for 'www.scribblehub.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
if len(item['tags']) == 2:
item_title, item_id = item['tags']
if item_id.isdigit():
... | python |
from taichi.profiler.kernelprofiler import \
KernelProfiler # import for docstring-gen
from taichi.profiler.kernelprofiler import get_default_kernel_profiler
| python |
from setuptools import setup
# Convert README.md to README.rst because PyPI does not support Markdown.
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst', format='md')
except:
# If unable to convert, try inserting the raw README.md file.
try:
with open('README.md', enco... | python |
from sanic import Sanic
from sanic.response import text
from sanic_plugin_toolkit import SanicPluginRealm
#from examples.my_plugin import my_plugin
from examples import my_plugin
from examples.my_plugin import MyPlugin
from logging import DEBUG
app = Sanic(__name__)
# mp = MyPlugin(app) //Legacy registration example
... | python |
from time import sleep
from procs.makeTree import rel2abs
# ์ํ๋ถ
def loadSet(): # ์ ์ ๊ฐ ๊ตฌ์ฑํ ๋งคํฌ๋ก ๋ถ๋ฌ์ค๊ธฐ ์ฝ๋
try:
f = open("macro.brn", 'r')
except FileNotFoundError:
return
try:
lines = f.readlines()
for line in lines:
spite_line = line.split()
list_make = ... | python |
from __future__ import print_function
import math, json, os, pickle, sys
import keras
from keras.callbacks import CSVLogger, EarlyStopping, ModelCheckpoint, LambdaCallback
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras.layers import Conv2... | python |
#This is an exercise program which shows example how while loop can be utilized.
password = ''
while password != 'python123':
password = input("Enter password:")
if password == 'python123':
print("You are logged in!")
else:
print("Try again.") | python |
import argparse
import random
from typing import Any, Dict, List, Sequence, Tuple
import segmentation_models_pytorch as smp
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.transforms.functional import (InterpolationMode, hflip,
resized_... | python |
import sys
from cx_Freeze import setup, Executable
build_exe_options = {"packages": ["os"]}
base="Win32GUI"
setup( name="NPSerialOscilloscopeGUI",
version="1.0",
description="potato",
options = {"build_exe": build_exe_options},
executables = [Executable("oscilloscope_gui.py", base=base)]) | python |
"""
Problem Statement:
Implement a function,ย `find_first_unique(lst)`ย that returns
the first unique integer in the list.
Input:
- A list of integers
Output:
- The first unique element in the list
Sample Input:
[9,2,3,2,6,6]
Sample Output:
9
"""
def find_first_unique(lst):
is_unique = {}
for i, v in enum... | python |
#!/usr/bin/env python
import itertools
with open('input') as f:
serial_number = int(f.read())
# Puzzle 1
def get_power_level(x, y, serial_number):
rack_id = x + 10
power_level = ((rack_id * y) + serial_number) * rack_id
power_level = (power_level // 100 % 10) - 5
return power_level
def get_total_... | python |
import os
import nose
import ckanext.dcatapit.interfaces as interfaces
from ckanext.dcatapit.commands.dcatapit import DCATAPITCommands
eq_ = nose.tools.eq_
ok_ = nose.tools.ok_
class BaseOptions(object):
def __init__(self, options):
self.url = options.get("url", None)
self.name = options.get("... | python |
from .Solver import Solver
| python |
#!/usr/bin/env python
# Copyright 2016 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... | python |
"""Location cards."""
import logging
from onirim.card._base import ColorCard
from onirim import exception
from onirim import util
LOGGER = logging.getLogger(__name__)
class LocationKind(util.AutoNumberEnum):
"""
Enumerated kinds of locations.
Attributes:
sun
moon
key
"""
... | python |
import logging
import argparse
import transaction
from pyramid.paster import bootstrap
from .actions import proceed_contest
from .db import Config
def process_queue():
parser = argparse.ArgumentParser()
parser.add_argument("config", help="config file")
args = parser.parse_args()
logging.basicConfig()... | python |
#!/usr/bin/env false
"""Generate script to activate project."""
# Internal packages (absolute references, distributed with Python)
# External packages (absolute references, NOT distributed with Python)
# Library modules (absolute references, NOT packaged, in project)
# from src_gen.script.bash.briteonyx.source import... | python |
from HTML import Curve_Write_HTML
from Data import Curve_Write_Data
from SVG import Curve_Write_SVG
class Curve_Write(
Curve_Write_HTML,
Curve_Write_Data,
Curve_Write_SVG
):
##!
##!
##!
def sifsdifdsgf(self):
return 0
| python |
"""
Python script containing methods for building machine learning model
"""
import utils.text_processing as tp
def classifier(X, y, tokenizer, config):
word_ind_dict = tokenizer.word_index
glove_path = config.get("glove_path")
vocab_size = config.get("vocab_size")
seq_len = config.get("seq_len")
... | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: proto/diff-img.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.... | python |
"""Example training a nobrainer model for brain extraction."""
import nobrainer
# Instantiate object to perform real-time data augmentation on training data.
# This object is similar to `keras.preprocessing.image.ImageDataGenerator` but
# works with volumetric data.
volume_data_generator = nobrainer.VolumeDataGenerat... | python |
from bflib import dice, movement, units
from bflib.attacks import AttackSet, Bite, Gaze
from bflib.attacks import specialproperties
from bflib.characters import specialabilities
from bflib.characters.classes.fighter import Fighter
from bflib.monsters import listing
from bflib.monsters.appearingset import AppearingSet
f... | python |
import requests
from bs4 import BeautifulSoup
address = []
def get_html(url):
r = requests.get(url, headers={
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/97.0.4692.99 Safari/537.36',
'accept': '*/*'})
return r... | python |
# Copyright 2018 Braxton Mckee
#
# 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 t... | python |
from blinker import NamedSignal, signal
from sagas.nlu.events import ResultDataset, RequestMeta
from sagas.conf.conf import cf
import sagas.tracker_fn as tc
from pprint import pprint
watch = signal('watch')
# evts=[watch]
@watch.connect
def console_watch(sender, **kw):
import datetime
from sagas.nlu.nlu_tool... | python |
import numpy as np
class SpatioTemporalSignal(object):
"""
This Class is used to create a group of N signals that interact in space
and time. The way that this interaction is carrieud out can be fully
determined by the user through a SpatioTemporal matrix of vectors that
specify how the signals mix... | python |
from . import Token
class TreeNode(object):
# dictionary mapping {str: TreeNode}
id_treeNodes = {}
def getTreeNode(idx):
return TreeNode.id_treeNodes[idx]
def __init__(self, idx, tkn):
self._id = idx
self._tkn = tkn
self._children = {}
TreeNode.id_treeNodes[i... | python |
from flask import Flask
from chatpy.api import API
from chatpy.auth import TokenAuthHandler
app = Flask(__name__)
app.config.from_object('config')
chatwork = API(auth_handler=TokenAuthHandler(app.config['CHATWORK_TOKEN']))
from app.endpoint import *
| python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by... | python |
# Copyright (c) 2021, CRS4
#
# 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 Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribu... | python |
import billboard
import json
import urllib
from urllib.parse import quote
apikey = 'APIKEY'
# make the empty dictionary
songs = {}
# loop through the years we're interested in
for x in range(1960, 2016):
# another dictionary inside
songs[x] = {}
# get the chart for the last week of that year
chart = ... | python |
#! /usr/bin/env python
"""Perform massive transformations on a document tree created from the LaTeX
of the Python documentation, and dump the ESIS data for the transformed tree.
"""
import errno
import esistools
import re
import string
import sys
import xml.dom
import xml.dom.minidom
ELEMENT = xml.dom.Node.ELEMENT_... | python |
import importlib.util
import os
def vyLoadModuleFromFilePath(filePath, moduleName=None):
if moduleName == None:
replacements = [
('/', '.'),
('\\', '.'),
('-', '_'),
(' ', '_'),
]
filePathSansExt = os.path.splitext(filePath)[0]
for iss... | python |
from ._plugin import Workplane
from ._plugin import extend | python |
"""Testing File for roman_ssg_util"""
import os
import shutil
import roman_ssg_util
def setup_test():
"""Setup Tests for tests"""
os.chdir(os.getcwd())
if os.path.isdir("dist"):
shutil.rmtree("dist")
if os.path.isdir("testCustomDirectory"):
shutil.rmtree("testCustomDirectory")
def te... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# */AIPND/intropylab-classifying-images/check_images.py
#
# DONE: 0. Fill in your information in the programming header below
# PROGRAMMER: Aimee Ukasick
# DATE CREATED: 11 April 2018
# REVISED DATE: <=(Date Revised - if any)
# PURPOSE: Check images & report re... | python |
# -*- coding: utf-8 -*-
# Copyright (C) 2017 Intel Corporation. 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
#
# ... | python |
import os
import sys
import hashlib
def e(s):
if type(s) == str:
return s
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
def running_in_virtualenv():
return hasattr(sys, 'r... | python |
import unittest
import pprint
import os
from numpy import testing
import invest_natcap.fisheries.fisheries_hst as main
import invest_natcap.fisheries.fisheries_hst_io as io
pp = pprint.PrettyPrinter(indent=4)
workspace_dir = './invest-data/test/data/fisheries/'
data_dir = './invest-data/Fisheries'
inputs_dir = os.p... | python |
"""
Decorators
"""
import sys
from contextlib import contextmanager
import mock
from maya_mock.cmds import MockedCmdsSession
from maya_mock.pymel import MockedPymelSession, MockedPymelNode, MockedPymelPort
@contextmanager
def _patched_sys_modules(data):
"""
Temporary override sys.modules with provided data.... | python |
# -*- coding: utf-8 -*-
from .torsimany import main
main() | python |
from cumulusci.tasks.metadata_etl.base import (
BaseMetadataETLTask,
BaseMetadataSynthesisTask,
BaseMetadataTransformTask,
MetadataSingleEntityTransformTask,
MetadataOperation,
)
from cumulusci.tasks.metadata_etl.duplicate_rules import SetDuplicateRuleStatus
from cumulusci.tasks.metadata_etl.layouts... | python |
# Copyright The PyTorch Lightning 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 law or agreed to i... | python |
features = [1,2,3]
prices = [1,2,3]
theta = [0,0]
LEARNING_RATE=0.01
NO_TRAINING_EXAMPLES=len(features)
EPSILON=0.000000001
#Cost function to calculate half the average of the squared errors for the given theta
def cost(features, prices, theta):
sum = 0
for i in range(NO_TRAINING_EXAMPLES):
... | python |
__all__ = ('WeakMap',)
from .docs import has_docs
from .removed_descriptor import RemovedDescriptor
from .weak_core import WeakReferer, add_to_pending_removals
@has_docs
class _WeakMapCallback:
"""
Callback used by ``WeakMap``-s.
Attributes
----------
_parent : ``WeakReferer`` to ``WeakMap``... | python |
import dash
import dash_table
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from database import get_data_cache, get_all_food_data
external_stylesheets = ['https://codep... | python |
# Generated by Django 3.1.7 on 2021-04-07 15:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Rubric',
fie... | python |
# based on django-markdownify
# https://github.com/erwinmatijsen/django-markdownify
# https://django-markdownify.readthedocs.io/en/latest/settings.html
from functools import partial
from django import template
from django.conf import settings
import bleach
from markdownx.utils import markdownify as markdownx_markdow... | python |
"""
Artificial Images Simulator
============================
The Artificial Images Simulator (AIS) class was developed to generate
artificial star images, similar to those images that would be acquired by
using the acquisition system of the instrument. To accomplish this,
the AIS models as star flux as a 2D gaussian d... | python |
from rest_framework import viewsets
from .models import RESP, REGONError, REGON, JSTConnection, Institution, ESP
from .serializers import RESPSerializer, REGONSerializer, REGONErrorSerializer, JSTConnectionSerializer, \
InstitutionSerializer, ESPSerializer
class InstitutionViewSet(viewsets.ReadOnlyModelViewSet):... | python |
# coding=utf-8
from OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField
from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde
# Generated with OTLEnumerationCreator. To modify: extend, do not edit
class KlEleAansluitvermogen(KeuzelijstField):
"""Keuzelijst met gangbare waarden voor ... | python |
# Generated by Django 2.0.2 on 2018-04-26 17:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0002_auto_20180406_1917'),
]
operations = [
migrations.AlterField(
model_name='profile',
name... | python |
# -*- coding: utf-8 -*-
'''
:file: score.py
:author: -Farmer
:url: https://blog.farmer233.top
:date: 2021/09/20 20:06:29
'''
# cjcx/cjcx_cxDgXscj.html?doType=query&gnmkdm=N305005&su=2018133209
from school_sdk.client.api import BaseCrawler
class Score(BaseCrawler):
def __init__(self, user_client)... | python |
# --------------------------------------------------------
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License
# --------------------------------------------------------
import os
import random
from PIL import Image
from PIL import ImageFile
from torch.utils.data import Dataset
from .transforms import tr... | python |
#
""""""
from os import getpid
import logging.handlers
from .snippet import T2I
def mapped_level(name):
levels = {'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'fatal': logging.FATAL}
return levels[name] if name in levels else logging.WARNING;
def mapped_wh... | python |
"""
October 2018
Simulations of a Ramsey experiment in the presence of flux 1/f noise
"""
import time
import numpy as np
import qutip as qtp
from pycqed.measurement import detector_functions as det
from scipy.interpolate import interp1d
import scipy
import matplotlib.pyplot as plt
import logging
from pycqed.simulation... | python |
from .cloudchain import checkconfig
from .cloudchain import CloudChainConfigError
from .cloudchain import CloudChainError
from .cloudchain import CloudChain
from .cloudchain import decryptcreds
from .cloudchain import encryptcreds
from .cloudchain import endpoint_url
from .cloudchain import getconn
from .cloudchain imp... | python |
import logging
from typing import List, Dict
from bs4 import BeautifulSoup, element
from .row_utils import (
movies_utils,
series_utils,
books_utils,
comics_utils,
music_utils,
videogames_utils,
)
logger = logging.getLogger(__name__)
def get_rows_from_topchart(soup: BeautifulSoup) -> List[e... | python |
#!/usr/bin/env python3
"""
For each family and device, obtain a tilegrid and save it in the database
"""
import os
from os import path
import subprocess
import extract_tilegrid
import database
def main():
devices = database.get_devices()
for family in sorted(devices["families"].keys()):
for device i... | python |
import os
import random
import string
import pytest
from check_mk_web_api import WebApi, CheckMkWebApiException
api = WebApi(
os.environ['CHECK_MK_URL'],
os.environ['CHECK_MK_USER'],
os.environ['CHECK_MK_SECRET']
)
def setup():
api.delete_all_hosts()
api.delete_all_hostgroups()
api.delete_a... | python |
from functools import reduce
hashes = [None] + [i for i in range(1, 11)]
index = 0
hash_list = [(lambda _h=h: _h, i == index, []) for i, h in enumerate(hashes)]
print(hashes)
print("zip = {0}".format(zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])))
while len(hash_list) > 1:
hash_list = [
(
... | python |
import numpy as np
import pandas as pd
from dataset import MultiDataset, RegressionDataset
def scatter_path_array(path_data, size, rank):
all_lst = []
for row, item in path_data.iterrows():
path, num = item['path'], int(item['num'])
all_lst.extend([[path, i] for i in range(num)])
all_lst ... | python |
from . import controller
from . import model
| python |
#------------------------------------------------------------------------------
# Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# Shar... | python |
'''
Comp_slice is a terminal fork of intra_blob.
-
It traces blob axis by cross-comparing vertically adjacent Ps: horizontal slices across an edge blob.
These low-M high-Ma blobs are vectorized into outlines of adjacent flat or high-M blobs.
(high match: M / Ma, roughly corresponds to low gradient: G / Ga)
-
Vectorizat... | python |
__version__ = "0.2"
from PyQNX6.core import *
| python |
import numpy
import six
from chainer.backends import cuda
from chainer import function_node
from chainer import utils
from chainer.utils import collections_abc
from chainer.utils import type_check
def _tensordot(a, b, a_axes, b_axes, c_axes=None):
a_col_ndim = len(a_axes[1])
b_row_ndim = len(b_axes[0])
i... | python |
import pytest
from di.core.element import Element
from di.core.module import (
Module,
ModuleElementConsistencyCheck,
ModuleElementConsistencyError,
ModuleImportSolver,
ModuleImportSolverError,
)
def test_module_cycle():
modules = [Module(name=f"{index}") for index in range(3)]
modules[0]... | python |
import acipdt
import xlrd
import xlwt
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from xlutils.copy import copy
from orderedset import OrderedSet
import sys
import time
import ipaddress
import getpass
import os
# Log levels 0 = None, 1 = Class only, 2 = Line
log_level = 2
#... | python |
from distutils.version import StrictVersion
from unittest.mock import patch
from keepassxc_pwned.keepass_wrapper import KeepassWrapper
from .common import *
# use keepassxc.cli wrapper script to test changing location of keepassxc-cli
keepass_different_binary = os.path.abspath(
os.path.join(this_dir, "keepassxc.... | python |
# -*- coding: utf-8 -*-
'''
Support for the softwareupdate command on MacOS.
'''
from __future__ import absolute_import
# Import python libs
import re
import os
# import salt libs
import salt.utils
import salt.utils.mac_utils
from salt.exceptions import CommandExecutionError, SaltInvocationError
__virtualname__ = '... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 23 13:01:46 2020
@author: dnb3k
"""
#use the unique Full Tokens code to get teh dataframe
import ossPyFuncs
import pandas as pd
import wordcloud
import re
import matplotlib.pyplot as plt
import os
import numpy as np
#perform sql query to get comp... | python |
# Write the benchmarking functions here.
# See "Writing benchmarks" in the asv docs for more information.
from math import radians
import numpy as np
from passpredict import _rotations
class Rotations:
"""
Example from Vallado, Eg 11-6, p. 912
"""
def setup(self, *args):
self.lat = radians(4... | python |
"""
Main file!
"""
import argparse
import logging
import pickle
import string
import sys
from typing import Optional, TextIO, BinaryIO
import ujson
from vk_dumper import utils, vk
log = logging.getLogger('vk-dumper')
def main() -> None:
log.info('Starting vk-dumper!')
args = parse_args()
# Output vari... | python |
from .iostream import cprint, cin, cout, cerr, endl
from .cmath import *
from . import cmath, iostream
| python |
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from tracpro.test import factories
from tracpro.test.cases import TracProTest
from .. import charts
from .. import models
class PollChartTest(TracProTest):
def setUp(self):
super(PollChartTest, self).setUp()
... | python |
# Copyright 2021 The Distla 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 ... | python |
"""
Train a DeeProtein-model.
"""
import argparse
import json
from DeeProtein import DeeProtein
import helpers
import os
def main():
with open(FLAGS.config_json) as config_fobj:
config_dict = json.load(config_fobj)
# set the gpu context
if not FLAGS.gpu:
if config_dict["gpu"] == 'True':
... | python |
# -*- coding: utf-8 -*-
__author__ = 'Lara Olmos Camarena'
import re
import json
import re
"""
utils
"""
def preprocess_text(text_str):
regular_expr = re.compile('\n|\r|\t|\(|\)|\[|\]|:|\,|\;|"|\?|\-|\%')
text_str = re.sub(regular_expr, ' ', text_str)
token_list = text_str.split(' ')
token_list = [e... | python |
import importlib
from time import clock
for i in range(2):
module = input("Enter module to import")
importlib.import_module(module)
start = clock()
print(iterativefact(27))
end = clock()
elapsed = end - start
print(elapsed)
start = clock()
print(recursivefactorial(27))
end = clock()
elapsed = end - start
prin... | python |
# -*- encoding: utf-8 -*-
"""
Boolean type comparator used to match Boolean
Comparators are used by Audit module to compare module output
with the expected result
In FDG-connector, comparators might also be used with FDG
Boolean comparator exposes various commands:
- "match"
Use Cases:
- To check a boolea... | python |
'''MobileNet in PyTorch.
See the paper "MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
for more details.
'''
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import os, sys
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sy... | python |
import numpy as np
import tensorflow as tf
import scipy.signal
def add_histogram(writer, tag, values, step, bins=1000):
"""
Logs the histogram of a list/vector of values.
From: https://gist.github.com/gyglim/1f8dfb1b5c82627ae3efcfbbadb9f514
"""
# Create histogram using numpy
counts, bin_edges... | python |
# See documentation in:
# http://doc.scrapy.org/topics/items.html
from scrapy.item import Item, Field
class Author(Item):
name = Field()
profile_url = Field()
avatar_url = Field()
class BlogAuthor(Author):
pass
class CommentAuthor(Author):
pass
class Post(Item):
author = Field()
title =... | python |
import xml.etree.ElementTree as ET
import fnmatch
import matplotlib.pyplot as plt
#rootDir = '/Users/yanzhexu/Desktop/Research/GBM/aCGH_whole_tumor_maps_for_Neuro-Onc_dataset/CEFSL_slices_only/slice22/ROI for +C_3D_AXIAL_IRSPGR_Fast_IM-0005-0022.xml'
# draw ROI from coordinates in XML file
def ParseXMLDrawROI(rootDir... | python |
word = 'Bye'
phrase = word * 3 + '!'
print(phrase)
name = input()
print('I love', name) | python |
# <<BEGIN-copyright>>
# Copyright 2021, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# <<END-copyright>>
from PoPs import IDs as IDsPoPsModule
from PoPs.groups import misc as chemicalElementMiscPoPsModule
from fudge.channelData i... | python |
import numpy as np
from scipy.linalg import expm
from tqdm import tqdm
import time
from utils import visualize_trajectory_2d,load_data
############## All Utility Functions ###############
def round_dot(vec):
'''
:param vec: A point in homogeneous co-ordinate
:return: 0 representation for the vector
... | python |
from rule import *
from operator import methodcaller
def chi_toi_checker(cards):
return 0
def ko_ku_shi_checker(cards):
return 0
def ron_dfs(handcards):
if (len(handcards) == 0):
return True
return False
#no matter whether have yaku
def can_ron(cards):
if (ron_dfs(cards.handcards)):
return True
... | python |
import pytest
import torch
import time
from ynot.datasets import FPADataset
from ynot.echelle import Echellogram
from torch.utils.data import DataLoader
import torch.optim as optim
import torch.nn as nn
@pytest.mark.parametrize(
"device", ["cuda", "cpu"],
)
def test_forward_backward(device):
"""Do the scene m... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.