text
string
size
int64
token_count
int64
# coding:utf-8 # version:python3.5.1 # author:kyh import flickrapi import datetime import psycopg2 import time # flickr照片类 class flickr_photo(object): def __init__(self, photo_id, photo_city, photo_url): self.id = photo_id self.city = photo_city self.url = photo_url # 将照片插入数据库 de...
5,788
1,950
# -*- coding:utf-8 -*- import requests from bs4 import BeautifulSoup import sys import csv reload(sys) sys.setdefaultencoding('utf-8') def not_empty(str): return str and str.strip() if __name__ == '__main__': url_main = 'http://gz.lianjia.com' f = open(u'广州二手房.csv', 'wb') f.write(unicode('\xEF\xB...
5,767
1,927
import argparse import tempfile import unittest from pygolf.__main__ import get_arguments_warning, read_input_code, shorten class TestMain(unittest.TestCase): def test_reduce(self): self.assertEqual(shorten("print( 1 + 2 )"), "print(1+2)") self.assertEqual(shorten("not valid code"), None) de...
1,165
367
import sys import numpy as np from matplotlib import pyplot as pl def koch(x0, y0, rho, phi, order): global xr, yr x1, y1 = x0 + rho * np.cos(phi), y0 + rho * np.sin(phi) if order: x, y = x0, y0 for angle in [0, np.pi/3, 5*np.pi/3, 0]: x, y = koch(x, y, rho / 3.0, phi + angle, ...
545
274
# -*- coding: utf-8 -*- """ Core views to provide custom operations """ import uuid from datetime import datetime from django.http import HttpResponseRedirect from threepio import logger from atmosphere import settings from django_cyverse_auth.decorators import atmo_login_required from django_cyverse_auth.models imp...
2,995
773
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from enum import Enum from indico.core.errors import IndicoError from indico.core.logger import Logger ...
1,714
481
#!/usr/bin/env python # -*- coding: utf-8 -*- """Check the state of an AWS AMI.""" from __future__ import annotations import json from typing import Any, Dict import boto3 print("Loading function get_image_status") ec2_client = boto3.client("ec2") # { # "instance_id": "i-identifier", # "kms_id": "KMS ID", # ...
814
297
# constants from starfish.core.types import ( # noqa: F401 Axes, Clip, Coordinates, CORE_DEPENDENCIES, Features, LOG, OverlapStrategy, PHYSICAL_COORDINATE_DIMENSION, PhysicalCoordinateTypes, STARFISH_EXTRAS_KEY, TransformType, ) from starfish.core.types import CoordinateValu...
344
136
#!/usr/bin/env python # encoding: utf-8 # # dangerKey.py # # Created by John Donor on 10 April 2019 import re, time from yaml import YAMLObject from alertsActor import log class diskCheck(YAMLObject): """evaluate a disk keyword """ def __init__(self): pass def __call__(self, keyState): ...
6,764
2,049
''' Created on June 24, 2019 @author: Andrew Habib ''' import copy import json import sys import math import numbers import intervals as I from abc import ABC, abstractmethod from greenery.lego import parse from intervals import inf as infinity import config import _constants from canoncalization import canoncalize_...
22,382
6,653
""" Various utilities functions used by django_community and other apps to perform authentication related tasks. """ import hashlib, re import django.forms as forms from django.core.exceptions import ObjectDoesNotExist from django.forms import ValidationError import django.http as http from django.conf import setting...
6,388
1,934
import os from pathlib import Path from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import IncludeLaunchDescription, SetEnvironmentVariable, Shutdown from launch.launch_description_sources import PythonLaunchDescriptionSource from launch_ros.a...
1,909
525
# A Rapid Proof of Concept for the eDensiometer # Copyright 2018, Nikhil Patel. All Rights Reserved. Created with contributions from Billy Pierce. # Imports from PIL import Image from pprint import pprint import numpy as np import time as time_ def millis(): # from https://stackoverflow.com/questions/5998245/get-curr...
1,856
686
import sys import os import matplotlib.pyplot as plt from matplotlib.pyplot import figure import matplotlib as mpl import config def main(): if 1 < len(sys.argv) : diagram_path = sys.argv[1] else: diagram_path = "" curDir = os.path.dirname(os.path.realpath(__file__)) data_path = o...
1,833
666
from core.utilities.functions import delete_message from core.utilities.message import message from core.database.repository.group import GroupRepository """ This function allows you to terminate the type of file that contains a message on telegram and filter it """ def init(update, context): apk = 'application/vnd...
3,157
1,006
from mipsplusplus import utils from mipsplusplus import operations OPERATOR_ORDERING = [ ['addressof', 'not', 'neg'], ['*', '/', '%'], ['+', '-'], ['<<', '>>', '<<<', '>>>'], ['<', '>', '<=', '>='], ['==', '!='], ['and', 'or', 'xor', 'nor'], ['as'] ] EXPR_OPERATORS = set([op for ops in OPERATOR_ORDERI...
4,287
1,433
the_simpsons = ["Homer", "Marge", "Bart", "Lisa", "Maggie"] print(the_simpsons[::-1]) for char in the_simpsons[::-1]: print(f"{char} has a total of {len(char)} characters.") print(reversed(the_simpsons)) print(type(reversed(the_simpsons))) # generator object for char in reversed(the_simpsons): # laduje za kazda...
464
174
from subprocess import call import os import sys sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)) import settings data_zip_path = os.path.join(settings.lfw10_root, "LFW10.zip") data_url = "http://cvit.iiit.ac.in/images/Projects/relativeParts/LFW10.zip" # Downloading the data zip ...
640
235
""" Utility functions to retrieve information about available services and setting up security for the Hops platform. These utils facilitates development by hiding complexity for programs interacting with Hops services. """ import pydoop.hdfs import subprocess import os import stat import sys import threading import t...
9,874
3,233
"""empty message Revision ID: e956985ff509 Revises: 4b471bbc0004 Create Date: 2020-12-02 22:47:08.536332 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'e956985ff509' down_revision = '4b471bbc0004' branch_labels = None depends_on = None def upgrade(): # ...
713
282
from behave.matchers import RegexMatcher from ahk import AHK from behave_classy import step_impl_base Base = step_impl_base() class AHKSteps(AHK, Base): @Base.given(u'the mouse position is ({xpos:d}, {ypos:d})') def given_mouse_move(self, xpos, ypos): self.mouse_move(x=xpos, y=ypos) @Base.when(u...
926
337
import pygame from pygame.locals import * class ControlScheme: def __init__(self): self.up = K_UP self.down = K_DOWN class Bat: def __init__(self, start_pos, control_scheme, court_size): self.control_scheme = control_scheme self.move_up = False self.move_down = False ...
1,703
562
""" An image store representing Rackspace specific images """ from __future__ import absolute_import, division, unicode_literals import attr from six import iteritems from mimic.model.rackspace_images import (RackspaceWindowsImage, RackspaceCentOSPVImage, RackspaceCentOSPVHMIma...
3,527
977
TEST_CONFIG_OVERRIDE = { # An envvar key for determining the project id to use. Change it # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a # build specific Cloud project. You can also use your own string # to use your own Cloud project. "gcloud_project_env": "BUILD_SPECIFIC_GCLOUD_...
926
404
def test(): assert "for ent in doc.ents" in __solution__, "Itères-tu sur les entités ?" assert x_pro.text == "X Pro", "Es-tu certain que x_pro contient les bons tokens ?" __msg__.good( "Parfait ! Bien sur, tu n'as pas besoin de faire cela manuellement à chaque fois." "Dans le prochain exerc...
476
158
filename = '//mx340hs/data/anfinrud_1903/Archive/NIH.pressure_downstream.txt'
77
37
import numpy as nm from sfepy.linalg import dot_sequences from sfepy.terms.terms import Term, terms class DivGradTerm(Term): r""" Diffusion term. :Definition: .. math:: \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u} \mbox{ , } \int_{\Omega} \nu\ \nabla \ul{u} : \nabla \ul{w} \\ ...
17,181
6,288
# Generated by Django 3.1.1 on 2021-09-21 04:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('crawler', '0012_auto_20210921_0451'), ] operations = [ migrations.AlterField( model_name='crawlerline', name='ustatu...
422
155
#!/usr/bin/env python # # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import logging import os import sys import tempfile from subprocess import PIPE, CalledProcessError, check_call # nosec from typing import List, Optional from onefuzztypes.models import NotificationConfig from onefuzzty...
2,713
807
from . import AWSObject, AWSProperty from .validators import * from .constants import * # ------------------------------------------- class WorkSpacesWorkspace(AWSObject): """# AWS::WorkSpaces::Workspace - CloudFormationResourceSpecification version: 1.4.0 { "Documentation": "http://docs.aws.amazon.com/...
3,721
1,108
""" Used to wrap code that will execute potentially risky functionality (typically meaning a service call over the network) with fault and latency tolerance, statistics and performance metrics capture, circuit breaker and bulkhead functionality. """ from __future__ import absolute_import import logging import six fro...
5,718
1,483
import os from functools import lru_cache import numpy as np from qtpy.QtCore import Qt from qtpy import QtCore, QtGui, QtWidgets from matplotlib.colors import ColorConverter from glue.utils.qt import get_qapp from glue.config import viewer_tool from glue.core import BaseData, Data from glue.utils.qt import load_ui ...
12,079
3,500
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
1,781
477
# Copyright 2015 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, ...
5,438
1,474
# -*- coding: utf-8 -*- # # Copyright 2018 Google LLC. 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 requir...
2,453
759
import wave import struct import subprocess import os import opusenc import base64 import zlib import sys tmp = sys.argv[1] + ".wav" subprocess.Popen(["ffmpeg", "-i", sys.argv[1], "-ar", "48000", "-ac", "2", "-y", tmp], stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait() f = open(sys.argv[2], "wb") e ...
775
381
from . import functions as _functions from .functions import * # noqa: F401,F403 from .quad_faces import quads_to_tris __all__ = _functions.__all__ + ["quads_to_tris"]
170
64
from collections import OrderedDict from pathlib import Path from typing import Dict, Optional, Set, Union from ._utils import _chained from .errors import DuplicateError from .mixins import MetadataMixin from .writable import Writable, _filter_out_nones PEGASUS_VERSION = "5.0" __all__ = ["File", "ReplicaCatalog"] ...
10,961
3,234
word_list = ['ABOUT', 'ABOVE', 'ABUSE', 'ACTOR', 'ACUTE', 'ADMIT', 'ADOPT', 'ADULT', 'AFTER', 'AGAIN', 'AGENT', 'AGREE', 'AHEAD', 'ALARM', 'ALBUM', 'ALERT', 'ALIKE', 'ALIVE', 'ALLOW', 'ALONE', 'ALONG', 'ALTER', 'AMONG', 'ANGER', 'ANGLE', 'ANGRY', 'APART', 'APPLE', 'APPLY', 'ARENA', 'ARGUE', 'ARISE', 'ARRAY', 'ASIDE', '...
4,513
2,279
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import itertools import operator from collections import OrderedDict, defaultdict from functools import reduce import six from .formatters import DEFAULT_FORMATTER, DEFAULT_LENGTH from .utils import is_site_package, is_st...
6,759
1,807
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-04-15 22:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("NLP4CCB", "0004_auto_20170330_0255")] operations = [ migrations.RenameField( model_name="userstat", old_name="index...
846
281
import socket import json import pdb import copy def dict_to_bytes(the_dict): string = json.dumps(the_dict).encode('utf-8') return(string) def bytes_to_dict(string): the_dict = json.loads(string.decode('utf-8')) return(the_dict) class server_con(): def __init__(self,host='',port=30): sel...
2,198
752
from collections import defaultdict def return_default(): return 0 def dd(): return defaultdict(return_default) CHALLENGE_DAY = "9" REAL = open(CHALLENGE_DAY + ".txt").read() assert len(REAL) > 1 SAMPLE = open(CHALLENGE_DAY + ".sample.txt").read() SAMPLE_EXPECTED = 127 # SAMPLE_EXPECTED = ...
2,243
860
#!/usr/bin/env python ''' Author : Jonathan Lurie Email : lurie.jo@gmail.com Version : 0.1 Licence : MIT description : The entry point to the library. ''' import GeoToolbox import exifread import piexif from IFD_KEYS_REFERENCE import * import exifWriter import os class ExifAddressFinderManager: ...
3,091
948
import json import logging import requests from typing import List from requests.exceptions import HTTPError, ConnectionError, SSLError, Timeout, ConnectTimeout, ReadTimeout from .User import User from .ModelDetails import ModelDetails logger = logging.getLogger(__name__) class Model(User): def get_models(self) -> ...
1,402
464
import torch from torch import nn from torch.nn import init from fastNLP.modules.encoder.bert import BertModel class Classifier(nn.Module): def __init__(self, hidden_size): super(Classifier, self).__init__() self.linear = nn.Linear(hidden_size, 1) self.sigmoid = nn.Sigmoid() def forw...
1,757
642
# -*- coding: utf-8 -*- """ Defines constants used by P4P2P. Usually these are based upon concepts from the Kademlia DHT and where possible naming is derived from the original Kademlia paper as are the suggested default values. """ #: Represents the degree of parallelism in network calls. ALPHA = 3 #: The maximum num...
2,226
672
from turtle import Turtle import random COLORS = ["red", "orange", "yellow", "green", "blue", "purple"] STARTING_MOVE_DISTANCE = 5 MOVE_INCREMENT = 10 class CarManager(Turtle): def __del__(self): print(f"Deleted: {self}") def __init__(self): super().__init__('square') self.speed(...
600
229
from django.shortcuts import get_object_or_404 from rest_framework import permissions from manabi.apps.flashcards.models import Deck WRITE_ACTIONS = ['create', 'update', 'partial_update', 'delete'] class DeckSynchronizationPermission(permissions.BasePermission): message = "You don't have permission to add this...
941
267
""" Function convert lists of 10 elements into in the format of phone number Example, (123) 456-789 """ def create_phone_number(n: list) -> str: """ >>> create_phone_number([1,2,3,4,5,6,7,8,9,0]) '(123) 456-7890' """ return "({}{}{}) {}{}{}-{}{}{}{}".format(*n) if __name__ == "__main__...
365
165
import click import logging import pandas as pd from pathlib import Path @click.group() def main(): pass @main.command(help="Scan for BACnet devices on your network") @click.option("--ip", help="source IP to use (interface)") @click.option("--dest", default=".", help="destination of scraped points") def scan(ip...
1,539
492
# Copyright 2013-2019 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 PyJdatetime(PythonPackage): """jdatetime is Jalali implementation of Python's datetime mod...
569
238
#!/usr/bin/env python from linklist import * class Solution: def insertionSortList(self, head): dumm = head while head: val, head, prev = head.val, head.next, dumm while val >= prev.val: prev = prev.next while prev != head: prev.v...
646
213
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('robocrm', '0019_auto_20141021_1157'), ] operations = [ migrations.RemoveField( model_name='robouser', ...
976
305
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import cv2 import imageio import numpy as np from tar.miscellaneous import convert_flow_to_color prev = imageio.imread("ressources/1_1.png") prev = cv2.cvtColor(prev, cv2.COLOR_RGB2GRAY) curr = imageio.imread("ressources/1_2.png") curr = cv2.cvtColor(curr, cv2.COLOR_RGB...
527
238
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt def plot_loss(model, n_iter): plt.figure() plt.plot(model.trainloss, 'b-', model.validloss, 'r-') plt.xlim(0, n_iter) plt.xlabel('iteration') plt.ylabel('loss') plt.title('learning curve') plt.legend(['training loss...
998
424
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-12-07 22:20 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('post', '0008_auto_20171207_2256'), ] operations = [ migrations.RemoveField( ...
746
244
import unittest import os import tempfile import shutil import contextlib from pytest import warns from scrapy.exceptions import ScrapyDeprecationWarning from scrapy.utils.project import data_path, get_project_settings @contextlib.contextmanager def inside_a_project(): prev_dir = os.getcwd() project_dir = t...
3,018
960
from trainer.normal import NormalTrainer from config import cfg def get_trainer(): pair = { 'normal': NormalTrainer } assert (cfg.train.trainer in pair) return pair[cfg.train.trainer]()
212
68
#!/usr/bin/python import logging # create logger logger = logging.getLogger() logger.setLevel(logging.DEBUG) # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create file handler which and set level to debug fh = logging.FileHandler('pythonLogging.log') fh.setLev...
776
243
# Copyright 2017 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
3,565
1,142
from sys import argv from server.AServer import AServer if '--old' in argv: from server.server import Server Server() else: AServer( websocket='--websocket' in argv ).Start()
181
62
#!/usr/bin/env python2.7 from common import * from random import randint, choice registers = {\ "a" : int("0000", 2), "f" : int("0001", 2), "b" : int("0010", 2), "c" : int("0011", 2), "d" : int("0100", 2), "e" : int("0101", 2), "h" : int("0110", 2), "l" : int("0111", 2), "af" : int("1000", 2), "bc" : int("1001...
3,081
1,218
from .presence import * from .button import button from .exceptions import * #from .get_current_app import GCAR (Disabling due to a bug) __title__ = "Discord-RPC" __version__ = "3.5" __authors__ = "LyQuid" __license__ = "Apache License 2.0" __copyright__ = "Copyright 2021-present LyQuid"
290
111
# Copyright 2021 The Brax Authors. # # 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 wri...
11,392
3,812
import os import sys def find_docs_root() -> str: filepath = os.path.abspath(__file__) path_chunks = filepath.split(os.path.sep) while path_chunks[-1] != "docs": path_chunks.pop() return os.path.sep.join(path_chunks) sys.path.append(find_docs_root()) from _rtd_conf import * from _sphinx_conf...
330
127
import socket import click import uvicorn # type: ignore def get_address(default: str = "127.0.0.1") -> str: try: ip_address = socket.gethostbyname(socket.gethostname()) except socket.gaierror: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(("8.8.8.8"...
1,314
455
# grappelli GRAPPELLI_ADMIN_TITLE = 'pangolin - Administration panel' # rest framework # REST_FRAMEWORK = { # 'PAGINATE_BY_PARAM': 'limit', # 'SEARCH_PARAM': 'q' # }
175
78
"""Shared clients for kubernetes avoids creating multiple kubernetes client objects, each of which spawns an unused max-size thread pool """ from unittest.mock import Mock import weakref import kubernetes.client from kubernetes.client import api_client # FIXME: remove when instantiating a kubernetes cli...
1,543
447
import dateutil.parser from datetime import datetime from functools import lru_cache from gitlab import Gitlab from gitlab.v4.objects import Project from logging import getLogger from typing import Dict, List, Optional, Union from .custom_types import GitlabIssue, GitlabUserDict from .exceptions import MovedIssueNotDe...
8,956
2,571
import pytheia as pt import os import numpy as np def test_track_set_descriptor_read_write(): recon = pt.sfm.Reconstruction() view_id1 = recon.AddView("0",0.0) m_view1 = recon.MutableView(view_id1) m_view1.IsEstimated = True view_id2 = recon.AddView("1",1.0) m_view2 = recon.MutableView(view_id2...
964
374
"""Common utilities used through this codebase.""" import logging import logging.config class LogMixin: """ A logging mixin class, which provides methods for writing log messages. """ def __init__(self, logger_name: str): """ Creates the logger with the specified name. :para...
1,732
457
import experimentation.statistics.statistics as statistics intersection = statistics.find_matches_from_file('result/experimentation/hmm/anomalous.json', 'result/experimentation/rnn/anomalous.json') print(len(intersection))
224
67
# -*- coding: utf-8 -*- """ @author: Yi Zhang. Department of Aerodynamics Faculty of Aerospace Engineering TU Delft, Delft, Netherlands """ from numpy import sin, cos, pi from objects.CSCG._3d.exact_solutions.status.incompressible_Navier_Stokes.base import incompressible_NavierStokes_Base f...
13,056
5,778
""" __init__.py summary for Transmission Line in a community """ from summary import *
93
29
#!/usr/bin/env python # Copyright (c) 2002-2005 ActiveState Software Ltd. """preprocess: a multi-language preprocessor There are millions of templating systems out there (most of them developed for the web). This isn't one of those, though it does share some basics: a markup syntax for templates that are processed to...
2,344
721
import os BEHIND_REVERSE_PROXY = bool(os.environ.get('BBBS_BEHIND_REVERSE_PROXY', False)) POSTS_PER_PAGE = 25 TEMPLATES_AUTO_RELOAD = True RECAPTCHA_ENABLED = os.environ.get('BBBS_RECAPTCHA_ENABLED', False) RECAPTCHA_SITE_KEY = os.environ.get('BBBS_RECAPTCHA_SITE_KEY', 'CHANGEGME') RECAPTCHA_SECRET_KEY = os.environ...
1,504
700
import os import wget import time import glob import getpass import tarfile import subprocess import email.mime.multipart import email.mime.text import email.mime.image import email.mime.audio from datetime import datetime from pprint import pprint from colorama import Style, Fore from smtplib import SMTP, SMTP_SSL fro...
11,497
3,660
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup(name="pyims", version='0.1.2', description='A python wrapper for the IMS Word Sense Disambiguation tool (Zhong and Ng, 2010)', url='http://github.com/vishnumenon/pyims', author="Vishnu Menon", aut...
736
247
""" This package contains the various actor implementations. """ import typing as T from .base import ActorBase from .custom import CustomActor from .generic import GenericActor from .switch import SwitchActor from .thermostat import ThermostatActor __all__ = [ "ActorBase", "CustomActor", "GenericActor"...
728
234
# UnitTests of all triggmine events import unittest import datetime from client import Client class ClientTest(unittest.TestCase): def setUp(self): self.client = Client('YOUR API_URL', 'YOUR API_KEY') # Registration event def test_registration_success(self): response = self.client.regist...
11,372
3,209
from matplotlib.testing.decorators import image_comparison from mpl_toolkits.axes_grid1 import ImageGrid import numpy as np import matplotlib.pyplot as plt @image_comparison(baseline_images=['imagegrid_cbar_mode'], extensions=['png'], remove_text=True) def test_imagegrid_cbar_mode...
1,605
581
# -*- coding: utf-8 -*- from xbmcgui import ListItem class ExtendedListItem(ListItem): def __new__(cls, name, label2="", path="", **kwargs): return super(ExtendedListItem, cls).__new__(cls, name, label2, path) def __init__( self, name, label2="", iconImage="", ...
4,985
1,501
import numpy as np import imageio import tensorflow as tf from keras.models import load_model from PIL import Image, ImageOps import numpy as np from numpy import asarray from matplotlib import pyplot as plt from keras.utils import normalize import os import random import azure_get_unet import random # for testing pu...
3,451
1,234
from streamlitfront.base import get_pages_specs, get_func_args_specs, BasePageFunc import streamlit as st from pydantic import BaseModel import streamlit_pydantic as sp def multiple(x: int, word: str) -> str: return str(x) + word class Input(BaseModel): x: int y: str def multiple_input(input: Input): ...
1,418
477
from flask_restful import Resource, reqparse parser = reqparse.RequestParser() parser.add_argument('command', required=True) parser.add_argument('docker', required=True) class Build(Resource): def get(self): return {'status': 'building'} def post(self): args = parser.parse_args() pr...
367
107
__copyright__ = "# Copyright (c) 2018 by cisco Systems, Inc. All rights reserved." __author__ = "dwapstra" from unicon.plugins.generic import GenericSingleRpConnection, service_implementation as svc from unicon.plugins.generic.connection_provider import GenericSingleRpConnectionProvider from unicon.plugins.generic im...
1,224
312
from pathlib import Path from shutil import which from subprocess import run, PIPE import click from .main import main, lprint @main.command() @click.pass_context @click.argument('watcher') def symlink(ctx, watcher): """Locally install a symlink to sera""" if ctx.parent.params['watcher']: click.echo...
702
227
import torch from torch import nn import torch.nn.functional as F from torch.utils.data import DataLoader from torchvision import transforms from torchvision.models import resnet18 from torchvision.datasets import CIFAR10 from tqdm import tqdm from torchvision.utils import save_image, make_grid from matplotlib import p...
3,597
1,314
from typing import Optional, Dict, List import aiohttp plate_to_version = { '真1': 'maimai', '真2': 'maimai PLUS', '超': 'maimai GreeN', '檄': 'maimai GreeN PLUS', '橙': 'maimai ORANGE', '暁': 'maimai ORANGE PLUS', '晓': 'maimai ORANGE PLUS', '桃': 'maimai PiNK'...
1,100
483
# # Module to allow connection and socket objects to be transferred # between processes # # multiprocessing/reduction.py # # Copyright (c) 2006-2008, R Oudkerk # Licensed to PSF under a Contributor Agreement. # from __future__ import absolute_import import os import sys import socket import threading from pickle imp...
6,390
2,059
""" 백준 19698번 : 헛간 청약 """ N, W, H, L = map(int, input().split()) print(min(W//L * H//L, N))
92
67
# # This code is part of Ansible, but is an independent component. # # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complet...
13,723
4,009
# Copyright 2020 Dell Inc, or its subsidiaries. # # SPDX-License-Identifier: Apache-2.0 import csv import datetime import os import sys from abc import ABC, abstractmethod from collections import namedtuple from typing import Tuple, List, Iterator from dateutil.relativedelta import relativedelta from dataiq.plugin.u...
2,315
741
import unittest class TestSum(unittest.TestCase): def test_sum(self): self.assertEqual(sum([1,2,3]), 6, 'Should be 6') def test_sum_tuple(self): self.assertEqual(sum((1,2,2)), 6, 'Should be 6') if __name__ == '__main__': unittest.main()
268
105
import os import re import time import numpy as np from msedge.selenium_tools import EdgeOptions, Edge from selenium.webdriver.common.action_chains import ActionChains headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36 Edg/8...
1,913
822
x=input("Enter a umber of which you want to know the square root.") x=int(x) g=x/2 while (g*g-x)*(g*g-x)>0.00000000001: g=(g+x/g)/2 print(g) print(g)
158
85
import pixiedust my_logger = pixiedust.getLogger(__name__)
59
21
# Generated by Django 2.1.11 on 2020-06-04 09:19 from django.db import migrations, models def fix_period_before_after(apps, schema_editor): # noinspection PyPep8Naming Form = apps.get_model("iaso", "Form") for form in Form.objects.filter(period_type=None).exclude(periods_before_allowed=0, periods_after_...
1,212
392
from vc.manager.base import Manager from vc.model.generation_result import GenerationResult class GenerationResultManager(Manager): model_class = GenerationResult
169
43