content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
# Copyright 2015 Criteo. All rights reserved.
#
# The contents of this file are 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.... |
from enum import Enum
import matplotlib as mpl
from cycler import cycler
import seaborn
#[x for x in list(rcParams.keys()) if 'font' in x or 'size' in x]
class Project(Enum):
THESIS = 1
SLIDE = 2
PAPER = 3
def cm2inch(value):
return value / 2.54
class KAOBOOK():
TEXTWIDTH = cm2inch(9)
FULLWIDT... |
from . import *
class AWS_AppStream_ImageBuilder_VpcConfig(CloudFormationProperty):
def write(self, w):
with w.block("vpc_config"):
self.property(w, "SecurityGroupIds", "security_group_ids", ListValueConverter(StringValueConverter()))
self.property(w, "SubnetIds", "subnet_ids", ListValueConverter(Str... |
from threading import Thread
import time
# IO
def music():
print('begin to listen music {}'.format(time.ctime()))
time.sleep(3)
print('stop to listen music {}'.format(time.ctime()))
def game():
print('begin to play game {}'.format(time.ctime()))
time.sleep(5)
print('stop to play game {}'.form... |
'''
Created on 15.04.2019
@author: mayers
'''
#
import os, shutil,sys
#
lib_path = os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) )
sys.path.append(lib_path)
print (lib_path)
from etc.settings import GIT_ROOT, SOURCE_DIR, GIT_BASE_DIR, TEMPLATE_DIR, LIBRARY_URL
from tkinter import filedialog
from t... |
from moai.modules.lightning.highres.highres import HighResolution
from moai.modules.lightning.highres.transition import (
StartTransition,
StageTransition
)
from moai.modules.lightning.highres.head import (
TopBranch as TopBranchHead,
AllBranches as AllBranchesHead,
Higher as HigherHead
)
__all__ =... |
from django.urls import path
from . import views
urlpatterns = [
path('add/', views.add_task, name='add_task'),
] |
#! /usr/bin/env python
# coding=utf-8
#================================================================
# Copyright (C) 2019 * Ltd. All rights reserved.
#
# Editor : VIM
# File name : demo.py
# Author : YunYang1994
# Created date: 2019-10-20 15:06:46
# Description :
#
#==========================... |
from GreedyGRASP.Solver import Solver
from GreedyGRASP.Solution import Solution
from GreedyGRASP.LocalSearch import LocalSearch
# Inherits from a parent abstract solver.
class Solver_Greedy(Solver):
def greedyFunctionCost(self, solution, remainCap, busesAssignments):
for busAssi in busesAssignments:
... |
from pathlib import Path
import json
import pandas as pd
import geopandas as gpd
from requests import Response
from shapely.geometry import Point
from utils import get_raw_data, create_folder, write_df_to_json, get_overpass_gdf, transform_dataframe
def test_get_raw_data(query_fixture):
response = get_raw_data(q... |
'''
With a starting point from train_latent_batching.py, a much more modularized generation script.
These all have no object!
'''
import sys
sys.path.append('curiosity')
sys.path.append('tfutils')
import tensorflow as tf
from curiosity.interaction import train, environment, data, cfg_generation
from curiosity.intera... |
import json
from functools import reduce
class Example(object):
"""Defines a single training or test example.
Stores each column of the example as an attribute.
"""
@classmethod
def fromJSON(cls, data, fields):
ex = cls()
obj = json.loads(data)
for key, vals in fields.ite... |
from typing import Dict
import asyncpg
async def create_pg_connection(pg_config: Dict[str, str]) -> asyncpg.Connection:
return await asyncpg.create_pool(**pg_config)
|
#!/usr/bin/python3
import os
from datetime import datetime
log_file = "/home/sysadmin/logs.txt"
backup_dir = "/home/sysadmin/backups"
time = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
php_sessions = []
for f in os.listdir('/tmp'):
if f[:5] == 'sess_':
php_sessions.append(f)
if not os.path.ex... |
# -*- coding: utf-8 -*-
__author__ = 'Brice Olivier'
import os
import scipy.io
from sea import MODWT
from sea import DATA_PATH
from .test_synchronized_eeg_trial import synchronized_eeg_trial_init
from sea import SynchronizedEEGTrial
import pytest
@pytest.fixture(scope="module")
def modwt_init():
eeg_data = scipy... |
#!/usr/bin/env python
# encoding: utf-8
#
######################################################################
## Application file name: greenhouse.py ##
## Description: A component of Ay-yahs-Greenhouse Automation System ##
## Description: Performs the primary greenhouse automation process. ##
## Descr... |
import os
import click
from mlcommons_box import parse # Do not remove (it registers schemas on import)
from mlcommons_box.common import mlbox_metadata
from mlcommons_box_ssh import ssh_metadata
from mlcommons_box_ssh.ssh_run import SSHRun
def configure_(mlbox: str, platform: str):
mlbox: mlbox_metadata.MLBox =... |
import os
from typing import Dict, List
class GlobalInputParser:
def __init__(self, command_args: Dict):
"""
Parses CLI args and environment variables for inputs that appear before the command
:param command_args: command_args is expected to be initialized using doc_opt
"""
... |
from typing import Optional
from pincer import Client, command
from pincer.objects import InteractionFlags, TextChannel
from app.bot import Bot
from app.classes.pot import Pot
CHANNEL_ID: int = 889523568298307594
MESSAGE_ID: int = 890313495030157313
class TicketCog:
"""A simple commands cog template."""
d... |
from random import randint
import random
class Player:
def __init__(self, startX = None, startY = None, startDirection = None, color = (50, 255, 50), window = None, apples = None, players = None, ki = True):
if startX == None:
startX = randint(0, 640 / 20 - 1)
if startY == None:
... |
#!/usr/bin/env python
import sys
for line in sys.stdin:
sys.stdout.write(line.lower()) |
import os
with open(os.path.join(os.path.dirname(__file__), "VERSION")) as f:
__version__ = f.read().strip()
from nics_fix_pt.consts import QuantizeMethod, RangeMethod
from nics_fix_pt.quant import *
import nics_fix_pt.nn_fix_inner
from nics_fix_pt import nn_fix
from nics_fix_pt.fix_modules import register_fix_mo... |
import adafruit_ahtx0
import adafruit_sgp40
import board
import click
import datetime
import json
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import os
import pandas as pd
import pathlib
import sys
import time
import traceback
# Setup I2C Sensor
i2c = board.I2C()
aht = adafruit_ahtx0.AHTx0(i2c)
s... |
# 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 t... |
# coding=utf-8
import itertools
import cv2
import numpy as np
class Distortion(object):
def __init__(self):
# K - Intrinsic camera matrix for the raw (distorted) images.
camera_matrix = [
305.5718893575089, 0, 303.0797142544728,
0, 308.8338858195428, 231.8845403702499,
... |
import nmslib
import numpy as np
def search(system_parameters, DB_features, query_features):
####################################################
# input->system_parameters:システムのパラメータ
# DB_features:DB内の画像をベクトル変換したリスト
# query_features:クエリ内の画像をベクトル変換したリスト
# output->result:re... |
confluence_space_name = 'DEMO'
confluence_space_home_page_name = 'DEMO Home'
confluence_name_of_root_directory = 'Atomic Threat Coverage'
md_name_of_root_directory = 'Atomic_Threat_Coverage'
list_of_detection_rules_directories = ['../detectionrules']
list_of_triggering_directories = ['../atomics']
confluence_rest_api_u... |
# https://wiki.xxiivv.com/site/varvara.html
# https://wiki.xxiivv.com/site/uxntal.html
# https://wiki.xxiivv.com/site/uxntal_cheatsheet.html
# https://wiki.xxiivv.com/site/uxntal_reference.html
# https://wiki.xxiivv.com/site/uxntal_stacking.html
# https://wiki.xxiivv.com/site/uxntal_macros.html
from rich.console impo... |
# -*- coding: utf-8 -*-
"""Module for parsing ISA-Tab files."""
# Make all models and the ``*Reader`` classes visible within this module.
from .headers import * # noqa: F403, F401
from .models import * # noqa: F403, F401
from .parse_assay_study import ( # noqa: F401
AssayReader,
AssayRowReader,
StudyRe... |
import re
from icon_validator.rules.validator import KomandPluginValidator
from icon_validator.exceptions import ValidationException
class HelpValidator(KomandPluginValidator):
taskExist = False
HELP_HEADERS_LIST = [
"# Description",
"# Key Features",
"# Requirements",
"# Doc... |
from bs4 import BeautifulSoup
import csv
import io
import pandas as pd
import re
from datetime import date
from datetime import datetime
import requests
from colorama import Back, Fore, Style
# With this function I make the webscrapping I need to extract the data from the tarifaluzahora website
def scrapping (tarifa, ... |
"""This declares the protocol routing for Ghostwriter."""
# Django & Other 3rd Party Libraries
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
# Ghostwriter Libraries
import ghostwriter.home.routing
import ghostwriter.oplog.routing
application = ProtocolTypeRo... |
from moonleap.session import get_session
def _get_extended_scope_names(root_block):
scope_names = []
for block in root_block.get_blocks(include_children=True):
for scope_name in block.scope_names:
if scope_name not in scope_names:
scope_names.append(scope_name)
return s... |
#!/usr/bin/python
import sys
from lxml import html
card = ''; expectUserResponse = False
tree = html.fromstring(sys.stdin.read())
speech = html.tostring(tree.xpath('//speak')[0])
subtree = tree.xpath('//body/p')
try:
card = subtree[0].xpath('string()')
if subtree[1].xpath('string()') == "False":
expe... |
# -*- coding: utf-8 -*-
"""
Function: Transform the four corners of the bounding box from one frame to another.
@author: Wenbo Zhang
"""
import numpy as np
from skimage import transform as tf
def applyGeometricTransformation(startXs, startYs, newXs, newYs, bbox):
# (INPUT) startXs: N × F matrix... |
import wx
import re
import os, os.path
import cPickle as pickle
# directory containing parsed opinions
OPINION_PATH = r"C:\Users\Daniel\Dropbox\Class_Files\CBH_301\Word_Cloud\supreme_court_opinions\test_output\test_opinions"
PICKLE_PATH = r"C:\Users\Daniel\Dropbox\Class_Files\CBH_301\Word_Cloud\supreme_court_opinions... |
import numpy as np
import astropy.units as u
import astropy.constants as const
from .optic import Optic
class Cutoff_Filter(Optic):
def __init__(self, name, cutoff_freq, absorption, temperature,
spill, spill_temperature):
self.cutoff = cutoff_freq
self.absorption = self._init_v... |
# Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
import logging
from typing import List, Optional, Set, Tuple
from copr.v3 import CoprRequestException
from ogr.abstract import GitProject
from ogr.parsing import parse_git_repo
from ogr.services.github import GithubProject
from packit.conf... |
"""Introduce several additons to `pygame gui
<https://pygame-gui.readthedocs.io/en/latest/>`_.
A toggle button, which is the same as a
:class:`UIButton <pygame_gui.elements.UIButton>` with additonal
settings. It stores a boolean value that remember which state the button is.
Event:
UI_TOGGLEBUTTON_TOGGLED
............ |
#
# Copyright (c) 2021 Blickfeld GmbH.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE.md file in the root directory of this source tree.
from __future__ import print_function
import argparse
from blickfeld_scanner import scanner
import numpy as np
from time ... |
################################################################################
# These computations are based off of Bernd Schober's notes for chart 66 in
# August.
# Maglione, August 2019
######################################################################... |
import sys
import pathlib
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import alpha_vantage
import plot_style
def show_frontier(symbol1, symbol2, interval='MONTHLY'):
returns1 = alpha_vantage.get_stock_returns_history(symbol1, interval)
returns2 = alpha_vantage.get_stock_returns_histo... |
import FWCore.ParameterSet.Config as cms
# -*-TCL-*-
#seqs/mods to make MuIsoDeposits
from RecoMuon.MuonIsolationProducers.muIsoDeposits_cff import *
# sequences suggested for reco (only isoDeposits are produced at this point)
muIsolation_muons = cms.Sequence(muIsoDeposits_muons)
muIsolation_ParamGlobalMuons = cms.Se... |
import discord
from discord.ext import commands
import calendar
import datetime
class Leader(commands.Cog):
def __init__(self, bot):
self.bot= bot
async def create_queue(self):
await self.bot.SQL.connect()
gymList = (await self.bot.SQL.fetch_all_list((await self.bot.SQL.query("SELECT ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pytorch_lightning.callbacks import Callback
class ExceptionCallback(Callback):
def on_exception(trainer, litmodel, exception):
print("saving checkpoints by Exception")
# TODO:save checkpoint
raise exception
|
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from label_label import label_top_disabled
from app import app
import dash
from HandlerWrapper import handler
from tools.serial.tools.list_ports import comports
import time
# from HandlerWrapper im... |
# Author: Laura Kulowski
'''
Create a r-theta grid, using Chebyshev points for r and Gauss-Legendre points for theta.
Define the Chebyshev and Gauss-Legendre weights for integration using quadrature rules
Define the Chebyshev differentiation matrix for taking derivatives on the r-grid.
Define the Legendre polynomial... |
from celery.utils.log import get_task_logger
from applications.async_update.celery import app
from applications.feed.service import (
update_feeds, get_feeds_for_update
)
from applications.subscription.service import (
update_subscriptions,
get_subscriptions_for_update
)
logger = get_task_logger(__name__... |
# -*- coding: utf-8 -*-
from rest_framework.serializers import *
from Data.models import *
class IPaddressSerializer(ModelSerializer):
class Meta(object):
model = IPaddressModel
fields = '__all__'
class PortSerializer(Serializer):
id = IntegerField()
ipid = IntegerField()
port = In... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020 Huawei Device Co., 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
... |
import numpy as np
import time
from numba import jit, prange
import matplotlib.pyplot as plt
from ..util import f_SRM, h_exp_update, h_erlang_update
def ASA1(
time_end,
dt,
Lambda,
Gamma,
c=1,
Delta=1,
theta=0,
interaction=0,
lambda_kappa=20,
base_I=0,
I_ext_time=0,
I_... |
#!/usr/bin/env python
# vim: noet sw=4 ts=4
import sys
import os
import argparse
import re
try:
from version import Verstion
except:
Version = '0.0.0rc0'
class KmRedact( object ):
def __init__( self ):
self._init_ip_hiding()
self._init_dns_hiding()
self._init_port_hiding()
self._init_email_hiding()
pas... |
import numpy as np
class SpectScaler:
"""class that scales spectrograms that all have the
same number of frequency bins. Any input spectrogram
will be scaled by subtracting off the mean of each
frequency bin from the 'fit' set of spectrograms, and
then dividing by the standard deviation of each
... |
import numpy as np
import cv2 as cv
import glob
def unsharp_mask(img, blur_size = (9,9), imgWeight = 1.5, gaussianWeight = -0.5):
gaussian = cv.GaussianBlur(img, (5,5), 0)
return cv.addWeighted(img, imgWeight, gaussian, gaussianWeight, 0)
for opt in ["capsule"]:
for name in glob.glob("./train/"+opt+"... |
#!/usr/bin/env python
"""Create a combined notebook. The first path is the assignment notebook.
Remaining paths are student notebooks.
"""
import argparse
import logging
import os
import sys
import nbformat
import nbformat.reader
import nbcollate as nbc
from minimalkeys import minimal_keys
from . import nbcollate
... |
while True:
n = int(input('Quer ver a tabuada de qual número: '))
print('=+=' * 5)
if n < 0:
break
for c in range(1, 11):
print(f'{n} x {c:2} = {n*c:2}')
print('=+=' * 5)
print('PROGRAMA TABUADA ENCERRADO. VOLTE SEMPRE.')
|
#-*- coding: UTF-8 -*-
import json
import datetime
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema
from sqlalchemy import *
from sqlalchemy.types import *
from sqlalchemy.orm import *
from ..engine.db import Base
class City(Base):
__table_args__ = { 'schema': 'mente' }
__tablename__ = 'city_info'
... |
"""
Given:
an sqlite database containing stackoverflow data as constructed by stackoverflow_to_sqlite.py
Construct:
a text file with one error message per line
"""
import re
import json
import sqlite3
import argparse
import collections
GOLANG_PATTERN = re.compile(r'(([^:]*\.go)\:(\d+)([^\d][^ ]*)?\:\ )(.*)')
de... |
import pandas as pd
# Type hinting
from typing import Tuple
def df_difference(a: pd.DataFrame, b: pd.DataFrame) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
"""Compute the difference of two DataFrames as sets.
Parameters:
a : First DataFrame
b : Second DataFrame
Returns:
... |
from fabric.api import *
from config import *
local('mysql -h %s -u %s -p%s %s' % (RDS_HOST, RDS_NAME, RDS_PASS, RDS_DB))
|
from typing import List
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms
class NNPolicy(nn.Module):
def __init__(self, input_dim, hidden_layers, output_dim, discrete):
super(NNPolicy, self).__init__()
layers = [nn.Linear(input_... |
# Generated by Django 4.0.2 on 2022-02-21 17:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('reviewApp', '0008_artist_background_image'),
]
operations = [
migrations.AlterField(
model_name='artist',
name='back... |
#********************************************************************************
#--------------------------------------------------------------------------------
#
# Significance Labs
# Brooklyn, NYC
#
# Author: Alexandra Berke (aberke)
# Written: Summer 2014
#
#
# /backstage/backstage.py
#
#
#--------------------... |
'''
Created on 9 Dec 2012
@author: kreczko
'''
from optparse import OptionParser
from rootpy.io import File
from array import array
from config.variable_binning import bin_edges
from tools.Unfolding import Unfolding
from tools.hist_utilities import hist_to_value_error_tuplelist
from tools.file_utilities import write_d... |
from PIL import Image
from predict import prediction
from preprocess_v3 import gen_images
### begin networking by xmcp
import getpass
import requests
import time
import io
import random
ELECTIVE_XH = input('学号:')
ELECTIVE_PW = getpass.getpass('密码:')
DELAY_S_MIN = 1.5
DELAY_S_DELTA = 1.5
adapter = requests.adapters.... |
"""
Base settings to build other settings files upon.
"""
import os
from django.urls import reverse_lazy
from decouple import config
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Quick-start developme... |
import corner
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import mod_temperature
import defaultparams.uconv as uconv
import defaultparams.cosmology as cosmo
import scipy
from mod_gasdensity import *
from mod_mass import *
'''
Plotting functions
'''
def seplog(n):
'''
For a floa... |
import os
max_connection_retires = int(os.environ.get("MF_SERVICE_CONNECTION_RETRIES", 3))
connection_retry_wait_time_seconds = int(os.environ.get("MF_SERVICE_CONNECTION_RETRY_WAITTIME_SECONDS", 1))
max_startup_retries = int(os.environ.get("MF_SERVICE_STARTUP_RETRIES", 5))
startup_retry_wait_time_seconds = int(os.envi... |
# Generated by Django 3.0.7 on 2020-06-12 08:27
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('references', '0002_auto_... |
# coding: utf-8
"""
Definition of CLI commands.
"""
import json
import logging
from os import path
from traceback import format_exc
from time import sleep
import click
from click.types import StringParamType
import docker
from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport
import yaml
... |
import gym
import torch
from torch import nn
from torch import optim
from torch.nn import functional as F
from torch.utils.data import TensorDataset, DataLoader
from torch import optim
import numpy as np
import copy
import babyai.utils as utils
from babyai.rl import DictList
from babyai.model import ACModel
import mul... |
# pylint:disable=unused-variable
# pylint:disable=unused-argument
# pylint:disable=redefined-outer-name
import json
import random
from typing import Any, Callable, Dict, Iterator, List
import httpx
import pytest
import sqlalchemy as sa
from _dask_helpers import DaskGatewayServer
from _pytest.monkeypatch import Monkey... |
"""
This part of code is the DQN brain, which is a brain of the agent.
All decisions are made in here.
Using Tensorflow to build the neural network.
View more on my tutorial page: https://morvanzhou.github.io/tutorials/
Using:
Tensorflow: 1.0
gym: 0.7.3
"""
import numpy as np
import pandas as pd
import tensorflow as... |
# python Python.py
from math import sin, pi
def composite_simpsons(f, a, b, n):
step_size = (b - a) / n
integral = 0
for k in range(1, n + 1):
x_k0 = a + step_size * k
x_k1 = a + step_size * (k - 1)
step = step_size / 6 * (f(x_k0) + f(x_k1) + 4 * f((x_k0 + x_k1) / 2))
int... |
def get(name):
return {}
def getMergedConf(name):
return {}
|
#!/usr/bin/env python3
import sys
def left(dx,dy):
if (dx,dy) == (1,0):
return (0,1)
elif (dx,dy) == (0,1):
return (-1,0)
elif (dx,dy) == (-1,0):
return (0,-1)
else:
return (1,0)
def main(args):
# nubs = [s.strip() for s in sys.stdin]
x = 0
y = 0
n = 1
... |
import json
import os
import tempfile
import datetime
import config
import pyorc
from dateutil import parser
from kafka import KafkaProducer
from hdfs import HdfsError, InsecureClient
from repository.interface import BaseRepository
from repository.singleton import singleton
KST = datetime.timezone(datetime.timedelt... |
from .base_installer import FlaskExtInstaller
from ..config import TAB
class FlaskTalismanInstaller(FlaskExtInstaller):
package_name = "Flask-Talisman"
imports = ["from flask_talisman import Talisman"]
inits = ["talisman = Talisman()"]
attachments = [
'force_https = True if app.config.get("ENV... |
from pathlib import Path
from os import path
# __file__ = "./__init__.py"
THIS_DIR = Path(path.dirname(path.abspath(__file__)))
PROJECT_DIR = THIS_DIR.parent.parent
DATA_DIR = PROJECT_DIR / "data"
|
import json
AUDIT_FILENAME = "apic-pipeline-audit.json"
FILE_NAME = "print_audit.py"
INFO = "[INFO]["+ FILE_NAME +"] - "
WORKING_DIR_BASIC = "../WORKSPACE"
def orchestrate():
try:
with open(WORKING_DIR_BASIC + "/" + AUDIT_FILENAME,'r') as f:
data = f.read()
data_json = json.loads(data)
... |
# pyramid
from pyramid.view import view_config
from pyramid.renderers import render_to_response
from pyramid.httpexceptions import HTTPNotFound
from pyramid.httpexceptions import HTTPSeeOther
# stdlib
# pypi
from six.moves.urllib.parse import quote_plus
# localapp
from ..lib import formhandling
from ..lib.docs impor... |
# Copyright (c) 2013 Rackspace Hosting, 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 ... |
#!/usr/bin/env casarun
""".. _Archive_Pipeline-api:
**Archive_Pipeline** --- Produces standard JAO ADMIT pipeline products for spectral line plus continuum images.
===========================================================
Example Usage:
admit_recipe Archive_Pipeline Spectral-Cube Continuum-Image
... |
'''
BMC HMM Router
'''
from Products.ZenUtils.Ext import DirectRouter, DirectResponse
from Products import Zuul
class bmcRouter(DirectRouter):
'''
BMC Router
'''
def _getFacade(self):
'''
getfacade
'''
# The parameter in the next line - myAppAdapter -... |
import tkinter
from tkinter import *
import tkinter.font as font
gui = Tk(className='Python Examples - Button') #initalises
gui.geometry("500x200") #sets the dimensions
gui.title("CODE::D") #title of window
myFont = font.Font(family='Helvetica', size=50, weight='bold') #define font
##################... |
class MultiSegmentGrid(Element,IDisposable):
"""
This element acts as a multi-segmented Grid. The individual grids associated to
the MultiSegmentGrid behave as a single unit and all share the same text. They inherit
their type (GridType) from the MultiSegmentGrid.
"""
@staticmethod
def AreGridsInS... |
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route('/')
def hello():
return render_template('student.html')
@app.route('/<name>')
def hello_name(name):
return "Hello {}!".format(name)
@app.route('/about/')
def about_page():
return render_template('about.html... |
"""Test the example calculator CLI binary."""
from subprocess import run
from typing import List
import pytest
from hypothesis import given
from hypothesis import strategies
from mylittleci.lib import simplemath
def test_calculator_binary(capfd: pytest.Class) -> None:
"""Add numbers together using binary and as... |
from django.shortcuts import render
from validator.models import Settings
def home(request):
return render(request, 'validator/index.html', {'news_text': Settings.load().news})
def alpha(request):
return render(request, 'validator/alpha.html')
def terms(request):
return render(request, 'validator/terms.... |
import re
import os
import shutil
import time
from datetime import datetime, timedelta
from gppylib.db import dbconn
from test.behave_utils.utils import check_schema_exists, check_table_exists, drop_table_if_exists
from behave import given, when, then
CREATE_MULTI_PARTITION_TABLE_SQL = """
CREATE TABLE %s.%s (trans_id... |
n,m=map(int,input().split());a=set(int(i) for i in input().split());b=set(int(i) for i in input().split());a-=b
r=str(len(a));a=list(a);a.sort()
if a!=[]:
r+='\n'
for i in a:
r+=str(i)+' '
print(r)
|
import os
from yaml import dump
from cfg import Opts
def test_default_args():
Opts.reset()
Opts.add_int('a', 1, 'a value')
opt = Opts()
assert opt.a == 1
opt.b = 2
assert opt['b'] == 2
data = opt.dumps()
assert data['b'] == 2
data1 = opt.dumps()
opt.loads(data, update=Fal... |
from torch import nn
from torch.nn import Sequential
from torch import zeros, unsqueeze
from hw_asr.base import BaseModel
class SimpleRnnModel(BaseModel):
def __init__(self, n_feats, n_class, fc_hidden=512, n_layers=2, dropout=0.25, *args, **kwargs):
super().__init__(n_feats, n_class, *args, **kwargs)
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import unittest
import json
from subprocess import Popen, PIPE
class TestArion(unittest.TestCase):
ARION_PATH = '../../build/arion'
# Images for general purpose testing (leave off file:// for testing)
IMAGE_1_PATH = '../../examples/images/image-1.jpg'
... |
#!/usr/bin/env python
#
# Copyright (c) 2015 Intel Corporation.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of works must retain the original copyright notice, this
# list of conditions and t... |
#!/usr/bin/env python
# Copyright 2015-present Samsung Electronics Co., Ltd. and other contributors
#
# 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/LIC... |
from dango import dcog, Cog
from .cmds import SubModule # noqa pylint: disable=unused-import
@dcog()
class InModule(Cog):
def __init__(self, config):
pass
|
from matplotlib.pyplot import axes
import pandas as pd
from fbprophet import Prophet
from pandas.core.frame import DataFrame
raw_data = pd.read_csv('./rawdata/student.csv', encoding='CP949')
raw_data = raw_data.fillna(0)
data = pd.DataFrame(raw_data.sum()) # 유학생 데이터
print(data.head(10))
all_data = pd.read_csv('./d... |
from Layer import *
class Cursor(Render):
def __init__(self, img, buttons):
self.img = pygame.image.load(img).convert_alpha()
self.location = buttons[0].location - Vector2(50, -30)
self.buttons = buttons
self.sounds = Sound()
self.point_to = 0
def move(self,... |
from torch import nn
class DPNet(nn.Module):
def __init__(
self, image_channels: int = 1, common_channels: int = 9, final_channel: int = 3
):
super().__init__()
self.conv1 = self._build_conv1(
in_channels=image_channels, out_channels=common_channels, kernel_size=3
)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.