content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
Fine-grained Classification based on textual cues
"""
# Python modules
import torch
import torch.nn as nn
import time
import torch
import numpy as np
import glob
import os
import json
from PIL import Image, ImageDraw, ImageFile
import torchvision
from torch.autograd import Variable
f... |
import os
import cv2
import numpy as np
from skimage.measure import compare_ssim, compare_psnr
#root = '/home/mengqi/fileserver/results/cross_scale/train-L_HR-L_LR-pix2pix/results_test/1215_0100_nc3/test_latest/images'
root = '/home/mengqi/fileserver/results/cross_scale/train-L_HR-L_LR-cyclegan/results_test/1215_010... |
"""
Implementation of the ABY3 framework.
"""
from __future__ import absolute_import
from typing import Tuple, List, Union, Optional, Callable
import abc
import sys
from math import log2, ceil
from functools import reduce
import numpy as np
import tensorflow as tf
from ...tensor.factory import (
AbstractFactory,
... |
/home/runner/.cache/pip/pool/cf/0a/b5/ca35a000c1454aeb9b61c66b32b1a72ea7d996e4e9c6e8af62a32513d1 |
class Solution:
# 1st solution
# O(n) time | O(n) space
def calculate(self, s: str) -> int:
res, num, sign, stack = 0, 0, 1, []
for ch in s:
if ch.isdigit():
num = 10 * num + int(ch)
elif ch in "+-":
res += sign * num
nu... |
# ### Problem 2
# Prompt the user with the message, ‘Is it better to be rude or kind to People?’
# Keeping prompting the user to enter an answer until they enter the word kind.
# Each time they enter something other than kind, print the message, ‘That’s not the answer I had hoped to hear. Try again.’ and prompt the u... |
class Gen_dummy:
def __init__(self):
self.X_ = None
def fit(self, X, y=None, metamodel=None):
self.X_ = X.copy()
return self
def sample(self, n_samples=1):
return self.X_.copy()
def my_name(self):
return "dummy"
# ==========================================... |
# Copyright (c) 2019 NETSCOUT Systems, Inc.
"""Manage a connection and interface with Equinix Smart Key to manage keys."""
import base64
import json
import logging
import os
import pprint
from builtins import object
import requests
TOKEN_DIR = os.getenv("HOME", default="/tmp")
APP_TOKEN_FILE = os.path.join(TOKEN_DI... |
"""knopy module - some space objects
In this script, some of solar planets' characteristics are defined.
"""
class Planet:
"""Defines a planet.
Attributes
----------
Aphelion: int
Aphelion distance of the planet
Perihelion: int
Perihelion dinstance of the planet
SemiMajorAxis:... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 19 2020
@author: Sergio Llana (@SergioMinuto90)
"""
from pandas import json_normalize
from abc import ABC, abstractmethod
import pandas as pd
import warnings
from statsbombpy import sb
import sbpUtils
warnings.simplefilter(action='ignore', categor... |
from django.shortcuts import render, redirect
from django.urls import reverse
from . import models
# Create your views here.
# /cars/
def show(request):
all_cars = models.Car.objects.all()
context = {'all_cars': all_cars}
return render(request, 'cars/html/show.html', context=context)
def add(request... |
#!/usr/bin/env python
#########################################################################################
#
# Perform various types of processing from the spinal cord segmentation (e.g. extract centerline, compute CSA, etc.).
# (extract_centerline) extract the spinal cord centerline from the segmentation. Output ... |
"""
Summary:
Contains the Conduit unit type classes.
This holds all of the data read in from the conduit units in the dat file.
Can be called to load in the data and read and update the contents
held in the object.
Author:
Duncan Runnacles
Copyright:
Duncan Runnacles 2020
... |
from tkinter import *
class Calculator(Frame):
def __init__(self):
Frame.__init__(self)
self.pack(expand=YES, fill=BOTH)
self.master.title('calculator')
self.master.rowconfigure(0, weight=1)
self.master.columnconfigure(0, weight=1)
self.grid(sticky=W + E + N + S)
... |
#!/usr/bin/env python
# Python script that grabs all the binaries produced when building the
# Sharpmake solution and copies them in a directory. (By default, in a
# directory named /deploy.) Without that script, you need to manually copy
# and paste the binaries of every platform implementation assembly you have
# bu... |
import reapy_boost
if reapy_boost.is_inside_reaper():
from reaper_python import *
# Generated for ReaImGui v0.5.9
|
# Probability of a segmentation =
# Probability(first word) * Probability(rest)
# Best segmentation =
# one with highest probability
# Probability(word)
# estimated by counting
# Eg. Best segmentation("nowisthetime...")
# Pf("n") * Pr("owisthetime...") = .003% * 10^-30% = 10^-34%
# Pf("no") * Pr("wisthetime..."... |
import pyblish.api
class IntegrateAutoRigPublishing(pyblish.api.InstancePlugin):
"""Auto publishing rig when model being published"""
label = "Integrate Auto Rig Publishing"
# This plugin must runs after disk and database integration
order = pyblish.api.IntegratorOrder + 0.499
hosts = ["maya"]
... |
import requests
from requests.exceptions import RequestException
from service_vncorenlp.config_vncorenlp import HOST, PORT, ANNOTATOR
import os
class VnCoreNLP():
def __init__(self):
self.url = f"http://{HOST}:{PORT}"
self.timeout = 30
self.annotators = set(ANNOTATOR.split(","))
if ... |
"""
Code for preprocessing streamflow data.
"""
import collections
import os
from pathlib import Path
from shapely.geometry import Point
import numpy as np
import pandas as pd
from gisutils import shp2df, df2shp, project, get_values_at_points
from mfsetup.obs import make_obsname
from mfsetup.units import convert_volume... |
import uuid
import pytest
from fastapi import UploadFile
from jinad.api.endpoints import flow
_temp_id = uuid.uuid1()
def mock_create_success(**kwargs):
return _temp_id, '0.0.0.0', 12345
def mock_flow_creation_exception(**kwargs):
raise flow.FlowCreationException
def mock_flow_parse_exception(**kwargs):... |
#!/usr/bin/env python
# encoding: utf-8
# Scott Newton, 2005 (scottn)
# Thomas Nagy, 2006 (ita)
"Custom command-line options"
import os, sys, imp, types, tempfile, optparse
import Logs, Utils
from Constants import *
cmds = 'distclean configure build install clean uninstall check dist distcheck'.split()
# TODO remov... |
import torch
import torch.nn as nn
from abc import ABC, abstractmethod
class BaseModel(nn.Module, ABC):
"""Base class for models."""
@abstractmethod
def forward(self, *inputs):
return NotImplemented
def __str__(self):
"""For printing the model and the number of trainable parameters.
... |
from typing import Optional, Tuple
from torch_geometric.typing import Adj, OptTensor, PairTensor
import torch
from torch import Tensor
from torch.nn import Parameter
from torch_scatter import scatter_add
from torch_sparse import SparseTensor, matmul, fill_diag, sum as sparsesum, mul
from torch_geometric.nn.conv import... |
import re
import sys
import traceback
class HandledException(Exception):
def __init__(self, value):
self.value = value
Exception.__init__(self)
def __str__(self):
return repr(self.value)
def json(self):
return self.value['json']
class ExceptionHandler(object):
""" Han... |
#TAREFA 2
#cálculo do gradiente
import numpy as np
def sigmoid(x):
return 1/(1 + np.exp(-x))
def sigmoid_prime(x):
#derivada da função sigmoide
return sigmoid(x) * (1-sigmoid(x))
#taxa de aprendizado
learnrate = 0.5
x = np.array([1, 2, 3, 4])
y = np.array([0.5])#erro
bies = 0.5
#pes... |
import csv
import os
from itemadapter import ItemAdapter
class RecipelinkextractorPipeline:
def process_item(self, item, spider):
path_to_file = item['dir_path'] + "/" + item['title']+".html"
# check if csv file exists
if not os.path.isfile(item['csv_path']):
with open(i... |
__version__ = '1.2.17' |
"""
Driver for CO2 sensor via USB
Intelligent Infrared CO2 Module
(Model: MH-Z19)
"""
import struct
from osgar.node import Node
from osgar.bus import BusShutdownException
class WinsenCO2(Node):
def __init__(self, config, bus):
super().__init__(config, bus)
bus.register('raw', 'co2')
... |
DUMMY_API_KEY = "dummykey"
DUMMY_LOCATION = "DUMMY LOCATION"
class MockSnips(object):
class MockDialogue(object):
def __init__(self):
self._called = False
self._speak_called = False
def speak(self, sentence, session_id):
self._speak_called = True
class Moc... |
from contextlib import contextmanager
import sqlite3 as sql
from sqlite3 import Error
from flask import Flask, render_template, redirect, jsonify, request, send_from_directory
#------------------------------------------------------------#
# Create variable for database file
#----------------------------------------... |
import configparser
import json
import os
conf = {}
default_conf_dir = os.path.join(os.path.expanduser("~"), ".config/fsspec")
conf_dir = os.environ.get("FSSPEC_CONFIG_DIR", default_conf_dir)
def set_conf_env(conf_dict, envdict=os.environ):
"""Set config values from environment variables
Looks for variable ... |
import os
import subprocess
import click
from make_lambda_package import archive
from make_lambda_package import deps
from make_lambda_package import fsutil
from make_lambda_package import scm
@click.command('make-lambda-package')
@click.argument('source',
metavar='<path_or_url>')
@click.option('--re... |
from di_container import DIContainerKeys, inject
from adapter_manager import AdapterManager, AdapterTypes
from display_adapter import DisplayAdapterCalls
class ErrorHandler:
def __init__(self):
self.display_manager = inject(DIContainerKeys.display_manager, AdapterManager)
def new_error(self, error, er... |
CURRENT_PARLIAMENT_VERSION = '151c'
DEBUG = True
# Feature knobs are only intended for incomplete functionality.
FEATURES = {
'PARSE_MARKERS': True,
}
|
""" Profile model. """
# Django
from django.db import models
# Utilities
from cride.utils.models import CRideModel
class Profile(CRideModel):
""" Profile model.
A profile holds a user's public data like biography, picture,
and statistics.
"""
user = models.OneToOneField('users.User', ... |
from tkinter import *
import math
#calc files
class calc:
def getandreplace(self):
self.expression = self.e.get()
self.newtext=self.expression.replace('/','/')
self.newtext=self.newtext.replace('x','*')
def equals(self):
self.getandreplace()
try:
self.value= eval(self.newt... |
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... |
import time
import logging
from pgoapi.exceptions import (ServerSideRequestThrottlingException,
NotLoggedInException, ServerBusyOrOfflineException,
NoPlayerPositionSetException, EmptySubrequestChainException,
UnexpectedResponseException)
from pgoapi.pgoapi import PGoApi, PGoApiRequest, RpcApi
from pgoapi.p... |
import select
import socket
import threading
from typing import List
from common.application_params import PORT, MAX_MSG_LEN
from common.message_frame import MessageFrame
from messages.ping import Ping
from server.middleware import Middleware
class Server(threading.Thread):
def __init__(self, middleware: Middlew... |
import torch
from CLAPPVision.vision.models import FullModel, ClassificationModel
from CLAPPVision.utils import model_utils
def load_model_and_optimizer(opt, num_GPU=None, reload_model=False, calc_loss=True):
model = FullModel.FullVisionModel(
opt, calc_loss
)
optimizer = []
if opt.model_sp... |
'''
Given an array with n integers, you need to find if there are triplets (i, j, k) which satisfies following conditions:
0 < i, i + 1 < j, j + 1 < k < n - 1
Sum of subarrays (0, i - 1), (i + 1, j - 1), (j + 1, k - 1) and (k + 1, n - 1) should be equal.
where we define that subarray (L, R) represents a slic... |
from os import environ
KCB_PASSWORD_GENERATOR_SIZE = int(environ.get(
"KCB_PASSWORD_GENERATOR_SIZE", 32))
KCB_AWS_REGION_NAME = environ.get("KCB_AWS_REGION_NAME", "us-east-1")
|
from django import VERSION as DJANGO_VERSION
from django.db import connection, transaction
from django.test import SimpleTestCase
from django_hstore.fields import HStoreDict
from django_hstore_tests.models import DataBag
class TestNotTransactional(SimpleTestCase):
allow_database_queries = True
if DJANGO_VE... |
import string, sys, os, getopt
from os.path import *
units = 'b'
def print_path (path, bytes):
if units == 'k':
print '%-8ld%s' % (bytes / 1024, path)
elif units == 'm':
print '%-5ld%s' % (bytes / 1024 / 1024, path)
else:
print '%-11ld%s' % (bytes, path)
def dir_size (start, follow_links, my_depth, max_dept... |
# Macro for BUG #11065. This makes it possible to show the grid for a dataset in
# the background.
try: paraview.simple
except: from paraview.simple import *
paraview.simple._DisableFirstRenderCameraReset()
spcth_0 = GetActiveSource()
ExtractSurface2 = ExtractSurface()
DataRepresentation5 = Show()
DataRepresentation5.... |
import logging
from enum import Enum
import requests
from back_office.config import ENVIRONMENT_TYPE, SLACK_ENRICHMENT_NOTIFICATION_URL, EnvironmentType
class SlackChannel(Enum):
ENRICHMENT_NOTIFICATIONS = 'ENRICHMENT_NOTIFICATIONS'
def slack_url(self) -> str:
if self == self.ENRICHMENT_NOTIFICATIO... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 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.
"""Serializer tests."""
from __future__ import absolute_import, print_function
from... |
import configparser
def bootPropsConfig(artifact, resources, targetDir, scalaVersion = "2.13.1"):
"""Create the configuration to install an artifact and its dependencies"""
scala = {}
scala["version"] = scalaVersion
app = {}
app["org"] = artifact.org
app["name"] = artifact.name
app["versi... |
#!/usr/bin/env python
# encoding: utf-8
"""
@version: v1.0
@author: Shijie Qin
@license: Apache Licence
@contact: qsj4work@gmail.com
@site: https://shijieqin.github.io
@software: PyCharm
@file: xmlrpc.py
@time: 2018/11/8 3:16 PM
"""
import xmlrpc.client
class XmlRpc:
@staticmethod
def connection(... |
import db
import add_idea
class MigrationManager:
def __init__(self, pen):
self.pen = pen
def run(self, to_version, name, data):
curr_version = data['version'] if 'version' in idea else 0
next_version = curr_version + 1
# already that version or newer
if curr_version >... |
# File automatically generated by mapry. DO NOT EDIT OR APPEND!
"""parses JSONable objects."""
import collections
import typing
import some.graph
import some.graph.parse
def some_graph_from(
value: typing.Any,
ref: str,
errors: some.graph.parse.Errors
) -> typing.Optional[some.graph.SomeG... |
import os
from os.path import exists, isfile, join
import sys
from langtests.c_test import runCTests
langFlags = {
"-c": "Run tests for the C language, requires additional argument for executable",
"-j": "Run tests for the Java language, requires additional argument for java file"
}
helpFlags = {
"-r": "R... |
#!/usr/bin/env python3
import os
def parse_csv():
with open("SPEAKERS.TXT") as f:
for line in f.readlines()[1:]:
line = line.strip()
array = line.split("\t")
if len(array) == 8:
yield int(array[1].strip()), array[6].strip()
def move_files(id: int, gend... |
name = zhangsan
this is zhangsan
|
"""
Adapted from https://github.com/simbilod/optio
SMF specs from photonics.byu.edu/FiberOpticConnectors.parts/images/smf28.pdf
MFD:
- 10.4 for Cband
- 9.2 for Oband
"""
import hashlib
from typing import Any, Dict, Optional
import meep as mp
import numpy as np
from gdsfactory.serialization import clean_value_name... |
from .mobile_robot_env import *
MAX_STEPS = 1500
class MobileRobot2TargetGymEnv(MobileRobotGymEnv):
"""
Gym wrapper for Mobile Robot environment with 2 targets
WARNING: to be compatible with kuka scripts, additional keyword arguments are discarded
:param urdf_root: (str) Path to pybullet urdf files
... |
# coding: utf-8
# #### Importing libraries
# In[6]:
from skimage.io import imread
from skimage.color import rgb2gray
import numpy as np
from matplotlib import pyplot as plt
# #### 1. Test the MATLAB image functions to read, display, and write images. Use buckeyes_gray.bmp and buckeyes_rgb.bmp from the class webp... |
#
# _/_/_/ _/_/_/ _/_/_/ _/_/_/ _/ _/ _/_/_/
# _/ _/ _/ _/ _/ _/ _/ _/ _/
# _/_/_/ _/_/_/ _/ _/ _/_/ _/_/
# _/ _/ _/ _/ _/ _/ _/ _/ _/
# _/_/_/ _/ _/ _/_/_/ _/_/_/ _/ _/ _/_/_/
#
# By Vlad Ivano... |
"""Security configuration for our Pyramid application."""
import os
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.security import Everyone, Authenticated, Allow
from pyramid.session import SignedCookieSessionFactory
from passlib.apps... |
# Python - 3.6.0
Test.it('Basic tests')
Test.assert_equals(solve('1 2 36 4 8', 2), 16)
Test.assert_equals(solve('1 2 36 4 8', 3), 8)
Test.assert_equals(solve('1 2 36 4 8', 4), 11)
Test.assert_equals(solve('1 2 36 4 8', 8), 4)
|
# pylint: disable=attribute-defined-outside-init
import unittest
from tests import vcr
from corkus import Corkus
from corkus.objects import PartialIngredient, ProfessionType, LogicSymbol, IdentificationType
from corkus.errors import BadRequest
class TestIngredient(unittest.IsolatedAsyncioTestCase):
async def asyn... |
from flask import render_template
from . import auth
@auth.app_errorhandler(404)
def fourOfour(error):
'''
view function that renders 404 error page when there is a 404 error in the app
'''
return render_template('fourofour.html'),404
|
import os
import os.path
import yaml
import terminal
from manifests import io
from manifests.deploymanifest import DeployManifest, DeployManifestArtifact, DeployManifestProcess
from manifests.errors import ReadManifestError
DEFAULT_MANIFEST_FILENAME = "deploy.yml"
def make_manifest_path(root_dir: str=None, filename:... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2020-02-05 11:03
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('questionnaires_manager', '0001_initial'),
]
operations = [
migrations.RenameField(... |
import logging
import numpy as np
import pytest
from sklearndf.classification import RandomForestClassifierDF
from sklearndf.pipeline import ClassifierPipelineDF, RegressorPipelineDF
from sklearndf.regression import RandomForestRegressorDF
from ..conftest import check_ranking
from facet.data import Sample
from facet... |
import libjevois as jevois
import cv2
import numpy as np
## Simple example of image processing using OpenCV in Python on JeVois
#
# This module is a basic FRC vision process.
#
# By default, it first gets an image, blurs it, extracts the green channel, thresholds that, and uses the threshold to place
# a mask over the... |
#!/usr/bin/python
#coding:utf-8
import os
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
# 从 Info.plist 中读取 QMUIKit 的版本号,将其定义为一个 static const 常量以便代码里获取
infoFilePath = str(os.getenv('SRCROOT')) + '/WXiOSCommonUtils/Info.plist'
infoTree = ET.parse(infoFilePath)
infoD... |
import datetime, sys
from os.path import *
MIT = """
The MIT License (MIT)
Copyright (c) %04d Jake Lussier (Stanford University)
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 restricti... |
import os
from os.path import join
from time import sleep
from tqdm import tqdm
import numpy as np
import pandas as pd
import gzbuilder_analysis.parsing as pg
import gzbuilder_analysis.aggregation as ag
# from shapely.affinity import scale
# from descartes import PolygonPatch
from PIL import Image
import argparse
loc ... |
import os
from collections import defaultdict
import tensorflow as tf
import numpy as np
import pdb
class Agent:
def __init__(self, name, sess, num_slots):
self.name_ = name
self.sess = sess
self.num_distractors_ = 2 ** num_slots
self.num_slots_ = num_slots
################
# Placeholders #
#########... |
#!/usr/bin/env python3
""" A Python script that displays the lyrics to the currently playing song on
Spotify in your terminal.
File name: spotify-lyrics.py
Author: Caleb Hamilton
Website: https://github.com/cjlh/spotify-lyrics
License: MIT
Python version: 3
Usage:
$ python spotify-lyrics.py
"""
import argparse
i... |
from django.db import models
from django.contrib.auth.models import User
from backoffice.models import Topic
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
interests = models.ManyToManyField(Topic, related_name="subscriptions", blank=True)
def __str__(self):
... |
# Adapted from https://github.com/aam-at/cpgd
import math
from functools import partial
from typing import Optional
import torch
from torch import Tensor, nn, optim
from torch.autograd import grad
from torch.nn import functional as F
from adv_lib.distances.lp_norms import l0_distances, l1_distances, l2_distances, lin... |
import logging
import os
from argparse import ArgumentParser
from datetime import date, datetime
from telegram import *
from telegram.ext import *
import settings
from utils import History, convert_date
logger = logging.getLogger(__name__)
class Stop(Exception):
pass
# get date from message text if any
def g... |
import pandas as pd
import numpy as np
import psycopg2
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold
import Constants
import sys
from pathlib import Path
output_folder = Path(sys.argv[1])
output_folder.mkdir(parents = True, exist_ok = True)
conn = psycopg2.connect('dbname=mimic user=haoran... |
from collections import defaultdict
import torch
import torch.nn as nn
from mighty.monitor.accuracy import AccuracyEmbedding
from mighty.trainer import TrainerEmbedding, TrainerGrad
from mighty.utils.common import batch_to_cuda, clone_cpu
from mighty.utils.data import DataLoader
from mighty.utils.stub import Optimize... |
# ---
# jupyter:
# jupytext:
# cell_markers: '{{{,}}}'
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Jupyter notebook
#
# This notebook is a simple jupyter notebook. It only has markdown and code cells. And it does not contain consecutive markdown cells. We sta... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
names = [
'Abeguwo', 'Abere', 'Adaro', 'Adi', 'Mailagu', 'Afekan', 'Agunua', 'Ahoeitu', 'Tupuai', 'Aiaru', 'Aku', 'Muki',
'Alalahe', 'Alilmenehune', 'Aluelop', 'Aluluei', 'Ao', 'Kahiwahiwa', 'Kanapanapa', 'Nue', 'Pakarea', 'Potano',
'Pour', 'Ro... |
import cv2
import mediapipe as mp
from mediapipe.framework.formats import landmark_pb2
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_face_mesh = mp.solutions.face_mesh
class FaceMeshPreview:
def __init__(self):
self.feature_drawing_spec = mp_drawing.DrawingSpe... |
from pathlib import Path
import os
import yaml
import command
class Config(object):
def __init__(self, directory, filename = '.exec-helper'):
self._settings_file = Path(directory).joinpath(filename)
self._directory = directory
self._commands = dict()
self._patterns = set()
... |
import pickle, os
import thorpy
from mapobjects.objects import MapObject
def ask_save(me):
choice = thorpy.launch_binary_choice("Do you want to save this map ?")
default_fn = me.get_fn().replace(".map","")
if choice:
fn = thorpy.get_user_text("Filename", default_fn, size=(me.W//2,40))
fn +=... |
from django import forms
from enrollment.models import Servicio
from enrollment.models import TipoServicio
from enrollment.models import Matricula
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django.forms import ModelForm, Form
from utils.models import TiposNivel
from django.ut... |
import numpy as np
import cv2 as cv
flann_params= dict(algorithm = 6,
table_number = 6, # 12
key_size = 12, # 20
multi_probe_level = 1) #2
def init_feature():
"""initialize feature detector and matcher algorithm
"""
detector = cv.ORB_create(300... |
''' Register rule-based models or pre-trianed models
'''
from rlcard.models.registration import register, load
|
# -*- coding: utf-8 -*-
from enum import IntFlag
from enum import unique
from utils.misc import escape_enum
from utils.misc import pymysql_encode
__all__ = ('ClientFlags',)
@unique
@pymysql_encode(escape_enum)
class ClientFlags(IntFlag):
# NOTE: many of these flags are quite outdated and/or
# broken and are ... |
import os
from django.contrib import messages
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.sites.shortcuts import get_current_site
from django.template.loader import render_to_string
from django.utils.http import urlsafe_base64_encode, u... |
# views.team.team
from flask import redirect, url_for, request, flash
from app.forms import CreateTeam as CreateTeamForm
from app.util import session as session_util, team as team_util
from .team import TeamView
class CreateTeamView(TeamView):
"""Create a team.
"""
def get_form(self):
return C... |
from flask import Blueprint
sc = Blueprint('sc', __name__, url_prefix='/sc')
from . import veiw |
"""!
This module contains code to estimate effective spring constants
of particles in crystals.
\ingroup lammpstools
"""
import lammpstools, dumpreader
import sys, os, numpy as np
def get_einstein_approx( d, ids, T, dims, alpha = 0.9, silent = True ):
""" ! Attempts to extract the chemical potential by determi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.AssetBomAttribute import AssetBomAttribute
from alipay.aop.api.domain.AssetBomItem import AssetBomItem
class AssetBom(object):
def __init__(self):
self._asset_sub_typ... |
# SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""Pin definitions for the STM32MP157C Development Kit 2."""
from adafruit_blinka.microcontroller.stm32.stm32mp157 import pin
D2 = pin.PA12
D3 = pin.PA11
D4 = pin.PA8
D5 = pin.PG2
D6 = pin.PH11
D7 = pin.PF... |
## this file is generated from settings in build.vel
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
# from options["setup"] in build.vel
config = %(setup)s
setup(**config)
|
# wrong version https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/her/README.md
# right version https://github.com/DLR-RM/stable-baselines3/blob/c41368f2ead24c0cea218164c19e58d48a47422c/docs/modules/her.rst
# her sb3 config https://stable-baselines3.readthedocs.io/en/master/mod... |
import os
import sys
base = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../')
sys.path.append(base)
import click
import glob
import subprocess
from collections import OrderedDict
from external.dada.flag_holder import FlagHolder
from external.dada.logger import Logger
from scripts.plot import plot
... |
import os
import git
import dvc
import dvc.repo
import numpy as np
import subprocess
import argparse
def create_fix_demo_stages(path):
os.makedirs(path)
os.chdir(path)
gitrepo = git.Repo.init()
dvcrepo = dvc.repo.Repo.init()
# TODO: the first stage needs also a dependency !!!
subprocess.call(... |
from collidoscope import Collidoscope
from vharfbuzz import Vharfbuzz
from fontTools.ttLib import TTFont
import sys
from argparse import ArgumentParser
import warnings
import re
from termcolor import colored
from stringbrewer import StringBrewer
parser = ArgumentParser(description="Shaping regression tests")
parser.a... |
from random_words import RandomWords, RandomNicknames
import requests
import socket
import hashlib
import json
import os
from .config import server_ip, server_port, listening_port
class IpExchange:
def __init__(self):
self.server_url = f'http://{server_ip}:{server_port}'
self.rw = RandomWords()
... |
# Copyright 2017 The TensorFlow 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 appl... |
import pyjion
import unittest
import gc
class RecursionTestCase(unittest.TestCase):
def setUp(self) -> None:
pyjion.enable()
def tearDown(self) -> None:
pyjion.disable()
gc.collect()
def test_basic(self):
def _f():
def add_a(z):
if len(z) < 5:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.