content stringlengths 5 1.05M |
|---|
print('sub')
|
def crear_usuario(n,a,e=5): # el valor por default omite el elemento, la asignacion no debe tener espacios
return {
'nombre': n,
'apellido':a,
'nombre_completo': "{} {}".format(n,a),
'edad': e
}
codi = crear_usuario(n="David",a="Lares") # al identificarlo no hay pele (sin import... |
#!/usr/bin/env python
from collections import defaultdict
sample = """NNCB
CH -> B
HH -> N
CB -> H
NH -> C
HB -> C
HC -> B
HN -> C
NN -> C
BH -> H
NC -> B
NB -> B
BN -> B
BB -> N
BC -> B
CC -> N
CN -> C"""
def parse(data):
template, rest = data.split("\n\n")
formula = {i[:2]: i[-1] for i in rest.split("\n"... |
from enum import Enum
class TestSessionState(Enum):
"""An enumeration describing the possible states of a :class:`.TestSession`."""
IDLE = 1
"""The :class:`.TestSession` is idle and not running.
Configuration changes can occur during this state.
"""
RUNNING = 2
"""The :class:`.TestSessi... |
import os
import sys
import cv2
import numpy as np
from IPython import embed
from PIL import Image
from random import randint
from scipy import ndimage
import matplotlib.pylab as plt
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
size = (192, 256)
# BGR MODE
mean = ... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
#!/usr/bin/env python
# Copyright 2020 The Amber 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 requi... |
import os
import time
import torch
# --- Data ---
TARGET = ['Meara', 'BarChartLit'][0]
SEC = 1
# DATASET_NAME = "{} ({} sec)".format(TARGET, SEC)
DATASET_NAME = "confusion"
PATH_TO_DATASET = os.path.join("dataset", DATASET_NAME)
PATH_TO_SEQS = os.path.join(PATH_TO_DATASET, "sequences")
MAX_SEQ_LEN = 150
TRUNCATION_S... |
"""Contains functions dealing with geolocation. This is mostly used for finding
coordinates from Slippy Map tiles and vice versa. Slippy Map tiles are used in
aerial imagery APIs.
For more information (and for the source of some of these functions) see
https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
"""
impo... |
from django.contrib import admin
from site_settings.models import SiteSettings
class SingletonModelAdmin(admin.ModelAdmin):
"""Prevent deletion or adding rows"""
actions = None
def has_add_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
@ad... |
import logging as lg
import random
import string
import warnings
from typing import List, Tuple
import geopandas as gpd
import networkx as nx
import numpy as np
import pandas as pd
from shapely.geometry import LineString, Point
from .utilities import log
def great_circle_vec(lat1: float,
lng1: ... |
import json
import os
import time
import uuid
from google.appengine.api import urlfetch
from google.appengine.ext import ndb
from models.profile import Profile, TeeShirtSize
def getUserId(user, id_type="email"):
"""
Retrieve User id from a given user object
:param user: A current user object from API en... |
#coding:utf-8
import json as Json
from flask import Response,make_response
from mantis.fundamental.errors import ErrorDefs,ValueEntry
SUCC = 0
ERROR = 1
class CallReturn(object):
def __init__(self,status=SUCC,errcode=0,errmsg='',result=None):
self.status = status
self.errcode = errcode
s... |
#!/usr/bin/env python
#
# Copyright 2020 Autodesk
#
# 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 ... |
import jaydebeapi
dirver = 'org.h2.Driver'
url = 'jdbc:h2:tcp://192.168.0.242:9101/~/ship5'
username = 'sa'
password = ''
jar = 'D:\development\h2gis-standalone\h2gis-dist-1.5.0.jar'
conn = jaydebeapi.connect(dirver, url, [username, password], jar)
curs = conn.cursor()
LINESTRING="LINESTRING(123.85507399897297 36.356... |
stations = [
# Stations and lines, etc... used in exploring the NYC Penn Station
# object network.
#https://www.openstreetmap.org/node/895371274
#https://www.openstreetmap.org/relation/1359387
#https://www.openstreetmap.org/relation/1377996
#https://www.openstreetmap.org/relation/1377998
#ht... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
def l1_loss(predictions, targets):
total_elements = (tf.shape(targets)[0] * tf.shape(targets)[1] * tf.shape(targets)[2]
* tf.shape(targets)[3])
total_elements = tf.to_float(t... |
from django.urls import path
from .views import *
urlpatterns = [
path('simple', SimpleOrderView.as_view()),
path('simple/<str:order_id>', SimpleOrderView.as_view()),
path('pintuan/<str:action>', PinTuanOrderView.as_view()),
path('pay/notify', pay_notify),
]
|
import os, csv
from google.cloud import storage
from google.cloud import bigquery
from google.cloud.bigquery import LoadJobConfig
from google.cloud.bigquery import SchemaField
import googleapiclient.discovery
#########################
#########################
##### CLOUD STORAGE #####
#########################
#####... |
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from werkzeug.local import LocalProxy
def get_expected_pathname():
global db_directory
from app.data.get_time import get_date
print ('NAME: path get {}'.form... |
import argparse
import os
import sys
import midi
from time import time
from create_pickle import log_replace
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "src"))
from beatsearch.rhythmcorpus import RhythmCorpus
from beatsearch.utils import print_progress_bar, get_default_beatsearch_rhythms_... |
from __future__ import unicode_literals
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
def get_secure_cache_opts():
if hasattr(settings, 'DJANGO_REDIS_SECURE_CACHE_NAME'):
cache_name = settings.DJANGO_REDIS_SECURE_CACHE_NAME
else:
cache_name = 'defaul... |
special.eval_chebyt(n, x) |
from logger.Logger import Logger
from MorseCoder import MorseCoder
from Utils import Utils
class Main:
__logger = Logger()
def __init__(self):
self.__logger.clear_logs()
def __get_next_command(self):
legal_commands = {
"encode": ["encode", "1"],
"decode": ["decode... |
#!/usr/bin/env python
# Copyright 2016-2021 Biomedical Imaging Group Rotterdam, Departments of
# Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... |
import sys
import sip
from PyQt4 import QtGui, QtCore
from epubcreator.gui import main_window
from epubcreator import config, version
if __name__ == "__main__":
# Necesito llamar a este método porque sino pyqt crashea cuando se cierra python (al menos en windows).
# No crashea siempre, sino que lo hace bajo ... |
'''
Using freeforexapi.com API to get some basic
currency-conversion pairings in real-time.
'''
from urllib.request import urlopen
import json
'''
List of all possible currency pairings
available on this API.
'''
def get_api_key():
with open('keys.json','r') as keys:
data = json.load(keys)
... |
from .client import qBittorrentClient
|
from __future__ import division
from albumentations.core.utils import DataProcessor
import numpy as np
__all__ = [
"normalize_bbox",
"denormalize_bbox",
"normalize_bboxes",
"denormalize_bboxes",
"calculate_bbox_area",
"filter_bboxes_by_visibility",
"convert_bbox_to_albumentations",
"co... |
__all__ = [
"LaMetricManager", "SimpleFrame", "GoalFrame", "SpikeChart",
"Sound", "Model", "CloudSession", "LocalSession"
]
from .lmnotify import LaMetricManager
from .models import SimpleFrame, GoalFrame, SpikeChart, Sound, Model
from .session import CloudSession, LocalSession
|
#!/usr/bin/env python
import sys
import numpy as np
import cv2
print sys.argv[1]
img = cv2.imread(sys.argv[1],0)
img1 = cv2.imread(sys.argv[1],0)
numnonzerorows = (img !=0).sum(1)
zeroindexvec = np.where(numnonzerorows == 0)[0]
img = np.delete(img,zeroindexvec, axis=0)
img = img.transpose()
numnonzerorows = (img !... |
#encoding: utf-8
import time
import json
import random
import requests
ua_list = [
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1',
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0',
'Mozilla/4.0 (compatible; MSIE 8.0; W... |
"""
SMT-based Model Checking Module for RS with Concentrations and Context Automaton
"""
from z3 import *
from time import time
from sys import stdout
from itertools import chain
import resource
from colour import *
from logics import rsLTL_Encoder
from logics import ParamConstr_Encoder
from rs.reaction_system_with_... |
#Program to count no. of vowels in the string
def main():
x=input("Enter a string")
b={'a','e','i','o','u'}
for i in b:
y=x.count(i);
if(y>0):
print(i,"present",y,"times")
if __name__=='__main__':
main()
|
# Copyright 2018 ETH Zurich
#
# 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, sof... |
#!/usr/bin/env python
import torch
from torch.utils.data.dataset import Dataset
# Wrapper class to return only subset of samples of original dataset
class MaskedDataset(Dataset):
def __init__(self, dataset, mask=None):
self.dataset = dataset
if mask is not None:
self.mask = mask.byte()
if len(se... |
import vtk
import numpy as np
from netCDF4 import Dataset
import sys
sys.path.append('../framework/')
import framework
#********************* CODE SPECIFIC TO DEMO ********************************
#Data transfer object
class DTO:
def SetData(self,data):
self.Data=data
def GetData(self):
... |
import configargparse
import torch
import torch.optim as optim
from environments import CartPoleRegulatorEnv
from environments import CartEnv
from environments import AcrobotEnv
from models.agents import NFQAgent
from models.networks import NFQNetwork, ContrastiveNFQNetwork, ContrastiveLinearModel
# from simulated_fq... |
b = 10; c = 20;
a=b+c;
print(a) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 2 21:37:34 2020
@author: Weifan Chen , Diala @ Boston Univeristy
A fast demo on the guided induction decision tree.
similarity matrix meaning, for m_ij
is the similarity score between class i and j (so the matrix is symmetric)
if i and j are the ... |
# -*- coding: utf-8 -*-
"""Run a python file within your Django app environment.
Example:
python manage.py run script.py
You can also pass arguments to the file using the following syntax:
python manage.py run script.py:"some_argument --another-argument=something"
"""
import runpy
import sys
import operator
f... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import Business, Community, Resident
from django.contrib.auth.decorators import login_required
from .forms import NewBusinessForm, NewCommunityForm, NewComment... |
#!/usr/bin/python3
DATABASE_NAME = 'epytodo'
DATABASE_HOST = 'localhost'
DATABASE_SOCK = '/var/lib/mysql/mysql.sock'
DATABASE_USER = 'lucas'
DATABASE_PASS = 'secretpass' |
def FeatureExtractor(framework='keras', net='VGG16', layer='default', weights='imagenet', size=None, cuda=False, config=None):
if config is not None:
framework = config.features.framework
net = config.features.net
weights = config.features.weights
cuda = config.gpu
if framework == 'keras' or framew... |
from src.tindeq import TindeqProgressor
from src.analysis import analyse_data
import time
import numpy as np
import asyncio
import tornado
from bokeh.server.server import Server
from bokeh.application import Application
from bokeh.application.handlers.function import FunctionHandler
from bokeh.plotting import figure, ... |
import numpy as np
import pandas as pd
from sklearn.base import TransformerMixin
fare_mean = None
class FareFiller(TransformerMixin):
def transform(self, features_raw, **transform_params):
features = features_raw.copy(deep=True)
global fare_mean
if fare_mean is None:
fare_mea... |
"""
Catching and handling exceptions demo
"""
import sys
while True:
line = sys.stdin.readline()
if line == "": break
try:
(x, y) = [int(n) for n in line.split()]
print "%d + %d = %d" % (x, y, x + y)
print "%d / %d = %d" % (x, y, x / y)
except ValueError as e:
print "... |
#
# 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... |
from .core import Node, HasInput, HasOutput, Output
class If(Node, HasInput, HasOutput):
def __init__(self, *args, **kwargs):
super(If, self).__init__(*args, **kwargs)
self._test = kwargs.get('test')
if not self._test:
raise ValueError('test not specified')
elif not hasa... |
import streamlit as st
from streamlit_drawable_canvas import st_canvas
import pandas as pd
from PIL import Image
from helpers import calculate_homography, apply_homography_to_image, line_intersect, get_si_from_coords
from pitch import FootballPitch
from itertools import product
st.set_option('deprecation.showfileUploa... |
import logging
from ibmsecurity.utilities import tools
logger = logging.getLogger(__name__)
uri = "/isam/dsc/config"
requires_modules = None
requires_version = None
requires_model = "Docker"
def get(isamAppliance, check_mode=False, force=False):
"""
Retrieve the current distributed session cache policy
... |
import copy
import random
import keras
import numpy as np
from keras2vec.encoder import Encoder
# TODO: Implement as a keras.utils.Sequence class
class DataGenerator(keras.utils.Sequence):
"""The DataGenerator class is used to encode documents and generate training/testing
data for a Keras2Vec instance. Curr... |
import csv
# csvfile 可以是具有 write() 方法的任何对象,如果 csvfile 是文件对象,则使用 newline='' 打开
with open('test.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['id', 'name', 'age'])
# writer.writerow(['1001', '张三', '222'])
# 写入多行
data = [('1001', '张三', '21'), ('1002', '李四', '31')]
... |
""" Temporary directory fixtures
"""
from __future__ import absolute_import
import os
import tempfile
import shutil
import logging
import subprocess
try:
from path import Path
except ImportError:
from path import path as Path
import pytest
from six import string_types
from . import cmdline
log = logging.get... |
from numba import types
from numba.core import cgutils
from numba.core.typing.arraydecl import get_array_index_type
from numba.extending import lower_builtin, type_callable
from numba.np.arrayobj import make_array, normalize_indices, basic_indexing
__all__ = ["atomic_add", "atomic_sub", "atomic_max", "atomic_min"]
d... |
from pydoc import classname
import dash_bootstrap_components as dbc
from dash import dcc, html
import globals
from datetime import date
from dash_extensions.enrich import Input, Output, State, ServersideOutput, dcc
def sidebar():
sidebar = html.Div(
children=[
dbc.Row(
dbc.Lab... |
#!/usr/bin/env python
import unittest
import lief
import tempfile
import sys
import subprocess
import stat
import os
import logging
import random
import itertools
from lief import Logger
Logger.set_level(lief.LOGGING_LEVEL.WARNING)
from unittest import TestCase
from utils import get_sample
class TestBuilder(TestCas... |
import unittest
from overtime.components.digraphs import TemporalDiGraph
from overtime.algorithms.paths.optimality import *
class OptimalityTest(unittest.TestCase):
"""
Tests functions which find optimal path metrics in temporal directed graphs.
"""
def setUp(self):
"""
Create a graph... |
import compas
from compas.datastructures import Mesh
from compas_plotters import MeshPlotter
mesh = Mesh.from_obj(compas.get('faces.obj'))
plotter = MeshPlotter(mesh, figsize=(12, 7.5))
plotter.draw_vertices(text={vertex: str(mesh.vertex_degree(vertex)) for vertex in mesh.vertices()}, radius=0.2)
plotter.draw_faces()... |
import os
from datetime import datetime
import time
import subprocess
LAST_CHANNEL = float("inf")
def get_bully_attack_list(d, victim):
l = {}
for channel in d[victim]["channels"]:
if not channel in l:
l[channel] = []
for bssid in d[victim]["channels"][channel]:
l[chan... |
import pyqtgraph as pg
import os
import numpy as np
path = os.path.dirname(os.path.abspath(__file__))
uiFile = os.path.join(path, '../ui/ecg_summary.ui')
ECGSummaryView, TemplateBaseClass = pg.Qt.loadUiType(uiFile)
class ECGSummaryWidget(TemplateBaseClass):
def __init__(self, ecg, raw):
TemplateBaseClas... |
__version__ = "3.2.7" |
from flask import Flask, render_template
from flask_restful import Api, Resource, reqparse, marshal_with, fields
from pymongo import MongoClient
from pymongo.database import Database
from pymongo.collection import Collection
from bson.objectid import ObjectId
from hashlib import md5
import os
app = Flask(__name__)
app... |
# Copyright 2018 The Bazel 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 la... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module description
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A special text formatter.
Compatibility
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- Python2: Yes
- Python3: Yes
Prerequisites
~~... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Season'
db.create_table(u'prescription_season', (
(u'id', self.gf('django.db.mod... |
import sys
import argparse
import os
import tempfile
from os.path import join, basename, isfile, splitext, isdir
from collections import OrderedDict
import torch
from rastervision.pipeline.file_system.utils import (
sync_to_dir, make_dir, get_local_path)
from rastervision.aws_s3.s3_file_system import S3FileSystem
... |
# coding=utf-8
# Copyright 2022 GradMax Authors.
#
# 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 ag... |
from django.contrib.admin import ModelAdmin, register
from .models import Worker, Department, Director, OrderedWorker, EducationOffice, GeneralOffice
@register(Worker)
class WorkerAdmin(ModelAdmin):
pass
@register(Department)
class DepartmentAdmin(ModelAdmin):
pass
@register(Director)
class DirectorAdmin... |
##
## Here we consider the function PL(d) = PL(d0) + 10*n*log(d/d0) -> y = theta0 + theta1*(10*log(d/d0))
## and we want to estimate the PL(d0) a constant and "n"
##
import numpy as np
from numpy.linalg import pinv
from numpy import dot
import math
from threading import Lock
import os
import glob
class RSSIKalmanFil... |
__author__ = 'Robin Cole'
__version__ = '0.1.0'
"""
Created on Wed Sep 7 10:33:49 2016
Iterate through file, print out search term and next line
@author: robincole
"""
import os
my_dir = "/Users/.../IAEA phase space files"
my_list = ['TITLE',
# 'COORDINATE_SYSTEM_DESCRIPTION',
'BEAM_NAME',
... |
#!/usr/bin/python
import sys
import os
import math
import pdb
from collections import defaultdict
if len(sys.argv) < 4:
print "usage : parse_output_gnu_plot.py <input-file> <output-dir and file prefix> <dataset name> [<support step size>] [<labels_as_K> (YI YF or N)= (F=float I=int) ] [<max support value>]"
sys.exi... |
# -*- coding: utf-8 -*-
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from ganjiScrapySpider.items import HouseItem
class GanjiSpider(CrawlSpider):
name="ganjiSpider"
allowed_domains=['gan... |
# V0
# IDEA : MATRIX IN ORDER + BRUTE FORCE
# Space: O(1)
# Time: O(m+n) # worst case
class Solution:
def searchMatrix(self, matrix, target):
if len(matrix) == 0:
return False
row, col = 0, len(matrix[0]) - 1
while row < len(matrix) and col >= 0:
if matrix[r... |
from globvar import *
from discordapi import *
def sendMessage(content, channelID, embed=None):
"""
Sends a message to the specified channel
uses globvar: apiBase, token
content: string
token: string
channelID: string
Possible embed categories: title, description, url, timestamp, color, f... |
"""
This file contain form class that get the user input from template to views.
"""
from django import forms
from django.contrib.auth.models import User
from .models import Profile
class ProfileUpdateForm(forms.ModelForm):
"""Form in user's settings page to update image of that user."""
profile_picture = for... |
# Run with:
# python -m rl_games.games.dqn.nac.profile
from typing import Sequence, Tuple
import cProfile
import pstats
import io
from pstats import SortKey
from rl_games.dqn.dqn_player import DqnPlayer
from rl_games.core.play import play_many
from rl_games.core.player import Player
from rl_games.core.game import... |
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any, Generator
class AbstractUnitOfWork(ABC):
def __enter__(self) -> AbstractUnitOfWork:
return self
def __exit__(self, *args: Any) -> None:
self.rollback()
def commit(self) -> None:
self._... |
from bs4 import BeautifulSoup
import requests
import config
import time
import mysql.connector
def main():
status_URL = 'http://192.168.100.1/RgConnect.asp'
# log_URL = ''
soup = getSoup(status_URL)
ds_levels, us_levels = getStatus(soup)
insert_into_db('downstream', ds_levels)
insert_into_db... |
"""DSM 6 datas."""
from .const_6_api_auth import DSM_6_AUTH_LOGIN
from .const_6_api_auth import DSM_6_AUTH_LOGIN_2SA
from .const_6_api_auth import DSM_6_AUTH_LOGIN_2SA_OTP
from .const_6_api_info import DSM_6_API_INFO
from .core.const_6_core_security import DSM_6_CORE_SECURITY
from .core.const_6_core_security import DSM... |
# ROS2 libraries
import rclpy
from rclpy.node import Node
# ROS2 messages
from carla_intersection_msgs.msg import Request, Grant, VehicleCommand
from geometry_msgs.msg import Vector3
# Other libraries
from src.utils import make_coordinate, ROSClock
from src.ros_utils import make_Vector3
from src.vehicle import Vehicl... |
# http://python-social-auth.readthedocs.org/
# https://github.com/python-social-auth/social-examples
from social_core.backends.deezer import DeezerOAuth2
from social_core.backends.utils import load_backends
from configparser import ConfigParser
import re
from social_core.backends.oauth import OAuthAuth
# NAME_RE =... |
# TODO: shadow `crowsetta` here? |
# import pypboy
# import settings
# import pygame
# import os
# import imp
# import glob
# import time
# import game
# from collections import deque
# import mutagen
# import random
# import configparser
# import sys
# import threading
#
# from pypboy.modules.data import entities
# import pypboy.data
#
# song = None
# ... |
from udi_interface import Node,LOGGER
class Device(Node):
def __init__(self, parent, address, name):
# The id (node_def_id) is the address because each hub has a unique nodedef in the profile.
self.did = address
address = "d" + address
self.id = address
self.parent = parent... |
# Copyright 2020-present, Apstra, Inc. All rights reserved.
#
# This source code is licensed under End User License Agreement found in the
# LICENSE file at http://www.apstra.com/eula
# pylint: disable=redefined-outer-name
import json
import pytest
from unittest import mock
from unittest.mock import call
from aos.cl... |
import feather
import pandas as pd
def get_df(index):
db = feather.read_dataframe('data/db.feather')
return get_data_df(index, db)
def get_data_df(index, db):
file = db.loc[index]['file']
return feather.read_dataframe('data/{}'.format(file))
def get_df_byname(name):
db = feather.read_dataframe... |
import cv2
import os, sys
import numpy as np
save_path = 'images/train/'
# Helpful functions #
def save_image(name, img):
if not os.path.exists(save_path):
os.makedirs(save_path)
cv2.imwrite(save_path+name+'.tif', np.array(img, dtype=np.uint8))
def get_api_key():
if len(sys.argv) is 2:
... |
import contextlib
import os
import shutil
import tempfile
_cache_root = os.environ.get(
'LINEFLOW_ROOT',
os.path.join(os.path.expanduser('~'), '.cache', 'lineflow'))
@contextlib.contextmanager
def tempdir(**kwargs):
ignore_errors = kwargs.pop('ignore_errors', False)
temp_dir = tempfile.mkdtemp(**kwa... |
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, redirect
from .forms import UploadFileForm
from utils.sudoku_grid import render_sudoku
from solver.solver import solve
from .forms import CreateUserForm
from django.contrib import messages
from django.contrib.auth import aut... |
#===============================================================
# DMXIS Macro (c) 2010 db audioware limited
#===============================================================
found=False
for ch in GetAllSelCh(True):
nm = GetChName(ch).lower()
if nm=="r" or nm=="g" or nm=="b" or nm=="red" or nm=="green" o... |
import os
from pydantic import BaseSettings
# 로컬에 동일한 이름의 환경변수가 적용되어있으면, 그걸로 덮어지게됨 (printenv 로 확인 필요)
class Settings(BaseSettings):
HOST: str
PORT: int
DATABASE: str
USERNAME: str
PASSWORD: str
class Config:
env_file = os.path.expanduser('~/.env')
env_file_encoding = 'utf-8'
|
import json
import pathlib
import airflow
import requests
import requests.exceptions as requests_exceptions
from airflow import DAG
from airflow.decorators import dag, task
from airflow.operators.subdag_operator import SubDagOperator
from airflow.operators.bash import BashOperator
from airflow.operators.python import ... |
#!/usr/bin/python
# change this to the IP address and port that will receive our OSC messages, if applicable
remoteIP = '10.0.0.111'
remotePort = 9000
import time, threading
import OSC # requires pyOSC from https://trac.v2.nl/wiki/pyOSC or https://gitorious.org/pyosc
import pygame
sendAddress = (remoteIP, remotePort... |
# This file allows us to define database models. Each model corresponds to a table in
# our relational database. If you've use web frameworks that utilize the
# Model-View-Controller (MVC) architecture, this is a part of the Model portion of that
# architecture, where we define the data structures in our database.
# Re... |
# Generated by Django 2.2.9 on 2020-01-24 20:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contact', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ContactMessage',
fields=[
... |
'''
Scivi is written/maintained/developed by:
S. Chris Colbert - sccolbert@gmail.com
Scivi is free software and is part of the scikits-image project.
Scivi is governed by the licenses of the scikits-image project.
Please report any bugs to the author.
The scivi module is not meant to be used directly.
Use skimage... |
from graphmix import Graph
import numpy as np
import scipy.sparse as sp
import os
import sys
import math
import argparse
import pickle as pkl
import networkx as nx
'''
Usage example: (in Dir Hetu/)
python ./tests/test_DistGCN/prepare_data_GCN15d.py --size 8 --replication 2 --dataset Reddit
'''
def coo_slice(a, ... |
# -*- coding: utf-8 -*-
#
# Copyright 2017 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compli... |
import tornado.websocket
import json
import datetime
from system.log import log
from system.webserver import Webserver
from game.player import Player
class WebsocketRTC(tornado.websocket.WebSocketHandler):
websocket_send_data = []
websocket_clients = []
def websocket_send(client,data,binary=False... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.