content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from tensorflow.keras import layers, models # (Input, Dense), (Model)
from tensorflow.keras.datasets import mnist
import numpy as np
import matplotlib.pyplot as plt
class AE(models.Model):
def __init__(self, x_nodes=784, h_dim=36):
x_shape = (x_nodes,)
x = layers.Input(shape=x_shape)
h = l... | python |
"""Find and filter files. Supports BIDSPath objects from `mne-bids`."""
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional, Sequence, Union
import mne_bids
from pte.filetools.filefinder_abc import DirectoryNotFoundError, FileFinder
def get_filefinder(
datatype: str, h... | python |
import chex
import jax
import jax.numpy as jnp
from typing import Callable, Optional, Tuple
from .moment import MomentTransform, MomentTransformClass
from chex import Array, dataclass
import tensorflow_probability.substrates.jax as tfp
dist = tfp.distributions
class UnscentedTransform(MomentTransformClass):
def ... | python |
"""
Core contributors is the cardinality of the smallest set of contributors whose \
total number of commits to a source code repository accounts for 80% or more of \
the total contributions.
"""
from pydriller import Repository
def core_contributors(path_to_repo: str) -> int:
"""
Return the number of develo... | python |
import numpy as np
from scipy.stats import pearsonr
import argparse
import data
import logging, sys
logger = logging.getLogger(__name__)
logger.setLevel(10)
ch = logging.StreamHandler(sys.stdout)
ch.setFormatter(logging.Formatter("[%(asctime)s] %(levelname)s - %(message)s"))
logger.addHandler(ch)
def main():
par... | python |
from cocoa.web.main.utils import Messages as BaseMessages
class Messages(BaseMessages):
ChatCompleted = "Great, you reached a final offer!"
ChatIncomplete = "Sorry, you weren't able to reach a deal. :("
Redirect = "Sorry, that chat did not meet our acceptance criteria."
#BetterDeal = "Congratulations, ... | python |
class Book:
def __init__(self, content: str):
self.content = content
class Formatter:
def format(self, book: Book) -> str:
return book.content
class Printer:
def get_book(self, book: Book, formatter: Formatter):
formatted_book = formatter.format(book)
return formatted_boo... | python |
import math
import numpy as np
import torch
import torch.nn as nn
def default_conv(in_channels, out_channels, kernel_size=3, bias=True):
return nn.Conv2d(
in_channels, out_channels, kernel_size,
padding=(kernel_size//2), bias=bias)
class MeanShift(nn.Conv2d):
def __init__(self, rgb_range, rg... | python |
from calendar import timegm
from datetime import datetime, timedelta
import jwt
import pytest
from oauthlib.oauth2 import (
InvalidClientError,
InvalidGrantError,
InvalidRequestFatalError,
)
from h.services.oauth._errors import (
InvalidJWTGrantTokenClaimError,
MissingJWTGrantTokenClaimError,
)
fr... | python |
import logging
from django.core.management import BaseCommand
from oldp.apps.laws.models import LawBook
LAW_BOOK_ORDER = {
'bgb': 10,
'agg': 9,
'bafog': 9,
}
# Get an instance of a logger
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = 'Assign predefined order values to la... | python |
# -*- coding: utf-8 -*-
from faker.providers import BaseProvider
class CustomProvider(BaseProvider):
sentences = (
'Hello world',
'Hi there',
'Ciao Bello',
)
def greeting(self):
return self.random_element(self.sentences)
| python |
from dcgan import *
from resnet import *
| python |
import socket, os, json, tqdm
import shutil
SERVER_PORT = 8800
SERVER_HOST = "0.0.0.0"
BUFFER_SIZE = 1024
root_dir = "/home/hussein/dfs_dir"
def connect_to_name_server(sock, command, name_server):
print(f"[+] Connecting to {name_server[0]}:{name_server[1]}")
sock.connect(name_server)
print("[+] Connecte... | python |
from rest_framework import serializers, status
from rest_framework.exceptions import APIException
from projects.serializers.base_serializers import ProjectReferenceWithMemberSerializer
from users.serializers import UserSerializer
from teams.serializers import TeamSerializer
from teams.models import Team
from .base_seri... | python |
from django.conf import settings
from django.urls import include, path, re_path
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
# CVAT engine.urls is redirecting 'unknown url' to /dashboard/ whi... | python |
# -*- coding:utf-8 -*-
import re
def parse(s):
l = re.sub(r'\s+', ', ', (' '+s.lower()+' ').replace('(', '[').replace(')', ']'))[2:-2]
return eval(re.sub(r'(?P<symbol>[\w#%\\/^*+_\|~<>?!:-]+)', lambda m : '"%s"' % m.group('symbol'), l))
def cons(a, d):
if atom(d):
return (a, d)
return (lambda... | python |
from flatland.envs.agent_utils import RailAgentStatus
from flatland.envs.malfunction_generators import malfunction_from_params
from flatland.envs.observations import GlobalObsForRailEnv
from flatland.envs.rail_env import RailEnv
from flatland.envs.rail_generators import sparse_rail_generator
from flatland.envs.schedule... | python |
# 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
# distribu... | python |
# Generated by Django 3.2.12 on 2022-03-31 23:23
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='LFPost',
fields=[
('id', m... | python |
from hamcrest import *
from utils import *
from vinyldns_context import VinylDNSTestContext
from vinyldns_python import VinylDNSClient
class ListGroupsTestContext(object):
def __init__(self):
self.client = VinylDNSClient(VinylDNSTestContext.vinyldns_url, access_key='listGroupAccessKey',
... | python |
#!/usr/bin/env python3
# Hackish script to automatically generate some parts of JSON file required for android-prepare-vendor
# Requires 4 arguments:
# (1) device name
# (2) module-info.json from build (3) below, can be found under out/target/product/<device>/module-info.json
# (3) listing of extracted files from a bu... | python |
import csv
from math import *
class Point:
def __init__(self, x, y, z, mag=0):
self.x = x
self.y = y
self.z = z
self.mag = mag
class Polar:
def __init__(self, r, theta, vphi, mag=0):
self.r = r
self.theta = theta # 0 < theta < pi
self.vphi = vphi # -pi < vphi < pi
self.mag = mag
def get_polar_... | python |
"""
The MIT License (MIT)
Copyright (c) 2014 NTHUOJ team
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, ... | python |
from tests.utils import W3CTestCase
class TestBottomOffsetPercentage(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'bottom-offset-percentage-'))
| python |
from collections import defaultdict
def top_3_words(text):
text = text.lower().strip(',').strip('.').strip('"')
print(text)
counter = defaultdict(int)
for word in text.split():
counter[word] += 1
return sorted(
counter.keys(),
reverse=True,
key = lambda item : counte... | python |
# Q. Take input from the user to get fibonacci series till the number entered
# Ex - input:3
# Ouput: 0, 1, 1
nterms = int(input("How many terms do you want? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there i... | python |
import topologylayer.nn
import topologylayer.functional
from topologylayer.functional.persistence import SimplicialComplex
| python |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 27 08:01:36 2020
@author: Ardhendu
"""
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 13 10:33:32 2019
@author: Ardhendu
"""
from keras.layers import Layer
#from keras import layers
from keras import backend as K
import tensorflow as tf
#from Spectr... | python |
from typing import Union, List, Optional
from pyspark.sql.types import (
StructType,
StructField,
StringType,
ArrayType,
DateType,
DataType,
)
# This file is auto-generated by generate_schema so do not edit manually
# noinspection PyPep8Naming
class DeviceSchema:
"""
This resource ide... | python |
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
import dace
import numpy as np
from dace.frontend.python.common import DaceSyntaxError
@dace.program
def for_loop():
A = dace.ndarray([10], dtype=dace.int32)
A[:] = 0
for i in range(0, 10, 2):
A[i] = i
return A
def ... | python |
import WebArticleParserCLI
urls = ['http://lenta.ru/news/2013/03/dtp/index.html',
'https://lenta.ru/news/2017/02/11/maroder/',
'https://lenta.ru/news/2017/02/10/polygon/',
'https://russian.rt.com/world/article/358299-raketa-koreya-ssha-yaponiya-kndr-tramp',
'https://russian.rt.com/russia/news/358337-sk-proverka-gibel-... | python |
#
# ida_kernelcache/build_struct.py
# Brandon Azad
#
# A module to build an IDA structure automatically from code accesses.
#
import collections
import idc
import idautils
import idaapi
from . import ida_utilities as idau
_log = idau.make_log(3, __name__)
def field_name(offset):
"""Automatically generated IDA ... | python |
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
# data_test.py
# Jun/05/2018
# ---------------------------------------------------------------
import cgi
import json
# ---------------------------------------------------------------
form = cgi.FieldStorage()
#
message = []
data_in = ""
message.append("start")
#
if "ar... | python |
import numpy as np
IS_AUTONOMOUS = False
X_TARGET = 2.0
Y_TARGET = 2.0
STOP_THRESHOLD = 0.03 # Unit: m
ROBOT_MARGIN = 130 # Unit: mm
THRESHOLD = 3.6 # Unit: m
MIN_THRESHOLD = 0.1
THRESHOLD_STEP = 0.25
THRESHOLD_ANGLE = 95 # Unit: deg, has to be greater than 90 deg
ANG... | python |
# -*- coding: utf-8 -*-
def relu(name, bottom, top, type="ReLU"):
layer = "layer {\n"
layer += " name: \"" + name + "\"\n"
if type not in ["ReLU", "ReLU6", "CReLU"]:
raise Exception("unknown relu: %s" % type)
layer += " type: \"" + type + "\"\n"
layer += " bottom: \"" + bottom + "\"\n"
... | python |
# Вступление
# В этом руководстве вы узнали, как создать достаточно интеллектуального агента с помощью алгоритма минимакса. В
# этом упражнении вы проверите свое понимание и представите своего агента для участия в конкурсе.
# 1) Присмотритесь
# Эвристика из учебника рассматривает все группы из четырех соседних местопо... | python |
# Copyright 2017 Insurance Australia Group Limited
#
# 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... | python |
import translate, command
while 1:
b=raw_input(">>>")
a=open("console.txt","w")
a.write(b)
a.close()
print(command.run(b))
| python |
import xmlrpclib
from tornado.options import options
from ate_logger import AteLogger
class BaseXmlRpcProcess(object):
def __init__(self):
self.logger = AteLogger('XmlRpcProcess')
self._tf_status = False
def status(self):
self.logger.debug('Calling status')
traceback = None
... | python |
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import plotly.express as px
import price_loader as pl
import spy_investments as spy
from datetime import datetime
import pandas a... | python |
from gym_network_intrusion.envs.network_intrusion_env_1 import NetworkIntrusionEnv
from gym_network_intrusion.envs.network_intrusion_extrahard_env_1 import NetworkIntrusionExtraHardEnv
| python |
from koans_plugs import *
def test_has_true_literal():
"""
У логического типа есть литерал, обозначающий истину
"""
a = True # попробуйте такие варианты: TRUE, true, True
assert a
def test_has_false_literal():
"""
У логического типа есть литерал, обозначающий ложь
"""
a ... | python |
import csv
import cv2
import numpy as np
import re
np.random.seed(0)
# Load data csv file
def read_csv(file_name):
lines = []
with open(file_name) as driving_log:
reader = csv.reader(driving_log)
next(reader, None)
for line in reader:
lines.append(line)
return lines
... | python |
from copy import deepcopy
import json
import os
from uuid import uuid4
import pytest
from starlette.testclient import TestClient
from hetdesrun.utils import get_uuid_from_seed
from hetdesrun.service.webservice import app
from hetdesrun.models.code import CodeModule
from hetdesrun.models.component import (
Comp... | python |
'''
Title : Day 25: Running Time and Complexity
Domain : Tutorials
Author : Ahmedur Rahman Shovon
Created : 03 April 2019
'''
def is_prime(n):
if n == 2:
return True
if n%2 == 0 or n < 2:
return False
max_limit = int(n**0.5) + 1
for i in range(3, max_limit):
i... | python |
from cassandra.cluster import Cluster
def create_connection():
# TO DO: Fill in your own contact point
cluster = Cluster(['127.0.0.1'])
return cluster.connect('demo')
def set_user(session, lastname, age, city, email, firstname):
# TO DO: execute SimpleStatement that inserts one user into the table
... | python |
"""
Tests for todos module
"""
import random
import string
from django.test import TestCase
DEFAULT_LABELS = [
'low-energy',
'high-energy',
'vague',
'work',
'home',
'errand',
'mobile',
'desktop',
'email',
'urgent',
'5 minutes',
'25 minutes',
'60 minutes',
]
class ... | python |
from .singleton import Singleton
from .visitor import visitor
| python |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.options
import tornado.gen
import os.path
from tornado.options import define, options
from cache_module import CacheHandler
define("port", default=8888, help="run on the given port", type=int)... | python |
"""
Exposes commonly used classes and functions.
"""
from .bencode import Bencode
from .torrent import Torrent
from .utils import upload_to_cache_server, get_open_trackers_from_local, get_open_trackers_from_remote
| python |
import numpy as np
import re
#------------------------------------------------------------------------------
"""
Correct positions in the vicon data to center on the middle of the enclosure.
This is due to inexact positioning of the enclosure and/or the wand during
motion capture, so this is only necessary to perform ... | python |
import csv
import sys
import urllib3
import json
from urllib.parse import quote
METAMAP = 'https://knowledge.ncats.io/ks/umls/metamap'
DISAPI = 'https://disease-knowledge.ncats.io/api'
DISEASE = DISAPI + '/search'
def parse_disease_map (codes, data):
if len(data) > 0:
for d in data:
if 'I_CODE... | python |
##
# @file elasticsearch.py
# @author Lukas Koszegy
# @brief Elasticsearch klient
##
from elasticsearch import Elasticsearch
import json
from time import time
from database.schemes.mapping import mappingApp, mappingEvent
import logging
class ElasticsearchClient():
def __init__(self, host="127.0.0.1", port=9200, ss... | python |
from argparse import ArgumentParser
import numpy as np
import pytorch_lightning as pl
from scipy.io import savemat
from torch.utils.data import DataLoader
from helmnet import IterativeSolver
from helmnet.dataloaders import get_dataset
class Evaluation:
def __init__(self, path, testset, gpus):
self.path ... | python |
import cv2
import numpy as np
import pandas as pd
date=datetime.datetime.now().strftime("%d/%m/20%y")
faceDetect = cv2.CascadeClassifier("C:/Users/Administrator/Desktop/haarcascade_frontalface_default.xml")
cam = cv2.VideoCapture(0)
rec = cv2.face.LBPHFaceRecognizer_create()
rec.read("C:/Users/Administrator/Desk... | python |
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import time
import os
import shutil
import copy
import datetime
from layers import ConvNet
import network_operators
import utils
# hyperparameters
mutation_time_limit_hours = 23
n_models = 8 # ... | python |
import subprocess , os
from tkinter import messagebox
from tkinter import filedialog
class Cmd:
def __init__(self,tk, app):
self.app = app
self.tk = tk
self.default_compileur_path_var = os.path.join(os.path.dirname(os.path.abspath(__file__)), "dart-sass\\sass.bat")
self.opt... | python |
import math
from typing import Optional
import torch
from torch import nn, Tensor
from torch.autograd import grad
from torch.nn import functional as F
from adv_lib.utils.visdom_logger import VisdomLogger
def ddn(model: nn.Module,
inputs: Tensor,
labels: Tensor,
targeted: bool = False,
... | python |
#!/usr/bin/python
def get_memory(file_name):
# vmstat
#procs - ----------memory - --------- ---swap - - -----io - --- -system - - ------cpu - ----
# r;b; swpd;free;buff;cache; si;so; bi;bo; in;cs; us;sy;id;wa;st
memory_swpd = list()
memory_free = list()
memory_buff = ... | python |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class CouponReward(models.Model):
_name = 'coupon.reward'
_description = "Coupon Reward"
_rec_name = 'reward_description'
... | python |
"""
=====================
Configuration Manager
=====================
"""
import os
from configparser import ConfigParser
from typing import Optional, Dict, TypeVar, Callable
from PySide2 import QtWidgets
WIDGET = TypeVar('QWidget')
########################################################################
class Con... | python |
import json
import yaml
from flask import jsonify, Blueprint, redirect
from flask_restless import APIManager
from flask_restless.helpers import *
sqlalchemy_swagger_type = {
'INTEGER': ('integer', 'int32'),
'SMALLINT': ('integer', 'int32'),
'NUMERIC': ('number', 'double'),
'DECIMAL': ('number', 'doubl... | python |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 24 12:35:04 2018
@author: Matthias N.
"""
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
import asyncio
import concurrent.futures
import json, codecs
async def speedcrawl(pages):
data = []
for p in range(... | python |
from .src import dwarfgen
def process(*args, **kwargs):
return dwarfgen.process(*args, **kwargs)
| python |
import tesseract
api = tesseract.TessBaseAPI()
api.SetOutputName("outputName");
api.Init("E:\\Tesseract-OCR\\test-slim","eng",tesseract.OEM_DEFAULT)
api.SetPageSegMode(tesseract.PSM_AUTO)
mImgFile = "eurotext.jpg"
pixImage=tesseract.pixRead(mImgFile)
api.SetImage(pixImage)
outText=api.GetUTF8Text()
print("OCR output:\n... | python |
import math
import torch
from torch import Tensor
from .optimizer import Optimizer
from typing import List, Optional
class RAdam(Optimizer):
r"""Implements RAdam algorithm.
.. math::
\begin{aligned}
&\rule{110mm}{0.4pt} \\
... | python |
"""
Author: Darren
Date: 30/05/2021
Solving https://adventofcode.com/2016/day/6
Part 1:
Need to get most frequent char in each column, given many rows of data.
Transpose columns to rows.
Find the Counter d:v that has the max value, keyed using v from the k,v tuple.
Part 2:
As part 1, but using mi... | python |
from flask import Flask, render_template, redirect
from flask_pymongo import PyMongo, ObjectId
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import ValidationError, URL
app = Flask(__name__)
app.config['SECRET_KEY'] = 'test'
app.config["MONGO_URI"] = "mongodb://14... | python |
"""added date_read_date
Revision ID: a544d948cd1b
Revises: 5c5bf645c104
Create Date: 2021-11-28 20:52:31.230691
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a544d948cd1b'
down_revision = '5c5bf645c104'
branch_labels = None
depends_on = None
def upgrade()... | python |
from django.contrib.auth import get_user_model
from django.test import TestCase
from src.activities.models import Activity
from src.questions.models import Question, Answer
class QuestionVoteTest(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(
username='test_user... | python |
#!/usr/bin/env python
import astropy.units as u
from typing import Union
from dataclasses import dataclass, field, is_dataclass
from cached_property import cached_property
import copy
from typing import ClassVar
from schema import Or
from tollan.utils.dataclass_schema import add_schema
from tollan.utils.log import ge... | python |
from hashlib import md5
def mine(secret: str, zero_count=5) -> int:
i = 0
target = '0' * zero_count
while True:
i += 1
dig = md5((secret + str(i)).encode()).hexdigest()
if dig.startswith(target):
return i
if __name__ == '__main__':
key = 'bgvyzdsv'
print(f'Par... | python |
import json
import os
def setAccount( persAcc, money, input=True ):
rez = True
if input == True:
persAcc += money
else:
if persAcc < money:
rez = False
else:
persAcc -= money
return persAcc, rez
# **********************************************
def setH... | python |
# Databricks notebook source
import pandas as pd
import random
# COMMAND ----------
# columns = ['id','amount_currency','amount_value','channel','deviceDetails_browser',
# 'deviceDetails_device','deviceDetails_deviceIp','merchantRefTransactionId','paymentMethod_apmType',
# 'paymentMethod_cardNum... | python |
import numpy as np
import cv2
def handle_image(input_image, width=60, height=60):
"""
Function to preprocess input image and return it in a shape accepted by the model.
Default arguments are set for facial landmark model requirements.
"""
preprocessed_image = cv2.resize(input_image, (width, height... | python |
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0 or (x != 0 and x % 10 == 0):
return False
res = 0
# 1221
while x > res:
res *= 10
res += x % 10
x //= 10
if x == res or x == res // 10:
return True
... | python |
from model.contact import Contact
from random import randrange
def test_delete_some_contact(app):
app.contact.ensure_contact_exists(Contact(fname="contact to delete"))
old_contacts = app.contact.get_contact_list()
index = randrange(len(old_contacts))
app.contact.delete_contact_by_index(index)
asse... | python |
"""
Number Mind
""" | python |
#!/usr/bin/env python3
# Up / Down ISC graph for ALL bins
# Like SfN Poster Figure 2
# But now for all ROIs in Yeo atlas
import tqdm
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import deepdish as dd
from HMM_settings import *
ISCdir = ISCpath+'shuff_Yeo_outlier_'
figdir = figurepath+'up... | python |
"""
Created Aug 2020
@author: TheDrDOS
"""
# Clear the Spyder console and variables
try:
from IPython import get_ipython
#get_ipython().magic('clear')
get_ipython().magic('reset -f')
except:
pass
from time import time as now
from time import perf_counter as pnow
import pickle
import numpy as np
impo... | python |
# -*- coding: utf-8 -*-
import cv2
# トラックバーの値を変更する度にRGBを出力する
def changeColor(val):
r_min = cv2.getTrackbarPos("R_min", "img")
r_max = cv2.getTrackbarPos("R_max", "img")
g_min = cv2.getTrackbarPos("G_min", "img")
g_max = cv2.getTrackbarPos("G_max", "img")
b_min = cv2.getTrackbarPos("B_min", "img")
... | python |
# Developed by Joseph M. Conti and Joseph W. Boardman on 1/21/19 6:29 PM.
# Last modified 1/21/19 6:29 PM
# Copyright (c) 2019. All rights reserved.
import logging
import logging.config as lc
import os
from pathlib import Path
from typing import Union, Dict
import numpy as np
from yaml import load
class Singleto... | python |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.15.0)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x07\x10\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x40\x... | python |
#!/usr/bin/python
# (c) 2018 Jim Hawkins. MIT licensed, see https://opensource.org/licenses/MIT
# Part of Blender Driver, see https://github.com/sjjhsjjh/blender-driver
"""Path Store unit test module. Tests in this module can be run like:
python3 path_store/test.py TestInterceptProperty
"""
# Exit if run other tha... | python |
from unittest.case import TestCase
from responsebot.handlers.base import BaseTweetHandler
from responsebot.handlers.event import BaseEventHandler
try:
from mock import MagicMock, patch
except ImportError:
from unittest.mock import MagicMock
class Handler(BaseTweetHandler):
class ValidEventHandler(BaseEv... | python |
# coding: utf-8
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from cmsplugin_bootstrap_grid.forms import ColumnPluginForm
from cmsplugin_bootstrap_grid.models import Row, Column
from django.utils.translation import ugettext_lazy as _
class BootstrapRowPlugin(CMSPluginBase):
mod... | python |
from scipy import spatial
from . import design
from .design import *
from .fields import *
schema = dj.schema('photixxx')
@schema
class Tissue(dj.Computed):
definition = """
-> design.Geometry
---
density : float # points per mm^3
margin : float # (um) margin to include on boundaries
min_dis... | python |
# Copyright 2017 The KaiJIN 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 ... | python |
import pandas as pd
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import modules.load_data_from_database as ldd
from db import connect_db
# connection with database
rdb = connect_db()
def day_figure_update(df, bar):
""" Update day figure depends on drop downs """
df_bar = df[df... | python |
import threading
import json
from socketIO_client import SocketIO, LoggingNamespace
class Cliente():
def __init__(self, ip):
self.socketIO = SocketIO(ip, 8000)
self.errors = ''
#thread_rcv= threading.Thread ()
#thread_rcv.daemon=True
#thread_rcv.start()
... | python |
import ctypes
import os
import warnings
from ctypes import (
byref, c_byte, c_int, c_uint, c_char_p, c_size_t, c_void_p, create_string_buffer, CFUNCTYPE, POINTER
)
from pycoin.encoding.bytes32 import from_bytes_32, to_bytes_32
from pycoin.intbytes import iterbytes
SECP256K1_FLAGS_TYPE_MASK = ((1 << 8) - 1)
SECP... | python |
from smach_based_introspection_framework.offline_part.model_training import train_anomaly_classifier
from smach_based_introspection_framework._constant import (
anomaly_classification_feature_selection_folder,
)
from smach_based_introspection_framework.configurables import model_type, model_config, score_metric
imp... | python |
from collections import deque
from time import perf_counter
def breadthFirstSearch(initialState, goalState, timeout=60):
# Initialize iterations counter.
iterations = 0
# Initialize visited vertexes as set, because it's faster to check
# if an item exists, due to O(1) searching complexity on average ... | python |
/home/runner/.cache/pip/pool/fd/94/44/56b7be5adb54be4e2c5a3aea50daa6f50d6e15a013102374ffe3d729b9 | python |
import FWCore.ParameterSet.Config as cms
def useTMTT(process):
from L1Trigger.TrackerDTC.Producer_Defaults_cfi import TrackerDTCProducer_params
from L1Trigger.TrackerDTC.Format_TMTT_cfi import TrackerDTCFormat_params
from L1Trigger.TrackerDTC.Analyzer_Defaults_cfi import TrackerDTCAnalyzer_params
Track... | python |
from datetime import timedelta
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
from matplotlib import rcParams
__author__ = 'Ben Dichter'
class BrokenAxes:
def __init__(self, xlims=None, ylims=None, d=.015, tilt=45,
su... | python |
# Copyright 2014-2015 ARM Limited
#
# 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 w... | python |
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture
from sklearn.cluster import DBSCAN
from .MetadataExtractor import Extractor
from .DataCleaner import cleaner, limited_cleaner
from joblib import dump, load
def predictor(extractor, name):
data = cleaner(extractor).drop_duplicates... | python |
# Copyright (c) 2021, Manfred Moitzi
# License: MIT License
from typing import (
Iterable,
List,
TYPE_CHECKING,
Tuple,
Iterator,
Sequence,
Dict,
)
import abc
from typing_extensions import Protocol
from ezdxf.math import (
Vec2,
Vec3,
linspace,
NULLVEC,
Vertex,
inter... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/12/30 21:02
# @Author : WIX
# @File : 青蛙跳.py
"""
青蛙跳台阶, 每次可以跳1级或2级,求青蛙跳上一个n级的台阶一共有多少种跳法?
当n > 2时,第一次跳就有两种选择:
1. 第一次跳1级,后面的跳法相当于剩下n-1级的跳法,即f(n-1)
2. 第一次跳2级,后面的跳法相当于剩下n-2级的跳法,即f(n-2)
即f(n) = f(n-1) + f(n-2)
"""
class Solution(object):
def jumpfrog... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.