content stringlengths 5 1.05M |
|---|
import random
###################
# Complexity:
# Time:
# Worst case (pivot is consistently the greatest element): O(Nˆ2)
# Average case: we halve the array with each call of quicksort O(N*logN)
##################
def quicksort(array):
quicksort_inplace(array, 0, len(array)-1)
def quicksort_inplace(array, ... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_moment import Moment
from flask_bootstrap import Bootstrap
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from config import Config
impor... |
class Computer:
def __init__(self,prog):
if type(prog)==str:
prog = [int(x.strip()) for x in prog.split(",") if x.strip()]
self.memory = prog
def evaluate(self):
pc = 0
while pc<len(self.memory) and self.memory[pc]!=99:
if self.memory[pc]==1:
from_, to_, store = self.memory[pc+1:pc+4]
self.memor... |
import multiprocessing
from typing import Callable
from typing import Iterable
from typing import Optional
consumer: Optional[Callable] = None
def init_fun(consumer_supplier):
global consumer # pylint: disable=global-statement
consumer = consumer_supplier()
def worker_fun(datum):
global consumer # py... |
from basetest import BaseToscaTest
from core.models import Service
class EngineTest(BaseToscaTest):
tests = ["intrinsic_get_artifact",
"intrinsic_get_script_env",
"intrinsic_get_script_env_noisy" ]
def cleanup(self):
self.try_to_delete(Service, name="testservice")
def i... |
import traceback
import sys
import os
"""
- loop as decorator?
- button to go back to ~/Documents/data
"""
# I for some reason have to do this to auto connect to my headset on startup
MAC_ADDR = "FC:58:FA:4F:D3:D0:" # mac addr of my bluetooth headset
def connect():
os.system("pulseaudio --start -D")
os.syste... |
# Generated by Django 3.1.7 on 2021-05-07 11:30
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('booking', '0012_auto_20210506_0650'),
]
operations = [
migrations.AlterModelOptions(
name='ticket',
options={'ordering': ['-... |
# Copyright 2012 OpenStack Foundation
# 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 requ... |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
import os
EXTENSIONS = ['ggrc_gdrive_integration']
exports = ["GAPI_KEY", "GAPI_CLIENT_ID", "GAPI_ADMIN_GROUP"]
GAPI_KEY = os.environ.get('GGRC_GAPI_KEY', "")
GAPI_CLIENT_ID = os.environ.get('GGRC_GAPI_CLIE... |
import re
from datetime import datetime
from operator import itemgetter
from dateutil.relativedelta import relativedelta
from django import forms
from django.conf import settings
from alice.helpers import get_form_field, rabbit
from alice.metaclasses import ReflectiveFormMetaclass
from ui.forms import BootstrappedFor... |
from privateleaguehelper import helper
helper.start()
|
"""Most of the code comes from seq2seq tutorial. Binary for training conversation models and decoding from them.
Running this program without --decode will tokenize it in a very basic way,
and then start training a model saving checkpoints to --train_dir.
Running with --decode starts an interactive loop so you can... |
from Core.Base.BaseComponent import BaseComponent
from selenium.webdriver.remote.webdriver import By
from Core.Config.SeleniumElement import BaseElement
from Core.Config.Service.ElementFinder import ElementFactory
from GUI.Component.SectionWithGroupFAQ import SectionWithGroupFAQ
from GUI.Component.SectionWithPairFAQ im... |
"""
Vicki Langer
Class: CS 521 - Fall 1
Date: 29 Sep 2021
Homework Problem # 4_3
zip lists together to make dictionary and fill in None
without using itertools.zip_longest()
"""
FIRST_NAMES = ['Aditi', 'Amun', 'Vicki']
LAST_NAMES = ['Lam', 'Langer', 'Liburd', "Morgan"]
# Validate that last name list is same size or >... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2017 - Anil Lakhman - MIT License
# -----------------------------------------------------------------------------
from docutils import nodes
from docutils.parsers.rst import Dire... |
from __future__ import unicode_literals
from django.utils import timezone
from factory import LazyAttribute, Sequence, SubFactory, post_generation
from factory.django import DjangoModelFactory
from factory.fuzzy import FuzzyChoice, FuzzyText
from . import models
class AffiliationFactory(DjangoModelFactory):
cla... |
# Generated by Django 3.1 on 2020-08-26 03:45
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('rosters', '0026_auto_20200826_0341'),
]
operations = [
migrations.RenameField(
model_name='daygroupday',
old_name='day_group',... |
"""Running inference on GraphSAGE-cleaned pulses in IceCube-Upgrade."""
import argparse
from typing import List
import dill
from glob import glob
import logging
from os import makedirs
from os.path import join, dirname
import torch
from I3Tray import I3Tray # pyright: reportMissingImports=false
from graphnet.deplo... |
#!/usr/bin/env python3
# Tobit Flatscher - github.com/2b-t (2022)
# @file main.py
# @brief Command line interface for stereo matching
import argparse
import matplotlib.pyplot as plt
import numpy as np
from matching_algorithm.matching_algorithm import MatchingAlgorithm
from matching_algorithm.semi_global_matching imp... |
from django.contrib import admin
from django.urls import path, include
from django.contrib.sitemaps.views import sitemap
from blog.sitemaps import PostSitemap
from django.conf import settings
from django.conf.urls.static import static
from filebrowser.sites import site
sitemaps = {
'posts': PostSitemap,
}
urlpatt... |
import sys
for line in sys.stdin:
parsedInput = line.split()
a = int(parsedInput[0])
b = int(parsedInput[1])
if(a > 0 and b < 10):
print(a + b) |
from django.http import HttpResponse
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect, render_to_response, get_object_or_404
from django.urls import reverse_lazy
from django.views import generic
from login.forms impo... |
from .chpdb import cursor
# Returns list of discretized machine types of order [6, 9, 13, 17, 19, 20, 9-FORD, 17BIO}.
def get_machine_type(machine_id):
type_list = [0, 0, 0, 0, 0, 0, 0, 0]
cursor.execute(f'SELECT effekt FROM anlaeg WHERE anlaegnr = {machine_id};')
effekt = cursor.fetchone()[0]
if ef... |
# pylint: disable=missing-docstring
from copy import deepcopy
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.contrib.contenttypes.models import ContentType
from guardian.models import GroupObjectPermission, UserObjectPermission
from guardian.shortcuts import as... |
#!/usr/bin/python
"""
#! /usr/bin/env python
This module creates data file using writetimes data for creating performance
plot using gnuplot.
"""
import os, time, math, tempfile, sys
import numpy, datetime, re
from dateutil.relativedelta import relativedelta
import logging, subprocess
try:
import Gnuplot, Gnup... |
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
import datetime, os
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from model_utils import FieldTracker
from time import strftime
from applications.adminportal.mail_h... |
import pytest
import pandas as pd
import numpy as np
import tcrdist as td
from tcrdist.repertoire import TCRrep
import os
def test_TCRrep_gamma_delta():
"""
Simple Execution of Workflow on small gamma delta dataset
"""
# sant.csv was generated from Sant et al. 2019
# Using
# 1. sant_et_all_... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
from scrapy.item import Item, Field
class Weather(Item):
# define the fields for your item here like:
# name = Field()
day = Field()
high_temp = Field... |
import os
import sys
import argparse
import logging
from compare_traces import load_file as load_trace_file
logger = logging.getLogger('houston') # type: logging.Logger
logger.setLevel(logging.DEBUG)
DESCRIPTION = "Performs sanity checking of trace files"
def setup_logging(verbose: bool = False) -> None:
log_... |
from sqlalchemy import Column, Integer, UniqueConstraint, ForeignKey
from sqlalchemy.orm import relationship
from clld.db.meta import Base
from . import IdNameDescriptionMixin, Language
__all__ = ('GlossAbbreviation',)
class GlossAbbreviation(Base, IdNameDescriptionMixin):
"""Possibly language-specific abbrev... |
long_word = 3
long_sentence = 9
fillers = []
passive_indicators = []
tagger = None
abbreviations = r"\b[A-Z][a-zA-Z\.]*[A-Z]\b\.?|.+\..?"
|
"""
Modprobe configuration - files ``/etc/modprobe.conf`` and ``/etc/modprobe.d/*``
===============================================================================
This parser collects command information from the Modprobe configuration
files and stores information about each module mentioned. Lines such as
comments a... |
"""Dependency downloader for open_fortran_parser."""
import logging
import os
import pathlib
import platform
import typing as t
import urllib
import wget
_LOG = logging.getLogger(__name__)
def ensure_dependencies(
dependencies: t.Mapping[str, t.Tuple[urllib.parse.ParseResult, pathlib.Path]],
target... |
from django.db import migrations
def add_example_pinboard_rows(apps, schema_editor):
Pinboard = apps.get_model('pinboard', 'Pinboard')
skullcal_pinboard = Pinboard.objects.get(id='22e66085')
watts_pinboard = Pinboard.objects.get(id='b20c2c36')
ExamplePinboard = apps.get_model('pinboard', 'ExamplePinb... |
"""
Preprocess Criteo dataset. This dataset was used for the Display Advertising
Challenge (https://www.kaggle.com/c/criteo-display-ad-challenge).
"""
import os
import sys
import click
import random
import collections
# There are 13 integer features and 26 categorical features
continous_features = range(1, 14)
categor... |
"""step 2, removing the old columns and making foreign key non-nullable
Revision ID: 48597efc947
Revises: 4e053afee480
Create Date: 2015-08-07 23:20:41.723749
"""
# revision identifiers, used by Alembic.
revision = '48597efc947'
down_revision = '4e053afee480'
branch_labels = None
depends_on = None
from alembic impo... |
"""*------------------------------------------------------------*-
Buzzer main functions - python file
Tested on Gwiot 7304D2 RFID Reader(26 bit Wiegand mode) and RASPBERRY PI 3B+
(c) Minh-An Dao 2019
version 1.00 - 28/10/2019
--------------------------------------------------------------
*
* Usage:
* ./b... |
import json
import yake
kw_extractor = yake.KeywordExtractor()
with open('med_robo_papers.json', 'r', encoding='utf-8') as data_file:
data = json.load(data_file)
language = "en"
max_ngram_size = 2
deduplication_threshold = 0.9
numOfKeywords = 20
custom_kw_extractor = yake.KeywordExtractor(lan=languag... |
'''Return a foobang plotz says to frobnicate the bizbaz first.'''
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-07-17 19:38
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
... |
from datetime import datetime
import pytest
from application.auth.models import TypeOfUser
from application.cms.models import Measure
from scripts.oneoff.import_new_dimension_titles import import_dimension_titles, STANDARD_EDIT_SUMMARY
from tests.models import MeasureVersionWithDimensionFactory, UserFactory, Dimensio... |
from dexp.datasets.synthetic_datasets import generate_nuclei_background_data
from dexp.utils.backends import Backend, CupyBackend, NumpyBackend
from dexp.utils.timeit import timeit
def demo_nuclei_background_data_numpy():
with NumpyBackend():
demo_nuclei_background_data()
def demo_nuclei_background_data... |
# Copyright (c) 2009 Conrad "Lynx" Wong
# 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 source code must retain the above copyright
# notice, this list of co... |
import os
from .utils import OctopartClient
from .models import Building, Room, StorageUnit, StorageBin, Component, ComponentMeasurementUnit
from rest_framework import serializers
class BuildingSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Building
fields = ['url', 'name'... |
import wx
from opengl_orbits import OrbitzGLCanvas
from body import EARTH_R
def reverse_dict(d):
return dict((v, k) for k, v in d.iteritems())
class VizWindow(wx.Frame):
"""Main visualization window"""
ID_First_Body = wx.NewId(); ID_Last_Body = wx.NewId(); ID_Next_Body = wx.NewId(); ID_Prev_Body = wx.Ne... |
from litex.build.microsemi.platform import MicrosemiPlatform
|
from django import forms
from django.contrib.auth.models import User
from fishbook.models import WebUser
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'email', 'password',)
class WebUserForm(forms.Mode... |
import sys
from nose.tools import with_setup
if sys.platform != 'win32': # No testing on Windows yet.
from util import main, setup_server, teardown_server, generate, begin
@with_setup(setup_server, teardown_server)
def test_generator():
for _test, browser in generate(__name__):
yiel... |
import pandas as pd
from pandas import DataFrame
from pm4py.objects.log.log import Trace, EventLog
from src.encoding.encoder import PREFIX_
from src.encoding.models import Encoding, TaskGenerationTypes
from src.labelling.common import compute_label_columns, get_intercase_attributes, add_labels
from src.labelling.model... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads_v6/proto/resources/group_placement_view.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
fro... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from preggy import expect
from tests.unit.base import ApiTestCase
from tests.fixtures import (
DomainsViolationsPrefsFactory, DomainFactory, KeyFactory
)
from holmes.models import DomainsViolationsPrefs, Key, Domain, KeysCategory
class TestDomainsViolationsPrefs(ApiTest... |
from django.test import TestCase
from django.test.client import RequestFactory, Client
from user.views import RegisterPatientView
class RegisterPatientViewTest(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.my_view = RegisterPatientView()
self.client = Client()
s... |
#!/usr/bin/env python
"""
Python script to analyse the dependence on relaxation time (=steps to reach equilibrium in ferromagnetic regime)
on grid size, for 2D square lattice. Usage ./eq_steps.py [N values separated by space]
__author__ = Blaise Delaney, JSTP
"""
import numpy as np
import matplotlib as plt
import s... |
arr = [10, 20, 30, 40]
arr[1] = 30
print(arr)
|
import codecademylib
import pandas as pd
orders = pd.read_csv('shoefly.csv')
print(orders.head())
emails = orders['email']
frances_palmer = orders[(orders.first_name == 'Frances') & (orders.last_name == 'Palmer')]
comfy_shoes = orders[orders.shoe_type.isin(['clogs', 'boots', 'ballet flats'])] |
from .response import CustomResponse
from .status import Status
from .ocr_document import DigitalDocumentModel |
from operator import itemgetter
from scipy.stats import kendalltau
def clean_arch_pool_with_performance(pool, perf):
new_arch_pool = dict()
new_arch_perf = dict()
for a, p in zip(pool, perf):
if a not in new_arch_pool.keys():
new_arch_pool[a] = 1
new_arch_perf[a] = [p]
... |
image = tf.placeholder(tf.float32, [None, None, None, 3])
kernel = tf.placeholder(tf.float32, [3, 3, 3, 3])
def conv(x, k):
return tf.nn.conv2d(x, k, strides=[1, 3, 3, 1],
padding='SAME')
output_image = conv(image, kernel)
output_pool = tf.nn.avg_pool(image, ksize=[1, 3, 3, 1],
... |
# encoding: UTF-8
'''
本文件包含了CTA引擎中的策略开发用模板,开发策略时需要继承CtaTemplate类。
v1 针对bitfinex gateway 进行了优化处理 对发单函数进行了改进操作
'''
import numpy as np
import pandas as pd
from datetime import datetime,timedelta,time
import talib
import requests
from collections import defaultdict
from vnpy.trader.vtConstant import *
from vnpy.trader.... |
import xbmc
from libs.pykodi import datetime_now, datetime_strptime
from libs import quickjson
def add_one(dbid, mediatype):
mediaitem = quickjson.get_details(dbid, mediatype)
playcount = mediaitem['playcount'] + 1
lastplayed = datetime_now()
quickjson.set_item_details(dbid, mediatype, playcount=playc... |
import unittest
import utils
# O(n) time. O(1) space. Counting, sliding window.
class Solution:
def minWindow(self, s: str, t: str) -> str:
counts = [0] * 128
for c in t:
counts[ord(c)] -= 1
result_length = 0x7FFFFFFF
result_lo = 0
result_hi = 0
lo = 0... |
# -*- coding:utf-8 -*-
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth import authenticate
from django.conf import settings
from utils.tools.password import Cryptography
class PasswordDecryptoApiView... |
CF=float(input("Quantos cigarros fumado por dia?: "))
TF=int(input("Há quantos anos você fuma?: "))
TPD=(CF*10)/60
DTP=TPD/24
DF=(TF*365)
DPM=DF*DTP
print("Tempo de vida perdido: %d Dias" % DPM)
|
candidates = {
"ods" : """1. Mgr. Martin Kupka, 44 let, starosta, poslanec PČR
2. Petr Vychodil MPA, 48 let, starosta
3. Ing. Jarmila Smotlachová, 54 let, starostka, soukromý zemědělec
4. Mgr. Martin Hrabánek, 47 let, starosta
5. PhDr. Ing. Mgr. Karel Bendl MBA, LL.M., 49 let, staros... |
## Q4
s = [0, 0, 1, 1, 0, 0, 1, 0]
t = [1, 1, 0, 0, 1, 1, 1, 1]
n = len(t)
diff_S_t = 0
diff_t = 0
## For individuals (i,j) if t[i] != t[j]
# and if s[i] != s[j]
# increase the total by 1
for i in range(n):
for j in [x for x in range(n) if x != i]:
if t[i] != t[j]:
diff_t += 1
if s... |
#!/usr/bin/python
'''Plots the PR curves from the analysis created by the RunVUEstimatorPRAnalysis script.'''
usage='PlotVUEstimatorPRCurves.py [options] <inputFile0> <inputFile1> ...'
import roslib; roslib.load_manifest('species_id')
import rospy
from optparse import OptionParser
from pylab import *
import re
import ... |
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import numpy as np
from model.layers.vgg import Vgg19
from utils.tensor_folder import TensorFolder
class VGGCosineSimilarity(nn.Module):
def __init__(self):
super(VGGCosineSimilarity, self).__init__()
self.vgg = Vgg1... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Room'
db.create_table(u'pyconkr_room', (
(u'i... |
#!/usr/local/bin/python3
###!/Users/zhiyang/anaconda3/bin/python3
"""
This is written by Zhiyang Ong to test the automatically generated
filename to store experimental data/results from running
experiments/simulations, and/or automated software regression
testing and hardware regression verification.
Synops... |
# -*- coding: utf-8 -*-
# Copyright (c) 2003, Taro Ogawa. All Rights Reserved.
# Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved.
# This library 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 Fo... |
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the MIT License.
# To view a copy of this license, visit https://opensource.org/licenses/MIT
from bongard import BongardProblemPainter
from bongard.sampler import FreeformSampler
import numpy as np
import os, time
import jso... |
from datetime import datetime, timedelta
from influxpy.model import InfluxMeasurement, ContinuousQuery
from influxpy.fields import InfluxField, InfluxTag, Hours, Days, Minutes
from influxpy.aggregates import Raw, Sum, Mean
from influxpy.queryset import InfluxSeries
from tests import InfluxTestCase
class CounterMeasu... |
from mock import patch, mock, ANY
from pathlib import Path
from context_cli.core import (
start_and_end_delimiter_context_factory_creator, single_delimiter_context_factory_creator,
get_context_factory_from_args, build_pipeline, construct_arg_parser,
parse_args, main
)
from context_cli.util import TypeArgDo... |
from rest_framework.reverse import reverse
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from thenewboston.utils.signed_requests import generate_signed_request
from v1.banks.helpers.most_trusted import get_most_trusted_bank
def primary_validator_updated(client, signing_key, validator, status):
... |
#!/usr/bin/env python3
# testOldMakeExRE.py
""" Test old version of utility for making excluded file name regexes. """
import time
import unittest
from rnglib import SimpleRNG
from merkletree import MerkleDoc
class TestOldMakeExRE(unittest.TestCase):
""" Test old version of utility for making excluded file nam... |
from django.db import transaction
from api.helper import json_error_response
from broker.models import Broker, BrokerVehicle, BrokerOwner, BrokerDriver, BrokerAccount
from owner.models import Owner, Vehicle
def authenticated_user(func):
def inner(request, *args, **kwargs):
if not request.user:
... |
def read_passport_file(file_path):
passports = []
passport = {}
with open(file_path, "r") as passport_file:
for line in passport_file:
if line == "\n":
passports.append(passport)
passport = {}
else:
line = line.split()
... |
# pylint: disable=duplicate-code
# pylint: disable=line-too-long
# pylint: disable=missing-function-docstring
# pylint: disable=missing-function-docstring
# pylint: disable=missing-module-docstring
# pylint: disable=too-many-arguments
# pylint: disable=too-many-branches
# pylint: disable=too-many-instance-attributes
# ... |
import argparse
import json
from tqdm import tqdm
import torch
from dataset import TwitterDataset
def main():
parser = argparse.ArgumentParser()
parser.add_argument("serialization_dir", help="save directory to load model")
parser.add_argument("file", help="file to evaluate on")
args = parser.parse_arg... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
#!/usr/bin/env python
# Adapted from code draft by Tiffany Timbers
# Author: Lianna Hovhannisyan, Karanpreet Kaur
# date: 2021-11-19
"""Downloads xls data from the web to a local filepath as csv file.
Usage: src/download_data.py --out_type=<out_type> --url=<url> --out_file=<out_file>
Options:
--out_type=<out_type> ... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from mrbob.configurator import Configurator
from mrbob.configurator import SkipQuestion
from plonecli.configure_mrbob import check_git_disabled
from plonecli.configure_mrbob import get_mrbob_config_variable
from plonecli.configure_mrbob import post_render
... |
import configuration.automation_settings as automation_settings
overtime_contribution = 0.021
rest_time_contribution = 0.016
email_reception_contribution = 0.0029
ambient_contribution = 0.0012
noise_contribution = 0.03
luminosity_contibution = 0.000153
if automation_settings.automate_tasks: tasks_automation_contribut... |
import numpy as np
import nrrd
import h5py
import glob, os
import cv2
def resize_with_padding(data, targetSize):
#print(data.ndim, len(targetSize))
#assert data.ndim != len(targetSize), "Dimension of data is wrong in resize_with_padding()"
if data.ndim != len(targetSize):
print("Dimension of data i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of the
# Apode Project (https://github.com/mchalela/apode).
# Copyright (c) 2020, Néstor Grión and Sofía Sappia
# License: MIT
# Full Text: https://github.com/ngrion/apode/blob/master/LICENSE.txt
from apode import ApodeData
from apode import datase... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Muges
#
# 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, mer... |
import os
import csv
import collections
import re
from pprint import pprint as pp
RAW_FILE = 'classic-rock-raw-data.csv'
SONG_FILE = 'classic-rock-song-list.csv'
RAW_FILE_LOW = 'classic-rock-raw-data-lowheaders.csv'
SONG_FILE_LOW = 'classic-rock-song-list-lowheaders.csv'
'''
raw_headers = re.sub('[ \?\*]', '_','SONG ... |
"""Create a downloads page for the current GO release."""
####
#### Create a downloads page for the current GO release.
####
#### Example usage to analyze "whatever":
#### python3 downloads-page-gen.py --help
#### python3 ./scripts/downloads-page-gen.py -v --report /tmp/all_combined.report.json --inject ./scripts/dow... |
# module imports
from nifti import volumeutils as vu
from nifti import spm2analyze as spm2
from nifti import nifti1
from nifti import minc
def load(filespec, *args, **kwargs):
''' Load file given filespec, guessing at file type
Parameters
----------
filespec : string or file-like
specification... |
# Copyright 2013, Nachi Ueno, NTT MCL, Inc.
# 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
#
# Unles... |
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
#import here, cause outside ... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.impute import KNNImputer
from sklearn.preprocessing import MinMaxScaler
from sklearn.cluster import KMeans
import wrangle as wr
import preprocessing as pr
im... |
import sys
import time
import array
from termios import TIOCGWINSZ
import fcntl
import cStringIO
import contextlib
from setup import parse_args
from lib import flatten
from qcommand import build_cluster, add_host_info, get_resource_option
from output import print_cluster_status, print_full_status, print_status
def m... |
import numpy as np
from scipy.io import loadmat
import matplotlib.pyplot as plt
mat = loadmat('E:\lessons\ML wu.n.g\coursera-ml-py-master\coursera-ml-py-master\machine-learning-ex7\ex7\ex7data1.mat')
#print(mat.keys())
#print(mat)
X = mat['X'] #(50, 2)
#print(X.shape)
plt.figure(figsize=(8,8))
#facecolor is pots' ... |
from helper import Event, print_error
from TodoModel import TaskModel
class TodoController:
"""
Main controller for handling the TodoApp
"""
def __init__(self):
self.taskModel = TaskModel()
self.event_task_add = Event()
def task_add(self, task: str, priority: int, description: str... |
""" Advent of code 2021 day 15 / 2 """
import math
from os import path
import heapq as hq
pos = [
(-1, 0), (1, 0), (0, -1), (0, 1),
# (-1, 1), (-1, -1), (1, -1), (1, 1)
]
class Code(object):
def __init__(self, lines):
self.lines = lines
self.height = len(lines)
self.width = len(l... |
import sys as _sys
import os as _os
import unittest as _unittest
from apodeixi.testing_framework.a6i_unit_test import ApodeixiUnitTest
from apodeixi.util.a6i_error import ... |
import os
import unittest
from skyscraper.scraper_service import ScraperServiceFactory
from skyscraper.utils.constants import SPEEDOMETER_KEY, AGE_KEY, CAR_KEY, PRICE_KEY, POWER_KEY, CURRENCY_KEY
from common_test_utils import gather_extension_files, VALIDATION_DATA
class TestScraping(unittest.TestCase):
files_under... |
#!/usr/bin/env python
import lxml.etree as ET
import sys
if len(sys.argv) != 4:
print("Usage: %s inputfile.xml transformation.xsl outputfile" % sys.argv[0])
sys.exit(1)
dom = ET.parse(sys.argv[1])
xslt = ET.parse(sys.argv[2])
transform = ET.XSLT(xslt)
newdom = transform(dom)
html=str(newdom)
with open (sys.a... |
import json
import time
import threading
from websocket_server import WebsocketServer
class WebsocketPublisher(object):
"""
Publish cluster state as JSON over a websocket.
Only sends CS state, and information on who is building on who.
This is enough information to draw a graph of the cluster.
Ex... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.