content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from util import start_game, tapToStart, check_game_state
# 从模拟器打开 没运行游戏开始
if __name__ == '__main__':
start_game()
tapToStart()
check_game_state()
# main()
| python |
import json
from datetime import date, datetime, timedelta
import pytest
from jitenshea.webapi import ISO_DATE, ISO_DATETIME, api
from jitenshea.webapp import app
app.config['TESTING'] = True
api.init_app(app)
def yesterday():
return date.today() - timedelta(1)
@pytest.fixture
def client():
client = app.t... | python |
# -*- coding:utf-8 -*-
import os
rootdir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SSL_DISABLE = False
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_RECORD_QUERIES = True
MAIL_S... | python |
## LOX-IPA sim
#@ Author Juha Nieminen
#import sys
#sys.path.insert(0, '/Users/juhanieminen/Documents/adamrocket')
import RocketComponents as rc
from physical_constants import poise, inches, Runiv, gallons, lbm, \
gearth, atm, psi, lbf
from numpy import pi, linspace, cos, radians, sqrt, exp, log, array, ... | python |
import unittest
from kaleidoscope.config import GalleryConfigParser
class TestGalleryConfigParser(unittest.TestCase):
def test_lowercase_key(self):
"""Lowercase option key is left as is."""
config = GalleryConfigParser()
config.read_string("[album]\ntitle: Example\n")
self.assertT... | python |
print("hello,world")
#print(5 ** 4321)
a = 1
if (a < 10 and a > -10):
print("fuck you")
| python |
# -*- coding: utf-8 -*-
"""Domain Driven Design framework."""
from ddd_base import ValueObject
class RouteSpecification(ValueObject):
def __init__(self, api_ref, upstream_ref, policies, tls):
super(RouteSpecification, self).__init__()
self.api_ref = api_ref
self.upstream_ref = upstream_re... | python |
load("//java/private:common.bzl", "has_maven_deps")
load("//java/private:dist_info.bzl", "DistZipInfo", "dist_aspect", "separate_first_and_third_party")
def _java_dist_zip_impl(ctx):
inputs = []
files = []
for file in ctx.files.files:
files.append("%s=%s" % (file.basename, file.path))
input... | python |
"""draws the price charts for all the securities in the currently active
case"""
from multiprocessing.connection import Listener
from bokeh.driving import count
from bokeh.layouts import layout, column, gridplot, row, widgetbox
from bokeh.models import ColumnDataSource, CustomJS, Span
from bokeh.plotting import curdoc,... | python |
#function = -x**2 + 2*x - 1
# x = [0,3]
import random
import easygui
import math
def representation(interval,precision,no_selected):
original_list = []
largest = int(interval*(10**precision))
select_interval = int(largest//no_selected)
for i in range(1,largest + 1):
str_temp = ''
if i %... | python |
import pytz
from datetime import datetime
from FlaskRTBCTF import create_app, db, bcrypt
from FlaskRTBCTF.helpers import handle_admin_pass
from FlaskRTBCTF.models import User, Score, Notification, Machine
from FlaskRTBCTF.config import organization, LOGGING
if LOGGING:
from FlaskRTBCTF.models import Logs
app = ... | python |
# This file is part of DroidCarve.
#
# Copyright (C) 2020, Dario Incalza <dario.incalza at gmail.com>
# All rights reserved.
#
__author__ = "Dario Incalza <dario.incalza@gmail.com"
__copyright__ = "Copyright 2020, Dario Incalza"
__maintainer__ = "Dario Incalza"
__email__ = "dario.incalza@gmail.com"
from adbutils impo... | python |
import logging
_FORMAT = '%(asctime)s:%(levelname)s:%(lineno)s:%(module)s.%(funcName)s:%(message)s'
_formatter = logging.Formatter(_FORMAT, '%H:%M:%S')
_handler = logging.StreamHandler()
_handler.setFormatter(_formatter)
logger = logging.getLogger('yatsm')
logger.addHandler(_handler)
logger.setLevel(logging.INFO)
lo... | python |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def pathSum(root: TreeNode, sum: int) -> [[int]]:
temp = []
result = []
def dfs(root: TreeNode, left: int) :
if not root :
return
... | python |
"""Perform non-linear regression using a Hill function."""
import numpy as np
import math
from scipy.optimize import curve_fit
class Hill:
"""A Hill function is for modeling a field falloff (i.e. penumbra). It's not a perfect model, but it fits to a
function, which is not limited by resolution issues as may ... | python |
### Wet HW2 DIP ###
import numpy as np
import matplotlib.pyplot as plt
import cv2
from scipy import fftpack
###########################################################################
###########################################################################
############################################################... | python |
from pathlib import Path
from code_scanner.data_validators import validator
from code_scanner.enums import FileType
class FileInfo:
def __init__(self, full_name: Path, file_type: FileType = FileType.UNKNOWN):
"""
:param full_name: Absolute folder without file, Path
:param file_type: ... | python |
#
# Base engine class
# Copyright EAVISE
#
import logging
import signal
from abc import ABC, abstractmethod
import lightnet as ln
__all__ = ['Engine']
log = logging.getLogger(__name__)
class Engine(ABC):
""" This class removes the boilerplate code needed for writing your training cycle. |br|
Here is th... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import yaml
import roslib
from sensor_msgs.msg import CameraInfo, Image
import rospy
class CameraInfoPublisher:
# Callback of the ROS subscriber.
def callback(self, data):
self.cam_info.header = data.header
self.publish()
def __init__... | python |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def cal_Nash(obs_path, predict_array):
obs = pd.read_csv(obs_path, index_col=0, parse_dates = True)
obs_chl = obs['chla'].iloc[:-1]
| python |
import serial
import time
arduino = serial.Serial("COM5", 9600, timeout=0)
time.sleep(5)
for i in range(10000):
arduino.write(chr(0+48).encode())
arduino.write(chr(1+48).encode())
arduino.write(chr(2+48).encode())
arduino.write(chr(3+48).encode())
arduino.write(chr(4+48).encode())
arduino.write(... | python |
#!/usr/bin/env python3
"""
domain2idna - The tool to convert a domain or a file with a list
of domain to the famous IDNA format.
This submodule contains all helpers that are used by other submodules.
Author:
Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom
Contributors:
Let's contribute to domains2id... | python |
from models.nasnet_do import NASNet_large_do
from tensorflow.keras import Model, Input
from tensorflow.keras.applications import DenseNet169
from tensorflow.keras.layers import Dropout, UpSampling2D, Conv2D, BatchNormalization, Activation, concatenate, Add
from tensorflow.keras.utils import get_file
from . import Net... | python |
"""
Profile ../profile-datasets-py/standard54lev_o3_trunc/005.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/standard54lev_o3_trunc/005.py"
self["Q"] = numpy.array([ 4.902533, 4.833692, 4.768255, 4.706048,
4.646861, 4.590505, 4... | python |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\rabbit_hole\tunable_rabbit_hole_condition.py
# Compiled at: 2018-08-14 18:06:05
# Size of source mod... | python |
# -*- coding: utf-8 -*-
"""FIFO Simulator."""
from __future__ import annotations
import queue
from queue import Queue
import threading
from typing import Any
from typing import Dict
from typing import Optional
from stdlib_utils import drain_queue
from xem_wrapper import DATA_FRAME_SIZE_WORDS
from xem_wrapper import D... | python |
import sys
from pathlib import Path
from setuptools import find_packages, setup
project_slug = "nptyping"
here = Path(__file__).parent.absolute()
def _get_dependencies(dependency_file):
with open(here / "dependencies" / dependency_file, mode="r", encoding="utf-8") as f:
return f.read().strip().split("\n... | python |
from math import pi
import numpy as np
cm = 0.23
km = 370.0
WIND = 5.0
OMEGA = 0.84
AMPLITUDE = 0.5
CHOPPY_FACTOR = np.array([2.3, 2.1, 1.3, 0.9], dtype=np.float32)
PASSES = 8 # number of passes needed for the FFT 6 -> 64, 7 -> 128, 8 -> 256, etc
FFT_SIZE = 1 << PASSES # size of the textures storing the waves in... | python |
from datasets.kitti import *
from Archs_3D.build_retina3d_model import build_model
from Solver.Solver import Solver
import operator
import logging
import os
import sys
import copy
import datetime
from datasets.distributed_sampler import *
from datasets.dataset_utils import AspectRatioGroupedDataset
import numpy as np
i... | python |
from __future__ import absolute_import, division, print_function
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
def create_flags():
# Importer
# ========
tf.app.flags.DEFINE_string ('train_files', '', 'comma separated list of files specifying the dataset used for training. multiple ... | python |
"""
Original Demo: http://js.cytoscape.org/demos/concentric-layout/
Original Code: https://github.com/cytoscape/cytoscape.js/blob/master/documentation/demos/concentric-layout/code.js
Note: This example is broken because layout takes a function as input, i.e.
```
layout: {
name: 'concentric',
concentric: func... | python |
import json
import hikari
async def debug(event: hikari.GuildMessageCreateEvent, command: str, config, *args) -> None:
await event.message.respond(json.dumps({
"command": command,
"args": args,
"user": event.message.author.username,
}))
| python |
from .models import TopLevelDomain,WhoisServer,Domain
import json
import dateutil.parser
from django.db.models.functions import Length
import xmltodict
import socket
import pythonwhois
TLD_FIELDS_MAP = {
'@name':"name",
'countryCode' : "country_code" ,
"created": 'created',
"changed": 'changed',
... | python |
# Copyright (c) 2020 - for information on the respective copyright owner
# see the NOTICE file and/or the repository https://github.com/boschresearch/blackboxopt
#
# SPDX-License-Identifier: Apache-2.0
import time
from typing import Callable
import parameterspace as ps
from blackboxopt import Evaluation, EvaluationS... | python |
from typing import Iterator # noqa
from pyramid.config import Configurator
from pyramid.httpexceptions import HTTPInternalServerError
from pyramid.response import Response
from pyramid.request import Request # noqa
import httpretty
import pytest
import _pytest # noqa
import webtest
httpretty.HTTPretty.allow_net_c... | python |
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
import xmlrpc.client
import time
import ntplib
from time import ctime
import _thread
import math
import psutil
s = xmlrpc.client.ServerProxy("http://localhost:9700")
while(True):
per_cpu = psutil.cpu_percent();
... | python |
from models.connection import get_cnx, tables
ballot_table = tables["ballot"]
ballot_info = tables["ballot_info"]
score_table = tables["scores"]
ranks_table = tables["ranks"]
class Ballot:
@staticmethod
def _bool_to_SQL(witness: bool):
return 1 if witness else 0
@staticmethod
def create_ball... | python |
"""
Martin Kersner, m.kersner@gmail.com
seoulai.com
2018
Adapted by Gabriela B. to work with python 2.7 and ROS
"""
from base import Constants
from base import Piece
import rospy #to print debug info
class Rules(object):
@staticmethod
def get_opponent_type(ptype) :
"""Get a type of opponent agent.
... | python |
"""Bubble sort Implementation in python."""
def bubble_sort(unsorted_list):
"""Iterate through an unsorted list and swap elements accordingly."""
# make a copy of the list
unsorted_copy = unsorted_list[:]
for index in range(len(unsorted_list) - 1):
if unsorted_copy[index] > unsorted_copy[ind... | python |
"""Builds a pip package suitable for redistribution.
Adapted from tensorflow/tools/pip_package/build_pip_package.sh. This might have
to change if Bazel changes how it modifies paths.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
impor... | python |
"""
TODO: Insert player name in combat text
"""
import random as random
import threading as threading
import config as config
import items as items
lock = threading.Lock()
def link_terminal(terminal):
global terminal_output
terminal_output = terminal
def success(strength, attack_modifier, defense, att... | python |
# Generated by Django 3.2.3 on 2021-05-26 16:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('TrafficMan', '0003_alter_violationprocess_options'),
]
operations = [
migrations.AlterField(
model_name='vehicle',
n... | python |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | python |
#!/usr/bin/env python
'''
We get the lidar point cloud and use it to determine if there are any obstacles ahead
Author:
Sleiman Safaoui & Kevin Daniel
Email:
snsafaoui@gmail.com
Github:
The-SS
Date:
Oct 3, 2018
'''
# python
from __future__ import print_function
import numpy as np
import copy
import math
from numpy ... | python |
from b3get import to_numpy
import numpy as np
def test_available():
assert dir(to_numpy)
def test_wrong_ds():
assert to_numpy(43) == (None, None)
def test_008():
imgs, labs = to_numpy(8)
assert len(imgs) > 0
assert len(imgs) == 24
assert isinstance(imgs[0], np.ndarray)
assert imgs[0].... | python |
"""/**
* @author [Jai Miles]
* @email [jaimiles23@gmail.com]
* @create date 2020-05-20 13:17:50
* @modify date 2020-08-15 14:38:03
* @desc [
Handlers for mode statistics.
- ModeStatsHandler
TODO: Consider refactoring this into differnet handlers??
]
*/
"""
##########
# Imports
##########
from as... | python |
import re
class Particle:
def __init__(self, number, position, velocity, acceleration):
self.number = number
self.position = position
self.velocity = velocity
self.acceleration = acceleration
self.destroyed = False
def move(self):
for i in range(len(self.accele... | python |
"""
Python code for hashing function
"""
def search(x):
if x > 0:
if has[x][0] == 1:
return True
# if X is negative take the absolute value of x.
x = abs(x)
if has[x][1] == 1:
return True
return False
def insert(a, n):
for i in range(0, n):
if a[i] >= 0:
... | python |
# -*- coding: utf-8 -*-
import numpy as np
from votesim.votemethods.ranked import borda
def test_wiki_1():
"""Test wiki example,
https://en.wikipedia.org/wiki/Borda_count, Mar-3-2021
"""
# Andrew Brian Catherine David
# A B C D
d = (
[[1, 3, 2, 4]] * 51 +
[[4, 2, 1, 3]]... | python |
from pypy.rpython.memory.gctransform.test.test_transform import rtype
from pypy.rpython.memory.gctransform.stacklessframework import \
StacklessFrameworkGCTransformer
from pypy.rpython.lltypesystem import lltype
from pypy.translator.c.gc import StacklessFrameworkGcPolicy
from pypy.translator.translator import Tran... | python |
from applauncher.kernel import ConfigurationReadyEvent
import redis
class RedisBundle(object):
def __init__(self):
self.config_mapping = {
'redis': {
'host': {'type': 'string', 'default': 'localhost'},
'port': {'type': 'integer', 'default': 6379},
... | python |
"""This class stores all of the samples for training. It is able to
construct randomly selected batches of phi's from the stored history.
"""
import numpy as np
import time
floatX = 'float32'
class DataSet(object):
"""A replay memory consisting of circular buffers for observed images,
actions, and rewards.
... | python |
from .client import ExClient
from .mock import MockTransport
from .models import ResponseMixin
from .transport import AsyncHTTPTransportMixin
| python |
import asyncio
import logging
import synapse.exc as s_exc
import synapse.telepath as s_telepath
import synapse.lib.base as s_base
import synapse.lib.stormtypes as s_stormtypes
logger = logging.getLogger(__name__)
stormcmds = (
{
'name': 'service.add',
'descr': 'Add a storm service to the cortex.... | python |
from datetime import date, datetime
import pytz
from Cinema.models.Actor import Discount
from Cinema.models.Actor import Actor
from Cinema.models.Movie import Movie
from Cinema.models.Projection import Projection, Entry
from Cinema.models.Hall import Seat
from django.db.models import Sum
from django.db.models impo... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
After 40755, what is the next triangle number
that is also pentagonal and hexagonal?
T285 = P165 = H143 = 40755.
"""
def pe45():
"""
>>> pe45()
(1533776805, 27549)
"""
limit = 30000
h = [n * ((n << 1) - 1) for n in range(144, limit)]
p = set... | python |
from kikola.core.context_processors import path
from kikola.core.decorators import render_to, render_to_json
@render_to_json
def context_processors_path(request):
return path(request)
@render_to('core/render_to.html')
def decorators_render_to(request):
return {'text': 'It works!'}
@render_to('core/render_... | python |
from .tasks import (
AsyncTasks,
Tasks,
CloudFunction,
as_completed,
GroupTerminalException,
BoundGlobalError,
)
# Backwards compatibility
from descarteslabs.common.tasks import FutureTask, TransientResultError
TransientResultException = TransientResultError
__all__ = [
"AsyncTasks",
... | python |
#!/usr/bin/env python
#
# utils.py
"""
Utility functions for Markdown -> HTML -> LaTeX conversion.
"""
#
# Copyright © 2020-2021 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (t... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Unit tests for nginxfmt module."""
import contextlib
import logging
import pathlib
import shutil
import tempfile
import unittest
import nginxfmt
__author__ = "Michał Słomkowski"
__license__ = "Apache 2.0"
class TestFormatter(unittest.TestCase):
fmt = nginxfmt.F... | python |
#!/usr/bin/python3
"""
Revision history:
24 Sep 2020 | 1.0 - initial release
"""
DOCUMENTATION = '''
---
module: hjson_to_json.py
author: Sanjeevi Kumar, Wipro Technologies
version_added: "1.0"
short_description: Read an .hjson file and output JSON
description:
- Read the HJON file specified and out... | python |
import django_userhistory.models as models
from django.contrib import admin
try:
admin.site.register(models.UserAction)
admin.site.register(models.UserHistory)
admin.site.register(models.UserTrackedContent)
except Exception, e:
pass | python |
"""
"""
load("@bazel_skylib//lib:shell.bzl", "shell")
def _stately_copy_impl(ctx):
input_files = ctx.files.srcs
if ctx.attr.state_file:
state_file = ctx.attr.state_file
else:
state_file = ".stately.yaml"
args = [
a
for a in ["copy"] + [f.short_path for f in input_files... | python |
from __future__ import unicode_literals
import logging
from django.utils.translation import ugettext as _
import django.views.decorators.cache
import django.views.decorators.csrf
import django.views.decorators.debug
import django.contrib.auth.decorators
import django.contrib.auth.views
import django.contrib.auth.forms... | python |
# -*- coding: utf-8 -*-
import unittest
import tempson
from .coloredPrint import *
vm = tempson.vm()
class vmTest(unittest.TestCase):
def test_execute_code (self):
result = vm.evalExpToStr('a + 3', { 'a': 1 }, True)
try:
self.assertEqual(result, '4', 'Evaluate error')
except A... | python |
#!/usr/bin/env python3
# Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import json
import os.path
import re
import sys
_COMPAT_KEY = '__compat'
_EXPERIME... | python |
from django.utils import timezone
def get_now():
"""
Separado para poder establecer el tiempo como sea necesario durante los tests
"""
return timezone.now()
def setallattr(obj, **kwargs):
for k in kwargs:
setattr(obj, k, kwargs.get(k))
def dict_except(obj, *args):
result = {}
f... | python |
"""
Link: https://www.hackerrank.com/challenges/py-if-else/problem?isFullScreen=true
Problem: Python If-ELse
"""
#Solution
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
if n % 2 != 0:
print("Weird")
else:
... | python |
import unittest
from pymal import account
from pymal.account_objects import account_animes
from pymal import anime
from pymal.account_objects import my_anime
from tests.constants_for_testing import ACCOUNT_TEST_USERNAME, ACCOUNT_TEST_PASSWORD, ANIME_ID
class AccountAnimeListTestCase(unittest.TestCase):
EXPECTED... | python |
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.views import APIView
from rest_framework import permissions
from views.retrieve_test_view import TEST_QUESTIONS, retrieve_test_data, is_test_public
class TestQuestionsSet(APIView):
def get(self, request):
return retrieve_tes... | python |
from flask import request
from flask_restplus import Namespace, Resource, fields
from api.utils import validator
from api.service.community_question import get_all_community_questions, create_community_question, get_all_question_comments
from .community_comment import community_comment_schema
import json
api = Names... | python |
import straws_screen
import gravity_screen
import diagon_screen
# 3440 x 1440
# WIDTH = 3440
# HEIGHT = 1440
# 2880 x 1800
WIDTH = 2880
HEIGHT = 1800
# 800 x 800
# WIDTH = 800
# HEIGHT = 800
#my_screen = straws_screen.StrawsScreen();
my_screen = gravity_screen.GravityScreen();
#my_screen = diagon_screen.DiagonScree... | python |
"""
File: hailstone.py
Name: Justin Kao
-----------------------
This program should implement a console program that simulates
the execution of the Hailstone sequence, defined by Douglas
Hofstadter. Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
def main():
"""
Use... | python |
# -*- coding: utf-8 -*-
"""
Base class for Topologies.
You can use this class to create your own topology. Note that every Topology
should implement a way to compute the (1) best particle, the (2) next
position, and the (3) next velocity given the Swarm's attributes at a given
timestep. Not implementing these methods... | python |
import numpy as np
import numpy.linalg as lin
MAX_ITERS = 20
EPSILON = 1.0e-7
def h(theta, X, y):
margins = y * X.dot(theta)
return 1 / (1 + np.exp(-margins))
def J(theta, X, y):
probs = h(theta, X, y)
mm = probs.size
return (-1 / mm) * np.sum(np.log(probs))
def gradJ(theta, X, y):
... | python |
#############################################################################
#
# Author: Ruth HUEY, Michel F. SANNER
#
# Copyright: M. Sanner TSRI 2000
#
#############################################################################
#
# $Header: /opt/cvs/python/packages/share1.5/AutoDockTools/autotors4Commands.py,v 1.... | python |
################################################################################
# siegkx1.py
#
# Post Processor for the Sieg KX1 machine
# It is just an ISO machine, but I don't want the tool definition lines
#
# Dan Heeks, 5th March 2009
import nc
import iso_modal
import math
###########################... | python |
#!/Users/duhuifeng/Code/RentHouseSite/renthouse/macvenv/bin/python
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| python |
from __future__ import absolute_import
from datetime import timedelta
from django.utils import timezone
from rest_framework.response import Response
from sentry.app import tsdb
from sentry.api.base import EnvironmentMixin
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.exceptions import ResourceD... | python |
# Generated by Django 2.2.1 on 2019-06-08 01:31
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Palace',
fields=[
... | python |
import re
from SingleLog.log import Logger
from . import i18n
from . import connect_core
from . import screens
from . import command
from . import _api_util
def has_new_mail(api) -> int:
cmd_list = list()
cmd_list.append(command.go_main_menu)
cmd_list.append(command.ctrl_z)
cmd_list.append('m')
... | python |
numerator = 32
denominator = 1
print numerator / denominator #dividing by zero, big no-no
#all code below this won't get executed
print "won't get executed"
| python |
from PIL import Image
import os
import glob
saveToPath = "C:\\Users\\phili\\Desktop\\"
filePath = input("File: ")
filePath = filePath[1:-1]
fileName = filePath.split("\\")[len(filePath.split("\\")) - 1]
image = Image.open(filePath)
size = image.size
print("Current image size of " + fileName + " is: " + str(size))... | python |
def log(msg, dry_run=False):
prefix = ''
if dry_run:
prefix = '[DRY RUN] '
print('{}{}'.format(prefix, msg))
| python |
#!/usr/bin/python3
"""
some code taken from huffman.py
"""
import sys
from functools import reduce
from operator import add
from math import log, log2
from random import shuffle, choice, randint, seed
from bruhat.argv import argv
EPSILON = 1e-8
def is_close(a, b):
return abs(a-b) < EPSILON
class Multiset... | python |
from graphene.types.generic import GenericScalar
from ..utils import dashed_to_camel
class CamelJSON(GenericScalar):
@classmethod
def serialize(cls, value):
return dashed_to_camel(value)
| python |
from django.conf.urls import url
from . import views
app_name = 'users'
urlpatterns = [
url(
regex=r'^~redirect/$',
view=views.UserRedirectView.as_view(),
name='redirect'
),
url(
regex=r'^$',
view=views.UserDetailView.as_view(),
name='detail'
),
url(... | python |
import torch
from PIL import Image
import torch.nn.functional as F
def load_image(filename, size=None, scale=None):
img = Image.open(filename).convert('RGB')
if size is not None:
img = img.resize((size, size), Image.ANTIALIAS)
elif scale is not None:
img = img.resize((int(img.size[0] / sca... | python |
class TrapException(RuntimeError):
pass
class Memory:
def __init__(self, comp):
self.storage = dict()
self.comp = comp
def __getitem__(self, key):
if not isinstance(key, int) or key < 0:
self.comp.trap("Invalid memory access key {}".format(key))
else:
... | python |
"""Dependency labeling Edge Probing task.
Task source paper: https://arxiv.org/pdf/1905.06316.pdf.
Task data prep directions: https://github.com/nyu-mll/jiant/blob/master/probing/data/README.md.
"""
from dataclasses import dataclass
from jiant.tasks.lib.templates.shared import labels_to_bimap
from jiant.tasks.lib.te... | python |
from pydigilent import *
import time
ad2 = AnalogDiscovery2()
v = 3.5
ad2.power.vplus.enable = 1
ad2.power.vplus.voltage = v
# after configuring power options, the master must be switched to enable
ad2.power.master.enable = 1
ad2.scope.channel1.vertical_division = 1.
while ad2.scope.channel1.voltage < v:
print... | python |
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
import os
author = " * author:tlming16\n"
email = " * email:tlming16@fudan.edu.cn\n"
license = " * all wrong reserved\n"
text= "/* \n" + author + email+ license +"*/\n";
file_list =os.listdir("./test");
def write_file( f):
if not f.endswith(".cpp"):
return
conte... | python |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | python |
# -*- coding: utf-8 -*-
"""
pygments.lexers.inferno
~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Inferno os and all the related stuff.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, include, by... | python |
# Generated by Django 3.2.7 on 2021-11-23 16:39
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Brand',
fields=[
... | python |
#!/user/bin/env python
# -*- coding: utf-8 -*-
import re
import sys
from flask import render_template, request, redirect
from flask_login import current_user
from Web import right_url_prefix as url_prefix, create_blue
from Web import control
sys.path.append('..')
__author__ = 'Zhouheng'
html_dir = "/RIGHT"
develo... | python |
#!/usr/bin/env python 3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 PanXu, Inc. All Rights Reserved
#
"""
flat pretrained vocabulary
Authors: PanXu
Date: 2021/02/24 10:36:00
"""
from easytext.data import PretrainedVocabulary, Vocabulary
class FlatPretrainedVocabulary(PretrainedVocabulary):
"""
Flat p... | python |
# This file is part of Indico.
# Copyright (C) 2002 - 2021 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 datetime import timedelta
import pytest
from indico.modules.events import Event
from indico.modules... | python |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(color_codes=True, font_scale=1)
import itertools
# marker = itertools.cycle(("o", "^", "s"))
marker = itertools.cycle((None,))
markevery = 20
from tensorboard.backend.event_processing import event_accumulator
def plot_result_csv(folders... | python |
loglevel = 'info'
errorlog = "-"
accesslog = "-"
bind = '0.0.0.0:5000'
workers = 2
timeout = 60
| python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.