text
string
size
int64
token_count
int64
#!/usr/bin/env python3 # NZART Exam Trainer # Written by Richard Walmsley <richwalm+nzarttrainer@gmail.com> (ZL1RSW) from flask import Flask, request, render_template, redirect, url_for, Response, abort import random import string import json import sys app = Flask(__name__, static_folder = 's') # Constants. Neede...
3,587
1,174
from typing import Dict import logging from src.middleware.profiler import do_cprofile logger = logging.getLogger(__name__) @do_cprofile def health() -> Dict[str, str]: return {"health": "ok"} def health_sync() -> Dict[str, str]: return health() async def health_async() -> Dict[str, str]: return heal...
325
110
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function from os.path import dirname, exists, join import sys, subprocess from setuptools import find_packages, setup setup_dir = dirname(__file__) git_dir = join(setup_dir, ".git") version_file = join(setup_dir, "cxxheaderparser", "version....
2,498
808
import json from flask import Blueprint, request from RobotCode import BehaviorDB from RobotCode.RobotModel import getRobotModel Robot_Api_BluePrint = Blueprint('Robot_Api_BluePrint', __name__, url_prefix="/robot_api") @Robot_Api_BluePrint.route('/getBehaviorMenu') def getBehaviorMenu(): return json.dumps(Behavior...
1,563
471
import pygame import random import math pygame.init() def newRain(width, rainlength): return (random.randint(-50,width),random.randint(-(rainlength),-(rainlength/2)),random.randint(1,3),0) def endpoint(start,length,angle): return ((start[0]+length*math.cos((angle/180)*math.pi)),(start[1])+length) ...
2,126
755
#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- coding: utf8 -*- from django.http import Http404 from django.contrib.auth.decorators import user_passes_test from django.utils.decorators import method_decorator from diogenis.teachers.models import Teacher def user_is_teacher(user): try: request_user =...
818
266
Import("env") import platform if platform.system() == 'Windows': print("Replace MKSPIFFSTOOL with mklittlefs.exe") env.Replace (MKSPIFFSTOOL = "tools/mklittlefs.exe") else: print("Replace MKSPIFFSTOOL with mklittlefs") env.Replace (MKSPIFFSTOOL = "tools/mklittlefs")
284
107
# importing the required libraries import pyautogui, time # delay to switch windows time.sleep(5) #setting count to 5 count = 5 # loop to spam while count >= 1: # fetch and type each word from the file pyautogui.write('Random Annoying Spam Words') # press enter to send the message pyautogui.press('ente...
371
118
import binascii import midstate import pytest import struct def test_initial_state(): SHA256_H0 = bytes([ # Byte-swap 32-bit words 0x6a, 0x09, 0xe6, 0x67, 0xbb, 0x67, 0xae, 0x85, 0x3c, 0x6e, 0xf3, 0x72, 0xa5, 0x4f, 0xf5, 0x3a, 0x51, 0x0e, 0x52, 0x7f, 0x9b, 0...
1,370
837
class Solution: def sortArrayByParityII(self, a): """ :type A: List[int] :rtype: List[int] """ evens = (x for x in a if x % 2 == 0) odds = (x for x in a if x % 2 == 1) return list(itertools.chain.from_iterable(zip(evens, odds)))
289
108
import numpy as np import cv2 import pyrealsense2 as rs import time, sys, glob focal = 0.0021 baseline = 0.08 sd = rs.software_device() depth_sensor = sd.add_sensor("Depth") intr = rs.intrinsics() intr.width = 848 intr.height = 480 intr.ppx = 637.951293945312 intr.ppy = 360.783233642578 intr.fx = 638.864135742188 in...
3,485
1,595
from argparse import ArgumentParser from evidencegraph.argtree import RELATION_SETS_BY_NAME from evidencegraph.corpus import CORPORA from evidencegraph.evaluation import evaluate_setting if __name__ == "__main__": parser = ArgumentParser( description="""Evaluate argumentation parsing predictions""" )...
1,043
313
from common.dataaccess import MongoAccessLayer from common.timeutil import now import numpy as np import os import sys from classifier import workload_comparision as wc # data = [] # data.append({'metric': metric, 'mean': query_mean[0], 'std': query_std[0]}) # data = { # 'metrics': {'n_samples': QUERY_STE...
4,221
1,284
''' Write a program that maps a list of words into a list of integers representing the lengths of the correponding words. Write it in three different ways: 1) using a for-loop, 2) using the higher order function map(), and 3) using list comprehensions. ''' #2 l = ['apple', 'orange', 'cat'] print map( la...
400
139
import filecmp import os import shutil import tempfile from datetime import date, datetime from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from unittest import TestCase import sec_certs.constants as constants import sec_certs.helpers as helpers from sec_certs.dataset.common_criteri...
10,199
3,416
#!/usr/bin/env python # -*- coding: utf-8 -*- import inkyphat import time import sys print("""Inky pHAT: Clean Displays solid blocks of red, black, and white to clean the Inky pHAT display of any screen burn. """.format(sys.argv[0])) if len(sys.argv) < 2: print("""Usage: {} <colour> <number of cycles> V...
1,234
476
# Python 3 version of index.py import math # Input -> 10 20 monkey a, b, c = input().split(' ') print(a, b, c) # Input with map -> 10 20 a, b = map(int, input().split(' ')) print(a, b) # Input with map -> 10, 20 a, b = map(int, input().split(',')) print(a, b) # Python has dynamic data type so integers, float are s...
1,165
607
# Project 1 - The Scope! # Scenario: Congrats, your Penetration testing company Red Planet has # landed an external assessment for Microsoft! Your point of contact has # give you a few IP addresses for you to test. Like with any test you # should always verify the scope given to you to make sure there wasn't # a mista...
1,507
492
/home/runner/.cache/pip/pool/75/74/1f/cd550c3fd39c07a88abf9ca8d462c4c05077809e3ca61220a3837e78cd
96
73
import itertools import logging import random from collections import defaultdict from concurrent.futures import wait from concurrent.futures.thread import ThreadPoolExecutor from bot import RedditBot from utils import rand_wait_min, rand_wait_sec class BotOrchestrator: def __init__(self, all_credentials: dict, ...
4,408
1,306
import numpy as np def normalize(v): nv = np.linalg.norm(v) if nv > 0.0: v[0] = v[0]/nv v[1] = v[1]/nv v[2] = v[2]/nv return v def skew_symmetric(v): """Returns a skew symmetric matrix from vector. p q r""" return np.array([[0, -v[2], v[1]], [v[2], 0,...
10,476
5,166
#!/usr/bin/env python3 import os import re import sys import operator import csv error_counter = {} error_user = {} info_user = {} #This function will read each line of the syslog.log file and check if it is an error or an info message. def search_file(): with open('syslog.log', "r") as myfile: for line in ...
3,363
1,039
from math import log10 from itertools import tee class Corpus: __global_corpus_frequency = 0.0 def __init__(self, size, depth, smoothing_value, label): self.depth = depth self.size = size self.smoothing_value = smoothing_value self.label = label self.frequencies = {}...
2,487
748
""" Writer for amber """ import time import pandas as pd import math import re import numpy as np from collections import Counter # Python 2/3 compat try: from StringIO import StringIO except ImportError: from io import StringIO import eex import logging # AMBER local imports from . import amber_metadata a...
16,117
5,754
import galaxy.model from galaxy.model.orm import * from galaxy.model.mapping import context as sa_session from base.twilltestcase import * import sys def delete_obj( obj ): sa_session.delete( obj ) sa_session.flush() def delete_request_type_permissions( id ): rtps = sa_session.query( galaxy.model.RequestTy...
8,457
2,538
from helpers.Logger import Logger from calendar import Calendar from employee import Employee import json import sys import prettytable import os import time import re # Logger setup logging = Logger() log = logging.realm('Shift Manager') def main(): # 1] Load Configuration file with open('../data/konfigurac...
7,085
2,492
"""Helpers for polyphemus. Utilities API ============= """ from __future__ import print_function import os import io import re import sys import glob import tempfile import functools import subprocess from copy import deepcopy from pprint import pformat from collections import Mapping, Iterable, Hashable, Sequence, na...
13,792
4,244
output_filename = 'kings_mountain_taxes.csv' output_pfilename = 'kmes_taxes.p' base_url = "https://gis.smcgov.org/maps/rest/services/WEBAPPS/COUNTY_SAN_MATEO_TKNS/MapServer/identify" token = "fytmg9tR2rSx-1Yp0SWJ_qkAExGi-ftZoK7h4wk91UY." polygon = [(-13622312.48,4506393.674), (-13622866.64,4504129.241), ...
6,698
2,940
from django.urls import path, re_path import multiprocessing import sys from . import views urlpatterns = [ path("", views.index, name='index'), path("create/", views.index, {"create": True}, name="create"), re_path(r"^logs/(?P<wid>[0-9]+)$", views.logs, name='logs'), re_path(r"^rules/(?P<wid>[0-9]+)$"...
351
128
from views import dump_result from django.http import HttpResponse class ErrorHandlingMiddleware(object): def process_exception(self, request, exception): response = HttpResponse(mimetype="application/json") error = {'error' : True, 'error_message' : str(exception)} dump_result(request, response, [], error) ...
344
105
class Solution: def XXX(self, root: TreeNode) -> List[int]: stack=[(None,root)] result=[] while stack: val,node=stack.pop() if val!=None: result.append(val) if node: stack.append([node.val,node.right]) if no...
555
156
#!/usr/bin/env python # Copyright (c) 2019 Nerian Vision GmbH # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, m...
4,552
1,431
from micarraylib.arraycoords.core import micarray from micarraylib.arraycoords import array_shapes_raw from micarraylib.arraycoords.array_shapes_utils import _polar2cart import pytest import numpy as np def test_micarray_init(): arr = micarray(array_shapes_raw.cube2l_raw, "cartesian", None, "foo") assert arr...
2,263
834
import ocr.utils as utils def toDataURL(img, mime = None): """Image to Data URL. Args: img: CV2 Image object or image path. mime: The media type of the Data URL. Required if the image is an CV2 Image object. Returns: Return Data URL and MIME type. Raises: ValueError: Image types other...
519
195
import math import heapq class Solution: def minStoneSum(self, piles, k: int) -> int: q=list() for i in piles: heapq.heappush(q,i) while k: c=q[-1] q.pop() c=c-math.floor(c/2) heapq.heappush(q,c) k-=1 res=0 ...
491
190
from .element import Element class Navigation(Element): """ Represents navigation link section. """ def __str__(self): return "nav"
159
45
#!/usr/bin/python # -*- coding: utf-8 -*- """ Leap Motion + Trello A plain Trello view with Leap Motion UI. """ import Leap, sys, os, math, time import ConfigParser, argparse from collections import deque from PyQt...
18,562
5,917
from keckdrpframework.primitives.base_primitive import BasePrimitive from kcwidrp.primitives.kcwi_file_primitives import kcwi_fits_reader, \ kcwi_fits_writer, get_master_name, strip_fname import os class SubtractSky(BasePrimitive): def __init__(self, action, context): BasePrimitive.__init__(self, act...
5,115
1,458
# -*- coding: utf-8 -*- # # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You may # not use this file except in compliance with the License. A copy of the # License is located at # # http://aws.amazon.com/apache2.0/ # # or in ...
2,517
669
import pytest import random import time import itertools from multiprocessing.pool import ThreadPool from datetime import timedelta from emit.globals import Proxy, GuardedProxy, Config, ConfigDescriptor, LoggerProxy, log, conf from ..helpers import TestCase @pytest.mark.conf @pytest.mark.log @pytest.mark.proxy class ...
15,581
4,860
numeros = input("Digite dois números: ").split(" ") num1 = float(numeros[0]) num2 = float(numeros[1]) # print(f"{num1} + {num2} = {num1 + num2}") print("%.2f + %.2f = %.2f" %(num1, num2, (num1 + num2))) # print(num1, "+", num2, "=", num1 + num2) print(num1, "-", num2, "=", num1 - num2) print(num1, "*", num2, "=", n...
374
179
#!/usr/bin/env python3 ## Copyright (c) 2011 Steven D'Aprano. ## See the file __init__.py for the licence terms for this software. """ Run the stats package as if it were an executable module. Usage: $ python3 -m stats [options] Options: -h --help Print this help text. -V --version Print the ...
2,149
675
import unittest import pymongo import datetime from bson import ObjectId from iu_mongo import Document, connect from iu_mongo.fields import * from iu_mongo.errors import ValidationError import iu_mongo class Person(Document): meta = { 'db_name': 'test' } name = StringField() age = IntField(def...
4,277
1,441
# -*- coding: utf-8 -*- # Copyright 2018 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Chrome OS Image file signing.""" from __future__ import print_function import collections from chromite.lib import commandli...
2,821
879
import requests import json from decimal import Decimal from bitsv.network import currency_to_satoshi from bitsv.network.meta import Unspent # left here as a reminder to normalize get_transaction() from bitsv.network.transaction import Transaction, TxInput, TxOutput from bitsv.constants import BSV DEFAULT_TIMEOUT = ...
3,874
1,275
from rest_framework.response import Response def create_response(data=None, error=None, status=None): if 200 <= status < 400: success = True else: success = False response = { "data": data, "error": error, "success": success } return Response(data=response,...
336
101
import pandas as pd import requests from pandas_datareader.base import _BaseReader class EcondbReader(_BaseReader): """Get data for the given name from Econdb.""" _URL = "https://www.econdb.com/api/series/" _format = None _show = "labels" @property def url(self): """API URL""" ...
1,699
510
# coding:utf-8 import numpy as np import torch import math class IOUMetric(object): """ Class to calculate mean-iou using fast_hist method """ def __init__(self, num_classes): self.num_classes = num_classes self.hist = np.zeros((num_classes, num_classes)) def _fast_hist(self, la...
2,500
991
# flake8: noqa: F401 from .core import db from .core import db_cli from .core import execute_query from .models.incidents import Incidents, IncidentSchema from .models.users import Users
188
59
"""Views to receive inbound notifications from Mattermost, parse them, and enqueue worker actions.""" import json import logging import shlex from django.conf import settings from django.http import HttpResponse from django.utils.decorators import method_decorator from django.views import View from django.views.decor...
11,524
3,114
from twisted.spread import pb from twisted.internet import reactor from tserver import User, CopyUser import sys, signal player_count = 0 loop = 0 client = None game_creator = False class Client(pb.Referenceable): def __init__(self, name): self.name = name self.players = [] def connected(sel...
2,592
821
""" MIT License Copyright (c) 2021 NextChai Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, dist...
2,401
753
COLOR_SCHEMES = [ " ", "picking", "random", "uniform", "atomindex", "residueindex", "chainindex", "modelindex", "sstruc", "element", "resname", "bfactor", "hydrophobicity", "value", "volume", "occupancy" ]
218
83
import os import webbrowser import numpy as np import csv import traceback import arabic_reshaper from tkinter import * from tkinter import messagebox from tkinter.filedialog import askopenfilename from PIL import ImageTk, Image from run_model import create_and_run_model def make_menu(w): global the_menu the_m...
5,007
1,741
import logging import os from crispy.lib.myparser import CrispyArgumentParser from rpyc.utils.classic import download from crispy.lib.module import * from crispy.lib.fprint import * logger = logging.getLogger(__name__) __class_name__ = "DownloadModule" class DownloadModule(CrispyModule): """ Download file from r...
1,394
393
""" Copyright (c) 2014-2015-2015, The University of Texas at Austin. All rights reserved. This file is part of BLASpy and is available under the 3-Clause BSD License, which can be found in the LICENSE file at the top-level directory or at http://opensource.org/licenses/BSD-3-Clause """ from ..he...
4,042
1,277
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from utils.torch_utils import * class Content_Encoder(nn.Module): def __init__(self, conv_dim=64, repeat_num=4, norm='in', activation='relu'): super(Content_Encoder, self).__init__() layers = [] ...
13,822
5,222
def test_late_crimes_2(): assert late_crimes.loc[7, 'HOUR'] == 20
69
31
import json import pythonosc import argparse import math import datetime from pythonosc import dispatcher, osc_server, udp_client, osc_message_builder import requests from collections import OrderedDict from statistics import mean ## added variables to change the ip and port easily ## testing if Git works with ST ip...
13,355
4,237
import argparse import importlib if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--input_path', help='Path that contains data in MOT format', required=True) parser.add_argument('--output_path', help='Path that will contains the output', required=True) parser.add_argum...
635
196
# Copyright (c) 2020, Huawei Technologies.All rights reserved. # # Licensed under the BSD 3-Clause License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://opensource.org/licenses/BSD-3-Clause # # Unless required by applicable law...
5,825
2,347
import requests from bs4 import BeautifulSoup url = 'https://www.vanityfair.com/style/society/2014/06/monica-lewinsky-humiliation-culture' vf = requests.get(url) vf.status_code s = BeautifulSoup(vf.text, 'lxml') print(s.prettify()) text_article = s.find('div', attrs={'class' : 'content-background'}).find_all('p') ...
370
149
import os from envpy.variables import Var as Variables from envpy.variables import __printenv__ def get_variables(readFile:bool=True, requiredFile:bool=False, readOS:bool=True, filepath:str=f'{os.getcwd()}', filename:str='.env', prefix:str=''): return Variables(readFile=readFile, requiredFile=requiredFile, readOS...
480
152
from models.base_model import BaseModel from keras.models import Sequential from keras.layers import Input, Dense, Conv1D, MaxPooling1D, Dropout, Flatten, BatchNormalization from keras.optimizers import Adam import tensorflow as tf class DeepFactorizedModel(BaseModel): def __init__(self, config): super(De...
2,518
868
debug_print = False has_run_once = False def d_print(*args, **kwargs): global debug_print global has_run_once if not has_run_once: m = "enabled" if debug_print else "disabled" print(f"Debug Print Mode is {m}") has_run_once = True if debug_print: print(*args, **kwargs)...
323
109
# Copyright 2020 EMBL - European Bioinformatics Institute # # 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...
3,849
1,152
def partido_rec_mem_camino(C, S, N, M): def L(n, m): if n == 0: return 0 if (n, m) not in mem: if m >= C[n - 1]: mem[n, m] = max((L(n - 1, m - d * C[n - 1]) + d * S[n - 1] + (1 - d) * N[n - 1], d) for d in range(2)) else: mem[n, m] = (L(n - 1, m) + N[n - 1], 0) return mem[n, m][0] # nr ciudad...
662
407
#!/usr/bin/env python3 # From https://people.sc.fsu.edu/~jburkardt/py_src/hilbert_curve/hilbert_curve.py # def d2xy ( m, d ): #*****************************************************************************80 # ## D2XY converts a 1D Hilbert coordinate to a 2D Cartesian coordinate. # # Licensing: # # This code is dis...
7,357
2,967
from rest_framework import permissions class IsReporter(permissions.BasePermission): """ Permission allowing reporters to access their own reports """ def has_object_permission(self, request, view, obj): return obj.reporter == request.user.IITGUser
295
77
#!/usr/bin/env python import sys import getopt import requests import urllib.parse import json class YoutubeSearch: def __init__(self, search_terms: str, max_results=None): self.search_terms = search_terms self.max_results = max_results self.videos = self.search() def search(self): ...
3,314
982
# -*- coding: utf-8 -*- ''' script for initialization. ''' import os import requests from .script_init_tabels import run_init_tables from mapmeta.model.mapmeta_model import MMapMeta from lxml import etree def do_for_maplet(mapserver_ip): ''' 代码来自 `maplet_arch//030_gen_mapproxy.py` , 原用来找到 mapfile , 生成 yaml . ...
3,716
1,423
from typing import Dict, Any import pandas as pd from tqdm.contrib import tmap from sage.all import RR, ZZ import dissect.utils.database_handler as database from dissect.definitions import STD_CURVE_DICT, ALL_CURVE_COUNT class Modifier: """a class of lambda functions for easier modifications if visualised values...
3,713
1,180
"""Bosch quirks.""" BOSCH = "Bosch"
37
21
# -*- coding: utf-8 -*- # This file is part of dj-cookieauth released under the Apache 2 license. # See the NOTICE for more information. import base64 import hmac import hashlib import time from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.contrib.auth.models import...
3,251
934
import sys import fileinput from collections import defaultdict from itertools import chain def solve(algo, grid, times): defaults = ['.', algo[0]] image = grid for i in range(times): image = enhance(algo, defaults[i%2], image) return sum(map(lambda c: c == '#', chain.from_iterable(image))) ...
1,225
466
# Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ 11:23 - 11:36 7/30 high level: BFS, level order traversal mid level: queue store cur level res, for the popped node, for its all children, add them to queue test: size = ...
981
323
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-payfast', version='0.3.dev', author='Mikhail Korobov', author_email='kmike84@gmail.com', maintainer='Piet Delport', maintainer_email='pjdelport@gmail.com', packages=find_packages(exclude=['payfast_tests']...
926
286
from utils import * from mpmath import ellipe, ellipk, ellippi from scipy.integrate import quad import numpy as np C1 = 3.0 / 14.0 C2 = 1.0 / 3.0 C3 = 3.0 / 22.0 C4 = 3.0 / 26.0 def J(N, k2, kappa, gradient=False): # We'll need to solve this with gaussian quadrature func = ( lambda x: np.sin(x) ** (...
12,036
5,276
from django.core.exceptions import ValidationError from django.utils.deconstruct import deconstructible from django.utils.translation import gettext_lazy as _ @deconstructible class CapitalistAccountValidator: message = _('Invalid Capitalist account number.') code = 'invalid_capitalist_account' account_ty...
821
250
from bolt_srl.model import BoltSRLModel from bolt_srl.predictor import BoltSRLPredictor from bolt_srl.reader import BoltSRLReader
130
49
from __future__ import print_function import sys import importlib from django.conf import settings import graphene from .base import sharedql for imports in settings.INSTALLED_APPS: imports = imports + ".schema" try: mod = importlib.import_module(imports + ".schema") except ImportError: ...
661
200
class Solution(object): def numIslands(self, grid): if not grid: return 0 count = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 1: self.dfs(grid, i, j) count += 1 return cou...
785
333
""" import pyaudio p = pyaudio.PyAudio() for i in range(p.get_device_count()) print(p.get_device_info_by_index(i)) """ import pyaudio p = pyaudio.PyAudio() for i in range(p.get_device_count()): info = p.get_device_info_by_index(i) print(info['index'], info['name'])
279
114
A_0203_11 = {0: {'A': -0.12570904708437197, 'C': -0.20260572185781892, 'E': -4.0, 'D': -4.0, 'G': -4.0, 'F': -4.0, 'I': 0.7830374415420228, 'H': -0.6847918068824875, 'K': -0.6847918068824875, 'M': 0.981018297402464, 'L': 1.1760718746127061, 'N': -0.09649609424570203, 'Q': 0.39410708558422325, 'P': -4.0, 'S': -0.2026057...
4,847
4,215
import werkzeug try: import dotmap except: dotmap = None try: import addict except: addict = None class QuerySpec(object): def __init__(self, query): # TODO: list all attributes of a query spec up front so others know what to expect md = werkzeug.MultiDict() for q in query...
2,644
852
# Generated by Django 2.2.1 on 2019-05-26 00:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('organization', '0002_courseorg_category'), ] operations = [ migrations.AddField( model_name='courseorg', name='cours...
595
194
import sys MASTER_PASSWORD = "opensesame" password = input("Please enter the super secret password: ") attempt_count = 1 while password != MASTER_PASSWORD: if attempt_count > 3: sys.exit("Too many invalid password attempts") password = input("Invalid password, try again: ") attempt_count += 1 pri...
349
105
import json import os from typing import Dict, Tuple, List import numpy as np import tensorflow as tf from keras import backend as K from textgenrnn.model import textgenrnn_model def rnn_generate(config_path: str, vocab_path: str, weights_path: str, min_words=50, temperature=0.5, start_char='\n', r...
5,984
2,003
from datetime import datetime from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand, no_translations from note.models import NoteIndexPage from note.models import NotePage class Command(BaseCommand): help = 'Create note page' def add_arguments(self, parser): ...
1,268
351
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-16 12:55 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('organizations', '0001_initial'), ] operations = [ migrations.RemoveField( ...
918
277
from flask_unchained import BundleConfig class Config(BundleConfig): """ Default configuration options for the controller bundle. """ FLASH_MESSAGES = True """ Whether or not to enable flash messages. NOTE: This only works for messages flashed using the :meth:`flask_unchained.Co...
780
240
from .norms.api import * from .losses.api import * from .sampler import selective_sampler_MH
94
34
from rest_framework import serializers from .models import Category, Brand, Supply, Unit, SupplyItem, Packaging, Product class CategorySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Category fields = ('id', 'name') class BrandSerializer(serializers.HyperlinkedModelSerial...
1,731
490
from flask import url_for, request, current_app from app.auth.models import User, PreAllowedUser from app.extensions import db def test_register_and_login(client, database): # Register unconfirmed user response = client.post(url_for('auth.register'), data={ 'email': 'a@a.com', 'password': 'a'...
2,077
650
from django.forms import ModelForm, ModelChoiceField from django.contrib import admin from django.utils.translation import gettext_lazy as _ from dal import autocomplete from .models import ( DiscountCategory, DiscountCombo, DiscountComboComponent, PointGroup, PricingTierGroup, RegistrationDiscount, Custo...
6,241
1,774
#!/usr/bin/env python # Copyright 2013 Google Inc. 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...
9,666
3,035
from dataclasses import dataclass # https://community.finicity.com/s/article/207505363-Multi-Factor-Authentication-MFA @dataclass class AnsweredMfaQuestion(object): text: str answer: str # Added by the partner for calls to the "MFA Answers" services _unused_fields: dict # this is for forward compatibili...
770
231
from __future__ import absolute_import import base64 import os import pathlib import unittest import conjur from OpenSSL import crypto, SSL CERT_DIR = pathlib.Path('config/https') SSL_CERT_FILE = 'ca.crt' CONJUR_CERT_FILE = 'conjur.crt' CONJUR_KEY_FILE = 'conjur.key' def generateKey(type, bits): """Generates a...
3,829
1,256
import os import pandas as pd def load_banana(): print(os.curdir) file_path = 'data/xgb_dataset/banana/banana.csv' data = pd.read_csv(file_path, delimiter=',',converters={2: lambda x:int(int(x) == 1)}).values return data[:, :2], data[:, 2]
256
101
import asyncio from asyncio.events import AbstractEventLoop import json import logging import zlib from aiohttp import ClientSession, ClientWebSocketResponse from ..cert import Cert from ..hardcoded import API_URL from ..net_client import BaseClient class WebsocketClient(BaseClient): """ implements BaseClie...
2,909
834