input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
# Copyright 2016 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... | |
<gh_stars>0
import pygame
from components import Btn, Text, Line, Image, Stage
import simpleaudio as sa
import os
def float_eq(f1, f2):
return abs(f1 - f2) <= 1e-4
#This class represents a musical bar
class Bar:
"""
[__init__ self bpm timing treble bass] generates a new Bar
with [bpm] beats per minute, [timing] a... | |
<reponame>rcooke-ast/PYPIT<gh_stars>0
"""
Provide basic mosaicing functions.
.. include common links, assuming primary doc root is up one directory
.. include:: ../include/links.rst
"""
from IPython import embed
import numpy as np
from scipy import ndimage
from pypeit import msgs
from pypeit.core import transform
f... | |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Catalog utility functions / classes."""
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
from astropy.coordinates import Angle, SkyCoord
__all__ = [
'coordinate_iau_format',
'ra_iau_format',
'dec_... | |
#!/usr/bin/env python
import time
import datetime
import os
import random
import threading
import argparse
import torch
import numpy as np
import cv2
from robot import Robot
from trainer import Trainer
from logger import Logger
import utils
from lwrf_infer import LwrfInfer
from policies import Explorer, Coordinator
... | |
<filename>libcloud/common/nttcis.py<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... | |
<gh_stars>1-10
import discord
from discord.utils import get
from discord.ext import commands, tasks
from functioning import *
from links import *
from responses import *
import mysql.connector as ms
import imdb
import random
import calendar
import pytz
import datetime
import regex
import praw
import pytube
import async... | |
#!/usr/bin/env python3
# (1) Wrap if, while, etc. statements in curly braces.
# (2) Insert fences; backup file as *.fibak first if it does not exist yet
# Transformations preserve line numbers.
# ------------------------------------------------------------------------------
# Current musketeer input format (SVN rev ... | |
e.message)
def DescribeServicesStatus(self, request):
"""本接口(DescribeServicesStatus)用于搜索查询某一个服务或多个服务的列表,并返回服务相关的域名、时间等信息。
:param request: Request instance for DescribeServicesStatus.
:type request: :class:`tencentcloud.apigateway.v20180808.models.DescribeServicesStatusRequest`
:rtype: :class:`tencentcloud.apiga... | |
<reponame>Shiguang-Guo/fairseq<filename>fairseq/models/speech_to_speech/s2s_transformer.py
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from pathlib import Path
from typing... | |
from .adt import ADT
from .adt import memo as ADTmemo
from .prelude import *
from . import atl_types as T
from .frontend import AST
from fractions import Fraction
from math import gcd as _gcd
def _lcm(x,y):
return (x*y)//_gcd(x,y)
# notes on symbols to use
# Note that BOOL is a type and Bool a formula constructor... | |
from __future__ import print_function, division
import numpy as np
import os
import cv2
from PIL import Image
import random
from functools import partial
import tensorflow as tf
from keras.models import Model, Sequential, load_model
from keras.layers.merge import _Merge
from keras.layers import Input, Conv2D, MaxPooli... | |
<filename>falcon_kit/run_support.py
from . import bash, functional
from .functional import cfg_tobool
from .io import NativeIO
from .util.system import (make_fofn_abs, make_dirs, cd)
import json
import logging
import logging.config
import os
import re
import io
import sys
import tempfile
import time
import uuid
logger... | |
<filename>cgi_ui/cgi-bin/strf_web.py<gh_stars>0
# -*- coding: utf-8 -*-
# !C:\tools\Python-3.6.2_64\pythonw.exe
# !/usr/local/bin/python3.6
import datetime
import math
import os
import sys
from pathlib import Path
from typing import List, Dict, Union, Tuple
from xml.etree.ElementTree import ParseError
from gemmi.cif ... | |
found in another datagroup it may be changed.
This will be used to navigate data_file and find the
correct final image. (Default: 'StitchedImage')
mode: str
Mode determines what color, quality and
how many images are saved.
Possible values for mode: save_ubyte, save_float,
save_rgb. If another or no value is giv... | |
<filename>sem_seg/get_info.py
import os
import re
import sys
import time
import copy
import math
import argparse
import numpy as np
import scipy as scp
import open3d as o3d
from natsort import natsorted
import matplotlib.pyplot as plt
from scipy.spatial import distance
from plyfile import PlyData, PlyElement
from mpl_t... | |
dose 50
Bioassay, Embryo Infective Dose 50
"""
zero029 = CodeSystemConcept(
{
"code": "0029",
"definition": "Bioassay, Embryo Lethal Dose 50",
"display": "Embryo lethal dose 50",
}
)
"""
Embryo lethal dose 50
Bioassay, Embryo Lethal Dose 50
"""
zero030 = CodeSystemConcept(
{
"code": "0030",
"defini... | |
<gh_stars>0
from io import StringIO
import pandas as pd
import networkx as nx
import wntr
import math
import os
import numpy as np
import geopandas as gpd
import infrarisk.src.physical.interdependencies as interdependencies
import infrarisk.src.physical.water.water_network_model as water
import infrarisk.src.physical.... | |
import h5py
import numpy as np
import tensorflow as tf
import tensorflow_addons as tfa
import math
from numpy.random import RandomState
import pandas as pd
import matplotlib.pyplot as plt
import time
import random
import pickle
def load_dataset(data, frac, list_of_inputs, list_of_outputs, consistent = False, seed = 4... | |
import logging
import os
import shutil
import warnings
from types import TracebackType
from typing import Any, Callable, Dict, List, Optional, Text, Type, Collection
import rasa.core.utils
import rasa.utils.io
from rasa.cli import utils
from rasa.cli.utils import bcolors
from rasa.constants import (
DEFAULT_LOG_LEVEL... | |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import copy
import time
from test.intelliflow.core.signal_processing.dimension_constructs.test_dimension_spec import TestDimensionSpec
from test.intelliflow.core.signal_processing.routing_runtime_constructs impor... | |
<reponame>pgniewko/deep-toxin
# -*- coding: utf-8 -*-
"""
##############################################################################
The calculation of molecular constitutional indices based on its topological
structure. You can get 30 molecular connectivity descriptors. You can freely
use and distribute i... | |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import cPickle as pickle
from uuid import UUID
class HFindTwoApplyElementsWithTraceLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HFindTwoApplyElementsWithTraceLHS.
"""
# Flag this... | |
"""
Provides a sparse representation of volumetric and/or surface data
The data can be either defined per voxel/vertex (:class:`DenseCifti`) or per parcel (`class:`ParcelCifti`).
The data can be read from NIFTI, GIFTI, or CIFTI files.
Non-sparse volumetric or surface representations can be extracte.
"""
from nibabel.... | |
"""Test ``sfini.execution._execution``."""
from sfini.execution import _execution as tscr
import pytest
from unittest import mock
import sfini
import datetime
import json
from sfini.execution import history
@pytest.fixture
def session():
"""AWS session mock."""
return mock.MagicMock(autospec=sfini.AWSSession)
cl... | |
= Var(within=Reals,bounds=(0,None),initialize=0.0333333333333333)
m.x1237 = Var(within=Reals,bounds=(0,None),initialize=0.0333333333333333)
m.x1238 = Var(within=Reals,bounds=(0,None),initialize=0.0333333333333333)
m.x1239 = Var(within=Reals,bounds=(0,None),initialize=0.0333333333333333)
m.x1240 = Var(within=Reals,bound... | |
None,
**kwargs
):
"""
:keyword virtual_path: Virtual path.
:paramtype virtual_path: str
:keyword physical_path: Physical path.
:paramtype physical_path: str
:keyword preload_enabled: :code:`<code>true</code>` if preloading is enabled; otherwise,
:code:`<code>false</code>`.
:paramtype preload_enabled: bool
:k... | |
select(population):
# for i, potential_parent in enumerate(population):
# y = simulate_ode(potential_parent, TIME_STEPS, BATCH_SIZE, NODES)
# # Multiple outputs
# cost_storage[i] = bandpass_cost_calculator(y[:, -1], BATCH_SIZE) * 1.5
# cost_storage[i] += switch_cost_calculator(y[:, -2], BATCH_SIZE) * 1.25
# # cost_stor... | |
<filename>boto3_type_annotations_with_docs/boto3_type_annotations/autoscaling_plans/paginator.py
from typing import Dict
from typing import List
from botocore.paginate import Paginator
class DescribeScalingPlanResources(Paginator):
def paginate(self, ScalingPlanName: str, ScalingPlanVersion: int, PaginationConfig: D... | |
', len(results)
print '\n debug -- len(results_plus): ', len(results_plus)
results.update(results_plus)
if rs_array_names:
codes['rs_array_names'] = rs_array_names
if debug:
print '\n debug -- codes: %s' % json.dumps(codes, indent=4, sort_keys=True)
print '\n debug -- final len(results): ', len(results)
keys ... | |
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
import torch
from . import enums
_end_ipu_block = torch.ops.poptorch.end_ipu_block
def ipu_print_tensor(tensor, title=""):
return torch.ops.poptorch.ipu_print_tensor(tensor, title)
def nop(tensor):
""" A no-operation: it is functionally the same as an iden... | |
"""Database helper functions for single database connectivity
Manage saved settings for Db2 connections
db_connect() - Connect using loaded/prompted credentials
db_connect_prompt() - Prompts for connection settings
db_connected() - Return connection status
db_connection() - Return handle for current connection
d... | |
<reponame>pulumi/pulumi-vault<filename>sdk/python/pulumi_vault/pkisecret/secret_backend_role.py
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pu... | |
<filename>sunshine_conversations_client/model/web_update_all_of.py
# coding: utf-8
"""
Sunshine Conversations API
The version of the OpenAPI document: 9.4.5
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from sunshine_conversations_client.configuration import ... | |
("xRealloc", c_void_p), # Resize an allocation
("xSize", c_void_p), # Return the size of an allocation
("xRoundup", c_void_p), # Round up request size to allocation size
("xInit", c_void_p), # Initialize the memory allocator
("xShutdown", c_void_p), # Deinitialize the memory allocator
("pAppData", c_void_p), # Arg... | |
self.model._reset_iter_counts()
self.final_setup()
self._run_counter += 1
record_model_options(self, self._run_counter)
self.model._clear_iprint()
return self.driver.run()
def compute_jacvec_product(self, of, wrt, mode, seed):
"""
Given a seed and 'of' and 'wrt' variables, compute the total jacobian vector ... | |
0 slopes. False otherwise.
"""
pass
def removeKey(self, keys):
"""self.removeKey(keys) -> None.
Remove some keys from the curve.
@param keys: The sequence of keys to be removed.
@return: None.
"""
pass
def size(self):
"""self.size() -> Number of keys.
@return: Number of keys.
"""
pass
def knobIndex(se... | |
<filename>addons/odoo/fields.py
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
""" High-level objects for fields. """
from collections import defaultdict
from datetime import date, datetime, time
from operator import attrgetter
import itertools
import logging
import... | |
mode == 'remove':
if len(t_seq + ext_seq) <= maxlen:
return [t_seq + ext_seq], [[0, len(t_seq + ext_seq)]]
else:
return [], [[0, 0]]
if mode == 'slide':
return nlp2.sliding_windows(t_seq, maxlen - len(ext_seq), append_seq=ext_seq)
if mode == 'start_slice':
slices = t_seq[:maxlen - len(ext_seq)]
slices.extend(e... | |
= spark_version
self.default_spark_log_folder = default_spark_log_folder
self.node_size = node_size
self.node_size_family = node_size_family
class CheckNameAvailabilityRequest(Model):
"""Check name availability request.
A request about whether a workspace name is available.
:param name: Workspace name
:type ... | |
<reponame>cltl-students/soren-fomsgaard-qanon-style
#%% ANCHOR IMPORTS
#import pickle
#import multiprocessing
#from os import read
## Preprocessing modules
import re
#import nltk
#from nltk.tokenize import RegexpTokenizer, WhitespaceTokenizer, word_tokenize
#from nltk.stem import WordNetLemmatizer
#from nltk.corpus ... | |
<reponame>pombredanne/docker-scripts<gh_stars>100-1000
import datetime
import docker
import hashlib
import json
import logging
import os
import re
import shutil
import six
import tarfile
import tempfile
import threading
from docker_squash.errors import SquashError, SquashUnnecessaryError
if not six.PY3:
import dock... | |
of <TEXT>
data = data.replace("<TEXT>", "⁂")
data = TAG_PATTERN.sub("", data)
min_offset = max(0, data.find("⁂"))
data = data.replace("⁂", "")
# Extract sentences from chunks
chunk_offset = 0
sentences = []
for chunk in chunks:
lines = chunk.split("\n")
current_sentence = []
start = offset = 0
for line in ... | |
<reponame>raphaeltinarrage/velour
'''
velour -> persistence
(list of functions)
Combinatorics of simplicial complexes:
- GetPowerSet
- CopySimplexTree
- GetVerticesSimplexTree
- GetSimplicesSimplexTree
- GetNeighborsSimplexTree
- IsFilteredSimplicialMap
- BarycentricSubdivisionSimplex
- BarycentricSubdivisionS... | |
<reponame>InDeepShip/InDeepShip
from django.shortcuts import render
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.response import Response
# from rest_framework.authentication import BaseAuthentication
from rest_framework import status
from aft import set... | |
y**2 + z**2)**(7/2)
@jit(nopython=True, cache=True)
def Txzxyz(x,y,z):
return 15*y*(-63*x**2*z**2/(x**2 + y**2 + z**2)**2 + 7*x**2/(x**2 + y**2 + z**2) + 7*z**2/(x**2 + y**2 + z**2) - 1)/(x**2 + y**2 + z**2)**(7/2)
@jit(nopython=True, cache=True)
def Txzxzx(x,y,z):
return 15*x*(-63*x**2*z**2/(x**2 + y**2 + z**2)**2 +... | |
(f_v[2]-isect).length
w0 = (l1+l2)
w1 = (l0+l2)
w2 = (l1+l0)
totw= w0 + w1 + w2
w0=w0/totw
w1=w1/totw
w2=w2/totw
return f, side, w0, w1, w2
def pickMeshGroupWeight(me, act_group, orig, rdir):
f, side, w0, w1, w2= pickMeshRayFaceWeight(me, orig, rdir)
if f==None:
return None
f_v= f.v
if side=... | |
iteration, using the parameters
from the previous fit as the starting point and use the intrinsic
scatter estimates provided by :func:`disk_fit_reject`. Covariance is
still ignored.
#. Reject outliers in both velocity and velocity dispersion (if the
latter is being fit) using :func:`disk_fit_reject`. The rejectio... | |
# encoding: utf-8
import MySQLdb as mdb
import time
import datetime
import logging
import json
from django.conf import settings
from django.http import HttpResponse, JsonResponse
from django.views.generic import CreateView, DeleteView, ListView, View
from django.conf import settings
from .models import Picture
from .re... | |
<filename>grblocalization/GRBToyModel3D.py<gh_stars>1-10
###################################################################################################
#
# GRBToyModel.py
#
# Copyright (C) by <NAME>, <NAME> & <NAME>.
# All rights reserved.
#
# Please see the file LICENSE in the main repository for the copyright-no... | |
<reponame>hughbg/hera_sim<filename>hera_sim/simulate.py<gh_stars>10-100
"""Module containing a high-level interface for :mod:`hera_sim`.
This module defines the :class:`Simulator` class, which provides the user
with a high-level interface to all of the features provided by :mod:`hera_sim`.
For detailed instructions on... | |
userMeans, userStdDevs = normalizeRatings(denseRatings, boolViewings)
similarities, user_commonViewings = buildUsersGraph(normRatings, boolViewings, verbose=verbose)
neighbors = buildNeighbors(user_commonViewings)
sorted_neighbors = sortNeighbors(neighbors, similarities, useTuples=True, verbose=verbose)
model = {'n... | |
(Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
back (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
"""
lib.TCOD_console_set_color_control(con, fore, back)
@deprecate("Check the `con.default_bg` attribute instead.")
def console_get_de... | |
#! usr/bin/python3.6
"""
Module initially auto generated using V5Automation files from CATIA V5 R28 on 2020-06-09 09:53:18.676780
.. warning::
The notes denoted "CAA V5 Visual Basic Help" are to be used as reference only.
They are there as a guide as to how the visual basic / catscript functions work
and thus hel... | |
== f"Level {level} not available. Number of available levels: 1"
)
@pytest.mark.parametrize(
"properties",
(
(
{
"openslide.objective-power": "20",
"openslide.level[1].downsample": "4.003",
"openslide.level[2].downsample": "16",
}
),
),
)
def it_knows_its_magnification(self, request, properties, tmpdir):... | |
"""
STARDATE
=====================
This package produces posterior PDFs over age, mass, bulk metalicity,
distance and V-band extinction for stars from their spectroscopic parameters
(T_eff, log g and observed bulk metallicity), their apparent magnitudes in
a range of bandpasses, their parallaxes and rotation periods, i... | |
# coding=utf-8
"""
Connections to IQFeed.exe to get different types of data.
This module contains various Conn classes called XXXConn each of
which connects to IQFeed and helps to return market data from it.
Some of the XXXConn classes (like HistoryConn), which provide data
that should be available when requested, p... | |
import os
import numpy as np
import matplotlib.pyplot as plt
from . import helper_generic as hlp
from . import helper_hh_model as hh
from . import helper_mkz_model as mkz
from . import helper_site_response as sr
class Curve:
"""
Class implementation of a strain-dependent curve. It can be a stress-strain
curve, a ... | |
# %%
import os
import sys
from collections import Counter
from datetime import datetime, timedelta
from pathlib import Path
from zipfile import ZipFile
# data wrangling
import geopandas as gpd
from numpy.lib.utils import deprecate
import pandas as pd
import json
import numpy as np
import requests
from urllib.error imp... | |
<reponame>smegurus/smegurus-django
import json
from django.core import mail
from django.db import transaction
from django.core.urlresolvers import resolve, reverse
from django.http import HttpRequest
from django.http import QueryDict
from django.test import TestCase
from django.test import Client
from django.utils impo... | |
<filename>flask_server/routes.py
from flask import g, render_template, flash, redirect, url_for, request
from flask_login import login_user, logout_user, current_user, login_required
from werkzeug.urls import url_parse
from flask_server import flask_server, db
from flask_server.forms import (
LoginForm,
RegistrationF... | |
'flag_tm'),
(b'\xf0\x9f\x87\xb9\xf0\x9f\x87\xb3', 'flag_tn', 'flag_tn'),
(b'\xf0\x9f\x87\xb9\xf0\x9f\x87\xb4', 'flag_to', 'flag_to'),
(b'\xf0\x9f\x87\xb9\xf0\x9f\x87\xb7', 'flag_tr', 'flag_tr'),
(b'\xf0\x9f\x87\xb9\xf0\x9f\x87\xb9', 'flag_tt', 'flag_tt'),
(b'\xf0\x9f\x87\xb9\xf0\x9f\x87\xbb', 'flag_tv', 'flag_tv')... | |
simple_embed(ctx, "Please enter the full url.")
return
params = {}
for i in range(1, 9):
params["card" + str(i)] = card_keys[i - 1]
await ctx.invoke(self.bot.get_command("deck add"), **params)
try:
await ctx.message.delete()
except Exception:
pass
@deck.command(name="list")
async def deck_list(self, ctx: co... | |
kommunenavn[int(1845.0)] = createStringReference("S\u00f8rfold")
kommunenavn[int(1848.0)] = createStringReference("Steigen")
kommunenavn[int(1849.0)] = createStringReference("Hamar\u00f8y \u2013 H\u00e1bmer")
kommunenavn[int(1850.0)] = createStringReference("Divtasvuodna \u2013 Tysfjord")
kommunenavn[int(1851.0)] =... | |
#
#
# Copyright (C) University of Melbourne 2012
#
#
#
#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... | |
<gh_stars>0
"""
Propagator for CSP constraints.
"""
from collections import OrderedDict
import clingo
from .parsing import AbstractConstraintBuilder, simplify, parse_theory
from .util import measure_time_decorator, IntervalSet
from .base import Config, Statistics, InitClauseCreator, ControlClauseCreator
from .solver ... | |
#!/usr/bin/env python3
desc="""Requiggle basecalled FastQ files and features in BAM file.
For all reference bases we store (as BAM comments):
- normalised signal intensity mean [tag si:B,f]
- reference base probability [tag tr:B:C] retrieved from guppy (trace scaled 0-255)
- dwell time [tag dt:B:C] in signal step cap... | |
0,
'end_modifications_member_start_slope_z': 0,
'end_modifications_member_end_extension': 0,
'end_modifications_member_end_slope_y': 0,
'end_modifications_member_end_slope_z': 0,
'is_deactivated_for_calculation' : False},
model = Model):
"""
Args:
no (int): Member Tag
start_node_no (int): Tag of Start Node
e... | |
:class:`com.vmware.vapi.std.errors_client.Unauthorized`
Forbidden
:raise: :class:`com.vmware.vapi.std.errors_client.NotFound`
Not Found
"""
return self._invoke('get',
{
'cursor': cursor,
'included_fields': included_fields,
'page_size': page_size,
'sort_ascending': sort_ascending,
'sort_by': sort_by,
'sync... | |
INDIVIDUAL_FILE)
target = open(OUTPUT_DIR + "/0_0_best_ever_fitness.txt", 'w')
target.write(str(best_ever["fitness"]))
target.close()
EVO_TESTAR_ACTIONS = 1000
GENERATION_IDX = 0
INDIVIDUAL_IDX = 0
evaluate_individual(best_ever)
# end by urueda
return best_ever
def print_stats(generation, individuals):
"... | |
if name[:4] in ['Heli', 'Shee', 'Coil', 'Turn', 'Stra']:
SS= g.SS
name='%s%s'%(SS.name, SS.chain.id)
#print name
colors=mol.geomContainer.getGeomColor(name)
if colors is None :
#get the regular color for this SS if none is get
colors = [SecondaryStructureType[SS.structureType],]
flag=mol.geomContainer.geoms[na... | |
<reponame>LYH-93/LYH-93.github.io
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
"""-------------------------------------------------------------------------------------------------------------------------------------------------------------- """
"""
자료구조 : 1. sequence 자료구조 (순... | |
<filename>pygears/hdl/sv/svcompile.py
from pygears import reg
from pygears.hls import ir, is_intf_id
from pygears.hls import Context, HDLVisitor, Scope
from pygears.typing import Bool, typeof
from pygears.core.port import HDLProducer, HDLConsumer
from pygears.core.gear import InSig, OutSig
from dataclasses import datac... | |
# -*- coding: utf-8 -*-
#import pdb; pdb.set_trace()
from __future__ import unicode_literals, print_function
import sys
import os
import pyloco
# Push name collection to leaf nodes
# filter part of subnodes to stop the push
# distinguish definition from reference
#self._search_subnodes(node, ids, rtypes)
class Pas... | |
None)
assert(vals.dtype == np.float64)
assert(np.array_equal(vals, np.array([1, 2.5, 3, 4.5, 5.5], dtype=np.float64)))
def test_process_continuous_obj_simple_missing():
vals, bad = _process_continuous(np.array([1, 2.5, "3", "4.5", np.float32("5.5")], dtype=np.object_), np.array([True, True, True, True, True, False]... | |
<reponame>lustered/youtube-mp3-GUI<gh_stars>1-10
from __future__ import unicode_literals
import os
import random
from time import sleep
import mutagen.mp3
import fnmatch
import pygame
from pygame import mixer
from tkinter import *
from tkinter import ttk
from subprocess import Popen
from threading import Thread
from su... | |
<filename>nested_lstm.py
from __future__ import absolute_import
import warnings
from keras import backend as K
from keras import activations
from keras import initializers
from keras import regularizers
from keras import constraints
from keras.engine import Layer
from keras.engine import InputSpec
from keras.legacy im... | |
for m in range(0,cols):
ys[n] = ys[n] + p[m+1,n]*y_seeds[n]
ys[n] = ys[n] + E[i,n]
for n in range(0,cols):
y_seeds[n] = ys[n]
syn_residuals[i,:] = np.reshape([ys],(1,cols))
for i in range(0,cols):
syn_residuals[:,i] = syn_residuals[:,i]*stds[i]*(1/np.std(syn_residuals[:,i])) + mus[i]
###########... | |
x = self._2_act2(x)
#x = torch.cat([r1, r2, x], 1)
x = self._2_conv_proj(x)
x = self._2_bn_proj(x)
x = self._2_act_proj(x)
r2 = x
x1 = self._3_conv1(x)
x1 = self._3_bn1(x1)
x2 = self._3_conv1_h(x)
x2 = self._3_bn1_h(x2)
x3 = self._3_conv1_v(x)
x3 = self._3_bn1_v(x3)
x = x1+x2+x3
x = self._3_act1(x)
... | |
automatically.
"""
# Create or coerce a protobuf request object.
# Quick check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([parent])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argu... | |
here')
assert 0, self.agent.message
# TODO: eat directly from ground if possible
item = self.move_to_inventory(item)
assert item in self.items.all_items, item or item in self.items_below_me
letter = self.items.get_letter(item)
with self.agent.atom_operation():
if quaff:
def text_gen():
if self.agent.message.... | |
= context.setdefault('email', self.email_address)
if not email:
return 0 # Not Sent
langs = i18n.parse_accept_lang(self.email_lang or 'en')
locale = i18n.match_lang(langs)
i18n.add_helpers_to_context(self._tell_sentry, context, locale)
context['escape'] = lambda s: s
context_html = dict(context)
i18n.add_helper... | |
import ast
import re
import json
import jwt
import requests
from django.contrib.gis.db.models.functions import AsGeoJSON
from django.contrib.gis.gdal import SpatialReference
from django.db.models.base import ModelBase
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_4... | |
= [default_values]
for j in range(len(default_values)):
point = []
for i in range(len(default_values)):
if isinstance(default_values[i], bool):
point.append(default_values[i])
else:
low = default_values[i]-1
high = default_values[i]+1
#checking if low is higher than the lower hard_bound
if h... | |
create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups')
root.initialize_storage()
observable = root.add_observable(F_TEST, '00:01|00:05')
root.save()
root.schedule()
engine = TestEngine(analysis_pools={'test_groups': 1})
engine.enable_module('analysis_module_test_delayed_analysis')
engine.con... | |
from __future__ import print_function, division
import numpy as np
from .astroTimeLegacy import premat, daycnv, precess, helio_jd
from .idlMod import idlMod
from PyAstronomy.pyaC import pyaErrors as PE
import six
import six.moves as smo
def baryvel(dje, deq):
"""
Calculate helio- and barycentric velocity.
.. note... | |
<filename>pypipeline/experiment_runner.py
#!/usr/bin/python
#
import os
import sys
import getopt
import math
import tempfile
import stat
import re
import shlex
import time
import subprocess
from subprocess import Popen
import glob
import topological
from util import get_new_directory
from util import get_new_file
from... | |
<gh_stars>0
"""
Handle the email *forward* and *reply*. phase. There are 3 actors:
- contact: who sends emails to <EMAIL> address
- SL email handler (this script)
- user personal email: to be protected. Should never leak to contact.
This script makes sure that in the forward phase, the email that is forwarded to user ... | |
""" Plotting of conformation distributions. """
import copy
import itertools
import math
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
from scipy.stats import entropy, gaussian_kde
from scipy.spatial import distance_matrix
from typing import Dict, List, Union
from ty... | |
"""
Description: IDA Python script to recursively descend through ScatterBee shellcode and rebuild an analysable binary. Output can be loaded into IDA with ScatterLoader.py
Author: @malworms
License:
Copyright 2021 PwC UK
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except i... | |
must be in self.model.x, output in self.model.y, loss in self.model.loss, and training using self.model.train_step '''
logger.info("fitting quadric model")
self.fitted_qs = []
log_str = "epoch: {:06d} ::: loss: {:.02e}"
for epoch in range(self.n_epochs):
batcher = tensorflow_models.np_batcher(X.shape[0], self.b... | |
if nrCertif.subclass:
return nrCertif.subclass(*args_, **kwargs_)
else:
return nrCertif(*args_, **kwargs_)
factory = staticmethod(factory)
def hasContent_(self):
if (
):
return True
else:
return False
def export(self, outfile, level, namespace_='', name_='nrCertif', namespacedef_='', pretty_print=True):
im... | |
<filename>pyrumpeltree.py
"""Python3 port of RumpelTree++.
This module constitutes a non capability-compatible port of RumpelTree++ to Python 3.
The pyrumpeltree module is meant as the core hashing and encoding logic for servers
and/or file-systems implementing sparse-cap designated singly attenuated Rumpelstiltskin... | |
'class': a.__class__.__name__}
a_con = a.Consumer(conn.channel())
b_con = b.Consumer(conn.channel())
c_con = c.Consumer(conn.channel())
# when cast is invoked for round-robin:
# only one consumer for that actor class receives the message and
# messages are consumed by consumers for other actor classes
a.cast(m... | |
if len(drive) == 23:
# binary data from parsed lnk
self.drive = drive[1:3]
else:
# text representation
m = _DRIVE_PATTERN.match(drive.strip())
if m:
self.drive = m.groups()[0].upper() + ':'
self.drive = self.drive.encode()
else:
raise FormatException("This is not a valid drive: " + str(drive))
@property
de... | |
tr1 = comp1.getTimeRange()
tr2 = comp2.getTimeRange()
stats1 = tree.stats.get("Wind", tr1, al1, mergeMethod = "Average")
stats2 = tree.stats.get("Wind", tr2, al2, mergeMethod = "Average")
# If past the first 5 periods, return 1 (combine)
hours = self.hoursPastProductStart(tree, comp1)
if hours >= 5*12:
return 1... | |
the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
AccessGroupIncludeOkta.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
AccessGroupIncludeOkta.__key_warning(key)
return super().get(key, default)
def __init__(__s... | |
"""
This file contains a function for reading in command-line arguments
so BIOM files or tab-delimited files can be read.
The BIOM format is a standardized biological format
that is commonly used to contain biological data.
Tab-delimited files should be supplied with the BIOM-format specified headers (# prefix).
The so... | |
# Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | |
<filename>lib/rtorrent/__init__.py<gh_stars>100-1000
# Copyright (c) 2013 <NAME>, <<EMAIL>>
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.