text stringlengths 1 927k |
|---|
import binascii
import hashlib
import itertools
import math
import operator
import re
from functools import reduce
import numpy as np
from numcodecs.compat import ensure_bytes, ensure_ndarray
from zarr.attrs import Attributes
from zarr.codecs import AsType, get_codec
from zarr.errors import ArrayNotFoundError, ReadOn... |
def logged():
from flask import session
try:
if session['id']:
return True
except Exception:
return False |
import pandas as pd
import os
from constants import LOCAL_PATH, APARTMENTS_FILENAME
def basic_write(df):
df.to_csv(os.path.join(LOCAL_PATH, APARTMENTS_FILENAME))
def basic_read():
return pd.read_csv(os.path.join(LOCAL_PATH, APARTMENTS_FILENAME)) |
def read_file(filename):
with open(filename) as fd:
input_list = fd.read().splitlines()
print input_list
return input_list
import sys
def main(argv):
if not argv:
print "Enter filename."
sys.exit()
filename = argv[0]
input_list = read_file(filename + '.in')
f = o... |
"""Test for anomalous backslash escapes in strings"""
BAD_ESCAPE = '\z' # [anomalous-backslash-in-string]
BAD_ESCAPE_NOT_FIRST = 'abc\z' # [anomalous-backslash-in-string]
BAD_ESCAPE_WITH_PREFIX = b'abc\z' # [anomalous-backslash-in-string]
BAD_ESCAPE_WITH_BACKSLASH = b'a\
\z' # [anomalous-backslash-in-string]
... |
# NUMPY MANIPULATIONS OF ARRAYS
# Santiago Garcia Arango
# -------------------------------------------------------------------------
import numpy as np
my_array = np.arange(1, 11) # [1,2,..,8,9,10]
print("my_array=\n", my_array, "\n")
# -----------------CHECKING CONDITIONS IN ARRAY ITEMS----------------------
# FIR... |
from abc import ABC, abstractmethod
from typing import Dict, List, Any, Type, Union, Optional, Tuple
from dash.dash import no_update
from dash.dependencies import Input, Output, State
from dash import dcc
import dash_bootstrap_components as dbc
from dash import html
from dash.development.base_component import Componen... |
# --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ""Software""), ... |
import sys,os
base = sys.path[0]
sys.path.append(os.path.abspath(os.path.join(base, "..")))
import json5
import shutil
from glob import glob
from docker.tool import yellow
with open('RootPath.json') as f:
root = json5.load(f)[r'%RESULT%']
assert len(sys.argv)>1, 'Project Name Needed!'
tars = glob(os.path.join(root... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import IPython
import os
def save_fig(fig_id, tight_layout=True):
if tight_layout:
plt.tight_layout()
plt.savefig(fig_id + '.png', format='png', dpi=300)
def draw_stickfigure(mocap_track, frame, data=None, joints=None, dra... |
from web_scrape import *
from modules import *
from sidebar import *
import extras
external_stylesheets = [extras.theme]
colors = {
'background': '#111111',
'text': '#FFFFFF'
}
sn = {'color':'white'}
app = dash.Dash(__name__,
external_stylesheets=external_stylesheets,
request... |
from faster_rcnn.rpn_msr.anchor_target_layer_2 import AnchorTargerLayer
import unittest
class AnchorTargerLayerTest(unittest.TestCase):
"""docstring for AnchorTargerLayerTest"""
def setUp(self):
self.anchor_scales = [8, 16, 32]
self.layer = AnchorTargerLayer(
[16, ], anchor_scales... |
from app.models import User
from flask_restful import Resource, reqparse
from sqlalchemy.orm.exc import NoResultFound
from flask import request, jsonify, make_response
def identity(payload):
username = payload['identity']
return User.query.filter_by(id = username).first()
def authenticate(username, password):... |
from threading import Thread
from math import ceil
from struct import unpack
from twisted.internet.protocol import Protocol, ClientFactory
from twisted.internet import reactor
from message import Message, MessageParser, MessageType, get_handshake, parse_handshake, \
is_handshake, MessageQueue, message_queue_worke... |
# Running into logical errors :(
import battlecode as bc
import random
import sys
import traceback
print("pystarting")
gc = bc.GameController()
directions = list(bc.Direction)
print("pystarted")
random.seed(8078)
worker_count = 1
knight_count = 0
factory_count = 0
gc.queue_research(bc.UnitType.Worker)
gc.queue_rese... |
# -*- coding: utf-8 -*-
import requests
import os
from com.gionee.ota import gol
import json
from com.gionee.ota.util import Util
from com.gionee.ota.Base import *
__author__ = 'suse'
url="http://api.appgionee.com/api/gionee/getDownloadUrl?packageName="
logger = Util.logger
class GN_Apps():
def __init__(self):
... |
# (c) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
# 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/licens... |
import hello_world |
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm, PasswordChangeForm
from django.contrib.auth.to... |
# -*- coding: utf-8 -*-
"""Deprecated modules"""
from .core import Schema, Field, validator, schema_validator, SchemaObjectField, ListOfSchemaObjectsField
from .schema_error import SchemaError |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
# /workspace/tangyang.sy/pytorch_CV/pytorch_CenterNet/src
try:
from utils_ctdet.lineNMS import do_nms_line, do_acl_line, do_acl_line_v1
except ImportError:
from utils.lineNMS import ... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import compas
from compas_rhino.forms import Form
try:
from System.Windows.Forms import TextBox
from System.Windows.Forms import DockStyle
from System.Windows.Forms import ScrollBars
from Syste... |
import sys
import time
sys.path.append("../Feed")
sys.path.append("../lib")
import crypto
import feed as fe
from generateJson import generate_json
from Feed import Feed
class Person:
name = "" # name of the user
id = 0 # BacNet id of the user
feed = None # feed of the user (refers to Feed.py)
... |
import FWCore.ParameterSet.Config as cms
#------------------
#Hybrid clustering:
#------------------
# Producer for Box Particle Flow Super Clusters
from RecoEcal.EgammaClusterProducers.particleFlowSuperClusterECAL_cfi import *
# Producer for energy corrections
#from RecoEcal.EgammaClusterProducers.correctedDynamicHyb... |
from __future__ import print_function
import numpy as np
## LOAD DATA ##
###############
print("Loading segments.")
from import_export import load_segments
segments, ids = load_segments(folder="/tmp/segment_matcher/")
from import_export import load_matches
matches = load_matches(folder="/tmp/segment_matcher/")
visua... |
"""blog_ruicci URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-b... |
#!/usr/bin/python
import subprocess
subprocess.call(['echo', '']) |
from .ModelOrchestrator import ModelOrchestrator
from .ModelTask import ModelTask |
from decimal import Decimal
import pytest
from ledger.balance import Balance
from ledger.transaction import IrrelevantTransactionError
class TestBalance:
def test_init(self):
balance = Balance(entity="mike", total="1.123")
assert balance.entity == "mike"
assert balance.total == Decimal("... |
import time
from tests.common.nebula_test_suite import NebulaTestSuite
class TestBugUpdate(NebulaTestSuite):
@classmethod
def prepare(self):
resp = self.execute(
'CREATE SPACE IF NOT EXISTS issue1827_update(partition_num={partition_num}, replica_factor={replica_factor})'
.forma... |
sum = 0
for num in range (10):
add = int(input(""))
sum = sum + add
avg = sum / 10
print(avg) |
# Generated by Django 3.0.8 on 2020-09-02 05:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0009_auto_20200828_1240'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
name='image... |
import os
import sys
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.append(os.path.abspath('.'))
sys.path.append(os.pat... |
"""
/********************************************************************************/
/* */
/* Copyright (c) 2020 Analog Devices, Inc. All Rights Reserved. */
/* This software is proprietary to Analog Devices, Inc. and its li... |
# Generated by Django 2.1.15 on 2020-12-04 05:33
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0009_alter_user_last_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
... |
from rumergy_backend.rumergy.models import AccessRequest
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import permissions
from rest_framework import status
from rest_framework.decorators import action, permission_classes
from rest_framework.response import Re... |
# Copyright (c) 2016 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 applic... |
#!/usr/bin/env python
from setuptools import setup
import codecs
import os
import re
with codecs.open(
os.path.join(
os.path.abspath(os.path.dirname(__file__)),
'binance',
'__init__.py'
), 'r', 'latin1') as fp:
try:
version = re.findall(r"^__version__ = ... |
import argparse
from graph.graph import Graph
from graph.regexp import Regexp
from graph_query.algo import algo
def main():
parser = argparse.ArgumentParser(
description=('Script to execute simple query on graph using '
'tensor product automata intersection'),
)
parser.add_ar... |
import os
SESSION_SECRET = os.getenv("SESSION_SECRET")
DB_URI = os.getenv("DB_URI", 'sqlite://dev.db')
DISCORD_CLIENT_ID = os.getenv("DISCORD_CLIENT_ID")
DISCORD_CLIENT_SECRET = os.getenv("DISCORD_CLIENT_SECRET") |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Maeja and Contributors
# See license.txt
from __future__ import unicode_literals
# import frappe
import unittest
class TestMeeting(unittest.TestCase):
pass |
from amcp_pylib.core import Command, command_syntax
@command_syntax('MIXER [video_channel:int]{-[layer:int]|-0} KEYER {[keyer:0,1]|0}')
def MIXER_KEYER(command: Command) -> Command:
"""
Replaces layer n+1's alpha with the R (red) channel of layer n, and hides the RGB channels of layer n.
If keyer equals 1... |
import logging
import time
import pytest
from ocs_ci.framework.testlib import (
tier4b,
ignore_leftovers,
ManageTest,
bugzilla,
skipif_external_mode,
skipif_ibm_cloud,
)
from ocs_ci.ocs.node import get_ocs_nodes
from ocs_ci.ocs.resources.pod import wait_for_pods_to_be_running
from ocs_ci.helpe... |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 29 11:20:51 2020
@author: 766810
"""
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from statsmodels.tsa.stattools import adfuller
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.tsa.arima_model import ARIMA
from pand... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import waldur_core.logging.loggers
import waldur_core.core.fields
import django.core.validators
import waldur_core.core.validators
class Migration(migrations.Migration):
dependencies = [
('structure'... |
# 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 writing, software
# distributed under the... |
from selenium.webdriver.common.keys import Keys
from .framework import (
selenium_test,
SeleniumTestCase
)
class CollectionEditTestCase(SeleniumTestCase):
ensure_registered = True
@selenium_test
def test_change_dbkey_simple_list(self):
self.use_beta_history()
self.create_simple_... |
import datetime as dt
def timestamp():
return dt.datetime.utcnow().isoformat() |
from abc import abstractmethod
from test.stubs.sublime import View
class TextCommand:
def __init__(self):
self.view = View()
@abstractmethod
def run(self, edit):
raise NotImplementedError
class EventListener:
pass
class WindowCommand:
def __init__(self, window):
self.... |
# -*- coding: utf-8 -*-
'''
Interface with a Junos device via proxy-minion.
'''
# Import python libs
from __future__ import print_function
from __future__ import absolute_import
import logging
# Import 3rd-party libs
# import jnpr.junos
# import jnpr.junos.utils
# import jnpr.junos.utils.config
import json
HAS_JUNOS... |
import numpy as np
from collections import deque
import torch
torch.manual_seed(0) # set random seed
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Categorical
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class model(nn.Mo... |
from networkx_mod.algorithms.assortativity import *
from networkx_mod.algorithms.block import *
from networkx_mod.algorithms.boundary import *
from networkx_mod.algorithms.centrality import *
from networkx_mod.algorithms.cluster import *
from networkx_mod.algorithms.clique import *
from networkx_mod.algorithms.communit... |
"""WSJ view"""
__docformat__ = "numpy"
import os
from tabulate import tabulate
from gamestonk_terminal.etf import wsj_model
from gamestonk_terminal.helper_funcs import (
export_data,
)
def show_top_mover(sort_type: str, limit: int = 20, export=""):
"""
Show top ETF movers from wsj.com
Parameters
... |
#!/usr/bin/env python3
import argparse
import sys
from netboot.web import spawn_app
def main() -> int:
parser = argparse.ArgumentParser(description="A debug version of the Netboot web services.")
parser.add_argument("-p", "--port", help="Port to listen on. Defaults to 80", type=int, default=80)
parser.add... |
#FLM: Font: Instances
# ----------------------------------------
# (C) Vassil Kateliev, 2018 (http://www.kateliev.com)
# (C) Karandash Type Foundry (http://www.karandash.eu)
#-----------------------------------------
# No warranties. By using this you agree
# that you use it at your own risk!
# - Init
global pLayers
... |
# -*- coding: utf-8 -*-
"""
Simple example using convolutional neural network to classify IMDB
sentiment dataset.
References:
- Andrew L. Maas, Raymond E. Daly, Peter T. Pham, Dan Huang, Andrew Y. Ng,
and Christopher Potts. (2011). Learning Word Vectors for Sentiment
Analysis. The 49th Annual Meeting of th... |
#
# Copyright 2021 Lars Pastewka
#
# ### MIT license
#
# 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, mer... |
import os
import discord
import json
from discord.ext import commands
import traceback
from dotenv import load_dotenv
load_dotenv()
if os.name == 'nt':
data_directory = 'json\\'
else:
data_directory = 'json/'
class Mochi(commands.Bot):
def __init__(self, command_prefix, **options):
self.prefix = c... |
# # Leaflet cluster map of talk locations
#
# (c) 2016-2017 R. Stuart Geiger, released under the MIT license
#
# Run this from the _talks/ directory, which contains 2020-10-01-Bouzebda-Elhattab-Nemouchi.md files of all your talks.
# This scrapes the location YAML field from each 2020-10-01-Bouzebda-Elhattab-Nemouchi.md... |
#!/usr/bin/env python3
import cv2
import sys
import time
import os
assert(len(sys.argv) == 2),'No input given. Please input path to image'
img_path = str(sys.argv[1])
t0 = time.time()
# Load the cascade
print('Analyzing image...')
cascade = cv2.CascadeClassifier('stop_data.xml')
# Read the image
img = cv2.imread(im... |
#!/usr/bin/env python
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test some functions of HFA driver. Most testing in ../gcore/hfa_*
# Author: Frank Warmerdam <warmerdam@pobox.com>
#
##############################################... |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from civil.library.models import BaseModel
#==============================================================================
class AddressType(BaseModel):
name = models.Cha... |
import os
import argparse
import numpy as np
from sklearn import metrics
import matplotlib.pyplot as plt
import torch
import torch.utils.data as datautils
from deepSM import StepPlacement
from deepSM import SMDUtils
from deepSM import post_processing
from deepSM import utils
parser = argparse.ArgumentParser()
par... |
from contextlib import contextmanager
import pytest
from napari_plugin_engine import (
HookCaller,
HookImplementation,
HookImplementationMarker,
HookSpecification,
HookSpecificationMarker,
PluginManager,
)
@pytest.fixture
def test_plugin_manager() -> PluginManager:
"""A plugin manager fi... |
# -*- coding: utf-8 -*-
import os
import re
import subprocess
import scrapy
from scrapy.http import Request, FormRequest
from scrapy.selector import Selector
from cy.items import PropertyItem
class Spider(scrapy.Spider):
name = "property"
allowed_domains = ["sunshine.cy.gov.tw"]
start_urls = ['http://suns... |
# Question: If we list all the natural numbers below 10 that are the multiples of 3 or 5, we get 3, 5, 6, 9. The sum of these is 23 Find the sum of all the multiples of 3 or 5
i = 0
num = 1000
count = 0
while i < num:
if i%3==0 or i%5==0:
print(i)
count = count + i # when i satisfies the condition ... |
import keras
from keras.utils import np_utils
from keras import layers
from keras import models
import os
from keras.models import Sequential
from keras.layers import Dense, Conv2D, MaxPool2D , Flatten, Dropout
from keras.preprocessing.image import ImageDataGenerator
import numpy as np
def build_vgg(in_shape):
model... |
"""
The Prefect Storage interface encapsulates logic for storing flows. Each
storage unit is able to store _multiple_ flows (with the constraint of name
uniqueness within a given unit).
"""
from warnings import warn
import prefect
from prefect import config
from prefect.storage.base import Storage
from prefect.storag... |
# -*- coding: utf-8 -*-
"""
Purpose: Character level Natural Language Generation (NLG). This file loads a
previously trained character NLG model from LanguageGenChars_train.py,
and predicts subsequent chars.
To run:
1) Set constants below to be the same as the languagegenchars_train.py file
2... |
# Generated by Django 3.1 on 2020-09-15 22:52
import daira.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sokna', '0006_auto_20200712_1329'),
]
operations = [
migrations.AlterField(
model_name='soknarequest',
... |
# -*- coding: utf-8 -*-
from decimal import Decimal as D
from django import template
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import translation
def render(template_string, ctx):
tpl = template.Template(template_string)
return tpl.render(template.Cont... |
from matplotlib.backend_tools import ToolBase, ToolToggleBase, Cursors
from PyQt5.QtCore import QObject, pyqtSignal
import logging
class ToolPickPoint(ToolToggleBase,QObject):
""" Marker selection tool. """
# Tool options for matplotlib.
description = 'Pick a point on the image'
image = 'pick.png'
cursor = Curso... |
#!/usr/bin/env python
import sys
import os
import argparse
from os.path import dirname
from os.path import join
project_dir = dirname(dirname(dirname(os.path.realpath(__file__))))
sys.path.append(join(project_dir, 'build'))
# Path to protobuf build.
#sys.path.append(join(project_dir, 'third_party', 'include'))
sys.pa... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 25 15:46:32 2019
@author: tadahaya
""" |
import pygame, sys, math
class Ball():
def __init__(self, image, speed=[0,0], pos=[0,0], size=None):
self.image = pygame.image.load("rsc/ball/"+image)
if size:
self.image = pygame.transform.scale(self.image, [size,size])
self.rect = self.image.get_rect(center = pos)
self... |
n = int(input())
s = list(input())
if n % 2 != 0:
print("No")
else:
if s[n//2:] == s[:n//2]:
print("Yes")
else:
print("No") |
"""
Classes to be used in the identification and validation of manifest columns
"""
import warnings
from abc import ABC
from enum import Enum, unique
import string
from urllib.parse import urlparse
from base64 import b64encode, b64decode
# Pre-defined supported column names
GUID_COLUMN_NAMES = ["guid", "GUID"]
GUID_S... |
from abc import ABC, abstractmethod
from typing import Tuple, Any, Optional
class AbstractMessageProtocol(ABC):
@abstractmethod
def unpack(self, message: Any) -> Tuple[str, Any]:
pass
@abstractmethod
def pack(self, target: Optional[str], message: Any) -> Any:
pass
class SimpleDictPr... |
from flask import current_app
from app import creat_app
app = creat_app()
if __name__ == '__main__':
app.run(debug=app.config['DEBUG'], host='0.0.0.0', port=81, threaded=True)
a = current_app |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 19 19:24:49 2019
@author: mlin
"""
import matplotlib.pyplot as plt
from collections import OrderedDict
import numpy as np
import copy
class ffd():
def __init__(self, ffd_file, incident_Power_W=1):
self.incident_Power_W=incident_Power_W
wi... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class AppleItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Flask Api Sign Verification
-------------
Flask extension of Api Sign Verification.
"""
from setuptools import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read(... |
from __future__ import annotations
import logging
import time
from dataclasses import replace
from secrets import token_bytes
from typing import Any, Dict, List, Optional, Set
from blspy import AugSchemeMPL, G2Element
from mint.consensus.cost_calculator import calculate_cost_of_program, NPCResult
from mint.full_node... |
#! /usr/bin/env python
"""Token constants (from "token.h")."""
# This file is automatically generated; please don't muck it up!
#
# To update the symbols in this file, 'cd' to the top directory of
# the python source tree after building the interpreter and run:
#
# python Lib/token.py
#--start constants--
ENDM... |
# (c) Copyright 2021, Ralf Haferkamp <ralf@h4kamp.de>
#
# 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 ... |
#!/usr/bin/env python
# coding: utf-8
import SimpleITK as sitk
import pandas as pd
import numpy as np
import radiomics
def radiomics_analysis(image_filepath, mask_filepath,img_label):
img = sitk.ReadImage(image_filepath)
mask = sitk.ReadImage(mask_filepath)
#Z-score normalisation for MRI
if img_l... |
def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Specific humidity', 'units': 'kg kg-1'},
{'abbr': 1, 'code': 1, 'title': 'Relative humidity', 'units': '%'},
{'abbr': 2, 'code': 2, 'title': 'Humidity mixing ratio', 'units': 'kg kg-1'},
{'abbr': 3, 'code': 3, 'title': 'Precip... |
from django.apps import apps
from datetime import datetime, date, timedelta
from django.conf import settings
import xarray as xr
import numpy as np
import collections
from rasterio.io import MemoryFile
from datacube.config import LocalConfig
import datacube
import configparser
def form_to_data_cube_parameters(form_... |
# import docker
from service.utilities.connection import ConnectionFactory, MongoConnection
import unittest
from unittest import TestCase
import toml
EXAMPLE_TOML = '''
uri = 'mongodb://127.0.0.1:27017'
name = "testing"
default_dbname = 'mydefault'
default_colname = 'mydefault_col'
id_key = 'msg2_id'
'''
class Te... |
import h5py
import json
import sys
import cv2
import os.path as osp
import numpy as np
from tools import Timer
from config import CAFFE_ROOT, DATA_ROOT
sys.path.insert(0, osp.join(CAFFE_ROOT, 'python'))
import caffe
BS = 1
def cnn_patch_feature(net, transformer, image, bbox, include_whole_image=False):
im_list ... |
from django.utils import timezone
from beehive.models import BeeHive
class BeeHiveService():
"""Sets service date for BeeHive"""
@staticmethod
def set_beehive_service_date(beehive_id):
beehive = BeeHive.objects.get(id=beehive_id)
beehive.service_date = timezone.now()
beehive.save... |
# Copyright 2022 The GPflow Contributors. 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 appl... |
import time
import os
import subprocess
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from nw_util import *
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common import utils
chrome_options = Options()
chrome_optio... |
# Generated by Django 2.1.4 on 2019-02-19 07:57
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('bills', '0003_auto_20190219_0709'),
]
operations = [
migrations.RemoveField(
model_name='bills'... |
# from datetime import datetime
# from typing import Optional
#
# from fastapi_users import models
# from sqlmodel import SQLModel
#
#
# class UserBase(models.BaseUser, SQLModel):
# first_name: str
# birthdate: Optional[datetime.date]
#
#
# class UserCreate(models.BaseUserCreate, SQLModel):
# first_name: st... |
# Listing_11-6.py
# Copyright Warren & Carter Sande, 2013
# Released under MIT license http://www.opensource.org/licenses/mit-license.php
# Version $version ----------------------------
# program to figure out combinations of hot dog ingredients
print "\tDog \tBun \tKetchup\tMustard\tOnions"
count = 1
for dog in [... |
# -*- coding: utf-8 -*-
""""
author: 'Omid Sadjadi, Timothee Kheyrkhah'
email: 'omid.sadjadi@nist.gov'
"""
import time
import warnings
from numbers import Number
import numpy as np
from scipy.linalg import cholesky, eigh, inv, solve, svd
from six import string_types
from odin.backend import calc_white_mat, length_nor... |
# coding: utf-8
"""
tweak-api
Tweak API to integrate with all the Tweak services. You can find out more about Tweak at <a href='https://www.tweak.com'>https://www.tweak.com</a>, #tweak.
OpenAPI spec version: 1.0.8-beta.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
... |
import warnings
import torch
from torch.nn import GroupNorm, LayerNorm
from torch.nn.modules.batchnorm import _BatchNorm
from torch.nn.modules.instancenorm import _InstanceNorm
from ..utils import build_from_cfg
from .builder import OPTIMIZER_BUILDERS, OPTIMIZERS
@OPTIMIZER_BUILDERS.register_module
class DefaultOpt... |
"""# Plagiarism Class - for document known plagiarism list - used for later evaluation
Members:
- this_offset
- this_length
- source_offset
- source_length
"""
class Plagiarism():
def __init__(self, this_offset, this_length, source_reference, source_offset, source_length):
self.this_offset = this_offset... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.