content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
# Building tool for cpp and hpp files
# @Author Leonardo Montagner https://github.com/leomonta/Python_cpp_builder
#
# Build only the modified files on a cpp project
# Link and compile using the appropriate library and include path
# Print out error and warning messages
# add the args for the link... |
from django.http import HttpResponse
from django.shortcuts import render
from django.template import TemplateDoesNotExist
from comments.forms import CommentForm, ReplyForm, BattleCommentForm
from comments.models import Comment
from posts.models.post import Post
from bookmarks.models import PostBookmark
from posts.mode... |
from django.conf.urls import include, url
from django.core import urlresolvers
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailcore import hooks
from wagtail.wagtailadmin.menu import MenuItem
from wagtail.wagtailusers import urls
def register_admin_urls():
return [
url(r'^use... |
"""
###############################################################################
# Copyright 2019, by the California Institute of Technology.
# ALL RIGHTS RESERVED.
#
# United States Government Sponsorship acknowledged. Any commercial use
# must be negotiated with the Office of Technology Transfer at the
# Cali... |
"""
There is another implementation of this using stack please look,
in stack folder
"""
def rightmost_greater(arr, left, right):
if left <= right:
if arr[left] > arr[right]:
rightmost_greater(arr, left, right-1)
else:
lst.append(arr[right])
rightmost_greater(a... |
''' data_handler.py '''
import os
from sorter.lib.db import DB
from sorter.lib.book_utils import get_by_id, get_by_isbn
from sorter.lib.parse_xml import parse_isbn13_response, parse_id_response
def store_data(books, db_file):
'''
Store the book data in the provided database
'''
database = DB(db_file)
... |
import typing
import warnings
from pathlib import Path
import numpy as np
import pandas as pd
from scipy.stats import wilcoxon
from cacp.util import to_latex
def bold_large_p_value(data: float, format_string="%.4f") -> str:
"""
Makes large p-value in Latex table bold
:param data: value
:param forma... |
# 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 writing, software
# distributed under the... |
import asyncio
import functools
import random
import time
from testing import Client
from testing import default_test_setup
from testing import gen_data
from testing import gen_points
from testing import gen_series
from testing import InsertError
from testing import PoolError
from testing import QueryError
from testing... |
#!/usr/bin/env python
import xdrlib
p = xdrlib.Packer()
p.pack_double(3.2)
p.pack_int(5)
# pack list; 2nd arg is the function used to pack each element
p.pack_array([1.0, 0.1, 0.001], p.pack_double)
f=open('tmp.dat','w'); f.write(p.get_buffer()); f.close()
f=open('tmp.dat','r');
u = xdrlib.Unpacker(f.read())
f.close(... |
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from .models import Site,SocialMedia,Position,Pages,Carousel,CarouselImage,Widget, FAQ
class SocialMediaInline(admin.StackedInline):
model = SocialMedia
extra = 1
class SiteAdmin(admin.ModelAdmin):
inlines = [SocialM... |
"""Add Point
Revision ID: 71de7d079c37
Revises: e6d7560692fe
Create Date: 2016-01-03 13:26:52.977321
"""
# revision identifiers, used by Alembic.
revision = '71de7d079c37'
down_revision = 'e6d7560692fe'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
# comm... |
# -*- coding: utf-8 -*-
import logging
import multiprocessing
import time
from ..utils import timing
logger = logging.getLogger(__name__)
def run_sequential(tasks, name=None):
"""
Args:
tasks(list(NXtask))
Returns:
bool
"""
with timing.timeit_logger(logger, name=name):
fo... |
import time
import numpy as np
from numba import jit
from matplotlib import colors
from matplotlib import pyplot as plt
@jit
def mandelbrot(creal, cimag, maxiter, horizon, log_horizon):
real = creal
imag = cimag
for n in range(maxiter):
real2 = real*real
imag2 = imag*imag
... |
from regression_tests import *
class Test(Test):
"""Checks that fileinfo does not crash when analyzing a PE sample for which
we are unable to find a signer or counter-signer.
https://github.com/avast/retdec/issues/87
"""
settings=TestSettings(
tool='fileinfo',
args='--verbose',
... |
import numpy as np
import cv2
class Sample(object):
def __init__(self, img_path):
self.img_path = img_path
def read_features(self):
img = cv2.imread(self.img_path[0], cv2.IMREAD_COLOR)
return img
class Sample_Architecture_V1(Sample):
def __init__(self, img_path, label_path):
super(Sample_Architecture_V1,... |
from moderngl_window.context.tk.window import Window # noqa
from moderngl_window.context.tk.keys import Keys # noqa
|
from flask import render_template, url_for, request, redirect, flash, abort
from Tetris import app, db, login_manager
from flask_login import current_user, logout_user, login_user, login_required
from .models import User, Game
from .forms import SignupForm, LoginForm
@login_manager.user_loader
def load_user(userid):... |
#!/usr/bin/env python3
from src.util import *
# tag::starOne[]
passwords = read_file_to_list("input.txt")
result = 0
for (rf,rt,ch,pw) in passwords:
c = count(pw,ch)
if(rf <= c and c <= rt):
result = result + 1;
print(result)
# end::starOne[]
# tag::starTwo[]
passwords = read_file_to_list("input.tx... |
#!/usr/bin/env python3
import unittest
from data import Data, Q, Var
d = Data()
d.load("supermorphgnt.txt")
class DepQueryTestCase(unittest.TestCase):
def test_match_query(self):
"""
how many times is the 'lemma' καθώς?
"""
self.assertEqual(
len(list(d.query(Q(lemm... |
import weakref
import numpy as np
class float64(np.float64):
r"""
Examples
--------
.. doctest::
>>> from ndarray_listener import ndl, float64
>>>
>>> print(float64(1.5))
1.5
>>> print(ndl(1.5))
1.5
"""
def __new__(cls, *args):
retur... |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
from decisionengine.framework.modules import Publisher
class PublisherWithMissingConsumes(Publisher.Publisher):
pass
|
# import requests
# from typing import Dict, Any, List, Union
#
#
# class CompaniesMatch:
#
# __baseurl: str = 'http://url.com.br'
# _companies: Union[List[Dict[str, Any]], None] = None
#
# def __init__(self):
# self._companies = None
#
# def get(self) -> None:
# """Return companies"""
#... |
__copyright__ = "Copyright (c) 2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
from .mongo_storage import MongoDBStorage
from .mongo_handler import MongoHandler
|
# Copyright 2020 The Caer Authors. All Rights Reserved.
#
# Licensed under the MIT License (see 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/MIT>
#
# ===============================================================... |
"""
@author: Shubham Shantaram Pawar
"""
# importing all the required libraries
import numpy as np
import matplotlib .pyplot as plt
from sklearn.datasets import load_iris
# function to plot the training data
def plotTrainingData(X, y):
versicolor = np.where(y==0)
verginica = np.where(y==1)
... |
import logging
import pathlib
BACKUP_DIR = pathlib.Path("/backup/")
CHUNK_SIZE = 4 * 1024 * 1024
class RemoteInitializationError(Exception):
pass
class Remote(object):
def __init__(self, remote_dir, use_filename=False):
# directory in which to store snapshot files
self.remote_dir = remote_d... |
from datesplitter import tokenize
import unittest
class TestTokenizing(unittest.TestCase) :
def test_split_on_punc(self) :
assert tokenize('foo,bar') == ['foo,', 'bar']
def test_spaces(self) :
assert tokenize('foo bar') == ['foo', 'bar']
assert tokenize('foo bar') == ['foo', 'b... |
"""Python math functions"""
import math
def convert_to_base(decimal_number, base, digits):
"""Converts decimal numbers to strings of a custom base using custom digits."""
if decimal_number == 0:
return ''
return digits[decimal_number % base] + convert_to_base(decimal_number // base, base, digits)
... |
import string
import pandas as pd
from keras.optimizers import Adam
from keras.utils import np_utils
import numpy as np
from config import *
import json
from keras import backend as K
from keras.layers import Dense, Dropout
from keras.models import Model, load_model
from sys import argv
from custom_layers import *
from... |
import argparse
import json
import os
import cv2 as cv
import keras.backend as K
import numpy as np
from tqdm import tqdm
from config import img_size, image_folder, eval_path, best_model
from model import build_model
from utils import random_crop, preprocess_input, psnr
if __name__ == '__main__':
names_file = 'v... |
import uuid
from djongo import models
from node.blockchain.inner_models import Block as PydanticBlock
from node.core.models import CustomModel
class PendingBlock(CustomModel):
_id = models.UUIDField(primary_key=True, default=uuid.uuid4)
number = models.PositiveBigIntegerField()
hash = models.CharField(... |
from math import floor
import numpy as np
from skimage.metrics import peak_signal_noise_ratio as psnr
from .metric_computer import MetricComputer
from ..common_util.image import get_comp_frame, get_mask_frame, pil_binary_to_numpy, pil_rgb_to_numpy
class PConsPSNRMaskComputer(MetricComputer):
def compute_metric... |
from sklearn.metrics.pairwise import cosine_similarity
import pickle
import json
import numpy as np
from tqdm import tqdm
import jsonlines
import argparse
if __name__ == "__main__":
argparser = argparse.ArgumentParser()
argparser.add_argument('--claim_file', type=str)
argparser.add_argument('--corpus_file',... |
"""trident layers"""
|
'''
Advent of Code - 2018
--- Day 5: Alchemical Reduction ---
Released under the MIT License <http://opensource.org/licenses/mit-license.php>
'''
def react(unit1, unit2):
return abs(ord(unit1) - ord(unit2)) == 32
def react_polymer(polymer):
res = []
res.append(polymer[0])
for p in polymer[1:]:
... |
import os
from iconsdk.builder.transaction_builder import (
DeployTransactionBuilder,
CallTransactionBuilder,
)
from iconsdk.builder.call_builder import CallBuilder
from iconsdk.icon_service import IconService
from iconsdk.libs.in_memory_zip import gen_deploy_data_content
from iconsdk.providers.http_provider i... |
__author__ = 'Kalyan'
# this is a sample module for the understanding_modules assignment.
def greet(name):
return "module1 says hi to " + name
def _private_func():
pass
|
#!/usr/bin/env python
""" LearnedLeague Luck
This is an implementation of SheahanJ's algorithm for computing
"luck" in the [LearnedLeague](http://learnedleague.com), as described
by his post at in the [LearnedLeague Forum](http://www.learnedleague.com/viewtopic.php?f=3&t=5250)
The program expects to receive a CSV of ... |
# MIT License
#
# Copyright (c) 2021 Richard Mah (richard@geometrylabs.io) & Geometry Labs (geometrylabs.io)
#
# 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, includ... |
from easygraphics.turtle import *
create_world(800, 600)
set_speed(400)
for i in range(6):
for j in range(60):
fd(3)
rt(1)
rt(120)
for j in range(60):
fd(3)
rt(1)
rt(120)
rt(60)
pause()
close_world()
|
# -*- python -*-
"""@file
@brief Basic stuff for constructing Pato requests
Copyright (c) 2014-2015 Dimitry Kloper <kloper@users.sf.net>.
All rights reserved.
@page License
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
... |
from common.caching import cached, read_log_dir
from common.math import sigmoid, log_loss
from . import body_zone_models
from . import tf_models
from . import dataio
import tensorflow as tf
import numpy as np
import os
import datetime
import time
import tqdm
def _heatmap(z):
return np.stack([z == i for i in ran... |
class MovingAverage:
def __init__(self, windowSize) -> None:
self._windowSize = windowSize
self._historyWindow = [0] * windowSize
self._historyIndex = 0
self._historyCount = 0
def recordValue(self, value):
self._historyWindow[self._historyIndex] = value
self._his... |
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import argparse
from torchvision import datasets
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "2,3"
import scipy.io
from models import Resnet50_ft
from utils.utils import extract_feature, get_id, evaluate
from utils.dataloader import preproc... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from torch import nn
from torch.nn import functional as F
from maskrcnn_benchmark.modeling.utils import cat
class FastRCNNPredictor(nn.Module):
def __init__(self, config, pretrained=None):
super(FastRCNNPredictor, self).__init__()
... |
left, top, right, bottom = 166, 56, 303, 84
import tkinter as tk
from turtle import RawTurtle, TurtleScreen, ScrolledCanvas
root = tk.Tk()
width, height = root.winfo_screenwidth(), root.winfo_screenheight()
root.overrideredirect(True)
root.attributes('-alpha', 0.08)
canvas = ScrolledCanvas(root)
canvas.pack(fill=tk.B... |
import bs4
from bs4 import BeautifulSoup, NavigableString, Tag
import time
import requests
import sys
from config import create_api
def getLyrics():
print("Enter a J. Cole song you'd like to return the lyrics for.")
print("Keep in mind, if the song has spaces, it must be one entirely lowercase string.")
... |
class SwimmingPoolPayDesk:
def calculate_admission_fee(self, age):
""" Calulate admission fee
:param age: age of visitor
:return: fee for visitor
"""
if not isinstance(age, (int, float)) : raise TypeError
if age < 0 : raise ValueError
elif 0 <= age <= 6 : ret... |
from keras import applications
from keras.models import Model, Sequential
from keras.layers import Dense, Input, BatchNormalization
from keras.layers.pooling import GlobalAveragePooling2D, GlobalAveragePooling1D
from keras.layers.recurrent import LSTM
from keras.layers.wrappers import TimeDistributed
from keras.optimiz... |
import copy
import os
import re
import time
from Constants import PrintOpts
from check_environment import check_lapack, check_python_environment
from import_user_input import get_user_input
from system_functions import print_it, get_p3can_version, in_d
class Sim:
# TODO: add class attribute describtion
"""Si... |
"""
Definition of forms.
"""
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext_lazy as _
from .models import Comment
from .models import Blog
class BootstrapAuthenticationForm(AuthenticationForm):
"""Authentication form which uses boostr... |
from typing import Dict
from abc import ABC, abstractmethod
from selenium_base import SeleniumBase
import logging
class TaxerDriverBase(ABC):
def __init__(self):
self._base_url = 'https://taxer.ua'
self._token = None
self._cookies = dict()
def get_url(self, path):
... |
dia = float(input('quantos dias o carro ficou alugado?'))
km = float(input('quantos km foram percorridos?'))
x= 60 * dia + 0.15 * km
print('\033[7;30m O total a ser pago é de R${:.2f}\033[m'.format(x)) |
from django.db import models
class Owl(models.Model):
ioc_sequence = models.IntegerField()
common_name = models.CharField(max_length=64)
binomial_name = models.CharField(max_length=64)
def __str__(self):
return self.common_name
|
import pandas as pd
import openpyxl
import json
from datetime import datetime, date
from pymongo import MongoClient
import math
# Paths necesarios
path_ayuntamiento = "C:\\Users\\crist\\OneDrive - UPV\\TFM - Cristian Villarroya\\datos\\datos_vehiculos\\ayuntamiento\\"
path_web = "C:\\Users\\crist\\OneDrive -... |
"""
Copyright Government of Canada 2020-2021
Written by: Xia Liu, National Microbiology Laboratory,
Public Health Agency of Canada
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this work except in compliance with the License. You may obtain a copy of the
License at:
http... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if root == None:
... |
"""Support for the Hive switches."""
from homeassistant.components.switch import SwitchDevice
from . import DATA_HIVE, DOMAIN
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up Hive switches."""
if discovery_info is None:
return
session = hass.data.get(DATA_HIVE)
... |
import os
config = os.environ.setdefault("CELERY_FUNTEST_CONFIG_MODULE",
"celery.tests.functional.config")
os.environ["CELERY_CONFIG_MODULE"] = config
os.environ["CELERY_LOADER"] = "default"
|
import os
import sys
import socket
import subprocess
import uuid
import time
import platform
import tempfile
import secrets
from pgrok import pgrok
from pyngrok import ngrok
from http import HTTPStatus
from urllib.request import urlopen
import logging
from kafka_logger import init_kafka_logger, OutputLogger
import gdri... |
# Code modified from https://github.com/clcarwin/focal_loss_pytorch/blob/master/focalloss.py
from strategies.strategy_template import StrategyTemplate
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class FocalLoss(StrategyTem... |
from .data import *
from .plot import *
from .data_acquisition import * |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'liuzhijun'
import os
import sys
import logging
import time
from datetime import timedelta
from tornado import queues
from tornado import gen
from tornado import ioloop
from core import crawl_detail_info, crawl_base_info
PROJECT_PATH = os.path.realpath(os.... |
#
# Copyright (c) 2012 Will Page <compenguy@gmail.com>
# See the file LICENSE.txt for your full rights.
#
# Derivative of vantage.py and wmr100.py, credit to Tom Keffer
"""Classes and functions for interfacing with Oregon Scientific WM-918, WMR9x8 and WMR-968 weather stations
See http://wx200.planetfall.com/wx200... |
o=[int(x) for x in input('Enter numbers seprated by space: ').split()]
o.sort()
r=[]
for i in range(0,len(o)-1):
if o[i]==o[i+1]:
r.append(o[i])
r=list(set(r))
o=set(o)
while(len(r)>0):
o.remove(r[0])
r.pop(0)
print(sum(o))
|
from dsame.trees.BinaryTreeNode import *
def search_element(ele, root: BinaryTreeNode):
if not root:
return False
if ele == root.data:
return True
if search_element(ele, root.left):
return True
else:
return search_element(ele, root.right)
print(search_element(4, ini... |
# Copyright 2017 Intel
#
# 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 writing, softwar... |
#the print function should not have '[]'
#the first 'if' should have and instead of or
#and after the first 'if', the other ones should be 'elif'
for number in range(1, 101):
if number % 3 == 0 and number % 5 == 0:
print("FizzBuzz")
elif number % 3 == 0:
print("Fizz")
elif number % 5 == 0:
print("Buzz... |
import datetime
import json
import typing
import pytest
from starlette.testclient import TestClient
from beaconator.backend import dao
from beaconator.backend.utils.images import image_queries
def test_index(client: TestClient):
response = client.get("/")
assert response.status_code == 200
def test_login_... |
class InitFromSlots(type):
def __new__(meta, name, bases, bodydict):
slots = bodydict['__slots__']
if slots and '__init__' not in bodydict:
parts = ['def __init__(self, %s):' % ', '.join(slots)]
for slot in slots:
parts.append(' self.%s = %s' % (slot, slot)... |
# -*- coding: utf-8 -*-
import os
import cv2
import csv
import numpy as np
import pandas as pd
import progressbar
from scripts import Timer
from scripts import Retrievor
from scripts import Extractor
from scripts import mean_reciprocal_rank
from scripts import mean_mean_average_precision
from scripts import rank1_accur... |
import unittest
#from nose.plugins.attrib import attr
class DummyTestL(unittest.TestCase):
"""Today is brought to you by the letter L"""
def test_something(self):
"""
Lizards love testing
Lizards have very long tongues.
"""
self.assertTrue(True, 'example assertion')
... |
#!/usr/bin/python3
import argparse
from http.server import HTTPServer, SimpleHTTPRequestHandler
def main(port):
SimpleHTTPRequestHandler.extensions_map[".wasm"] = "application/wasm"
server = HTTPServer(("localhost", port), SimpleHTTPRequestHandler)
server.serve_forever()
if __name__ == "__main__":
p... |
# Link --> https://www.hackerrank.com/challenges/30-binary-numbers/problem
# Code:
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
binary = bin(n).replace("0b", "")
answer = 0
current_answer = 0
for i in range(len(binary)):
if bi... |
# ==================================================================================
#
# Copyright (c) 2018, Evangelos G. Karakasis
#
# 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 with... |
from netforce.model import get_model
from netforce import migration
class Migration(migration.Migration):
_name="cms.theme"
_version="1.183.0"
def migrate(self):
res=get_model("cms.theme").search([["state","=","active"]])
if res:
return
vals={
"name": "olson... |
#!/usr/bin/env python3
def find_matching(L, pattern):
indices = []
for idx, value in enumerate(L):
if pattern in value:
indices.append(idx)
return indices
def main():
indices = find_matching(["english", "finnish", "book", "cat", "ticklish"], "ish")
print(indices)
... |
#Задача 4
#Найти произведение ряда чисел от 1 до 10. Полученный результат вывести на экран.
n = 1
for i in range(1,11):
n *= i
print(n) |
from django.db.models import Q
from accounts.models import User
from accounts.serializers import UserSerializer
from chanel.models import Chanel
from django.http import JsonResponse
from rest_framework.status import HTTP_200_OK
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthentica... |
# -*- coding: utf-8 -*-
"""
Watch commandline is not tested because of some limitations with
``CliRunner`` that is not able to communicate with invoked command, so we
won't be able to send interrupt with "CTRL+C" to stop watching at the end of
tests.
"""
|
#!/usr/bin/env python3.6
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Employees Service'
if __name__ == '__main__':
app.run(ssl_context=('../ca2/server-cert.pem', '../ca2/server-key.pem')) |
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
from config import chains, isValidAppId, APP_ID
import json, base64
from database import client
from binascii import hexlify,unhexlify
from utils.base58 import burn_address
def BlockchainDaemon(app):
try:
uri = "http://%s:%s@%s:%s"%(chains[chains['... |
class Solution:
def solve(self, matrix, r, c, target):
dfs = [[r,c]]
original_color = matrix[r][c]
seen = {(r,c)}
while dfs:
cr,cc = dfs.pop()
matrix[cr][cc] = target
for nr,nc in [[cr+1,cc],[cr-1,cc],[cr,cc+1],[cr,cc-1]]:
if 0<=n... |
# import sys
# input = sys.stdin.readline
N, *a = [int(x) for x in open(0)]
a.insert(0, None)
first = 1
pres = first
count = 0
nex = a[pres] # press the button
count += 1
for i in range(N - 1): # operations are at most N-1 times.
if nex == 2:
break
prev = pres
pres = nex
nex ... |
from __future__ import print_function
import os
from tqdm import tqdm
import time
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torch.autograd import Variable
import torch.optim as optim
from torchvision import datasets, transforms
import numpy as np
from mod... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# code mostly stolen from Dennis Kaarsemaker (see https://github.com/rthalley/dnspython/blob/master/examples/zonediff.py)
# i use this to verify my zones are imported correctly
# run sync.py, afterwards login to inwx web interface, go to nameservers, and you can download... |
import uuid
import time
from sqlalchemy import Column, Integer, String
from anarcho import db
ANDR = 'andr'
IOS = 'ios'
class Application(db.Model):
__tablename__ = "apps"
id = Column('id', Integer, primary_key=True)
name = Column('name', String)
package = Column('package', String)
app_key = Co... |
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from indico.core.db import db
from indico.core.db.sqlalchemy.prin... |
import os
from pathlib import Path
import unittest, pytest
import numpy as np
import torch as th
import dgl_graphloader
def create_category_node_feat(tmpdir, file_name, separator='\t'):
node_feat_f = open(os.path.join(tmpdir, file_name), "w")
node_feat_f.write("node{}feat1{}feat2{}feat3\n".format(separator,s... |
from datetime import date, timedelta
from allocation.domain import events
from allocation.domain.model import Product, OrderLine, Batch
today = date.today()
tomorrow = today + timedelta(days=1)
later = tomorrow + timedelta(days=10)
def test_prefers_warehouse_batches_to_shipments():
in_stock_batch = Batch("in-sto... |
from unittest import TestCase
from unittest.mock import MagicMock
from src.Core import Core
from src.Processor import Processor
from src.Queue import Queue
class TestProcessor(TestCase):
def setUp(self):
mock_core = Core()
mock_core.canHostEntity = MagicMock(return_value=True)
mock_core.n... |
#!/usr/bin/env python
#Run this .py file in your PowerShell(windows) or Console (Linux), don't edit the code if you don't know what you're doing; it may (and most likely will) cause issues later on.
#SINGLE Call naar libwide.ini
######Importing dependencies
import platform
import time
import os
import subprocess
impo... |
from math import pi
from approxeng.chassis.simulation import Simulation, SimulationDrive
from approxeng.chassis.simulationplot import show_plot
from approxeng.chassis.util import get_regular_triangular_chassis
simulation = Simulation()
drive = SimulationDrive(simulation=simulation,
chassis=get... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from operator import add
from operator import mul
from functools import partial
def test():
add1 = partial(add, 1)
mul100 = partial(mul, 100)
print(add1(10))
print(mul100(2))
if __name__ == '__main__':
test()
|
import gym
import gym_grand_prix
import numpy as np
from math import pi
class Agent:
def __init__(self):
self.prev_sin = None
self.prev_cos = None
self.prev_steering = None
self.prev_values_valid = False
def optimal_action(self, sensor_info, p1=0.45, p2=1.0):
"""
... |
import string
class City:
def __init__(self, name):
self.name = string.capwords(name, sep = None)
def __str__(self):
return self.name
def __bool__(self):
if self.name[-1] in ['a','e','i','o','u']:
return False
return True
p1 = City('new york')
print(p1... |
from flexget.components.pending_approval.db import PendingEntry
from flexget.manager import Session
class TestPendingApproval:
config = """
tasks:
test:
mock:
- {title: 'title 1', url: 'http://localhost/title1', other_attribute: 'bla'}
pending_approval: yes
... |
import numpy as np
import matplotlib.pyplot as plt
from uncertainties import correlated_values
from scipy.optimize import curve_fit
from uncertainties.unumpy import nominal_values as noms
from uncertainties.unumpy import std_devs as stds
from lmfit import Model
from scipy.special import wofz
from scipy.special import e... |
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import time
import re
class HobbyStats(object):
"""
书影音数据
"""
def __init__(self, hobby, do=0, wish=0, collect=0):
"""
初始化数据
:param hobby: 喜好的类型:book, movie, music
:param do: 对应正在的数量
:param wish: 对应想要的数量
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.