text
string
size
int64
token_count
int64
"""A logging handler class which produces coloured logs.""" import logging import click class ColorHandler(logging.StreamHandler): """A color log handler. You can use this handler by incorporating the example below into your logging configuration: ``conf/project/logging.yml``: :: for...
2,508
686
# -*- coding: utf-8 -*- from PyQt5 import QtCore import numpy as np from matplotlib.figure import Figure import time import matplotlib matplotlib.use("Qt5Agg") # 声明使用QT5 from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas class QtFigure(FigureCanvas): def __init__(self, width=5, he...
1,468
635
#!/usr/bin/env python # -*- coding: utf-8 -*- # # @Author: Tom Dwelly # @Date: 2020-03-03 # @Filename: bhm_spiders_agn.py # @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause) # derived from guide.py # ### flake8: noqa # isort: skip_file import peewee from peewee import JOIN from peewee import fn...
124,267
46,564
# Generated by Django 3.1.6 on 2021-04-22 00:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('emails', '0037_remove_emailstats_connected_count'), ] operations = [ migrations.AddField( model_name='emailstats', n...
776
228
""" Data terrain model (DTM). Examples:: >>> from worldmap import DTM >>> dtm = DTM() >>> print(dtm["NOR"]) Location('Norway') """ from typing import Dict, List, Tuple, Set, Optional from bokeh.models import Model from bokeh.models import ColumnDataSource, Patches, LabelSet import logging import num...
1,488
416
""" """ from Crypto.PublicKey import RSA from Crypto.Hash import SHA256 from Crypto.Signature import PKCS1_v1_5 from base58 import b58encode, b58decode # ================= cryptography helpers ====================================== def hash(data): """Hash some data """ # Hash the stuff we need to hash ...
1,865
618
import numpy as np import matplotlib.pyplot as plt def mandelbrot(threshold, density): atlas = np.empty((density, density)) with open('set', 'r') as f: for line in f.readlines(): i, j, val = line.split(",") atlas[int(i), int(j)] = val plt.imshow(atlas.T, interpolation="ne...
365
135
import unittest import copy import os import tempfile from config_tool.utils import * class TestConfigurationTransformation(unittest.TestCase): @classmethod def setUpClass(cls): base_path = os.path.dirname(os.path.realpath(__file__)) file_path = os.path.join(base_path, 'files') def f...
19,303
5,484
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2019-Present Datadog, Inc. from datadog_api_client.v2.model_utils import ( ModelNormal, cached_property, ...
2,133
599
import logging logging.Filter.filter logging.getLogger().propagate logging.StreamHandler.emit
95
27
import platform import pytest @pytest.mark.skipif( platform.system() == "Windows", reason="cannot test this on windows" ) def test_set_key(set_key, pb_api, mocker): import keyring import getpass import six prev_token = six.text_type(keyring.get_password("pushbullet", "cli")) try: moc...
536
177
def cargar_fecha(): dd=int(input("Ingrese numero de dia:")) mm=int(input("Ingrese numero de mes:")) aa=int(input("Ingrese numero de año:")) tupla = (dd,mm,aa) return tupla def imprimir_fecha(fecha): print(fecha[0],fecha[1],fecha[2],sep="/") # bloque principal fecha=cargar_fecha(...
344
153
# %% l = [38,32,49,15,806,806] sum(l) # %% len(l) # %% sum(l)//len(l) # %% l.sort() # %% l # %% # %% l.most_common(1) # %% ''' 求众数:出现频率最高的数据 ''' from collections import Counter l = ['38','32','49','15','806','806'] c = Counter(l) print(c.most_common()[0][0]) print(c.most_common(1)) print(c.most_common(2)) # %% c.m...
356
210
""" Network class is in charge of: 1. Storing M - User Cache Size, N - Number of Files, K - Number of Users 2. Storing User instances, Server instance, and attacker instance """ import numpy as np from scipy import special import itertools from Server import Server from User import User from tabulate import tabulate ...
5,475
1,824
from . import omniglot
23
8
# two templates are used in this app from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/student/<idnum>') def student(idnum): return render_template('student.html', id=idnum) if __name__ == '__main__': app.run(de...
330
113
import asyncio class MyClass: def my_func(self): """ Normal function """ @asyncio.coroutine def my_coro(self): """ This is my coroutine """ @asyncio.coroutine def coro(param): """ Module level async function """
250
85
import json from io import BytesIO from app.ext.api.exceptions import ( ChefNotFound, InvalidToken, MaximumImageCapacityError, OperationNotAllowed, RecipeWithoutIngredient, RecipeWithoutPreparationMode, ) from app.ext.api.services import token_services def test_edit_recipe(client, admin_user)...
25,266
8,523
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-28 09:36 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('survey', '0017_auto_20161128_0242'), ] operations = [ migrations.AlterField...
521
192
import os import sys from pathlib import Path sys.path.insert(0, 'exactdelaypathfinder')
90
31
import time from collections import defaultdict def profiler(method): def wrapper_method(*arg, **kw): t = time.time() method(*arg, **kw) print('Method ' + method.__name__ + ' took : ' + "{:2.5f}".format(time.time()-t) + ' sec') return wrapper_method @profiler def part1(...
1,885
657
from microbit import * import struct from time import sleep SENSORS = 2 def spi_read(sensor): pin16.write_digital(0) # Chip select ibuffer = struct.pack('<B', sensor) spi.write(ibuffer) result = spi.read(1) pin16.write_digital(1) # Chip select off return result spi.init(baudrate=100000) whi...
403
166
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import datetime import typing as t import json from dataclasses import dataclass, field from mypy_boto3_dynamodb.service_resource import Table from boto3.dynamodb.conditions import Attr, Key """ Data transfer object classes to be used with dynamod...
16,653
5,244
from .bucket_tensor_copy import BucketizedTensorCopy __all__ = ['BucketizedTensorCopy']
89
31
from django.apps import AppConfig class AppyConfig(AppConfig): name = 'appy'
83
27
import numpy as np import pytest from ddtruss import Truss, DataDrivenSolver points = np.array([[0, 0], [1, 0], [0.5, 0.5], [2, 1]]) lines = np.array([[0, 2], [1, 2], [1, 3], [2, 3]], dtype=int) truss = Truss(points, lines) E = 1.962e11 A = [2e-4, 2e-4, 1e-4, 1e-4] U_dict = {0: [0, 0], 1: [0, 0]} F_dict = {3: [0, -...
998
558
from datetime import datetime from app import db class City(db.Model): __tablename__ = 'Cities' __table_args__ = {'sqlite_autoincrement': True} id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), index=True) class Venue(db.Model): __tablename__ = 'Venues' __table_arg...
2,563
943
import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from utils.utils import gpu_wrapper from Modules.subModules.attention import AttentionUnit from torch.nn.utils.rnn import pack_padded_sequence as pack from torch.nn.utils.rnn import pad_pa...
2,326
829
def continueLearning(losses): improving = losses[0] < losses[1] or losses[1] < losses[2] return improving
122
40
""" `minion-ci` is a minimalist, decentralized, flexible Continuous Integration Server for hackers. This module contains the parser to parse the `minion.yml` file. :copyright: (c) by Timo Furrer :license: MIT, see LICENSE for details """ import yaml from .errors import MinionError def parse(path):...
569
179
class Solution: def peakIndexInMountainArray(self, A: List[int]) -> int: if not A: return None #前向差分 for k in range(1, len(A)-1): if A[k-1]<A[k] and A[k]>A[k+1]: return k return None #最大值 return A.index(max(A)) ...
585
227
# -*- coding: utf-8 -*- from pymongo import MongoClient from finace import settings class SpiderCity(object): """获取所有城市列表""" def __init__(self, ip=settings.MONGODB_HOST, port=settings.MONGODB_PORT, db_name=settings.MONGO_DATA_BASE, user=settings.MONGO_USER, password=settings.MONGO_PWD): ...
1,431
502
import structlog import logging import sys import os from structlog.processors import JSONRenderer from structlog.stdlib import filter_by_level from structlog.stdlib import add_log_level_number from .datadog import tracer_injection def rename_message_key(_, __, event_dict): event_dict["message"] = event_dict["e...
1,464
463
""" templator.py reads in an excel file and a template and outputs a file for each row in the excel file, by substituting the template variables with the values in the columns. This technique uses pandas to read the excel file into a DataFrame and the python format operator ``%``` to apply the values. """ import sys ...
990
286
import unittest from test_base import TestBaseImporter from test_child import TestChildImporter if __name__ == '__main__': test_loader = unittest.TestLoader() test_classes_to_run = [TestBaseImporter, TestChildImporter] suites_list = [] for test_class in test_classes_to_run: suite = test_loader...
483
157
# import tensorflow as tf # print(tf.__version__) # # # with tf.name_scope('scalar_set_one') as scope: # tf_constant_one = tf.constant(10, name="ten") # tf_constant_two = tf.constant(20, name="twenty") # scalar_sum_one = tf.add(tf_constant_one, tf_constant_two, name="scalar_ten_plus_twenty") # # # # with tf...
1,015
394
from objects.user.User import User from objects.interface.dbconn import DB from objects.user.Currency import get_currency_symbol from objects.threads.UploadThread import UploadThread import utils.globals as _globals from utils.print import print_message, print_error from utils.enums import Months, SettingsSelection, is...
24,952
6,609
# -*- coding: UTF-8 -*- import base64 from functools import wraps import pyaes from flask import request from werkzeug.utils import redirect from website.domain.UserVO import UserVO class CookieHelper(object): def init_app(self, app): self.app = app self.app.cookie_helper = self def SetCook...
1,717
563
#!/usr/bin/env python """ export_resized_ios_images Gimp plugin to export image to icon files usable on iOS. Author: ------- Tobias Blom, Techne Development AB <tobias.blom@techne-dev.se> Installation: ------------- Under Mac OS X, copy this file to ~/Library/Application Support/GIMP/x.x/plug-ins and make it exec...
3,652
1,311
from timeit import default_timer as timer import random def insertion_sort(list_to_sort): for step in range(1, len(list_to_sort)): key = list_to_sort[step] j = step - 1 while j >= 0 and list_to_sort[j] > key: list_to_sort[j + 1] = list_to_sort[j] j -= 1 list...
3,696
1,322
import datetime from django.utils.functional import cached_property from django.utils.safestring import mark_safe from office.offices import Office, OfficeSection from psalter.utils import get_psalms class Compline(Office): name = "Compline" office = "compline" def __init__(self, *args, **kwargs): ...
8,417
2,557
import tide_constituents as tc from py_noaa import coops import pandas as pd import numpy as np import tappy start = '20180201' end = '20180228' interval = 1 start = pd.to_datetime(start) end = pd.to_datetime(end) d = start w, t, p, r = [], [], [], [] while d < end: start_ = d end_ = start_ + pd.DateOffs...
1,735
691
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
24,862
7,279
# -*- coding: utf-8 -*- """「hw10_adversarial_attack.ipynb」的副本 Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1yPa2ushzqw8FNobfonL79PHzudn0vjrN # **Homework 10 - Adversarial Attack** Slides: https://reurl.cc/v5kXkk Videos: TA: ntu-ml-2021spring-ta@g...
10,457
3,836
#!/usr/bin/env python3 import argparse, os, sys, pickle import numpy as np, pathos.multiprocessing as mp, torch import gym_util.common_util as cou, polnet as pn, util_bwopt as u from collections import defaultdict from poleval_pytorch import get_rpi_s, get_Ppi_ss, get_ppisteady_s, get_Qsa def main(): arg = parse_a...
7,867
2,955
# automatically generated by the FlatBuffers compiler, do not modify # namespace: FBOutput import tdw.flatbuffers class StaticSpring(object): __slots__ = ['_tab'] @classmethod def GetRootAsStaticSpring(cls, buf, offset): n = tdw.flatbuffers.encode.Get(tdw.flatbuffers.packer.uoffset, buf, offset)...
3,158
1,128
# -*- coding: utf-8 -*- from locoresponse import LocoResponse class LocoBuyTicketResponse(LocoResponse): def host(self): return self._data["host"] def port(self): return self._data["port"]
221
74
RESOURCE_TYPES = ['lumber', 'clay', 'iron', 'crop'] LUMBER = 0 CLAY = 1 IRON = 2 CROP = 3
91
53
"""Check the syntax and execute Pikachu commands. Methods: run -- The main context for the pikachu vm. """ from pikapy.utils import pika_error, pika_print from pikapy.reader import PikaReader from pikapy.stack import PikaStack def run(file_name, args, debug): """ Run a specified Pikachu file in a virtual en...
4,716
1,383
from rest_framework import status from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView, UpdateAPIView from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import GenericViewSet from _helpers.permissions imp...
1,865
548
""" Tkinter UI for PlotOptiX raytracer. https://github.com/rnd-team-dev/plotoptix/blob/master/LICENSE.txt Have a look at examples on GitHub: https://github.com/rnd-team-dev/plotoptix. """ import logging import numpy as np import tkinter as tk from PIL import Image, ImageTk from ctypes import byref, c_float, c_uint ...
31,394
9,463
#!/usr/bin/python # Author: Luisxue <luisxue@gmail.com> # BLOG: https://luisxue.xcodn.com # # Notes: TreesShell for CentOS/RadHat 6+ Debian 7+ and Ubuntu 12+ # # Project home page: # http://trees.org.cn # https://github.com/luisxue/TreesShell import socket,sys sk = socket.socket(socket.AF_INET, socket.SO...
453
191
import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func import os import requests import urllib.parse # API key introduction # API_KEY = os.environ.get('API_KEY', '') finnhub_API_Key = os.environ.get('finnhub_API_Key', '') from...
4,144
1,469
import json from difflib import get_close_matches data = json.load(open("data.json")) word = input("Enter a word: ") try: def translate(word): word = word.lower() if word in data: return data[word] elif word.title() in data: return data[word.title()] ...
1,156
361
#coding: utf8 """ built-in资源采用按需加载策略, 无需在此引入. 如要启用对应的资源, 请在项目的settings文件中配置RUST_RESOURCES """
94
78
__version_info__ = (0, 1, 5) __version__ = '.'.join([str(v) for v in __version_info__])
88
39
import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) DEBUG = True ALLOWED_HOSTS = [] DATABASES = { 'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'djangox509.db'} } SECRET_KEY = 'fn)t*+$)ugeyip6-#txyy$5wf2ervc0d2n#h)qb)y5@ly$t*@w' INSTALLED_APPS = [ 'django.contrib.auth', 'djan...
2,173
781
import config import recv_db import node_rpc_helper import threading from time import sleep, time setup_check_background_result = {"msg": "(uninitialized)"} config = config.readConfig() last_check_time = time() - 10000 def get_setup_check_background(): global setup_check_background_result return setup_check_...
3,472
1,181
# # PySNMP MIB module NSCHippiSonet-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NSCHippiSonet-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:25:03 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
23,602
10,071
#!/usr/bin/env python3 import os dir_path = os.path.dirname(os.path.realpath(__file__)) file = open(dir_path + "/input.txt", "r") lines = file.readlines() lines = [line.strip() for line in lines] # lines = ["2x3x4", "1x1x10"] total = 0 for line in lines: l, w, h = [int(v) for v in line.split('x')] side1 = ...
784
339
import os from distutils.core import setup from distutils.command.install import INSTALL_SCHEMES from setuptools import find_packages from hypermap import __version__, __description__ def read(*rnames): with open(os.path.join(os.path.dirname(__file__), *rnames)) as ff: return ff.read() setup( name=_...
1,522
514
from creeps.scheduled_action import ScheduledAction def part_count(creep, of_type): count = 0 for part in creep.body: if part['type'] == of_type: count += 1 return count def get_first_spawn(room): for s in room.find(FIND_MY_STRUCTURES): if s.structureType == STRUCTURE_SPAWN...
2,611
949
# -*- coding: utf-8 -*- import json import logging import os from sockjs.tornado import SockJSRouter, SockJSConnection from tornado.web import RequestHandler, StaticFileHandler from tornado.web import Application from tornado.ioloop import IOLoop from sidecar.utils import log class WebHandler(RequestHandler): d...
2,419
748
class Solution(object): def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ flag = False for i in range(len(nums)-2, -1, -1): if nums[i] < nums[i+1]: flag = True...
1,210
400
import time from z3 import Solver, Implies, sat, Const, Function, IntSort, ForAll, DeclareSort from recognizer.pddl.pddl_planner import applicable from recognizer.pddl.sat_planner import SATPlanner from recognizer.plan_recognizer import PlanRecognizer class SATPlanRecognizer(PlanRecognizer): name = "sat" ...
4,584
1,421
cand = open('lbp-bond/data.cbond') gold = open('data/connor_split.csv') tot,good = 0,0 for line in cand: cand_bonds = [] for v in line.split(): x,y = v.split('-') cand_bonds.append((int(x),int(y))) line = gold.readline() items = line.split() if items[1] != 'test': continue ...
925
387
import os.path as op import numpy as np import matplotlib.pyplot as plt import mne from nilearn.plotting import plot_anat from config import fname, subject_id, n_jobs report = mne.open_report(fname.report) epochs = mne.read_epochs(fname.epochs) noise_cov = mne.compute_covariance(epochs, tmin=-0.2, tmax=0, method='s...
1,431
598
# Faça um programa que verifique se uma letra digitada é vogal ou consoante. vogais = ['A', 'E', 'I', 'O', 'U'] letra = input('Digite uma letra: ').strip() letra = letra.capitalize() if letra in vogais: print(f'A letra {letra} é uma vogal') else: print(f'A letra {letra} é uma consoante')
299
124
#!/usr/bin/env python # # Copyright (C) 2015 The Android Open Source Project # # 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 req...
19,236
5,985
import ast import hashlib import json import os from collections import defaultdict from typing import Tuple, Sequence, Dict, Optional, Union, Any, Set import compress_pickle import matplotlib.pyplot as plt import numpy as np import pandas import pandas as pd from filelock import FileLock from allenact.utils.misc_uti...
21,443
6,678
def addition(x: int, y: int) -> int: return x + y # addition_lambda = lambda x, y: x + y # Test: if __name__ == "__main__": print(addition(78, 98))
159
68
import datetime def format_time(t): return f'{t.seconds:2}.{t.microseconds:06}' def log(message): ''' prints a line with: elapsed time since this function was first called elapsed time since this function was previously called message Elapsed times are shown in seconds with mi...
899
269
#!/usr/bin/env python import sys, re # init def printHelp(): sys.stderr.write("""\ lmpsizes.py, a tool for adjusting the size of a .lmp file Syntax: lmpsizes.py <source.lmp> (operation)... lmpsizes.py -h|--help Description: This script reads the size limits from basis.lmp, alters them using any numbe...
9,563
3,463
"""Configuration for tests""" import tempfile DEBUG = True TESTING = True WTF_CSRF_ENABLED = False # APP CONFIG # Creating a tempfile SQLALCHEMY_DATABASE_URI = f"sqlite://{tempfile.mkdtemp()}/test.db" # WEBSERVER SUPERSET_WEBSERVER_ADDRESS = "0.0.0.0" SUPERSET_WEBSERVER_PORT = 8080
286
122
# Copyright 2020-present Kensho Technologies, LLC. from datetime import datetime import glob import os import time from unittest.mock import Mock import funcy import gpg import pytest from . import _UNSAFE_KEY_PASSPHRASE, FAKE_KEYS_DIR, TESTING_ENVVAR, TRUSTED_DIR_ENVVAR from ..check_gpg_keys import ( _verify_tru...
22,051
7,872
import os import re from setuptools import find_packages, setup root = os.path.dirname(__file__) settingsf = open(os.path.join(root, 'qatrack', 'settings.py'), 'r') __version__ = re.findall(r"""VERSION\s+=\s+['"]+(.*)['"]""", settingsf.read())[0] setup( name='qatrackplus', version=__version__, packages...
4,054
1,716
import argparse from torch.utils.data import DataLoader from .model import BERT from .trainer import BERTTrainer from .dataset import DataReader, UnitedVocab, CORALDataset, my_collate, key_lib import pdb import os import json import torch class Session(): def __init__(self, dataset, mod...
4,603
1,523
from haystack import Pipeline from haystack.retriever.anserini import DenseAnseriniRetriever # LOAD COMPONENTS retriever = DenseAnseriniRetriever(prebuilt_index_name="wikipedia-bpr-single-nq-hash", binary=True, query_encoder="castorini/bpr-nq-questi...
532
183
#!/usr/bin/env python import rospy from std_msgs.msg import String, Float32 import time import subprocess def voltage_monitor(): rospy.init_node('voltage_monitor') info_pub = rospy.Publisher('bus_comm', String, queue_size=1) voltage_pub = rospy.Publisher('voltage', Float32, queue_size=1) while True:...
854
335
from __future__ import annotations from spark_auto_mapper_fhir.fhir_types.uri import FhirUri from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType # This file is auto-generated by generate_classes so do not edi...
2,739
876
import datetime import hashlib import json import os import random import string from PIL import Image from urlparse import urlparse from django.conf import settings from django.db import models, connection from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager from django.core.mail imp...
94,984
31,898
#!/usr/bin/env python # -*- coding: utf-8 -*- from .model import Base from .model import Dense from .model import SeriesNet from .model import NP from .model import CNP from .model import RNN from .model import Seq2Seq from .model import DARNN from .model import RGAN from .model import CRGAN from .model import CGAN...
322
107
import logging import time # import the original example.py from handler import DigitalBeing as DB logger = logging.getLogger('server_logger') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages fh = logging.FileHandler('grpc_server.log') fh.setLevel(logging.DEBUG) logger.addHandler(f...
594
185
import logging from json import loads from time import time from flask import request, abort from telebot.apihelper import ApiException from telebot.types import Update from app import db, new_functions as nf from app.constants import ( webhook_url_base, webhook_url_path, ids, other_error_answer ) from app.models...
2,679
821
"""Tools for working with segmented systems.""" from collections import namedtuple import numpy as truenp from .geometry import regular_polygon from .mathops import np Hex = namedtuple('Hex', ['q', 'r', 's']) def add_hex(h1, h2): """Add two hex coordinates together.""" q = h1.q + h2.q r = h1.r + h2.r ...
7,391
2,595
import numpy as np from matplotlib import pyplot as plt from scipy.optimize import curve_fit import random as rd import plotter def model_function(X, a, b, c): """ - the analytical expression for the model that aims at describing the experimental data - the X argument is an array of tuples of the form X=...
1,156
477
class Solution: def countNegatives(self, grid): ans = 0 for row in grid: for ele in row: if ele < 0: ans += 1 return ans
197
56
#!/usr/bin/env python3 # Simple script to compute correlations for inserted and removed tokens import numpy as np import pandas as pd from tqdm import tqdm import os import sqlite3 from datetime import datetime import scipy.stats import scipy.sparse def create_array(token_index, db, total=9584147): token_indicat...
3,740
1,384
from bootstrapvz.base import Task from bootstrapvz.common import phases import os import shutil class EnableInsecureAccess(Task): description = 'Enabling shell access via /dev/ttyS1' phase = phases.system_modification @classmethod def run(cls, info): # Append a line to /etc/inittab launching /bin/bash on # /...
590
222
serialized_string = b'gAN9cQBYEAAAAG1vZGVsX3N0YXRlX2RpY3RxAWNjb2xsZWN0aW9ucwpPcmRlcmVkRGljdApxAilScQMoWCEAAABiYXNlLmxheWVycy4wLm1lc3NhZ2VfcGFzc2luZ19tYXRxBGN0b3JjaC5fdXRpbHMKX3JlYnVpbGRfdGVuc29yX3YyCnEFKGN0b3JjaC5zdG9yYWdlCl9sb2FkX2Zyb21fYnl0ZXMKcQZCPJ0AAIACigps/JxG+SBqqFAZLoACTekDLoACfXEAKFgQAAAAcHJvdG9jb2xfdmVyc2lvbn...
446,260
353,948
from django.db import models # Create your models here. class Gallery(models.Model): """ Model for gallery. Cards with title and thumbnail along with a link to google album """ title = models.CharField(max_length=200) thumbnail = models.CharField(max_length=100) url = models.URLField() ...
368
111
from pwn import * g_local=False e=ELF('/lib/x86_64-linux-gnu/libc-2.23.so') context.log_level='debug' if g_local: sh = process('./candcpp')#, env={'LD_PRELOAD':'./libc-2.23.so'}) gdb.attach(sh) else: sh = remote('154.8.222.144', 9999) MAIN_FUNC = 0x4009A0 LEAK_FUNC = 0x400E10 NAME_BUF = 0x602328 def init_name(nam...
1,687
834
def player_interaction(player, object): if object[0] == 'coin': old_objects.append(object) game_objects[player]['coins'] += 1 def wave_interaction(wave, object): if object[0] == 'player' or object[0] == 'soft_wall': old_objects.append(object) ################3 old_objects = [] ga...
2,164
747
from django.contrib import admin from trade_system.users.models import Wallet from django.contrib.auth import get_user_model User = get_user_model() admin.site.register(User) admin.site.register(Wallet)
206
65
import unittest from mock import Mock from foundations_spec.helpers import let, let_patch_mock, let_patch_instance, set_up from foundations_spec.helpers.spec import Spec from foundations_contrib.models.queued_job import QueuedJob from fakeredis import FakeRedis class TestQueuedJob(Spec): mock_time = let_patc...
4,961
1,685
""" Defines caching before for user preferences """ import jwt import time from cachetools import TTLCache from typing import Optional class CredentialCache(TTLCache): """ Subclass of TTLCache that temporarily stores and retreives user login credentials Arguments: TTLCache {TTLCache} -- A TTLCac...
1,400
362
# -*- coding: utf-8 -*- from numpy import array from numpy.testing import assert_allclose from python_geometry.simple_polygon import SimplePolygon class TestEquality(object): def test_SelfPolygon_ReturnTrue(self): polygon = SimplePolygon( vertices=[ (0, 0, 0), ...
3,013
980
#!/usr/bin/env python3 # validation_curve.py """ Generates the validation curve visualizations for the documentation """ ########################################################################## ## Imports ########################################################################## import os import numpy as np import...
3,432
1,167
import caffe import numpy as np import random import os import sys import re import json import spacy from operator import mul GLOVE_EMBEDDING_SIZE = 300 CURRENT_DATA_SHAPE = None SPATIAL_COORD = None GLOVE = None class LoadVQADataProvider: def __init__(self, ques_file_path, img_file_pre, vdict_path, adict_pat...
14,722
5,114
""" tictoc matlab-like tic and toc functions see https://stackoverflow.com/questions/5849800/what-is-the-python-equivalent-of-matlabs-tic-and-toc-functions """ import time tics = [] def tic(): tics.append(time.process_time()) def toc(): if len(tics) == 0: return None else: return time.p...
347
137