text stringlengths 957 885k |
|---|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from gi.repository import Notify
from PySide import QtCore, QtGui, QtDeclarative
import subprocess
import os
import datetime
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop
try:
from gi.repository import Unity
LAUNCHER = Unity.LauncherEntry.get_for_de... |
from __future__ import print_function
import numpy as np
import nlcpy as vp
import numba
from math import *
import time
# target libraries
nb = 'numba'
vp_naive = 'nlcpy_naive'
vp_sca = 'nlcpy_sca'
@numba.stencil
def numba_kernel_1(din):
return (din[0, 0, -1] +
din[0, 0, 0] +
din[0, 0, 1]... |
import json
import logging
import os
import shutil
import sys
import tarfile
import numpy as np
from qtpy import QtCore
import llspy
import llspy.gui.exceptions as err
from llspy.gui.helpers import byteArrayToString, newWorkerThread, shortname
logger = logging.getLogger(__name__) # set root logger
try:
_CUDAB... |
<reponame>EuphoriaYan/sales_pred
# -*- coding: utf-8 -*-
# @Time: 2021/3/13 15:47
# @Author: Euphoria
# @File: model.py
import os
import sys
import torch
from torch import nn
# 很简单的3层mlp
class mlp(nn.Module):
def __init__(self, in_feature, **kwargs):
super().__init__()
self.in_feature = in... |
<filename>bfd/datastore/logic.py
"""
Defines the logical operations that make use of the data layer.
Copyright (C) 2020 <NAME>.
"Commons Clause" License Condition v1.0:
The Software is provided to you by the Licensor under the License, as defined
below, subject to the following condition.
Without limiting other con... |
#!/usr/bin/env python3
""" This entry knows how to manipulate Python's module path to jump the queue.
"""
import sys
def use(abs_packages_dir):
"""Make an entry that contains an installed pip package the preferred location to import the package from.
Usage examples :
axs byname numpy_1.16.4_pip... |
<gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.Principal import Principal
class SignTask(object):
def __init__(self):
self._biz_data = None
self._biz_id = None
self._cb_ty... |
<gh_stars>0
"""
Import as:
import core.signal_processing as csigna
"""
import collections
import functools
import logging
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
import pandas as pd
import pywt
import helpers.dataframe as hdataf
import helpers.dbg as dbg
_LOG = loggi... |
from PIL import Image, ImageDraw, ImageFont
import math
def get_widths(columns, sizes, participants_by_column, PARTICIPANTS_PER_COLUMN, COLUMN_MARGIN):
# Calculate the last column on its own
columns_width = []
for col_number in range(0, columns):
column_length = len(participants_by_column[col_number])
te... |
# by cefuve electronics
# Github: https://www.github.com/cefuve
# Webpage: https://www.cefuve.com
import serial, sys, time
import PySimpleGUI as sg
import serial.tools.list_ports
ports = list(serial.tools.list_ports.comports())
puertos = []
conectado = False
Arduino = None
#Get port devices
for p in port... |
<reponame>LP-CDF/AMi_Image_Analysis<filename>Setup_local.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 20 09:57:50 2020
"""
__date__ = "11-03-2021"
import os
import sys
import argparse
from pathlib import Path
import stat
from utils import _RAWIMAGES
def CreateUninstall(app_path, venv_pa... |
<reponame>yourmoonlight/maro
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import os
from statistics import mean
import numpy as np
from maro.simulator import Env
from maro.rl import AgentManagerMode, Scheduler, SimpleActor, SimpleLearner
from maro.utils import LogFormat, Logger, convert_d... |
MNIST = False
if MNIST:
import mnist as IAM
else:
#import IAM_data as IAM
import IAM_data_words as IAM
import numpy as np
import os
if MNIST:
OUTPUT_MAX_LEN_TEXTLINE = IAM.MAX_DIGITS_TOTAL
else:
# OUTPUT_MAX_LEN_TEXTLINE = 80 # textline
OUTPUT_MAX_LEN_TEXTLINE = 20 # word
BATCH_SIZE = 32
MAX_PO... |
import os
import os.path
import sys
from maintenance.stubs import packagestubs
def pymelstubs(extensions=('py', 'pypredef', 'pi'),
modules=('pymel', 'maya', 'PySide2', 'shiboken2'),
skip_module_regex=None,
pyRealUtil=False):
""" Builds pymel stub files for autocompleti... |
# -*- coding: utf-8 -*-
import click
import logging
from pathlib import Path
from dotenv import find_dotenv, load_dotenv
import json
import os
import re
from nltk.corpus import stopwords
from gensim.utils import simple_preprocess
import spacy
from gensim.models.phrases import Phrases, Phraser
def set_as_continous(vid... |
<reponame>Westlake-AI/openmixup<gh_stars>1-10
import torch.nn as nn
from mmcv.cnn import kaiming_init, normal_init, ConvModule
from ..registry import NECKS
@NECKS.register_module
class ConvNeck(nn.Module):
"""The N layers conv neck: [conv-norm-act] - conv-{norm}.
Args:
in_channels (int): Channels of ... |
#-*- encoding: utf-8 -*-
# python client for openstf STFService & Agent.
#
# Api:
# start(adbprefix=None, service_port=1100, agent_port=1090)
# stop(adbprefix=None, service_port=1100, agent_port=1090)
#
# wake() # return None
# type(text) # return None
# ascii_type(text) ... |
<gh_stars>0
import requests
import json
def make_kml_stop_without_names(overpass_base_url, kml_wrapper) :
overpass_url = overpass_base_url + '[out:json][timeout:125];area(3600008649)->.area;node["highway"="bus_stop"][!"name"][!"disused"](area.area);out skel;'
#overpass_url = overpass_base_url + '[out:json][t... |
<filename>piper/test/test_io.py
from piper.io import list_files
from piper.io import read_csv
from piper.io import read_text
from piper.io import to_tsv
from piper.io import write_text
from piper.io import zip_data
from piper.factory import bad_quality_orders
import pandas as pd
import pytest
directory = '... |
import os
import pytest
from bless.aws_lambda.bless_lambda import lambda_handler
from tests.ssh.vectors import EXAMPLE_RSA_PUBLIC_KEY, RSA_CA_PRIVATE_KEY_PASSWORD, \
EXAMPLE_ED25519_PUBLIC_KEY
class Context(object):
aws_request_id = 'bogus aws_request_id'
invoked_function_arn = 'bogus invoked_function_a... |
<reponame>lucien-sim/cloudsat-viz
#!/usr/bin/python3
import os
import pickle
import geopandas as gpd
import pandas as pd
import numpy as np
from shapely.geometry import Polygon, MultiPolygon, Point, box
import json
from rasterio.warp import calculate_default_transform, reproject, Resampling
from rasterio.transform... |
<filename>pyserver/serv_simple.py
import os.path, os
if not os.path.exists("./config_local.py"):
f = open("config_local.py", "w")
f.close()
import config, sys
if not hasattr(config, "doc_root"):
config.doc_root = os.path.abspath(os.path.normpath(os.getcwd()+"/..".replace("/", os.path.sep)))
if not os.path.e... |
from sqlite_utils.db import (
Index,
Database,
ForeignKey,
AlterError,
NoObviousTable,
ForeignKey,
)
from sqlite_utils.utils import sqlite3
import collections
import datetime
import decimal
import json
import pathlib
import pytest
from .utils import collapse_whitespace
try:
import pandas a... |
<reponame>richardeverson/warpcmap
import numpy as np
from scipy.special import betainc
from matplotlib import cm, rcParams
from matplotlib.colors import ListedColormap
from matplotlib.pyplot import gca
from scipy.optimize import root_scalar
def warp_colormap(basemap, z, beta=1, Nentries=256):
"""
Construct a n... |
"""
Provides the main Hibiki class used for the music synchronization.
"""
import json
import os
import os.path
import random
import shutil
from .config import HibikiConfig
from .itunes import iTunesLibrary
class Hibiki(object):
"""Main class used for the music syncing."""
def __init__(self, config=None):
... |
import os, uuid, time
from datetime import datetime
import boto3
import requests
from urllib3.util import Url
from .parallel_logger import logger
from .utils import sizeof_fmt, measure_duration_and_rate
class BundleStorer:
def __init__(self, bundle, dss_url, use_rest_api=False, report_task_ids=False):
... |
import matplotlib.pyplot as plt
from beast.observationmodel.noisemodel import toothpick
from beast.physicsmodel.grid import SEDGrid
from beast.plotting.beastplotlib import set_params
__all__ = ["plot_toothpick_details"]
def plot_toothpick_details(asts_filename, seds_filename, savefig=False):
"""
Plot the de... |
# -*- coding=utf-8 -*-
from flask import render_template, request, current_app, flash
from flask import jsonify, json
from flask_login import login_required
from xp_mall.extensions import db
from xp_mall.utils import redirect_back
from xp_mall.admin.admin_module import admin_module
from xp_mall.models.goods import Go... |
<reponame>sergej-C/dl_utils<gh_stars>0
import os
from os import listdir
from os.path import isfile, join
from shutil import copyfile, copy
from glob import glob
import numpy as np
def test():
print 'test'
def mkdir_ifnotexists(path):
"""
create a folder with the specified path if not exists
"""
if... |
<reponame>jowage58/cassyy
"""
Central Authentication Service (CAS) client
"""
import dataclasses
import logging
import urllib.parse
import urllib.request
import xml.etree.ElementTree
from typing import Dict, Optional, Union
logger = logging.getLogger(__name__)
def _fetch_url(url: str, timeout: float = 10.0) -> bytes... |
<filename>protlearn/features/moran.py
# Author: <NAME> <<EMAIL>>
import numpy as np
import pandas as pd
from ..utils.validation import check_input, check_alpha, check_natural
import pkg_resources
PATH = pkg_resources.resource_filename(__name__, 'data/')
# default indices of AAIndex1 (Xiao et al., 2015)
default = ['C... |
import sys
sys.path.extend(['..'])
import tensorflow as tf
config = tf.ConfigProto(log_device_placement=False)
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
from generator.generate_code import *
from nltk.translate.bleu_score import corpus_bleu
from config.config import *
from base.BaseModel... |
<reponame>aisportsbets/pygrid
from base64 import b64encode, b64decode
from json import dumps
from syft import deserialize
from syft.core.store.storeable_object import StorableObject
from syft.core.store import Dataset
from syft.core.common import UID
from flask import current_app as app
import torch as th
import pytes... |
<reponame>py-az-cli/py-az-cli<gh_stars>0
'''
Manage kusto pool with synapse
'''
from .... pyaz_utils import _call_az
def list_sku(name, resource_group, workspace_name):
'''
Returns the SKUs available for the provided resource.
Required Parameters:
- name -- The name of the Kusto pool.
- resource_g... |
<gh_stars>0
import random
class Igralec :
def __init__(self, ime, simbol) :
self.ime = ime
self.simbol = simbol
def Preveri_simbol(simbol1, simbol2) :
if len(simbol1) == 1 and len(simbol2) == 1 :
return True
else :
return False
class Igra :
d... |
import debug # pyflakes:ignore
import factory
import datetime
from django.conf import settings
from ietf.doc.models import Document, DocEvent, NewRevisionDocEvent, DocAlias, State, DocumentAuthor, StateDocEvent
from ietf.group.models import Group
def draft_name_generator(type_id,group,n):
return '%s-%s-%s... |
# This Python module is part of the PyRate software package.
#
# Copyright 2017 Geoscience Australia
#
# 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/... |
#!/usr/bin/python
"""
Configure filebrowser service
"""
import os
import sys
import json
import bcrypt
import logging
import coloredlogs
import argparse
from urllib.parse import quote, urljoin
from subprocess import run, call
import functions as func
### Enable logging
logging.basicConfig(
format='%(asctime)s ... |
# Combo helpers independent of GUI framework - these operate on
# SelectionCallbackProperty objects.
from __future__ import absolute_import, division, print_function
import weakref
from glue.core import Data, Subset
from glue.core.hub import HubListener
from glue.core.message import (DataReorderComponentMessage,
... |
<filename>test/test_user_store.py
import unittest
from models.user import User, UserError
from models.user_store import UserStore
from elasticsearch import Elasticsearch
import time
from itsdangerous import (TimedJSONWebSignatureSerializer
as Serializer, BadSignature, SignatureExpired)
class Te... |
import codecs
import csv
import argparse
import re
METRIC_FILE = 'logs/chatbot_metrics.txt'
CLASSES_FILE = 'logs/class_correspondances.csv'
PROPERTIES_FILE = 'logs/property_correspondances.csv'
UNDER_BRACKETS_RE = re.compile('\[(.*?)\]')
DATE_FORMAT = '%Y-%m-%d %H:%M:%S,%f'
CSV_PROPERTIES_HEADER = ['domain_field',
... |
# Databricks notebook source exported at Mon, 14 Mar 2016 03:21:05 UTC
# MAGIC %md
# MAGIC **SOURCE:** This is from the Community Edition of databricks and has been added to this databricks shard at [/#workspace/scalable-data-science/xtraResources/edXBigDataSeries2015/CS100-1x](/#workspace/scalable-data-science/xtraRes... |
from typing import Optional
import torch
from torch.nn import functional as F
def aa_to_rotmat(theta: torch.Tensor):
"""
Convert axis-angle representation to rotation matrix.
Works by first converting it to a quaternion.
Args:
theta (torch.Tensor): Tensor of shape (B, 3) containing axis-angle r... |
<reponame>Stegallo/adventofcode
from .common import AoCDay
class Day(AoCDay):
def __init__(self):
super().__init__(16)
def _preprocess_input(self):
self.__input = [i for i in self._input_data]
def _calculate_1(self):
# info(self._input_data)
# return 0
rules = {}
... |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from matplotlib.ticker import EngFormatter, ScalarFormatter
def clip(value_before_switch, value_after_switch, t_switch, t):
"""
logical function of time. Changes value at threshold time t_switch.
"""
if t <= t_switch:
return... |
<reponame>kcotar/Gaia_clusters_potential
import numpy as np
from astropy.table import Table
from copy import deepcopy
class ISOCHRONES():
"""
"""
def __init__(self, file_path, photo_system='UBVRIJHK'):
"""
:param file_path:
:param photo_system: Can be UBVRIJHK or Gaia
""... |
<reponame>Bensonlmx/data.gov.sg-visualisations-using-pandas-matplotlib
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv('/Users/benson/Desktop/Upskilling/SP/IT8701 Introduction to Programming for Data Science/CA2/median-rent-by-town-and-flat-type.csv', sep=',')
re2020 = '^2020'
... |
import random
import threading
import functools
from collections import Counter
from src.gamemodes import game_mode, GameMode
from src.messages import messages
from src.containers import UserList, UserDict
from src.decorators import command, handle_error
from src.functions import get_players, change_role
from src.statu... |
from onegov.ballot import ElectionCollection
from onegov.ballot import ElectionCompoundCollection
from onegov.ballot import VoteCollection
from onegov.election_day.collections import DataSourceCollection
from onegov.election_day.collections import DataSourceItemCollection
from onegov.election_day.collections import Ema... |
import pandas as pd
from utils.storage import load_frame, dump_frame, DATA_PATH, check_if_stepframe, check_if_vecframe
def daySplitter(step_name, data_path=DATA_PATH):
"""
Splits entries into days and saves results as vecframe.
"""
stepframe = load_frame(step_name, data_path)
check_if_stepframe(s... |
<gh_stars>1-10
from __future__ import division
import os, gc
import pandas as pd
import ipywidgets as widgets
from seaborn import get_dataset_names
from IPython.display import display
from glob import glob
from contextlib import suppress
class DataFrameLoader(object):
def __init__(self, filename=""):
self... |
<reponame>zutn/Simple-Catchments-Hesse
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 19 09:44:13 2019
@author: <NAME>
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.interpolate import interp1d
import math
import matplotlib.patches as patches... |
<reponame>jlin/inventory<filename>core/keyvalue/views.py
from django.shortcuts import render
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.http import HttpResponse
from django.http import Http404
from core.keyvalue.utils import get_aa, get_docstrings
import simplejson as json
fro... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class Competition(models.Model):
name = models.CharField(max_length=128, blank=False)
introduction = models.CharField(max_length=8096, blank=False, default="")
parameters_description = models.CharField(max_length=1024,... |
import logging
import salt.exceptions
import saltext.vmware.utils.common as utils_common
import saltext.vmware.utils.datacenter as utils_datacenter
# pylint: disable=no-name-in-module
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
log = logging.getLogger(_... |
<reponame>ubcbraincircuits/pyDynamo
from PyQt5.QtGui import QPen, QPainter, QBrush, QFont, QColor
from PyQt5.QtCore import Qt, QPointF, QRectF
import matplotlib.pyplot as plt
import numpy as np
import pydynamo_brain.util as util
from .branchToColorMap import BranchToColorMap
_BRANCH_TO_COLOR_MAP = BranchToColorMap(... |
# Copyright 2017. <NAME>. 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 copyright notice, this list of conditions and the following
# dis... |
import sys
import gym
import pylab
import random
import numpy as np
from collections import deque
import torch
from torch import nn, optim
import torch.nn.functional as F
'''
일단 하이퍼파라미터에 None이라고 되어있는 부분 위주로 수정해주세요. (다른 것들 잘못 건드시면 안될수도 있음)
cartpole_dqn.py에 있는 예제 그대로 복사하셔도 됩니다.
하지만 이것 저것 수정해 보시면서 더 좋은 에이전트를 만들어 보는 것도 좋... |
<reponame>sherry255/locust<gh_stars>0
# -*- coding: utf-8 -*-
import csv
import json
import sys
import traceback
import gevent
import requests
from gevent import pywsgi
from locust import events, runners, stats, web
from locust.core import Locust
from locust.main import parse_options
from locust.runners import Locust... |
<reponame>zhouwenfan/temp
# Author: <NAME>
import unittest
from kernel.type import TVar, Type, TFun, boolT
from kernel.term import Var, Const, Term
from kernel.thm import Thm
from kernel.extension import AxType, AxConstant, Theorem, Attribute
from logic import logic, induct
imp = Term.mk_implies
eq = Term.mk_equals
... |
#!/usr/bin/env python
# Variables needed for pre-setting up the session.
session_type = 'train'
# ========== Variables needed for the session itself. ========
# === Variables that are read from the cmd line too. ===
# WARN: Values given in cmd line overwrite these given below.
out_path = "./output/mnist100/"
device =... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Visualization routines using matplotlib
"""
import copy
import logging
import numpy as np
from astropy import units as u
from matplotlib import pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.colors import Normalize, L... |
<reponame>viitormiiguel/AnalysisFinancial<filename>BuildLex/countWords.py
import sys
import codecs
import nltk
from nltk.corpus import stopwords
from nltk import pos_tag, word_tokenize
import csv
import datetime
from collections import Counter
import re
import math
from textblob import TextBlob as tb
now ... |
<gh_stars>1-10
#!/usr/bin/python
# -*- coding: utf-8 -*-
import functools
import re
try:
unicode('a')
except:
unicode=str
from ..logger import get_module_logging
logging = get_module_logging(__name__)
navigator_domains = []
#FIXME: hacks!
isDataset = lambda ds: (hasattr(ds, 'dstype') and hasattr(ds, 'datatype... |
import requests
import json
import UnityClasses
from .UnityClasses import *
requests.packages.urllib3.disable_warnings()
class Unity:
""" Class representing an EMC Unity Array """
def __init__(self, ip_addr, username, password):
self.ip_addr = ip_addr
self.username = username
... |
<gh_stars>10-100
# Copyright 2019 The OpenSDS 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... |
<filename>skibidi/backend/models.py
from typing import Protocol
from django.db import models
from django.db.models.deletion import CASCADE
from django.contrib.auth.models import User
class Kind(models.Model):
kind_id = models.AutoField(primary_key=True)
kind_name = models.CharField(max_length=255, null=False,... |
import torch
from .util import enable_running_stats, disable_running_stats
import contextlib
from torch.distributed import ReduceOp
class GSAM(torch.optim.Optimizer):
def __init__(self, params, base_optimizer, model, gsam_alpha, rho_scheduler, adaptive=False, perturb_eps=1e-12, grad_reduce='mean', **kwargs):
... |
"""
BAE (BAE: BERT-Based Adversarial Examples)
============================================
"""
from textattack.constraints.grammaticality import PartOfSpeech
from textattack.constraints.pre_transformation import (
RepeatModification,
StopwordModification,
)
from textattack.constraints.semantics.sentence_encod... |
<gh_stars>10-100
"""Helps to collect information about the host of an experiment."""
import os
import platform
import re
import subprocess
from xml.etree import ElementTree
import warnings
from typing import List
import cpuinfo
from sacred.utils import optional_kwargs_decorator
from sacred.settings import SETTINGS
... |
import torch
from torch.nn import Sigmoid
from transformers.modeling_bert import BertModelWithHeads
import pytorch_lightning as pl
from pytorch_lightning.metrics import Metric
import numpy as np
from torch.nn.modules.loss import BCELoss, BCEWithLogitsLoss
from pytorch_lightning.callbacks.early_stopping import EarlyStop... |
#!/usr/bin/env python3
import json
import pathlib
HERE = pathlib.Path(__file__).parent
DATAFILE = HERE / "../port/wasm/_common/eiafx/eiafx-data.json"
GOFILE = HERE / "effect_numbers.go"
NAME = {
0: "api.ArtifactSpec_LUNAR_TOTEM",
3: "api.ArtifactSpec_NEODYMIUM_MEDALLION",
4: "api.ArtifactSpec_BEAK_OF_MID... |
<filename>venv/lib/python3.6/site-packages/ansible_collections/inspur/sm/plugins/modules/edit_ad.py
#!/usr/bin/python
# -*- coding:utf-8 -*-
# Copyright (C) 2020 Inspur Inc. All Rights Reserved.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolu... |
<filename>utils/arc.py
from .lib.dequedict import DequeDict
class ARC:
class ARC_Entry:
def __init__(self, oblock):
self.oblock = oblock
def __repr__(self):
return "({})".format(self.oblock)
def __init__(self, cache_size, **kwargs):
self.cache_size = cache_siz... |
import os
from parsimonious.grammar import Grammar
from parsimonious.nodes import NodeVisitor
class _NodeSetVisitor(NodeVisitor):
def visit_sentence(self, _, children):
return children[0]
def visit_list_form(self, _, children):
value = children[0]
for item in children[1]:
... |
<reponame>HollyXie/wae
# Copyright 2017 <NAME> Society
# Distributed under the BSD-3 Software license,
# (See accompanying file ./LICENSE.txt or copy at
# https://opensource.org/licenses/BSD-3-Clause)
"""Tensorflow ops used by GAN.
"""
import tensorflow as tf
import numpy as np
import logging
def lrelu(x, leak=0.3):... |
<reponame>mjbrewer/testIndex
# Copyright 2015 Rackspace 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 re... |
import json
import logging
from typing import List
import arrow
import cherrypy
import jose
import requests
from cryptography.fernet import InvalidToken
from jose import jwt
from simple_settings import settings
from deli.counter.auth.permission import SYSTEM_PERMISSIONS
from deli.kubernetes.resources.project import P... |
<reponame>wombat70/behave<filename>tests/unit/tag_expression/test_parser.py<gh_stars>10-100
# -*- coding: UTF-8 -*-
# pylint: disable=bad-whitespace
"""
Unit tests for tag-expression parser.
"""
from __future__ import absolute_import, print_function
from behave.tag_expression.parser import TagExpressionParser, TagExpr... |
from gridData import Grid
import numpy as np
import sys
sys.path.append("/home/abdullah/Code/Python/SFED/")
from gridcollector import GridCollector
from SFED_routines import sfed_gf_3drism, integrate_sfed
from pathlib import Path
base_path = Path(__file__).parent
data_path = file_path = (base_path / "../data/DATA/HNC... |
<reponame>calio/taski<gh_stars>0
import random
import math
from . import util
import npyscreen
orig_sorted = sorted
bag = {}
random.seed()
K = 16
# what is the expectation of Ra wins Rb
def expected(ra, rb):
return 1.0 / (1 + math.pow(10, float(rb - ra)/400))
# Ra' = Ra + K(Sa - Ea)
# Ra is A's score
# Rb is... |
<reponame>ehoogeboom/convolution_exponential_and_sylvester
import torch
import numpy as np
import torch.nn.functional as F
from models.transformations import BaseTransformation
from models.transformations.conv1x1 import Conv1x1
from models.transformations.emerging.masks import get_conv_square_ar_mask
class SquareAuto... |
<reponame>JuiceFV/stankin_pst_project<filename>application/sources/validator/vote.py
"""This module contains the class responsible for voting for a girl.
"""
import application.sources.validator.exception as errors
from matplotlib.widgets import CheckButtons
import matplotlib.pyplot as plt
class Vote:
"""The cla... |
<filename>ver6.py<gh_stars>1-10
#---------------------NEAREST NEIGHBOURS USING KD-TREES----------------------
#Imported modules and files
import math
import matplotlib.pyplot as plt #matplotlib for plotting graphs
import time
from kdtree2 import KDTree
from kdtree2 import binaryheap #The KD-Tree class
#Passing... |
########################################################################
import sys
import math
import numpy
import vtk
from heartFEM.lcleeHeart.vtk_py.createFloatArray import *
from heartFEM.lcleeHeart.vtk_py.getABPointsFromBoundsAndCenter import *
from heartFEM.lcleeHeart.vtk_py.getCellCenters ... |
from datetime import datetime
DEFAULT_CONTEXT = "default_attributes"
class AllVoiceTestUtils(object):
def get_mock_alexa_event(self, intent=None, session_id="SessionId.uuid", user_id="user_id", attributes=None, parameters=None):
mock_event = {
"session": {
"sessionId": sessi... |
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
import re
import json
import logging
logger = logging.getLogger(__name__)
# set of message types to be used when invoking send_notification
# important for client to demultiplex messages
TRANSFER_CONFIRMATION = 'TRANSFER_CONFIRMATION... |
# Generated by Django 2.2.10 on 2020-06-11 13:33
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.db.models.manager
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... |
import spotipy
from typing import List, Dict, Tuple, Set
import models
from db import Session_Factory
from threading import Thread
from time import time
from sqlalchemy import cast, desc, asc, Float
# Global Variables
scopes_list = [
"user-read-playback-state",
"user-read-email",
"playlist-read-collaborati... |
<filename>f5_cccl/test/test_f5_cccl.py
#!/usr/bin/env python
# Copyright 2017 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/LICENSE-2.... |
<reponame>rprabhuh/SDNDDoS
# encode categorical protocol name to number
def encode_protocol(text):
# put frequent cases to the front
if 'tcp' in text:
return 6
elif 'udp' in text:
return 17
elif 'icmp' in text:
return 1
elif 'hopopt' in text:
return 0
elif 'igmp' in text:
return 2
elif... |
<filename>switchboard/tasks.py
from switchboard.models import Registry, SearchQuery
import requests
import logging
from celery.decorators import task
from celery.utils.log import get_task_logger
from django.core.cache import caches
import json
import time
class SearchQueryStatusLogger(object):
''' A he... |
from gsi_handlers.gameplay_archiver import GameplayArchiver
from sims4.gsi.schema import GsiGridSchema, GsiFieldVisualizers
import services
from protocolbuffers import Sims_pb2
sim_buff_log_schema = GsiGridSchema(label='Buffs Log', sim_specific=True)
sim_buff_log_schema.add_field('buff_id', label='Buff ID', type=GsiFie... |
from functools import partial
from typing import Optional, Tuple
import torch
from torch import nn, Tensor
from torch.autograd import grad
from torch.nn import functional as F
from adv_lib.utils.losses import difference_of_logits, difference_of_logits_ratio
from adv_lib.utils.visdom_logger import VisdomLogger
def p... |
<filename>message_html.py
from bs4 import BeautifulSoup
from icecream import ic
from scrape import get_image
from quotes import Quotes
import random_stuff as rs
import itertools
import copy
from dining import DiningInfoManager, all_days, weekdays, weekends
from send import send_mail, email_recipients, debug_email, emai... |
<filename>platform/core/polyaxon/polypod/kf_experiment.py
from kubernetes.config import ConfigException
from constants.k8s_jobs import EXPERIMENT_KF_JOB_NAME_FORMAT
from db.redis.ephemeral_tokens import RedisEphemeralTokens
from polyaxon_k8s.exceptions import PolyaxonK8SError
from polypod.experiment import ExperimentS... |
<filename>multicell/unsupervised_aligned.py
import numpy as np
import os
import matplotlib.pyplot as plt
import seaborn as sns
import pickle
import umap
sns.set(style='white', context='notebook', rc={'figure.figsize':(14,10)})
from utils.file_io import RUNS_FOLDER, INPUT_FOLDER
REDUCER_SEED = 100
REDUCER_COMPONENT... |
<gh_stars>1000+
# -*- coding: utf-8 -*-
# Based upon makeunicodedata.py
# (http://hg.python.org/cpython/file/c8192197d23d/Tools/unicode/makeunicodedata.py)
# written by <NAME> (<EMAIL>)
#
# Copyright (C) 2011 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under t... |
from typing import Any, Dict, List, NewType, TYPE_CHECKING, Optional, Union
if TYPE_CHECKING:
from .client import Client as TwitchClient
import re
from .message import Message
from .user import User
from .stores import UserStore
from .userstate import UserState
from .undefined import UNDEFINED
from ..Utils.regex impo... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import, unicode_literals
__all__ = ["make_ladder", "Sampler"]
import attr
import itertools
import numpy as np
from numpy.random.mtrand import RandomState
from . import util, chain, ensemble
def make_ladder(ndim, ntemps=None, Tmax=N... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.