text stringlengths 38 1.54M |
|---|
import json
from pathlib import Path
from typing import Dict, Tuple, Any
import gym
from gym import spaces
import numpy as np
from gym_d2d.actions import Action, Actions
from gym_d2d.envs.obs_fn import LinearObsFunction
from gym_d2d.envs.reward_fn import SystemCapacityRewardFunction
from gym_d2d.id import Id
from gym... |
'''
查询协议接口
https://payment.test.bkjk.com/api/protocol/find
'''
#coding:utf-8
import json
import request
transNo = 'TR181212113002713403251'
print('####################查询协议开始##################')
##查询协议入参
data2 = {"transNo":transNo}
#查询协议请求地址
url2 = 'https://payment.test.bkjk.com/api/protocol/find'
t2 = request.reque... |
a = 3
b = 5
#I Sposób
# temp = a
# a = b
# b = temp
#II Sposób
# b = a + b #b = 8
# a = b - a #a = 5
# b = b - a #b = 3
#III Sposób
a, b = b, a
#c, d, e = [1, 2, 3]
print("a:",a,"oraz b:",b) |
__author__ = 'Justin'
w = "CAB"
def prepend(l, s):
return l+s
def append(l, s):
return s+l
num_tests = int(raw_input())
for x in xrange(1, num_tests+1):
w = raw_input()
first = w[0]
rest = w[1:]
words = list(first)
for letter in rest:
ws = []
for wor... |
import matplotlib.pyplot as plt
from math import exp, log
from numpy.random import uniform, exponential
SAMPLE_SIZE = 10 ** 6
A = 0.3
C = 1 / (2 * A + 2 * exp(-A))
EPS = 0
BINS = 1000
def save_plot(filename, ys):
plt.clf()
xs = list(range(len(ys)))
plt.plot(xs, ys)
plt.savefig(filename)
def save_hi... |
from rest_framework import serializers
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
from .models import Drone, Command
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'password')
extra_... |
import logging
from decimal import Decimal
from typing import List
from pyinjective.composer import Composer as InjectiveComposer
from pyinjective.constant import Denom, Network
from pyinjective.orderhash import OrderHashResponse, build_eip712_msg, hash_order
from pyinjective.proto.injective.exchange.v1beta1 import (
... |
import time
import pandas as pd
import numpy as np
import os
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一(替换sans-serif字体)
df = pd.read_csv('Metadata.csv')
accounts = df['account'].values
names = df['中译'].values
account2name = dict(zip(accounts, names))
token = 'http://api.moe... |
'''
Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.
Example 1:
Input: [[0, 30],[5, 10],[15, 20]]
Output: 2
Example 2:
Input: [[7,10],[2,4]]
Output: 1
'''
class Solution:
def minMeetingRooms(self, in... |
import cv2
import numpy as np
img = np.zeros((512, 512, 3), np.uint8)
img = cv2.line(img, (10,30), (400,400), (0,255,0), 5)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
# Generated by Django 3.0.2 on 2020-04-23 00:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0042_statements_ending_balance'),
]
operations = [
migrations.AddField(
model_name='statements',
name='R... |
a = '''A: Hi miss, how are you today? Are you checking in?
B: Yes, I had a room reserved under the name Rebecca
A: Oh ok, let me check. Oh great I found your reservation, you are in room 207.
B: Great so here are your keys and we have a complimentary continental breakfast between 7am and 10am in the lobby. Wou... |
# Copyright 2023 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provides a layer of abstraction for the issue tracker API."""
from http import client as http_client
import json
import logging
from apiclient import discovery
from apiclient ... |
# -*-coding:utf-8 -*-
"""
"""
import os
import shutil
from application.model.event import Event
from application.model.payment_method import PaymentMethod
from application.model.permission import Permission
from application.model.role import Role
from application.model.role_permission import RolePermission
from appli... |
from NeuralNetwork import NeuralNetwork
from random import choice
from pygame.draw import circle
import numpy as np
from colorsys import hsv_to_rgb
species = []
maxSpecies = 10
inputs = 13
outputs = 2
layers = range(1, 6)
layerSizes = range(2, 15)
def generateSpecies(num):
global species
species = []
for i in ran... |
parta = "smallsdss"
partb = ["12.5", "17.5", "22.5", "27.5"]
neg = ["", "neg"]
end = ".csv"
error = ["", "Calc_Error_", "Error_"]
temp = []
for a in error:
for b in neg:
for c in partb:
temp.append(a+parta+b+c+end)
print(temp)
titles = temp
positive_ang = [10,31,50,70,94,110,130,150,178,187,2... |
#Daniel Ogunlana
#9/9/2014
#Task 6
#1.Write a program that will ask the user for three integers and display the total.
#2.Write a program that will ask the user for two integers and display the result of multiplying them together.
#3.Ask the user for the length, width and depth of a rectangular swimming pool. Calc... |
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from main.models import Skill
# Create your views here.
class IndexView(ListView):
template_name = 'skills/index.html'
context_object_name = 'skills'
model = Skill
def get_context_data(self, **kwargs):
c... |
#
# Bug:36536
# Title: The glite wms purge storage library should rely on LBProxy while logging CLEAR events
# Link: https://savannah.cern.ch/bugs/?36536
#
import logging
from libutils import Job_utils
from libutils.Exceptions import *
def run(utils):
bug='36536'
logging.info("Start regression test for... |
from pages.allsubjectspage.add_subject_page import AddSubjectPage
from pages.datasenderpage.data_sender_locator import SEND_IN_DATA_LINK, PROJECT_LIST, REGISTER_SUBJECT, SMARTPHONE_NAV
from pages.page import Page
from pages.smartphoneinstructionpage.smart_phone_instruction_page import SmartPhoneInstructionPage
from pag... |
# This monkey-patches scons' CacheDir to synchronize the cache
# to an s3 bucket.
#
# To enable it:
#
# - ensure python packages are installed: boto3, humanize
# - create a site_init.py file in site_scons containing 'import s3_cache'
# - setup ~/.aws/credentials with an access key
# - set the SCONS_CACHE_S3_BUCKET env... |
n = int(input())
nails = [int(x) for x in input().split()]
"""def count_crossed_lines(i, j, crossed=0):
# base case
if i == n-1:
return crossed
# recursive loop
if nails[i] > nails[j]:
crossed += 1
j += 1
if j == n:
i += 1
j = i + 1
return count_crossed_l... |
# -*- coding:UTF-8 -*_
import psutil
a = psutil.cpu_count() # CPU逻辑数量
b = psutil.cpu_count(logical=False) # CPU物理核心
# 2说明是双核超线程,4则是4核非超线程
print(a, b) |
import nltk
from nltk import word_tokenize
from nltk.corpus import stopwords, wordnet
from unidecode import unidecode
import string
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize, sent_tokenize
import spacy
nlp = spacy.load('fr_core_news_md')
french_stopwords = nltk.corpus.stopwords.wo... |
import re
from util import hook, http, pystuff, randout
import usertracking
import sys
import time
re_lineends = re.compile(r'[\r\n]*')
@hook.command
def python(inp, prefix="direct call", conn=None, nick=None):
".python <prog> -- executes python code <prog>"
i = 0
while i < 3:
if not output and... |
from typing import *
import os.path
# types
Clause = Sequence[int]
Solution = Sequence[int]
PartialSolution = Union[Solution, Literal[False]]
class KissatError(Exception):
...
def replacedict(s: str, d: Mapping[str, str]) -> str:
for pattern, replacement in d.items():
s = s.replace(pattern, replacement)
ret... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from pykafka import KafkaClient
from pykafka.common import OffsetType
from schemas.MonitorMessage import MonitorMessage
from schemas.DataField import DataField
from schemas.GEMHist import GEMHist
from schemas.GEMTrack import GEMTrack
import pylab as pl
import matplotlib.pyplot... |
import numpy as np
import time
import matplotlib.pyplot as plt
from matplotlib import cm
from multires2DRendering import multires2DRendering
def computeCorrectRefl(material,idd,blockWidth):
filename = 'input/'+ material +'/' + material + repr(idd+1) + '.png'
output = np.loadtxt('output/'+ material ... |
import math
from copy import deepcopy
import random
import pyximport
pyximport.install()
import dfunc
import sys
#stone & stage reading
#data = two stone
#onedata = one stone
#twostage = two stage
#onestage = one stage
param = sys.argv
data = dfunc.getdata(param[1]+'.txt') #stage & stone two data
stage = data[0]... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
# import the classes in the files of the data folder here.
from .base import TransformerXHDataset
from .hotpotqa import HotpotDataset, batcher_hotpot
from .fever import FEVERDataset,batcher_fever
from .utils import load_data |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
DIALECT = 'mysql'
DRIVER = 'pymysql'
USERNAME = 'root'
PASSWORD = 'password'
HOST = '192.168.99.100'
PORT = '3306'
DATABASE = 'react_template'
SQLALCHEMY_DATABASE_URI = '{}+{}://{}:{}@{}:{}/{}?charset=utf8'.format(
DIALECT, DRI... |
import func_bsearch
def contains(a, q):
p = func_bsearch.bsearch(a, q)
return p < len(a) and a[p] == q
def main():
print contains([2,3,6,6,7,8], 1) # False
print contains([2,3,6,6,7,8], 2) # True
print contains([2,3,6,6,7,8], 6) # True
print contains([2,3,6,6,7,8], 8) # True
print contains([... |
#!/usr/bin/env python
# coding: utf-8
from __future__ import (absolute_import, division,
print_function, unicode_literals)
try:
# noinspection PyUnresolvedReferences, PyCompatibility
from builtins import * # noqa
except ImportError:
pass
import os
import pandas as pd
from climate... |
from util import *
from ADI_SOLVER import *
import ipywidgets
def start():
layout = ipywidgets.Layout(width= '100%',height='20px')
bc1 = ipywidgets.IntSlider(min=0,max=1000,value = 681,step=1,description='Top BC' ,layout=layout,continuous_update=False,style = {'description_width': 'initial'})
bc2 = ipywid... |
from config.base_config import BaseConfig
class DatabaseConfig(BaseConfig):
def __init__(self):
super().__init__()
self.file = 'database.ini'
|
import os
import datetime
from etl.scripts import RetrieveProcedureComplicationsDPCA
from barbell2light.utils import Logger, current_time_secs, elapsed_secs, duration
class ScriptRunner:
def __init__(self, output_dir, log_dir):
self.output_dir = self.update_output_dir(output_dir)
self.logger = s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: fm_footer.py
Author: tdoly
"""
class Footer(object):
""" Footer class that outputs text to a curses screen """
msg = None
curses_screen = None
def __init__(self):
self.width = None
def set_screen(self, curses_screen):
self... |
from selenium import webdriver
from time import sleep
import iamarobot
driver = webdriver.Firefox()
driver.get('https://google.com/recaptcha/api2/demo')
sleep(4)
d = iamarobot.Docaptcha(driver, '//iframe[@title="reCAPTCHA"]')
d.solve() |
import os
import sys
sys.path.append( os.path.abspath(os.path.join(os.path.dirname(__file__), '..','dots_and_squares')))
from dots_and_squares_game import dots_and_squares_game
import unittest
import pygame
class test_dots_and_squares_game(unittest.TestCase):
"""Tests for functions in dots_and_squares_game. The u... |
"""
steps
1. search & locates modules src file
2. execute
3. object for the imported module
"""
from glob import glob
from psmakearchive import make_archive, make_tarball
file_list = glob('*.py')
make_archive('source.zip', *file_list) # content of the list as arguments
make_tarball('source.tar', *file_list)
|
#-*- coding: utf-8 -*-
import copy
from django.contrib import admin
from app_data.forms import multiform_factory
from app_data.admin import AppDataModelAdmin
from .models import MyModel, Tag
MyModelMultiForm = multiform_factory(MyModel)
class MyModelAdmin(AppDataModelAdmin):
multiform = MyModelMultiForm
@p... |
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_m1(x):
return -np.log((1 / x) - 1)
class data_preparing:
... |
import sys
class Person ():
def __init__(self, name, surname, age):
self.name=name
self.surname=surname
self.age=age
class Employee(Person):
def __init__(self, name, surname, age, position, specialization, salary):
super().__init__(name, surname, age)
self.position = ... |
import logging
import elks
logging.getLogger().setLevel(logging.INFO)
def main():
username = '<Your 46elks API username>'
password = '<Your 46elks API password>'
elk = elks.API(username, password)
number = elk.allocateNumber()
logging.info('Allocated number: %s' % number))
number.modify(sms_... |
import csv
from pygal.maps.world import World
from pygal.style import RotateStyle as RS, LightColorizedStyle as LCS
from country_codes import get_country_code
# Load CO2 emissions data.
filename = 'co-emissions-per-capita.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
... |
from math import ceil
import numpy as np
import fenics as pde
import matplotlib.pyplot as plt
import mshr
from tqdm import trange
# Aliases for FEniCS names we will use
dx = pde.dx
ds = pde.ds
sym = pde.sym
grad = pde.grad
nabla_grad = pde.nabla_grad
div = pde.div
dot = pde.dot
inner = pde.inner
def epsilon(u): re... |
from django.contrib.auth.models import User,Group
from django.test import TestCase
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase,APIClient
from .factory import populate_test_db_docs,populate_test_db_users
from .models import Document
class Tes... |
import serial
from . import make_command as cmd
from .response import Response
tf = cmd.TelegramFactory()
IDN = cmd.IDN.from_string
class IndraDrive:
def __init__(self):
self.serial = None
self.known_parameter_sizes = {}
@classmethod
def with_serial(cls, *args, **kwargs):
if 'ba... |
import argparse
import os
import matplotlib.pyplot as plt
import numpy as np
import wandb
from torchvision import transforms
from MODELS.model_resnet import *
from custom_dataset import DatasetISIC2018
from gradcam import GradCAM, GradCAMpp
from gradcam.utils import visualize_cam
parser = argparse.ArgumentParser(des... |
import time
import ApplicationPerformance.applicationperformance.launchTime as launchTime
from appium import webdriver
from selenium.common.exceptions import NoSuchElementException
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '4.4.2'
desired_caps['deviceName'] = 'emulator... |
from typing import List
from ex3.src import GraphInterface
from ex3.src.DiGraph import DiGraph
from ex3.src.GraphAlgoInterface import GraphAlgoInterface
import json
import heapq
import queue
import math
import numpy as np
import matplotlib.pyplot as plt
import random
class GraphAlgo(GraphAlgoInterface):
def __... |
from flask import Blueprint, session, render_template, flash, request, redirect, url_for
from werkzeug.exceptions import abort
from my_app.auth.model.user import User, LoginForm, RegisterForm
from my_app import db
from flask_login import login_user, logout_user, current_user, login_required
from my_app import login_ma... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import, unicode_literals
#TODO
##from infrastructure.sumoapi import (api_get_position, api_get_destination, api_get_speed, api_set_color, api_get_road, api_change_destination, api_get_origin)
##from .api import (api_get_position, api_get... |
from django.shortcuts import redirect
from django.http.response import HttpResponse
def index(request):
return redirect("/register")
def register(request):
return HttpResponse("marcador de posición para que los usuarios creen un nuevo registro de usuario")
def login(request):
return HttpResponse("marcad... |
"""
Attempting to support yTube Music in Home Assistant
"""
import asyncio
import logging
import time
import random
import pickle
import os.path
import random
import datetime
from urllib.request import urlopen
from urllib.parse import unquote
from .const import *
import voluptuous as vol
from homeassistant.helpers im... |
def pow2(n):
return n ** 2
pow2_new = lambda n: n**2
mysum = lambda a, b: a + b
val = pow2(10)
val_new = pow2_new(10)
sum_val = mysum(10, 20)
print(val)
print(val_new)
print(sum_val)
print(type(pow2))
print(type(pow2_new)) |
from base import *
from user import User
from city import City
class Place(BaseModel):
owner = peewee.ForeignKeyField(User, related_name="places")
city = peewee.ForeignKeyField(City, related_name="places")
name = peewee.CharField(128, null=False)
description = peewee.TextField()
number_rooms = peew... |
from flask import Flask, request, render_template, jsonify
import os
from Model import multiple_prediction_model
app = Flask(__name__)
# not actually a secret since no need for authentication
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
# standard route
@app.route('/')
def loadViz():
return render_template('/i... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import datetime
from testing_utils import testing
from model.suspected_cl_confidence import ConfidenceInformation
from model.suspected_cl_confidence import... |
# -*- coding: utf-8 -*-
'''
transforms使用
'''
#%%
import os
import numpy as np
import torch
import random
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
from my_dataset import RMBDataset
from PIL import Image
from matplotlib import pyplot as plt
os.chdir('E:\pytorch_learning')
de... |
import sqlite3 as sq
DB_NAME = "ipl.db"
try:
conn = sq.connect(DB_NAME)
cur = conn.cursor()
DELETE = "DROP TABLE IF EXISTS POINTS_TABLE;"
cur.execute(DELETE)
conn.commit()
CREATE = """
CREATE TABLE IF NOT EXISTS POINTS_TABLE
(
team_id INTEGER PRIMARY KEY,
... |
#APPENDING OPERATION ON LISTS
#appendig list as a element
print("\nAppending using list as a element:\n")
list_A = ['DIGITAL', 'SIGNAL']
print ("list_A before appendig",list_A )
list_A.append('PROCESSING')
print ("list_A after appendig",list_A )
#appending using two lists
print("\nAppending using two lists\n")
list1 ... |
# -*- coding: utf-8 -*-
import time, sys, cPickle, os, socket
from pylearn2.utils import serial
from itertools import izip
from pylearn2.utils import safe_zip
from collections import OrderedDict
from pylearn2.utils import safe_union
import numpy as np
import scipy.sparse as spp
import theano.sparse as S
from the... |
import sys
@task
def source():
"""Generates source (development) version of test runner"""
core.test_source()
@task
def build():
"""Generates build (deployment) version of test runner"""
core.test_build()
@task
def clean():
"""Cleans up project environment"""
session.clean()
Rep... |
#! /usr/bin/env python
import rospy
import numpy as np
import tf
import tf2_ros
import sys
import math
from geometry_msgs.msg import Pose, TransformStamped, PoseStamped, Vector3, Quaternion, Transform
from visualization_msgs.msg import Marker, MarkerArray
from nav_msgs.msg import Odometry
from std_msgs.msg import Heade... |
import argparse
import pickle
import spacy
from dataset import process_20newsgroup_dataset
def main(args):
nlp = spacy.load("en")
train_dataset, test_dataset = process_20newsgroup_dataset(nlp)
print("-- Saving processed dataset to: {}".format(args.dataset_file))
with open(args.dataset_file, mode="w... |
import numpy as np
import lttb
def test_downsampling():
csv = 'tests/timeseries.csv'
data = np.genfromtxt(csv, delimiter=',', names=True)
xs = data['X']
ys = data['Y']
data = np.array([xs, ys]).T
out = lttb.downsample(data, 100)
assert out.shape == (100, 2)
|
## vamos agora, por fim, vermos como funciona o while.
## While significa 'enquanto', e trabalha com valores
## booleanos, assim como o if. Vejamos sua estrutura:
a = 5
while (a > 0):
print(a)
a -= 1
## --------- EXECUTE O CÓDIGO --------------
## nossa estrutura é a seguinte: ENQUANTO ('a' for maior
##... |
from sqlalchemy import Column, Integer, String, Boolean
from api.models import Base
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(String(255), unique=True)
first_name = Column(String(255))
last_name = Column(String(255))
password = Column(S... |
# -*- coding: utf-8 -*-
import pygame
import json
from classes import *
from loaders import *
TILE_W, TILE_H = 40, 26
class Game(object):
def __init__(self, screen, movekeys):
self.movekeys = movekeys
self.screen = screen
self.width, self.height = screen.get_width(), screen.get_height()
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 20 11:28:15 2015
@author: Kapil Chandra
"""
import xlrd
from selenium.webdriver import Firefox
import time
from selenium import webdriver
#opening the xl sheet which is having all the numbers
workbook= xlrd.open_workbook('sms_sender.xlsx')
#going into the par... |
#!/usr/bin/python
import sys, os
sys.path.append ("../scripts")
import vlaunch
import ihex2mem
def run_sim(ihx_name):
# open the test ihx file and populate ROM
memim = ihex2mem.mem_image()
memim.load_ihex (ihx_name)
print "Loaded",memim.bcount,"bytes"
for addr in range(memim.min, 32768):
... |
# Generated by Django 2.2.3 on 2019-07-03 13:44
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Region',
fields=[
... |
"""
Reads pickled results from multivaraite TE or MI outputs and creates
a file with the adjaceny matrix of the information bits. This is a light
modification of the original pickle reader file script.
Created: July 25, 2019
Updated: November 12, 2019
Seth Campbell
"""
#Import classes
from idtxl.... |
"""
recursive result
TC: O(n) --->n in no of nodes in tree
SC: O(h) --->h is height of tree
iterative using queue level order traversal --> if perfect bin tree is there it will take more space
if it is skewed tree then it will take O(1) space
TC: O(n) --->n in no of nodes in tree
SC: O(w) --->w is width of tree
"""
i... |
# -*- coding: utf-8 -*-
#
# This file is part of PyBuilder
#
# Copyright 2011-2020 PyBuilder Team
#
# 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/l... |
from bot import bot
import config
import send_movie
from models import Movie, Video
from telebot import types
import upload_video
def register_video_info(message, video_id: int, type: str, old_message_id: int, tapped_message_id: int):
if message.text == '/cancel':
return
video = Video.select().where(V... |
# Put '' [empty string] if you dont want any cell type
from tqdm import tqdm
from functions import AVAILABLE_BEHAVIORS
import logging
class CellTransConfig:
"""
Define a class with sample_id, cell_type, event_time and filter_pattern (for behavioral_transitions)
"""
def __init__(
self,
... |
from django.db import models
class Trainer(models.Model):
first_name=models.CharField(max_length = 50)
second_name=models.CharField(max_length = 50)
gender=models.CharField(max_length=20)
id_number=models.CharField(max_length=50, null=True)
email=models.EmailField(max_length=70)
phone_number=models.CharField(max... |
#!/usr/bin/env python
fake = 'fL492_r_h4rd3r_th4n_th1s'
flag = ''
target = [58, 49, 82, 48, 52, 54, 82, 48, 51, 92, 58, 81, 115, 48, 53, 69, 92, 49, 90, 52]
for i in range(len(target)):
flag += chr(((target[i] ^ 0x32) - 1) ^ 0x32)
print flag
|
# --- --- IMPORTS --- ---
import ConfigParser
import json
import markdown
import logging
from logging.handlers import RotatingFileHandler
from math import ceil
from urllib import urlencode
from os import listdir
from os.path import basename
from flask import Flask, render_template, flash, redirect, url_for, request
#... |
#!/usr/bin/env python
from fastcgi import *
from time import sleep
@fastcgi
def hello():
name = sys.stdin.read()
sys.stdout.write(f'Content-type: text/html\n\nHello {name}\n')
sys.stdout.write(f'{os.environ}\n')
|
import os, sys, logging, argparse, pdb, imp, time
import unittest as test
from copy import deepcopy
from nistoar.testing import *
from nistoar.pdr import cli
from nistoar.pdr.publish.cmd import prepupd
from nistoar.pdr.exceptions import PDRException, ConfigurationException
import nistoar.pdr.config as cfgmod
testdir ... |
# Once for All: Train One Network and Specialize it for Efficient Deployment
# Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han
# International Conference on Learning Representations (ICLR), 2020.
from .imagenet import *
|
# -*- coding:utf-8 -*-
i = 0
residual = 500000.0
interest_tuple = (0.01, 0.02, 0.03, 0.035)
repay = 30000.0
while residual > 0:
i = i + 1
print("第",i,"年还是要还钱")
if i <= 4:
interest = interest_tuple[i - 1]
else:
interest = 0.05
residual = residual*(1 + interest) - repay
print("... |
__all__ = ()
import os
from json import dumps as to_json, load as from_json_file, loads as from_json
from math import ceil, floor
from zlib import compress, decompress
from hata import BUILTIN_EMOJIS, Color, DiscordException, ERROR_CODES, Embed, Emoji, KOKORO
from hata.ext.slash import Button, ButtonStyle, Row, Timeo... |
from alltrain.Train import *
import torch
from torch.utils.tensorboard import SummaryWriter
import time
# import alltrain.bratsUtils as bratsUtils
import alltrain.atlasUtils as atlasUtils
from multiatlasDataset import *
from tqdm import tqdm
from torch.utils.data import DataLoader
import json
import os
class MATrai... |
from flask_assets import Bundle
bundles = {
'js': Bundle(
'js/loader.js',
'js/cache_timer.js',
'js/index.js',
'js/info.js',
'js/profile.js',
output='gen/main.js'),
'css': Bundle(
'css/loader.css',
'css/base.css',
'css/index.css',
... |
import argparse
import os
from collections import OrderedDict
import random
import matplotlib.patches as patches
import matplotlib.pyplot as plt
from PIL import Image
import pdb
def get_video_list(dir):
new_list = [name for name in os.listdir(dir) if len(name)>2]
new_list = make_video_name(new_list)
return... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.24 on 2020-01-26 22:17
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('genres', '0003_auto_20200126_2216'),
]
operations = [
migrations.AlterFiel... |
import logging
import os
import sys
from pathlib import Path
from typing import cast
import click
import click_pathlib
from rich.console import Console
from rich.emoji import Emoji
from rich.logging import RichHandler
from rich.progress import (
BarColumn,
DownloadColumn,
Progress,
TextColumn,
Time... |
import pkg_resources
try:
pkg_resources.get_distribution('RelStorage')
except pkg_resources.DistributionNotFound:
HAS_RELSTORAGE = False
else:
HAS_RELSTORAGE = True
from relstorage.storage import RelStorage
from relstorage.adapters.stats import OracleStats
def get_object_count(db):
"""Returns... |
from utils import ModuleHandler
class BaseModuleHandler(ModuleHandler):
def __init__(self, settings):
super(BaseModuleHandler,self).__init__(settings)
def handle_command(self, command):
if command[0] == 'settings':
self.__print_settings()
return True
elif co... |
"""
Tic Tac Toe Player
"""
from copy import deepcopy
from math import inf
X = "X"
O = "O"
EMPTY = None
# ---------------HELPER---------------
def maxMinValue(board):
if terminal(board):
return utility(board)
value = -inf
for action in actions(board):
value = max(value, minimum(result(bo... |
import googleapi
results = googleapi.standard_search.search("albert einstein")
print("%s - %s" % (len(results), results[0].description))
|
__all__ = [
'Section', 'StringField', 'IntegerField', 'BooleanField', 'FloatField', 'IniConnector', 'ListField'
]
from .ConfigORM import Section
from .Fields import StringField
from .Fields import IntegerField
from .Fields import BooleanField
from .Fields import FloatField
from .Fields import ListField
from .Conne... |
#рисує коло по точках
import math
from tkinter import *
root = Tk()
root.title("PythonicWay Pong")
# встановлюєм канву
c = Canvas(root, width=400, height=400)
c.pack()
# радіус кола
r = 120
# створюєм пустий лист для запису в нього точок, по яких побудується нижня частина кола
circl1 = []
# створюєм пустий лист для ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import redis
def main():
r = redis.Redis(host='127.0.0.1', port=6379, db=0)
# 提取1到100页的url
r.lpush("taobao", 'jianjian')
if __name__ == '__main__':
main()
|
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
def find_local_min_max(series, x):
state = {
'pmin': None,
'pmin_ind': None,
'pmax': None,
'pmax_ind': None,
'lmin': None,
'lmax': None
}
state['pmin_ind'] = series.index.tolist... |
"""
Utility methods for development
"""
import json
def dict_to_file(dict_input, filename):
with open(filename, 'w') as f:
json.dump(dict_input, f, indent=4, sort_keys=True)
def file_to_dict(filename):
with open(filename, 'r') as f:
return json.load(f)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.