text stringlengths 1 927k |
|---|
from typing import List, Union, NoReturn
from copy import deepcopy, copy
from pandas import Index
from .component import Component
class ComponentHandler:
""" Helper class to manage many components
The purpose of this class is to make the management of components in a
time series as simple as possible,... |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the dir... |
# Generated by Django 3.2.9 on 2021-12-27 03:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('inheritanceapp', '0002_remove_artifact_description_remove_artifact_img_link_and_more'),
]
operations = [
migrations.AlterField(
... |
#
# DVR-Scan: Find & Export Motion Events in Video Footage
# --------------------------------------------------------------
# [ Site: https://github.com/Breakthrough/DVR-Scan/ ]
# [ Documentation: http://dvr-scan.readthedocs.org/ ]
#
# This file contains all code related to timecode formats, inter... |
# Copyright 2014-2016 OpenMarket Ltd
#
# 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 w... |
import numpy as np
import scipy.sparse as sp
import torch
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from torch_geometric.utils import to_networkx, degree
import torch.nn.functional as F
def convert_to_nodeDegreeFeatures(graphs):
# print(graph.x)
gra... |
# Copyright 2021 VMware, Inc.
# SPDX-License-Identifier: Apache-2.0
from vdk.internal.builtin_plugins.connection.decoration_cursor import DecorationCursor
from vdk.internal.builtin_plugins.connection.decoration_cursor import ManagedOperation
from vdk.internal.builtin_plugins.connection.pep249.interfaces import PEP249Cu... |
# Natural Language Toolkit: Decision Tree Classifiers
#
# Copyright (C) 2001-2015 NLTK Project
# Author: Edward Loper <edloper@gmail.com>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
A classifier model that decides which label to assign to a token on
the basis of a tree structure, where bra... |
# lang是提供股票编程语言,注重语法的翻译
# 利用了python 的ply lex,yacc
# setPY提供klang和python之间桥梁可以同享 函数和变量
from .kparse import *
from .mAST import setPY |
import pytest
from test_project.users.forms import UserCreationForm
from test_project.users.tests.factories import UserFactory
pytestmark = pytest.mark.django_db
class TestUserCreationForm:
def test_clean_username(self):
# A user with proto_user params does not exist yet.
proto_user = UserFactor... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from io import BytesIO
import logging
import warnings
import string
import numpy as np
import torch
import base64
from torchvision import tra... |
'''
SDL2 text provider
==================
Based on SDL2 + SDL2_ttf
'''
__all__ = ('LabelSDL2', )
from kivy.compat import PY2
from kivy.core.text import LabelBase
try:
from kivy.core.text._text_sdl2 import (_SurfaceContainer, _get_extents,
_get_fontdescent, _get_fontasce... |
from .base import Base
class Opengraph(Base):
endpoint = '/opengraph'
def get_opengraph_metadata_for_url(self, options):
return self.client.post(
self.endpoint,
options=options
) |
import os
import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset
from dataloaders.adult_process import get_adult_data
class AdultDataset(Dataset):
"""
The UCI Adult dataset.
"""
def __init__(self, root_dir, phase, tar_attr, priv_attr, clr_ratio):
self.tar_att... |
#!/usr/local/bin/python3
import numpy as np
import numpy.random as npr
import matplotli... |
from .download import load_concrete
from .download import load_energy
from .download import load_credit
from .download import load_occupancy
from .download import load_mushroom
from .download import load_hobbies
from .download import load_game
from .download import load_bikeshare
from .download import load_spam |
from ._base import register_app, App
@register_app
class PurePy(App):
alias = 'py'
description = 'Pure wsgi application' |
#!/usr/bin/env python
import ftplib
def banner():
print " ##### Malicious Inject p61 #####"
print " There is some use of Metasploit in this "
print " section that warrants a good read. "
def injectPage(ftp, page, redirect):
f = open(Page + '.tmp', 'w')
ftp.retrlines('RETR ' +page.,... |
import requests
import os.path
import json
import pprint
import sys
import getopt
class FHIRSearchClient:
def __init__(self, hostURL, cookies, debug=False ):
self.hostURL = hostURL
self.debug = debug
self.headers = {
'content-type': 'application/json'
}
self.cookies = cookies
def runQuery(self, que... |
import matplotlib.pyplot as plt
from scipy.io import wavfile # get the api
from scipy.fftpack import fft
from pylab import *
import os
import math
import contextlib # for urllib.urlopen()
import urllib
import os
################################
#### Ragas.py functions ########
################################
def rea... |
# pylint:disable=no-member
import os
from collections import OrderedDict
import numpy as np
import pycuda.gpuarray as garray
from pycuda.tools import dtype_to_ctype
import pycuda.driver as drv
from pycuda.compiler import SourceModule
from neurokernel.LPU.NDComponents.NDComponent import NDComponent
CUDA_SRC = """
#de... |
import argparse
import os
import os.path as osp
import shutil
import tempfile
import mmcv
import torch
import torch.distributed as dist
from mmcv.runner import load_checkpoint, get_dist_info
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmdet.apis import init_dist
from mmdet.core import res... |
import gym, torch, copy, os, xlwt, random
import torch.nn as nn
from datetime import datetime
import numpy as np
env = gym.make("clusterEnv-v0").unwrapped
state_dim, action_dim = env.return_dim_info()
####### initialize environment hyperparameters ######
max_ep_len = 1000 # max timesteps in one episode
auto_save = 1... |
import pytz
import logging
from datetime import datetime
from bs4 import BeautifulSoup
from habari.apps.crawl.models import Article
from habari.apps.crawl.crawlers import AbstractBaseCrawler
from habari.apps.utils.error_utils import error_to_string, http_error_to_string
logger = logging.getLogger(__name__)
class DNCr... |
class Leapx_org():
def __init__(self,first,last,pay):
self.f_name = first
self.l_name = last
self.pay_amt = pay
self.full_name = first+" "+last
def make_email(self):
return self.f_name+ "."+self.l_name+"@xyz.com"
def incrementpay(self):
self.pay_amt = int(self.pay_amt*1.20)
return self.pay_amt
... |
#
# 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 us... |
f = open('RESULT_SIS.INC')
lines = f.readlines()
d = {}
for line in lines:
if line in d:
d[line] += 1
else:
d[line] = 1
print d |
import sys
import requests
from . import settings
spotify_base = "https://api.spotify.com/v1"
def get_spotipy_token():
import spotipy.util as util
params = get_spotify_auth_params()
return util.prompt_for_user_token(**params)
def get_headers(token):
return {"Authorization": "Bearer %s" % (token)}
... |
# Copyright (c) 2018 PaddlePaddle 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
#
# Unless required by app... |
# Copyright 2019 Lukas Jendele and Ondrej Skopek.
# Adapted from The TensorFlow Authors, under the ASL 2.0.
#
# 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/licen... |
# coding: utf-8
# Copyright (c) 2019-2020 Latona. All rights reserved.
import time
from aion.logger import lprint
from aion.microservice import Options, main_decorator
from .check import UpdateUsbStateToDB, UsbConnectionMonitor, DATABASE
SERVICE_NAME = "check-usb-storage-connection"
EXECUTE_INTERVAL = 5
def fillt... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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 Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... |
import os
import pandas as pd
import fsspec
import argparse
from src.defaults import args_info
env_vars = open("/content/credentials","r").read().split('\n')
for var in env_vars[:-1]:
key, value = var.split(' = ')
os.environ[key] = value
storage_options={'account_name':os.environ['ACCOUNT_NAME'],\
... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
##############################################################################
#
# Copyright Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS ... |
def poly(*args):
"""
f(x) = a * x + b * x**2 + c * x**3 + ...
*args = (x, a, b)
"""
if len(args) == 1:
raise Exception("You have only entered a value for x, and no cofficients.")
x = args[0] # x value
coef = args[1:]
results = 0
for power, c in enumer... |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import base64
import os
import sys
import logging
from six import print_ as print
from tzlocal import get_localzone
from aws_saml_auth import amazon
from aws_saml_auth import configuration
from aws_saml_auth import saml
from aws_saml_auth im... |
#!/usr/bin/env python
#
# Use the raw transactions API to spend eves received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a eved or Eve-Qt runn... |
import pytest
import json
import os
from lkmltools.linter.rules.filerules.data_source_rule import DataSourceRule
from conftest import get_lookml_from_raw_lookml
def test_run1():
raw_lookml = """
view: aview {
sql_table_name: bqdw.engagement_score ;;
}
"""
lookml = get_lookml_from_raw_l... |
import setuptools
setuptools.setup(
name="sb6183_exporter",
version="0.0.1",
author="Steven Brudenell",
author_email="steven.brudenell@gmail.com",
packages=setuptools.find_packages(),
install_requires=[
"requests>=2.18.4",
"beautifulsoup4>=4.6.0",
"prometheus_client>=0.... |
# -*- 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... |
# Copyright 2014 Rackspace
#
# 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 agree... |
#
# (c) 2017, Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is... |
# coding: utf-8
# Copyright (c) 2016, 2020, 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... |
import argparse
import argparse
import json
import os
import queue
import sys
import time
from Constants import RunMode
from NetworkConfiguration import network_config_map
from calc.service_fee_calculator import ServiceFeeCalculator
from cli.wallet_client_manager import WalletClientManager
from config.config_parser im... |
# Boto3 code to delete an object
import json
import boto3
from botocore.exceptions import ClientError
s3 = boto3.client('s3')
def lambda_handler(event, context):
try:
bucketname = 'whizlabs-53210'
result = s3.delete_object(Bucket=bucketname, Key='iam.png')
return result
except ClientE... |
import io
from flask import jsonify
from google.cloud import storage, vision
from PIL import Image
vision_client = vision.ImageAnnotatorClient()
storage_client = storage.Client()
def detect_cat(request):
"""
param:
bucket: gcs bucket
resource: gcs bucket resource
returns:
information ... |
from __future__ import print_function
def str_aec(text, color):
"""Returns text wrapped by the given ansi color code"""
AEC_COLORS = {
'black': (0, 30),
'red': (0, 31),
'green': (0, 32),
'yellow': (0, 33),
'blue': (0, 34),
'purple': (0, 35),
'cyan': (0, ... |
#!/afs/bx.psu.edu/project/pythons/linux-i686-ucs4/bin/python2.7
"""
'Tile' the blocks of a maf file over each of a set of intervals. The
highest scoring block that covers any part of a region will be used, and
pieces not covered by any block filled with "-" or optionally "*". The list
of species to tile is specified ... |
# This is a script to write an XML geometry for our "cubanova" calculation
import sys
import numpy
from BlockIt import block
from BlockIt import branson_run_param
from BlockIt import generate_input
# generate branson run_param
run_param = branson_run_param(t_stop=1.0e-2, dt_start=1.0e-3, photons=5000, seed=14706)
#... |
# Copyright 2010-2021 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 agreed to in writing... |
# Copyright 2016 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
#
# Unless required by applicable ... |
# -*- coding: utf-8 -*-
from cms.signals.apphook import debug_server_restart
from cms.signals.page import pre_save_page, post_save_page, pre_delete_page, post_delete_page, post_moved_page
from cms.signals.permissions import post_save_user, post_save_user_group, pre_save_user, pre_delete_user, pre_save_group, pre_delete... |
import requests
from django.utils.dateparse import parse_datetime
from typing import List, Dict
from data_refinery_common.job_lookup import ProcessorPipeline, Downloaders
from data_refinery_common.logging import get_and_configure_logger
from data_refinery_common.models import (
Experiment,
ExperimentAnnotatio... |
# coding: utf-8
"""
Cisco Intersight OpenAPI specification.
The Cisco Intersight OpenAPI specification.
OpenAPI spec version: 1.0.9-1461
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import sys
import os
import re
# python 2 and p... |
# Copyright 2018 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
class MassSimulator:
name = "Mass Simulator"
params = [
{
"key": "mass",
"label": "",
"units": "kg",
"private": False,
"value": 100000000,
"confidence": 0,
"notes": "",
"source": "fake"
},
{
... |
###
#
# Lenovo Redfish examples - Get FW inventory
#
# Copyright Notice:
#
# Copyright 2018 Lenovo Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/l... |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... |
#!/usr/bin/env python3
# coding: utf-8
import xml.etree.ElementTree as ET
import subprocess
import sys
import re
import rospy
from pprint import pprint
from collections import defaultdict
NODE_NM = 'genpc'
LOG_HEADER = '<cam_prm_reader> '
print (LOG_HEADER + "start")
if len(sys.argv) != 3:
# print('Usage:cali... |
"""CLI argument parsing."""
import argparse
# from ..io import EXTENSIONS
from ._parseutil import Color
from ._parseutil import CustomFormatter
from ._parseutil import FileFolderType
from ._parseutil import FileType
from ._parseutil import FolderType
from ._parseutil import ProbabilityType
from ._parseutil import Sha... |
#!/usr/bin/env python3
from cereal import car
from selfdrive.config import Conversions as CV
from selfdrive.controls.lib.drive_helpers import EventTypes as ET, create_event
from selfdrive.controls.lib.vehicle_model import VehicleModel
from selfdrive.car.hyundai.carstate import CarState, get_can_parser, get_can2_parser,... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: rpc.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf ... |
"""
WSGI config for jobTracker project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_S... |
# coding: utf-8
"""
Mailchimp Marketing API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 3.0.74
Contact: apihelp@mailchimp.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import... |
#
# 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... |
from azsc.handlers.Handler import Handler
from azsc.handlers.az.Generic import GenericHandler
class ResourceGroupHandler(GenericHandler):
azure_object = "group"
def execute(self):
self.add_context_parameter("location", "location")
cmd = super(ResourceGroupHandler, self).execute()
se... |
import setuptools
# Get requirements from requirements.txt, stripping the version tags
with open('requirements.txt') as f:
requires = [x.strip().split('=')[0]
for x in f.readlines()]
with open('README.md') as file:
readme = file.read()
with open('HISTORY.md') as file:
history = file.read(... |
from pymongo import MongoClient
client = MongoClient('128.199.138.180',27017)
db = client.rhime_prod
articles = db.articles |
"""
decorator for functions that take a unique model attribute as
url parameter (or other string argument), and convert that
into an actual instance of that model as argument for the function
e.g. django url sees this function:
my_view(request, example_pk)
which is defined as
@instantiate(Example)
def my_vie... |
"""
Common arguments for BabyAI training scripts
"""
import os
import argparse
import numpy as np
class ArgumentParser(argparse.ArgumentParser):
def __init__(self):
super().__init__()
# Base arguments
self.add_argument("--env", default=None,
help="name of the... |
#%%
import numpy as np
import pandas as pd
import futileprot.io
import futileprot.viz
import altair as alt
import altair_saver
colors, palette = futileprot.viz.altair_style()
# Define experiment parameters
DATE = '2021-08-12'
STRAINS = 'DoubleKO'
MEDIUM = 'acetate'
RUN_NO = 1
ROOT = '../../../..'
SKIPROWS = 36
OD_... |
import argparse
import collections
import datetime
import json
import logging
import math
import urllib
from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy.dialects.my... |
import simplejson as json
import requests, sys, time, multiprocessing, threading
# import logging, httplib
# httplib.HTTPConnection.debuglevel = 1
# logging.basicConfig()
# logging.getLogger().setLevel(logging.DEBUG)
# requests_log = logging.getLogger("requests.packages.urllib3")
# requests_log.setLevel(logging.DEBUG)... |
from django.urls import path
from shop.views import HomeListView, ProductListView, ProductDetailView, contact, about
urlpatterns = [
path('', HomeListView.as_view(), name='home'),
path('contact/', contact, name='contact'),
path('about/', about, name='about'),
path('<slug:category_slug>/', ProductListVi... |
import logging
LOG_OPTIONS = {
'filemode': 'a',
'format': '%(asctime)s [%(module)20s] %(levelname)7s - %(funcName)s'
' - %(message)s',
'level': logging.INFO
} |
# Imports from 3rd party libraries
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
# Imports from this application
from app import app, server
from pages import index, predictions, insights, process, ... |
# pigeonhole
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
return len(set(zip(s, t))) == len(set(s)) == len(set(t))
# two dict
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
dx, dy = {}, {}
for x, y in zip(s, t):
if (x in dx and dx[x] != y)... |
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# 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 use, copy, modify,... |
# Copyright (c) Facebook, Inc. and its affiliates.
# 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.
import unittest
import torch
from common_testing import TestCaseMixin, get_random_cuda_device
from pytorch3d.ops... |
# Generated by Django 2.1.7 on 2019-05-24 00:52
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('courses', '0007_auto_20190520_0046'),
]
operations = [
migrations.DeleteModel(
name='BannerCourse',
),
] |
from classifyHistology.train_net import vars_phs_consts_metrics as vars
from classifyHistology.train_net import functions as func
from classifyHistology.extract_images import rw_images as extract
from classifyHistology.application import net_plot as netplot
from classifyHistology.application import classify_tissue as c... |
#!/usr/bin/env python
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
import ctypes
import numpy
from pyscf import lib
libcgto = lib.load_library('libcgto')
ANG_OF = 1
NPRIM_OF = 2
NCTR_OF = 3
KAPPA_OF = 4
PTR_EXP = 5
PTR_COEFF = 6
BAS_SLOTS = 8
def getints(intor_name, atm, bas, env, shls_slice=None... |
"""isort:skip_file"""
# start_pipeline_marker
from dagster import pipeline, solid
@solid
def get_name(_):
return "dagster"
@solid
def hello(context, name: str):
context.log.info("Hello, {name}!".format(name=name))
@pipeline
def hello_pipeline():
hello(get_name())
# end_pipeline_marker
# start_ex... |
# Based on condition we can execute some statements
# if elif help us to do
print("Welcome To Leap Year Check")
year = int(input("Enter year you need to check : "))
if (year % 100==0 and year % 400==0) or (year%100!=0 and year % 4 ==0):
print("Leap Year")
else:
print("Not Leap Year") |
#!D:\web_map\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip3.7'
__requires__ = 'pip==19.0.3'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
... |
import numpy as np
import matplotlib.pyplot as plt
def train_test_splitter(X, y, ratio = 0.8, random_seed = 0):
assert(len(X) == len(y)), "The number of points in feature matrix and target vector should be the same."
np.random.seed(random_seed)
n = len(y)
idx = np.arange(n)
np.random.shuffle... |
from torch import nn, Tensor
from typing import Any, Callable, Iterable, Sequence, Tuple, TypeVar, Union
from .utils.device import Device
try:
from typing import GenericMeta, NamedTupleMeta # type: ignore
class GenericNamedMeta(NamedTupleMeta, GenericMeta):
pass
except ImportError:
from typing i... |
from type.cell.cell_type import CellType
class SemanticCellType:
EMPTY = CellType("empty", 0)
CARDINAL = CellType("cardinal", 1)
STRING = CellType("string", 2)
DATETIME = CellType("datetime", 3)
LOCATION = CellType("location", 4)
ORG = CellType("organization", 5)
ORDINAL = CellType("ordin... |
from ldap3 import Server, Connection, ALL
from utils.config import get_config
_client = None
_base_dn = None
def init(serverUrl):
global _client
if _client is None:
server = Server(serverUrl, get_info=ALL)
_client = Connection(server, None, None, auto_bind=True)
return _client
def ini... |
# Copyright 2018-2022 Streamlit 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 wr... |
from datetime import date, timedelta
from django.db import models
class Plant(models.Model):
name = models.CharField(max_length=100)
image_url = models.URLField(max_length=200)
description = models.TextField()
def __str__(self):
return self.name
class WateringLog(models.Model):
plant = ... |
import pandas as pd
import re
import requests as rq
from bs4 import BeautifulSoup
header = {'User-Agent' : 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36'}
r = rq.get("https://www.thecricketmonthly.com/", headers=header)
soup = BeautifulSoup(r.content, 'html.p... |
import socket
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.bind(('127.0.0.1', 50007))
while True:
data, addr = s.recvfrom(1024)
print("data: {}, addr: {}".format(data, addr)) |
"""trello URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based ... |
from textwrap import wrap, fill
from tqdm import tqdm
from decimal import Decimal
from json import dumps
from mysql.connector.conversion import MySQLConverterBase
from mysql.toolkit.utils import cols_str, wrap
from mysql.toolkit.commands.dump import write_text
def insert_statement(table, columns, values):
"""Gen... |
# Generated by Django 3.1.5 on 2021-01-08 20:56
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
... |
import os
def encode_path(path):
if not path:
return path
if os.name == "nt":
if os.path.isabs(path):
drive, rest = os.path.splitdrive(path)
return "/" + drive[:-1].upper() + rest.replace("\\", "/")
else:
return path.replace("\\", "/")
else:
return path
def decode_path(path):
... |
"""Common verification functions for ping"""
# Python
import logging
# Genie
from genie.utils.timeout import Timeout
from genie.metaparser.util.exceptions import SchemaEmptyParserError
# pyATS
from genie.utils import Dq
log = logging.getLogger(__name__)
def verify_ping(device,
address=None,
... |
# Copyright (c) 2010 Upi Tamminen <desaster@gmail.com>
# See the COPYRIGHT file for more information
import time, anydbm
from rassh.core.config import config
def addToLastlog(message):
f = file('%s/lastlog.txt' % config().get('honeypot', 'data_path'), 'a')
f.write('%s\n' % (message,))
f.close()
def durat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.