content
stringlengths
0
894k
type
stringclasses
2 values
import datetime as dt from pathlib import Path import uuid from typing import Dict, Any, List, Callable import numpy as np import pandas as pd Row = Dict[str, Any] def generate_timestamp(color: str) -> str: if color == "red": weights = np.ones(12) else: weights = np.concatenate([np.ones(9)...
python
from flask import current_app, g from werkzeug.local import LocalProxy from flask_pymongo import PyMongo import shortuuid def get_db(): """ Configuration method to return db instance """ db = getattr(g, "_database", None) if db is None: db = g._database = PyMongo(current_app).db return...
python
import gi gi.require_version('Gst', '1.0') from gi.repository import Gst import math from abc import ABC, abstractmethod MAX_BUFFERS = 100 class VideoFrame: def __init__(self, width, height, data=None): self.width = width self.height = height if data is None: self.data = b'\x...
python
import json import os import re from pyaofit import * class campaignfile(campaign): @classmethod def openFile(cls, campaign_filename): with open(campaign_filename) as campaign_file: campaign_dict = json.load(campaign_file) campaign_name = os.path.splitext(os.path.basename(campaign_filename))[0] campaign_pr...
python
from django import forms from accounts.models import Profile class ProfileForm(forms.ModelForm): profile_picture = forms.ImageField(required=False, \ error_messages ={'invalid':("Image files only")},\ widget=forms.FileInput) class Meta: model = Profile fields = ['profile_picture','...
python
# coding: utf-8 from django.db import models, transaction from django.utils.translation import ugettext as _ from grappelli.fields import PositionField ITEM_CATEGORY_CHOICES = ( ('1', _('internal')), ('2', _('external')), ) class Navigation(models.Model): """ Sidebar-Navigation on the Admin Index-Si...
python
import simpy import sys sys.path import random import numpy as np import torch from tabulate import tabulate import sequencing import routing class machine: def __init__(self, env, index, *args, **kwargs): # initialize the environment of simulation self.env = env self.m_idx = ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import import argparse import logging logging.basicConfig( level='DEBUG', format='%(asctime)s|%(name)s|%(levelname)s|%(message)s') logger = logging.getLogger(__name__) def main(args): logger.debug(args) ...
python
import numpy as np import scipy as sp import scipy.linalg import numba import time from ..local_tree import LocalTree import sys def fake_print(*args, **kwargs): pass def myprint(*args, **kwargs): print(*args, **kwargs) sys.stdout.flush() def get_print_function(verbose): return myprint if verbose else ...
python
from huobi.client.trade import TradeClient from huobi.constant import * from huobi.utils import * symbol = "htusdt" trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key) list_obj = trade_client.get_orders(symbol=symbol, order_state=OrderState.FILLED, order_type=Order...
python
print("/" * 51)
python
#!/usr/bin/env python3 PKG = 'lg_mirror' NAME = 'test_touch_router' import os import rospy import unittest from lg_mirror.constants import MIRROR_ACTIVITY_TYPE from lg_msg_defs.msg import StringArray from interactivespaces_msgs.msg import GenericMessage from lg_common.test_helpers import gen_touch_window from lg_com...
python
import autograd as ag import click import copy import numpy as np import logging import pickle from sklearn.model_selection import train_test_split from sklearn.metrics import roc_auc_score from sklearn.preprocessing import RobustScaler from sklearn.utils import check_random_state from recnn.preprocessing import rewr...
python
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.runner import BaseModule, Sequential import mmocr.utils as utils from mmocr.models.builder import BACKBONES from mmocr.models.textrecog.layers import BasicBlock @BACKBONES.register_module() class ResNetABI(BaseModule): """Implement R...
python
import numpy as np from sklearn.preprocessing import MinMaxScaler, StandardScaler from sklearn.cross_validation import train_test_split import theanets import climate climate.enable_default_logging() X_orig = np.load('/Users/bzamecnik/Documents/music-processing/music-processing-experiments/c-scale-piano_spectrogram_2...
python
from django.shortcuts import render from django.shortcuts import redirect from django.urls import reverse from django.core.handlers.wsgi import WSGIRequest from tool.session import * from tool.struct import * from tool.check import * from config import log from user.models import User # from books.views import # Cr...
python
from django.apps import AppConfig, apps from django.conf import settings from django.core.exceptions import ImproperlyConfigured class WagtailAPIAppConfig(AppConfig): name = 'wagtail.contrib.wagtailapi' label = 'wagtailapi_v1' verbose_name = "Wagtail API" def ready(self): # Install cache purg...
python
#!/usr/bin/env python3 import os, filecmp from ccjtools import ccj_make def test_mcux(): """Produce compilation database from MCUExpresso build log, check if as expected""" projectDir = '/home/langrind/Documents/MCUXpresso_11.0.1_2563/workspace/evkmimxrt1064_lwip_ping_bm' existingFile = 'tests/mcux...
python
# ---------------------------------------------------------------------------- # Title: Scientific Visualisation - Python & Matplotlib # Author: Nicolas P. Rougier # License: BSD # ---------------------------------------------------------------------------- # Defaults settings / Custom defaults # -------------------...
python
x= int(input()) if x>=1 and x<=100: for y in range(0,x): S = input()[::-1] if len(S)<=1000: print(S)
python
import os def list_files_absolute(start_dir, extensions=None, ignore_empty=False): start_dir = os.path.expanduser(start_dir) return _list_files(start_dir, start_dir, extensions, ignore_empty=ignore_empty) def list_files_relative(start_dir, extensions=None, ignore_empty=False): start_dir = os.path.expand...
python
from torch.nn import functional as F class TensorResize(): def __init__(self, img_size): self.img_size = img_size def __call__(self, img): # XXX interpolate first dim is a batch dim return F.interpolate(img.unsqueeze(0), self.img_size, mode='bilinear')[0] def __repr__(self): ...
python
import argparse import os import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim from torch.utils.data import DataLoader from torch.autograd import Variable import torch.nn.functional as F import numpy as np import time from tensorboardX ...
python
import os from subprocess import PIPE, run import time thisdir = os.path.dirname(__file__) version_c = os.path.join(thisdir, 'Src', 'versions.c') git = run(['git', 'describe', '--dirty', '--always', '--tags'], check=True, stdout=PIPE) revision = git.stdout.decode('ascii').strip() with open(version_c, 'w') ...
python
import datetime import pickle as pkl import time import cv2 import numpy as np import save_dice_traj import serial from testbench_control import TestBench # from notify_run import Notify side_camera_index = 2 tb_camera_index = 0 tb = TestBench('/dev/ttyACM0', tb_camera_index, side_camera_index) resetter = serial.Se...
python
import csv from decimal import Decimal from mkt.prices.models import Price, PriceCurrency def update(tiers): """ Updates the prices and price currency objects based on the tiers. Tiers should be a list containing a dictionary of currency / value pairs. The value of US is required so that we can look...
python
#!/usr/bin/python import unittest import sys import autocertkit.utils class DevTestCase(unittest.TestCase): """Subclass unittest for extended setup/tear down functionality""" session = "nonexistent" config = {} @classmethod def setUpClass(cls): # Read user config from file ...
python
import logging import numpy as np from scipy.special import jv from aspire.basis import FBBasisMixin, SteerableBasis2D from aspire.basis.basis_utils import unique_coords_nd from aspire.image import Image from aspire.utils import complex_type, real_type, roll_dim, unroll_dim from aspire.utils.matlab_compat import m_fl...
python
#! /usr/bin/python3 import os import sys import argparse import time import signal from ivy.std_api import * import logging PPRZ_HOME = os.getenv("PAPARAZZI_HOME", os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../'))) sys.path.append(PPRZ_HOME + "/var/lib/python") from pprzlink.iv...
python
# Program to generate random account names # Start simple. Just considering distribution of consonants and # vowels first. And then look into including the other arrays. # Compare which will give better results. Just distribution of letters? # Or taking into account other rules and distribution of other morphemes :) ...
python
from __future__ import unicode_literals from cradmin_legacy.crispylayouts import CradminSubmitButton class BulkFileUploadSubmit(CradminSubmitButton): template = 'cradmin_legacy/apps/cradmin_temporaryfileuploadstore/bulkfileupload-submit.django.html' extra_button_attributes = { 'cradmin-legacy-bulkfile...
python
# coding:utf-8 import os import timeit import tensorflow as tf from tensorflow.python.keras.api._v2.keras import backend as K from core.get_model import create_EEGNet, create_TSGLEEGNet from core.training import crossValidate, gridSearch from core.dataloaders import RawDataloader from core.generators import RawGenerat...
python
"""Manipulate tem variants.""" import os import sys from tem import util, var from tem.cli import common as cli from .common import print_cli_err def setup_parser(p): cli.add_general_options(p) p.add_argument("variants", nargs="*", help="set the active variant") mutex = p.add_mutually_exclusive_group()...
python
import os import pathlib import random import json import kinpy as kp import numpy as np from tests.test_urdf_parser import ( urdf_path_to_json_path, PRECOMPUTED_KINEMATICS_DIR_NAME, URDF_EXAMPLES_DIR ) def initialize_state(robot): """Creates a dictionary whose entries each correspond ...
python
""" Object representation of features. Includes an abstract feature class that is also used by transcripts. Each object is capable of exporting itself to BED and GFF3. """ from typing import Optional, Any, Dict, List, Set, Iterable, Hashable from uuid import UUID from inscripta.biocantor.exc import ( EmptyLocatio...
python
from django.urls import url from .views import SignUpView,ProfilePageView, ProfileEditPageView urlpatterns = [ url(r'', SignUpView.as_view(), name='signup'), url(r'profile/$', ProfilePageView.as_view(), name='profile'), url(r'profile_edit/$', ProfileEditPageView, name='profile_edit') ]
python
#!/usr/bin/python import numpy as np import theano import theano.tensor as T import reberGrammar dtype = theano.config.floatX # SET the random number generator's seeds for consistency SEED = 123 np.random.seed(SEED) # refer to the tutorial # http://christianherta.de/lehre/dataScience/machineLearning/neuralNetworks/...
python
import os import sys import time import json import h5py import argparse import librosa import numpy as np from tqdm import tqdm from glob import glob from typing import Any from tf_lite.filter import Filter from tf_lite.tf_lite import TFLiteModel import webrtcvad class Dataset_Filter: def __init__(self, ...
python
import sys import hmac import time import crypt import hashlib import sqlite3 import ConfigParser from flask import session, render_template, g, flash, redirect, url_for, request, jsonify """ cgroup_ext is a data structure where for each input of edit.html we have an array with: position 0: the lxc container opt...
python
import numpy as np import pandas as pd # generate a daily signal covering one year 2016 in a pandas dataframe N = 365 np.random.seed(seed=1960) df_train = pd.DataFrame({"Date" : pd.date_range(start="2016-01-25", periods=N, freq='D'), "Signal" : (np.arange(N)//40 + np.arange(N) % 21 + np.random...
python
import warnings from asl_data import SinglesData def recognize(models: dict, test_set: SinglesData): """ Recognize test word sequences from word models set :param models: dict of trained models {'SOMEWORD': GaussianHMM model object, 'SOMEOTHERWORD': GaussianHMM model object, ...} :param test_set: SinglesData obj...
python
from django.template.loaders.app_directories import Loader as AppDirectoriesLoader from .mixins import TemplateMinifierMixin class Loader(TemplateMinifierMixin, AppDirectoriesLoader): pass
python
import pygame from pygame import mixer from pygame import time from pygame.locals import * import random pygame.mixer.pre_init(44100, -16, 2, 512) mixer.init() pygame.font.init() # define fps clock = pygame.time.Clock() fps = 60 screen_width = 600 screen_height = 800 screen = pygame.display.set_mode((screen_width,...
python
if __name__ == '__main__': n = int(input()) numbers = [None]*(n+1) a = list(map(int,input().split())) for i in a: numbers[i] = True for i in range(1,n+1): if numbers[i] is None: print(i)
python
import zmq import uuid from random import randint from common.settings import * context = zmq.Context() servers = SERVERS_LOCAL connections = [] for i in xrange(N_SERVERS): socket = context.socket(zmq.REQ) socket.connect("tcp://" + servers[i]["client2server"]) connections.append(socket) for i in range(6...
python
#!/usr/bin/env python import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np plt.rcParams.update({'font.size': 16}) dt = 0.02 dims = 201, 201 x = range(-100, 101) for i in range(0,1100, 100): input_file = 'tsunami_h_' + '%4.4i' % i + '.dat' print('Plotting ' + input_file) field ...
python
import filecmp import os.path class dircmp(filecmp.dircmp): """ Compare the content of dir1 and dir2. In contrast with filecmp.dircmp, this subclass compares the content of files with the same path. """ def phase3(self): """ Find out differences between common files. Ensure ...
python
wrf_dir="/home/WRFV4.1.3/run_tutorial/" wrf_input_file="wrfinput_d01" wrf_bdy_file="wrfbdy_d01" wrf_met_dir="/home/WPSV4.1.3/run_tutorial/" wrf_met_files="met_em.d01.2010*" mera_dir="/home/Merra2_data/" mera_files="svc_MERRA2_300.inst3_3d_aer_Nv.2010*" do_IC=True do_BC=True #########################################...
python
import pathlib import numpy as np from scipy import sparse import pandas as pd from sklearn.preprocessing import normalize from sklearn.utils.extmath import safe_sparse_dot from nilearn import image from neuroquery.img_utils import get_masker from neuroquery import tokenization, smoothed_regression, ridge _MAX_SIMIL...
python
def dutch(arr): low = 0 mid = 0 high = len(arr) - 1 while mid <= high: if arr[mid] == 0: arr[low], arr[mid] = arr[mid], arr[low] low += 1 mid += 1 elif arr[mid] == 1: mid += 1 else: arr[mid], arr[high] = arr[high], arr[m...
python
# find an specific element of a list import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.aer import QasmSimulator from qiskit.visualization import plot_histogram # Use Aer's qasm_simulator simulator = QasmSimulator() # Create a oracle operator oracle ...
python
import re regex = r"\*\*(?P<bold>\S+)\*\*|\*(?P<italic>\S+)\*|==(?P<wrap>\S+)==|\[(?P<url>\S+\]\(\S+)\)" p = re.compile(regex, re.MULTILINE) func_dict = { 'wrap': lambda x: (f"<mark>{x}</mark>", f"=={x}=="), 'bold': lambda x: (f"<b>{x}</b>", f"**{x}**"), 'italic': lambda x: (f"<i>{x}</i>", f"*{x}*"), ...
python
import numpy as np import math import rospy from tf.transformations import quaternion_from_euler, euler_from_quaternion from geometry_msgs.msg import Quaternion from geometry_msgs.msg import Point, PoseArray from visualization_msgs.msg import Marker from visualization_msgs.msg import MarkerArray from ackermann_msgs.m...
python
from sqlalchemy.orm.collections import attribute_mapped_collection from emonitor.extensions import db from emonitor.modules.alarmkeys.alarmkeycar import AlarmkeyCars from emonitor.modules.alarmkeys.alarmkeyset import AlarmkeySet class Alarmkey(db.Model): """Alarmkey class""" __tablename__ = 'alarmkeys' __...
python
n1 = float(input('Nota 1: ')) n2 = float(input('Nota 2: ')) m = (n1 + n2) / 2 if m < 5: print('REPROVADO :(') elif m < 7: print('RECUPERAÇÃO...') else: print('APROVADO!! :D')
python
''' prompt = "If you tell us who you are, we can personalize the messages you see" prompt += "\nWhat is your first name: " name = input(prompt) print("\nHello, " + name + "!\n") age = int(input("how old are you? ")) print(age, end="\n\n") height = float(input("How tall are you, in meters? ")) if height >= 1.50: ...
python
''' Get the residue depth for each residue in BioLiP run as: python -m ResidueDepth.Controller ''' from Bio.PDB import PDBParser from Bio.PDB import Selection from Bio.PDB.ResidueDepth import get_surface, residue_depth, ca_depth from Bio.PDB.Polypeptide import is_aa import os from AABindingSiteDist.Controll...
python
# Copyright (c) 2012 NetApp, Inc. All rights reserved. # Copyright (c) 2014 Ben Swartzlander. All rights reserved. # Copyright (c) 2014 Navneet Singh. All rights reserved. # Copyright (c) 2014 Clinton Knight. All rights reserved. # Copyright (c) 2015 Tom Barron. All rights reserved. # Copyright (c) 2015 Alex Meade...
python
# -*- coding: utf-8 -*- from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('transmittals', '0047_auto_20160224_1220'), ] operations = [ migrations.AlterField( model_name='outgoingtransmittal', name='latest_revision'...
python
""" 一键编译测试版本的app给qa: 1、改库版本号为测试版本号 2、改app的库依赖为测试版本号依赖 3、编库 4、编app """ import json import sys from base import sb_nexus, sb_jenkins, sb_config, sb_gitlab def _print_task(task): print(f'apps: {str(task["apps"])}') print(f'libs: {str(task["libs"])}') print(f'branch: {task["branch"]}') print(f'release_n...
python
from typing import Any from unittest.mock import MagicMock, patch import pytest from operatorcert import pyxis from requests import HTTPError, Response def test_is_internal(monkeypatch: Any) -> None: assert not pyxis.is_internal() monkeypatch.setenv("PYXIS_CERT_PATH", "/path/to/cert.pem") monkeypatch.se...
python
from pybuilder.core import use_plugin, init use_plugin("python.core") use_plugin("python.unittest") default_task = "publish" @init def initialize(project): project.version = "0.1.0.SNAPSHOT"
python
from drpg.sync import DrpgSync __all__ = ["DrpgSync"] __version__ = "2021.11.0"
python
import logging from django.contrib.auth.decorators import login_required from django.contrib.auth.signals import user_logged_in from django.core.urlresolvers import reverse from django.dispatch import receiver from django.http import HttpResponse, Http404 from django.shortcuts import redirect, render from django.utils...
python
import unittest from skills import ( Match, Matches, Team, ) from skills.glicko import ( GlickoCalculator, GlickoGameInfo ) class CalculatorTests(object): ERROR_TOLERANCE_RATING = 0.085 ERROR_TOLERANCE_MATCH_QUALITY = 0.0005 def assertAlmostEqual(self, first, second, places, msg, delta): ...
python
#! /bin/python __author__ = "glender" __copyright__ = "Copyright (c) 2018 glender" __credits__ = [ "glender" ] __license__ = "MIT" __version__ = "0.1" __maintainer__ = "glender" __email__ = "None" __status__ = "Production" DEBUG = False alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ" message = ("6340 8309 14010") for i in me...
python
from __future__ import print_function import sys import os import sysconfig import filecmp def diff_q(first_file, second_file): """Simulate call to POSIX diff with -q argument""" if not filecmp.cmp(first_file, second_file, shallow=False): print("Files %s and %s differ" % (first_file, second_file), ...
python
from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import os import random from collections import namedtuple import re import numpy as np import tensorflow as tf import csv import tokenization from mask import Mask, PinyinConfusionSet, Strok...
python
"""Calculate autosome ratios for each cell. This script calculates the {X, 4, and Y} to autosome ratios for each individual cell. I consider chromosomes 2L, 2R, 3L, and 3R as autosomes. 1. Pull out target FBgns. 2. Sum the number of raw reads for each chromosome. 3. Normalize totals by the number of genes on each chr...
python
from django.conf.urls import url from . import views urlpatterns = [ url('api/product/search', views.GoodsSearch), url('api/product/history', views.GetHistory) ]
python
import logging import importlib from volttron.platform.agent import utils import volttron.pnnl.models.input_names as data_names _log = logging.getLogger(__name__) utils.setup_logging() class ahuchiller(object): def __init__(self, config, parent, **kwargs): self.parent = parent equipment_conf = c...
python
import sys sys.path.append('../') import lcm import time from exlcm import ax_control_t from exlcm import veh_status_t from exlcm import net_status_t from exlcm import mode_control_t from exlcm import eng_toggle_t lc = lcm.LCM() test_message = veh_status_t() test_message.running = True test_message.rpm = 3110 test_m...
python
import datetime import json import pathlib import time import httpx import xmltodict import yaml nyaa_url = 'https://nyaa.si' transmission_rpc_url = "http://localhost:9091/transmission/rpc" session_field = 'X-Transmission-Session-Id' class TransmissionApi(): def __init__(self): self.restar...
python
from cedar_settings.default_settings import default_settings default_settings['assets__default_search_results_per_page'] = ('int', 20) # integer hours. default_settings['assets__default_asset_source_string'] = ('text', "Miscellaneous") default_settings['assets__default_files_div_id'] = ('text', "#tab-files")
python
# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See LICENSE import click import frappe @frappe.whitelist() def download_pdf(doctype, name, print_format, letterhead=None): doc = frappe.get_doc(doctype, name) generator = PrintFormatGenerator(print_format, doc, letterhead) pdf = g...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals import sys import argparse import abc from six import add_metaclass, text_type import argparse import re from mCli.utils import get_resource_classes, Singleton from mCli.commands.base import Command @add_metaclass(abc.ABCMeta) class CommandManager(Singl...
python
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ This package defines the astrophysics-specific units. They are also available in the `astropy.units` namespace. """ from . import si from astropy.constants import si as _si from .core import (UnitBase, def_unit, si_prefixes,...
python
""" ######################### Linalg (``utils.linalg``) ######################### Linear algebra helper routines and wrapper functions for handling sparse matrices and dense matrices representation. """ import sys import copy import numpy as np import scipy import scipy.sparse as sp import sci...
python
import wx class SimpleSizer(wx.BoxSizer): def __init__(self, first, second, gap=0, leftHeavy=False, rightHeavy=False, topHeavy=False, bottomHeavy=False): self.first = first self.second = second horizontal = leftHeavy or rightHeavy vertical = topHeavy or bottomHeavy assert horizontal or verti...
python
from bank_account import BankAccount class User(object): def __init__(self, username, email_address): self.name = username # and we use the values passed in to set the name attribute self.email = email_address # and the email attribute self.accounts = { 'default': BankAccount(int_rate=0.02, bala...
python
from boids.code.boids import Boids import pytest from os.path import dirname, split, join import yaml import numpy as np config = yaml.load(open(split(dirname(__file__))[0] + '/code/config.yaml')) def test_bad_boids_regression(): ''' test compares a single position update of the refactored code to the...
python
# -*- coding: utf-8 -*- """Top-level package for appliapps.""" __author__ = """Lars Malmstroem""" __email__ = 'lars@malmstroem.net' __version__ = '0.1.0'
python
import socket from datetime import datetime import os.path as osp import huepy as hue import numpy as np import torch from torch.backends import cudnn from torch.utils.tensorboard import SummaryWriter import sys sys.path.append('./') from configs import args_faster_rcnn_hoim from lib.datasets import get_data_loader ...
python
import smtplib import os import mimetypes from email import encoders from email.mime.base import MIMEBase from email.mime...
python
import os from typing import Union import sqlite3 from sqlite3 import Error from coordinates import Coordinates class SqlHandler: def __init__(self): self._database = "data.db" self._connection = None self._cursor = None self.connected = False def _create_new_database(self) ->...
python
# -*- coding: utf8 -*- __description__ = "Pick a random item from a given list of items. The trigger is 'pick'." __version__ = "1.0" __author__ = "Dingo" from core.plugin import Plugin import re import random async def pick(command): message = " ".join(command.args) message = message.replace(" and say:", ":...
python
#! /usr/bin/env python # -*- coding:UTF-8 -*- """ ------------------------------------------------------------------------------------------ It is used to get the longest mRNA of gene and filter pep and cds result with a certain length; usage: python xx.py -i GFF -f FASTA -g out.gff -o out.fa -s species_short_n...
python
import httpx group_types = ("group", "supergroup") http = httpx.AsyncClient(http2=True) class Permissions: can_be_edited = "can_be_edited" delete_messages = "can_delete_messages" restrict_members = "can_restrict_members" promote_members = "can_promote_members" change_info = "can_change_info" ...
python
#!/usr/bin/python3 from pwn import * binary = ELF('./dead-canary') libc = ELF('/lib/x86_64-linux-gnu/libc.so.6') context.update(arch='amd64',os='linux') binary.symbols['main'] = 0x400737 offset = 6 libcoffset = 41 #p = process(binary.path) p = remote('2020.redpwnc.tf', 31744) # first pass, inf. retries if we blow ...
python
""" Typcasting w. Integers & Floats """ # Convert these numbers into floats and back. Print out each result as well as its data type. five = 5 zero = 0 neg_8 = -8 neg_22 = -22 five = float(five) zero = float(zero) neg_8 = float(neg_8) neg_22 = float(neg_22) print(five, type(five)) # 5.0 <class 'float'> print(zero,...
python
from io import StringIO import json import streamlit as st from water_rocket import WaterRocket def page_introduction(wr: WaterRocket) -> WaterRocket: st.title("Open Water Rocket") st.write(""" ## Objectives The goal of this app to provide a simple platform for analysing wate...
python
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class SurfaceClassifier(nn.Module): def __init__(self, filter_channels, num_views=1, no_residual=True, last_op=None): super(SurfaceClassifier, self).__init__() self.filters = [] self.num_views = num_view...
python
class PushwooshException(Exception): pass class PushwooshCommandException(PushwooshException): pass class PushwooshNotificationException(PushwooshException): pass class PushwooshFilterException(PushwooshException): pass class PushwooshFilterInvalidOperatorException(PushwooshFilterException): ...
python
import socket from smtplib import SMTPException from django.core.mail import EmailMessage from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ def send_email(instance): context = { "user": instance, "api_key": instance.client.api_key, } ...
python
import numpy as np from scipy.spatial import Delaunay import matplotlib.pyplot as plt from matplotlib.collections import LineCollection class AlphaVisualization: """ Visualization methods for AlphaShapes class. """ def plot_boundary(self, color='k', ax=None, **kwargs): """ Plot boundary of c...
python
import os.path import argparse import json import yaml from datetime import datetime import numpy as np import plotly.graph_objects as go import plotly.express as px import ctypes import PySimpleGUI as sg class Stats: '''Yliluokka, joka sisältää päivämäärät sekä metodin näiden muuttamiseksi oikeaan muotoon ja meto...
python
from keg_elements.extensions import lazy_gettext as _ def base36_to_int(s): """ Convert a base 36 string to an int. Raise ValueError if the input won't fit into an int. https://git.io/vydSi """ # To prevent overconsumption of server resources, reject any # base36 string that is longer tha...
python
from ..data.context import setCurTxn, getCurTxn from ..data.txn import Transaction from ..constants import classNameKey, methodNameKey, preHookKey, postHookKey def captureTxn(args, kwargs): txn = Transaction() setCurTxn(txn) def endTxn(args, kwargs): txn = getCurTxn() if txn is None or args is None: ...
python
from django.contrib.auth.models import User, Group from django.db import models from primer.db.models import UUIDField # Monkey Patch User Model User.add_to_class('uuid', UUIDField()) User.add_to_class('created', models.DateTimeField(auto_now_add=True, editable = False, blank = True, null = True)) User.add_to_class('m...
python
# -*- coding: utf-8 -*- from __future__ import absolute_import import collections import os from contextlib import contextmanager import six from python_pachyderm.client.pfs.pfs_pb2 import * from python_pachyderm.client.pfs.pfs_pb2_grpc import * BUFFER_SIZE = 3 * 1024 * 1024 # 3MB TODO: Base this on some grpc va...
python