content stringlengths 5 1.05M |
|---|
import os
import torch
from sklearn.manifold import TSNE
from matplotlib import cm
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
def plot_tsne(feat, index, output_dir):
print("feat: global mean = {:.4f}, {:.4f}".format(feat.mean(), feat.std()))
embed = TSNE(n_components=2).fit_tran... |
# pylint: skip-file
from yamicache import Cache
c = Cache()
class App1(object):
@c.cached()
def test1(self, argument, power):
"""running test1"""
return argument ** power
@c.clear_cache()
def test2(self):
return 0
def test_clear():
"""Make sure cache gets cleared"""
... |
import os
import argparse
import requests
from sanic import Sanic
from sanic.response import json
from osf_pigeon.pigeon import main, sync_metadata, get_id
from concurrent.futures import ThreadPoolExecutor
from sanic.log import logger
from asyncio import events
def run(main):
loop = events.new_event_loop()
tr... |
import random
import requests
from bs4 import BeautifulSoup
from colorama import Fore
from colorama import Style
from blagues_api import BlaguesAPI
import asyncio
def faituneblague():
blagues = BlaguesAPI(
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMjAwNTQ5NjM1MDY3MDg0ODAwIiwibGltaXQiOjEwMCwia2... |
from .weibo_h5 import WeiboH5API as WeiboAPI
from .base import WeiboVisible
|
class Cursor:
def __init__(self, wnd):
self.wnd = wnd
self.pos = 0
self.preferred_col = 0
self.preferred_linecol = 0
self.last_screenpos = (-1, -1)
def refresh(self, top=None, middle=None, bottom=None,
align_always=False):
self.pos, y, x = self.w... |
import warnings
import numpy as np
import math
def ugly_number(n):
"""
Returns the n'th Ugly number.
Ugly Numbers are numbers whose only prime factors are 2,3 or 5.
Parameters
----------
n : int
represent the position of ugly number
"""
if(n<1):
raise NotImplemente... |
"""
ARC's settings
"""
import os
import string
import sys
servers = {
'local': {
'path': '/storage/ce_dana/',
'cluster_soft': 'HTCondor',
'un': '[username]',
'cpus': 8,
'memory': 256,
},
}
# List here servers you'd like to associate with specific ESS.
# An ordered list... |
from setuptools import setup, find_packages
setup(
name='PyloXyloto',
version='1.0',
description='PyloXyloto is a simple Deep learning framework built from scratch with python that supports the main '
'functionalities needed for a deep learning project',
py_modules=["activation... |
import unittest
from libsaas.executors import test_executor
from libsaas.services import base, twilio
class TwilioTestCase(unittest.TestCase):
def setUp(self):
self.executor = test_executor.use()
self.executor.set_response(b'{}', 200, {})
self.service = twilio.Twilio('my-sid', 'my-token... |
from __future__ import print_function, division
import numpy as np
import matplotlib.pyplot as plt
import os
import pandas
from functions import getbinary
from sklearn.utils import shuffle
class LogisticModel(object):
def __init__(self):
pass
def fit(self,X,Y,X_test,Y_test,lr = 10e-7,reg = 10e-22,epoc... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
# Copyright 2013 OpenStack Foundation
# 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 requ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import print_function
# Let's import what we need
import os
import sys
import tld
import time
import random
import warnings
import argparse
import threading
from math import log
from re import search, findall
from requests import get, post
try:
impor... |
from flask import Flask
from flask_restful import Api
from status import Status
from runner import Runner
app = Flask(__name__)
api = Api(app)
# Routing
api.add_resource(Status, '/')
api.add_resource(Runner, '/analyze')
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True, port=3000)
|
"""
Main lesscss parse library. Contains lexer and parser, along with
utility classes
"""
|
# coding=utf-8
# Marcelo Ambrosio de Goes
# marcelogoes@gmail.com
# 2022-03-07
# 100 Days of Code: The Complete Python Pro Bootcamp for 2022
# Day 20/21 - Snake Game
from turtle import Turtle
import random
class Food(Turtle):
def __init__(self, input_width, input_height):
super().__init__()
self... |
from tests.nlg.test_nlg import BaseTestTemplateNLG, BaseTestCamrest
from convlab2.nlg.template.camrest.nlg import TemplateNLG
class TestTemplateCamrest(BaseTestTemplateNLG, BaseTestCamrest):
@classmethod
def setup_class(cls):
BaseTestTemplateNLG.setup_class()
BaseTestCamrest.setup_class()
... |
from threading import Thread, Timer
from time import time
import logging
import random
import numpy as np
class Brandbox_temperature_humidity(Thread):
"""This class is reads out continiously the temperature and humidity from the Brandbox
This class inherits all function from the threading class an therefore c... |
#!/usr/bin/env python3
#
# laaso/hydrator.py
#
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
#
'''
Main program to hydrate the Lustre namespace from blob.
'''
import datetime
import multiprocessing
import os
import pickle
import queue
import stat
import sys
import syslog... |
from admin_tabs.tests.metaadminpageconfig import *
|
#!/usr/bin/env python3
import sys
import operator
import unittest
import hypothesis
from .util import lattice_dimensions_with_lower_bound
from synth.search import Simple
from synth.search import MinimizedSplit
from synth.search import BinaryPartition
from synth.search import Saddleback
class DummyFunction:
def ... |
from vumi.transports.twitter.twitter import (
ConfigTwitterEndpoints, TwitterTransport)
__all__ = ['ConfigTwitterEndpoints', 'TwitterTransport']
|
#!/usr/bin/env python
"""A mercurial external differ for notebooks.
Uses nbdime to create diffs for notebooks instead of plain text diffs of JSON.
See the documentation for how to correctly configure mercurial to use this.
Use with:
hg extdiff -p hg-nbdiff [<commit> [<commit>]]
"""
from __future__ import print_... |
# imports
import matplotlib.pyplot as plt
import scipy.stats as stats
import numpy as np
import json
import pickle
from urllib.request import urlopen
# helper functions
def bisection(array, value):
'''Given an ``array`` , and given a ``value`` , returns an index j such that ``value`` is between array[j]
a... |
# Copyright 2016 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 agreed ... |
#!/usr/bin/python3
"""
Consumer
--------
Write a generator that consumes lines of a text and prints them to standard
output. Use this generator and a `flatten` function from the previous task to
print contents of two different files to a screen pseudo-simultaneously.
"""
from course.lesson07.task05.flatten import flat... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 6 13:55:09 2019
@author: Mrinmoy Bhattacharjee, PhD Scholar, EEE Dept., IIT Guwahati
"""
import os
import numpy as np
import pickle
from sklearn import preprocessing
import json
from sklearn.metrics import confusion_matrix, precision_recall_fscore_... |
"""
Incident Updates API Endpoint
"""
# Third Party Library
from django.views import View
from django.urls import reverse
from pyvalitron.form import Form
from django.http import JsonResponse
from django.forms.fields import DateTimeField
from django.utils.translation import gettext as _
# Local Library
from app.modul... |
class TreeNode:
def __init__(self, val, left, right):
self.val = val
self.right = right
self.left = left
class Solution:
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
Given two binary trees and imagine t... |
from owslib.etree import etree
from owslib.util import Authentication, openURL
from urllib.parse import urlencode, parse_qsl
class WFSCapabilitiesReader(object):
"""Read and parse capabilities document into a lxml.etree infoset
"""
def __init__(self, version="1.0", username=None, password=None, headers=... |
import shutil
from django.core.checks import Error, register
@register
def check_binaries(app_configs, **kwargs):
errors = []
if not shutil.which("convert", path="/usr/local/bin:/usr/bin:/bin"):
errors.append(
Error(
'The "convert" binary could not be found',
... |
import pytest
from ..traittypes import _DelayedImportError
def test_delayed_access_raises():
dummy = _DelayedImportError('mypackage')
with pytest.raises(RuntimeError):
dummy.asarray([1, 2, 3])
|
import os
import time
import pytest
from huntsman.drp.services.plotter import PlotterService
@pytest.fixture(scope="function")
def plotter_service(config, exposure_collection_real_data):
ps = PlotterService(config=config)
yield ps
# Make sure the service is stopped
ps.stop()
# Cleanup the imag... |
from nn_recipe.NN import Network
import numpy as np
from nn_recipe.utility import OneHotEncoder
from nn_recipe.DataLoader import MNISTDataLoader
# Loading Data fro mnist Data set
mnist = MNISTDataLoader(rootPath="C:\\Users\\mgtmP\\Desktop\\NNRecipe\\mnist", download=False)
mnist.load()
X_test = mnist.get_test_data().... |
import os
import unittest
from conans.model.env_info import DepsEnvInfo
from conans.model.profile import Profile
from conans.model.settings import Settings
from conans.paths import CONANFILE
from conans.test.utils.tools import TestBufferConanOutput, TestClient
from conans.util.files import save
class MockSetting(str... |
from abc import ABCMeta, abstractmethod
from argparse import ArgumentParser
from distutils import dir_util
import logging
from pathlib import Path
import platform
import sys
from typing import NoReturn
from hephaistos import backups, config, hashes, helpers, interactive, lua_mod, patchers, sjson_data
from hephaistos.c... |
############################################################
# -*- coding: utf-8 -*-
#
# # # # # # #
# ## ## # ## # #
# # # # # # # # # # #
# # ## # ## ## ######
# # # # # # #
#
# Python-based Tool for interaction with the 10micron mounts
# GUI with PyQT5 fo... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
import requests
import os
if 'TPU_DRIVER_MODE' not in globals():
url = 'http://' + os.environ['COLAB_TPU_ADDR'].split(':')[0] + ':8475/requestversion/tpu_driver0.1-dev20191206'
resp = requests.post(url)
TPU_DRIVER_MODE = 1
# The following is required to use TPU Driver as JAX's backend.
from jax.config import con... |
"""usersエンティティ用モジュール"""
from dataclasses import dataclass
from decimal import Decimal
from typing import Optional
from aws.dynamodb.base import Base
from aws.exceptions import DynamoDBError
ALL = 0
WEST_JR = 1
HANKYU = 2
HANSHIN = 3
@dataclass
class DelayInfoMessages(Base):
"""鉄道遅延情報メッセージ群クラス"""
west_jr: ... |
from typing import Optional, Iterable, Any
from platypush.message.event import Event
class DbusSignalEvent(Event):
"""
Event triggered when a signal is received on the D-Bus.
"""
def __init__(
self, bus: str, interface: str, sender: str, path: str, signal: str,
params: Optional[Iterab... |
"""
https://github.com/invl/retry
"""
import random
import time
from functools import partial, wraps
from typing import Callable, Optional, ParamSpecArgs, ParamSpecKwargs, Tuple, Type, List, Any
# sys.maxint / 2, since Python 3.2 doesn't have a sys.maxint...
from pydantic import Field, PositiveFloat, PositiveInt, ... |
# Distributed under the terms of the BSD 3-Clause License.
# The full license is in the file LICENSE, distributed with this software.
#
# Author: Philipp Schmidt <philipp.schmidt@xfel.eu>
# Copyright (c) 2020, European X-Ray Free-Electron Laser Facility GmbH.
# All rights reserved.
from collections.abc import Sequenc... |
# coding: utf-8
"""
SnapshotSnapshotsApi.py
Copyright 2016 SmartBear Software
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 ... |
#
# [To-Do] 1. Loop-Unrolling
# 2. Boundary Checks
# 3. Instuction Reordering
#
def tc_code_kernel_Store_Results(f, opt_gen_full, l_t3_mapping_tb_2D, l_t3_mapping_reg, size_reg_x, size_reg_y, idx_kernel, opt_accumulated):
#
#
#
f.write("\n")
f.write("\t// Store Results (Registe... |
# -*- coding: utf-8 -*-
from openprocurement.auctions.core.utils import opresource
from openprocurement.auctions.core.views.mixins import AuctionAuctionResource
@opresource(name='belowThreshold:Auction Auction',
collection_path='/auctions/{auction_id}/auction',
path='/auctions/{auction_id}/auc... |
from django.db import models
# ePrice(比價王)
# Create your models here.
class Post(models.Model):
### id
post_id = models.CharField(max_length=64) #帖子ID
# 以 https://www.eprice.com.tw/life/talk/9/5242470/1/ 而言, 帖子ID = 5242470
### user
pu_id = models.CharField(max_length=255) #... |
import lmfit
from time import time
class ModelFit:
""" We collect all information related to a fit between a pygom model and a set of data in this class
It has access to the model structure and defines all required parameters and details of fit """
def dumpparams(self,run_id=''): # Have to add self si... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-10-28 13:54
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ems', '0023_auto_20171028_0756'),
('registrations',... |
VO = "https://www.vote.org"
VA = "https://www.voteamerica.com"
CODE = 'code'
REG = 'reg'
POLLS = 'polls'
CITIES = 'cities' # XXX This should move to campaign.Campaign but it's disruptive
ABS = 'abs'
REGDL = 'regdl'
ABROAD = 'abroad'
class States:
ALABAMA = 'Alabama'
ALASKA = 'Alaska'
ARIZONA = 'Arizona'
ARKANSAS... |
from azure.mgmt.keyvault import KeyVaultManagementClient
from azure.keyvault import KeyVaultClient
from common_util import CommonUtil
from credentials.credentials_provider import ResourceCredentialsProvider
import logging as log
from azure.mgmt.keyvault.v2016_10_01.models import AccessPolicyUpdateKind, VaultAccessPolic... |
import numpy as np
from numpy.linalg import norm
from MeshFEM import sparse_matrices
def preamble(obj, xeval, perturb, etype, fixedVars = []):
if (xeval is None): xeval = obj.getVars()
if (perturb is None): perturb = np.random.uniform(low=-1,high=1, size=obj.numVars())
if (etype is None): etype = obj._... |
from functools import partial
from importlib import import_module
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.crypto import get_random_string
generate_random_string = partial(
get_random_string,
length=50,
allowed_chars='abcdefghijklmnopqrstu... |
from setuptools import setup
from os import path
# Read the contents of the README file
cwd = path.abspath(path.dirname(__file__))
with open(path.join(cwd, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name="pysvglib",
version="0.3.2",
description="SVG drawing library",
... |
from argparse import ArgumentParser
import numpy as np
import py360convert
import os
import cv2
import os.path as osp
from typing import Union
from mmseg.apis import inference_segmentor, init_segmentor, show_result_pyplot, ret_result
from mmseg.core.evaluation import get_palette
from PIL import Image
import mmcv
fro... |
import json
import requests
import logging
import hashlib
import time
from fake_useragent import UserAgent
from uuid import uuid4
from .camera import EzvizCamera
# from pyezviz.camera import EzvizCamera
COOKIE_NAME = "sessionId"
CAMERA_DEVICE_CATEGORY = "IPC"
API_BASE_URI = "https://apiieu.ezvizlife.com"
API_ENDPOINT... |
# coding: utf-8
import os
import sh
import logging
import shutil
import tempfile
from unittest import TestCase
from nose.tools import nottest
class UncanningTest(TestCase):
""" Let's try to uncan a new project and run tests to see everything is ok
Estimated running time 260s"""
def setUp(self):
... |
"""
Solution to https://adventofcode.com/2018/day/4
"""
from pathlib import Path
# path from the root of the project
INPUT_FILE = Path.cwd() / "2018" / "dec4.txt"
def part1() -> int:
sorted_lines = sorted(line for line in INPUT_FILE.read_text().split("\n") if line)
if __name__ == "__main__":
print(part1())... |
# -*- coding: utf-8 -*-
from numpy import cos, exp, sin
from ....Classes.Arc1 import Arc1
from ....Classes.Segment import Segment
from ....Classes.SurfLine import SurfLine
def build_geometry(self, alpha=0, delta=0, is_simplified=False):
"""Compute the curve (Segment) needed to plot the Hole.
The ending poin... |
import pydantic
import os
import yaml
import re
import typing
@pydantic.dataclasses.dataclass(frozen=True, order=True)
class RegexTestCase:
text: pydantic.constr()
matches: typing.Optional[typing.List[str]] = None
def run(self, regex):
""" evaluate the test case against the pattern """
ac... |
#!/usr/bin/env python3
__author__ = "Leon Wetzel"
__copyright__ = "Copyright 2021, Leon Wetzel"
__credits__ = ["Leon Wetzel"]
__license__ = "MIT"
__version__ = "1.0.1"
__maintainer__ = "Leon Wetzel"
__email__ = "post@leonwetzel.nl"
__status__ = "Production"
import praw
from nltk import sent_tokenize
def main():
... |
# coding: utf-8
# # Download TCGA Pan-Cancer Datasets from the UCSC Xena Browser
#
# This notebook downloads TCGA datasets for Project Cognoma. The file contents (text) remains unmodified, but files are given extensions and bzip2 compressed.
#
# [See here](https://genome-cancer.soe.ucsc.edu/proj/site/xena/datapages... |
def palindromeRearranging(inputString):
characters = {}
error_count = 0
for character in inputString:
if character not in characters:
characters[character] = 1
else:
characters[character] += 1
print(characters.values())
for value in characters.values(... |
from .mock_plugin import MockPlugin
__all__ = ['mock_plugin']
|
# encoding: utf-8
import os.path as osp
from .bases import BaseImageDataset
class target_test(BaseImageDataset):
"""
target_training: only constains camera ID, no class ID information
Dataset statistics:
"""
dataset_dir = 'target_test'
def __init__(self, root='./example/data/challenge_data... |
#!/usr/bin/python
from bs4 import BeautifulSoup
import urllib2
import csv
import codecs
linksList = []
#f = csv.writer(open("worksURI.csv", "w"))
#f.writerow(["Name", "Link"])
f = codecs.open("alllinkstrial.txt", encoding='utf-8', mode='w+')
#'http://www.isfdb.org/cgi-bin/ea.cgi?12578 ',
target_url=['ht... |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 16 21:11:25 2019
@author: Jorge
"""
import tkinter as tk
from tkinter import ttk
import crearcapasconv
from threading import Thread
import sys
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure impor... |
#!/usr/bin/env python
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
plt.style.use('classic')
fig = plt.figure()
population_age = [22,55,62,45,21,22,34,42,42,4,2,102,95,85,55,110,120,70,65,55,111,115,80,75,65,54,44,43,42,48]
bins = [0,10,20,30,40,50,60,70,80,90,100]
plt.hist(population_age,... |
# -----------------------------------------------------------------------------
# Copyright * 2014, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration. All
# rights reserved.
#
# The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache
#... |
from django.shortcuts import render,redirect
from django.contrib.auth.models import User
from .models import Project,Profile
from .forms import ProjectForm,ProfileForm,VoteForm
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.response im... |
from torchvision import datasets, transforms
def imagenet_transformer():
transform=transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.2... |
import base64
import json
import logging
from io import BytesIO
from urllib.parse import urljoin
import feedparser
from flask_babel import lazy_gettext as _
from PIL import Image
from authentication_document import AuthenticationDocument
from model import Hyperlink
from opds import OPDSCatalog
from problem_details im... |
#!/usr/bin/env python
# Copyright 2005-2009,2011 Joe Wreschnig
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
import glob
import os
import shutil
import sys
import subprocess
from... |
# -*- coding: utf-8 -*-
# :Project: pglast -- DO NOT EDIT: automatically extracted from pg_trigger.h @ 13-2.0.6-0-ga248206
# :Author: Lele Gaifax <lele@metapensiero.it>
# :License: GNU General Public License version 3 or later
# :Copyright: © 2017-2021 Lele Gaifax
#
from enum import Enum, IntEnum, IntFlag, auto... |
import ops
import ops.cmd
import ops.env
import ops.cmd.safetychecks
VALID_OPTIONS = ['all', 'permanent', 'cached']
class PasswordDumpCommand(ops.cmd.DszCommand, ):
def __init__(self, plugin='passworddump', **optdict):
ops.cmd.DszCommand.__init__(self, plugin, **optdict)
def validateInput(self):
... |
"""An App Template based on Bootstrap with a header, sidebar and main section"""
import pathlib
import awesome_panel.express as pnx
import panel as pn
from awesome_panel.express.assets import SCROLLBAR_PANEL_EXPRESS_CSS
BOOTSTRAP_DASHBOARD_CSS = pathlib.Path(__file__).parent / "bootstrap_dashboard.css"
BOOTST... |
import codecs
import json
import matplotlib.pyplot as plt
import numpy as np
import os
import itertools
def plot_confusion_matrix(cm,
target_names,
title='Confusion matrix',
prefix="",
cmap=None,
... |
class DataFilePath:
def __init__(self):
self.dataDir = '../data/citydata/season_1/'
return
def getOrderDir_Train(self):
return self.dataDir + 'training_data/order_data/'
def getOrderDir_Test1(self):
return self.dataDir + 'test_set_1/order_data/'
def getTest1Dir(self)... |
from __future__ import print_function
import argparse
import logging
import os
import warnings
import torch.nn as nn
import torch.utils.data
from torch.utils.data import SubsetRandomSampler
from torch.utils.tensorboard import SummaryWriter
from Colorization import utils
from Multi_label_classification.dataset.datase... |
from django.shortcuts import render
from django.http import Http404
from django.views.generic.edit import UpdateView
from django.views.generic import ListView, View
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.utils.decorators import method_decorator... |
from src.traces.traces import main as traces_main
import pandas as pd
def main():
db_path = '/Users/mossad/personal_projects/AL-public/src/crawler/crawled_kaggle.db'
traces_path = '/Users/mossad/personal_projects/AL-public/src/traces/extracted-traces.pkl'
clean_traces_path = '/Users/mossad/personal_project... |
# -*- coding: UTF-8 -*-
# Copyright 2012-2017 Luc Saffre
#
# License: BSD (see file COPYING for details)
"""Defines the :class:`Page` model.
"""
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import pgettext_lazy
from django.utils.translation import... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from annotator import annotation
from annotator import document
from h._compat import text_type
class Annotation(annotation.Annotation):
@property
def uri(self):
"""Return this annotation's URI or an empty string.
The uri is es... |
import os
import string
from file2quiz import utils, reader
def convert_quiz(input_dir, output_dir, file_format, save_files=False, *args, **kwargs):
print(f'##############################################################')
print(f'### QUIZ CONVERTER')
print(f'##############################################... |
# Copyright (c) 2021 by xfangfang. All Rights Reserved.
#
# Using potplayer as DLNA media renderer
#
# Macast Metadata
# <macast.title>PotPlayer Renderer</macast.title>
# <macast.renderer>PotplayerRenderer</macast.title>
# <macast.platform>win32</macast.title>
# <macast.version>0.4</macast.version>
# <macast.host_versi... |
import numpy as np
from metod_alg import objective_functions as mt_obj
from metod_alg import metod_algorithm_functions as mt_alg
def test_1():
"""
Test for mt_alg.forward_tracking() - check that when flag=True,
track is updated.
"""
np.random.seed(90)
f = mt_obj.several_quad_function
g = ... |
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import absolute_import, division, print_function, unicode_literals
from logging import getLogger
import os
import sys
from .main import main as main_main
from .. import CondaError
from .._vendor.auxlib.i... |
with open('input') as fp:
grid = [line[:-1] for line in fp]
grid_width = len(grid[-1])
x, y = (0, 0)
n_trees = 0
while y < len(grid):
if grid[y][x % grid_width] == '#':
n_trees += 1
x += 3
y += 1
print(n_trees, "trees")
|
from __future__ import absolute_import
import sys, os
from subprocess import Popen, PIPE, check_output
import socket
from ..seqToolManager import seqToolManager, FeatureComputerException
from .windowHHblits import WindowHHblits
from utils import myMakeDir, tryToRemove #utils is at the root of the package
class HHBlit... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
# edge cases - if the element is present at start or last
if not head:
... |
# Export individual functions
# Copy
from .scopy import scopy
from .dcopy import dcopy
from .ccopy import ccopy
from .zcopy import zcopy
# Swap
from .sswap import sswap
from .dswap import dswap
from .cswap import cswap
from .zswap import zswap
# Scaling
from .sscal import sscal
from .dscal import dscal
from .cscal i... |
import torch
import trtorch
precision = 'fp16'
ssd_model = torch.hub.load('NVIDIA/DeepLearningExamples:torchhub', 'nvidia_ssd', model_math=precision)
input_shapes = [1, 3, 300, 300]
model = ssd_model.eval().cuda()
scripted_model = torch.jit.script(model)
compile_settings = {
"input_shapes": [input_shapes],
"... |
# Main file for the PwnedCheck distribution.
# This file retrieves the password, calls the module check_pwd,
# and check if the password has been breached by checking it with
# the database in the following website
# https://haveibeenpwned.com/Passwords
import sys
import logging
from getpass import getpass
from checkp... |
"""
================================
Symbolic Aggregate approXimation
================================
Binning continuous data into intervals can be seen as an approximation that
reduces noise and captures the trend of a time series. The Symbolic Aggregate
approXimation (SAX) algorithm bins continuous time series into... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-10-10 01:54
from __future__ import unicode_literals
import django.core.files.storage
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cxp_v1', '0001_initial'),
]
operations = [
m... |
# -*- coding: utf-8 -*-
import pytest
from click.testing import CliRunner
from jak.app import main as jak
import jak.crypto_services as cs
@pytest.fixture
def runner():
return CliRunner()
def test_empty(runner):
result = runner.invoke(jak)
assert result.exit_code == 0
assert not result.exception
... |
try:
import matplotlib.pyplot as plt
import fuzzycorr.prepro as pp
from pathlib import Path
import numpy as np
import gdal
except:
print('ModuleNotFoundError: Missing fundamental packages (required: pathlib, numpy, gdal).')
cur_dir = Path.cwd()
Path(cur_dir / "rasters").mkdir(exist_ok=True)
... |
"""Support for Vallox ventilation units."""
from __future__ import annotations
from dataclasses import dataclass, field
import ipaddress
import logging
from typing import Any, NamedTuple
from uuid import UUID
from vallox_websocket_api import PROFILE as VALLOX_PROFILE, Vallox
from vallox_websocket_api.exceptions impor... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.