content stringlengths 5 1.05M |
|---|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2021 Chao Pan <chaopan2@illinois.edu>
#
# Distributed under terms of the MIT license.
"""
This file is for automatic modified bases signal extraction. The overall
idea is to first find the correct current level for polyA ... |
"""
specs
=====
Functions generating specifiers for output naming conventions.
Functions reading model specifications from SHEMAT-Suite output.
"""
import os
import numpy as np
from pskf.tools.run import pythonmodule as pm
from pskf.tools.run import runmodule as rm
##################################################... |
from itertools import cycle, islice
from players.base_player import BasePlayer
class ReducingCycle:
"""
This is a generic implementation of a cycle which can reduce in size.
"""
def __init__(self, players: list, start_index: int = 0):
self.__players = players
self.__set_active_player... |
"""
Polimorfismo é o principio que permite que classes derivadas de uma mesma superclasse tenham metodos iguais (de mesma assinatura)
mas comportamentos diferentes.
Mesma assinatura = Mesma quantidade e tipo de parametros
Obs: O Python só suporta esse tipo de polimorfismo(sobreposicao)
"""
from abc import ABC, abstrac... |
from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl
"""Reader for a single worksheet."""
from io import BytesIO
# compatibility imports
from openpyxl.xml.functions import iterparse
# package imports
from openpyxl.cell import Cell
from openpyxl.worksheet import Worksheet, ColumnDimension, RowDim... |
"""
SUMMARY
Quadratic Programming optimizer.
It outputs a JSON file containing a list of nodes and roads. Each road will have a calculated AADT value.
"""
import argparse
import json
import pickle
import sys
from matplotlib.colors import LinearSegmentedColormap
import matplotlib.pyplot as plt
import ... |
"""
Spheral CRKSPH module.
Provides implementations of CRKSPH (fluid and solid).
"""
from PYB11Generator import *
from SpheralCommon import *
from spheralDimensions import *
dims = spheralDimensions()
from CRKSPHHydroBase import *
from SolidCRKSPHHydroBase import *
#-------------------------------------------------... |
import torch
import numpy as np
import random
import cv2
def process_image(img, center, scale):
mean = np.array([123.675, 116.280, 103.530])
std = np.array([58.395, 57.120, 57.375])
img, _, _ = generate_image_patch(img, center[0], center[1], scale, scale, 256, 256, False, 1.0, 0.0)
img = img[:, :, ::-... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import subprocess
import shlex
import glob
try:
import argparse
except ImportError:
sys.exit("Please install or run Python 2.7 or later")
HOME = os.path.expanduser("~") # User Home Directory
DOTFILES = os.path.join(HOME, ".dotconfig/dotfiles... |
# Blen64 (modified)
# forked from https://github.com/GCaldL/Blen64
# this script uses the vertex buffer inefficiently, which can result in poor
# rendering performance. keep that in mind if you use it.
# - fixed invalid output of x,y,z
# - fixed invalid use of vertex buffer indices > 32
# - fixed random value used for ... |
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=500)
add_date = models.DateTimeField(auto_now_add=True)
update_date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class ... |
"""
util.py
Utility functions for parsing words and helping with lookups
Largely taken from Whitaker's tricks_package.ad[b,s]
"""
def is_a_vowel(char):
return
def a_roman_digit(char):
return
def value(char):
return
def only_roman_digits(s):
return
def roman_number(s):
return
def bad_... |
customer = {
'name': 'anurag',
'lastName': 'arwalkar'
}
print(customer['name'])
|
"""Library to access del.icio.us data via Python.
:examples:
Using the API class directly:
>>> a = pydelicious.apiNew('user', 'passwd')
>>> # or:
>>> a = DeliciousAPI('user', 'passwd')
>>> a.tags_get() # Same as:
>>> a.request('tags/get', )
Or by calling the 'convenience' methods on the module.
- d... |
'''
Created on Mar 29, 2016
@author: dj
'''
# Could be List or Set.
list1 = [1, 2]
listA = ['A', 'B', 'C']
print("list1 =", list1)
print("listA =", listA)
print("-" * 40)
# Empty [] is False; Not empty [] is True.
list2 = []
print("list2 =", list2)
if list2:
print("list2 is not empty")
el... |
# 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 the... |
import sys
import re
import os
from shutil import copyfile
import json
#########################################
#
#防止将修改的文件直接写入而删除文件
#
#########################################
path = './weibo.json' # 文件路径
if os.path.exists(path): # 如果文件存在
# 删除文件,可使用以下两种方法。
os.remove(path)
#############################... |
from django.db import models
class Submission(models.Model):
title = models.CharField(max_length=200)
external_link = models.URLField()
upvotes = models.IntegerField()
downvotes = models.IntegerField()
|
# MIT License
# Copyright (c) 2018 NCC Group
# 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, merge, publ... |
from synapyse.base.learning.training_set import TrainingSet
from synapyse.impl.activation_functions.sigmoid import Sigmoid
from synapyse.impl.input_functions.weighted_sum import WeightedSum
from synapyse.impl.learning.momentum_back_propagation \
import MomentumBackPropagation
from synapyse.impl.multi_layer_perceptr... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from constants import *
class Event:
"""
This object represents the 'Event' object in the database.
It is used instead of a simple dictionary in order to be able
to link it with the parsing of the scraper and with its specific SQL queries.
It is also used... |
# Copyright (c) Aaron Gallagher <_@habnab.it>
# See COPYING for details.
import string
from passacre._backend_capnp import default_client
from passacre.compat import hexlify
from passacre.schema import multibase_of_schema
from passacre import features, signing_uuid
_site_multibase = multibase_of_schema([string.asci... |
from pybricks.pupdevices import Light
from pybricks.hubs import CPlusHub
from pybricks.parameters import Port
from pybricks.tools import wait, StopWatch
from math import cos, pi
hub = CPlusHub()
print(hub.battery.voltage())
# Initialize the light and a StopWatch
lightA = Light(Port.A)
lightB = Light(Port.B)
lightC = ... |
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
hashmap = {}
for word in strs:
hashed = self.hashStr(word)
if hashed not in hashmap.keys():
hashmap[hashed] = []
hashmap[hashed].append(word)
... |
# -*- coding: utf-8 -*-
class Solution:
def getMaximumGenerated(self, n: int) -> int:
nums, result = [0] * (n + 1), 0
for i in range(1, n + 1):
if i == 1:
nums[i] = 1
elif i % 2 == 0:
nums[i] = nums[i // 2]
elif i % 2 == 1:
... |
"""
Test the canvas basics.
"""
import wgpu.gui # noqa
class TheTestCanvas(wgpu.gui.WgpuCanvasBase):
def __init__(self):
super().__init__()
self._count = 0
def draw_frame(self):
self._count += 1
if self._count <= 4:
self.foo_method()
else:
sel... |
# SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
import abc
class BundleLocation(abc.ABC):
def __init__(self, path: str, filename: str) -> None:
self.path = path
... |
import FWCore.ParameterSet.Config as cms
process = cms.Process( "SiStripDQMOfflineGlobalRunCAF" )
process.MessageLogger = cms.Service( "MessageLogger",
destinations = cms.untracked.vstring(
'cout'
),
cout = cms.untracked.PSet(
# threshold = cms.untracked.string( 'ERROR' )
threshold... |
'''
Copyright (c) 2020-present NAVER Corp.
MIT license
'''
# encoding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import mxnet as mx
from gluoncv import model_zoo
from gluoncv2.model_provider import get_mod... |
import datetime
from django.test import TestCase
from django.utils import timezone
from camphoric import models
from freezegun import freeze_time
class OrganizationTests(TestCase):
@freeze_time("2019-02-25 17:00:05")
def setUp(self):
self.organization = models.Organization.objects.create(name="Test Or... |
# Copyright (C) 2021-2022, Mindee.
# This program is licensed under the Apache License version 2.
# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.
import os
from copy import deepcopy
from typing import Any, List, Tuple
import numpy as np
import tensorflow as tf
from... |
# 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
import plotly.express as px
import dash
app = dash.Dash(__name__)
app.layout = html.Div(html.Img(src=app.get_asset_ur... |
import math
import time
import numpy as np
from score_keeper import get_timesteps
symmetric = True
def kalman(v, r, q):
"""
v - array to filter
t - time steps, usually just range(len(v))
r - how much we trust our path def=0.1
q - decreasing it makes it smoother def=0.01
"""
p = 12... |
# Please download the attached ZIP file. Inside the ZIP file there's a directory named subdirs.
# That directory contains other directories inside. Please write a script
# that counts the number of .py files contained inside subdirs and all its sub-directories.
import glob
file_list = glob.glob("./93_files/**/*.py",... |
"""Regression testing framework
This module will search for scripts in the same directory named
test_*.py. Each such script should be a test suite that tests a
module through PyUnit. This script will aggregate all
found test suites into one big test suite and run them all at once.
Usage: test_all.py [<options>]
wher... |
from __future__ import annotations
import datetime
import urllib.parse
from tank_game.promise import PromisingThread
from typing import Union
import logging
import dateparser
import requests
END_NEWSCORE_SCORE = 'http://dreamlo.com/lb/%s/add/%s/%i'
END_NEWSCORE_SCORE_TIME = 'http://dreamlo.com/lb/%s/add/%s/%i/%i'
EN... |
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
from twilio.rest import Client
from google.cloud import storage
from google.cloud.storage import blob
from datetime import datetime, timedelta
from flask import Flask, request
from twilio.twiml.messaging_response import Messa... |
from __future__ import unicode_literals
import six
from ..shared.objects import Property
from .operations import CypherExpression, ComparisonExpression, QueryParams
class CypherQuery(list):
def __init__(self, graph_obj, use_full_pattern=False):
self.params = QueryParams()
try:
verb ... |
#
# Copyright (C) 2015 Satoru SATOH <ssato @ redhat.com>
# License: MIT
#
"""anyconfig module initialization before any other things.
"""
import logging
import anyconfig.compat
# See: "Configuring Logging for a Library" in python standard logging howto,
# e.g. https://docs.python.org/2/howto/logging.html#library-confi... |
import modelexp
from modelexp.experiments import Generic
from modelexp.models.generic import Parabola
from modelexp.data import XyeData
from modelexp.fit import LevenbergMarquardt
import numpy as np
import random
app = modelexp.Cli()
app.setExperiment(Generic)
dataRef = app.setData(XyeData)
dataRef.loadFromFile('./p... |
from flask import abort, current_app, jsonify
from flask_restful import Resource, fields, marshal_with
from flask_jwt_extended import jwt_required, get_jwt_identity
from webapp.blog.models import db, Post, Tag, Reminder
from webapp.auth.models import User
from .parsers import (
post_get_parser,
post_post_parser... |
# makes the website folder into a python package
# when importing the website folder, the commands in this file will be run
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path
from flask_login import LoginManager
db = SQLAlchemy()
DB_NAME = "database.db"
def create_app():
app = F... |
#!/usr/bin/env python
# Filters Scintilla.h to not contain generated stuff or deprecated defines
import sys
import fileinput
def main():
inhibit = 0
for line in fileinput.input():
if line.startswith("/* ++Autogenerated") or line.startswith("#ifdef INCLUDE_DEPRECATED_FEATURES"):
inhibit += ... |
from common import *
import asyncio
from aiohttp import web
from functools import partial
import json
class Server():
def __init__(self, hub):
async def handler(request):
if (request.method == 'GET'):
proxies = []
if (request.path == '/'):
for... |
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2012, Erkan Ozgur Yilmaz
#
# This module is part of oyProjectManager and is released under the BSD 2
# License: http://www.opensource.org/licenses/BSD-2-Clause
import os
import shutil
import tempfile
import unittest
from sqlalchemy import Column, Integer
from oyProjectMana... |
# Copyright (c) Open-MMLab. All rights reserved.
import os
import os.path as osp
from pathlib import Path
def is_filepath(x) -> bool:
r"""Path check function.
Args:
x (str | obj:`Path`): path address
Returns:
bool: is a path or not
"""
return isinstance(x, (str, Path))
def che... |
print("Hello Indonesia!")
print("Hello Jakarta!")
#This text won't be printed, it's a comment! |
from ..base_commands import SetStateCommand
from ..base_commands import CommandExecutionCode
import numpy as np
class Switch(SetStateCommand):
def __init__(self, _state):
SetStateCommand.__init__(self, _state)
names = ['switch', 'sw']
description = 'Switch to favorites and vice versa'
argv = ... |
"""
Naively scans python code for credentials
"""
import tokenize
import re
from pylint.checkers import BaseTokenChecker
from pylint.interfaces import ITokenChecker, HIGH
class CredentialChecker(BaseTokenChecker):
"""
Checks if any credentials exist as python strings
"""
__implements__ = ITokenChe... |
#!/usr/bin/env python
import os
from flask import Flask, abort, request, jsonify, g, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_httpauth import HTTPBasicAuth
# initialization
app = Flask(__name__)
app.config['SECRET_KEY'] = 'The super secret key CHANGE IN PRODUCTION'
app.config['SQLALCHEMY_DATABASE_U... |
import gym
import gym.spaces
import gym.utils
import gym.utils.seeding
import numpy as np
from gym_extensions.continuous import mujoco
import sys
try:
from gym.envs.mujoco.mujoco_env import MujocoEnv
except:
print("This example depends on mujoco, see README.md for information on installing.")
sys.exit()
try... |
# -*- coding: utf-8 -*-
"""
3_sim
=====
FSIC implementation of Model *SIM* (the SIMplest model with government money)
from Chapter 3 of Godley and Lavoie (2007).
While FSIC only requires NumPy, this example also uses:
* `pandas`, to generate a DataFrame of final results using `fsic.tools`
* `matplotlib`, to replicate... |
"""Container overriding example."""
from dependency_injector import containers, providers
class Service:
...
class ServiceStub:
...
class Container(containers.DeclarativeContainer):
service = providers.Factory(Service)
class OverridingContainer(containers.DeclarativeContainer):
service = prov... |
'''
The ferryman problem is a logic puzzle where a ferryman has to carry across a river
several entities but being only able to carry a limited amount together.
Some of the entities cannot be left unattended alone, for example the sheep would
eat the cabbage if the ferryman isn't with them.
This e... |
import re
import os
from glob import glob
import argparse
import traceback
import pandas as pd
from tqdm import tqdm
from colorama import Fore
def extract_info(input_path, output_path, columns) -> bool:
"""
Args:
input_path (str): The first parameter, path of one file.
output_path (str): The ... |
from __future__ import division
import click
from app.workflow import Workflow
from app.drawing_dataset import DrawingDataset
from app.image_processor import ImageProcessor, tensorflow_model_name, model_path
from app.sketch import SketchGizeh
from pathlib import Path
from os.path import join
import logging
import datet... |
"""
This is a simple python script to test the autogenerated module
"""
print ' START TESTING ALMotionExample MODULE'
from naoqi import ALProxy
import argparse
def main(robotIP, PORT):
#________________________________
# Generic Proxy creation
#________________________________
try:
... |
# function to show the inventory
import variables as var
from helpers.menu import menu
def inventory_menu(header):
# show a menu with each item of the inventory as an option
if len(var.inventory) == 0:
options = ['Inventory is empty.']
else:
# options = [item.name for item in var.inventory... |
import gpiod
class APA102:
def __init__(self, pixel_count=8, gpio_chip="gpiochip0", gpio_clk=24, gpio_dat=23, consumer_name="apa102", clear_on_enter=True, clear_on_exit=True):
self.pixel_count = pixel_count
self.consumer_name = consumer_name
self.clear_on_enter = clear_on_enter
sel... |
__module_name__ = "_write_GTF_csv.py"
__author__ = ", ".join(["Michael E. Vinyard"])
__email__ = ", ".join(["vinyard@g.harvard.edu",])
# import local modules #
# -------------------- #
from ._Messages import _Messages
def _write_GTF_csv(GTF_df, path, silent=False):
msg = _Messages(silent)
msg.writing(p... |
from django.urls import path
from rested import rest, authorize
from rested import signals
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
restpatterns = [
rest("ping", "get", views.ping),
rest("login", "post", views.login),
rest("logout", "post", views.logout),
rest("m... |
# Copyright 2014 Diamond Light Source 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 t... |
from __future__ import annotations
from spark_auto_mapper_fhir.fhir_types.uri import FhirUri
from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode
from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType
# This file is auto-generated by generate_classes so do not edi... |
#!/usr/bin/env python3
from os import listdir
from os.path import basename, dirname
__all__ = [basename(f)[:-3] for f in listdir(dirname(__file__))
if f[-3:] == ".py" and not f.endswith("__init__.py")]
|
# Python-SDL2 : Yet another SDL2 wrapper for Python
#
# * https://github.com/vaiorabbit/python-sdl2
#
# [NOTICE] This is an automatically generated file.
import ctypes
from .api import SDL2_API_NAMES, SDL2_API_ARGS_MAP, SDL2_API_RETVAL_MAP
# Define/Macro
# Enum
# Typedef
# Struct
# Function
def ... |
import numpy as np
import os
import time
import dask
import dask.array as da
from distributed import Client
from dask_jobqueue import SLURMCluster
from ipflag import compute_uv_bins, gridflag
# Job parameters (to be set by pipeline manager or command line arguments)
msfile = '/scratch/users/jbochenek/data/153885605... |
import time
from MultiUART import MultiUART
muart=MultiUART(1,64)
muart.setBaud(6)
#muart=MultiUART(0,64)
#muart.setBaud(4)
muart.flushRx()
for i in range(1,1000):
c=muart.checkRx()
c2=muart.checkTx()
if c>0:
ch=muart.receiveBytes(c)
print "c=",c,c2,ch
else:
#print "nothing",c,c2
#ch=muart.receiveByte(0)... |
import random
import torch
import numpy as np
def dict2tensor(d):
for key, value in d.items():
if type(value) != str:
d[key] = torch.from_numpy(np.array(value))
return d
def Time2FrameNumber(t, ori_fps, fps=10):
""" function to convert segment annotations given in seconds to frame nu... |
from galaxy_exporter.galaxy_exporter import GalaxyData
def test_galaxydata_defaults():
gd = GalaxyData("test.test")
assert gd.url() is None
assert gd._setup_metrics() == dict()
|
import math
import itertools
import bisect
import heapq
from sys import stdin
from collections import deque
from sys import setrecursionlimit
from functools import reduce
from collections import defaultdict
setrecursionlimit(10**7)
input = stdin.readline
def I():
return int(input())
def IN():
return map(in... |
#!/usr/bin/env python
#
# Copyright 2006 The Closure Library Authors. All Rights Reserved.
"""Calculates Javascript dependencies without requiring Google3.
It iterates over a number of search paths and builds a dependency tree. With
the inputs provided, it walks the dependency tree and outputs all the files
require... |
from enum import IntFlag
from .api import *
from .utils import H2RequestsSession
import dateutil
import dateutil.parser
from collections import OrderedDict
class AddonType(IntFlag):
extension=0
theme=1
dictionary=2
class ExtensionType(IntFlag):
xul = 0
restartless = 1
WebExtension = 2
def lang... |
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.safestring import mark_safe
from website.validators import validate_gh_token
def email_verify_warning(request):
messages.warning(req... |
# class Node:
# def __init__(self, data):
# self.left = None
# self.right = None
# self.data = data
# def preOrderTree(self):
# print(self.data)
# if self.left:
# self.left.preOrderTree()
# if self.right:
# self.right.preOrderTree()
# ... |
#!/usr/bin/python3
import pytest
from brownie import Wei
from brownie.network.account import PublicKeyAccount
def test_init(accounts):
PublicKeyAccount("0x14b0Ed2a7C4cC60DD8F676AE44D0831d3c9b2a9E")
PublicKeyAccount(accounts[0])
with pytest.raises(ValueError):
PublicKeyAccount("0x416b8a7d9290502f... |
import nussl
import scipy.io.wavfile as wav
import pytest
import numpy as np
import tempfile
import librosa
from nussl.core.audio_signal import AudioSignalException, STFTParams
from nussl.core.constants import ALL_WINDOWS
from nussl import AudioSignal
from scipy.signal import check_COLA
import copy
import itertools
sr... |
from flake8_plugin_utils import assert_error, assert_not_error
from flake8_pytest_style.config import DEFAULT_CONFIG
from flake8_pytest_style.errors import FixturePositionalArgs
from flake8_pytest_style.visitors import FixturesVisitor
def test_ok_no_args():
code = """
import pytest
@pytest.fixtu... |
#!/usr/bin/python3
# test_notice_creation.py
# Date: 03/02/2022
# Author: Eugeniu Costetchi
# Email: costezki.eugen@gmail.com
""" """
from pprint import pprint
from deepdiff import DeepDiff
import pytest
from pydantic import ValidationError
from ted_sws.core.model.manifestation import XMLManifestation, Manifestat... |
#!/usr/bin/python
import time
from dotstar import Adafruit_DotStar
colors = ['#e70000', '#e80700', '#ea0d00', '#eb1400', '#ec1b00', '#ed2200', '#ef2900', '#f03100', '#f13800', '#f23f00', '#f44600', '#f54e00', '#f65500', '#f75d00', '#f96500', '#fa6c00', '#fb7400', '#fc7c00', '#fe8400', '#ff8c00', '#ff9100', '#ff9600',... |
# Generated by Django 3.1.7 on 2021-04-02 18:35
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('unievents', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
name='location',
unique_together={('longitude'... |
"""exercises/process_fasta.py"""
import argparse
parser = argparse.ArgumentParser(description="Parses a single-entry fasta file and returns some stats.")
parser.add_argument("inputFasta", type = str, help = "The input fasta file")
parser.add_argument("-S", "--search", type = str, default = "",
he... |
# encoding=utf-8
import torch
from scipy.sparse.csr import csr_matrix
def reserve_nn_scores(similarities, nn_num):
"""Reserver top-k nearest neighbors' similarity scores
Args:
similarities (Matrix): test_num * train_num
Returns:
nn_scores (Matrix): only keep the scores of the top... |
import unittest
from decimal import Decimal
from Broker import Broker
from Portfolio import Account, Portfolio
from tests.MockAuthenticator import MockAuthenticator, load_test_balance, \
load_test_positions
class TestPortfolio(unittest.TestCase):
def setUp(self):
self.broker = Broker()
self.... |
# -*- coding: utf-8 -*-
#
"""
Filename: deeplearning.py
Date: Wed Oct 24 13:04:16 2018
Name: Arnaud Rosay
Description:
- Deep learning library
"""
import pandas as pd
import numpy as np
import tensorflow as tf
# from tensorflow.python.client import timeline
import math
import os
from datetime import datetime
imp... |
from __future__ import absolute_import
import numpy as np
from matplotlib import pyplot as plt
# from astroML.plotting.tools import draw_ellipse
from astroML.plotting import setup_text_plots
# from sklearn.mixture import GMM as skl_GMM
def plot_bic(param_range,bics,lowest_comp):
plt.clf()
setup_text_plots(font... |
#!/usr/bin/env python
# niryo_one_robot_state_publisher.py
# Copyright (C) 2017 Niryo
# All rights reserved.
#
# This program 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, o... |
import numpy as np
import matplotlib.pyplot as plt
from imageio import imread, imsave
# NOTE: The majority of the code in this file was taken from Fall 2019 CS189 HW4
imFile = './images/stpeters_probe_small.png'
compositeFile = './images/tennis.png'
targetFile = './images/interior.jpg'
def loadImages():
imFile =... |
import math
# Constants
DEFAULT=-1
ENABLED=1
DISABLED=0
INF=1e38
NINF=-1e38
###############################################
class Color:
def __init__(self,s):
if type(s) is str:
self.rgb = tuple(float(x) for x in s.split(','))
elif type(s) is tuple:
self.rgb = s
def __getitem__(se... |
# -*- coding: utf-8 -*-
from .amplitudechain import LS
from .amplitudechain import AmplitudeChain
__all__ = ("LS", "AmplitudeChain")
|
from . import common, data, integration, preproc
__all__ = ["data", "preproc", "common", "integration"]
__version__ = "0.4.3"
|
# -*- encoding: utf-8 -*-
"""
@File : urls.py
@Date : 2019/11/1
@Author : Regulus
@Contact : yusheng831143@gmail.com
@Desc : wfuser模块相关url映射。
"""
from django.urls import path
from apps.wfusers import views
app_name = 'app_wfusers'
urlpatterns = [
path('', views.index, name='index'),
path('sign', vi... |
class Problem:
WIDTH = 50
HEIGHT = 6
def __init__(self, inp):
self.data = [[False] * Problem.WIDTH for i in range(Problem.HEIGHT)]
for instructions in list(map(lambda row: row.split(" "), inp.read().strip().split("\n"))):
if instructions[0] == "rect":
w, h = list... |
# 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 Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
from pickletools import UP_TO_NEWLINE
from re import L
from tensorflow import keras
import model_utils
from math import floor, ceil
def load_model():
model = keras.models.load_model("pretrained/New_32CL_5LR_43Epoc")
return model
def prepare_output(pred):
# This function will return the final output ... |
from datetime import datetime
from parsons import db
class Program(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.DateTime(), nullable=False,
default=datetime.utcnow)
title = db.Column(db.Text(), nullable=False)
code = db.Column(db.Text(), nullable=... |
import csv
def load_to_tsv(output_file_name, data: []):
with open(output_file_name, 'w') as tsvfile:
writer = csv.writer(tsvfile, delimiter='\t', newline='\n')
for row in data:
writer.writerow(row)
|
from django.db import models
# Create your models here.
class Image(models.Model):
name = models.CharField(max_length=255)
posted_date = models.DateTimeField(auto_now_add=True)
image_description = models.CharField(max_length=500, default='DEFAULT VALUE')
image = models.ImageField(upload_to='images/', blank=Tru... |
import uvicorn
from fastapi import FastAPI
from app.api.v1 import api_router
from app.core import settings
app = FastAPI(title=settings.PROJECT_NAME)
app.include_router(api_router, prefix=settings.API_V1_STR)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
|
import os
import re
jena_dir = '/home/chenjiaqi/jena/bin/'
gstore_dir = '/home/chenjiaqi/gStore-master/'
devgstore_dir = '/home/chenjiaqi/devGstore/'
query_dir = '/home/chenjiaqi/useful/allquery'
if __name__ == '__main__':
gstore_nores = open('gstore.nores', 'w')
query_set = open(query_dir, 'r').read().split('myow... |
from backports_abc import Coroutine, Generator
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.