content stringlengths 5 1.05M |
|---|
#!/usr/bin/python3
import shutil
import os
import base64
from time import sleep
import flask
import requests.exceptions
import blueprint
from flask_cors import CORS
from confhttpproxy import ProxyRouter, ProxyRouterException
from flask import Flask, jsonify
import rest_routes
from lmsrvcore.utilities.migrate import... |
from .util.network import check_ssl_expiry_date
from .util.format import pretty_ssl_format
import csv
def check_certs():
result = []
# check_ssl_expiry_date(item)
return result
def print_results_to_screen(res):
# for (v,n,d) in res:
print()
def print_result_to_csv(res):
print()
|
import copy
import itertools
from collections import defaultdict
from boto.ec2.instance import Instance as BotoInstance, Reservation
from moto.core import BaseBackend
from .exceptions import InvalidIdError
from .utils import (
random_ami_id,
random_instance_id,
random_reservation_id,
random_security_g... |
from django.utils.text import slugify
from .page import PageCommand
from js_locations.models import Location
class Command(PageCommand):
help = 'Creates a Location with a .yaml template.'
def _get_placeholder(self, obj, placeholder_name):
if hasattr(obj, placeholder_name):
return getattr(o... |
'''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 ctypes
_... |
#!/usr/bin/env python
import os
from alignclf import analyze
from alignclf.utils import setup_logging
if __name__ == '__main__':
# use default logging
setup_logging(default_path='')
agg_result_dir = os.path.join('.', 'results-agg', '2018-12-03')
for dirname in os.listdir(agg_result_dir):
re... |
"""
Extension desined to test bot functionality, just for testing
"""
# Library includes
from discord.ext import commands
# App includes
from app.client import BotClient
class TestCog(commands.Cog):
"""
Class cog for the testing_cog cog extension
"""
def __init__(self, client: BotClient):
... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
plugin_test.py
---------------------
Date : May 2017
Copyright : (C) 2017, Sandro Santilli
Email : strk at kbt dot io
***********************************... |
# -*- coding: utf-8 -*-
from openprocurement.api.utils import get_now, raise_operation_error
from openprocurement.tender.core.utils import optendersresource, calculate_business_date
from openprocurement.tender.openua.views.lot import (
TenderUaLotResource as TenderLotResource
)
from openprocurement.tender.openuadef... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Script to generate categorized normalization inventory which feeds into
a Xerox FSM format normalization scripts to generate a .lexc file
"""
import io, os, sys, re
from collections import defaultdict
import subprocess
script_dir = os.path.dirname(os.path.realpath(__file... |
# -*- coding: utf-8 -*-
import os
import logging as log
from flask import Flask, Blueprint
from common import COMMON_DIRECTORY, BASE_DIR
from common.helpers.operation_results import OperationResults
CONFIGURE_FILE = f'{COMMON_DIRECTORY}/config.json'
CONFIGURE_DATA = "COMPANY_SECURITY_DATA"
LOG_FORMAT = '[ %(asctime)-1... |
'''
42-Refaça o desafio 35 dos triângulos,acrescentando o recurso de mostrar que tipo de triângulo será formado.
==>Equilátero:Todos os lados iguais.
==>Isósceles:Dois lados iguais.
==>Escaleno:Todos os lados diferentes.
'''
print('-'*50)
print('ANALISADOR DE TRIÂNGULO VERSÂO 2.0')
print('-'*50)
print('\n')
valor1=f... |
print('Cleaning isolated non-directional regions using morphological opening')
X_binop = apply_bin_op(X_fill, binop_dim)
# clean up
# pool = Pool(os.cpu_count())
# # Add your data to the datasplit variable below:
# indices = [(i,j) for i,j in itertools.combinations(range(h),r=2) if i <= j]
# results = poo... |
import numpy as np
import pandas as pd
from keras.preprocessing import text, sequence
from keras.preprocessing.text import Tokenizer
from keras.utils import to_categorical
from keras.models import *
from keras.layers import *
from keras.regularizers import l2
from sklearn.model_selection import train_test_split, GridSe... |
"""
Created on Apr 24, 2013
@author: agross
"""
import numpy as np
import pandas as pd
import matplotlib.pylab as plt
import Stats.Scipy as Stats
from Figures.Helpers import latex_float, init_ax
from Processing.Helpers import match_series
colors = plt.rcParams['axes.color_cycle'] * 10
def _violin_plot(ax, data, p... |
# Copyright (c) 2021, Dashiell Ratcliffe
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
def Gaminghub(currentdir):
os.system('cls' if os.name == 'nt' else 'clear')
print(colored("""
___ ... |
"""
Tests for the Files endpoint.
"""
import pytest
PROJECT_ID = "454087345e09f3e7e7eae3.57891254"
@pytest.mark.vcr
def test_files(client):
"""Tests fetching of all files
"""
files = client.files(PROJECT_ID)
assert files.project_id == PROJECT_ID
assert files.items[0].filename == "%LANG_ISO%.xml"... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
return self.dfs(root)[0]
def dfs(self, root: TreeNode):
if root == None: return Tr... |
# Routines that find coordinate estimates in images
from .find import find_ellipse, find_ellipsoid, find_disks
# Routines that refine coordinates starting from known estimates
from .refine import (refine_ellipse, refine_ellipsoid_fast, refine_ellipsoid,
refine_disks)
# Routines that combine find an... |
"""
A simple server using the aioweb library
"""
import signal
import asyncio
import functools
import argparse
import logging
import uvloop
import aioweb.container
import aioweb.protocol
counter = 0
async def handler(request, container):
"""
This is the handler that will be executed for every request
... |
#!/usr/bin/env python
import random
class C(object):
def __setattr__(self, name, value):
pass
def __getattr__(self, name):
return random.randint(100, 200)
# START OMIT
c = C()
c.foo = 42
print c.foo
# END OMIT
|
import collections
Rect = collections.namedtuple('Rect', ['x', 'y', 'w', 'h'])
def intersect_intervals(l0, s0, l1, s1):
"""
Compute the intersection of intervals (l0, l0+s0) and (l1, l1+s1).
"""
l = max(l0, l1)
r = min(l0+s0, l1+s1)
if l > r:
return None
return (l, r-l)
def int... |
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import math
import numbers
from tracing.value.diagnostics import diagnostic
try:
StringTypes = basestring
except NameError:
StringTypes = str
class ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
import six
from durga import exceptions, validators
@pytest.mark.parametrize('value', [
"http://foo.com/blah_blah",
"http://foo.com/blah_blah/",
"http://foo.com/blah_blah_(wikipedia)",
"http://foo.com/blah_blah_(wikipedia)... |
"""
Copyright (c) 2019 The Cereja Project
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distrib... |
from dataclasses import dataclass, asdict
@dataclass
class ServerConfig:
server_ip: str
server_port: int
worldId: int
userName: str
password: str
def as_dict(self):
return asdict(self)
def get_uri(self):
return self.server_ip + ":" + str(self.server_port) + "/ws"
|
import pathlib
import time
import subprocess
import yaqc_bluesky
from yaqd_core import testing
from bluesky import RunEngine
from bluesky.plans import rel_list_scan
__here__ = pathlib.Path(__file__).parent
@testing.run_daemon_entry_point(
"fake-triggered-sensor", config=__here__ / "triggered-sensor-config.toml"... |
import unittest
import numpy as np
from railrl.misc import hyperparameter as hp
from railrl.testing.testing_utils import is_binomial_trial_likely, are_dict_lists_equal
class TestHyperparameters(unittest.TestCase):
def test_log_float_param(self):
param = hp.LogFloatParam("variable", 1e-5, 1e-1)
n... |
from typing import Optional
#from lib.world.WorldProjection import WorldProjection
from .Projection import Projection
class RenderSettings:
def __init__(
self,
render_width: int,
render_height: int,
projection: Optional[Projection] = None,
mag_filt... |
# author: Rohit Rawat
# date: 2021-11-18
"""This script prints out docopt args.
Usage: demo.py <arg1> [<arg4>] --arg2=<arg2> [--arg3=<arg3>]
Options:
<arg1> Takes any value (this is a required positional argument)
--arg2=<arg2> Takes any value (this is a required option)
[--arg3=<arg3>] Takes any... |
import argparse
import copy
import os
from bunch import Bunch
from mock import Mock
import sys
import re
from ml_utils import id_generator, TimeSeries, LogTimeseriesObserver
def create_mock():
return Mock()
class DummyUrlTranslator(object):
def url_to_path(self, url):
return url
def path_to_url(s... |
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django.forms import ModelForm
from .mixins import FormContextMixin
class BaseModelForm(FormContextMixin, ModelForm):
"""Base form for the majority of model forms in the project."""
def __init__(self, *args, **kwargs):
... |
# -*- coding: utf-8 -*-
from unittest.mock import Mock, patch
from django.test import SimpleTestCase
from api.permissions import HasAPIAccess
class HasAPIAccessTest(SimpleTestCase):
def test_has_permission_empty_meta(self):
request = Mock(META={})
self.assertFalse(HasAPIAccess().has_permission(... |
class Solution:
def countBits(self, num: int) -> List[int]:
result = [0] * (1 + num)
for i in range(1, 1 + num):
result[i] = result[i&(i - 1)] + 1
return result
|
#!/bin/python
import copy
# list of all folders
path_list = [ "./C", "./C-Plus-Plus", "./C#", "./Go", "./Java",
"./Javascript", "./Kotlin", "./PHP", "./Python", "./Scala"]
# checking all files
for path in path_list :
path+="/readme.md"
lines=[]
format_line=[]
with open(path) as f:
for i,line in ... |
import json
from . import BaseTestCase
class FormValidationTest(BaseTestCase):
def test_validate_form(self):
response = self.client.post('/articles/en')
assert response.status_code == 200
json_data = json.loads(response.content.decode('utf-8'))
assert json_data['ok'] is False
... |
from webrecorder.rec.storage.s3 import S3Storage
from webrecorder.rec.storage.local import LocalFileStorage
def get_storage(storage_type, redis):
"""Return Webrecorder storage.
:param str storage_type: type of storage
:param StrictRedis redis: Redis interface
:returns: Webrecorder storage or None
... |
from datetime import timedelta
import pytest
from channels.db import database_sync_to_async
from channels.testing import WebsocketCommunicator
from cms.api import add_plugin
from django.test import RequestFactory
from django.utils.lorem_ipsum import words
from django.utils.timezone import now
from djangocms_blog.cms_... |
import sys
def solve(upper, lower, G):
#print G
uarr = [0] * (upper[-1][0]+1)
larr = [0] * (upper[-1][0]+1)
for i in xrange(len(upper)-1):
for x in xrange(upper[i][0], upper[i+1][0]):
uarr[x] = upper[i][1] + (x - upper[i][0])*(upper[i+1][1] - upper[i][1])*1.0 / (upper[i+1]... |
from manimlib.imports import *
from numpy import sin, cos
from scipy.integrate import odeint
COBALT = "#0047AB"
class DouPen(Scene):
def construct(self):
Tit = Title("Double-Pendulum")
Tit.to_edge(UP)
Tit.set_color(COBALT)
Tit.scale(0.90)
self.play(Write(Tit))
self.Double(100,90,5,0,9.8,RED,BLUE,GREEN,YE... |
import re
import json
from ..base_request import BaseRequest
from .device import Device
from ..settings import Settings
from .. import exceptions
def _is_valid_env_var_name(env_var_name):
return re.match('^[a-zA-Z_]+[a-zA-Z0-9_]*$', env_var_name)
class EnvironmentVariable(object):
"""
This class is a w... |
# Generated by Django 2.1.3 on 2018-12-28 05:29
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0004_auto_20181222_1252'),
]
operations = [
migrations.RenameField(
model_name='document',
old_name='document',
... |
__all__ = ['cluster', 'clusterfiles', 'clusterinstance', 'clusterinstance_binding', 'clusterinstance_clusternode_binding', 'clusternode', 'clusternodegroup', 'clusternodegroup_authenticationvserver_binding', 'clusternodegroup_binding', 'clusternodegroup_clusternode_binding', 'clusternodegroup_crvserver_binding', 'clust... |
from pathlib import Path
import typer
from .config import get_settings
from .orm import compile_schema as _compile_schema
app = typer.Typer()
settings = get_settings()
@app.command()
def dev(host: str = settings.host, port: int = settings.port):
"""Run the development server."""
try:
import uvicorn... |
import pyaurorax
import datetime
def main():
# set parameters
start_date = datetime.datetime(2020, 1, 1)
end_date = datetime.date(2020, 1, 10)
program = "trex"
platform = "gillam"
instrument_type = "RGB ASI"
print("Retrieving data products availability with the parameters:")
print(" S... |
import numpy as np
from copy import deepcopy
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from IPython import display
# load MNIST dataset with added padding
def load_mnist_32x32():
# mnist data is by default 28x28 so we add a padding ... |
import numpy as np
from pathlib import Path
from tqdm import tqdm
from multiprocessing import Pool
import functools
import pickle
import scipy.spatial
from .. import logger
from ..settings import DATA_PATH, LOC_PATH
from ..utils.colmap import read_model
from ..utils.io import parse_image_lists
def preprocess_slice(s... |
# Generated by Django 3.1.2 on 2021-08-17 10:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('MyApp', '0022_db_project_user_id'),
]
operations = [
migrations.AddField(
model_name='db_project',
name='global_data... |
import fitsio
import sys
import os
import numpy as np
import glob
class BeamConverter:
def __init__(self, root, thetamax = 90):
self.root = root
self.thetamax = thetamax
def find_single_file(self, pattern, filt = None, ok_if_not_found = False):
pat = os.path.join(self.root,pattern)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def menu(list, question):
for entry in list:
print 1 + list.index(entry),
print ") " + entry
return input(question) - 1
items = [u"корзинка" , u"картина" , u"ваза" , u"абажур" , u"туфля" , u"двери"]
keylocation = 2
keyfound = 0
loop = 1
... |
# Generated by Django 2.1.1 on 2019-01-16 07:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_asset', '0001_initial'),
]
|
if __name__ == "__main__":
numSetA = int(input())
setA = set(map(int, input().split()))
numSetB = int(input())
setB = set(map(int, input().split()))
print(len(setA.intersection(setB)))
|
"""
paddle_predict
"""
import os
import time
import sys
import argparse
import json
import codecs
import numpy as np
import random
import paddle
import paddle.nn.functional as F
from pahelix.model_zoo.protein_sequence_model import ProteinEncoderModel, ProteinModel, ProteinCriterion
from pahelix.utils.protein_tools im... |
import scipy as sp
from scipy.stats import truncnorm
import fitter
import itertools
def solar(nbinaries=1e6):
"""Returns a randomly generated dataset of `nbinaries` solar-type binaries.
These can be used to fit an observed radial velocity distribution or to generate random radial velocity datasets for Monte C... |
#
# Load the libraries that are used in these commands.
#
import subprocess
from core.quicksearch_matchers import contains_chars
from fman import DirectoryPaneCommand, show_prompt, show_quicksearch, QuicksearchItem, show_status_message, clear_status_message, save_json, load_json, show_alert
import os
import json... |
from collections import namedtuple
from leapp import reporting
# Line affected by incompatible NSS configuration
AffectedLine = namedtuple('AffectedLine', 'lineno column module')
def check_modules(lines, blacklist):
'''
Find and return all `lines` that contain an item
from `blacklist` such that the ite... |
# import .Auth
# import .gaonnuri
# import .lms
# import .student
# import .exploit
# # from .Auth import *
# # from .gaonnuri import *
# # from .lms import *
# # from .student import *
# # from .exploit import *
# # from .parserlib import HTMLTableParser
# # from .simplefunctions import download |
import numpy as np
import random
import seaborn as sns
import matplotlib.pyplot as plt
from proglearn.forest import LifelongClassificationForest, UncertaintyForest
from proglearn.sims import *
def get_colors(colors, inds):
c = [colors[i] for i in inds]
return c
def plot_xor_nxor(data, labels, title):
... |
"""Policy that performs a fixed sequence of actions."""
from metarl.np.policies.policy import Policy
class FixedPolicy(Policy):
"""Policy that performs a fixed sequence of actions.
Args:
env_spec (metarl.envs.env_spec.EnvSpec): Environment specification.
scripted_actions (list[np.ndarray] or ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 2 12:42:22 2021
@author: yokoyama
"""
from IPython import get_ipython
from copy import deepcopy, copy
get_ipython().magic('reset -sf')
# get_ipython().magic('cls')
import os
current_path = os.path.dirname(__file__)
os.chdir(current_path)
import sys
fig_save_dir = c... |
# SPDX-FileCopyrightText: Copyright (c) 2020 Dan Halbert for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`_bleio`
=======================================================================
_bleio implementation for Adafruit_Blinka_bleio
* Author(s): Dan Halbert for Adafruit Industries
"""
# pylint: disable... |
from django.apps import AppConfig
class BabarTwitterConfig(AppConfig):
name = 'babar_twitter'
|
# Script collecting absolute paths of all PDF files in a specified directory tree
# Sam Sciolla, Garrett Morton
# SI 699
# This script provides a function for collecting path of all PDF files in the target directory and all its descendants. The script then writes this list to a json file, unless such a file already e... |
#!/usr/bin/python
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Main entry point for toolchain_build buildbots.
Passes its arguments to toolchain_build.py.
"""
import os
import subprocess
i... |
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from .views import UserViewSet
router = DefaultRouter()
router.register(r'users', UserViewSet, basename='users')
urlpatterns = router.urls
|
# Copyright 2021 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
import numpy as np
from numpy import diag, sqrt, hstack, ones, eye
from numpy.linalg import inv
from scipy.linalg import qr, solve_triangular, cholesky, svd
def ols(A, b):
"""
Ordinary Least-Squares Regression
Coefficients Estimation.
This is the linear algebra solution to
OLS; minimising |Ax-b|... |
from setuptools import setup, find_packages
setup(
name='tracker',
version='0.0.1',
description="Progress tracker Library/app for tracking OpenElections metadata",
long_description="Library/app for tracking OpenElections metadata",
author=["Serdar Tumgoren", "Derek Willis"],
author_email='zstum... |
# Copyright 2018 The Cornac Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
'''
ABOUT THIS SCRIPT:
Converts ground-truth from the annotation files
according to the https://github.com/qqwweee/keras-yolo3
or https://github.com/gustavovaliati/keras-yolo3 format.
And converts the predicitons from the annotation files
according to the https://github.com/gustavovaliati/keras-yolo3 format.
'... |
#!/usr/bin/env python
import click
from BALSAMIC.commands.config.case import case_config as case_command
from BALSAMIC.commands.config.pon import pon_config as pon_command
@click.group()
@click.pass_context
def config(context):
"create config files required for running the pipeline."
pass
config.add_comman... |
from odoo import api, fields, models
class CrmLeadConvert2Task(models.TransientModel):
""" wizard to convert a Lead into a Project task and move the Mail Thread """
_name = "crm.lead.convert2task"
_inherit = 'crm.partner.binding'
_description = 'Lead convert to Task'
@api.model
def default_... |
import pypianoroll
import numpy as np
import matplotlib
def metrics_function(mid_path, verbose=True):
multitrack = pypianoroll.read(mid_path)
tracks = multitrack.tracks
N = len(tracks) # N may not be 4 depending on the mid file
N = 4
# 1. empty_beat_rate
empty_beat_rate = np.zeros((N,))
... |
# Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and
# Technical University of Darmstadt.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source ... |
import pytest
from requests.exceptions import HTTPError
from commercetools import types
def test_shipping_method_get_by_id(client):
shipping_method = client.shipping_methods.create(
types.ShippingMethodDraft(
key="test-shipping-method", name="test shipping method"
)
)
assert ... |
# Code to connect the NodeMCU (ESP8266) to a WiFi network.
import network # The network module is used to configure the WiFi connection.
sta_if = network.WLAN(network.STA_IF) # Station interface.
ap_if = network.WLAN(network.AP_IF) # Access point interface.
# Checking if interfaces are active.
"""
Upon ... |
# Copyright (c) Open-MMLab. All rights reserved.
from .io import imfrombytes, imread, imwrite
from .transforms import (bgr2gray, bgr2hls, bgr2hsv, bgr2rgb, gray2bgr,
gray2rgb, hls2bgr, hsv2bgr, imcrop, imdenormalize,
imflip, iminvert, imnormalize, impad,
... |
import ctypes
import sys
import os
import selenium.webdriver
import requests
import datetime
from util import *
import argparse
SK_APPDATA = 'APPDATA'
SK_APPSETTINGS = 'APPSETTINGS'
STORAGEKEY_FILENAME_MAP = {
SK_APPDATA: 'appdata.json',
SK_APPSETTINGS: 'settings.json',
}
'''
retrives
'''
def load_storage():... |
#!/usr/bin/env python
"""
This CLI script will take host AWS account id, guest external id and
the name of a host account IAM role, to obtain temporary AWS service
credentials to execute an AWS Secure Token Service-mediated access
to a Simple Storage Service (S3) bucket given as an argument.
"""
import sys
from json i... |
import os
from helpers.db import add_suggestion
async def suggest(ctx, args):
bug = args[1]
# check if it is in quotes
if len(bug.split(" ")) < 2:
return "Use quotes for sentences with more than one word."
await add_suggestion(ctx.username, ctx.user_id, bug)
return "Suggestion submitted! Yo... |
from __future__ import unicode_literals, print_function, division
import time
import math
import re
import pickle
import unicodedata
from io import open
from random import shuffle
import torch
# import torchtext
# fast_text = torchtext.vocab.FastText(language='en')
SOS_TOKEN = 0
EOS_TOKEN = 1
MAX_LENGTH = 15
eng_pr... |
#!/usr/bin/env python3
from os.path import isfile
import sys
def read_contract(path):
result = ''
with open(path) as f:
lines = f.readlines()
dependencies = [path.rsplit('/', maxsplit=1)[0] + line.strip().split()[1][2:-2]
for line in lines if line.strip().startswith('im... |
from django.conf.urls import url
urlpatterns = [
url(r'^(?P<path>.*)/$', 'django_contract.views.serve', name='serve'),
]
|
"""
Author: Henry Ugochukwu Odoemelem
Created: 4-May-2020
"""
import cv2
import math
import numpy as np
import camV4L
import time
"""
I recommend running camCalib on a windows PC
"""
############### Uncomment this code block to take chessboard images #################################################... |
from twisted.internet import reactor, protocol
from twisted.internet.protocol import ClientFactory as ClFactory
from twisted.internet.endpoints import TCP4ClientEndpoint
# a client protocol
class Client(protocol.Protocol):
def __init__(self):
reactor.callInThread(self.send_data)
def dataReceived(sel... |
from django import forms
from .models import Group, Post, Comment
class PostForm(forms.ModelForm):
def clean_text(self):
cleaned_data = self.clean()
text_validate = cleaned_data.get('text')
duplicate_text = Post.objects.filter(text__contains=text_validate)
if duplicate_text.count... |
import logging
import datetime
from contextlib import contextmanager
import traceback
import sys
# Replace the except hook to make sure exceptions are logged in log files
def logging_except_hook(exception_type, value, traceback):
if __logger is not None:
error("Uncaught exception. ", value)
sys.__exc... |
import json
import numpy as np
from lib.utils.util import check_path, copy_file_to, remove_file
class VisionBuffer(object):
def __init__(self, name, path):
self._file_name = name
self._folder_path = path
self._file_path = self._folder_path / (self._file_name + '.json')
self._buffe... |
import time
import numpy as np
import matplotlib.pyplot as plt
from env_survive.env_survive import EnvSurvive
raw_vision = True
true_hidden = False
different_lr = True
path = './env_survive/mnist'
env = EnvSurvive(path='./env_survive/mnist', seed=0, raw_vision=True)
for i in range(1):
obs = env.reset()
obs_pr... |
#
# PySNMP MIB module A3COM-HUAWEI-L2VPN-PWE3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-L2VPN-PWE3-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:50:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... |
from generic_api import *
# Simple Python wrapper around the SBA Business API.
def build_api_list(list, base):
result = []
for item in list:
result.append((item, base + "/" + item + "/" ))
return result
#These are the function calls that the SBABusinessesAPI object exposes.
list = [ "by_category"
... |
""" Django models utilities"""
from django.db import models
class CRideModel(models.Model):
"""
Comparte Rise base model.
CRideModel acts an abstract base class from each every
other model in the project will inherit. This class provides
every table with the following attributes:
+ created... |
import enum
class FitterType(enum.Enum):
GRADIENT = 0,
NON_GRADIENT = 1
|
from datetime import datetime
n = int(input())
dic = {
"true vampires" : 0,
"early birds" : 0,
"sunny warmers" : 0,
"lunch workers" : 0,
"sunset lovers" : 0,
"prime timers" : 0
}
for i in range(0,n):
entrada = input()
fecha = datetime.strptime(entrada,'%Y-%m-%d %H:%M:%S')
if fec... |
import torch
def sinkhorn(feature1, feature2, pcloud1, pcloud2, epsilon, gamma, max_iter):
"""
Sinkhorn algorithm
Parameters
----------
feature1 : torch.Tensor
Feature for points cloud 1. Used to computed transport cost.
Size B x N x C.
feature2 : torch.Tensor
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Edgar Arturo Haas Pacheco
# @Date: 2015-10-04 19:49:33
from django.contrib.auth.models import AnonymousUser
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.... |
#!/usr/bin/env python
import os
import sys
import argparse
import generalUtils
parser = argparse.ArgumentParser(description='converts sga to bed')
parser.add_argument('-i', nargs='?', type=argparse.FileType('r'), default=sys.stdin, help='input')
parser.add_argument('-o', nargs='?', type=argparse.FileType('w'), default... |
#!/usr/bin/python
from k5test import *
for realm in multipass_realms(create_user=False):
# Test kinit with a keytab.
realm.kinit(realm.host_princ, flags=['-k'])
realm = K5Realm(get_creds=False, start_kadmind=True)
# Test kinit with a partial keytab.
pkeytab = realm.keytab + '.partial'
realm.run([ktutil], inp... |
from models.sql.basemodel import SqlBaseModel
from sqlalchemy import Column, Integer, String, DateTime, Float
from sqlalchemy.sql.expression import func
class SqlModel(SqlBaseModel):
"""
This is the basic class for extensions to put their code
which is relevant for all models of this type.abs
... |
from config import DatasetName, AffectnetConf, InputDataSize, LearningConfig, ExpressionCodesAffectnet
from config import LearningConfig, InputDataSize, DatasetName, RafDBConf, DatasetType
from sklearn.metrics import precision_recall_fscore_support as score
import numpy as np
import os
import matplotlib.pyplot as plt
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.