content stringlengths 5 1.05M |
|---|
"""
constants
"""
ACTION_SELECT = 0
ACTION_MOVE_SELECTED = 1
ACTION_RECT = 20
ACTION_ELLIPSE = 21
ACTION_ARROW = 22
ACTION_LINE = 23
ACTION_FREEPEN = 24
ACTION_TEXT = 25
ACTION_UNDO = 26
ACTION_SAVE = 27
ACTION_CANCEL = 28
ACTION_SURE = 29
DRAW_ACTION = [ACTION_RECT, ACTION_ELLIPSE, ACTION_ARROW, ACTION_LINE, ACTION_... |
import requests
# parameters : faceListId, userData,
userName = "user"
faceListId = "aperture_" + userName
keyfile = open("./key.txt")
key = keyfile.readline()
headers = {
# Request headers
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': key,
}
body = {
'url' : 'h... |
""" Eyes blinking detector """
import numpy as np
from util import coeffbandpass_filter, filtfilt, peaks_detection
class EyesBlinkDetector:
def __init__(self):
# channels
self.chl_hl = 13 # horizontal left
self.chl_hr = 5 # horizontal right
self.chl_vl = 0 # v... |
# -*- encoding: utf-8 -*-
"""
Dimensions – Preparation
========================
This script prepares the structures for the module 'Dimensions'. You don't
necessarily have to understand it at this point.
Warning: this script is destructive – rebuilds all structures that are being
used by this module.
"""
import sqla... |
# Author: Qinghui Liu @ USN 2017-04-25
# For master thesis project
# Data input generation and model histories plot function
# Score mean merge function
# Create CSV for kaggle submission
# Need to reflect and refine the source code in future
import os
import numpy as np
import cv2
import matplotlib.pyplot as ... |
from day09.script1 import parse, Program
def solve(memory):
program = Program(memory, [2])
program.run()
return program.outputs
if __name__ == '__main__':
print(solve(parse("data.txt")))
|
# -*- coding: utf-8 -*-
try:
# Python 2.6
import unittest2 as unittest
except ImportError:
# Python >= 2.7
import unittest
class BaseTestCase(unittest.TestCase):
def test_can_wrap_jac(self):
from flask_static_compress import FlaskStaticCompress
self.assertIsNotNone(FlaskStaticCo... |
import json
import socket
import logging
from mythril.rpc.base_client import BaseClient
from .utils import (get_default_ipc_path, to_text, to_bytes)
import threading
try:
from json import JSONDecodeError
except ImportError:
JSONDecodeError = ValueError
IPC_PATH = None
'''
This code is mostly adapted from:
- ... |
from pygame import Rect
from random import random
from random import randint
import math
color_sets = {
"red": [
(255, 0, 0)
],
"green": [
(0, 255, 0)
],
"blue": [
(0, 0, 255)
],
"ice": [
(0, 0, 255),
(255, 255, 255),
(50, 50, 255)
],
... |
from random import sample
numbers = sample(range(1,101),100)
print(numbers)
def find_indices_total(l,start,stop):
# your code here
total = sum(l[start:stop])
return total
total = find_indices_total(numbers,0,3)
print(total) |
import copy
import numpy as np
import torch
from torchvision import datasets, transforms
from sklearn.metrics import roc_curve, auc
from src.utils import DatafeedImage
def load_corrupted_dataset(dname, severity, data_dir='../../data', batch_size=256, cuda=True, workers=4):
assert dname in ['CIFAR10', 'CIFAR100'... |
import json
from schema import And, Use, Schema
def is_json_serializable(data):
if data is None:
return True
try:
json.dumps(data)
return True
except Exception:
return False
doc_schema = Schema({
'method': And(Use(str)),
'data': And(Use(is_json_serializable)),
... |
# encoding=utf-8
"""
@author huxujun
@date 2019-05-24
"""
import os
def get_build_dir() -> str:
build_dir = os.path.join(os.getenv('JENKINS_HOME'), 'jobs', os.getenv('JOB_NAME').replace('/', '/branches/'),
'builds',
os.getenv('BUILD_NUMBER'))
if not os... |
"""Testing that the plugin for wepy tests actually works."""
import pytest
fixtures = [
'lj_sanity_test',
]
def test_lj_plugin(
lj_sanity_test,
):
# sanity test to make sure its even on the path
assert lj_sanity_test == "sanity"
@pytest.mark.usefixtures(*fixtures)
class TestP... |
"""
Demonstrates the use of the ASE library to load and create atomic
configurations that can be used in the describe package.
"""
import os
os.chdir('..')
import ase.io
from describe.descriptors import MBTR
from describe.descriptors import CoulombMatrix
from describe.descriptors import SineMatrix
from describe.util... |
# Statuses a task can be in.
WAITING = 0
SUCCESS = 1
FAILED = 2
DELAYED = 3
RETRYING = 4
CANCELED = 5
# The default queue name for Alligator.
ALL = "all"
|
import requests
def get_accesstoken(client_id, client_secret, code, redirect_uri):
url = "https://account.health.nokia.com/oauth2/token"
payload = {
"grant_type": "authorization_code",
"client_id": client_id,
"client_secret": client_secret,
"code... |
# coding=utf-8
from multiprocessing import *
from src.common.AppInit import *
from src.common.LaunchAppiumServices import *
from src.suite.ScanCaseName import *
from src.testcase.WaitCase import *
from src.utils.SendMail import *
__author__ = "Maiyajj"
__version__ = "V3.2.8.180411"
class MainFunc(object):
def r... |
import os, sys
import datetime
import io
import re
import tempfile
from flask import Flask, redirect, render_template, send_file, request, url_for
from flask_sqlalchemy import SQLAlchemy
from .lib import xlsxlib
if getattr(sys, "frozen", False):
dirpath = os.path.dirname(sys.executable)
else:
d... |
"""
练习1: 编写一个程序,删除主目录下 “下载”
文件夹中大小 小于1kb的文件
"""
import os
dir = "/home/tarena/下载/"
for file in os.listdir(dir):
filename = dir + file
# 普通文件 and 小于1kb
if os.path.getsize(filename) < 1024 and \
os.path.isfile(filename):
os.remove(filename) # 删除文件
|
#!/usr/bin/env python3
# Copyright (C) 2017-2019 The btclib developers
#
# This file is part of btclib. It is subject to the license terms in the
# LICENSE file found in the top-level directory of this distribution.
#
# No part of btclib including this file, may be copied, modified, propagated,
# or distributed except... |
from .base import BaseModule
class Public(BaseModule):
def get_shop_by_partner(self, **kwargs):
"""
:param kwargs
:return
"""
return self.client.execute("public/get_shop_by_partner", "GET", kwargs) |
#!/usr/bin/python
from ansible.module_utils.basic import *
import requests
from requests.auth import HTTPBasicAuth
def artifactory_repo_present(data):
# Additionally required params if creating user
required_arguments = ['email', 'password']
missing = []
for required_argument in required_arguments... |
"""Contains Classes for different View Routes
Attributes:
url_rules (list): contains url rule objects, for add_url_rules() function
"""
import flask, flask.views
import functools
import config
import json
from nltk import word_tokenize
from nltk.corpus import stopwords
from hln.user import User
from hln import app... |
config ={
'CONTEXT' : 'We are in Master context',
'Org_Name': 'Sample Inc',
'Department_name': 'Department of silly walks',
'HQ_Address': { 'City': 'London', 'Country': 'UK'}
} |
"""
Tests for the scheduler implementation.
"""
import unittest
from coilmq.scheduler import FavorReliableSubscriberScheduler
from tests.mock import MockConnection
__authors__ = ['"Hans Lellelid" <hans@xmpl.org>']
__copyright__ = "Copyright 2009 Hans Lellelid"
__license__ = """Licensed under the Apache License, Versi... |
# ---------------------------------------------------------------------
# Raisecom.ROS.get_version
# ---------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# Python... |
"""
ZTF stamps outlier loader
safe max data loading float64 (~50GB): (by using float 32 it is reduced to half)
(4500000, 21, 21, 3) == (180*25000, 21, 21, 3)
(500000, 63, 63, 3) == (20*25000, 63, 63, 3)
"""
import os
import sys
import warnings
import numpy as np
import pandas as pd
PROJECT_PATH = os.path.abspath(
... |
from login_manager import *
from util_functions import UtilFunctions
class RemoveTag:
"""
This class delete a given tag from the local domain management server
"""
def __init__(self, tag, args):
"""
:param tag: tag name which will be deleted
:param args: the argume... |
import time
import os
import psutil
# 1. Написать декоратор, замеряющий время выполнение декорируемой функции.
def timer_decorator(f):
def wrapper(*args, **kwargs):
time_start = time.time()
f(*args, **kwargs)
time_finish = time.time()
print(f'Время исполнения функции {f.__name__}: ... |
# Contents in this file are referenced from the sphinx-generated docs.
# "magictoken" is used for markers as beginning and ending of example text.
def ex_inferred_list_jit():
# magictoken.ex_inferred_list_jit.begin
from numba import njit
from numba.typed import List
@njit
def foo():
# Ins... |
#!/usr/bin/env python
#
# Copyright 2018 Confluent 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... |
"""
MultiPlot.py
Author: Jordan Mirocha
Affiliation: University of Colorado at Boulder
Created on 2011-06-27.
Description: Make multipanel plots with shared axes, with or without AxesGrid.
"""
import numpy as np
from math import ceil
import matplotlib.pyplot as pl
# Matplotlibrc defaults
#figsize = pl.rcPara... |
from flask import Flask
import os
from lidar import lidar
from photogrammetry import photogrammetry
app = Flask(__name__)
app.register_blueprint(lidar)
app.register_blueprint(photogrammetry)
@app.route("/")
def hello():
return "3D Cut&Paste"
if __name__ == '__main__':
os.environ['FLASK_ENV'] = 'development'
... |
# Código com exemplo com implementação de Adapter patterns
class Target:
# O Target define a interface específica do domínio usada pelo código do cliente.
def request(self) -> str:
return "Alvo: o comportamento do alvo padrão."
class Adaptee:
# O Adaptee contém alguns comportamentos úteis, mas... |
import re
import json
class SourceData:
def __init__(self, source_file):
self.source_file = source_file
self.length_of_year = 0
self.year_data = []
self.year_data_lines = []
self.day_verse_list = []
self.last_three_lines = []
self.ending_info = []
sel... |
import os
import setuptools
import setuptools.command.test
import sys
pkgdir = {"": "python%s" % sys.version_info[0]}
VERSION = "0.19.1"
# `python setup.py test` uses existing Python environment, no virtualenv, no pip.
# Use case: Archlinux package. https://github.com/httplib2/httplib2/issues/103
# Otherwise, use `s... |
import os
from .config import CONFIG
class Style:
def style(color, text):
if os.isatty(1) and os.isatty(2) and CONFIG['misc']['colors']:
return '\033[{}m{}\033[0m'.format(color, text)
return text
def bold(text):
return Style.style(1, text)
def red(text):
retu... |
import logging
import pytest
from psyneulink.components.functions.function import Linear
from psyneulink.components.mechanisms.processing.transfermechanism import TransferMechanism
from psyneulink.components.projections.pathway.mappingprojection import MappingProjection
from psyneulink.composition import Composition
... |
import pandas as pd
from pathlib import Path
from steinbock import io
from steinbock.export import graphs
class TestGraphsExport:
def test_convert_to_networkx(self):
neighbors = pd.DataFrame(
data={
"Object": [1, 2],
"Neighbor": [2, 1],
"Distan... |
# Weight converter
weight = float(input("Weight?"))
unit = input("(L)bs or (K)g?")
if unit.upper() == "K":
print(weight*2.2)
elif unit.upper() == "L":
print(weight*0.45)
else:
print("Error, please verify your input") |
from pathlib import Path
import torch
from models.dsd.dsd import DSD
from models.dsd.stylegan import G_mapping, G_synthesis
from models.losses.dsd_loss import LossBuilderStyleGAN
class DSDStyleGAN(DSD):
def __init__(self, opt, cache_dir):
super(DSDStyleGAN, self).__init__(opt, cache_dir)
def load_sy... |
"""Runs the Secret Santa program."""
import sys
from getopt import GetoptError
from view.cli.cli import CLI
if __name__ == '__main__':
cli = None
try:
cli = CLI(sys.argv[1:])
except (GetoptError, ValueError) as err:
print('Error:', err)
CLI.usage()
if cli is not None:
... |
import numpy as np
class ExperimentViewProperties(object):
""" An instance of this class is returned for each experiment
and contains plotting information.
"""
title = 'experiment'
info = ''
dataset = ''
x_axis_name = 'x-axis'
y_axis_name = 'y-axis'
xscale = 'linear'
fea... |
from django.http import HttpResponse
from django.utils.translation import gettext as _
import json
from functools import partial, update_wrapper
from django.shortcuts import get_object_or_404, redirect
from django.conf import settings
from django.contrib import admin
from django.contrib.admin.exceptions import Disallow... |
"""
Utils
This module contains a general purpose classes to handle
encoding, time, among other things.
"""
import argparse
import json
import datetime
import geopy
import yaml
def serialize(obj) -> str:
""" Serializes an object into json """
return json.dumps(obj, cls=DateTimeEncoder, sort_keys... |
import logging
from resteasycli.lib.workspace import Workspace
logger = logging.getLogger('test_logger')
workspace = Workspace(logger=logger)
|
"""
Generate test code tool
copyrigth https://github.com/shigeshige/py-ut-generator
"""
import ast
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
@dataclass
class Value:
"""
Const value class.
"""
value: Any
is_literal: bool = False
description: str = ''... |
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... |
from django.urls import path
from . import views
app_name = "vote"
urlpatterns = [
path("", view=views.Vote_main.as_view(), name='main_view'),
path("add/candi", view=views.Add_candi.as_view(), name='add_candi'),
path("add/poll", view=views.Add_poll.as_view(), name='add_poll'),
path("canditopoll", view=... |
from reviewlogic.domains import review
from reviewlogic.gateways import review_gateway as rg
from reviewlogic.value_objects import ProposalId, ReviewId, UserId
class ReviewUseCase:
def __init__(self, port: rg.ReviewPort) -> None:
self.port = port
def save(
self,
user_id: UserId,
... |
#!/usr/bin/env python3
# A simple script to generate the resource_sets sections of the container_mapper_rules.yml
# file that will be used to `helm upgrade` clusters.
#
# USAGE
#
# python3 make-job-conf.py CPU_LIMIT MEMORY_LIMIT
#
# EXAMPLE
#
# python3 make-job-conf.py 4 16
import sys
from ruamel.yaml import YAML
re... |
from unittest import TestCase
from unittest.mock import MagicMock
from oxygen.zap import ZAProxyHandler
from ..helpers import get_config
class TestParseZapAlertDict(TestCase):
def setUp(self):
self.object = ZAProxyHandler(get_config()['oxygen.zap'])
self._params = {
'instances': [True... |
try: # pragma: no cover
from unittest.mock import patch
except ImportError: # pragma: no cover
from mock import patch
import pytest
import besepa
from besepa.resource import Create, Delete, Find, List, Post, Resource, Update
besepa.configure(api_key='dummy')
class TestResource(object):
def test_gette... |
from flask import Flask,redirect, url_for, request
import pandas as pd
import scipy.stats as ss
import numpy as np
import math
from pandas import to_datetime
from collections import Counter
from sklearn import mixture
import os,gc
def get_percentage(percent, number_of_time_points):
return int(percent/100*number_of... |
#! /usr/bin/python
import threading
import numpy as np
import time
import math
import sys
np.random.seed(20)
ALPHA = 0.0005
BETA = 0.0005
# e1 and e2 are supposed to be 1 x DIM vectors
# r1 is supposed to be DIM x DIM matrix
# return sigmoid function value
def logistic( e1, r1, e2 ):
if e1.shape != (1, DIM) or e... |
from sources import *
from diagnostic import *
from magnets import *
from pipes import *
import xml.etree.ElementTree as ET
class Accelerator:
def __init__(self, source=IonSource(), xml_root=None):
if xml_root:
self.devices = []
for child in xml_root.iter():
if chi... |
#!/usr/bin/env python
import time
import test_dashvisor
def main():
try:
test_dashvisor.setUp()
while True:
time.sleep(10)
except KeyboardInterrupt:
print 'stoping..'
test_dashvisor.tearDown()
print 'stoped'
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('course_selection', '0019_auto_20150903_0458'),
]
operations = [
migrations.CreateModel(
name='Friend_Request',
... |
# -*- coding: utf-8 -*-
"""Helper functions to load and save CSV data.
This contains a helper function for loading and saving CSV files.
"""
import csv
# This load_csv function is so the app knows where to go to retrieve the banks max loan amount, Loan to value,
# required credit score, ect..
def load_cs... |
import config.config as config_module
import os
import GooglePlus.ModifyDataGooglePlus as modify_plus
if __name__ == '__main__':
dir_path = config_module.config_file('dir', 'path')
lst_json_file = [files for files in os.listdir(dir_path) if files.endswith('.json')]
plus_ins = modify_plus.ReadFile()
... |
"""
Django settings for web project.
Generated by 'django-admin startproject' using Django 3.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
from d... |
# -*- coding: utf-8 -*-
description = 'Andor IKON-L CCD camera'
group = 'optional'
includes = ['filesavers']
tango_base = 'tango://192.168.20.31:10000/antares/'
devices = dict(
timer_ikonl = device('nicos.devices.vendor.lima.LimaCCDTimer',
description = 'The camera\'s internal timer',
tangodevi... |
'''
Created on Nov 9, 2017
Life - Game of Life
@author: jschmid3@stevens.edu
Pledge: I pledge my honor that I have abided by the Stevens Honor System -Joshua Schmidt
CS115 - Lab 10
'''
import random
import sys
from pip._vendor.html5lib._inputstream import spacesAngleBrackets
from random import randint
def createO... |
"""These are the texts shown in card_menu's and card_popup's"""
# GAME SALES
GS_CARD_TITLE = 'JUEGOS'
GS_CARD_SUBTITLE = 'COLECCIÓN DE JUEGOS Y SUS\nVENTAS EN DIFERENTES PAÍSES'
GS_CARD_CONTENT = 'A muchos nos gustan los juegos retro\n\n¿Cuáles son los 10 juegos más vendidos\nantes de los 2000?'
# MÚSICA
MUSIC_CARD_TI... |
from hexonet.apiconnector.apiclient import APIClient as AC
from hexonet.apiconnector.response import Response
import re
import argparse
import textwrap
import sys
from pathlib import Path
from datetime import datetime, timedelta
import json
import time
import os
from tabulate import tabulate
from textwrap import TextWr... |
import os
from ismain import is_main
from sundry import mkdirs, rmdir
def test_robust_os():
test_dir = os.path.join("temp", "test")
mkdirs(test_dir, remove_first=True)
assert os.path.exists(test_dir)
rmdir(test_dir)
assert not os.path.exists(test_dir)
if is_main():
test_robust_os()
|
import argparse
from commands import base_command
class Npm(base_command.BaseCommand):
@staticmethod
def argparse(parser, subparsers):
parser_main = subparsers.add_parser('npm', help="runs npm inside a node container")
parser_main.add_argument('-p', '--project', nargs="?", help="set node proj... |
import math
ang = float(input('Digite o ângulo:'))
print('O seno de {}, é igual a:{:.2f}.'.format(ang, math.sin(math.radians(ang))))
print('O cosseno é :{:.2f}.'.format(math.cos(math.radians(ang))))
print('E a tangente é:{:.2f}.'.format(math.tan(math.radians(ang))))
|
import pandas
import numpy
# Read the data
data = pandas.read_csv('data.csv')
# Split the data into X and y
X = numpy.array(data[['x1', 'x2']])
y = numpy.array(data['y'])
# Import the SVM Classifier
from sklearn.svm import SVC
# TODO: Define your classifier.
# Play with different values for these, fro... |
from django.urls import path
from . import views
urlpatterns = [
path('list', views.MicroRegionsList.as_view(), name='cities_list'),
path('detail/<int:pk>', views.MicroRegionDetail.as_view(), name='city_detail'),
path('update/<int:pk>', views.MicroRegionUpdate.as_view()),
path('delete/<int:pk>', view... |
blacklist = [
"bedrock","potato","poisonous_potato","lava","water","air",
"farmland","tipped_arrow","bow","trident","crossbow",
"elytra","shield","dead_bush","end_portal_frame",
"turtle_egg","flint_and_steel","saddle","dragon_egg",
"fishing_rod","shears","command_block","spectral_arrow",
"barrier"
]
black... |
def select2(self, fields=from):
pass
|
v = float(input('Quanto você tem na carteira? Rlx não é um assalto: R$'))
print('Convertendo este valor R${} em dólar, fica US${:.2f}!\n Sim, você é pobre'.format(v, v/3.27))
|
from flask import Flask, render_template, flash, request
from flask_wtf import Form
from flask_wtf.file import FileField
from tools import s3_upload
app = Flask(__name__)
app.config.from_object('config')
class UploadForm(Form):
example = FileField('Example File')
@app.route("/upload", methods=['POST... |
import tflearn
def clf_3d(cnn_model, cnn_params):
network = None
return network |
# -*- coding: utf-8 -*-
from datetime import datetime
from braces.views import CsrfExemptMixin, LoginRequiredMixin
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.views import View
from django.views.generic.list import ListView
from P2PLending.lending.forms import MoneyRequestFor... |
from typing import Callable, Dict, List, Optional
from vosekast_control.connectors import SMBusConnection
import threading
import logging
from vosekast_control.Log import LOGGER
from inspect import iscoroutinefunction
from asyncio import create_task, BaseEventLoop
from time import sleep
from vosekast_control.connector... |
"""
Fully connected network for example.
"""
from abc import ABCMeta
from torch import Tensor, nn
from torch.nn.utils.weight_norm import weight_norm
class FCNet(nn.Module, metaclass=ABCMeta):
"""
Fully connected network for example.
Usage example:
FCNet([4096, 1000, 200], 'ReLU', 0.2) - for a fully c... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
class AlipayUserAntpaasTestaccountCreateModel(object):
def __init__(self):
self._account_level = None
self._cert_name = None
self._cert_no = None
self._cer... |
# coding: utf-8
from .models import User, Role
from flask import request, jsonify, abort
from user_service import app, rest_manager
from datetime import datetime
from user_service.models import Country, Region, City, Customer, Address
from flask_jwt import JWT, jwt_required, current_identity
from flask.ext.restless imp... |
import numpy as np
from evaluate.bbox import bbox_overlaps
def evaluate_recall(roidb, thresholds=None,
area='all',
limit=None):
"""Evaluate detection proposal recall metrics.
Returns:
results: dictionary of results with keys
'ar': average recall
'recalls'... |
import os
from getpass import getpass
from netmiko import SSHDetect, ConnectHandler
# Code so automated tests will run properly
password = os.getenv("NETMIKO_PASSWORD") if os.getenv("NETMIKO_PASSWORD") else getpass()
base_device = {"device_type": "autodetect", "username": "pyclass", "password": password}
hosts = [
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
if __name__ == '__main__':
"""
SeeAlso:
~/code/ibeis/ibeis/tests/reset_testdbs.py
"""
import ibeis
from ibeis.tests import reset_testdbs
ibeis.ENABLE_WILDBOOK_SIGNAL = False
... |
# Proxy management.
#
# Copyright © 2014, 2015 Zack Weinberg
#
# 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
# There is NO WARRANTY.
import colle... |
from binarytree import tree, bst, Node, build
class MyNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
a = tree(height=4, is_perfect=False)
print(a)
b = bst(height=3, is_perfect=True)
print(b)
c = Node(7)
c.left = Node(3)
c.ri... |
"""
INPUT/OUTPUT OPERATIONAL OBJECT CLASS
@author: Paolo Santancini
"""
import csv
class Io:
f = ''
def __init__(self, filelog):
self.filelog = filelog
def Open(self, mode):
Io.f = open(self.filelog, mode)
def Close(self):
Io.f.close()
... |
import pymongo
import os
from config import CONNECTION_URI
# Now it reads from the enviornment string
class MongoDatabaseHandler(object):
def __init__(self):
self.connection = pymongo.MongoClient(CONNECTION_URI)
self.database = self.connection.urlshortener
def get_shortURL_collection(self):... |
import json
from rest_framework import serializers
# from django_celery_beat.models import CrontabSchedule
from workflows.models import Workflow, WorkflowRun, NotebookJob
class WorkflowSerializer(serializers.ModelSerializer):
"""
Serializer for the model NotebookJob
"""
triggerWorkflow = serializers.Se... |
import tkinter as tk
from tkinter import ttk
from datetime import datetime
class DateEntry(ttk.Entry):
"""An Entry for ISO-style dates (Year-month-day)"""
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.config(
validate='all',
... |
import os
import tempfile
import uuid
from StringIO import StringIO
from django.test import SimpleTestCase, TestCase
from casexml.apps.phone.cache_utils import extract_synclog_id_from_filelike_payload, \
replace_sync_log_id_in_filelike_payload, copy_payload_and_synclog_and_get_new_file
from casexml.apps.phone.excep... |
###############################################################################
# Copyright 2018 The AnPyLar Team. All Rights Reserved.
# Use of this source code is governed by an MIT-style license that
# can be found in the LICENSE file at http://anpylar.com/mit-license
################################################... |
from __future__ import unicode_literals
from django.db import models
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from mptt.models import MPTTModel, T... |
import glob
import tempfile
import unittest
import zipfile
from io import BytesIO
from pycaption import (ScenaristDVDWriter, DFXPReader)
from tests.samples.dfxp import DFXP_FROM_SAMI_WITH_POSITIONING
class ScenaristDVDWriterTestCase(unittest.TestCase):
def setUp(self):
self.writer = ScenaristDVDWriter()... |
import numpy as np
def get_fuel_v1(mass):
return int(np.floor(mass / 3) - 2)
def get_fuel_v2(mass):
fuel = int(np.floor(mass / 3) - 2)
if fuel <= 0:
return 0
else:
return fuel + get_fuel_v2(fuel)
def load_inputs(filename):
with open(filename) as f:
return [int(line.strip()... |
#!/usr/bin/env python
"""
In this module, the underlying implementation for word2vec uses 2 models - either skipGram or continuous bag of words
(CBOW).
Each of those 2 models can use one of 2 cost functions - either softmax or negative-sampling, each with their own
corresponding derivatives (aka gradients)
"""
import ... |
# Validating and Parsing Email Addresses
# Problem Link: https://www.hackerrank.com/challenges/validating-named-email-addresses/problem
import re
n = int(input())
for _ in range(n):
x, y = input().split(" ")
m = re.match(r"<[A-Za-z](\w|-|\.|_)+@[A-Za-z]+\.[A-Za-z]{1,3}>", y)
if m:
print(x, y)
|
#!/usr/bin/env python
import numpy as np
import subprocess
import argparse
import os
import astropy.io.fits as pyfits
from SULI import which
from SULI.work_within_directory import work_within_directory
if __name__ == "__main__":
parser = argparse.ArgumentParser(
'Submit simulation to the farm at Stanfor... |
from cadnano.gui.controllers.itemcontrollers.partitemcontroller import PartItemController
from .emptyhelixitem import EmptyHelixItem
from .virtualhelixitem import VirtualHelixItem
from .activesliceitem import ActiveSliceItem
from . import slicestyles as styles
import cadnano.util as util
from cadnano import getReopen... |
# coding: utf-8
from __future__ import print_function
import logging
from PySide2.QtWidgets import (
QVBoxLayout,
QHBoxLayout,
QGroupBox,
QFormLayout,
QLabel,
QComboBox,
QCheckBox,
QPushButton,
QWidget,
QGridLayout,
)
from ProfileInspector.src.util import widget_color, doc_fi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.