content stringlengths 5 1.05M |
|---|
# Copyright © 2019 Province of British Columbia
#
# 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... |
# Generated by Django 2.0.3 on 2018-03-20 23:23
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('students', '0003_userprofile_stu_class'),
]
operations = [
migrations.Alte... |
from pipeline import PipelineCloud, pipeline_function
api = PipelineCloud()
@pipeline_function
def add_lol(a: str) -> str:
return a + " lol"
upload_output = api.upload_function(add_lol.__function__.__pipeline_function__)
print(upload_output)
|
from django.contrib.auth import get_user_model
from django.contrib.auth.models import update_last_login
from drf_rw_serializers import viewsets
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.views import ObtainAuthToken
from .permissions import IsAuthorOrAdminOrReadOnly
from .seriali... |
from __future__ import unicode_literals, division, absolute_import
import logging
from datetime import datetime, timedelta
from sqlalchemy import Table, Column, Integer, Float, String, Unicode, Boolean, DateTime, delete
from sqlalchemy.schema import ForeignKey, Index
from sqlalchemy.orm import relation, joinedload
fr... |
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Datetime : 2019/11/12 下午11:17
# @Author : Fangyang
# @Software : PyCharm
from PyQt5.QtWidgets import (
QMainWindow, QTextEdit, QAction, QFileDialog, QApplication
)
from PyQt5.QtGui import QIcon
import sys
class Example(QMainWindow):
def __init__(self):
... |
#!/usr/bin/python3
# --- 001 > U5W2P1_Task13_w1
def solution( a, b, c, d, e, f ):
input = [ a, b, c, d, e, f ]
larger = -float('inf')
for x in input:
if(larger<x):
larger = x
return larger
if __name__ == "__main__":
print('----------start------------')
a = -2
b = 20
... |
"""Some Signals & Systems Helping Routines."""
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from matplotlib.patches import Circle
import numpy as np
from scipy import signal
def plot_zplane(z, p, k):
"""Plot pole/zero/gain plot of discrete-time, linear-time-invariant system.
Note... |
from .base import BaseResource
class LambdasContexts(BaseResource):
grn_type = 'contexts'
|
#!/usr/bin/env python
import optparse
import sys
from collections import defaultdict
import itertools
import math
from scipy.special import digamma
import pickle
optparser = optparse.OptionParser()
optparser.add_option("-d", "--data", dest="train", default="data/hansards", help="Data filename prefix (default=data)")
o... |
"""
@file fib.py
@author Johnny Gilbert
@brief This file contains both a recursive and iterative version of calculating fibonacci combinations
"""
def fib_recursive(n):
if n == 1 or n == 2:
return 1
return fib_recursive(n - 1) + fib_recursive(n - 2)
def fib_iterative(n):
temp = 0
... |
from typing import List, Optional
from fastapi.encoders import jsonable_encoder
from sqlalchemy.orm import Session
from ultron8.api.db_models.item import Item
from ultron8.api.models.item import ItemCreate, ItemUpdate
def get(db_session: Session, *, id: int) -> Optional[Item]:
return db_session.query(Item).filt... |
# Copyright 2020 Axis Communications AB.
#
# For a full list of individual contributors, please see the commit history.
#
# 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.apac... |
from django.contrib import admin
from applications.core.models import Clients
admin.site.register(Clients)
|
from config import db
journey_version_step = db.Table('journey_version_step',
db.Column('journey_version_id', db.Integer, db.ForeignKey('journey_version.journey_version_id'), nullable=False),
db.Column('journey_step_id', db.Integer, db.ForeignKey('journey_step.journey_step_id'), nullable=False),
db.Primary... |
#! /usr/bin/env python3
import os,sys,string
def main():
if len(sys.argv)==1:
print(HelpString)
Dir = sys.argv[1]
Dst = '~/poaching'
Ends = sys.argv[2]
Ends = Ends.split('.')
if len(sys.argv)>3:
Dst = sys.argv[3]
if not os.path.exists(Dst): os.mkdir(Dst)
if not os.path.e... |
# -*- coding: utf-8 -*-
"""
Draw map.
"""
import numpy as np
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
from dk_met_io.read_micaps import read_micaps_4
plt.rcParams['figure.figsize'] = (16, 12)
def plotMap():
# Set the projection information
proj = ccrs.La... |
from setuptools import setup
setup(
name='python-josso-auth',
description='A JOSSO backend for python-social-auth',
keywords='python-social-auth,social-auth-app-django,sso,josso',
version='0.1.4',
packages=['josso'],
package_dir={'josso': 'josso'},
package_data={'josso': ['wsdl/*.xml']},
... |
# 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 GetSecurityGroupRes... |
""" Data training and validation tools """
import torch
from tqdm import tqdm
from torch.cuda.amp import autocast, GradScaler
class TrainingManager:
""" PyTorch Training Manager with Mixed Precision Support
Args:
model: PyTorch model to be trained
loss_fn: Cost function
train_dloader:... |
"""anime and ratings tables
Revision ID: 1a8992efe615
Revises: 066925d2e669
Create Date: 2021-01-21 17:33:45.841056
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1a8992efe615'
down_revision = '066925d2e669'
branch_labels = None
depends_on = None
def upgrad... |
# Python program to find maximum XOR subset
# Number of bits to represent int
INT_BITS = 32
# Function to return maximum XOR subset in set[]
def maxSubarrayXOR(set, n):
# Initialize index of chosen elements
index = 0
# Traverse through all bits of integer starting from the most significant bit (MSB)
... |
import pytest
from ..take2 import (
Block,
BlockDirective,
DefListItem,
Example,
Header,
Lines,
main,
make_block_3,
)
examples = [
(
"""
This is a block
This is a second block
""",
3,
),
(
"""
This is a block
with a subblock
This is a second b... |
# Copyright 2012 OpenStack Foundation
#
# 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 a... |
import time
while True:
print('some time has passed')
time.sleep(2)
|
import pymysql.cursors
# Debug
debug = False
# site info
# only used for initialize
site_info = {
'site_title': 'Eureka',
'site_description': 'Eureka Blog CMS'
}
# article statuses
statuses = [
'draft',
'published'
]
# beaker session options
beaker_opts = {
'session.type': 'redis',
'session.... |
from collections import OrderedDict
import torch.nn as nn
from pretrainedmodels.models import senet
class SENet(senet.SENet):
def __init__(self, block, layers, groups, reduction, first_stride=1, dropout_p=0.2,
inplanes=128, input_3x3=True, downsample_kernel_size=3,
downsample_pa... |
# -*- coding: utf-8 -*-
'''Classic module.
'''
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import sys, logging, inspect
from ctypes import (CDLL, cdll, c_uint, c_ulong, c_float)
from future.builtins import (ascii, filter, hex, map, oct, zip)
__all__ = ['fact_i', 'fact_lp... |
class Account:
def __init__(self, amount):
self._amount = amount
def transfer(self, amount, dest_account):
dest_account._amount = dest_account._amount + amount
self._amount = self._amount - amount
def amount(self):
return self._amount
|
"""
Backend database modules for SKA SDP configuration information.
At the moment we only support etcd3.
"""
import time
import queue as queue_m
import etcd3
# Some utilities for handling tagging paths.
#
# The idea here is that etcd3 only supports straight-up prefix
# searches, but we do not want to get "/a/b/c" ... |
from player import HumanPlayer, RandomComputerPlayer, GeniusComputerPlayer
import time
class TicTacToe:
def __init__(self):
self.board = [" " for _ in range(9)]
self.current_winner = None
def print_board(self):
for row in [self.board[i*3:(i+1)*3] for i in range(3)]:
... |
import os
import time
from edge.command.common.precommand_check import precommand_checks
from edge.config import EdgeConfig, ModelConfig
from edge.enable_api import enable_service_api
from edge.endpoint import setup_endpoint
from edge.exception import EdgeException
from edge.state import EdgeState
from edge.tui import ... |
# encoding: utf-8
"""
@author: Jiayang Chen
@contact: yjcmydkzgj@gmail.com
"""
from .defaults import _C as cfg
|
from typing import List, Tuple
import cairocffi as cairo
import pangocairocffi
import pangocffi
from pangocffi import Attribute, AttrList, FontDescription, Layout, Rectangle, ffi
from ....text.textstyle import TextStyle
from ....utils.geom import Rect
from .utils import get_rgb_color
def to_pango_units(size: float)... |
import subprocess
import os
import re
import sys
import numpy as np
from pandas import *
if __name__ == '__main__':
from vbench.git import GitRepo
repo = GitRepo('/Users/wesm/code/pandas')
churn = repo.get_churn_by_file()
file_include = []
for path in churn.major_axis:
if path.endswith(... |
# #! /usr/bin/env python
# Load Libraries
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import pytest
from .. import api
# Fixtures.
@pytest.fixture
def create_dummy_dataset(n=50, expt_groups=6):
# Dummy dataset
Ns = n
... |
import urllib.request,json
from app.models import News, Articles
# Getting api key
api_key = 'bcb0f779f8e84531abdb5f1550f7d466'
# Getting the news base url
base_url = None
# Getting the articles_url base url
articles_url = None
def configure_request(app):
global api_key,base_url,articles_url
api_key = app.... |
class Solution:
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 1:
return True
elif n <= 2:
return False
while n > 3:
if n % 3 == 0:
n /= 3
else:
return Fal... |
import os
import json
import argparse
import subprocess
import sentencepiece as spm
from pathlib import Path
from tqdm import tqdm
from multiprocessing import Pool
def count_file_lines(file_path):
"""
Counts the number of lines in a file using wc utility.
:param file_path: path to file
:return: int, n... |
# *****************************************************************************************
#
# Simple compiler for TAB1 format
#
# *****************************************************************************************
import re,sys
# ************************************************************************... |
import io
from setuptools import setup, find_packages
def get_long_description():
with io.open('README.md', encoding='utf-8') as f:
return f.read()
setup(
name='AssetVendor',
version='0.0.2',
author='Ryan P Kilby',
url='https://github.com/rpkilby/AssetVendor',
description='A simple ... |
"""
Module that defines Tool functions and test runners/result for use with
the unittest library.
"""
from typing import Optional, Any, Type
import sys
import unittest
import os
import posixpath
import yaml
def get_posix_path(path : str) -> str:
"""translates path to a posix path"""
heads = []
tail = path
... |
"""Basic Integration tests for the BaseTransformer."""
import numpy as np
import pandas as pd
from rdt.transformers.base import BaseTransformer
def test_dummy_transformer_series_output():
"""Test a transformer that outputs a Series.
This validates that a Transformer that is implemented to
produce a Ser... |
import pygame
from pgu import gui as pgui
from colors import WHITE
def radio_button_action(args):
model, value = args
# 'manhattan' or 'euclidean'
if value == 1:
model.heuristic = 'manhattan'
elif value == 2:
model.heuristic = 'euclidean'
def create_radio_button(container, windos_si... |
generatedDelKmers = set()
actualKmers = set()
with open(snakemake.input[0], "r") as infile, open(snakemake.output[0], "w") as outfile:
# read the lines and transform to list so it can be iterated twice
lines = list(infile.read().splitlines())
for l in lines:
kmer = l.split()[0]
actualKme... |
import numpy as np
import jax
from scico import functional, linop, loss, random
from scico.pgm import (
PGM,
AcceleratedPGM,
AdaptiveBBStepSize,
BBStepSize,
LineSearchStepSize,
RobustLineSearchStepSize,
)
class TestSet:
def setup_method(self, method):
np.random.seed(12345)
... |
def transpose(list_of_lists):
return [list(k) for k in zip(*list_of_lists)]
|
from Katari.sip import SipMessage
class Trying100(SipMessage):
def __init__(self):
super().__init__()
self.method_line = "SIP/2.0 100 Trying\r\n"
class Ringing180(SipMessage):
def __init__(self):
super().__init__()
self.method_line = "SIP/2.0 180 Ringing\r\n"
class CallisBe... |
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
from libcloud.storage.providers import get_driver as get_storage_driver
from libcloud.storage.types import Provider as StorageProvider
import boto
import boto.ec2
import boto.ec2.elb
import boto.ec2.cloudwatch
import boto.sns
... |
#! /usr/bin/env python3
# coding=utf-8
"""Fake application web server"""
from http.server import HTTPServer, BaseHTTPRequestHandler
from subprocess import run, PIPE, STDOUT
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
"""Server that test FPGA presence"""
def do_GET(self):
"""GET"""
... |
from .misc import namedtuple_with_defaults
from sqlalchemy import event, and_
from sqlalchemy.orm import relationship, foreign, remote, backref
from sqlalchemy.ext.associationproxy import association_proxy
import inflection
import logging
logger = logging.getLogger(__name__)
DELIMITER = '__'
Relation = namedtuple_wit... |
class Document:
"""
INCEpTION's Document object
"""
def __init__(self, project_id: int, document_id: int, document_name: str, document_state: str):
self.project_id = project_id
self.document_id = document_id
self.document_name = document_name
self.document_state = docume... |
# -*- coding:utf-8-*-
name = ["dzj","zz","ljx"]
name_1 = name.pop()
print(name)
print(name_1)
name_1 = name.pop(0)
print(name)
print(name_1)
name.append("zke")
name.insert(0,"gyj")
print(name)
print("以上内容毫无意义,不必观看")
print("--------------------分界线----------------------")
print("以下是我的女性朋友名单:")
print(name)
n... |
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
def load_airlines_series():
airlines = pd.read_csv('data/AirPassengers.csv')[:-1]
airlines.Month = pd.to_datetime(airlines.Month)
airlines = airlines.set_index('Month')
airlines.col... |
from antarest.study.storage.rawstudy.model.filesystem.config.model import (
FileStudyTreeConfig,
)
from antarest.study.storage.rawstudy.model.filesystem.folder_node import (
FolderNode,
)
from antarest.study.storage.rawstudy.model.filesystem.inode import TREE
from antarest.study.storage.rawstudy.model.filesyste... |
"""Patterns and labels for index extraction"""
import re
from enum import Enum
# ------ Patterns ------
IN_PAREN = re.compile(r"([^(]*\S)\((.*)\)(.*)") # Ajengo(a)
EXT_PAREN = re.compile(r"([^(]*) \((.*)\)") # Delftse Poort (Colombo)
VOL_PAGE = re.compile(r"\D*_(\d+)_\D*(\d+)\D*") # gm_8_foo_255_... |
#
# 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
# ... |
from lx16a import *
from math import sin, cos
import time
# This is the port that the controller board is connected to
# This will be different for different computers
# On Windows, try the ports COM1, COM2, COM3, etc...
# On Raspbian, try each port in /dev/
LX16A.initialize("/dev/ttyUSB0")
# There should t... |
'''
Created on Jan 19, 2017
@author: Dibyojyoti
'''
from pycas.cas.core.SofaFS import SofaFS
from pycas.cas.core.TOP import TOP
from pycas.cas.core.Annotation import Annotation
class CAS(object):
'''
This class represents a UIMA CAS
'''
def __init__(self, typesystem):
'''
Constructor
... |
import calendar
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.config import PSQL_ENVIRONMENT
from app.database.models import Base
pytest_plugins = [
'tests.user_fixture',
'tests.event_fixture',
'tests.dayview_fixture',
'tests.invitation_fixture',
... |
# !/usr/bin/python3
#
# Back to the Future Clock
# MP3 player functions
# Version 4.1
# Change to MPD/MPC
#
# CADJ 28/12/2018
#
#
# OS and low-level
import time
import signal
import subprocess
import datetime
from datetime import datetime
import re
# Local modules
import globals
import mpc
from Display import *
from... |
from __future__ import annotations
from aoc.d19.main import Simulator, _read_instructions
from aoc.d21.annotated_input_v4 import main as part2
def simulate(filename: str):
instructions = _read_instructions(filename, "21")
simulator = Simulator(*instructions, 10504829)
simulator.watchlist = 28
while s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##
## @file train_classification.py
## @brief Trainer Class for Classification CNN Training
## @author Keitetsu
## @date 2020/05/22
## @copyright Copyright (c) 2020 Keitetsu
## @par License
## This software is released under ... |
from django.shortcuts import render
from tapiriik.services import Service
from tapiriik.settings import WITHDRAWN_SERVICES
def privacy(request):
OPTIN = "<span class=\"optin policy\">Opt-in</span>"
NO = "<span class=\"no policy\">No</span>"
YES = "<span class=\"yes policy\">Yes</span>"
CACHED = "<span class=\"cach... |
import math
from logging import getLogger
from typing import List, NamedTuple, Optional
from eth_abi.packed import encode_abi_packed
from hexbytes import HexBytes
from web3 import Web3
from web3.types import TxParams, Wei
from gnosis.eth.constants import GAS_CALL_DATA_BYTE, NULL_ADDRESS
from gnosis.eth.contracts impo... |
# Generated by Django 1.10.1 on 2016-09-19 00:08
from django.db import migrations
class Migration(migrations.Migration):
def set_initial_orders(apps, schema_editor):
GameCategory = apps.get_model("games", "GameCategory")
for category in GameCategory.objects.all():
category.order = cate... |
"""
Set of classes to support two and three dimensional vector manipulation.
"""
import math
from random import uniform
class Vector2d(object):
"""
Class to implement two dimensional vector with supporting classes and
operator overloads.
:param x: x component or pair of components.
:type x: ... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
import os
import glob
import imageio
import random
import scipy.misc as misc
import numpy as np
from cStringIO import StringIO
#make sure that the sequence is multiple of batches, necessary?
def padding_seq(seq, batc... |
import cv2
import os
import pickle
from os.path import join, exists
import handsegment as hs
import argparse
import numpy as np
from tqdm import tqdm
from config import *
hc = []
def convert(gesture_folder, target_folder):
if not exists('./'+target_folder):
os.makedirs(target_folder)
gestures ... |
# Copyright (C) 2016-2017 DLR
#
# All rights reserved. This program and the accompanying materials are made
# available under the terms of the 2-Clause BSD License ("Simplified BSD
# License") which accompanies this distribution, and is available at
# https://opensource.org/licenses/BSD-2-Clause
#
# Contributors:
# Fra... |
# Launch with
#
# gunicorn -D --threads 4 -b 0.0.0.0:5000 --access-logfile server.log --timeout 60 server:app glove.6B.300d.txt bbc
from flask import Flask, render_template
from doc2vec import *
import sys
app = Flask(__name__)
@app.route("/")
def articles():
"""Show a list of article titles"""
@app.route("/ar... |
def shakehand(data):
##rest
i01.setHandSpeed("left", 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
i01.setHandSpeed("right", 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed("left", 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed("right", 1.0, 1.0, 1.0, 1.0)
i01.setHeadSpeed(1.0, 1.0)
i01.setTorsoSpeed(1.0, 1.0, 1.0)
i01.moveHead(80,... |
# third party
import pytest
# syft absolute
import syft as sy
from syft import serialize
from syft.core.node.common.service.child_node_lifecycle_service import (
RegisterChildNodeMessage,
)
@pytest.mark.slow
def test_child_node_lifecycle_message_serde() -> None:
bob_vm = sy.VirtualMachine(name="Bob")
bob... |
"""
.torrent file processing library.
This library strives to be the definitive work of art on .torrent file processing and augmentation.
"""
from .TorrentFile import TorrentFile
|
#!/usr/bin/python
# coding=UTF-8
# -*- coding: UTF-8 -*-
# This file is part of the StructureMapper algorithm.
# Please cite the authors if you find this software useful
#
# https://academic.oup.com/bioinformatics/advance-article/doi/10.1093/bioinformatics/bty086/4857361
# MIT License
#
# Copyright 2018 Anssi Nurmin... |
# This script calculcates the median LOC per repository as presented in RQ3
# Input files are generated by boxplot_cs.py & boxplot_java.py
import os
import re
import pandas as pd
from pandas.errors import EmptyDataError
### Read csv file and create pandas DataFrame
def read_file(filepath, column_list, duplicate_flag... |
import os
from datetime import datetime
from time import mktime
import feedparser
import listparser
from peewee import *
from bs4 import BeautifulSoup as bs
import favicon
db = SqliteDatabase('database.db', threadlocals=True, timeout=5000)
#db = MySQLDatabase('microreader', user = 'microreader', passwd='...', thread... |
# twitter bot coded in python to post images
# you need a developer account for this to work
import os
import time
import tweepy as tp
# important data from your account
account_key = "Put your account key here"
account_secret = "Put your account secret here"
access_token = "Put your access token here"
access_secr... |
# -*- coding: utf-8 -*-
# @Time : 2020/10/6
# @Author : Changxin Tian
# @Email : cx.tian@outlook.com
r"""
KGCN
################################################
Reference:
Hongwei Wang et al. "Knowledge graph convolution networks for recommender systems." in WWW 2019.
Reference code:
https://github.com/hww... |
from constance import config
from django.db import models, transaction, IntegrityError
from django.utils import timezone
import schools.models
import users.models
from . import main as main_models
class CheckingGroup(models.Model):
school = models.ForeignKey(
schools.models.School,
related_name='... |
#
# Copyright 2019 Xilinx 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 writing... |
#!/usr/bin/env python
# TODO(eric.cousineau): Replace with Naveen's optitrack simulator connection.
import sys
import os
import time
import lcm
sys.path.append(os.path.join(os.environ['SPARTAN_SOURCE_DIR'], 'src/optitrack'))
from optitrack import optitrack_data_descriptions_t
from optitrack import optitrack_frame_t
... |
# -*- coding: utf-8 -*-
"""Core flow direction functionality. All functions work based on the an array of
next downstream indices (idxs_ds) and mostly return indices."""
from numba import njit
from numba.typed import List
import numpy as np
from . import gis_utils
__all__ = []
_mv = np.intp(-1)
# flwdir properties... |
import model
import upload
import json
import requests
#This should be moved to a class
SESSION = None
API_KEY = None
START_IMGUR_ENDPOINT = "https://api.imgur.com/3/gallery/hot/viral/1.json"
GALLERY_IMAGE_ENDPOINT = "https://api.imgur.com/3/gallery/image/{id}"
IMAGE_ENDPOINT = "https://api.imgur.com/3/image/{id}"
GAL... |
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
import json
import logging
import os
import uuid
from c7n.config import Config
from c7n.loader import PolicyLoader
# Load resource plugins
from c7n_gcp.entry import initialize_gcp
initialize_gcp()
log = logging.getLogger('custodian.gcp.f... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 18 23:04:30 2016
@author: utkarsh
"""
# RIDGESEGMENT - Normalises fingerprint image and segments ridge region
#
# Function identifies ridge regions of a fingerprint image and returns a
# mask identifying this region. It also normalises the intesity values of
# the ima... |
# Copyright 2014 Google Inc. All Rights Reserved.
"""Command for snapshotting disks."""
from googlecloudapis.compute.v1 import compute_v1_messages as messages
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.compute.lib import base_classes
from googlecloudsdk.compute.lib import name_generator
class ... |
if __name__ == "__main__":
from gui import gui
gui.run()
|
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
result = set()
def find_values(value, idx):
nonlocal result
start = idx + 1
end = len(nums) - 1
while start < end:
rest = value + nums[start... |
#!/usr/bin/env python
from __future__ import print_function
import os
import os.path
import sys
import shutil
import subprocess
def main():
if len(sys.argv) < 2:
print('usage: empkg.py <data file>', file=sys.stderr)
sys.exit(1)
targetdir = os.path.dirname(sys.argv[1])
data = os.path.basen... |
from hypothesis import given
from tests.bind_tests.hints import (BoundOperation,
BoundSweepEvent)
from . import strategies
@given(strategies.operations, strategies.sweep_events)
def test_basic(operation: BoundOperation, event: BoundSweepEvent) -> None:
assert isinstance(operat... |
import sys
sys.path.append('../..')
import codestudio
z = codestudio.load('s1level59')
for count in range(4):
z.move(100)
z.right()
z.check()
|
"""
0966. Vowel Spellchecker
Medium
Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word.
For a given query word, the spell checker handles two categories of spelling mistakes:
Capitalization: If the query matches a word in the wordlist (case-insensitive), then the que... |
import json
import time
from bitcom.client.subscribe_client import SubscribeClient
from bitcom.constant import *
def on_wss_open(ws):
cmd = {"type": "subscribe", "instruments": ["BTC-PERPETUAL"],
"channels": ["ticker"], "interval": "raw", "token": "13c8df77-038d-451b-9460-7de6c271efd8"}
# convert... |
# -*- coding: utf-8 -*-
"""
Code for preparing raw PPMI neuroimaging data to be converted to BIDS format
with heudiconv.
"""
from os import PathLike
import pathlib
from pkg_resources import resource_filename
from typing import List, Union
import pandas as pd
try:
import docker
import nibabel as nib
impor... |
import time
from django.db import connections
from django.db.utils import OperationalError
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""Django command to pause execution untill database is availaible"""
def handle(self, *args, **options):
self.stdout.write('waiti... |
#!/usr/bin/env python
""" generated source for module LogItem """
import logging
logger = logging.getLogger('console')
class LogItem(object):
""" Basic log properties """
def __init__(self):
self.importLog = bool()
self.name = str()
self.type_ = str()
#convert to SI
... |
"""
"""
## Imports
from corona.utils import *
from corona.maths import *
from corona.model import *
from corona.plotting import *
## Params
model = SEIR2(t_intervention=100)
# Population size
nPop = 5*10**6
# Ens size
N = 20
# Time -- unit: days
t_end = 365
dt = 1
tt = linspace(0 , t_end , int(t_end/dt)+1)
date... |
import requests
import csv
import json
import sys
sys.path.append("..")
import mytemp
import re
import time
def main():
M={}
M['民航局CAAC']='402881fa2c3e722b012c3e7b56a00005'
M['华北地区管理局']='402881fa2c954d54012c954d54530000'
M['东北地区管理局']='402881fb2c965e73012c965e73e20000'
M['华东地区管理局... |
from shufflenet_v2 import (
shufflenet_v2_x0_5,
shufflenet_v2_x1_0,
shufflenet_v2_x1_5,
shufflenet_v2_x2_0,
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.