content stringlengths 5 1.05M |
|---|
while True:
N = int(input())
if not N: break
ans = float('inf')
for c200 in range(N//200+1):
for c300 in range(N//300+1):
for c500 in range(N//500+1):
if 200 * c200 + c300 * 300 + c500 * 500 == N:
ans = min(ans, 1520*(c200//5)+380*(c200%5)+1870*(c3... |
from nexus_auth import app, celery, db, users
from nexus_auth.models.mumble import MumbleAccount
from nexus_auth.models.jabber import Prosody
from nexus_auth.utils.services import JabberTools
from nexus_auth.utils.eventlog import post_jabber
from celery.utils.log import get_task_logger
logger = get_task_logger(__name... |
class SSSSGException(Exception):
pass
|
# Copyright 2010 Jacob Kaplan-Moss
# Copyright 2011 OpenStack LLC.
# Copyright 2012 Kevin Minnick
# 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
#
# h... |
# Generated by Django 3.2.7 on 2021-09-12 18:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mapthing', '0004_auto_20210911_1410'),
]
operations = [
migrations.RemoveField(
model_name='attend',
name='attendee'... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""tests for link prediction API"""
import unittest
from abc import ABC
from typing import Iterable
import numpy as np
from sknetwork.data import house
from sknetwork.linkpred.base import BaseLinkPred
class Dummy(BaseLinkPred, ABC):
"""Dummy algorithm for testing p... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens
# www.pagebot.io
#
# P A G E B O T E X A M P L E S
#
# Licensed under MIT conditions
#
# Supporting DrawBot, www... |
import gen.constants as constants
from gen.agents.agent_base import AgentBase
from gen.game_states.planned_game_state import PlannedGameState
from gen.utils import game_util
class PlanAgent(AgentBase):
def __init__(self, thread_id=0, game_state=None, controller_agent=None):
super(PlanAgent, self).__init__... |
# -*- coding: utf-8 -*-
"""
Overview
--------
Hordak features multi currency support. Each account in Hordak can support one or more currencies.
Hordak does provide currency conversion functionality, but should be as part of the display logic
only. It is also a good idea to make it clear to users that you are showing... |
'''
api
存在问题:
- 并发请求时,且前一请求正在查询会导致卡死
'''
import time
from pymongo import MongoClient
from flask import Flask, request, jsonify, Response
from flask_restful import Api, Resource, reqparse
from werkzeug.datastructures import Headers
from conf.config import MongoDBConfig
app = Flask(__name__)
client = MongoClient(MongoD... |
# Generated by Django 3.1.8 on 2021-08-16 17:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('flags', '0031_auto_20210816_1709'),
]
operations = [
migrations.AddField(
model_name='color',
name='meaning',
... |
import FWCore.ParameterSet.Config as cms
# creates the recoGsfTracks_electronGsfTracks__RECO = input GSF tracks
from TrackingTools.GsfTracking.GsfElectronTracking_cff import *
ecalDrivenElectronSeeds.initialSeedsVector = ["hiPixelTrackSeeds"]
electronCkfTrackCandidates.src = "ecalDrivenElectronSeeds"
ecalDrivenElect... |
def entrada():
coordenadas = list(map(int, input().split(' ')))
n1 = coordenadas[0]
n2 = coordenadas[1]
return n1, n2
def quadrante():
while True:
x, y = entrada()
if x == 0 or y == 0:
break
elif x > 0 and y > 0:
print('primeiro')
elif x < 0 ... |
import sys,os
import pandas
from Bio import SeqIO
"""
Converter script for Percolator output to create Fido-readable files.
By Jose Fernandez Navarro,
SLIGHTLY MODIFIED BY WILLIAM BARSHOP (LABORATORY OF JAMES A WOHLSCHLEGEL)
These modifications allow input of multiple tab delimited peptide-level percolator outputs. ... |
import numpy as np
import cv2
def rescale(img):
img = img.astype(np.float32)
new_img = img - img.min()
new_img /= (new_img.max() + 1e-6)
return new_img
def img_resize(img, resize=None):
img = img.astype(np.float32)
img = rescale(img)
if resize is None or (resize == img.shape[1] and resize... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 26 09:58:24 2020
@author: glpyz
"""
# --- MODULOS E IMPORTS ---------------------------------
import datetime
#import os.path
import easygui
from easygui import *
import openpyxl
from openpyxl import load_workbook
import pandas as pd
# import shutil
# from shutil impo... |
#! /usr/bin/env python3
# # -*- coding: UTF-8 -*-
import time, sys, errno, struct, threading, socket
from . import EventTypes, SocketError
class CastReceiver:
'''建立多播監聽器(Multicast)類別
傳入參數:
`port` `int` -- 欲監聽的通訊埠號
'''
def __init__(self, host):
if isinstance(host, int):
sel... |
# Copyright (c) Ryan Kingsbury
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
"""
Membrane potential related methods
"""
import numpy as np
def apparent_permselectivity(
E_mem: float,
E_ideal: float,
t_counter: float = 0.5... |
# Copyright (c) 2010 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.
{
'includes': [
'../../../../../build/common.gypi',
],
'targets': [
{
'target_name': 'call_broker',
'type': 'executable',
... |
import os
import pytest
import yaml
from dotty_dict import Dotty
from ddb.__main__ import main
from ddb.config import config
from tests.utilstest import get_user_uid_gid, get_group_gid
class TestJsonnet:
def test_jsonnet_ext_var(self, project_loader):
project_loader("jsonnet-extvar")
main(["con... |
from widgets.widget import _Widget, WidgetByShape
from prefabs.rmath import move_negativity
import prefabs.animator as animator
from base_node import get_surface
from prefabs.surface import blit
from prefabs.inputter import *
from widgets.text import Text
from shape import *
import pygame
class _Button(_Widget):
... |
import discord, sys, os, asyncio, sqlite3, ast
from discord.ext import commands
from datetime import datetime
from .namedtuples import AntiSpam, AntiSlur, AntiInvite, AntiNSFW, AntiLink, Case, Tag
from .exceptions import InvalidConfig, TagNotFound
async def handle_invalid_config(ctx, error):
if error.subs... |
# -*- coding: utf8 -*
from selenium import webdriver
from time import sleep
from toolbox import log_record
'''
модуль с функциями связанными с фреймворком selenium
'''
def get_filter_string(flag:str):
filter_for_span_a_button_only = "@id != contains(@id, 'КоманднаяПанель') and \
... |
"""Leetcode 252. Meeting Rooms (Premium)
Easy
URL: https://leetcode.com/problems/meeting-rooms
Given an array of meeting time intervals consisting of start and end times
[[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings.
Example 1:
Input: [[0,30],[5,10],[15,20]]
Output: false
Example ... |
from __future__ import print_function
import logging, re, os
from langlab.pymake import data, parser, util, errors
from langlab.pymake.globrelative import hasglob, glob
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
_log = logging.getLogger('pymake.data')
_tabwidth = 4
clas... |
from django.conf.urls.defaults import *
urlpatterns = patterns('dreamdesktop.views',
#settings dialog
url(r'^settings/$', 'settings_front'),
url(r'^settings/password/$', 'settings_change_pw'),
url(r'^settings/userinfo/$', 'settings_insert_email_phonenumber'),
url(r'^settings/join/$', 'settings_join'),
url... |
# -*- coding: utf-8 -*-
"""
Launches SeleniumBase Commander | GUI for pytest.
Usage:
seleniumbase commander [OPTIONAL PATH or TEST FILE]
sbase commander [OPTIONAL PATH or TEST FILE]
seleniumbase gui [OPTIONAL PATH or TEST FILE]
sbase gui [OPTIONAL PATH or TEST FILE]
E... |
# coding: utf-8
from flask import render_template, redirect, url_for, abort, flash, request,\
current_app, make_response, session, g
from flask_login import login_required, current_user
from flask_babel import gettext as _
from flask_sqlalchemy import get_debug_queries
from . import main
from .forms import EditProf... |
p1 = (123, 84)
p2 = (213, 84)
p3 = (321, 84)
p4 = (378, 84)
p5 = (485, 84)
p6 = (576, 84)
p7 = (123, 155)
p8 = (213, 155)
p9 = (268, 155)
p10 = (321, 155)
p11 = (378, 155)
p12 = (431, 155)
p13 = (485, 155)
p14 = (576, 155)
p15 = (123, 209)
p16 = (213, 209)
p17 = (268, 209)
p18 = (321, 209)
p19 = (... |
import unittest
from nose.tools import assert_true
from nose.tools import assert_false
from pjxxs import fields
class TestValidation(unittest.TestCase):
def setUp(self):
schema = fields.Schema("main/schema", 1)
# required should be forced to not required.
schema.add_field(fields.Null("required", required=True)... |
from django.core.exceptions import ObjectDoesNotExist
from tethys_apps.cli.cli_colors import pretty_output, BOLD, FG_RED
def app_settings_list_command(args):
from tethys_apps.models import (TethysApp, PersistentStoreConnectionSetting, PersistentStoreDatabaseSetting,
SpatialDat... |
import asyncio
import httpcore
import httpx
import pytest
from sanic_testing.testing import SanicTestClient
from sanic import Sanic
from sanic.response import text
class DelayableHTTPConnection(httpcore._async.connection.AsyncHTTPConnection):
async def arequest(self, *args, **kwargs):
await asyncio.sle... |
from .core import EmpiricalFormula, OpenBabelUtils
# from .marvin import get_major_micro_species, draw_molecule
|
import configparser
def section_present(config, key):
"""
It indicates whether the key section is present in the config file
Args:
config: config parser object
key: section key
Returns:
True if the section is present, False elsewhere
"""
keys = config.sections()
if... |
import urllib.request as req
import os
IO_CHUNK_SIZE = 1024
def get_file_from(url, filename):
"""Encapsulates capability to download big file from given URL in the efficient way.
Args:
url: The URL to download file from.
filename: The name of the file where downloaded content will be saved.
... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 os
import pygame
# pygame.init()
# CONSTANTS
map_size = m_width, m_size = 3000, 3000
SIZE = WIDTH, HEIGHT = 1280, 720
BLACK = 0, 0, 0
WHITE = 255, 255, 255
GREEN = 0, 255, 0
MAX_BALL_SPEED = 10
blanc = pygame.image.load(os.path.join("assets", "blanc.png"))
green = pygame.image.load(os.path.join("assets", "sh... |
from ...shared.utils.restApi import RestResource
from ...shared.utils.api_utils import build_req_parser
from ..models.api_baseline import APIBaseline
from ..models.api_reports import APIReport
from ..connectors.influx import get_aggregated_test_results
class BaselineAPI(RestResource):
get_rules = (
dict(n... |
from tracardi_plugin_sdk.service.plugin_runner import run_plugin
from tracardi_string_splitter.plugin import SplitterAction
def test_string_splitter_plugin():
payload = {"string": 'a,b,c'}
init = dict(
string='payload@string',
delimiter=',',
)
result = run_plugin(SplitterAction, init,... |
from poodle import Object
from kalc.model.system.primitives import StatusServ, StatusNode, StatusPod, StatusLim, StatusSched, StatusReq, TypePolicy, TypeServ, StatusDeployment, StatusDaemonSet
STATUS_POD = {
"Running" : StatusPod("Running"),
"Pending" : StatusPod("Pending"),
"Killing" : StatusPod("Killing... |
#!/usr/bin/env python
import baxter_interface
import rospy
if __name__ == '__main__':
rospy.init_node("set_left_arm_py")
names = ['left_e0', 'left_e1', 'left_s0', 'left_s1', 'left_w0', 'left_w1', 'left_w2']
joints = [-0.8022719520640714, 1.7184419776286348, 0.21399031991001521, 0.324436936637765, 2.586291... |
# coding=utf-8
"""
This module contains config objects needed by paypal.interface.PayPalInterface.
Most of this is transparent to the end developer, as the PayPalConfig object
is instantiated by the PayPalInterface object.
"""
import logging
import os
from pprint import pformat
from paypal.compat import basestring
fro... |
from abc import ABCMeta, abstractmethod
from .exceptions import TembaSerializationException
from .utils import format_iso8601, parse_iso8601
class TembaObject(metaclass=ABCMeta):
"""
Base class for objects returned by the Temba API
"""
@classmethod
def create(cls, **kwargs):
source = kwa... |
import nltk
import truecase
from nltk.corpus import movie_reviews
#nltk.download('punkt')
sentence = 'michael jackson AnD His Dog like To eat At mcDonalds'
text_to_tag = nltk.word_tokenize(truecase.get_true_case(sentence))
#print(nltk.pos_tag(text_to_tag))
print(dir(movie_reviews))
|
from threading import Thread
from flask import render_template
from flaski import app
from flask_mail import Message
from flaski import mail
from werkzeug.utils import secure_filename
import io
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
def send_email(subject, sender, recipient... |
import datetime
import glob
import math
import os
import paraview.simple as pvs
from paraview.web import protocols as pv_protocols
from wslink import register as exportRpc
from evolution import Evolution
# Global definitions of variables
# Range for each lookup table
LUT_RANGE = {'Vr': [300, 900],
'Dens... |
import numpy as np
import pytest
from scipy import sparse as sp
from numpy.testing import assert_array_equal
from sklearn.base import BaseEstimator
from sklearn.feature_selection._base import SelectorMixin
from sklearn.utils import check_array
class StepSelector(SelectorMixin, BaseEstimator):
"""Ret... |
"""
This module handles importing data from csv files and creating the whole game world from these data.
"""
from __future__ import print_function
from muddery.utils import utils
from muddery.utils.object_key_handler import OBJECT_KEY_HANDLER
from muddery.utils.game_settings import GAME_SETTINGS
from muddery.mappings... |
from scrapy.http import Request
class FTPRequest(Request):
pass
class FTPFileRequest(FTPRequest):
pass
class FTPListRequest(FTPRequest):
pass
|
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015, 2016 Daniel Rodriguez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License ... |
import unittest
import time
import threading
from datetime import datetime
from flask import Flask, request
from smsframework import Gateway, exc
from smsframework.providers import ForwardClientProvider, ForwardServerProvider, LoopbackProvider
from smsframework import OutgoingMessage, IncomingMessage
from smsframewor... |
# anchors the root directory
# and helps pytest find all the files
|
# Copyright 2020 Mycroft AI Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Richard Hull and contributors
# See LICENSE.rst for details.
import time
from luma.led_matrix.device import neopixel
from luma.core.render import canvas
device = neopixel(cascaded=32)
for i in range(device.cascaded):
with canvas(device) as draw:... |
"""Lydia AI plugin for @UniBorg
.eai <as a reply to user's message //Turns AI on For that user.
.dai <as a reply to user's message //Turns AI off For that user.
.lai // Outputs List Of Currently added Users in AI Auto-Chat.
Description: A module that Act as a chatbot and chat with a User/other Bot.
This Module Needs ... |
from . import config
from uoimdb.uoimdb import uoimdb, Pipeline, get_config
|
from .task import Task, register_task
__version__ = "0.1.4"
__all__ = ["register_task", "Task"]
default_app_config = "django_cloudtask.apps.TasksConfig"
|
"""!
@file main.py
Adapted from Professor Ridgely's basic_tasks.py program, this
file creates two motor step response tasks, gives them to the
task manager, and runs them at given intervals. The time and
encoder values are passed back to the PC via serial.
@author JR Ridgely, Kyle Jennings, Zarek Lazo... |
"""
Turn entities to and fro various representations.
This is the base class and interface class used to transform strings
of various forms to model objects and model objects to strings of various
forms.
"""
from tiddlyweb.serializer import NoSerializationError
from tiddlyweb.model.tiddler import tags_list_to_string,... |
from distutils.core import setup
from distutils.command.install import INSTALL_SCHEMES
import distutils.cmd
import platform,sys
import os,os.path
import subprocess
import ctypes
class InstallationError(Exception): pass
major,minor,_,_,_ = sys.version_info
if major != 2 or minor < 5:
print "Python 2.5+ required, g... |
#!/usr/bin/env python3
#System Imports
import configparser as cp
import os
from packaging import version
import shutil as sh
import subprocess
import sys
import time
db = True
try:
import psycopg2
from psycopg2 import sql
except ImportError:
db = False
print("No psycopg2 module available, db access w... |
import argparse
import sys
from time import sleep
import uuid
import rclpy
from rmf_task_msgs.msg import Delivery
def main(argv=sys.argv):
rclpy.init(args=argv)
args_without_ros = rclpy.utilities.remove_ros_args(argv)
parser = argparse.ArgumentParser()
parser.add_argument('-p',
... |
from .responseData import ResponseDataWrapper
class ResponseDataGetAutoBoostCo2Wrapper(ResponseDataWrapper):
def __init__(self, responseData) -> None:
super().__init__(responseData)
@property
def AutoBoostCO2(self) -> bool:
return self._rd.AutoBoostCO2
@property
def BoostState(se... |
#
# Andrei Korostelev <andrei at korostelev dot net>
#
# Before using this product in any way please read the license agreement.
# If you do not agree to the terms in this agreement you are not allowed
# to use this product or parts of it. You can read this license in the
# file named LICENSE.
#
"""
Git task
"""... |
import matplotlib.pyplot as plt
import os
import utils
root_path = './'
data_name = 'UCSD_P2_256'
data_path = os.path.join(root_path, 'dataset', data_name)
res_root = os.path.join(root_path, 'video-proj_results')
model_setting = 'MemAE_Conv3DSpar_UCSD_P2_256_MemDim2000_EntW0.0002_ShrThres0.0025_Non'
res_path = os.pa... |
import io
from PIL import Image
import pytesseract
import numpy as np
import pandas as pd
from utils.text import (amount, remove_single_nonletters)
def tabularize_amounts(df):
'''
Use their right positional value to group
the data into the correct columns.
Since our columns have numbers in them,
w... |
from datetime import datetime, date, timedelta
from dateutil.relativedelta import relativedelta
from ib_insync import util as ib_insync_util
from ib_insync import Contract
from loguru import logger
from typing import List
from ibdatafetcher.util import is_trading_day
from ibdatafetcher.security_master import InMemSecu... |
import os, sys, getpass, stat, glob, json, platform
import subprocess, time, traceback
from collections import OrderedDict
import fnmatch, re
from ..config import get_config
from ..plugins.common import plugins_get_mgr
from .common import clone as common_clone, init as common_init, post as common_post
from .files impor... |
from django.contrib.auth import authenticate, login
from django.contrib.auth.views import LoginView
from django.contrib.messages.views import SuccessMessageMixin
from django.shortcuts import redirect, render
from django.urls import reverse_lazy
from users.forms import RegistrationForm
def signup(request):
"""Reg... |
# -*- coding: utf-8 -*-
from fe_cipher.models.card import Card
# 手札
class Hand:
# 0 は一番左のカード
cards: [Card] = []
def __init__(self):
pass
# カードを手札に追加
def add_card(self, card: Card):
self.cards.append(card)
|
# solution to a kata on codewars
# https://www.codewars.com/kata/exes-and-ohs/python
# idea is to determine whether there is an
# equal number of "x" and "o" in a string
# (count the total of both upper and lower case)
def xo(s):
return s.lower().count('x') == s.lower().count('o')
|
from anytree import Node, RenderTree, AsciiStyle, LevelOrderGroupIter, PostOrderIter
from anytree.dotexport import RenderTreeGraph
from .utils import (
FLOAT_MAX, FLOAT_MIN, isfloat, getNormHist,
getKLD, getUCT, post_order_traversal, checksum, convert_encoding_to_dict, shuffle_e... |
# -*- coding: utf-8 -*-
# cython:language_level=2
"""
-------------------------------------------------
File Name: eventOut
Description :
Author : liaozhaoyan
dat 2021/11/3
-------------------------------------------------
Change Activity:
2021/11/3:
-----------------... |
####################################################################
# Copyright (c) 2019 Nobuyuki Umetani #
# #
# This source code is licensed under the MIT license found in the #
# LICENSE file in the root directory of this... |
#cont = ('zero', 'um', 'dois', 'tres', 'quatro', 'cinco',
# 'seis', 'sete', 'oito', 'nove', 'dez',
# 'onze', 'doze', 'treze', 'quartoze', 'quinze',
# 'dezesseis', 'dezessete', 'dezoito', 'dezenove', 'vinte')
#while True:
# num = int(input('digite um numero entre 0 e 20: '))
# if 0 <= num <= 2... |
"""Advent of Code 2017 Day 22."""
INFECTED = '#'
CLEAN = '.'
WEAKENED = 'W'
FLAGGED = 'F'
DIRECTION_TO_MOVE = {
90: (-1, 0),
0: (0, 1),
180: (0, -1),
270: (1, 0),
}
SIDES = {
'right': -90,
'left': 90,
'reverse': 180,
}
def main(file_input='input.txt'):
lines = [line.strip() for line i... |
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
class User(UserMixin):
#password_hash = store this in the db somehow
def __init__(self,e):
self.email = e["email"]
@property
def password(self):
raise AttributeError('password ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-08 13:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('setup', '0005_auto_20171206_0034'),
]
operations =... |
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
import unittest
from iptest import IronPythonTestCase, run_test
global flag
def new_classes():
class C1: ... |
"""Environment for training automated vehicles in a mixed-autonomy setting."""
import collections
import numpy as np
import random
import os
from gym.spaces import Box
from copy import deepcopy
from collections import defaultdict
from csv import DictReader
from scipy.optimize import fsolve
from flow.envs import Env
fr... |
from random import Random
from .logging import logger
from .pop_miner import PopMiner
class RandomMiner:
def __init__(self, node, apm, seed):
self.miner = PopMiner(node, apm)
self.random = Random(seed)
self.btc_txs = []
self.btc_tx_vbk_block = {}
self.vbk_pop_txs = []
... |
from LivestockCV.core.roi.roi_methods import circle
from LivestockCV.core.roi.roi_methods import ellipse
from LivestockCV.core.roi.roi_methods import from_binary_image
from LivestockCV.core.roi.roi_methods import rectangle
from LivestockCV.core.roi.roi_methods import multi
from LivestockCV.core.roi.roi_methods import c... |
"""Tasks related to Tamr Projects"""
from . import schema_mapping
from . import mastering
from . import golden_records
from . import categorization
__all__ = ["schema_mapping", "mastering", "golden_records", "categorization"]
|
#!/usr/bin/env python
from Tkinter import *
import tkFileDialog
import data_analyzer
import logging
logging.basicConfig()
class App:
def __init__(self, master):
# initializing variables
self.filepath_open = None
frame_1 = Frame(master)
frame_2 = Frame(master)
frame_3 = Fram... |
from setuptools import setup, find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="raML", # Replace with your own username
version="0.0.0",
author="Ramil Aleskerov",
author_email="ramilraleskerov@gmail.com",
description="The Best Machine Learning Framewor... |
import torch
import torch.nn.functional as F
import math
EPS = 1e-7
def _calc_param(model, x, tile_size):
p = {}
offset = model.offset
p["x_h"] = x.shape[1]
p["x_w"] = x.shape[2]
scale = model.scale
input_offset = math.ceil(offset / scale)
process_size = tile_size - input_offset * 2
h... |
"""
This module provides a sequence class which can be used for cyclic values
"""
from typing import Generic, TypeVar
T = TypeVar('T')
class Cycle(list,Generic[T]):
"""This class can be used to store cyclic values"""
def __getitem__(self,key:int) -> T:
return super().__getitem__(key%len(self))
... |
# NOTE:
# To test on 'real' bigdata:
# xtc_dir = "/reg/d/psdm/xpp/xpptut15/scratch/mona/test"
# >bsub -n 64 -q psfehq -o log.txt mpirun python user_loops.py
# cpo found this on the web as a way to get mpirun to exit when
# one of the ranks has an exception
import sys
# Global error handler
def global_except_hook(exct... |
import base64
import hashlib
import hmac
import os
from urllib.parse import urlencode
from geopy.point import Point
GOOGLE_API_KEY_ENV = "GOOGLE_MAPS_API_KEY"
GOOGLE_SIGN_SECRET_ENV = "GOOGLE_MAPS_URL_SIGN_SECRET"
MAPS_ENDPOINT = "https://maps.googleapis.com"
MAPS_API_PATH = "/maps/api/staticmap"
def get_static_ma... |
#!python
#
# This file is part of https://github.com/zsquareplusc/python-embedded-launcher
# (C) 2016-2019 Chris Liechti <cliechti@gmx.net>
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Extract the official Python embedded distribution
- download when necessary
- extract a cached version by default
- 32/64 bit and ... |
from datetime import datetime
from operator import itemgetter
from os.path import dirname, join
import pytest # noqa
from city_scrapers_core.constants import COMMISSION, PASSED
from city_scrapers_core.utils import file_response
from freezegun import freeze_time
from city_scrapers.spiders.mi_redistricting_commission ... |
from django.http import Http404
from django_policies.filters import conjunct
class FilterQuerysetMixin:
def _get_filter(self):
filters = set(
perm.get_filter(self.request, self)
for perm in self.get_permissions()
if hasattr(perm, "get_filter")
)
return... |
import os
import sys
from dagster import (
ExecutionTargetHandle,
DependencyDefinition,
InputDefinition,
OutputDefinition,
PipelineDefinition,
RepositoryDefinition,
SolidDefinition,
)
from dagster.utils import script_relative_path
from dagster_graphql.implementation.context import Dagste... |
import cv2
import numpy as np
import time
'''
Parameters Used inside Code
'''
#Gaussian kernel size used for blurring
G_kernel_size = (3,3)
#canny thresholding parameters
canny_u_threshold = 200
canny_l_threshold = 80
# define the upper and lower boundaries of the HSV pixel
# intensities to be considered 'skin'
low... |
# Copyright 2021 Google LLC.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
import sys
import os
from PyQt5 import QtCore, uic
from PyQt5.QtWidgets import QApplication, QWidget
from .pulsegen import PulseGen
def gui(p: PulseGen):
"""Creates a simple GUI for a pulse generator object."""
# Determines if the app has been run from an ipython console.
try:
from IPython impo... |
import torch
import torch.nn as nn
import torchvision.models as models
from torch.utils.data.dataset import Dataset
from learning import train_model, validate_model
from thesis_dataset import ParasiteDatasetTrain, ParasiteDatasetTest
from assistant import save_models
from metric import cvs_to_arr, get_metrics
# from to... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################## ##############################
######################### Detection module #########################
######################### ######################### #############################
### Contains all the function... |
from __future__ import absolute_import
from django.db.models import Q
from pontoon.base.utils import glob_to_regex
from pontoon.tags.exceptions import InvalidProjectError
from .base import TagsDataTool
class TagsResourcesTool(TagsDataTool):
""" Find, link and unlink Resources for Tags
"""
filter_meth... |
from collections import defaultdict
def solve(input):
par = defaultdict(list)
for l in input.split("\n"):
n, _, c = l.partition(" contain ")
parent = n.removesuffix(" bags")
for child in c.split(", "):
par[" ".join(child.split()[1:-1])].append(parent)
seen = set()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.