input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<reponame>raghavp96/league-ai
from __future__ import absolute_import, division, print_function
# To make sure the same randomness is used for feature in the hidden layers
# From: https://machinelearningmastery.com/reproducible-results-neural-networks-keras/
from numpy.random import seed
seed(1)
from tensorflow import ... | |
__author__ = "<NAME>"
__copyright__ = "Copyright 2022"
__UID__ = "117513615"
'''
Instructions to run the code
1. To run the file in Ubuntu, open a terminal and enter python dijkstras_algorithm.py or python3 dijkstras_algorithm.py.
2. Use input the start and goal positions in the terminal
3. The output will be sho... | |
from datetime import datetime
from dateutil.tz import tzlocal, tzutc
import pandas as pd
import numpy as np
from hdmf.backends.hdf5 import HDF5IO
from hdmf.common import DynamicTable
from pynwb import NWBFile, TimeSeries, NWBHDF5IO, get_manager
from pynwb.file import Subject
from pynwb.epoch import TimeIntervals
from... | |
= "com_github_go_bindata_go_bindata",
importpath = "github.com/go-bindata/go-bindata",
sum = "h1:5vjJMVhowQdPzjE1LdxyFF7YFTXg5IgGVW4gBr5IbvE=",
version = "v3.1.2+incompatible",
)
go_repository(
name = "com_github_go_check_check",
importpath = "github.com/go-check/check",
sum = "h1:0gkP6mzaMqkmpcJYCFOLkIBwI7xFE... | |
self.is_off_grid(x, y, x, y + h):
return
line = color.to_bytes(2, 'big') * h
self.block(x, y, x, y + h - 1, line)
def fill_circle(self, x0, y0, r, color):
"""Draw a filled circle.
Args:
x0 (int): X coordinate of center point.
y0 (int): Y coordinate of center point.
r (int): Radius.
color (int): RGB565 color... | |
import argparse
import xml.etree.ElementTree as ET
import sys
import os
import re
import getopt
#return codes of interpret
ARGUMENT_ERROR = 10
FILE_ERROR_IN = 11
FILE_ERROR_OUT = 12
XML_ERR = 31
SYNLEX_ERR = 32
SEMANTIC_ERR = 52
WRONG_OPERAND_TYPE = 53
VAR_DOESNOT_EXIST = 54
FRAME_DOESNOT_EXIST = 55
MISSING_VALUE = 5... | |
<filename>src/server/server.py
# built in
import socket
import threading
import _thread
import logging
import os.path
import signal
from sys import exit
import zlib
import re
from typing import Tuple, Dict, List
from queue import deque
from time import sleep
# dependecies
from Crypto.Cipher import PKCS1_OAEP
from Cryp... | |
<filename>src/test-zones.py
import glob
import os
import xml.etree.ElementTree as et
from xml.etree.ElementTree import tostring
import pyproj
from geomeppy import IDF
from geomeppy.utilities import almostequal
from geomeppy.geom.polygons import Polygon3D
import platform as _platform
###################################... | |
{
'Assessment': {
'row_warnings': {
errors.UNMODIFIABLE_COLUMN.format(
line=3,
column_name="Verified Date"
)}}}
response = self.import_data(collections.OrderedDict([
("object_type", "Assessment"),
("Code", assessment.slug),
("Verifiers", "<EMAIL>"),
("Verified Date", "01/21/2019"),
]))
self._check_csv_resp... | |
<reponame>DylanClarkOffical/TwitchBot
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# bot.py
import os
import re
import socket
import random
import requests
import datetime
import math
import csv
import tinyurl
from names import *
from config import *
from time import sleep
from decimal import *
s = socket.socket()
s... | |
In case it is modify, we still need to return self.prefixPoolObj
self.topoTypeDict = {'Custom': 'NetTopologyCustom',
'Fat Tree': 'NetTopologyFatTree',
'Grid': 'NetTopologyGrid',
'Hub-And-Spoke': 'NetTopologyHubNSpoke',
'Linear': 'NetTopologyLinear',
'Mesh': 'NetTopologyMesh',
'Ring': 'NetTopologyRing',
'Tree': ... | |
<reponame>gabstopper/smc-python<filename>smc/policy/rule_elements.py
from smc.base.model import Element, ElementCreator
from smc.base.structs import NestedDict
from smc.api.exceptions import ElementNotFound
from smc.base.util import element_resolver
class RuleElement(object):
"""
Rule Element encapsulates actions f... | |
<reponame>khelsabeck/felony_records_nc<gh_stars>0
from src.charge import Charge
import pytest
from datetime import date, datetime, timedelta
import typing
@pytest.fixture
def charge1():
charge1 = Charge("Simple Assault", "Class 2 Misdemeanor", date(2009,1, 1), date(2010,1, 1), "Randolph", "NCGS 14-33")
return charge... | |
# -*- coding: utf-8 -*-
import lxml.etree
import lxml.html
import weakref
import traceback
class RbElementMixin( object ):
def __enter__( self ):
self.tree()._push( self )
return self
def __exit__( self, exc_type, exc_value, tb ):
if exc_type :
print('[Rb]', ''.join( traceback.format_tb(tb) ) )
print('[... | |
"""
Toolset module for AWS using blt.
Currently, the primary use case is access to the Amazon Simple Storage Service
(`S3 <http://aws.amazon.com/s3/>`_) through the
`boto api <http://boto.s3.amazonaws.com/ref/s3.html>`_. More functionality
may be added down the road for other AWS services.
Author: @dencold (<NAME>)
"... | |
= True
model.Nodes[n].dofs['RY'].constrained = True
model.Nodes[n].dofs['RZ'].constrained = True
if j == 0:
model.Nodes[n].dofs['UY'].constrained = True
model.Nodes[n].dofs['UZ'].constrained = True
if j == self.nele_J:
model.Nodes[n].dofs['UZ'].constrained = True
vec_xz = (1,0,0)
for j in range(self.nele_J)... | |
import re
import xlrd
import operator
import unicodecsv
from openelex.base.load import BaseLoader
from openelex.models import RawResult
from openelex.lib.text import ocd_type_id, slugify
from .datasource import Datasource
"""
Wyoming elections have CSV results files for elections in 2006, along with special elections... | |
<gh_stars>1-10
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: <EMAIL>
# Maintained By: <EMAIL>
import datetime
import ggrc.builder.json
import hashlib
import logging
import time
from blinker imp... | |
!= 0 or v_offset != 0:
def offset(bbox):
left, top, right, bottom = bbox
return (left + h_offset, top + v_offset, right + h_offset, bottom + v_offset)
self.apply_offsets = offset
else:
self.apply_offsets = lambda bbox: bbox
# Supported modes
supported = (width, height) in [(160, 80), (160, 128), (128, 128)]
i... | |
"""
Power, Inverse, Factorial, InvFactorial, Combination
best solution:
- Power: makePowerTableMaspyNumba 13msec
- Inverse: makeInverseTableNumba 47msec
- Factorial: makeFactorialTableMaspyNumba: 13msec (K is excluded)
- ...: makeFactorialTableMaspy2Numba: 13msec (K is included, x! == ret[n-1])
- InvFactorial: makeIn... | |
a length
equal to the number of expected parameters.
>>> self.Make_surface([PIBYTWO,1.,0.9,4000.,0.08,300e3,5000.,10.,0.])
"""
# Apply a function that can modify the value of parameters.
if func_par is not None:
par = func_par(par)
# check if we are dealing with a dictionary
if isinstance(par, dict):
par = [p... | |
-> None:
"""Should return 400 Bad request."""
RACEPLAN_ID = "290e70d5-0933-4af0-bb53-1d705ba7eb95"
mocker.patch(
"race_service.services.startlists_service.create_id",
return_value=RACEPLAN_ID,
)
mocker.patch(
"race_service.adapters.startlists_adapter.StartlistsAdapter.create_startlist",
return_value=RACEPLAN_I... | |
from collections import defaultdict
from typing import List
from copy import deepcopy
class Mask:
def __init__(self, pattern: str) -> None:
self.pattern = pattern
def apply(self, to: int) -> int:
print(to)
for i, v in enumerate(self.pattern[::-1]):
if v == "X":
continue
print(i, v)
to = to & ~(1 << i) | (int... | |
<filename>Variables.py
"""
Created on Jun 16, 2016
@author: MarcoXZh
"""
cssFF = [
# Background
"background-color", "background-image",
# Border
"border-bottom-color", "border-bottom-style", "border-bottom-width",
"border-left-color", "border-left-style", "border-left-width",
"border-right-color", "border-right... | |
<gh_stars>1-10
# pylint: disable=too-many-lines
import heapq
import random
from eth_utils import encode_hex
from raiden.constants import EMPTY_HASH_KECCAK, MAXIMUM_PENDING_TRANSFERS, UINT256_MAX
from raiden.settings import DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS
from raiden.transfer.architecture import Event, StateChan... | |
<reponame>mazgutheng/Public
# -*- coding: utf-8 -*-
import LINETCR
from LINETCR.lib.curve.ttypes import *
from datetime import datetime
import time,random,sys,json,codecs,threading,glob,re,os,subprocess
cl = LINETCR.LINE()
#cl.login(qr=True)
cl.login(token='TOKEN_<PASSWORD>')
cl.loginResult()
print "Cl-Login Success\... | |
<reponame>Xinrihui/DeepLearningApp<gh_stars>1-10
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 适用于 tensorflow >= 2.0, keras 被直接集成到 tensorflow 的内部
# ref: https://keras.io/about/
from tensorflow.keras.layers import Input, LSTM, TimeDistributed, Bidirectional,Dense, Lambda, Embedding, Dropout, Concatenate, RepeatVector
fr... | |
# Copyright (C) 2018, <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the ho... | |
<gh_stars>0
'''Constants for MachineThematicAnalysis Toolkit'''
import sys
import os
import shutil
import platform
import wx
#import wx.lib.agw.flatnotebook as FNB
import External.wxPython.flatnotebook_fix as FNB
CUR_VER = '0.8.11'
#Variables to configure GUI
FNB_STYLE = FNB.FNB_DEFAULT_STYLE|FNB.FNB_HIDE_ON_SINGLE_T... | |
{k} not present in one of the parameter params"
@pytest.mark.parametrize("optim_name,defaults,params", [
('AdamOptimizer', {'lr': -1}, []), # invalid lr
('FooOptimizer', {'lr': 0.001}, []), # invalid name
('SGDOptimizer', [], []), # invalid type(defaults)
(optim.AdamConfig, {'lr': 0.003}, []), # invalid type(name... | |
True
self.severity = 3
self.args = {'ff': 10, 'ff1': 15}
def method(self, taf, mtr):
try:
mff = mtr['wind']['ff']['hi']
tfflo = taf['wind']['ff']['lo']
tffhi = taf['wind']['ff']['hi']
if mff < tfflo:
self.setmsg('Wind speeds differ by %d, TAF wind >= %d KTS',
self.args['ff'], self.args['ff1'])
return tfflo-... | |
__author__ = 'sibirrer'
import numpy as np
import copy
from lenstronomy.GalKin.analytic_kinematics import AnalyticKinematics
from lenstronomy.GalKin.galkin import Galkin
from lenstronomy.Cosmo.lens_cosmo import LensCosmo
from lenstronomy.Util import class_creator
from lenstronomy.Analysis.lens_profile import LensProfi... | |
import requests
import enum
import tarfile
import zipfile
import gzip
import lzma
import shutil
from abc import abstractmethod
from datetime import timedelta
from hashlib import sha1
from pathlib import Path
from furl import furl
from typing import Optional, Set, List, Dict, Type
from marshmallow import Schema
from sq... | |
"""
Created on March 7th, 2021
Contains some common loss functions and error metrics used to train / evaluate models.
CREDITS: Some of these were taken/adapted from https://github.com/agrimgupta92/sgan, and also from
https://github.com/abduallahmohamed/Social-STGCNN; https://github.com/quancore/social-lstm;
https://gi... | |
except:
self.errorMessages(5)
if self.mustCheckCompatibility():
if self.areFileCompatible():
self.setAnnotationFlags()
else:
self.errorMessages(1)
self.logger.error("Could not load" + self.annotationFileName + " annotation file! "
"Reason: bag is incompatible with the given annotation file.")
self.annotationF... | |
"""
Plotly-to-Matplotlib conversion functions.
"""
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government re... | |
< th).type(torch.FloatTensor)
conf = torch.exp(sharpness * (1.0 - dist/th)) - 1
conf0 = torch.exp(torch.FloatTensor([sharpness])) - 1 + eps
conf = conf / conf0.repeat(8, 1)
# conf = 1.0 - dist/th
conf = mask * conf
return torch.mean(conf)
def corner_confidences9(gt_corners, pr_corners, th=80, sharpness=2, im_wi... | |
Process {}".format(
run_config.local_rank)}},
every=100), Event.ON_TEST_BATCH_END) \
.with_event_handler(
PlotCustomVariables(visdom_logger, "Generated Intensity Histogram", PlotType.HISTOGRAM_PLOT,
params={"opts": {"title": "Generated Intensity Histogram",
"store_history": True,
"numbins": 128}}, every=100), Ev... | |
kann nicht mittels Formel berechnet werden, nur näherungsweise über 15°
# # Erster Wert ist die horziontale Höhe
# # Zweiter Wert ist 1/Refraktion, da dies einen annähernd linearen Verlauf ergibt
# REFRACTION = [[0.0, 1.6949],
# [0.3, 1.9262],
# [0.5, 2.0408],
# [1.0, 2.4374],
# [1.5, 2.8458],
# [2.0, 3.2787],
# [2.5, ... | |
# Copyright 2019-2020 Xanadu Quantum Technologies 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 agr... | |
raise http_exceptions.BadRequest("Request argument not recognized")
# get single rule by ruleid
rule_id = request.args.get('ruleid')
if rule_id is not None:
res = db.query(InboundMapping).filter(InboundMapping.groupid == settings.FLT_INBOUND).filter(
InboundMapping.ruleid == rule_id).first()
if res is not None:
... | |
<reponame>gokhanForesight/elasticsearch-py
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.... | |
<reponame>sathiscode/trumania
import pandas as pd
import logging
import numpy as np
import os
import functools
from trumania.core.operations import AddColumns, SideEffectOnly
from trumania.core.relationship import Relationship
from trumania.core.attribute import Attribute
from trumania.core.util_functions import make_... | |
# coding: utf-8
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
import numpy as np
import os
import time
import datetime
import json
import sys
import sklearn.metrics
from tqdm import tqdm
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import r... | |
as f:
textDic.append(json.load(f))
for i in range(len(textDic)):
for k in textDic[i].keys():
textDic[i][k] = text2num(textDic[i][k])
self.textDics[mode] = textDic
l = [dd['annotations'] for dd in d]
print('Loading data...')
for i, ll in enumerate(l):
for d in ll:
for dd in d['annotations']:
if dd['ins... | |
<reponame>avigmati/channels_endpoints<filename>src/channels_endpoints/main.py
import asyncio
import traceback
import importlib
import json
import datetime
import logging
import uuid
from asgiref.sync import sync_to_async
from async_timeout import timeout as atimeout
from functools import wraps
from django.conf import ... | |
<reponame>christopherjenness/ML-lib
"""
Tree based methods of learning (classification and regression)
"""
import abc
import numpy as np
import networkx as nx
from scipy.stats import mode
class BaseTree(object):
"""
Base Tree for classification/regression. Written for single
variable/value binary split critereon. ... | |
<reponame>rshk/exif-py
"""
Definition of tags
"""
from exifpy.utils import make_string, make_string_uc
__all__ = ['EXIF_TAGS', 'IGNORE_TAGS', 'MAKERNOTE_NIKON_OLDER_TAGS',
'MAKERNOTE_NIKON_NEWER_TAGS', 'MAKERNOTE_OLYMPUS_TAGS',
'MAKERNOTE_CASIO_TAGS', 'MAKERNOTE_FUJIFILM_TAGS',
'MAKERNOTE_CANON_TAGS', 'MAKERNOTE_C... | |
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response... | |
for child in node:
# if( child.tag == "explanation" ):
# explanationText = parse_contents(child) #found some explanation text
# elif( child.tag == "config" ):
# block.config = json.loads(parse_contents(child))
# elif( child.tag == "worldmap-config" ):
# block.worldmapConfig = json.loads(parse_contents(child))
# ... | |
<reponame>Voice-First-AI/generative-music-watson<filename>src/Skeleton/Skeleton.py
from __future__ import print_function
from Arranging.ArrangeSections import *
from Moods.Mood import Mood
import re
import os
import sys
import json
import random
import Section
import argparse
import requests
import Dev... | |
0): # Just guessing this is a hex value
return(value,RAW)
else:
return(addquotes(value,flag_quotes),STRING) # String
except:
return(addquotes(str(value),flag_quotes),RAW)
def addquotes(inString,flag_quotes):
if (isinstance(inString,dict) == True): # Check to see if this is JSON dictionary
serialized = json.du... | |
there is at least one prune, and any players should be treated as
# having played prune even though they haven't, fiddle the matrix
# accordingly
pi = 0
if a_prune_index is not None:
for p in players:
if p.avoid_prune:
played_matrix[pi][a_prune_index] += 1
played_matrix[a_prune_index][pi] += 1
pi += 1
# Adju... | |
self.__psplups_data is not None:
self.__psplups_transitions_mask = np.flatnonzero(
np.logical_and(
np.isin(self.psplups_lower_levels, included_levels),
np.isin(self.psplups_upper_levels, included_levels),
)
)
self.restrict()
def restrict(self):
assert self.__hasattr("levels_mask")
self.__unrestricted_popula... | |
# -*- coding: utf-8 -*-
"""
..
.. seealso:: `SPARQL Specification <http://www.w3.org/TR/rdf-sparql-query/>`_
Developers involved:
* <NAME> <http://www.ivan-herman.net>
* <NAME> <http://www.wikier.org>
* <NAME> <http://www.dayures.net>
* <NAME> <https://indeyets.ru/>
Organizations involved:
* `World Wide We... | |
as c:
c.argument('team_id', type=str, help='key: id of team')
c.argument('channel_id', type=str, help='key: id of channel')
c.argument('id_', options_list=['--id'], type=str, help='Read-only.')
c.argument('display_name', type=str, help='The display name of the user.')
c.argument('roles', nargs='+', help='The roles... | |
skipna : bool, default True
ddof : int, default 1
Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements.
mask : ndarray[bool], optional
nan-mask if known
Returns
-------
result : float
Unless input is a float array, in which case use the same
precis... | |
= 0
self.err_code = 0
def set_camera_mode(self, mode):
self.msg_buff.init()
self.msg_buff.append('mode', 'uint8', mode)
self.msg_buff.cmd_id = duml_cmdset.DUSS_MB_CMD_SET_WORKMODE
duss_result, resp = self.event_client.send_sync(self.msg_buff, 0.5)
return duss_result
def set_camera_ev(self, ev):
self.msg_buff... | |
<gh_stars>1-10
# Lint as: python2, python3
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LIC... | |
<gh_stars>1-10
from discord import Embed, Color, Member, utils, File
from discord.ext import commands
from db import dbconn
from utils import cf_api, paginator
from random import randint
from datetime import datetime
from io import BytesIO
import asyncio
import matplotlib.pyplot as plt
from matplotlib.ticker import For... | |
<reponame>mofeing/autoray<gh_stars>10-100
import importlib
import pytest
import autoray as ar
# find backends to tests
BACKENDS = [pytest.param("numpy")]
for lib in ["cupy", "dask", "tensorflow", "torch", "mars", "jax", "sparse"]:
if importlib.util.find_spec(lib):
BACKENDS.append(pytest.param(lib))
if lib == "j... | |
# -*- coding: utf-8 -*-
import csv
import os
import platform
import codecs
import re
import sys
from datetime import datetime
import pytest
import numpy as np
from pandas._libs.lib import Timestamp
import pandas as pd
import pandas.util.testing as tm
from pandas import DataFrame, Series, Index, MultiIndex
from pand... | |
from copy import deepcopy
from math import *
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.utils import shuffle
algorithms = ['MultiLayerPerceptron', 'LR', 'RandomForest', 'GaussianNB']
fair_algorithms = ['Feldman-' + algorithm for algorithm in algorithms]
all_algorithms = algorithms + ... | |
<gh_stars>1-10
from abc import ABCMeta
import tqdm
import copy
import numpy as np
import networkx as nx
import random
from dynsimf.models.components.Memory import MemoryConfiguration
from dynsimf.models.components.Memory import MemoryConfigurationType
from dynsimf.models.components.Update import Update
from dynsimf.mo... | |
<gh_stars>1-10
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..registry import LOSSES
from .utils import weight_reduce_loss, convert_to_one_hot
def cross_entropy(pred,
label,
weight=None,
reduction='mean',
avg_factor=None,
class_weight=None,
**kwargs):
r"""Calculate the CrossEntropy ... | |
The observable sequence that merges the elements of the
observable sequences.
"""
from .observable.merge import merge_
return merge_(*sources)
def never() -> Observable[Any]:
"""Returns a non-terminating observable sequence, which can be used
to denote an infinite duration (e.g. when using reactive joins).
.... | |
# coding=utf-8
"""Variant on standard library's cmd with extra features.
To use, simply import cmd2.Cmd instead of cmd.Cmd; use precisely as though you
were using the standard library's cmd, while enjoying the extra features.
Searchable command history (commands: "history")
Run commands from file, save to file, edit ... | |
state
self.provision_info = provision_info
self.control_server = grpc.server(
thread_pool_executor.shared_unbounded_instance())
self.control_port = self.control_server.add_insecure_port('[::]:0')
self.control_address = 'localhost:%s' % self.control_port
# Options to have no limits (-1) on the size of the message... | |
"""
Interactive Ansys
Maintained & Created by : <NAME>
"""
import os
import re
from datetime import datetime
import pexpect
import logging
import pandas as pd
from .utility_functions import return_value, calculate_skip_rows
class Ansys(object):
"""Ansys session class
Ansys class to create an interactive ansys ... | |
solar = solar.astype("float32", casting="same_kind")
solar.name = "solar"
solar.attrs["level"] = "surface"
solar.attrs["long_name"] = "Downward Short-Wave Radiation Flux"
solar.attrs["standard_name"] = "net_downward_shortwave_flux_in_air"
solar.attrs["units"] = "W/m^2"
with xarray.open_dataset(missing_hr["ds_path... | |
# The MIT License (MIT)
# Copyright (c) 2021-present foxwhite25
#
# 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, ... | |
optional
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:type _preload_content: bool, optional
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can ... | |
and cluster_data.gene_tree and gene_tree_scale > 0 and
# cluster_alg == "hierarchical" and MATRIX.ncol() > 1):
if(cluster_data.gene_tree and gene_tree_scale > 0 and
cluster_alg == "hierarchical" and MATRIX.ncol() > 1):
# Only add the dendrogram if hierarchical clustering was
# requested. If clustering not done, ... | |
'CM Mobile', 'zh': u('\u6da6\u8fc5\u901a\u4fe1'), 'zh_Hant': u('\u6f64\u8fc5\u901a\u4fe1')},
'852906':{'en': 'China Mobile', 'zh': u('\u4e2d\u56fd\u79fb\u52a8'), 'zh_Hant': u('\u4e2d\u570b\u79fb\u52d5')},
'852907':{'en': 'PCCW Mobile', 'zh': u('\u9999\u6e2f\u79fb\u52a8\u901a\u8baf'), 'zh_Hant': u('\u9999\u6e2f\u79f... | |
<filename>stagpy/_step.py
"""Implementation of Step objects.
Note:
This module and the classes it defines are internals of StagPy, they
should not be used in an external script. Instead, use the
:class:`~stagpy.stagyydata.StagyyData` class.
"""
from collections.abc import Mapping
from collections import namedtuple... | |
source: either a list of lines or a path to the source code
:param target: either save to this file
or return the generated documentation
:param fun: use ``#gen_<fun>(lns,**kw):`` to extract the documentation
:param kw: kw arguments to the ``gen_<fun>()`` function
::
>>> source=[i+'\\n' for i in """
... #def g... | |
MCOI.items()])
MCORWA_input = np.array([np.mean(val) for key, val in MCORWA.items()])
MCORSA_input = np.array([np.mean(val) for key, val in MCORSA.items()])
nMarks_input = np.array([np.mean(val) for key, val in nMarks.items()])
ObjN = np.array([int(i) for i in keys_input])
mask = ~np.any(np.isnan(tsne_input_norm)... | |
relationship(
"Tag",
)
def test_one(self):
Sample = self.classes.Sample
session = fixture_session()
user_sample_query = session.query(Sample)
unioned = user_sample_query.union(user_sample_query)
q = unioned.options(joinedload(Sample.tags)).limit(10)
self.assert_compile(
q,
"SELECT anon_1.anon_2_sample_i... | |
raise error.CorruptImageError("Unknown format " + str(g_object.format))
else:
assert 0, "not reachable"
def ischar(self, g_object):
g_char = self.special_g_object_safe(constants.SO_CHARACTER_CLASS)
return (self.ispointers(g_object) and g_object.g_class == g_char)
def isblockclosure(self, g_object):
g_closure =... | |
[]
else:
chroms = set(cliParser.chroms.split(","))
fs = cliParser.fnIn.split(",")
for f in fs:
if not os.path.isfile(f):
report = "Input file %s not exitst!" % f
logger.error(report)
return
if cliParser.trans:
cis = False
else:
cis = True
#parse BEDPE files into xy coordinates
if cliParser.format == "bed... | |
to a temporary
# file, the original file is deleted, and the temporary file is
# renamed to the original file name and reopened in the update
# mode. To a user, these two kinds of updating writeback seem
# to be the same, unless the optional argument in flush or
# close is set to 1.
del u[2]
u.flush()
# The wr... | |
#
# This file is part of LUNA.
#
# Copyright (c) 2020 <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-3-Clause
""" Integrated logic analysis helpers. """
import io
import os
import sys
import math
import unittest
import tempfile
import subprocess
from abc import ABCMeta, abstractmethod
from nmigen import Signal, Mo... | |
<filename>cutiepy/symbolic.py
'''
Computer Algebra Core
=====================
This module permits the creation of symbolic representation of mathematical
operations.
Implementation details
======================
The code here is meant to be simple at the expense of not being easy to
generalize or extend. Repetition ... | |
to see if a resource has changed, avoid overwriting objects with the same id if it does. Returns 304 with empty body if nothing has changed.
:param int since: Get entries after a timestamp.
:param int before: Get entries before a timestamp.
:param list[str] sort: Comma separeted list of fields to sort ascending on a... | |
<gh_stars>1-10
# Borrowed from https://github.com/ProGamerGov/pytorch-places
import torch
import torch.nn as nn
import torch.nn.functional as F
class GoogLeNetPlaces205(nn.Module):
def __init__(self):
super(GoogLeNetPlaces205, self).__init__()
self.conv1_7x7_s2 = nn.Conv2d(in_channels=3, out_channels=64, kernel_s... | |
<filename>src/pyquickhelper/sphinxext/sphinx_runpython_extension.py
# -*- coding: utf-8 -*-
"""
@file
@brief Defines runpython directives.
See `Tutorial: Writing a simple extension
<https://www.sphinx-doc.org/en/master/development/tutorials/helloworld.html>`_
"""
import sys
import os
from contextlib import redirect_std... | |
<reponame>ayush4921/pyami<filename>pyami/xml_lib.py
# from xml.etree import ElementTree as ET
import logging
logging.debug("loading xml_lib")
from lxml import etree as LXET
import os
from pathlib import Path
from file_lib import FileLib
from util import AmiLogger
# make leafnodes and copy remaning content as XML
TERMI... | |
'yì',
0x2639E: 'shān',
0x263A2: 'jí',
0x263A3: 'yān',
0x263A6: 'wù',
0x263A7: 'chún,dūn,dùn',
0x263A8: 'máng',
0x263AB: 'chún',
0x263AD: 'fú',
0x263AE: 'jiā',
0x263AF: 'gòu',
0x263B0: 'gú',
0x263B1: 'jiá',
0x263B5: 'xián',
0x263B7: 'jìn',
0x263B8: 'zì',
0x263B9: 'lóu',
0x263BC: 'gòu',
0x263C0: 'rén',
... | |
#!/usr/bin/env python3
"""
A script that imports and analyzes Garmin health device data into a database.
The data is either copied from a USB mounted Garmin device or downloaded from Garmin Connect.
"""
import logging
import sys
import argparse
import datetime
import os
import tempfile
import zipfile
import glob
fr... | |
(self < other)
def __le__(self, other):
return not (self > other)
def __ne__(self, other):
return not (self == other)
# Utility (class-)methods
def satisfies(self, sel):
"""Alias for `bool(sel.matches(self))` or `bool(SemSel(sel).matches(self))`.
See `SemSel.__init__()` and `SemSel.matches(*vers)` for possi... | |
import streamlit as st
import torch
import pickle
import os
from pathlib import Path
import yaml
import time
from seal import Ciphertext, \
Decryptor, \
Encryptor, \
EncryptionParameters, \
Evaluator, \
IntegerEncoder, \
FractionalEncoder, \
KeyGenerator, \
MemoryPoolHandle, \
Plaintext, \
SEALContext, \
Ev... | |
""" Control flow graph algorithms.
Functions present:
- dominators
- post dominators
- reachability
- dominator tree
- dominance frontier
"""
import logging
# TODO: this is possibly the third edition of flow graph code.. Merge at will!
from .digraph import DiGraph, DiNode
from . import lt
from .algorithm.fixed_poi... | |
range of [0,1]
two_sided percentile interval to highlight, which must be between
0 and 1 inclusive. For example, when ``q=.90``, the 5th and
95th percentile of the ultimate/reserve distribution will be
highlighted in the exhibit $(\frac{1 - q}{2}, \frac(1 + q}{2})$.
actuals_color: str
A color name or hexidecimal... | |
from collections import defaultdict, namedtuple
from collections.abc import Set
from dataclasses import dataclass
# unused?
from enum import Enum
from inspect import isclass
from itertools import chain, product
# remove after dev
from pprint import pprint
from typing import List
from uuid import UUID, uuid4
from warni... | |
similar levels
# of ability, so this might not be a problem in the long run. There is
# a similar problem where the random sampling results in all jurors
# producing the same responses for a given statement: this can be
# mitigated by increasing the jury size.
responses = []
for j, statement in enumerate(statemen... | |
opcode):
""" Implements the TAD (two's complement add) instruction """
self._ac += self.getArg(opcode)
# handle overflow
if (self._ac > 0o7777):
self._l = (~self._l) & 0o1
self._ac &= 0o7777
def op_isz(self, opcode):
""" Implements the ISZ (increment and skip if zero) instruction """
# Incremen... | |
0]
[ 0 x^2 + 1]
sage: V, from_V, to_V = L.vector_space(); V
Vector space of dimension 2 over Rational function field in x over Rational Field
sage: I.module().is_submodule(V)
True
"""
return self._module
def gens(self):
"""
Return a set of generators of this ideal.
EXAMPLES::
sage: K.<x> = FunctionField(... | |
<filename>geom.py
#!/usr/bin/env python3
# coding: utf-8
import math
from util import UniqueList, float_close, float_gt, float_lt
class Geometry():
__slots__ = []
def disjoint(self, other):
"""Return whether two geometries are spatially disjoint.
Two geometries are spatially disjoint if they have no contact
w... | |
<reponame>j-erler/sz_tools<filename>sz_tools/ilc.py
import numpy as np
import healpy as hp
import datetime
from astropy.io import fits
from astropy.io import ascii
from scipy import ndimage
import sz_tools as sz
import os.path
datapath = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data")
fwhm2sigma = 1/... | |
maximum number of Query Terms Suggestions
to be returned.
:param lang: List of strings to select the language to be used for result rendering
from a list of BCP 47 compliant language codes.
:param political_view: Toggle the political view.
:param show: Select additional fields to be rendered in the response. Pleas... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.