content stringlengths 5 1.05M |
|---|
from django.db import models
from django.contrib.postgres.fields import ArrayField
from django.contrib.postgres.search import (
SearchVector,
SearchVectorField,
SearchQuery,
SearchRank,
SearchHeadline,
)
from regcore.models import Part
class SearchIndexQuerySet(models.QuerySet):
def effectiv... |
import copy
from typing import List, Optional, Union
import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
def cast(
value: Union[tf.Tensor, np.ndarray], dtype: tf.DType, name: Optional[str] = None
) -> tf.Tensor:
if not tf.is_tensor(value):
# TODO(awav): Release TF2.2 resol... |
import io
from enum import Enum
from typing import Optional, Union
import numpy as np
import onnxruntime as ort
from PIL import Image
from PIL.Image import Image as PILImage
from pymatting.alpha.estimate_alpha_cf import estimate_alpha_cf
from pymatting.foreground.estimate_foreground_ml import estimate_foreground_ml
fr... |
# -*- coding:utf-8 -*-
"""
Project: rocekpl_api_client
File: /phonecalls.py
File Created: 2022-02-28, 13:04:13
Author: Wojciech Sobczak (wsobczak@gmail.com)
-----
Last Modified: 2022-02-28, 13:07:41
Modified By: Wojciech Sobczak (wsobczak@gmail.com)
-----
Copyright © 2021 - 2022 by vbert
"""
from .api_client import Api... |
"""
The provided code stub will read in a dictionary containing key/value pairs of name:[marks] for a list of students. Print the average of the marks array for the student name provided, showing 2 places after the decimal.
Example
The query_name is 'beta'. beta's average score is .
Input Format
The first line c... |
#!/usr/bin/python3
if __name__ == "__main__":
import sys
if (len(sys.argv) == 1):
print("0 arguments.")
elif (len(sys.argv) == 2):
print("1 argument:")
else:
print("{:d} arguments:".format(len(sys.argv) - 1))
for argv in range(1, len(sys.argv)):
print("{:d}: {}".forma... |
# -*- coding: utf-8 -*-
"""
pypages
~~~~~~~
A module that brings easier pagination. Mainly useful for web
applications.
:copyright: (c) 2014 by Shipeng Feng.
:license: BSD, see LICENSE for more details.
"""
import math
class Paginator(object):
"""Paginator.
Basic usage::
... |
import requests
import json
import argparse
import unicodecsv as csv
api_version = "v6"
base_url = "https://channelstore.roku.com/api/" + api_version + "/channels/detailsunion"
# ======================================================================================================================
# util functions fo... |
import torch
import random
import torch.nn.functional as F
import os
import numpy as np
from scipy.spatial.distance import cdist
def get_accuracy(prototypes, embeddings, targets):
"""Compute the accuracy of the prototypical network on the test/query points.
Parameters
----------
prototypes : `torch.F... |
# -*- coding: utf-8 -*-
from __future__ import division #对未来版本兼容 只能放第一句
import Adafruit_PCA9685 #舵机控制库 pwm、频率等
import time #time库,用于延时
import cv2
import threading
import socket
import RPi.GPIO as GPIO #树莓派的gpio库
GPIO.setmode(GPIO.BCM) ... |
from msrest.serialization import Model
class LineGroup(Model):
"""LineGroup.
:param naptan_id_reference:
:type naptan_id_reference: str
:param station_atco_code:
:type station_atco_code: str
:param line_identifier:
:type line_identifier: list of str
"""
_attribute_map = {
... |
import sys
import boto3
try:
def main():
create_s3bucket(bucket_name, region=None)
except Exception as e:
print(e)
def create_s3bucket(bucket_name, region=None):
"""Create an S3 bucket in a specified region
If a region is not specified, the bucket is created in the S3 default
region (us-... |
# -*- coding: utf-8 -*-
__version__ = '0.1'
from getpass import getpass
from smtplib import SMTP
from email.header import Header
from email.mime.text import MIMEText
class Postbox(object):
host = None
port = None
user = None
password = None
tls = True
prompt_user = 'username? '
prompt_p... |
# 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
# "License"); you may not u... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-17 16:42
from __future__ import unicode_literals
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Manager', '0008_auto_20170417_1602'),
]
opera... |
from os import environ
from fastapi import FastAPI
from models import Student, Settings
from config import EXAMPLE_KEY
settings = Settings()
app = FastAPI()
database = []
@app.get('/')
async def read_index():
return {'msg': 'welcome'}
@app.get('/health')
async def read_health():
return {'status': 'ok'}
@a... |
from django.db import models
from django.db.models import Q
from enum import Enum
# custom
from Tools.model_util import CModel
# Create your models here.
LOW_QTY_COUNT = 5
class ProductStatus(Enum):
ProductAll='0'
ProductOnsale='1'
ProductOffsale='2'
class Category(CModel):
category_id = models.... |
# Generated by Django 3.2.9 on 2021-12-06 20:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('search', '0020_file_facet_values'),
]
operations = [
migrations.CreateModel(
name='CellLine',
fields=[
... |
# Copyright 2015 The TensorFlow Authors. 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
from __future__ import absolut... |
#!/usr/bin/env python3
import sys, subprocess
# "dm -l -verbose GesuProject.dme"
result = subprocess.run(['dm', '-l', '-verbose', 'GesuProject.dme'], stdout=subprocess.PIPE)
result.stdout.decode('utf-8')
sys.exit(0)
|
"""
Test writing python dictionaries to csv files
"""
import csv
import itertools
#test dictionary
testD1 = {'d1key1':1111, 'd1key2':2222, 'd1key3':3333}
#test dictionary with dictionary
testD2 = {'d2key1':1111, 'd2key2':2222, 'd2dict2':{'d2key3':3333, 'd2key4':4444}}
#test dictionary lists
testD3 = [ {'d3key1':11... |
import tensorflow as tf
import tensorflow_probability as tfp
import experiments.models.model_factory as model_factory
import experiments.models.unitary_rnn as urnn
def get_unitary_matrix(vector):
triangular_matrix = tfp.math.fill_triangular(vector)
skew_hermitian_matrix = triangular_matrix - tf.linalg.adjoin... |
from hippy.builtin import wrap
from rpython.rlib.rstring import StringBuilder
@wrap(['interp', str])
def escapeshellarg(interp, arg):
s = StringBuilder(len(arg) + 2)
s.append("'")
for c in arg:
if c == "'":
s.append("'")
s.append("\\")
s.append("'")
... |
from setuptools import setup, find_packages
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
name="timeseries_generator",
description="Library for generating time series data",
long_description=long_description,
long_description_content_type="text/markdown",... |
from low_rank_data import XY, XY_incomplete, missing_mask
from common import reconstruction_error
from fancyimpute import IterativeSVD
def test_iterative_svd_with_low_rank_random_matrix():
solver = IterativeSVD(rank=3)
XY_completed = solver.fit_transform(XY_incomplete)
_, missing_mae = reconstruction_erro... |
"""
Define various propagators for the PDP framework.
"""
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file
# in the project root for full license information.
import torch
import torch.nn as nn
import torch.nn.functional as F
from pdp.nn import util
#... |
import logging
import pytest
@pytest.fixture(scope='session', autouse=True)
def setup_logging():
logging.root.handlers = []
logging.basicConfig(level='INFO')
logging.getLogger('tests').setLevel('DEBUG')
logging.getLogger('peerscout').setLevel('DEBUG')
|
from js9 import j
import sys
import capnp
from collections import OrderedDict
import capnp
from .ModelBase import ModelBase
from .ModelBase import ModelBaseWithData
from .ModelBase import ModelBaseCollection
JSBASE = j.application.jsbase_get_class()
class Tools(JSBASE):
def __init__(self):
JSBASE.__init__... |
import wx
import wx.grid as gridlib
from wx.lib import masked
from wx.grid import GridCellNumberEditor
import wx.lib.buttons
import math
import Model
import Utils
from ReorderableGrid import ReorderableGrid
from HighPrecisionTimeEdit import HighPrecisionTimeEdit
from PhotoFinish import TakePhoto
from SendPhotoReques... |
#Filip Jenis, kvinta B
#Úloha: Rigorózka
from itertools import permutations
veta = input("Zadaj vetu:").split(" ")
moznosti = permutations(veta)
for i in moznosti:
print(" ".join(i)) |
node = S(input, "application/json")
childNode1 = node.prop("customers")
childNode2 = node.prop("orderDetails")
list = childNode1.elements()
customerNode = list.get(0)
property1 = node.prop("order")
property2 = customerNode.prop("name")
property3 = childNode2.prop("article")
value1 = property1.stringValue()
value2 = p... |
#!/usr/bin/python3
import requests, argparse, sys
from configparser import ConfigParser
requests.packages.urllib3.disable_warnings()
config = ConfigParser()
config.read('/etc/config.edc')
token = config.get('auth', 'token')
url = config.get('instance', 'curl')
headers = {'Authorization': 'Token {}'.format(token)}
par... |
"""
Just find file. Needs to be independent to avoid circular imports
"""
import os
def find_file(file_name: str, executing_file: str) -> str:
"""
Create/find a valid file name relative to a source file, e.g.
find_file("foo/bar.txt", __file__)
"""
file_path = os.path.join(
os.path.dirname(... |
#!/usr/bin/env python
# The MIT License (MIT)
#
# Copyright (c) 2015 Corrado Ubezio
#
# 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 ri... |
#!/usr/bin/env python3
"""
Module for interacting with the database
"""
# -*- encoding: utf-8 -*-
#============================================================================================
# Imports
#============================================================================================
# Standard imports
# T... |
#!/usr/bin/env python3
"""This is a nice simple server that we could be using if there were any JS
ZLIB libraries that actually worked (or the browsers exposed the ones they
have built in).
"""
import http.server
from http.server import HTTPServer, BaseHTTPRequestHandler
import socketserver
PORT = 8000
Handler = http.... |
# a other way to create a function
# way 1
def squre(num): return num * num
print(squre(5))
# way 2
squre2 = lambda num: num * num
print(squre2(5))
print("--------------")
# example way 2
sumNumbers = lambda first, second: first + second
print(sumNumbers(5, 10))
print("---------------")
... |
#!/usr/bin/env python
import time
import six
from flyteidl.core.errors_pb2 import ErrorDocument
from flyteidl.core.literals_pb2 import LiteralMap
from flytekit.clients import helpers as _helpers
from flytekit.clients.friendly import SynchronousFlyteClient
from flytekit.clis.sdk_in_container.pyflyte import update_conf... |
"""
Copyright (c) 2020, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import prin... |
# Generated by Django 3.2.8 on 2021-11-09 20:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0005_case_description'),
]
operations = [
migrations.AddField(
model_name='case',
name='last_filed',
... |
def go_to_beach():
print("I will go to the beach more often")
go_to_beach()
|
r"""
This module implements differential operators on cylindrical grids
.. autosummary::
:nosignatures:
make_laplace
make_gradient
make_divergence
make_vector_gradient
make_vector_laplace
make_tensor_divergence
.. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de>
"""
from typing impo... |
#!/usr/bin/python
import argparse as ap
import sys
import re
from scipy.stats import chisquare
from itertools import compress
gens_d = {'0/0':0, '0/1':1, '1/1':2, '1/2':3, '2/2':4, '0/0/0/0':0, '0/0/0/1':1, '0/0/1/1':2, '0/1/1/1':3, '1/1/1/1':4, '1/1/1/2':5, '1/1/2/2':6, '1/2/2/2':7, '2/2/2/2':8}
gens_tassel = {'0/0':... |
import os
from simplySQL import SQL
from flask_session import Session
from flask import Flask, render_template, redirect, request, session, jsonify
from datetime import datetime
import sqlalchemy.dialects.postgresql
DATABASE_URL = os.environ.get('DATABASE_URL', None)
DATABASE_URL = 'postgresql' + DATABASE_URL[8:]
# ... |
import os
import unittest
from common_helper_yara.yara_scan import _parse_yara_output, scan
DIR_OF_CURRENT_FILE = os.path.dirname(os.path.abspath(__file__))
class TestYaraScan(unittest.TestCase):
def test_parse_yara_output(self):
with open(os.path.join(DIR_OF_CURRENT_FILE, 'data', 'yara_matches'), 'r')... |
import numpy as np
from ...utils import mkvc
import discretize
import warnings
def edge_basis_function(t, a1, l1, h1, a2, l2, h2):
"""
Edge basis functions
"""
x1 = a1 + t * l1
x2 = a2 + t * l2
w0 = (1.0 - x1 / h1) * (1.0 - x2 / h2)
w1 = (x1 / h1) * (1.0 - x2 / h2)
w2 = (1.0 - x1 / h1)... |
from inspect import isabstract
from typing import Dict
from clean.request.filters.abs import BaseFilter
class FooFilter(BaseFilter):
def __init__(self, gte: str = "", lte: str = ""):
self.gte = gte
self.lte = lte
def to_dict(self):
return {
'gte': self.gte,
'... |
"""
...
"""
devicekeys = {'0001': 'asdfsfgw3g',
'0002': 'uhwefuihwef',
'0003': 'uihwefiuhawefawef',
'0004': 'uoihwefiuhwef',
'0005': 'iqweroih1r'}
def getDeviceKey(deviceid):
return devicekeys.get(deviceid)
|
dog_breeds = ['french_bulldog', 'dalmation', 'shihtzu', 'poodle', 'collie']
for breed in dog_breeds:
print(breed)
# for <temporary variable> in <list variable>:
# <action>
# for dog in dog_breeds:
# print(dog)
## Examples
board_games = ['Settlers of Catan', 'Carcassone', 'Power Grid', 'Agricola', 'Scra... |
"""Integration tests configuration file."""
from {{cookiecutter.package_name}}.tests.conftest import pytest_configure # pylint: disable=unused-import
|
"""Setup oaff-app"""
from setuptools import find_namespace_packages, setup # type: ignore
with open("README.md") as f:
long_description = f.read()
inst_reqs = [
"uvicorn==0.13.4",
"gunicorn==20.1.0",
"uvloop==0.15.2",
"httptools==0.2.0",
"pygeofilter==0.0.2",
"psycopg2==2.8.6",
"asyn... |
"""
Coeficient rule
f(n) == O(g(n)) -> c * f(n) == O(g(n)); c > 0
It means that if n -> oo, then c is not important, 'cause it's not related
to the input (n) lengh
# TIP: think in infite when form bigO notations
"""
def linear(n: int) -> int:
accum: int = 0
for i in range(n):
accum += 1
return a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import time
'''
这种方式的问题在于,读取文件写入文件的过程中,文件有可能有其他的写入
'''
def del_lines(path, key_word):
sign = False
with open(path, 'r') as f:
lines = f.readlines()
with open(path, 'w') as fw:
for line in lines:
if key_word in line or... |
"""定义learning_logs的URL模式"""
from django.urls import path
from . import views
app_name = 'learning_logs'
urlpatterns = [
# Home page
path('', views.index, name='index'),
# 显示所有主题
path('topics/', views.topics, name='topics'),
# 特定主题的详细页面
path('topics/<int:topic_id>/', views.topic, name='topic'),... |
import random
import discord
client = discord.Client()
@client.event
async def on_ready():
print("Running as {}".format(client.user))
@client.event
async def on_message(message):
if "@someone" in str(message.content).lower():
members_array = []
async for member in message.guild.fetch_memb... |
#!/usr/bin/env python3
import logging
from dataclasses import dataclass, field
from .parsing import parse_input, parse_output
LOGGER = logging.getLogger(__name__)
@dataclass
class Score:
scores: list = field(default_factory=list)
total: int = 0
def add(self, other):
self.scores.append(other)
... |
"""
Utilities functions for A* algorithm.
Author : Ismail Sunni
Email : imajimatika@gmail.com
Date : Jun 2019
"""
import json
from osgeo import ogr, osr
def get_nodes(G, key, value):
"""Return list of nodes that has attribute key = value"""
result_nodes = []
for node in G.no... |
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import resnet50, resnet18
from torch.hub import download_url_to_file
from face_recognition.utils.constants import TRAINED_WEIGHTS_DIR, FACESECURE_MODEL
device = "cuda" if torch.cuda.is_available() else "cpu"
def loa... |
import logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
from multiprocessing import Process, Queue
from queue import Empty
import RPi.GPIO as GPIO
import os
import json
import requests
import serial
import time
from signal import *
import secrets
... |
# Copyright 2013 the Neutrino authors (see AUTHORS).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
# Test case generator for python
from framework import *
class PythonAssembly(AbstractAssembly):
def __init__(self):
self.ops = []
def tag(self, code):
self.ops.append('tag(%i)' % code... |
from django.db import models
class BaseTable(models.Model):
"""
公共字段列
"""
class Meta:
abstract = True
verbose_name = "公共字段表"
db_table = 'BaseTable'
create_time = models.DateTimeField('创建时间', auto_now_add=True)
update_time = models.DateTimeField('更新时间', a... |
"""
TeSS to iAnn events sync v 0.0
This module aims to provide a schedulable process to make automatic sync
from TeSS to iAnn event registry.
"""
from dateutil.parser import parse
from pytz import UTC as utc
from datetime import datetime
import pysolr
import urllib2
import json
from docs import conf
import logging
imp... |
# https://www.acmicpc.net/problem/2581
m = int(input())
n = int(input())
isPrime = True
firstNum = 0
sumNum = 0
for i in range(m, n+1):
if i > 1:
for j in range(2, i):
if i%j == 0:
isPrime = False
break
isPrime = True
if isPrime:
i... |
# Copyright (C) 2015-2020 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
#... |
from django.http import HttpResponse, HttpResponseNotFound, HttpResponseServerError, HttpResponsePermanentRedirect, HttpResponseNotAllowed
from django.core.exceptions import ObjectDoesNotExist
from uriredirect.models import UriRegister,Profile
from uriredirect.http import HttpResponseNotAcceptable, HttpResponseSeeOt... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
{% if group == 'beat' %}from setuptools import setup, find_packages
def load_requirements(f):
retval = [str(k.strip()) for k in open(f, 'rt')]
return [k for k in retval if k and k[0] not in ('#', '-')]
install_requires=load_requirements('requirements.txt')
{% else %}... |
import datetime, io, os, socket
from contextlib import contextmanager
from unittest.mock import patch
from umatobi import constants
constants.SIMULATION_DIR = os.path.join(os.path.dirname(__file__), 'umatobi-simulation')
constants.FIXTURES_DIR = os.path.join(os.path.dirname(__file__), 'fixtures')
constants.LOGGER_STR... |
from data_structure_and_algorithms.python.code_challenges.stack-queue-brackets.stack_queue_brackets import check
def test_true():
exbected = True
actual = check('{}')
assert actual == exbected
def test_true_0():
exbected = True
actual = check('{}(){}')
assert actual == exbected
def test_true... |
from configparser import ConfigParser
from spaghettiqueue.logparser import LogsParser
from spaghettiqueue.client import APIClient
from spaghettiqueue.ui import Spaghetti
from PyQt5.QtWidgets import QApplication
from sys import platform, exit
from os import getenv
from os.path import expanduser, join, isfile
def main()... |
"""
pipeline_utils.py
------------------------------------
Contains utilities for:
- Saving and loading piplelines
- Constructing pipelines
- Running pipelines
- Loading primitives
"""
import sys
import glob
import pdb
import shutil
import uuid
import json
import random
import pandas
import numpy as np
import os
impor... |
# Falola Yusuf, Github: falfat
class Matrix:
"""
A matrix class to handle intersection matrix appropriately
Attributes
----------
matrix: matrix
intersection matrix
rows: int
number of rows of matrix
cols: int
number of column of matrix
size: int
matrix s... |
from classes import Api
class AptTradeDetail(Api):
pass |
from ds2.orderedmapping import BSTMapping as BST
from ds_viz.style import Style
def x(node, offset):
nodewidth = 40
lenleft = len(node.left) if node.left is not None else 0
return nodewidth * (lenleft + 1) + offset
# textstyle = {"stroke_width" : "0", "stroke" : "black",
# "fill" : "black", "fill_opaci... |
# 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>
#
# ===============================================================... |
class Wrapper(object):
def __init__(self, data, env):
self.data = data.decode("utf8")
self.env = env
def get_resp(self):
# Note: Nginx add additional response headers if and only if
# format of response accord with HTTP protocol
# 200
return "HTTP/1.1 200 OK\r\nC... |
from .base import *
DEBUG = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/storage/db.sqlite3',
}
}
|
#%%
# Objective, determining a basic normalized hero data format.
|
#!/usr/bin/env python
import json
import logging
import os
import sys
from collections import defaultdict
from typing import Union, Dict, Tuple
import fire
import numpy as np
import pandas as pd
from datasets import load_dataset
from gensim.models import KeyedVectors
from pandas import DataFrame
from tqdm.auto import ... |
import torch.nn.functional as F
import scipy.sparse as ssp
import numpy as np
import torch
from models import AGD
from deeprobust.graph.data import Dataset, PrePtbDataset
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--seed', type=int, default=15, help='Random seed.')
parser.add_argument('--f... |
import ast
import tingle
class ExtraSyntax(ast.NodeTransformer):
def visit_FunctionDef(self, node): return node
visit_AsyncFunctionDef = visit_FunctionDef
def visit_Return(self, node):
replace = ast.parse(
'''__import__('IPython').display.display()''').body[0]
replace.value.ar... |
from selenium.webdriver import ChromeOptions,Chrome,PhantomJS
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import time
class SeleniumDriver:
def __init__(self):
self.options = ChromeOptions()
self.options.add_argument(
'user-agent=Mozilla/5.0 (Windows N... |
"""
abc-classroom.roster
====================
"""
import csv
from pathlib import Path
from . import config as cf
def column_to_split_exists(input_file_path, column_to_split):
"""Given a path to the input file and a column name to
split into first_name, last_name, this method checks that the
column_to_s... |
import streamlit as st
import numpy as np
import pandas as pd
from prophet import Prophet
from prophet.diagnostics import performance_metrics
from prophet.diagnostics import cross_validation
from prophet.plot import plot_cross_validation_metric
import base64
st.title('📈 Automated Time Series Forecasting')
... |
import pickle, gnosis.xml.pickle
import funcs
funcs.set_parser()
gnosis.xml.pickle.setParanoia(0)
print "DESIRED BEHAVIOR:"
print " X.__init__() should be called when instances are created,"
print " and also when either a plain or xml pickle is restored."
class X:
__safe_for_unpickling__ = 1
def __init__(s... |
from .login import watch_login
from .login import watch_logout
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-"
# vim: set expandtab tabstop=4 shiftwidth=4:
"""
$Id$
This file is part of the xsser project, http://xsser.03c8.net
Copyright (c) 2011/2016 psy <epsylon@riseup.net>
xsser is free software; you can redistribute it and/or modify it under
the terms of the GNU General Publi... |
# Author: Mohit Sakhuja
def karatsuba(x, y):
"""Performs Karatsuba multiplication on two numbers."""
# Calculate the length of the two integers and take the minimum of the two.
n = min(len(str(x)), len(str(y)))
# Perform simple multiplication if any of the two numbers is less than 10.
if n == 1:
... |
from pyparsing import *
class FirewallFilter(object):
def __init__(self):
startDelim = Literal('{').suppress()
endDelim = Literal('}').suppress()
word = Word(alphanums + ',:-=[]"\'_\\')
ip_octet = Word(nums, min=1, max=3)
ip = Combine(ip_octet + '.' + ip_octet + '.' + ip_o... |
import hashlib
import responses
from georef_ar_etl.extractors import DownloadURLStep
from georef_ar_etl.exceptions import ProcessException
from . import ETLTestCase
# pylint: disable=no-member
class TestDownloadURLStep(ETLTestCase):
_uses_db = False
@responses.activate
def test_download(self):
""... |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
try:
from pathlib import Path
Path().expanduser()
except (ImportError,AttributeError): # Python < 3.5
from pathlib2 import Path
#
from . import hwm14
import logging
from numpy import append, arange, ceil, floor, meshgrid, ones,reshape
try:
from matplotlib.pyplot import figure,show,subplots,cm
from ... |
import numpy as np
# TODO(Jefferson): after switching to use numpy for general calculation, data model
# here feels less optimal and could likely be improved.
class Vec3:
def __init__(self, data = np.array([0., 0., 0.])):
self.data = np.array(data)
def x(self):
return self.data[0]
def y(s... |
import requests
import re
from util import Profile, write_poem
from bs4 import BeautifulSoup
import time
from random import randint
BASE_URL = 'http://www.zgshige.com'
list_reg = re.compile(r"javascript:window.location.href='(http://www.zgshige.com/zcms/poem/list\?SiteID=\d+&poetname=)'\+encodeURI\('(.+?)'\)\+'(&arti... |
import json
import os
import socket
import subprocess
from pathlib import Path
import requests
from repo2docker.app import Repo2Docker
from repo2docker.utils import chdir
from tqdm import tqdm
from . import __version__
from .cache import REPO2SINGULARITY_CACHEDIR, TMPDIR
class Repo2Singularity(Repo2Docker):
"""... |
import Keywords
import sys
class Evaluator:
def __init__(self, AST):
self.AST = AST
def execute(self, loc):
if isinstance(loc[1], list):
self.run(loc[1])
elif loc[0] == Keywords.t_print:
self.echo(loc[1])
elif loc[0] == Keywords.t_stop:
... |
from floodsystem.stationdata import build_station_list
from floodsystem.geo import stations_by_distance
from floodsystem.station import MonitoringStation
from floodsystem.geo import stations_within_radius
from floodsystem.station import inconsistent_typical_range_stations
def test_stations_by_distance():
## creat... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from .aperture import aperture_photometry
from .detection import (background, sepfind, daofind, calc_fwhm,
recenter_sources, starfind)
from .solve_photometry import (solve_photometry_median,
solve_pho... |
import click
import requests
import time
import os
import psycopg2
from flask import current_app, g
from flask.cli import with_appcontext
from bs4 import BeautifulSoup
def get_db():
if 'db' not in g:
g.db = psycopg2.connect(os.environ["DATABASE_URL"], sslmode='require')
return g.db
def close_db(e=... |
__author__ = '4ikist'
import data_handler
if __name__ == '__main__':
dh = data_handler.FlickrDataHandler()
photo_objects = dh.get_photo_objects(size='Square', tags=['enot'])
photo_objects2 = dh.get_photo_objects(size=['Square', 'Original'], tags='test')
print '' |
# queen.py - QuantumChess
# Author: Cody Lewis
# Date: 24-FEB-2018
import piece
import functions
from functions import Direction
class Queen(piece.Piece):
def __init__(self, superposNum, frstSuperPos, col, idT):
idT = 'Q ' + str(idT)
piece.Piece.__init__(self, superposNum, frstSuperPos, col, idT)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.