content stringlengths 5 1.05M |
|---|
"""
===============
05. Apply ICA
===============
Blinks and ECG artifacts are automatically detected and the corresponding ICA
components are removed from the data.
This relies on the ICAs computed in 04-run_ica.py
!! If you manually add components to remove (config.rejcomps_man),
make sure you did not re-run the IC... |
'''py.test standard config file.'''
import sys
# pylint: disable=invalid-name
collect_ignore = ('setup.py',)
# pylint: enable=invalid-name
def pytest_cmdline_preparse(args):
is_pylint_compatible = sys.version_info < (3, 6)
if not is_pylint_compatible:
args.remove('--pylint')
|
# transfer functions
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# derivative of sigmoid
def dsigmoid(y):
return y * (1.0 - y)
def tanh(x):
return np.tanh(x)
# derivative for tanh sigmoid
def dtanh(y):
return 1 - y*y |
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import SGDClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn import svm
from sklearn import cross_validation
import pandas as pd
import numpy as np
print "L... |
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import StandardScaler
scaler1 = MinMaxScaler(feature_range=(0, 1))
scaler0 = StandardScaler()
#Importing sample data
news_data = pd.read_csv("/Users/jonathanhale/Documents/Courses/Machine Learning/example_data/news_sample (1... |
class Parser:
def parse(self):
print("hello world!") |
class BucketCollectionAPI(object):
def on_get(self, req, resp):
resp.data = 'BucketCollection'
class BucketAPI(object):
def on_get(self, req, resp, bucket_name):
resp.data = 'Bucket: %s' % bucket_name
|
from .trans_base import trans_comp_check_mdoe_base
import csv
import six
import re
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
from ..exceptions import SettingError
import logging
__all__ = ['trans_comp_csv', 'trans_comp_tsv', 'trans_comp_psv']
logger = loggi... |
class Queue:
def __init__(self):
self.queuearray = []
self.stackarray = []
def push(self,data):
self.queuearray.append(data)
print("Pushing"), data
def pop(self):
if not self.stackarray:
while self.queuearray:
self.stackarray.append(self.queuearray.pop(0))
while self.stackarray:
self.queuearr... |
# Constantes Figurativas
cf = { 'ZERO' : 0
, 'ZEROS' : 0
, 'ZEROES' : 0
, 'SPACE' : ' '
, 'SPACES' : ' '
, 'HIGH-VALUE' : '\xFF'
, 'HIGH-VALUES' : '\xFF'
, 'LOW-VALUE' : '\x00'
, 'LOW-VALUES' : '\x00'}
|
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
model_urls = {
'alexnet': 'https://download.pytorch.org/models/alexnet-owt-4df8aa71.pth',
}
settings = { 'input_space': 'RGB',
'input_size': [3, 450, 450],
'input_range': [0, 1],
'mean': [0.485, 0.456, 0.406],
... |
# Copyright 2022 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from __future__ import absolute_import, division, print_function
from iotbx.dtrek import reflnlist_reader
def extract_from(file_name):
with open(file_name) as f:
cs = reflnlist_reader.reflnlist(f, header_only=True).crystal_symmetry()
return cs
|
from django.contrib.auth.models import User
from rest_framework import serializers
from ricommender_backend.musicstreamer.models import Music
from ricommender_backend.musicstreamer.models import History
class MusicSerializer(serializers.ModelSerializer):
class Meta:
model = Music
fields = '__all_... |
from flask import jsonify
from app.libs.global_varible import g
from app.libs.red_print import RedPrint
api = RedPrint('meta')
@api.route('/version', methods=['GET'])
def get_version_api():
return jsonify({
'code': 0,
'version': g.run_start_time
})
|
from django.core import serializers
from django.shortcuts import render
from django.http import JsonResponse
from .forms import HeroForm
from myapi.models import Hero
# Create your views here.
def index(request):
hero_form = HeroForm()
return render(request, "index.html", {'hero_form': hero_form}) #file name ... |
from resteasy import RESTEasy
from collections import OrderedDict
from resteasycli.config import Config
from resteasycli.lib.endpoint import Endpoint
from resteasycli.exceptions import EntryNotFoundException
class Site(RESTEasy):
'''A site is a modified RESTEasy object'''
def __init__(self, site_id, workspac... |
import io
import pytest
import pandas as pd
from doltpy.cli.dolt import Dolt
from doltpy.cli.write import CREATE, UPDATE
from doltpy.cli.read import read_pandas
from doltpy.etl import (get_df_table_writer,
insert_unique_key,
get_unique_key_table_writer,
... |
""" Unittests for data types""" |
w, h, k = list(map(int, input().split()))
c=0
for i in range(k):
c = c+ ( (h-4*i)*2 +( w - 2-4*i)*2)
print(c)
|
import os
import threading
import string
from random import *
from .config import Configurator
from .helpers import uuid
from von_agent.nodepool import NodePool
from von_agent.wallet import Wallet
from von_agent.agents import _BaseAgent
from von_agent.agents import Issuer as VonIssuer
from von_agent.agents import Ve... |
from django import template
from dojo.models import System_Settings
register = template.Library()
@register.filter
def get_system_setting(system_setting):
try:
system_settings = System_Settings.objects.get()
if getattr(system_settings, system_setting, None):
return getattr(system_sett... |
from covid_model_seiir_pipeline.pipeline.regression.specification import (
REGRESSION_JOBS,
RegressionSpecification,
HospitalParameters,
)
from covid_model_seiir_pipeline.pipeline.regression.data import (
RegressionDataInterface,
)
from covid_model_seiir_pipeline.pipeline.regression.task import (
be... |
########
# Copyright (c) 2016 GigaSpaces Technologies Ltd. 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/1/30 下午12:10
# @Author : wook
# @File : url.py
"""
the url structure of website
"""
from app.index.handlers.index import IndexHandler
url = [
(r'/', IndexHandler),
]
|
import math
import numpy as np
from numpy.linalg import inv, cholesky
class Digit:
def __init__(self):
self.curves = []
self.label = -1
def add_curve(self, points):
self.curves.append(points)
def set_label(self, label):
self.label = int(label)
def set_observations(se... |
from django.urls import NoReverseMatch
from . import schema
def reverse(feature_name, **kwargs):
feature_schema = schema.get_schema()
try:
feature = feature_schema[feature_name]
except KeyError:
raise NoReverseMatch(feature_name)
else:
return substitute(feature['coerced_url'],... |
from pymodbus.client.sync import ModbusSerialClient
from time import sleep
"""
import serial
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(14, GPIO.OUT)
GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_OFF)
"""
walli = ModbusSerialClient(method="rtu",
#port='COM9',
... |
from django.urls import path,include
from .views import GetAllData,GetFavData,UpdateFavData,PostModelData,SearchData,DeleteData,allApi,SetData
app_name='book'
urlpatterns = [
path('get-all-data/',GetAllData.as_view(),name='get-all-data'),
path('all-data/',allApi,name='all-data'),
path('get-fav-data/',Ge... |
import httpx
import dataset
from dynaconf import settings
def main(db):
"""
Consumes Deezer API and get list of my favorite tracks and stores in database
:param db:
:return:
"""
url = f"https://api.deezer.com/user/me/tracks?output=json&access_token={settings.DEEZER_ACCESS_TOKEN}"
while ur... |
# Form implementation generated from reading ui file 'c:\Users\Marin\Documents\Team-Project_Python\backend_files\createCustomer.ui'
#
# Created by: PyQt6 UI code generator 6.1.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic6 is
# run again. Do not edit this file unless you know what you are... |
import os
import yaml
import json
import pandas as pd
directory = './ipl_yaml'
csv={'date':[], 'venue':[], 'innings':[], 'target':[], 'team':[], '0.1': [], '0.2': [], '0.3': [], '0.4': [], '0.5': [], '0.6': [], '0.7': [], '0.8': [], '0.9': [], '0.10': [], '0.11': [], '0.12': [], 'd1': [], 'r1': [], 'w1': [], '1.1': [... |
import os
import re
import string
from multiprocessing import Pool
import category_encoders as ce
import cv2
import numpy as np
import pandas as pd
from PIL import Image, ImageStat
from sklearn.model_selection import KFold
from sklearn.externals import joblib
from sklearn import preprocessing as prep
from sklearn.feat... |
from pathlib import Path
import shelve
import openpyxl
def get_unique_states(worksheet):
column = 'A'
states = set()
for x in range(2, worksheet.max_row + 1):
states.add(worksheet[f'{column}{x}'].value)
return sorted(states)
def get_unique_regions(worksheet):
column = 'E'
regions ... |
"""
cal_kts.py
Author: Joseph D Daws Jr
This file contains classes and methods
for calculating the value of K_tree(s)
given a sparsity parameter s for the case of
binary trees
"""
class BiNode:
def __init__(self,j=0,k=0):
self.parent = None
self.lchild = None
self.rchild = None
se... |
"""
Copyright 2018 Copenhagen Center for Health Technology (CACHET) at the Technical University of Denmark (DTU).
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 wit... |
from datetime import datetime
import json
import logging
import requests
from backup_secretary.target import Target
from . import BaseHandler
class WebhookHandler(BaseHandler):
def __init__(self, config: dict):
super().__init__(config)
self.url = self.config['url']
def execute_one(self, targ... |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2016-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http... |
"""
The CoverageType module is a critical component of the the by group :meth:`~Paletable.Paletable.byCoverageType` in :class:`Paletable`.
This module only contains one class, CoverageType.
"""
# -------------------------------------------------------
#
#
#
# -------------------------------------------------------
cl... |
import os
import time
import glob
from app import app
from flask import render_template
from app.api.scope_service_api_calls import get_named_graphs
@app.route("/", methods=["GET"])
def home():
return render_template("index.html")
@app.route("/TS", methods=["GET"])
@app.route("/ts", methods=["GET"])
@app.route... |
from django.db import models
from decimal import Decimal
import operator
from organization.models import Organization
# Create your models here.
class Product(models.Model):
brand = models.CharField(max_length=255, blank=True)
name = models.CharField(max_length=255)
sale_price = models.DecimalField(decimal... |
import json
import sqlite3
import git
import pandas as pd
from rich import progress
DATA_BRANCH = 'data'
FORECASTS_FILE = 'forecasts.json'
FORECASTS_TABLE = 'forecasts'
OBSERVATIONS_FILE = 'observations.json'
OBSERVATIONS_TABLE = 'observations'
SQLITE_PATH = 'bbc_weather.sqlite'
def load_forecasts_from_commit(comm... |
from nomenklatura.model.dataset import Dataset
from nomenklatura.model.entity import Entity
from nomenklatura.model.account import Account
__all__ = [Dataset, Entity, Account]
|
from robosuite.models.tasks import Task
from robosuite.utils.mjcf_utils import new_joint, array_to_string
import numpy as np
class SlideTask(Task):
"""
Creates MJCF model of a slide t task.
"""
def __init__(self, mujoco_arena, mujoco_robot, slide_object):
"""
Args:
mujoco_... |
# Scripts to score text polarity and subjectivity
from src.utils import data_connector
from textblob_de import TextBlobDE as TextBlob
class SentimentAnalyzer:
def __init__(self, model_name):
self.model_name=model_name
def score(self, text):
result={}
if self.model_name=='blob':
... |
#!/usr/bin/env python
import os
import subprocess
import shutil
def deleteDir(directory):
try:
if os.path.exists(directory) and os.path.isdir(directory):
print("Removing directory '%s'" % (directory))
shutil.rmtree(directory)
except OSError as e:
print ("Error: %s - %s.... |
"""\
Essence of bulk-solvent mask calculation, testing interaction of
symmetry summation in maptbx.structure_factors.from_map with handling
of grid points. This script demonstrates that grid points redundant
under symmetry must be kept at zero and that all grid points inside
the asu have to be weighted by site-multipli... |
# Generated by Django 3.2.8 on 2021-11-25 08:43
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('core', '0026_alter_objec... |
from sympy import Matrix
import numpy as np
M = Matrix( [ [ 1, 2, 2, 2 ], \
[ 2, 4, 6, 8 ], \
[ 3, 6, 8, 10 ] ] )
result = M.rref()
# Reduced Row Form
np.array( result[0].tolist(), dtype=float )
# Pivot Variables
pivots = result[ 1 ]
pivots |
from copy import copy
class NGramsExtractor:
NGRAMS_NAME_SPLIT_SYMBOL = ':'
NONE_TYPE = 'NONE'
def ngrams_recurrent_build(self, n, params, ngrams_on_path, node_type):
"""
Recurrent n-grams building: append of current node type to n-grams of previous nodes
(according to max dis... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'resources/templates/wizard_depend_file.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form)... |
#!/usr/bin/env python
import sys
import argparse
import spidev
import opc
import time
import threading
import signal
import datetime
import smbus
import serial
opc_cols = ['Bin {0}'.format(i) for i in range(0, 16)]
opc_cols.extend(['Bin{0} MToF'.format(i) for i in range(1, 2, 8)])
opc_cols.extend(['PM1', 'PM10', 'PM2... |
from .videocapture import VideoCapture
from .videocaptureex import VideoCaptureEX
from .multiplevideocapture import MultipleVideoCapture
from .synchronizedvideocapture import SynchronizedVideoCapture
from .utils import EasyPySpinWarning
|
# Python script to convert the given image
# into a dotted text using opencv
# import the required modules
import cv2
from PIL import Image, ImageDraw, ImageFont
import os
import requests
from modifiedbraillegraph import vertical_graph, horizontal_graph
# Read the image
def imagetobraille(image_location = "", size... |
import pdb
import json
import requests
import os
import datetime as dt
import logging
logger = logging.getLogger(__name__)
class Forecast():
def __init__(self, config):
self.api_key = config['darksky']['api_key']
self.lat_long = config['darksky']['lat_long']
path = os.pa... |
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from rangers import constants
from series.models import Series
from weapons.models import Weapon
from zords.models import Zord
@python_2_unicode_compatible
class Ranger(models.Model):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Basic flask app with auth
'''
from flask import Flask, make_response, jsonify
from flask_httpauth import HTTPBasicAuth
app = Flask(__name__)
auth = HTTPBasicAuth()
@auth.get_password
def get_password(username):
if username == 'skpt':
return '0000'
ret... |
from threading import RLock
from rx.core.typing import Disposable
class SingleAssignmentDisposable(Disposable):
"""Single assignment disposable.
Represents a disposable resource which only allows a single
assignment of its underlying disposable resource. If an underlying
disposable resource has alrea... |
from functools import partial
from flask import Blueprint, g
from api.mapping import Mapping
from api.observables import Observable
from api.schemas import ObservableSchema
from api.client import GuardDuty
from api.utils import (
get_json,
get_jwt,
jsonify_data,
remove_duplicates,
jsonify_result
)... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
PyCOMPSs Testbench Tasks
========================
"""
# Imports
import unittest
from pycompss.api.task import task
from pycompss.functions.reduce import mergeReduce, simpleReduce
from pycompss.functions.map import map
@task(returns=int)
def sumTask(x, y):
return x... |
"""Implement a simple XMLRPC server."""
from base64 import b64decode
import six
from fdep.servers import RPCServer
from six.moves.xmlrpc_server import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
class XMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
"""Implement a simple basic auth."""
username = None
... |
from scriptutils import colors
class Log:
@staticmethod
def _print(label: str, label_color: str, msg: str) -> None:
print(
f"{colors.B_WHITE}> [{label_color}{label}{colors.WHITE}] {colors.CLR}{msg}"
)
@classmethod
def err(cls, msg: str) -> None:
cls._print("ERR", c... |
from .utils import pysed
from .core import MECSIM
from .input import Specie
from .input import Reaction, ChargeTransfer, ChemicalReaction, CatalyticReaction
from .input import Voltammetry, DCVoltammetry, ACVoltammetry
from .input import Electrode, PlanarElectrode, SphericalElectrode, CylindricalElectrode, RDEElectrode
... |
# coding: utf-8
# flake8: noqa
"""
Portainer API
Portainer API is an HTTP API served by Portainer. It is used by the Portainer UI and everything you can do with the UI can be done using the HTTP API. Examples are available at https://gist.github.com/deviantony/77026d402366b4b43fa5918d41bc42f8 You can find ou... |
from django.db import models
# Create your models here.
class FrontUser(models.Model):
username = models.CharField(max_length=100,unique=True,null=False)
def __str__(self):
return '<FrontUser:(id:%s,username:%s)>' % (self.id,self.username)
class UserExtension(models.Model):
school = models.CharF... |
import math
def distance(a,b,c,d):
return math.sqrt((a-c)**2 + (b-d)**2)
|
# (c) 2022- Spiros Papadimitriou <spapadim@gmail.com>
#
# This file is released under the MIT License:
# https://opensource.org/licenses/MIT
# This software is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied.
import os
import sys
import unittest
from gradescope_utils.auto... |
from __future__ import division
import numpy as np,opticstools as ot,matplotlib.pyplot as plt,math,scipy.ndimage as nd
import astropy.io.fits as pyfits
import os,sys,aplpy
from matplotlib import ticker
import matplotlib.cm as cm
numCals = [4,8,12]
name = 'HL Tau'
objNoSpaces = name.split(' ')
objName = ''.join(objNoSpa... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('company', '0008_company_created_at'),
]
operations = [
migrations.AddField(
model_name='company',
name='Editor_notes',
field=models.TextField(
... |
#!/usr/bin/python
"""setup.py for PyFLX."""
from setuptools import setup
from setuptools.dist import Distribution
# To use a consistent encoding
from codecs import open
from os import path
import platform
here = path.abspath(path.dirname(__file__))
if platform.system() == 'Windows':
packagefile = 'pyflx.pyd'
els... |
from .templates import NODE_TEMPLATE
from graphviz import Digraph
import os
class Tree:
def __init__(self, members):
self.members = members
def makeGraph(self, data):
"""
Creates a graph to visualize a tree
:param data: The root object of the tree to visualize
:type ... |
from __future__ import unicode_literals
from django.test import TestCase
from django.test.utils import override_settings
from ..models import UrlArticle
@override_settings(ROOT_URLCONF='view_tests.urls')
class DefaultsTests(TestCase):
"""Test django views in django/views/defaults.py"""
fixtures = ['testdata... |
'''
uix.stacklayout tests
=====================
'''
import unittest
from kivy.uix.stacklayout import StackLayout
from kivy.uix.widget import Widget
class UixStackLayoutTest(unittest.TestCase):
def test_stacklayout_no_children(self):
sl = StackLayout()
sl.do_layout()
def test_stacklayout_de... |
import logging
import urllib.request
from bs4 import BeautifulSoup
import threading
from .proxy_tool import proxy_tool
#from .XiciDaili import XiciDaili
# from .JingDongWanXiang import JingDongWanXiang
from .ZhiMaIp import ZhiMaIp
from pprint import pprint , PrettyPrinter
from twisted.internet.error import Connectio... |
from blip_session.blip_session import BlipSession
|
from googletrans import Translator
from summarizer import textrank
f=open('HindiText.txt','r')
hinText=f.read()
f.close()
translator = Translator()
engText=translator.translate(hinText,src='hi',dest='en')
engSum=textrank(engText.text)
for sentence in engSum:
hinSent=Translator().translate(sentence,src='en',dest='hi'... |
# -*- coding: utf-8 -*-
"""Preprocessing.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Ki4uz_95gbrKgxIf-TotuaURE3LX2dh_
"""
from google.colab import drive
drive.mount('/content/drive')
import click
import numpy as np
import pandas as pd
im... |
from __future__ import print_function
import argparse
import joblib
import os
import pandas as pd
import logging
import numpy as np
from sklearn.linear_model import Ridge, RidgeCV, LassoCV, Lasso
from sklearn.model_selection import cross_val_score
def train(args, train_X, train_y, model):
'''
아래 모델의 타입에 따라 ... |
# -*- coding: utf-8 -*-
"""
chemdataextractor.tests.parse_tests.test_table
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:author: Ed Beard
:license: MIT, see LICENSE file for more details.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_l... |
from celery import Celery
from world.importer import WorldImporter
from django.conf import settings
from celery import shared_task
app = Celery('tasks', broker='redis://localhost')
@shared_task
def scrape_world():
staytoken = settings.STAY_ALIVE_TOKEN
tokens = settings.TOKENS
for token in tokens:
importer = ... |
from django.urls import path, include
from introduction import views
urlpatterns = [
# introductions list
path('introductions', views.introduction_list, name='introduction_list'),
path('introductions/', views.introduction_list, name='introduction_list'),
# introduction item
path('introductions/<i... |
"""
* Copyright 2019 OpenStack Foundation
* 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 ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-23 07:55
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
import django.db.models.deletion
import modelcluster.contrib.taggit
import modelcluster.fields
import wagtail.contrib.wagtailroutablepage.models
impo... |
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
start =[]
end = []
for i in intervals:
start.append(i[0])
end.append(i[1])
start.sort()
end.sort()
low=0
high=0
idx=0
res=[]
... |
import scipy.ndimage as im
import numpy as np
import os
import h5py
import cv2
from UG2.lib.pyblur import LinearMotionBlur
from coherentImageFormation.utils import data as data_utils
import torch
import torch.nn as nn
from torch.autograd import Variable
import copy
import random
import numpy.fft as fft
from mpl_toolki... |
class AppNotRunningException(Exception):
"""Raise when app accidentally exited"""
class SkipIrrelevantExceedLimit(Exception):
"""Reach maximum recursive call of skip_irrelevant"""
class GenymotionTimeoutException(Exception):
"""Genymotion management action timeout"""
class GenymotionActionException(Ex... |
import numpy as np
import random
import linecache
import re
import matplotlib.pyplot as plt
from nltk.tokenize import sent_tokenize
from keras.utils import Sequence
from keras.utils.np_utils import to_categorical
def plotLineChart(x, y, xlabelName, ylabelName, figname):
plt.figure(figsize=(13,7))
# create... |
def combo_breaker_part1(data: str) -> int:
key1, key2 = tuple(map(int, data.splitlines(keepends=False)))
subject = 7
found = False
loop_size = None
loop_count = 1
while not found:
loop_count += 1
subject = transform(subject)
if subject == key2:
loop_size = loo... |
from django.conf.urls import url,include
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^auth/', views.auth, name='auth'),
] |
from __future__ import unicode_literals
import erpnext.education.utils as utils
import frappe
from datetime import date, datetime
import json
from frappe import utils
import datetime
no_cache = 1
@frappe.whitelist(allow_guest=True)
def get_attendance_data(stud_id=None):
student_id = stud_id
response = {}
studen... |
#
# Copyright 2019-2020 Lukas Schmelzeisen
#
# 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 collections import Counter
my_dict = dict(Counter(input()))
for key, value in my_dict.items():
if key != ' ':
print(key, '->', value)
|
import abc
from enum import Enum
from datetime import datetime
class Entity:
@classmethod
@abc.abstractmethod
def from_dict(cls, adict):
pass
def entity2dict(self, entity):
def _type_switcher(value):
if isinstance(value, Entity):
return self.entity2dict(va... |
from custom_envs.pybulletgym_custom.envs.roboschool.envs.locomotion.humanoid_env import HumanoidBulletEnv
from custom_envs.pybulletgym_custom.envs.roboschool.robots.locomotors import HumanoidFlagrun, HumanoidFlagrunHarder
class HumanoidFlagrunBulletEnv(HumanoidBulletEnv):
random_yaw = True
def __init__(self,... |
# Copyright 2019, OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
#!/usr/bin/env python
import sys
import time
from zabbix.api import ZabbixAPI
for x in range(20):
try:
zapi = ZabbixAPI(url="http://localhost:8050/api_jsonrpc.php",
user="Admin",
password="zabbix")
except:
print('Zabbix 5.0 API is not ready...')... |
from django.conf import settings
from django.contrib import admin
from django.urls import include, path
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from rest_framework import permissions
schema_view = get_schema_view(
openapi.Info(
title="{{cookiecutter.project_name}}",
defau... |
from PIL import Image, __version__
EXIF_ORIENTATION = 0x0112
ROTATION = {3: Image.ROTATE_180, 6: Image.ROTATE_270, 8: Image.ROTATE_90}
def convert(input_filename, output_filename, image_format="PNG"):
img = Image.open(input_filename)
exif = img._getexif()
if exif is not None:
if EXIF_ORIENTATION ... |
import sys
import os
import random
import time
sys.path.append(os.getcwd())
import torch
import src.training.train as train
import src.models.baselines as baselines
import src.data.data as data
import utils.utils as utils
import src.data.config as cfg
config_file = "config/class_config.json"
config = cfg.read_confi... |
from __future__ import annotations
import time
from typing import Tuple, NoReturn
from ...base import BaseEstimator
import numpy as np
from itertools import product
class DecisionStump(BaseEstimator):
"""
A decision stump classifier for {-1,1} labels according to the CART algorithm
Attributes
------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.