content stringlengths 5 1.05M |
|---|
from threading import Semaphore
import threading, random
from arg import args
from profe import profesor,Materias,profesores
mutexP = [Semaphore(1) for i in range(args.profeso)]
listA = [Semaphore(0) for i in range(args.profeso)]
contadorA= 0
mutexC= Semaphore(1)
class Alumno(threading.Thread):
def __init__(self,... |
from datetime import date
history_date = {'上期标准仓单交易正式上线': [date(2018, 5, 28), date(2018, 6, 1)],
'中东局势动荡': [date(2018, 4, 10), date(2018, 4, 20)],
'中国对美国加征关税': [date(2018, 4, 4), date(2018, 4, 11)],
'美国再次开启贸易战': [date(2018, 6, 15), date(2018, 6, 30)],
'中美... |
#!/usr/bin/env python
"""
BehaviorModule
^^^^^^^^^^^^^^
.. moduleauthor:: Martin Poppinga <1popping@informatik.uni-hamburg.de>
Starts the body behavior
"""
import actionlib
import os
import rospy
from geometry_msgs.msg import PoseWithCovarianceStamped
from tf2_geometry_msgs import PoseStamped
from humanoid_league_ms... |
# https://adventofcode.com/2018/day/6
def dist(a,b):
return abs(b[0]-a[0]) + abs(b[1]-a[1])
def find_single_closest(x,y, points):
closest_points = []
closest_dist = -1
for p in range(len(points)):
d = dist(points[p], (x,y))
if d < closest_dist or closest_dist == -1:
closest... |
import eventlet
import eventlet.event
import logging
logger = logging.getLogger(__name__)
class GreenletRace:
def __init__(self, tasks):
self._event = eventlet.event.Event()
self._tasks = [eventlet.spawn(self._wrap, fn) for fn in tasks]
def _resolve(self, value=None):
if not self._ev... |
import pytest
from ceph_deploy.cli import get_parser
SUBCMDS_WITH_ARGS = ['push', 'pull']
class TestParserConfig(object):
def setup(self):
self.parser = get_parser()
def test_config_help(self, capsys):
with pytest.raises(SystemExit):
self.parser.parse_args('config --help'.split... |
import sqlite3
import os
import random, string
def randomword(length):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(length))
class DBWrapper:
def __init__(self):
self.dbname = randomword(16) + ".db"
os.system("touch " + self.dbname)
self.conne... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Course :
GTI770 — Systèmes intelligents et apprentissage machine
Project :
Lab # X - Lab's name
Students :
Names — Permanent Code
Group :
GTI770-H18-0X
"""
from __future__ import division, print_function, absolute_import
import tensorflow as tf
imp... |
# coding=utf-8
from argparse import ArgumentParser
import os
from torchvision import models
import cv2
import torch
import shutil
from torchvision import transforms as T
from torch.autograd import Variable
car_label = ["GMC_SAVANA", "Jeep(进口)_大切诺基(进口)", "Jeep(进口)_牧马人", "Jeep(进口)_自由侠(海外)", "MINI_MINICOUNTRYMAN", "smart... |
# adjuster.py Demo of Adjusters linked to Labels
# Released under the MIT License (MIT). See LICENSE.
# Copyright (c) 2021 Peter Hinch
# hardware_setup must be imported before other modules because of RAM use.
import hardware_setup # Create a display instance
from gui.core.ugui import Screen, ssd
from gui.widgets.l... |
from copy import copy
NL_type = 'NEWLINE'
INDENT_type = 'INDENT'
DEDENT_type = 'DEDENT'
PAREN_OPENERS = 'LPAR', 'LBRACE', 'LSQB'
PAREN_CLOSERS = 'RPAR', 'RBRACE', 'RSQB'
class Tok():
def __init__(self, type=None, value=None, lexer=None):
self.type = type
self.value = value
self.lineno = N... |
import numpy as np
import matplotlib.pyplot as plt
import os
import glob
def matlab_multiply(Array_A, Array_B):
'''perform matlab style matrix multiplication with
implicit expansion of dimesion'''
assert np.ndim(Array_A)==1 & np.ndim(Array_B)==1
NewArray = np.zeros((len(Array_B), len(Array_A)))
fo... |
from .run import _reifiers
from .unify import _converters, _occurs_checkers, _unifiers
def register(key, *, convert=None, unify=None, occurs=None, reify=None):
if convert:
_converters.add(key, convert)
if unify:
_unifiers.add(key, unify)
if occurs:
_occurs_checkers.add(key, occurs)... |
# -*- coding: utf-8 -*-
"""
:Author: Jaekyoung Kim
:Date: 2018. 8. 24.
"""
from unittest import TestCase
from pandas.util.testing import assert_frame_equal
from ksif import *
class TestBenchmark(TestCase):
def test_benchmark(self):
pf = Portfolio()
# The return of Portfolio.benchmark should be... |
from collections import Counter
from datetime import datetime
import os
import requests
from subprocess import Popen, PIPE
from pathlib import Path
import json
from typing import Dict, Union, TYPE_CHECKING
from kipoi_utils.external.torchvision.dataset_utils import download_url
if TYPE_CHECKING:
import zenodoclien... |
"""Nearly empty __init__.py to keep pylint happy."""
from __future__ import annotations
|
from Rules import Rules
import random
import copy
class Montecarlo:
def __init__(self, n=1000):
self.iterations = n
self.game = Rules()
def gameOver(self):
winner = self.game.get_winner(end=True)
if winner == 1:
print('AI Winner')
elif winner == 0:
... |
import sys
import re
import os
from setuptools import setup
from setuptools import find_packages
PY_VER = sys.version_info
if PY_VER < (3, 6):
raise RuntimeError("asynceth doesn't support Python version prior 3.6")
install_requires = [
'regex',
'ethereum',
'eth_abi>=2.0.0-beta.1'
]
tests_require = [... |
from hashlib import md5
from os.path import join, dirname, exists, samefile
from os import walk, unlink, chmod, rename, link, symlink, stat
from logging import info, error
from tempfile import mktemp
from stat import S_ISREG, S_IWUSR
class Database(dict):
def add(self, path, size, ino, dev, mtime):
# dev... |
# Run this if you want to see that a simple network can be set up and left idle
# Just tries to make a CH and a CM and have them connect to each other
import CM,CH
import time
from common import handlers
if __name__ == "__main__":
head = CH.ClusterHead(CH.UDPHandler,CH.TCPHandler,spoofContract=True)
mem = CM.C... |
nome=input('Digite o nome do aluno: ')
n1=float(input('Digite a nota da primeira prova: '))
n2=float(input('Digite a nota da segunda prova: '))
n3=float(input('Digite a nota da terceira prova: '))
nt=(n1+n2+n3)
md=(nt/3)
print('A nota final do aluno(a) {} foi de {:.2f}.'.format(nome,md))
|
import tensorflow as tf
def model_softmax(x,batch_size,total_speakers):
print('I/P shape ',x.get_shape())
x=tf.reshape(x,[batch_size,-1,64,1])
with tf.variable_scope('conv2D_A'):
x=tf.layers.conv2d(x,filters=32,kernel_size=5, strides=(2,2),padding='SAME',kernel_initializer=tf.contrib.layers.x... |
# (C) Datadog, Inc. 2022-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
# This file is autogenerated.
# To change this file you should edit assets/configuration/spec.yaml and then run the following commands:
# ddev -x validate config -s <INTEGRATION_NAME>
# ddev -x va... |
import datetime
import logging
from typing import Any, Dict, Optional, List, Generic, TypeVar
from urbanairship import common, Airship
logger = logging.getLogger("urbanairship")
ChannelInfoType = TypeVar("ChannelInfoType", bound="ChannelInfo")
class ChannelInfo(object):
"""Information object for iOS, Android, ... |
import requests
import os
from forms.utils import get_config_dict, send_message
def create_formatted_message(response, breaks='\n'):
config = get_config_dict(response['Config'])
question_mapping = {}
for count, question in enumerate(config['questions'], 1):
question_mapping[question['title']] = ... |
import tkinter as tk
import mysql.connector
import tkinter.font as tf
from tkinter import *
def search_user_account():
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="aniket123",
database='project_dbms'
)
mycursor = mydb.cursor()
... |
# Demonstration of a magnifier on a map
import simplegui
# 1521x1818 pixel map of native American language
# source - Gutenberg project
image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/gutenberg.jpg")
# Image dimensions
MAP_WIDTH = 1521
MAP_HEIGHT = 1818
# Scal... |
def call(g):
next(g)
|
import sys
Height = 48
Width = 128
def is_too_far(cell):
dist_sqrt = cell.real*cell.real + cell.imag * cell.imag
return dist_sqrt > 4
def iterations(x,y):
c = complex(x,y)
z = 0
for i in range(0,250):
if is_too_far(z):
return i
z = z*z + c
return 256
def plot():
start_posX = -3.0
end_posX = 1.0
... |
############################################################
# -*- coding: utf-8 -*-
#
# # # # # # #
# ## ## # ## # #
# # # # # # # # # # #
# # ## # ## ## ######
# # # # # # #
#
# Python-based Tool for interaction with the 10micron mounts
# GUI with PyQT5 fo... |
import string
import re
import nltk
class LimpiadorDeTexto():
def __init__(self,dir_stopwords):
"""
Inicializa y carga lista de stopwords desde el path recibido
"""
arc = open(dir_stopwords, "r", encoding='utf-8')
self.stp_wrds = [line.strip() for line in arc]
... |
import requests
import facebook
from Reposter.utils.logger import logger
import urllib.request
import os
class PostSubmitter:
def __init__(self, page_id,
token,
message=False):
self.page_id = page_id
self.oauth_access_token = token
self.message = message
... |
import textwrap
import wx
from utils.logger import get_logger
from utils.utils import SetIcon2Frame
logger = get_logger(__name__)
class QRcodeFrame(wx.Frame):
def __init__(self, image, meeting_dict, *args, **kwds):
self.image = image
self.config = args[0].config
self.icon_path = args[0].... |
"""This script deletes all duplicate sentences in a parallel corpus of two languages, L1 and L2. A sentence is considered
to be duplicate if the same string appears in L1 in two lines and if in the same two lines in L2, the strings are also the
same (with regard to each other only in L2). This means if the L1 corpus e... |
""" dmt/data/loading/oto_loader.py
OTO = OneToOne. Meaning 1 subject loads exactly 1 batch example.
Daemon loader wraps torch's Dataloader by continuously loading into a queue.
'Daemon' here refers to its original software interpretation (not Python's)
where a process works continuously in the background.
Added Func... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:Mod: test_package_pool
:Synopsis:
:Author:
servilla
:Created:
7/26/20
"""
from dateutil import tz
from pathlib import Path
import pytest
from sniffer.config import Config
from sniffer.package.package_pool import PackagePool
ABQ_TZ = tz.gettz("America/De... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Django Markdownx documentation build configuration file, created by
# sphinx-quickstart on Fri Mar 10 22:41:38 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in ... |
"""
Since our development environment is controlled completely by passing
environment variables from one process to its children, in general we allow all
variables to flow freely. There are, however, a few circumstances in which we
need to inhibit this flow.
Maya and Nuke, for example, add to the :envvar:`python:PYTH... |
import os
import time
def os_walk(folder_dir):
for root, dirs, files in os.walk(folder_dir):
files = sorted(files, reverse=True)
dirs = sorted(dirs, reverse=True)
return root, dirs, files
def time_now():
'''return current time in format of 2000-01-01 12:01:01'''
return time.strft... |
from setuptools import find_packages, setup
with open('README.md', encoding='utf-8') as f:
long_description = f.read()
setup(
name='RailgunS',
version='0.56',
author='NY',
author_email='nyssance@icloud.com',
description='Only My Railgun',
long_description=long_description,
long_descr... |
from django import forms
from loginApp.models import User, Profile
class smsForm(forms.ModelForm):
field_10_student = forms.MultipleChoiceField(required=False, label='دانش آموزان پایه دهم')
field_10_mom = forms.MultipleChoiceField(required=False, label='مادر دانش آموزان پایه دهم')
field_10_dad = forms.Mul... |
#!/usr/bin/env python
# -*-coding:utf8 -*-
'''
合并webface数据集和vggface2数据集
注意相同类别的进行合并
'''
import os
from PIL import Image
def read_overlap(file):
# 读取overlap文档,输出对应的dict
simi_dict = {}
with open(file, 'r') as f:
alllines = f.readlines()
for line in alllines:
line_split = line.str... |
import numpy as np
import math
c = 2.9979 * pow(10,8)
#Practice test question 1 Type
def MagneticField():
dielecConst = float(input("Input the Dielectric Constant: "))
Speed = (c / math.sqrt(dielecConst)) * pow(10,-8)
print("Speed:", Speed , "x10^8 m/s")
MagneticField()
|
# -*- coding: utf-8 -*-
import maths.parser
import util.html
from .AstNode import *
from .IdentifierNode import *
from .NumberNode import *
from .StringNode import StringNode
class BinOpNode(AstNode):
"""Binary (two operands) operator node
left -- left operand (AstNode)
right -- right operand (AstNode... |
import sys
import unittest
import mock
from datetime import datetime
import json
from .messages import HipchatMessage
def setup_mock_request(mock_method, status_code, json_data):
mock_response = mock.Mock()
mock_response.read.return_value = json.dumps(json_data)
mock_response.getcode.return_value = status... |
class ColourImage(object):
def __init__(self,r,g,b):
self.r=r
self.g=g
self.b=b
def _determineColorValue(self):
return str("#%02x%02x%02x" % (self.r, self.g, self.b))
# return ("hello")
|
#!/usr/bin/env python
import os
import socket
import requests
server = os.environ.get("RATSERVER", "localhost")
port = os.environ.get("RATPORT", "8000")
username = os.environ.get("USER", "")
hostname = socket.gethostname()
data = {
"user": username,
"host": hostname,
}
def rat(message):
data["message... |
import tensorflow as tf
from layers import SparseDense, KWinner, SparseConv2D
def dense_mlp():
inputs = tf.keras.Input(shape=(784,))
dense1 = tf.keras.layers.Dense(128, activation='relu')(inputs)
dense2 = tf.keras.layers.Dense(64, activation='relu')(dense1)
logits = tf.keras.layers.Dense(10)(dense2)
... |
from .base import SampleExtension
from application.src.misc.health import ReceivedTreatment, PriorInfection
class PatientTreatment(SampleExtension):
submit_table_name = "samples_patient_treatment"
clean_keys_strings = ["date_of_prior_antiviral_treat",
"date_of_prior_sars_cov_2_infe... |
# coding:utf-8
import time
from util.tools import *
from util.city import *
from search import Search
from comment import Comments
from exception import InvalidCityUrl
from util.http import send_http
from util.thread import CrawlThread
from decorator.city import recover, \
has_id, has_city_list, map_required
from d... |
def item_already_equipped(lingo, item):
if item == 'streak_freeze':
return lingo.__dict__['user_data'].__dict__['tracking_properties']['num_item_streak_freeze']
if item == 'rupee_wager':
return lingo.__dict__['user_data'].__dict__['tracking_properties']['has_item_rupee_wager']
def process_singl... |
"""
This modul contains benchmark script testing performance of modul cevast.certdb.cert_file_db
Run as:> python3 -m cProfile -s calls cert_file_db.py {storage} {10000_certs.gz} {CPUs} > profiles/{commit}_cert_file_db_CPUs
"""
import sys
import time
import shutil
import cevast.dataset.unifiers as unifier
from cev... |
print("Initializing...") |
import mock
import pytest
from utils.objects import immutable
from utils.objects import get_attr
class ObjectsTestCase(object):
@pytest.fixture
def simple_object(self):
return mock.Mock(
first=mock.sentinel.FIRST,
second=mock.Mock(
first=mock.sentinel.SECOND,
... |
# -*- coding: utf-8 -*-
"""
pytest-pylint
=============
Plugin for py.test for doing pylint tests
"""
from setuptools import setup
setup(
name='pytest-pylint',
description='pytest plugin to check source code with pylint',
long_description=open("README.rst").read(),
license='MIT',
version='0.18.0'... |
#!/usr/bin/env python
# Copyright (c) 2014, Tully Foote
# 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, ... |
import tempfile
import webbrowser
TEMPLATE_FILENAME = 'templates/color_sample.html'
class Page:
def __init__(self):
self.baseHtml = self._get_base_html()
@staticmethod
def _get_base_html():
with open(TEMPLATE_FILENAME, 'r') as templateFile:
return templateFile.read()
def... |
#
# Embed a photo data inside a Tk frame
#
import tkinter as tk
import smimgpng as smimg
AUTHOR = "Alexandre Gomiero de Oliveira"
REPO = "https://github.com/gomiero/bin2src"
class App(tk.Frame):
def __init__(self, master):
super().__init__(master)
self.config(width=427, height=640)
canvas ... |
# necessary packages
import cv2
import imutils
class AspectAwarePreprocessor:
def __init__(self, width, height, inter=cv2.INTER_AREA):
# store the target image width, height, and interpolation
self.width = width
self.height = height
self.inter = inter
def preprocess(self, imag... |
# Databricks notebook source
dbutils.widgets.text("infilefolder", "", "In - Folder Path")
infilefolder = dbutils.widgets.get("infilefolder")
dbutils.widgets.text("loadid", "", "Load Id")
loadid = dbutils.widgets.get("loadid")
# COMMAND ----------
import datetime
# For testing
# infilefolder = 'datalake/data/lnd/201... |
import torch
import torchvision.transforms as transforms
import torchvision
from tqdm import tqdm
from torch.quantization import QuantStub, DeQuantStub
import torch.nn as nn
import torchvision.models as models
transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5,... |
"""
Write a client program permutation.py that takes an integer k
as a command-line argument; reads a sequence of strings from
standard input, and prints exactly k of them, uniformly at
random. Print each item from the sequence at most once.
"""
import sys
from deque import RandomizedQueue
if __name__ == "__main__"... |
#!/usr/bin/env python
# coding: utf-8
###############################################################################
# PARAMETERS
#
# change these values to change the protocol behavior
#
###############################################################################
# doesn't matter which units (uM or ug/mL)
# as l... |
"""
Quick plot of the dam break outputs
"""
import anuga.utilities.plot_utils as util
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as pyplot
from numpy import ones, zeros
p_st = util.get_output('immersed_bump.sww')
p2_st=util.get_centroids(p_st)
v = p2_st.y[10]
v2=(p2_st.y==v)
#p_dev = ... |
"""Integration tests module.
"""
from revived.action import action
from revived.action import ActionType
from revived.reducer import combine_reducers
from revived.reducer import Module
# from revived.reducer import reducer
from revived.store import ActionType as StoreAT
from revived.store import Store
#
# Building rev... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
class OrderStatusName(models.CharField):
def __init__(
self,
verbose_name=_('Name'),
max_length=255,
*args, **kwargs):
super(OrderStatusName, self).__init__(
... |
from wsrpc.websocket.handler import WebSocketRoute, WebSocket, WebSocketThreaded
|
#
# Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list o... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2014, 2015 Robert Simmons
#
# This file is part of PlagueScanner.
#
# PlagueScanner 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... |
def load_assets():
assets = {}
# background do jogo
assets['background'] = pygame.image.load(r'img\spacebg.jpg').convert()
assets['background']= pygame.transform.scale(assets['background'],(largura,altura))
# tela inicial
assets['tela_init'] = pygame.image.load(r'img\screen_start1.png').... |
import os
from ...helpers import DIV
PRELOADER = DIV(
DIV(
DIV(
DIV(
DIV(_class="phanterpwa_square"),
_class="phanterpwa_square_container"
),
_class='preloader-wrapper enabled'
),
_class="phanterpwa-preloader-wrapper"),
... |
# Copyright (C) 2015-2021 Swift Navigation Inc.
# Contact: https://support.swiftnav.com
#
# This source is subject to the license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIN... |
class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
if not s:
return []
current = []
result = []
self.helper(s, current, result)
return result
def helper(self, s, cur, r... |
import logging
from nightshift import constants
from typing import Dict, List, Tuple
import matplotlib.cm
from matplotlib.axes import Axes
from matplotlib.colors import is_color_like
AXIS_LABELS: Dict[str,str] = {
'H': r'$^{1}$H (ppm)',
'N': r'$^{15}$N (ppm)',
'C': r'$^{13}$C (ppm)',
}
Correlations = ... |
# Generated by Django 3.0.7 on 2020-08-01 10:48
import django.core.validators
from django.db import migrations
from django.db import models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Social",
fiel... |
import math
import numpy as np
import viz
def is_collinear(p1, p2, p3):
return (p2[0] - p3[0]) * (p1[1] - p2[1]) == (p2[1] - p3[1]) * (p1[0] - p2[0])
def on_segment(p1, p2, p3):
return (p1[0] < p3[0] < p2[0]) or (p1[0] > p3[0] > p2[0])
def orientation(p, q, r):
return (q[1] - p[1]) * (r[0] - q[0]) -... |
""" Texext package """
from . import math_dollar
from . import mathcode
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
def setup(app):
math_dollar.setup(app)
mathcode.setup(app)
|
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [
Extension(
"qdr.ranker",
sources=['qdr/ranker.pyx'],
extra_compile_args=['-std=c++0x'],
language="c++"),
]
setup(name='qdr',
version='0.0',
de... |
from django.shortcuts import render
from twobuntu.routers import ReadOnlyError
class ReadOnlyMiddleware(object):
"""
Catch ReadOnlyError exceptions and display the appropriate error page.
"""
def process_exception(self, request, exception):
if isinstance(exception, ReadOnlyError):
... |
import re
from django import forms
from .models import (
Filtro,
ClasseFiltro,
ItemFiltro
)
class BaseModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for key in self.fields:
field = self.fields[key]
if type(fi... |
import os
import logging
from .app import app
from .weather_services import OpenWeatherMapAPI, FakeWeatherAPI
DEBUG = os.environ.get("FLASK_ENV", "production") == "dev"
logging.basicConfig(
level=logging.DEBUG if DEBUG else logging.INFO,
format="[%(levelname)-5s] <%(name)-10s> %(lineno)-4s - %(message)s'",
)... |
#########################################################################
# File Name: test.py
# Author: Walker
# mail:qngskk@gmail.com
# Created Time: Thu Dec 9 11:25:59 2021
#########################################################################
# !/usr/bin/env python3
import numpy as np
import pandas as pd
impor... |
import bpy, os
from math import *
def MAT_texture_new(name,size, colorspc, q_alpha = True):
tex = bpy.data.images.get(name)
if tex is None:
tex = bpy.data.images.new(name, width=size[0], height=size[1], alpha = q_alpha)
tex.colorspace_settings.name = colorspc
else:
#change re... |
from typing import TypedDict
import re
from xml.etree import ElementTree as ET
ET.register_namespace("", "http://www.w3.org/2000/svg")
class License(TypedDict):
"""License information for each icon."""
type: str
url: str
class Icon:
"""An icon with all relevant data and methods."""
def __init... |
import argparse
class BaseEngine(object):
def __init__(self, opt) -> None:
self.opt = opt
@staticmethod
def modify_commandline_options(parser: argparse.ArgumentParser,
additional_args=None):
return parser
|
from enum import Enum
import pygame
from pygame.locals import *
import random
from cell import Cell
from pprint import pprint as pp
from utils import _time
class MouseBtnState(Enum):
LEFT_BTN = 1
RIGHT_BTN = 3
NOTHING = 0
class GameOfLife:
def __init__(self,
width: int = 640,
... |
from app import app
from flask import flash, redirect, url_for, render_template, request
from app.forms import URLForm, LoginForm
from app.pulltext import pull_text
@app.route("/", methods=['GET','POST'])
@app.route("/index", methods=['GET','POST'])
def index():
form = URLForm()
if form.validate_on_submit():
... |
import mysql.connector
class Database:
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="Piku123.",
database="datascience"
)
mycursor = mydb.cursor()
def __init__(self):
pass
def execute_query_with_params(self, query, params):
... |
# Copyright (C) 2017, 2018 International Business Machines Corporation
# All Rights Reserved
import os
import sys
import json
import streamsx.rest
################### parameters used in this script ############################
here = os.path.dirname(os.path.realpath(__file__))
vcapFilename = here + '/vcap.json'
#... |
import os
relative_path = "../hierarchical_localization/Hierarchical-Localization/datasets/inloc/query/iphone7/"
image_paths = [relative_path + f for f in os.listdir(relative_path) if f.endswith(".JPG")]
with open("image_list_inloc.txt", 'w') as f:
f.write("\n".join(map(str, image_paths))) |
# Copyright 2016 Euclidean Technologies Management LLC 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 requi... |
import DistConvGAN as model
import lbann.contrib.launcher
import lbann.contrib.args
import argparse
import os
from lbann.core.util import get_parallel_strategy_args
import lbann
import lbann.modules as lm
def list2str(l):
return ' '.join([str(i) for i in l])
def construct_lc_launcher_args():
parser = argpars... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""django-sqlprint-middleware - pretty-print Django's SQL statments.
"""
import io
from setuptools import setup
version = '0.1.3'
setup(
name='django-sqlprint-middleware',
version=version,
packages=['django_sqlprint_middleware'],
install_requires=[
... |
from dirutility import DirPaths
from looptools.timer import Timer
def test_case(case):
test_cases = {
'projects': {
'rootpath':
'/Volumes/Storage/HPA Design',
'exclude': [
'20080081_Rosenfeld_Realty', '20080082_Clarewood_Homes_WEB', '20080083_Dipersio_WE... |
from graphviz import Digraph
from nujo.autodiff._node import _Node
from nujo.autodiff.tensor import Tensor
class ComputationGraphPlotter:
''' Computation Graph Plotter
Uses graphviz.
'''
def __init__(self, **kwargs):
self.computation_graph = Digraph(**kwargs)
@staticmethod
def ... |
import math
def cal_pmv(ta=None, tr=None, rh=None, v=None, clo=None, met=None, top=None, w=0):
"""
This function is used to calculated Predicted Mean Vote(PMV) through environmental parameters
cal_pmv(ta=None, tr=None, rh=None, v=None, clo=None, met=None, top=None, w=0)
ta: Air temp... |
from pydantic import ValidationError
from one_time_secret.app import schemas
def test_good_argument():
validation_model = schemas.SecretKey(
secret_key="984ae013e1304e54a5b2a1aec57fac36",
)
expected = "984ae013e1304e54a5b2a1aec57fac36"
assert validation_model.secret_key == expected
def test... |
input()
l = list(map(int, input().split()))
l_ = [str(i) for i in range(len(l))]
again = True
while again:
again = False
for i in range(len(l)-1):
if l[i] > l[i+1]:
l[i], l[i+1], l_[i], l_[i+1] = l[i+1], l[i], l_[i+1], l_[i]
again = True
print(" ".join(l_))
|
from boa.interop.Neo.App import RegisterAppCall
CalculatorContract = RegisterAppCall(b'W\xa7\x18\x08MZh\xbdu\xb7%\x88\x8e\x19J\x9e\xd4|\xe1\xe3\xaa', 'operation', 'a', 'b')
def Main(operation, a, b):
result = CalculatorContract(operation, a, b)
return result
|
import numpy as np
import config
class Trajectory:
"""
Trajectory class using trajectory generation with via points, with constant velocity segments and
continous acceleration blends. For more info on this check out W.Khalils book Modeling, identification and control of robots
Formulas and c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.