text stringlengths 2 999k |
|---|
from r_boulton1 import Spam
s = Spam()
del s[42]
|
from typing import Dict # isort:skip
from catalyst.core import _State
from catalyst.utils.tools.typing import (
Criterion, Device, Model, Optimizer, Scheduler
)
class State(_State):
"""
An object that is used to pass internal state during train/valid/infer.
"""
def __init__(
self,
... |
import numpy as np
from monty.ops import *
def test_get_size_on_first_dim():
assert get_size_along_first_dim(tf.convert_to_tensor([1, 2])) == 2
def test_assign_zero_at_index_list():
out = set_index_list_to_zero(tf.constant([[1, 1], [1, 2]], dtype=tf.int32, shape=[2, 2]),
tf.... |
from enum import IntEnum
from typing import Dict, Union, Callable
from cereal import log, car
import cereal.messaging as messaging
from common.realtime import DT_CTRL
from selfdrive.config import Conversions as CV
from selfdrive.locationd.calibrationd import MIN_SPEED_FILTER
AlertSize = log.ControlsState.AlertSize
Al... |
"""Support for Android IP Webcam settings."""
from homeassistant.components.switch import SwitchDevice
from . import (
CONF_HOST, CONF_NAME, CONF_SWITCHES, DATA_IP_WEBCAM, ICON_MAP, KEY_MAP,
AndroidIPCamEntity)
DEPENDENCIES = ['android_ip_webcam']
async def async_setup_platform(
hass, config, async_... |
from django.db import models
from django.contrib.auth.models import User
import uuid
# Create your models here.
class Article(models.Model):
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
user = models.ForeignKey(User,on_delete=models.SET_NULL, null=True, blank=True)
... |
"""
A fake implementation of the Vuforia Web Services API.
See
https://library.vuforia.com/articles/Solution/How-To-Use-the-Vuforia-Web-Services-API
"""
from __future__ import annotations
import base64
import dataclasses
import datetime
import email.utils
import random
import uuid
from http import HTTPStatus
from ty... |
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
import discord
from discord.ext import commands
import user_db
import config
# connect to coind
rpc_connection = 'http://{0}:{1}@{2}:{3}'.format(config.rpc_user, config.rpc_password, config.ip, config.rpc_port)
class Info(commands.Cog):
def __i... |
def vote(ack, body, respond, action):
ack()
user = body["user"]["id"]
blocks = body["message"]["blocks"]
for block in blocks:
if block["block_id"] == action["block_id"]:
break
if user not in block["text"]["text"]:
block["text"]["text"] += "<@" + user + ">\n"
else:
... |
# -*- coding: utf-8 -*-
#
# mlops-alura-deploy documentation build configuration file, created by
# sphinx-quickstart.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration va... |
from veidt.rfxas.core import XANES
from veidt.rfxas.prediction import CenvPrediction
import pandas as pd
import os, unittest
import warnings
comp_test_df_path = os.path.join(os.path.dirname(__file__), 'comp_spectra_test.pkl')
comp_test_df = pd.read_pickle(comp_test_df_path)
Fe_tsv = os.path.join(os.path.dirname(__fil... |
# Generated by Django 3.1.3 on 2020-12-18 13:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('Accounts', '0016_delete_timetable'),
]
operations = [
migrations.CreateModel(
... |
from keras.engine import Layer, InputSpec
from keras import initializers, regularizers
from keras import backend as K
class FixedBatchNormalization(Layer):
def __init__(self, epsilon=1e-3, axis=-1,
weights=None, beta_init='zero', gamma_init='one',
gamma_regularizer=None, beta_re... |
from typing import Dict, Generator
import pytest
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
from app.core.config import settings
from app.db.session import SessionLocal
from app.main import app
from app.tests.utils.user import authentication_token_from_email
from app.tests.utils.util... |
import string
class strprocess:
"""add all extra processing method """
def __init__(self):
self.data=""
self.tags=["</p>","</br>","<br/>","<br>","<p>","</P>"]
self.marks=["/","?","-","!","@","#","$","%","^","*","(",")",";","{","}","~"]
def makehtml(self,data):
self.data="<"+"... |
import asyncio
import copy
import math
from abc import ABC, abstractmethod
from decimal import Decimal
from typing import (
Dict,
List,
Optional,
)
from hummingbot.client.config.global_config_map import global_config_map
from hummingbot.core.api_throttler.async_request_context_base import AsyncRequestCont... |
from django import forms
class SubscriberEmailForm(forms.Form):
email_address = forms.EmailField()
|
#!/usr/bin/env python
"""
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
# Reference: http://www.w3.org/TR/1999/REC-html401-19991224/sgml/entities.html
htmlEntities = {
'quot': 34,
'amp': 38,
'lt': 60,
'gt': 62,
'n... |
"""
Author: OMKAR PATHAK
Created On: 5th August 2017
Linked l_list and Node can be accommodated
in separate classes for convenience
"""
import inspect
class Node(object):
"""
Node class for creating a node
for linked list.
Each node has its data and a pointer that
points to next node in the Linke... |
import argparse
import os
import time
import warnings
from collections import OrderedDict
from pprint import pprint
from typing import Any, Callable, Dict, List, Optional, Tuple
import gym
import numpy as np
import optuna
import yaml
from optuna.integration.skopt import SkoptSampler
from optuna.pruners import BasePrun... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains implementation for Viewport Plugin
"""
from __future__ import print_function, division, absolute_import
__author__ = "Tomas Poveda"
__license__ = "MIT"
__maintainer__ = "Tomas Poveda"
__email__ = "tpovedatd@gmail.com"
from collections import Ord... |
print( '<' + __name__ + ' name=\'' + __file__ + '\'>' )
import IceRayPy.core.material.instruction.illumination
import IceRayPy.core.material.instruction.pattern
import IceRayPy.core.material.instruction.transmission
import IceRayPy.core.material.instruction.light
import IceRayPy.core.material.instruction.label... |
class Document:
"""
Document class that represents an annotated text
"""
def __init__(self, text: str):
"""
Create a Document object setting possible parameters other than the text as None
Keyword arguments:
param text: The text of the document
"""
sel... |
###############################################################################
## Lifted from pyxnat and ported to Py3
###############################################################################
# This software is OSI Certified Open Source Software. OSI Certified is a
# certification mark of the Open Source Init... |
"""Tests for :mod:`compiler.services.filemanager`."""
|
#!/usr/bin/env python
# encoding: utf-8
"""
@author: zhanghe
@software: PyCharm
@file: exception.py
@time: 2019-07-29 18:50
"""
from __future__ import print_function
from __future__ import unicode_literals
import time
from functools import wraps
def ignore_exception(func):
@wraps(func) # 为了保留被装饰函数的函数名和帮助文档信息
... |
grammar = {
'2-2-1-2': [
# 森罗/仪卫/振/华缨
# 皇图/大业/超/前古
"n n vt n",
# 暮云/朝雨/长/相见
"n n d vi",
# 细香/明艳/尽/天与
"n n d a/n-v",
# 长空/黯淡/连/芳草
# 凤楼/郁郁/呈/嘉瑞
"n a vt n",
# 花光/媚春/醉/琼楼
# 琵琶/闲抱/理/相思
"n vi vt n",
# 江南/依旧/称/佳丽
"n d vt n",
# 吴姬/个个/是/神仙
"n ? v n",
# 多情/自... |
from django.conf import settings
from systems.plugins.index import BasePlugin
from systems.commands import profile
from utility.runtime import Runtime
from utility.data import ensure_list, deep_merge
import os
import re
import pathlib
import yaml
import glob
import copy
class BaseProvider(BasePlugin('module')):
... |
import autoarray as aa
import os
import numpy as np
class TestUnmaskedSparseForSparse:
def test__mask_full_false__image_mask_and_pixel_centres_fully_overlap__each_sparse_maps_to_unmaked_sparse(
self,
):
ma = aa.Mask2D.manual(
mask=np.array(
[[False, F... |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.conditions import IfCondition
from launch.substitutions import Command, FindExecutable, LaunchConfiguration, PathJoinSubstitution
from launch.actions import IncludeLaunchDescription, ExecuteProcess
from launch_ros.actions ... |
class Important_Dates():
def __init__(self,birth_day,wedding_day):
self.birth_day=birth_day
self.wedding_day=wedding_day
def getDaysPassedInMyLife(self):
return 8000
def get_days_passed_in_marriage(self):
return 300
|
steps, limit = [int(x) for x in input().split()]
x = 1
while x <= limit:
if x % steps != 0:
print('{} '.format(x), end='')
else:
print('{}'.format(x))
x += 1
|
#
# Copyright 2013, Couchbase, 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 l... |
# coding: utf-8
#
from __future__ import absolute_import, print_function
import threading
import re
import time
import datetime
import csv
import sys
import atexit
from collections import namedtuple
_MEM_PATTERN = re.compile(r'TOTAL[:\s]+(\d+)')
# acct_tag_hex is a socket tag
# cnt_set==0 are for background data
# c... |
#!/usr/bin/env python3
import numpy as np
import control
dt = 0.01
A = np.array([[ 0. , 1. ], [-0.78823806, 1.78060701]])
B = np.array([[-2.23399437e-05], [ 7.58330763e-08]])
C = np.array([[1., 0.]])
# Kalman tuning
Q = np.diag([1, 1])
R = np.atleast_2d(1e5)
(_, _, L) = control.dare(A.T,... |
import re
import socket
from base64 import b64decode
from urllib.parse import unquote, urlparse
from scrapeops_python_logger.normalizer.domains import DomainNormalizer
from scrapeops_python_logger.exceptions import DecodeError
class ProxyNormalizer(object):
def __init__(self):
pass
@staticmeth... |
from sys import stdin, stdout, setrecursionlimit
from collections import defaultdict
# Done
setrecursionlimit(10 ** 6)
def dfs(start):
global visited
visited[start] = True
for node in graph[start]:
if not visited[node]:
dfs(node)
graph = defaultdict(list)
v, e = ... |
# Copyright (c) 2018-2020, NVIDIA CORPORATION. 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 of conditi... |
import sys
from pianokeyfreq import PianoNotes
if sys.platform != 'win32':
print('Currently only Windows is supported.')
exit()
import winsound
from samples import *
import tempfile
def play_freq(waves, secs, file=tempfile.mktemp()):
wav = write_wav(file, create_samples(waves, 44100 * secs), 44100 * s... |
#!/usr/bin/env python3
# Copyright (c) 2016 The DigiByte Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import DigiByteTestFramework
from test_framework.util import (
start_n... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
"""
Reconstruct tree by ScisTree
----------------------------
This example shows how to construct a phylogenetic tree using ScisTree on a
binary single-cell genotype matrix.
"""
import scphylo as scp
# sphinx_gallery_thumbnail_path = "_static/thumbnails/scistree.png"
# %%
# First, we load a binary test single-cell ... |
from unittest import TestCase
from phi import math
from phi.field import AngularVelocity
from phi.math import channel
from phi.physics._boundaries import Domain
class TestAngularVelocity(TestCase):
def test_sample_at(self):
DOMAIN = Domain(x=4, y=3)
field = AngularVelocity([0, 0])
self.a... |
import numpy as np
import npx
def test_unique_tol():
a = [0.1, 0.15, 0.7]
a_unique = npx.unique(a, 2.0e-1)
print(a_unique)
assert np.all(a_unique == [0.1, 0.7])
a_unique, inv = npx.unique(a, 2.0e-1, return_inverse=True)
assert np.all(a_unique == [0.1, 0.7])
assert np.all(inv == [0, 0, 1... |
# STUMPY
# Copyright 2019 TD Ameritrade. Released under the terms of the 3-Clause BSD license.
# STUMPY is a trademark of TD Ameritrade IP Company, Inc. All rights reserved.
from . import aamp, aamped, mpdist
from .core import _mass_absolute_distance_matrix
def _aampdist_vect(
Q,
T,
m,
percentage=0.0... |
from __future__ import absolute_import, unicode_literals
import json
import mock
import pytest
from six import string_types
from aioarangodb.database import BatchDatabase
from aioarangodb.exceptions import (
DocumentInsertError,
BatchExecuteError,
BatchJobResultError,
BatchStateError
)
from aioarango... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# BThreadPack documentation build configuration file, created by
# sphinx-quickstart on Sat Jan 26 18:42:39 2019.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 Malcolm Ramsay <malramsay64@gmail.com>
#
# Distributed under terms of the MIT license.
"""Testing for the Civilisation simulator."""
import pytest
from hypothesis import given
from hypothesis.strategies import integers
from civ impo... |
"""System-provided config objects and constructors."""
import warnings
from collections import namedtuple
from dagster import check
from dagster.core.definitions.pipeline import PipelineDefinition
from dagster.core.definitions.run_config_schema import create_environment_type
from dagster.core.errors import DagsterInva... |
import sys
from shutil import copy
from setuptools import find_packages, setup
import versioneer
# We want to have the license at the top level of the GitHub repo, but setup
# can't include it from there, so copy it to the package directory first thing
copy('LICENSE', 'bokeh_phon/')
# State our runtime deps here, al... |
from mock import Mock
def spy_on(method):
"""
Spy on a function (record its calls, but don't interrupt their usage).
Keep these records in a Mock object and store the Mock object as
an attribute on the function.
"""
m = Mock()
def wrapper(*args, **kwargs):
m(*args, **kwargs)
... |
import os,re,glob,sys,argparse,tempfile
from subprocess import Popen, PIPE, run, TimeoutExpired, DEVNULL
import datetime,shlex,time
import nibabel, nibabel.processing
import gzip, shutil
from copy import deepcopy
import sys
if sys.version_info[0] < 3:
raise Exception("Python 3.0+ is needed.")
# Get Arguments
pars... |
"""
This module contains CommonPage,
the page object for all the common methods
"""
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class CommonPage:
# Locators
NAVIGATION_PIPE = (By.CSS_SELE... |
# -*- coding: utf-8 -*-
"""
Need to enhance the tracebacks to spit out something more useful
TODO: rename to test traceback
"""
from xdoctest import utils
from xdoctest.utils.util_misc import _run_case
def test_fail_call_onefunc():
text = _run_case(utils.codeblock(
'''
def func(a):
""... |
# project/server/models.py
import datetime
import jwt
from project.server import app, db, bcrypt
class User(db.Model):
""" User Model for storing user related details """
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
email = db.Column(db.String(255), uniqu... |
from ..day03 import count_trees, compare_routes
from textwrap import dedent
test_map = dedent(
"""\
..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#
""").splitlines()
def test_count_... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
#
# Copyright (C) 2018-2019 de4dot@gmail.com
#
# 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, publ... |
from typing import Any, Optional
from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.db import models
from django.db.models import BooleanField, Case, Count, Value, When
from django.http.response import HttpResponse... |
#!/usr/bin/env python3
"""
Validate all the publication entries.
"""
import os
import sys
import traceback
import utils
def main():
errors = []
try:
errors += utils.checkPubs(utils.PUBS_DIR)
except Exception as ex:
errors.append("Caught exception while checking for pub errors: " + str(e... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import mapMisc as mapMisc
from sklearn import cluster
import fiona
import matplotlib.patches as patches
from matplotlib.lines import Line2D
GBRshpfile = 'data/boundaryline/district_borough_unitary_region.shp'
NIshpfile = 'data/OSNI_Open_Data_Large... |
#!/usr/bin/env python
# ------------------------------------------------------------------------------------------------------%
# Created by "Thieu Nguyen" at 11:01, 19/07/2020 %
# ... |
from django.shortcuts import render
from .models import Product
from .forms import ProductForm
# Create your views here.
def product_create_view(request):
form = ProductForm(request.POST or None)
if form.is_valid():
form.save()
context = {
'form': form
}
return r... |
"""Test the SSDP integration."""
from datetime import datetime, timedelta
from ipaddress import IPv4Address, IPv6Address
from unittest.mock import ANY, AsyncMock, patch
from async_upnp_client.ssdp import udn_from_headers
from async_upnp_client.ssdp_listener import SsdpListener
from async_upnp_client.utils import CaseI... |
# Filtering Rows
# import pandas
import pandas as pd
# read movie data
movies = pd.read_csv("http://bit.ly/imdbratings")
# examine first few rows
movies.head()
## Filtering Movies with `for` Loop
booleans = []
for length in movies.duration:
if length >= 200:
booleans.append(True)
else:
... |
#! /usr/bin/env python
# coding=utf-8
# Copyright (c) 2019 Uber Technologies, 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
#
# Unles... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
import numpy as np
import tensorflow as tf
from niftynet.layer import layer_util
from niftynet.layer.base_layer import Layer
class CropLayer(Layer):
"""
This class defines a cropping operation:
Removing `2*border` pixels from... |
import random
array = []
for i in range(10):
array.append(random.randint(1, 10))
# creates array ----------------------->
key = 0
for i in range(len(array)):
key = i
for j in range(i, 0, -1):
if(array[key] < array[j]):
z = array[j]
array[j] = array[key]
array[key... |
def test(n, arr):
left_max = arr[0]
for i in range(1, n):
if arr[i] < left_max:
continue
else:
left_max = arr[i]
for j in range(i+1, n):
if arr[i] > arr[j]:
break
if j == n-1 and arr[i] <= arr[j]:
... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from base import BaseObject
class ExclusiveFlagComputer(BaseObject):
def __init__(self,
some_analyses: dict,
is_debug: bool = False):
"""
Create:
6-Apr-2017
craig.trim@ibm.com
* r... |
_base_ = [
'../_base_/models/faster_rcnn_r50_fpn.py',
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
pretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_small_patch4_window7_224.pth' # noqa
data_root = '/swi... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import ensemble
from sklearn import metrics
from statistics import mean
def etudeRelationSigne(df_knockouts,df_wildtype,v=.12):
m = len(df_knockouts.values)
mat = np.zeros((m,m))
for i in range(m):
for j in range(m... |
def pay_debt_in_period_months(balance, annual_interest_rate, monthly_payment, time_remain_months):
unpaid = balance - monthly_payment
interest = annual_interest_rate / 12 * unpaid
if time_remain_months == 1:
return unpaid + interest
else:
return pay_debt_in_period_months(unpaid + interes... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.views import generic
from .forms import ContactForm
from django.core.mail import send_mail, BadHeaderError
from .models import Suggestions, Comment, UserProfile, Post, Category, F... |
from ...predict import Predict
from .lexicon import Lexicon
class CRNNPredict(Predict):
def __init__(self, model, lexicon: Lexicon, transform=None):
super().__init__(model, transform)
self._lexicon = lexicon
def process(self, img):
x = self._process(img)[0]
idx_maxs = x.argma... |
# -*- coding: utf-8 -*-
# Unit tests for cache framework
# Uses whatever cache backend is set in the test settings file.
from __future__ import unicode_literals
import copy
import io
import os
import re
import shutil
import tempfile
import threading
import time
import unittest
import warnings
from django.conf import... |
"""Plot profiles of the velocity at different locations in the x direction."""
from matplotlib import pyplot
import pathlib
import rodney
def get_velocity_profiles(datadir,config, time, xlocs):
"""Get the velocity profiles at given time and x locations."""
profiles = {'u': {'locs': None, 'vals': []},
... |
import os
PREFIX = "codewisdom"
base_path = os.getcwd()
build_paths = []
def main():
if not mvn_build():
print("mvn build failed")
init_docker_build_paths()
# docker_login()
docker_build_and_push()
def mvn_build():
mvn_status = os.system("mvn clean package -DskipTests")
return mvn_... |
import random
from PIL import Image, ImageDraw
image = Image.open("../bear.jpg")
draw = ImageDraw.Draw(image)
width = image.size[0]
height = image.size[1]
pix = image.load()
for x in range(width):
for y in range(height):
a = pix[x, y][0]
b = pix[x, y][1]
c = pix... |
#!/usr/bin/env python3
r"""
The classes, functions and objects in this module make it (comparatively)
easy to define custom generating functions which act as "Mother shearlets".
.. warning::
Implementing custom "Mother shearlets" is a complex task and thus should
only be done if really needed. Proceed with cau... |
from sklearn.manifold import TSNE
import json
import numpy as np
from sklearn.cluster import KMeans
# embedded data has fasttext vectors of the sentences
with open("embedded_data_short.json") as file:
data = json.load(file)
X = []
for intent in data['intents']:
for pattern in intent['patterns']:
if no... |
import sys
import getopt
import multiprocessing
import os
# For Python 2.X.X
if sys.version_info[0] == 2:
from log import py_printf
# For Python 3.X.X
else:
from openmoc.log import py_printf
class Options(object):
"""Command-line options for runtime configuration of OpenMOC.
This class parses, inter... |
import numpy as np
from hexrd import constants
from hexrd.ui.constants import ViewType
class RotationSeriesSpotOverlay:
def __init__(self, plane_data, instr,
crystal_params=None,
eta_ranges=None,
ome_ranges=None,
ome_period=None,
... |
# Copyright (c) 2019 NVIDIA Corporation
import os
import random
import time
import matplotlib
from matplotlib import pyplot as plt
import numpy as np
from sklearn.metrics import confusion_matrix, classification_report
from nemo.utils.exp_logging import get_logger
matplotlib.use("TkAgg")
logger = get_logger('')
de... |
#!/usr/bin/env python
# Copyright (c) 2016 Hewlett Packard Enterprise Development Company, L.P.
#
# 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... |
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
BASE
Base object. Provides common methods used by all library objects.
License:
-------------------------------------------------------------------------------
The MIT License (MIT)
Copyright 2017-2021 Pablo Pizarro R. @ppizarror
Permission is hereby granted, ... |
import psycopg2
from datetime import datetime
import settings as my_settings
def create_db_connection():
conn = psycopg2.connect(my_settings.DATABASE_URL)
return conn
def create_table():
connection = create_db_connection()
command = "CREATE TABLE searches (id SERIAL PRIMARY KEY,user_id VARCHAR(255) N... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import argparse
from pathlib import Path
import geopandas as gpd
import pandas as pd
from shapely.geometry import Point
from geopandas.tools import sjoin
from pyproj import Proj, transform
def parse_args():
parser = argparse.ArgumentParser()
parser.add... |
from __future__ import division
from __future__ import print_function
import os
import random
import logging
import torch.optim as optim
# IMPORT CONSTANTS
import Constants
# NEURAL NETWORK MODULES/LAYERS
from model import *
# DATA HANDLING CLASSES
from tree import Tree
from vocab import Vocab
# DATASET CLASS FOR SI... |
from django import test
from django.core.exceptions import ObjectDoesNotExist
from hexa.pipelines.models import PipelinesIndexType, PipelinesIndex
from hexa.plugins.connector_airflow.models import Cluster, ClusterPermission
from hexa.user_management.models import Team, User, Membership
class ModelsTest(test.TestCase... |
#!/usr/bin/env python3
# import gi
# gi.require_version("Gtk", "3.24")
from gi.repository import Gtk as g,Gdk
import psutil as ps
from time import time
from os import popen
# Importing neccessary files
try:
from gi_composites import GtkTemplate
except ImportError:
from sysmontask.gi_composites import GtkTempl... |
"""
Copyright (c) 2019-present NAVER Corp.
MIT License
"""
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from ..basenet.vgg16_bn import init_weights
class RefineNet(nn.Module):
def __init__(self):
super(RefineNet, self).__in... |
from __future__ import division
import numpy as np
from collections import OrderedDict
from covertrace.data_array import Sites, DataArray
def modify_prop(func):
def wrapper(arr, **args):
if isinstance(arr, OrderedDict):
for key, value in arr.iteritems():
bool_arr = func(value, *... |
__all__ = ['find']
from ip import find
|
#!/usr/bin/env python
"""
Some setup for improved latex/pdf output
at top of workbook, use
from ipynb_latex_setup import *
"""
from __future__ import division as _division
# Py2/Py3 compatibility
# =====================
from __future__ import print_function as _print_function
# PYTHON
# =======
# IPYTHON
# ==... |
from unittest.mock import patch
from tests.test_base import BaseTestCase
from werkzeug.exceptions import Unauthorized, Forbidden
import dateutil.parser
from ago import human
import csv
import io
from datetime import datetime
from tests.mock.factories import (
generate_fake_users,
generate_fake_typeforms,
... |
"""
Gradient ML SDK
"""
from .metrics import MetricsLogger, add_metrics
from .init import init
__all__ = [
"init",
"add_metrics",
"MetricsLogger",
]
|
# -*- coding: utf-8 -*-
from pymba import Vimba
from display_frame import write_frame
if __name__ == '__main__':
time_between_frame_ms = 1000 # ms
with Vimba() as vimba:
camera = vimba.camera(0)
camera.open()
camera.arm('SingleFrame')
acquiring = True
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.