text stringlengths 3.07k 12.6k |
|---|
# Copyright (c) 2019 UAVCAN Consortium
# This software is distributed under the terms of the MIT License.
# Author: <NAME> <<EMAIL>>
import typing
from pyuavcan.transport import Timestamp
from ._frame import SerialFrame
class StreamParser:
"""
A stream parser is fed with bytes received from the channel.
... |
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, random_split
import torch.optim as optim
from tqdm import tqdm
from matplotlib import pyplot as plt
from datetime import datetime
from util import WavData
from torch.utils.tensorboard import SummaryWriter
# fixed : pip3 install torch torchvi... |
import cv2
import urllib.request as request
import numpy as np
import sys
import matplotlib.pyplot as plt
from linesearch import *
'''
Prepare:
In raspberryPi:
```
cd Tools
bash change_network.sh wifi
bash remote_camera.sh
```
In laptop computer:
```
conda env create -f=envi... |
import torch
from torch.utils import data
from Datasets.dataset_semantic_SHAB import Dataset as full_supervise_Dataset
from Models.model import Model
import os
import argparse
import matplotlib.pyplot as plt
import torch.nn.functional as F
import numpy as np
checkpoint_logs_name = 'SHA'
parser = argparse.ArgumentParse... |
from itertools import islice, count
from tqdm import tqdm
def _k_mers(sequence, k):
it = iter(sequence)
result = tuple(islice(it, k))
if len(result) == k:
yield "".join(result)
for elem in it:
result = result[1:] + (elem,)
yield "".join(result)
def transform(sequence, method... |
import logging
import ply.yacc as yacc
from functools import partial
from rita.lexer import RitaLexer
from rita import macros
logger = logging.getLogger(__name__)
def stub(*args, **kwargs):
return None
def either(a, b):
yield a
yield b
def load_macro(name, config):
try:
return partial(... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import *
import logging
import emission.core.get_database as edb
import emission.core... |
# Copyright (c) Facebook, Inc. and its affiliates.
import logging
import numpy as np
from itertools import count
import torch
from caffe2.proto import caffe2_pb2
from caffe2.python import core
from .caffe2_modeling import META_ARCH_CAFFE2_EXPORT_TYPE_MAP, convert_batched_inputs_to_c2_format
from .shared import Scoped... |
DATASETS_DIR = "./data/datasets/"
DATASET_SIZE = 1000
PRIME_LIST_DIR = "./data/prime_lists/"
RANGE_MAX = 982451653
from random import shuffle
from time import time
from model.primality import trial_division
def is_prime(n):
if n < 2:
return 0
if n == 2:
return 1
if n % 2 == 0:
re... |
"""Script for coverting pdf and doc/docx files into txt.
Convertions were done from pdf to txt and docx to txt, using downloaded
modules (pdfminer and docx).
Important: pdf convertion to txt is not as simple as it's seem. We created
a new version since the former one had many errors in symbol convertion. The
results... |
# @File(label = "Image File", persist=True) JSONPARAMFILE
# @OUTPUT String JSONPARAMFILE
#@UIService uiService
#@LogService log
"""
File: GuidedAcq_fromZEN.py
Author: <NAME>
Date: 2018_10_11
Version: 0.23
"""
import json
# get the JSONPARAMFILE as string
jsonfile = JSONPARAMFILE.toString()
INPUT_JSON = json.loads(op... |
####################
# ES-DOC CIM Questionnaire
# Copyright (c) 2017 ES-DOC. All rights reserved.
#
# University of Colorado, Boulder
# http://cires.colorado.edu/
#
# This project is distributed according to the terms of the MIT license [http://www.opensource.org/licenses/MIT].
####################
from djan... |
import numpy as np
from geometry import Point, Rectangle, Circle, Ring
from typing import Union
import copy
class Entity:
def __init__(self, center: Point, heading: float, movable: bool = True, friction: float = 0):
self.center = center # this is x, y
self.heading = heading
self.movable =... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import cv2
import numpy as np
import os
import sys
import shutil
import time
import tensorflow as tf
from google.protobuf import text_format
from tensorflow.python.platform import app
from de... |
import platform
import os
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
import vlc
from PyQt5.QtCore import QTimer
class Player(QtWidgets.QMainWindow):
"""A simple Media Player using VLC and Qt
"""
def __init__(self, master=None):
QtWidgets.QMainWindow.__init__(self, master)
self... |
# -*- coding: utf-8 -*-
# Natural Language Toolkit: NIST Score
#
# Copyright (C) 2001-2017 NLTK Project
# Authors:
# Contributors:
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""NIST score implementation."""
from __future__ import division
import math
import fractions
from collections import ... |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
def variable_summaries(var):
"""
This helper function, taken from the official TensorFlow documentation,
simply adds some ops that take care of logging summaries
:type var: tf.Variable
:return:
"""
with tf.n... |
#!/usr/bin/env python3
import re
import subprocess
import nanodurationpy as durationpy
import csv
import time
import datetime
import os
import shutil
import shlex
# output paths should be mounted docker volumes
RESULT_CSV_OUTPUT_PATH = "/benchmark_results_data"
RESULT_CSV_FILENAME = "parity_precompile_benchmarks.csv... |
"""
mi2app_utils.py
Define utility variables and functions for apps.
"""
# FIXME (likayo): subprocess module in Python 2.7 is not thread-safe.
# Use subprocess32 instead.
import subprocess as sp
import os
import re
import jnius
import hashlib
from jnius import autoclass, cast, PythonJavaClass, java_method
from kivy.l... |
# Copyright 2018 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
__source__ = 'https://leetcode.com/problems/find-k-pairs-with-smallest-sums/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/find-k-pairs-with-smallest-sums.py
# Time: O(k * log(min(n, m, k))), where n is the size of num1, and m is the size of num2.
# Space: O(min(n, m, k))
#
# Description: Leetcode # 373. ... |
# Blender modules
# 2020-03-28
import bpy
from bpy import *
import bpy.path
from bpy.path import abspath
from mathutils import *
# Python standard modules
from urllib.parse import urlencode
from urllib.request import *
from html.parser import *
from smtplib import *
from email.mime.text import MIMEText
i... |
import pygame, sys, math, random
def pixel_collision(mask1, rect1, mask2, rect2):
offset_x = rect2[0] - rect1[0]
offset_y = rect2[1] - rect1[1]
overlap = mask1.overlap(mask2, (offset_x, offset_y))
return overlap
class Sprite:
def __init__(self, image):
self.image = image
self.recta... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 13:32:44 2019
@author: prasad
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from tensorflow import keras
def get_data(names):
'''
Args
column_names: names of the features in dataset
'''
trai... |
from musixmatch.expections import NotFound
class ResultSet(list):
"""A list like object that holds results from a Musixmatch API query."""
class Model(object):
_not_found_error_class = NotFound
_remove_tag = None
def __init__(self, **kwargs):
self._repr_values = {"id": "Id"}
@classmeth... |
from __future__ import unicode_literals
from collections import OrderedDict
from six import text_type
from prompt_toolkit.auto_suggest import DynamicAutoSuggest
from prompt_toolkit.completion import DynamicCompleter, ThreadedCompleter
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import ... |
import random
import re
import numpy as np
import torch
from torch.utils import data
tokenizer = None
def get_lm_path(lm, lm_path):
if lm_path != None:
return lm_path
if lm == 'bert':
return 'bert-base-uncased'
elif lm == 'distilbert':
return 'distilbert-base-uncased'
elif ... |
import logging
from string import Template
from django.db import transaction
from django.http import HttpResponseRedirect
from django.views.generic.base import TemplateView
from django.views.generic.list import ListView
from django.views.generic import CreateView
from django.shortcuts import render
from django.urls im... |
# Copyright 2018 The Cirq Developers
#
# 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 applicable law or agreed to in ... |
import unittest
from hinanbasho.db import DB
from hinanbasho.models import (
AreaAddressFactory,
CurrentLocation,
EvacuationSite,
EvacuationSiteFactory
)
from hinanbasho.services import AreaAddressService, EvacuationSiteService
test_evacuation_site_data = [
{
"site_id": 1,
"site_na... |
# -*- coding: utf-8 -*-
from flair.file_utils import *
from flair.embeddings import *
from flair.models.sequence_tagger_model import *
import dataiku
from dataiku.customrecipe import *
try:
model_folder = get_input_names_for_role('model_folder')[0]
except IndexError:
raise Exception(
"In order to use ... |
#!/usr/bin/env python
"""
***BORROWED FROM IMAGEPYPELINES AND <NAME>***
This is a script that will verify that all .py contained in our repo
contain our license and copyright.
if desired, this script can also modify each file and add the license and copyright
to each file
travis will run it with default arguments au... |
from mo_dots import Data, DataObject, FlatList, from_data, to_data, literal_field
from dotty_dict import Dotty, dotty
import json
from traversy import traverse
from typing import Dict, List, Literal, Tuple, Union, Any, Callable, Set
import copy
Boolean = Literal[True, False]
def do_nothing(var: Any) -> Any:
"""
Do... |
import json
import os
import pytest
from cryptojwt.jwk.hmac import SYMKey
from oidcmsg.time_util import time_sans_frac
from oidcendpoint.authn_event import AuthnEvent
from oidcendpoint.cookie import CookieDealer
from oidcendpoint.endpoint_context import EndpointContext
from oidcendpoint.id_token import IDToken
from o... |
from __future__ import absolute_import
from django import forms
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from sentry import roles
f... |
import os
from flask import Flask, render_template, request, redirect, flash, url_for, jsonify, make_response
from werkzeug.utils import secure_filename
from datetime import datetime
import json
import pandas as pd
import sqlite3 as sql
UPLOADS = r'S:\Python Projects\Job Search Data Visualization\Project MDIB\... |
from typing import List, Union, Tuple, Dict, Any, Optional
from .words_object import Action, WordsObject, POS, Obj, Position, Cluster
def resolve_phrases(items: List[Union[Action, Cluster]],
trees_list: List[List[Tuple[int, WordsObject]]],
text_info: Dict[str, Any]) -> List[Un... |
import csv
import itertools
import pyaavso
class FormatException(Exception):
"""
Raised when the data does not conform to AAVSO format specification.
"""
class VisualFormatWriter(object):
"""
A class responsible for writing observation data in AAVSO
`Visual File Format`_.
The API here ... |
# Copyright 2018-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 applicabl... |
import dicom
import os
from dicom.sequence import Sequence
import numpy as np
import glob
np.random.seed(1234)
import matplotlib.pyplot as plt
from matplotlib import animation
import os
import pickle as pickle
#file_list = glob.glob('/data/dsb15_pkl/pkl_validate/*/study/sax_*.pkl')
file_list = glob.glob(... |
import http.server
import socketserver
import cgi
import json
import logging
import os
import posixpath
import re
import traceback
import urllib.parse
import Constants
class HTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
def __init__(self, RequestHandlerClass,port,controller,basedir):
self.b... |
import os
import re
import sys
import json
import click
import codecs
import requests
###
#
# Global variables.
#
###
PATH_ES_CONFIG = 'es_config.json'
PATH_DATA_FOLDER = 'data/json_data_new/'
HOST_URL = 'http://localhost'
HOST_PORT = '9200'
BULK_INSERT_RATE = 1000
INDEX_NAME = 'lb'
#with open('../json_data_new/lb... |
# Copyright (c) 2020 <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 restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, ... |
# Copyright 2020 <NAME> and <NAME>. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import BMPxlsx
import fiona
import glob
import json
import os
import shutil
import StringIO
import tempfile
import zipfile
from django.conf import settings
from django.core.exceptions ... |
import string
def key_generation(key):
# initializing all and generating key_matrix
main=string.ascii_lowercase.replace('j','.')
# convert all alphabets to lower
key=key.lower()
key_matrix=['' for i in range(5)]
# if we have spaces in key, those are ignored automatically
i=0;... |
"""
Misc. utility functions
"""
import os
import logging
import json
import random
import math
from typing import *
import torch
import numpy as np
import pandas as pd
import scipy
import Bio.Data.CodonTable as CodonTable
def min_power_greater_than(
value: SupportsFloat, base: SupportsFloat = 2
) -> SupportsFlo... |
import torch
import torch.nn as nn
from models.word_model import CaptionModel
class Seq2SeqAttention(nn.Module):
def __init__(self, hs_enc, hs_dec, attn_size):
"""
Args:
hs_enc: encoder hidden size
hs_dec: decoder hidden size
attn_size: attention vector size
... |
import sys
import numpy as np
from collections import deque
import matplotlib.pyplot as plt
from functools import lru_cache
import typing
import numba
TOMATO = -1
MUSHROOM = 1
global_pizza = None
valid_shapes = []
nb_indices = numba.int32[:]
@numba.jitclass([
('r1', numba.int32),
('r2', numba.int32),
('... |
#!/usr/bin/python3
from typing import Dict, Union, Tuple, Any, List
from hashlib import sha1
from pathlib import Path
import re
import textwrap
from brownie.cli.utils import color
from brownie.exceptions import ContractExists
MINIFY_REGEX_PATTERNS = [
r"(?:\s*\/\/[^\n]*)|(?:\/\*[\s\S]*?\*\/)", # comments
r... |
#!/usr/bin/env python
# -*-coding:utf-8 -*-
'''
@author: daishilong
@contact: <EMAIL>
'''
import pickle
from crl_kino.policy.rl_policy import load_policy, policy_forward
from matplotlib import pyplot as plt
import imageio
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from crl_kino.env impo... |
import os
import random
import re
from datetime import datetime, timedelta
import discord
import pandas as pd
from discord.ext import commands
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
class NLP(commands.Cog):
def __init__(self, bot):
... |
# 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/LICENSE-2.0
#
# Unless required by applica... |
from unittest import TestCase
from ingestion.comment import Comment, CommentScanner
# Array of test data tuples (comment text, score, expected sentiment)
test_comments = [
("""I almost spent 1 BTC on 2000 ETH in the crowd sale but they didn't even have a working product then so I said fuck that. I have NO regrets... |
import json
import sys
import math
from argparse import ArgumentParser, FileType
from pprint import pprint
from os.path import splitext
from itertools import combinations
from graphviz import Digraph
# from xml.sax.saxutils import escape as xmlescape
# Solarised
NAME, _ = splitext(__file__)
COLORS = {
'bg': '#fd... |
# -*- coding: utf-8 -*-
'''
Global nearest neighbor
'''
from __future__ import division, absolute_import, print_function
__all__ = [
'GNNTrack', 'GNNFilterGenerator', 'GNNFilterInitializer',
'GNNLogicMaintainer', 'GNNTracker'
]
import numpy as np
import scipy.optimize as op
from .common import *
class GNNT... |
from .physics import *
class EdgeOptions(object):
"""
This is where the construction of the edges' options takes place.
So far, the edge smoothness can be switched through this object
as well as the edge color's inheritance.
"""
def __init__(self):
self.smooth = self.Smooth(... |
from keras.preprocessing.text import Tokenizer, text_to_word_sequence
from keras.engine.topology import Layer
from keras import initializers as initializers, regularizers, constraints
from keras.callbacks import Callback, ModelCheckpoint
from keras.utils.np_utils import to_categorical
from keras.layers import Embeddin... |
import os
import json
import datetime
from django.http import HttpResponse
from django.views.generic import TemplateView
from django.utils.safestring import mark_safe
from django.utils import timezone
from django.template.loader import render_to_string
from person.models import Person
from document.models import Doss... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class GetEve... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class BinaryFocalLoss(nn.Module):
"""
One possible pytorch implementation of focal loss (https://arxiv.org/abs/1708.02002) for binary classification. The
idea is that the binary cross entropy is weighted by one minus the estimated probabili... |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
import json
import sys
import pandas as pd
import tempfile
import os
import os.path
import glob
import shutil
import tempfile
import xml.dom
import xml.dom.minidom
def add_garminID_gpx(gpxfile,garminID):
"""
Add garmin ID to a gpx file at the metadata tag.
"""
tf = xml.dom.minidom.parse( gpxfile )
... |
import collections
from _datetime import datetime
import cv2
import numpy as np
import firebase_admin
import requests
from firebase_admin import credentials, firestore
import pyrebase
station = "Station B"
station_id = "5"
loc = {
"Latitude": "19.044197669339596",
"Longitude": "72.86488164388184"
}
services =... |
"""An exact Riemann solver for the Euler equations with a gamma-law
gas. The left and right states are stored as State objects. We then
create a RiemannProblem object with the left and right state:
> rp = RiemannProblem(left_state, right_state)
Next we solve for the star state:
> rp.find_star_state()
Finally, we ... |
### most of this will only work for Blast -- not psi-blast
def is_new_query_id_line( line ):
return line and line.split() and line.split()[0] == 'Query='
def is_new_hit_id_line( line ):
return line and line[0] == '>'
def is_new_match_line( line ):
return line and line[:3] == ' Sc'
def is_query_alig... |
"""
Copyright (c) 2020 <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 restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublice... |
#!/usr/bin/env python3
#
# Copyright 2015 Dovetail Genomics LLC
#
#
from __future__ import division
from __future__ import print_function
from builtins import str
from builtins import range
from past.utils import old_div
import sys
import math
import random
import json
def log(s):
sys.stderr.write( "%s\n" %(s) ... |
import pandas as pd
import os
import numpy as np
from sklearn.linear_model import LinearRegression
def get_rainfall_prediction():
dir_path = os.getcwd()
dataset = pd.read_csv(os.path.join(dir_path,'dashboard','dataset','yearly_rainfall.csv'))
a = list()
for i in range(2,14):
y = dataset.iloc[:... |
import torch
import numpy as np
def get_sigmas(config):
if config.model.sigma_dist == 'geometric':
sigmas = torch.tensor(
np.exp(np.linspace(np.log(config.model.sigma_begin), np.log(config.model.sigma_end),
config.model.num_classes))).float().to(config.device)
... |
import os
os.environ["OPENBLAS_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["MKL_NUM_THREADS"] = "1"
from typing import Union, Optional, Iterable
import numpy as np
import pandas as pd
from functools import partial, reduce
from anndata import AnnData
import shutil
import sys
import copy
import ... |
#!/usr/bin/python
#
# written by @wahyu9kdl
# https://github.com/wahyu9kdl/wahyu9kdl.github.io/DASHBOARD/TOOLS/AUTO VISITOR/web-traffic-generator
#
# published under MIT license :) do what you want.
#
# 20170714 shyft ADDED python 2.7 and 3.x compatibility and generic config
# 20200225 rarawls ADDED recursive, depth-... |
#
# Copyright (C) 2020 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
import re
import itertools
from collections import OrderedDict
from .struct_utils import parse_format
from .parse_openfst import parse_openfst
DEFAULT_ALPHABET = [b' abcdefghijklmnopqrstuvwxyz\''[i:i+1] for i in range(28)]
def find_t... |
import cmath
import math
import numpy
import scipy.sparse.linalg
import time
import sys
from pauxy.propagation.operations import local_energy_bound
from pauxy.utils.linalg import exponentiate_matrix, reortho
from pauxy.walkers.single_det import SingleDetWalker
class PlaneWave(object):
"""PlaneWave class
"""
... |
"""
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... |
#!/usr/bin/python
# Copyright (c) 2017-present Alibaba Group Holding Limited. <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
# -*- coding: utf-8 -*-
import json
from werkzeug.exceptions import BadRequest, NotFound
from pipelines.controllers.pipeline import Pipeline
from pipelines.controllers.utils import init_pipeline_client, format_pipeline_run_details, \
get_operator_parameters, get_operator_task_id
from pipelines.jupyter import read_... |
from collections import namedtuple
from walt.server.autoglob import autoglob
import pickle, resource
COLUMNATE_SPACING = 2
PARAGRAPH_FORMATING = """\
\033[1m\
%(title)s
\033[0m\
%(content)s
%(footnote)s"""
def as_string(item):
if item == None:
return ''
else:
return str(item)
def columnat... |
#!/usr/bin/env python3
import sys
import time
import argparse
from getpass import getpass
from urllib import request, parse
from configparser import ConfigParser
from os.path import join, expanduser
import subprocess
categories = {
'btech': 22,
'dual': 62,
'diit': 21,
'faculty': 82,
'integrated':... |
"""
This file is part of nucypher.
nucypher 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.
nucypher is distributed in the hope that it wil... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Decrypt and encrypt messages compatible to the "Stanford Javascript Crypto
Library (SJCL)" message format.
This module was created while programming and testing the encrypted
blog platform on cryptedblog.com which is based on sjcl.
"""
import base64
from Crypto.Hash... |
import asyncio
import itertools
import functools
import math
import re
from attr import __description__
import discord
import os
from discord.ext import tasks, commands
from discord.ext.commands.errors import MissingPermissions
from discord.user import Profile
from discord.utils import get
from dns.message ... |
import socket
import sys
import threading
def hexdump(src_bytes, length=16):
'''
Dump hexadecimal
:param src_bytes: Bytes, Bytearray, or compatible object
:param length: Length of each output line
:return:
'''
result = []
digits = 4 # python2 code, all python3 strings are Unicode: if ... |
# Copyright 2018 Red Hat, 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 agreed to in writing, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Monkey patch oss2 library.
'''
import functools
import json
import logging
import os
import oss2
from oss2 import defaults
from oss2.compat import to_unicode
from oss2.exceptions import ServerError
from oss2.resumable import _ResumableUploader
from oss2.task_queue impo... |
'''Extension for Nemo's context menu to easily convert images to PNG and
optimize their filesize with pngcrush.'''
from __future__ import annotations
import os
import subprocess
from urllib.parse import unquote_plus, urlparse
from PIL import Image, UnidentifiedImageError
import PySimpleGUI as sg
import gi
gi.require... |
from os import environ, remove
from platform import uname
from os.path import join, isfile, exists
from subprocess import check_output
import kivy
if environ.get('KIVENT_USE_SETUPTOOLS'):
from setuptools import setup, Extension
print('Using setuptools')
else:
from distutils.core import setup
from dist... |
from scipy.sparse import csr_matrix
from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
import pickle
from sklearn.feature_extraction.text import TfidfVectorizer
import re
from joblib import Memory
cachedir = 'cache/'
memory = Memory(cachedir, verbose=0)
path_to_site_dict = 'data/site_dic.... |
import numpy as np
import hypers as hp
from typing import Tuple, List
__all__ = ['decompose', 'vca']
class decompose:
""" Provides instances of decomposition classes """
def __init__(self, X: 'hp.hparray'):
self.vca = vca(X)
class vca:
def __init__(self, X: 'hp.hparray'):
self.X = X
... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe, os, json
from frappe import _
from frappe.utils import get_timestamp
from frappe.utils import cint, today, formatdate
import frappe.defa... |
#!/usr/local/bin/python3
import asyncio
import datetime
import os
import uuid
import importlib
import sys
from grpclib.client import Channel
from model import SecurityReportTestResult, SecurityReportIngestionServiceStub, SecurityReportContext, SecurityReport, \
SecurityReportTestResultResult
from model.helper impo... |
"""This file defines functions to generated different splits of
the data for federated simulations.
"""
from collections import OrderedDict, defaultdict
import numpy as np
import tensorflow as tf
from data_utils import create_masks
def gather_indices(idxs, in_data, out_inputs, padding_masks, look_ahead_masks,
... |
# -*- coding: utf-8 -*-
"""Filter out duplicate text evidences (the ones that appear more than two times)."""
import logging
import re
import os
from collections import Counter
from typing import Optional
import pandas as pd
from sklearn.model_selection import train_test_split
from transformers import BertTokenizer
... |
"""
Unload data from data warehouse to S3.
A "unload" refers to the wholesale dumping of data from any schema or table involved into
some number of gzipped CSV files to a given S3 destination. The resulting data files
can be loaded back into the data warehouse using the "load" step.
(1) CSV files will have fields del... |
import autode.pes.pes_2d as pes_2d
import numpy as np
from autode.species.molecule import Reactant, Product
from autode.atoms import Atom
from autode.species.complex import ReactantComplex, ProductComplex
from autode.bonds import FormingBond, BreakingBond
from autode.reactions.reaction import Reaction
from autode.wrapp... |
# -*- coding: utf-8 -*-
"""
connection: Provides a HTTP client to make requests to calm
Example:
pc_ip = "<pc_ip>"
pc_port = 9440
client = get_connection(pc_ip, pc_port,
auth=("<pc_username>", "<pc_passwd>"))
"""
import traceback
import json
import urllib3
from requests import Session as No... |
import requests
import boto3
import botocore
import sys
import json
import random
from weatherfood import application
app = application.app
API_KEY = app.config['API_KEY']
BASE_URL = "http://api.openweathermap.org/data/2.5/weather?zip={0},us&appid={1}"
RESULT_BASE = "{0}, and {1} degrees Fahrenheit"
USE_LOCAL_DYNAMO... |
import numpy as np
import cv2
def norm_rot_angle(rot):
norm_rot = rot
while norm_rot > 180:
norm_rot = norm_rot - 360
while norm_rot <= -180:
norm_rot = norm_rot + 360
return norm_rot
def rotate_2d(pt_2d, rot_rad):
x = pt_2d[0]
y = pt_2d[1]
sn, cs = np.sin(rot_rad), np.co... |
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 13 11:56:44 2022
@author: dleon
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from scipy.stats import norm,gamma,cauchy,invgauss,norminvgauss,\
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.