input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
""" Converter for Faceswap """
import logging
import cv2
import numpy as np
from plugins.plugin_loader import PluginLoader
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
class Converter():
""" The converter is responsible for swapping the original face(s) in a frame with the output
of a tr... | |
db_delete_value(self, value):
self._db_value = None
def getPrimaryKey(self):
return self._db_id
class DBLocation(object):
vtType = 'location'
def __init__(self, id=None, x=None, y=None):
self._db_id = id
self._db_x = x
self._db_y = y
self.is_dirty = True
self.is_new = True
def __copy__(self):
return ... | |
<filename>google/cloud/securitycenter/settings/v1beta1/securitycenter-settings-v1beta1-py/google/cloud/securitycenter/settings_v1beta1/services/security_center_settings_service/transports/grpc_asyncio.py
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License... | |
<reponame>samuelebortolotti/wikidump<filename>wikidump/processors/user_warnings_templates_tokens.py
"""Extract the most recurrent tokens of the template text"""
import json
import more_itertools
import mwxml
import datetime
from typing import Iterable, Iterator, Mapping, Optional
from backports.datetime_fromisoformat ... | |
scalar estimate), we preserve the uncertainty that reflects the instability of statistical inference of a small N dataset.
#
# One may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computationally-simpler, frequentist methods. ... | |
"""
Update components for HySDS.
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import os
from fabric.api import execute, hide
from tqdm impor... | |
"""
Created on Sep 14, 2017
@author: riteshagarwal
"""
import zlib
import copy
import json as Json
import json as pyJson
import os
import logging
import random
import socket
import string
import time
from httplib import IncompleteRead
from BucketLib.BucketOperations import BucketHelper
from BucketLib.MemcachedOperatio... | |
<gh_stars>10-100
# Mini-project 7 for Principles of Computing class, by k., 08/02/2014
# The Fifteen Puzzle
# http://www.codeskulptor.org/#poc_fifteen_template.py
'''
Loyd's Fifteen puzzle (solver and visualizer)
note that solved configuration has the blank (zero) tile in upper left;
use the arrows key to swap this t... | |
<reponame>samcom12/anuga_core
#!/usr/bin/env python
from __future__ import print_function
from __future__ import division
from builtins import zip
from builtins import map
from builtins import str
from builtins import range
from past.utils import old_div
import unittest
from math import sqrt, pi
import tempfile
from ... | |
# Copyright 2014 <NAME>
#
# 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
... | |
linked_aop = AffordanceObjectPair(aop.affordance, body_target, aop.affordance, None)
if not linked_aop.test(linked_context):
self.cancel()
return False
execute_result = linked_aop.interaction_factory(linked_context)
linked_si = execute_result.interaction
else:
posture_transition_context = PostureContext(self.int... | |
found %d other possible plays"%(len(final_set))
for i in range(len(final_set)):
show(final_set[i])
print
final_set = []
return True
##############end find_all_plays##################
def find_more():
'''
Offer all possible optimal plays!
By analysis..
'''
global roc
global qua
global tri
global pai
... | |
CC matrix, call build_cc_*() methods first!'
raise pexceptions.PySegInputError(expr='save_cc (ClassStar)', msg=error_msg)
if txt:
np.savetxt(fname, self.__cc)
else:
np.save(fname, self.__cc)
# Loads numpy array from disk and store it as a CC matrix
# fname: full path where CC 2D numpy array is stored, see nump... | |
#
#
"""
Created on Mon Jun 29 17:30:58 2020 author: <NAME>; building on code from <NAME>/<NAME>
Improvements by <NAME> June 2021 (clean-up and allowing verious rivers to be analysed in one Python program)
See: https://github.com/Flood-Excess-Volume
"""
# Imports
import matplotlib.pyplot as plt
import pandas as pd
from... | |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.patches as patches
from matplotlib.ticker import MultipleLocator, IndexLocator, LinearLocator
from floris.utils.visualization import property as ppt
default_fluent_dir = "../data/fluent"
basel... | |
(['pd'], self.PhantomDamage),
(['dtest'], self.DamageTest),
(['route', 'ルート'], self.Route),
(['allroute', '全ルート'], self.AllRoute),
(['clanattack'], self.AllClanAttack),
(['clanreport'], self.AllClanReport),
(['active', 'アクティブ'], self.ActiveMember),
(['servermessage'], self.ServerMessage),
(['serverleave'], self... | |
def verify_format(_, res):
return res
def format_index(body): # pragma: no cover
"""Format index data.
:param body: Input body.
:type body: dict
:return: Formatted body.
:rtype: dict
"""
result = {
'id': body['id'].split('/', 1)[-1],
'fields': body['fields']
}
if 'type' in body:
result['type'] = body['t... | |
<gh_stars>10-100
from functools import reduce
import itertools
from llvmlite import ir
import ctypes
from mathics.core.expression import Expression
from mathics.core.atoms import Integer, Real
from mathics.core.symbols import Symbol
from mathics.builtin.compile.types import int_type, real_type, bool_type, void_type
f... | |
of pcolor.
Args:
p1,p2,pcolor : parameter names
npoints : first thins the chain so this number of points are plotted
cmap : a colormap (default: jet)
nsig : map the range of the color map to +/- nsig
ax : axes to use for plotting (default: current axes)
cbar : whether to draw a colorbar
cax : axes to use for ... | |
#
#
#
from optparse import OptionParser
from pykd import *
IPv4 = 0x0008
ARP = 0x0608
IPv6 = 0xdd86
ICMP_PROTO = 0x01
UDP_PROTO = 0x11
TCP_PROTO = 0x06
NET_BUFFER_LIST = None
MDL = None
NET_BUFFER = None
def getNdisTypesInfo():
ndis = module("ndis")
global NET_BUFFER_LIST
global MDL
global NET_BUFFER
try... | |
_f is not None:
rc = repr(_f.f_code).split(',')[0].split()[-1]
rc = as_unicode(rc)
code_list.insert(0, rc)
_f = _f.f_back
finally:
f = None
_f = None
tb = None
_tb = None
ctx.frame_release()
#print code_list
__s = [(a, b, c, d) for (a, b, c, d) in s if g_fDebug or c != 'rpdb2_import_wrapper']
if (ct... | |
<reponame>takehuge/PYQUM
'''Basic QuBit Characterizations'''
from colorama import init, Fore, Back
init(autoreset=True) #to convert termcolor to wins color
from os.path import basename as bs
mdlname = bs(__file__).split('.')[0] # instrument-module's name e.g. ENA, PSG, YOKO
from time import time, sleep
from numpy im... | |
matrix_type = info_map[ subroutine ][ 'argument_map' ][ matrix_arg ][ 'code' ][ 'level_1_static_assert' ]
matrix_with_trans += [ matrix_type ]
else:
matrix_wo_trans.append( info_map[ subroutine ][ 'argument_map' ][ matrix_arg ][ 'code' ][ 'level_1_static_assert' ] )
#
# Matrices have trans options in this case. I... | |
#!/usr/bin/python2
# -*- coding: utf-8 -*-
import os
import json
import requests
from tabulate import tabulate
from HTMLParser import HTMLParser
log = []
h = HTMLParser()
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(s... | |
occurs that is
longer than `max_rate_limit` when making a request.
hikari.errors.RateLimitedError
Usually, Hikari will handle and retry on hitting
rate-limits automatically. This includes most bucket-specific
rate-limits and global rate-limits. In some rare edge cases,
however, Discord implements other undocument... | |
# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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... | |
better, better_rows):
i = 0
table1 = []
table2 = []
sheet_name = []
for title in titles:
print("\n")
print("Test Name: " + title)
print("---------------------------------------------------------------------------------------------------")
if not better[i]:
print("Response Times Worse than in the Previous Bui... | |
<reponame>ItGirls/event_extraction<gh_stars>100-1000
import os
import numpy as np
import time
import logging
from common_utils import set_logger
import tensorflow as tf
from sklearn.metrics import f1_score
from models.bert_mrc import bert_mrc_model_fn_builder
from models.bert_event_type_classification import bert_cla... | |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as data
import torch.optim as optim
import itertools
import tqdm
import copy
import scipy.stats as st
import os
import time
from scipy.stats import norm
device = 'cuda'
def gen_net(in_size=1, out_size=1, H=1... | |
not provided, the default SSL client certificate will be used if
present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
set, no client certificate will be used.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``Non... | |
= scene.camera
if self.renderFrom == 'TAB':
bpy.context.space_data.camera = bpy.data.objects[scene.camera.name]
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
context.area.spaces[0].region_3d.view_perspective = 'CAMERA'
break
for marker in marker_list:
if self._chosenCamera == marker... | |
# -*- coding: UTF-8 -*-
import maya.cmds as cmds
import maya.mel as mel
import socket
import pymel.core as pm
import os
import maya.OpenMayaUI as omui
from shiboken2 import wrapInstance
from inspect import getsourcefile
from PySide2 import QtCore
from PySide2 import QtUiTools
from PySide2 import QtWidgets
def maya_m... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE 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/L... | |
matrix=_create_matrices, name=name, deterministic=deterministic,
random_state=random_state)
class Emboss(Convolve):
"""
Emboss images and alpha-blend the result with the original input images.
The embossed version pronounces highlights and shadows,
letting the image look as if it was recreated on a metal plate ... | |
<filename>plasmasm/get_symbols.py
# Copyright (C) 2011-2020 Airbus, <EMAIL>
try:
from plasmasm.python.compatibility import reversed, sorted
except ImportError:
pass
from plasmasm.symbols import comm_symbol_section
def get_dynsyms(e):
if hasattr(e, 'Ehdr'):
relocs = [ sh for sh in e.sh if sh.sh.name in
[ a+b for a... | |
sl[35] = 0, 1289
sl[36] = 65, 1326
sl[37] = 65, 1251
sl[38] = 65, 1176
sl[39] = 65, 1026
sl[40] = 65, 876
sl[41] = 65, 726
sl[42] = 65, 576
sl[43] = 65, 426
sl[44] = 65, 276
sl[45] = 65, 126
sl[46] = 65, 51
sl[47] = 65, 201
sl[48] = 65, 351
sl[49] = 65, 501
sl[50] = 65, 651
sl[51] = 65, 951
sl[52] = 65... | |
3-D array
transformers = reshaped_temp + pstar # [2, grow, gcol]
# Correct the points where pTwp is singular
if flag:
blidx = det == np.inf # bool index
transformers[0][blidx] = vx[blidx] + qstar[0][blidx] - pstar[0][blidx]
transformers[1][blidx] = vy[blidx] + qstar[1][blidx] - pstar[1][blidx]
# Removed the po... | |
#!/usr/bin/env python
# Copyright 2016 <NAME>
# Apache 2.0.
from __future__ import print_function
from __future__ import division
from collections import defaultdict
import argparse
import sys
import math
def GetArgs():
parser = argparse.ArgumentParser(
description="Use a Bayesian framework to select"
"pronuncia... | |
from enum import Enum
from typing import List, Literal, Optional
from pydantic import BaseModel
from .bytes_to_base64url import bytes_to_base64url
from .cose import COSEAlgorithmIdentifier
from .json_loads_base64url_to_bytes import json_loads_base64url_to_bytes
from .snake_case_to_camel_case import snake_case_to_came... | |
<reponame>bcov77/npose<filename>voxel_array.py
#!/usr/bin/env python
import os
import sys
import itertools
import numpy as np
import random
if ( hasattr( os, "FAKE_NUMBA" ) ):
def njit(**k):
def outer_wrapper(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
return outer_wrapper
e... | |
<gh_stars>1-10
# Copyright 2020 Red Hat, 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 applic... | |
kwlabels = {
'top': self._cparams.get('toplabel', None),
'bot': self._cparams.get('botlabel', None),
'lft': self._cparams.get('lftlabel', None),
'rgt': self._cparams.get('rgtlabel', None),
'center': self._cparams.get('clabel', None)
}
if 'label' in self._cparams:
kwlabels[lblloc] = self._cparams.get('label')
... | |
from lib.base_controller import CommandHelp
from lib.utils import common, util, version, constants
from lib.get_controller import (
GetConfigController,
GetDistributionController,
GetPmapController,
GetRolesController,
GetSIndexController,
GetStatisticsController,
GetUdfController,
GetUsersController,
GetLaten... | |
"""Connects to TAXII servers via cabby and formats the data received for dispatching to a Carbon Black feed."""
import argparse
import logging
import traceback
import urllib3
import copy
import yaml
import os
from cabby.exceptions import NoURIProvidedError, ClientException
from requests.exceptions import ConnectionErr... | |
== 'alpha' and version[1] == 0)
)
)
)
) and 2 or 1 # NOQA
return self._SKIP_VERSION
if get_skip_version() == 1:
try:
# Django trunk since r7722 uses CollectedObjects instead of dict
from django.db.models.query import CollectedObjects
sub_objects = CollectedObjects()
except ImportError:
# previous versions ... | |
for p in root.self_and_parents(copy=False):
if p.isCloned():
clones.append(p.v)
if clones:
for p in c.all_positions(copy=False):
if predicate(p):
# Match if any node in p's tree matches any clone.
for p2 in p.self_and_subtree():
if p2.v in clones:
return [p.copy()]
return []
#@+node:tbrown.20140311095634.1518... | |
== pygame.K_2:
if midiplay == 1:
midi_notes = []
midiout.send_message([176, 123, 0])
midiplay = 0
odabrana_lista_nota = [i for i in lista_nota if findNote(i,obj_cursor.pozicija, obj_cursor.trajanje)]
lista_nota_sorted = []
lista_nota_index = []
kljucevi_nota = {}
midi_notes = []
for i in odabrana_lista_nota:
... | |
<reponame>GDGSNF/PXXTF
#!/usr/bin/env python
# -*- coding: utf-8 -*-"
# vim: set expandtab tabstop=4 shiftwidth=4:
"""
$Id$
This file is part of the xsser project, http://xsser.03c8.net
Copyright (c) 2011/2016 psy <<EMAIL>>
xsser is free software; you can redistribute it and/or modify it under
the terms of the GNU G... | |
237, 0x1DA, -1, False, -1
)
W110 = SimpleProperty(
PropertyCategory.FUNCTIONAL_REGISTER, PropertyType.WORD, 238, 0x1DC, -1, False, -1
)
W111 = SimpleProperty(
PropertyCategory.FUNCTIONAL_REGISTER, PropertyType.WORD, 239, 0x1DE, -1, False, -1
)
W112 = SimpleProperty(
PropertyCategory.FUNCTIONAL_REGISTER, PropertyType... | |
<filename>lib/twisted/web/sux.py
# -*- test-case-name: twisted.web.test.test_xml -*-
#
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
*S*mall, *U*ncomplicated *X*ML.
This is a very simple implementation of XML/HTML as a network
protocol. It is not at all clever. Its main features are tha... | |
rf_h = self.image_size / float(self.shape[1]) * scale_y / 2.0
rf_w = self.image_size / float(self.shape[2]) * scale_x / 2.0
else:
rf_h = self.receptive_field[0] * scale_y / 2.0
rf_w = self.receptive_field[1] * scale_x / 2.0
tl = (max(0, center_y - rf_h), max(0, center_x - rf_w))
tr = (max(0, center_y - rf_h), ... | |
list_project_files(self, project_id):
query_txt = (
"""{datanode(first:-1,project_id: "%s") {type file_name id object_id}}"""
% (project_id)
)
res = self.sub.query(query_txt)
if len(res["data"]["datanode"]) == 0:
print("Project " + project_id + " has no records in any data_file node.")
return None
else:
df = ... | |
is None:
W = SU2_get_Ws(tl)
prod = sp.array([[1]])
for i in xrange(tl):
prod = sp.kron(U, prod)
Ul = sp.zeros((tl + 1, tl + 1), dtype=sp.complex128)
for m in xrange(tl + 1):
for n in xrange(tl + 1):
Ul[m, n] = W[m].T.dot(prod.dot(W[n]))
return Ul
paus = [0.5 * sp.array([[0, 1], [1, 0]]),
0.5j * sp.ar... | |
<filename>test_Feb_18.py
#7.7.2019: Addition of axis ticks and labels and legends.
#7.7.2019: classifier comparison alpha colors adjusted to make testing points more transparent, removed QDA and neural net
##7.7.2019: runlog60. Emphasis on knn and svc.
##7.8.2019: n_neighbors reduced to 10; too slow
#7.13.2019: mod... | |
st.session_state:
Load_Data(20)
## Title
if st.session_state['init_data']['finished_game']:
st.markdown("<h1 style='text-align:left; float:left; color:blue; margin:0px;'>Guess Who?</h1>", unsafe_allow_html=True)
else:
st.markdown("<h1 style='text-align:left; float:left; color:blue; margin:0px;'>Guess Who... | |
#!/usr/bin/env python
#
# SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
# SPDX-License-Identifier: Apache-2.0
#
import os
import sys
import tempfile
import unittest
from io import StringIO
try:
from ldgen.fragments import Align, Flag, Keep, Sort, Surround, parse_fragment_file
from ldgen.sdkc... | |
import io
import datetime
from typing import TYPE_CHECKING, Optional, Union, Type, List, Dict, Awaitable
from .base.http import HTTPRequestBase, EmptyObject
from .model import Channel, Message, MessageReference, AllowedMentions, Snowflake, Embed, Attachment, Overwrite, \
Emoji, User, Interaction, InteractionResponse, ... | |
import numpy as np
from gym.spaces import Dict
from rlkit.data_management.replay_buffer import ReplayBuffer
from rlkit.torch.relational.relational_util import get_masks, pad_obs
class ObsDictRelabelingBuffer(ReplayBuffer):
"""
Replay buffer for environments whose observations are dictionaries, such as
- OpenAI Gy... | |
<gh_stars>1-10
from urllib import parse
from typing import Dict, Optional
from tea_client.http import HttpClient
from tea_client.handler import handler
from paperswithcode.config import config
from paperswithcode.models import (
Paper,
Papers,
Repositories,
Conference,
Conferences,
Proceeding,
Proceedings,
A... | |
<reponame>bruinxiong/pytorch3d<gh_stars>0
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
"""
Sanity checks for output images from the renderer.
"""
import os
import unittest
from collections import namedtuple
import numpy as np
import torch
from common_testing import (
TestCaseMixin,
get_p... | |
<filename>ae.py<gh_stars>1-10
"""
@summary: Python attribute editor template extending Maya's
Some methods have been re-implemented to have better control
Coding convention assimilates Maya's camelCase on purpose
@run: import coop.ae as cae (suggested)
@license: MIT
@repository: https://github.com/artineering-io/maya... | |
<gh_stars>0
from py42._compat import str
from py42._compat import UserDict
from py42._compat import UserList
from py42.clients.settings import check_lock
from py42.clients.settings import SettingProperty
from py42.clients.settings import show_change
from py42.clients.settings._converters import bool_to_str
from py42.cl... | |
# -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2020 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""Tests for Mir class.
Performs a series of test for the Mir class, which inherits from UVData. Note that
there is a separate test module for the MirParser class (mir_parser.py), which ... | |
'S', 'E', 'S', 'S', 'W', 'W', 'W', 'W', 'N', 'W', 'W', 'N', 'N', 'E', 'E', 'N', 'N', 'E', 'N']
# E7 F5 G5 H5
# Score 4 for path: ['E', 'S', 'E', 'S', 'S', 'W', 'W', 'W', 'W', 'N', 'W', 'W', 'N', 'N', 'E', 'E', 'N', 'E', 'N', 'N']
# E7 F5 G5 H5
# Score 4 for path: ['E', 'S', 'E', 'S', 'S', 'W', 'W', 'W', 'W', 'N', 'W', ... | |
<filename>projects/hog/tests/10.py
test = {
'name': 'Question 10',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> bacon_strategy(0, 9, cutoff=8, num_rolls=5)
26f5762c932a578994ea1c8fc7fa6c02
# locked
""",
'hidden': False,
'locked': True
},
{
'code': r"""
>>> bacon_strategy(9, 0, cutoff=6, num... | |
<reponame>IFinners/ligrarian
#!/usr/bin/env python3
"""Automatically update Goodreads and local Spreadsheet with book read info.
Args:
Three operational modes (g)ui, (s)earch or (u)rl
gui arguments:
None
search arguments:
Title of Book: Enclosed in double quotation marks
Author of Book: Enclosed in double quo... | |
not list else sorted(set([lb for lbs in lb_df for lb in lbs]))
self.binlb = OrderedDict([(lb, i) for i, lb in enumerate(labels)])
self.binlbr = OrderedDict([(i, lb) for i, lb in enumerate(labels)])
self.mltl = True
elif (binlb is None):
lb_df = self.df[self.df[self.label_col].notnull()][self.label_col]
labels = s... | |
'proceeding_paper',
'flight_readiness_report',
'post_flight_performance_report',
'education_outreach',
'verified_budget',
'final_motor_selection',
'close_out_finance_document',
'invoice_q1',
'invoice_q2',
'invoice_q3',
'invoice_q4',
'charges_certification',
'institutional_w9',
'url1',
'url2',
'url3',
't... | |
<filename>scripts/maint/updateFallbackDirs.py
#!/usr/bin/env python
# Usage:
#
# Regenerate the list:
# scripts/maint/updateFallbackDirs.py > src/or/fallback_dirs.inc 2> fallback_dirs.log
#
# Check the existing list:
# scripts/maint/updateFallbackDirs.py check_existing > fallback_dirs.inc.ok 2> fallback_dirs.log
# mv ... | |
temp <<= 1
if (self.flags & FC):
temp |= 1 # aka FC
if (temp & 0x100):
self.flags |= FC
else:
self.flags &= (~FC & 0xff)
temp &= 0xff
self.assign_then_set_flags(operand_ref, OperandRef(BYTE_VAL, temp))
# #define ROR(data) \
# { \
# temp = data; \
# if (flags & FC) temp |= 0x100; \
# if (temp & 1) flags |=... | |
#!/usr/bin/python
# OpenGL 1.4 code
import math
import os
import numpy
from freetype import *
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import pygame, pygame.image
from pygame.locals import *
width = 1600
height = 960
arrIcons = []
texIdB_P = None
texIdB_R =... | |
import torch
import torch.nn as nn
import torch.nn.functional as F
class SupConUnet(nn.Module):
def __init__(self, num_classes, in_channels=1, initial_filter_size=64,
kernel_size=3, do_instancenorm=True, mode="cls"):
super(SupConUnet, self).__init__()
self.encoder = UNet(num_classes, in_channels, initial_filter_s... | |
"Implements ConstraintSet"
from collections import defaultdict, OrderedDict
from itertools import chain
import numpy as np
from ..small_classes import Numbers
from ..keydict import KeySet, KeyDict
from ..small_scripts import try_str_without
from ..repr_conventions import GPkitObject
from .single_equation import SingleE... | |
import h5py
import os
import glob
import re
import numpy as np
from . import peano
import warnings
from scipy.integrate import quad
base_path = os.environ['EAGLE_BASE_PATH']
release = os.environ['EAGLE_ACCESS_TYPE']
class Snapshot:
""" Basic SnapShot superclass which finds the relevant files and gets relevant inform... | |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'resources/gui.ui'
#
# Created by: PyQt5 UI code generator 5.15.3
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore,... | |
import configparser
import json
import os
import socket
import time
import timeit
import datetime
import random
import docker
from requests.packages.urllib3.exceptions import ReadTimeoutError
from requests.exceptions import ReadTimeout, ConnectionError
from agaveflask.logs import get_logger, get_log_file_strategy
log... | |
from abc import abstractmethod, ABC
from .config import CoreConfig
from ..common_imports import *
from ..util.common_ut import concat_lists, ContentHashing
HASH_METHODS = ('causal', 'content')
COLLECTION_HASH_METHOD = 'causal'
################################################################################
### base... | |
<reponame>capsulecorplab/adventofcode2019<filename>day3/test_crossed_wires_part1.py
from crossed_wires import FuelManagementSystem
import pytest
class Test1:
@pytest.fixture
def fms(self):
return FuelManagementSystem("R8,U5,L5,D3", "U7,R6,D4,L4")
@pytest.fixture
def trace_dir1(self, fms):
return fms._trace_dir... | |
<reponame>annacrombie/meson<gh_stars>10-100
# Copyright 2016-2021 The Meson development team
# 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
# Un... | |
"""
mp7 module. Contains the Modpath7List and Modpath7 classes.
"""
import numpy as np
from ..mbase import BaseModel
from ..modflow import Modflow
from ..mf6 import MFModel
from ..pakbase import Package
from .mp7bas import Modpath7Bas
from .mp7sim import Modpath7Sim
from .mp7particledata import CellDataType, NodePar... | |
<gh_stars>0
import os
import json
import tempfile
import shutil
from django.core.files.uploadedfile import UploadedFile
from django.test import TestCase, RequestFactory
from django.contrib.auth.models import Group
from django.core.urlresolvers import reverse
from rest_framework import status
from hs_core import hydr... | |
<filename>autoreduce/local_sensitivity.py
from .system import System
from autoreduce import utils
import numpy as np
# from .ode import ODE
from scipy.integrate import solve_ivp, odeint
from sympy import lambdify
class SSM(System):
'''
Class that computes local sensitivity
analysis coefficients for the given Model... | |
#!/usr/bin/env python
u"""
infer_minor_corrections.py (08/2020)
Return correction for minor constituents based on Richard Ray's PERTH3 code
PERTH: PREdict Tidal Heights
CALLING SEQUENCE:
dh = infer_minor_corrections(t,zmajor,constituents)
INPUTS:
t: days relative to Jan 1, 1992 (48622 MJD)
zmajor: Complex HC for ... | |
= None
def __init__(self, Id=None, Status=None, StatusInfo=None, Message=None, gds_collector_=None, **kwargs_):
self.gds_collector_ = gds_collector_
self.gds_elementtree_node_ = None
self.original_tagname_ = None
self.parent_object_ = kwargs_.get('parent_object_')
self.ns_prefix_ = None
self.Id = Id
self.valida... | |
+ 0.5*m.b684*m.b807 + 0.5*m.b684*m.b808
+ 0.5*m.b684*m.b818 + 0.5*m.b684*m.b825 + 0.5*m.b685*m.b691 + 0.5*m.b685*m.b692 + 0.5*m.b685*
m.b696 + 0.5*m.b685*m.b698 + 0.5*m.b685*m.b701 + 0.5*m.b685*m.b707 + 0.5*m.b685*m.b710 + 0.5*
m.b685*m.b711 + 0.5*m.b685*m.b712 + 0.5*m.b685*m.b713 + 0.5*m.b685*m.b715 + m.b685*m.b720... | |
<filename>habitat/tasks/nav/nav_task.py
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, List, Optional, Type, Tuple
import attr
import cv2
impo... | |
# 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 applicable ... | |
# Adapted by <NAME>, 2019
#
# Based on Detectron.pytorch/lib/roi_data/fast_rcnn.py
# Original license text:
# --------------------------------------------------------
# Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in co... | |
<filename>alerter/src/monitors/contracts/chainlink.py
import copy
import json
import logging
from datetime import datetime
from datetime import timedelta
from http.client import IncompleteRead
from typing import List, Dict, Optional, Tuple
import pika
from requests.exceptions import (ConnectionError as ReqConnectionEr... | |
<reponame>wadmp/wadmp.github.io
#! /usr/bin/env python
"""
This script uses the public API to read the latest settings (both Reported and Desired),
for one or multiple sections,
from multiple devices.
<NAME>, January 2020
Copyright Advantech B+B SmartWorx, 2020
Version 0.6
Last tested on Ubuntu 18.04 with Python 3.... | |
file will have higher perf
lines = [file.readline().decode('ascii') for i in range(page_size)]
buf = io.StringIO('\n'.join((l for l in lines if not l.startswith('!'))))
# buf = io.StringIO('\n'.join(lines))
# lines = [file.readline() for i in range(page_size)]
# buf = io.BytesIO(b''.join(lines))
opts = dict(delim... | |
1,
int(ceil(D / blockdim[2])) if int(ceil(D / blockdim[2])) != 0 else 1)
if self.network_struc[i]['Type'] == 'conv':
# Set conv params
alpha = self.network_struc[i]['alpha']
beta = self.network_struc[i]['beta']
delay = self.network_struc[i]['delay']
C = self.layers[i]['C'][:, :, :] # Output delay counter before... | |
is received), call connect()
"""
log.debug("reconnecting...")
async def handler(event: Any) -> None:
# We yield here to allow synchronous handlers to work first
await asyncio.sleep(0)
self.connect()
self.add_event_handler('disconnected', handler, disposable=True)
self.disconnect(wait, reason)
def configure_so... | |
from typing import Any, Dict, List, Optional, Set, Callable, Tuple, Union
import torch
import copy
import warnings
from torch.fx import (
GraphModule,
)
from torch.fx.graph import (
Graph,
Node,
Argument,
)
from ..utils import (
activation_is_statically_quantized,
weight_is_quantized,
get_qparam_dict,
_parent_n... | |
'''Optimize rateless codes for distributed computing
'''
import math
import random
import logging
import numpy as np
import pandas as pd
import pyrateless
import stats
import complexity
import overhead
import pynumeric
import tempfile
import subprocess
from os import path
from multiprocessing import Pool
def optimi... | |
<reponame>cmcmaster1/pytorch-widedeep<filename>pytorch_widedeep/models/saint.py<gh_stars>0
"""
The code in this module is inspired by a number of implementations:
Classes PositionwiseFF and AddNorm are 'stolen' with much gratitude from the fantastic d2l.ai book:
https://d2l.ai/chapter_attention-mechanisms/transformer.... | |
import os
import dtlpy as dl
import tqdm
from keras.optimizers import Adam
import numpy as np
import json
import shutil
from collections import namedtuple
from train_with_params import get_anchors, get_classes, create_model, create_tiny_model, data_generator_wrapper
YOLO_DEFAULTS_PATH = os.path.join(os.environ.get('ZO... | |
<reponame>dimagilg/commcare-hq
import datetime
import random
from decimal import Decimal
from django.conf import settings
from django.core import mail
from django.test import override_settings
from dimagi.utils.dates import add_months_to_date
from corehq.apps.accounting import tasks, utils
from corehq.apps.accountin... | |
to control who can delete which keys.
Supported methods:
DELETE: /{mount_point}/keys/{name}. Produces: 204 (empty body)
:param name: Specifies the name of the encryption key to delete. This is specified as part of the URL.
:type name: str | unicode
:param mount_point: The "path" the method/backend was mounted o... | |
<reponame>GO-Eratosthenes/dhdt<filename>dhdt/postprocessing/solar_tools.py
import numpy as np
from pysolar.solar import get_azimuth, get_altitude
from datetime import datetime
from pytz import timezone
from scipy import ndimage
from scipy.spatial.transform import Rotation
from skimage import transform
# general loc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.