content stringlengths 5 1.05M |
|---|
# For compatibilty
from ignite.utils import convert_tensor, apply_to_tensor, apply_to_type, to_onehot
def _to_hours_mins_secs(time_taken):
"""Convert seconds to hours, mins, and seconds."""
mins, secs = divmod(time_taken, 60)
hours, mins = divmod(mins, 60)
return hours, mins, secs
|
class ScoreCard:
def __init__(self, score_text: str):
score_texts = score_text.split('|')
self.normal_turns = [score_texts[i] for i in range(10)]
if len(score_texts) == 12:
self.additional_turns = [score_texts[11]]
self.all_turns = self.normal_turns + self.additional_tur... |
import os
import cgi
import requests
import shutil
def download_file(url, path, file_name=None):
"""Download file from url to directory
URL is expected to have a Content-Disposition header telling us what
filename to use.
Returns filename of downloaded file.
"""
res = requests.get(url, stre... |
from lib.getItensFromEntrance import getItens
from lib.controllerImage import controllerImg
import os
import sys
arguments = sys.argv
pathDirect = os.getcwd()
resizeImage = controllerImg(pathDirect, arguments)
resizeImage.resizeImage()
|
from django.test import TestCase
from .models import Location, Category, Photographer, Image
# Create your tests here.
class LocationTestClass(TestCase):
def setUp(self):
self.loc = Location(location_name = 'Mombasa, Kenya')
# Testing instance
def test_instance(self):
self.assertTrue(isin... |
#!/usr/bin/env python
import sys
field = int(sys.argv[1])
for i in sys.stdin:
try:
print(i.split()[field - 1], end=" ")
print()
except:
pass
|
"""maillinter uses setuptools based setup script.
For the easiest installation type the command:
python3 setup.py install
In case you do not have root privileges use the following command instead:
python3 setup.py install --user
This installs the library and automatically handle the dependencies.
"""
impor... |
import logging
import re
import os
import sys
from flexget import plugin
from flexget import validator
log = logging.getLogger('rtorrent_magnet')
pat = re.compile('xt=urn:btih:([^&/]+)')
class PluginRtorrentMagnet(object):
"""
Process Magnet URI's into rtorrent compatible torrent files
Magnet URI's wil... |
from collections import OrderedDict
from os.path import dirname, join
from library.commands.nvidia import NvidiaSmiCommand
from library.commands.sensors import SensorsCommand
ROOT_DIR = dirname(__file__)
DATA_FOLDER = join(ROOT_DIR, "data")
COMMANDS = [
SensorsCommand,
NvidiaSmiCommand
]
# How far to look ... |
n1 = float(input("Digite uma nota: "))
n2 = float(input("Digite a outra nota: "))
media = (n1 + n2)/2
print("A média das notas {:.1f} e {:.1f} é {:.1f}".format(n1, n2, media)) |
'''def do_twice(f):
f()
f()
def print_spam():
print('spam')
do_twice(print_spam)
'''
s = input('input string: ')
def do_twice(function, a):
function(a)
function(a)
def print_twice(a):
print(a)
print(a)
def do_four(function, a):
do_twice(function, a)
do_twice(function, a)
do_twice(p... |
"""Module with implementation of utility classess and functions."""
from WeOptPy.util.utility import (
full_array,
objects2array,
limit_repair,
limit_invers_repair,
wang_repair,
rand_repair,
reflect_repair,
explore_package_for_classes
)
from WeOptPy.util.argparser import (
make_arg_parser,
get_args,
get_dic... |
from typing import Optional
from ray.rllib.utils.annotations import override
from ray.rllib.utils.framework import try_import_tf, try_import_torch
from ray.rllib.utils.schedules.schedule import Schedule
from ray.rllib.utils.typing import TensorType
tf1, tf, tfv = try_import_tf()
torch, _ = try_import_torch()
class ... |
from carla_utils import carla
import os
from os.path import join
import random
import signal
import subprocess
import time
import psutil, pynvml
from carla_utils.basic import YamlConfig, Data
from carla_utils.system import is_used
class Core(object):
'''
Inspired by https://github.com/carla-simulator/... |
"""
File Name : apiview.py
Description :
Author : mxm
Created on : 2020/8/16
"""
import tornado.web
import tornado.ioloop
import tornado.httpserver
import tornado.options
from abc import ABC
from tornado.options import options, define
from tornado.web import RequestHandler
clas... |
from rest_framework import serializers
from .models import UserInfo
class json(serializers.ModelSerializer):
class Meta:
model = UserInfo
fields = ('UserName', 'UserBookLogo') |
from django.contrib.auth.models import AbstractUser
from django.core import mail
from django.db.models.signals import post_save
from django.dispatch import receiver
class User(AbstractUser):
pass
@receiver(post_save, sender=User)
def send_success_email(sender, **kwargs):
"""Sends a welcome email after user ... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###################################################################
# Author: Mu yanru
# Date : 2019.2
# Email : muyanru345@163.com
###################################################################
from dayu_widgets.label import MLabel
from dayu_widgets.tool_button impo... |
input = "hello my name is sparta"
def find_max_occurred_alphabet(string):
alphabet_occurrence_array = [0] * 26
for char in string:
if not char.isalpha():
continue
arr_index = ord(char) - ord("a")
alphabet_occurrence_array[arr_index] += 1
result = find_max_occurred_alphab... |
import itertools
import numpy as np
from sklearn.preprocessing import scale
import matplotlib.pyplot as plt
from matplotlib import collections as mc
# TODO: document it and wrap it as pip package, make ipynb example
def get_cmap(n, name='hsv'):
"""
Returns a function that maps each index in 0, 1, ..., n-1 t... |
import numpy as np
import pandas as pd
import time
import os
import sys
from copy import copy
from fastdtw import fastdtw
from scipy import interpolate
from scipy.stats import levy, zscore, mode
from sklearn.metrics import silhouette_score
from sklearn.metrics.pairwise import *
from scipy.spatial.distance import *
from... |
import cv2
import math
import time
import numpy as np
mmRatio = 0.1479406021
scale = 2
frameWidth = 2304
frameHeight = 1536
frameCroopY = [650,950]
windowsName = 'Window Name'
def playvideo():
vid = cv2.VideoCapture(0)
vid.set(cv2.CAP_PROP_FRAME_WIDTH, frameWidth)
vid.set(cv2.CAP_PROP_FRAME_HEIGHT, fram... |
import os
from setuptools import setup, find_packages
import lendingblock
def read(name):
filename = os.path.join(os.path.dirname(__file__), name)
with open(filename) as fp:
return fp.read()
meta = dict(
version=lendingblock.__version__,
description=lendingblock.__doc__,
name='lb-py',
... |
# pylint: disable=import-error
from importlib import import_module
from flask_restplus import Api
# pylint: disable=no-name-in-module
from utils.configmanager import ConfigManager
from app import resources
def make_api(api_config):
api = Api(
prefix=api_config["prefix"],
title=api_config["title"]... |
import os
import sys
import random
import time
import traceback
import torch
import torch.optim as optim
from configs import g_conf, set_type_of_process, merge_with_yaml
from network import CoILModel, Loss, adjust_learning_rate_auto
from input import CoILDataset, Augmenter, select_balancing_strategy
from logger import... |
import json
import urllib.request
from urllib.error import URLError
from django.shortcuts import render, get_object_or_404, redirect
from django.core.cache import cache
from django.http import HttpResponse, Http404
from django.template import Context, Template, RequestContext
from django.db.models import Q, Prefetch, C... |
"""
After implementation of DIP (Dependency Inversion Principle).
The dependency (Database or CSV) is now injected in the Products class via a repository of type Database or CSV.
A factory is used to create a Database or CSV repository.
"""
class ProductRepository:
@staticmethod
def select_products():
... |
##
import os
from setuptools import setup, find_namespace_packages
from pkg_resources import get_distribution, DistributionNotFound
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup (
name = "namespace.HeardBox",
use_scm_version = True,
setup_requ... |
"""Regression."""
from ._linear_regression import LinearRegression
from ._neighbors_regression import (
KNeighborsRegressor,
RadiusNeighborsRegressor,
)
|
#!/usr/bin/python
#-*- coding: utf-8 -*-
# >.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.
# Licensed under the Apache License, Version 2.0 (the "License")
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# --- File Name: parser.py
# --- Creation Date: 24-02-2020
# --- Last Modified: Tue 25 Feb... |
# Generated by Django 3.2.6 on 2021-08-27 19:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('university', '0006_representative'),
]
operations = [
migrations.AddField(
model_name='course',
name='slug_unimi',
... |
from utils import hashable_boundaries, predicted_len
from objects import Database
from collections import defaultdict
from math import ceil
import gen_spectra
def modified_sort_masses_in_sorted_keys_b(db_dict_b,mz,kmer_list_b):
kmers = db_dict_b[mz]
kmer_list_b += kmers
def modified_sort_masses_in_sorted_key... |
"""This module contains the support resources for the two_party_negotiation protocol."""
|
"""
Manages updateing info-channels (Currently only `log` channel)
"""
from typing import Union
import discord
from discord.ext import commands
class InfoChannels(commands.Cog):
def __init__(self, bot: commands.Bot):
print('Loading InfoChannels module...', end='')
self.bot = bot
self.gui... |
print("""
042) Refaça o DESAFIO 035 dois triângulos, acrescentando o recurso de mostrar que
tipo de triângulo será formado:
- Equilátero: todos os lados iguais
- Isósceles: dois lados iguais
- Escaleno: todos os lados diferentes
""")
print("""
Este programa recebe o valor de três retas e verifica se, com elas,
é possí... |
import unittest
import hcl2
from checkov.common.models.enums import CheckResult
from checkov.terraform.checks.resource.aws.AppLoadBalancerTLS12 import check
class TestAppLoadBalancerTLS12(unittest.TestCase):
def test_failure(self):
resource_conf = {'load_balancer_arn': ['${aws_lb.examplea.arn}'], 'port... |
class Solution:
def longestValidParenthesesSlow(self, s: str) -> int:
stack, ans = [-1], 0
for i in range(len(s)):
if s[i] == ")" and len(stack) > 1 and s[stack[-1]] == "(":
stack.pop()
ans = max(ans, i - stack[-1])
else:
stack.... |
from flask import Flask, redirect
from flask_fileupload import FlaskFileUpload
from flask_login import LoginManager, UserMixin, login_user, logout_user
app = Flask(__name__)
app.config.from_object("config")
lm = LoginManager(app)
fue = FlaskFileUpload(app)
class User(UserMixin):
def __init__(self, user_id):
... |
"""
This module implements graph/sparse matrix partitioning inspired by Gluon.
The goal of this module is to allow simple algorithms to be written against the current sequential implementation,
and eventually scale (without changes) to parallel or even distributed partitioning.
As such, many functions guarantee much le... |
## www.pubnub.com - PubNub Real-time push service in the cloud.
# coding=utf8
## PubNub Real-time Push APIs and Notifications Framework
## Copyright (c) 2010 Stephen Blum
## http://www.pubnub.com/
## -----------------------------------
## PubNub 3.1 Real-time Push Cloud API
## -----------------------------------
imp... |
# Configuration file for the Sphinx documentation builder.
#
# For a full list of configuration options, see the documentation:
# http://www.sphinx-doc.org/en/master/usage/configuration.html
# Project information
# --------------------------------------------------
project = 'Apollo'
version = '0.2.0'
release = ''
... |
from bson.objectid import ObjectId
from pymongo import MongoClient
def readValue(value):
try:
return float(value)
except ValueError:
pass
try:
return int(value)
except ValueError:
pass
return value
def run(host=None, db=None, coll=None, key=None, prop=None, valu... |
from flask import Flask, render_template, Blueprint
from modules.BBCScraper import BBCScraper
from modules.MaanScraper import MaanHealthScraper
from modules.MOHScraper import CovidPalestine
from modules.MaanScraper import MaanNewsScraper
import time
import concurrent.futures
from modules.CovidScraper import BBCCovi... |
from fractions import Fraction
def answer(pegs):
arrLength = len(pegs)
if ((not pegs) or arrLength == 1):
return [-1,-1]
even = True if (arrLength % 2 == 0) else False
sum = (- pegs[0] + pegs[arrLength - 1]) if even else (- pegs[0] - pegs[arrLength -1])
# print sum
if (arrLength... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
# In[2]:
df=pd.read_csv('car_data.csv')
# In[3]:
df.head()
# In[5]:
df.shape
# In[6]:
print(df['Seller_Type'].unique())
# In[26]:
print(df['Transmission'].unique())
print(df['Owner'].unique())
print(df['Fuel_Type'].unique())
# I... |
from PIL import Image
import numpy as np
import time
def renk_degisimi():
h=pic.shape[0]
w=pic.shape[1]
newpic=np.zeros((h ,w ))
for i in range(h):
for j in range(w):
newpic[i][j]+=pic[i][j][0]*0.2989+pic[i][j][1]*0.5870+pic[i][j][2]*0.1140
matrix2=[]
for i in ran... |
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate,logout
from django.http import HttpResponse
from account.forms import AccountAuthenticationForm, RegistrationForm,AccountUpdateForm
from django.contrib import messages
from django.conf import settings
from django.contrib.... |
import numpy as np
import cv2
from skimage import segmentation
def runGrabCut(_image, boxes, indices):
imgs = []
image = _image.copy()
# ensure at least one detection exists
indices = len(boxes)
if indices > 0:
# loop over the indices we are keeping
for i in range(0,indices):
... |
"""
Copyright Tiyab KONLAMBIGUE
Licensed under the BSD 3-Clause "New" or "Revised" license;
you may not use this file except in compliance with the License.
You may obtain a copy of the License at : https://opensource.org/licenses/BSD-3-Clause
"""
from google.appengine.ext import ndb
class Job(ndb.Model):
creati... |
#!/usr/bin/env python
#
# 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
# "... |
# tuples are lists but immutable
# the syntax is ( parenthesis )
# list
l = [1,2,3]
l[0] = 5 # you can do this
print(type(l))
print(l)
# tuple
t = (1,2,3)
# t[0] = 5 # you can't do this
print(type(t))
print(t)
# tuples only have two methods, a lot less than lists
t = ('a', 'a', 'b', 'b', 'c', 'c')
print(f"the amount... |
import sys
import re
from functools import partial
def flush_print(st, *args, **kwargs):
end = kwargs.pop('end', '\n')
if args:
st = st % args
print(st, end=end)
if sys.stdout.isatty():
sys.stdout.flush()
def cprint(color_fn, st, *args):
if args:
st = st % args
print(... |
#!/usr/bin/env python
print("hi from Python 3")
|
"""Background job to perform a DNS lookup and insert into or update in the db.
Attributes:
DNS_SERVERS: A list of strs representing which DNS servers to use
DNS_BLOCKLIST: A str representing the blocklist to send a DNS lookup to
"""
import dns.resolver
from models import IPDetails, ResponseCode
# Spamhaus w... |
from scrapy import cmdline
if __name__ == '__main__':
# cmdline.execute('scrapy crawl xinFang'.split())
# cmdline.execute('scrapy crawl erShouFang'.split())
cmdline.execute('scrapy crawl zuFang'.split()) |
from .build_model import add_weights, build_model
|
#!/usr/bin/env python3
# _*_ coding:utf-8 _*_
import requests
from Config.config_requests import ua
requests.packages.urllib3.disable_warnings()
# 脚本信息
######################################################
NAME = 'pentaho_bruteforce'
AUTHOR = "Trans"
REMARK = 'pentaho密码爆破'
FOFA_RULE = 'app="pentaho"'
##############... |
# Copyright (c) 2019, Palo Alto Networks
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS... |
import pycountry
from matcher.server.main.elastic_utils import get_analyzers, get_char_filters, get_filters, get_index_name, get_mappings
from matcher.server.main.logger import get_logger
from matcher.server.main.my_elastic import MyElastic
SOURCE = 'country'
logger = get_logger(__name__)
def download_country_data... |
#--------------#
# Look Away! #
# By: Santo C. #
#--------------#
# Created October 26, 2006 (c) Santo C.
# Import the modules needed.
import random
from time import sleep
# Rules Document
Rules = """==========
Rules of the game:
------------------
Standing in front of you is your game host.
He will point in on... |
from django.db import models
# model to store incoming unpaid cheque details
class UnpaidCheque(models.Model):
raw_string = models.CharField(max_length=100)
voucher_code = models.CharField(max_length=3)
cheque_number = models.CharField(max_length=100)
reason_code = models.CharField(max_length=3)
ch... |
# Copyright 2019 DeepMind Technologies Limited.
#
# 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 agr... |
from django.contrib import admin
from activities.models import *
# Register your models here.
admin.site.register(Activity)
|
from django.contrib import admin
from .models import GoogleAuthUser
class GoogleAuthUserOption(admin.ModelAdmin):
"""GoogleAuthUser options"""
list_display = ('user', 'refresh_token')
search_fields = ('user',)
admin.site.register(GoogleAuthUser, GoogleAuthUserOption)
|
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""Translate a glob-style pattern to a regular expression.
"""
__version__ = "$Id$"
#end_pymotw_header
import fnmatch
pattern = 'fnmatch_*.py'
print 'Pattern :', pattern
print 'Regex :', fnmatch.translate(pattern) |
#!/usr/bin/env python
from icecube import icetray, dataclasses
def ConvertToLinearizedMCTree(frame):
if 'I3MCTree' in frame:
try:
tree = dataclasses.I3LinearizedMCTree(frame['I3MCTree'])
except:
icecube.icetray.logging.log_error('cannot convert to I3LinearizedMCTree')
... |
import json
from unittest import mock
from routemaster.db import Label, History
def test_root(client, version):
response = client.get('/')
assert response.json == {
'status': 'ok',
'state-machines': '/state-machines',
'version': version,
}
def test_root_error_state(client, versi... |
"""A `WorkItem` carries information about potential and completed work in the
Cosmic Ray system.
`WorkItem` is one of the central structures in CR. It can describe both work
to be done and work that has been done, and it indicates how test sessions have
completed.
"""
def make_record(name, fields=(), docstring=""):
... |
import sys, os
sys.path.append(os.pardir)
import numpy as np
from dataset.mnist import load_mnist
(x_train, t_train), (x_test, t_test) = \
load_mnist(normalize=True, one_hot_label=True)
train_size = x_train.shape[0]
batch_size = 10
batch_mask = np.random.choice(train_size, batch_size)
x_batch = x_train[batch_mask]
... |
import requests
from src.mercadolibre.OAuth import OAuth
from src.mercadolibre.enums import paths
from src.mercadolibre.enums.HttpMethods import HttpMethods
class Client:
def __init__(self, access_token=None, refresh_token=None):
self.access_token = access_token
self.refresh_token = refresh_token... |
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
# Create your views here.
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
username = for... |
""""""
__all__ = ['Pipeline']
# Standard library modules.
import asyncio
# Third party modules.
from loguru import logger
import tqdm
# Local modules.
# Globals and constants variables.
class Pipeline:
def __init__(self, tasks, stop_on_failure=False):
self.tasks = tuple(tasks)
self.stop_on_fa... |
class Solution:
def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:
|
#!/usr/bin/env python
#
import os, unittest
here = os.path.abspath(os.path.dirname(__file__))
class TestCase(unittest.TestCase):
def test(self):
"neutron_storage: no neutron saved"
workdir = 'NeutronStorage-zero-neutrons'
saved = os.path.abspath('.')
os.chdir(workdir)
... |
import re
#source: https://en.wiktionary.org/wiki/Category:English_abbreviations
ABBREVIATIONS_COMMON = [(re.compile(r'\b%s\.?(,?)\b' % x[0]), r'%s\1 ' % x[1]) for x in [
("abbr", "abbreviation"),
("abbrev", "abbreviation"),
#("abr", "abridged"),
("abstr", "abstract"),
("AI", "artificial intelligence"),
#... |
def insertionSort(arr):
for x in range(1, len(arr)):
item = arr[x]
i = x - 1
while i >= 0 and item < arr[i]:
arr[i + 1] = arr[i]
i -= 1
arr[i + 1] = item
return arr
print(insertionSort([1,9,8,4,6,7,3,12,5,18,2,22])) |
"""Originally Adapted from sphinxcontrib.details.directive
"""
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.util.docutils import SphinxDirective
from sphinx.transforms.post_transforms import SphinxPostTransform
from sphinx.util.nodes import NodeMatcher
def setup_dropdown(app):
... |
from robocorp_code.protocols import IRcc, IRccRobotMetadata
import py.path
def test_rcc_template_names(rcc: IRcc):
result = rcc.get_template_names()
assert result.success
assert result.result
assert "standard" in result.result
def test_rcc_cloud(rcc: IRcc, ci_credentials: str, tmpdir: py.path.local)... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
lookup = {1:[TreeNode(0)]}
def allPossibleFBT(self, N):
if N%2 == 0:
return None
if N n... |
import unittest
from preset import ActionTypes, Step, Preset
class TestStep(unittest.TestCase):
def test_01_constructor_and_properties(self):
temp_name = "name"
temp_value = "value"
temp_executable = lambda x: x
temp_action_type = ActionTypes.filter
temp_instance = Step(t... |
import logging
import os
import pickle
from typing import Generator, List, Tuple, Dict
from gensim.models import Word2Vec
from gensim.test.utils import common_texts
from wbtools.db.dbmanager import WBDBManager
from wbtools.lib.nlp.common import PaperSections
from wbtools.lib.nlp.text_preprocessing import preprocess
f... |
# game.py (c) 2017 D.J.Whale 22/01/2017
# Star-Wars 'Use the Force, Luke' game
# Using many moving parts provided by Martin O'Hanlon
#----- CONFIGURATION ----------------------------------------------------------
DEATHSTAR_CENTRE_POS = (100,100,10)
TARGET_POS = (100,100,10)
IN_RANGE = ((100,1... |
from toontown.coghq.SpecImports import *
GlobalEntities = {1000: {'type': 'levelMgr', 'name': 'LevelMgr', 'comment': '',
'parentEntId': 0,
'cogLevel': 0,
'farPlaneDistance': 1500,
'modelFilename': 'phase_11/models/lawbotHQ/LB_Zone7a',
'wantDoors': 1},
1001: {'t... |
__author__ = "The One & Only Javi"
__version__ = "1.0.0"
__start_date__ = "25th July 2020"
__end_date__ = "5th August 2020"
__maintainer__ = "me"
__email__ = "little_kh@hotmail.com"
__requirements__ = "SQL-Alchemy, MySQL," \
" Flask-SQLAlchemy, database.py, " \
"models.py, video_op... |
from .PZT import PZTMountedGrounded
|
from robofab.world import CurrentGlyph
from robofab.pens.filterPen import thresholdGlyph
d = 10
thresholdGlyph(CurrentGlyph(), d) |
# Two-sided notes
create_table_notes_ab = """
create table if not exists notes_ab
(
id text,
front text,
back text,
PRIMARY KEY(id)
)
"""
# One-sided notes
create_table_notes_qa = """
create table if not exists notes_qa
(
id text,
front text,
back text,
PRIMARY KEY(id)
)
"""
# Th... |
import pysftp
server_host = "demo.wftpserver.com"
username = "demo"
password = "demo"
with pysftp.Connection(server_host, username=username, password=password,port=2222)as sftp:
print(sftp.pwd)
# with sftp.cd('public'): # temporarily chdir to public
# sftp.put('/my/local/filename') # upl... |
# -*- coding: utf-8 -*-
"""
netvisor.responses.products
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2013-2016 by Fast Monkeys Oy.
:license: MIT, see LICENSE for more details.
"""
from ..schemas import GetProductSchema, ProductListSchema
from .base import Response
class ProductListResponse(Response):
... |
#
# Copyright 2015 BMC Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
#!/usr/bin/python3
from venus.stock_base import StockEventBase
class EventStockFlag(StockEventBase):
def flag_quit_stock(self, stock_code):
import datetime
import pandas as pd
from datetime import date
from dev_global.env import TIME_FMT
result = self.mysql.select_values(st... |
class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
if len(matchsticks) < 4:
return False
perimeter = sum(matchsticks)
if perimeter % 4 != 0:
return False
A = sorted(matchsticks)[::-1]
def dfs(selected: int, edges: List[int]) -> bool:
if selected == len(A):
... |
#!/usr/bin/env python
tuple= ["Juan", 5, 20.80, "HOLA"]
tuple2= [1,2,3]
lista3= [[1,2,3], [1, 3, 6], "HOLA"]
print tuple[0]
print tuple[1:2]
print tuple[2:]
print tuple *2
print tuple+tuple2
print lista3
|
# Copyright 2016-2017 Curtis Sand <curtissand@gmail.com>
#
# 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 l... |
from plenum.common.constants import ALIAS, SERVICES, VALIDATOR
from plenum.test.helper import sendReqsToNodesAndVerifySuffReplies
from plenum.test.node_catchup.helper import waitNodeDataEquality, \
checkNodeDataForInequality
from plenum.test.pool_transactions.helper import \
updateNodeData
from stp_core.common.... |
#!/usr/bin/python
"""
Commander.py - Python Backend for the WiFi Pineapple Commander module.
Version 2 Codename: Electric Boogaloo
Thanks to: sebkinne & tesla
Foxtrot (C) 2016 <foxtrotnull@gmail.com>
"""
import os
import ConfigParser
import sys
import socket
import time
import string
import select
import errno
cla... |
# Copyright (c) 2016-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
from freeswitch import... |
from scrapy.selector import Selector
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from scrapy.utils.url import urljoin_rfc
from sitegraph.items import SitegraphItem
class GraphspiderSpider(CrawlSpider):
name = 'graphspider'
allowed_domains = ['sastra.edu']
st... |
from ocean_spark.hooks import OceanSparkHook
from unittest.mock import MagicMock
def test_get_app(successful_get_app: None, get_connection_mock: None) -> None:
hook = OceanSparkHook()
app_dict = hook.get_app("test-app-name")
assert app_dict is not None
assert app_dict["displayName"] == "test app name"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.