content stringlengths 5 1.05M |
|---|
def chart(theme, tests):
id_name_dict = {}
min_li = []
for test in tests:
id_name_dict[test._id] = test._name
duration = test._duration.split(':')
hour = float(duration[0])
min = float(duration[1])
sec = float(duration[2]) + min * 60 + hour * 60 * 60
min_li.ap... |
from django import forms
from.models import Message,Group,Friend,Good
from django.contrib.auth.models import User
# Messageのフォーム(未使用)
class MessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['owner','group','content']
# Groupのフォーム(未使用)
class GroupForm(forms.ModelForm):
... |
#!/usr/bin/env python3
#
# Copyright 2017 gRPC 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 la... |
############################################################################
# * Copyright 2019 Amazon.com, Inc. and its affiliates. All Rights Reserved.
#
# Licensed under the Amazon Software License (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located ... |
"""WiZ Light integration."""
import logging
from pywizlight import PilotBuilder, wizlight
import voluptuous as vol
try:
from homeassistant.components.switch import SwitchEntity
except ImportError:
from homeassistant.components.switch import SwitchDevice as SwitchEntity
from homeassistant.components.switch imp... |
#!/usr/bin/env python3
from gzip import decompress
from subprocess import check_call
from os import environ
from tempfile import NamedTemporaryFile
from urllib.request import urlopen
server = environ["SERVER"]
manager = environ["MANAGER"]
agent = environ["AGENT"]
iptables_rules = [f"PREROUTING -t nat -p tcp -m tcp ... |
"""
File for representing argus-specific exceptions.
"""
class ArgusException(Exception):
"""
Exception class for the Argus application
"""
pass
class ImageLoadException(ArgusException):
"""
Exception raised when an image file could not be loaded
"""
pass
class InvalidQueryExceptio... |
#!/usr/bin/env python3
"""
Random walk with probabilities p and q = 1 – p respectively. p to move to the right.
Tijms, Henk (2012-06-14). Understanding Probability (p. 93). Cambridge University Press. Kindle Edition.
"""
import argparse
import numpy as np
import matplotlib.pyplot as plt
import sys
def simulate(p, ... |
from atomium import Model, Atom
def hydrophobic_contrast_function(residues):
"""Calculates the hydrophobic contrast function for the centre of some
residues."""
locations = [r.atom(name="CB").location for r in residues if r.atom(name="CB")]
location = [sum(dimension) / len(dimension) for dimension in ... |
import numpy as np
import time
from tclab import TCLab
import pyfirmata
import pandas as pd
import tclab_modules as tcm
import matplotlib.pyplot as plt
import itertools
# Connect to Arduino
heater_board = TCLab(port='4')
fan_board = pyfirmata.Arduino("com5")
it = pyfirmata.util.Iterator(fan_board)
it.start()
pntxt2 ... |
"""gunicorn WSGI server configuration."""
from os import environ
def max_workers():
return environ.get('WORKER_QUANTITY', 4)
bind = '0.0.0.0:' + environ.get('PORT', '5000')
max_requests = 5000
worker_class = 'gevent'
workers = max_workers()
|
import unittest
class PetriNetPlace:
def __init__( self, id_, numberOfTokens=0 ):
assert id_ >= 1 and numberOfTokens >= 0
self.id_ = id_
self.numberOfTokens = numberOfTokens
def hasTokens( self, count ):
return self.numberOfTokens >= count
def putToken( self ):
self.numberOfTokens += 1
def getToken( s... |
# Generated by Django 2.2.3 on 2019-12-27 19:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dotacni_matice', '0007_area'),
]
operations = [
migrations.AlterField(
model_name='dotacnititul',
name='url',
... |
from sqlalchemy import Column, Boolean, Integer, String, DateTime, ForeignKey, and_, not_, or_, event
from tensorhive.database import db_session, Base
from tensorhive.models.CRUDModel import CRUDModel
from tensorhive.utils.DateUtils import DateUtils
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm ... |
import os
import sys
import numpy as np
import argparse
import nnvm.testing
import nnvm.compiler
import tvm
from tvm import autotvm
from tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner
from tvm.contrib.util import tempdir
import tvm.contrib.graph_runtime as runtime
#from mxnet.gluon.model_zoo... |
import PIL
from PIL import Image
import os, sys
from PIL import ImageFilter
import numpy as np
from matplotlib.image import imread
import matplotlib.pyplot as plt
print "Manipulation For: ", sys.argv[1]
print "a. Conversion of RGB to Greyscale!"
img = Image.open(sys.argv[1])
img = img.convert('LA')
img.save('Gre... |
# Generated by Django 3.2.8 on 2021-11-27 10:33
from django.db import migrations, models
import user.models
class Migration(migrations.Migration):
dependencies = [
('user', '0004_alter_profile_profile_picture'),
]
operations = [
migrations.AlterField(
model_name='profile',
... |
from ydk.services import CRUDService
from ydk.providers import NetconfServiceProvider
from ydk.models.cisco_ios_xr import Cisco_IOS_XR_mpls_ldp_cfg as xr_mpls_ldp_cfg
from ydk.types import Empty
import logging
"""
Q: What is the object/method/variable corresponding to the yang path variable?
Ans: A python IDE w... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-04-11 15:58
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import markupfield.fields
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
... |
##############################################################
### Copyright (c) 2018-present, Xuanyi Dong ###
### Style Aggregated Network for Facial Landmark Detection ###
### Computer Vision and Pattern Recognition, 2018 ###
##############################################################
impor... |
import appdirs
__conf_name = "neoload-cli"
__version = "1.0"
__author = "neotys"
__config_dir = appdirs.user_data_dir(__conf_name, __author, __version)
def get_config_dir():
return __config_dir
|
"""
Created on: 22-Mar-2018
Created by: Maneesh D
"""
from __future__ import absolute_import
from Stack import Stack
def is_balanced(expression: str) -> bool:
"""Checks if a given expression is balanced or not"""
exp_stack = Stack(100)
index = 0
balanced = True
while index < len(expression):
... |
"""
This is sample config file for start_topo.py.
Please rename to topo.`hostname`.py before use.
"""
def createTopo():
return {
"controllers": {
"onosdev1" : "192.168.56.11:6633",
"onosdev2" : "192.168.56.12:6633"
},
"switches": {
# Note that dpid is optional.
# If omitted... |
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn import metrics
x_train = pd.read_csv("./data/train.csv")
y_train = x_train.ilo... |
import json
import pytest
import library_registry.drm.templates.adobe_xml_templates as t
from library_registry.drm.controller import (
AdobeSignInRequestParser,
AdobeAccountInfoRequestParser,
AdobeVendorIDClient,
AdobeVendorIDRequestHandler,
AdobeVendorIDModel,
VendorIDAuthenticationError,
... |
import json
import os
import re
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional
from unittest import mock
from packaging.utils import canonicalize_name
from package_info import PKG
from pipx import constants, main, pipx_metadata_file, util
WIN = sys.platform.startswith("win")
MOCK_P... |
"""Return coordinates of free/open fields and the coordinates of the occupying armies."""
class KingdomSolver(object):
"""Class."""
def __init__(self, string_grid):
"""Initialize matrix."""
if isinstance(string_grid, list):
self.matrix = string_grid
else:
self.m... |
import zsorder_pb2
from QAPUBSUB import consumer
# from StockOrderApi import *
def Buy(stkCode, vol, price, formulaNum, ZhuShouHao):
print("buy code=%s, vol=%d, price=%6.2f, no=%d" % (stkCode, vol, price, ZhuShouHao))
# api.Buy1(stkCode, vol, price, formulaNum, ZhuShouHao)
def Sell(stkCode, vol, price, formu... |
# --------------------------------------------------------
# Pytorch FPN implementation
# Licensed under The MIT License [see LICENSE for details]
# Written by Jianwei Yang, based on code from faster R-CNN
# --------------------------------------------------------
from __future__ import absolute_import, division, prin... |
import math
import time
t1 = time.time()
def digt(num):
n = num
digt = 0
while n > 0:
digt += n%10
n = n//10
return digt
temp = []
for i in range(2,200):
for j in range(2,50-i//10):
t = round(math.pow(i,j))
if digt(t) == i:
temp.append(t)
def quickSor... |
# -*- coding: utf-8 -*-
import itertools
import re
import six
from okcupyd import util
from okcupyd.question import UserQuestion
class maps(six.with_metaclass(util.GetAttrGetItem)):
bodytype = util.IndexedREMap(
'rather not say', 'thin', 'overweight', 'skinny', 'average', 'fit',
'athletic', 'ja... |
#!/usr/bin/python3
import numpy as np
# import math
# import matplotlib.pyplot as plt
import logging
import propagation
########################################
# ICIOT Alg
########################################
def GetCij(sr_info, G, PL, params):
'''
Get important notation Cij in the ICIOT paper showing the con... |
import discord
from discord.ext import commands
from discord_slash import cog_ext
from discord_slash.utils.manage_commands import create_option, create_permission
from discord_slash.model import SlashCommandPermissionType
class Slash(commands.Cog):
def __init__(self, bot):
self.bot = bot
@cog_ext.cog_... |
# [Description] ------------------------------
# Module name "Reservoir_retrieval.py"
# This module loops through the dam points to retrieve their associated reservoir polygons from a given
# water mask (such as HydroLAKES).The retrieval process involves two consecutive rounds, with the first
# using a 500-m spatia... |
import os
import time
import math
from glob import glob
import tensorflow as tf
import numpy as np
import h5py
import cv2
import mcubes
from ops import *
class IMSVR(object):
def __init__(self, sess, is_training = False, z_dim=128, ef_dim=64, gf_dim=128, dataset_name='default', checkpoint_dir=None, pretrained_z_dir=... |
# Copyright 2015 Google 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
#
# Unless required by applicable law or agreed ... |
import os
import time
from glob import glob
import tensorflow as tf
from ops import *
'''
conv vae implementation, alpha version, used with mnist, but easy to change to work with cifar-10
mnist samples cropped to 26x26 from 28x28 to produce more diverse training examples
LOADS of code sniplets was taken from:
http... |
'''
Name: trait_extract_parallel.py
Version: 1.0
Summary: Extract plant traits (leaf area, width, height, ) by paralell processing
Author: suxing liu
Author-email: suxingliu@gmail.com
Created: 2019-09-29
USAGE:
python3 color_cluster_cv.py -p /home/suxingliu/plant-image-analysis/test/ -ft jpg
'''
# import... |
import math
while(True):
inp_str = input()
if(int(inp_str) == 0):
break
save_inp = inp_str
res = ''
while(int(inp_str) >= 2):
temp = int(inp_str) % 2
res = str(temp) + res
inp_str = str(math.floor(int(inp_str) / 2))
res = inp_str + res
count = 0
for i in range(0,len(res)... |
import pytest
from django.urls import resolve, reverse
from coding_challenge.ship_manager.models import Ship
pytestmark = pytest.mark.django_db
def test_ship_list():
"""
Test ship list urls.
"""
assert reverse("api:ship-list") == "/api/ships/"
assert resolve("/api/ships/").view_name == "api:ship... |
NO_OF_CHAR=256
def firstNonRepeatingCharacter(string):
# Write your code here.
count = [0] * NO_OF_CHAR
for ch in string:
count[ord(ch)]+=1
for i,ch in enumerate(string):
if count[ord(ch)]==1:
return i
return -1
print(firstNonRepeatingCharacter("abcdcaf")) |
# Copyright 2019 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, ... |
import dydx.constants as consts
class EthPerp(object):
def __init__(
self,
eth,
public_address
):
self.eth = eth
self.public_address = public_address
# initialize contracts
self.btc_perpetual = self.eth.create_contract(
consts.BTC_PERPETUAL... |
from flask_cors import CORS
from flask_login import LoginManager
from flask_redis import FlaskRedis
from app.models.base import db
from .app import Flask
cors = CORS(supports_credentials=True)
login_manager = LoginManager()
redis = FlaskRedis(decode_responses=True)
def register_blueprints(flask_app):
from app.a... |
import numpy as np
import random
from copy import copy, deepcopy
from time import time
import argparse
import multiprocessing
import rank
from cube_model import MoveSpace as MS
import move_coord
import search
"""
Handles user input and constructs 3 search threads.
Each thread has a different cube that is rotated at 12... |
# -*- coding: utf-8 -*-
# @date 20111228
# @author grtfou
# @version - 0.1 [test]
# @brief It is web crawling to get stock price/vol from yahoo stock.
# @brief http://hk.finance.yahoo.com/
import sys
import urllib
import datetime
from lxml import etree
from StringIO import StringIO
f... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rcParams
from scipy.stats import pearsonr
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
AutoMinorLocator)
# customized settings
params = { #... |
# coding=utf-8
from OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField
from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde
# Generated with OTLEnumerationCreator. To modify: extend, do not edit
class KlBestratingSteenverband(KeuzelijstField):
"""De steenverbanden van de bestratin... |
# USAGE
# python photo_booth.py --output output
# import the necessary packages
from __future__ import print_function
from pyimagesearch.photoboothapp import PhotoBoothApp
from imutils.video import VideoStream
import argparse
import time
# construct the argument parse and parse the arguments
ap = argparse.ArgumentPar... |
from tf_fourier_features.fourier_features import FourierFeatureProjection
from tf_fourier_features.fourier_features_mlp import FourierFeatureMLP
__version__ = '0.0.2.1'
|
# ---------------------------------------------------------------------
# Eltex.MES.get_interface_status
# ---------------------------------------------------------------------
# Copyright (C) 2007-2011 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# ... |
from django.db import models
import pytest
import strict_fields
from .common import END_OF_2019_AWARE
from .common import END_OF_2019_NAIVE
@pytest.mark.parametrize('model_name', [('CharField'), ('TextField')])
def test_original_fields_get_default(model_name):
# NOTE: Including this here to showcase the problem ... |
import re
class Token:
def __init__(self, name, value):
self.name = name
self.value = value
def get_name(self):
return self.name
def get_value(self):
return self.value
def __str__(self):
return self.get_name() + ': ' + self.get_value()
# TODO: instead of returning a... |
import unittest
import warnings
import matplotlib.pyplot as plt
import pandas as pd
from rpy2.rinterface import RRuntimeWarning
from roses.statistical_test.kruskal_wallis import kruskal_wallis
# Filter the warnings from R
warnings.filterwarnings("ignore", category=RRuntimeWarning)
class RunningKruskal(unittest.TestC... |
from math import log2, sqrt
import torch
from torch import nn, einsum
import torch.nn.functional as F
from einops import rearrange
from x_transformers import Encoder, Decoder
# helpers
def exists(val):
return val is not None
def is_empty(t):
return t.nelement() == 0
def masked_mean(t, mask, dim = 1):
t... |
import json
import scrapy
with open('sendereihen.json') as f:
sendereihen = json.load(f)
class SendungenSpider(scrapy.Spider):
name = 'sendungen'
allowed_domains = ['oe1.orf.at']
start_urls = ['https://oe1.orf.at%s' % sendereihe['url'] for sendereihe in sendereihen]
def parse(self, response):
... |
import rospy
from yaw_controller import YawController
from pid import PID
from lowpass import LowPassFilter
GAS_DENSITY = 2.858
ONE_MPH = 0.44704
class Controller(object):
def __init__(self,
vehicle_mass=0.,
fuel_capacity=0.,
brake_deadband=0.,
... |
class DatabaseAccessBlocked(Exception):
pass
|
import numpy as np
import pandas as pd
def normalization(df, feature):
from sklearn.preprocessing import MinMaxScaler
normalScaler = MinMaxScaler()
df[feature] = normalScaler.fit_transform(np.array(df[feature]).reshape(-1, 1))
def standardization(df, feature):
from sklearn.preprocessing impor... |
"""core URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vi... |
import logging
import random
import string
from lsassy.dumpmethod import IDumpMethod, CustomBuffer
from lsassy.impacketfile import ImpacketFile
class DumpMethod(IDumpMethod):
need_debug_privilege = True
def __init__(self, session, timeout):
super().__init__(session, timeout)
self.comsvcs_co... |
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f'{self.name} - {self.age}'
def __repr__(self):
return f'{self.name} - {self.age}'
class AnimalList:
def __init__(self):
self.__animal_list = [
A... |
from __future__ import print_function
import requests
import sys
import calendar
import time
import math
import json
CHUNK_ATTEMPTS = 6
CHUNK_ATTEMPT_SLEEP = 10
if len(sys.argv) < 2 or len(sys.argv) > 3:
print("usage:")
print(" rechat-dl.py VOD-ID [FILE]")
print(" VOD-ID: can be found in the vod url ... |
"""Combines translated strings from a spreadsheet with a fr.json file.
This utility assumes you have already run `npm run translations`, so that
fr.json already contains keys for all the strings you want translated, but some
of those keys still have english values.
The spreadsheet must be a csv file with only two col... |
from __future__ import absolute_import
from __future__ import unicode_literals
from corehq.apps.locations.tests.util import LocationHierarchyTestCase
from corehq.apps.users.dbaccessors.all_commcare_users import delete_all_users
from corehq.apps.users.models import WebUser
from custom.m4change.reports import get_locatio... |
import graphing
import gspread
import graphing
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('natural language-7c67e633a610.json', sc... |
#n = int(input('Dgite um numero '))
#c = n
#f = 1
#while c > 0 :
# print('{}'.format(c), end='')
# print('x'if c > 1 else '=', end='')
# f = f * c
# c = c-1
#print('O fatorial de {} é '.format(n))
n = int(input('Dgite um numero '))
c = n
f = 1
for g in range(c, -1, -1):
print('{}'.format(c), end='')
... |
import os
from dbnd._core.configuration.environ_config import ENV_DBND_USER
def _default_getuser():
return "unknown"
def _find_getuser_f():
try:
if ENV_DBND_USER in os.environ:
return lambda: os.environ[ENV_DBND_USER]
if os.name == "nt":
if hasattr(os, "getlogin"):
... |
import logging
def setup_logger(name: str, log_file: str, log_format: str = "%(levelname)s:%(name)s:%(asctime)s:%(message)s",
date_format: str = "%D:%H.%M.%S", log_level: int = logging.INFO) -> logging.Logger:
"""
Creates new logger from the logging module with ease and returns it
To use... |
#!/usr/bin/env python
import os
import sys
from django.conf import settings
class AlternateDBTestRouter(object):
def allow_syncdb(self, db, model):
"""
The ``Party`` and ``Politician`` objects in our initial_data
(.py and .json) fixtures are not allowed to enter the "alternate"
dat... |
# Generated by Django 3.1.4 on 2021-05-28 10:54
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='room',
old_name='votes',
new_name='v... |
from dataclasses import dataclass
@dataclass
class Event:
pass |
import jwt
import bcrypt
import pytest
import config
from model import UserDao, TweetDao
from service import UserService, TweetService
from sqlalchemy import create_engine, text
from unittest import mock
database = create_engine(config.test_config['DB_URL'], encoding='utf-8', max_overflow=0)
@pytest.fixture
def use... |
from app import create_app
import config
config.load('./config.json')
app = create_app(config)
|
#
# A random agent, and very simple example of the core methods needed for
# an RL-Glue/pyRL agent. The RL-Glue methods all begin with "agent_",
# and pyRL expects __init__ and randomize_parameters of the form shown
# here.
#
# This was based upon the skeleton_agent that comes with the RL-Glue
# python codec (Brian Tan... |
# all_unique
# Checks a flat list for all unique values. Returns True if list values are all unique and False if list values
# aren't all unique.
# This function compares the length of the list with length of the set() of the list. set() removes duplicate values
# from the list.
def all_unique(lst):
return len(... |
from django.utils import timezone
from threading import Thread, Event
from apps.vnc.models import Session
from utils.singleton import SingletonType
from datetime import timedelta
import socket
import time
# need to wrap in mutex locks
class VNCSessions(Thread):
__metaclass__ = SingletonType
def __init__(self):
... |
"""This module provides a generalized implementation of UNet.
See the `UNet` class docstring for more information.
"""
import attr
from typing import List, Optional, Text
from sleap.nn.architectures import encoder_decoder
from sleap.nn.config import UNetConfig
import numpy as np
import tensorflow as tf
@attr.s(auto... |
import logging
import datetime
LOG = logging.getLogger('strvup.hrmparser')
class HrmParser:
_PARSERS = {
'Params': '_parse_params',
'HRData': '_parse_hrm_data',
}
def __init__(self, path):
self.path = path
self.sections = {}
@staticmethod
def _parse_params(line... |
import requests
from bs4 import BeautifulSoup
import json
import twitter
def oauth_login():
# XXX: Go to http://twitter.com/apps/new to create an app and get values
# for these credentials that you'll need to provide in place of these
# empty string values that are defined as placeholders.
# See https:... |
from blogfetch import BlogFetch
from gspreadsheet import DB
|
import json
import os
from typing import Optional
from urllib.parse import urlparse
import click
import requests
import requests.auth
from click_aliases import ClickAliasedGroup
from requests.exceptions import RequestException
from requests_toolbelt.sessions import BaseUrlSession
from . import auth, config, index, mc... |
from tensorflow.keras.layers import *
from tensorflow.keras.models import *
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.optimizers import *
class CharCNN(tf.keras.models.Model):
def __init__(self, feature, units, embedding_size, vocab_size, input_length, ... |
"""
[2015-07-27] Challenge #225 [Easy/Intermediate] De-columnizing
https://www.reddit.com/r/dailyprogrammer/comments/3esrkm/20150727_challenge_225_easyintermediate/
# [](#EasyIcon) _(Easy/Intermediate)_: De-columnizing
Often, column-style writing will put images and features to the left or right of the body of text, ... |
import threading
from time import time
def job_scheduler(f, n):
return threading.Timer(n * time() * 1000, f).start()
class Scheduler:
def __init__(self):
# tuple (fn, time)
self.fns = []
# Locking for no changing fns at same time
self.lock = threading.RLock()
# waitin... |
def write_design_matrix_csv(patsy_dmatrix, participant_column, column_names,
outfile_path):
import pandas as pd
try:
# TODO
# patsy dmatrix might actually already be a dataframe- rename this
# variable please
patsy_dmatrix.to_csv(outfile_path)
... |
"""heibon_django URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class... |
import base64
def parse_basic_auth(header_value):
"""
Attempts to parse the given header value as a Base64-encoded Basic auth header.
"""
if not header_value:
return None
parts = header_value.split(" ")
if len(parts) != 2 or parts[0].lower() != "basic":
return None
try:
... |
import spacy
from urllib.request import urlopen
from bs4 import BeautifulSoup
from act_dictionary import act_dic
def load_model(text):
nlp = spacy.load("section_model")
# html_url = html_link
html_text = text
# print(html)
soup = BeautifulSoup(html_text, features="html.parser")
# kill all sc... |
#A* pathfinding algorithm
class Cell:
def getF(self):
return self.g + self.h
def __init__(self, x, y, passabru, parent = None, g = 0, h = 0):
self.x = x
self.y = y
self.passable = passabru
self.parent = parent
self.g = g
self.h = h
def setG(self, ... |
import os
import wget
def download_zenodo():
if os.path.exists("MatlabData"):
pass
else:
print("Download files from Zenodo ... ")
os.mkdir("MatlabData")
wget.download("https://zenodo.org/record/4157615/files/Au_rock_scan_geometry.txt", out="MatlabData")
wget.downloa... |
"""
Mask grid points based on different criteria.
"""
import numpy as np
from .base import n_1d_arrays
try:
from pykdtree.kdtree import KDTree
except ImportError:
from scipy.spatial import cKDTree as KDTree # pylint: disable=no-name-in-module
def distance_mask(
data_coordinates, maxdist, coordinates=No... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 7 11:50:39 2021
@author: Ashish
"""
from matplotlib import pyplot as plt
import math
import seaborn as sns
import pandas as pd
# create sample
df = pd.read_csv('uciml_adult.csv')
# replace all occurence of ? with NA
df1 = df.replace(to_replace='?', value=' ')
# print(d... |
#!/usr/bin/env python2.7
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.proxy import *
from... |
import unittest
from credentials import Credentials
class CredentialsTest(unittest.TestCase):
def setUp(self):
'''
Set up method to run before each test cases.
'''
self.new_credentials = Credentials('Twitter','paulmburu65','paulmburu08@gmail.com','python3465')
def tearDow... |
# -*- coding: utf-8 -*-
"""The log2timeline devtools module."""
__version__ = '20150218'
|
import csv, os, json, argparse, sys
"""
use with wd ee
"""
# Initiate the parser
parser = argparse.ArgumentParser()
parser.add_argument("-q", "--query", help="perform SPARQL query",
action="store_true")
# Read arguments from the command line
args = parser.parse_args()
#print(args)
# Check for --version or -... |
@auth.requires_login()
def _novoUsuario():
usuario_logado = auth.user_id
tipo = db(db.auth_user.id == usuario_logado).select(db.auth_user.tipo)[0].tipo
funcionario = 3
adm = 1
if tipo == funcionario or tipo == adm:
form = SQLFORM(db.auth_user, _class='ui form')
if form.accepts(request.vars):
session.f... |
import argparse
import os
from os.path import join, isfile, isdir
from os import listdir, stat
from plot_model import visualize_model
def run_directory(root_dir, filename):
dirs = [d for d in listdir(root_dir) if isdir(join(root_dir, d))]
files = [f for f in listdir(root_dir) if isfile(join(root_dir, f))]
if fil... |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
n = int(input())
a = input().strip().split(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.