text
string
size
int64
token_count
int64
# from pypy-benchmarks/own/chaos.py, with some minor modifications # (more output, took out the benchmark harness) # import random, math, sys, time SIZE = 9 GAMES = 200 KOMI = 7.5 EMPTY, WHITE, BLACK = 0, 1, 2 SHOW = {EMPTY: '.', WHITE: 'o', BLACK: 'x'} PASS = -1 MAXMOVES = SIZE*SIZE*3 TIMESTAMP = 0 MOVES = 0 def to...
13,902
4,187
# SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) # # SPDX-License-Identifier: MIT import argparse import os import sys sys.path.append("../../tools/usb_descriptor") from adafruit_usb_descriptor import audio, audio10, cdc, hid, mi...
24,265
8,084
from tqdm import tqdm import pandas as pd import numpy as np, argparse, time, pickle, random, os, datetime import torch import torch.optim as optim from model import MaskedNLLLoss, BC_LSTM from dataloader import MELDDataLoader from sklearn.metrics import f1_score, confusion_matrix, accuracy_score, classification_re...
7,500
2,628
#!/usr/bin/env python import os import sys import argparse import pat3dem.star as p3s import math def main(): progname = os.path.basename(sys.argv[0]) usage = progname + """ [options] <coord star files> Output the coord star files after deleting duplicate particles """ args_def = {'mindis':150} parser = argp...
1,828
769
from bs4 import BeautifulSoup import pandas as pd import requests import time import sys def reviews_scraper(asin_list, filename): ''' Takes a list of asins, retrieves html for reviews page, and parses out key data points Parameters ---------- List of ASINs (list of strings) Returns: -----...
4,251
1,193
# noinspection PyUnresolvedReferences import os import re # TODO I'm going to need to make a dictionary for my big list of stuff i care about and what's needed for # every file type.... RAF = ['EXIF:LensModel', 'MakerNotes:RawImageHeight', 'MakerNotes:RawImageWidth', 'EXIF:CreateDate', 'EXIF:ModifyDate', 'EXI...
3,788
1,211
import logging from typing import List, Callable import numpy as np from pyquaternion import Quaternion from pyrep import PyRep from pyrep.errors import IKError from pyrep.objects import Dummy, Object from rlbench import utils from rlbench.action_modes import ArmActionMode, ActionMode from rlbench.backend.exceptions ...
27,214
9,383
from django import forms from django.contrib.contenttypes.forms import generic_inlineformset_factory from django.contrib.contenttypes.models import ContentType from django.db import models from django.test import TestCase from django.test.utils import isolate_apps from .models import ( Animal, ForProxyMode...
11,795
3,971
from .PyPolyBoRi import (BooleSet, Polynomial, BoolePolynomialVector, FGLMStrategy) def _fglm(I, from_ring, to_ring): r""" Unchecked variant of fglm """ vec = BoolePolynomialVector(I) return FGLMStrategy(from_ring, to_ring, vec).main() def fglm(I, from_ring, to_ring): ...
3,192
1,226
""" Uses UMAP (https://umap-learn.readthedocs.io/en/latest/index.html) to reduce course embeddings to two dimensions for visualization. """ import pandas as pd import umap from sklearn.preprocessing import StandardScaler from ferry import config courses = pd.read_csv( config.DATA_DIR / "course_embeddings/courses_...
797
299
import inheritance class Flora: def __init__(self, name, lifespan, habitat, plant_type): self.name = name self.lifespan = lifespan self.habitat = habitat self.plant_type = plant_type self.plant_size = 0 class Fauna: def __init__(self, name): self.name = name...
1,359
494
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2017, Luis Pedro Coelho <luis@luispedro.org> # vim: set ts=4 sts=4 sw=4 expandtab smartindent: # # 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,057
1,030
"""Tests for simple search controller, :mod:`search.controllers.simple`.""" from http import HTTPStatus from unittest import TestCase, mock from werkzeug.datastructures import MultiDict from werkzeug.exceptions import InternalServerError, NotFound, BadRequest from search.domain import SimpleQuery from search.control...
16,307
4,513
#!/usr/bin/env python # ROS Libraries import actionlib from actionlib_msgs.msg import GoalStatus from control_msgs.msg import JointTrajectoryControllerState, FollowJointTrajectoryAction, FollowJointTrajectoryGoal from kuri_wandering_robot.msg import Power from wandering_behavior.msg import WanderAction, WanderGoal impo...
19,270
5,587
# - Generated by tools/entrypoint_compiler.py: do not edit by hand """ Trainers.LightGbmBinaryClassifier """ import numbers from ..utils.entrypoints import EntryPoint from ..utils.utils import try_set, unlist def trainers_lightgbmbinaryclassifier( training_data, predictor_model=None, number_...
11,636
3,474
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """ Automated tests for checking transformation algorithms (the models package). """ import logging import unittest import numpy as n...
2,353
804
import tensorflow as tf from tensorflow import keras class CondGeneratorModel(keras.Model): def __init__(self): super(CondGeneratorModel, self).__init__() # Expand 7*7*128 features into a (7,7,128) tensor self.dense_1 = keras.layers.Dense(7*7*256) self.reshape_1 = keras.layers.Resh...
3,306
1,356
import base64 import datetime import logging import os import time from typing import List, Tuple import structlog import tenacity from averbis import Pipeline from fhir.resources.bundle import Bundle from fhir.resources.codeableconcept import CodeableConcept from fhir.resources.composition import Composition, Composi...
13,115
3,509
# -*- coding: utf-8 -*- from selectable.decorators import login_required from maestros.models import TiposMedidasActuacion, TiposLimitesCriticos, TiposMedidasVigilancia, TiposTemperaturas, TiposFrecuencias, Zonas, Terceros, CatalogoEquipos, Personal, Consumibles, ParametrosAnalisis, Actividades, Etapas, Peligros, Tipos...
12,521
4,107
"""Define commands for Python 2.7""" import argparse import traceback from . import util from .cmd import run from .cmd import extractpipenv def main(): """Main function""" print("This version is not supported! It has limitted analysis features") parser = argparse.ArgumentParser(description='Analyze Jupyt...
828
256
#!/usr/bin/env python import os import imp gpcrondump_path = os.path.abspath('gpcrondump') gpcrondump = imp.load_source('gpcrondump', gpcrondump_path) import unittest2 as unittest from datetime import datetime from gppylib import gplog from gpcrondump import GpCronDump from gppylib.operations.utils import DEFAULT_NUM_...
62,352
21,926
#!/usr/bin/env python ''' Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License")...
5,118
1,513
#!/usr/bin/env python # Copyright (c) 2017 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies the use of linker flags in environment variables. In this test, gyp and build both run in same local environment. """ import ...
1,273
455
# -*- coding: utf-8 -*- from .context import sample def test_thoughts(): assert(sample.hmm() is None)
109
43
###################################################################### # LeetCode Problem Number : 145 # Difficulty Level : Medium # URL : https://leetcode.com/problems/binary-tree-postorder-traversal/ ###################################################################### from binary_search_tree.tree_node import TreeNo...
2,572
671
# -*- coding: utf-8 -*- """This python module aims to manage `DokuWiki <https://www.dokuwiki.org/dokuwiki>`_ wikis by using the provided `XML-RPC API <https://www.dokuwiki.org/devel:xmlrpc>`_. It is compatible with python2.7 and python3+. Installation ------------ It is on `PyPi <https://pypi.python.org/pypi/dokuwik...
18,290
5,263
import setuptools import re with open("README.md", "r") as fh: long_description = fh.read() # get version from _version.py file, from below # https://stackoverflow.com/questions/458550/standard-way-to-embed-version-into-python-package VERSION_FILE = "test_aide/_version.py" version_file_str = open(VERSION_FILE, "r...
1,449
476
"""Simple matshow() example.""" from matplotlib.pylab import * def samplemat(dims): """Make a matrix with all zeros and increasing elements on the diagonal""" aa = zeros(dims) for i in range(min(dims)): aa[i, i] = i return aa # Display 2 matrices of different sizes dimlist = [(12, 12), (15, ...
510
181
#! /usr/bin/env python3 import importlib import logging import os import subprocess from setuptools import setup from setuptools.command.install import install as install from setuptools.command.develop import develop as develop logger = logging.getLogger(__name__) stan_model_files = [ os.path.join("nonperiod...
4,445
1,448
import os import h5py import nibabel as nb import numpy as np import torch import torch.utils.data as data from torchvision import transforms import utils.preprocessor as preprocessor # transform_train = transforms.Compose([ # transforms.RandomCrop(200, padding=56), # transforms.ToTensor(), # ]) class Imdb...
9,909
3,099
import argparse import yaml import sys from .conf import MysqlConf from lib.db import mysql parser = argparse.ArgumentParser() parser.add_argument("--config", help="config file name", type=str, required=False, default='office') input_args = parser.parse_args() class PartConfig: def __init__(self): self._...
2,764
917
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'design.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtC...
4,164
1,550
from simulation.car import spawn_drivers from simulation.passenger import spawn_passengers from simulation.core import World, Clock conf = { "x": 100, "y": 100, "drivers": 200, "users": 1000, "start": "2019-07-08T00:00:00", "end": "2019-07-08T00:01:00" } clock = Clock(conf["start"], conf["end"...
597
244
#!/bin/python3 import math import os import random import re import sys # # Complete the 'reverse_words_order_and_swap_cases' function below. # # The function is expected to return a STRING. # The function accepts STRING sentence as parameter. # def reverse_words_order_and_swap_cases(sentence): # Write your cod...
795
260
import json d1 = {} with open("/home/qinyuan/zs/out/bart-large-with-description-grouped-1e-5-outerbsz4-innerbsz32-adapterdim4-unfreeze-dec29/test_predictions.jsonl") as fin: for line in fin: d = json.loads(line) d1[d["id"]] = d["output"][0]["answer"] d2 = {} dq = {} with open("/home/qinyuan/zs/out...
1,245
522
import json, requests from pprint import pprint CREEDS_URL = 'http://amp.pharm.mssm.edu/CREEDS/' response = requests.get(CREEDS_URL + 'search', params={'q':'STAT3'}) if response.status_code == 200: pprint(response.json()) json.dump(response.json(), open('api1_result.json', 'wb'), indent=4)
294
114
# Generated by Django 2.2.3 on 2019-07-31 13:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("admin", "0040_auto_20190718_0938")] operations = [ migrations.AddField( model_name="course", name="color", field=models.CharField(default="#0...
355
136
# Forma sem bugs expressao = (str(input('Digite a expressão: '))) pilhaParenteses = [] for v in expressao: if v == '(': pilhaParenteses.append('(') elif v == ')': if len(pilhaParenteses) > 0: pilhaParenteses.pop() else: pilhaParenteses.append(')') bre...
673
245
# Copyright 2018 TNG Technology Consulting GmbH, Unterföhring, Germany # Licensed under the Apache License, Version 2.0 - see LICENSE.md in project root directory import logging from xml.sax.saxutils import escape log = logging.getLogger() class Todo: def __init__(self, file_path, line_number, content): ...
1,607
531
import dash_core_components as dcc import dash_html_components as html import plotly.graph_objs as go import plotly.express as px from plotly.subplots import make_subplots import pandas as pd import math from datetime import datetime, time from utils import MONTH_NAMES, month_range def section(title, content, gray=Fa...
9,595
3,165
# -*- coding: utf-8 -*- from gengine.app.tests.base import BaseDBTest from gengine.app.tests.helpers import create_user, update_user, delete_user, get_or_create_language from gengine.metadata import DBSession from gengine.app.model import AuthUser class TestUserCreation(BaseDBTest): def test_user_creation(self):...
3,651
1,187
from __future__ import annotations import collections import copy import itertools import math import os import posixpath from io import BytesIO, StringIO from textwrap import indent from typing import Any, Dict, List, MutableMapping, Optional, Tuple, Union from fontTools.misc import etree as ET from fontTools.misc i...
119,159
31,271
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Any, Optional, Tuple import torch from botorch.acquisition.acquisition import AcquisitionFunction ...
3,230
944
# Copyright 2018 the Autoware Foundation # # 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 ...
2,240
699
# USAGE # python example.py --source images/ocean_sunset.jpg --target images/ocean_day.jpg # import the necessary packages from color_transfer import color_transfer import numpy as np import argparse import cv2 def show_image(title, image, width = 300): # resize the image to have a constant width, just to # make di...
1,425
451
import copy import numpy as np import open3d as o3d from tqdm import tqdm from scipy import stats import utils_o3d as utils def remove_ground_plane(pcd, z_thresh=-2.7): cropped = copy.deepcopy(pcd) cropped_points = np.array(cropped.points) cropped_points = cropped_points[cropped_points[:, -1] > z_thresh...
9,060
3,508
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2019 "Neo4j," # Neo4j Sweden AB [http://neo4j.com] # # This file is part of Neo4j. # # 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 L...
36,825
9,808
import os import imp from setuptools import setup, find_packages __version__ = imp.load_source( "hsfs.version", os.path.join("hsfs", "version.py") ).__version__ def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="hsfs", version=__version__, install_...
1,831
614
#!/usr/bin/env python3 from . import signup, signin, signout, update, info, detail
87
32
# Optional list of dependencies required by the package dependencies = ['torch'] from focal_loss import FocalLoss, focal_loss
127
35
#!/usr/bin/env python ############################################################################### # $Id$ # # Project: GDAL/OGR Test Suite # Purpose: Test GPX driver functionality. # Author: Even Rouault <even dot rouault at mines dash paris dot org> # ###########################################################...
15,609
5,872
# Code Taken from https://github.com/LYH-YF/MWPToolkit # -*- encoding: utf-8 -*- # @Author: Yihuai Lan # @Time: 2021/08/21 04:59:55 # @File: sausolver.py import random import torch from torch import nn import copy from module.Encoder.rnn_encoder import BasicRNNEncoder from module.Embedder.basic_embedder import BasicE...
22,377
7,051
import unittest from functools import partial import pandas as pd from pandas.util.testing import assert_frame_equal, assert_series_equal import numpy as np import threading from StringIO import StringIO from rosetta.parallel import parallel_easy, pandas_easy from rosetta.parallel.threading_easy import threading_easy...
8,128
2,887
import time import srt import re import datetime from mqtthandler import MQTTHandler INIT_STATUS={ "video": { "title": None, "series_title": None, "season": None, "episode": None }, "time": None, "events": None } class SubtitleHandler: subtitles = [] phrases = ...
3,349
1,013
#!/usr/bin/env python import os import numpy as np import pandas as pd os.getcwd() # Request for the filename # Current version of this script works only with TSV type files mainFilename = input('Input your file name (diabetes.tab.txt or housing.data.txt): ') print() # To create proper dataframe, transforming it wi...
1,165
347
from donkeycar.parts.web_controller.web import WebSocketCalibrateAPI from functools import partial from tornado import testing import tornado.websocket import tornado.web import tornado.ioloop import json from unittest.mock import Mock from donkeycar.parts.actuator import PWMSteering, PWMThrottle class WebSocketCal...
3,057
1,048
# TracIncludeMacro macros import re import urllib2 from StringIO import StringIO from trac.core import * from trac.wiki.macros import WikiMacroBase from trac.wiki.formatter import system_message from trac.wiki.model import WikiPage from trac.mimeview.api import Mimeview, get_mimetype, Context from trac.perm import IPe...
5,709
1,556
# Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
12,497
3,371
from __future__ import absolute_import from unittest import TestCase import os import importlib import inspect from plotly.basedatatypes import BasePlotlyType, BaseFigure datatypes_root = "new_plotly/graph_objs" datatype_modules = [ dirpath.replace("/", ".") for dirpath, _, _ in os.walk(datatypes_root) if...
1,468
399
import logging from collections import namedtuple from . import export log = logging.getLogger(__name__) NO_QUERY = 0 PARSED_QUERY = 1 RAW_QUERY = 2 SpecialCommand = namedtuple('SpecialCommand', ['handler', 'command', 'shortcut', 'description', 'arg_type', 'hidden', 'case_sensitive']) COMMANDS ...
4,184
1,279
from abc import ABC, abstractmethod class BaseDataGenerator(ABC): def __init__(self): pass @staticmethod @abstractmethod def generate(cls): pass
180
51
# convert2.py # A program to convert Celsius temps to Fahrenheit. # This version issues heat and cold warnings. def main(): celsius = float(input("What is the Celsius temperature? ")) fahrenheit = 9 / 5 * celsius + 32 print("The temperature is", fahrenheit, "degrees fahrenheit.") if fahrenhei...
466
154
"""The Wolf SmartSet Service integration.""" from datetime import timedelta import logging from httpx import ConnectError, ConnectTimeout from wolf_smartset.token_auth import InvalidAuth from wolf_smartset.wolf_client import FetchFailed, ParameterReadError, WolfClient from homeassistant.config_entries import ConfigEn...
5,082
1,396
class LevenshteinDistance: def solve(self, str_a, str_b): a, b = str_a, str_b dist = {(x,y):0 for x in range(len(a)) for y in range(len(b))} for x in range(len(a)): dist[(x,-1)] = x+1 for y in range(len(b)): dist[(-1,y)] = y+1 dist[(-1,-1)] = 0 for i in range(len(a)):...
932
339
import numpy as np import unittest from pyapprox.benchmarks.spectral_diffusion import ( kronecker_product_2d, chebyshev_derivative_matrix, SteadyStateDiffusionEquation2D, SteadyStateDiffusionEquation1D ) from pyapprox.univariate_polynomials.quadrature import gauss_jacobi_pts_wts_1D import pyapprox as pya cla...
24,156
9,437
import torch from torch import nn from torch.nn import functional as F from torchdrug import layers class ConditionalFlow(nn.Module): """ Conditional flow transformation from `Masked Autoregressive Flow for Density Estimation`_. .. _Masked Autoregressive Flow for Density Estimation: https://arxi...
2,145
601
#!/usr/bin/env python3 import logging import json import os __author__ = 'adamkoziol' class MetadataPrinter(object): def printmetadata(self): # Iterate through each sample in the analysis for sample in self.metadata: # Set the name of the json file jsonfile = os.path.join(...
1,531
361
import numpy as np from sklearn.utils.multiclass import type_of_target from mindware.base_estimator import BaseEstimator from mindware.components.utils.constants import type_dict, MULTILABEL_CLS, IMG_CLS, TEXT_CLS, OBJECT_DET from mindware.components.feature_engineering.transformation_graph import DataNode class Clas...
6,424
1,997
# -*- coding: utf-8 -*- import scrapy import json import os import codecs from AnimeSpider.items import AnimespiderItem class AinmelinklistSpider(scrapy.Spider): name = 'AinmeLinkList' allowed_domains = ['bilibili.com'] start_urls = ['http://bilibili.com/'] def start_requests(self): jsonpath ...
871
288
import cv2 print cv2.__version__
34
13
"""Setup for pytest-testplan plugin.""" from setuptools import setup setup( name='pytest-testplan', version='0.1.0', description='A pytest plugin to generate a CSV test report.', author='Darlene Wong', author_email='darlene.py@gmail.com', license='MIT', py_modules=['pytest_testplan'], ...
416
145
# 环境变量配置,用于控制是否使用GPU # 说明文档:https://paddlex.readthedocs.io/zh_CN/develop/appendix/parameters.html#gpu import os os.environ['CUDA_VISIBLE_DEVICES'] = '0' from paddlex.det import transforms import paddlex as pdx # 下载和解压铝材缺陷检测数据集 aluminum_dataset = 'https://bj.bcebos.com/paddlex/examples/industrial_quality_inspection/da...
2,271
997
# Generated by Django 3.1.4 on 2021-01-07 19:32 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0003_auto_20210107_2010'), ] operations = [ migrations.AlterField( model_name='extrainfo...
950
325
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import wooey.models.mixins class Migration(migrations.Migration): dependencies = [ ('wooey', '0008_short_param_admin'), ] operations = [ migrations.CreateModel( name='Scr...
1,882
532
#!/usr/bin/python """ Firewall for munkireport. By Tuxudo Will return all details about how the firewall is configured """ import subprocess import os import sys import platform import re import plistlib import json sys.path.insert(0,'/usr/local/munki') sys.path.insert(0, '/usr/local/munkireport') from munkilib impo...
3,976
1,186
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/metrics.ipynb (unless otherwise specified). __all__ = ['recall_at_k', 'precision_at_k'] # Cell from typing import List # Cell def recall_at_k(predictions: List[int], targets: List[int], k: int = 10) -> float: """Computes `Recall@k` from the given predictions and ta...
842
281
#!/usr/bin/env/ python import os from math import pi import numpy as np from numpy import ma from scipy.optimize import leastsq import matplotlib.pyplot as plt from uncertainties import ufloat # local modules from .io import load_pendulum_mat_file def average_rectified_sections(data): '''Returns a slice of an o...
15,849
5,401
import time import warnings import matplotlib.pyplot as plt import numpy as np import sympy as sp from .global_qbx import global_qbx_self from .mesh import apply_interp_mat, gauss_rule, panelize_symbolic_surface, upsample def find_dcutoff_refine(kernel, src, tol, plot=False): # prep step 1: find d_cutoff and d_...
11,597
3,847
# -*- coding: utf-8 -*- BROKER_URL = 'amqp://guest@localhost//' CELERY_ACCEPT_CONTENT = ['json'], CELERY_RESULT_BACKEND = 'amqp://guest@localhost//' CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Shanghai' CELERY_ENABLE_UTC = False
277
134
import logging as log class Log: def __init__(self, level): self.level = level log.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s', level=level) self.log = log def info(self, msg): self.log.info(msg) de...
476
169
def structural_loss_dst68j3d(p_pred, v_pred): v_pred = K.stop_gradient(v_pred) def getlength(v): return K.sqrt(K.sum(K.square(v), axis=-1)) """Arms segments""" joints_arms = p_pred[:, :, 16:37+1, :] conf_arms = v_pred[:, :, 16:37+1] diff_arms_r = joints_arms[:, :, 2:-1:2, :] - joint...
7,308
3,802
import aspose.email from aspose.email.clients.imap import ImapClient from aspose.email.clients import SecurityOptions from aspose.email.clients.imap import ImapQueryBuilder import datetime as dt def run(): dataDir = "" #ExStart: FetchEmailMessageFromServer client = ImapClient("imap.gmail.com", 993, "user...
729
231
# Server UID SERVER_UID = 45158729 # Setup Logging system ######################################### # import os from FileConsoleLogger import FileConsoleLogger ServerLogger = FileConsoleLogger( os.path.join(os.path.dirname(os.path.abspath(__file__)), "_w3server.log") ) W3Logger = FileConsoleLogger( os.path.join(os.pa...
2,363
987
from regression_tests import * class Test1(Test): settings = TestSettings( tool='fileinfo', input='8b280f2b7788520de214fa8d6ea32a30ebb2a51038381448939530fd0f7dfc16', args='--json --verbose' ) def test_certificates(self): assert self.fileinfo.succeeded assert self....
46,930
22,727
import subprocess def run(cmd): subprocess.run(cmd.split(' ')) def ls(): subprocess.call(["ls", "-l"])
111
41
# -*- coding: utf-8 -*- # Copyright: (c) 2018, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ become: runas short_description: Run As user ...
2,380
669
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ~Gros ''' from hashlib import sha256 import random def add_padding(data, block_size=16): """add PKCS#7 padding""" size = block_size - (len(data)%block_size) return data+chr(size)*size def strip_padding(data, block_size=16): """strip PKCS#7 padding"...
698
260
# # Copyright (c) 2019 Intel 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...
3,848
1,274
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyMdanalysis(PythonPackage): """MDAnalysis is a Python toolkit to analyze molecular dynami...
4,070
2,037
from requests import get import matplotlib.pyplot as plt import matplotlib.animation as animation import datetime as dt from bme280 import BME280 try: from smbus2 import SMBus except ImportError: from smbus import SMBus fig = plt.figure() ax = fig.add_subplot(1, 1, 1) xs = [] ys =[] bus = SMBus(1) bme280 = ...
786
324
from bootstrapvz.base import Task from bootstrapvz.common import phases from bootstrapvz.common.tasks import workspace import os import shutil assets = os.path.normpath(os.path.join(os.path.dirname(__file__), 'assets')) class CheckOVAPath(Task): description = 'Checking if the OVA file already exists' phase = phase...
5,912
2,274
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
3,498
1,021
# -*- coding: utf-8 -*- # # Copyright (c) 2019~2999 - Cologler <skyoflw@gmail.com> # ---------- # some object for parser # ---------- from typing import List import enum import dis from collections import defaultdict class ID: def __init__(self, name): self._name = name # a name use to debug def __r...
7,742
2,377
from django import forms from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.utils.safestring import mark_safe from django.utils.translation import gettext as _ from dcim.models import DeviceRole, DeviceType, Platform, Region, Site, SiteGroup from tenancy....
15,055
4,416
import torch import torch.nn as nn import torch.nn.functional as F from models.misc import modules constrain_path = { ('threeD', 'normal'): (True, True, ''), ('threeD', 'depth'): (True, True, ''), ('normal', 'depth'): (True, True, ''), ('depth', 'normal'): (True, True, ''), } class UnwarpNet(nn.Modu...
3,122
1,156
import configparser import os import hashlib import json import shutil import sys import tempfile import subprocess import tarfile import re import stat from functools import cmp_to_key from contextlib import closing from gzip import GzipFile from pathlib import Path from urllib.error import HTTPError from urllib.reque...
12,768
3,864
""" Query BGP neighbor table on a Juniper network device. """ import sys from jnpr.junos import Device from jnpr.junos.factory import loadyaml def juniper_bgp_state(dev, bgp_neighbor): """ This function queries the BGP neighbor table on a Juniper network device. dev = Juniper device connection bgp_ne...
690
224
import cherrypy from cherrypy.test import helper class SessionAuthenticateTest(helper.CPWebCase): def setup_server(): def check(username, password): # Dummy check_username_and_password function if username != 'test' or password != 'password': return 'Wrong...
2,170
597
#!/usr/bin/env python from typing import List import aoc from collections import defaultdict @aoc.timing def solve(inp: str, part2=False): def find_path(current: str, path: List[str] = []): if current == 'end': yield path return for nxt in caves[current]: if n...
1,145
393
import numpy as np from ltr.data import transforms import ltr.data.processing_utils as prutils from pytracking.libs import TensorDict class BaseProcessing: """ Base class for Processing. Processing class is used to process the data returned by a dataset, before passing it through the network. For e...
11,387
3,286