content stringlengths 5 1.05M |
|---|
from django.apps import AppConfig
from django.contrib.auth.signals import user_logged_in
from .config import access_and_compliance_group_name
class AccessAndComplianceConfig(AppConfig):
name = 'django_access_and_compliance'
verbose = 'Access and Compliance'
def ready(self):
from .signals import ... |
from . import APP_NAME, PROJECT_NAME, APP_BASE
def application_routes(config):
config.add_route(APP_NAME + '.home', '/')
config.add_static_view('static', 'static', cache_max_age=3600)
|
import attr
@attr.dataclass
class Pembelajaran:
rombongan_belajar_id: str
status_di_kurikulum_str: str
mata_pelajaran_id: int
nama_mata_pelajaran: str
sk_mengajar: str
ptk_terdaftar_id: str
tanggal_sk_mengajar: str
jam_mengajar_per_minggu: int
induk_pembelajaran_id: str = ""
st... |
import cmatrix as cmat
import qsim
import qgates
# demonstration of basic entangled state simulation (bell state)
# initial state |00>
state = qsim.create_state([0, 0])
# create state 1/sqrt(2)*(|00> + |10>)
state = qsim.apply_gate(state, qgates.H, 0)
# apply cnot to combined state, producing 1/sqrt(2)*... |
from collections import namedtuple
from marshmallow import Schema, fields, post_load, pre_dump
from werkzeug.exceptions import Conflict
from .exceptions import FlumpUnprocessableEntity
EntityData = namedtuple('EntityData', ('id', 'type', 'attributes', 'meta'))
ResponseData = namedtuple('ResponseData', ('data', 'li... |
from flask import Blueprint, render_template
from . import db
from flask_login import login_required, current_user
import os
import pandas as pd
import plotly.express as px
main = Blueprint('main', __name__)
# filepath = os.path.join(os.path.dirname(__file__),'results.csv')
# open_read = open(filepath,'r')
# page =''... |
# coding: utf-8
print('Já passoooou!!!')
|
from django.urls import path
from . import views
urlpatterns = [
path('district', views.add_district, name='district'),
path('Region', views.add_Region, name='Region'),
path('Ministry', views.add_Ministry, name='Ministry'),
]
|
import hashlib
import magic
import os
import re
import struct
import subprocess
from pixaxe.steg import ImageInfo, NotSupported
from assemblyline_v4_service.common.base import ServiceBase
from assemblyline_v4_service.common.result import Result, ResultSection, BODY_FORMAT
from assemblyline.common.str_utils import safe... |
import json
from tiledb import TileDBError
from tiledb.cloud import rest_api
class TileDBCloudError(TileDBError):
pass
def check_exc(exc):
internal_err_msg = (
"[InternalError: failed to parse or message missing from ApiException]"
)
# Make sure exc.status and exc.body exist before derefer... |
############################################################
# -*- coding: utf-8 -*-
#
# # # # # # #
# ## ## # ## # #
# # # # # # # # # # #
# # ## # ## ## ######
# # # # # # #
#
# Python-based Tool for interaction with the 10micron mounts
# GUI with PyQT5 fo... |
from abc import ABC, abstractmethod
import re
from commiter.src.types import Status
from commiter.src.utils import parse_printer_format_range
from commiter.src.command.observers import *
from commiter.src.backend.tasks import AbstractTask
from commiter.src.command.selectors import *
class AbstractAction(TaskObservabl... |
"""\
Self installs IronPkg into the current IronPython environment.
egg: ironpkg-1.0.0-1.egg
md5: 41787f5a12384e482e8e9f1d90f8bcdc
Options:
-h, --help show this help message and exit
--install self install
"""
import os
import sys
import base64
import hashlib
import tempfile
import zipfile
from os.path im... |
import time
import curses
HIGH = 1
LOW = 0
COL_WIDTH = 23
GAME_SECONDS = 30
class Game(object):
time = 0
score = 0
playing = False
def __init__(self, stdscr, machine_id, sensor_pin,
button1_pin, button2_pin, timer_display, score_display):
self.stdscr = stdscr
self... |
import os, shutil, zipfile, random
# Qt imports
from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot
# Local imports
from alfred import alfred_globals as ag
from . import RequestThread
from .module_info import ModuleInfo
from alfred.logger import Logger
import tarfile
class ModuleManager(QObject):
_instance ... |
import numpy as np
from astropy.coordinates.distances import Distance
from astropy import units as u
import scipy.constants as c
from astropy.cosmology import FlatLambdaCDM
cosmo=FlatLambdaCDM(H0=70,Om0=0.3)
#Flat cosmology, might want to update this
import pandas as pd
from os.path import expanduser
home = expanduser... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import numpy as np
from skimage.util import view_as_windows
import warnings, logging
import tensorflow as tf
from tensorflow.python.framework import ops
from tensorflow.python.ops import nn_grad, mat... |
from pybpodgui_api.models.user.user_io import UserIO
class User(UserIO):
pass
|
from django.db import connection
def print_queries():
retval = list()
for i, query in enumerate(connection.queries):
q = query['sql']
if q.find('SELECT "django_session"."session_key"') == 0 : continue
if q.find('SELECT "auth_user"."id", "auth_user"."password"') == 0 : continue
... |
# This Python file uses the following encoding: utf-8
# ___________________________________________________________________
# directories.py
# rosevomit.core.directories
# ___________________________________________________________________
"""This file contains the 'get_dir' function, which should theoretically be able... |
from __future__ import print_function
import unittest
import numpy as np
from SimPEG import EM
from scipy.constants import mu_0
from SimPEG.EM.Utils.testingUtils import getFDEMProblem
testJ = True
testH = True
verbose = False
TOL = 1e-5
FLR = 1e-20 # "zero", so if residual below this --> pass regardless of order
CON... |
from django.contrib import admin
from bmh_lims.database import models
from simple_history.admin import SimpleHistoryAdmin
# Register your models here.
admin.site.register(models.Sample, SimpleHistoryAdmin)
admin.site.register(models.WorkflowDefinition, SimpleHistoryAdmin)
admin.site.register(models.WorkflowBatch, Simp... |
import util
import events
import calabi_yau
import macro
'''
Uncomment to enable code reloading in development environments:
```
reload(util)
reload(calabi_yau)
```
Example:
`RunPythonScript` `~/lib/macro/build.py`
`RunPythonScript` `~/lib/macro/export.py`
'''
|
'''
This script finds the top third-party domains (TPs) setting cookies in the news websites.
Also, finds top 10 TPs and plots a barplot.
'''
import sqlite3
import matplotlib.pyplot as plt
import operator
import numpy as np
import pandas as pd
import seaborn as sns
# LEFT_TO_LEFTCENTRE
left = ["ndtv24x7","indianexpre... |
"""Register a number of portable filters (with a Coffin library object)
that require a compatibility layer to function correctly in both engines.
"""
from jinja2 import Markup
from django.utils.safestring import mark_safe, mark_for_escaping
def needing_autoescape(value, autoescape=None):
return str(autoescape)
n... |
from collections import namedtuple
import re
import spacy
from spacytextblob.spacytextblob import SpacyTextBlob
class AnalyticsCreator:
"""Adds desired datapoints to each hansard element in the inputted named_tuple. This class acts a bit like a
library of different methods that can be incorporateed as and whe... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 28 09:39:44 2021
@author: ike
"""
import os.path as op
import torch
from .endonet import EndoNet
from .resunet import ResUNet, ResUNetClassifier
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
MODELS = dict(R=ResUNet, E=E... |
# -*- coding: utf-8 -*-
"""Disaggregation related utilities"""
import logging
import numpy as np
def mains_to_batches(mains, num_seq_per_batch, seq_length, pad=True, stride=1):
"""
In the disaggregation step this is used
convert mains into batches. E.g. [0,1,2,3,4,5] with num_seq_per_batch=4, stride=1, se... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
IKA overhead stirrer.
"""
import argparse
import logging
from serial import Serial
from instruments.instrument import Instrument
from lib import helper_functions
__author__ = "Brent Maranzano"
__license__ = "MIT"
logger = logging.getLogger("instrument.Bronkhorst")
... |
# coding: utf-8
"""
Description:
Contains helper functions to assist you when working with database translations
Functions:
all_instances_as_translated_dict: Applies 'instance_as_translated_dict' to the iterable of instances
get_current_language: Returns the current active language. Will set a default langu... |
from setuptools import setup
setup(name='dmiyakawabadlogging',
version='0.1',
author='Daisuke Miyakawa',
author_email='d.miyakawa+badlogging@gmail.com',
description='Demonstrates bad logging strategy',
long_description='Demonstrates bad logging strategy',
packages=['dmiyakawabadlogg... |
# coding: utf-8
#
import functools
import inspect
import shlex
from typing import Union
import six
from ._proto import Direction
from .exceptions import SessionBrokenError, UiObjectNotFoundError
def U(x):
if six.PY3:
return x
return x.decode('utf-8') if type(x) is str else x
def E(x):
if six.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Author: José Sánchez-Gallego (gallegoj@uw.edu)
# @Date: 2018-09-22
# @Filename: mangadb.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
from peewee import (BooleanField, FloatField, ForeignKeyField,
IntegerField, Prima... |
from __future__ import print_function
from __future__ import unicode_literals
import logging
import sys
from os.path import abspath, dirname
import webbrowser
from fs.opener import open_fs
from ...context import Context
from ...command import SubCommand
from ...wsgi import WSGIApplication
from ...compat import urle... |
# -*- encoding: utf-8 -*-
#Written by: Karim shoair - D4Vinci ( Cr3dOv3r )
import sys,os
from . import updater
from .websites import *
from .color import *
def getinput(text):
# Return the suitable input type according to python version
if ver=="3":
return input(text)
else:
return raw_input(text)
def banner(... |
import _pytest.mark
import pytest
unit: _pytest.mark.MarkDecorator = pytest.mark.unit
param: _pytest.mark.MarkDecorator = pytest.mark.parametrize
web: _pytest.mark.MarkDecorator = pytest.mark.web
api: _pytest.mark.MarkDecorator = pytest.mark.api
|
importCommon()
import DicerMiRNA
#########################
## Functions: About SHAPE and Structure
#########################
class TransInfo:
def __init__(self, name):
self.full_shape = []
self.full_seq = ""
self.stem_loop = [0,0,0,0]
self.full_dot = ""
self.name = name
... |
from tkinter import *
import tkinter.messagebox
from random import *
import datetime
now = datetime.datetime.now()
def dayandnight():
if now.strftime("%X") > '16:45:39':
return 'black'
elif now.strftime("%X") < '15:40:00':
return 'white'
def dayand():
if now.strftime("%X") > '16:45:39':
return 'white'
... |
import os
import json
import yaml
from pathlib import Path
def first_time_setup(credential_location="."):
settings_path = os.path.join(credential_location, "settings.yaml")
client_secrets_path = os.path.join(credential_location, "client_secrets.json")
credentials_json_path = os.path.join(credential_locati... |
"""
Stack - List
LIFO
"""
class Stack:
def __init__(self):
self.array = []
def __str__(self):
return str(self.__dict__)
def print_length(self):
print(len(self.array))
def peek(self):
return self.array[-1]
def push(self, data):
self.array.append(data)
... |
# Copyright 2019 Google LLC
#
# 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/python
import sys
from collections import defaultdict
from collections import OrderedDict
import re
import os
import argparse
import pysam
import glob
def usage():
test="name"
message='''
RelocaTE2: improved version of RelocaTE for calling transposable element insertions
'''
print message
... |
import time
import os
import random
import httplib, urllib
import time
import nosuch.midiutil
from subprocess import call,Popen
from nosuch.oscutil import *
from time import sleep
from vsthost import VstHost,VstPlugin
from nosuch.midiutil import MidiVstHostHardware
V = VstHost()
v1 = V.getVstInstance(0)
v2 = V.getVs... |
'''
Exercício 1
Escreva um programa que recebe como entradas (utilize a função input) dois números inteiros correspondentes
à largura e à altura de um retângulo, respectivamente. O programa deve imprimir, usando repetições encaixadas
(laços aninhados), uma cadeia de caracteres que represente o retângulo informado com c... |
import logging
import pprint
import copy
import types
import six
from mixbox.entities import EntityList
from cybox.core import Object
from cybox.common import ObjectProperties
from stix.core import STIXPackage
import certau.util.stix.helpers as stix_helpers
class StixTransform(object):
"""Base cl... |
from django.utils.translation import ugettext_lazy as _
from mayan.apps.smart_settings.classes import SettingNamespace
from .literals import (
DEFAULT_CONVERTER_ASSET_STORAGE_BACKEND,
DEFAULT_CONVERTER_ASSET_STORAGE_BACKEND_ARGUMENTS,
DEFAULT_CONVERTER_GRAPHICS_BACKEND,
DEFAULT_CONVERTER_GRAPHICS_BACK... |
# coding: utf-8
"""
Inventory API
The Inventory API is used to create and manage inventory, and then to publish and manage this inventory on an eBay marketplace. There are also methods in this API that will convert eligible, active eBay listings into the Inventory API model. # noqa: E501
OpenAPI spec ve... |
a = 123
print(a)
b = a
print(b)
c = 123.4
print(c)
d = c
print(d)
e = 'こんにちは'
print(e)
f = e
print(f)
g = True
print(g)
g = False
print(g) |
import logging
from typing import Optional
from networkx import shortest_path
import pulp
from vrpy.masterproblem import _MasterProblemBase
from vrpy.restricted_master_heuristics import _DivingHeuristic
logger = logging.getLogger(__name__)
class _MasterSolvePulp(_MasterProblemBase):
"""
Solves the master p... |
from office365.sharepoint.base_entity import BaseEntity
class FieldLink(BaseEntity):
pass
|
'''' Solution uses reverse funtion to reavers each words and they are then joined in the string
using join method'''
class Solution:
def rev(self, s:str) -> str:
s = s[::-1]
return s
def reverseWords(self, s: str) -> str:
ls = s.split()
for i in range(len(ls)... |
#!/usr/bin/python
import os
import sys
def train():
os.system("python tools/train_nlu.py")
os.system("sleep 5")
os.system("python tools/train_core.py")
os.system("sleep 5")
def test():
os.system('python tools/test_core.py')
def main(todo=None):
if (todo == 't'):
train()
elif (... |
#!/usr/bin/python
# Define a stack to host a Consul cluster.
#
# Template Parameters (provided at templat creation time):
# - name
# Name of the stack, of course. Required.
# - description
# Description of the stack. Please provide one.
# - region
# The AWS region in which this template will be executed
# - buck... |
"""
Request and Response model for position book request
"""
"""
Request and Response model for trade book request
"""
from typing import Optional
from pydantic import BaseModel
from datetime import datetime
from ....common.enums import ResponseStatus
from ....utils.decoders import build_loader, datetime_decoder
__a... |
# Copyright 2019 Google LLC
#
# 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, ... |
import sys
from unittest.mock import MagicMock
import pytest
import pytorch_lightning as pl
import torch
from transformers import AutoTokenizer
from lightning_transformers.core.nlp import HFBackboneConfig
from lightning_transformers.task.nlp.translation import TranslationTransformer, WMT16TranslationDataModule
from l... |
import pandas as pd
import numpy as np
from joblib import load
model=load('app/assets/model.pkl')
"""
FEATURES USED FOR TRAINING:
['household_type', 'length_of_stay', 'case_members', 'race', 'gender',
'income', 'ethnicity', 'HIV_AIDs', 'drug_abuse', 'alcohol_abuse',
'mental_illness', 'chronic_health_is... |
import sys
# import libraries
import numpy as np
import pandas as pd
import re
from sqlalchemy import create_engine
import nltk
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import classification_report, fbeta_score, make_scorer, accuracy_s... |
from ai.action import Action
from ability import EffectType, Effect
import random
class SingleTargetAttack(Action):
def __init__(self, name: str, cooldown: int, base_crit_chance: float, effects: [Effect]):
for effect in effects:
if effect.type not in [EffectType.damage_health, EffectType.burn... |
import datetime
import logging
from .tempsensor import TempReading
from boilerio import pid, pwm
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
class TemperatureSetting(object):
def __init__(self, target, zone_width=0.6):
self._target = target
self._zone... |
#src module
from src.utilities import Preprocessing
#sklearn
from sklearn.base import BaseEstimator
class PreprocessNgram(BaseEstimator):
'''Preporcesses data for ngram features.'''
def preprocess(self, text):
upre=Preprocessing()
text=upre.replace_emojis(text)
text=upre.... |
"""
This contains functions that were not implemented (yet).
Consider them TODO items.
"""
def swatershed(f, g, B=None, LINEREG="LINES"):
"""
- Purpose
Detection of similarity-based watershed from markers.
- Synopsis
y = swatershed(f, g, B=None, LINEREG="LINES")
- I... |
#!/usr/bin/env python3
"""nested functions"""
def addBy(val):
def func(inc):
return val + inc
return func
addFive = addBy(5)
print(addFive(4))
addThree = addBy(3)
print(addThree(7))
|
import numpy as np
import pandas as pd
import pickle
import os
from bokeh.layouts import row
from bokeh.plotting import figure, output_file, show, gridplot
from bokeh.models import ColumnDataSource, FactorRange
from bokeh.palettes import Spectral6
from bokeh.transform import factor_cmap, dodge
########################... |
import click
import geojson
import requests
@click.command()
@click.argument(
'files',
required=True,
type=click.Path(
exists=True, file_okay=True, dir_okay=False, resolve_path=True),
nargs=-1)
def main(files):
"""Get GeoJSON for grid cells
"""
# Load files
# Each file should ... |
def findComplement(num):
"""
:type num: int
:rtype: int
"""
# Conver number into binary string
num_str = format(num,'b')
# List to hold individual bits
num_list = []
for i in num_str:
# Calculate the reverse
val = (int(i)+1)%2
num_list.append(str(val))
pri... |
from django.utils.functional import cached_property
from rest_framework import viewsets, mixins
from .models import (
Group,
BudgetAccountGroup,
TemplateAccountGroup,
BudgetSubAccountGroup,
TemplateSubAccountGroup
)
from .serializers import (
BudgetAccountGroupSerializer,
BudgetSubAccountGr... |
import pytest
from fastapi.testclient import TestClient
from main import app
@pytest.fixture
def client():
return TestClient(app)
def test_base_endpoint_get(client):
""" test base endpoint """
response = client.get('/')
assert response.status_code == 404
def test_base_endpoint_post(client):
... |
from block import Block
class Blockchain:
def __init__(self):
"""
This function initializes our Blockchain
Inputs Desc:
chain: collection of objects of type Block
unconfirmed_transactions:mempool i.e. pool of transactions yet to be confirmed
and inserted in the Blockchain chain
... |
import tensorflow as tf
a = tf.Variable(5)
b = tf.Variable(4.1151, name="float", dtype=tf.float16)
c = tf.Variable("english", dtype=tf.string)
d = tf.Variable(tf.ones([4, 4]))
init = tf.global_variables_initializer()
init_d = tf.variables_initializer([d])
sess = tf.Session()
sess.run(init)
sess.run(init_... |
import numpy as np
from PIL import Image
from tempfile import mkdtemp
from redpil.bmp import imwrite, imread
from pathlib import Path
import imageio
import shutil
class BMPSuite8bpp:
params = ([(128, 128), (1024, 1024),
(2048, 4096)], # (2**5 * 1024, 2 ** 5 *1024)],
['redpil', 'pillow'... |
from __future__ import print_function
"""
Author:
Jack Duryea
Waterland Lab
Computational Epigenetics Section
Baylor College of Medicine
PReLIM: Preceise Read Level Imputation of Methylation
PReLIM imputes missing CpG methylation
states in CpG matrices.
"""
# standard imports
from scipy import stats
import numpy ... |
from app import db
class Dataset(db.Model):
__tablename__ = 'dataset'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
user_id = db.Column(db.ForeignKey('user.id'), index=True)
creation_date = db.Column(db.DateTime)
modification_date = db.Column(db.DateTime)
r... |
#!/usr/bin/env python
import os
import os.path as osp
import argparse
from dataclasses import dataclass
from datetime import datetime
import numpy as np
import tqdm
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torchvision.datasets import CocoDetection, CIFAR10, ImageN... |
import os, time, sys
import matplotlib.pyplot as plt
import itertools
import pickle
import imageio
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
# G(z)
class generator(nn.Module):
# ini... |
def parse_pointer_leak(leaked_data):
if isinstance(leaked_data, bytes):
leaked_data = leaked_data.decode()
leaked_data = leaked_data.replace("(nil)", "0x0")
return list(map(lambda addr: int(addr, 16), parts))
|
"""
Based on
https://github.com/chipsalliance/chisel3/blob/master/src/main/scala/chisel3/util/Decoupled.scala
(missing support for `flow` and `pipe` parameters)
"""
import magma as m
from mantle2.counter import CounterTo
class Queue(m.Generator2):
def __init__(self, entries: int, T: m.Kind):
assert entrie... |
#! python3
import time
from colorama import Fore, Back
indent = 0
indent_increasing = True
while True:
print(" " * indent, end=" ")
print(f"{Back.RED + Fore.WHITE}*********\n\n")
time.sleep(0.1)
if indent_increasing:
indent = indent + 1
if indent == 15:
indent_increasing... |
import torch
from typing import Optional, Tuple
from pytorch_lightning import LightningDataModule
from sklearn.model_selection import train_test_split
from torch.utils.data import DataLoader, Dataset, WeightedRandomSampler, Subset
import numpy as np
import pandas as pd
from collections import Counter
from src.utils imp... |
#!/usr/bin/env python
#
# system imports
#
import cPickle, Image
from scipy.misc import fromimage
import numpy as np
import sys
#
# user defined imports
#
from DefinitionsAndUtils import *
from ImageProcessing import thresholdNDArray
from GraphAndHistogramUtilities import timeToIdx, toProbs
removeN... |
import properties
import numpy as np
from scipy.constants import mu_0
import warnings
from SimPEG.Utils import Zero
from .. import Survey, Problem, Utils
from .. import Utils as emutils
from ..Base import BaseEMSrc
class BaseFDEMSrc(BaseEMSrc):
"""
Base source class for FDEM Survey
"""
freq = prope... |
# -*- coding: utf-8 -*-
from ..libgnss.constants import *
import numpy as np
class Discriminator():
"""A channel component for performing discriminations on correlations."""
def __init__(self, flavor, channel=None):
"""Constructs Discriminator with specified flavor."""
if flavor in ['DLL']:... |
import os
import json
import logging
import requests
import urllib.parse
from datetime import datetime
# logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Google Chat Webhook URL
WEBHOOK_URL = os.environ['GOOGLE_CHAT_WEBHOOK_URL']
CARD_IMAGE_URL = os.environ['CARD_IMAGE_URL']
# HTTP Header
... |
#!/usr/bin/python3
# forms.py
########## imports ##########
from flask_wtf import FlaskForm
from wtforms import TextField, StringField, SubmitField, HiddenField, SelectField, FloatField
from wtforms.validators import DataRequired, Length, ValidationError, Email
#from app import db
from application.m... |
# -*- coding: utf-8 -*-
import os
import itertools
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import globalcache
import definitions
# sns.set(style="white", rc={"axes.facecolor": (0, 0, 0, 0)})
sns.set()
pd.options.mode.chained_assignment = 'raise'
import votesim
fr... |
#Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the #node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, #you should return NULL.
# Definition for a binary tree node.
# class TreeNode:
# def __init__... |
import cloupy as cl
import pytest
import matplotlib.pyplot as plt
import urllib.request
import urllib.error
def check_if_NOT_connected_to_the_internet(host='http://google.com'):
try:
urllib.request.urlopen(host)
return False
except urllib.error.URLError:
return True
@pytest.mark.skip... |
#!/usr/bin/python
import sys, os, getpass, subprocess, argparse, stat, logging, grp, pwd
logging.basicConfig(level = logging.INFO)
logger = logging.getLogger(__name__)
class IgnoreAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
# do nothing
pass
class... |
"""
Assigns attributes to dictionnary values for easier object navigation.
"""
from dataclasses import dataclass
from typing import Optional
from open_sea_v1.responses.abc import BaseResponse
from open_sea_v1.responses.collection import CollectionResponse
@dataclass
class _LastSale:
_last_sale: dict
def __s... |
import argparse
import os
import torch
from torch import nn, optim
from torchvision import models
from dataloader import get_dataloader
from trainer import Trainer
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--batch-size', type=int, default=64)
parser.add_argument('--lr', type=fl... |
import os, os.path
import sys
import ast
import megalex
from megalex import safelyAccessFirstString, safelyAccessStrings
import datetime
if 3 > len(sys.argv):
print("Must supply at least two parameters! Usage: \n\tbackend_KPML.py infile outfile\n")
sys.exit(1)
outfilePath = sys.argv[2]
infilePath = sys.arg... |
from metrics.Metric import Metric
from metrics.TNR import TNR
from metrics.TPR import TPR
class BCR(Metric):
def __init__(self):
Metric.__init__(self)
self.name = 'BCR'
def calc(self, actual, predicted, dict_of_sensitive_lists, single_sensitive_name,
unprotected_vals, positive_pre... |
from ..unit import Unit
from ..lin import Weights, Biases
from ..activations import Identity
from murmeltier.utils import assert_equal_or_none
class Layer(Unit):
'''
weights -> biases -> activation
'''
def __init__(self, in_specs, out_specs, activation_type = Identity, **kwargs):
self.config(i... |
from OpenGL.GL import *
import gcraft.utils.state_manager as sm
class RenderBuffer:
def __init__(self, buffer_id, texture_id):
self.texture_id = texture_id
self.buffer_id = buffer_id
def bind(self):
glBindFramebuffer(GL_FRAMEBUFFER, self.buffer_id)
def release(self):
glB... |
'''
DictUtils.py
Utility methods and classes that provide more efficient ways of handling python dictionaries
Copyright (C) 2013 Timothy Edmund Crosley
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by th... |
"""
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, software
distri... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Author: José Sánchez-Gallego (gallegoj@uw.edu)
# @Date: 2019-10-03
# @Filename: events.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
import enum
__all__ = ["CameraSystemEvent", "CameraEvent"]
class CameraSystemEvent(enum.Enum):
... |
import MySQLdb
import random
import argparse
import textwrap
# MySQL config
MYSQL_USER = 'root'
MYSQL_PASSWD = 'linux'
MYSQL_HOST = '127.0.0.1'
MYSQL_OAI_DB = 'oai_db'
# APN config
APN_NAME = 'oai.ipv4'
# MME config
MME_HOST = 'labuser.111.111'
MME_REALM = '111.111'
# PGW config
PGW_IPV4_VAL = '10.0.0.2'
PGW_IPV6_V... |
# -*- coding: utf-8 -*-
"""
Simple Counter
~~~~~~~~~~~~~~
Instrumentation example that gathers method invocation counts
and dumps the numbers when the program exists, in JSON format.
:copyright: (c) 2014 by Romain Gaucher (@rgaucher)
:license: Apache 2, see LICENSE for more details.
"""
import sys
from eq... |
# Copyright 2018 reinforce.io. 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.