text stringlengths 3.07k 12.6k |
|---|
import sys
import os
try:
import configparser
except:
import ConfigParser as configparser
import logging
# import json
import datetime
import argparse
import csv
import boto3
from get_solr_json import get_solr_json
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
def get_solr_docs(solr_ur... |
# Copyright (c) 2020, 2021 The Linux Foundation
#
# SPDX-License-Identifier: Apache-2.0
from datetime import datetime
from west import log
from zspdx.util import getHashes
# Output tag-value SPDX 2.2 content for the given Relationship object.
# Arguments:
# 1) f: file handle for SPDX document
# 2) rln: Relation... |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.serializers import serialize, deserialize
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import redirect
from django.views.generic import FormView
from accounts.models import BaseUser
from database.forms import... |
"""Standard Light-node types"""
from OpenGL.GL import *
from math import pi
from vrml.vrml97 import basenodes, nodetypes
from vrml.vrml97 import transformmatrix
from vrml import node
from OpenGLContext.arrays import array, dot, identity
from OpenGLContext import vectorutilities
class Light(object ):#nodetypes.Light, n... |
# -*- coding: utf-8 -*-
"""
This module will provide a plugin for Darjeeling that adds CMT support.
"""
__all__ = ('StartTest',)
from typing import (Tuple, Dict, Any, Sequence, NoReturn, Mapping, Iterator,
Optional, Callable)
import os
import attr
import bugzoo
import darjeeling
from darjeeling im... |
"""
The Specializer is responsible for loading up sourcecode,
specializing code-templates for Externs and possibly other
things down the road.
"""
# pylint: disable=no-member
# The ndarray member is added dynamically and therefore not visible to pylint.
import logging
import os
import numpy as np
from py... |
import time
from functools import wraps
import os
import sys
import traceback
import _ctypes
IS_CUS_ENABLE = True
STDOUT = sys.stdout
#python setup.py sdist bdist_wheel
#python -m twine upload dist/*
def set_cus_enable():
global IS_CUS_ENABLE
IS_CUS_ENABLE = True
def set_cus_disable():
global IS_CUS_EN... |
import os, glob
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import javabridge
import bioformats
def init_vm():
javabridge.start_vm(class_path=bioformats.JARS)
#remove annoying logs
myloglevel="ERROR" # user string argument for logLevel.
rootLoggerName = javabridge.get_static_field("... |
"""
HAProxy SPOA - Modsecurity and Python
This is a heavily Work in Progress
Run this with the spoa binary, like:
RULES=modsec-rules.conf ./spoa -f modsecurity-spoa.py
"""
import logging
import os
import spoa
import sys
import ModSecurity
import time
import json
from pprint import pprint
class modsectransaction():
... |
from typing import List, Optional, Union, cast
import torch
from torch import nn
from .base import ContinuousQFunction, DiscreteQFunction
def _reduce_ensemble(
y: torch.Tensor, reduction: str = "min", dim: int = 0, lam: float = 0.75
) -> torch.Tensor:
if reduction == "min":
return y.min(dim=dim).val... |
import codecs
from os import replace
from pathlib import Path
from typing import Callable, Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
from scipy import sparse, stats
from sklearn.model_selection import train_test_split
def create_validation_dataset(test: np.ndarray, val_size: float, random_sta... |
import pefile
from os import listdir
from os.path import isfile, join
from unicorn import UC_PROT_EXEC, UC_PROT_READ, UC_PROT_NONE, UC_PROT_WRITE
from utility import *
class Target_PEFile:
"""
Class to represent a PE file that is the target of the ROP exploit.
Attributes:
path (str): the PE fil... |
import argparse
import cv2
import json
import numpy as np
import os
import pickle
import torch
from argparse import Namespace
from scipy.special import softmax
from sklearn.externals import joblib
from pyquaternion import Quaternion
from tqdm import tqdm
from network import CameraBranch
class Camera_Branch_Inferenc... |
# For more details, see
# http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#declare-a-mapping
from anthill.framework.db import db
from anthill.framework.utils import timezone
from anthill.framework.utils.asynchronous import as_future, thread_pool_exec as future_exec
from anthill.framework.utils.translation import ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: Yizhong
# created_at: 10/27/2016 下午8:34
import numpy
class Performance(object):
def __init__(self, percision, recall, hit_num):
self.percision = percision
self.recall = recall
self.hit_num = hit_num
class Metrics(object):
def _... |
import multiprocessing
import os
import inspect
import json
import tempfile
import sys
from calamari_ocr.ocr import CrossFold
from calamari_ocr.utils.multiprocessing import prefix_run_command, run
# path to the dir of this script to automatically detect the training script
this_absdir = os.path.dirname(os.path.abspat... |
#! /usr/bin/env python
import sys
import getopt
import os.path
import logging
import random
# Intrapackage imports
libpath = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))
if os.path.isdir(libpath):
sys.path.insert(0, libpath)
import pyx12
import pyx12.x12file
import pyx12.x12context
import pyx... |
'''
@author: rtermondt
'''
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import Context
from django.template import RequestContext
from django.template.loader import get_template
from django.db import IntegrityError
from django.db import ... |
import numpy as np
import warnings
from scipy.ndimage.interpolation import zoom
import torch
import math
import copy
import cv2
from skimage import measure
import pandas as pd
def resample(imgs, spacing, new_spacing, order=2):
if len(imgs.shape) == 3:
new_shape = np.round(imgs.shape * spacing / new_spacing... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
Apply batch effect labels to VCF from Talkowski SV pipeline
"""
import argparse
import sys
import pysam
import csv
def reclassify_record(record, reclass, plus_samples):
if 'PCRPLUS_ENRICHED' in reclass:
record.filter.add('PCRPLUS_ENRICHED')
if 'PC... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class LocalAwareAttention(nn.Module):
'''
Local Aware Attention Module
'''
def __init__(self, kernel_size=4, stride=4, beta=0.07):
super(LocalAwareAttention, self).__init__()
# Module Network Parameters
self.... |
'''
@author: MRB
'''
import socket
import threading
import time
import os
from gbn import SendingWindow, RecvingWindow
import json
from args import args
from utils import *
from gbn import *
file_in = 'resource/Harry Potter.txt'
ip = '127.0.0.1' # 服务器ip和端口
port1, port2, port3, port4 = args.port1, args.port2, args.p... |
import cv2
from pygame import mixer
import pandas as pd
from config import GameConfig
import time
config = GameConfig()
def play_music(music_file, time=0.0): # music 함수
mixer.init()
mixer.music.load(music_file)
mixer.music.play(1, time)
# clock = pygame.time.Clock()
# clock.tick(10)
def play_s... |
#!/usr/bin/env python2
'''
description: Convert directory with downloaded zipped KNMI ascii files to
netCDF format. Station information is obtained from a csv file.
Creation of the csv file and downloading of the KNMI data is
performed in another script (knmi_getdata.py).
aut... |
#! /usr/local/bin/python
# ! -*- encoding:utf-8 -*-
from pathlib import Path
import pandas as pd
import numpy as np
import random
import os
import argparse
proj_path = Path(__file__).parent.resolve().parent.resolve().parent.resolve()
data_path = proj_path / 'data' / 'PPP'
def read_csv(data_file, dataset):
cci_la... |
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import ListView, DetailView
from django.views.generic.edit import UpdateView, DeleteView, CreateView
from django.urls import reverse_lazy
from django.template.loader import render_to_string
from .forms import Articl... |
import glob
from pathlib import Path
import json
import re
import os
import numpy as np
import pandas as pd
from isochrones.models import StellarModelGrid, ModelGridInterpolator
from isochrones.mist.models import MISTEvolutionTrackGrid
from isochrones.mist.bc import MISTBolometricCorrectionGrid
from isochrones.mags i... |
# DESCRIPTION: The classes that pertain to the UI and GUI.
# 50726f6772616d6d696e6720697320627265616b696e67206f66206f6e652062696720696d706f
# 737369626c65207461736b20696e746f207365766572616c207665727920736d616c6c20706f73
# 7369626c65207461736b732e
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MAIN~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
from django.shortcuts import render,redirect
from django.http import HttpResponseNotFound
from .models import Cart,Shipment
from product.models import Product
from account.models import Address
from django.contrib.auth.models import User,auth
def cart_data_add(cid):
data = Cart.objects.filter(customer_id=cid,shipm... |
import random
def nums_compressed(nums: list[int]) -> tuple[list[int], list[int]]:
"""Sums up consecutive pairs and returns new list and nums removed
>>> nums_compressed([2, 2, 4, 4, 4, 8])
([4, 8, 4, 8], [2, 4])
"""
# Processes nums as a stack with the first element at the top
stack = nums[:... |
import random
import os
import numpy as np
from scipy.ndimage.filters import median_filter
import os
import random
import numpy as np
from scipy.ndimage.filters import median_filter
def gaussian_noise(img, mean=0, sigma=0.03):
img = img.copy()
noise = np.random.normal(mean, sigma, img.shape)
mask_overflo... |
import nltk
import os
import re
def get_filename(full_path):
'''Given a full absolute path to a file, return the filename only (including extension).
If path separators are not present, return the original argument.'''
# Automatically detect the default OS path separator (Windows-style or
... |
import os
from parglare import GLRParser, Grammar, NodeNonTerm, NodeTerm, REDUCE
class CParser:
def __init__(self):
self._glr = None
self._setup_parser()
self.user_defined_types = set()
def _setup_parser(self):
"""Setup parser."""
file_path = os.path.realpath(os.path... |
import itertools
import json
from django.http import HttpResponse, Http404
from django.shortcuts import get_object_or_404
from django.template.defaultfilters import date
from django.urls import reverse
from django.utils.timezone import now
from django.views import View
from django.views.decorators.cache import cache_p... |
"""
Data module for configuration, data storage and file manipulation
"""
import os
import sys
import yaml
import platform
import shutil
from datetime import date
from pathlib import Path
from typing import List, Dict, Any
class Account:
"""
Helper class for Config
Account:
user_id: string
... |
from functools import reduce
def test_find_longest_sequence():
"""
Given an array L,
find the position p and length k which
- all elements to the left of p from p-k position are in ascending order
- all elements to the right of p until p+k position are in descending order
- and L[p] is the biggest a... |
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2010 Camptocamp SA (http://www.camptocamp.com)
# All Right Reserved
#
# Author : <NAME> (Camptocamp)
#
# WARNING: This program as such is intended to be used by professional
# programmers who take t... |
import collections
import logging
import nltk
import operator
import os
import pathlib
import re
from typing import List, Optional, Tuple
from transformers import PreTrainedTokenizer
logging.basicConfig(level=logging.DEBUG)
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
class NEA_NLTK_Tokenizer(object):
"""... |
"""Strategies and fuzzer class module"""
import random
import re
from wafamole.payloadfuzzer.fuzz_utils import (
replace_random,
filter_candidates,
random_string,
num_tautology,
string_tautology,
num_contradiction,
string_contradiction,
)
def reset_inline_comments(payload: str):
"""Re... |
from mock import AsyncMock
import pytest
from opentrons.drivers.smoothie_drivers import SmoothieDriver
from opentrons.tools import write_pipette_memory
@pytest.fixture
def mock_driver() -> AsyncMock:
return AsyncMock(spec=SmoothieDriver)
async def test_write_identifiers(mock_driver: AsyncMock) -> None:
"""... |
import random
import array
import time
def generate32bitStringFromDecimal(decimal):
not32bit = bin(decimal).replace("0b", "")
boyut = len(not32bit)
zero = 32 - boyut
fixed32bit = ""
for i in range(zero):
fixed32bit = fixed32bit + "0"
for i in range(boyut):
fixed32bi... |
#!/usr/bin/env python3
import argparse
'''
* Stream of numbers.
* First N numbers (N=25 for this code) are part of the preamble.
* Every number following the preamble must be a sum of two of the N numbers prior to it
Part 2:
For the invalid number you found, there is a contiguous set of numbers in the prior preamble... |
import gzip
import os
import os.path
import data_algebra
import data_algebra.data_ops
import data_algebra.db_model
_have_bigquery = False
try:
# noinspection PyUnresolvedReferences
import google.cloud.bigquery
_have_bigquery = True
except ImportError:
pass
def _bigquery_median_expr(dbmodel, express... |
from functools import partial
import mock
import re
import os
from dmcontent import ContentLoader
from dmutils.user import User
from flask import json, Blueprint
from werkzeug.datastructures import MultiDict
from flask_login import login_user
from app import create_app, data_api_client, _make_content_loader_factory
f... |
"""
This module handles the selection of image regions, the second stage of
processing.
"""
import re
from typing import Callable, Any, Sequence, Tuple
import numpy as np
import cv2
import matplotlib.pyplot as plt
import pytesseract
from fuzzywuzzy import process
from .text_row_extractors import RowExtraction
def ... |
from collections import namedtuple
import re
Quantity = namedtuple(
"Quantity", ["quantity", "unit", "containerName"], defaults=(None, None, None))
def convertQuantity(mappingDict, toUnit, quantity):
fromFactor = mappingDict[quantity.unit]
toFactor = mappingDict[toUnit]
return Quantity(quantity.quantity *... |
from flask import Blueprint, redirect, render_template , request ,session, g , current_app ,jsonify , flash ,send_from_directory,make_response
from werkzeug.utils import secure_filename
from db import User,db
from flask_socketio import emit
import logging
import os
from utils import *
import magic
import pandas as pd
... |
from django.template import loader
from django.http import HttpResponse, JsonResponse
from django.views.generic import ListView
from rest_framework.permissions import AllowAny
from rest_framework.views import APIView
from .models import Semester, Course, Section, SectionCapacities
import datetime
import pytz
from res... |
#!/usr/bin/env python3.9
from user import User
from user import Credentials
def logo():
print(" ____ _ _ ")
print(" | _ \ | | | | /\ ")
print(" | |_) ) ____ ___ ___ | | __... |
## GROUP
import numpy as np
import cv2
from PIL import Image
import os
from options.test_options import TestOptions
from options.train_options import TrainOptions
from data import create_dataset
from models import create_model
from util.visualizer import save_images
from util import html
import torch
i... |
# No shebang line, this module is meant to be imported
#
# Copyright 2013 <NAME>
# Copyright 2014 Ambient Entertainment GmbH & Co. KG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ht... |
from django.conf import settings
class ChoiceSetMeta(type):
"""
Metaclass for ChoiceSet
"""
def __new__(mcs, name, bases, attrs):
# Extend static choices with any configured choices
if key := attrs.get('key'):
assert type(attrs['CHOICES']) is list, f"{name} has a key defin... |
"""
File to handle the rollback process in order to delete users added.
"""
import logging
import logging.config
import time
from concurrent.futures import ThreadPoolExecutor
from multiprocessing import Lock
import requests
from janrain.capture import ApiResponseError
from tqdm import tqdm
from utils.reader import C... |
import numpy as np
from pysal.lib.common import requires
@requires('matplotlib')
def shift_colormap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'):
'''
Function to offset the "center" of a colormap. Useful for
data with a negative min and positive max and you want the
middle of the colormap... |
from get_dane import get_dane
from pprint import pprint
import math
class Wojewodztwo():
def __init__(self, nazwa, k2013, m2013, k2014, m2014):
self.nazwa = nazwa # np.: `w01D`
self.numer = nazwa[1:3]
self.region = nazwa[3:4]
self.k2013 = int(k2013)
self.m2013 = int(m2013)
... |
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c) 2020 <NAME>
# All rights reserved.
"""Widgets to interact with TPM FAPI objects."""
import gi # isort:skip
gi.require_version("Gtk", "3.0") # pylint: disable=wrong-import-position
# isort:imports-thirdparty
from gi.repository import Gtk
from .widgets impor... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from datetime import datetime
import time
import sqlite3 as sqlite
import psycopg2
SQLITE_ARCHIVE = "/var/lib/weewx/weewx.sdb"
PG_HOST = "some.host.tld"
PG_DB = "db_name"
PG_PORT = 5432
PG_USER = "username"
PG_PASS = "password"
## TESTING AREA
def main():
... |
import os
import sys
#import json
#import datetime
#import numpy as np
#import skimage.draw
# Root directory of the project
ROOT_DIR = os.path.abspath("../../")
# Import Mask RCNN
sys.path.append(ROOT_DIR) # To find local version of the library
from mrcnn.config import Config
from mrcnn import model as modellib, ut... |
# -*- coding: utf-8 -*-
from typing import Any, Type, TypeVar, Generic
from uiclasses import Model
from uiclasses.typing import Property
from humanfriendly.tables import format_robust_table, format_pretty_table
from .helpers import AlmostDict
T = TypeVar("T")
class Config(Model):
data: Any
type: Type
... |
from coldtype import *
from coldtype.pens.datpen import DPR
from functools import partial
Style.RegisterShorthandPrefix("≈", "~/Type/fonts/fonts")
sinaloa_ufo = raw_ufo("fonts/sinaloa.ufo")
BLOCK = 350
class sinaloa(glyph):
def __init__(self, glyphName, **kwargs):
self.ufo_glyph = sinaloa_ufo[glyphName]... |
import RPi.GPIO as GPIO
import posix
from fcntl import ioctl
IOCTL_I2C_SLAVE = 0x0703
class KEY:
def __init__(self, symbol):
self._symbol = symbol
self._is_pressed = False
self._was_pressed = False
self._get_presses = 0
def __str__(self):
return self._symbol
def i... |
"""Analysis tools."""
import ast
import json
import os
from typing import Any, Dict, Optional, Union
import matplotlib.dates as dates
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def analyze() -> None:
"""Return info messages as dict, plot prize timeline and save both.
Notes
--... |
from __future__ import print_function
import copy
import pytest
import lena.core
from lena.core import (
Split, Sequence, Source, Call, FillComputeSeq, FillRequestSeq,
FillCompute, FillRequest,
)
from lena.core import (
LenaAttributeError, LenaRuntimeError, LenaTypeError, LenaValueError,
LenaStopFill,... |
""" Test idlelib.outwin.
"""
import unittest
from tkinter import Tk, Text
from idlelib.idle_test.mock_tk import Mbox_func
from idlelib.idle_test.mock_idle import Func
from idlelib import outwin
from test.support import requires
from unittest import mock
class OutputWindowTest(unittest.TestCase):
@... |
import torch
# def _decoder(pred):
# for i in range(7):
# for j in range(7):
# cell = pred[i][j]
def encoder(boxes, labels): ## length is ratio
target = torch.zeros((7,7,26))
cell_size = 1./7
width_height = boxes[:,2:] - boxes[:,:2]
center_x_ys = (boxes[:,2:]+ box... |
#! /usr/bin/env python
from numpy.testing import TestCase, assert_equal
from aubio import source
from utils import list_all_sounds, parse_file_samplerate
import unittest
from _tools import assert_raises, assert_equal, assert_warns
from _tools import parametrize, skipTest
list_of_sounds = list_all_sounds('sounds')
sa... |
import torch
import torch.nn as nn
from .encoders import LBSNet, LEAPOccupancyDecoder, BaseModule
class INVLBS(LBSNet):
def __init__(self, num_joints, hidden_size, pn_dim, fwd_trans_cond_dim):
self.fwd_trans_cond_dim = fwd_trans_cond_dim
super().__init__(num_joints, hidden_size, pn_dim)
... |
#!/usr/bin/env python3
# coding:utf-8
import cv2
import numpy as np
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from paddle.inference import Config
from paddle.inference import PrecisionType
from paddle.inference import create_predictor
import yaml
import time
# ————... |
import csv
import random
from pathlib import Path
import numpy as np
import time as t
from data.model import Record, calculate_ranges
from data.utils import bin_array
from visualise import graph_power
from matplotlib import pyplot as plt
from model.model import LSTM, ClassicRNN
from tqdm import tqdm
parent = Path(__fil... |
# -*- coding: utf-8 -*-
import asyncio
import re
from PIL import Image
import os
import json
import subprocess
import time
import overwrite
from datetime import datetime
import hashlib
import threading
from PIL import ImageFile
#To ensure that *.png file are read
ImageFile.LOAD_TRUNCATED_IMAGES = True
#how to use ima... |
import errno
import os
import logging
import urllib2
import httplib
import urlparse
import m3u8
import shutil
import crypto
from futures import ThreadPoolExecutor, TimeoutError
import helpers
import atomic
from transcode import transcode_playlist
config = helpers.load_config()
NUM_THREAD_WORKERS = config.getint('hls... |
import functools
from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from zxcvbn import zxcvbn
import nacl.pwhash
from nut_cloud.db import get_db
bp = Blueprint('auth', __name__, url_prefix='/auth')
@bp.route('/register', methods=['GET', 'POST'])
def register():
i... |
"""A simple web application using epubmangler"""
import os
import re
import shutil
import time
import uuid
import uvicorn
from multiprocessing import Process
from pathlib import Path
from xml.etree.ElementTree import Element
from fastapi import FastAPI, File, UploadFile, Request
from fastapi.responses import FileRe... |
#######
#
# cct_json_utils.py
#
# Utilities for working with COCO Camera Traps .json databases
#
# Format spec:
#
# https://github.com/Microsoft/CameraTraps/blob/master/data_management/README.md#coco-cameratraps-format
#
#######
#%% Constants and imports
import os
import json
from collections import defaultdict, Ord... |
'''
This module provides functions to work with clingo's theories.
Example
-------
```python-repl
>>> from clingo.control import Control
>>> from clingox.theory import evaluate
>>>
>>> prg = """\
... #theory test {
... term {
... - : 3, unary;
... ** : 2, binary, right;
... * : 1, binary... |
# -*- coding: utf-8 -*-
import tensorflow as tf
from tensorflow.python.platform import gfile
import attention
import content_functions
import decoders
import nmt_models
def create_seq2seq_model(session, forward_only, model_path=None, use_best=False, FLAGS=None, buckets=None, translate=False):
"""Create translati... |
import streamlit as st
import streamlit.components.v1 as stc
# Text Cleaning Pkgs
import neattext as nt
import neattext.functions as nfx
from collections import Counter
import pandas as pd
# Text Viz Pkgs
from wordcloud import WordCloud
from textblob import TextBlob
# Data Viz Pkgs
import matplotlib.pyplot as plt
... |
import sys
import json
from .utils import check_inputs, zopen
from .gff import gff2dict
from .genbank import tbl2dict
def stats(args):
check_inputs([args.input] + [args.fasta])
if not args.input_format: # we have to guess
if args.input.endswith((".tbl", ".tbl.gz")):
args.input_format = "t... |
"""
92. Reverse Linked List II
Medium
Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5], left = 2, right = 4
Output: [1,4,3,2,5]
Exampl... |
from abc import ABC, abstractmethod
from typing import AnyStr, List, Dict, Optional, Union
from functools import partial
class AdvancedFeaturizer(ABC):
pass
class SimpleFeaturizer(ABC):
id = None
parameters = []
# def __init__(self, files: Union[str, List[str]], series: Union[str, List[str], None]):... |
import requests
import pandas
def get_bool(prompt):
while True:
try:
return {"true":True, "t": True, "false":False, "f":False, "yes":True, "no":False, "y":True, "n":False}[input(prompt).lower()]
except KeyError:
print("Invalid input, please enter True or False")
def get_yea... |
import onmt
import numpy as np
import argparse
import torch
import codecs
import json
import sys
import csv
parser = argparse.ArgumentParser(description='preprocess.py')
##
## **Preprocess Options**
##
parser.add_argument('-config', help="Read options from this file")
parser.add_argument('-train_src', required=T... |
# Python modules
# 3rd party modules
import wx
#import wx.aui as aui
import wx.lib.agw.aui as aui # NB. wx.aui version throws odd wxWidgets exception on Close/Exit ?? Not anymore in wxPython 4.0.6 ??
# Our modules
import vespa.common.wx_gravy.util as wx_util
"""This module contains two classes that are su... |
from ..exceptions import RedisError
from ..utils import b
from ..utils import nativestr
def parse_georadius_generic(response, **options):
if options['store'] or options['store_dist']:
# `store` and `store_diff` cant be combined
# with other command arguments.
return response
if not is... |
import os
import sys
import glob
import subprocess
from functools import partial
import concurrent.futures
import filecmp
import helpers
WHERE_AM_I = os.path.dirname(os.path.realpath(__file__)) # Absolute Path to *THIS* Script
BENCH_INPUT_HOME = WHERE_AM_I + '/inputs/'
BENCH_BIN_HOME = WHERE_AM_I + '/tests/test-pro... |
# coding = utf-8
# @time : 2019/6/4 3:15 PM
# @author : alchemistlee
# @fileName: Spear.py
# @abstract:
import sys
sys.path.append('../')
import modeling
import os
import tensorflow as tf
import numpy as np
import utils
import collections
import tokenization
import config
import time
class MultiLabelSpear(ob... |
import ctypes
import functools
import random
import struct
from fcntl import ioctl
from trio import socket
from wrath.bpf import create_filter
IP_VERSION = 4
IP_IHL = 5
IP_DSCP = 0
IP_ECN = 0
IP_TOTAL_LEN = 40
IP_ID = 0x1337
IP_FLAGS = 0x2 # DF
IP_FRAGMENT_OFFSET = 0
IP_TTL = 255
IP_PROTOCOL = 6 # TCP
IP_CHECKSUM... |
# -*- coding: utf-8 -*-
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... |
"""
Extension name: admin commands
Author: <NAME>
Created: 18.03.19 - Europe
"""
# import discord py library
import discord
# Imports commands
from discord.ext import commands
# import permissions
from discord.ext.commands import has_permissions
import asyncio
import json
from data.functions.MySQL_Connector import MyDB... |
#!/usr/bin/env python3
import requests
import hashlib
import time
import json
import sys
#from yolink_mqtt_clientV2 import YoLinkMQTTClientV2
import paho.mqtt.client as mqtt
client_id = '60dd7fa7960d177187c82039'
client_secret = '3f68536b695a435d8a1a376fc8254e70'
yolinkURL = 'https://api.yosmart.com/openApi'
yoli... |
#!/usr/bin/env python
import numpy as np
def ltr_parts(parts_dict):
# when we flip image left parts became right parts and vice versa. This is the list of parts to exchange each other.
leftParts = [ parts_dict[p] for p in ["Lsho", "Lelb", "Lwri", "Lhip", "Lkne", "Lank", "Leye", "Lear"] ]
rightParts = [ p... |
import numpy as np
import random
from scipy.misc import imresize
from PIL import Image
import math
# from torchvision import transforms
import torch
class MultiRescale(object):
"""MultiScale the input image in a sample by given scales.
Args:
scales_list (tuple or int): Desired output scale list.
... |
from enum import Enum
import numpy as np
import scipy.stats as scistats
import matplotlib.pyplot as plt
from tqdm import tqdm
class Noise(Enum):
NORMAL = 1
CAUCHY = 2
def generate(
n_steps=101,
plate_width=10,
plate_height=10,
dx=0.1,
dy=0.1,
thermal_diffusivity=4,
temperature_co... |
import pygame
from constants import (
MAILRAYS,
BUTTON_NORMAL,
BUTTON_MOUSE_OVER,
TEXTBOX_NORMAL,
TEXTBOX_MOUSE_OVER,
)
from sheldonchess.game.normal import ChessBoard
from pieces import Piece
class Widget(object):
def handle_event(self, event):
pass
class Button(Widget):
F... |
"""model"""
from core import solution
class Station:
"""
station class
"""
def __init__(self, st_name, is_trans=False):
self._name = st_name
self._trans = is_trans
@property
def name(self):
"""get station's name"""
return self._name
@property
def is_t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 6 00:11:55 2020
@author: andreas
"""
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from PlotScatter import hue_order
from Basefolder import basefolder
import pickle
import numpy as np
my_pal = {'FINDER_1D_loop':'#701a... |
"""
Copyright (c) 2018, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
from crawl.releasereason import ReleaseReason
def get_libraries_to_release(artifact_nodes):
"""
... |
"""
Use the library to calculate stiffness matrices for Zysset-Curnier Model based orthotropic materials
and extract the engineering constants from the stiffness matrices.
"""
from collections import namedtuple
import numpy as np
import tenseng.tenseng.tenseng as t
cubic = namedtuple('CubicAnisotropic', ['E', 'nu', ... |
import sys
import tkinter as tk
import cv2
from datetime import date, datetime
from PIL import ImageTk, Image
from dobe_config import *
from dobe_api import *
LARGE_FONT = ("ChicagoFLF", 90)
MED_FONT = ("ChicagoFLF", 20)
DIVIDER_HEIGHT = 3
class Dobe_View():
def __init__(self):
root = tk.Tk()
co... |
import struct
import time
import yaml
import yaml.resolver
from collections import OrderedDict
import data_types
from data_types import TypeID
def now_ns():
return int(time.time() * 10 ** 6)
class Schema:
""" The schema for the data in the atomic multilog.
"""
def __init__(self, columns):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.