content stringlengths 5 1.05M |
|---|
""" Provides the CoinMessenger class definition.
Module content
--------------
"""
# The python-cctalk package allows one to send ccTalk messages and decode replies from a coin validator.
license_text = "(C) 2011 David Schryer GNU GPLv3 or later."
__copyright__ = license_text
__autodoc__ = ['CoinMessenger']
__all__ ... |
#!/usr/bin/env python3
from typing import List, Dict, Union
from hiro_graph_client.clientlib import AuthenticatedAPIHandler, AbstractTokenApiHandler
class HiroVariables(AuthenticatedAPIHandler):
"""
Python implementation for accessing the HIRO Variables REST API.
See https://core.arago.co/help/specs/?url... |
# Copyright 2014 Facebook, Inc.
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.
# As with any software that integrates with the Fa... |
from . import RecordField, RecordClass
try:
import attr
except ImportError:
pass
else:
class AttrField(RecordField[attr.Attribute]):
def is_required(self) -> bool:
return self.default is attr.NOTHING
class AttrClass(RecordClass[attr.Attribute]):
fields_attribute = "__attrs... |
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2021 all rights reserved
#
# externals
import collections
from .. import tracking # for locators
from ..traits.Property import Property as properties # to get the default trait type
# superclass
from ..calc.Hierarchical import Hierarchical
# m... |
import numpy as np
from pathlib import Path
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
from cv2 import cv2
import csv
# location of metadata file with bboxes corresponding to imagenames
METADATA_LOCATION = 'C:\\Users\\e.marcus\\datasets\\node21\\cxr_images\\proccessed_data\... |
import pytest
@pytest.fixture
def torr_test_file(datafix_dir):
return str(datafix_dir / 'test_file.torrent')
@pytest.fixture
def torr_test_dir(datafix_dir):
return str(datafix_dir / 'test_dir.torrent')
@pytest.fixture(scope='session')
def struct_torr_dir():
return {
'announce': 'http://track1.... |
import pytest
import mock
import json
from prometheus_udp_gateway import (
ReceiveMetricProtocol, UDPRegistry, Counter
)
@pytest.fixture()
def udp_registry():
return UDPRegistry(host='invalid', port=0000)
@pytest.fixture()
def counter(udp_registry):
counter = Counter('test_counter', '... |
#!/usr/bin/env python2.7
'''
Check the schematics of all the KiCAD demo projects
'''
import os
import glob
import traceback
import find_kipy
from kipy.fileobjs.paths import kicad_demo_root
from kipy.project import Project
from kipy.parsesch import ParseSchematic
from kipy.fileobjs.net import kicadnet
for projname ... |
from dataset.dataset import *
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import pandas as pd
import numpy as np
size = 128
# df = pd.read_csv('../../data/train.csv').set_index('image_id')
# files_path = '../../CLAM/pandaPatches10x/patches'
files_path = '../../CLAM/TCGA/pat... |
import pmast
from ast import *
source = '''
def some_function(a, b):
a - 3
return a + b
'''
tree = parse(source)
pm = pmast.PatternDispatch()
@pm('BinOp.Add')
def add(data, node_binop, node_add):
assert node_add is node_binop.op
assert isinstance(node_add, Add)
data['addleft'] = node_binop.left
... |
import os
print(os.getcwd())
os.chdir('../resource/output')
print(os.getcwd())
print()
print(os.path.join('/Users/moqi/Documents/Code/dive-into-python3-practice/c04/', 'p108_os1.py'))
print(os.path.join('/Users/moqi/Documents/Code/dive-into-python3-practice/c04', 'p108_os1.py'))
print()
print(os.path.expanduser('~')... |
import os
import unittest
import ddt
import time
from pages.managerListPage import ManagerListPage
from lib.scripts import (
select_Browser_WebDriver,
reply_case_fail,
get_data,
genrandomstr,
join_url
)
from lib import (
gl,
HTMLTESTRunnerCN
)
@ddt.ddt
class TestManagerList(unittest.TestCa... |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
import logg... |
from random import randint, shuffle
from Support.code.utils import filters
from asks.models import Question
from room.models import Room
from django.db.models import Q, F
# support functions
def save_questions_for_vote(questions: dict):
for theme_name, set_of_questions in questions.items():
questions[them... |
# Main File - Driver for the Application PcapXray
# Import Libraries
import os #-- default lib - packed with python
import sys #-- default lib
import datetime #-- default lib
from Tkinter import *
import ttk
# Import Custom Modules - Self created by the author
if sys.path[0]:
sys.path.insert(0,sys.path[0]+'/M... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 16 10:44:03 2019
Functions required to generate stability diagrams
@author: Giovanni Oakes
"""
import itertools
import numpy as np
from scipy.signal import convolve
import matplotlib.pyplot as plt
def rand_c(cs, r):
return abs(np.random.normal(cs, cs / 10, 1)) * r... |
# i90/test_tracker.py
from json import loads
from i90.config import config
from i90.test_helpers import *
from i90.track import Tracker
def test_record():
firehose = FakeFirehose()
tracker = Tracker(client=firehose)
tracker.record("test", other="arg")
recorded = loads(firehose.records[-1]["Data"])
... |
from code.generator.lib.htmllib import *
from code.generator.lib.page import *
from code.util.db.simple import *
from code.util import register
register.web("/login", "any", lambda params, user: Page(
div(cls="login-box", contents=[
h2("Login", cls="login-header"),
h.label("Username", c... |
#!/usr/bin/env python
# -*-coding:utf-8-*-
import gevent.event
import gevent.greenlet
from xnrpc.common.log import get_log
_log = get_log(__name__)
WAIT_INTERVAL = 5
class ServerThread(gevent.greenlet.Greenlet):
"""gevent服务器协程"""
def __init__(self):
super(ServerThread, self).__init__()
self.... |
# Copyright (c) 2021 Seagate Technology LLC and/or its Affiliates
#
# 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... |
#
# PySNMP MIB module DULD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DULD-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:54:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... |
from __future__ import print_function
import logging
import os
import registry
from . import utils
from . import net
from . import servicediscovery
import threading
import socket
import subprocess
logger = logging.getLogger(__name__)
# Do not assign a local IP to the node
# DOCKER_FIX trick to avoid this issue:
# htt... |
class BadToken(Exception):
pass
class TokenExpired(Exception):
pass
class Forbidden(Exception):
pass
|
def recursive_power(num, power):
return num ** power |
# kcauto Copyright (C) 2017 Minyoung Choi
from datetime import datetime
from util.logger import Logger
class Stats(object):
def __init__(self, config):
"""Initializes the Stats module.
Args:
config (Config): azurlane-auto Config instance
"""
self.reset_... |
from django.db.models import fields
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import User
from django import forms
from .models import *
class UserRegistrationForm(UserCreationForm):
first_name = forms.CharField(required=True)
last_... |
import numpy as np
from citysim3d.envs import Env
from citysim3d.spaces import DictSpace
class ServoingEnv(Env):
def __init__(self, env, max_time_steps=100, distance_threshold=4.0):
"""
env should implement get_relative_target_position, is_in_view for this
instance to return a reward that ... |
from django.test import TestCase
from .models import User,Image
import datetime as dt
class UserTestClass(TestCase):
#setup method
def setUp(self):
self.enock=User(firstname="Enock",lastname="Rotich",email="rotichenoch27@gmail.com",phone_number="1234567890")
#Testing instance
def test_inst... |
# coding: utf-8
"""
ELEMENTS API
The version of the OpenAPI document: 2
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from elements_sdk.configuration import Configuration
class Asset(object):
"""NOTE: This class is auto generated by OpenAPI Gen... |
# Copyright (c) 2012, Machinalis S.R.L.
#
# Author: Rafael Carrascosa <rcarrascosa@machinalis.com>
#
# This file is part of REfO and is distributed under the Modified BSD License.
# You should have received a copy of license in the LICENSE.txt file.
import unittest
import refo
from refo.match import Match, match a... |
"""# Utilities"""
import numpy as np
import pandas as pd
from sklearn.base import (
BaseEstimator, RegressorMixin,
TransformerMixin as TransformerMixinBase
)
class TransformerMixin(TransformerMixinBase, BaseEstimator):
"""
Version of scikit-learn's [`TransformerMixin`](https://scikit-learn.org/stabl... |
"""
Test connections to folded interface.
"""
from gaphor import UML
from gaphor.tests import TestCase
from gaphor.diagram.classes.implementation import ImplementationItem
from gaphor.diagram.classes.interface import InterfaceItem, Folded
from gaphor.diagram.classes.association import AssociationItem
from gaphor.diagr... |
import time,cfg
from modules.banner import *
from modules.wipe import *
from modules.clean import *
from modules.handler import *
cfg.global_variables()
def scout_console():
while True:
try:
input = raw_input(cfg.prompt_scouts).strip().split(' ')
command = input[0]
... |
import cv2
import numpy as np
import torch
import torch.utils.data as Data
from model import RAS
from utils import trans_im, trans_gt
IMAGES_NUM = 3372
MINI_IMAGES_NUM = 1120
BATCH_SIZE = 1
EPOCHS_NUM = 200
def get_train_data(start_image_id, end_image_id):
image_num = end_image_id - start_image_id
x = np.ze... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import lz
from lz import *
import os
from datetime import datetime
import os.path
from easydict import EasyDict as edict
import time
import json
import sys
import numpy as np
import importlib
import itertools
i... |
"""Soar-like rule-based water jug puzzle solver."""
from .app import app as water_jug
|
import ssl
import pandas
from apps.abstracts import AbstractExcelToApi
from apps.helpers import cache
# unblocking checking certs https
ssl._create_default_https_context = ssl._create_unverified_context
class Excel(AbstractExcelToApi):
def __init__(self):
AbstractExcelToApi.__init__(self)
@cache(... |
import copy
import os
import json
import importlib
from typing import List
from typing import Dict
from typing import Union
import numpy as np
from joblib import Parallel, delayed
from prettytable import PrettyTable
from ase import Atoms
from ase.io.jsonio import encode as atoms_encoder
from ase.io.jsonio import decod... |
from django import forms
from .models import Hint, Problem
class HintUpdateFormWithReason(forms.ModelForm):
reason = forms.CharField(max_length=255, help_text="Reason for editing.", required=False)
class Meta:
model = Hint
fields = (
'problem',
'number',
'keywords',
'content',
'reason',
)
c... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask,render_template
from flask_bootstrap import Bootstrap
from flask_mail import Mail
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from config import config
bootstarp = Bootstr... |
# DO NOT EDIT THIS FILE. This file will be overwritten when re-running go-raml.
from .exists_service import ExistsService
from .insert_service import InsertService
from .passthrough_client_jwt import PassThroughClientJwt
from .http_client import HTTPClient
class Client:
def __init__(self, base_uri=""):
... |
import unittest
from decawave_1001_rjg.messages.dwm_location_response import DwmLocationResponse
class TestDwmLocationResponse(unittest.TestCase):
data = [0x40, 0x01, 0x00, 0x41, 0x0D,
0x01, 0x02, 0x00, 0x00,
0x05, 0x00, 0x00, 0x00,
0xFB, 0x00, 0x00, 0x00,
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def change_categories(apps, before, after):
CFGOVPageCategory = apps.get_model('v1', 'CFGOVPageCategory')
categories = CFGOVPageCategory.objects.filter(name=before)
categories.update(name=after)
def... |
import json
import asyncio
import websockets
import signal
import sys
from prettytable import PrettyTable
from bfxapi import Client
from pyee import EventEmitter
from ..utils.custom_logger import CustomLogger
from ..utils.mock_websocket_client import MockClient
from ..utils.mock_order_manager import MockOrderManager
... |
'''
1. get all individual postprocessed
2. combine the dicts and manage span index fixing
3. combine dialogue types too!!
''' |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PyDDSBB test example with unknown constraints and known constraints
@author: JianyuanZhai
"""
import PyDDSBB
def objective(x):
return x[0]
def constraints(x):
if (x[0]-2.0)**2 + (x[1]-4.0)**2 <= 4.0 and (x[0]-3.0)**2 + (x[1]-3.0)**2 <= 4.0:
return 1.... |
if '__metaclass__' in d: M = d['__metaclass__']
elif b: M = type(b[0])
elif '__metaclass__' in globals(): M = globals()['__metaclass__']
else: M = types.ClassType
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import numpy
import copy
import string
from molsys.addon import base
from molsys.util.constants import debye, angstrom
eA2debye = 1./(debye/angstrom)
def read_until(f,s):
while True:
line = f.readline()
if len(li... |
file_name = 'data/day13.txt'
dots: set[tuple[int, int]] = set()
folds: list[tuple[str, int]] = list()
with open(file_name) as file:
for line in file.readlines():
if ',' in line:
a, b = line.strip().split(',')
dots.add((int(a), int(b)))
elif 'fold along' in line:
... |
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys
sys.path.append('../')
# End of fix
import random
import logging
import matplotlib.pyplot as plt
from NiaPy.algorithms.basic import FireflyAlgorithm
logging.basicConfig()
logger = logging.getL... |
#%%
import random
import graphviz, re, time, os, sys, glob, json, ntpath
import matplotlib.cbook as cbook
from pathlib import Path
from graphviz import Digraph
# CPLC info collected from:
# 1. own analysis
# 2. https://www.javatips.net/api/bankomatinfos-master/src/at/zweng/bankomatinfos/iso7816emv/CPLC.java
# 3. NIST ... |
"""
base configuration file
"""
from os.path import abspath, dirname, join
from os import environ as env
TEST_MODE = env.get('TEST_MODE')
LOCAL_STORAGE_MODE = env.get('TEST_MODE')
CORE_ROOT = dirname(abspath(__file__))
PROJECT_ROOT = dirname(CORE_ROOT)
SECRET_KEY = env['FLASK_SECRET_KEY']
STATIC_URL = env['STATIC_U... |
"""
Import json data from JSON file to Datababse
"""
from ....page.models import Page, PageTranslation
from ....menu.models import Menu, MenuItem, MenuItemTranslation
from django.core.management.base import BaseCommand
from googletrans import Translator
class Command(BaseCommand):
def pages(self):
page_sl... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 chris <chris@home>
#
# Distributed under terms of the MIT license.
"""
Unit test package
"""
|
import os
from alchemy.db.fs import models_dir
def mkd(*dir_path):
"""Return dir path, make sure it exists"""
dir_path = [str(x) for x in dir_path]
d = os.path.join(*dir_path)
os.makedirs(d, exist_ok=True)
return d
def get_model_dir(uuid, version, abs=True):
# TODO: Legacy function with sid... |
#coding:utf-8
from django.conf.urls import url
from comments.views import CommentView
__author__ = 'qiye'
__date__ = '2018/3/12 18:15'
app_name = 'comments'
urlpatterns = [
url(r'^post/(?P<article_id>\d+)/$', CommentView.as_view(),name='comment_post'),
] |
__doc__ = """WhPy - Webhook Python
Webhook Python is a Python 3 module for interacting with various chat
applications via established webhooks.
Modules:
discord
slack *PLANNED*
"""
|
import numpy as np
import skimage
import skimage.io
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
import torch.nn.functional as F
from torchvision.utils import save_image
import torch.backends.cudnn as cudnn
from dataloader import KITTI_testloader as D... |
# This program counts the number of times
# the letter T (uppercase or lowercase)
# appears in a string.
def main():
# Create a variable to use to hold the count.
# The variable must start with 0.
count = 0
# Get a string from the user.
my_string = input('Enter a sentence: ')
# Count the ... |
from django.test import override_settings
from functional_tests import pages
from functional_tests.base import FunctionalTestCase
@override_settings(ACCOUNT_EMAIL_VERIFICATION="mandatory")
class SignupTestCase(FunctionalTestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.us... |
"""
Semi-Quantum Conference Key Agreement (SQCKA)
Author:
- Ruben Andre Barreiro (r.barreiro@campus.fct.unl.pt)
Supervisors:
- Andre Nuno Souto (ansouto@fc.ul.pt)
- Antonio Maria Ravara (aravara@fct.unl.pt)
Acknowledgments:
- Paulo Alexandre Mateus (pmat@math.ist.utl.pt)
"""
# Class for IBM Qiskit's SWAP Test
clas... |
# coding: utf-8
import os
import json
import pytest
from webob import Request
from pynch.wsgi import handler
@pytest.fixture
def process(request):
os.environ['PYNCH_CONFIG'] = os.path.join(
os.path.dirname(__file__),
'container.json'
)
return handler(
config_file_name='$PYNCH_CO... |
from cumulusci.core.utils import process_bool_arg
from cumulusci.salesforce_api.package_zip import DestructiveChangesZipBuilder
from cumulusci.tasks.salesforce import Deploy
uninstall_task_options = Deploy.task_options.copy()
uninstall_task_options["purge_on_delete"] = {
"description": "Sets the purgeOnDelete opti... |
import re
import sys
import logging
from textwrap import indent
from peewee import (
Model,
IntegerField,
CharField,
SqliteDatabase,
IntegrityError,
TextField,
)
from beyond.orbits import Ephem, Orbit
import beyond.io.ccsds as ccsds
from beyond.io.tle import Tle
from beyond.propagators import g... |
import pygame
import pygame.locals
from pygame.locals import *
from random import random
from gameobject import GameObject
class Blob(GameObject):
backgroundColor = (55, 151, 144)
classification = "blob"
health = 1000
speed = 0
# NEW CODE
# Image to be shown for ea... |
#!/usr/bin/env python
from __future__ import print_function
from scapy.all import *
import sys
import numpy
host_list = []
input_file = sys.argv[1]
def get_src_dst_pairs(all_packets):
""" Takes in tcpdump formatted output (file) and counts the number of connections between hosts"""
d = {}
fo... |
#coding=utf-8
'''/*
* Copyright 2015 lixiaobo
*
* VersionUpgrade project licenses this file to you 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
... |
from typing import AnyStr, List
import os
import matplotlib.image as mpimg
import numpy as np
import cv2
def calibrate_camera(directory: AnyStr):
'''
@params:
directory: The path to the directory where chessboard images are stored
@return: (a tuple)
retval, cameraMatrix, distCoeffs, rvecs, tvecs
... |
#API endpoints for base view
from flask import Blueprint
api = Blueprint('base',__name__)
from app.base import routes |
import logging
from shapely.geometry import Polygon, shape, mapping
PRECISION = 5
logger = logging.getLogger(__name__)
def round_geometry_coordinates(geometry: Polygon) -> Polygon:
"""round coordinates of polygon to reduce topology error and geojson file size"""
geojson_geom = mapping(geometry)
_round_... |
def main(j, args, params, tags, tasklet):
page = args.page
attributes = "class='nav nav-list' style='-moz-column-count: 3; -webkit-column-count:3; column-count:3;'"
refresh = j.tools.text.getBool(args.tags.tagGet('refresh', False))
page.addHTML("""
<a class="right margin-right-medium" href="/... |
def merge(self):
for i in self.children:
if i:
if i.count > 0:
self.oTree.leafList.remove(i)
self.oTree.numLeaves -= 1
else:
print("Recursively Merging non-leaf...")
i.merge()
self.count += i.count
self.red += i.red
self.green += i.green
self.blue += i.blue
for i in range(8):
sel... |
"""
Copyright (c) 2020 CRISP
generator for CSC and CDL
:author: Andrew H. Song
"""
import numpy as np
from .BaseCSC import BaseCSC
from .BaseCDL import BaseCDL
from .BaseInitializer import BaseInitializer
from .COMP import COMP
from .CKSVD import CKSVD
def generateCSC(dlen, error_tol, sparsity_tol,... |
#! /usr/bin/env python
#
# The MIT License (MIT)
#
# Copyright (c) 2016 Takeshi HASEGAWA <hasegaw@gmail.com>
#
# 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 w... |
import pandas as pd
import numpy as np
from sklearn.preprocessing import RobustScaler
from imblearn.under_sampling import NearMiss
from application_logging.logging import logger_app
import warnings
warnings.filterwarnings("ignore")
class Preprocessor:
def __init__(self):
self.logFilePath = ... |
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import x25519
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes
from cryptography... |
# ---------------------------------------------------------------------
# FM module database models
# ---------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# Third... |
from simulater import DataManager
from model.trained_transporter import Transporter
import operator
import numpy as np
import tensorflow as tf
class HeuristicABSLAP(object):
def __init__(self, path, width=5, height=5):
# 입력 데이터 가져오기 및 멤버변수 저장
space, blocks = DataManager.import_data_from_csv(path, w... |
from typing import List
"""
Binary search
TC: O(logM*N) M is the sum of weights, N is length of Weights
SC: O(1)
"""
class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
if days >= len(weights):
return max(weights)
sum_weight = sum(weights)
min_cap = ma... |
#!/usr/bin/python3
import sys
from PyQt5.QtWidgets import QMainWindow, QDesktopWidget, QApplication
from LaunchScreen import LaunchScreen
from CollectionScreen import CollectionScreen
from ChooseScreen import ChooseScreen
from ContainerScreen import ContainerScreen
from ListScreen import ListScreen
from SearchScreen... |
# Generated by Django 3.2.7 on 2021-09-19 17:46
import core.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('links', '0002_link_published'),
]
operations = [
migrations.AlterField(
model_name='link',
name='... |
import _plotly_utils.basevalidators
class TemplateitemnameValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name='templateitemname',
parent_name='sankey.link.colorscale',
**kwargs
):
super(TemplateitemnameValidator, self).__init__(
... |
from math import sin
def solve(f, a, b, c):
m = (a + b) / 2.0
while a != m and m != b:
if f(m) < c:
a = m
else:
b = m
m = (a + b) / 2.0
return a
a = 1.6
b = 3
print(solve(lambda x: sin(x) - x / 3, a, b, 0))
|
import logging
loggers = {}
def get_logger(name: str,
level = logging.INFO,
format = "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s"
) -> logging.Logger:
"""
returns a logger with predefined formatting
"""
if name in loggers:
return logger... |
'''
URL: https://leetcode.com/problems/find-lucky-integer-in-an-array/
Difficulty: Easy
Description: Find Lucky Integer in an Array
Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value.
Return a lucky integer in the array. If there are multiple lucky in... |
# Generated by Django 3.2.4 on 2021-06-14 10:38
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... |
import re
import sys
from sys import exit
from pydynpd.info import options_info
from pydynpd.variable import gmm_var, regular_variable
class temp_list:
def __init__(self, cols):
self.names = []
self.lags = []
self.cols = cols
self.adjustable_min_lags = [] # True Fals... |
import time
import torch
from torchtext.experimental.datasets import AG_NEWS
from torchtext.experimental.vectors import FastText as FastTextExperimental
from torchtext.vocab import FastText
def benchmark_experimental_vectors():
def _run_benchmark(tokens, vector):
t0 = time.monotonic()
for token i... |
"""
Reference: https://github.com/apache/lucene-solr/blob/master/lucene/analysis/nori/src/test/org/apache/lucene/analysis/ko/TestKoreanTokenizer.java
TODO Test List.
- test_reading
- test_random_strings
- test_random_huge_strings
- test_random_huge_string_mock_graph_after
- test_combining
"""
import os
import un... |
#!/usr/bin/env python3
#
# Copyright 2022 Graviti. Licensed under MIT License.
#
"""The implementation of the Commit and CommitManager."""
from functools import partial
from typing import TYPE_CHECKING, Any, Dict, Generator, Optional, Tuple
from tensorbay.utility import AttrsMixin, attr
from graviti.dataframe impor... |
# NearDuplicatesIndex class
#
# Generates an entry for each appended document, that allows for estimating
# the Jaccard Coefficient between documents.
import math, random, sys
from .ngram import Ngram
class NearDuplicatesIndex:
def __init__(self):
self.docs_to_ngrams = {} # maps filenames to Ngram objec... |
from . import HTMLGenerator
from . import Keywords
from . import Lexer
from .DispatchHandler import DispatchHandler
from _SilverCity import find_lexer_module_by_id, PropertySet, WordList
from .ScintillaConstants import SCLEX_CSS
from . import LanguageInfo
class _CSSLexerTemplate(Lexer.Lexer):
def __init__(self, p... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
img1 = cv2.imread('opencv-feature-matching-template.jpg', 0)
img2 = cv2.imread('opencv-feature-matching-image.jpg', 0)
orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(img1, None)
kp2, des2 = orb.detectAndCompute(img2, None)
bf = cv2.BFMatcher(cv2.... |
import TestPlantUtil
TestPlantUtil.loadProject("1F", ["AGXSimulator", "AISTSimulator"], "AizuWheel")
|
#!/usr/bin/env python3
"""Alta3 Research | Author: RZFeeser@alta3.com"""
# imports always go at the top of your code
import requests
def main():
"""Run time code"""
# create r, which is our request object
r = requests.get("https://cat-fact.herokuapp.com/facts")
# display the methods available to our ... |
from visual import *
from random import random, randrange
## this is mostly for experimenting with zooming and rotating
print("""
Right button drag or Ctrl-drag to rotate "camera" to view scene.
Middle button to drag or Alt-drag up or down to zoom in or out.
On a two-button mouse, middle is left + right.
""")
def ... |
from django.shortcuts import render
# Create your views here.
def main_page(request):
if request.user.groups.filter(name='pracownik').exists():
return render(request, 'pracownik.html')
else:
return render(request, 'index.html')
|
#!/usr/bin/python
import tensorflow as tf
import RPi.GPIO as GPIO
import time
from imutils.video import VideoStream
import numpy as np
import datetime
import imutils
import time
import cv2
GPIO.setmode(GPIO.BCM)
PWM_PIN1 = 17
PWM_PIN2 = 18
GPIO.setup(PWM_PIN1,GPIO.OUT)
GPIO.setup(PWM_PIN2,GPIO.OUT)
pw... |
'''
Manage SVN repositories
=======================
Manage repositiry checkouts via the svn vcs system:
.. code-block:: yaml
http://unladen-swallow.googlecode.com/svn/trunk/:
svn.latest:
- target: /tmp/swallow
'''
# Import python libs
import logging
import os
# Import salt libs
from salt import e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.