text
string
size
int64
token_count
int64
# Credits to https://stackoverflow.com/a/56944256/9470078 # I wanted a colored logger without dependencies, so here it is! import logging class ColoredFormatter(logging.Formatter): grey = "\x1b[38;20m" yellow = "\x1b[33;20m" red = "\x1b[31;20m" blue = "\x1b[34;20m" bold_red = "\x1b[31;1m" rese...
818
306
import os os.system('mkdir -p LOG') for i in range(8): os.system('./zk_proof SHA256_64_merkle_' + str(i + 1) + '_circuit.txt SHA256_64_merkle_' + str(i + 1) + '_meta.txt LOG/SHA256_' + str(i + 1) + '.txt')
207
106
from Lex import Lex, ARITHMETIC_COMMANDS, PUSH_OR_POP_COMMANDS class Parser: def __init__(self, src_file_name): self._line_index = 0 self._line_index = 0 self._lines = [] f = open(src_file_name) # First assesment of the Assembler for line in f.readlines(): ...
1,539
501
from astral import Vision # noqa: F401
40
17
from loguru import logger from ..base import base class async(base): def __init__(self, token) -> None: super().__init__(token) def syncuser(self, data): api_name = "batch/syncuser" response = self.request( api_name=api_name, method="post", json=data) logger.debug(...
1,297
448
# Generated by Django 2.2 on 2019-12-20 06:56 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('University', '0011_auto_20191219_1913'), ] operations = [ migrations.RemoveField( model_name='university', name='user', ...
551
177
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-06 23:40 from __future__ import unicode_literals from django.conf import settings import django.contrib.gis.db.models.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = ...
1,539
467
#!/usr/bin/env python P = int(input()) for _ in range(P): N, n, m = [int(i) for i in input().split()] print(f"{N} {(n - m) * m + 1}")
143
67
#importing lib import pandas as pd import numpy as np #Take data df = pd.DataFrame({"Name":['Kunal' , 'Mohit' , 'Rohit' ] ,"age":[np.nan , 23, 45] , "sex":['M' , np.nan , 'M']}) #check for nnull value print(df.isnull().sum()) print(df.describe()) # ignore the nan rows print(len(df.dropna()) , df.dropna()) #for ...
462
197
import datetime from .consola import Consola from .uiscreen import UIScreen from ..core.reloj import Reloj class AjustarReloj(UIScreen): def __init__(self, unMain, unUsuario): super().__init__(unMain) self.usuario = unUsuario def run(self): self.consola.prnt("") self.consola.prnt(" Ahora: %s" %...
2,774
1,120
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import traceback from selenium.webdriver import ChromeOptions from signin.chrome import find_chrome_driver_path, JdSession from signin.jd_job import jobs_all from lib.log import logger from lib.settings import PC_UA from lib.settings import MOBILE_UA class JDUser: ...
2,359
724
from unittest import TestCase from unittest.mock import Mock from tests.test_types_generator import athena_task class TestAwsAthenaTask(TestCase): def test_run_task(self) -> None: with self.assertRaises(NotImplementedError): athena_task()._run_task(Mock())
284
90
#!/usr/bin/env python import os from lazagne.config.write_output import print_debug from lazagne.config.moduleInfo import ModuleInfo class Gnome(ModuleInfo): def __init__(self): options = {'command': '-g', 'action': 'store_true', 'dest': 'gnomeKeyring', 'help': 'Gnome Keyring'} ModuleInfo.__init__(self, 'gnomeKey...
1,966
886
from . import db from flask import Flask, current_app from . import create_app import os from . import db app = create_app() with app.app_context(): if os.path.exists("clearsky/config.json"): pass else: with open('clearsky/config.json', 'w') as configuration: print("Opened config ...
810
276
import logging from abc import ABC, abstractmethod from file_read_backwards import FileReadBackwards import threading import os class Logger(ABC): def __init__(self,filename): self.lock = threading.Lock() self.dir = "Logs" if(not os.path.isdir(self.dir)): os.mkdir(self.dir) ...
6,966
1,957
""" nydus.db.base ~~~~~~~~~~~~~ :copyright: (c) 2011-2012 DISQUS. :license: Apache License 2.0, see LICENSE for more details. """ __all__ = ('LazyConnectionHandler', 'BaseCluster') import collections from nydus.db.map import DistributedContextManager from nydus.db.routers import BaseRouter, routing_params from nydus...
5,387
1,493
from __future__ import absolute_import from voluptuous import MultipleInvalid from pytest_voluptuous.voluptuous import S def pytest_assertrepr_compare(op, left, right): if isinstance(left, S) and (op == '<=' or op == '==') or isinstance(right, S) and op == '==': if isinstance(left, S): sourc...
1,212
360
from path import path_code_dir import sys sys.path.insert(0, path_code_dir) from amftrack.pipeline.functions.image_processing.extract_width_fun import * from amftrack.pipeline.functions.image_processing.experiment_class_surf import Experiment, save_graphs, load_graphs from amftrack.util import get_dates_datetime...
1,487
530
# Copyright 2019 Gilbert Francois Duivesteijn # # 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 appli...
12,476
4,279
# -*- mode: python; coding: utf-8 -*- """ Torncache Connection """ from __future__ import absolute_import import os import stat import socket import time import numbers import logging import functools from tornado import iostream from tornado import stack_context from tornado.ioloop import IOLoop from tornado.platf...
6,980
1,964
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from rlf.rl.loggers import sanity_checker def weight_init(module, weight_init, bias_init, gain=1): weight_init(module.weight.data, gain=gain) bias_init(module.bias.data) return module def no_bias_weight_init(m): if...
10,025
3,439
''' Common Verify functions for IOX / app-hosting ''' import logging import time log = logging.getLogger(__name__) # Import parser from genie.utils.timeout import Timeout from genie.metaparser.util.exceptions import SchemaEmptyParserError def verify_app_requested_state(device, app_list=None, requested_st...
4,407
1,323
# import scipy.signal from gym.spaces import Box, Discrete import numpy as np import torch from torch import nn import IPython # from torch.nn import Parameter import torch.nn.functional as F from torch.distributions import Independent, OneHotCategorical, Categorical from torch.distributions.normal import Normal # # fr...
15,350
5,222
# -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import import numpy as np def extfrm(data, npow, power_threshold=-20): """Extract frame over the power threshold Parameters ---------- data: array, shape (`T`, `dim`) Array of input data npow : array, shap...
855
272
import uuid from django.db import models from partnerweb_parser.manager import NewDesign, Ticket import re from partnerweb_parser import system, mail, manager import json import datetime from partnerweb_parser.date_func import dmYHM_to_datetime from tickets_handler.tasks import update_date_for_assigned class Modify(m...
9,317
2,795
from django.shortcuts import render from django.http import HttpResponse import datetime as dt from django.views import View from photos.models import Image, category # Create your views here. def welcome(request): return render(request, 'welcome.html') def display_page(request): image = Image.objects.all()...
1,184
340
# -*- coding: utf-8 -*- """ file: constants.py Description: some useful constants that could be of some use in SEM and beyond. author: Yoann Dupont MIT License Copyright (c) 2018 Yoann Dupont Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation...
2,530
954
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This module provides a command line interface to news_munger. """ import datetime import random import argparse from munger import DocumentCatalog, Munger parser = argparse.ArgumentParser() parser.parse_args() ## Classes ## class MadLib(Munger): """Real soo...
2,383
762
"""This module contains the code related to the DAG and the scheduler.""" from pathlib import Path import matplotlib.pyplot as plt import networkx as nx import numpy as np from matplotlib.colors import LinearSegmentedColormap from mpl_toolkits.axes_grid1 import make_axes_locatable from networkx.drawing import nx_pydot...
8,246
2,580
from windyquery.provider._base import JSONB from ._base import _rule from .fullname import Fullname from .number import Number from .operators.minus import Minus class FullnameJson(Fullname, Number, Minus): reserved = {**Fullname.reserved, **Number.reserved, **Minus.reserved} tokens = Fullname.tokens + Number...
2,459
941
from .heatmap import generate_heatmap
37
12
import os, os.path, urllib.request, sys, getopt def main(argv): print(argv) input_file = '' download_dir = '' try: opts, args = getopt.getopt(argv, "hi:d:", ["input-file=","download-dir="]) except getopt.GetoptError as ...
1,575
475
import os import gdown import torch import yaml from pynif3d.common.verification import check_in_options, check_path_exists from pynif3d.log.log_funcs import func_logger class BasePipeline(torch.nn.Module): @func_logger def __init__(self): super().__init__() def load_pretrained_model(self, yaml...
929
318
from spotify_auth import auth from urllib import parse import json def search(track_name, artist, type='track'): parsed = parse.quote_plus(query) query = "artist:{}%20track:{}".format(artist, track_name) response = auth.get( 'https://api.spotify.com/v1/search?q={}&type={}'.format(query, type)) ...
392
129
from caproto.server import PVGroup, SubGroup, pvproperty, get_pv_pair_wrapper from caproto import ChannelType from . import utils, pvproperty_with_rbv, wrap_autosave, FastAutosaveHelper from textwrap import dedent import sys from caproto.server import ioc_arg_parser, run from caproto.sync.client import write, read fro...
9,910
2,949
def handler(event, context): return { "statusCode": 302, "headers": { "Location": "https://www.nhsx.nhs.uk/covid-19-response/data-and-covid-19/national-covid-19-chest-imaging-database-nccid/" }, }
241
94
#!/usr/bin/env python # coding: utf-8 # ## E2E Xgboost MLFLOW # In[45]: from pyspark.sql import SparkSession from pyspark.sql.functions import col, pandas_udf,udf,lit import azure.synapse.ml.predict as pcontext import azure.synapse.ml.predict.utils._logger as synapse_predict_logger import numpy as np import panda...
1,529
619
#-*- coding: utf-8 -*- """ gaze_rnn7.py Implement a simple recurrent gaze prediction model based on RNN(GRU). In this version, the gaze DIM is REDUCED to 7x7 dimension. """ # TODO separate pupil from gazemaps, AWFUL design import numpy as np import os import sys import time from PIL import Image import tensorflow ...
2,930
1,020
from collections import defaultdict from .common import IGraph ''' Remove edges to create even trees. You are given a tree with an even number of nodes. Consider each connection between a parent and child node to be an "edge". You would like to remove some of these edges, such that the disconnected subtrees that rem...
1,218
333
# # test KNN # # @ author becxer # @ email becxer87@gmail.com # from test_pytrain import test_Suite from pytrain.KNN import KNN from pytrain.lib import autotest from pytrain.lib import dataset import numpy as np class test_KNN_iris(test_Suite): def __init__(self, logging = True): test_Suite.__init__(self,...
1,362
493
__all__ = ['RandomForestBinaryModel'] from pyspark.sql import DataFrame from pyspark.ml.classification import RandomForestClassifier from python_data_utils.spark.evaluation.multiclass import MulticlassEvaluator from python_data_utils.spark.ml.base import BinaryClassCVModel, Metrics class RandomForestBinaryModel(Bin...
2,416
695
import sys import cv2 from keras.models import load_model from matplotlib import pyplot as plt import time model = load_model("models/model.h5") def find_faces(image): face_cascade = cv2.CascadeClassifier('data/haarcascade_frontalface_default.xml') face_rects = face_cascade.detectMultiScale( image,...
2,815
1,064
""" Implementation of Brute Force algorithm. Checks all possible tours and selects the shortest one. """ from itertools import permutations def brute_force(graph): """Calculates and returns shortest tour using brute force approach. Runs in O(n!). Provides exact solution. Args: graph: instance ...
1,088
299
#! /usr/bin/env python3 # coding=utf-8 import streamlit as st import numpy as np import pandas as pd import joblib from sklearn.ensemble import RandomForestClassifier from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.compose import ColumnTransformer from sklearn.impute import SimpleImpute...
5,414
1,762
#! /usr/bin/env python3 import argparse import random import timeit import copy from sequence_generation import State_Search_Flags, Topology, topological_sort from enzian_descriptions import enzian_nodes, enzian_wires, enzian_nodes_EVAL3 problems = [ ("p1", {"cpu" : "POWERED_ON", "fpga": "POWERED_ON"}, {"vdd_ddr...
9,315
3,312
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2011 Radim Rehurek <radimrehurek@seznam.cz> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """ Automated tests for probability estimation algorithms in the probability_estimation module. """ import logging import un...
3,647
1,110
import numpy as np from geomm.centroid import centroid def center(coords, center_point): """Center coordinates at the origin based on a center point. If idxs are given the center of mass is computed only from those coordinates and if weights are given a weighted center of mass is computed. Param...
5,877
1,675
import logging from os.path import isfile, join as pjoin from os import environ try: from delphin import tsdb except ImportError: raise ImportError( 'Could not import pyDelphin module. Get it from here:\n' ' https://github.com/goodmami/pydelphin' ) # ECC 2021-07-26: the lambda for i-comm...
4,082
1,306
import numpy as np import matplotlib.pyplot as plt import g_functions as g_f R1 = 2 R2 = .6 M = 500 Delta = .1 NB_POINTS = 2**10 EPSILON_IMAG = 1e-8 parameters = { 'M' : M, 'R1' : R1, 'R2' : R2, 'NB_POINTS' : NB_POINTS, 'EPSILON_IMAG' : EPSILON_IMAG, 've...
1,072
475
# Utwórz klasy do reprezentacji Produktu, Zamówienia, Jabłek i Ziemniaków. # Stwórz po kilka obiektów typu jabłko i ziemniak i wypisz ich typ za pomocą funkcji wbudowanej type. # Stwórz listę zawierającą 5 zamówień oraz słownik, w którym kluczami będą nazwy produktów # a wartościami instancje klasy produkt. class Pr...
1,129
404
""" Example (and test) for the NDC coordinates. Draws a square that falls partly out of visible range. * The scene should show a band from the bottom left to the upper right. * The bottom-left (NDC -1 -1) must be green, the upper-right (NDC 1 1) blue. * The other corners must be black, cut off at exactly half way: the...
2,625
940
from django.contrib import admin # Register your models here. from .models import Register admin.site.register(Register)
122
31
import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import statsmodels.api as sm import datetime as dt from statsmodels.stats.multitest import fdrcorrection from pylab import savefig # FUNCTIONS YOU CAN USE: # analyses(filepath) spits out a nifty heatmap to let you check ...
12,572
4,189
import pytest from eunomia.config._default import Default from eunomia.config.nodes import ConfigNode from tests.test_backend_obj import _make_config_group # ========================================================================= # # Test YAML & Custom Tags # # ===...
7,482
2,374
"""This module contains the implementation of the coordinator.""" from typing import Any, Dict, Optional, Type, List, Callable import stp.play import stp.rc as rc import stp.role.assignment as assignment import stp.situation import stp.skill from rj_msgs import msg NUM_ROBOTS = 16 class Coordinator: """The coor...
3,499
1,063
from apf.core.step import GenericStep import logging class {{step_name}}(GenericStep): """{{step_name}} Description Parameters ---------- consumer : GenericConsumer Description of parameter `consumer`. **step_args : type Other args passed to step (DB connections, API requests, etc...
651
178
__author__ = 'nb254' #requires question_title_length.csv for processing: TITLE, BODY, POSTID, USERID import nltk, csv import pandas as pd import Features as features #test = "<p>I have an original Arduino UNO R3 that I bought and an <a href='http://arduino.cc/en/Main/ArduinoBoardSerialSingleSided3' rel='nofollow'>Ardui...
5,107
1,867
import os import logging import gi gi.require_version('Gtk', '3.0') gi.require_version('Notify', '0.7') from locale import atof, setlocale, LC_NUMERIC from gi.repository import Notify from itertools import islice from subprocess import check_output, check_call, CalledProcessError from ulauncher.api.client.Extension i...
4,925
1,397
from flask import current_app from flask import g from flask import request from flask_restful.reqparse import RequestParser from flask_restful import Resource from models import db from models.user import User from utils.decorators import login_required from utils.parser import image_file from utils.storage import up...
2,037
734
"""Implement the Unit class.""" import numpy as np from .. import config, constants __all__ = ["Pixels", "Degrees", "Munits", "Percent"] class _PixelUnits: def __mul__(self, val): return val * config.frame_width / config.pixel_width def __rmul__(self, val): return val * config.frame_width ...
905
303
from .auth_serializer import MyTokenObtainPairSerializer from .register_serializer import UserRegisterSerializer
112
25
"""A module for defining Sensor types. Classes: Sensor -- Base Sensor class, all unknown types default to this. MotionSensor -- Subclass of Sensor, for HC-SR501 type PIR sensors. ReedSwitch -- Subclass of Sensor, for basic door/window reed switches. Functions: build_sensor -- Build & return a ...
3,137
939
from urllib.request import urlopen from bs4 import BeautifulSoup as soup import re import pandas as pd def getContainerInfo(container): name = container.img['title'] itemInfo = container.find('div',class_='item-info') itemBranding = itemInfo.find('div',class_ = 'item-branding') brandName = itemBranding...
1,940
667
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved. # Use of this source code is governed by a BSD-style license (see the COPYING file). """ Change the branch of the manifest Also, checkout the correct branch for every git project in the worktree """ from __fu...
1,228
388
import statistics import hpbandster.core.result as hpres # smallest value is best -> reverse_loss = True # largest value is best -> reverse_loss = False REVERSE_LOSS = True EXP_LOSS = 1 OUTLIER_PERC_WORST = 0.1 OUTLIER_PERC_BEST = 0.0 def analyze_bohb(log_dir): # load the example run from the log files res...
961
358
""" Contains CTImagesAugmentedBatch: masked ct-batch with some augmentation actions """ import numpy as np from .ct_masked_batch import CTImagesMaskedBatch from ..dataset.dataset import action, Sampler # pylint: disable=no-name-in-module from .mask import insert_cropped class CTImagesAugmentedBatch(CTImagesMaskedBa...
2,926
844
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 2D linear elasticity example Solve the equilibrium equation -\nabla \cdot \sigma(x) = f(x) for x\in\Omega with the strain-displacement equation: \epsilon = 1/2(\nabla u + \nabla u^T) and the constitutive law: \sigma = 2*\mu*\epsilon + \lambda*(\nabla\cdot u)I,...
9,155
3,702
from typing import Sequence, Any import torch def clamp_n(tensor: torch.Tensor, min_values: Sequence[Any], max_values: Sequence[Any]) -> torch.Tensor: """ Clamp a tensor with axis dependent values. Args: tensor: a N-d torch.Tensor min_values: a 1D torch.Tensor. Min value is axis dependent...
1,224
432
def bin2dec(binNumber): decNumber = 0 index = 1 binNumber = binNumber[::-1] for i in binNumber: number = int(i) * index decNumber = decNumber + number index = index * 2 return decNumber print('ВВЕДИТЕ ДВОИЧНОЕ 8-БИТНОЕ ЧИСЛО') binNumber = input('>') if len(binNumber) != 8: print('ВВЕДИТЕ ПРАВИЛЬНОЕ 8-БИТН...
437
226
from typing import Any, Dict from meiga import Result, Error, Success from petisco import AggregateRoot from datetime import datetime from taskmanager.src.modules.tasks.domain.description import Description from taskmanager.src.modules.tasks.domain.events import TaskCreated from taskmanager.src.modules.tasks.domain.t...
1,227
347
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # Distributed under the terms of the MIT License. """ Script to search for and collect CIFs using a list of authors. Author: Andrew Tarzia Date Created: 1 Mar 2019 """ import ccdc.search import sys import CSD_f def write_entry(file, author, number, DOI, CSD, solvent,...
4,085
1,221
import stacks1 def is_match(ch1, ch2): match_dict = { ")": "(", "]": "[", "}": "{" } return match_dict[ch1] == ch2 def is_balanced(s): stack = stacks1.Stack() for ch in s: if ch == '(' or ch == '{' or ch == '[': stack.push(ch) if ch == ')' or...
641
245
# -*- coding: utf-8 -*- """ Created on Thu May 3 18:30:29 2018 @author: Koushik """ import pandas as pd from IPython.display import display import sys # -*- coding: utf-8 -*- """ Created on Sun Apr 29 19:04:35 2018 @author: Koushik """ #Python 2.x program for Speech Recognition import re #ent...
2,100
762
from image_pipeline.stages.crop_stage import CropStage from image_pipeline.stages.jpeg_lossless_compression import JPEGLossLessCompressionStage from image_pipeline.stages.jpeg_lossy_compression import JPEGLossyCompressionStage from image_pipeline.stages.resize_stage import ResizeStage pre_stages = [ ResizeStage, ...
584
201
import pytest import pyunitwizard as puw def test_string(): puw.configure.reset() assert puw.get_form('1 meter')=='string' def test_pint_quantity(): puw.configure.reset() puw.configure.load_library(['pint']) ureg = puw.forms.api_pint.ureg q = ureg.Quantity(1.0,'meter') assert puw.get_form(...
538
219
"""In this module we provide the functionality of a Modal. The Modal can be used to focus some kind of information like text, images, chart or an interactive dashboard. The implementation is inspired by - https://css-tricks.com/considerations-styling-modal/ - https://codepen.io/henchmen/embed/preview/PzQ...
4,393
1,481
# Copyright (c) 2020 PaddlePaddle 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 app...
5,696
1,700
__name__ = 'factory_djoy' __version__ = '2.2.0' __author__ = 'James Cooke' __copyright__ = '2021, {}'.format(__author__) __description__ = 'Factories for Django, creating valid model instances every time.' __email__ = 'github@jamescooke.info'
245
89
from collections import defaultdict from sugarrush.solver import SugarRush from garageofcode.common.utils import flatten_simple N = 3 def get_state(solver): # one-hot encoding X = [[[solver.var() for _ in range(N**2)] for _ in range(N)] for _ in range(N)] ...
3,928
1,468
import re import sys import os # Lists of same characters alpha_equiv = ['Α','Ά','ά','ὰ','ά','ἀ','ἁ','ἂ','ἃ','ἄ','ἅ','ἆ','ἇ','Ἀ','Ἁ','Ἂ','Ἃ','Ἄ','Ἅ','Ἆ','Ἇ','ᾶ','Ᾰ','Ᾱ','Ὰ','Ά','ᾰ','ᾱ'] #Converts to α alpha_subscripted = ['ᾀ','ᾁ','ᾂ','ᾃ','ᾄ','ᾅ','ᾆ','ᾇ','ᾈ','ᾉ','ᾊ','ᾋ','ᾌ','ᾍ','ᾎ','ᾏ','ᾲ','ᾴ','ᾷ','ᾼ','ᾳ'] #Converts to...
3,435
1,728
import datetime import os import sys from cmath import inf from typing import Any import hypothesis.extra.numpy as xps import hypothesis.strategies as st import numpy import pytest from hypothesis import assume, given from eopf.product.utils import ( apply_xpath, conv, convert_to_unix_time, is_date, ...
10,756
3,902
#!/usr/bin/env python import rospy from std_msgs.msgs import UInt16, Float32, String from mavros_msgs.msg import Mavlink from struct import pack, unpack def listener(): rospy.init_node('depth_listener', anonymous=True) pub_pressure = rospy.Publisher("depth_listener/pressure_diff", Float32, queue_size=10) pub_throt...
1,227
560
def get_lorawan_maximum_payload_size(dr): mac_payload_size_dic = {'0':59, '1':59, '2':59, '3':123, '4':230, '5':230, '6':230} fhdr_size = 7 #in bytes. Assuming that FOpts length is zero fport_size = 1 #in bytes frm_payload_size = mac_payload_size_dic.get(str(dr)) - fhdr_size - fport_size ret...
6,354
2,447
from django.shortcuts import render, redirect from .models import FormModel from datetime import datetime def index(request): form_list = FormModel.objects.all() context = {'form_list': form_list} return render(request, 'forms_app/index.html', context) def post_new(request): if request.method == "PO...
741
208
from . import svg_to_axes #reload(svg_to_axes) from . import mpl_functions from .svg_to_axes import FigureLayout from . import mpl_fig_to_figurefirst_svg from . import svg_util from . import deprecated_regenerate import sys if sys.version_info[0] > 2: # regenerate uses importlib.utils, which requires python 3? fro...
342
115
#!/usr/bin/python3 # -*- coding: utf-8 -*- import tensorflow as tf import numpy as np import pandas as pd import json import nltk from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.layers import Input, Embedding, LSTM , Dense,GlobalMaxPooling1D,Flatten from tensorflow.keras.preprocessing.s...
3,152
1,130
import pytest from app.html.inline_builder import InlineBuilder, LinkBuilder, CodeBuilder, ImageBuilder from app.markdown.inline_parser import InlineParser, LinkParser, CodeParser, ImageParser from app.settings import setting class TestInlineBuilder: """ Inline要素からHTML文字列が得られるか検証 """ # HTML組み立て @pytest....
5,069
1,644
import common import student_code import array class bcolors: RED = "\x1b[31m" GREEN = "\x1b[32m" NORMAL = "\x1b[0m" def read_data(training_data, test_data1, gold_data1, filename): data = array.array('f') test = array.array('f') with open(filename, 'rb') as fd: data....
5,728
2,141
from bottle import request, response, HTTPResponse import os, datetime, re import json as JSON import jwt class auth: def gettoken(mypass): secret = str(os.getenv('API_SCRT', '!@ws4RT4ws212@#%')) password = str(os.getenv('API_PASS', 'password')) if mypass == password: ...
7,670
2,512
from django.conf.urls import include, url from django.conf import settings from .views import data_sniffer_health_check if settings.DATA_SNIFFER_ENABLED: urlpatterns = [ url(r'^(?P<key>[-\w]+)', data_sniffer_health_check, name="data_sniffer_health_check"), ] else: urlpatterns = []
304
108
# Copyright (c) 2011-2017 Spotify AB # # 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 w...
2,430
738
from flask import request from flask_restplus import Resource from editor.api.terminal.business import get_terminal_output from editor.api.terminal.serializers import terminal_response, terminal_cmd from editor.api.restplus import api ns = api.namespace('terminal', description='Operations related to terminal') @ns.ro...
836
243
# Generated by Django 2.1.2 on 2018-10-19 14:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mediumwave', '0010_auto_20181017_1937'), ] operations = [ migrations.AddField( model_name='transmitter', name='iso',...
400
146
#!/usr/bin/env python import sys import csv import json mostRatingUser = None mostRatingCount = 0 mostRatingInfo = None for line in sys.stdin: line = line.strip() user, genreString = line.split("\t", 1) genreInfo = json.loads(genreString) if not mostRatingUser or len(genreInfo) > mostRatingCount: ...
953
316
import logging import os import sys import time LOG_LEVEL = logging.INFO OPEN_CONSOLE_LOG = True OPEN_FILE_LOG = False LOG_FILE_PATH = None LOG_NAME = "null" ############################################################################################################### # 初始化日志 def _create_logger( level=LOG_LE...
2,901
955
# -*- coding: utf-8 -*- import cv2 import sys import os # 定义旋转rotate函数 def rotate(image, angle, center=None, scale=1.0): # 获取图像尺寸 (h, w) = image.shape[:2] print(image.shape) # 若未指定旋转中心,则将图像中心设为旋转中心 if center is None: center = (w / 2, h / 2) # 执行旋转 M = cv2.getRotationMatrix2D(cen...
2,083
1,052
from unittest import TestCase from giru.core.commands import PaDondeHoy from tests.mocks import MockBot, MockUpdate class TestPaDondeHoy(TestCase): def test_catalogue_response_same_chat_same_day(self): bot = MockBot() update = MockUpdate() PaDondeHoy(bot, update) response_1 = bot...
503
167
import socket import select import config class IRCConnection: def __init__(self, serverName, port=6667): self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connection.connect((serverName, port)) self.connection.setblocking(0) def sendMessage(self, toSend): ...
2,395
698
import pandas as pd import numpy as np df = pd.DataFrame({"A":[1,2,3,4], "B":[5,6,7,8]}) print(df)
99
48
import sys, os.path sys.path.append(os.path.abspath('..')) from models import * from . import AbstractSwimmerService class SwimmerService(AbstractSwimmerService): def __init__(self): # assume this is a database self._data_store = [ { 'swimmer_id': 1, '...
1,314
402