text stringlengths 1 927k |
|---|
"""
Adopted from AllenNLP:
https://github.com/allenai/allennlp/blob/v0.6.1/allennlp/nn/initializers.py
An initializer is just a PyTorch function.
Here we implement a proxy class that allows us
to register them and supply any additional function arguments
(for example, the ``mean`` and ``std`` of a normal initializ... |
coordinates_BCBCBC = ((159, 111),
(162, 108), (163, 108), )
coordinates_993300 = ((222, 14),
(222, 16), (222, 17), (222, 18), (222, 19), (222, 20), (222, 21), (222, 22), (222, 23), (222, 24), (222, 25), (222, 26), (222, 27), (222, 28), (222, 29), (222, 30), (222, 31), (222, 32), (222, 34), (222, 42), (222, 44), (2... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import gc
import time
import numpy as np
import matplotlib.pyplot as plt
from pyintdem.core import Band, RGB
from pyintdem.data import Sentinel2
# Directory Settings
input_dir='/run/media/khan/Backup KE Maxelev'
output_dir =... |
# -*- coding: utf-8 -*-
"""Test the terminaltables output adapter."""
from __future__ import unicode_literals
from textwrap import dedent
import pytest
from cli_helpers.compat import HAS_PYGMENTS
from cli_helpers.tabular_output import terminaltables_adapter
if HAS_PYGMENTS:
from pygments.style import Style
... |
#!/usr/bin/env python3
# Ensure environmental variables i.e. paths are set to used the modules
from xf_fintech_python import DeviceManager, MCEuropeanDJE, OptionType
import array
# State test financial model
print("\nThe Dow Jones MCEuropean financial model\n========================================\n")
# Declaring V... |
#
# Copyright (c) Pret-a-3D/Paolo Ciccone. All rights reserved.
# Modified by Fuzzy70/Lee Furssedonn with kind permission from Paolo Ciccone
#
from Reality_services import *
from Reality import *
# To customize this script all you need to do is to
# change the following variable
Re_sIBL_Map = ":Runtime:Textures:Reali... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import locale
import os
import re
import sys
import shutil
from PIL import Image
# setup done to /opt/bing-desktop-wallpaper-changer by BDWC Installer v3.3.1-release
path_to_Bing_Wallpapers="/opt/bing-desktop-wallpaper-changer"
# wait computer internet connection
os.system("... |
# coding: utf-8
"""
Accounting API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
OpenAPI spec version: 2.4.0
Contact: api@xero.com
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
from xero_pytho... |
# 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... |
import os
import sys
import time
import shlex
import shutil
import random
import inspect
import logging
import asyncio
import pathlib
import traceback
import math
import re
import aiohttp
import discord
import colorlog
from io import BytesIO, StringIO
from functools import wraps
from textwrap import dedent
from datet... |
# coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
import threading
from xrd.core.Singleton import Singleton
from pyqryptonight import pyqryptonight
class Qryptonight7(object, metaclass=Singleton):
def __init__(... |
# Copyright 2015, 2018 IBM Corp.
#
# 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 require... |
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from flask import session
from indico.core import signals
from indico.core.logger import Logger
from indi... |
# -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Licen... |
from google.appengine.ext import webapp
from django.utils import simplejson
import logging, pdb, traceback
from PdfMaker import PdfMaker
from MailInterface import MailInterface
from HtmlParser import HtmlParser
from django.utils import simplejson
from model.Hits import SiteStats
class ExtensionPostHandler(webapp.Reque... |
# Copyright 2007 by Tiago Antao <tiagoantao@gmail.com>. All rights reserved.
"""
This module allows to cache Simcoal2 results, and return on the fly
in case the calculation was done.
"""
import os
import tarfile
from .Controller import SimCoalController
class SimCoalCache(object):
def __init__(self, data_dir,... |
###
#
# Lenovo Redfish examples - Insert vitual media
#
# Copyright Notice:
#
# Copyright 2019 Lenovo Corporation
#
# 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.or... |
"""Plot the surface pressure coefficient at final time step."""
from matplotlib import pyplot
import numpy
import pathlib
import petibmpy
import rodney
def get_pressure(simudir, timestep):
name = 'p' # name of the field variable to load
datadir = simudir / 'output'
# Load the gridlines from file.
... |
import torch
import dgl
def cosine(nodes):
"""
Compute the cosine distance between all pairs of nodes adjacent on a source node.
"""
# ```m``` is a matrix of N nodes x E edges x F features
# representing the messages incident on source nodes with E edges
m = nodes.mailbox['m']
N = m.shap... |
"""
Django settings for UnoCPI project.
Generated by 'django-admin startproject' using Django 2.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
from dj... |
from BaseClient import BaseClient
class Client(BaseClient):
def createNetworkOffering(self, args={}):
'''
Creates a network offering.
args - A dictionary. The following are options for keys:
displaytext - the display text of the network offering
guestiptype - guest ... |
#!/usr/bin/python
#
# Copyright 2018-2020 Polyaxon, 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 ... |
#!/usr/bin/env python
# coding=utf-8
import requests,ssl,json,time,os
import threading
import sys
import re
import os.path
import os
from pyquery import PyQuery as pq
QRImagePath = os.path.join(os.getcwd(), 'qrcode.jpg')
def getInfos():
global uid,uidTime,sign,session_id
url = 'http://passport.115.com'
p... |
# AutoTransform
# Large scale, component based code modification library
#
# Licensed under the MIT License <http://opensource.org/licenses/MIT>
# SPDX-License-Identifier: MIT
# Copyright (c) 2022-present Nathan Rockenbach <http://github.com/nathro>
# @black_format
"""The settings command is used to update AutoTransf... |
import numpy as np
import pandas as pd
import os
from pytorch_widedeep.preprocessing import ImagePreprocessor
full_path = os.path.realpath(__file__)
path = os.path.split(full_path)[0]
df = pd.DataFrame({"galaxies": ["galaxy1.png", "galaxy2.png"]})
img_col = "galaxies"
imd_dir = os.path.join(path, "images")
processor... |
from whereami_server.version import GIT_SHA
def version(request):
return {
'version': GIT_SHA
} |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import json
import os
import pytest
from datadog_checks.dev import docker_run
from datadog_checks.mesos_slave import MesosSlave
from . import common
from .utils import read_fixture
@pytest.fixture(scope='sess... |
"""
Collection of Ivy activation functions.
"""
# global
from typing import Union
# local
import ivy
from ivy.framework_handler import current_framework as _cur_framework
# Extra #
# ------#
def relu(x: Union[ivy.Array, ivy.NativeArray])\
-> ivy.Array:
"""
Applies the rectified linear unit function... |
from requests import get
import datetime
import pandas as pd
from starlingpy.StarlingAPIs import Account_APIs
BASE_PATH = "https://api.starlingbank.com/api/v2/"
class TransactionHistory:
"""
A history of transactions associated with the Starling account, between stipulated datetimes.
Requires the Sta... |
import models, handlers
class Login(handlers.Handler):
"""Allows registered user to login"""
def get(self):
"""Renders login page"""
caller = handlers.sanitize(self.request.get('caller'))
self.render('login.html', caller=caller)
def post(self):
"""Accepts login info from lo... |
import argparse
import logging
import sys
import time
import coloredlogs
from basset.helpers.configuration_manager import ConfigurationManager
from basset.helpers.converter import Converter
from basset.helpers.extractor import Extractor
from basset.helpers.merger import Merger
from basset.exceptions import *
class ... |
GET = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3',
'Connection': 'keep-alive',
'Host': 'play.google.com',
'Upgrade-Insecure-Requests': '1',
'User-Age... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets, metrics
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.neural_network import BernoulliRBM
from sklearn.naive_bayes import GaussianNB
from sklearn.pipeline import Pipeline
b... |
"""
This script demonstrates how one can specify custom env APIs in
combination with RLlib's `remote_worker_envs` setting, which
parallelizes individual sub-envs within a vector env by making each
one a ray Actor.
You can access your Env's API via a custom callback as shown below.
"""
import argparse
import gym
import... |
import os
import shutil
import git
import yaml
from configuration import Configuration
from repoLoader import getRepo
from aliasWorker import replaceAliases
from commitAnalysis import commitAnalysis
from centralityAnalysis import centralityAnalysis
from tagAnalysis import tagAnalysis
def main():
try:
# r... |
# -*- coding: utf-8 -*-
from .BinaryTimeseries import BinaryTimeseries |
from math import hypot, atan2, sin, cos, pi
import random
import time
import xy
class Model(object):
def __init__(self):
self.particles = []
def add(self, x, y, m=1.0):
self.particles.append((x, y, m))
def test(self, x, y):
dx = 0
dy = 0
for px, py, pm in self.partic... |
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils import timezone
import datetime
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.Da... |
from sympy import Abs, exp, Expr, I, pi, Q, Rational, refine, S, sqrt
from sympy.abc import x, y, z
def test_Abs():
assert refine(Abs(x), Q.positive(x)) == x
assert refine(1 + Abs(x), Q.positive(x)) == 1 + x
assert refine(Abs(x), Q.negative(x)) == -x
assert refine(1 + Abs(x), Q.negative(x)) == 1 - x
... |
import pytest
import jax
import netket as nk
import numpy as np
from functools import partial
@pytest.mark.parametrize("jit", [False, True])
@pytest.mark.parametrize("batch_size", [None, 16, 10000, 1000000])
@pytest.mark.parametrize("return_forward", [False, True])
@pytest.mark.parametrize("batch_argnums", [1, (1,)]... |
import django
from django.conf import settings
from django.contrib.auth.models import User
from django.test import TestCase
import json
from django.core.urlresolvers import reverse
from core.models import Note, MediaBit
from core.tests.resources import HttpRequest
from core.tests.mocks import MockRequest
from tastypie ... |
# import pathlib
from pathlib import Path
ASSETS_PATH = Path(Path.cwd(), 'data') |
"""distutils
The main package for the Python Module Distribution Utilities. Normally
used from a setup script as
from distutils.core import setup
setup (...)
"""
__revision__ = "$Id$"
# Distutils version
#
# Updated automatically by the Python release process.
#
#--start constants--
__version__ = "2.7.1"
#-... |
""" Extend basic agent to an emotional agent.
"""
#: Dependencies
import numpy
import random
from .base import Agent
class EmotionalAgent(Agent):
""" Create emotional agent by extending and overriding base class Agent.
"""
def __init__(self, unique_id, experiment, memory=0):
""" Extended subcl... |
# Author: Kenta Nakamura <c60evaporator@gmail.com>
# Copyright (c) 2020-2021 Kenta Nakamura
# License: BSD 3 clause
from setuptools import setup
import muscle_tuning
DESCRIPTION = "muscle-tuning: A hyperparameter tuning tool, easy to use even if your brain is made of muscle"
NAME = 'muscle-tuning'
AUTHOR = 'Kenta Nak... |
try:
from better_exceptions import format_exception
except ImportError:
from traceback import format_exception
import sys
class TableExistsError(Exception):
pass
class StopOptimizationError(Exception):
def __init__(self, message, current_status):
super().__init__(message)
self.messag... |
# Frontend for neopo scripting interface
import sys
# Local imports
from .common import ProcessError
from .command import script_command
def main():
try:
script_command([None, *sys.argv])
except ProcessError as error:
print(error)
if __name__ == "__main__":
main() |
"""
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
"""
class Tests:
lc_tool_opened = (
"Landscape Canvas tool opened",
"Failed to open Landscape ... |
# -*- coding: utf-8 -*-
from tnn.calcdata import CalcData
# количество бинов
CD = CalcData( 5 )
# длина истории
history_tail = 5
for i in range(history_tail):
# задаем индикаторы
CD.addLookBackOp( "rsi", i, 6 )
CD.addLookBackOp( "stochastic", i, 6 )
CD.addLookBackOp( "roc", i, 6 )
CD.addLookBackOp( "sma", i, 6... |
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import absolute_import, division, print_function, unicode_literals
from collections import defaultdict, OrderedDict, deque
import copy
from logging import DEBUG, getLogger
from .auxlib.collection import ... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... |
from django.core.management.base import BaseCommand
from django.contrib.auth.models import Group
from symposion.review.models import ProposalResult
class Command(BaseCommand):
def handle(self, *args, **options):
ProposalResult.full_calculate() |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import win32api
import nonebot
from nonebot.adapters.cqhttp import Bot as CQHTTPBot
nonebot.init()
app = nonebot.get_asgi()
driver = nonebot.get_driver()
driver.register_adapter("cqhttp", CQHTTPBot)
nonebot.load_builtin_plugins()
nonebot.load_plugins("qqbot/plugins")... |
# Copyright 2018 The Bazel 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 applicable la... |
"""Provides modules for interacting with external services."""
from . import legacy, users
from .sessions import SessionStore |
# Copyright 2018-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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
# Copyright 2013 OpenStack Foundation
#
# 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 a... |
import unittest
import aiopg
from minos.common.testing import (
PostgresAsyncTestCase,
)
from minos.networks import (
BrokerPublisherSetup,
)
from tests.utils import (
BASE_PATH,
)
class TestBrokerSetup(PostgresAsyncTestCase):
CONFIG_FILE_PATH = BASE_PATH / "test_config.yml"
def setUp(self) -> ... |
# Copyright 2017 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 applicab... |
# -*- coding: utf-8 -*-
import scrapy
from paper.items import SciRobIssueItem
from scrapy.shell import inspect_response
class ScirobSpider(scrapy.Spider):
name = 'scirob'
base_url = "https://robotics.sciencemag.org/content/by/year/"
start_year = 2016
current_year = 2020
custom_settings = {
... |
import json
import logging
import traceback
def helper(function):
"""Decorator to mark helper functions.
Will do nothing to the original function.
"""
return function
def flask_method(function):
"""Decorator to handle errors."""
def generate_errcode(*args, **kwargs):
try:
... |
# Copyright 2015 Internap.
#
# 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, so... |
"""Settings for the Topology NApp."""
# Set this option to true if you need the topology with bi-directional links
# DISPLAY_FULL_DUPLEX_LINKS = True
# Time (in seconds) to wait before setting a link as up
LINK_UP_TIMER = 10
# Time (in seconds) to wait retrieve box from storehouse
BOX_RESTORE_TIMER = 0.1
# Time (in s... |
#!/usr/bin/env python3
"""conditions"""
name = input('What is your name? ')
age = int(input('Hi, ' + name + '. What is your age? '))
if age < 0:
print("That isn't possible.")
elif age < 18:
print('You are a minor.')
else:
print('You are an adult.') |
# @file Edk2Update
# Updates external dependencies for project_scope in workspace_path
# as listed in Platform Config file.
##
# Copyright (c) Microsoft Corporation
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
##
import logging
from edk2toolext import edk2_logging
from edk2toolext.environment import self_describing... |
import os
import time
import warnings
import multiprocessing as mp
from typing import List
import pandas as pd
import numpy as np
import scipy
import scipy.stats as stats
import matplotlib.pyplot as plt
from dateutil.relativedelta import relativedelta
from datetime import datetime
from tqdm import tqdm
from pvrpm.cor... |
# 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
from ... import _utilities, _tables
from... |
# Generated by Django 3.1b1 on 2020-12-10 17:42
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dtf', '0011_add_reference_sets_3'),
]
operations = [
migrations.AlterField(
model_name='project... |
#! /usr/bin/env python2.7
"""This program converts Datalog programs written in the Souffle dialect to
Datalog programs written in the Differential Datalog dialect"""
# pylint: disable=invalid-name,missing-docstring,global-variable-not-assigned,line-too-long
import json
import gzip
import os
import argparse
import p... |
import sys
import logging
from ._cli import YouTubeTranscriptCli
def main():
logging.basicConfig()
print(YouTubeTranscriptCli(sys.argv[1:]).run())
if __name__ == '__main__':
main() |
"""Laplacian matrix of graphs.
"""
# Copyright (C) 2004-2013 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
import networkx as nx
from networkx.utils import not_implemented_for
__author__ = "\n".join(['Aric ... |
import inspect
import scipy.constants
from scipy.optimize import newton
from scipy.optimize.optimize import _minimize_scalar_bounded
# Some useful physical constants (CODATA 2018: https://physics.nist.gov/cuu/Constants/).
# elementary charge, 1.602176634e-19 C.
q_C = scipy.constants.value('elementary charge')
# Bol... |
"""
Maigret main module
"""
import aiohttp
import asyncio
import csv
import http.cookiejar as cookielib
import json
import logging
import os
import platform
import re
import requests
import ssl
import sys
import tqdm.asyncio
import xmind
from aiohttp_socks import ProxyConnector
from argparse import ArgumentParser, Raw... |
import numpy as np
import matplotlib.pyplot as mpl
from matplotlib.ticker import NullFormatter
import sys
from glob import glob
import re
import os
if __name__=="__main__":
# Plot these ranges
plotranges = {
5.0 : [0.009 , 0.011],
10.0: [0.007 , 0.011],
15.0: [0.005 , 0.010],
20.0: [0.005 , 0.010],
25.0: [0.00... |
import datetime
import json
from sqlalchemy.event import listens_for
from backend.models.base import db, Column
class CTimestampMixin(object):
created_at = Column(db.DateTime(True), default=db.func.now())
updated_at = Column(db.DateTime(True), default=db.func.now())
def serialize_time(self, column):
... |
"""
Django settings for django_project project.
Generated by 'django-admin startproject' using Django 4.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from ... |
# coding=utf-8
from flask import flash
from flask_babel import gettext
from flask_wtf import Form
from wtforms import StringField, BooleanField, TextAreaField, PasswordField, \
validators
from flask_wtf.file import FileField, FileRequired
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from wtforms.valid... |
# Copyright (C) 2010-2011 Richard Lincoln
#
# 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, publish... |
import torch
from deepsnap.graph import Graph
from deepsnap.hetero_graph import HeteroGraph
from typing import (
Callable,
Dict,
List
)
class Batch(Graph):
r"""
A plain old python object modeling a batch of
:class:`deepsnap.graph.Graph` objects as one big (disconnected) graph,
with :class:... |
# MINLP written by GAMS Convert at 08/20/20 01:30:36
#
# Equation counts
# Total E G L N X C B
# 68 7 60 1 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc ... |
from models import Substantiv, Verb, StructAlt
cuvinte_din_enigma_otiliei = [
[Substantiv,
lambda cuvant:cuvant["singular"]["nume"],
"search_value",
[
{"singular": {"nume": "", "nev": ""}},
{"singular": {"nume": "", "nev": ""}},
{"singular": {"nume": "",... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
import numpy as np
class Flatten(nn.Module):
def __init__(self):
super(Flatten, self).__init__()
def forward(self, x):
"""
Arguments:
x: a float tensor with shape [batch... |
# -*- coding: utf-8 -*-
"""
Application views.
"""
# pylint: disable=W0223,E1101,W1203
import logging
from django.core.exceptions import ValidationError
from rest_framework import fields, filters, generics, serializers, status
from rest_framework.decorators import api_view, parser_classes
from rest_framework.paginat... |
from hashlib import md5
from hashlib import sha1
def hash_str(string, hash_type='md5'):
byte = string.encode('UTF-8')
if hash_type == 'md5':
hasher = md5
elif hash_type == 'sha1':
hasher = sha1
else:
raise ValueError('Unknown hash type: {}'.format(hash_type))
return hasher(... |
from django.contrib import admin
from fl_user.models import Job_status
from django.contrib import admin
# Register your models here.
class CustomUserAdmin(admin.ModelAdmin):
list_display = ('Doctor_user','date_submitted','assign_first_level_user','is_asigned','transcription_completed', 'QA_passed')
search_fie... |
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
"""
Test Creator role with Program scoped roles
"""
from integration.ggrc impor... |
from collections import defaultdict
import numpy as np
from yt.frontends.gadget_fof.io import IOHandlerGadgetFOFHaloHDF5
from yt.funcs import parse_h5_attr
from yt.units.yt_array import uvstack
from yt.utilities.io_handler import BaseIOHandler
from yt.utilities.on_demand_imports import _h5py as h5py
class IOHandler... |
# -*- coding: utf-8 -*-
# Copyright 2020 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... |
from form import Ui_Widget
from algorithm import Sorter
from globals import dprint
import globals
from PySide2 import QtCore, QtWidgets, QtGui
import sys
import random
class Widget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.ui = Ui_Widget()
self.ui.setupUi(self)
... |
def C(a, b, **kwargs):
print "C invoked: a=%s, b=%s, kwargs=%s" % (a, b, kwargs) |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
import gzip
import marshal
from math import log, exp
from ..utils.frequency import AddOneProb
class Bayes(object):
def __init__(self):
self.d = {}
self.total = 0
def save(self, fname, iszip=True):
d = {}
... |
import tensorflow as tf
def masked_softmax_cross_entropy(preds, labels, mask):
"""Softmax cross-entropy loss with masking."""
loss = tf.nn.softmax_cross_entropy_with_logits(logits=preds, labels=labels)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
loss *= mask
return ... |
import datetime
import os
from unittest import mock
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.core import mail
from django.core.files.base import ContentFile
from django.http import HttpRequest, HttpResponse
from django... |
# -*- coding: utf-8 -*-
"""
The configuration is a user specified file. This module works with those
user specified files.
The user must currently define a user_config.py file locally. This user_config
file can point to another file outside the repo that gets synced across
computers. More info on this can be found at ... |
#!/usr/bin/python3
import argparse
import importlib
import sys
def requester(service_pkg, service_name, namespace):
import rclpy
# Import the service
module = importlib.import_module(service_pkg + '.srv')
srv_mod = getattr(module, service_name)
req = srv_mod.Request()
resp = srv_mod.Response... |
# -*- coding: utf-8 -*-
#
# This file is part of Sequana software
#
# Copyright (c) 2016 - Sequana Development Team
#
# File author(s):
# Thomas Cokelaer <thomas.cokelaer@pasteur.fr>
# Dimitri Desvillechabrol <dimitri.desvillechabrol@pasteur.fr>,
# <d.desvillechabrol@gmail.com>
#
# Distributed un... |
# Created by MechAviv
# Knife Wound Damage Skin (30 Day) | (2436749)
if sm.addDamageSkin(2436749):
sm.chat("'Knife Wound Damage Skin (30 Day)' Damage Skin has been added to your account's damage skin collection.")
sm.consumeItem() |
# coding: utf-8
"""
CRM Objects
CRM objects such as companies, contacts, deals, line items, products, tickets, and quotes are standard objects in HubSpot’s CRM. These core building blocks support custom properties, store critical information, and play a central role in the HubSpot application. ## Supported O... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.