content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
"""
********************************************************************************
post_processing
********************************************************************************
Polyline simplification
=======================
.. autosummary::
:toctree: generated/
:nosignatures:
simplify_paths_rdp
So... | python |
#!/usr/bin/env python2.7
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import json
import logging
import os
import pprint
import sys
import time
LOG = logging.getLogger()
LOG.setLevel(logging.DEBUG) # For now, let Handlers control t... | python |
import json
import asyncio
from os import environ
from functools import partial
from aiohttp import ClientSession, ClientConnectionError
from pyee import AsyncIOEventEmitter
from aiohttp_sse_client.client import EventSource
DEFAULT_STREAM_URL = 'https://stream.flowdock.com/flows'
__all__ = ["EventStream"]
class Eve... | python |
"""
File: My_drawing.py
Name:Elsa
----------------------
TODO:
"""
from campy.graphics.gobjects import GOval, GRect
from campy.graphics.gwindow import GWindow
from campy.graphics.gobjects import GOval, GRect,GPolygon,GLabel
from campy.graphics.gwindow import GWindow
def main():
"""
TODO:
This figure uses ... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import json
from lib import xmltodict
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
SCRAMBLED = u'да'
class ReferenceBase(object):
def __init__(self, url):
self.url = url
self.data = {}
... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__name__ = "Phoniebox"
import configparser # needed only for the exception types ?!
from ConfigParserExtended import ConfigParserExtended
import codecs
import subprocess # needed for aplay call
import os,sys
from time import sleep
from mpd import MPDClient
# get absolut... | python |
from datetime import timedelta
from django.db import models
from django.utils import timezone
import time
from .config import YEKPAY_SIMULATION
class TransactionManager(models.Manager):
""" Manager for :class:`Transaction` """
def create_transaction(self, transaction_data):
transaction_data["status"... | python |
from Utility.Types.Reconstruction import Reconstruction
class Background_Reconstruction(Reconstruction):
def __init__(self, cams, points, image_folder_path, sparse_reconstruction_type):
super(Background_Reconstruction, self).__init__(
cams,
points,
image_folder_path,
... | python |
from .approach import Approach
from .challenge import Challenge
from .review_history import ReviewHistory
from .submission import Submission
from .task import Task
from .team import Team
from .team_invitation import TeamInvitation
__all__ = ['Approach', 'Challenge', 'ReviewHistory', 'Submission', 'Task', 'Team', 'Team... | python |
# Telegram
# TELEGRAM
import telegram
from telegram import ReplyKeyboardMarkup
from telegram.error import NetworkError, Unauthorized
# ACCESO A DATOS EN SERVIDORES (usado por telegram)
import json
import requests
import config
import emailUtil
import Datos
# mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
# F... | python |
# Andrew Riker
# CS1400 - LW2 XL
# Assignment #04
import math
# user enters length of sides
length = eval(input("Enter length of the polygon sides: "))
# user enters number of sides
numOfSides = eval(input("Enter the number of sides the polygon has: "))
# calculate the area of the polygon
area = (numOfSide... | python |
# flake8: noqa
import geonomics as gnx
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
from mpl_toolkits.axes_grid1 import make_axes_locatable
# define number of individuals to plot tracks for, and number of timesteps for
# tracks
n_individs = 20
n_timesteps = 5000
# make figure
fi... | python |
#!/usr/bin/env python
import paramiko
import sys
hostname = sys.argv[1]
port = 22
usr = 'user'
pwd = 'pass'
try:
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
client.connect(hostname, port=port, username=usr, password=pwd)
ex... | python |
#!/usr/bin/env python3
# Imports
import prometheus_client
import traceback
import speedtest
import threading
import argparse
import time
# Arguments
parser = argparse.ArgumentParser(description='Prometheus exporter where it reports speedtest statistics based on user\'s preference.')
parser.add_argument('--w... | python |
import logging
import os
import signal
import socket
import time
from contextlib import contextmanager
from subprocess import Popen
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed
class UserObject:
def predict(self, X, features_names):
logging.info("Predict called")
... | python |
__author__ = 'alex'
import os
import subprocess
import logging
from mountn.utils import lsblk, SubprocessException
from mountn.gui import gui
from locale import gettext as _
class TcplayDevice(object):
class Item(object):
def __init__(self, plugin, **kwargs):
self.plugin = plugin
... | python |
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from numpy import pi
qreg_q = QuantumRegister(3, 'q')
creg_c = ClassicalRegister(3, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
circuit.h(qreg_q[1])
circuit.cx(qreg_q[1], qreg_q[2])
circuit.barrier(qreg_q[1], qreg_q[2], qreg_q[0])
circuit.cx(qreg... | python |
from mmdet.models.necks.fpn import FPN
from .second_fpn import SECONDFPN
from .imvoxelnet import ImVoxelNeck, KittiImVoxelNeck, NuScenesImVoxelNeck
__all__ = ['FPN', 'SECONDFPN', 'ImVoxelNeck', 'KittiImVoxelNeck', 'NuScenesImVoxelNeck']
| python |
import cv2
face_cascade = cv2.CascadeClassifier("./haarcascade_frontalface_default.xml")
img = cv2.imread("face1.jpg")
gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces= face_cascade.detectMultiScale(gray_img, scaleFactor = 1.15, minNeighbors=5)
print(type(faces))
print(faces)
# for x,y,w,h in face... | python |
# Copyright 2018 IBM Corp. 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 law or a... | python |
try:
from setuptools import setup
except:
from distutils.core import setup
setup(
name='pytorch_custom',
version='0.0dev',
author='Alexander Soare',
packages=['pytorch_custom'],
url='https://github.com/alexander-soare/PyTorch-Custom',
license='Apache 2.0',
description='My own miscel... | python |
'''
Copyright Hackers' Club, University Of Peradeniya
Author : E/13/181 (Samurdhi Karunarathne)
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 r... | python |
# 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 u... | python |
import datetime
import logging
import random
from GameParent import Game
from GameParent import SetupFailure, SetupSuccess
logger = logging.getLogger(__name__)
handler = logging.FileHandler('../logs/{}.log'.format(str(datetime.datetime.now()).replace(' ', '_').replace(':', 'h', 1).replace(':', 'm').split('.')[0][:-2]... | python |
import torch.nn as nn
import torch
from .initModel import initModel
import torch.nn.functional as F
from torch.autograd import Variable
import codecs
import os
import json
class simplE(initModel):
def __init__(self, config):
super(simplE, self).__init__(config)
self.entHeadEmbedding = nn.Embedding... | python |
__author__ = 'jonnyfunfun'
| python |
# A few convenient math functions for the bicorr project
import matplotlib
#matplotlib.use('agg') # for flux
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='ticks')
import sys
import os
import os.path
import scipy.io as sio
from scipy.optimize import curve_fit
import time
import numpy as np
np.s... | python |
import sys
import os
project = u'Pelikan'
description = u"Unified cache backend. http://go/pelikan"
copyright = u'Twitter'
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.ifconfig',
]
exclude_patterns = ['_build']
html_static_path = ['_static']
source_suffix = '.rst'
master_do... | python |
from random import (randrange, shuffle)
from copy import deepcopy
from forest_calculations import (get_forest_dimensions, get_tree_counts)
from forest_transpormations import (flatten_forest, deflatten_forest)
from forest_constants import (LEAFY, CONIFEROUS)
def get_random_position(rows, cols):
return randrange(ro... | python |
from img_utils import img_utils as _lib
from .utils import u8
def darken_pixels(src_path: str, dst_path: str, amount: int, cutoff: int):
""" Darken Pixels
Darkens all pixels in the image by percentage, specified by `amount`. Any pixel
that doesn't have a subpixel below than the `cutoff` will be ignored.... | python |
import asyncio
import logging
import os
import socket
import uuid
import pika
import pika.adapters.asyncio_connection
from .subscription import QueueSubscriptionObject, ExchangeSubscriptionObject
from ..broker import Broker
#
L = logging.getLogger(__name__)
#
class AMQPBroker(Broker):
'''
The broker that uses ... | python |
from urllib import urlencode
from django import forms
from django.conf import settings
from django.contrib import admin
from django.core import validators
from django.core.urlresolvers import resolve
from django.utils.html import format_html
from django.utils.translation import ugettext
from olympia import amo
from o... | python |
def ext_gcd(p, q):
if p == 0:
return q, 0, 1
else:
# gcd, s_i, t_i
gcd, u, v = ext_gcd(q % p, p)
return gcd, v - (q // p) * u, u
p = 240
q = 46
gcd, u, v = ext_gcd(p, q)
print("[+] GCD: {}".format(gcd))
print("[+] u,v: {},{}".format(u,v))
print(f"\n[*] FLAG: crypto{{{u},{v}... | python |
# Generated by Django 2.2.6 on 2019-11-21 17:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('selections', '0009_auto_20190529_0937'),
]
operations = [
migrations.AlterField(
model_name='selection',
name='is_no... | python |
import urllib
import time
def main(request, response):
index = request.request_path.index("?")
args = request.request_path[index+1:].split("&")
headersSent = 0
for arg in args:
if arg.startswith("ignored"):
continue
elif arg.endswith("ms"):
time.sleep(float(arg[0... | python |
import dotenv
from pathlib import Path
from .exceptions import EnvKeyNotFoundError, EnvNotFoundError
BASE_PATH = Path(__file__).resolve().parent.parent
if not (ENV := dotenv.dotenv_values(BASE_PATH / '.env')):
raise EnvNotFoundError()
if not (BOT_CLIENT_TOKEN := ENV.get((key := 'BOT_CLIENT_TOKEN'))):
raise EnvKe... | python |
from django.db import models
class Customer(models.Model):
id = models.AutoField(primary_key=True, null=False)
name = models.CharField(max_length=200, null=False)
keyAPI = models.CharField(max_length=200, null=False)
pathTrainingDataSet = models.CharField(max_length=1000, null=True)
status = models... | python |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import configparser
import nbformat
from .static_text import Common, EvasionAttack
# Type of printing.
OK = 'ok' # [*]
NOTE = 'note' # [+]
FAIL = 'fail' # [-]
WARNING = 'warn' # [!]
NONE = 'none' # No label.
# Create report.
class IpynbRepor... | python |
"""
pygments.lexers.email
~~~~~~~~~~~~~~~~~~~~~
Lexer for the raw E-mail.
:copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, DelegatingLexer, bygroups
from pygments.lexers.mime import MIM... | python |
# import dota_utils as util
import os
# import cv2
import json
# from PIL import Image
import xmltodict
import xml.etree.ElementTree as ET
# from ShipRSImageNet_devkit import ShipRSImageNet_utils as util
# from collections import OrderedDict
wordname_50 = ['Other Ship', 'Other Warship', 'Submarine', 'Other Aircraft Ca... | python |
from draw2d import Viewer, Text, Line, Rectangle, Frame, Point, Circle
import math, time, random
viewer = Viewer(600,600)
W = 1.0
F = viewer.frame(0., W, 0., W)
F.add(Text("North", anchor_x="center", anchor_y="top", color=(0.2,0.2,1.0)).move_to(0.5,0.9))
F.add(Text("South", anchor_x="center", anchor_y="bottom", col... | python |
class Student():
# 类变量
# name = ''
sum = 0
age = 0
def __init__(self, name, age):
# 实例变量
self.name = name
self.age = age
self.__score = 0
# print(name) # xiaoming
# print(age) # 18
print(Student.age)
print(self.__class__... | python |
import os
import pytest
from ci_framework import FlopyTestSetup, base_test_dir
import flopy
base_dir = base_test_dir(__file__, rel_path="temp", verbose=True)
pthtest = os.path.join("..", "examples", "data", "swtv4_test")
swtv4_exe = "swtv4"
isswtv4 = flopy.which(swtv4_exe)
runmodel = False
verbose = False
swtdir ... | python |
from ursina import *
from model.pion import PionBlanc, PionNoir
class VuePion(Entity):
def __init__(self, position, qubic, *args, **kwargs):
self.qubic = qubic
super().__init__(
position=position,
*args, **kwargs
)
class VuePionFactory:
def __init__(self, qubic, pion='Classic'):
"""
Args:
pion... | python |
import db_handler
ZONE_MAPPING = {
27721: 3,
27767: 9,
-2: 7,
45041: 8,
27723: 3,
-6: 5,
27724: 5,
115_092: 5,
33130: 5,
27770: 2,
27726: 5,
61204: 4,
117_928: 4,
30754: 9,
35673: 8,
27774: 8,
27775: 8,
110_924: 8,
130_226: 12,
27779: 12,
... | python |
# Copyright (c) Microsoft Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | python |
# -*- test-case-name: mimic.test.test_cinder -*-
"""
Defines a mock for Cinder
"""
import json
from uuid import uuid4
from six import text_type
from zope.interface import implementer
from twisted.plugin import IPlugin
from mimic.rest.mimicapp import MimicApp
from mimic.catalog import Entry
from mimic.catalog import En... | python |
from sklearn.metrics import classification_report
import pandas as pd
import tests.test_utils as t
import unittest
from nlu import *
class SentimentTrainingTests(unittest.TestCase):
def test_sentiment_training(self):
#sentiment datase
df_train = self.load_sentiment_dl_dataset()#'/home/loan/Docum... | python |
import ntpath
import os
import sys
import tempfile
import unittest
from itertools import count
try:
from unittest.mock import Mock, patch, call, mock_open
except ImportError:
from mock import Mock, patch, call, mock_open
from flask import Flask, render_template_string, Blueprint
import six
import flask_s3
from... | python |
# Copyright (c) 2018, Ioannis Tziakos
# All rights reserved.
#
# Plugin hooks are inspired by the current implementations found in
# the tox.venv module and adapted to support edm.
import subprocess
import os
import re
import sys
from tox import hookimpl, exception
from tox.venv import VirtualEnv
COMMAND_FAILED = (
... | python |
# Generated by Django 2.1.1 on 2018-09-23 18:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0002_song'),
]
operations = [
migrations.AlterModelOptions(
name='song',
options={'ordering': ['position'... | python |
#!/usr/bin/env python
import dfl.dynamic_system
import dfl.dynamic_model as dm
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
m = 1.0
k11 = 0.2
k13 = 2.0
b1 = 3.0
class Plant1(dfl.dynamic_system.DFLDynamicPlant):
def __init__(self):
self.n_x = 2
self.n... | python |
# RUN this file for an example adventure.
# THEN go to 02_my_adventure.py to make your own!
from random import randint
def startGame():
print("This is an adventure game.")
input("Press enter to continue the text.")
print("When you see this you will need to respond. Here type 'ok'. Then press ent... | python |
from src.preprocessing.data_filter import DataFilter
from src.preprocessing.dataset import Article, Sentence, Token
class ThreeSentenceDataFilter(DataFilter):
def __init__(self, total_sentence_limit=None, *args, **kwargs):
self.article = None
self.sentence = None
self.last_entity = None
... | python |
import pytest
from pyvipr.examples_models.lopez_embedded import model
from pyvipr.pysb_viz.static_viz import PysbStaticViz
@pytest.fixture
def viz_model():
viz = PysbStaticViz(model)
return viz
def test_viz_exists(viz_model):
assert viz_model
def test_graphs(viz_model):
g_sp = viz_model.species_gr... | python |
# Generated by Django 2.1.5 on 2019-01-31 18:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ipam', '0023_change_logging'),
]
operations = [
migrations.AlterField(
model_name='vrf',
name='rd',
fiel... | python |
from itertools import product
with open("day-04.txt") as f:
numbers_str, *boards_str = f.read().rstrip().split("\n\n")
numbers = [int(n) for n in numbers_str.split(",")]
boards = {}
for b, board_str in enumerate(boards_str):
boards[b] = {}
for r, row in enumerate(board_str.splitlines()):
for c, n... | python |
import gffutils
import pyfaidx
def select_annotation_type(db, fasta, selectionAnnotationType):
"""
list of gff3 features as fasta record of selected gff3 type (e.g. mRNA)
"""
countFeature = db.count_features_of_type(selectionAnnotationType)
featureList = [None] * countFeature
i = 0
for feat... | python |
import socket
import win32.lib.win32serviceutil as win32serviceutil
import win32.servicemanager as servicemanager
import win32.win32event as win32event
import win32.win32service as win32service
class SMWinServiceBase(win32serviceutil.ServiceFramework):
_svc_name_ = "SampleleService"
_svc_display_name_ = "Sam... | python |
import os
import re
import subprocess
import shlex
from ConfigParser import SafeConfigParser
CONFIG_FILE = os.path.join(os.getcwd(), '.forrest')
def get_config():
config = SafeConfigParser()
config.read(CONFIG_FILE)
return config
def save_config(config):
config.write(open(CONFIG_FILE, 'w'))
def get_inpu... | python |
from http import HTTPStatus
from django.urls import reverse
from mock import patch
from barriers.models import Company
from core.tests import MarketAccessTestCase
class EditCompaniesTestCase(MarketAccessTestCase):
company_id = "0692683e-5197-4853-a0fe-e43e35b8e7c5"
company_name = "Test Company"
company_... | python |
#!/usr/bin/env python3
# Reading and Writing files
# Creates a new file object and assigning it to a variable called file
file = open ("spider.txt")
# readline method reads a single line of a file
print(file.readline())
# readline method reads the second line of a file - each time the readline method isi called the... | python |
import math
def length_norm(score):
length_tgt = len(score)
return sum(score) / length_tgt
def word_reward(score, reward):
length_tgt = len(score)
return sum(score) - reward * length_tgt
def bounded_word_reward(score, reward, bound):
"""
bound = L_predict
L_predict could be:
... | python |
import pandas as pd
while(1):
menu = {1:"Driver Login",
2:"Customer Login",
3:"ZULA Administarator",
4:"Exit"}
intial_cab_drivers = {"id":[1,2,3,4],
"Name":["aaa","bbb","ccc","ddd"],
"Pass":[111,222,333,444],
... | python |
# =============================================================================
# Copyright (c) 2016, Cisco Systems, Inc
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of sour... | python |
"""
link: https://leetcode.com/problems/word-ladder
problem: 给起始单词,结尾单词,与单词列表,问能否每次转换一个字母,使用列表中的单词由起始变换到结尾
solution: 无权最短路图,即BFS。难点在于如何构造图,一个很巧妙的思路,增加虚拟节点。将 hit 的相邻节点记为 hi*, h*t, *it,
将 hot 的相邻节点记为 ho*, h*t, *ot,这样两个节点就存在了相连路径。构造图后做BFS即可。
"""
class Solution:
def ladderLength(self, beginWord: str, end... | python |
import numpy as np
import pandas as pd
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
df_train = pd.read_csv('train.csv')
train=pd.DataFrame(df_train)
train = pd.crosstab(index=train["Type"],columns="count")
type = [[1,"Dog"], [2,"Cat"]]
pet = pd.DataFrame(type, columns = ['Type','Animal... | python |
#!/usr/bin/env python
import rospy
import numpy as np
from sensor_msgs.msg import CompressedImage,Image # @UnresolvedImport
from duckietown_msgs.msg import AntiInstagramHealth, BoolStamped, AntiInstagramTransform # @UnresolvedImport
from anti_instagram.AntiInstagram import *
from duckietown_utils.jpg import image_cv_... | python |
# coding: utf-8
import types
import pymssql
from itertools import chain
from .abstract import DatabaseAdapter
class MSSQLAdapter(DatabaseAdapter):
last_table = None
def get_connection(self):
if hasattr(self, 'connection') and self.connection:
return self.connection
params = {
... | python |
class Camera:
def __init__(self, game):
self.game = game
self.dx = 0
self.dy = 0
self.ny = 240
self.is_start = True
def start_camera(self):
self.dx = -2100
self.dy = -2100
def apply(self, obj):
obj.rect.x += self.dx
obj.rect.y += self... | python |
import libres
import threading
from cached_property import cached_property
from contextlib import contextmanager
from libres.modules import errors
missing = object()
required = object()
class StoppableService(object):
""" Services inheriting from this class have their stop_service method
called when the se... | python |
"""
COMMAND: SELECT
Select objects by id or name for further
command processes.
"""
import command
import cache
from util import logger
from api import APIRequests
class Select(command.Command):
@staticmethod
def get_invoke():
return 'SELECT'
@staticmethod
def get_args():
retur... | python |
from testcases import TestCaseWithFixture as TestCase
from django.http import HttpRequest
from django.contrib.auth.models import User, Permission
from core.models import Note
from tastypie.authorization import Authorization, ReadOnlyAuthorization, DjangoAuthorization
from tastypie import fields
from tastypie.resources ... | python |
from django.core.exceptions import ValidationError
from pulpo_forms.fieldtypes.Field import Field
from pulpo_forms.statistics.ListStatistics import ListStatistics
class ListField(Field):
"""
List field validator, render and analize methods
"""
def get_methods(self, **kwargs):
base = super(Li... | python |
from sqlalchemy import Column, Integer, Float, String, Date, Time
from shared.core.db import Base
class HourlyMainData(Base):
__tablename__ = 'HourlyMain'
Id = Column(Integer, primary_key=True, nullable=False)
StationId = Column(Integer, nullable=False)
Date = Column(Date, nullable=False)
Hour =... | python |
#!/usr/bin/env python
from __future__ import division
from __future__ import print_function
from builtins import range
from past.utils import old_div
import sys
from forcebalance.molecule import *
# Script to generate virtual sites and rename atoms in .gro file.
M = Molecule(sys.argv[1])
if 'M' in M.elem:
print(... | python |
from django.utils import timezone
from django.conf import settings
import datetime
from rest_framework_jwt.settings import api_settings
expires_delta = (api_settings.JWT_REFRESH_EXPIRATION_DELTA) - datetime.timedelta(seconds=200)
def jwt_response_handler(token, user=None, request=None):
return {
'token':... | python |
import zeit.cms.testing
import zeit.content.article.testing
def test_suite():
return zeit.cms.testing.FunctionalDocFileSuite(
'edit.landing.txt',
'edit.txt',
'edit.form.txt',
package='zeit.content.article.edit.browser',
layer=zeit.content.article.testing.WSGI_LAYER)
| python |
"""Auxiliar functions that may be used in most modules"""
from typing import List
import numpy as np
def compute_permutation_distance(
distance_matrix: np.ndarray, permutation: List[int]
) -> float:
"""Compute the total route distance of a given permutation
Parameters
----------
distance_matrix
... | python |
'''
test_var = False
if(test_var == True):
print("okay")
else:
print("this is not true")
number_a = 500.6
number_b = 100.4
if(number_a > number_b):
print(number_a,"is bigger than",number_b)
else:
print(number_b,"is bigger than",number_a)
# name = input("what's your name? ")
# print("your name is",n... | python |
#!/usr/bin/env python
"""Example script"""
from __future__ import division, print_function
import random
import time
from simanneal import Annealer
import click
import numpy as np
import rasterio
from rasterio.plot import reshape_as_image
from rio_color.operations import parse_operations
from rio_color.utils impor... | python |
class Card:
def __init__(self, card_type):
"""
card_type 0 is a skipbo card
card_type 1-12 are the normal value cards
actual value indicates the value a skipbo card takes on after it is played
"""
self.card_type = card_type
self.actual_value = card_type if car... | python |
import numpy as np
from lagom.envs.spaces import Box
from lagom.envs.wrappers import ObservationWrapper
class PartialFlattenDict(ObservationWrapper):
"""
Returns flattened observation from a dictionary space with partial keys into a Box space.
"""
def __init__(self, env, keys):
super().__ini... | python |
#
# Copyright 2022 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
import environ
ROOT_DIR = environ.Path(__file__) - 3
ENVIRONMENT = environ.Env()
if ENVIRONMENT.bool("DJANGO_READ_DOT_ENV_FILE", default=False):
# Operating System Environment variables have precedence over variables
# defined in the .e... | python |
# coding: utf-8
# # Performance of various Machine Learning Algorithms on Electrical Impedance Tomography Images
#
# ## Copyright (c) 2018, Faststream Technologies
#
# ## Author: Sudhanva Narayana
# In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
from sklearn.neighbors imp... | python |
import os
import numpy as np
import torch
import nibabel as nib
from glob import glob
import scipy.io
import random
from PIL import Image
import elastic_transform as elt
from torch.utils.data import Dataset
import torchvision.transforms.functional as F
def load_nifty(full_file_name):
img = nib.load(full_file_name... | python |
import functools
from typing import Type, Generic, TypeVar, Dict, Any, Optional
from drf_yasg.utils import swagger_auto_schema
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework_dataclasses.serializers import DataclassSerializer
from thairod.utils.decorators im... | python |
"""A config store holds the configuration data for running system-of-systems models with smif:
- model runs
- system-of-systems models
- model definitions
- strategies
- scenarios and scenario variants
- narratives
"""
from abc import ABCMeta, abstractmethod
class ConfigStore(metaclass=ABCMeta):
"""A ConfigStore ... | python |
# Copyright (C) 2018 Intel Corporation
#
# SPDX-License-Identifier: MIT
import os
path_prefix = os.path.join('cvat', 'apps', 'annotation')
BUILTIN_FORMATS = (
os.path.join(path_prefix, 'cvat.py'),
os.path.join(path_prefix, 'pascal_voc.py'),
os.path.join(path_prefix, 'yolo.py'),
os.path.join(path_prefi... | python |
dataFile = open("Day10_Data.txt")
asteroidCoordinates =[]
for corY,line in enumerate(dataFile):
for corX,c in enumerate(line):
if(c=="#"):
asteroidCoordinates.append([corX,corY])
curMax=0
astBaseX = astBaseY =0
for astBase in range( len(asteroidCoordinates)):
seenDivisionsR = ... | python |
# -*- encoding: utf-8 -*-
#
#
# Copyright (C) 2006-2011 André Wobst <wobsta@users.sourceforge.net>
#
# This file is part of PyX (http://pyx.sourceforge.net/).
#
# PyX 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 Founda... | python |
'''OpenGL extension ARB.transform_feedback3
This module customises the behaviour of the
OpenGL.raw.GL.ARB.transform_feedback3 to provide a more
Python-friendly API
Overview (from the spec)
This extension further extends the transform feedback capabilities
provided by the EXT_transform_feedback, NV_tran... | python |
"""
Meshing: Make and plot a 3D prism mesh
"""
from fatiando import mesher
from fatiando.vis import myv
mesh = mesher.PrismMesh(bounds=(-2, 2, -3, 3, 0, 1), shape=(4,4,4))
myv.figure()
plot = myv.prisms(mesh)
axes = myv.axes(plot)
myv.show()
| python |
import click
@click.command()
def main():
print("This is the CLI!")
if __name__ == '__main__':
main()
| python |
from absl import flags
FLAGS = flags.FLAGS
flags.DEFINE_integer('h_dim', default=32,
help='Hidden dim in various models.')
flags.DEFINE_integer('rnn_dim', default=256,
help='RNN hidden dim.')
flags.DEFINE_integer('rnn_n_layers', default=2,
help='Number ... | python |
"""
Compared with model_baseline, do not use correlation output for skip link
Compared to model_baseline_fixed, added return values to test whether nsample is set reasonably.
"""
import tensorflow as tf
import numpy as np
import math
import sys
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sy... | python |
"""
TODO module docstring
"""
from re import fullmatch
from typing import Optional
from datetime import timedelta, datetime
from jose import JWTError, jwt
from passlib.hash import bcrypt
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi import APIRouter, Depends, HTTPException, s... | python |
from webapp import db, login_manager
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin # is_authenticated is_loggedin usw...
@login_manager.user_loader # if user is authenticated, then....
def load_user(user_id):
return Us... | python |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... | python |
var1 = 'Geeks'
print("Original String :-", var1)
print("Updated String :- ", var1[:5] + 'for' + 'Geeks') # statement 1
| python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.