input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<reponame>picca/fabio
# coding: utf-8
#
# Project: X-ray image reader
# https://github.com/silx-kit/fabio
#
#
# Copyright (C) European Synchrotron Radiation Facility, Grenoble, France
#
# Principal author: <NAME> (<EMAIL>)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of ... | |
self.__using_bundles[bundle].dec():
# This bundle has cleaner all of its usages of this
# reference
del self.__using_bundles[bundle]
except KeyError:
# Ignore error
pass
def used_by(self, bundle):
"""
Indicates that this reference is being used by the given bundle.
This method should only be used by the fram... | |
<reponame>oeljeklaus-you/ParallelTripleBit<gh_stars>0
load complete!
>>>queryLUBM5
>>>tripleID 0 selectivity : 3199424
tripleID 1 selectivity : 5001
tripleID 2 selectivity : 99987
tripleID 3 selectivity : 104426368
tripleID 4 selectivity : 12596397
tripleID 5 selectivity : 32390686
TripleNodeID: 1 Selectivity: 5001
Tri... | |
form binocular map from fusing left and right retinal maps across depths
def binoc_fuse(self, y, x, size):
out = self.cfns.binoc_fuse(y, x, size)
return out
# filter binocular map with nearest neighbor kernel
def binoc_map_trans(self, map, size):
pre_out = self.cfns.binoc_map(map, size)
post_out = 8 * self.thre... | |
<reponame>computationalcore/gameobjects
from math import *
from util import format_number
class ColorRGBA(object):
__slots__ = ('_c',)
def __init__(self, *args):
"""Creates a color object."""
if not args:
self._c = [0.0, 0.0, 0.0, 1.0]
return
if len(args) == 1:
args = args[0]
... | |
"""NAPALM Alcatel-Lucent AOS Handler."""
# Copyright 2017. All rights reserved.
#
# The contents of this file are 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/license... | |
<filename>src/finn/builder/build_dataflow_steps.py
# Copyright (c) 2020 Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copy... | |
<gh_stars>0
# -*- coding: utf-8 -*-
# FOGLAMP_BEGIN
# See: http://foglamp.readthedocs.io/
# FOGLAMP_END
""" The OMF North is a plugin output formatter for the FogLAMP appliance.
It is loaded by the send process (see The FogLAMP Sending Process) and runs in the context of the send process,
to send the reading data to ... | |
on
either side of operator
Parameters
----------
other : scalar,numpy.ndarray,Matrix object
the thing for element-wise multiplication
Returns
-------
Matrix : Matrix
"""
if np.isscalar(other):
return type(self)(x=self.x * other)
if isinstance(other, np.ndarray):
assert self.shape == other.shape, \
"Mat... | |
such as FeC0.00001) the composition will be truncated (to Fe
in this example). In such extreme cases, the truncation likely reflects the
true physics of the situation (i.e. that the dilute element does not
significantly contribute orbital character to the band structure), but the
user should be aware of this behavi... | |
import os
import pickle
from pathlib import Path
from joblib import load
import numpy as np
from scipy.ndimage import center_of_mass
from scipy.interpolate import splev
import skimage.io
from .segmentation import (
segment_cellpose,
tracking,
segment_farid,
contour_spline,
segment_conv_paint
)
from .displacementes... | |
(R_values[25] / (1 + w * 1j * t_values[25]))
+ (R_values[26] / (1 + w * 1j * t_values[26]))
+ (R_values[27] / (1 + w * 1j * t_values[27]))
+ (R_values[28] / (1 + w * 1j * t_values[28]))
+ (R_values[29] / (1 + w * 1j * t_values[29]))
)
def KK_RC31(w, Rs, R_values, t_values):
"""
Kramers-Kronig Function: -RC-
... | |
# -*- coding: utf-8 -*-
'''
Created on 2017-07-18
@author: <NAME>
'''
from __future__ import absolute_import
import logging
import os #for filelist
from datetime import datetime #for filelist
from System import DBNull, Array #for list of cond format
import bkt
import bkt.library.excel.helpers as xllib
import bkt.li... | |
78 - 78: OoOoOO00
if 16 - 16: I1Ii111 % OoO0O00 - OoO0O00 % OoOoOO00 * OoO0O00
def lisp_mac_input ( packet ) :
return ( packet )
if 36 - 36: OoOoOO00 * II111iiii . OoooooooOO * I11i . I11i
if 13 - 13: I1ii11iIi11i * II111iiii
if 93 - 93: OOooOOo / O0 - o0oOOo0O0Ooo + OoO0O00 * I1IiiI
if 53 - 53: I1ii11iIi11i
if ... | |
<filename>tests/brython_jinja2/test_expression.py
from unittest.mock import patch
from pytest import raises
from tests.utils import TObserver
import brython_jinja2.expression as exp
from brython_jinja2.context import Context, Immutable
def test_parse_number():
assert exp.parse_number(" 123.5.6", 1) == (123.5, 6)
a... | |
<reponame>experiortec/dxm-toolkit<filename>dxm/lib/DxRuleset/rule_worker.py<gh_stars>1-10
#
# 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... | |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================
"""
Unit tests for reshaping operations.
"""
from __future__ import division
impor... | |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
depends_on = (
("django_prbac", "0001_initial"),
)
def forwards(self, orm):
# Adding model 'Invoice'
db.create_table(u'accounting_invoice', (
(u'id', ... | |
None:
return 1
elif 'number_of_folds' in data_params:
number_of_folds = int(data_params['number_of_folds'])
if number_of_folds < 1:
raise exceptions.InvalidArgumentValueError("Number of folds cannot be less than 1, but it is {number_of_folds}.".format(number_of_folds=number_of_folds))
return number_of_folds
else... | |
totalOffset*.75
#totalOffset *= 0.95
positioningOffset = offset_min
#print(offset_min)
shotOffset = carOffset + ballOffset
#ballOffset -= clamp(35, 0, targetVec[2] - 92.5)
# futurePos = agent.me.location + agent.me.velocity.scale(agent.ballDelay)
futurePos = agent.me.location + agent.me.velocity.scale(
agent.... | |
<gh_stars>0
#!/usr/bin python3
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (... | |
value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
ListenerRuleHttpHeaderConfig.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
ListenerRuleHttpHeaderConfig.__key_warning(key)
return super().get(key, default)
def __in... | |
break
frame = ID3v2Frame(file, self.major_version)
if frame.padding:
file.seek(self.header_size)
break
self.frames = self.frames + [frame]
self.tags[frame.name] = frame.data
_bitrates = [
[ # MPEG-2 & 2.5
[0,32,48,56, 64, 80, 96,112,128,144,160,176,192,224,256,None], # Layer 1
[0, 8,16,24, 32, 40... | |
<gh_stars>0
import numpy as np
import uuid
from qcodes.instrument.channel import InstrumentChannel, ChannelList
from qcodes.instrument.visa import VisaInstrument
from pyvisa.errors import VisaIOError
from qcodes.utils import validators
from typing import Any, NewType, Sequence, List, Dict, Tuple, Optional
from packagin... | |
import argparse
import filecmp
import logging
import os.path
import unittest
import sys
from distutils import spawn
from functools import lru_cache
from pathlib import Path
from subprocess import run
from unittest.mock import Mock
from unittest_expander import foreach, expand
from py2many.cli import (
_create_cmd,
... | |
<gh_stars>100-1000
from ctypes import *
from .pmat_blasfeo_wrapper import *
from .pvec import *
from .blasfeo_wrapper import *
from multipledispatch import dispatch
from abc import ABC
class pmat_(ABC):
pass
class pmat(pmat_):
blasfeo_dmat = None
def __init__(self, m: int, n: int):
self.blasfeo_dmat = c_pmt_crea... | |
"""
Elementwise division using AMEN
@author: ion
"""
import torch as tn
import numpy as np
import datetime
from torchtt._decomposition import QR, SVD, rl_orthogonal, lr_orthogonal
from torchtt._iterative_solvers import BiCGSTAB_reset, gmres_restart
import opt_einsum as oe
def local_product(Phi_right, Phi_left, coreA,... | |
<gh_stars>100-1000
import logging
import os
import random
import unicodedata
from datetime import datetime
from functools import partial
from importlib import import_module
from inspect import isclass
from io import BytesIO
import exifread
from django.conf import settings
from django.contrib.sites.models import Site
f... | |
= toGuess[:4] + "r" + toGuess[5:]
if word[1] != "R" and word[1] != "r" and word[2] != "R" and word[2] != "r" and word[3] != "R" and word[3] != "r" and word[4] != "R" and word[4] != "r" :
print("\nWrong!\n")
numberOfErrors = numberOfErrors + 1
wrongChars = wrongChars + "r" + ", "
if guessChar == "S" or ... | |
<gh_stars>0
import logging
import os
import random
import shlex
import sys
import traceback
from typing import TYPE_CHECKING, Any, Callable, Iterable, List, Optional, TextIO, Union, cast
import click
import numpy as np
from pkg_resources import iter_entry_points
import vpype as vp
from .decorators import global_proc... | |
<reponame>jfahlen/isofit<filename>examples/py-hypertrace/hypertrace.py
#!/usr/bin/env python3
#
# Authors: <NAME>
import copy
import pathlib
import json
import shutil
import logging
import numpy as np
import spectral as sp
from scipy.io import loadmat
from scipy.interpolate import interp1d
from isofit.core.isofit im... | |
@closeUnadjusted.setter
def closeUnadjusted(self, value: dict):
self.__closeUnadjusted = value
self._property_changed('closeUnadjusted')
@property
def valueUnit(self) -> dict:
return self.__valueUnit
@valueUnit.setter
def valueUnit(self, value: dict):
self.__valueUnit = value
self._property_changed('valueU... | |
<filename>coherence/web/ui.py
# -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2018, <NAME> <<EMAIL>>
'''
WebUI
=====
The :class:`WebUI` is used to enable an html interface where the user can
browse the devices content via web browser. By default,... | |
import random
import zipfile
import itertools
import operator
import csv
from datetime import datetime
import random
import sys
import nltk
import numpy as np
nltk.download('punkt')
vocabulary_size = 8000
unknown_token = "<PASSWORD>"
sentence_start_token = "<PASSWORD>"
sentence_end_token = "<PASSWORD>"
# Read the dat... | |
<reponame>jlk/qualys-cs-python-client
# coding: utf-8
"""
Container Security APIs
All features of the Container Security are available through REST APIs.<br/>Access support information at www.qualys.com/support/<br/><br/><b>Permissions:</b><br/>User must have the Container module enabled<br/>User must have API ACCE... | |
the intervals of continuity <S>.
:param C:
:type C: Adaptor2d_Curve2d &
:param T:
:type T: TColStd_Array1OfReal &
:param S:
:type S: GeomAbs_Shape
:rtype: void
"""
return _Extrema.Extrema_Curve2dTool_Intervals(*args)
Intervals = staticmethod(Intervals)
def IsClosed(*args):
"""
:param C:
:type C: Adapto... | |
= self.destroy_user_with_http_info(id, **kwargs) # noqa: E501
return data
def destroy_user_with_http_info(self, id, **kwargs): # noqa: E501
"""destroy_user # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.dest... | |
<filename>estados/migrations/0001_initial.py
# Generated by Django 3.0.6 on 2021-01-18 20:11
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Aguascalientes',
fields=[
('id', models.AutoField(auto... | |
<reponame>a1600012888/mmdetection3d
import copy
import cv2
import numpy as np
import torch
from matplotlib import pyplot as plt
try:
import open3d as o3d
from open3d import geometry
except ImportError:
raise ImportError(
'Please run "pip install open3d" to install open3d first.')
def _draw_points(points,
vis,
... | |
files1, corrected_group, basecall_subgroups)
raw_read_coverage2 = nh.parse_fast5s(
files2, corrected_group, basecall_subgroups)
raw_read_coverage1 = nh.filter_reads(raw_read_coverage1, obs_filter)
raw_read_coverage2 = nh.filter_reads(raw_read_coverage2, obs_filter)
if calc_stats:
if VERBOSE: sys.stderr.write('Ca... | |
redistributed redistributes redistributing
redistribution redo redoes redoing redone redraft redraw redress
redressed redresses redressing reds redundancies reed reeds reef
reefed reefing reefs reek reeked reeking reeks reel reelect reelected
reelecting reelects reeled reeling reels referee refereed refereeing
referees... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2017,2018,2019 <NAME> (http://www.jdhp.org)
# 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 wit... | |
import json
import bz2
from systemtools.basics import *
from systemtools.location import *
from systemtools.duration import *
from systemtools.file import *
from enum import Enum
import numpy as np
def ndarrayToList(*args, **kwargs):
return ndarray2list(*args, **kwargs)
def ndarray2list(data):
data = list(data)
fo... | |
"""
__author__: satheesh.k
Created: Wednesday, 2nd December 2020 4:29:37 pm
"""
from pathlib import Path
import pandas as pd
import numpy as np
from tabulate import tabulate
from random import shuffle
from joblib import Parallel, delayed
from typing import Optional, Tuple
from PIL import Image
import json
import xml.e... | |
self.lex.define(noun, 'child1')
self.assertFalse(child1.is_a_noun(recursion=0))
self.assertTrue(child1.is_a_noun(recursion=1))
self.assertTrue(child1.is_a_noun(recursion=2))
self.assertTrue(child1.is_a_noun(recursion=3))
child2 = self.lex.define(child1, 'child2')
self.assertFalse(child2.is_a_noun(recursion=0))
... | |
[name_btn, self.float117, units_btn, description_btn]
box121 = Box(children=row, layout=box_layout)
name_btn = Button(description='apoptosis_hill_power', disabled=True, layout=name_button_layout)
name_btn.style.button_color = 'tan'
self.float118 = FloatText(value='1', step='0.1', style=style, layout=widget_layout... | |
<gh_stars>0
"""Convenience functions related to Hail."""
import asyncio
import inspect
import os
import pathlib
import textwrap
from typing import Optional, Union, List
from abc import ABC, abstractmethod
import hail as hl
import hailtop.batch as hb
from cloudpathlib import CloudPath
from cloudpathlib.anypath import ... | |
from typing import Union
from typing_extensions import Self
from mesa.space import Coordinate
import networkx as nx
import numpy as np
import typing
from enum import IntEnum
from mesa import Agent
from copy import deepcopy
from fire_evacuation.utils import get_random_id
def get_line(start, end):
"""
Implementaiton... | |
<filename>trestle/core/profile_resolver.py
# Copyright (c) 2021 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
#
# https://www.apache.org/licenses/LICENSE-2.0
... | |
# Copyright (c) 2016 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... | |
m.x316 + m.x321 + m.x322 + m.x386 + m.x391 + m.x392 <= 12)
m.c4357 = Constraint(expr= 12*m.b108 + 12*m.b111 + 12*m.b112 - m.x220 - m.x223 - m.x224 + m.x290 + m.x293 + m.x294
+ m.x304 + m.x307 + m.x308 + m.x318 + m.x321 + m.x322 + m.x388 + m.x391 + m.x392 <= 12)
m.c4358 = Constraint(expr= 12*m.b72 + 12*m.b75 - m.x184... | |
<reponame>Rod-Persky/pyIGES<filename>pyiges/IGESGeomLib.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
.. module:: IGES.IGESGeomLib
:platform: Agnostic, Windows
:synopsis: Main GUI program
.. requires math (pi)
.. Created on Sun Mar 31 16:57:00 2013
.. codeauthor:: <NAME> <rodney.persky {removethis} AT gmail... | |
#!/usr/bin/python3
# Polyglot Node Server for EnvisaLink EVL 3/4 Device (DSC)
import sys
import envisalinktpi as EVL
import polyinterface
# TODO: Test Fire zone and reporitng functionality
# TODO: Add heartbeat from nodeserver
# TODO: Add shortcut arming (with #)
# TODO: Process CID events for more information
# con... | |
import json
import time
import unittest
import urllib.request, urllib.parse, urllib.error
import testconstants
from TestInput import TestInputSingleton
from community.community_base import CommunityBaseTest
from community.community_base import CommunityXDCRBaseTest
from memcached.helper.data_helper import MemcachedCli... | |
<filename>xymodel/xymodel.py
"""
Module for partition function estimation of square lattice XY model
with free boundary conditions using Monte Carlo methods.
Focus is Sequential Monte Carlo (SMC) methods.
Current supported methods:
Sequential Monte Carlo methods for graphical models
-- Naesseth et. al. 2014
Annealed... | |
"""JSON implementations of commenting managers."""
# pylint: disable=no-init
# Numerous classes don't require __init__.
# pylint: disable=too-many-public-methods,too-few-public-methods
# Number of methods are defined in specification
# pylint: disable=protected-access
# Access to protected methods allowed in package j... | |
"""Tests for clover.data_ingest.parsing.parsers.table_structures"""
# pylint: disable=too-many-lines
import copy
import pytest
import sqlalchemy as sa
import sqlalchemy.dialects.postgresql as sa_pg
import sqlalchemy.sql.elements as sa_elements
import sqlalchemy.sql.functions as sa_func
from yalchemy import table_stru... | |
# The MIT License (MIT)
# Copyright (c) 2014 Microsoft Corporation
# 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... | |
filter bins to user specifications
bin_indices = []
for filter_bin in filter_bins[i]:
bin_index = filter.get_bin_index(filter_bin)
if filter_type in ['energy', 'energyout']:
bin_indices.extend([bin_index, bin_index+1])
elif filter_type == 'distribcell':
indices = [(bin,) for bin in range(filter.num_bins)]
bin_... | |
+ 2*g*(-4 + b*(-2 + (2 + b)*g + Sqrt(16 + (2 + b)**2*g**2)))))))/(2.*Sqrt(-(g**3*(2 + g)*(5*(6 + b) + (1 + b)*(8 + 3*b)*g)))))
M5 = Sqrt(-1 + 1.8*g)
print M2
fig = plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(121, projection='3d')
ax2 = fig.add_subplot(122)
# get plane intersection idx
g_int_p... | |
<reponame>descarteslabs/descarteslabs-python<filename>descarteslabs/workflows/types/function/function.py<gh_stars>100-1000
import typing
import keyword
from inspect import signature, Signature, Parameter
from descarteslabs.common.graft import client
from ...cereal import serializable
from ..core import (
Proxytype,... | |
<reponame>GAIPS/OpenMDP<filename>openmdp/PartiallyObservableMarkovDecisionProcess.py
import numpy as np
from typing import Sequence, Optional
import yaaf
from yaaf import ndarray_index_from
from openmdp import MarkovDecisionProcess
from openmdp.utils import normalize
class PartiallyObservableMarkovDecisionProcess(M... | |
# -*- coding: utf-8 -*-
'''
Execution module for `ciscoconfparse <http://www.pennington.net/py/ciscoconfparse/index.html>`_
.. versionadded:: 2019.2.0
This module can be used for basic configuration parsing, audit or validation
for a variety of network platforms having Cisco IOS style configuration (one
space indenta... | |
<filename>hhpy/ds.py<gh_stars>0
"""
hhpy.ds.py
~~~~~~~~~~
Contains DataScience functions extending on pandas and sklearn
"""
# ---- imports
# --- standard imports
import numpy as np
import pandas as pd
import warnings
import os
# --- third party imports
from copy import deepcopy
from scipy import stats, signal
from ... | |
from typing import Optional
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Parameter, ReLU
from torch_scatter import scatter_add
from torch_sparse import SparseTensor
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.dense.linear import Linear
from ... | |
npoint, nsample, mlp[-1])
new_points = tf.reduce_sum(new_points, axis=2, keep_dims=True)
elif pooling=='max_and_avg':
max_points = tf.reduce_max(new_points, axis=[2], keep_dims=True, name='maxpool')
avg_points = tf.reduce_mean(new_points, axis=[2], keep_dims=True, name='avgpool')
new_points = tf.concat([avg_points... | |
<filename>complex/complex/client.py
from __future__ import absolute_import
import json
import logging
import os
import sys
from brewtils.decorators import command, system, parameter
from .model import MyModel, MyNestedModel, MyListModel, MyModelWithDefaults
@system
class ComplexClient:
"""Plugin that shows all the... | |
<gh_stars>1-10
#!/usr/bin/env python3
"""
Contains the GraphManager class. For the command line utility that makes use of it, see graph_manager_user.py. The
graph_optimization_analysis.ipynb notebook also makes use of this class.
"""
from __future__ import annotations
import json
from typing import *
import matplotl... | |
<filename>homework3.py<gh_stars>0
from __future__ import print_function, division
from collections import deque
import math
import sys
import time
import pickle
BOARD_SIZE = 16
INPUT_FILE = './input6.txt'
INFINITY = sys.maxsize
NEGATIVE_INFINITY = -1*sys.maxsize
DIRECTIONS = [(1, 1), (1, -1), (1, 0), (0, 1), (0, -1), (... | |
<gh_stars>0
import argparse
import csv
import json
import os
from datetime import datetime
from io import StringIO
import pytz
from core_data_modules.cleaners import Codes, PhoneCleaner
from core_data_modules.cleaners.cleaning_utils import CleaningUtils
from core_data_modules.logging import Logger
from core_data_modul... | |
#!/usr/bin/env python2
import os
import StringIO
import shutil
from itertools import izip_longest
from Tkinter import *
from PIL import Image
import tkFileDialog
import tkMessageBox
class Application(object):
def __init__(self, master):
self.master = master
self.master.title("CurseCreator")
# Variables
self.... | |
<reponame>NMTHydro/Recharge
# ===============================================================================
# Copyright 2018 gabe-parrish
#
# 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
#
#... | |
angle detected for each
'look' of the opening angle method. The 'sea' region is the convex
hull which envelops the shoreline as well as the delta interior.
"""
Sx, Sy = np.gradient(below_mask)
G = np.sqrt((Sx*Sx) + (Sy*Sy))
# threshold the gradient to produce edges
edges = np.logical_and((G > 0), (below_mask >... | |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Open Source Robotics Foundation, Inc.
# Copyright (c) 2013, <NAME>, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# *... | |
success:
jsonResult = the_result
# filter out references if present
if jsonResult != None:
if "reference" in jsonResult:
del jsonResult["reference"]
return jsonResult
def unpaywalling_doi(self, doi):
"""
Check the Open Access availability of the DOI via Unpaywall, return the best download URL or None otherw... | |
<gh_stars>1-10
import glob
import math
import os
import pickle as pkl
import random
import shutil
import datetime
from collections import deque
from hashlib import sha1
from os.path import join, isfile
import cv2
import numpy as np
import tensorflow as tf
from matplotlib import pyplot as plt
import networkx as nx
fr... | |
power.
WMOD = 0 by default.
WPF: Power factor used in calculating reactive power limits or output when WMOD is 2 or 3.
WPF = 1.0 by default.
Args:
data:
version:
"""
self.I = 0
self.ID = 0
self.PG = 0
self.QG = 0
self.QT = 0
self.QB = 0
self.VS = 0
self.IREG = 0
self.MBASE = 0
self.ZR = 0
self.ZX = 0... | |
<filename>backend/src/gloader/gserver.py
#!/usr/bin/python
from PyQt4 import QtNetwork, QtCore
from TaskManager import *
import os, sys, readline, time, subprocess, signal
version = "1.0"
GL_PROG = "gloader"
basedatadir = os.environ["GINI_HOME"] + "/data"
datadir = basedatadir
recovery = False
server = None
shell = N... | |
'St. Louis', 'state': 'Missouri'},
{'city': 'St. Louis Park', 'state': 'Minnesota'},
{'city': 'St. Martin', 'state': 'Mississippi'},
{'city': 'St. Martinville', 'state': 'Louisiana'},
{'city': 'St. Marys', 'state': 'Georgia'},
{'city': 'St. Marys', 'state': 'Pennsylvania'},
{'city': 'St. Marys', 'state': 'Ohio'},... | |
# -*- coding: utf-8 -*-
# CCP in Tomographic Imaging (CCPi) Core Imaging Library (CIL).
# Copyright 2017 UKRI-STFC
# Copyright 2017 University of Manchester
# 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 t... | |
# Advent of Code 2020 Day 17
# https://adventofcode.com/2020/17
from copy import deepcopy
from typing import DefaultDict
DEBUG = False
class ConwayState:
STAY_ACTIVE_RULE = [2, 3]
BECOME_ACTIVE_RULE = [3]
def __init__(self, filename):
with open(filename) as f:
initial_state_xy = [line.rstrip() for line in f... | |
<filename>code/ARAX/test/test_ARAX_workflows.py
#!/usr/bin/env python3
# Intended to test our more complicated workflows
import sys
import os
import pytest
from collections import Counter
import copy
import json
import ast
from typing import List, Union
import numpy as np
sys.path.append(os.path.dirname(os.path.abs... | |
<reponame>jrmh96/algorithm_toolkit
import json
import os
import re
import shutil
import subprocess
import sys
import unittest
import warnings
from logging import StreamHandler
from flask_testing import TestCase
from wtforms.fields import core as wtfields
from wtforms import widgets as wtwidgets
from wtforms.validato... | |
<filename>tools/peach-apport/apport/crashdb_impl/memory.py
# coding=utf-8
'''Simple in-memory CrashDatabase implementation, mainly useful for testing.'''
# Copyright (C) 2007 - 2009 Canonical Ltd.
# Author: <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms... | |
return int(round(random.gauss(self.mu, self.sigma)))
class RandNumExpo(RandField):
def __init__(self, lambd):
self.lambd = lambd
def _fix(self):
return int(round(random.expovariate(self.lambd)))
class RandByte(RandNum):
def __init__(self):
RandNum.__init__(self, 0, 2L**8-1)
class RandShort(RandNum):
def __ini... | |
path)
if not dir_id:
error_msg = 'Folder %s not found.' % path
return api_error(status.HTTP_404_NOT_FOUND, error_msg)
# permission check
permission = check_folder_permission(request, repo_id, path)
if not permission:
error_msg = 'Permission denied.'
return api_error(status.HTTP_403_FORBIDDEN, error_msg)
retu... | |
:param region: Region which this metric comes from. Default: - Deployment region.
:param statistic: What function to use for aggregating. Can be one of the following: - "Minimum" | "min" - "Maximum" | "max" - "Average" | "avg" - "Sum" | "sum" - "SampleCount | "n" - "pNN.NN" Default: Average
:param unit: Unit used to ... | |
USER_NAME)
self.owner_id = self.get_user_id_from_email(self.OWNER_EMAIL)
self.user_id = self.get_user_id_from_email(USER_EMAIL)
rubrics = [
skill_domain.Rubric(
constants.SKILL_DIFFICULTIES[0], ['Explanation 1']),
skill_domain.Rubric(
constants.SKILL_DIFFICULTIES[1], ['Explanation 2']),
skill_domain.Rubric(
c... | |
<reponame>thomaslu2000/Incremental-Parsing-Representations<filename>src/benepar/tetra_tag.py
import nltk
import numpy as np
## PUBLIC API
class TetraTagSequence(list):
"""A sequence of tetra-tags corresponding to a particular tree."""
default_ignore_labels = set(["TOP", "ROOT", "VROOT", "S1"])
@classmethod
de... | |
<filename>hsds/domain_sn.py
##############################################################################
# Copyright by The HDF Group. #
# All rights reserved. #
# #
# This file is part of HSDS (HDF5 Scalable Data Service), Libraries and #
# Utilities. The full HSDS copyright notice, including #
# terms governing use... | |
<filename>pyrt/aerosol.py
"""The :code:`aerosol` module contains structures to make the aerosol properties
required by DISORT.
"""
# TODO: add parameter validators if these classes are ok
import numpy as np
from pyrt.eos import _Altitude
from scipy.interpolate import interp2d
class Conrath:
r"""A structure to comput... | |
<filename>release/stubs.min/System/__init___parts/DateTime.py<gh_stars>100-1000
class DateTime(object,IComparable,IFormattable,IConvertible,ISerializable,IComparable[DateTime],IEquatable[DateTime]):
"""
Represents an instant in time,typically expressed as a date and time of day.
DateTime(ticks: Int64)
... | |
# TODO(colin): fix these lint errors (http://pep8.readthedocs.io/en/release-1.7.x/intro.html#error-codes)
# pep8-disable:E128
"""Linters that warn about common problems with jinja2 templates.
This category includes people using jinja2 functionality inside python
when they shouldn't -- the linters that keep the separat... | |
<reponame>quocvule/PointerSQL<gh_stars>100-1000
from __future__ import absolute_import
from __future__ import print_function
from model.pointer_net import *
from model.pointer_net_helper import *
from pprint import pprint
default_var_dict = {
"train_inputs": "graph/train_inputs:0",
"train_outputs": "graph/train_ou... | |
<reponame>kaspermunch/argweaver
#
# ARGweaver: Ancestral Recombination Graph sampling
#
# python libs
from collections import defaultdict
from contextlib import closing
import heapq
from itertools import chain
from math import exp, log
import random
import os
import subprocess
# add pre-bundled dependencies to the py... | |
#!/usr/local/bin/python3
import sys
import pickle
import argparse
import json
import numpy as np
from pathlib import Path
import SimpleITK as sitk
from cinemri.definitions import Patient, Study, CineMRISlice
from cinemri.utils import get_patients
from data_conversion import convert_2d_image_to_pseudo_3d
from vs_comput... | |
is above `zscore` threshold...')
max_len_i = np.round(max_len * sfreq).astype(int)
audio = abs((audio - np.median(audio)) / audio.std())
if zscore is None:
zscore = _get_audio_zscore(audio, sfreq)
candidates = np.where(audio > zscore)[0]
delete_indices = list()
for i, candidate in enumerate(candidates):
if any(... | |
== 10053 or e1.errno == 10054) and idx < 4:
idx += 1
print('encounter 10053 error, trying %d reconnecting...' % idx)
try:
if method == 'get':
response = client.get(url.request_uri, headers)
elif method == 'put':
response = client.put(url.request_uri, data, headers)
elif method == 'delete':
response = client.de... | |
the integration range of the intensity image as a string in nm and eV."""
int_lambda_min = self.spim.int_lambda_min[1]
int_lambda_max = self.spim.int_lambda_max[1]
title_pattern = 'Integration range : [{:.2f}, {:.2f}]nm | [{:.3f}, {:.3f}]eV'
title = title_pattern.format(
int_lambda_min, int_lambda_max, fct.nm_eV(i... | |
# Copyright 2020-present <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, s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.