text stringlengths 3.07k 12.6k |
|---|
#!/usr/bin/python
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
"metadata_version": "0.1.0",
"status": ["preview"],
"supported_by": "community",
}
DOCUMENTATION = r"""
---
module: launchdarkly_user_segment_sync
short_description: Sync LaunchDar... |
"""
Utility functions for gene annotation
"""
import logging
import re
import urllib
from io import StringIO
import pandas as pd
def cog2str(cog):
"""
Get the full description for a COG category letter
Parameters
----------
cog : str
COG category letter
Returns
-------
str
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# created by restran on 2015/12/19
from __future__ import unicode_literals, absolute_import
import hmac
import logging
import random
import time
from base64 import urlsafe_b64encode
from hashlib import sha1
from future.utils import iteritems
from tornado.escape import to... |
from tkinter import *
from tkinter.ttk import *
from functools import partial
import zmq
from zmq import ssh
class configGUI(Tk):
btnNum = 0
btnCaptions = None
btnCommands = None
commandEntry = None
captionEntry = None
def __init__(self, btnNum, btnCaptions, btnCommands):
super().__i... |
from django.shortcuts import render, redirect
from django.core.exceptions import ValidationError
from django.db.models import ProtectedError
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from ..main.decorators import checkUserAccess
from ..main.errorFunctions import *
fro... |
from anchore_engine.subsys.events import Event, SystemEvent, UserEvent
_image_digest_resource_type = 'image_digest'
_image_tag_resource_type = 'image_tag'
_image_resource_type = 'image'
# Image user category events
class ImageVulnerabilityUpdate(UserEvent):
__event_type__ = 'image_vuln_update'
__resource_typ... |
#!/usr/bin/env python
import getopt
import signal
import sys
import os
import extdocker
import subprocess
running = True
headfoot_identifier = "DOCKER CONTAINERS"
header_identifier = "# === " + headfoot_identifier + " START ==="
footer_identifier = "# === " + headfoot_identifier + " END ==="
# Default: Hosts-file pat... |
# -*- coding: utf-8 -*-
# vim: ts=2 sw=2 et ai
###############################################################################
# Copyright (c) 2012,2021 <NAME> <EMAIL>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"... |
import json
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render... |
import operator
import numba
from numba.extending import (box, unbox, typeof_impl, register_model, models,
NativeValue, lower_builtin, lower_cast, overload,
type_callable, overload_method, intrinsic)
from numba.targets.imputils import impl_ret_new_ref, impl_ret_... |
import json, re, os
try:
from mitmproxy.models import HTTPResponse
except ImportError:
from mitmproxy.http import HTTPResponse
#from pprint import pprint
class Config:
def __init__(self):
self.initialized = False
self.config = {}
# Content type is handled separately
self.defaultHeaders = [
("Cache-Co... |
import csv
import logging
import os
import SimpleITK as sitk
import numpy as np
import radiomics
from radiomics import featureextractor
from filelock import FileLock
from scipy import ndimage
from random import randint
'''
This file contains functions which interact with the Pyradiomics library.
<NAME> 2020
... |
# coding: utf-8
#import networkx as nx
#import matplotlib.pyplot as plt
#import operator
#from collections import defaultdict
#from collections import Counter
#from collections import deque
# from functools import reduce
# from math import log
#from itertools import product
import copy
import operator
import re
import ... |
"""Sensor classes represent modbus registers for an inverter."""
from __future__ import annotations
import logging
from math import modf
from typing import Any, Dict, Generator, List, Sequence, Tuple, Union
import attr
_LOGGER = logging.getLogger(__name__)
def ensure_tuple(val: Any) -> Tuple[int]:
"""Return a ... |
import curses
from networkmonitor import Config, Ping, TerminalOutput
class CursesHelper():
def __init__(self, stdscr):
#self.stdscr = curses.initscr()
#curses.noecho()
#curses.cbreak()
#self.stdscr.keypad(True)
self.stdscr = stdscr
curses.start_color()
... |
import urllib2
import urlparse
from xml.etree import ElementTree
from django.http import HttpResponse
from tastypie.authentication import Authentication
from tastypie.authorization import Authorization
from tastypie.resources import Resource
from tastypie.serializers import Serializer
from tastypie.throttle import Cach... |
#!/usr/bin/env python3
# last modified by handyc on 12 Nov 2021
# klurp genetic algorithm system for text alignment
# this file is the outermost layer of the klurp system
# which parses user input and invokes the population manager
import sys
import os
import getpass
import glob
from pathlib import Path
import dat... |
# Variaveis: Para declararmos uma varíavel em python é um processo muito simples e fácil, basta dar um nome para a varíavel e definir um valor com algum dos tipos primitivos? String, inteiro, float, bool
# Exemplos
nome = "gabriela";
idade = 32;
altura = 1.75;
ligado = False;
#variaveis na pratica:
#calcular a soma ... |
from keras.datasets import cifar10
from keras.layers import Input, Dense, Reshape, Flatten, Dropout
from keras.layers import BatchNormalization, Activation, ZeroPadding2D
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.convolutional import UpSampling2D, Conv2D
from keras.models import Model
fr... |
from modules import set_placeholders, set_queue, create_graph
from modules import start_queue_threads
from preprocess import *
from default_settings import model_settings, set_model_settings
from datetime import datetime
from sklearn import svm
from sklearn.model_selection import train_test_split
import sklearn.metric... |
#!/usr/bin/env python
# filename: outputs.py
#
# Copyright (c) 2015 <NAME>
# License: The MIT license (http://opensource.org/licenses/MIT)
#
# 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 wi... |
# -*- coding: utf-8 -*-
""".. moduleauthor:: <NAME>"""
from dataclasses import dataclass
from enum import Enum
from typing import Dict, List, Tuple, final
from rewowr.rewowr_library.check_process.errors.custom_errors import CheckWorkerPathError
from rewowr.rewowr_library.check_process.check_functions.check_worker impo... |
"""Test NotesApp backend for its rest api."""
import requests
import unittest
import subprocess
import time
import json
PORT = 3456
URL = "http://localhost:" + str(PORT)
def get(path):
"""Perform Get request."""
return requests.get(URL + path)
def put(path, it):
"""Perform Put request."""
return r... |
import textwrap
import unittest
from itertools import chain, combinations
from aimacode.utils import expr
from aimacode.planning import Action
from aimacode.search import Node
from example_have_cake import have_cake
from air_cargo_problems import (
air_cargo_p1, air_cargo_p2, air_cargo_p3, air_cargo_p4
)
from my... |
# -*- coding: utf-8 -*-
import pybayes as pb
import numpy as np
class UniIntPdf(pb.UniPdf):
def __init__(self, a, b, rv = None, cheat=False):
super(UniIntPdf, self).__init__(a, b, rv)
self.cheat = cheat
def sample(self, cond = None):
return np.round(super(UniIntPdf, self).sample(cond... |
import argparse
import tensorflow as tf
from poseModels import HumanPoseModel
import cv2
import json
import numpy as np
import pandas as pd
import pickle
def save_as_json(serializable_data, file_path):
output = json.dumps(serializable_data)
with open(file_path, "w") as f:
f.write(output)
def classif... |
import json
import matplotlib.pyplot as plt
import seaborn as sb
import numpy as np
import torch
from torch import nn, optim
from torch.nn import functional as F
from torchvision import datasets, transforms, models
from PIL import Image
def load_data(data_dir):
train_dir = data_dir + '/train'
valid_dir = da... |
from datetime import date
from io import StringIO
import unittest
import web_backend.utils.pubmed as pubmed
class TestCountGroupedIds(unittest.TestCase):
@staticmethod
def stub_term_bucket_mapping():
return {
"Philadelphia": {"Cities"},
"Boston": {"Cities"},
"Finlan... |
# -*- coding: utf-8 -*-
"""
Module implementing dialogDrawCurve.
"""
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from Ui_drawCurve import Ui_Dialog
from serial_ctrl import *
from SettingCtrl import *
import numpy as np
import random
import re
import time
from mpl_toolkits.mplot3d import Axes3D
from m... |
'''
Example Resistor test
================================================================
This is a simple example of using the TMPL framework to measure a
resistor.
The resistor will be measured under different conditions of temperature
and humidity. Also different types of resistor will be measured.
As this is an e... |
# This code scraps through the advertisement picture from a newspaper and extracts a text separately ad by ad.
# Imports the Google Cloud client library
import os
import statistics
from google.cloud import vision
import io
import cv2
import numpy as np
from PIL import Image, ImageDraw
import pandas as pd
def get_... |
# -*- mode: python; coding: utf-8 -*-
import os
import fcntl
import Queue
import select
import threading
import sublime
import sublime_plugin
from lldb_wrappers import thread_created
from debug import debug, debugMonitors
from root_objects import lldb_views_update, del_lldb_view, \
... |
#!/usr/bin/env python
'Corresponds to a glyph, for analysis purposes, for GDL generation'
__url__ = 'http://github.com/silnrsi/pysilfont'
__copyright__ = 'Copyright (c) 2012 SIL International (http://www.sil.org)'
__license__ = 'Released under the MIT License (http://opensource.org/licenses/MIT)'
import re, traceback
... |
# DUCK
# Aircraft proximity alerts for DUMP1090
# https://github.com/cjeholm/DUCK
# Version 1.0
import json
import time
import os
import urllib.request
import math
if os.name == 'nt':
import winsound
# User settings
alert_alt = 1000
play_sound = True
metric = True
refresh_timer = 2
timeout = 10
json_source = "ht... |
# -*- coding: utf-8 -*-
"""
@name: new_program.py
@vers: 0.1.0
@author: dthor
@created: Tue Dec 30 12:46:46 2014
@descr: A new file
Usage:
new_program.py
Options:
-h --help # Show this screen.
--version # Show version.
"""
from __... |
"""Defines tests for the @observe decorator.
"""
from typing import Any, Dict
from unittest import TestCase
from mock import Mock, patch
from atl_observe import observe
from atl_observe.lib.metrics import (IMetric, IncrementNotImplementedError,
TimingNotTImplementedError)
class ... |
import os
import sys
import subprocess
import urllib
import re
import glob
import shutil
import json
import tempfile
import requests
from bs4 import BeautifulSoup
from .langinfo import LangInfo
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
def extract_to_txt(iso_639_3: str, output_filename: str):
"""... |
#!/usr/bin/python3
# Exploit Title: Nagios-XI 5.5.6 RCE
# Exploit Author: (m4ud)
import http.server
import ssl
import sys
import requests
import threading
import time
import subprocess
from optparse import OptionParser
from OpenSSL import crypto, SSL
def get_cert(
emailAddress="<EMAIL>",
commonName="m4ud",
... |
import sys
from functools import partial
import argparse
from cmd import Cmd
from .cpu import INSTRUCTION_SET
from .printer.instr import InstrJsonPrinter
from .printer.instr import InstrPrettyPrinter
class ArgumentError(Exception):
pass
class ArgumentParser(argparse.ArgumentParser):
def exit(self, status=0,... |
import ruamel.yaml
import subprocess
import rospkg
import rosdep2
import os
import catkin_pkg.package
import json
import datetime
import copy
yaml = ruamel.yaml.YAML()
yaml.indent(mapping=2, sequence=4, offset=2)
def convert_os_override_option():
return 'conda', '10'
try:
# json_result = subprocess.check_out... |
import cv2
import argparse
import numpy as np
import distance_to_camera
from centroidtracker import CentroidTracker
from centroidtracker import RingBuffer
from collections import OrderedDict
ap = argparse.ArgumentParser()
ap.add_argument('-v', '--video', required=False,
help='path to input image')
ap.a... |
import os
import sys
import time
import requests
from argparse import ArgumentParser
import multiprocessing
from xml.dom.minidom import parseString
import json
import logging
def parse_metadata(xml_metadata, output_file):
xml_tree = parseString(xml_metadata)
id = xml_tree.getElementsByTagName('id')[0].childN... |
import discord
from discord.ext import commands
from discord.ext.commands import CommandNotFound
from discord.utils import get
import asyncio
import random
import time
import os
import requests
import json
import re
def save(savemap, file):
with open(file, "w") as f:
json.dump(savemap, f)
def... |
import os
import pytest
import jsonpickle
from enum import Enum
import json as oldJson
# Simple Enum Class
class Type(Enum):
ONE = 1
TWO = 2
# Class to test Enum issue with
class TestEnumObject:
def __init__(self, num, objectType):
self.num = num
self.type = objectType
def __repr__(... |
# Copyright (c) <NAME> (<EMAIL>) and <NAME> (<EMAIL>)
#
# Please cite the following papers if you use any part of the code.
# - <NAME>, <NAME>, <NAME>, Deep Global Registration, CVPR 2020
# - <NAME>, <NAME>, <NAME>, Fully Convolutional Geometric Features, ICCV 2019
# - <NAME>, <NAME>, <NAME>, 4D Spatio-Temporal ConvNet... |
from flask import (Blueprint, flash, g, redirect, render_template, request, url_for)
from werkzeug.security import check_password_hash, generate_password_hash
# from datetime import datetime
from foodhubsg.auth import login_required
from foodhubsg.db import get_db
from foodhubsg.classes import *
bp = Blueprint('user... |
"""Track packages from dhl via api"""
from urllib.parse import urlparse
import json
import logging
from datetime import timedelta
import requests
import voluptuous as vol
#from homeassistant.helpers.entity import Entity
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.components.senso... |
import logging
from typing import Dict, List
from django.conf import settings
from apps.authentication.models import OnlineUser as User
from apps.gsuite.mail_syncer.utils import (
get_excess_groups_for_user,
get_excess_users_in_g_suite,
get_g_suite_users_for_group,
get_missing_g_suite_group_names_for_... |
# ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~
# MIT License
#
# Copyright (c) 2022 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without res... |
from collections import defaultdict
from types import SimpleNamespace
from typing import Union
import torch
import numpy as np
import warnings
from msdm.core.problemclasses.mdp import \
TabularMarkovDecisionProcess, TabularPolicy
from msdm.core.algorithmclasses import Plans, PlanningResult
def clamp_zero(tensor):
... |
import sys
import weakref
from _pydev_imps._pydev_saved_modules import thread
from _pydevd_bundle.pydevd_constants import STATE_RUN, PYTHON_SUSPEND, dict_iter_items
from _pydevd_bundle.pydevd_frame import PyDBFrame
#======================================================================================================... |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Parses a JSON request log created by log_requests.py."""
import collections
import json
import operator
import urlparse
Timing = collections.namedtuple(... |
from . import texcommands
import panflute as pf
import sys
import os
from xml.sax.saxutils import quoteattr
import locale
from datetime import date
inline_const_commands = {
r'newLine':
pf.LineBreak(),
r'tabL':
pf.RawInline(
'<w:r><w:ptab w:relativeTo="margin" w:alignment="left" w:leader="none"... |
# -*- coding: UTF-8 -*-
import tensorflow as tf
import numpy as np
import sys
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, '../utils'))
import tf_util
def input_transform_net(point_cloud, is_training, bn_decay=None, K=3):
""" Input... |
"""
Import data from django-manolo database into Manolo-v2
"""
import codecs
import dataset
import datetime
import json
import hashlib
import re
import sys
import os.path
import argparse
from unidecode import unidecode
import pyprind
def get_db_credentials(settings):
if settings == 'local':
from manolo.s... |
from node import Node
class NodeNetwork(object):
''' Handles a collection of nodes in a grid. '''
def __init__(self, d1=5, d2=9):
''' Initialize stuff like the node grid. '''
# TODO?: Consider using numpy arrays
self.node_grid = [[None for b in range(0,d2)] for a in range(0,d1)]
... |
# this project is licensed under the WTFPLv2, see COPYING.txt for details
from contextlib import contextmanager
import re
from PyQt5.QtCore import QObject, QTimer, QElapsedTimer
from ..connector import registerSignal, CategoryMixin
from ..widgets.editor import HasWeakEditorMixin, SciModification
from ..widgets impor... |
from typing import Dict, List, NamedTuple, Optional, Tuple
from app import db
from app.models import Project, Schedule, User, Team
from sqlalchemy import func
class WeekProject(NamedTuple):
week: int
project_id: int
class WeekUser(NamedTuple):
week: int
user_id: int
def set_schedule(
user_id:... |
import numpy as np
import torch
import torch.nn as nn
from torch.distributions import Normal, Bernoulli, kl_divergence as kl
import torch.nn.functional as F
Downsample = 1000
Downsample2 = 500
MID_LAYER = 100
FIRST_LAYER = 1000
def dice_loss(pred, target):
pred = torch.sigmoid(pred)
smooth = 1e-13
iflat ... |
"""
Functions for creating, activating and maintaining conda environments.
"""
import subprocess
import os
from pathlib import Path
from ..config import config
def get_conda_envs():
"""Get a list of all conda environments on the system.
Returns
-------
list
Name (str) of all the conda enviro... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# スペクトラム領域での演算を行うフィルタ
# FFTとIFFTの間で使う
import numpy as np
from filter.base import FilterBase, FilterRoot, InheritCh
# 音程変更フィルタ
# スペクトラムをずらす
# d > 0 で高周波数域にずらす
# d < 0 で低周波数域にずらす
class SpectrumShift(InheritCh):
def __init__(self, source: FilterBase, d: int):
... |
import operator
from math import sin, cos, sqrt, atan2, radians
from src.SuperMarket import SuperMarket
def getUserLocation(user):
"""
This function is used to call the user's method getlocation that returns his gps coordinates
:param user: a user
:return: the user's location
"""
return user... |
#Utility
import Visualisierungen
import prettytable
import pandas as pd
import json
import re
from bokeh.io import output_notebook, show
from bokeh.models import GMapOptions,HoverTool,ColumnDataSource
from bokeh.plotting import gmap
import bokeh.palettes as bp
def string2list(string,with_None=True):
p = re.compil... |
# owner_mail.py / IsaacII Discord Bot
# Author: https://github.com/doncato
# Created on: 10/07/21
import os,discord,json,random,time
from discord.ext import commands
class mail(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.filepath = os.path.join(os.path.dirname(__file__), '../settin... |
import functools
import tensorflow as tf
import tensorflow_addons as tfa
def sortkey(x):
sp = x.split('_')
return int(sp[2])*100000+int(sp[3])
def filter_fn(x, y):
return tf.reduce_sum(y) > 0 # or tf.random.uniform([],0,1) < 0.05
def process_pathnames(fname, label_path):
''' fetch the image data
... |
import bpy
import json
import math
import mathutils
import sys
cubeTemplate = bpy.data.collections['cube-template']
cubeletSize = 1.02
cubeSize = 3 * cubeletSize
def currentKeyframe():
return bpy.data.scenes['Scene'].frame_current
def setKeyframe(frame):
return bpy.data.scenes['Scene'].frame_set(frame)
d... |
#!/usr/bin/env python
#
# Copyright (c) 2005-2009 <NAME>
#
# Distributed under the MIT license (See accompanying file
# LICENSE.txt or copy at http://jagpdf.org/LICENSE.txt)
#
import jagpdf
import sys
import os
import jag.testlib as testlib
g_font = testlib.EasyFontTTF()
#raw_input("attach")
def do_some(doc):
... |
#!/usr/bin/env python3
"""
Intcode processor simulator
"""
from typing import Optional
from copy import copy
class IntCode:
"""An IntCode instance represents a unique intcode processor.
The processor runs in asynchronous style, running until it exits
normally, or needs to wait for input to become availabl... |
#!/usr/bin/env python
# coding: utf-8
import requests
import json
import threading
from queue import Queue
import time
import os
lock_player = threading.Lock()
lock_match = threading.Lock()
api_key = "### PUT YOUR PUBG API KEY HERE ###"
class players_matches(object):
def __init__(self, data=[], flag='p'):
... |
# Copyright 2020-2021 Foreseeti AB <https://foreseeti.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
#!/usr/bin/env python3
from __future__ import print_function
import fasm
import argparse
import json
import os
import os.path
from prjxray import fasm_assembler
from prjxray.db import Database
from prjxray.roi import Roi
class FASMSyntaxError(SyntaxError):
pass
def dump_frames_verbose(frames):
print()
... |
from collections import defaultdict
from functools import wraps
from lru import LRU
import math
BoundCache = defaultdict(lambda: LRU(3000))
class Color:
ZERO = (0, 0, 0, 0)
WHITE = (0, 0, 1, 3500)
EMPTIES = (ZERO, None)
@classmethod
def dead(kls, color):
return color in kls.EMPTIES or c... |
import itertools
import time
start_time = time.process_time()
def palindrome_found(num):
print("%08.4f: %s" % (time.process_time() - start_time, num))
def check_if_binary_palindrome(num):
bin_str = bin(num)[2:]
if bin_str == bin_str[::-1]:
palindrome_found(num)
def is_in_table(subtraction_suffix... |
#!/usr/bin/env python
# coding: utf-8
# # pyLectureMultiModalAnalysis
#
# ## Feature extraction from video segment
#
# ### Functions: 4
# #### RandomVector(), video2frame(), frame2features(), Video2feature()
#
# ### Author: <NAME>
# ## RandomVector()
# In[51]:
def RandomVector(trainmode=True,sz=100, debug=False... |
# -*- encoding: utf-8 -*-
"""
Weekly rebalance
1. pe ratio < 15
2. pb ratio < 1.5
3. inc_earning_per_share > 0
4. inc_profit_before_tax > 0
5. current_ratio > 2
6. quick_ratio > 1
universe : hs300
init_balance = 1e8
start_date 20140101
end_date 20170301
"""
from __future__ import print_function
from __future__ impo... |
import unittest
import uuid
import tempfile
from pathlib import Path
import numpy as np
import globus_sdk
from ibllib.misc import version
from ibllib.io import hashfile, params
from oneibl.one import ONE
from oneibl.patcher import SSHPatcher, GlobusPatcher, FTPPatcher
_ONE = ONE(base_url='https://test.alyx.internat... |
"""
Tensorflow implementation of functions to perform the Cholesky factorization
of a block tridiagonal matrix. Ported from <NAME>'s implementation here:
https://github.com/earcher/vilds/blob/master/code/lib/blk_tridiag_chol_tools.py
"""
import tensorflow as tf
def blk_tridiag_chol(A, B):
"""
Compute the cho... |
import re
import os
import os.path as osp
import argparse
from copy import deepcopy
from pprint import pprint
def analyze_patterns(fd):
"""analyze all patterns (discard extension) of the given directory, and returns them (as string for re.compile -> number of matches)
"""
fns = os.listdir(fd) # list of o... |
#!/usr/bin/python
from PySide2.QtCore import Slot
__author__ = "<NAME>, <NAME>"
__copyright__ = "Copyright 2019, Brexit boy and SaLmon king"
__credits__ = ["<NAME>, <NAME>"]
__license__ = "Apache License"
__version__ = "2.0"
__maintainer__ = "<NAME>, <NAME>"
__status__ = "Development"
import sys
import logging
import... |
from util import resolve, genson_dumps
class GenSONBinaryOp:
def __init__(self, a, b, op):
self.a = a
self.b = b
self.op = op
def __genson_eval__(self, context):
res_a = resolve(self.a, context)
res_b = resolve(self.b, context)
if self.op is '+':
... |
# coding=utf-8
# Copyright 2019 The Google Research Authors.
# Modified Copyright 2020 by <NAME> and <NAME>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/lice... |
import collections
import copy
import os
from urllib.parse import urlsplit
import munge
import munge.util
# this wouldn't work with tabular data
# need metaclass to allow users to set info once on class
# TODO rename to BaseConfig, set standard setup for Config?
class Config(collections.abc.MutableMapping):
"""
... |
from datanodes.core.utils import dumpException
from datanodes.graphics.graphics_scene import GraphicsScene
from datanodes.core.node_serializer import Serializer
from datanodes.core.node_node import Node
from datanodes.core.node_edge import Edge
from datanodes.core.node_socket import Socket
import json, os
from collecti... |
import datetime
import re
from dateutil import parser
import phonenumbers
from .utils import memoize
class DataType(object):
super_types = []
SIMILARITY_MATCH_THRESHOLD = .95
def __init__(self, **kwargs):
pass
def validate_and_clean(self, s):
if not s:
return None
... |
#!/usr/bin/env python
# Copyright 2018 National Technology & Engineering Solutions of Sandia, LLC
# (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
# Government retains certain rights in this software.
import os
import re
from .errors import TestSpecError
from .wordexpr import WordExpression, ... |
import time
from decimal import Decimal, InvalidOperation
from typing import Dict, List, Union
import dateutil.parser
from .utils import D
order_vocab = frozenset([
'client_oid', 'type', 'side', 'product_id', 'stp',
'price', 'size', 'time_in_force', 'cancel_after',
'post_only', 'funds', 'overdraft_enabl... |
"""Change instructions having only constant operands to a constant.
This pass tends to leave dead instructions, so dead_inst_elim should
be run after."""
from spirv_tools import ir
def transform_1op_componentwise(module, transform, type_id, const_inst):
"""Helper function for transform_componentwise)."""
if ... |
"""
Module to work with result data
"""
import glob
import collections
import logging
import os
import shutil
from typing import Dict
import pandas as pd
import numpy as np
import tensorflow as tf
import settings
clinical = None
# Get the mixed results
def all_results(path, select_type, predictions=False, elem_fol... |
"""
Google style docstring parser.
"""
import re
import inspect
from typing import Any, Dict, Optional, List, Tuple
from enum import Enum
from textwrap import dedent
from nb_autodoc.schema import DocstringParam, DocstringSection
class _DocstringSlot(Enum):
MODULE = 0
VARIABLE = 1
FUNCTION = 2
CLASS =... |
"""
TencentBlueKing is pleased to support the open source community by making
蓝鲸智云PaaS平台社区版 (BlueKing PaaSCommunity Edition) available.
Copyright (C) 2017-2018 THL A29 Limited,
a Tencent company. All rights reserved.
Licensed under the MIT License (the "License");
you may not use this file except in compliance with the... |
# Provides methods for manipulating text styling in specific terminals.
# Uses a basic chaining method where text properties are added by calling
# methods with related names.
#
# For example, to print "Hello, world!" in red:
# print pyfancy().red("Hello, world!").get()
#
# Styles can be changed for different text co... |
# coding: utf-8
from __future__ import print_function, division, absolute_import
import operator
import sys
import routing
from xbmcgui import ListItem
from xbmcplugin import (addDirectoryItem, endOfDirectory, setResolvedUrl,
setContent)
from resources.lib import http, kodi, settings
from resources.lib.helpers i... |
# standard libraries
import json
import os
# third-party libraries
import numpy as np
import pytest
import torch
import torch.nn as nn
# project libraries
from speech.models.ctc_model_train import CTC_train
import speech.loader as loader
from speech.utils.compat import get_main_dir_path
from speech.utils.d... |
NOT_ACCEPTED_DETAILS = ["", "None", None]
colors = ["#2a2d34", "#009ddc", "#f26430", "#6761a8", "#009b72"]
class Member:
def __init__(
self, username: str, name: str, love: str, location: str, avatar: str, importance: str, community: int
):
self.username = username if username not in NOT_ACCE... |
# Author: <NAME>
# Author: <NAME>
#
# For license information, see LICENSE.txt
"""
Implements functions for simulating time dependent Hawkes process following the Twitter model.
Provides different functions for simulating counts of follower, in the simplest approach they are extracted from a file
containing real ... |
'''
Table of Contents
Functions and Interdependencies:
butter_bandpass
butter_bandpass_filter
- butter_bandpass
mtaper_specgram
simple_cwt
'''
import scipy.signal
import numpy as np
import matplotlib.pyplot as plt
import pywt
def butter_bandpass(lowcut, highcut, fs, order=5, plot_pref=True):... |
"""
Script for translating the MIT Street Scenes Dataset annotation to BBTXT format.
A BBTXT file is formatted like this:
filename label confidence xmin ymin xmax ymax
filename label confidence xmin ymin xmax ymax
filename label confidence xmin ymin xmax ymax
...
-------------------------------------------------------... |
""" Image generation and manipulation routines"""
from __future__ import print_function, absolute_import, division, unicode_literals
import numpy as np
from astropy.wcs import WCS
from astropy.wcs.utils import proj_plane_pixel_scales
from kcwitools import plot as kp
from copy import deepcopy
import pdb
from scipy.stats... |
#------------------------------------------------------------------------------
# Script Preflight
#------------------------------------------------------------------------------
# this plugin requires Python 3
try:
import os
import sys
import glob
import json
import shutil
import zipfile
i... |
# coding: utf-8
import re
from findaconf import db
from flask.ext.login import UserMixin
from hashlib import md5, sha512
from os import urandom
from uuid import uuid4
conferences_keywords = db.Table(
'conferences_keywords',
db.metadata,
db.Column('conference_id', db.Integer, db.ForeignKey('conference.id')... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.