id
int64
0
10k
text
stringlengths
186
4k
length
int64
128
1.02k
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import find_packages, setup with open('README.md', 'r') as fp: README = fp.read() setup( name='zerobounce', version='0.1.5', description='ZeroBounce Python API - https://www.zerobounce.net.', author='Tudor Aursulesei', author_email...
397
1
# 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"); you may not u...
389
2
config = { "interfaces": { "google.ads.googleads.v6.services.DynamicSearchAdsSearchTermViewService": { "retry_codes": { "retry_policy_1_codes": [ "UNAVAILABLE", "DEADLINE_EXCEEDED" ], "no_retry_codes": [] }, "retry_params": { "retry_policy_1_pa...
663
3
import hashlib import os import re import shutil import subprocess import sys # copy the required files into repo root shutil.copy('docs/favicon.ico', '.') shutil.copy('deploy/windows/instaloader.spec', '.') code = """ import contextlib import psutil import subprocess def __main(): with contextlib.suppress(Attri...
887
4
from flask import jsonify from .settings.default import DefaultConfig from . import create_app # 创建flask应用 app = create_app(DefaultConfig, enable_config_file=True) @app.route('/') def route_map(): """ 主视图 :return: """ rules_iterator = app.url_map.iter_rules() return jsonify({rule.endpoint: ...
156
5
# Generated by Django 2.0 on 2019-05-06 13:31 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('project', '0014_auto_20190505_1708'), ] operations = [ migrations.AlterField( model_name='menuitem', n...
196
6
# coding: utf-8 from leancloud import Engine from app import app from leancloud import Query import leancloud #from leancloud import HttpsRedirectMiddleware #app = HttpsRedirectMiddleware(app) engine = Engine(app) @engine.define def hello(**params): if 'name' in params: return 'Hello, {}!'.format(para...
256
7
"""Model config in json format""" CONFIG = { 'data': { 'train_path': 'data/task1_headline_ABSA_train.json', 'test_path': 'data/task1_headline_ABSA_test.json', 'n_level_1_classes': 4, 'n_level_2_corporate': 12, 'n_level_2_economy': 2, 'n_level_2_market': 4, 'n...
759
8
# Generated by Django 3.1.4 on 2020-12-20 13:57 import core.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0004_recipe'), ] operations = [ migrations.AddField( model_name='recipe', name='image', ...
189
9
from common import log from common.constants import CLIENTS from common.vsphere_api import VsphereApi logger = log.get_logger(__name__) def _get_vsphere_api(hostname): return VsphereApi(hostname) def handler(event, context): logger.debug("Beginning network copy!") from_device_number = event.get("from_d...
492
10
# -*- coding: utf-8 -*- from unittest import mock import pytest from pytube import YouTube from pytube.exceptions import VideoUnavailable @mock.patch("pytube.__main__.YouTube") def test_prefetch_deferred(youtube): instance = youtube.return_value instance.prefetch_descramble.return_value = None YouTube("...
777
11
from django.contrib.auth.middleware import AuthenticationMiddleware from django.contrib.auth.models import User from django.http import HttpRequest from django.test import TestCase class TestSessionAuthenticationMiddleware(TestCase): def setUp(self): self.user_password = 'test_password' self.user ...
921
12
from typing import List, Optional class Error(Exception): """Base W&B Error""" def __init__(self, message): super(Error, self).__init__(message) self.message = message # For python 2 support def encode(self, encoding): return self.message class CommError(Error): """Erro...
977
13
# model settings model = dict( type='ImageClassifier', backbone=dict( type='OTEEfficientNet', version='b0'), neck=dict(type='GlobalAveragePooling'), head=dict( type='LinearClsHead', num_classes=1000, in_channels=1280, loss=dict(type='CrossEntropyLoss', los...
157
14
import time def echo(i): time.sleep(0.001) return i from multiprocessing.pool import Pool p = Pool(10) run1 = [a for a in p.imap_unordered(echo, range(10))] run2 = [a for a in p.imap_unordered(echo, range(10))] run3 = [a for a in p.imap_unordered(echo, range(10))] run4 = [a for a in p.imap_unordered(echo, ...
192
15
# coding: utf-8 """ Isilon SDK Isilon SDK - Language bindings for the OneFS API # noqa: E501 OpenAPI spec version: 10 Contact: sdk@isilon.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import isi_sdk_9_0_0 from ...
381
16
twoStrings=input() stringList=twoStrings.split(" ") str1=stringList[0]; str2=stringList[1] sum=0 k=0;j=0 while True: if k<len(str1): if j<len(str2): multipliedCodes=ord(str1[k])*ord(str2[j]) sum+=multipliedCodes k+=1; j+=1 else: sum+=ord(st...
301
17
# Copyright 2020 MONAI Consortium # 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, s...
491
18
# 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...
554
19
class Player: def __init__(self, x, y): self.name = x self.health = y self.level = 1 def take_hit(self, damage): self.health-=damage def heal(self, amount): self.health+=amount def level_up(self): self.level+=1 self.health = 100 def describe(se...
188
20
import pytest from src.junit_report import JunitTestSuite, JunitTestCase, JunitFixtureTestCase from tests import REPORT_DIR class TestJunitSuiteNoCases: @JunitTestCase() def dummy_test_case(self): pass @JunitTestCase() def other_test_case(self): pass @JunitTestCase() def ex...
401
21
# Copyright 2018-2020 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" fil...
884
22
a = b = c = d = e = f = 69 print(c) x, y, z = 1, 2, 3 print(x) print(y) print(z) data = 1, 2, 3 # Tuple x, y, z = data print(x) print(y) print(z) # Practical applications for t in enumerate("abcdef"): print(t) ninja = ("Kakashi", "Hatake", "Jonin", "Raiton", "Sharingan") name, clan, rank, chakra, special = ...
163
23
# coding=utf-8 # Author: Jianghan LI # Question: 093.Restore_IP_Addresses # Date: 2017-05-13 # 2:22 - 2:34 # Complexity: O(C12^3) class Solution(object): def restoreIpAddresses(self, s): """ :type s: str :rtype: List[str] """ if len(s) > 12: return [] ...
442
24
from setuptools import find_packages, setup import iitgauth try: readme = open('README.rst').read() except IOError: readme = '' setup( name='django-iitg-auth', version='.'.join(str(i) for i in iitgauth.VERSION), description='``django-iitg-auth`` is a reusable Django application ' ...
676
25
""" I18n utilities. """ from gettext import translation _t = translation('udiskie', localedir=None, languages=None, fallback=True) def _(text, *args, **kwargs): """Translate and then and format the text with ``str.format``.""" msg = _t.gettext(text) if args or kwargs: return msg.format(*args, *...
138
26
# Generated by Django 2.2.1 on 2019-05-28 07:19 from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ ('contests', '0003_auto_20190522_1558'), ('countries', '0002_auto_20190522_1513'), ...
405
27
from typing import Dict, Optional from common.constant import HATENA_BLOG_TO_DOC_ENTRY_DICTIONARY_PATH from files.file_accessor import load_json, dump_json class BlogDocEntryMapping: def __init__(self): blog_to_doc: Dict[str, str] = load_json(HATENA_BLOG_TO_DOC_ENTRY_DICTIONARY_PATH) self.__blog_...
597
28
# Let's draw a square on the canvas import turtle ##### INFO ##### # Your goal is to make the turtle to walk a square on the # screen. Let's go through again turtle commands. # this line creates a turtle to screen t = turtle.Turtle() # this line tells that we want to see a turtle shape t.shape("turtle") # this lin...
237
29
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="autopacmen-Paulocracy", version="0.6.0", author="Paulocracy", author_email="bekiaris@mpi-magdeburg.mpg.de", description="The AutoPACMEN package", long_description=long_description, ...
361
30
from .abi import ( # noqa: F401 Decodable, TypeStr, ) from .bls import ( # noqa: F401 BLSPubkey, BLSSignature, ) from .encoding import ( # noqa: F401 HexStr, Primitives, ) from .enums import ( # noqa: F401 ForkName, ) from .ethpm import ( # noqa: F401 URI, ContractName, Mani...
218
31
while True: n = int(input('Quer ver a tabuada de qual valor?[P/ finalizar digite um valor negativo] ')) print(75*'=') if n<0: print('Obrigado por utilizar meus serviços de tabuada!!!\n\033[1;32mVolte sempre ;-)') break c = 1 while c<=10: print(f'{n} x {c} = {n*c}') c+...
181
32
#!/usr/bin/env python # -*- coding: utf-8 -*- """ DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE Version 2, December 2004 Copyright (C) 2015 Thoms Maurice <thomas@maurice.fr> Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing i...
297
33
#!/usr/bin/python # encoding: utf-8 #pylint: disable=R0904 """ Handle imported files """ # upconvert - A universal hardware design file format converter using # Format: upverter.com/resources/open-json-format/ # Development: github.com/upverter/schematic-file-converter # # Copyright 2011 Upverter, Inc. # # Lice...
859
34
""" Django settings for school project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) imp...
794
35
from tests.util import * import pytest def test_failed_always_hungry_fail_escape(): game = get_game_turn() team = game.get_agent_team(game.actor) game.clear_board() passer = team.players[0] passer.role.skills = [] passer.role.ag = 2 passer.extra_skills = [Skill.THROW_TEAM_MATE, Skill.ALWAY...
952
36
"""Utilities for Maps""" from math import sqrt from random import sample # Rename the built-in zip (http://docs.python.org/3/library/functions.html#zip) _zip = zip def map_and_filter(s, map_fn, filter_fn): """Return a new list containing the result of calling map_fn on each element of sequence s for which fi...
993
37
#! /usr/bin/python # -*- coding: utf-8 -*- import tensorflow as tf from tensorlayer import logging from tensorlayer.initializers import constant from tensorlayer.layers.core import Layer __all__ = [ 'Scale', ] class Scale(Layer): """The :class:`Scale` class is to multiple a trainable scale value to the lay...
682
38
# Copyright 2021 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 in wr...
329
39
# Generated by Django 3.0.6 on 2020-05-18 03:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('profiles', '0002_auto_20200517_1855'), ] operations = [ migrations.RemoveField( model_name='profile', name='created_...
295
40
from flask import Flask from config.custom_exception import handle_not_acceptable from controller.restaurants_controller import restaurants_blueprint from documented_endpoints import blueprint as documented_endpoint app = Flask(__name__) app.config['RESTPLUS_MASK_SWAGGER'] = False app.register_blueprint(restaurants_...
143
41
import bitstring zbase32_chars = b'ybndrfg8ejkmcpqxot1uwisza345h769' zbase32_revchars = [ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 25...
942
42
from bitmovin.resources.models import AbstractModel from bitmovin.utils import Serializable class AbstractMP4Representation(AbstractModel, Serializable): def __init__(self, encoding_id, muxing_id, media_file, language=None, track_name=None, id_=None, custom_data=None): super().__init__(i...
503
43
# -*- coding: utf-8 -*- from setuptools import setup, find_packages package_name = "eutils" short_description = open("doc/short-description.txt").read() long_description = open("README.rst").read() setup( author = package_name + " Committers", description = short_description.replace("\n", " "), license =...
858
44
"""Logging to both file and terminal""" import logging import os from pathlib import Path import sys # Instantiate LOGGER LOGGER = logging.getLogger("optimade") LOGGER.setLevel(logging.DEBUG) # Handler CONSOLE_HANDLER = logging.StreamHandler(sys.stdout) try: from optimade.server.config import CONFIG CONSOLE...
820
45
""" Unit tests for decay.py""" # Author: Genevieve Hayes # License: BSD 3 clause import unittest from mlrose import GeomDecay, ArithDecay, ExpDecay, CustomSchedule class TestDecay(unittest.TestCase): """Tests for decay.py.""" @staticmethod def test_geom_above_min(): """Test geometric decay eval...
942
46
class Student(object): def __init__(self, name, gender): self.name = name self.gender = gender def get_name(self): return self.__name def get_score(self): return self.__score def set_score(self, score): if 0 <= score <= 100: self.__score = scor...
364
47
import re from sublime import Region import sublime_plugin REPLACEMENTS = { '\u00a0': ' ', # no-break space '\u200b': '', # zero-width space } class UnicodeTrapsListener(sublime_plugin.EventListener): @staticmethod def on_pre_save(view): view.run_command('unicode_traps') class UnicodeTrap...
261
48
"""Test features process.""" import logging import unittest from titanic.features.feature_config import CONFIG logging.basicConfig() LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.INFO) class TestFeatureConfig(unittest.TestCase): """Simple test example.""" def setUp(self): """Setup w...
177
49
import unittest import networkx as nx import dwave_networkx as dnx from dimod import ExactSolver, SimulatedAnnealingSampler, qubo_energy class TestMaxCut(unittest.TestCase): # def test_edge_cases(self): # # get the empty graph # G = nx.Graph() # S = dnx.maximum_cut(G, ExactSolver()) ...
546
50
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.errors import AnsibleError, AnsibleFilterError import re ''' Strip leading and trailing whitespace from each line while keeping newlines intact ''' def strip_lines(text, collapse=True): text = re.sub('^[ \t...
228
51
import sys import os #Se o rótulo for 1 ou 2 é positivo; se for -1 ou -2 é negativo #=================== #Importante #Assume-se que a estrutura do arquivo lido é composta por tweet, espaço e rótulo #=================== fname = '../label/allLabeled.txt' path = '../label/' path2 = 'train/TwoClasses/' pos = path2 + 'p...
652
52
from django.conf import settings from django.test import TestCase from scan_models.settings import DEFAULT_SETTINGS from scan_models.tests.constances import create_test class TestVerbosity(TestCase): def test_lowest_verbosity(self): self.assertEqual(create_test("tests.TestVerbosity"), {}) def test_f...
336
53
from numify import numify import unittest # ** Tests** class TestNumify(unittest.TestCase): # Test if middle spaces are ignored def test_middle_space(self): testcase = "2 k" expected = 2000 self.assertEqual(numify(testcase), expected) # Test if the trailing alphabet if case...
300
54
# Monkey-patch jinja to allow variables to not exist, which happens with sub-options import jinja2 jinja2.StrictUndefined = jinja2.Undefined # Monkey-patch cookiecutter to allow sub-items from cookiecutter import prompt from ccds.monkey_patch import generate_context_wrapper, prompt_for_config prompt.prompt_for_con...
212
55
# -*- Python -*- # Jiao Lin <jiao.lin@gmail.com> # Refs. Vogel thesis import numpy as np def phi1(theta1): def sum_series(theta1): n = np.arange(1., 35.) series = 1./np.exp(n/theta1)/n/n return np.sum(series) return 1./2+2*(theta1*np.log(1-np.exp(-1/theta1))+theta1**2*(np.pi**2/6 - ...
356
56
"""empty message Revision ID: 7a4a335c28d0 Revises: 38bf7545187a Create Date: 2021-06-19 18:50:31.534280 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '7a4a335c28d0' down_revision = '38bf7545187a' branch_labels = None depends_on = None def upgrade(): # #...
661
57
# -*- coding: utf-8 -*- """ Created on Mon Feb 11 07:57:02 2019 This program is the second challenge in the CodeForCanada 2019 Fullstack Fellowship challenge This program obtains the earliest date and the latest date of violations in each given category. @author: sid ramesh """ ## importing the libraries...
634
58
import signal import pianohat print(""" This simple example shows you how to make Piano HAT keypresses do something useful. You should see details of each press appear below as you touch Piano HAT's keys Press CTRL+C to exit. """) pianohat.auto_leds(True) def handle_touch(ch, evt): print(ch, evt)...
191
59
import pathlib from setuptools import setup import os import sys import re from pathlib import Path # The directory containing this file current_path = pathlib.Path(__file__).parent # The text of the README file readme_path = (current_path / "README.md").read_text() install_requires = ['dtaidistance', 'matplotlib', ...
787
60
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Room.shortname_display' db.add_column('core_room', 'shortname_display', self.gf('django.db...
565
61
import contextlib import time class Timer: def __init__(self, description: str) -> None: self.description = description def __enter__(self): self.start = time.time() def __exit__(self, type, value, traceback): self.end = time.time() elapsed_time = self.end - self....
277
62
import sys from collections import deque from numpypy import * MAXN = 1000005 sys.stdin = open('input.txt') while True: T = int(input()) if not T: break teamOf = zeros((MAXN), dtype=int16) for t in range(T): line = map(int, raw_input().split()) for m in line[1:]: tea...
522
63
import torch import torch.fx.experimental.fx_acc.acc_ops as acc_ops from caffe2.torch.fb.fx2trt.tests.test_utils import AccTestCase, InputTensorSpec from parameterized import parameterized class TestLinearConverter(AccTestCase): @parameterized.expand( [ ("default"), ("no_bias", Fal...
757
64
from mail import mail_time from screenshoot import screenshootfunc import os import sys from sound import sound_go from keystroke import main class keylogger(): def screenshootgo(self): screenshootfunc() def system_name_go(self): return os.environ["USERNAME"] def sys_info(self): ...
207
65
from django.test import TestCase from .sentiment_analyzer import get_article_sentiment class SentimentTest(TestCase): pos_text = """ This is a positive text. What a great story. Excellent! I feel so much joy. This is fantastic! Awesome! I love Hungary! """ neg_text = """ This is a negativ...
257
66
# Generated by Django 2.0.8 on 2018-08-05 10:30 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(...
624
67
players = [] numbers = list(map(int, input().split(","))) input() while True: try: board = [] for _ in range(5): line = list(map(int, input().split())) board.append(line) players.append(board) input() except: break def check(b, i, j): #ro...
723
68
from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.schema import FetchedValue from sqlalchemy.ext.associationproxy import association_proxy from app.api.utils.models_mixins import Base, AuditMixin from app.extensions import db class ConsequenceClassificationStatusCode(Base, AuditMixin): __tablename_...
299
69
import tkinter import cv2, PySimpleGUI as sg USE_CAMERA = 0 # change to 1 for front facing camera window, cap = sg.Window('Demo Application - OpenCV Integration', [[sg.Image(filename='', key='image')], ], location=(0, 0), grab_anywhere=True),\ cv2.Vide...
212
70
from jd.api.base import RestApi class SellerProductApiWriteAddProductRequest(RestApi): def __init__(self,domain,port=80): RestApi.__init__(self,domain, port) self.spuInfo = None self.skuList = None def getapiname(self): return 'jingdong.seller.product.api.write.addProduct' class SpuInfo(object...
555
71
# Copyright (c) Mathias Kaerlev # See LICENSE for details. import os import glob import imp from chowdren.data import ObjectType OBJECTS_DIRECTORY = os.path.join(os.getcwd(), 'objects') class state: objects = None def get_objects(): if state.objects is None: state.objects = {} for name in os...
826
72
#!/usr/bin/env python # Copyright 2016 Criteo # # 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 agree...
748
73
# -*- coding: utf-8 -*- import os import subprocess import click from flask import cli @click.command() @cli.pass_script_info def init(info): """Initialize current app with Relask. :type info: cli.ScriptInfo """ app = info.load_app() relask_dir = os.path.dirname(__file__) package_json = os...
667
74
""" WSGI config for prhood project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTIN...
131
75
from django import template register = template.Library() @register.filter def truncate_char(value, arg): """ Truncates a string after a given number of chars Argument: Number of chars to truncate after """ try: length = int(arg) except ValueError: # invalid literal for int(...
212
76
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the COPYING file. """ Change the branch of the manifest Also, checkout the correct branch for every git project in the worktree """ import sys import qisrc.parsers d...
370
77
''' @Author: Mr.Sen @LastEditTime: 2020-05-27 13:12:02 @Website: https://grimoire.cn @Mr.Sen All rights reserved ''' import time import os from webdav3.client import Client options = { 'webdav_hostname': "https://pan.grimoire.cn/dav", 'webdav_login': "mrsen@grimoire.cn", 'webdav_password': "g6DReYbJFZMtrGXUCROId...
812
78
import unittest from os import path from agora.jobs import VideoStreamCondense HERE = path.abspath(path.dirname(__file__)) class VideoStreamCondenseTestcase(unittest.TestCase): """ Test agora.jobs.VideoStreamCondense job. """ @classmethod def setup_class(cls): cls.sample_data_file = pat...
408
79
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import hashlib import hmac import base64 import json from urllib import parse import requests import time import uuid ecs_url = 'https://ecs.aliyuncs.com/' ram_url = 'https://ram.aliyuncs.com' access_key = "access_key" access_key_secret = "access_key_secret" FORMAT_ISO_...
819
80
import datetime import collections import kungfu.yijinjing.time as kft from kungfu.data.sqlite.data_proxy import CalendarDB, make_url from kungfu.wingchun.constants import * class Calendar: def __init__(self, ctx): self.holidays = CalendarDB(ctx.system_config_location, "holidays").get_holidays() se...
533
81
import numpy as np # import cv2 from matplotlib import pyplot as plt import os from utils import filename_templates as TEMPLATES def prop_flow(x_flow, y_flow, x_indices, y_indices, x_mask, y_mask, scale_factor=1.0): flow_x_interp = cv2.remap(x_flow, x_indices, ...
1,004
82
from fabric.api import local, settings, abort from fabric.contrib.console import confirm # prepare for deployment def test(): with settings(warn_only=True): result = local( "python test_tasks.py -v && python test_users.py -v", capture=True ) if result.failed and not confirm("Tests...
376
83
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright © 2015-2016 Franklin "Snaipe" Mathieu <http://snai.pe/> 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 the Software without restriction, including ...
364
84
# Generated by Django 3.1.6 on 2021-03-15 19:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('fytnet', '0006_weightclass'), ] operations = [ migrations.AddField( model_name='fighter', name='weight', ...
172
85
import re def is_number(str): try: int(str) return True except ValueError: return False def peek(stack): return stack[-1] if stack else None def apply_operator(operators, values): operator = operators.pop() right = values.pop() left = values.pop() values.append(...
672
86
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser # Register your models here. class CustomUserAdmin(UserAdmin): add_form = UserCreationForm form = UserChangeForm model = Cus...
320
87
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_marshmallow import Marshmallow from app.config import Config app = Flask(__name__) db = SQLAlchemy(app) app.config.from_object(Config) migrate = Migrate(app, db) ma = Marshmallow(app) from app import routes, ...
130
88
from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( data_files = [( "dep",["dep/creepon.ppm", "dep/download.ppm", "dep/login.ppm", "dep/quit.ppm", "dep/p...
387
89
# 24. 两两交换链表中的节点 # 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 # 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 # 示例: # 给定 1->2->3->4, 你应该返回 2->1->4->3. # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs(self, head: ListNode) -> List...
740
90
__author__ = 'wanghao' # import threading import sys import socket from struct import * import time import threading def run_flow(dst_ip, port, size): def run(dst_ip, port, size): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # data = os.urandom(size) data = pack('c', 'a') ...
795
91
import numpy as np from three.mathutils import Matrix import math from three.components import * #Plane component, can be used for several things, including collisions #represented by the planes normal and its offset from the center class Plane(Shape): def __init__(self,normal = (0,1,0), offset = 0): super...
275
92
from PyQt5.QtWidgets import * from PyQt5.QtCore import * from easygraphics.widget import ImageWidget from easygraphics import Image import random class MyWindow(QWidget): def __init__(self): super().__init__() self._image = Image.create(800, 600) imageWidget = ImageWidget() imageW...
389
93
from django.db import models class ApiKey(models.Model): key = models.CharField(max_length=300, null=False, blank=False) def __str__(self): return self.key class YoutubeAPIResult(models.Model): video_title = models.TextField(null=False, blank=False) description = models.TextField(null=False...
181
94
#!/usr/bin/env python3 from pynamodb.models import Model from pynamodb.attributes import ( NumberAttribute, UnicodeAttribute, MapAttribute, UTCDateTimeAttribute, BooleanAttribute ) class ContextTable(Model): class Meta: read_capacity_units = 1 write_capacity_units = 1 table_name = "Con...
196
95
import web import importlib try: settings = importlib.import_module('settings') # Assuming that only MySQL is used db = web.database( dbn='mysql', user=getattr(settings, 'dbuser'), pw=getattr(settings, 'dbpw'), db=getattr(settings, 'dbname', 'sprks'), host=getattr(s...
314
96
import typing as t import typing_extensions as te import pytest T = t.TypeVar('T') def typing_modules_for_member(member_name: str) -> t.Sequence[t.Any]: assert hasattr(te, member_name), member_name if hasattr(t, member_name): return (t, te) return (te,) def parametrize_typing_module(member_name: str, a...
197
97
from __future__ import absolute_import, division, print_function import torch def _patch(target): parts = target.split('.') assert parts[0] == 'torch' module = torch for part in parts[1:-1]: module = getattr(module, part) name = parts[-1] old_fn = getattr(module, name) old_fn = ge...
576
98
import os from conans import ConanFile, CMake class TestPackageConan(ConanFile): settings = "os", "compiler", "build_type", "arch" generators = "cmake" def build(self): cmake = CMake(self) cmake.configure() cmake.build() def test(self): assert os.path.isfile(os.path.j...
212
99
# Copyright (c) 2015 Uber Technologies, Inc. # # 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 the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publ...
650