content stringlengths 5 1.05M |
|---|
from winrm.protocol import Protocol
import sys
'''
Author: Mike Felch (c) 2020, @ustayready
-
Copyright 2020 Mike Felch
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 restrictio... |
# https://leetcode.com/problems/linked-list-cycle/description/
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
"""
传统思路,循环一遍,每次都做一个标记
"""
if not head:
return False
... |
from flask import Flask, request, jsonify
from flask_cors import CORS
from os.path import dirname, realpath
from os import listdir
from analyze_documents import build_lda_model
app = Flask(__name__)
CORS(app)
def json_response(status_code, data):
res = jsonify(data)
res.status_code = status_code
return r... |
from urllib.parse import urljoin
from scrapy import Request
from product_spider.items import RawData
from product_spider.utils.maketrans import formula_trans
from product_spider.utils.spider_mixin import BaseSpider
class VivanSpider(BaseSpider):
name = "vivan"
allowd_domains = ["vivanls.com/"]
start_url... |
import numpy as np
from tabulate import tabulate
def _derive_coco_results(self, coco_eval, iou_type, class_names=None):
"""
Derive the desired score numbers from summerized COCOeval.
Args:
coco_eval (None or COCOEval): None represents no predictions from model.
iou_type... |
#! /usr/bin/env python
import rospy
from multimodal_writer.msg import HandInfoList, HandInfo, FingerInfo
from visualization_msgs.msg import Marker, MarkerArray
import tf
from geometry_msgs.msg import Pose, Vector3, Quaternion, Point
from tf import transformations as transf
from std_msgs.msg import Header, ColorRGBA
br... |
# -*- coding: utf-8 -*-
"""Edit tests for the flow module."""
#
# (C) Pywikibot team, 2015
#
# Distributed under the terms of the MIT license.
#
from __future__ import unicode_literals
__version__ = '$Id: 9844f5d04efa704b740caff527921bade7038828 $'
from pywikibot.flow import Board, Topic, Post
from pywikibot.tools i... |
"""Combine all winner solutions in previous challenges (AutoCV, AutoCV2,
AutoNLP and AutoSpeech).
"""
import os
import sys
here = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(here, ""))
model_dirs = [
"", # current directory
"Auto_Tabular",
]
for model_dir in model_dirs:
sys.... |
from dataclasses import dataclass, field
from typing import List, Optional
__NAMESPACE__ = "sdformat/v1.2/sensor.xsd"
@dataclass
class Sensor:
"""
The sensor tag describes the type and properties of a sensor.
Parameters
----------
always_on: If true the sensor will always be updated according to... |
"""Classes for representing properties of STIX Objects and Cyber Observables."""
import base64
import binascii
import copy
import inspect
import re
import uuid
from .base import _STIXBase
from .exceptions import (
CustomContentError, DictionaryKeyError, MissingPropertiesError,
MutuallyExclusivePropertiesError... |
###################################################################################
# Author: Bert Van Acker (bva.bmkr@gmail.com)
# Version: 0.1.0
# Lisence: LGPL-3.0 (GNU Lesser General Public License version 3)
#
# Description: Documentor class handling document and template generation
###########################... |
from rest_framework import serializers
#from .models import Account
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
# class UserSerializer(serializers.ModelSerializer):
# def create(self, *args, **kwargs):
# user = super().create(*args, **kwargs)
# ... |
"""DSM Upgrade data and actions."""
class SynoCoreUpgrade:
"""Class containing upgrade data and actions."""
API_KEY = "SYNO.Core.Upgrade"
API_SERVER_KEY = API_KEY + ".Server"
def __init__(self, dsm):
"""Constructor method."""
self._dsm = dsm
self._data = {}
... |
import os
import shutil
import time
import click
from flask import Flask, current_app
from flask.cli import with_appcontext
from flask_sqlalchemy import SQLAlchemy
import flask_uploads
from flask_uploads import UploadSet, configure_uploads
import flask_login
from flask_apscheduler import APScheduler
from flask_bootstr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#------------------------------------------------------
# @ File : cfgs.py
# @ Description:
# @ Author : Alex Chung
# @ Contact : yonganzhong@outlook.com
# @ License : Copyright (c) 2017-2018
# @ Time : 2020/9/7 下午2:45
# @ Software : PyCharm
#-----... |
# user_model.py
# Bibliotkek für Data Visualizing
# Author : Dr.-Ing. The Anh Vuong
# + your Name
# Model Template
# yc(x) = function(y(x), reprod, Incubation Period, recovery rate)
# x = date time
# implement
# yc[] = my_model_x(y[],faktor,Tau, gesund)
# faktor = R -Factor Fix or realtiv
# Tau ... |
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.urls import path, include
from .views import (
Go_theme_Page,
Theme1_View,
PubTopic_View,
Index_View,
default_index,
Topic_Content_View,
Topic_Content_View1,
Go_Page,
Go_Comment_Page,
Theme2_View,
delete_to... |
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from shared import config
engine = create_engine(config.get_engine_uri())
Session = sessionmaker(bind=engine)
Base = declarative_base()
|
from .nested import * |
import ezdxf
import numpy as np
import matplotlib.pyplot as plt
def inch_to_mm(val):
return 25.4*val
def mm_to_inch(val):
return val/25.4
def get_sawtooth_point_list(param):
inner_radius = param['arena_radius'] - 0.5*param['sawtooth_depth']
outer_radius = param['arena_radius'] + 0.5*param['sawtooth_... |
# -*- coding: utf-8 -*-
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from nose.tools import eq_, ok_
from mozillians.common.tests import TestCase
from mozillians.groups.models import Group, GroupAlias, GroupMembership
from mozillians.groups.tests import (GroupAliasFa... |
from collections import deque
from hashlib import md5
normal_puzzle_input = 'pslxynzg'
test_case1 = 'ihgpwlah'
test_case2 = 'kglvqrro'
test_case3 = 'ulqzkmiv'
test_case1_answer = 'DDRRRD'
test_case2_answer = 'DDUDRLRRUDRD'
test_case3_answer = 'DRURDRUDDLLDLUURRDULRLDUUDDDRR'
def next_moves(current):
puzzle_inpu... |
"""
Copyright: MAXON Computer GmbH
Author: Maxime Adam
Description:
- Convert a Polygon Object to a Volume and save this volume to a VDB File
- Save a VDB file.
Class/method highlighted:
- maxon.Vector
- maxon.BaseArray
- maxon.frameworks.volume.VolumeRef
- maxon.frameworks.volume.VolumeConver... |
# -*- coding: utf-8 -*-
import docutils
from docutils import nodes
from docutils.parsers import rst
from docutils.parsers.rst import directives, roles, Directive
from pelican import signals
from pelican.readers import RstReader, PelicanHTMLTranslator
class SemanticHTMLTranslator(PelicanHTMLTranslator):
def visit... |
import math
import sys
import pytest
from selenium.common.exceptions import NoSuchElementException, \
WebDriverException
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
import qmxgraph.constants
from qmxgraph import constants, js, server
from qmxgraph.api import QmxGrap... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import numpy as np
from simulariumio.mcell import McellConverter, McellData
from simulariumio import DisplayData, MetaData
from simulariumio.constants import (
DEFAULT_CAMERA_SETTINGS,
CURRENT_VERSION,
DISPLAY_TYPE,
)
@pytest.mark.parametrize(... |
# Copyright 2018 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# Simple TMX library
#
# 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... |
#!/usr/bin/env python3
import numpy as np
import spacy
from spacy.lang.en import English
import torch
from infersent.models import InferSent
MODEL_VERSION = 1
MODEL_PATH = "infersent/encoder/infersent%s.pkl" % MODEL_VERSION
MODEL_PARAMS = {'bsize': 64, 'word_emb_dim': 300, 'enc_lstm_dim': 2048,
'pool... |
import discord
from discord.ext import tasks, commands
import asyncio
import socketio
import threading
import subprocess
import time
from queue import Queue, Empty
from threading import Thread
from requests import get
import os
import re
import boto3
import utils
client = boto3.client('ec2')
chat_reg = re.comp... |
import tensorflow as tf
import argparse
import os
import re
from PIL import Image
import numpy as np
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def parse_a... |
from enum import Enum
from collections import defaultdict
import multiprocessing
import os
import sys
import pickle
import random
import time
import warnings
from ilm.string_util import check_exists_and_return
import numpy as np
import torch
import torch.nn.functional as F
from torch.utils.data import (DataLoader, Ran... |
import numpy as np
from ignite.metrics import Metric
class IntersectionOverUnion(Metric):
"""Computes the intersection over union (IoU) per class.
based on: https://github.com/wkentaro/pytorch-fcn/blob/master/torchfcn/utils.py
- `update` must receive output of the form `(y_pred, y)`.
"""
... |
'''
Sample colours from selected image and overlay selected colours along bottom edge of image.
For use in Pythonista
UI selector borrowed directly from Ole Zorn @olemoritz: https://gist.github.com/omz/ae96874dfbda54ed2771
'''
import photos
import Image
import random
import ui
import console
import clipboard
colourc... |
need_domains = ['github.com',
'gist.github.com',
'assets-cdn.github.com',
'raw.githubusercontent.com',
'gist.githubusercontent.com',
'cloud.githubusercontent.com',
'camo.githubusercontent.com',
'avatars0.gith... |
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import logging
from buckshot import errors
from buckshot import signals
from buckshot import tasks
from buckshot import threads
LOG = logging.getLogger(__name__)
class Suicide(Exception):
"""Raised when a Listener kills it... |
'''
The client manager manages data in client table
'''
from datetime import datetime
import asyncpg
import pytz
from .const import connection_url
class ClientManager(object):
async def init(self):
conn = await asyncpg.connect(connection_url())
await conn.execute('''
CREATE TABLE IF ... |
#! /usr/bin/python
"""
dispatch_async.py
By Paul Malmsten, 2010
pmalmsten@gmail.com
This example continuously reads the serial port and dispatches packets
which arrive to appropriate methods for processing in a separate thread.
"""
from xbee.thread import XBee
from xbee.helpers.dispatch import Dispatch
import time
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 23 08:15:36 2019
@author: 42895538859
"""
import numpy as np
A = np.array([[1,2,3],[4,5,6]])
B = np.array([[1,2,3,4],[5,6,7,8]])
m,n = A.shape
p,q = B.shape
K = np.zeros((m*p, n*q))
for i in range(m):
for j in range(n):
K[i*p:(i+1)*p, j*q:(j+1)*q] = A[i,... |
def read_next(*args):
for item in args:
for i in item:
yield i
for item in read_next('string', (2,), {'d': 1, 'I': 2, 'c': 3, 't': 4}):
print(item, end='')
for i in read_next('Need', (2, 3), ['words','.']):
print(i) |
import re
from functools import partial
from marshmallow import Schema
snake_case = re.compile(r"(?<=\w)_(\w)")
camel_case = partial(snake_case.sub, lambda m: m[1].upper())
class CamelCasedSchema(Schema):
def on_bind_field(self, field_name, field_obj, _cc=camel_case):
field_obj.data_key = _cc(field_name... |
import click
from datetime import datetime as dt
from secrets import token_urlsafe
from flask.cli import FlaskGroup
from {{cookiecutter.app_name}} import create_app
@click.group(cls=FlaskGroup, create_app=create_app)
def cli():
pass
@cli.command('init')
def init():
""" Init admin user """
from {{cookiec... |
from django.conf import settings
from django.db import models
# from django.core.urlresolvers import reverse
from django_hosts.resolvers import reverse
from .validators import validators_url, validators_dot_com
from .utils import code_generator, create_shortcode
SHORTCODE_MAX = getattr(settings, "SHORTCODE_MAX", ... |
#!/usr/bin/env python
# This is a script intended to be ran only when there are updates to the item
# database. The results are dumped into a file as JSON to be read by the app.
#
# This script requires an installed (and updated) copy of Eve Online. This
# requires Reverence, a tool which looks at the game cache to get... |
import logging
logger = logging.getLogger("naucse")
logging.basicConfig(level=logging.DEBUG)
|
import argparse
import platform
import subprocess
from edgetpu.detection.engine import DetectionEngine
import socket
import io
import time
import numpy as np
import json
from lib import read_label_file
from PIL import Image
from PIL import ImageDraw
# UDP_IP = '192.168.2.183'
UDP_IP = '127.0.0.1'
TCP_IP = UDP_IP
# ... |
import sys
import os
import re
import OsTools as ot
import GMX as gmx
def put_grofile_in_memory(ifile):
fi = open(ifile,"r")
fi_mem = fi.readlines()
fi.close()
length = len(fi_mem)
for i in range(2):
l = fi_mem[i].strip().split()
fi_mem[i] = l
for i in range(2,lengt... |
"""
false_triples.py
Creates false training triples under CWA.
"""
from random import choice
from collections import defaultdict
import numpy as np
from false_generator import FalseGenerator
def get_domains(subjects, predicates):
out = defaultdict(set)
for s,p in zip(subjects,predicates):
out[p].ad... |
import math
import operator
import numpy as np
import cv2
from util.long import typeVal
class ArithmeticList:
def __init__(self, *args):
self.coords = list(args)
def __add__(self, other):
return self._mapOperation(other, operator.add)
def __sub__(self, other):
return self._ma... |
from Dog import Dog
fido = Dog() |
# This file is part of ranger, the console file manager.
# License: GNU GPL version 3, see the file "AUTHORS" for details.
"""Shared objects contain singletons for shared use."""
from ranger.ext.lazy_property import lazy_property
class FileManagerAware(object):
"""Subclass this to gain access to the global "FM"... |
def test_jenkins_is_installled(host):
jenkins = host.package("jenkins")
assert jenkins.is_installed
assert jenkins.version.startswith("2.2")
def test_jenkins_running_and_enabled(host):
jenkins = host.service("jenkins")
assert jenkins.is_running
assert jenkins.is_enabled
def test... |
import argparse
import logging
import os
import random
import socket
import sys
from sklearn.utils import shuffle
import numpy as np
import psutil
import setproctitle
import torch
sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../../")))
from fedml_api.model.finance.vfl_classifier import VFLClassif... |
#!/usr/bin/env python
import sys
import sqlite3
import random
def _main(args):
if len(args) < 6:
print "usage: patser_hit_window_xls.py <patser_hit_db> <matrix_name> <winsize> <xls> <nrandom> <xls-type; 0=(name\tchr\tpeak);1=MACS>"
sys.exit(1)
conn = sqlite3.connect(args[0])
conn.row... |
'''OpenGL extension EXT.shared_texture_palette
Overview (from the spec)
EXT_shared_texture_palette defines a shared texture palette which may be
used in place of the texture object palettes provided by
EXT_paletted_texture. This is useful for rapidly changing a palette
common to many textures, rather than having... |
#!/usr/bin/env python
import pygame
from mob_class import Mob
#-------- This is the method I wanted to test, but trying to import it just launches the game..... so I brought it here for proof of concept.
all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
def newmob(health): #Evan
if health != 100:... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: chia_tea/protobuf/generated/hardware.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _r... |
# -*- coding: utf-8 -*-
# Author: jlopes@usp.br
import os
import numpy as np
import pickle
class KitData(object):
def __init__(self,workspace,corpus_name,language):
self.workspace = workspace
self.corpus_name = corpus_name
self.language = language
def info_get(self):
... |
import pygame
pygame.init()
win = pygame.display.set_mode((500,500))
pygame.display.set_caption("First Game")
x = 50
y = 50
width = 40
height = 60
vel = 5
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = ... |
# Copyright 2015 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""Manages PubSub topic that receives notifications about AuthDB changes.
The topic is hosted in auth_service Cloud Project and auth_service mana... |
from direct.interval.IntervalGlobal import *
from direct.distributed.ClockDelta import *
from toontown.toonbase import ToontownGlobals
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM
import DistributedCogHQDoor
from toontown.hood import ZoneUtil
from BossLobbyGui import BossLobbyGui... |
import pandas as pd
from Model.resnet18 import ResNet
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, Sequential, optimizers
from LoadData.LoadData import InputTrainImg, InputTestImg
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
from sklearn.metrics... |
#!/usr/bin/env python
# coding=utf-8
__author__ = 'zhaoliang'
__email__ = 'zhaoliang@iflytek.com'
__created__ = '15/12/19'
import os
CSRF_ENABLED = True
SECRET_KEY = 'guess what you can and try it'
DATABASE_URI = {
'host': 'localhost',
'user': 'root',
'passwd': 'root',
'port': 3306,
'db': 'vans... |
FAKE_REGION = 'eu-west-1'
FAKE_IDENTITY_DOCUMENT_STRING = """{
"accountId" : "000011112222",
"architecture" : "x86_64",
"availabilityZone" : "eu-west-1a-ignored",
"billingProducts" : null,
"devpayProductCodes" : null,
"marketplaceProductCodes" : null,
"imageId" : "ami-00001111222233334",
"instanceId" : ... |
from mopidy_tunein import tunein
ASX = b"""<ASX version="3.0">
<TITLE>Example</TITLE>
<ENTRY>
<TITLE>Sample Title</TITLE>
<REF href="file:///tmp/foo" />
</ENTRY>
<ENTRY>
<TITLE>Example title</TITLE>
<REF href="file:///tmp/bar" />
</ENTRY>
<ENTRY>
<TITLE>Other title</TITLE>
<REF href... |
def rectangle(length, width):
if length <= 0 or width <= 0:
raise ValueError("The side length cannot be negative or zero!")
measures = {"area": length * width}
print(f'The rectangle has area {format(measures["area"])}')
return measures
|
# Day3 of my 100DaysOfCode Challenge
# Instructions
# Congratulations, you've got a job at Python Pizza. Your first job is to build an automatic pizza order program.
# Based on a user's order, work out their final bill.
# Small Pizza: $15
# Medium Pizza: $20
# Large Pizza: $25
# Pepperoni for Small Pizza: +$2
# ... |
import numpy as np
def camera_matrix_to_intrinsics(K):
'''
If camera matrix is a 3x3 matrix where:
| fx 0 cx |
K = | 0 fy cy |
| 0 0 1 |
Then the function returns:
fx = K[0,0]
fy = K[1,1]
cx = K[0,2]
cy = K[1,2]
:param K: 3x3 camera matrix
:return: (fx, fy), (c... |
"""
"""
import numpy as np
import tensorflow as tf
# from libs.sn import spectral_normed_weight
def embed_y(inputs, vocab_size=1000, embedding_dim=300, word2vec_file=None,
spectral_normed=False, update_collection=None, reuse=False):
"""
Args:
inputs: int, (batch size, 1).
vocab_siz... |
from sklearn.manifold import TSNE
import pandas as pd
from . import scale_and_pca
from .predictor import optimal_bayes, optimal_K, gaussian_clustering
from .utils import group_samples
def quick_TSNE(X, random_state=420, dim=2):
"""
Quick and easy method of visually validating predictions
X: 2d array of ... |
'''
Клавиатура
'''
def isBroken(a, k):
cnt = [0] * len(a)
for e in k:
cnt[e - 1] += 1
for e in range(len(a)):
if (a[e] < cnt[e]):
print('YES', end='\n')
else:
print('NO', end='\n')
n = int(input())
a = [int(j) for j in input().split()]
k = int(input())
p = ... |
import os
import re
from datetime import timedelta
from .._exceptions import ConfigError
from .default import NAMELIST_DEFAULTS
from .._asset_list import config_to_asset_list
from ..filesystem import get_fs
def get_n_processes(config):
n_tiles = config["namelist"]["fv_core_nml"].get(
"ntiles", NAMELIST_DE... |
from RecAPI import get_recognitions
def rec_etl(file, client_key, start, end):
quit()
|
from django.contrib import admin
from .models import URLScraped,ColumnData
admin.site.register(URLScraped)
admin.site.register(ColumnData) |
import uuid
from django.db import models
class Currency(models.Model):
"""Currency model"""
name = models.CharField(max_length=120, null=False,
blank=False, unique=True)
code = models.CharField(max_length=3, null=False, blank=False, unique=True)
symbol = models.CharField(m... |
import sys # using local mdml_client
sys.path.insert(1, '../')
import mdml_client as mdml
import time
exp = mdml.experiment("TEST", "test", "testtest", "merfpoc.egs.anl.gov")
exp.add_config('dev_config.json')
exp.send_config()
time.sleep(1)
curr_time = mdml.unix_time(True) # True for integer return instead of string
... |
from launch import LaunchDescription
from launch_ros.actions import Node
from launch.actions import ExecuteProcess
def generate_launch_description():
cmd = ['MicroXRCEAgent', 'udp', '-p 2018']
env = {'LD_PRELOAD': "/usr/local/lib/libfastrtps.so.1 /usr/local/lib/libfastcdr.so.1"}
return LaunchDescription([... |
class QueueTests:
def test_init(self):
q = self.Queue()
def test_add_and_remove_oneitem(self):
q = self.Queue()
q.enqueue(3)
self.assertEqual(q.dequeue(), 3)
def test_alternating_addremove(self):
q = self.Queue()
for i in range(1000):
q.enqueue(i... |
import discord
import asyncio
import random
import requests
from bs4 import BeautifulSoup
from discord.ext import commands
class Background_Tasks_Cog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bg_task = self.bot.loop.create_task(self.status())
self.bg_task =... |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import json
import multiprocessing
import os
import sys
import time
import pprint
import hyperopt
from hyperopt import hp
def run_vgg19(batch_size=64):
import numpy as np
import keras
import plaidml
# cifar10 data is 1/7th ... |
import base64
import json
import typing
from datetime import datetime, timedelta
from Crypto.Cipher import AES
from Crypto.Util import Padding
from starlette.responses import Response
class PrettyJSONResponse(Response):
media_type = "application/json"
def render(self, content: typing.Any) -> bytes:
... |
from py_counter.py_counter import py_counter |
#
# PySNMP MIB module CLAB-ANI-DEV-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CLAB-ANI-DEV-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:24:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
import numpy as np
def sigmoid(X):
return 1 / (1 + np.exp(-X))
def softmax(X):
if X.ndim == 1:
exp = np.exp(X)
return exp / np.sum(exp)
elif X.ndim == 2:
exp = np.exp(X)
sum = np.sum(exp, axis=1, keepdims=True)
return exp / sum
def cross_entropy(Y, T):
EPSION ... |
######## Snakemake header ########
import sys; sys.path.append("/home/cmb-panasas2/skchoudh/software_frozen/anaconda27/envs/riboraptor/lib/python3.5/site-packages"); import pickle; snakemake = pickle.loads(b'\x80\x03csnakemake.script\nSnakemake\nq\x00)\x81q\x01}q\x02(X\x06\x00\x00\x00configq\x03}q\x04X\x0b\x00\x00\x00... |
from requests import put, delete
response = delete('http://localhost:9200/customer')
print(response.json())
response = put('http://localhost:9200/customer?pretty')
print(response.json())
|
from builtins import dict
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import BaseUserManager
from django.conf import settings
from django.core.validators import MaxValueValidator, MinValueVal... |
from flask import Flask, g, redirect, request
from app.core import db, jwt, sg, configure_app, mail_services, gc_services
from flask_cors import CORS, cross_origin
from models import User
from app.helpers.response import response_error
from app.routes import init_routes
from datetime import datetime
import time
import... |
"""Lists"""
from functions.lists import no_language_tag_list
from functions.lists import nosplit_bnode_list
"""Imported Functions"""
from functions.formatting_functions import create_bnode_name
from functions.logical_source_functions import generate_constant_logical_source
from functions.logical_source_function... |
# -*- coding: utf-8 -*-
"""Filesystem functionality."""
import logging
import os
import magic
from sqlalchemy.exc import OperationalError
from esis.db import Database
logger = logging.getLogger(__name__)
class TreeExplorer(object):
"""Look for sqlite files in a tree and return the valid ones.
:param di... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
import re
import time
from settings import URL, applet, key
def get_data(URL):
resp = requests.get(URL)
pat = r"(?<=\[\[\[\"tsp-mr4\",\"tsp-vm\"]).+(?=,\[null,\[\[\"tsp-mr4\")"
x = re.findall(pat, resp.text)
x = str(x)
scores = re.sub(r'\[... |
from flask import json, jsonify
from datetime import datetime
from os import path
GARASTAVOKLIS = "garastavoklis.txt"
def pieraksti_garastavokli(dati):
# Sākumā ielasām visus garastāvokļus masīvā no faila
faila_esosie_garastavokli = []
# Uzstādām karogu uz False, jo sākumā neko neesam meklējuši
lieto... |
from .api import SchoologyApi
from .objects import *
import click_log
from cached_property import cached_property
log = click_log.basic_config('lms')
class Schoology:
def __init__(self, config):
RestObject._sc = self # XXX HACK!
self.conf = config['schoology']
self.api = SchoologyApi(self... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r"contributions/(\d+)/total", views.total_contributions, name="total_contributions"),
url(r"expenditures/(\d+)/total", views.total_expenditures, name="total_expenditures"),
url(r"expenditures/categories/(\d+)/total", views.spending_ca... |
# -*- coding: utf-8 -*-
# Copyright 2011-2012 Antoine Bertin <diaoulael@gmail.com>
#
# This file is part of subliminal.
#
# subliminal is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 3 of... |
"""
Tagging related views.
"""
from django.http import Http404
from django.utils.translation import ugettext as _
from django.views.generic.list_detail import object_list
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import get_object_or_404, render_to_response
from django.http import... |
import pathlib
import torch
from google.protobuf import text_format
from second.protos import pipeline_pb2
from second.builder import target_assigner_builder, voxel_builder
from second.pytorch.builder import box_coder_builder
from second.pytorch.builder import second_builder_for_official_onnx_and_cuda
import onnx
impor... |
from django.http import HttpResponse
class MyException(Exception):
pass
def ok(request):
"""
View that doesn't raise
"""
return HttpResponse("<html><body>OK</body></html>")
def oh_no(request):
"""
View that raises an exception
"""
raise MyException("oh no")
|
import pytest
import rasterio
from rasterio.errors import RasterioDeprecationWarning
from rasterio.profiles import default_gtiff_profile
def test_set_band_descriptions(tmpdir):
"""Descriptions can be set when dataset is open"""
tmptiff = str(tmpdir.join('test.tif'))
with rasterio.open(
tmptif... |
################################
#
# Default component settings
#
################################
# Pinlabel
pinlabel = {
"tag": "pinlabel",
"body": {
"x": 6,
"y": 0,
"width": 80,
"height": 26,
"corner_radius": 3,
"tag": "pinlabel__body",
},
"leaderline"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.