text stringlengths 2 999k |
|---|
import logging
import torch
import torch.nn.functional as F
from torch import nn
from predict_pv_yield.models.base_model import BaseModel
from nowcasting_dataloader.batch import BatchML
logging.basicConfig()
_LOG = logging.getLogger("predict_pv_yield")
class Model(BaseModel):
name = "conv3d_sat_nwp"
def ... |
from .. import ContainerAbilityInterface
from .. import QLayout
from .. import ui_extension
@ui_extension
class Layout(QLayout, ContainerAbilityInterface):
pass
|
import sys
sys.path.append('..')
from collections import UserString
from emrap.common import Cacheable, Sortable, \
SortedUniqueContainer, ReverseOrderedContainer, \
ReverseOrderedUniqueContainer
class C(Cacheable):
_holds = list
class S(Sortable, UserString):
@property
def _comparables(self):
... |
# -*- coding: utf-8 -*-
import base64
import logging
import os
import re
import zlib
from babelfish import Language, language_converters
from guessit import guessit
from six.moves.xmlrpc_client import ServerProxy
from . import Provider, TimeoutSafeTransport
from .. import __short_version__
from ..exceptions import (A... |
#!/usr/bin/env python
# Control program for the Red Pitaya Scanning system
# Copyright (C) 2015 Pavel Demin
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, o... |
def autolabel(rects, ax):
"""Attach a text label above each bar in *rects*, displaying its height."""
for rect in rects:
height = rect.get_height().round(1)
ax.annotate('{}%'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), ... |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise Runtime... |
"""Emoji
Available Commands:
.np
"""
import asyncio
from telebot.utils import admin_cmd
@telebot.on(admin_cmd(pattern="np"))
async def _(event):
if event.fwd_from:
return
animation_interval = 0.1
animation_ttl = range(0, 36)
# input_str = event.pattern_match.group(1)
# if input_str == "... |
"""
This file is for preprocessing of dataset.
Dataset: UMN Dataset
Original dataset distribution link: https://www.crcv.ucf.edu/projects/Abnormal_Crowd/
"""
import re
import os
import cv2
import glob
pwd = os.getcwd()
DATASET_NAME = 'umn'
def download_dataset(delete_archive=False):
os.chdir(os.path.join(pwd, 'da... |
import psutil
def cpu(locacao):
cpu_freq = psutil.cpu_freq() # 0-Freq atual 1-min 2-max
cpu_percent = psutil.cpu_percent(interval=0.1) # porcentagem de uso do processador
cpu_status = (str(int(cpu_freq[0]))+ ' Ghz' , str(int(cpu_freq[1]))+ ' Ghz', str(int(cpu_freq[2]))+ ' Ghz'... |
import pytest
from s3contents import S3ContentsManager
from s3contents.ipycompat import TestContentsManager
@pytest.mark.minio
class S3ContentsManagerTestCase(TestContentsManager):
def setUp(self):
"""
This setup is a hardcoded to the use a minio server running in localhost
"""
se... |
"""
Django settings for iclone project.
Generated by 'django-admin startproject' using Django 1.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
im... |
import torch
from torch.autograd import Function
from torch import nn
from .alias_multinomial import AliasMethod
import math
class NCEFunction(Function):
@staticmethod
def forward(self, x, y, memory, idx, params):
K = int(params[0].item())
T = params[1].item()
Z = params[2].item()
... |
#!/usr/bin/env python
"""Email live output plugin."""
import cgi
import urllib
from grr.lib import aff4
from grr.lib import config_lib
from grr.lib import email_alerts
from grr.lib import output_plugin
from grr.lib import utils
from grr.lib.rdfvalues import structs as rdf_structs
from grr.proto import output_plugin... |
import bpy
def import_animations(armature_name, model_data):
model_armature = bpy.data.objects[armature_name]
model_armature.animation_data_create()
bpy.context.view_layer.objects.active = model_armature
bpy.ops.object.mode_set(mode="POSE")
for animation_name, animation_data in list(model_data.an... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from scipy import stats
#TODO what does this function mean?
def pred_bbox_by_F(bbox, F, show_flag, img1, img2):
# Create figure and axes
if show_flag==1:
fig1, ax1 = plt.subplots(1)
# Display the image
if ... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "telegramtoken.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django... |
# ===================================================================
#
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributio... |
#!/usr/bin/env python
import numpy as np
import random
from pycrazyswarm import *
def randomWaypoints():
waypoints = []
for i in range(100):
waypoints.append([random.uniform(-0.3, 0.3), random.uniform(-0.3, 0.3), random.uniform(0.8, 1.2)])
waypoints.append([0.0, 0.0, 1.0])
return waypoint... |
import os
from norc.settings import NORC_LOG_DIR, BACKUP_SYSTEM
if BACKUP_SYSTEM == 'AmazonS3':
from norc.norc_utils.aws import set_s3_key
from norc.settings import (AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY, AWS_BUCKET_NAME)
def s3_backup(fp, target):
NUM_TRIES = 3
for i in range(NUM_TRIES)... |
import _plotly_utils.basevalidators
class TicksValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="ticks", parent_name="surface.colorbar", **kwargs):
super(TicksValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import six
import pytest
from flask_cdn import _get_checksum_for, _download_manifest, CDNManifestUrlError, CDNFileNotFoundInManifest
cdn_manifest = pytest.mark.cdn_manifest
@pytest.fixture
def filename():
return 'js/script.js'
@pytest.fixture
... |
''' Test example images '''
from nipy import load_image
from nipy.testing import funcfile, anatfile
from nose.tools import assert_true, assert_false, assert_equal
def test_dims():
fimg = load_image(funcfile)
# make sure time dimension is correctly set in affine
yield assert_equal, fimg.coordmap.affine[3... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making Metis available.
Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with th... |
#! /usr/bin/env python3
REQUEST = 'Request'
PRE_PREPARE = 'PrePrepare'
PREPARE = 'Prepare'
COMMIT = 'Commit'
RESULT = 'Result'
VIEW_CHANGE = 'ViewChange'
NEW_VIEW = 'NewView'
# Decouple actual message from preprepare message is highly recommended for optimization (etc. choice of protocol for small and... |
# Copyright 2020 NREL
# 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
# distri... |
from django.http import HttpResponseForbidden, HttpResponseNotFound
from django.views.static import serve
from ..core.config import config
from ..utils.auth import has_perm
from ..utils.rest_api import ModelViewSet, ValidationError
from .access_permissions import MediafileAccessPermissions
from .models import Mediafil... |
"""This file tests the input factories."""
from difflib import Differ
from logging import getLogger
from pathlib import Path
from typing import List
import pytest
from pdb2pqr.io.factory import input_factory, output_factory
from pdb2pqr.io.pdb_record import BaseRecord
from .common import INPUT_DIR, REF_DIR
_LOGGER = ... |
# -*- coding: utf8 -*-
'''
This module contains a few utility functions.
'''
import re
from pyramid_skosprovider.renderers import (
json_renderer,
concept_adapter,
collection_adapter,
label_adapter,
note_adapter,
source_adapter
)
import logging
log = logging.getLogger(__name__)
class QueryB... |
# -- Imports --------------------------------------------------------------------------
from .console import console
# -------------------------------------------------------------------------- Imports --
|
"""
See https://gist.github.com/dkarchmer/d85e55f9ed5450ba58cb
This API generically supports DjangoRestFramework based APIs
It is based on https://github.com/samgiles/slumber, but customized for
Django Rest Frameworks, and the use of TokenAuthentication.
Usage:
# Assuming
# v1_api_router.register(r'some_model',... |
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this sof... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier
from ipywidgets import interact
def visualize_tree(estimator, X, y, boundaries=True,
xlim=None, ylim=None, ax=None):
ax = ax or plt.gca()
# 绘制训练数据点
ax.scatter(X[:, 0], X[:, 1], c=y, ... |
# Copyright 2018 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... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Hetzner Cloud GmbH <info@hetzner-cloud.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
"met... |
import math
import random
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import scipy.io
from pdb import set_trace as bp
for i in range(10):
file_name = '../CORL_FW_SR/CORL_record_%d.txt'%(i)
equal_delay = np.... |
"""Application Models."""
from marshmallow import fields, Schema
from marshmallow.validate import OneOf
from ..enums import *
from ..models.BaseSchema import BaseSchema
class ChargeCustomerResponse(BaseSchema):
# Payment swagger.json
message = fields.Str(required=False)
success =... |
import numpy as np
import pytest
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import Lasso, LogisticRegression
from sklearn.model_selection import KFold, StratifiedKFold
from sklearn.tree import DecisionTreeRegressor
from feature_engine.selection import (
RecursiveFeatureAddition,
... |
from django.http import HttpResponse
def index(request):
informasi="""
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>PERCOBAAN OM</h1>
</body>
</html>
"""
return HttpResponse(informasi)
|
# 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... |
# Phono3pyPowerTools/Plotting.py
# ----------------
# Module Docstring
# ----------------
""" Routines for working with Matplotlib. """
# -------
# Imports
# -------
import math
import numpy as np
import matplotlib as mpl
from matplotlib.ticker import FuncFormatter
# -------------------
# Default Initialiser
... |
import pytest
from jupytext.magics import comment_magic, uncomment_magic, unesc
def test_unesc():
assert unesc('# comment', 'python') == 'comment'
assert unesc('#comment', 'python') == 'comment'
assert unesc('comment', 'python') == 'comment'
@pytest.mark.parametrize('line', ['%matplotlib inline', '#%mat... |
# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0
# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0
#
import logging
from typing import List
import volatility3
from volatility3.framework import exceptions, interfaces
from volatility3.... |
import configparser
import os
from shutil import copyfile
from unittest import mock
from unittest.mock import patch, mock_open
import pytest
import castero.config as config
my_dir = os.path.dirname(os.path.realpath(__file__))
config_default_path = config._Config.DEFAULT_PATH
@pytest.fixture(autouse=True)
def rest... |
import numpy as np
from deep_learning_101.component.utils import softmax, cross_entropy_error
class ReLU:
def __init__(self):
self.mask = None
def forward(self, x):
self.mask = (x <= 0)
out = x.copy()
out[self.mask] = 0
return out
def backward(self, dout):
... |
"""
This Python3 script creates a Pythagoras tree in SVG or PNG format
Requires numpy and matplotlib to create pngs.
Get started with : python Pythagoras_tree.py --help
"""
import argparse
from math import atan2, ceil, pi, sqrt
from typing import List
import matplotlib
import matplotlib.pyplot as plt
import numpy as... |
#!/usr/bin/env python3
from abc import ABCMeta, abstractmethod
# Given Book class
class Book(object, metaclass=ABCMeta):
def __init__(self,title,author):
self.title=title
self.author=author
@abstractmethod
def display():
pass
# MyBook class
class MyBook(Book):
price = 0
def __init__(self, title, author,... |
#!/usr/bin/env python
# Example of "filter" file to parse the output of the SLURM scheduler upon
# job submission and extract the job ID only.
#
# NOTE: This filter is only needed when the job dependencies are delegated
# to the scheduler (it is NOT needed when Kronos events mechanism is used).
import sys
import subp... |
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
import logging
import string
from typing import Mapping, MutableMapping, Sequence
from cloud_blobstore import BlobPagingError, PagedIter
from dss.config import Config, Replica
from dss.index import DEFAULT_BACKENDS
from dss.index.backen... |
"""This module contains the general information for FabricSanPinGroup ManagedObject."""
from ...ucscmo import ManagedObject
from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta
from ...ucscmeta import VersionMeta
class FabricSanPinGroupConsts():
INT_ID_NONE = "none"
POLICY_OWNER_LOCAL = "local"
... |
# encoding: utf-8
"""
memory_cache.py
Provides classes for in memory caching
"""
import time
import requests
import logging
import pprint
from abc import ABCMeta, abstractmethod
from .base_cache import Cache
class BaseMemoryCache(Cache):
__metaclass__ = ABCMeta # Marks this as an abstract class
EXPIRY_T... |
import socket
import select
import time
import re
import logging
from datetime import datetime
LOGGER = logging.getLogger(__name__)
re_event = re.compile(r"^(?P<date>[0-9-]*)T(?P<time>[0-9:]*)\s+(?P<uptime>[0-9.]*)\s+(?P<loglevel>[A-Z]*)\s+(?P<message>.*)")
re_chat = re.compile(r"^Chat\s+\(from '(?P<from>[^']*)', ent... |
from fixture.orm import ORMFixture
from model.group import Group
db = ORMFixture(host='127.0.0.1', name='addressbook', user='root', password='')
try:
l = db.get_addresses_not_in_group(Group(id="26"))
for item in l:
print(item)
print(len(l))
finally:
pass # db.destroy()
|
from flask import Flask, current_app, jsonify
from sqlalchemy.exc import IntegrityError
import stripe, json, sys, os, traceback, requests
from datetime import timedelta, datetime
from types import SimpleNamespace
from sys import stdout
from uuid import UUID
from json import JSONEncoder
from stripe.api_resources import... |
from collections import deque, defaultdict
import datetime
import functools
import http.client
import logging
import subprocess
from flask import Flask, jsonify
import httplib2
from oauth2client.client import AccessTokenRefreshError
from gchatautorespond.apps.autorespond.models import AutoResponse
from .bot import Au... |
'''ShuffleNet in PyTorch.
See the paper "ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices" for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class ShuffleBlock(nn.Module):
def __init__(self, groups):
super(ShuffleBlock, self).__init... |
# (c) 2012-2019, Ansible by Red Hat
#
# This file is part of Ansible Galaxy
#
# Ansible Galaxy is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by
# the Apache Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#... |
import numpy as np
import scipy.sparse as spa
import os
def count(Input, Value):
return(len([x for x in Input if x == Value]))
class LAE():
def __init__(self, System = None, Frame = None, Adj1 = None, Adj2 = None, HeAdj = None,
EleNN = None, lae = None, HomoBonds = None, HeteroBonds = ... |
#!/usr/bin/env python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep
import cgi
PORT_NUMBER = 8765
# Used to:
# * Change on the fly the parameters.
# * See the internal status.
# There will be an extra class to set up some parameters that all daemons have.
# Each engine has ... |
from ae_python.layer.layer import Layer
from ae_python.standalone_functions import hash_maker
from colour import Color
from ae_python.property import Property
class TextLayer(Layer):
"""
The TextLayer object represents a text layer within a composition.
:parameter text: The text of the text layer.
:pa... |
import unittest, random, sys, time, math
sys.path.extend(['.','..','py'])
import h2o, h2o_cmd, h2o_rf as h2o_rf, h2o_hosts, h2o_import as h2i, h2o_exec
import h2o_browse as h2b
print "This test will be good for testing RF against continuous feature (note the output depends only on col 0)"
print "We have to make the ou... |
from django.contrib.auth.decorators import login_required
from django.conf.urls import include, url
from django.contrib import admin
from quiz.views import answer_reader, QuestionDetail, QuizDetail, QuizList
urlpatterns = [
url('^accounts/', include('django.contrib.auth.urls')),
url(r'^admin/', admin.site.ur... |
# coding=utf-8
# Copyright 2021 Google LLC..
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
import numpy as np
from numpy.core.defchararray import upper
import pandas as pd
from scipy.optimize import minimize
import warnings
from . import utility_functions as utility_functions
import cvxpy as cp
class BaseEstimator:
def __init__(self, tickers) -> None:
self.tickers = tickers
def _get_logret... |
# Copyright 2013 Viewfinder Inc. All Rights Reserved.
"""Operation context support.
When an operation is executed, the Operation object is made available to all code executing
within the scope of that operation via a ContextLocal object. Furthermore, all logging within
this same scope is redirected to an op-specific ... |
# -*- coding: utf-8 -*-
"""DNA Center Delete SP Profile data model.
Copyright (c) 2019 Cisco and/or its affiliates.
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 ... |
# coding: utf-8
from __future__ import absolute_import, division, print_function
import sys
import _pytest._code
import pytest
import mock
from test_excinfo import TWMock
from six import text_type
def test_ne():
code1 = _pytest._code.Code(compile('foo = "bar"', "", "exec"))
assert code1 == code1
code2 = ... |
from CameraOrMarker import *
class Scenarios:
def __init__(self, scenario):
self.num_generated_samples = 217
self.std_corners_f_image = 0.3
self.marker_len = 0.162717998
# generate_solve_pnp_inputs options
self.use_sigma_points = False
self.use_dist_params = True... |
"""New features for Python v3.9.0.
- Dictionary Unions
- Typehints
- Timezones
- Removed prefix/suffix
"""
# Dictionary unions
a = {"name": "Taras", "job": "Adventurer"}
b = {"name": "Taras", "job": "Creator"}
print(a | b) # instead of {**a, **b}
a |= b # instead of a.update(b)
print(a)
# Timezones
from datetime... |
"""Constants for ledfxrm."""
# Base component constants
NAME = "LedFx ReMote"
DOMAIN = "ledfxrm"
DOMAIN_DATA = f"{DOMAIN}_data"
VERSION = "0.2.6"
MANUFACTURER = "YeonV"
ISSUE_URL = "https://github.com/YeonV/ledfxrm/issues"
# Icons
ICON_STRIP = "mdi:led-strip-variant"
ICON_STRIP_DEVICE = "mdi:led-strip"
ICON_SCENE = "... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class LyricsfreakcrawlerPipeline(object):
def process_item(self, item, spider):
return item
|
#!/usr/bin/env python
import sys, rospy, tf, actionlib, moveit_commander
from geometry_msgs.msg import *
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
from tf.transformations import quaternion_from_euler
from control_msgs.msg import (GripperCommandAction, GripperCommandGoal)
if __name__ == '__main__':
... |
from typing import Dict, List # isort:skip
import numpy as np
from sklearn.metrics import confusion_matrix as confusion_matrix_fn
from catalyst_rl.dl import Callback, CallbackNode, CallbackOrder, State, utils
from catalyst_rl.utils import meters
class ConfusionMatrixCallback(Callback):
def __init__(
se... |
# Copyright (c) 2021 Food-X Technologies
#
# This file is part of foodx_devops_tools.
#
# You should have received a copy of the MIT License along with
# foodx_devops_tools. If not, see <https://opensource.org/licenses/MIT>.
import copy
import pathlib
import typing
import unittest.mock
import pydantic
import pyte... |
import numpy as np
import numpy.testing as npt
import pandas as pd
from statsmodels.tsa.base.tsa_model import TimeSeriesModel
from statsmodels.tools.testing import assert_equal
from datetime import datetime
def test_pandas_nodates_index():
data = [988, 819, 964]
dates = ['a', 'b', 'c']
s = pd.Series(data... |
#!/usr/bin/env python3
# Copyright (c) 2017-2020 The XBit Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test various command line arguments and configuration file parameters."""
import os
from test_framework.... |
import os
import json
import yaml
import mlflow
from mlflow.tracking import MlflowClient
from mlflow.tracking.artifact_utils import _download_artifact_from_uri
from mlops.utils.sysutils import is_windows
class MlflowUtils:
mlflow_client: MlflowClient = None
@classmethod
def init_mlflow_client(cls, trac... |
#!/usr/bin/env python
# coding=utf-8
from openstack import connection
auth_token = "replace-with-your-token-id"
auth_url = "https://iam.example.com/v3"
token_conn = connection.Connection(
auth_url=auth_url,
auth_token=auth_token,
)
def test_list_endpoints(conn):
query = {
"limit": 3,
}
o... |
"""
Copyright (c) 2019 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from textwrap import dedent
import sys
from flexmock import flexmock
import pytest
import atomic_reactor.utils.koji as koji_util
from atomi... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com thumbor@googlegroups.com
from thumbor.loaders import LoaderResult
from thumbor_aws.config i... |
import json
from authomatic.adapters import WerkzeugAdapter
from flask import (
flash,
make_response,
redirect,
render_template,
request,
session,
url_for,
)
from flask_login import current_user, login_user, logout_user
from app import app, authomatic
from app.libraries.... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from pytorch_metric_learning import losses
class TripletLoss(nn.Module):
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
self.loss_fn = losses.TripletMarginLoss(**kwargs)
def forward(self, feats1, feats2):
... |
import numpy as np, pandas as pd
from scipy.sparse import csc_matrix, csr_matrix, issparse, isspmatrix_csc, isspmatrix_csr, vstack as sp_vstack
import warnings
import multiprocessing
import ctypes
import json
import os
from copy import deepcopy
from ._cpp_interface import (
isoforest_cpp_obj, _sort_csc_indices, _re... |
# This is a sample commands.py. You can add your own commands here.
#
# Please refer to commands_full.py for all the default commands and a complete
# documentation. Do NOT add them all here, or you may end up with defunct
# commands when upgrading ranger.
# A simple command for demonstration purposes follows.
# ---... |
from __future__ import unicode_literals
from __future__ import absolute_import
import json
import django
import django.utils.timezone as timezone
import datetime
from rest_framework import status
from rest_framework.test import APITestCase, APITransactionTestCase
import job.test.utils as job_test_utils
import metric... |
#!/usr/bin/env python
from setuptools import setup
import sys
assert sys.version_info[0] == 3, "creacli requires Python > 3"
__VERSION__ = '0.1.2'
setup(
name='creacli',
version=__VERSION__,
description='Command line tool to interface with the Crea network',
long_description=open('README.md').read()... |
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
from .imdb import imdb
from .pascal_voc import pascal_voc
from .pascal3... |
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# Copyright 2020 Open Reaction Database Project Authors
#
# 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... |
"""Intermediate representation of classes."""
from typing import List, Optional, Set, Tuple, Dict, Union, NamedTuple
from collections import OrderedDict
from mypyc.common import JsonDict
from mypyc.ir.ops import Value, DeserMaps
from mypyc.ir.rtypes import RType, RInstance, deserialize_type
from mypyc.ir.func_ir impo... |
import io
import os
import re
import numpy as np
import pytest
from lxml import etree
from extractnet import Blockifier, BlockifyError
from extractnet.features import KohlschuetterFeatures
from extractnet.compat import range_, str_cast
@pytest.fixture(scope="module")
def html():
fname = os.path.join("test", "da... |
#!/usr/bin/python
# Copyright (c) 2014 Wladmir J. van der Laan
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the directory ... |
from collections import deque
from typing import Tuple
import numpy as np
from gym import logger
from tensorflow import keras
"""
# References
# 1. https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf
# 2. https://arxiv.org/pdf/1509.06461.pdf
# 3. https://arxiv.org/pdf/1703.01327.pdf
# 4. https://drive... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# -*- coding: utf-8 -*-
from datetime import datetime, time
import warnings
import numpy as np
from pytz import utc
from pandas._libs import lib, tslib
from pandas._libs.tslibs import (
NaT, Timestamp, ccalendar, conversion, fields, iNaT, normalize_date,
resolution as libresolution, timezones)
import pandas.c... |
"""
A module for finding, managing, and using fonts across platforms.
This module provides a single `FontManager` instance that can
be shared across backends and platforms. The `findfont`
function returns the best TrueType (TTF) font file in the local or
system font path that matches the specified `FontProperties`
in... |
from webob.multidict import MultiDict
from pyramid.compat import text_
from pyramid.view import render_view_to_response
from pyramid.testing import DummyRequest
from pyramid.httpexceptions import HTTPFound, HTTPForbidden
import djed.form
from djed.testing import BaseTestCase, TestCase
class TestFormWidgets(TestCase)... |
from rest_framework import viewsets
from .models import Device, SensorType
from .serializers import DeviceSerializer, SensorTypeSerializer
class SensorTypeViewSet(viewsets.ReadOnlyModelViewSet):
queryset = SensorType.objects.all()
serializer_class = SensorTypeSerializer
class DeviceViewSet(viewsets.ReadOnl... |
{
'targets': [
{
'target_name': 'ml_mojo_bindings',
'type': 'static_library',
'variables': {
'mojo_root': '<(platform2_root)',
},
'sources': [
'mojom/graph_executor.mojom',
'mojom/machine_learning_service.mojom',
'mojom/model.mojom',
'mojom/ten... |
html_structure = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Files and Folder Srtucture by CodeStructureMaker</title>
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.