content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from setuptools import setup
with open("README.md") as f:
readme = f.read()
with open("LICENSE") as f:
license = f.read()
setup(
name="PERFORM",
version=0.1,
author="Christopher R. Wentland",
author_email="chriswen@umich.edu",
url="https://github.com/cwentland0/pyGEMS_1D",
description... | python |
class ProxyError(StandardError):
def __init__(self, title, message):
super(ProxyError, self).__init__()
self.title = title
self.message = message
self.error = "Error"
def __str__(self):
return "%s => %s:%s" % (self.error, self.title, self.message)
class ResourceError(... | python |
__author__ = 'wanghao'
# import threading
import sys
import socket
from struct import *
import time
import threading
def run_flow(dst_ip, port, size):
def run(dst_ip, port, size):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# data = os.urandom(size)
data = pack('c', 'a')
... | python |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torch
import os
# Implementing relu()
def relu(z):
if z > 0:
return z
else:
retur... | python |
'''
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
'''
# Write your code here
def right(a,b):
r=a
for... | python |
import mykde
"""
If a font in the browser is not Droid, in Google Chrome right click on the text
with the wrong font, select 'Inspect element', find 'Computed style' and
'font-family' in it:
font-family: 'lucida grande', tahoma, verdana, arial, sans-serif;
And for each font do 'fc=match':
$ fc-match Helvetica
Liber... | python |
# -*- coding: utf-8 -*-
"""
Created on Thu May 25 11:25:36 2017
@author: azkei
We Briefly covered operations between two data structures last file.
We will cover how arithmetic operators apply between two or more structured here
using Flexible Arithmetic Methods such as
add(), sub(),div(),mul()
"""
# 1. Flexible Arith... | python |
from django.utils import timezone
import pytz
class TimeZoneMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
tzname = request.session.get("time_zone")
if tzname:
timezone.activate(pytz.timezone(tzname))
el... | python |
from podcast.views import home_page
from django.urls import path
from . import views
app_name = "podcast"
urlpatterns = [
path('', views.home_page, name="home-page"),
path('podcast/',views.podcast_list, name="podcast-list"),
path('podcast/search/',views.search_podcast, name="podcast-search"),
path('po... | python |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2019 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Pytest configuration."""
from __future__ import absolute_import, print_function
... | python |
import requests
from bs4 import BeautifulSoup
from .handler import add_handler
@add_handler(r'http(s?)://drops.dagstuhl.de/(\w+)')
def download(url):
metadata = dict()
metadata['importer'] = 'drops'
data = requests.get(url)
soup = BeautifulSoup(data.text, "lxml")
authortags = soup.find_all("meta"... | python |
# reference page
# https://iric-solver-dev-manual-jp.readthedocs.io/ja/latest/06/03_reference.html
import sys
import iric
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import LightSource
from scipy import signal, interpolate
import flow
class cgns():
def __in... | python |
from django.urls import path
from . import views
urlpatterns = [
path('',views.index, name='homePage'),
path('profile/<username>/', views.profile, name='profile'),
path('profile/<username>/update', views.edit_profile, name='update'),
path('category/<category>/', views.category, name='category'),
pa... | python |
"""
Leetcode #300
"""
from typing import List
import bisect
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
inc = [float("inf")] * len(nums)
size = 0
for num in nums:
i = bisect.bisect_left(inc, num)
inc[i] = num
size = max(i+1, siz... | python |
import random
from multiprocessing import Pool
from gym_puyopuyo.agent import tree_search_actions
from gym_puyopuyo.state import State
def benchmark(depth, threshold, factor):
state = State(16, 8, 5, 3, tsu_rules=False)
total_reward = 0
for i in range(1000):
if i % 100 == 0:
print(i, ... | python |
import json
import csv
import sys
from pathlib import Path
import datetime
import pytest
import networkx as nx
from sb.aws_trace_analyzer import CSV_FIELDS, extract_trace_breakdown, longest_path, create_span_graph, duration, get_sorted_children, is_async_call, call_stack # noqa: E501
def test_get_sorted_children():... | python |
# -*- coding: utf-8 -*-
import math
import numpy as np
import numpy.random as npr
import cv2
# from matplotlib.colors import rgb_to_hsv
# from matplotlib.colors import hsv_to_rgb
from configure import cfg
import utils.blob
# from caffe.io import resize_image
def GenerateBatchSamples(roi, img_shape):
sampled_bbo... | python |
from django.urls import path
from .views import ResultListView, create_result, edit_results
urlpatterns = [
path("create/", create_result, name="create-result"),
path("edit-results/", edit_results, name="edit-results"),
path("view/all", ResultListView.as_view(), name="view-results"),
]
| python |
"""
Class for manipulating user information.
"""
from datetime import date, timedelta
from functools import total_ordering
from logging import getLogger
from os import stat
from os.path import exists
from re import compile as re_compile
from stat import (S_IMODE, S_ISDIR, S_ISREG)
from typing import (
Any, Collecti... | python |
import os
import setuptools
with open("README.md") as f:
long_description = f.read()
with open(
os.path.join(os.path.dirname(__file__), "config", "requirements", "base.txt")
) as f:
requirements = [i.strip() for i in f]
setuptools.setup(
name="rembrain_robot_framework",
version="0.1.4",
auth... | python |
#coding:utf-8
from flask import Flask, redirect, url_for, request
from datetime import datetime
from flask_bootstrap import Bootstrap
from app.config_default import Config as DefaultConfig
bootstrap = Bootstrap()
def check_start(app, db):
from app.includes.start import _exist_config, exist_table, create_path, se... | python |
"""
Generate_branched_alkane
========================
"""
from rdkit import Chem
import numpy as np
import random
def generate_branched_alkane(num_atoms: int, save: bool=False) -> Chem.Mol:
"""Generates a branched alkane.
Parameters
----------
num_atoms : int
Number of atoms in molecule to be ... | python |
from django.core.exceptions import ValidationError
from django.test import TestCase
from openwisp_users.models import OrganizationUser, User
from .utils import TestOrganizationMixin
class TestUsers(TestOrganizationMixin, TestCase):
user_model = User
def test_create_superuser_email(self):
user = User... | python |
from tensorflow_functions import cosine_knn
import collections
import numpy as np
import logging
from embedding import load_embedding
import operator
from sklearn.cluster import KMeans
from utils import length_normalize, normalize_questions, normalize_vector, calculate_cosine_simil, perf_measure
import sklearn.metrics
... | python |
from Impromptu import * | python |
import pytch
from pytch import (
Sprite,
Stage,
Project,
when_green_flag_clicked,
when_this_sprite_clicked,
)
import random
# Click the balloons to pop them and score points
class BalloonStage(Stage):
Backdrops = [('midnightblue', 'library/images/stage/solid-midnightblue.png')]
# TODO: ... | python |
from environment import environment as env
class syscalls:
"""This class holds a framework for system calls and should ultimately depend on an
architecture template I think. For now, it's basically a function map to allow
programming system calls like you really would.
"""
def __init__(self):
... | python |
from astute.__main__ import main
from astute.__main__ import Icon
if __name__ == '__main__':
main(icon=Icon('astute/astute.ico'))
| python |
# *ex2 - Escreve um programa com laço de repetição para o usuario encerra-lo apenas quando desejar, onde seu objetivo será fornecer a nota musical, bem como sua frequencia. bom base na tecla fornecida pelo usuario
from os import system
from time import sleep
from cores import *
def sair():
print(f'\t\t{cor["ve... | python |
# coding: utf-8
# libraries import
import json
from flask import Flask, render_template, redirect, url_for, request, jsonify, flash
from flask_zurb_foundation import Foundation
from sqlalchemy_wrapper import SQLAlchemy
app = Flask(__name__)
# Configuration
app.config["DEBUG"] = True
from models import RandomData,... | python |
class Solution(object):
def match_note_to_magazine(self, ransom_note, magazine):
if ransom_note is None or magazine is None:
raise TypeError('ransom_note or magazine cannot be None')
seen_chars = {}
for char in magazine:
if char in seen_chars:
seen_ch... | python |
# File : text.py
# Author : Zhengkun Tian
# Email : zhengkun.tian@outlook.com
import torch
import logging
from otrans.data import *
from torch.utils.data import Dataset
class TextDataset(Dataset):
def __init__(self, params, datadict, is_eval=False):
self.params = params
self.is_eval = is_eva... | python |
"""Custom test and setup properties for checkin pull_info provider."""
load("//container:providers.bzl", "PullInfo")
def _pull_info_validation_test_impl(ctx):
pull_info = ctx.attr.target[PullInfo]
compare_script_file = ctx.actions.declare_file("compare.sh")
compare_script = """#!/usr/bin/env bash
function... | python |
# Converting the main code to use datetime objects as well instead of just time objects
# Took out defaults from the iter functions
import time, math
from datetime import datetime
from models.energy import defaultModel, load_data, GPSCoordinate#, powerConsumption
from models.Predictor import powerGeneration
# function ... | python |
#!/usr/bin/env python3
#ccc 2021 senior 10/15
from sys import stdin
from itertools import repeat
m = int(stdin.readline())
n = int(stdin.readline())
k = int(stdin.readline())
canvas = []
for _ in range(m):
canvas.append(list(repeat(False,n)))
gold = 0
for _ in range(k):
query = stdin.readline().split()
qu... | python |
import requests
import json
from . import filler, models
VALID_HTTP_METHODS = {
'GET': ['url'],
'PATCH': ['url', 'data'],
'PUT': ['url', 'data'],
'POST': ['url', 'data'],
'DELETE': ['url'],
}
def call(step, responses, config: models.SuiteConfig):
"""
Main API Caller
... | python |
'''
Created on 1.12.2016
@author: Darren
''''''
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
Examples:
[2,3,4] , the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5
Design a d... | python |
from tkinter import *
import sys
import os.path
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from search import *
import numpy as np
distances = {}
class TSP_problem(Problem):
""" subclass of Problem to define various functions """
def two_opt(self, state):
""" Neighbour generatin... | python |
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
import matplotlib.animation as animation
from matplotlib.text import OffsetFrom
import numpy as np
import csv
a = []
b = []
with open('curvatest.csv','r') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
for row in plots:
a.ap... | python |
#!/usr/bin/env python
import argparse
parser = argparse.ArgumentParser(description='Gossip Chat via GPT2')
parser.add_argument('-m', '--model', dest="model", help="pretrained model path")
parser.add_argument('-c', '--config', dest="config", help="model config path")
parser.add_argument('-p', '--port', dest='port', def... | python |
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
from .models import Employee
from django.forms import ModelForm, fields
from .models import Order
from .models import Customer
from .models import Tag
from .models import Product
... | python |
from django.http import HttpResponse
from django.shortcuts import reverse
from django.views import View
class HeavenTestAPIView(View):
def get(self, request):
link_format = "<a href='{reversed_link}'>{link}</a>"
example_urls = [link_format.format(reversed_link=reverse(link), link=link) for link i... | python |
"""
@author: Gabriele Girelli
@contact: gigi.ga90@gmail.com
"""
import argparse
from fastx_barber import scriptio
from fastx_barber.const import PATTERN_EXAMPLE, FlagData
from fastx_barber.exception import enable_rich_assert
from fastx_barber.flag import (
FastqFlagExtractor,
FlagStats,
get_fastx_flag_extr... | python |
"""
Minimal and functional version of CPython's argparse module.
"""
import sys
try:
from ucollections import namedtuple
except ImportError:
from collections import namedtuple
class _ArgError(BaseException):
pass
class _Arg:
def __init__(self, names, dest, metavar, arg_type, action, nargs, const, d... | python |
import json
from hashlib import sha256
from typing import List
from ..configs import BaseLayerConfig
def create_dir_name_from_config(config: BaseLayerConfig, prefix: str = "") -> str:
config_class_name = config.__class__.__name__
config_json = json.dumps(config.to_dict_without_cache())
return f"{prefix}{... | python |
#!/usr/bin/env python3
# @Time : 27/6/29 2:46 PM
# @Author : fangcheng.ji
# @FileName: qfl_atss.py
import math
import torch
import torch.nn.functional as F
from torch import nn
import os
from typing import Dict, List
from .fcos import Scale
from detectron2.modeling.proposal_generator.build import PROPOSAL_GENERAT... | python |
# -*- coding: utf-8 -*-
# Copyright 2020 The Matrix.org Foundation C.I.C.
#
# 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 require... | python |
#pragma repy
# This test tries to do recvmess / stopcomm in a loop
def foo(ip,port,mess, ch):
print ip,port,mess,ch
if callfunc == 'initialize':
for x in xrange(0,10):
ch = recvmess(getmyip(),<messport>,foo)
sleep(.1)
stopcomm(ch)
sleep(.1)
| python |
import os
from datetime import timedelta
class Config(object):
DEBUG = False
AUTHENTICATED_SEARCH_API = os.environ['AUTHENTICATED_SEARCH_API']
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
CASES_URL = os.environ['CASES_URL']
MATCHING_URL = os.environ['MATCHING_URL']
OWNERSHIP_URL = os.en... | python |
import gym
import random
import tensorflow
import numpy as np
from collections import deque
import matplotlib.pyplot as plt
import utils.utils as utils
import tensorflow as tf
from ddpg_tf import DDPG
env = gym.make('BipedalWalker-v2')
env.seed(0)
sess = tf.Session()
agent = DDPG('ddpg', utils.load_args(), sess=sess)... | python |
from factory import robot
import rospy
from std_msgs.msg import Float64
from std_msgs.msg import Bool
from geometry_msgs.msg import Point
import time as t
import math as m
t0=t.time()
Robot=None
class rosact(object):
def __init__(self):
rospy.init_node('act')
self.pubs=[]
self.pubs.append(... | python |
import time
from os import path
from collections import defaultdict
import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from ... | python |
import pandas as pd
import matplotlib.pyplot as plt
import math
class Frame():
def __init__(self, path_):
self.path = path_
self.data =pd.read_csv(filepath_or_buffer=path_, delimiter=',')
def clean(self, subs:bool):
Ncol = len( self.data.columns )
self.data.dropna(inplace=Tru... | python |
# 본 Code에서 사용할 tensorflow, matplotlib.pyplot, nupmy, random을 import한다.
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import random
# MNIST data를 불러오고 이를 one_hot encoding합니다.
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./mnist/data/", one_ho... | python |
def kw_only_args(*, kwo):
pass
def kw_only_args_with_varargs(*varargs, kwo, another='default'):
pass
| python |
# Copyright 2017 NTRLab
#
# 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, softw... | python |
import logging
from logging.config import dictConfig
def setup(conf):
dictConfig(conf)
class LoggerMixIn:
def __init__(self, *args, **kwargs):
logger_name = getattr(self, "__logger_name__", self.__class__.__name__)
self.logger = logging.getLogger(logger_name)
for lvl in ["CRITICAL"... | python |
# Copyright © 2019 Province of British Columbia
#
# 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 agr... | python |
from . import location
| python |
import os
import sys
import time
import machine
import badger2040
from badger2040 import WIDTH, HEIGHT
REAMDE = """
Images must be 296x128 pixel with 1bit colour depth.
You can use examples/badger2040/image_converter/convert.py to convert them:
python3 convert.py --binary --resize image_file_1.png image_file_2.png ... | python |
import requests
from requests_oauthlib import OAuth1
import json
reload(sys)
sys.setdefaultencoding("utf-8")
params = {'app_key': 'xx',
'app_secret': 'xx',
'access_token': 'xx-xx',
'access_secret': 'xx'}
auth = OAuth1(params['app_key'],
params['app_secret'],
... | python |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from ....Functions.init_fig import init_fig
def plot(
self,
fig=None,
ax=None,
sym=1,
alpha=0,
delta=0,
is_edge_only=False,
comp_machine=None,
is_show_fig=True,
save_path=None,
win_title=None,
):
"""Plot the Machin... | python |
from core.Model import *
from core.Utils import Utils
from models.User import User
from models.AppVersion import AppVersion
class Device(Base, Model):
__tablename__ = "device"
id = Column(BigInteger, primary_key=True, autoincrement=True)
uuid = Column(String(300), nullable=False)
user_id = Column(Int... | python |
from .BaseCamera import BaseCamera
import numpy as np
import math
class PersPectiveCamera(BaseCamera):
def __init__(self):
BaseCamera.__init__(self, "PerspectiveCamera")
def get_projection_mat(self):
# http://www.songho.ca/opengl/gl_projectionmatrix.html
projection_mat = np.eye(4)
... | python |
"""
django admin pages for program support models
"""
from config_models.admin import ConfigurationModelAdmin
from django.contrib import admin
from openedx.core.djangoapps.programs.models import ProgramsApiConfig
class ProgramsApiConfigAdmin(ConfigurationModelAdmin):
pass
admin.site.register(ProgramsApiConfi... | python |
import pandas
def find_na(df):
print(pd.isna(df).sum())
| python |
#!/usr/bin/env python3
import pyglet
import glooey
import run_demos
window = pyglet.window.Window()
gui = glooey.Gui(window)
bin = glooey.Bin()
widget = glooey.Placeholder(100, 100)
bin.add(widget)
gui.add(bin)
@run_demos.on_space(gui)
def test_bin():
bin.add(widget)
yield "Put a widget in the bin."
bi... | python |
# -*- coding:utf-8 -*-
import os
import random
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sentencepiece as spm
import tensorflow as tf
import tensorflow.keras.backend as K
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
random_seed = 1234
random.seed(random_seed)
np.random.seed(random_see... | python |
#!/usr/bin/python
import simple_test
simple_test.test("test9", ["-VVV", "-N", "--noise", "-rr", ], expect_fail=True)
| python |
import minpy
import minpy.numpy as np
import minpy.numpy.random as random
from minpy.core import grad_and_loss
# from examples.utils.data_utils import gaussian_cluster_generator as make_data
# from minpy.context import set_context, gpu
# Please uncomment following if you have GPU-enabled MXNet installed.
# This single... | python |
from .pytorch_sampler import PyTorchSampler
from .sampler import Sampler
from .unigram import UnigramDistribution
from .vocab import Vocabulary
| python |
import json
import os
import tempfile
from datetime import datetime, timedelta
from enum import Enum
from itertools import zip_longest, groupby
from threading import Timer
from typing import Any, List, Optional, Dict, Iterable, Tuple, Set
import sentry_sdk
from telegram import ParseMode, TelegramError, Update, Message... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
#
# Licensed under the GNU General Public License, version 3 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://jxs... | python |
#
# Copyright (c) 2017-2018 Joy Diamond. All rights reserved.
#
__import__('Boot').boot()
def line(format, *args):
print format % args
def main():
if 0:
from Pattern import make_match_function
joy_match = make_match_function('[Aa](m)i(?P<what>t)\Z')
else:
import _sre
... | python |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 20 15:12:49 2016
@author: uzivatel
"""
import numpy as np
import scipy
from functools import partial
from copy import deepcopy
from .general import Coordinate,Grid
from ...General.UnitsManager import PositionUnitsManaged,position_units
from ...General.types ... | python |
from unittest import TestCase
from unittest.mock import patch
import getting_logs
class TestGetLog(TestCase):
"""Testing of getting logs from a third-party resource.
Testing the correctness of the transmitted data
for saving to the database."""
@classmethod
def setUpClass(cls):
super().s... | python |
# coding: utf8
import requests
import json
import os
import time
import pymysql.cursors
connection = pymysql.connect(host='127.0.0.1', port=3306, user='ub', password='UB@018_world_cup', db='db_world_cup',
charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
g_stake_addre... | python |
from .bar import f
| python |
from django.contrib.auth.models import User
from django_grpc_framework import proto_serializers
import account_pb2
class UserProtoSerializer(proto_serializers.ModelProtoSerializer):
class Meta:
model = User
proto_class = account_pb2.User
fields = ['id', 'username', 'email', 'groups']
| python |
from minecraftmath import calculator
from system import window_management as wm
xFirThr = 0
zFirThr = 0
angleFirThr = 0
def findSecondSuggestedThrow(startPosX, startPosZ, startAngle):
global xFirThr, zFirThr, angleFirThr
xFirThr = startPosX
zFirThr = startPosZ
angleFirThr = startAngle
inRing, dist... | python |
"""The builtin object type implementation"""
from pypy.interpreter.baseobjspace import W_Root
from pypy.interpreter.error import OperationError, oefmt
from pypy.interpreter.gateway import applevel, interp2app, unwrap_spec
from pypy.interpreter.typedef import (
GetSetProperty, TypeDef, default_identity_hash)
from p... | python |
import collections
from sgfs import SGFS
ReferenceStatus = collections.namedtuple('ReferenceStatus', ('path', 'used', 'latest', 'is_latest', 'all'))
def check_paths(paths, only_published=True):
sgfs = SGFS()
res = []
for path in paths:
publishes = sgfs.entities_from_path(path... | python |
'''
Written by Jason Reaves - @sysopfb
Free to use, attribute properly.
'''
import sys
import pefile
import struct
import re
def decrypt(keystream, blob):
for i in range(len(blob)):
blob[i] ^= keystream[i%len(keystream)]
def rc4_crypt(data, sbox):
S = list(sbox)
out = []
i = j = 0
for char in data:
i = ( ... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__title__ = 'baidupcsapi'
__version__ = '0.2.12'
__author__ = 'mozillazg,latyas'
__license__ = 'MIT'
from .api import PCS | python |
import inspect
class SuperMixin(object):
def super(cls, *args, **kwargs):
frame = inspect.currentframe(1)
self = frame.f_locals['self']
methodName = frame.f_code.co_name
method = getattr(super(cls, self), methodName, None)
if inspect.ismethod(method):
return metho... | python |
#Includes BaseClassApi class
import BaseClassApi
class Augmentor(BaseClassApi.Api):
pass
#print "This is augmentor api class: \n"
def execute_augmentor_api():
BaseClassApi.Api.url_path = "api/v1/augmentors"
aug_api = Augmentor()
#This module gives list of organizations available.
... | python |
from ..abstract import ErdReadOnlyConverter
from ..primitives import *
from gehomesdk.erd.values.oven import OvenConfiguration, ErdOvenConfiguration
class OvenConfigurationConverter(ErdReadOnlyConverter[OvenConfiguration]):
def erd_decode(self, value: str) -> OvenConfiguration:
if not value:
n ... | python |
from __future__ import unicode_literals
import datetime
from django.http import Http404
from django.utils.timezone import utc
from model_mommy import mommy
from kb.tests.test import ViewTestCase
from kb.models import Article
class TestCategoryFeed(ViewTestCase):
view_name = 'kb:category_feed'
view_kwargs ... | python |
"""
test_ext_autodoc_configs
~~~~~~~~~~~~~~~~~~~~~~~~
Test the autodoc extension. This tests mainly for config variables
:copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import platform
import sys
import pytest
from sphinx.testing imp... | python |
from collections import Counter
def mejority(lst):
freDict = Counter(lst)
size = len(lst)
for key, value in freDict.items():
if value > (size//2):
print(key)
return
print("None")
if __name__ == "__main__":
lst = [3, 3, 4, 2, 4, 4, 2, 2,2,2,2]
mejority(lst)
| python |
import pytest
import pathlib
from align.cell_fabric import Canvas, Pdk, Wire
mydir = pathlib.Path(__file__).resolve().parent
pdkfile = mydir.parent.parent / 'pdks' / 'FinFET14nm_Mock_PDK' / 'layers.json'
@pytest.fixture
def setup():
p = Pdk().load(pdkfile)
c = Canvas(p)
c.addGen( Wire( nm='m2', layer='M2... | python |
# -*- coding: utf-8 -*-
"""
Script Name: PipelineTool.py
Author: Do Trinh/Jimmy - 3D artist.
Description:
This is main UI of PipelineTool.
"""
# -------------------------------------------------------------------------------------------------------------
""" Import """
# PLM
from PLM ... | python |
from pyiced import (
column, css_color, IcedApp, Length, radio, Settings, text,
WindowSettings,
)
class RadioExample(IcedApp):
class settings(Settings):
class window(WindowSettings):
size = (640, 320)
def __init__(self):
self.__season = None
def title(self):
r... | python |
# Copyright (C) 2021 ServiceNow, Inc.
""" Combine output datasets from different source datasets
e.g. If you have generated training datasets for dataset A and dataset B
you can combine them into A+B using this script
It will *not* overwrite existing files (an error will be thrown).
Input files must ... | python |
import logging, queue
from datetime import datetime
import threading
from time import strftime
from .scanner_thread import ScannerThread
from scapy.all import *
class PyScanner:
def __init__(self, params_names={"-threads":5, "-ip": "127.0.0.1", "-ports":"0-100", "-scan_type": "S"}):
# print("ok")
#... | python |
def som(n):
if len(n) == 1: return n
s = 0
for i in range(len(n)):
s += int(n[i])
return som(str(s))
while True:
e = str(input()).split()
a = e[0]
b = e[1]
if a == b == '0': break
ta = som(a)
tb = som(b)
if ta > tb: print(1)
elif ta < tb: print(2)
else: prin... | python |
# Generated by Django 2.0.4 on 2018-12-13 12:38
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('tradukoj', '0007_bcp47_default'),
]
operations = [
migrations.CreateModel(
name='GetTextFile',
... | python |
import shutil
from pathlib import Path
import hydra
import matplotlib.pyplot as plt
import numpy as np
import torch
from hydra.utils import to_absolute_path
from omegaconf import OmegaConf
from torch import nn, optim
from torch.utils import data as data_utils
from torch.utils.tensorboard import SummaryWriter
from ttsl... | python |
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed... | python |
from flask import flash
def Euclidean_Algorithm(number_x, number_y):
try:
x, y = int(number_x), int(number_y)
r = x % y
while r > 0:
x = y
y = r
r = x % y
else:
gcd = y
anser = str(number_x)+"と"+str(number_y)+"の最大公約数は"+str(gc... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.