content stringlengths 5 1.05M |
|---|
def selection_sort(seq):
for i in range(len(seq)):
low = i
for j in range (i + 1, len(seq)):
if seq[j] < seq[low]:
low = j
seq[i], seq[low] = seq[low], seq[i]
return seq |
from sqlalchemy import func
from datetime import datetime
def tz_str(mins):
prefix = "+" if mins >= 0 else "-"
return "%s%02d:%02d" % (prefix, abs(mins) / 60, abs(mins) % 60)
def tz_convert(datetime_col, timedelta_mins):
return func.convert_tz(
datetime_col, '+00:00', tz_str(timedelta_mins))
d... |
import argparse
import h5py
import imageio
import numpy as np
import skimage.measure
import time
import torch
import torch.nn.functional as torchfunc
import torch.backends.cudnn as cudnn
import torchvision.transforms as transforms
import _init_paths
from config import cfg
from config import update_config
import mode... |
from datetime import date
import unittest
from mintamazontagger import amazon
from mintamazontagger.amazon import Item, Order, Refund
from mintamazontagger.mockdata import item, order, refund, transaction
class HelperMethods(unittest.TestCase):
def test_parse_amazon_date(self):
self.assertEqual(
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2018-05-28 04:37
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('drp', '0005_occurrence_field_number_orig'),
]
operatio... |
from flask import Blueprint, flash, redirect, abort
from libs.admin_authentication import authenticate_admin_study_access
from pipeline.boto_helpers import get_aws_object_names
from pipeline.index import create_one_job, refresh_data_access_credentials
data_pipeline_api = Blueprint('data_pipeline_api', __name_... |
# -*- coding: utf-8 -*-
import csv, os, shutil, argparse, errno
import glob
def argparser_prepare():
class PrettyFormatter(argparse.ArgumentDefaultsHelpFormatter,
argparse.RawDescriptionHelpFormatter):
max_help_position = 35
parser = argparse.ArgumentParser(description='',
forma... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-13 18:45
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('symposion_speakers', '0007_auto_20170810_1651'),
('... |
import argparse
import json
import subprocess
import sys
from pathlib import Path
from typing import Dict, List, Optional, Union
from shlex import join
import lddwrap
from fzf.app import fzf
def find_lib_candidates(basename: str) -> List[str]:
result = subprocess.run(
["nix-locate", "--minimal", "--whole... |
import affine
import numpy
import pytest
import rasterio
@pytest.mark.xfail(reason="Likely upstream bug")
@pytest.mark.parametrize("nodata", [-1, -128])
def test_write_int8_mem(nodata):
profile = {
"driver": "GTiff",
"width": 2,
"height": 1,
"count": 1,
"dtype": "int8",
... |
#!/usr/bin/env python3
# You've seen the use of context managers with file I/O. You can write your own managers for classes. We're going to
# use a fictional database access example to show how it works. Typically, to use a database, you first need to open
# a connection to it, just like a file. When you're done, ... |
"""Module of Game class."""
import random
from typing import Dict, Optional, Tuple
from dataclass_factory import Factory
from tictactoe.board import Board
from tictactoe.bot_handler import OhMyBot
from tictactoe.keyboard import create_button, create_keyboard
from tictactoe.mark import Mark
from tictactoe.xobot import ... |
from flask_login import LoginManager
# Create the login manager to be shared throughout the application
login_manager = LoginManager()
|
#coding=utf-8
import sys
assert sys.version[0]!='2', 'Please Use Python3'
import urllib.request
import urllib.parse
import bs4
import time
import socket
import base64
import json
from http.cookiejar import Cookie
class Accepted(Exception):
pass
class Error(Exception):
def __init__(self,s):
self.s=s
... |
from scrapy.utils.httpobj import urlparse
from urllib.parse import urlparse, parse_qs
def get_id(url):
""" parse YouTube urls for id """
u_pars = urlparse(url)
quer_v = parse_qs(u_pars.query).get('v')
if quer_v:
return quer_v[0]
pth = u_pars.path.split('/')
if pth:
return pth[-1... |
number_list = [x for x in range(1, 21)]
squarenumbers = map(lambda x: x ** 2, number_list)
# squarenumbers is created as object via lambda x: x ** 2
# list(squarenumbers) will return a list of object created by lambda.
print(list(squarenumbers)) |
# -*- coding: utf-8 -*-
# Copyright (c) 2017 - for information on the respective copyright owner
# see the NOTICE file and/or the repository https://github.com/boschresearch/statestream
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.... |
from typing import Callable, List, Optional, Tuple, Union
import kornia.filters as fil
import numpy as np
import torch
try:
from kornia.filters import filter3D
except ImportError:
# polyfill kornia == 0.2.2 without filter3D
from .polyfill import filter3D
def convolve(im: torch.Tensor,
kern:... |
with open('./test.txt') as f:
try:
while True:
line = next(f) #next(f, None) to avoid exception
print( line, end='')
except StopIteration:
print()
pass
items = [1, 2, 3]
it = iter( items )
print( next( it,None ) )
print( next( it, None) )
print( next( it, None)... |
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import numpy as np
import json
import dash_design_kit as ddk
import plotly.graph_objects as go
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css',
'/assets/... |
#!/usr/bin/env python
# Publish an existing GitHub draft release. --id required.
# Optimized for CircleCI
import json
import os
import argparse
import httplib
from base64 import b64encode
def request(org, repo, id, data):
user_and_pass = b64encode(b"{0}:{1}".format(os.environ['GITHUB_USERNAME'], os.environ['GITHU... |
import tensorflow as tf
from ops import conv2d, lrelu, de_conv, log_sum_exp, instance_norm
from utils import save_images, get_image
from tensorflow.python.framework.ops import convert_to_tensor
import numpy as np
import time
class reImageGAN(object):
# build model
def __init__(self, batch_size, max_iters, mod... |
import unittest
import numpy as np
from services.path_finder import find_path
from services.models import OcrResult
def create_object_matrix_from_str_matrix(matrix):
obj_matrix = []
for row in matrix:
new_row = []
for element in row:
new_row.append(OcrResult(element, None))
... |
"""Examples that serve as documentation and tests."""
|
""" estimate time and express in proper format. """
def get_time(n: int, factor1: float = 1.0, factor2: float = 2.0) -> str:
""" estimate time and express in proper format. """
time1 = n * factor1
time2 = n * factor2
unit = "sec."
if time1 > 86400:
time1 = time1 / 86400.0
time2... |
#! /usr/bin/env python3.4
# Copyright 2017 Gavin Hurlbut
# vim:ts=4:sw=4:ai:et:si:sts=4
import logging
from random import shuffle
from plateball.database import Database
from plateball.database.schema import *
from plateball.singleton import Singleton
logger = logging.getLogger(__name__)
class PlateballDatabase(Data... |
# Copyright (c) 2017-2022 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""
This module contains configuration parameters used by the rest of the library.
"""
# We override types in this file LOTS because mypy does not understand what is happening
#... |
from datetime import datetime
import mailchimp
from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
from django.test import TestCase
from . import TEST_DATA, BODY, create_user, create_profile, create_message
from ..models import Profile
class ProfileTestCase(TestC... |
from functools import wraps
import errno
import os
import signal
import time
class TimeoutError(Exception):
pass
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
def decorator(func):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
def wrapper(... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021 by Phuc Phan
from transformers import pipeline
fill_mask = pipeline(
"fill-mask",
model="models/coberta-tiny/checkpoint-330000",
tokenizer="models/coberta-tiny/checkpoint-330000"
)
result = fill_mask("giá đt này là <mask>")
from pprint import pprint
pprint(re... |
#!/usr/bin/env python
#
# Parameters are passed using a configuration file.
# DVF+ PG database credentials are passed with env. var PATH_CRED_PG_DVFPLUS.
# dbug flag is hardcoded or passed with env. variable DBUG_EK.
#
# ** coding: utf-8 **
#
# std
import glob
import os
import multiprocessing
import json
import sys
fr... |
# Resource object code (Python 3)
# Created by: object code
# Created by: The Resource Compiler for Qt version 5.15.2
# WARNING! All changes made in this file will be lost!
from PySide2 import QtCore
qt_resource_data = b"\
\x00\x00\xd8\x01\
\x00\
_\xec\x86x\x9c\xec\xdd_l\x1c\xf7\x81\xe0y\x1ep\
\x87{\x19\xe... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class GetSitesResult:
... |
import numpy as np
import pandas
import io
def generate_lines(filePath, delimiters=[]):
with open(filePath) as f:
for line in f:
line = line.strip() # removes newline character from end
for d in delimiters:
line = line.replace(d, " ")
yield line
gen = gene... |
from PIL import Image
import os
import matplotlib.pyplot as plt
def description(filename):
#print "Processing ... ", fileName
if filename == '':
return
#only process the jpg file
# sufix = os.path.splitext(fileName)[1][1:]
# if sufix != 'jpg':
# return
#... |
from django.template import RequestContext, Template
def test_google_tag_manager(settings, rf):
settings.GTM_ID = "GTM_ID"
settings.GTM_AUTH = "GTM_AUTH"
settings.GTM_PREVIEW = "GTM_PREVIEW"
settings.GTM_COOKIES_WIN = "GTM_COOKIES_WIN"
request = rf.get("/")
t = Template("{% load gtm %}{% goo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: Shiyu Huang
@contact: huangsy13@gmail.com
@file: init_dirs.py
"""
import os, sys, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
|
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include(('runner.urls', 'runner'), namespace='runner')),
]
|
"""
Implementation of the method proposed in the paper:
'Adversarial Attacks on Graph Neural Networks via Meta Learning'
by Daniel Zügner, Stephan Günnemann
Published at ICLR 2019 in New Orleans, USA.
Copyright (C) 2019
Daniel Zügner
Technical University of Munich
"""
import tensorflow.compat.v1 as tf
tf.disable_v2_be... |
import random
roll_again='Yes'
while roll_again=='Yes' or roll_again=='Y':
print('===Rolling the Dice===')
print(random.randint(1,6))
roll_again=input('Roll the dice again [Yes/No]:')
roll_again=roll_again.title()
|
import unittest
from coldtype.geometry import *
from coldtype.sh import sh
class TestTest(unittest.TestCase):
def test_test(self):
r = Rect(0, 0, 100, 100)
self.assertEqual(sh(f"{r}TX=50"), [Rect([25.0,0,50,100])])
self.assertEqual(sh("↗|65|10|↑"), [["NE", 65, 10, "N"]])
if __name__ == "__... |
import bpy
bpy.ops.quietude.add_qcollection_modifier()
bpy.data.objects['Cylinder'].select_set(True)
bpy.data.objects['Cube.001'].select_set(True)
bpy.ops.quietude.add_qcollection_modifier()
bpy.ops.quietude.add_qcollection_modifier()
bpy.data.objects['Cube.001'].select_set(False)
bpy.ops.quietude.add_qcollectio... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import itertools
import time
from functools import lru_cache
import neo4j
import networkx as nx
import textwrap
import matplotlib
from helpers.time_tools import timeit_context
from language.heuristic.hardcore_annotated_expression import eL, eT, apply_fun_to_nested
from ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.validators import EmailValidator
from rest_framework import serializers
from apps.users.models import SEX_OPTIONS, RELATIONSHIP_STATUS
class ProfileUpdateSerializer(serializers.Serializer):
first_name = serializers.CharField(max_leng... |
import fakeredis.aioredis
import pytest
from fastapi.testclient import TestClient
from app.core.dependencies import get_redis
from app.main import create_app
async def override_get_redis():
return await fakeredis.aioredis.create_redis_pool()
@pytest.fixture
def client() -> TestClient:
app = create_app()
... |
from django.contrib.auth import authenticate, login
from django.contrib.auth import logout
from django.shortcuts import render, get_object_or_404, redirect
from .forms import *
from django.http import Http404
from .models import Movie, Myrating, MyList
from django.db.models import Q
from django.contrib import messages
... |
import numpy as np
import torch
import mmdet
from mmdet.apis import init_detector
from mmdet.datasets import build_dataset, build_dataloader
from tqdm import tqdm, trange#progress bar
import pickle
import sys
import argparse
import torch.multiprocessing
torch.multiprocessing.set_sharing_strategy('file_system')
# pars... |
import matplotlib.pyplot as plt
import pandas as pd
import sqlalchemy
import numpy as np
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter, AutoMinorLocator)
from datetime import datetime, timedelta
im... |
from zeit.cms.application import CONFIG_CACHE
import gocept.lxml.objectify
import logging
import urllib2
import zeit.calendar.interfaces
import zope.interface
log = logging.getLogger(__name__)
class RessortGroupManager(object):
zope.interface.implements(zeit.calendar.interfaces.IRessortGroupManager)
def _... |
"""
Entrypoints for `sbin/*` scripts that call into tasks.
"""
|
import pytest
from datetime import datetime
from conftest import CI_ENV
from app.bq_service import BigQueryService, split_into_batches, generate_timestamp
def test_generate_timestamp():
assert isinstance(generate_timestamp(), str)
assert isinstance(generate_timestamp(datetime.now()), str)
assert generate... |
width = input("Podaj dł. podstawy: ")
height = input("Podaj dł. wysokości: ")
triangle_area = (width * height) / 2
print("Pole trójkąta wynosi {triangle_area} cm^2")
print(f"Pole trójkąta wynosi {triangle_area} cm^2")
print("Pole trójkąta wynosi", triangle_area, "cm^2")
|
# The MIT License (MIT)
#
# Copyright (c) 2004-2017 Holger Krekel and others
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
... |
# TLock: OpenSSL lock support on thread-enabled systems.
# Copyright 2012 Ray Brown
#
# 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
#
# The... |
from .server_handler import ServerHandler
"""
Square Customer Group Object Handler between the Square Client and Squre Online server
"""
class Tournament:
def __init__(self, details):
# Dicitonary object to compensate for overall JSONObject usage
self.details = details
class TournamentHandler(Se... |
#!/usr/bin/env python3
import argparse
import os, atexit
import textwrap
import time
import tempfile
import threading, subprocess
import barrier, finishedSignal
import signal
import random
import time
from enum import Enum
from collections import defaultdict, OrderedDict
BARRIER_IP = 'localhost'
BARRIER_PORT = 10... |
# Demux loader: imports a demux module appropriate for this platform.
# Copyright 2012 Ray Brown
#
# 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/LICENS... |
from docassemble.base.util import validation_error, value, path_and_mimetype
import json
import requests
import xmltodict
def contains_spolek(x):
x = x.lower()
if "spolek" in x:
return True
elif "z. s." in x:
return True
elif "zapsaný spolek" in x:
return True
else:
validation_error('Název sp... |
from Frame.Extensions.NodeEditor.Nodes.P3DEventNode import Node as P3DEventNode
from Frame.Extensions.NodeEditor.Nodes.P3DCallScriptNode import Node as P3DCallScriptNode
from Frame.Extensions.NodeEditor.Nodes.P3DScriptLoaderNode import Node as P3DScriptLoaderNode
from Frame.Extensions.NodeEditor.Exporters.PythonExporte... |
"""
Modified from https://github.com/facebookresearch/deit/blob/main/resmlp_models.py
"""
import oneflow as flow
import oneflow.nn as nn
import oneflow.nn.init as init
from flowvision.layers import DropPath, PatchEmbed, Mlp
from .utils import load_state_dict_from_url
from .registry import ModelCreator
model_urls = {... |
#!/usr/bin/env python
from distutils.core import setup
import sys
for cmd in ('egg_info', 'develop'):
if cmd in sys.argv:
from setuptools import setup
setup_args = dict(
name = 'packbits',
version = '0.6',
author = 'Mikhail Korobov',
author_email = 'kmike84@gmail.com',
url = 'https://g... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import requests
import os.path
import sys
import spotilib
from bs4 import BeautifulSoup
import Tkinter as tk
import tkMessageBox
from PIL import ImageTk, Image
import webbrowser
def resource_path(relative):
return os.path.join(getattr(sys, ... |
from .base import * # noqa
DEBUG = True
ALLOWED_HOSTS = [
'127.0.0.1',
'localhost',
]
INTERNAL_IPS = (
'127.0.0.1',
)
|
import pandas as pd
import numpy as np
from datetime import datetime
from abc import ABC, abstractmethod
import scipy.stats as stats
import cvxpy as cvx
class AbstractOptimalHoldings(ABC):
@abstractmethod
def _get_obj(self, weights, alpha_vector):
raise NotImplementedError()
@abstractmethod
d... |
# this should possibly be a abstract class as well
from . import ConfigSource
class DictSource(ConfigSource):
def __init__(self, **kwargs):
"""If your backend data is exposable as a python dict, you can
subclass from this class to avoid implementing :py:meth:`has`,
:py:meth:`get`, :py:meth... |
#
# Copyright (c) 2009-2015, Jack Poulson
# All rights reserved.
#
# This file is part of Elemental and is under the BSD 2-Clause License,
# which can be found in the LICENSE file in the root directory, or at
# http://opensource.org/licenses/BSD-2-Clause
#
from environment import *
from imports import mpi
i... |
import pygame
pygame.init()
y = 60 # Height at which to start
width = 400
height = 400
surf = pygame.display.set_mode((width, height),
pygame.SRCALPHA)
surf.fill ((255,255,255))
y = 60 # Height at which to start
for n in range (0, 27): # Draw 30 horizontal bl... |
# Copyright 2020 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#"""
#Created on Tue Dec 19 11:18:44 2017
#
#@author: bas
#"""
import sys
import rospy
from moveit_commander import RobotCommander, PlanningSceneInterface
from geometry_msgs.msg import PoseStamped
import rospkg
import tf
import socket
def main(argv):
#This should b... |
import argparse
import os
import tensorflow as tf
import numpy as np
from datasets.cityscapes import CityscapesDatset
from datasets.concrete_damage_as_cityscapes import Concrete_Damage_Dataset_as_Cityscapes
from model import CGNet
from pipeline import batch_generator
from utils import load_config
from loss import co... |
# This file assumes that IREE has been built with python extensions.
# Assuming the IREE build directory is ${IREE_BUILD_DIR}, one would export the
# PYTHONPATH command in ${IREE_BUILD_DIR}/.env
#
# We reproduce it here:
# ```
# PYTHONPATH=${PYTHONPATH}:${IREE_BUILD_DIR}/compiler-api/python_package:${IREE_BUILD_DIR}... |
###Titulo: Organizador de fila
###Função: Este programa identifica entradas e saídas de uma fila
###Autor: Valmor Mantelli Jr.
###Data: 31/12/2018
###Versão: 0.0.2
### Declaração de variáve
último = 10
fila = list(range(1, último+1))
x = 0
### Atribuição de valor
while True:
print ("\nExistem %d clientes na fi... |
########################################################################
##
## CS 101
## Program #7
## Landon Volkmann
## lsvr34@mail.umkc.edu
##
## PROBLEM :
##
## 1. Simulate Orgeon Trail
## 2. Game ends when one of exit conditions met:
## a. All settlers dead
## b. Destination reached
## c. Run out ... |
import torch
from .equation import Equation
from .extend import semiring_einsum_forward
from .utils import add_in_place, sum_block, multiply_in_place
def real_einsum_forward(
equation: Equation,
*args: torch.Tensor,
block_size : int) -> torch.Tensor:
r"""Einsum where addition and multiplic... |
import struct
class StructField:
def __init__(self,format, offset):
self.format = format
self.offset = offset
def __get__(self,instance,cls):
if instance is None:
return self
else:
r = struct.unpack_from(self.format, instance._buffer, self.offset)
... |
#! /usr/bin/python
#===============================================================================
# File Name : .py
# Date : 12-20-2015
# Input Files : Nil
# Author : Satheesh <sathishsms@gmail.com>
# Description : This file just interfaces to neo4J and brings you the handle so that multi... |
import os
import argparse
import torch
import time
import sys
from torchvision import transforms
from models.fast_scnn import get_fast_scnn
from PIL import Image as Imag
from utils.visualize import get_color_pallete
sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages') # in order to import cv2 under python3... |
# -*- coding: utf-8 -*-
import os
import h5py
import numpy as np
THRESHOLD = float(os.environ.get('THRESHOLD', '0.85')) # 检索阈值
class NumpyRetrieval(object):
def __init__(self, index_dir, emb_size=512):
self.emb_size = emb_size
self.load(index_dir)
def load(self, index_dir):
h5f = h... |
# -*- coding: utf-8 -*-
import time, datetime
from blueking.component.shortcuts import get_client_by_request,get_client_by_user
import base64
from iwork.models import Host_Celery_log
from common.log import logger
from celery import task
from celery.schedules import crontab
from celery.task import periodic_task
def get... |
import gc
from collections.abc import MutableMapping
import pytest
from zict import Func
from zict.common import ZictBase
from zict.tests import utils_test
def inc(x):
return x + 1
def dec(x):
return x - 1
def rotl(x):
return x[1:] + x[:1]
def rotr(x):
return x[-1:] + x[:-1]
def test_simple(... |
a = set(list(input()))
if len(a) == 1:
print("Won")
else:
print("Lost")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 18-8-8 下午8:25
# @Author : Tom.Lee
# @File : consul_exporter.py
# @Product : PyCharm
# @Docs :
# @Source :
from .exporter import Exporter
from ..prometheus import prom
from ..prometheus import relabel
class C... |
#!/usr/bin/python3
# BSD-2-Clause
#
# Copyright (c) 2020 Tristan
# All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# ... |
import numpy as np
from astropy.wcs import WCS
from glue.utils import unbroadcast, broadcast_to
from glue.core.coordinates import LegacyCoordinates
def default_world_coords(wcs):
if isinstance(wcs, WCS):
return wcs.wcs.crval
else:
return np.zeros(wcs.world_n_dim, dtype=float)
def pixel2worl... |
# Unit tests for buttonManager
import mock
from mock import call
from mock import Mock
from mock import patch
import os
from os import sys, path
import unittest
sys.path.append(os.path.realpath('..'))
import buttonManager
import GeoFenceManager
import shots
from dronekit import Vehicle
# on host systems these files ... |
# -*- coding: UTF-8 -*-
import tensorflow as tf
import tensorflow.contrib.layers as layers
# Fully connected layer
def dense(input_, output_size, scope=None, stddev=0.02, bias_start=0.0, sn=False, with_w=False):
shape = input_.get_shape().as_list()
with tf.variable_scope(scope or "FC"):
w = tf.get_v... |
s = "Why, sometimes I’ve believed as many as six impossible things before breakfast."
def wordlist(sentence):
words = sentence.split(" ")
clean = []
for word in words:
clean.append(word.rstrip(",.").lower())
return sorted(clean)
print(wordlist(s))
|
import inqcipher
import sys
import os
import json
from argparse import ArgumentParser
if __name__ == '__main__':
if not os.path.isfile('config.json'):
print('Missing config file!')
raise SystemExit
with open('config.json', 'r') as raw:
config = json.loads(raw.read())
chars = c... |
#!python3.6
import re
print(re.match(r"\W(.)\1\W", " ff "))
print(re.match("\\W(.)\\1\\W", " ff "))
print()
print(re.match(r"\\", r"\\"))
print(re.match("\\\\", r"\\"))
|
# ----------------------
# settings
pw = ph = 500
amount = 5
stroke_w = 20
margin = stroke_w * sqrt(2)
y_size = (pw - 2*margin) / (amount)
# ----------------------
# function(s)
def y_shape(pos, s, rot ):
x, y = pos
with savedState():
translate(x + s/2, y + s/2)
rotate(rot)
for ... |
# caesar cipher
def encrypt(text, s):
result = ""
# traverse text
for i in range(len(text)):
char = text[i]
# Encrypt uppercase characters
if char.isupper():
result += chr((ord(char) + s - 65) % 26 + 65)
# Encrypt lowercase characters
else:
... |
from subprocess import Popen, PIPE
from socket import inet_ntoa
from random import sample
from struct import pack
from os.path import abspath
from time import sleep
from datetime import datetime
from collections import defaultdict
import jinja2
import webbrowser
import argparse
import json
import sys
parser = argparse... |
from django.db import models
from django.utils import timezone
# Create your models here.
class PileColor(models.Model):
"""Holds the Pile Color, like SALT & PEPPER, Cinnamon"""
name = models.CharField(max_length=50)
description = models.CharField(max_length=250)
def __str__(self):
return se... |
"""Examples for recommender system simulating envs ready to be used by
RLlib Trainers.
This env follows RecSim obs and action APIs.
"""
import gym
import numpy as np
from typing import Optional
from ray.rllib.utils.numpy import softmax
class ParametricRecSys(gym.Env):
"""A recommendation environment which ... |
from django.conf import settings
from ambulance.models import Ambulance, AmbulanceStatus
from equipment.models import EquipmentItem
from hospital.models import Hospital
from mqtt.tests.client import TestMQTT, MQTTTestCase, MQTTTestClient
from mqtt.tests.test_mqtt_3 import logger
class TestMQTTPublish(TestMQTT, MQTTT... |
import os
import sys
import logging
import json
import requests
from msal import ConfidentialClientApplication
from requests.adapters import HTTPAdapter, Retry
# Function that creates a logging mechanism
def create_logger(logfile=None):
# Create a logging handler that will write to stdout and optionally to a log ... |
import json
def rec(n):
if n == 1:
return 1
if n == 2:
return 2
if n == 3:
return 4
else:
return rec(n-1)+rec(n-2)+rec(n-3)
#TODO Complete!
def compute_ways(n):
return rec(n)
if __name__ == '__main__':
with open('./data.json') as f:
tests = json.load(f)
... |
from django.urls import path
from . import views
app_name = 'student'
urlpatterns = [
path('', views.student_list, name='student_data'),
]
|
from ..consts import GitHubRawBase
from ..KSEnumValue import KSEnumValue
from ..Source import Source
from ..nameNormalizer import prepareNamesAndOrigIds
from .ptags import parseValueFromSourceEnumStr
from .OxProps import SectionDict2Enum
from typed_ast import ast27
from typed_ast import ast3 as ast
from typed_ast.conv... |
from PySide2.QtCore import QObject, Signal
from cmri.trajectory.generator import Generator
class QGenerator(Generator, QObject):
generated = Signal(dict)
def __init__(self):
super().__init__()
QObject.__init__(self)
self.auto_update = True
def generate(self):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.