content stringlengths 5 1.05M |
|---|
import sys, subprocess, os.path
from os import path
if len(sys.argv) > 2:
prefix = sys.argv[1]
targetLanguage = sys.argv[2]
else:
print("please provide the prefix, and the target language")
exit(-1)
print("## video2image, prefix: " + prefix + ", targetLanguage: " + targetLanguage)
filePath = "build/... |
import io
import sys
from argparse import Namespace
from pathlib import Path
from project.core import command
from project.core.parser import Parser
from project.core.terminal import Terminal
def setup(parser: Parser) -> None:
parser.add_command(BrainFuck())
class BrainFuck(command.Command):
"""
Brainf... |
from .. import api
from lib.mongodb import db
from .model import FeedModel
class Venue(FeedModel):
collection = db.venues
api_function = api.venue
api_id_name = 've'
cache_time = 60 * 60 * 24
|
import gym
from ..simulator.Simulator import Simulator
from gym import error, spaces, utils
from gym.utils import seeding
import numpy as np
class DCGymEnv(gym.Env):
metadata = {'render.modes': ['human']}
def __init__(self):
self.num_packets = 0
self.num_sp = 0
self.num_storage = 0
... |
t = int(input())
answers = []
for a in range(t):
line = input().split()
a = int(line[0])
b = int(line[1])
x = int(line[2])
y = int(line[3])
n = int(line[4])
ans = 10000000000000000
for i in range(0,2):
da = min(n, a-x)
db = min(n - da, b - y)
ans = min(ans, (a - d... |
#!/usr/bin/pyhton
#from guppy import hpy; h = hpy()
#import cProfile,pstats
import numpy as np
from line_profiler import LineProfiler
from PlexFile import PlexFile
from PlexUtil import PlexUtil,reconstruct_word
def run():
with PlexFile('../../data/sparse-noise.plx') as pf:
pu = PlexUtil()
#print "r... |
#! uenv/bin/python3.4
#-*-coding:utf8 -*-
# open 打开文件 r 代表读
try:
f = open("../README.md",'r')
print(f.read())
finally:
if f:
f.close()
#打开文件必须关闭,但是可以用以下方式
with open("../README.md",'r') as f:
print(f.read())
#read(size)
print('<----------3-------->')
with open("../README.md",'r') as f:
pr... |
"""
Tags
====
Tagservice group->tag
"""
_schema = {
'tag': {'type': 'string',
'required': True,
},
'group': {'type': 'string',
'required': True},
'freq': {'type': 'integer',
... |
import argparse
import ftfy
import json
import os
import random
from fever_utils import extract_sentences, make_sentence_id, normalize_text, split_sentence_id, truncate
def generate_data(args):
queries = {}
labels = {}
evidences = {}
evidence_relevances = {}
docs = {}
num_truncated = 0
#... |
from core.vectors import PhpFile
from core.module import Module
from core.argparsers import SUPPRESS
from core import modules
from core.loggers import log
from core import messages
import utils
import os
class Scan(Module):
"""TCP Port scan."""
aliases = ['nmap']
def init(self):
self.register_i... |
import matplotlib.pyplot as plt
import matplotlib
import cPickle as pic
print "Loading Aromatic"
aromatic = pic.load(open('aromatic.pkl','rb'))
aromatic = [i/max(aromatic) for i in aromatic]
print "Loading Positive"
positive = pic.load(open('positive.pkl','rb'))
positive = [i/max(positive) for i in positive]
print "... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import traceback
PATH = 'C:\Program Files (x86)\chromedriver.exe'
driver =... |
# script for processing Weinstock(2016)
# Author: Sangaman Senthil
# Date: February 5th, 2020, edited June 14th, by Elizabeth Chun
import pandas as pd
# This study downloads as a zipped folder containing data tables and forms
# First download the entire dataset. Do not rename the downloaded folder
# Place the downloa... |
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [[0 for _ in range(m + 1)] for _ in range(n + 1)]
'''
ans = 0
def backtrack(cur_m, cur_n):
if cur_m == m and cur_n == n:
nonlocal ans
ans += 1
return
... |
import googlemaps
import sys
from .models.location import Location
from .models.distance import Distance
from .exceptions.invalid_use_error import InvalidUseError
from .exceptions.server_error import ServerError
from .models.db_distance import DbDistance
class GMapsService:
googleMapsClient = None
GOOGLE_MAPS_... |
print 7,49
for i in range(1,8):
for j in range(1,8):
print i,j
|
import requests
import os
import sys
if len(sys.argv) <= 1:
print("Please pass your Shuffle apikey")
exit()
apikey = sys.argv[1]
print(apikey)
baseurl = "https://shuffler.io"
if len(sys.argv) > 2:
baseurl = "http://localhost:5002"
baseurl = sys.argv[2]
print("Uploading apps to %s" % baseurl)
def up... |
from .NAF import *
from .PG import *
from .DQN import * |
import sqlite3
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
from flask import Flask, render_template, \
redirect
from flask import request
from model_sqlite import save_doc_as_file_sqlite, \
read_doc_as_file_sqlite, \
get_last_entries_f... |
from idact.detail.nodes.node_internal import NodeInternal
def install_compute_node_access_key(access_node: NodeInternal):
"""Adds the local key to authorized keys file for compute nodes,
in case it was not added, which is a plausible scenario, when pulling
deployments.
:param access_node:... |
# -*- coding: UTF-8 -*-
# Copyright 2012-2017 Luc Saffre
# License: BSD (see file COPYING for details)
from __future__ import unicode_literals
"""Importing this module will install default workflows for
`lino_xl.lib.courses`.
"""
from django.utils.translation import ugettext_lazy as _
from lino.api import dd, rt... |
# -*- coding: utf-8 -*-
r"""
tsgettoolbox command line/library tools to retrieve time series.
This program is a collection of utilities to download data from various
web services.
"""
from __future__ import absolute_import, division, print_function
import datetime
import logging
import os
from typing import List, Op... |
"""
sphinx_matlabdoc_builder
~~~~~~~~~~~~~~~~~~~~~~~~
A Sphinx extension for generating Matlab HTML docs.
:copyright: Copyright 2019 Isaac Lenton (aka ilent2)
:license: BSD, see LICENSE for details.
"""
from .matlab_doc_builder import MatlabDocBuilder
def setup(app):
app.add_builder(MatlabDoc... |
from flask import request
from flask_restful import Resource
from flask_jwt_extended import jwt_required, create_access_token, get_jwt_identity, get_raw_jwt
from app.utils import str2uuid
from app.utils.resource_extention import ResourceMixin
from app.security import TokenBlacklist
from app.api.user.models import Us... |
from sqlalchemy import or_
from models import OSMPoint
# This file contains the OSM tags we want to consider as amenities.
# Edit this file to change OSM density and accessibility analysis.
# The same tag set is used for *both* OSM amenity density layer
# *and* OSM amenity accessibility layer.
#
# We want to consider... |
from collections import Counter
from textwrap import dedent
from typing import List
from cool_commits.utils import git_commit_info
# A list of instances of BaseParser, this way
# we can auto discover al inherited parsers
all_parsers = []
class BasePaerserMeta(type):
def __init__(cls, name, bases=None, object=No... |
# MIT License
# Copyright (c) 2018 Addison Lynch
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, ... |
from hypothesis import given
from hypothesis.strategies import text
from iso3166 import countries
import pytest
from profiles.exceptions import AffiliationNotFound
from profiles.models import Address, Affiliation, Date, Name, Profile
@given(text(), text(), text())
def test_it_can_be_printed(id_, name, orcid):
pr... |
# -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011, 2012 Sebastian Wiesner <lunaryorn@gmail.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at... |
# =============
# SCIENCE
# =============
MATH_FORMULAS = [
"A = (ab)/2",
"A = a2",
"A = ab",
"A = (h(a + b))/2",
"V = (Ah)/3",
"xn*xm = xn + m",
"(xn)/(xm) = x^n - m",
"(x/y)^n = (x^n)/(y^n)",
"x^n*y^n = (xy)^n",
"ax2 + bx + c = 0.",
"(a/b)/(c/d) = (a/b) * (d/c)",
"π = p... |
import calendar
import collections
from braces.views import JSONResponseMixin, PermissionRequiredMixin
from django.conf import settings
from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.... |
"""
Form for creating a group object
"""
from django import forms
from django.contrib.auth.models import Group as Role
class RoleForm(forms.ModelForm):
"""
DjangoForm Class, that can be rendered to create deliverable HTML
Args:
forms : Defines the form as an Model form related to a database objec... |
import collections
from typing import Dict, List, Union
AttrMap = Dict[str, str]
Text = str
ElementData = collections.namedtuple("ElementData", ["tag_name", "attributes"])
NodeType = Union[Text, ElementData]
class Node():
def __init__(self, children, node_type):
# type: (List[Node], NodeType) -> None
... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Read image
img = cv2.imread("imori.jpg").astype(np.float)
H, W, C = img.shape
# Bi-lenear
a = 1.5
aH = int(a * H)
aW = int(a * W)
y = np.arange(aH).repeat(aW).reshape(aW, -1)
x = np.tile(np.arange(aW), (aH, 1))
y = (y / a)
x = (x / a)
... |
import subprocess
"""
▄▀▀▄ ▄▀▄ ▄▀▀█▄ ▄▀▀▄ ▀▄ ▄▀▀█▄▄▄▄ ▄▀▀▀▀▄ ▄▀▀█▄▄▄▄ ▄▀▄▄▄▄
█ █ ▀ █ ▐ ▄▀ ▀▄ █ █ █ █ ▐ ▄▀ ▐ █ █ ▐ ▐ ▄▀ ▐ █ █ ▌
▐ █ █ █▄▄▄█ ▐ █ ▀█ █▄▄▄▄▄ ▀▄ █▄▄▄▄▄ ▐ █
█ █ ▄▀ █ █ █ █ ▌ ▀▄ █ █ ▌ █
▄▀ ▄▀ █ ▄▀ ▄▀ █ ▄▀▄▄▄▄ ... |
import base64
import time
from collections import defaultdict
import pytest
from cryptography.fernet import Fernet
from dask_gateway_server import objects
def check_consistency(db):
users = db.db.execute(objects.users.select()).fetchall()
clusters = db.db.execute(objects.clusters.select()).fetchall()
wo... |
import jsonschema
import json
from jsonschema import validate
from iccjson.jconnect import *
def test_ing_schema():
'''
should update this part
using separate schema file for ingredient
# ing_schema = get_schema("ing")
# print(ing_schema)
# ing = ing_test[0]
# ing_schema = get_schema("ing... |
import os
from os.path import join, dirname, abspath
import pytest
EXAMPLE_DIR = abspath(join(dirname(__file__), '..'))
def iter_example_filenames():
for filename in os.listdir(EXAMPLE_DIR):
if filename.startswith('__'):
continue
if not filename.endswith('.py'):
continue
... |
'''
Notice how this file does not import syshub or know about it
in any way.
'''
import sys
def say_something():
print('hello')
def input_something():
print('prompt: ', end='')
print(sys.stdin.readline())
def raise_something():
raise ValueError |
#!/usr/bin/env python3
"""
Problem : Insertion Sort
URL : http://rosalind.info/problems/ins/
Author : David P. Perkins
"""
def swap(array, a, b):
array[a], array[b] = array[b], array[a]
swap.swapcount += 1
swap.swapcount = 0;
def insertionSort(array):
for k in range(1, len(array)):
while k... |
import altair as alt
import pandas as pd
import numpy as np
from datetime import date
from os import path
from flask import current_app as app
import redis, requests, time, pyarrow
def connect():
return redis.Redis( host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT'] )
def fetchData(rconn):
context =... |
"""Train and save neural networks from the DeepOBS library."""
import os
import warnings
import numpy as np
from deepobs.pytorch.runners import StandardRunner
from shared import CONFIGURATIONS, get_summary_savepath, save_checkpoint_data
from exp.utils.path import write_to_json
HEREDIR = os.path.dirname(os.path.absp... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.management.base import BaseCommand
from credocommon.jobs import recalculate_user_stats
from credocommon.models import User
class Command(BaseCommand):
help = "Recalculate stats for all users"
def handle(self, *args, **options)... |
from chatbot_payload.payloads import Payloads as ChatbotPayloads
__all__ = [
"ChatbotPayloads"
]
__version__ = "0.0.1"
|
#!/usr/bin/python
import os,sys
import HAConf
from HAConf import configuration
from GenerateCGSystem import generic_system
import pdbio,ndxio,CartesianToolkit
gromacs = configuration['gromacs_location']
def lipid_list_breakdown(lipid_positions,number_of_atoms):
return [lipid_positions[i*number_of_atoms:(i+1)*number... |
"""Example python 3.x web project with everything from unit testing to continuous deployment."""
__title__ = "minimalpy"
__version__ = VERSION = "0.3.0"
__author__ = "blankdots"
__license__ = "Apache License 2.0"
|
# Copyright 2013 IBM Corp.
#
# 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 agree... |
import re
from dataclasses import dataclass
from z3 import Int, Optimize, If
@dataclass
class Nano:
x: int
y: int
z: int
r: int
@property
def pos(self):
return self.x, self.y, self.z
def __sub__(self, other):
return sum(abs(a - b) for a, b in zip(self.pos, other.pos))
... |
import heapq
import math
n, m = map(int, input().split())
start = int(input())
graph = [[] for _ in range(n + 1)]
distance = [math.inf] * (n + 1)
for _ in range(m):
a, b, c = map(int, input().split())
graph[a].append((b, c))
def dijkstra(start):
queue = []
heapq.heappush(queue, (0, start))
dista... |
from functools import lru_cache
from typing import Any
try:
import ujson as json
JDecodeError = ValueError
except ImportError:
import json
JDecodeError = json.decoder.JSONDecodeError
import attr
from multidict import MultiDict, MultiDictProxy
class JsonDecodeError(JDecodeError):
pass
def json_du... |
# True means refresh all test files (only partially implemented at the moment)
import os
refresh_files = False
# True means that we skip all tests that go outside our own environment (e.g. wikidata, etc)
# You can set this to True, False or base it on the present of a file in the root directory called "tests/data/SK... |
from itertools import permutations
n, m = [int(each) for each in input().split(" ")]
for each in permutations(range(1, n+1), m):
print(" ".join([str(e) for e in each]))
|
import numpy
my_array = numpy.array(input().split(), int)
print(numpy.reshape(my_array,(3,3)))
|
from django.contrib import admin
from gcb_web_auth.models import *
# Register your models here.
admin.site.register(OAuthService)
admin.site.register(OAuthToken)
admin.site.register(DukeDSAPIToken)
admin.site.register(GroupManagerConnection)
admin.site.register(DDSUserCredential)
admin.site.register(DDSEndpoint)
|
from opendc.util.database import DB
def test_get_traces(client, mocker):
mocker.patch.object(DB, 'fetch_all', return_value=[])
assert '200' in client.get('/v2/traces').status
|
from __future__ import absolute_import
import os
import logging
import shutil
import subprocess
import six
from functools import wraps
from six.moves.urllib.parse import urlparse, urlunparse
log = logging.getLogger(__name__)
def log_io_error(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
... |
"""
This module provides dictionaries to look up synonyms and antonyms
"""
# -*- coding: utf-8 -*-
import nltk
import pickle
import pkg_resources
from .utils import eprint
try:
nltk.data.find('wordnet')
from nltk.corpus import wordnet
NLTKWORDNET = True
except:
eprint("* NOTE: Synonym dictionary is im... |
import pytest
pytest.main(['-s'])
|
import nibabel as nib
import nrrd
import os
import numpy as np
from nipype.interfaces.base import (
BaseInterface, TraitedSpec,
BaseInterfaceInputSpec, traits,
Directory)
from core.utils.filemanip import split_filename
from skimage.transform import resize
from skimage.filters.thresholding import threshold_o... |
@task()
def path(self):
url = self.locust.host + '/path'
data = '''content'''
self.response = self.client.request(
method='POST',
url=url,
data=data,
)
|
# follow.py
from module import Module
import sys, os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from constants import *
class FollowModule(Module):
def __init__(self, timer, leftMotor, rightMotor, intakeMotor, wallFollow, forwardSpeed, blockSwitch):
self.timer = t... |
import ROOT
from ROOT import gROOT , gStyle
import os, sys
import time
from collections import OrderedDict
sys.path.append('%s/../analysis/utils' %os.getcwd() )
from helper import *
#from workflow import *
ROOT.ROOT.EnableImplicitMT(12)
ROOT.TH1.SetDefaultSumw2()
gROOT.SetBatch(True)
gStyle.SetOptStat(0)
gStyle.Se... |
# ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2009 cocos2d
# 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 sou... |
# Copyright (c) 2019 Riverbed Technology, Inc.
#
# This software is licensed under the terms and conditions of the MIT License
# accompanying the software ("License"). This software is distributed "AS IS"
# as set forth in the License.
import abc
class Transport(object, metaclass=abc.ABCMeta):
"""
Abstract ... |
# coding: utf-8
from django.conf import settings
from django.db import models
from django.utils.translation import gettext_lazy as _
# TODO
class Merchant(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='merchants')
member_unified = models.CharField(_('會員證號'), max_length=10, he... |
"""
show_igmp_interface.py
IOSXR parsers for the following show commands:
* show igmp interface
* show igmp vrf <vrf> interface
* show igmp summary
* show igmp vrf <vrf> summary
* show igmp groups detail
* show igmp vrf <vrf> groups detail
"""
# python
import re
import logging
from ge... |
from .gbif import GBIFExtractor
from .scholar import GoogleScholarExtractor
from .wikipedia import WikipediaExtractor
from .coreac import CoreACExtractor
from .scimagojr import load_scimagojrdb |
import sys
import ftplib
import os
from ftplib import FTP
import datetime as dt
ftp = FTP("ftp.msci.com")
ftp.login('wnvyzpng', 'hxcksyyx')
# START USER INPUT
# source is file directory of MSCI FTP
source = "/download/"
# source = "/download/history/"
# choose where to download to local drive
dest = "F:/download/"
# ... |
# Copyright 2019 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, ... |
# Description: Run the AO function from the pymolshortcuts.py file to generate the photorealistic effect.
# Source: placeHolder
"""
cmd.do('cmd.do("AO")')
"""
cmd.do('cmd.do("AO")')
|
# Defining imports
import cv2
import video as vid
import thresholding as thresh
import person as p
print(cv2.__version__)
# Defining video paths
lengthsVideoPath = "../media/video/edited/lengths.avi"
lengthsVideoPath2 = "../media/video/edited/lengths2.avi"
splashingVideoPath = "../media/video/edited/splashing.avi"
co... |
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd
import numpy
import random
from sklearn.decomposition import TruncatedSVD
from pandas import DataFrame
vectorizer = TfidfVectorizer(stop_words='english')
df = pd.read_csv("train_set.cs... |
"""
@auther Hyunwoong
@since 6/28/2020
@see https://github.com/gusdnd852
"""
from kochat.model.intent.cnn import CNN
from kochat.model.intent.lstm import LSTM
__ALL__ = [CNN, LSTM]
|
"""
In this module we test the air_quality blocks with kuzzle. Air quality appears when an admin (city
or suburd) is called.
"""
from pydantic import ValidationError
from pytest import raises
from idunn.blocks.environment import Weather
from idunn.places import Admin
import json
import os
import responses
import re
f... |
#!/usr/bin/python
# Test that we can change build directory using
# the 'build-dir' project attribute.
from BoostBuild import Tester
import string
import os
t = Tester()
# Test that top-level project can affect build dir
t.write("project-root.jam", "import gcc ; ")
t.write("Jamfile", """
project
: build-dir b... |
# -*- coding: utf-8 -*-
"""
Serialization schemas for Asset_groups resources RESTful API
----------------------------------------------------
"""
from flask_marshmallow import base_fields
from flask_restx_patched import ModelSchema
from .models import AssetGroup, AssetGroupSighting
class BaseAssetGroupSightingSchem... |
# encoding: UTF-8
"""
Implement phytool command 'frib-layout'.
Convert FRIB Expanded Lattice File (XLF) to general layout data file.
:author: Dylan Maxwell <maxwelld@frib.msu.edu>
:date: 2015-06-09
"""
from __future__ import print_function
import sys, os.path, logging, traceback
from argparse import ArgumentPars... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import os.path as op
import sys
import logging
from jinja2 import Template
from jcvi.apps.base import sh, mkdir
from jcvi.formats.base import must_open
tmpl_slurm = '''#!/bin/bash -l
#SBATCH -N {{ nodes }} -n {{ ntasks }} -c {{ cores }}
#SBATCH --time={{ time }... |
import os
import queue
import pytest
from raythena.drivers.communicators.harvesterFileMessenger import HarvesterFileCommunicator
from raythena.drivers.communicators.harvesterMock import HarvesterMock
from raythena.drivers.communicators.harvesterMock2205 import HarvesterMock2205
@pytest.fixture
def request_queue():
... |
from unittest import TestLoader
def get_tests():
return TestLoader().discover('tests/')
|
# -*- coding: utf-8 -*-
import sys
import difflib
import numpy as np
import pandas as pd
from ..utils import units
from ..utils import instance
from ..utils import listtools
def arg_closest_num(arr, value, check):
if check(value):
return value
else:
return np.argmin(np.abs(arr - value))
def... |
#!/usr/bin/env python
#porting from https://github.com/cfce/chilin/blob/master/chilin2/modules/ceas/qc.py
from optparse import OptionParser
import sys
import os
import json
def json_dump(json_dict): # json
"""
dump out uniform json files for collecting statistics
:param json_dict: output python dict to j... |
import os
import argparse
os.system('rm -rf reports')
os.system('mkdir -p reports')
parser = argparse.ArgumentParser()
parser.add_argument("--browser", help="Browser to run tests against")
parser.add_argument("--test", help="Test to run")
args = parser.parse_args()
#CMD = f'python -m unittest -k test_ {args.test if... |
import sys
from datetime import datetime
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
class Plotter:
def __init__(self, since=None, until=None):
figsize = (12, 6)
self.fig = plt.figure(figsize=figsize)
self.fig.suptitle('profile plotter')
self.subp... |
project = "OCDS Additions"
master_doc = "index"
|
# coding:utf-8
#!/usr/bin/python
#
# Copyright (c) Contributors to the Open 3D Engine Project.
# For complete copyright and license terms please see the LICENSE at the root of this distribution.
#
# SPDX-License-Identifier: Apache-2.0 OR MIT
#
#
# -- This line is 75 characters ------------------------------------------... |
# Generated by Django 2.0.6 on 2018-08-30 14:48
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('notifications', '0002_auto_20180829_2317'),
]
operations = [
migrations.Al... |
import torch
from torch_scatter import scatter_add
from torch_geometric.utils import softmax
from ..inits import reset
class GlobalAttention(torch.nn.Module):
r"""Global soft attention layer from the `"Gated Graph Sequence Neural
Networks" <https://arxiv.org/abs/1511.05493>`_ paper
.. math::
\ma... |
import time
import contextlib
from cloudant.client import CouchDB
from app.config import config
@contextlib.contextmanager
def get_db_connection():
client = CouchDB(config['DBUSER'], config['DBPASS'],
url=config['COUCHDB'], connect=True,
auto_renew=True)
db = client[config['DBNAME']]
try:
... |
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
root.geometry("1255x944")
# photo = PhotoImage(file="1.png")
# For Jpg Images
image = Image.open("photo.jpg")
photo = ImageTk.PhotoImage(image)
label = Label(image=photo)
label.pack()
root.mainloop()
|
import sqlite3
from sqlite3 import Error
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
import folium
conn = sqlite3.connect('../data/rodents_data.db')
sql_statement = """SELECT latitude,longitude,count(inspection_date) as recurrence_index FROM 'rodent_incidents' where inspection_dat... |
import json
from xautoml.model_details import ModelDetails
from xautoml.tests import get_168746, get_7306
from xautoml.util import pipeline_utils
def test_source():
main = get_7306()
X, y, pipeline = main.pipeline('00:00:00')
step = 'SOURCE'
pipeline, X, additional_features = pipeline_utils.get_subp... |
# import tensorflow as tf
# from tensorflow import keras
from typing import List
import numpy as np
def compute_accuracy(ground_truth: List[str], predictions: List[str]) -> np.float32:
accuracy = []
for index, label in enumerate(ground_truth):
prediction = predictions[index]
total_count = len(l... |
# -*- coding: utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the... |
import os
os.environ["GLOG_minloglevel"] = "2"
os.environ["MAGNUM_LOG"] = "quiet"
import logging
import numpy as np
import quaternion
import cv2
import habitat
habitat.logger.setLevel(logging.ERROR)
from habitat.utils.visualizations.maps import get_topdown_map_from_sim, colorize_topdown_map
cfg = habitat.get_config... |
# -*- coding: utf-8 -*-
from typing import Optional, Any, List
from datetime import datetime
from overrides import overrides
from recc.chrono.datetime import today
from recc.log.logging import recc_database_logger as logger
from recc.database.struct.daemon import Daemon
from recc.database.interfaces.db_daemon import D... |
import datetime
from telethon import events
from telethon.errors.rpcerrorlist import YouBlockedUserError
from telethon.tl.functions.account import UpdateNotifySettingsRequest
from uniborg.util import admin_cmd
@borg.on(admin_cmd("df ?(.*)"))
async def _(event):
if event.fwd_from:
return
if not event.... |
# Copyright (c) 2022 PaddlePaddle 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 appli... |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Qbox(MakefilePackage):
"""Qbox is a C++/MPI scalable parallel implementation of first-prin... |
import numpy as np
from openpnm.utils import Docorator
docstr = Docorator()
__all__ = ["antoine", "water"]
@docstr.get_sections(base='models.phase.vapor_pressure', sections=['Returns'])
@docstr.dedent
def antoine(target, A, B, C, temperature='pore.temperature'):
r"""
Uses Antoine equation to estimate vapor ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.