text stringlengths 3.07k 12.6k |
|---|
import numpy as np
import pandas as pd
import sys
import glob
import torch
from rdkit import Chem
from rdkit import DataStructs
from rdkit.Chem import AllChem
from rdkit import RDLogger
from moses.script_utils import read_smiles_csv
def get_smiles_from_lbann_tensors(fdir, sequence_length, zdim, batch_num=0):
'''
... |
from functools import reduce
import operator
import random
import sys
import numpy as np
sys.setrecursionlimit(50000)
def extract(x, *keys):
if isinstance(x, (dict, LazyDict)):
return tuple(x[k] for k in keys)
elif isinstance(x, list):
return tuple([xi[k] for xi in x] for k in keys)
else... |
# SPDX-FileCopyrightText: 2020 <NAME>, written for Adafruit Industries
#
# SPDX-License-Identifier: Unlicense
"""
PyPortal implementation of Busy Simulator notification sound looper.
"""
import time
import board
import displayio
import adafruit_touchscreen
from adafruit_displayio_layout.layouts.grid_layout import GridL... |
import argparse
from pathlib import Path
import warnings
import crowsetta
import evfuncs
import numpy as np
import pandas as pd
import pyprojroot
import soundfile
from tqdm import tqdm
PROJ_ROOT = pyprojroot.here()
def get_seg_feature_vals(audio_data_dir,
annot_data_dir):
scribe = crow... |
import numpy as np
from mpi4py import MPI
from mpi4py_fft import PFFT, newDistArray, DistArray
import time
import copy as cp
def get_local_mesh(FFT, L):
"""Returns local mesh."""
X = np.ogrid[FFT.local_slice(False)]
N = FFT.global_shape()
for i in range(len(N)):
X[i] = (X[i]*L[i]/N[i])
X =... |
from tkinter import *
import os
import time
from functools import partial
import subprocess
from tkinter import messagebox , ttk
win=Tk()
def VM_ip(host_ip):
ip=(host_ip.get())
ipv=ip+"/24"
checkip=os.popen('ifconfig '+interface.get()+' | grep -Eo "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"')
hostip=checkip.... |
#############################################################
#
# Validation - continutous distribution
#
#############################################################
import sys, os
sys.path.append("../..")
sys.path.append("..")
sys.path.append(os.getcwd())
import numpy as np
import pandas as pd
import copy
import pi... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 14 03:02:11 2018
@author: se93w
"""
import tensorflow as tf
l2 = tf.contrib.layers.l2_regularizer(scale=0.01)
def inception(input, filters_1x1, filters_3x3_reduce, filters_3x3, filters_5x5_reduce, filters_5x5, filters_pool_proj):
conv_1x1 = tf.layers.conv2d(inputs=i... |
import collections
import ctypes
import time
from ctypes import (
c_ubyte as BYTE,
c_uint16 as WORD,
c_uint32 as DWORD,
c_int32 as LONG,
)
import PIL.Image
import PIL.ImageGrab
import pyautogui
NULL = 0
PW_RENDERFULLCONTENT = 2
DIB_RGB_COLORS = 0
ERROR_INVALID_PARAMETER = 87
HGDI_ERROR = -1
# http... |
# Copyright (c) 2014, 2015 Scality
#
# 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 writ... |
from imports import *
from tensorflow.keras import backend as K
import tensorflow as tf
import math
from load import load_data
def _1cycle_mom(iteration_idx:int,
cyc_iterations:int,
min_mom:float,
max_mom:float):
'TODO: docstring'
mid = math.floor((cyc_iterations ... |
from django.test import TestCase
from django.test import override_settings
from mock import Mock
from mock import patch
from phone_numbers.models import PhoneNumber
from bots.models import Bot
from bots import tasks
class BotsTasksNoContactTestCase(TestCase):
def setUp(self):
self.bot = Bot.objects.cre... |
from __future__ import annotations
import bisect
from dataclasses import dataclass, field
from typing import Any, cast, Generic, Iterator, List, Optional, Sequence, TypeVar, Union
from typing_extensions import final
from ._query import ConstraintsAlias, Query
from .predicate import NeutralWeight, Predicate, Predicat... |
import enum
from datetime import datetime
from typing import Optional
import rapidjson
from pyramid.config import Configurator
from pyramid.renderers import RendererHelper
from pyramid.request import Request
from sqlalchemy import inspect
from sqlalchemy.ext.associationproxy import _AssociationList
from sqlalchemy.orm... |
"""
Description:
------------
python wrapper around the TLPM.dll from Thorlabs
it supports the following Thorlabs power meters and appropriate sensors and can administer them in parallel.
· PM101x (PM101, PM101A, PM101R, PM101U)
· PM102x (PM102, PM102A, PM102U)
· PM103x (PM103, PM103A, PM103U)
· PM100USB
· PM16-Series... |
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn
from data import get_loaders, load_dataset
from definitions import device
from metrics import RMSE
from models import create_model, load_model
from training import get_test_predictions, test_step
from utils import print_losses
class... |
"""Kindle Model parser and model.
This module parses model configuration yaml file
and generates PyTorch model accordingly.
- Author: <NAME>
- Contact: <EMAIL>
"""
import os
from typing import Dict, List, Optional, Tuple, Type, Union
import numpy as np
import torch
import torch.nn as nn
import yaml
from kindle.gen... |
from typing import List
import os
from omegaconf import DictConfig, OmegaConf
import hydra
from torchmetrics.functional import accuracy
from high_order_layers_torch.layers import *
from pytorch_lightning import LightningModule, Trainer
import torch.optim as optim
import torch
from high_order_layers_torch.networks impo... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import random
import torch
from torch import Tensor
from fairseq.models import register_model_architecture, register_model
from fairseq.model... |
from io import StringIO
import warnings
import subprocess
from pathlib import Path
from .blockelements import Face
from .geometry import _of_distribution_geometries
from .boundary_tags import BoundaryTag, _Boundary, _of_distribution_constraints
from .version import __version__
import numpy as np
init_pos = np.arange(3... |
import psycopg2, psycopg2.extras
import sys
import os
import glob
import csv
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from matplotlib import patches
from matplotlib.pyplot import figure
from datetime import timedelta, date
from sklearn.metrics import confusion_matr... |
from typing import Callable, Union
import cv2 as cv
import numpy as np
from PIL import Image
from .parser import parser, get_var
from .objects import *
def _fromarray(arr: np.ndarray) -> Image.Image:
return Image.fromarray(
cv.cvtColor(
arr, cv.COLOR_BGR2RGB
)
)
def cv_process(st... |
"""Manages the v6 batch configuration schema"""
from __future__ import unicode_literals
import logging
import os
import re
from jsonschema import validate
from jsonschema.exceptions import ValidationError
from ingest.handlers.file_handler import FileHandler
from ingest.handlers.file_rule import FileRule
from ingest.... |
import logging
import urllib
import md5
import functools
import xmltodict
import shortuuid
import tornado.httpclient
from async_keepalive_httpc.aws.common import AWSClient
sqs_v_logger = logging.getLogger("sqs_verification")
def md5_hexdigest(data):
m = md5.new()
m.update(data)
return m.hexdigest()
... |
# Python Imports
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# Environment Variables
DATAFRAME = pd.core.frame.DataFrame
def read_excel(filename):
return pd.read_excel(filename, header=0, index_col=0)
def check_dataframe(data):
... |
'''
Copyright 2018 University of Michigan
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 o... |
import numpy as np
import torch
import os
from torch.utils.data import DataLoader
from torch import autograd, optim
from torchvision.transforms import transforms
from losses import CrossEntropy
from losses import DiceLoss
from dataset.mydataset import myDataset
from matric import segmetric
# import torch.nn.f... |
import operator
import re
from functools import reduce
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import transaction
from django.db.models import Q
from django.http import Http404
from django.urls import reverse
from tracker import search_filters
from tracker.models... |
# encoding=utf-8
import os, warnings
import sys
import pyfaidx
from rsds import SequenceContainer
from rsds import process_inputFiles
import argparse
import logging.handlers
from datetime import datetime
from rsds import man
import memory_profiler
if not sys.warnoptions:
warnings.simplefilter("default") # Change ... |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
from pprint import pprint
import pytest
from ibm_zos_ims.tests.functional.module_utils.ims_test_gen_utils import PSBInputParameters as ip
__metaclass__ = type
GEN_FAIL_MSG = 'FAILURE - PSBGEN execution unsuccessful'
SOURCE = i... |
# import serial
# import time
#
#
# #init serial
# gyro =serial.Serial("/dev/ttyACM0",115200,timeout=5)
# time.sleep(5)
# gyro.write("start".encode())
#
# while True:
#
# row_value =gyro.readline()
# print(row_value.decode())
# !/usr/bin/env python
from OpenGL.GL import *
from OpenGL.GLU import *
import pygame
fro... |
import itertools
assignments = []
rows = 'ABCDEFGHI'
cols = digits = '123456789'
square_rows = ('ABC', 'DEF', 'GHI')
square_cols = ('123', '456', '789')
def cross(A, B):
"Cross product of elements in A and elements in B."
return [r + c for r in A for c in B]
boxes = cross(rows, cols)
row_units = [cross(r, c... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pandas as pd
import _init_paths
import os
import os.path as osp
import cv2
import logging
import argparse
import motmetrics as mm
import numpy as np
import torch
from tracker.multitracker import JDETra... |
# See: https://docs.djangoproject.com/en/1.8/topics/auth/default/#using-the-views
from django.contrib.auth import views
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, render_to_response
from django.conf import settings
from django.core.... |
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Chenest
"""
# this profile contains LSTM model for complex values.
import math
import torch
import torch.nn as nn
from complex_layers import ComplexLinear
from complex_activations import modSigmoid, modTanh
from complex_dropout import Cdropout1... |
#!/usr/bin/env python3
import requests ,json ,time
def everyWeek (OOO0O0OO0OOO0O000 ):
""
OO0OOOO0000OO0000 ='每周青年大学习\n'
O00000O00OOOOOOO0 ='http://home.yngqt.org.cn/qndxx/xuexi.ashx'
OOOO000OOOOOOOO0O ={"Host":"home.yngqt.org.cn","Accept":"application/json, text/javascript, */*; q=0.01","X-Reque... |
"""
##### Unfinished module ######
The functions in this module provide utilities to build all possible paths
in a tree. The paths can later be used to navigate the tree and perform
operations with its nodes.
This procedure is highly inefficient when the tree is very big, so it is
recommended to use these functions on... |
# Import Libraries
import config
import imdb
import json
import requests
from googlesearch import search
from bs4 import BeautifulSoup
from pygoogletranslation import Translator
import smtplib
# Configure Browser Header and URL
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36... |
from typing import Optional
import click
from montag.cli import spotify, ytmusic
from montag.cli.support import handle_response
from montag.domain.entities import (
Playlist,
PlaylistId,
Provider,
SuggestedTrack,
Track,
TrackId,
TrackSuggestions,
)
from montag.system import System
from mont... |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import os
from typing import Iterable
from pants.backend.python.subsystems.ipython import IPython
from pants.backend.python.subsystems.setup import Pyt... |
""" Functions for accessing the Herschel Science Archive """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import astropy.io.fits as fits
import astropy.io.votable
import urllib, shutil, os, tempfile
import numpy ... |
import json
import os.path
import random
import dnd.err
import dnd.jsonutil
import dnd.template
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Any, Dict, List, Optional, Tuple, Union
from dnd.jsonutil import Number
def _pathparts(path: "str") -> "list[str]":
parts = list()
r... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""=================================================================
@Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3
@File : LC-1584-Min-Cost-to-Connect-All-Points.py
@Author : [YuweiYin](https://github.com/YuweiYin)
@Date : 2022-04-26
====================... |
import argparse
import os
from os.path import join
from keras import backend as K
from keras.models import load_model
import pydicom as pyd
import numpy as np
import cv2
import pyinotify
import asyncio
import mvp
parser = argparse.ArgumentParser()
def make_predictition_acr(image, model_path='/home/haimin/PycharmPr... |
from collections import defaultdict
from typing import Any, Dict, Iterator, List, Tuple
from sphinx.domains import Index, IndexEntry
from sphinx.domains.javascript import JavaScriptDomain
from sphinx.locale import __
from sphinx.util import logging
from sphinx.util.console import bold
logger = logging.getL... |
"""
This module is used to batch requests to the Graph Batch endpoint. Two additional functions,
get_object_assignment and get_object_details is used to retrieve the objects assignment and details from
the batch request.
Parameters batch_request
----------
data : list
List of object IDs to get data for
url : str
... |
import requests
import os
import time
import server
import utils
import routine
from threading import Thread
from replit import db
from datetime import datetime
from matplotlib import pyplot as plt
routine.delete_logs()
WEBHOOKS_EBK = os.getenv('WEBHOOKS_EBK').split(',')
USERNAME_EBK = 'ebk'
WEBHOOKS_MISFIT = os.get... |
# (c) 2019 <NAME>
# This file is part of nuskybgd released under MIT License.
# See LICENSE file for full details.
import astropy.io.fits as pf
import os
import numpy as np
from . import caldb
from . import util
def add_abs_hdu(detabshdu, rmfhdu):
"""
Add detector absorption to response matrix. Doing so may ... |
import cv2
import numpy as np
def rot_from_euler_4D(theta):
R_x = np.array([[ 1, 0, 0, 0 ],
[ 0, np.cos(theta[0]), -np.sin(theta[0]), 0 ],
[ 0, np.sin(theta[0]), np.cos(theta[0]), 0 ],
[ 0, 0, 0, ... |
import os
import copy
import numpy as np
from scipy.spatial import distance
import PELEpharmacophore.helpers as hl
import PELEpharmacophore.analysis.grid as gr
import PELEpharmacophore.analysis.simulation_analyzer as sa
import PELEpharmacophore.output.pharmacophore_writer as pw
class GridAnalyzer(sa.SimulationAnalyzer... |
"""
Google Calendar Interface
"""
import logging
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Dict, List
import pyrfc3339 as rfc3339
from dateutil import tz
from dateutil.tz import tzutc
from file_secrets import secret
from google.oauth2.credentials import Crede... |
"""
Main file used to run the Redtest Helloworld API.
.. moduleauthor:: <NAME> <<EMAIL>>
*Date: 06/03/2020*
*License:*
*Copyright (C) 2019 "IoT.bzh"*
*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 c... |
#!/usr/bin/env python
#
# 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.
import argparse
import json
import os
import sys
import tempfile
import zipfile
from util import build_utils
from util import progua... |
#!/bin/sh
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
''''exec python -u -- "$0" ${1+"$@"} # '''
import os
import sys
from pathlib import Path
from datetime import datetime
# Add lib folder to path to import boto3 library.
# Normally with Lambda Layers, python ... |
from uuid import uuid4
from urllib import parse as urlparse
from flask import jsonify, request, Blueprint
from flask_restless import APIManager
from sqlalchemy.orm.attributes import InstrumentedAttribute
from flask_restless.helpers import *
sqlalchemy_swagger_type = {
'INTEGER': {'type': 'integer', 'format': 'int6... |
import pygame, sys, random, math
from tkinter import messagebox, Tk
size = (width, height) = 640, 480
cols, rows = 64//2, 48//2
grid = []
openSet, closeSet = [], []
path = []
w = width//cols
h = height//rows
class Spot:
def __init__(self, i, j):
self.x, self.y = i, j
self.f, self.g, self.h =... |
# coding=utf-8
#
"""Classes and functions for configuring BIG-IP"""
# Copyright 2014 F5 Networks 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/LIC... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..initializer import create_initializer
from ..functions.shake_shake_function import get_alpha_beta, shake_function
class ResidualPath(nn.Module):
def __init__(self, in_channels, out_channels, stride):
super().__init__()
sel... |
# Copyright 2020 <NAME>
"""
Configuration-related helpers.
"""
# Adapted from Black https://github.com/psf/black/blob/master/black.py.
import configparser
import os
import pathlib
import attr
import click
import toml
@attr.s
class InterrogateConfig:
"""Configuration related to interrogating a given codebase.
... |
import pandas as pd
import numpy as np
import os
import time
import shutil
import multiprocessing
from collections import Counter
# Cantidad de Cores a ejecutar
n_core = 5
# Lista de Procesos con cada tipo de review
review_process = list()
# Lista con caracteres especiales
_Review__characters = [',', '.', '(', ')',... |
import theano
import theano.tensor as T
from theano.tensor.signal import downsample
from theano.tensor.nnet import conv
import numpy
import math
from .hidden_layer_model import HiddenLayerModel
from .logistic_regression_model import LogisticRegressionModel
class LeNetConvPoolLayer(object):
"""Pool Layer of a con... |
# -*- coding: utf-8 -*-
# FSRobo-R Package BSDL
# ---------
# Copyright (C) 2019 FUJISOFT. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above... |
import yaml
import os
from enum import Enum
from metaroot.utils import get_logger
class ConfigParams(Enum):
"""
Named parameters used for mapping configuration file content to getters
"""
MQUSER = 'MQUSER'
MQPASS = '<PASSWORD>'
MQHOST = 'MQHOST'
MQPORT = 'MQPORT'
MQNAME = 'MQNAME'
... |
"""Module for the markdown file writer"""
from abc import abstractmethod, ABCMeta, ABC
from typing import Optional, Union
class MarkdownElementError(Exception):
def __init__(self, message: str):
super().__init__(message)
class MarkdownElement(metaclass=ABCMeta):
"""Superclass for all markdown elemen... |
#contentRecog/recogUi.py
#A part of NonVisual Desktop Access (NVDA)
#Copyright (C) 2017 NV Access Limited
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
"""User interface for content recognition.
This module provides functionality to capture an image from the sc... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
from numpy.testing import assert_allclose
from astropy.tests.helper import pytest
import itertools
from ..background import Back... |
import pytest
from tiletanic.tileschemes import DGTiling
@pytest.fixture
def tiler():
return DGTiling()
def test_bounds(tiler):
"""Geographic bounds."""
assert tiler.bounds.xmin == -180.
assert tiler.bounds.xmax == 180.
assert tiler.bounds.ymin == -90.
assert tiler.bounds.ymax == 90.
d... |
import json
import unittest
import pkg_resources
import pytest
from pydantic import ValidationError
from spacenet import test
from spacenet.schemas import edge as eos
from spacenet.schemas.edge import EdgeType, FlightEdge, SpaceEdge, SurfaceEdge
pytestmark = [pytest.mark.unit, pytest.mark.edge]
class TestEdge(unit... |
import logging
import logging.handlers
import sys
import threading
from sw_utils.dummy_obj import DummyObj
from sw_utils.logs.logger import SwLogger, SwSelectiveLogger, SwLoggerAdapter
from sw_utils.logs.constants import TRACE_LVL
from sw_utils.logs.utils import pre_log
t_data = threading.local()
#ToDo: Poner un parc... |
# MIT License
#
# Copyright (c) 2019 Morning Project Samurai (MPS)
#
# 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, cop... |
import warnings
import numpy as np
from pymanopt.manifolds.manifold import RiemannianSubmanifold
class _SphereBase(RiemannianSubmanifold):
def __init__(self, *shape, name, dimension):
if len(shape) == 0:
raise TypeError("Need at least one dimension.")
self._shape = shape
supe... |
# -*- coding: utf-8 -*-
"""
model_300_basicStVs.py: models discharge and erosion across a topographic
surface assuming (1) stochastic Poisson storm arrivals, (2) single-direction
flow routing, and (3) a variable-source-area (VSA) runoff-generation model.
Model 300 BasicStVs
This model combines linear diffusion and ba... |
import csv
import tarfile
import zipfile
import os
from tempfile import gettempdir, mkstemp
from uuid import uuid4
from os import path, makedirs, getenv
from shutil import rmtree, copy
from bigdatavoyant import RasterData
from flask import abort
from flask_wtf import FlaskForm
from werkzeug.utils import secure_filenam... |
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "l... |
import random
import os
import torch
import torch.optim as optim
import torch.nn.functional as F
import torchvision.transforms as transforms
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from tqdm import tqdm
from torch.autograd import Variable
from PIL import Image
from ... |
# -*- coding: utf-8 -*-
"""Module providing blog category management"""
from future import standard_library
standard_library.install_aliases()
from builtins import next
from builtins import str
import datetime
import json
import time
import urllib.request, urllib.error, urllib.parse
from AccessControl import Unauthori... |
# STAGE-1 Importing dependidecies
import numpy as np
import math
import re
import pandas as pd
from bs4 import BeautifulSoup
import tensorflow as tf
from tensorflow.keras import layers
import tensorflow_datasets as tfds
# Stage 2 Importing the dataset
cols = ["sentiment", "id", "date", "query", "user", "text"]
trai... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
from datetime import timedelta
import pytest
from django.utils import timezone
from reprohack_hub.models import Event, Paper, Review, PaperReviewer
from reprohack_hub.models import User
from reprohack_hub.tests.factories import ReviewFactory, EventFactory, ... |
# coding=utf-8
#from common.cache_tool import get_cache
from portal.models import *
from common.log_tool import get_logger
# def load_from_cache(key, time):
# '''
# 返回key对应的缓存,time是缓存的有效时间,秒为单位,如果不存在就调用fun函数获取
# '''
# def __fun_deco(fun):
# def __fun_arg_deco(*args, **kwargs):
# ca... |
"""
The ROP module contains a function to find gadgets in ELF binaries that can
be used to create ROP chains.
"""
from __future__ import print_function
import argparse
import re
import six
import sys
import pwnypack.codec
import pwnypack.elf
import pwnypack.main
import pwnypack.asm
import pwnypack.target
import pwnypa... |
import torch
from torch import nn
from torch_scatter import scatter
import numpy as np
from abc import abstractmethod, ABC
from .utils import repeat_counts
from .event_representation import EventRepresentation
class HandCraftedSurface(nn.Module, ABC):
def __init__(self, frame_size, bins):
super().__ini... |
# Python 2 and 3 support
from future.standard_library import install_aliases
install_aliases()
import urllib.request
import urllib.error
import urllib.parse
import logging
import jsonpatch
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
from sendgrid.helpers.mail import Email
from sendgr... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from MTNN.utils import deviceloader, logger
from abc import ABC, abstractmethod
#=====================================
# Loss functions
#=====================================
mse_loss = lambda outputs, true_outputs : torch.sum(F.mse_loss(outputs, true... |
#!/usr/bin/env python
# AUTHOR: jo
# DATE: 2019-09-15
# DESCRIPTION: "Sudoku Solver" problem from codewars
# PROBLEM: https://www.codewars.com/kata/sudoku-solver/train
from os import system
from time import sleep
puzzle = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, ... |
from itertools import product
from pprint import pprint
search_range = 0.4
ROTATION_LEN = 5
##################
# Ragular Config #
##################
# PROD_COUNTS = (63, 10, 11, 1, 1)
# PROD_ITEM_COUNTS = (200, 160, 100, 160, 100)
#
# STORE_COUNTS = (2, 6, 9)
# STORE_ROTATION_COUNTS = (182, 182, 184)
#
# PROD_STOR... |
"""Use the existing VGG16 classifications to feed into a linear model.
In this example, what we'll be doing is using the second last layer of
the VGG16 model and training a new linear layer to just give us the
probability that an image is a cat or a dog, thus reducing the dimensions
of the image down from 4096 to 2.
... |
#!/usr/bin/env python
"""Add new functionality to allow logger to exit."""
import logging
import sys
from datetime import datetime
CRITICAL = logging.CRITICAL
FATAL = logging.FATAL
ERROR = logging.ERROR
WARNING = logging.WARNING
WARN = logging.WARN
INFO = logging.INFO
DEBUG = logging.DEBUG
NOTSET = logging.NOTSET
# ... |
#!/usr/bin/env python3
from smbus2 import SMBus
from mlx90614 import MLX90614
import cv2
import numpy as np
import face_recognition
import os
from datetime import datetime
# import serial
import time
import json
# from PIL import ImageGrab
tempList = []
mList = []
tCheck = []
tempCounts = 0
textState = 0
start = 0
f... |
# -*- coding: utf-8 -*-
"""
LoggedFS-python
Filesystem monitoring with Fuse and Python
https://github.com/pleiszenburg/loggedfs-python
tests/lib/procio.py: Library routines, processes, I/O, ...
Copyright (C) 2017-2020 <NAME> <<EMAIL>>
<LICENSE_BLOCK>
The contents of this file are subject to the Apache License
Ve... |
import pathlib
import logging
import pandas
import pytest
from unittest.mock import patch, call
@pytest.fixture
def listing():
return ["noaa-goes16/ABI-L1b-RadC/2020/060/12/"
"OR_ABI-L1b-RadC-M6C10_G16_s202006012"
+ m
for m in [
'01142_e20200601203527_c202006012... |
from sklearn.ensemble import BaggingRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import AdaBoostRegressor
import os
from sklearn.tree import DecisionTreeRegressor
import water.SVR.data_generate as data_generate
import numpy as np
from sklearn.svm import SVR
from sklearn.pipeline im... |
################################################################
# System's dependencies
################################################################
import os
import sys
import time
import argparse
################################################################
# Local dependencies
##############################... |
from ast import literal_eval
from pwn import *
import fuckpy3
import string
USERNAME = "Qwaz"
PROC = None
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise... |
import math
import random
import numpy as np
from numpy import random
from H_Hy_Men import VRPLibReader
import copy
def value_function(distmat, list1, weight, things):
s = 0
w = weight
tlist = list(list1).copy()
tlist.insert(0, 0)
for i in range(0, len(tlist) - 1):
w = w - things[tlist[i +... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import logging
import simple_audit
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django_extensions.db.fields.encrypted import (EncryptedCharField,
... |
"""
<NAME>
CS152A Final Project
December 1, 2021
File to make the multidimensional array for the icebreaker routing project.
Cannot be run from terminal, part of the modular design.
"""
import random
class Map:
def __init__(self, rows = 10, columns = 10, obstacles = 10):
"""Initialization function for th... |
# SPDX-FileCopyrightText: Copyright (c) 2021 <NAME>
#
# SPDX-License-Identifier: MIT
# Many Pylnt conventions are broken for the sake of test readability
# Others fail because Pylint doesn't understand Pytest.
# Therefore skip this file.
# pylint: skip-file
import pytest
from CircuitPython_AS3935 import biffobear_as3... |
import csv
import click
from dataclasses import dataclass
from io import IOBase
from typing import Iterable, Mapping, Optional, Sequence, Tuple, Union
import numpy as np
from slicedimage import ImageFormat, Tile, WriterContract
from starfish.core.experiment.builder import FetchedTile, TileFetcher, write_irregular_ex... |
import tensorflow as tf
from utils.bert import bert_utils
from utils.adversarial_utils import logits_utils
from utils.adversarial_utils import perturbation_utils
"""
taken from https://github.com/takerum/vat_tf
"""
def kl_divergence_with_logit(q_logit, p_logit):
# [batch_size, seq_length, classes]
q_logit = tf.nn.l... |
# Copyright 2017 BlueCat Networks (USA) Inc. and its affiliates
# 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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.