content stringlengths 5 1.05M |
|---|
"""Review a change"""
import argparse
import logging
import os
from libpycr.editor import raw_input_editor, strip_comments
from libpycr.exceptions import NoSuchChangeError, PyCRError
from libpycr.gerrit.client import Gerrit
from libpycr.meta import GitClBuiltin
from libpycr.utils.output import Formatter, NEW_LINE
fro... |
from discord.ext import commands
import discord, praw, datetime, json, os
version_number = "1.4.2"
version = version_number + " Created by bwac#2517"
red = 0xFF0000
with open("secrets.json") as json_file:
secrets = json.load(json_file)
trophyemojis = None
with open("trophyemoji.json") as json_file:
trophyem... |
import setuptools
import PyVuka.pyvuka as pvk
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name=pvk.__app_name__,
version=pvk.__version__,
author=pvk.__author__,
author_email=pvk.__email__,
description=pvk.__description__,
long_description=l... |
import os, sys
import numpy as np
import tensorflow as tf
import model
from model.util import *
class PseudoLabeling:
"""Pseudo-labeling function, which is implemented in the python iterator"""
def __init__(self, model_base, model_conf, ld_src, ld_tar, ideal=False):
"""
model_base: a c... |
"""The Strava integration."""
from __future__ import annotations
import logging
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import con... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
import binascii
import os
import struct
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/nfcpy')
import nfc
num_blocks = 20
service_code = 0x090f
class StationRecord(object):
db = None
def __init__(self, row):
self.area_k... |
# -*- coding: utf-8 -*-
"""Adult dataset example.
Neural network model definition
Example:
>>> ./dq0 project create --name demo # doctest: +SKIP
>>> cd demo # doctest: +SKIP
>>> copy user_model.py to demo/model/ # doctest: +SKIP
>>> ../dq0 data list # doctest: +SKIP
>>> ../dq0 model attach --id <d... |
#
# Copyright (C) 2009-2021 Alex Smith
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS A... |
#Test Online Decoder Set up
from definitions import *
### TODO
class PSTH: ###Initiate PSTH with desired parameters, creates unit_dict which has wanted units and will catch timestamps from plexon.
def __init__(self, channel_dict, pre_time_start, pre_time_end, post_time_start, post_time_end, pre_total_bin... |
from django.db import models
from core.models import FactionType, User
class Faction(models.Model):
name = models.CharField(max_length=250)
description = models.TextField(blank=True, null=True)
image = models.ImageField(upload_to='factions', blank=True, null=True)
type = models.ForeignKey(FactionType... |
import random
finish=[]
start=[0,0]
fires=[]
walls=[]
env=[]
def init_env():
for i in range(102):
env.append([])
for j in range(102):
env[i].append(0)
def init_finish():
x=random.randint(1,101)
y=random.randint(1,101)
finish.append(x)
finish.append(y)
... |
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from xinfo.getXInfo import get_xSettings
# Hospital Information Model.
class HospitalInformation(models.Model):
type = models.CharField(
max_length=4,
help_text="Type of hospital ... |
import re
import numpy as np
import lib.libhelperfunctions as hf
import lib.errors as err
import matplotlib.pyplot as plt
def import_cnc(fname):
with open(fname) as f:
text = f.read()
return text
def clear_code(s):
# replace all linebreaks
lines = s.splitlines()
# replace all indentati... |
import numpy as np
import os
import re
from collections import defaultdict
from scipy import random
validationDir = 'validation'
if not os.path.exists(validationDir):
os.makedirs(validationDir)
output = np.genfromtxt('whales.csv', skip_header=1, dtype=[('image', 'S10'), ('label', 'S11')], delimiter=',')
whales = ... |
import torch
import cv2
import numpy as np
def size(net):
pp = 0
for p in list(net.parameters()):
nn = 1
for s in list(p.size()):
nn = nn * s
pp += nn
return pp
def gen_trimap(segmentation_mask, k_size = 7, iterations = 6):
kernel = cv2.getStructuringElement(cv2.MOR... |
# This __init__.py file for the vscmgStateEffector package is automatically generated by the build system
from vscmgStateEffector import * |
#!/usr/bin/env python3
s, _, *i = open(0).read().replace(" ", "").split()
for j in sorted(i, key = lambda a: int(a.translate(str.maketrans(s, "0123456789")))):
print(j) |
#
# Copyright 2021 W. Beck Andrews
#
# MIT License
#
# 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... |
import requests
import json
from DNA_Token import get_auth_token
def get_device():
"""Building out function to retrieve the uuid of a device. Using requests.get to make a call to the network device"""
token = get_auth_token() # Get Token
url = "https://10.1.100.9/dna/intent/api/v1/network-device/ip-address... |
# coding=utf-8
from singer import Singer
import requests
import json
import xlwt
# pip3 install singer xlwt
class GitlabRest(object):
def __init__(self):
config = Singer.config(mode='gitlab')
self.__gateway = config.get_config('url').strip('/')
self.__api_url = "%s/api/v4" % self.__gatew... |
import re
import yaml
class Character:
def __init__(self, name):
self.name = name
class Event:
def __init__(self, template_text):
self.template_text = template_text
def format(self, context):
tag_pattern = re.compile('<[a-z]+>')
formatted_text = self.template_text
... |
#!/usr/bin/env python3
import argparse
import sys
import matplotlib.pyplot as plt
import numpy as np
from scipy.special import softmax
import sklearn.datasets
import sklearn.metrics
import sklearn.model_selection
from sklearn.metrics import log_loss
if __name__ == "__main__":
parser = argparse.ArgumentParser()
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from itertools import product, chain
from pathlib import Path
import numpy as np
import tensorflow as tf
from dotenv import load_dotenv
from annotation.direction import Direction, get_diagonal_directions
from annotation.piece import Piece
from ..gi import Black... |
import math
import torch
import numpy as np
import matplotlib.pyplot as plt
from tme6 import CirclesData
def init_params(nx, nh, ny):
params = {}
# TODO remplir avec les paramètres Wh, Wy, bh, by
# params["Wh"] = ...
return params
def forward(params, X):
outputs = {}
# TODO remplir avec le... |
import click
import redis
from prometheus_client import start_http_server
from huey_exporter.EventQueue import EventQueue
@click.command()
@click.option('--connection-string', '-c',
envvar='REDIS_CONNECTION_STRING',
default='redis://localhost:6379',
help='Connection string t... |
x = int(input())
n = 1
while 2 ** n <= x:
n += 1
print(n - 1, 2 ** (n - 1)) |
import discord
import random
import urllib
from discord.ext import commands
class MarioParty(commands.Cog):
"""Cog for Mario Party commands"""
def __init__(self, bot):
self.bot = bot
#Board Command
@commands.group(pass_context=True)
async def board(self, ctx): pass
#1 Subc... |
from anthill.framework.utils.asynchronous import as_future, thread_pool_exec as future_exec
from anthill.framework.core.exceptions import ImproperlyConfigured
from anthill.framework.core.paginator import Paginator, InvalidPage
from anthill.framework.handlers import RequestHandler
from anthill.framework.http.errors impo... |
#!/usr/bin/python
#
# Copyright (C) 2018 stephen.farrell@cs.tcd.ie
#
# 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, c... |
#!/usr/bin/env python
import gevent.monkey; gevent.monkey.patch_all()
import sys
from argparse import ArgumentParser
import yaml
from rtmbot import RtmBot
import logging
def parse_args():
parser = ArgumentParser()
parser.add_argument(
'-c',
'--config',
help='Full path to config file.',... |
"""
Tools for visualization, including metrics plots, and generating the html
graph of the nodes in a pipeline
"""
from .plot_metrics import plot_metrics
|
### Base class for Collage plugins ###
import math
import logging
import pygame
from plugin import Plugin
class Collage(Plugin):
"""
Base class for collage plugins
See simple_resize.py or recursive_split.py for example implementation of a plugin
"""
def __init__(self, config):
... |
# The code is based on code publicly available at
# https://github.com/rosinality/stylegan2-pytorch
# written by Seonghyeon Kim.
import math
import random
import torch
from torch import nn
from torch.nn import functional as F
from models.gan.stylegan2.op import FusedLeakyReLU
from models.gan.stylegan2.layers impor... |
import numpy as np
from scipy.special import erfc, erfcinv
def phi(input):
"""Phi function.
:param input:
Input value.
:returns:
Phi(input).
"""
return 0.5 * erfc(-input/np.sqrt(2))
def invphi(input):
"""Inverse of Phi function.
:param input:
Input value.
:... |
from .base_unit import BaseUnit
from ..utils import ListUtils
from .transport_event import TransportEvent
class LinkElement(BaseUnit):
def __init__(self):
BaseUnit.__init__(self)
self.sources = None
self.destinations = None
self.guards = None
self.accepts = None
... |
# Copyright (c) 2020 Sony 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
#
# Unless required by applicabl... |
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
map = dict()
map["2"] = ["a","b","c"]
map["3"] = ["d","e","f"]
map["4"] = ["g","h","i"]
map["5"] = ["j","k","l"]
map["6"] = ["m","n","o"]
map["7"] = ["p","q","r","s"]
map["8"] = ["... |
from .base import Base
from collections import Counter
class SizePerType(Base):
def fill(self):
request_size = self.__sum_request_size_per_type()
metrics = []
for key, value in request_size.items():
if key is None or key == "":
continue
metric = {
... |
# -*- coding: utf-8 -*-
import IPython
import os
def get_ipython_dir():
return IPython.paths.get_ipython_dir()
def list_profiles(project_path, project=None, show_project=True):
if os.path.isdir(project_path):
return [
('{}:{}'.format(x, project) if project and show_project else x)
... |
#Author: Maximilian Beckers, EMBL Heidelberg, Sachse Group (2018)
import numpy as np
import time
import argparse, os, sys
import mrcfile
import math
from FDRutil import *
#*************************************************************
#****************** Commandline input ************************
#********************... |
import pandas as pd
import numpy as np
from pandas_datareader import data as pdr
import yfinance
import datetime as dt
from sklearn import covariance
import seaborn as sns
import matplotlib.pyplot as plt
import networkx as nx
from pylab import rcParams
yfinance.pdr_override()
num_of_years = 10
start = dt.datetime.n... |
"""
©Pulzar 2018-20
#Author : Brian Turza
version: 0.4
#Created : 14/9/2019 (this version)
"""
from Lib.math.main import *
import numpy as np
import re
class Parser:
def __init__(self, token_stream, include):
self.tokens = token_stream
self.include = include
self.ast = {'main_scope': []}... |
import configparser
import pathlib
from . import cli
from .log import logger
_here = pathlib.Path(__file__).resolve().parent
_root = _here.parent
SAMPLE_CONFIG = '''\
[common]
# Instagram user handle.
username = instagram
# Data directory for database and downloaded media; can be overridden by more
# specific con... |
import pytest, fastai
from fastai.gen_doc.doctest import this_tests
def test_has_version():
this_tests('na')
assert fastai.__version__
|
"""
Setup of meshpy python codebase
Author: Jeff Mahler
"""
from setuptools import setup
requirements = [
'numpy',
'scipy',
'autolab_core',
'matplotlib',
'multiprocess',
'opencv-python',
'keras',
'cycler',
'Pillow',
'pyserial>=3.4',
'ipython==5.5.0',
'scikit-image',
... |
from flask import Flask
from flask import render_template
import csv
app = Flask(__name__)
def load_topics():
f_topics = open('data/topics_scores.csv', 'rb')
reader = csv.reader(f_topics,delimiter=",")
headers = reader.next()
topics = []
for row in reader:
topic = {}
topic["topic_id"] = row[headers.in... |
from typing import Dict, Any
import datetime as dt
from weather import arrange_data
class WeatherService:
@classmethod
def get_weather(cls) -> Dict[str, Any]:
return getAndParseData()
def getAndParseData():
forecast = arrange_data.arrange_data()
today = dt.datetime.now()
tomorrow = dt... |
import json
import os
import re
from django.http import HttpResponse
from django.views import View
class SandboxView(View):
def get(self, request, *args, **kwargs):
base_path = os.path.dirname(__file__)
get_fixture = lambda filename: open(
os.path.join(base_path, "sandbox-responses", ... |
#coding: utf8
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class serializableModel(db.Model):
__abstract__ = True
def as_dict(self, recursif=False):
if recursif :
return self.as_dict_withrelationships()
else :
return {c.name: getattr(self, c.name) for c in... |
#!/usr/bin/env python
import numpy as np
from itertools import product
from attacks.differential_evolution import differential_evolution
import cma
from attacks.base_attack import Attack
class OurAttack(Attack):
"""
TODO: Write Comment
"""
def __init__(self, args):
"""
TODO: Write ... |
import unittest
import io
from tokenizer.jsontokenizer import JsonTokenizer
from decoder.streamdecoder import JsonDecoder
class TestJsonDecoderMethods(unittest.TestCase):
def test_decode(self):
json = '{"name1": "value1", "name2": "value2"}'
result = list()
stream = io.StringIO(json)
... |
import os
from verify import expect
from click.testing import CliRunner
from pyhistory.cli import main
from . import (
load_fixture, get_fixture_content, get_test_file_content, isolated_workdir,
)
@isolated_workdir
def test_add_list_delete_and_clear():
open('HISTORY.rst', 'w').close()
result = _run(['l... |
'''
Copyright 2021 Flexera Software LLC
See LICENSE.TXT for full license text
SPDX-License-Identifier: MIT
Author : sgeary
Created On : Fri Dec 03 2021
File : upload_project_codebase.py
'''
import logging
import requests
logger = logging.getLogger(__name__)
#--------------------------------------------------
def ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-03-07 09:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('book', '0022_auto_20180307_1551'),
]
operations = [
migrations.AddField(
... |
# coding: utf-8
"""
Server API
Reference for Server API (REST/Json)
OpenAPI spec version: 1.4.58
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import sys
import os
import re
# python 2 and python 3 compatibility library
from six i... |
from PyQt5 import QtCore
from PyQt5.QtCore import QVariant
import sys
from packaging import version as version_mod
python_version = f'{str(sys.version_info.major)}.{str(sys.version_info.minor)}'
if version_mod.parse(python_version) >= version_mod.parse('3.8'): # from version 3.8 this feature is included in the
# ... |
### extends 'class_empty.py'
### block ClassImports
# NOTICE: Do not edit anything here, it is generated code
from . import gxapi_cy
from geosoft.gxapi import GXContext, float_ref, int_ref, str_ref
### endblock ClassImports
### block Header
# NOTICE: The code generator will not replace the code in this block
### end... |
# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 2 16:06:59 2019
@author: rainfall
"""
import settings
import numpy as np
import pandas as pd
import os, sys
import logging
from PRE_PROCESS_TRAINING.PCA import HelloFunction
class BRain:
'''
This is my custom rain classifier embeded wit... |
import json
import logging
from collections import defaultdict
from typing import Optional, Dict, List, Tuple
from model.jriver.common import get_channel_idx, user_channel_indexes
from model.jriver.filter import MixType, Mix, CompoundRoutingFilter, Filter, Gain, XOFilter
logger = logging.getLogger('jriver.routing')
... |
import meshio
mesh = meshio.read('I:\Program/Pix2Vox-master/voxel_log/voxel_process/gv_mha_000000_up.vtu')
mesh.write("I:\Program/Pix2Vox-master/voxel_log/voxel_process/gv_mha_000000_up.obj") |
from flask import Blueprint, jsonify, render_template, abort, request
import os
name = os.path.basename(os.path.dirname(os.path.realpath(__file__)))
maths = Blueprint(name, __name__, template_folder='templates')
import config
# Is value an int?
@maths.route('/is/int/<value>', methods=['GET'])
def is_int(value):
"... |
import os
from twisted.trial import unittest
from twisted.internet.defer import Deferred
from zope.interface.verify import verifyObject
from scrapyd.interfaces import IPoller
from scrapyd.config import Config
from scrapyd.poller import QueuePoller
from scrapyd.utils import get_spider_queues
from mock import Mock
c... |
from deepbgc.commands.base import BaseCommand
from deepbgc.converter import SequenceToPfamCSVConverter
class PfamCommand(BaseCommand):
command = 'pfam'
help = """Convert genomic BGCs sequence into a pfam domain CSV file by detecting proteins and pfam domains.
Examples:
# Detect proteins and pfam d... |
from .dataset_source import DatasetSource
from .dataset_writer import DatasetWriter
|
#!/usr/bin/env python3
import pytest
from report_generator.partner import sponsor
class TestSponsor:
@pytest.fixture(scope="class")
def sponsors(self):
return sponsor.get_all_sponsors("test/data/packages.yaml", "test/data/sponsors.yaml")
@pytest.fixture(scope="class")
def platinum_partner(se... |
# Generated by Django 3.0.5 on 2020-04-11 22:34
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='OitsParams',
fields=[
('id', mo... |
import numpy as np
class DynSys():
"""
The dynamical system class.
Author: Haimin Hu (haiminh@princeton.edu)
Reference: Ellipsoidal Toolbox (MATLAB) by Dr. Alex Kurzhanskiy.
Supports:
DTLTI: Discrete-time linear time-invariant system.
x[k+1] = A x[k] + B u[k] + c + G d[k]
DTLTV:... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import Float64MultiArray
import math
pub = rospy.Publisher('/adaptive_lighting/light_driver/pwm', Float64MultiArray, queue_size=10)
rospy.init_node('sin_test')
t = 0.0
intensity = 1.0;
rate = 200.0
r = rospy.Rate(rate)
while not rospy.is_shutdown():
msg = Floa... |
# =================================================================
#
# Authors: Tom Kralidis <tomkralidis@gmail.com>
#
# Copyright (c) 2018 Tom Kralidis
#
# 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 ... |
## Copyright (c) 2010, Coptix, Inc. All rights reserved.
## See the LICENSE file for license terms and warranty disclaimer.
"""prelude -- extra builtins"""
from __future__ import absolute_import
import os, __builtin__ as py, contextlib
import abc, functools as fn, logging, collections as coll, itertools as it
__all... |
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import... |
import sys
import os
from .constants import VERSION, DEFAULT_PROCESSES, CONFIG_FILE_NAMES, PROJECT_BOUNDARIES
from .backports import Backports
from .features import Features
from .config import Config
from .printing import nprint
from . import formats
class Arguments:
def __init__(self, args):
self.__args = arg... |
from . import util
from .vectors import VectorMap
def load(name=None, via=None):
package = util.get_package_by_name(name, via=via)
vector_map = VectorMap(128)
vector_map.load(package.path)
return vector_map
|
import cv2
import math
import pandas as pd
import numpy as np
import time, sys, os, shutil
import yaml
from multiprocessing import Process, Queue
from Queue import Empty
import random
import imageFeatures as imf
import pickle
from sklearn import gaussian_process
"""
# This script collects data
if len(sys.argv) < 2:
... |
from rest_framework import serializers
from core.models import Recipe, Ingredient
class IngredientSerializer(serializers.ModelSerializer):
class Meta:
model = Ingredient
fields = ("name",)
class RecipeSerializer(serializers.ModelSerializer):
ingredients = IngredientSerializer(many=True, requ... |
from rich import print
from rich.table import Table
from .ui import loading
from rich.console import Console
from .ui import Prompt
import time
class Mode():
def __init__(self, mode, about, theme):
self.mode = mode
self.about = about
self.theme = theme
self.products = ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 9 17:18:07 2018
@author: dawnstear
"""
import pandas as pd
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
#from plots import ecgplot
ecg = '/Users/dawnstear/desktop/PWC44/ecg.csv'
fnirs = '/Users/dawnstear/deskto... |
# interface to run psi4 from the embedded system.
# modified Psi4 need to be complied from source to read embedding potential
# compiled version can be found in /home/goodpast/shared/Xuelan/psi4.
# change made to psi4/psi4/src/psi4/libscf_solver/hf.cc to read embpot.dat.
# add the following PSI4 executable2 to your ~/.... |
"""A module consisting of various meshing functions."""
# ***********************************************************************
#
# FILE mesh.py
#
# AUTHOR Dr. Vishal Sharma
#
# VERSION 1.0.0-alpha4
#
# WEBSITE https://github.com/vxsharma-14/project-NAnPack
#
# NAnPack L... |
# coding: utf-8
from DataFormats import FWLite
def getGeantTrackIds(obj):
geantTracks = obj.g4Tracks()
return [t.trackId() for t in geantTracks]
def makeTPtoSCMap(trackingParticles, simClusters):
tp_map = {t.g4Tracks().at(0).trackId() : t for t in trackingParticles}
tp_map = {}
tp_sc_map = {}
... |
""" NOTES
- based on the awesome work by the fmriprep people
To do
- add cosine basis set
- add WM and global signal (global signal cf. power 2016, GSSCOR)
"""
import nipype.pipeline as pe
from nipype.interfaces.io import DataSink
from nipype.interfaces.utility import IdentityInterface, Merge, Rename
from nipype.algo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 15 10:36:47 2018
Generate the summary file for one clade of below:
Fungi, Prokaryote, All unclassified Eukaryote, Viruses, Metazoa (animal), Viridiplantae (Plant)
Two files will be generated:
ncbi_[clade]_gtdb_taxonomy.txt
ncbi_[cla... |
#!/usr/bin/python3
"""
Script to parse Intersight HAR files
Returns:
HTTP Method
X-Startship-Token
URL
"""
import json
filename = input("Please enter the HAR Filename: ")
with open(filename, "r") as f:
har_data = f.read()
json_data = json.loads(har_data)
for entry in json_data["log"]["entries"... |
from ..Model.Player.Player import Player
from ..Model.Board.Board import Board
class GameController:
def __init__(self, debug=False):
self.board = Board()
self.red = Player(True, self.board, debug)
self.black = Player(False, self.board, debug)
self.redNext = True
self.debug ... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import warnings
from tonnikala.languages.base import LanguageNode, ComplexNode, BaseGenerator
from slimit.parser import Parser
from slimit import ast
from slimit.ast import *
from collections import... |
# -*- coding: utf-8 -*-
'''
Manage the master configuration file
'''
from __future__ import absolute_import
# Import python libs
import logging
import os
# Import third party libs
import yaml
# Import salt libs
import salt.config
log = logging.getLogger(__name__)
def values():
'''
Return the raw values of... |
# -*- coding: utf-8 -*-
# Reference VOC scrips
# Author : Andy Liu
# last modify : 2020-08-15
# input : python count_classes_by_xml.py "/home/andy/data/xml"
import xml.dom.minidom
import random
import pickle
import os
import sys
import cv2
import argparse
from os import listdir, getcwd
from os.path import join
from t... |
from distutils.core import setup, Extension
import numpy
setup(name='pafprocess_ext', version='1.0',
ext_modules=[Extension('_pafprocess', ['pafprocess.cpp', 'pafprocess.i'], swig_opts=['-c++'],
depends=["pafprocess.h"], include_dirs=[numpy.get_include(), '.'])],
py_modules=["p... |
import time
import random
# global variable to store list of all available algorithms
algorithm_list = ["dfs_backtrack", "bin_tree"]
def depth_first_recursive_backtracker(maze, start_coor):
k_curr, l_curr = start_coor # Where to start generating
path = [(k_curr, l_curr)] # To track path of solution
maz... |
""" solution to the josephus problem """
def safe_position(n):
"""
function to get the safe position
formulae
Initial(n) = 2^a +l
W(n) = 2l + 1;
where n = the total number
a = the power of two
l = the reminder after the power is deducted from n
"""
pow_two = 0
i = 0
while (n - pow_two) ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 15 20:55:19 2016
@author: ajaver
"""
import json
import os
from collections import OrderedDict
import zipfile
import numpy as np
import pandas as pd
import tables
from tierpsy.helper.misc import print_flush
from tierpsy.analysis.feat_create.obtainFeaturesHelper import ... |
from django import forms
from django.contrib.auth.models import User
from .models import Profile, Posts, Business, Area
class EditProfileForm(forms.ModelForm):
class Meta:
model = Profile
exclude = ('user', 'location')
class AreaForm(forms.ModelForm):
class Meta:
model = Area
exclud... |
# Excel Column Number
# https://www.interviewbit.com/problems/excel-column-number/
#
# Given a column title as appears in an Excel sheet, return its corresponding
# column number.
#
# Example:
#
# A -> 1
#
# B -> 2
#
# C -> 3
#
# ...
#
# Z -> 26
#
# AA -> 27
#
# AB -> 28
#
# # # # # # # # # # # # # # # # # # # # # # # ... |
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
--- Nokia 1830 PSS SWDM Performance Collection Tool
--- Created by Naseredin aramnejad
--- Tested on Python 3.7.x
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
#___________________________________IMPORTS_____________________________________
imp... |
import torch
import dgl.function as fn
import torch.nn as nn
from graphgallery.nn.layers.pytorch import activations
def drop_node(feats, drop_rate, training):
n = feats.shape[0]
drop_rates = torch.ones(n) * drop_rate
if training:
masks = torch.bernoulli(1. - drop_rates).unsqueeze(1)
f... |
# WARNING: Do not edit by hand, this file was generated by Crank:
#
# https://github.com/gocardless/crank
#
import json
import requests
import responses
from nose.tools import (
assert_equal,
assert_is_instance,
assert_is_none,
assert_is_not_none,
assert_not_equal,
assert_raises
)
from gocardless_pro.e... |
import numpy as np
import Python.density_matrix as DM
import scipy.sparse as sp
import matplotlib.pyplot as plt
from measurements import temps
for i in range(100):
print(i)
pops = [.1, .1, .4]
therm2 = DM.n_thermal_qbits(pops)
therm2.change_to_energy_basis()
temps(therm2)
# print(therm2.ptrace([... |
import os
from app.app import create_app
from app import jwt
flask_config = os.getenv("FLASK_CONFIG")
app_host = os.getenv("HOST")
app_port = os.getenv("PORT")
user = os.getenv("DB_USER")
passwd = os.getenv("DB_PASSWORD")
host = os.getenv("DB_HOST")
database = os.getenv("DB_DATABASE")
db_uri = "mysql+pymysql://{}:{}@... |
# -*- coding: utf-8 -*-
import unittest
from openprocurement.auctions.core.tests.question import AuctionQuestionResourceTestMixin
from openprocurement.auctions.tessel.tests.base import BaseInsiderAuctionWebTest
class InsiderAuctionQuestionResourceTest(BaseInsiderAuctionWebTest, AuctionQuestionResourceTestMixin):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.