input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
#!/usr/bin/env python3
from astroquery.simbad import Simbad
from astroquery.vizier import Vizier
from cat_setup import src_localDB, src_onlineDB
from buildDB import addData, check_ldb
import sys, os
import csv
from more_itertools import locate
import argparse
import subprocess
from pathlib import Path
# for the spect... | |
<reponame>wisematch/KDMOT<gh_stars>0
import time
from collections import OrderedDict
import torch
from torch import nn
import torch.nn.functional as F
from torchvision.ops import boxes as box_ops
from torchvision.ops import MultiScaleRoIAlign
from src.test_person_search.project.misc import util
from src.test_person_s... | |
import functools
import operator
import pickle
import numpy as np
import pandas as pd
import pytest
from numpy.testing import assert_allclose, assert_array_equal
from packaging.version import Version
import xarray as xr
from xarray.core.alignment import broadcast
from xarray.core.computation import (
_UFuncSignature... | |
import os
import pygal
import shutil
from pygal.style import Style
from random import randint
from datetime import timedelta
from datetime import time
from datetime import datetime
from datetime import date
from graphs import Graphs
from dbtools import DbTools
gintMachineID = 0
gintCountryNr = 0
gintPlan... | |
<filename>overtime/algorithms/sliding_window_temporal_vertex_cover.py
import overtime as ot
import copy
import itertools
# Give a vertex set and return all subsets
def getSubSet(vertexSet):
"""
A method which returns the subset of a set
Parameter(s):
-------------
vertexSet : List
A list with node... | |
<reponame>jeremyfix/gan_experiments
#!/usr/bin/env python3
# coding: utf-8
# Standard imports
from typing import Optional, Tuple
from functools import reduce
import operator
# External imports
import torch
import torch.nn as nn
def conv_bn_leakyrelu(in_channels, out_channels):
"""
Conv(3x3, same) - BN - LeakyRelu(... | |
block to the committed chain, this function extends the
chain by updating the most recent committed block field
Args:
tblock (Transaction.TransactionBlock) -- block of transactions to
be committed
"""
with self._txn_lock:
logger.info('blkid: %s - commit block from %s with previous '
'blkid: %s',
tblock.Ident... | |
import torch.nn.functional as F
import torch
import logging
import torch.nn as nn
import numpy as np
import time
from torch.autograd import Variable
__all__ = ['sigmoid_dice_loss','softmax_dice_loss','GeneralizedDiceLoss','FocalLoss','dice','CE_loss','bce_loss','IOU_loss','TverskyLoss','SSIM']
cross_entropy... | |
<gh_stars>0
# Standard
import re
# PIP
import cupy
import torch
kernel_Softsplat_updateOutput = """
extern "C" __global__ void kernel_Softsplat_updateOutput(
const int n,
const float* input,
const float* flow,
float* output
) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex ... | |
<reponame>oi-analytics/oia-transport-archive
# -*- coding: utf-8 -*-
"""
Python script to create transport networks in Vietnam
Created on Wed June 27 2018
@author: <NAME>, <NAME>
"""
import pandas as pd
import os
import psycopg2
import networkx as nx
import csv
import igraph as ig
import numpy as np
import geopandas ... | |
# -*- coding: utf-8 -*-
from framework import BasePlayer, Choice, ChoiceDetails, utils, HintDetails
import functools
from copy import deepcopy
debug = False
class BaseTrustful:
def __init__(self):
self.card_hint_type = {}
self.hand_size = 5
def initialize_card_hint_history(self, round_info):
original_player_n... | |
"""
Python Interchangeable Virtual Instrument Driver
Copyright (c) 2017 <NAME>
derived from agilent436a.py driver by:
Copyright (c) 2012-2014 <NAME>
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 Soft... | |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 31 15:05:36 2018
@author: a001985
"""
import os
import shutil
import time
import json
import codecs
import pandas as pd
import logging
import importlib
# TODO: Move this!
#current_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
#... | |
ctx.channel, [url])
except Exception:
await ctx.send(
"Oops, an error occured. If this continues please use the contact command to inform the bot owner."
)
@commands.command(aliases=["setvoice"])
async def myvoice(self, ctx, voice: str = None):
"""
Changes your TTS voice.
Type `[p]listvoices` to view all poss... | |
<filename>jekyll.py
# -*- coding: utf-8 -*-
import imghdr
import io
import os
import re
import sublime
import sublime_plugin
import sys
import traceback
import uuid
import shutil
from datetime import datetime
from functools import wraps
try:
import simple_json as json
except ImportError:
import json
## ********... | |
#!/usr/bin/env python
# -*-coding:utf-8 -*-
import numpy as np
import numpy_financial as npf
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
class Mortgage:
"""
A class to represent a mortgage loan for purchasing a house. This is a base class that builds an amortization table... | |
<filename>ansible/modules/network/cloudengine/ce_mtu.py<gh_stars>1-10
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lice... | |
tabs ##
tab_def_content += '''\n<div class="tab">\n'''
## Operations tabs ##
for i, (op, heatmap_html_dir) in enumerate(zip(operations, heatmap_html_dir_l)):
viewer_name = 'op%s_%s' % (i, op)
tab_def_content += '''\n<button class="tablinks" '''
tab_def_content += '''onclick="openTab(event, '%s')"''' % viewer_nam... | |
# -*- coding: utf-8 -*-
# Copyright (c) 2020 Red Hat, Inc.
#
# 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, modif... | |
not str:
raise BadRequest("Attachment content must be str")
attachment.attachment_size = len(attachment.content)
attachment_content = attachment.content
elif attachment.attachment_type == AttachmentType.ASCII:
if type(attachment.content) is not str:
raise BadRequest("Attachment content must be str")
attachment.a... | |
import sys
import math
import scipy
import pylab
import scipy.io.wavfile as wav
import wave
from scipy import signal
from itertools import product
import numpy
def readWav():
"""
Reads a sound wave from a standard input and finds its parameters.
"""
# Read the sound wave from the input.
sound_wave = wave.open(s... | |
<reponame>paradiseng/jasmin
from datetime import datetime, timedelta
import re
import json
import pickle
from twisted.internet import reactor, defer
from twisted.web.resource import Resource
from twisted.web.server import NOT_DONE_YET
from smpp.pdu.constants import priority_flag_value_map
from smpp.pdu.smpp_time impor... | |
help='mining scenario either mp or mf')
parser.add_argument('--intrusion_time', type=int, default= 100, help='intrusion time for nuts release model')
# Spacer
opt = parser.parse_args()
print(opt)
#Nuts release data in units of [ci]
nuts_folder = opt.dir_NUTS
assert os.path.exists(nuts_folder)
print('Success... | |
stride of the sliding window for each dimension of the input tensor.
padding : string
'VALID' or 'SAME'. The padding algorithm. See the "returns" section of tf.ops.convolution for details.
data_format : string
'NDHWC' and 'NCDHW' are supported.
name : string
Optional name for the operation.
Returns
-------
A ... | |
<filename>pixel_link.py
import tensorflow as tf
import numpy as np
import cv2
import os
import util
PIXEL_CLS_WEIGHT_all_ones = 'PIXEL_CLS_WEIGHT_all_ones'
PIXEL_CLS_WEIGHT_bbox_balanced = 'PIXEL_CLS_WEIGHT_bbox_balanced'
PIXEL_NEIGHBOUR_TYPE_4 = 'PIXEL_NEIGHBOUR_TYPE_4'
PIXEL_NEIGHBOUR_TYPE_8 = 'PIXEL_NEIGHBOUR_TYPE... | |
<filename>easyscan_app/tests.py<gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime, pprint
# from easyscan_app.models import LasDataMaker, ScanRequest, StatsBuilder
from django.http import QueryDict
from django.test import TestCase
from easyscan_app.lib.data_prepper import LasD... | |
<gh_stars>1-10
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS ... | |
# -*- coding: utf-8 -*-
#
# Copyright © 2014, Emutex Ltd.
# All rights reserved.
# http://www.emutex.com
#
# Author: <NAME> <<EMAIL>>
# Author: <NAME> <<EMAIL>>
#
# See license in LICENSE.txt file.
#
# Wiring-x86 is a Python module that lets you use Arduino like functionality
# on
# Intel® Gaileo
# Intel® Gaileo Gen2
#... | |
<filename>main.py
#######################################################################
# Copyright (C) 2017 <NAME>(<EMAIL>) #
# Permission given to modify the code as long as you keep this #
# declaration at the top #
#######################################################################
import logging
from agent ... | |
from sympy import (
Basic,
Symbol,
sin,
cos,
atan,
exp,
sqrt,
Rational,
Float,
re,
pi,
sympify,
Add,
Mul,
Pow,
Mod,
I,
log,
S,
Max,
symbols,
oo,
zoo,
Integer,
sign,
im,
nan,
Dummy,
factorial,
comp,
floor,
)
from sympy.core.parameters import distribute
from sympy.core.expr import unchanged... | |
number of grid points"""
return self.params.gridPointsX*self.params.gridPointsY*\
self.params.gridPointsZ
def autocenterCoarseGrid(self):
"""Autocenters coarse grid"""
coords = self.getCoords()
center=(Numeric.maximum.reduce(coords)+Numeric.minimum.reduce(coords))*0.5
center = center.tolist()
self.params.coar... | |
import matplotlib.pyplot as plt
import tensorflow as tf
from keras.engine.input_layer import InputLayer
from keras.layers import Lambda, BatchNormalization
from keras.models import Model
from keras import backend as K
from sklearn import metrics
from fully_connected_opt_weight_generation import *
import time
import wa... | |
Two kinds of bad characters:
1. Unicode replacement characters: These indicate that either the file
contained invalid UTF-8 (likely) or Unicode replacement characters (which
it shouldn't). Note that it's possible for this to throw off line
numbering if the invalid UTF-8 occurred adjacent to a newline.
2. NUL byt... | |
x)*r[-1]/wr, x)*i/r[order]
negoneterm *= -1
if r.get('simplify', True):
psol = simplify(psol)
psol = trigsimp(psol, deep=True)
return Eq(f(x), gsol.rhs + psol)
def ode_separable(eq, func, order, match):
r"""
Solves separable 1st order differential equations.
This is any differential equation that can be wri... | |
# Copyright 2011 OpenStack Foundation
# Copyright 2013 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
#
# Unle... | |
"""This module contains unit tests for :mod:`~prody.select`."""
import os
import os.path
import inspect
import numpy as np
from numpy.testing import *
from prody import *
from prody import LOGGER
from prody.tests import unittest
from prody.tests.datafiles import *
from prody.atomic.atommap import DUMMY
try:
range =... | |
<reponame>jay51/pyscript<filename>test/test_all.py<gh_stars>0
import pytest
from pjscript import *
from io import StringIO
import sys
example1 = """
var x = 2;
log("x: ", x);
var y = x++ * 2;
log("y: ", y);
log("x: ", x);
var x = 2;
log("x: ", x);
var y = ++x * 2;
log("y: ", y);
log("x: ", x);
"""
examp... | |
"""Main Flask code handling REST API"""
import base64
import json
import os
import re
import rq
import saml2
import threading
import time
import uuid
import crackq
from crackq.db import db
from crackq.logger import logger
from crackq.models import User, Templates, Tasks
from crackq import crackqueue, hash_modes, auth
... | |
info_poi = info_poi[:int(num_poi)]
return jsonify(result = info_poi, status = query_success, timestamp=time.time(), log_time=task_id)
#-----------------------------------------------------------------
#Get points that are a certain travel time away from a point selected by ID, can filter by category and/or concel... | |
"""
Core functions of the forward models.
.. seealso::
:mod:`arim.models`
:mod:`arim.scat`
:mod:`arim.ut`
"""
# This module is imported on demand. It should be imported only for modelling.
# Function that are not modelling-specific should go to arim.ut, which is always imported.
import warnings
import abc
import ... | |
axis=[1,2,3], keepdims=True)
lname = self._write_caffe(name)
return res , lname
class activation(KLayer):
"""
Basic activation layer
"""
def __init__(self, param, **kwargs):
"""
Possible values:
- model3.PARAM_RELU
- model3.PARAM_LRELU
- model3.PARAM_ELU
- model3.PARAM_TANH
- model3.PARAM_MF... | |
# -*- coding: utf-8 -*-
from sst_unittest import *
from sst_unittest_support import *
import os
import shutil
import fnmatch
import csv
################################################################################
# Code to support a single instance module initialize, must be called setUp method
module_init = 0
m... | |
<reponame>luxunxiansheng/DRLGP<gh_stars>0
# Lint as: python3
from __future__ import absolute_import, division, print_function
import collections
import enum
import math
import threading
import typing
from typing import Dict, List, Optional
import numpy
import torch
import torch.nn as nn
import torch.nn.functional as ... | |
(mantissa, int(exp))
def __write_images(image_outputs, display_image_num, file_name):
"""Save output image
Arguments:
image_outputs {Tensor list} -- list of output images
display_image_num {int} -- number of images to be displayed
file_name {str} -- name of the file where to save the images
"""
image_outputs =... | |
| wx.EXPAND,
)
self.text_content = wx.TextCtrl(self.panel,
wx.ID_ANY,
style=wx.TE_MULTILINE
)
self.text_content.SetMinSize((400, 200))
self.vbox1.Add(self.text_content)
# Button definitions and bindings
self.button_add = wx.Button(self.panel, wx.ID_ANY, label=_(u'新增'))
self.butto... | |
#!/usr/bin/python
import os
import sys
import codecs
import re
import locale
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)
class Node(object):
def __init__(self, text):
self.text = text
self.lex = None
self.type = None
self.__attributes = {}
self.errors = []
self.name = None
self.pa... | |
<filename>modules/pytket-qiskit/pytket/extensions/qiskit/backends/aer.py
# Copyright 2019-2021 Cambridge Quantum Computing
#
# 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.apach... | |
import numpy as np
import scipy as sp
from scipy.sparse import linalg
import copy
import moments.Spectrum_mod
from . import Numerics
import Jackknife as jk
import LinearSystem_1D as ls1
import LinearSystem_2D as ls2
from . import Reversible
#------------------------------------------------------------------------------... | |
'Nangus'},
'61269448':{'en': 'Burra'},
'6126945':{'en': 'Coolac'},
'61269456':{'en': 'Tooma'},
'61269457':{'en': 'Tumbarumba'},
'61269458':{'en': 'Tumorrama'},
'61269459':{'en': 'Tumut'},
'612694600':{'en': 'Wallendbeen'},
'612694601':{'en': 'Wallendbeen'},
'612694602':{'en': 'Wallendbeen'},
'612694603':{'en'... | |
de Caxias",
"es_ES": "Duque de Caxias",
"fr_FR": "Duque de Caxias",
"it_IT": "Duque de Caxias",
"ja_JP": "ドゥケ・デ・カシアス",
"ko_KR": "두키지카시아스",
"pl_PL": "Duque de Caxias",
"pt_BR": "Duque de Caxias",
"ru_RU": "Дуки-ди-Кашиас"
},
"DURMUTI": {
"de_DE": "Durmuti",
"es_ES": "Durmuti",
"fr_FR": "Durmuti",
"it_IT": ... | |
import numpy as np
import matplotlib.pyplot as plt
import os, sys, time
from scipy.interpolate import RectBivariateSpline
from sklearn.metrics.pairwise import euclidean_distances
from matplotlib.ticker import FuncFormatter, MaxNLocator
import matplotlib.lines as mlines
from se2waveload import *
from Lib_GeneralFunc... | |
<gh_stars>0
import re
import codecs
import os
from pythonds.basic.stack import Stack
"""
[1] Main Function
"""
def main():
directory = os.getcwd() + '/InputDataType2'
filename = 'BGHO0437.txt'
filename = os.path.join(directory, filename)
f = open(filename, 'r', encoding='utf-16')
is_inside = False
line_counter ... | |
+= 1
# Store the model states before and after resampling
if self.do_save or self.p_save:
self.save(before=True)
if self.do_resample: # Can turn off resampling for benchmarking
self.reweight()
self.resample()
weightdf=pd.DataFrame(list(self.weights))
self.weight_hist = pd.concat([self.weight_hist,weightdf],a... | |
import logging
import numpy as np
import numba
import math
import sys
import time
from multiprocessing.pool import ThreadPool
from plato.backend.common import *
from plato.backend.branch_common import *
from plato.backend.stat_expression import *
from .adapter import BranchTrainingHeatMapAdapter, calc_location
logg... | |
<filename>spearmint/kernels/kernel_utils.py
# -*- coding: utf-8 -*-
# Spearmint
#
# Academic and Non-Commercial Research Use Software License and Terms
# of Use
#
# Spearmint is a software package to perform Bayesian optimization
# according to specific algorithms (the “Software”). The Software is
# designed to automat... | |
import asyncio
import json
import time
import logging
from datetime import timedelta
from functools import partial
from dataclasses import dataclass
import async_timeout
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from aiohttp import ClientSession
from homeassistant.const import *
fro... | |
# not all required parameters are in voevent xml file
# return id if it is already in the database
return self.get_id_existing(table, cols, value)
except psycopg2.IntegrityError:
# rollback changes
self.connection.rollback()
# re-raise exception
raise
def get_authortime(self):
'''
Get time voevent file was a... | |
<filename>tests/unit_tests/test_set_dropin.py
import pytest
from unittestmock import UnitTestMock
from cykhash import Int64Set, Int32Set, Float64Set, Float32Set, PyObjectSet
import cykhash
SUFFIX={Int64Set : "int64",
Int32Set : "int32",
Float64Set : "float64",
Float32Set : "float32",
PyObjectSet : "pyobject"... | |
value > a:
return a
else:
return value
def pivotScalar(scalar, pivot):
# reflect scalar about pivot; see tests below
return pivot + (pivot - scalar)
if __debug__ and __name__ == '__main__':
assert pivotScalar(1, 0) == -1
assert pivotScalar(-1, 0) == 1
assert pivotScalar(3, 5) == 7
assert pivotScalar(10, 1) =... | |
Shape [N, H, W, C]
alpha (float, optional): Regularization weight. Defaults to 0.012.
ratio (float, optional): Downsample ratio. Defaults to 0.8.
min_width (int, optional): Minimal witdth of the coarsest level. Defaults to 20.
n_outer_fp_iterations (int, optional): Number of outer fixed point iterations. Defaults t... | |
8:2.000000 9:1.000000 10:1.000000
... '''
>>>
>>> import numpy as np
>>> # Each row is an instance and takes the form **<target value> <feature index>:<feature value> ... **.
... # Dataset is 'classification' type and target values (first column) represents class label of each sample, i.e., type='classification' (... | |
<reponame>kiranrraj/100Days_Of_Coding
# Title : Selection sort Method#1
# Author : <NAME>.
# Date : 05:11:2020
arr=[50,5,7,1,34,22,12,3,45,2,16,8,48]
def selection_sort(arr):
length = len(arr)
# loop = 0
for i in range(length):
print(f"Main Loop:{i+1}")
for j in range(i+1,length):
# loop+=1
print(f"Sub loop:... | |
<reponame>tkamishima/kamrecsys<filename>kamrecsys/model_selection/split.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Data Splitter for hold-out tests or cross validation.
The usage of these splitter classes are similar to the splitters of `sklearn`
such as :class:`sklearn.model_selection.KFold` .
"""
from __f... | |
"""
Support for STATS data files.
STATS binary file structure
===========================
A stats binary output files begins with a stats_hdt_t structure::
typedef struct
{
(unsigned short header_size /* bytes, may or may not be there */
unsigned short spcid; /* station id - 10, 40, 60, 21 */
unsigned short vs... | |
below to reduce I/O ?
echo -e "\nMapping sample to assembly ... "
bwa mem -t {config[cores][metabat]} $fsampleID.fa *.fastq.gz > $id.sam
echo -e "\nConverting SAM to BAM with samtools view ... "
samtools view -@ {config[cores][metabat]} -Sb $id.sam > $id.bam
echo -e "\nSorting BAM file with samtools sort ... ... | |
bias correction for: " + \
input_forcings.productName + " (" + str(npe) + ")"
err_handler.log_critical(config_options, mpi_config)
err_handler.check_program_status(config_options, mpi_config)
try:
input_forcings.final_forcings[input_forcings.input_map_output[force_num], :, :] = lwdown_in[:, :]
except NumpyExcept... | |
HTTP header `Accept`
header_params['Accept'] = self._select_header_accept(
['application/json'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self._select_header_content_type(
['application/json'])
body_params = request
# Authentication setting
auth_settings = ['JWT']
http_request_object = Htt... | |
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy import (abs, asarray, cos, exp, floor, pi, sign, sin, sqrt, sum,
size, tril, isnan, atleast_2d, repeat)
from numpy.testing import assert_almost_equal
from .go_benchmark import Benchmark
class Carr... | |
`examples/user_team_mgmt_extended.py <https://github.com/draios/python-sdc-client/blob/master/examples/user_team_mgmt_extended.py>`_
'''
res = self.list_memberships(team)
if res[0] is False:
return res
full_memberships = res[1]
full_memberships.update(memberships)
res = self.edit_team(team, full_memberships)... | |
<reponame>MediaBrain-SJTU/GroupNet
import copy
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
def encode_onehot(labels):
classes = set(labels)
classes_dict = {c: np.identity(len(classes))[i, :] for i, c in
enumerate(classes)}
labels_onehot... | |
or reservation.start_time < '14:30' < reservation.end_time:
if r1400_1430_yesterday.count(reservation) == 0:
r1400_1430_yesterday.append(reservation)
if '14:30' <= reservation.start_time < '15:00':
r1430_1500_yesterday.append(reservation)
if '14:30' < reservation.end_time <= '15:00' or reservation.start_time < '1... | |
X2=x2, X3=x3, *X4, **X5): X1, X5, x6, X9
def F2(X7=x7): X7
def F3(a1): a1
def F4(): a1
''').lstrip())
db = ImportDB("from m2 import x1, x2, x3, x4, x5, x6, x7, a1, a2")
output = fix_unused_and_missing_imports(input, db=db)
expected = PythonBlock(dedent('''
from m1 import X9
from m2 import a1, x2, x3, x6, x7
d... | |
<reponame>ivanmm25/FLYCOPtools
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 25 11:52:44 2021
@author: <NAME>
"""
"""
DESCRIPTION (see detailed description in each plotting function)
Plotting script for Input & Output Analysis in:
- InputParametersAnalysis.py
- OutputParametersAnalysis.py
... | |
thread responsible for calling this
self.start()
def run(self):
logger = logging.getLogger(__name__+".RetrieveTwitterDatasetThread.run")
logger.info("Starting")
status_flag = True
dataset_source = "Twitter"
retrieval_details = {
'query': self.query,
'start_date': self.start_date,
'end_date': self.end_date,
... | |
<filename>openquake/risklib/riskmodels.py<gh_stars>1-10
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2013-2018 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the... | |
# Copyright 2001-2007 by <NAME>. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permissio... | |
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class LISPMapRequest(Base):
__slots__ = ()
_SDM_NAME = 'lISPMapRequest'
_SDM_ATT_MAP = {
'HeaderType': 'lISPMapRequest.header.type-1',
'HeaderA': 'lISPMapRequest.header.a-2',
'HeaderM': 'lISPMapRequest.header.M-3',
'HeaderP': 'lISP... | |
#!/usr/bin/env python
# coding: utf-8
import time
import atexit
import weakref
import pybullet
import threading
from qibullet.tools import *
from qibullet.controller import Controller
class BaseController(Controller):
"""
Class describing a robot base controller
"""
# _instances = set()
FRAME_WORLD = 1
FRAME_... | |
<filename>tasty.py
from position import PositionType
import pandas as pd
from history import History
from transaction import Transaction
import math
from money import Money
from typing import List
import logging
from pathlib import Path
import pprint
from dataclasses import dataclass
from dataclasses_json import datacl... | |
sample and this is known.
outfile = open(fasta_out, 'w')
iter_fst = util.iter_fst
seq_counter = 0
for record in iter_fst(fasta_in):
sid = record[0][1:] # id
seq = record[1] # sequence
record[0] = '>' + sampleID + '_' + str(seq_counter)
outfile.write('\n'.join(record) + '\n')
seq_counter += 1
outfile.close()
... | |
return
def adsorbate_placement(system, molecule_file, ads_vector):
coords, coords2, atom_type, ads_frac, com_frac, mol_com_rotated = [], [], [], [], [], []
# Read a pre-defined molecule file
mol = Molecule.from_file(molecule_file)
com_xyz = mol.center_of_mass # get CoM in cartesian
diff_com_ads_vector = np.arra... | |
type: (...) -> Iterable["models.CollectionOfProfilePhoto"]
"""Get photos from users.
Get photos from users.
:param user_id: key: id of user.
:type user_id: str
:param orderby: Order items by property values.
:type orderby: list[str or ~users.models.Enum93]
:param select: Select properties to be returned.
:typ... | |
<filename>src/mushme.py<gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from src import app
import os
import shutil
from flask import Flask, render_template, session, request, flash, url_for, redirect
from Forms import ContactForm, LoginForm, editForm, ReportForm, CommentForm, searchForm, AddPlaylist
from f... | |
<gh_stars>0
#!/usr/bin/env python
'''
log analysis program
<NAME> December 2014
'''
import sys, struct, time, os, datetime
import math, re
import Queue
import fnmatch
import threading, multiprocessing
from math import *
from MAVProxy.modules.lib import rline
from MAVProxy.modules.lib import wxconsole
from MAVProxy.mod... | |
<reponame>jormono/Vinyl_Inventory
#! python3
from PyQt5 import QtCore, QtGui, QtWidgets
import sqlite3
# TODO: Error Handling on integer inputs
conn = sqlite3.connect('vinyl_inventory.db')
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS vinyl(id INTEGER, rack INTEGER, shelf INTEGER, box INTEGER, album... | |
<filename>generate-grammars/grammar_to_ply.py
#!/usr/bin/env python
# Written by <NAME>
# Copyright (c) 2008 by Dalke Scientific, AB
# Modified by <NAME>, 2016
#
# (This is the MIT License with the serial numbers scratched off and my
# name written in in crayon. I would prefer "share and enjoy" but
# apparently that ... | |
headers['Accept'] = 'application/vnd.quantized-mesh,application/octet-stream;q=0.9'
response = gHttpClient['tiles'].get(url.request_uri, headers)
if response and response.status_code == 200:
if '.terrain' in tilepath:
with gzip.GzipFile(fileobj=StringIO.StringIO(response.read())) as f1:
ret1 = f1.read()
if gIsSav... | |
__author__ = 'laiyu'
import logging
import json
from django.http import HttpResponse
from django.db import transaction
from django.db.models import Max
from django.db.models import Min
from django.db.models import F
from django.core import serializers
from django.template import loader
from website.models import Spri... | |
#
# Copyright The NOMAD Authors.
#
# This file is part of NOMAD. See https://nomad-lab.eu for further info.
#
# 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/... | |
common geno / total samples gives correctness when guessing most common for every sample
genotype_conc_per_marker = counts/n_samples
genotype_conc = np.average(genotype_conc_per_marker)
return genotype_conc
def get_pops_with_k(k, coords_by_pop):
'''
Get a list of unique populations that have at least k samples
... | |
<reponame>johnpaulguzman/py-gql<filename>tests/test_execution/test_coercion.py<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Tests related to how raw JSON variables are coerced and forwared to the
execution context.
"""
import json
import pytest
from py_gql.exc import VariablesCoercionError
from py_gql.schema import (
... | |
feed_dict=None,
hide_tqdm_progress=False):
"""
Evaluate the network.
The network evaluation method works by walking through the graph from all input nodes, along all possible paths.
The evaluation of each path is stopped as soon as the total path amplitude falls below the amplitude_cutoff limit.
:param amplitud... | |
<filename>TEST/main.py
"""
Simulator of NB-IoT cell at the MAC level.
In this simulator :
- Slotted Aloha contention
- 3 M/D/1-PS queues
- Impatience
- Ghost messages suppression
- User Plane optimization
"""
from enum import Enum
import math
import random
import time
# General Conf
id_max = 1000000
debug_ = Fal... | |
import csv
from pathlib import Path
import shutil
import itertools
from judge import Judge
from student import Student
from util import (
PresentationAssignmentError,
OutputVerificationError,
time_slot_to_time,
column_name_to_date,
date_and_time_to_index,
index_to_datetime,
index_to_datetime_str,
get_column_na... | |
<gh_stars>0
from enum import Enum
import time
from collections import defaultdict
from nltk.corpus import stopwords
from dataanalysis import nlp_utils as nlp
from ontomatch import glove_api
from ontomatch import ss_utils as SS
from datasketch import MinHash, MinHashLSH
from knowledgerepr.networkbuilder import LSHRandom... | |
import os
from sqlalchemy import Column, Integer, String, DateTime, Float
from sqlalchemy.orm import declared_attr
from sqlalchemy.sql.expression import func
from {{appname}}.database.sqldblib import engine,session
from {{appname}}.lib.powlib import pluralize
import datetime
import uuid
from sqlalchemy import orm
impo... | |
character control")
return
#Remove existing driven attrs
cmds.aliasAttr(character + "spine_04_anim.driven", rm=True )
attrs = cmds.listAttr(character + "spine_04_anim", keyable = True)
for attr in attrs:
if attr.find("blend") == 0:
cmds.deleteAttr(character + "spine_04_anim", at = attr)
... | |
,
u'縰' : [u'x'] ,
u'媳' : [u'x'] ,
u'莹' : [u'y'] ,
u'噀' : [u'x'] ,
u'㳇' : [u'f'] ,
u'齆' : [u'w'] ,
u'旍' : [u'j'] ,
u'乐' : [u'y', u'l'] ,
u'煚' : [u'j'] ,
u'川' : [u'c'] ,
u'苣' : [u'q', u'j'] ,
u'楪' : [u'y', u'd'] ,
u'㿱' : [u'x'] ,
u'鹰' : [u'y'] ,
u'擷' : [u'x'] ,
u'䅺' : [u'm'] ,
u'霁' : [u'j'] ,
u'炄' : [u'n'] ,
u'輑' : [u'y'... | |
<filename>tools/MethylSig/rpy2/rpy/rinterface/tests/test_SexpVector.py
import unittest
import sys, struct
import rpy2.rinterface as ri
ri.initr()
def evalr(string):
res = ri.parse(string)
res = ri.baseenv["eval"](res)
return res
def floatEqual(x, y, epsilon = 0.00000001):
return abs(x - y) < epsilon
IS_PYTHON3 =... | |
else:
print("You just entered " + SAVE_dict['CurrentTownName'] + ". The next 3 turns are SAFE")
blockType_Safe()
if SAVE_dict['InTown'] == 1 and CONT2_dict['TravelledCONT2'] == 1: # --------------------------------------------- S E C O N D . C O N T I N E N T . N A M E S . -------------------------------------------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.