input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
# -*- coding: utf-8 -*-
from typing import Iterable, Union
import numpy as np
def retrieve_neighbours(v: int, graph: Iterable) -> np.ndarray:
r"""Retrieves the neighbours of `v`.
Args:
v:
graph:
"""
t = np.nonzero(graph[v] + 1)
# + 1 because the indexing of vertices starts from 0. So adding 1
# enables to g... | |
= Var(within=Reals,bounds=(0.01,100),initialize=1)
m.x1238 = Var(within=Reals,bounds=(0.01,100),initialize=1)
m.x1239 = Var(within=Reals,bounds=(0.01,100),initialize=1)
m.x1240 = Var(within=Reals,bounds=(0.01,100),initialize=1)
m.x1241 = Var(within=Reals,bounds=(0.01,100),initialize=1)
m.x1242 = Var(within=Reals,bounds... | |
many directories
# NumberOfRvaAndSizes says there are
#
# We assume a normally sized optional header, hence that we do
# a sizeof() instead of reading SizeOfOptionalHeader.
# Then we add a default number of directories times their size,
# if we go beyond that, we assume the number of directories
# is wrong and s... | |
self.start
class MainFrame(wx.Frame):
'''
Main Processing Window
'''
def __init__(self, parent, id_, title, farm_key='depth', reg_key='hand',
data={}):
wx.Frame.__init__(self, parent, id_, title)
self.Center()
self.farm_key = farm_key
self.reg_key = reg_key
self.data = data
if self.data:
found = 0
for k... | |
#!/usr/bin/env python3
'''
Wrapper for phase unwrapping
'''
import pathlib
import os
import time
import h5py
import journal
import numpy as np
from osgeo import gdal
import isce3
import isce3.unwrap.snaphu as snaphu
from nisar.workflows import h5_prep
from nisar.products.readers import SLC
from nisar.workflows.unwr... | |
y2**2)*tf.exp((-(y1 - y2)**2*t1**2 - (x1 - x2)**2*t2**2)/(2*t1**2*t2**2))*(x1 - x2)/(t1**2*t2**6)
k11 = tf.exp((-(y1 - y2)**2*t1**2 - (x1 - x2)**2*t2**2)/(2*t1**2*t2**2))*(3*t2**4 - 6*t2**2*y1**2 + 12*t2**2*y1*y2 - 6*t2**2*y2**2 + y1**4 - 4*y1**3*y2 + 6*y1**2*y2**2 - 4*y1*y2**3 + y2**4)/t2**8
k12 = -15*(y1 - y2)*tf... | |
"""Precipitation factor to apply to the original series."""
return self.mbmod.prcp_fac
@prcp_fac.setter
def prcp_fac(self, value):
"""Precipitation factor to apply to the original series."""
for attr_name in ['_lazy_interp_yr', '_lazy_interp_m']:
if hasattr(self, attr_name):
delattr(self, attr_name)
self.mbmod... | |
indexKey_regs = [params[2] + x for x in range(params[3])]
self._condJump(indexKey_regs, params[1])
def _op_IdxLT(self, params):
self._op_IdxCommon(params, '<')
def _op_IdxLE(self, params):
self._op_IdxCommon(params, '<=')
def _op_IdxGE(self, params):
self._op_IdxCommon(params, '>=')
def _op_IdxGT(self, params... | |
<reponame>NIRMAL1508/-Conductng_Election_In_Terminal-using-python
import pyttsx3
speaker = pyttsx3.init()
import sqlite3
from colorama import Fore , Back , Style
import matplotlib.pyplot as plt
conn = sqlite3.connect('ELECTION.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS Student_Panel (username tex... | |
+ selected_bssid + "_" + four_way_handshake_file_timestamp + "-01.log.csv")
if self.check_four_way_handshake_log_csv_file.is_file(): #Check "00:00:00:00:00:00_00000000-000000-01.log.csv" is really exist
subprocess.Popen("echo " + sudo_password + " | sudo -S rm " + current_path + "/handshake/" + selected_bssid + "_" +... | |
staticmethod(factory)
def hasContent_(self):
if (
):
return True
else:
return False
def export(self, outfile, level, namespace_='', name_='indRetif', namespacedef_='', pretty_print=True):
imported_ns_def_ = GenerateDSNamespaceDefs_.get('indRetif')
if imported_ns_def_ is not None:
namespacedef_ = imported_ns_... | |
#! /usr/bin/env python3
from math import sqrt, pow, atan2, pi
import pygame
# problem: decorate a saturnalia tree
# input:
# - tree:
# - base radius
# - height
# - limb positions
# - height
# - angle
# - number of ornaments
# given (height, angle) of limb
# compute (x, y, z) of limb tip
# compute polar coordinat... | |
survol: <%s>
SELECT ?subdirectory_name WHERE {
?url_directory_0 a survol:CIM_Directory .
?url_directory_1 a survol:CIM_Directory .
?url_directory_2 a survol:CIM_Directory .
?url_directory_3 a survol:CIM_Directory .
?url_directory_0 survol:CIM_DirectoryContainsFile ?url_directory_1 .
?url_directory_1 survol:CIM_D... | |
<reponame>takehuge/PYQUM
# Communicating with Benchtop TKAWG (Tektronix AWG)
from colorama import init, Fore, Back
init(autoreset=True) #to convert termcolor to wins color
from os.path import basename as bs
mdlname = bs(__file__).split('.')[0] # module's name e.g. PSG
import pyvisa as visa
from pyqum.instrument.logge... | |
0 and 30000. Defaults to `30000`.
:param pulumi.Input[bool] muted: Determines if any notifications will be sent out when a check fails and/or recovers. Possible values `true`, and `false`.
:param pulumi.Input[str] name: The name of the check.
:param pulumi.Input[pulumi.InputType['CheckRequestArgs']] request: . An AP... | |
<filename>videos/manimTutorial/part5_Coordinates.py
from manimlib.imports import *
from manim_sandbox.utils.imports import *
from manim_sandbox.videos.manimTutorial.utils import *
from manim_projects.tony_useful.imports import *
numberline_t2c = {
"NumberLine": BLUE_D,
"x_min": ORANGE,
"x_max": ORANGE,
"include_t... | |
spectrogram
:pplot: if True, plot spectrogram along with power band
:sptype: if sptype='fine' plot 'special' spectrogram, save under sp_fine_$name.mat;
otherwise plot 'normal' spectrogram sp_$name.mat
:filt_dim: list or tuple; the two values define the dimensions of box filter
used to filter the normalized spectr... | |
import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
import requests
from IPython.core.display import display, HTML
"""
Functions for gettig movie/director/actor info on IMDb.
1. get_movie_detail(soup)
2. get_movie_brief(soup)
"""
# get detailed data from individual movie webpage
def get_movie_detail... | |
from decimal import Decimal
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.utils import timezone
from rest_framework.views import APIView, status
from rest_framework.response import Response
from rest_framework import viewsets, mixins, decorators, generics
from rest_fram... | |
rp is None: # pragma: no cover
rp = {}
return rp
def __call__(self) -> Optional[Dict[str, Any]]:
"""
Execute a CloudFormation custom resource event.
"""
result = {"Status": "FAILED"} # type: Dict[str, Any]
try:
handler = self.request_type_handlers.get(self.request_type)
if not handler:
raise InvalidParamet... | |
<reponame>nightvision04/cellular-learn<gh_stars>0
import matplotlib.pyplot as plt
import numpy as np
import random
import time
import copy
from Genotype import JSONData
from CellularA import CellularA
import unittest
import Viewer
import math
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection i... | |
import logging
from dataclasses import dataclass
from typing import List, Optional, Union
import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...file_utils import ModelOutput
from ...modeling_outputs import (
MultipleChoiceModelOutput,
QuestionAnsweringModelOutpu... | |
<reponame>IsaacJordannn/Hasami-Shogi<filename>HasamiShogiGame.py
# Author: <NAME>
# Date: 12/2/21
# Description: A HasamiShogiGame class is created to represent the board game. When the class is initialized the private
# data members are defined and the function creating the board is called. There is an optional fun... | |
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Tests for ``admin.packaging``.
"""
from glob import glob
from subprocess import check_output
from textwrap import dedent
from unittest import skipIf
from StringIO import StringIO
from twisted.python.filepath import FilePath
from twisted.python.procutils... | |
<reponame>ashishdhngr/baserow
from __future__ import annotations
import csv
import os
import re
import random
import string
import hashlib
import math
from itertools import islice
from decimal import Decimal
from collections import namedtuple
from typing import List, Optional, Iterable
from django.db.models import F... | |
"""Add Deep Learning Indaba Application Form
Revision ID: 1c3fda18bad6
Revises: <PASSWORD>
Create Date: 2020-03-26 14:39:36.628724
"""
# revision identifiers, used by Alembic.
revision = '1c3fda18bad6'
down_revision = 'c3c5ef958ca1'
from alembic import op
import sqlalchemy as sa
from sqlalchemy import orm
from sql... | |
import datetime
import re
import vaping
import vaping.config
from vaping.plugins import PluginConfigSchema
import confu.schema
class FieldSchema(confu.schema.Schema):
parser = confu.schema.Str(
help="Regex pattern to parse field value, needs to one group in it"
)
type = confu.schema.Str(help="Value type (int, f... | |
cont_global_map_pred=None):
if self.params.start_with_spin and np.abs(self.accumulated_spin) < SPIN_TARGET and self.step_i < 40:
if self.spin_direction is None:
self.spin_direction = SPIN_DIRECTION * np.sign(target_fi) # spin opposite direction to the goal
self.accumulated_spin += ang_vel
# spin
status_message ... | |
example for what to pass via arg_callable_filter to
get_list_of_pairs_paths_and_node_children_relevant_to_object()
get_list_of_pairs_paths_and_node_children_relevant_to_object() interprets this method's returned value as boolean logic.
Any callable passed this way has the following requirements:
-Must accommodat... | |
<gh_stars>10-100
"""
pyrad.io.read_data_mxpol
========================
Functions for reading radar mxpol data files
.. autosummary::
:toctree: generated/
classes - MXPOL:
pyrad_MXPOL
classes - MCH:
pyrad_MCH
utilities - read:
row_stack
findTimes
int2float_radar
readMXPOLRadData
readCHRadData
utilities - con... | |
= model_fitter.make_gen(p_in['muS_N']-0.1, p_in['muS_N']+0.1)
fitter.priors['q'] = model_fitter.make_gen(p_in['q']-0.1, p_in['q']+0.1)
fitter.priors['sep'] = model_fitter.make_gen(p_in['sep']-0.1, p_in['sep']+0.1)
fitter.priors['alpha'] = model_fitter.make_gen(p_in['alpha']-0.1, p_in['alpha']+0.1)
fitter.priors['... | |
<filename>addons/bundle_exporter/modifiers/modifier_export_textures.py
import os
import bpy
import math
from . import modifier
import mathutils
file_formats_enum = {
'BMP': '.bmp',
'IRIS': '.sgi',
'PNG': '.png',
'JPEG': '.jpg',
'JPEG2000': '.jp2',
'TARGA': '.tga',
'TARGA_RAW': '.tga',
'CINEON': '.cin',
'DPX':... | |
spec
else:
specstr = str(level)
elif dimtype == 'elevel':
if elevel is None:
specstr = spec
else:
specstr = str(elevel)
return specstr
path = _specre.sub(retpath, template)
return path
# Search an object or list of objects for a string attribute which
# contains a pattern. If the object is a dataset, all o... | |
in the database are shown.'
'(Default:Do not show disabled users).')
@click.option('-o', '--order', type=str, default=None, metavar='FIELDNAME',
help='Sort by the defined field name. Names are viewed with the '
'targets fields subcommand or "-o ?" to interactively '
'select field for sort')
@click.option('-c', '--c... | |
<reponame>ifraixedes/saltstack-salt<filename>tests/unit/utils/test_ssdp.py
"""
:codeauthor: :email:`<NAME> <<EMAIL>>`
"""
import datetime
import salt.utils.ssdp as ssdp
import salt.utils.stringutils
from tests.support.mock import MagicMock, patch
from tests.support.unit import TestCase, skipIf
try:
import pytest
e... | |
'S82123G',
'S82123H',
'S82123J',
'S82123K',
'S82123M',
'S82123N',
'S82123P',
'S82123Q',
'S82123R',
'S82123S',
'S82124A',
'S82124B',
'S82124C',
'S82124D',
'S82124E',
'S82124F',
'S82124G',
'S82124H',
'S82124J',
'S82124K',
'S82124M',
'S82124N',
'S82124P',
'S82124Q',
'S82124R',
'S82124S',
'S82125A... | |
import numpy as np
from math import sqrt
import time
import multiprocessing
import copy
from functools import partial
from datetime import date
import matplotlib.pyplot as plt
import matplotlib
from ROAI_class import ROAI, RANDOM, RR, WRR
# this function is used to generate the instance
def generate_instance_bernoul... | |
#
# core.py: public Python interface for core components
#
# Subversion is a tool for revision control.
# See http://subversion.apache.org for more information.
#
######################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor lic... | |
<gh_stars>1-10
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); ... | |
<reponame>google-cloud-sdk-unofficial/google-cloud-sdk
# -*- coding: utf-8 -*- #
# Copyright 2013 Google LLC. 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://w... | |
<reponame>jp8042/oppia
# coding: utf-8
#
# Copyright 2014 The Oppia 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.... | |
<reponame>hacknaman/glStream
# Copyright (c) 2001, Stanford University
# All rights reserved.
#
# See the file LICENSE.txt for information on redistributing this software.
"""Chromium mothership functions
These functions are used in configuration files to direct the mothership.
Use these functions to describe your SP... | |
a
# successful auto-follow.
# Type: Int
c.hints.auto_follow_timeout = 0
# CSS border value for hints.
# Type: String
c.hints.border = '1px solid #E3BE23'
# Padding (in pixels) for hints.
# Type: Padding
c.hints.padding = {'bottom': 0, 'left': 3, 'right': 3, 'top': 0}
# Rounding radius (in pixels) for the edges of hi... | |
<reponame>OtonicarJan/resolwe<filename>resolwe/flow/tests/test_filtering.py
# pylint: disable=missing-docstring
import datetime
from django.contrib.auth import get_user_model
from django.utils.timezone import get_current_timezone
from rest_framework import status
from rest_framework.test import APIRequestFactory, for... | |
31 1.3923
nd-cc-os 114.1 116.74 CORR_SOURCE5 156 2.0183
nd-cc-sh 79.2 124.97 SOURCE4_SOURCE5 18 0.8493
nd-cc-ss 83.3 114.51 SOURCE3 8 0.3449
nd-cc-sx 76.8 127.74 SOURCE4_SOURCE5 33 0.6804
nd-cc-sy 79.3 123.03 SOURCE4_SOURCE5 33 1.1587
ne-cc-ss 81.7 117.03 SOURCE4_SOURCE5 17 0.2106
nh-cc-nh 111.7 115.96 SOURCE3 1
nh-cc-... | |
importo_totale = Money(str(importo_totale),"EUR")
importo_totale = importo_totale.format("it_IT").encode('ascii', 'ignore').decode('ascii')
fattura.footer(str(importo_totale)," "," "," "," ",str(importo_totale),str(return_currency(imposta_totale)))
fattura.totale(str(importo_totale_da_salvare))
lista_... | |
data = data.to(device)
optimizer = torch.optim.Adam(model.parameters(),lr=0.005,weight_decay=0.0005)
print(aggr, "开始训练")
t = StopEarly(2)
try:
for epoch in range(1, 501):
model.train()
optimizer.zero_grad()
out = model(data)
loss = None
if (node_norm != None):
loss = F.nll_loss((out[sample_mask]),data.y[samp... | |
"updateId": "BFA831DB0000000072B933040000000E",
"updateName": "北京发改委",
"updateDate": "2020-06-24",
"isSubmit": 1,
"stage": 3,
"isNewProject": 1
},
"projcectLnvestments": [
{
"id": "75214fdb-3c56-4497-9947-fa6c701b1024",
"projectId": "675e9449-0f82-46f3-886d-640acc55559d",
"tzdwmcName": "浪潮",
"btzdwmcName": ... | |
der DIO Gruppe kein Output ist (als Input)
:rtype: bool
'''
if (self.getDIOdirection(gruppe) == 0x00):
return True
else:
return False
def isDIOgroupInput(self, gruppe):
'''
gibt True zurueck, wenn die Direction der gewaehlten DIO Gruppe als Input konfiguriert ist.
:param gruppe: Muss die DIO G... | |
<gh_stars>0
from numpy import array
def scigrid_2011_01_06_11():
ppc = {"version": '2'}
ppc["baseMVA"] = 100.0
ppc["bus"] = array([
[586, 3, 0, 0, 0, 0, 0, 1.0, 0, 220.0, 0, 1.1, 0.9 ],
[589, 2, 0, 0, 0, 0, 0, 1.0, 0, 380.0, 0, 1.1, 0.9 ],
[590, 2, 0, 0, 0, 0, 0, 1.0, 0, 380.... | |
<reponame>PlumpMath/Panda3DCraft
from panda3d.core import *
from direct.gui.DirectGui import *
from direct.showbase.ShowBase import ShowBase
from noise import snoise2
import os
import random
from Block import *
loadPrcFile('config/general.prc')
if __debug__:
loadPrcFile('config/dev.prc')
base = ShowBase()
octavesE... | |
<filename>code/python/AITextSummarization/v1/fds/sdk/AITextSummarization/api/default_api.py
"""
AI Text Summarization
AI Text Summarization # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from multiprocessing... | |
(outroot, w)
dat = data[w, :, :]
pf.PrimaryHDU(dat, w2dhdr).writeto(outname, overwrite=True)
# -----------------------------------------------------------------------
def select_cube(self, wlim=None, xlim=None, ylim=None, wmode='slice',
dmode='input', verbose=False):
"""
Creates a cube to analyze, defined by r... | |
= {}
self.access = {}
self.access[c.COMPUTE] = []
self.access[c.STORAGE] = []
self.access[c.ANY] = []
self.conn, self.backend = self._adaptor.connect (session, url)
self.templates = []
self.images = []
# FIXME: we could pre-fetch existing resources right now...
# ------------------------------------------... | |
``NextToken`` from a previous response.
:rtype: dict
:returns:
"""
pass
class GetJobs(Paginator):
def paginate(self, PaginationConfig: Dict = None) -> Dict:
"""
Creates an iterator that will paginate through responses from :py:meth:`Glue.Client.get_jobs`.
See also: `AWS API Documentation <https://docs.aws.ama... | |
typ == 1: mess = 'ERROR: '
if typ == 2: mess = 'WARNING: '
if dontShow == 0: currentButtons = 'Ok'
if dontShow == 1: currentButtons = ['Ok', 'Dont show this again']
confirm = cmds.confirmDialog(t = obj.script_label + ' message', m = mess + main_text,
b = currentButtons, db = 'Ok',
... | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import ctypes # type: ignore
import typing # NOQA: F401
import warnings
from nixnet import _ctypedefs
from nixnet import _errors
from nixnet import _funcs
from nixnet import _props
from nixnet import _utils
fr... | |
# Copyright 2016-2018, Rigetti Computing
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
QuantumFlow representations of pure quantum states and actions on states.
.. contents:: :local:
State objects
#############
.... | |
"""
TODO:
* Move producer, consumer into their own files
* ZKUtil should be broken up into two pieces -- one with path info, the rest
to get folded into consumer and producer as necessary.
FIXME: Extract the logic for testing how the brokers get partitioned so we can
test them in simple unit tests without involving... | |
<reponame>NYPL-Simplified/metadata_wrangler<filename>controller.py
import base64 as stdlib_base64
from datetime import datetime
import flask
from flask import make_response
from flask_babel import lazy_gettext as _
from lxml import etree
from sqlalchemy import (
and_,
not_,
)
from sqlalchemy.orm import joinedload
fro... | |
<reponame>xsuite/xcol
import json
from pathlib import Path
import numpy as np
import xobjects as xo
import xpart as xp
import xcoll as xc
def test_horizontal_parallel():
for context in xo.context.get_test_contexts():
jaw_L, jaw_R, _, _, cox, _, L, coll = _make_absorber(_context=context)
part, x, _, _, _ = _genera... | |
<filename>lcls_live/klystron.py
from .devices import Device
from math import pi, cos
class Klystron(Device):
"""
Klystron
"""
def __init__(self, name=None,
sector=-1, station=-1,
faults_callback=None, triggers_callback=None,
epics=None,
verbose=False):
if sector > -1 and station > -1:
name = klystron_n... | |
base_dir="%(install_location)s"
%(indent1)s base_log_dir="%(factory_logs)s"
%(indent1)s base_client_log_dir="%(client_log_dir)s"
%(indent1)s base_client_proxies_dir="%(client_proxy_dir)s"/> """ % \
{ "indent1" : common.indent(1),
"install_location" : self.install_location(),
"factory_logs" : self.logs_dir(),
"cli... | |
ops.get_default_graph().get_tensor_by_name(constant_6_name)
b = constant_op.constant(5.0)
c = a * b
self.assertEqual(30.0, sess.run(c))
def testNoOverwrite(self):
export_dir = self._get_export_dir("test_no_overwrite")
builder = saved_model_builder.SavedModelBuilder(export_dir)
# Graph with a single variable. S... | |
import math
from .utils import build_mantissa
from .mantissa_operation import compare, mantissa_sum, mantissa_sub, mantissa_mul, mantissa_div
class FPANumber:
def __init__(self, base, exponent, mantissa, sign):
self._base = base
self._exponent = exponent
self._mantissa = mantissa
self._sign = sign
@classmetho... | |
# Copyright 2021 University College London. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | |
import pandas as pd
import copy
from pathlib import Path
import pickle
pd.set_option('display.max_colwidth', 100)
pd.options.display.max_rows = 999
from tqdm import tqdm
tqdm.pandas()
import numpy as np
import math
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib... | |
<gh_stars>1-10
"""Checkout-related utility functions."""
from datetime import date
from decimal import Decimal
from typing import Iterable, List, Optional, Tuple
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import Max, Min, Sum
from django.utils import time... | |
- U[iU][1]) * 1.0 / (U[iU + 1][0] - U[iU][0])
s = sU - sL
nxL = L[iL + 1][0]
nxU = U[iU + 1][0]
nx = min(nxL, nxU)
na = 2 * w * (nx - x) + s * (nx - x) * (nx - x)
if a + na >= part:
dx = (part - a) * 1.0 / (w + math.sqrt(w * w + (part - a) * s))
x += dx
a += 2 * w * dx + s * dx * dx
cuts.append(x)
w += s * d... | |
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify,... | |
import os
import sys
import gzip
import shutil
import base64
import logging
import optparse
import mimetypes
import subprocess
from tempfile import mkdtemp, mkstemp
try:
import cssutils
except ImportError:
cssutils = None
try:
from urllib.parse import urlparse
except ImportError:
#python 2
from urlparse import u... | |
<gh_stars>0
"""
The ``clearsky`` module contains several methods
to calculate clear sky GHI, DNI, and DHI.
"""
import os
from collections import OrderedDict
import calendar
import numpy as np
import pandas as pd
from pvlib import atmosphere, tools
def ineichen(apparent_zenith, airmass_absolute, linke_turbidity,
a... | |
<filename>contrib/rackspace/rackspace/tests/test_rackspace_cloud_server.py
# 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 ... | |
"""
module for review submit-review api tests
Copyright (c) 2018 Qualcomm Technologies, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the
limitations in the disclaimer below) provided that the following conditions are met:
... | |
<reponame>mmaltafe/Learning
import numpy as np
import pandas as pd
import scipy.stats as stats
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
import pickle
import SODA
import threading
from datetime import datetime
from psutil import cpu_percent, s... | |
<gh_stars>10-100
# Author-<NAME>
# Description-Directly publish to OctoPrint
# Referenced heavily from: https://github.com/boboman/Octonomous/blob/master/Octonomous.py
import adsk.core, traceback
import adsk.fusion
import tempfile
import json
import webbrowser
from .packages import requests
from .packages.requests_t... | |
<reponame>PiRAT4/py-pf<gh_stars>0
"""Mapping of C structs, required by ioctl() calls, to ctypes."""
from ctypes import *
from pf.constants import *
__all__ = ['timeval',
'pfioc_limit',
'pfioc_tm',
'pf_status',
'pf_addr_wrap',
'pf_rule_addr',
'pfsync_state_peer',
'pfsync_state_key',
'pfsync_state',
'pfioc_s... | |
<gh_stars>1-10
# Copyright 2015, Google 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 copyright
# notice, this list of condition... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2021 Tianmian Tech. 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/LICE... | |
a value for rxd:AmendmentNumber in the Required Context."),
modelObject=modelXbrl, documentType=documentType)
else:
modelXbrl.error("EFM.6.23.07",
_("The DTS must use a standard schema from Family RXD in edgartaxonomies.xml."),
modelObject=modelXbrl, instance=instanceName)
class Rxd(): # fake class of rxd qnames ... | |
<filename>src/botModerationCommands.py
# ---------------------------------------------------------------------
# IMPORTS
from discord.ext import commands
import discord
from botMethodsClass import BotMethods
# ---------------------------------------------------------------------
class BotModerationCommands(comma... | |
# Generated from Guarded.g4 by ANTLR 4.7.2
from antlr4 import *
if __name__ is not None and "." in __name__:
from .GuardedParser import GuardedParser
else:
from GuardedParser import GuardedParser
# This class defines a complete listener for a parse tree produced by GuardedParser.
class GuardedListener(ParseTreeListe... | |
G, B) color. Every item has to be an integer in range (0,255).
linear_scaling : bool, optional
Either if Linear or Log Scale will be used. Default is `True`.
label : str, optional
Y axis label.
Returns
-------
bool
"""
props = [
"NAME:ChangedProps",
[
"NAME:Text Font",
"Height:=",
-1 * font_size - 2,
"Wi... | |
import datetime
import unittest
from unittest import mock
from lgrez import config, bdd
from lgrez.features import open_close
from test import mock_discord, mock_bdd, mock_env
class TestOpenCloseFunctions(unittest.IsolatedAsyncioTestCase):
"""Unit tests for lgrez.features.open_close utility functions."""
def setU... | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
last mod 7/16/19
much of this code is highly optimized to the point of being pretty unreadable
The algorithm has this general layout
- modify boosted tree for fast use, generate lookup table of detection overlaps
- for each detection
- transform lidar points to local ground ... | |
<reponame>sparkslabs/kamaelia_orig<gh_stars>10-100
#!/usr/bin/env python
# The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a co... | |
<filename>src/redfish/ris/rmc.py<gh_stars>10-100
# Copyright Notice:
# Copyright 2016-2021 DMTF. All rights reserved.
# License: BSD 3-Clause License. For full text see link:
# https://github.com/DMTF/python-redfish-library/blob/master/LICENSE.md
# -*- coding: utf-8 -*-
"""RMC implementation """
#---------Imp... | |
default_subnetwork = gcp.compute.Subnetwork("defaultSubnetwork",
ip_cidr_range="10.1.2.0/24",
region="us-central1",
network=default_network.id,
opts=pulumi.ResourceOptions(provider=google_beta))
instance_template = gcp.compute.InstanceTemplate("instanceTemplate",
machine_type="e2-medium",
network_interfaces=[gcp... | |
"""
Module related to LIME method
"""
import warnings
import tensorflow as tf
import numpy as np
from tensorflow.keras.losses import cosine_similarity #pylint: disable=E0611
from sklearn import linear_model
from skimage.segmentation import quickshift, felzenszwalb
from .base import BlackBoxExplainer, sanitize_input_... | |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 IBM Corporation
# and other contributors as indicated by the @author tags.
#
# 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
#
# ht... | |
<filename>SS_Embedding_Calculation/run_OpenKEmodel.py
import warnings
warnings.filterwarnings("ignore")
import tensorflow as tf
import numpy as np
import os
import json
import rdflib
import sys
from OpenKE import config
from OpenKE import models
from process_KG import *
#####################
## Functions ##
#####... | |
*serfHealth* check.
*lock_delay* is an integer of seconds.
*behavior* can be set to either 'release' or 'delete'. This
controls the behavior when a session is invalidated. By default,
this is 'release', causing any locks that are held to be released.
Changing this to 'delete' causes any locks that are held to be... | |
#!/usr/bin/env python
import numpy as np
# No error is raised if matplotlib cannot be imported here, because
# matplotlib and plotly are not needed for core operation of
# booz_xform, so we don't want to make them mandatory requirements.
try:
import matplotlib.pyplot as plt
except:
pass
try:
import plotly.graph_ob... | |
from __future__ import print_function, unicode_literals, absolute_import, division
from six.moves import range, zip, map, reduce, filter
from keras.layers import Input, Conv2D, Conv3D, Activation, Lambda
from keras.models import Model
from keras.layers.merge import Add, Concatenate
import tensorflow as tf
from keras i... | |
and try again' % self.uuid)
else:
raise Exception('unable to attach the iso to the VM[uuid:%s].' % self.uuid)
def check(_):
me = get_vm_by_uuid(self.uuid)
for disk in me.domain_xmlobject.devices.get_child_node_as_list('disk'):
if disk.device_ == "cdrom" and xmlobject.has_element(disk, 'source'):
if disk.target.... | |
the JSON parsing of `output` string. aws commands can
be filtered using the --query parameter to produce more manageable
output before JSON parsing.
"""
return json.loads(output)
def parse_none(output):
"""Return the input as the output, i.e. no changes."""
return output
def test_function(parameters):
return... | |
not bm_contract_project:
project_name = ""
else:
project_name = bm_contract_project.project_name
# 查找volume信息
bm_contract_volume = service_model.BmServiceMaterialVolume.objects.filter(
openstack_volume_type=auth_models.VOLUME_BACK_TYPE).first()
if not bm_contract_volume:
material_number = ""
volume_type_name ... | |
if chunk_id in pending_s3_read:
# already a read in progress, wait for it to complete
read_start_time = pending_s3_read[chunk_id]
log.info(f"s3 read request for {chunk_id} was requested at: {read_start_time}")
while time.time() - read_start_time < 2.0:
log.debug("waiting for pending s3 read, sleeping")
await asyn... | |
a + '/assets/minecraft/textures/blocks'
file_names = os.listdir(file_path)
shutil.copy(file_path + '/cauldron_bottom.png', b + '/textures/blocks')
if 'cauldron_bottom.png' in file_names:
os.rename(os.path.join(b + '/textures/blocks', 'cauldron_bottom.png'),
os.path.join(b + '/textures/blocks', str('cauldron_b... | |
204,
219,
203,
232,
241,
244,
212,
210,
219,
200,
234,
209,
218,
213,
221,
236,
212,
189,
219,
221,
223,
222,
212,
251,
263,
417,
1038,
879,
855,
716,
645,
665,
715,
673,
724,
646,
681,
697,
745,
816,
787,
800,
826,
790,
764,
724,
730,
764,
833,
1188,
1416,
1302,
1253... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.