input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
# 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 applicable ... | |
"""Base class for modeling portfolio and measuring its performance.
The job of the `Portfolio` class is to create a series of positions allocated
against a cash component, produce an equity curve, incorporate basic transaction costs
and produce a set of statistics about its performance. In particular it outputs
... | |
<reponame>snapwire-media/arion<filename>tests/functional/test.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import unittest
import json
from subprocess import Popen, PIPE
class TestArion(unittest.TestCase):
ARION_PATH = '../../build/arion'
# Images for general purpose testing (leave off file:// for testi... | |
<filename>tensorflow/python/autograph/pyct/cfg.py<gh_stars>1-10
# 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.ap... | |
#!/usr/bin/python
#
# jvm-blocking-monitor.py Monitor JVM threads and prints stacktraces for long blocking threads.
# For Linux, uses BCC, eBPF.
#
# USAGE: jvm-blocking-monitor.py [-h] [-p PID | -u | -k] [-U | -K]
#
# Copyright 2021 <NAME>
# Licensed under the Apache License, Version 2.0 (the "License")
#
#
# This prog... | |
<filename>src/plottoolbox/functions/kde.py
# -*- coding: utf-8 -*-
"""Collection of functions for the manipulation of time series."""
from __future__ import absolute_import, division, print_function
import itertools
import os
import warnings
import mando
import numpy as np
import pandas as pd
from mando.rst_text_for... | |
<reponame>ZeayW/graph-contrastive-learning
from dataset_gcl import Dataset_gcl
from options import get_options
from model import *
from unity import CV_plot
import dgl
import pickle
import numpy as np
import os
from MyDataLoader_ud import *
from time import time
import math
import networkx as nx
from random import shuf... | |
= QLabel("")
img = QPixmap("icons/fan.png")
img_library.setContentsMargins(60,0,0,0)
img_library.setPixmap(img)
right_bottom_layout.addWidget(img_library)
fan_main_right_layout.addLayout(right_bottom_layout,60)
def tabChanged(self,i):
self.getTemperature()
self.getHumiditiy()
self.getWater()
self.ge... | |
<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 19 17:06:15 2014
@author: <NAME>
"""
# make sure the rest of the ABXpy package is accessible
import os
import sys
package_path = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
if not(package_path in sys.path):
sys.path.append... | |
that is necessary to
# capture RDKit error/warning messages. See
# https://stackoverflow.com/questions/24277488/in-python-how-to-capture-the-stdout-from-a-c-shared-library-to-a-variable
stderr_fileno = sys.stderr.fileno()
stderr_save = os.dup(stderr_fileno)
stderr_pipe = os.pipe()
os.dup2(stderr_pipe[1], stderr_f... | |
1, Pin name = IO_L40P_GCLK11_M1A5, Sch name = E-GTXCLK
Subsignal("gtx", Pins("L12")),
# NET "phyrxclk" LOC = "K15"; # Bank = 1, Pin name = IO_L41P_GCLK9_IRDY1_M1RASN, Sch name = E-RXCLK
Subsignal("rx", Pins("K15")),
IOStandard(LVCMOS_BANK1)
),
("eth", 0,
# NET "phyrst" LOC = "G13"; # Bank = 1, Pin name = IO_L32N... | |
activation='linear')(x)
outputs_gain = Lambda(lambda x: x * output_gain)(predictions)
# this creates a model that includes
# the Input layer and three Dense layers
opt_q_fa = RMSprop(lr = self.alpha)
self.q_fa = Model(input=inputs_q_fa, output=outputs_gain)
self.q_fa.compile(optimizer=opt_q_fa, loss='mse')
self... | |
it to the list of
# batches.
batch_info['type'] = batch_type
batches.append(batch_info)
prev_batch_info = batch_info
prev_batch_type = batch_type
# Now let's perform one last pass, this time through the new
# consolidated batches. That information will be used to generate
# the SQL and combined state needed d... | |
# -*- coding: utf-8 -*-
'''Simplicity masking and scoring classes.
'''
import os
import shutil
# 3rd-party packages
import pyfaidx
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# module packages
from . import cli
from .common import *
#
# global constants
#
TERM_CHAR = '$'
NUM_HISTOGRAM_BINS ... | |
1.0)
assert(X_cols[0][1][1] == 4.0)
assert(X_cols[1][1][0] == 2.0)
assert(X_cols[1][1][1] == 5.0)
assert(X_cols[2][1][0] == 3.0)
assert(X_cols[2][1][1] == 6.0)
def test_unify_feature_names_types_pandas_names1():
X = pd.DataFrame()
X["feature1"] = [1, 4]
X["feature2"] = [2, 5]
X["feature3"] = [3, 6]
X, n_samp... | |
<reponame>tamuhey/pytype<filename>pytype/tools/xref/indexer.py
#!/usr/bin/env python
"""Generate cross references from a project."""
from __future__ import print_function
import collections
from pytype import abstract
from pytype import analyze
from pytype import errors
from pytype import io
from pytype import load... | |
for this step
"""
if self._measure_shadow_work:
self.addComputeSum("old_ke", self._kinetic_energy)
# update velocities
if self._mts:
self.addComputePerDof(
"v", "v + ((dt / {}) * f{} / m)".format(
self._force_group_nV[force_group], force_group))
else:
self.addComputePerDof(
"v", "v + (dt / {}) * f / m".form... | |
import pandas as pd
import numpy as np
import random
import datetime
from tqdm import tqdm
from tr.core.resources import f1_in_tasks, f1_in_checks
from tr.core.utils import dict_to_list, diff_time_list, get_slots, diff_time_list_peak_season
from tr.core.utils import advance_date, days_between_dates, convert_iso_to_tim... | |
= chess.Move(squares[0], squares[1])
if not mv in board.legal_moves:
mv = chess.Move(squares[1], squares[0])
elif len(squares) == 3: # En passant capture.
if board.turn == chess.WHITE: # White move.
if squares[1] == squares[2] - 8: # Taken black pawn square.
mv = chess.Move(squares[0], squares[2])
else:
mv = ch... | |
<filename>src/icosahedron.py<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 26 09:41:29 2015
@author: sacim
"""
import numpy as np
import math
#=============================================================================
class Icosahedron:
def __init__(self, ngrid, name='ellipsoid'):
self.name = name ... | |
<filename>WDL/runtime/task_container.py
"""
Abstract interface for task container runtime + default Docker Swarm backend
"""
import os
import logging
import time
import json
import contextlib
import shutil
import random
import threading
import base64
import uuid
import hashlib
import shlex
from typing import Callable, ... | |
static_values_shape = None
with self.cached_session() as sess:
for op in ops:
if static_indices_shape is None:
static_indices_shape = op.indices.get_shape()
else:
self.assertAllEqual(
static_indices_shape.as_list(), op.indices.get_shape().as_list())
if static_values_shape is None:
static_values_shape = op.valu... | |
0.00000000371 * mu.cost(2.23508025241 + 4996.17273089800 * x)
R0 += 0.00000000300 * mu.cost(6.04069385215 + 9499.25986200560 * x)
R0 += 0.00000000345 * mu.cost(1.74260482164 + 5617.91076994730 * x)
R0 += 0.00000000302 * mu.cost(3.01127349940 + 7483.58877584580 * x)
R0 += 0.00000000289 * mu.cost(0.39479288685 + 2412... | |
= points
self.rotation = rotation
def to_inch(self):
self.start_point = tuple([inch(x) for x in self.start_point])
self.points = tuple([(inch(x), inch(y)) for x, y in self.points])
def to_metric(self):
self.start_point = tuple([metric(x) for x in self.start_point])
self.points = tuple([(metric(x), metric(y)) f... | |
"""
Webserver module based on aiohttp to handle web/api requests
"""
# flake8: noqa
# pylint: disable=wrong-import-position, wrong-import-order
import aiohttp
setattr(aiohttp.http, 'SERVER_SOFTWARE', '')
import sys
import re
import argparse
import uuid
import gc
from typing import Callable, Optional, Type, List, Dict,... | |
'3_dx', e1_crop_3.get())
config.set('Crop', '3_dy', e2_crop_3.get())
config.set('Crop', '3_width', e3_crop_3.get())
config.set('Crop', '3_height', e4_crop_3.get())
config.set('Crop', 'gravity', img_crop_gravity.get())
config.add_section('Border')
config.set('Border', 'on', str(img_border_on.get()))
config.set('B... | |
list.
"""
table = {"i":_readInt, "f":_readFloat, "s":_readString, "b":_readBlob, "d":_readDouble, "t":_readTimeTag}
decoded = []
address, rest = _readString(data)
if address.startswith(","):
typetags = address
address = ""
else:
typetags = ""
if address == "#bundle":
time, rest = _readTimeTag(rest)
d... | |
<reponame>fgonzalezvenegas/GridReconstructrion
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 16 18:02:09 2020
Pandapower !
@author: U546416
"""
#import mobility as mb
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection, PatchCollection
i... | |
for j in range(1, 13):
for k in range(2, 13):
for l in range(3, 13):
for m in range(4, 13):
if m == l + 1 and l == k + 1 and k == j + 1 and j == i + 1:
STRAIGHT_SCCHC.append({S[i], C[j], C[k], H[l], C[m]})
STRAIGHT_SCCHC.append({S[9], C[10], C[11], H[12], C[0]})
STRAIGHT_SCCHH = []
for i in range(13):
for j in r... | |
ID
"""
group_id = group_id or self.id_group(role)
try:
group_id = int(group_id)
except:
group_id = self.id_group(group_id) # interpret group_id as a role
if not user_id and self.user:
user_id = self.user.id
membership = self.settings.table_membership
record = membership(user_id = user_id,
group_id = group_i... | |
)
# self.plot_enc_attn.append(plot_attn_chunk)
# --------------------
hs_pad_temp1 = hs_pad_temp
mem_size = self.hwsize//self.compressive_rate
if self.conv1d2decoder is not None and not self.usespk_version2:
hs_pad_temp_mask = torch.ones(hs_pad_temp.size(0),1,hs_pad_temp.size(1)).type(memsh_mask.dtype).to(memsh_m... | |
<reponame>juanmed/singleshot6Dpose<filename>test2.py
# import support libraries
import os
import time
import numpy as np
# import main working libraries
import cv2
import torch
from torch.autograd import Variable
from torchvision import transforms
from PIL import Image
# import app libraries
from darknet import Darkn... | |
to remove in #5389
assert {perm["code"].lower() for perm in data["user"]["permissions"]} == {
permission_manage_orders.codename,
}
def test_staff_update_out_of_scope_user(
staff_api_client,
superuser_api_client,
permission_manage_staff,
permission_manage_orders,
media_root,
):
"""Ensure that staff user canno... | |
# Copyright 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 writing, softw... | |
<gh_stars>1-10
# Author:柠檬班-木森
# E-mail:<EMAIL>
import copy
import re
import json
import os
from numbers import Number
import requests
import jsonpath
from apin.core.dataParser import DataParser
from apin.core.initEvn import ENV, func_tools, DB
from apin.core.basecase import BaseTestCase
from apin.core.basecase import ... | |
<gh_stars>0
#!/usr/local/bin/python3
# DISCLAIMER:
"""
This script is for demo purposes only which provides customers with programming information regarding the Developer APIs. This script is supplied "AS IS" without any warranties and support.
We assume no responsibility or liability for the use of the script, conve... | |
word[1] == "j" :
toGuess = toGuess[:1] + "j" + toGuess[2:]
if word[2] == "J" or word[2] == "j" :
toGuess = toGuess[:2] + "j" + toGuess[3:]
if word[3] == "J" or word[3] == "j" :
toGuess = toGuess[:3] + "j" + toGuess[4:]
if word[4] == "J" or word[4] == "j" :
toGuess = toGuess[:4] + "j" + toGuess[... | |
Hera': ['Hera Boss'],
'Agahnims Tower': ['Tower Agahnim 1'],
'Palace of Darkness': ['PoD Boss'],
'Swamp Palace': ['Swamp Boss'],
'Skull Woods': ['Skull 1 Lobby', 'Skull 2 East Lobby', 'Skull 2 West Lobby', 'Skull Boss'],
'Thieves Town': ['Thieves Boss', ('Thieves Blind\'s Cell', 'Thieves Boss')],
'Ice Palace': ['... | |
= property(fget=lambda self: self._get_header_byte_range()[0])
def _populatePrco(self):
"Populate the package object with the needed PRCO interface."
tag2prco = { "OBSOLETE": share_data("obsoletes"),
"CONFLICT": share_data("conflicts"),
"REQUIRE": share_data("requires"),
"PROVIDE": share_data("provides") }
fo... | |
# -*- coding: utf-8 -*-
"""
Temporary file handling
AUTHORS:
- <NAME>, <NAME> (2012-10-18): move these functions here
from sage/misc/misc.py and make them secure, see :trac:`13579`.
- <NAME> (2013-03-17): add :class:`atomic_write`,
see :trac:`14292`.
"""
# **********************************************************... | |
'''
To run a Bokeh application on a Bokeh server from a single Python script,
pass the script name to ``bokeh serve`` on the command line:
.. code-block:: sh
bokeh serve app_script.py
By default, the Bokeh application will be served by the Bokeh server on a
default port ({DEFAULT_PORT}) at localhost, under the pat... | |
import tkinter as tk
from tkinter import ttk
import pandas as pd
from os import path
import random
import csv
import time
from datetime import datetime
from rfid.rfid import RFID
from pump.pump import Pump
class GUI(tk.Tk):
file_path = "/home/pi/Documents/CS179J-Smart-Water-Station/data/user_data.csv"
already_cou... | |
ims, markers=markers, marker_kwargs=marker_kwargs, save_file=save_file, **kwargs)
# plot differences
if interp_func.__name__ == 'interpolate_2d':
# use upper left corner as base frame for whole grid
base_im = ims[0][0]
ims_diff = [[None for _ in range(n_frames)] for _ in range(n_frames)]
for r, ims_list_y in enu... | |
<filename>gen/SessionTypeParser.py
# Generated from /Users/lorenzobacchiani/Desktop/session-subtyping-tool/SessionType.g4 by ANTLR 4.9
# encoding: utf-8
from antlr4 import *
from io import StringIO
import sys
if sys.version_info[1] > 5:
from typing import TextIO
else:
from typing.io import TextIO
def serializedATN(... | |
<gh_stars>0
# Translator of mathematical expressions into code in Assembler language.
from pythonds.basic.stack import Stack
from pythonds.trees.binaryTree import BinaryTree
from graphviz import Digraph
from sys import argv
from re import match
OPERATORS = frozenset("+-*/") | {'mul', 'add', 'sub', 'div'}
DIGITS = froz... | |
<filename>dlkit/abstract_osid/mapping/managers.py
"""Implementations of mapping abstract base class managers."""
# pylint: disable=invalid-name
# Method names comply with OSID specification.
# pylint: disable=no-init
# Abstract classes do not define __init__.
# pylint: disable=too-few-public-methods
# Some interfaces a... | |
<filename>rstoolbox/utils/tools.py
# -*- coding: utf-8 -*-
"""
.. codeauthor:: <NAME> <<EMAIL>>
.. affiliation::
Laboratory of Protein Design and Immunoengineering <lpdi.epfl.ch>
<NAME> <<EMAIL>>
.. func:: format_Ipython
.. func:: use_qgrid
.. func:: add_column
.. func:: split_values
.. func:: make_rosetta_app_path... | |
get_thread_full(9403)
return render_template_g('usermedals.html.jinja',
page_title = '勋章墙',
medals = medals,
t = t,
)
@app.route('/p/<int:pid>')
def getpost(pid):
p = get_post(pid)
url = get_url_to_post(str(pid))
resp = make_response('', 307)
resp.headers['Location'] = url
resp.headers['Cache-Control']= 'ma... | |
<gh_stars>1-10
import ujson as json
import pickle as pkl
import numpy as np
import logging
import os
import argparse
import random
import torch
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.data.distributed import DistributedSampler
import torch.distributed as dist
imp... | |
import sys
import time
from PyQt5 import QtCore
from dvg_qdeviceio import QDeviceIO, DAQ_TRIGGER
from dvg_debug_functions import dprint, tprint, ANSI
# Show extra debug info in terminal?
DEBUG = True
global cnt_DAQ_updated, cnt_jobs_updated, cnt_DAQ_paused
@QtCore.pyqtSlot()
def process_DAQ_updated():
# In product... | |
maximum of 5 roads in a row, so choose something else
r = random()
if r < 0.6:
row_class, index = Grass, randint(0,6)
elif r < 0.9:
row_class, index = Rail, 0
else:
row_class, index = Pavement, 0
# Create an object of the chosen row class
return row_class(self, index, self.y - ROW_HEIGHT)
class Pavement(Row)... | |
# -*- coding: utf-8 -*-
# Copyright 2017 IBM RESEARCH. 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... | |
tdl.losses.AddNLosses(reg))
else:
raise AttributeError(
'None of the Layers has a regularizer defined')
return reg
def __init__(self, input_shape, n_filters, filter_sizes, pool_sizes,
name='MultiConv2D'):
''' All variables corresponding to the weights of the network are defined
'''
assert len(input_shape) == ... | |
<filename>manuscript/python_generators/local_imports/PeptideBuilder.py
'''This module is part of the PeptideBuilder library,
written by <NAME>, <NAME>,
<NAME>, and <NAME>.
The PeptideBuilder module contains code to generate 3D
structures of peptides. It requires the Geometry module
(also part of the PeptideBuilder lib... | |
<reponame>biocore/gneiss
# ----------------------------------------------------------------------------
# Copyright (c) 2016--, gneiss development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# -----------------------... | |
<filename>tests/app/submitter/test_convert_payload_0_0_1.py
from app.data_model.answer_store import AnswerStore
from app.questionnaire.location import Location
from app.questionnaire.questionnaire_schema import QuestionnaireSchema
from app.submitter.convert_payload_0_0_1 import convert_answers_to_payload_0_0_1
from app... | |
SIGN TU': None,
'OLD PERSIAN SIGN U': None,
'OLD PERSIAN SIGN VA': None,
'OLD PERSIAN SIGN VI': None,
'OLD PERSIAN SIGN XA': None,
'OLD PERSIAN SIGN XSHAAYATHIYA': None,
'OLD PERSIAN SIGN YA': None,
'OLD PERSIAN SIGN ZA': None,
'OLD PERSIAN WORD DIVIDER': None,
'OLD SOUTH ARABIAN LETTER ALEF': None,
'OLD SOUTH ARABIAN ... | |
import re
from collections import namedtuple
from copy import copy
from difflib import SequenceMatcher
from pprint import pformat
from bs4 import BeautifulSoup
from bs4 import NavigableString
from bs4 import Tag
logger = None
def restore_refs(old_content: str,
new_content: str,
resolved_ids: list,
logger_,
res... | |
# coding=utf-8
# Copyright 2021 The Google Research 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... | |
-7.975908114097E-22, -8.350115450764E-22, -4.488982302467E-22,
1.385029207141E-22, 7.049456954407E-22, 7.049456954407E-22, 7.049456954407E-22,
7.049456954407E-22, 7.049456954407E-22, 7.049456954407E-22, 7.049456954407E-22,
7.049456954407E-22, 7.049456954407E-22, 7.049456954407E-22, 1.385029207141E-22,
1.38502920714... | |
None:
fn = self.rqdata.taskData.fn_index[self.rqdata.runq_fnid[task]]
taskname = self.rqdata.runq_task[task]
if task in self.rq.scenequeue_covered:
logger.debug(2, "Setscene covered task %s (%s)", task,
self.rqdata.get_user_idstring(task))
self.task_skip(task, "covered")
return True
if self.rq.check_stamp_tas... | |
True)
return False
if dbfunctions.get_playlist(self.db_session, text): # playlist exists
answer = self.create_dialog_ok_or_close(_("Overwrite Playlist?"), _("A playlist by the name '%s' already exists, overwrite?" % text))
if answer != "ok":
return False
dbfunctions.set_playlist(self.db_session, text, self.audio_... | |
import unittest
class Empty(Exception):
pass
class _DoublyLinkedBase(object):
"""A base class providing a doubly linked list representation."""
class _Node:
"""Lightweight, nonpublic class for storing a doubly linked node."""
__slots__ = '_element', '_prev', '_next' # streamline memory
def __init__(self, elem... | |
import logging
import os
import shutil
import socket
import time
import pytest
import salt.cache
import salt.loader
from salt.exceptions import SaltCacheError
from saltfactories.utils import random_string
from saltfactories.utils.ports import get_unused_localhost_port
from tests.support.mock import MagicMock, patch
d... | |
value=0.0, tags=tags101 + ['port:eth101/1/8'], hostname=hn101)
aggregator.assert_metric(metric_name, value=0.0, tags=tags101 + ['port:eth101/1/9'], hostname=hn101)
aggregator.assert_metric(metric_name, value=0.0, tags=tags101 + ['port:eth101/1/10'], hostname=hn101)
aggregator.assert_metric(metric_name, value=0.0, ta... | |
#-*- coding: utf-8 -*-
#!/usr/bin/env python
from telegram.ext import Updater
from telegram.ext import CommandHandler
from telegram.ext import MessageHandler, Filters
import telegram
import sys
import logging
import random
from string import maketrans
import time
from ip import facecount
root = logging.getLogger()
ro... | |
self.UserInput[-1].SetRect((pad + 165 + 15, offset, 100, 22))
self.UserInput[-1].Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
offset += 30
idx += 1
offset += 10
width, height = self.parent.GetClientSize()
self.DefaultButton = Button(self, label=u'Default')
self.DefaultButton.SetRect((15, height - 24 - 15, 75, 24))
se... | |
import matplotlib.pyplot as plt
import numpy as np
import pytest
from matplotlib.backends.backend_pdf import PdfPages
import landlab
from landlab.plot.imshow import _guess_location_from_name, _guess_location_from_size
@pytest.mark.slow
def test_imshow_grid():
rmg = landlab.RasterModelGrid((4, 5))
pp = PdfPages("t... | |
'''
@author <NAME>, <NAME>, <NAME>, <NAME>
@date 30.03.2015
@brief module for generating & matching particle distributions
'''
import numpy as np
from scipy.constants import e, c
from PyHEADTAIL.general.element import Printing
from PyHEADTAIL.particles.particles import Particles
from PyHEADTAIL.particles.rfbucket_m... | |
<filename>randomimagedownload.py<gh_stars>0
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Finds and downloads random images using the Google Custom Search API.
"""
__author__ = '<NAME> <$(echo nqnz.enshfr#tznvy.pbz | tr a-z# n-za-m@)>'
import os
import sys
import random
import datetime
import time
import argpar... | |
<filename>lib/check/__init__.py
# Copyright © 2012-2021 <NAME> <<EMAIL>>
#
# 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 us... | |
<filename>VL-BERT/common/backbone/resnet/resnet.py<gh_stars>10-100
"""
Modified from torchvision, but exposes features from different stages
"""
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch
import warnings
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet15... | |
= [
p for p in playlists if p not in [
'Music', 'Movies', 'TV Shows', 'Podcasts', 'iTunes\xa0U',
'Books', 'Genius', 'iTunes DJ', 'Music Videos',
'Home Videos', 'Voice Memos', 'Audiobooks'
]
]
playlists.sort(key=lambda x: x.lower())
except Exception as exc:
print('Error getting iTunes playlists:', exc)
playlis... | |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 24 15:55:28 2016
@author: sasha
"""
import os
from .init import QTVer
if QTVer == 4:
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import Navigatio... | |
= _messages.IntegerField(27, variant=_messages.Variant.INT32)
class BackupConfig(_messages.Message):
r"""BackupConfig defines the configuration of Backups created via this
BackupPlan.
Fields:
allNamespaces: If True, include all namespaced resources
encryptionKey: This defines a customer managed encryption key t... | |
import torch
import utils
from utils.hparams import hparams
from .diff.net import DiffNet
from .diff.shallow_diffusion_tts import GaussianDiffusion, OfflineGaussianDiffusion
from .diffspeech_task import DiffSpeechTask
from vocoders.base_vocoder import get_vocoder_cls, BaseVocoder
from modules.fastspeech.pe import Pitc... | |
<reponame>Vinomo4/Cryptography
# **BLOCKCHAIN**
# LIBRARIES
import sympy
import math
import random
import hashlib
import pickle
import time
import numpy as np
from prettytable import PrettyTable
import csv
#-------------------------------------------------------------------------------
# Filepaths
generated_path = "./... | |
"""****************************************************************************
@author: damv_ Hecho con amor, no olvides eso
Equilibrio para proyecto Calculos Equilibrio
Funciones y algoritmos necesarios para calculo de equilibrio. Libreria personal.
VALORES CONSTANTE R
R = 83.14472 Bar cm3 / mol K
R = 8.314472 MPa c... | |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/012_data.external.ipynb (unless otherwise specified).
__all__ = ['decompress_from_url', 'download_data', 'get_UCR_univariate_list', 'UTSC_datasets', 'UCR_univariate_list',
'get_UCR_multivariate_list', 'MTSC_datasets', 'UCR_multivariate_list', 'UCR_list', 'classification... | |
# -*- coding: utf-8 -*-
"""
Liouville pathways and their analysis
"""
import numpy
from ..utils.types import Integer
#from ..core.units import cm2int
from ..core.managers import UnitsManaged
import quantarhei as qr
class liouville_pathway(UnitsManaged):
order = Integer("order")
nint = Integer("nint")
de... | |
3)]
differentiator = 'enr'
class ConsentCompoundId(DatasetCompoundId):
"""
The compound id for an consent
"""
fields = DatasetCompoundId.fields + [
CompoundId.differentiatorFieldName, 'consent']
containerIds = DatasetCompoundId.containerIds + [('consent_id', 3)]
differentiator = 'con'
class DiagnosisCompoun... | |
<reponame>sn0b4ll/Incident-Playbook
# -*- coding: utf-8 -*-
# Copyright 2017-2019 ControlScan, Inc.
#
# This file is part of Cyphon Engine.
#
# Cyphon Engine 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, ver... | |
<gh_stars>0
# -*- coding:utf-8 -*-
"""
.. module:: ETFL
:platform: Unix, Windows
:synopsis: flux balance models accounting for expression, thermodynamics, and resource allocation constraints
.. moduleauthor:: ETFL team
Core for the ME-part
"""
from typing import Generic
import numpy as np
import opt... | |
"""
Endpoints file , for api code
"""
import logging
import os
import json
import redis
from celery import Celery
from app import Resource, request
from models import CustomActionsModel, ProjectsModel, \
CopyProjectModel, DomainsModel, ConversationsModel
from models import RefreshDbModel, IntentsModel, \
IntentDetai... | |
<filename>python_code/Quadrotor/Quadrotor.py
import math
import numpy as np
import random
import sys
sys.path.append('../../')
from Agent import Agent
radianToDegree = 180/math.pi
degreeToRadian = math.pi/180
# Rotation Matrix -> QTGM (Quadrotor To Global Matrix)
'''
phi =
theta =
psi = + -> Counter-clockwise (rotat... | |
import os
import xml.etree.ElementTree as et
import pickle
SHRUNK_RES_SUFFIX = '_shrunk'
XML_REF = 'http://www.mscsoftware.com/:xrf10'
STEPMAP_TAG = 'StepMap'
ENTITY_TAG = 'Entity'
COMPONENT_TAG = 'Component'
STEP_TAG = '{' + XML_REF + '}' + 'Step'
def get_results(result_file, reqs_to_get=None, t_min=None, t_max=None,... | |
<filename>MetaScreener/external_sw/mgltools/lib/python2.7/site-packages/openbabel.py<gh_stars>1-10
import sys
if sys.platform.find('linux') != -1:
try:
import dl
except ImportError:
import DLFCN as dl
sys.setdlopenflags(sys.getdlopenflags() | dl.RTLD_GLOBAL)
# This file was automatically generated by SWIG (http://... | |
from __future__ import unicode_literals
import collections
import logging
import pytz
import re
from django.db import transaction
from django.db.models import Q
from django.utils import timezone
from django.utils.translation import ugettext, ugettext_lazy as _
from rest_framework import serializers
from rest_framewor... | |
<reponame>panosmdma/SlackOnly-SlackBuilds
from __future__ import print_function, absolute_import
from distutils import sysconfig
from distutils import version
from distutils.core import Extension
import glob
import io
import multiprocessing
import os
import re
import subprocess
import sys
import warnings
from textwrap... | |
u'bn_lid_l_u_07', u'bn_lid_l_d_04', u'bn_lid_l_d_05', u'bn_lid_l_u_08', u'bn_lid_l_u_03',
u'bn_br_l_08', u'bn_br_l_09', u'bn_lid_l_u_01', u'bn_lid_l_u_02', u'bn_br_l_04',
u'bn_br_l_05', u'bn_br_l_06', u'bn_br_l_07', u'bn_br_l_01', u'bn_br_l_02', u'bn_br_l_03',
u'bn_nose_l', u'bn_mouth_l_01', u'bn_cheek_l_04', u'b... | |
<gh_stars>1-10
import django
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'exotic_bay_project.settings')
django.setup()
from exotic_bay.models import Pet
import datetime
def populate():
pets = {'Mexican Red Knee':
{'scientificName': '<NAME> (ex smithi)',
'price': 35,
'type': 'Inverts',
'stock': 1... | |
<filename>tests/test__default.py
# Copyright 2016 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 l... | |
import random
import time
from typing import (
Dict,
Iterable,
Sequence,
Tuple,
)
from cytoolz import (
pipe,
)
from eth_typing import (
BLSPubkey,
BLSSignature,
Hash32,
)
from eth_utils import (
to_tuple,
)
from eth.constants import (
ZERO_HASH32,
)
from py_ecc import bls
from eth2._utils.bitfield impor... | |
<reponame>Janspiry/A-Demo-for-Image-Inpainting-by-React
import torch.nn as nn
import torch
import numpy as np
import torch.nn.functional as F
from einops import rearrange, repeat
class ScaledDotProductAttention(nn.Module):
"""Scaled dot-product attention mechanism."""
def __init__(self, attention_dropout=0.0):
sup... | |
# from .global_variables import *
from PyPATools.field import Field
from PyPATools.pusher import ParticlePusher
import numpy as np
# import multiprocessing as mp
# import time
def track(si, r_start=None, v_start=None, nsteps=10000, dt=1e-12, omit_b=False, omit_e=False):
# TODO: For now break if r_start or v_start ar... | |
True},
}
#here, ga ada requested predicate
})
alice['job_application_proof'] = \
await anoncreds.prover_create_proof(alice['wallet'], alice['registration_req_proof_request'],
alice['registration_req_requested_creds'], alice['master_secret_id'],
alice['schemas'], alice['cred_defs'], alice['revoc_states'])
prin... | |
"""
Code adapted from the Mathis Lab
MIT License Copyright (c) 2022 <NAME>
DataJoint Schema for DeepLabCut 2.x, Supports 2D and 3D DLC via triangulation.
"""
import datajoint as dj
import os
import inspect
import importlib
import numpy as np
from pathlib import Path
from datetime import datetime
import ya... | |
in foreign_graph[part]:
if f not in graph[part]:
graph[part].append(f)
# graph[part] += foreign_graph[part]
continue
# print "get FK: {0}".format(field)
if not ForeignModel:
ForeignModel = cls.get_fk_model(field)
if not ForeignModel:
rest_helpers.log_print("no foreignkey: {0}".format(field))
continue
# prin... | |
payload = json.loads(r.text)
except Exception as e:
print("Failed to query DN. Exception: {}".format(e))
status = 666
return (status, payload)
def query_class(self, query_class, query_filter=''):
s = requests.Session()
try:
r = s.get('https://{}/api/node/class/{}.json{}'.format(self.apic,
query_class, query_f... | |
If one
number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
sho... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.