text
string
size
int64
token_count
int64
wordCounter = dict() while True : inputFile = input('Enter a file: ') try : fileName = open(inputFile) except : fileName = 'invalid' if fileName == 'invalid' : if inputFile == 'done' : break else : print('Invalid Input') continue ...
857
231
from iris.cli.base import Command, format_docstring, get_command_class HELP = format_docstring(""" Usage: iris [options] <command> [<args>...] Iris is the personification of the rainbow and messenger of the gods. {COMMON_OPTIONS} Commands: instance Run a single service instance (one process). node Run ...
1,022
290
# ---------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License # ---------------------------------------------------------------------- """Generates JSON files based on data previously pickled""" import lzma import o...
3,321
852
# Two lines that remove tensorflow GPU logs # import os # os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import numpy as np import pandas as pd import matplotlib.pyplot as plt from keras.optimizers import Adam from keras.models import Sequential, model_from_json from keras.layers import Conv2D, MaxPooling2D, Dense, Flatten,...
7,152
2,672
from pprint import pprint import requests from lxml import etree def itter(tree): for ele in tree.iter(): print("##########################") print("Tag:", ele.tag) print("Text:", ele.text) print("Attributes:", ele.attrib) print("##########################") def main(): ...
705
245
import urllib.request,json from .models import Source,Article from . import main # Getting Api Key api_Key = None #Getting the base urls sources_base_url = None articles_base_url = None def configure_request(app): ''' Function to acquire the api key and base urls ''' global api_Key,sources_base_url,articles_base_...
2,962
981
def get_names(): names = [] while True: name = input("Enter players name: ") if name != 'done': print(f'{name} added to the list of players') names.append(name) continue else: break return names def get_player_scores(players): for...
727
202
import os os.environ['SLACK_WEBHOOK_URL'] = 'https://example.com/slack'
74
32
from twisted.protocols import basic from twisted.internet import protocol, reactor class HTTPEchoProtocol(basic.LineReceiver): def __init__(self): self.lines = [] def lineReceived(self, line): self.lines.append(line.decode()) if not line: self.sendResponse() def sendRe...
760
239
import requests import json import os import time from app01.models import UserTitle # 爬取个人主页关注用户的id和naame URL = "https://video.kuaishou.com/graphql" headers = { "accept":"*/*", "Content-Length":"<calculated when request is sent>", "Accept-Encoding": "gzip, deflate", "Connection": "keep-alive", "co...
2,804
1,323
import os import sys this_dir = os.path.dirname(__file__) import numpy as np openpose_path = os.path.join(this_dir, 'openpose') op_release_path = os.path.join(openpose_path, 'Release') model_path = os.path.join(openpose_path, 'models') print(op_release_path) sys.path.append(op_release_path); os.environ['PATH'] = os.e...
2,183
837
import pytest import importlib import numba, numba.cuda import numpy as np from pybench import run_benchmark _shapes = { "small": [(int(2 ** 14), 512), (int(2 ** 15), 512), (int(2 ** 16), 512)], "large": [(int(2 ** 20), 512), (int(2 ** 21), 512), (int(2 ** 22), 512)], } def load_data(nrows, ncols, cached, ...
11,193
4,016
def resolve(): ''' code here ''' N , M = [int(item) for item in input().split()] LRs = [[int(item) for item in input().split()] for _ in range(M)] L_max = 0 R_min = N for L, R in LRs: L_max = max(L_max, L) R_min = min(R_min, R) delta = R_min - L_max if delta >=...
420
173
# ====================================================================== # Globally useful modules, imported here and then accessible by all # functions in this file: from __future__ import print_function # Fonts, latex: import matplotlib matplotlib.rc('font',**{'family':'serif', 'serif':['TimesNewRoman']}) matplotli...
7,109
2,580
# -*- coding: utf-8 -*- def produtos(): prod = [["Rack de Teto Uno 2010 2011 2012 2013 2014 2015 a 2020 Preto", '<iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&Mar...
25,254
11,558
""" Modified version of ../muvm/registers.py. Will update as needed. """ #from rpython.jit.backend.arm.locations import VFPRegisterLocation #from rpython.jit.backend.arm.locations import SVFPRegisterLocation #from rpython.jit.backend.arm.locations import RegisterLocation from rpython.jit.metainterp.history import (Cons...
1,213
414
""" This file contains code to post data from the database. This is meant to centralize the insertion of data into the database so that multiple apps can call on the methods in this file without having to define their own and to prevent code redundancy. """ from ..models import * from ..utils.common import ensure_re...
1,536
452
# this actually won't work with keras... not exactly a keras utility import tensorflow as tf def ae_loss_fn(model, x, y, training=None): pred = model(x, training) mse = tf.keras.losses.MSE(y, pred) return tf.reduce_mean(mse), pred # function is untested def vae_loss_fn(model, x, y, training=None): z, ...
527
213
# coding:utf-8 from __future__ import unicode_literals from __future__ import division from __future__ import print_function import os from src.utils import utils from src.data_generator import vocabulary def process(hparam): utils.raise_inexistence(hparam.tmp_dir) tokenizer = vocabulary.Tokenizer(segment=h...
834
308
from elasticsearch import Elasticsearch # TODO: Not implemented yet es = Elasticsearch(["localhost"], sniff_on_connection_fail=True, sniffer_timeout=60) def threads_all(): res = es.search(index="mthreads", body={"query": {"match_all": {}}}) print("Got %d Hits:" % res['hits']['total']) # for hit in res['hi...
419
142
from init import * VOC_CLASSES = [ "background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "potted plant", "sheep", "sofa",...
2,750
1,322
""" A utility function to generate yaml config for SkyQ media players. To support easy usage with other home assistant integrations, e.g. google home """ import os.path as _path import yaml from ..const import CONST_ALIAS_FILENAME class Switch_Maker: """The Switchmaker Class.""" def __init__(self, config_...
2,898
851
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8 import datetime import logging from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserChangeForm from django.core.exceptions import ValidationError from django.forms import CharField from django.utils.translation import ugettext_lazy as _ f...
24,528
7,343
import pytest from unittest import mock import os import pathlib @pytest.fixture(scope="session", autouse=True) def set_pythonpath(): testlib_path = pathlib.Path.cwd() / "tests" / "testlib" with mock.patch.dict(os.environ, {"PYTHONPATH": str(testlib_path)}): yield
283
98
# This is mostly a repeat of model.setup from the pygemini repository except for that it setups up a periodic # grid for us in full-globe simulations. from __future__ import annotations import argparse from pathlib import Path import typing as T import shutil import os from gemini3d.config import read_nml import g...
1,870
639
import board class Floodfill: frontier = [] grid = None board = None def __init__(self, game_board, start_cord): self.board = game_board self.grid = [[None for i in range(self.board.width)] for j in range(self.board.width)] start_node = self.create_node(start_cord["x"], star...
2,580
785
import wpilib import ctre from wpilib.drive import DifferentialDrive from wpilib.interfaces import GenericHID #MOTOR PORTS LEFT = 1 RIGHT = 3 CENTER1 = 2 CENTER2 = 4 #BALL MANIPULATOR BALL_MANIP_ID = 5 GATHER_SPEED = 1.0 SPIT_SPEED = -1.0 STOP_SPEED = 0.0 LEFT_HAND = GenericHID.Hand.kLeft RIGHT_HAND = GenericHID.Han...
3,736
1,369
from . import base from mock import patch import decorators class TestDecorators(base.BaseCase): @patch('decorators.LOG.info') def test_timeit_smoke_test(self, info): @decorators.timeit def some_task(param, **kwargs): pass some_task(42, option='value') (args, _) = in...
1,789
588
import re, operator, array from collections import namedtuple class Argument(object): def __init__(self, viewtype, begin, end=None): self.type = viewtype self.begin = int(begin) self.end = None if end is not None: self.end = int(end) class Lram(bytearray): pass cla...
2,158
770
""" Ramsay RSG1000B RF Signal Generator, controlled via RS-323 interface See: Ramsay RSG1000B RF Signal Generator User Guide, p.10-11 Settings: 9600 baud, 8 bits, parity none, stop bits 1, flow control none DB09 connector pin 2 = TxD, 3 = RxD, 5 = Ground The controller accepts unterminate ASCII text commands and gene...
10,538
3,337
import json def save_json(dict_, json_filepath): ''' [Example] Write JSON ''' ''' dict_ = {"0":{"title":"test-A", "is-available": False, "link":"https://www.AAA.XXX..."}, "1":{"title":"test-B", "is-available": True, "link":"https://www.BBB.XXX..."}} with open("dict_.txt", 'w') as output_fi...
819
281
# GUI Application automation and testing library # Copyright (C) 2006 Mark Mc Mahon # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation; either version 2.1 # of the License, or (at you...
17,570
5,543
from setuptools import setup, find_packages exclude_dirs = ['ez_setup', 'examples', 'tests', 'venv'] # Runtime requirements reqs = [ 'requests', 'six', 'future', 'aenum' ] # Requirements for testing test_reqs = ['pytest', 'hypothesis', 'requests_mock'] # Requirements for setup setup_reqs = ['flake8'...
1,074
360
s3_available_options = ['s3', 'aws_s3', 'aws'] gcs_available_options = ['gcs', 'google_storage', 'google storage']
115
43
from __future__ import print_function, division if __name__=='__main__': from cc_weights import Weight_model else: from . import Weight_model from keras.models import load_model import keras.backend as K import plotload import sys from selector import Selector #from masker import mask_from_template,mask_randoml...
12,607
4,308
# -*- coding: utf-8 -*- # Copyright 2014 OpenMarket Ltd # # 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 la...
6,585
1,845
from pythonforandroid.toolchain import CythonRecipe, shprint, current_directory, ArchAndroid from os.path import exists, join import sh import glob class KivyRecipe(CythonRecipe): version = 'stable' url = 'https://github.com/kivy/kivy/archive/{version}.zip' name = 'kivy' depends = ['pygame', 'pyjniu...
359
126
import random import json import torch from model import NeuralNet from nltk_utils import * device = "cuda" with open('intents.json','r') as f: intents = json.load(f) FILE = 'data.pth' data = torch.load(FILE) input_size = data['input_size'] output_size = data['output_size'] hidden_size = data['hidden_size'] all_wor...
1,220
447
# -*- utf-8 -*- import random import redis import requests def GetIps(): li = [] # url = 'http://122.51.95.201:8000/?country=国内&count=20' url = 'http://127.0.0.1:8000/?country=国内&count=20' ips = requests.get(url) for ip in eval(ips.content): li.append(ip[0]+':'+str(ip[1])) return li # ...
329
153
# -*- coding: utf-8 -*- import setuptools setuptools.setup( name='ftpservercontext', version='2018.3.0', license='commercial', author='Thomas Guettler', author_email='guettliml.ftpservercontext@thomas-guettler.de', url='https://github.com/tbz-pariv/ftpservercontext', long_description=open(...
876
307
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ * Filename: cli.py * Description: cli program entry * Time: 2020.11.30 * Author: liuf5 */ """ import os import sys import argparse module_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.insert(1, module_path) from zoomeye import core ...
3,428
1,082
import scipy.stats as stats def mannwhitneyu(sample_0, sample_1, one_sided=False): """ Performs the Mann-Whitney U test :param sample_0: array of values :param sample_1: array of values :param one_sided: True iff you want to use less than alternative hypothesis :return: statistic, pvalue "...
462
153
import cv2 as cv if __name__ == "__main__": # 0 => first (default) webcam connected, # 1 => second webcam and so on. cap = cv.VideoCapture(0, cv.CAP_DSHOW) # cv.namedWindow("Window") if not cap.isOpened(): raise IOError("Webcam could not be opened!") while True: ...
862
274
import datetime from current_user.models import CurrentUserField from django.conf import settings from django.db import models from django.urls import reverse from django.utils.timezone import now from django.utils.translation import gettext_lazy as _ from sso.accounts.models import Application from sso.models import ...
3,928
1,098
import os from time import time import numpy as np import soundfile from matplotlib import pyplot as plt from wavelet.fast_transform import FastWaveletTransform from wavelet.util.utility import threshold, mad, snr, amp_to_db INPUT_FILE = "/example/input/file.wav" OUTPUT_DIR = "/example/output/" info = soundfile.inf...
1,518
518
# -*- coding: utf-8 -*- from pynput import keyboard from PyQt5.QtCore import QThread, pyqtSignal class KeyHooker(QThread): # シグナル pushCtrlSignal = pyqtSignal() releaseCtrlSignal = pyqtSignal() pushShiftSignal = pyqtSignal() releaseShiftSignal = pyqtSignal() pushCommandSignal = pyqtSignal() ...
1,546
555
""" Commands and operators used by NAD. CMDS[domain][function] """ CMDS = { 'main': { 'dimmer': {'cmd': 'Main.Dimmer', 'supported_operators': ['+', '-', '=', '?'] }, 'mute': {'cmd': 'Main.Mute', 'supp...
2,243
625
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'addsite.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Addsite(object): def setupUi(self, Addsite): Addsite.setObject...
7,846
2,954
from enum import Enum, auto class SetuGuiAutoActorStateActionType(Enum): INIT_STATE = auto() END_STATE = auto() class SetuGuiAutoActorAutomatorActionType(Enum): LAUNCH = auto() QUIT = auto() GO_TO_URL = auto() GO_BACK = auto() GO_FORWARD = auto() REFRESH = auto() EXECUTE_JAVASCR...
1,772
750
def prompt(msg: str) -> bool: return input(msg).lower() in ["y", "yes"]
76
28
""" In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data. You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshap...
1,758
585
#!/usr/bin/env python3 import socket import select from time import sleep import message_pb2 from google.protobuf.internal import encoder import tensorflow as tf from tensorflow.keras import preprocessing import pickle import numpy as np ## RNN part # Load the inference model def load_inference_models(enc_file, dec_f...
4,629
1,776
"""JSON implementations of authorization sessions.""" # pylint: disable=no-init # Numerous classes don't require __init__. # pylint: disable=too-many-public-methods,too-few-public-methods # Number of methods are defined in specification # pylint: disable=protected-access # Access to protected methods allow...
161,322
42,300
############################################################################################### # 还是常规题,和【5. 最长回文子串】不同在于【子串】和【子数组】是【连续】的,而【子序列】可以不连续 # 因此定义dp的方式就不一样,对于【子序列】可以定义长度,而【连续】的【子串】则用是否 ########### # 时间复杂度:O(n^2) # 空间复杂度:O(n^2) ##############################################################################...
1,031
512
"""Variational auto-encoder for MNIST data. References ---------- http://edwardlib.org/tutorials/decoder http://edwardlib.org/tutorials/inference-networks """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import edward as ed import numpy as np import os i...
3,427
1,300
#!/usr/bin/env python """copy-couch makes copies of couches. no joke. License: Apache 2.0 - http://opensource.org/licenses/Apache-2.0 """ import argparse import base64 import ConfigParser import datetime import json import requests argparser = argparse.ArgumentParser() argparser.add_argument('config_file', type=fi...
2,196
763
#Script para la importacion de datos netCDF de un mes del GPCC en PostGIS. #Autor: José I. Álvarez Francoso import sys from osgeo import gdal, ogr, osr from osgeo.gdalconst import GA_ReadOnly, GA_Update # Funcion para sobreescribir el mensaje de porcentaje completado def restart_line(): sys.stdout.write('\r') sys.s...
3,568
1,368
import streamlit as st import pandas as pd import numpy as np import plotly.express as px from plotly.subplots import make_subplots import plotly.graph_objects as go import matplotlib.pyplot as plt def load_data(data): data=pd.read_csv(data) return data df = load_data('hdi.csv') st.title('Human Development Index i...
2,829
1,048
# main.py import pycom import time pycom.heartbeat(False) red = 0x08 blue = 0x00 green = 0x00 sleepTime = 0.01 def setRgb(red, green, blue): rgbValue = 0x000000 rgbValue |= (red << 16) | (green << 8) | blue pycom.rgbled(rgbValue) return while True: ### #if red >= 0x08: # if green > 0:...
657
289
from spacetime import get_s_address_for_t_address from s_address import node_for_s_address from dsn.s_expr.structure import TreeText from dsn.pp.structure import PPNone, PPSingleLine, PPLispy, PPAnnotatedSExpr from dsn.pp.clef import PPUnset, PPSetSingleLine, PPSetLispy def build_annotated_tree(node, default_annota...
1,891
572
"""A module to parse genetics file formats.""" # This file is part of geneparse. # # The MIT License (MIT) # # Copyright (c) 2017 Pharmacogenomics Centre # # 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...
3,704
1,197
from cadquery import * from math import sin,cos,acos,asin,pi,atan2 class Pallet: def __init__(self): self.torx6 = { 6:(1.75,1.27), 8:(2.4,1.75), 10:(2.8,2.05), 15:(3.35,2.4), 20:(3.95,2.85), 25:(4.50,3.25), 30:(5.6,4.05), 40:(6.75,4.85),45:(7.93,5.64), 50:(8.95,6.45), ...
3,285
1,633
# Copyright (c) 2015 Microsoft Corporation from z3 import * print(simplify(Sqrt(2)).sexpr()) set_option(":pp-decimal-precision", 50, pp_decimal=True) print(simplify(Sqrt(2)).sexpr()) set_option(precision=20) print(simplify(Sqrt(2)))
235
105
import pytest import allure from data_detective_airflow.constants import PG_CONN_ID, S3_CONN_ID from data_detective_airflow.dag_generator.results import PgResult, PickleResult from data_detective_airflow.dag_generator import ResultType, WorkType @allure.feature('Dag results') @allure.story('Create Pickle') def test_...
2,044
609
from typing import List class Solution: def largeGroupPositions(self, S: str) -> List[List[int]]: l = [] start = end = 0 while start < len(S): while end < len(S) and S[start] == S[end]: end += 1 if end - start >= 3: l.append([start, e...
478
151
import time import math import py_qmc5883l import pigpio import adafruit_bmp280 from i2c_ADXL345 import ADXL345 import numpy as np from i2c_ITG3205 import Gyro class IMU: def __init__(self, pi): self.gyro = Gyro(pi) self.accel = ADXL345(pi) self.mag = py_qmc5883l.QMC5883L(pi) rpy =...
1,727
738
import pandas as pd from sklearn.model_selection import GridSearchCV, train_test_split, cross_val_score from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score, classification_report import matplotlib.pyplot as plt import numpy as np import category_encoders as ce from sklearn.preproc...
8,892
3,076
name = "magic_markdown" from magic_markdown.MagicMarkdown import MagicMarkdown def load_ipython_extension(ipython): ipython.register_magics(MagicMarkdown)
161
55
import matplotlib.pyplot as plt import pandas as pd from house.production.solar_panel import SolarPanel from house import House from math import pi from time import time start_time = time() solar_panel_east = SolarPanel(285.0, 10*pi/180, -pi/2, 0.87, 1.540539, 10) solar_panel_west = SolarPanel(285.0, 10*pi/180, pi/2...
1,167
489
from tensorflow.keras.layers import Layer, Conv1D, Input, Dropout, MaxPool1D, Masking import tensorflow.keras.backend as K from tensorflow.keras import Model import tensorflow as tf class CNN1D(Layer): def __init__(self, filters=(32, 64), pooling_sizes=(4, 4), kernel_size=3, stride_size=1, using_dropout=True, ...
2,468
788
""" Play with autoformatting on save Ensure to pip install black within your environment """ # test linting with an unnecessary import # it should complain and suggest a solution import sys thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964, "okay": "This is getting way too long", } def...
339
111
import json import os import mock def mock_response(json_str=None, raw=None): resp = mock.MagicMock() if json_str is not None: loaded_json = json.loads(json_str) resp.json = mock.MagicMock(return_value=loaded_json) if raw is not None: resp.raw = mock.MagicMock() resp.raw.r...
931
297
import sys peak=[] with open(sys.argv[1],'r') as f: for line in f: line=line.strip('\n').split('\t') peak.append(int(line[3])) f.close() num=int(len(peak)/100.0) bin=[] for i in range(99): bin.append(str(i+1)+'\t'+str(sum(peak[num*i:num*(i+1)])/(num*1.0))+'\n') bin.append('100'+'\t'+str(sum(peak[num*99:])/(num*...
391
204
import csv from faker import Faker fake = Faker() for x in range(0, 10): placa = fake.pystr(min_chars=3, max_chars=3).upper() + str(fake.pydecimal(left_digits=1, right_digits=1, positive=True)) + str(fake.pydecimal(left_digits=1, right_digits=1, positive=True)) placa = placa.replace(".","") atua...
1,347
636
from PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QLabel, QLineEdit, QVBoxLayout, QMessageBox, QCheckBox,\ QSpinBox, QComboBox, QListWidget, QDialog, QFileDialog, QProgressBar, QTableWidget, QTableWidgetItem,\ QAbstractItemView, QSpinBox, QSplitter, QSizePolicy, QAbstractScrollArea, QHBoxLayout, Q...
4,595
1,335
import os import psutil import json import sqlite3 import threading from datetime import datetime, timezone from websocket import create_connection class CustomHandler: def __init__(self): self.working = False self.counter = 0 self.ws = None if self.dbReady('./data/wiki_statsDB'):...
3,813
1,089
from __future__ import print_function from simtk.openmm import app import simtk.openmm as mm from simtk import unit from sys import stdout import os import time import numpy as np import argparse from equil import setup_sim, dynamix parser = argparse.ArgumentParser(description='equilibrate structures') parser.add_argu...
1,035
382
# Copyright 2020 DeepMind Technologies Limited. # # 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 ag...
40,893
13,911
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 23b.py ~~~~~~ Advent of Code 2017 - Day 23: Coprocessor Conflagration Part Two Now, it's time to fix the problem. The debug mode switch is wired directly to register a. You flip the switch, which makes register a now start at 1 when the pr...
1,897
661
# -*- coding: utf-8 -*- """ Created on Thu Sep 20 11:59:50 2018 @author: klaus """ import numpy as np import matplotlib.pyplot as plt import time import random from argparse import ArgumentParser, RawTextHelpFormatter class GameOfLife: def __init__(self, width, height, interval, seed): ran...
4,456
1,365
from ebird.api.constants import DEFAULT_BACK from tests.mixins.base import BaseMixin class BackTestsMixin(BaseMixin): def test_back_is_sent(self): query = self.api_call(back=10)[1] self.assertEqual(query["back"], 10) def test_default_back_is_not_sent(self): query = self.api_call(back=...
520
188
""" Export data from Tamr using df-connect. An example where everything is default in config file, which implies exported data is written back to same database as ingested from. """ import tamr_toolbox as tbox my_config = tbox.utils.config.from_yaml("examples/resources/conf/connect.config.yaml") my_connect = tbox.dat...
506
157
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField from wtforms.validators import DataRequired, Length, EqualTo, URL from project.auth.models import User class LoginForm(FlaskForm): username = StringField('Username', [DataRequired(), Length(max=64)]) password = Passwo...
1,700
444
from flask import Flask, render_template, request, jsonify import sqlite3 import json import re import logging from applicationInfo import ApplicationInfo logging.basicConfig(filename='/var/www/SoftDev2/projectGo.log', level=logging.DEBUG) app = Flask(__name__) applicationInfo = ApplicationInfo() row_pos_obligation...
10,619
3,278
# Copyright (c) 2018, NVIDIA CORPORATION. # # 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...
1,396
536
N = int(input()) ans = 0 for _ in range(N): p, q = map(int, input().split()) ans += (1 / p) * q print(ans)
114
50
from heapq import heappush, heappop class ListNode: def __init__(self, x): self.val = x self.next = None def __lt__(self, other): return self.val < other.val def mergeKLists(lists): result = ListNode(-1) p = result heap = [] for l in lists: if l: heappush(heap...
769
326
def archive_link(link): # Create a snapshot of the link on the internet archive # ToDo # Ref: https://archive.readme.io/docs/creating-a-snapshot pass
166
53
import argparse import glob import numpy as np import os import skimage.io import torch import tifffile from cellpose import models def _parse_args(): """Parse command-line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( "-i", "--input", type=str, def...
2,297
724
# # Customer cliff dive data challenge # 2020-02-17 # Leslie Emery # ## Summary # ### The problem # The head of the Yammer product team has noticed a precipitous drop in weekly active users, which is one of the main KPIs for customer engagement. What has caused this drop? # ### My approach and results # I began b...
14,134
4,620
import socket import threading import random def send_message(): try: while True: msg = input() sock.send(bytes(name + ": " + msg, 'utf-8')) if msg == '\leave chat': sock.close() break except Exception: pass finally: ...
796
243
from collections import defaultdict import heapq from itertools import chain, repeat from feature_dict import FeatureDictionary import json import numpy as np import scipy.sparse as sp class TokenCodeNamingData: SUBTOKEN_START = "%START%" SUBTOKEN_END = "%END%" NONE = "%NONE%" @staticmethod def _...
23,587
7,401
words = open("words.txt", "r") words = [x.rstrip("\n") for x in words.readlines()] refwords = open("referencewords.txt", "r") refwords = [x.strip("\n") for x in refwords.readlines()] def find_word(word): retunrval = False if word.lower() in words: retunrval = True return retunrval words_needed = [] def main(): ...
550
220
# pylint: disable=too-few-public-methods,no-self-use from django.utils.crypto import get_random_string from django.utils.translation import gettext_lazy as _ from democrasite.users.forms import ( DisabledChangePasswordForm, DisabledResetPasswordForm, DisabledResetPasswordKeyForm, DisabledSetPasswordFor...
2,736
754
# -*- coding: utf-8 -*- """ @author: Terada """ from keras.models import Sequential, Model from keras.layers import Dense, MaxPooling2D, Flatten, Dropout from keras.layers import Conv2D, BatchNormalization, ZeroPadding2D, MaxPool2D from keras.layers import Input, Convolution2D, AveragePooling2D, merge, Reshape, Activat...
3,359
1,397
from contextlib import closing, contextmanager import StringIO as s import unittest as t from lambdak import * # A helper class to test attribute access. class A: pass # Helper functions for the tests. def inc(x): return x + 1 def double(x): return x * 2 class test_lambdak(t.TestCase): def test_init_k_x(self): ...
9,951
3,862
# Coded By : Ismael Al-safadi from win32gui import GetWindowText, GetForegroundWindow from pyperclip import copy from re import findall from win32clipboard import OpenClipboard , GetClipboardData , CloseClipboard from time import sleep class BitcoinDroper: """ class for spoofing Bitcoin Wallet address...
2,327
771
#!/usr/bin/env python # $Id: stack2.py,v 1.0 2018/06/21 23:12:02 dhn Exp $ from pwn import * level = 2 host = "10.168.142.133" user = "user" chal = "stack%i" % level password = "user" binary = "/opt/protostar/bin/%s" % chal shell = ssh(host=host, user=user, password=password) padding = "A" * 64 addr = p32(0x0d0a0...
504
229
import urllib.parse, urllib.request,json import time import hmac, hashlib,random,base64 #yahoo stuff #client ID dj0yJmk9S3owYWNNcm1jS3VIJmQ9WVdrOU1HMUZiMHh5TjJNbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD0xOQ-- #client secret ID fcde44eb1bf2a7ff474b9fd861a6fcf33be56d3f def setConsumerCreds(cons_key,cons_s...
5,096
1,613
import os, sys, logging, threading, tempfile, shutil, tarfile, inspect from ConfigParser import RawConfigParser import requests from DXLiquidIntelApi import DXLiquidIntelApi log = logging.getLogger(__name__) class UpdateManager: def __init__(self, liquidApi, packageType, checkUnpublished, packageCheckInterval, c...
5,246
1,259