content stringlengths 5 1.05M |
|---|
from math import sqrt
def is_prime(num):
if num <= 1:
return False
for denominator in range(2, int(sqrt(num)) + 1):
if num % denominator == 0:
return False
return True
def is_circular_prime(num):
num_permutations = get_rotations(str(num))
for permutation in num_permu... |
from typing import Dict
from unittest.mock import MagicMock
import pytest
from openapi_parser.builders.common import extract_extension_attributes
from openapi_parser.builders.schema import merge_all_of_schemas, SchemaFactory
from openapi_parser.enumeration import DataType
from openapi_parser.errors import ParserError... |
import pytest
from ddtrace import config as ddconfig
from ..trace_utils import int_service
from ...constants import SPAN_KIND
from ...ext import SpanTypes, ci, test
from ...pin import Pin
from .constants import FRAMEWORK, HELP_MSG, KIND
def is_enabled(config):
"""Check if the ddtrace plugin is enabled."""
r... |
import random
import requests
import demjson
from bs4 import BeautifulSoup
__url = 'http://fundf10.eastmoney.com/FundArchivesDatas.aspx?type=jjcc&code={}&topline=50&year=&month=&rt=' + \
str(random.random())
__url_zcpz = 'http://fundf10.eastmoney.com/zcpz_{}.html'
headers = {
'User-Agent': 'Mozilla/5.0 (Window... |
# Use this file in conjunction with config-iris.py by setting:
#
# export PALLADIUM_CONFIG=config-iris.py,config-iris-dataset-from-python.py
{
'dataset_loader_train': {
'!': 'palladium.dataset.CSV',
'path': 'iris.data',
'names': [
'sepal length',
'sepal width',
... |
a=5
b=4
print("multiplication is",(a*))
print("multiplication success")
|
__version__ = '3.0.6'
FORDONSPOSITION_URL = 'https://api.sl.se/fordonspositioner/GetData?' \
'type={}&pp=false&cacheControl={}'
TRAFIKLAB_URL = 'https://api.sl.se/api2/'
SI2_URL = TRAFIKLAB_URL + 'deviations.json?key={}&siteid={}&lineNumber={}'
TL2_URL = TRAFIKLAB_URL + 'trafficsituation.json?ke... |
import pandas as pd
####### Read file
df = pd.read_csv("salaries.csv")
df.head()
############3 Drop Column 'salary_more_then_100k'
inputs = df.drop('salary_more_then_100k',axis='columns')
target = df['salary_more_then_100k']
from sklearn.preprocessing import LabelEncoder
le_company = LabelEncoder()
... |
#Cory Mavis
import cv2
import numpy
import sys
import subprocess
import os
cv2.namedWindow("LiveFeed")
def callback (event,x,y,flags,params):
global blueMark #update the position of the blue point
global greenMark #update the position of the green point
global redMark #update the position of... |
# Copyright (c) 2018 The Chromium Embedded Framework Authors. All rights
# reserved. Use of this source code is governed by a BSD-style license that
# can be found in the LICENSE file.
from __future__ import absolute_import
from cef_parser import *
from file_util import *
import os
# Other headers that export C API f... |
from mrjob.job import MRJob,MRStep
class ForbeniusCalculation(MRJob):
"""[summary]
Args:
MRJob ([type]): [description]
"""
def steps(self):
""" This method defines the number of steps involved to execute the mapreduce job."""
return [
MRStep(mapper_raw=self.mapper,
... |
'''
Estimate rms of closure phase error due to scattering.
'''
import numpy as np
from scipy.ndimage import imread
import time
import matplotlib.pyplot as plt
from palettable.colorbrewer.qualitative import Dark2_5
plt.rcParams['image.cmap'] = 'gray_r'
plt.rcParams['image.origin'] = 'lower'
plt.rcParams['patch.edgecolo... |
# Copyright 2019 Eli Lilly and Company
#
# 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 l... |
# This file is part of the QuTIpy package.
# https://github.com/sumeetkhatri/QuTIpy
#
# Copyright (c) 2022 Sumeet Khatri.
# --.- ..- - .. .--. -.--
#
#
# SPDX-License-Identifier: AGPL-3.0
#
# This program is free software: you can redistribute it and... |
import os
import json
from collections import OrderedDict
from lib.config import cfg
def id_to_name(id, category_list):
for k, v in category_list.items():
if v[0] <= id and v[1] > id:
return (k, id - v[0])
def category_model_id_pair(dataset_portion=[]):
'''
Load category, model name... |
import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
from scipy import stats
from sklearn.neighbors import KernelDensity
# plot distribution of X_A, X_B
fig, ax = plt.subplots(1, 1)
fig.set_size_inches(5, 2)
x_min = 1e20
x_max = -1e20
y_max = -1e20
for i in range(2):
x_suffix = ("A",... |
# Add parent directory to path
import sys
sys.path.append('../..')
# Unit test modules
import unittest
from unittest import mock
from textwrap import dedent
import os
from generate_manifest import *
def Create_fastq():
SAMPLE_NAME = 1
mockfiles = []
# Create 3 empty files with fastq.gz extensions
for... |
#! /usr/bin/env python
"""
Given a list of folders, recursively searches for svg files.
Then, examines each file and ensures each element id is unique across all svg files.
"""
# from lxml import etree
import sys, os, os.path, re
srcfolders = sys.argv[1:] if len(sys.argv) >= 2 else [os.getcwd()]
svgs = []
for srcfo... |
class SolarPanel(object):
"""Solar Panel type to be used in the model with the following properties:
Attributes:
efficency: The manufacturer stated efficiency.
cost: The cost of a single solar panel_area.
area: The useful surface area of the panel.
power: The max power producti... |
'''
Bayesian sequence combination, variational Bayes implementation.
'''
import datetime
import numpy as np
from scipy.sparse.coo import coo_matrix
from scipy.special import logsumexp, psi, gammaln
from scipy.optimize.optimize import fmin
from joblib import Parallel, delayed, cpu_count, effective_n_jobs
import warning... |
class ProcessModuleCollection(ReadOnlyCollectionBase,ICollection,IEnumerable):
"""
Provides a strongly typed collection of System.Diagnostics.ProcessModule objects.
ProcessModuleCollection(processModules: Array[ProcessModule])
"""
def Contains(self,module):
"""
Contains(self: ProcessModuleCollect... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import logging
import numpy as np
from scipy import interpolate
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler(level=logging.INFO))
__all__ = ['py2round', 'interpolate_missing_data']
... |
import numpy as np
def rsq(true, predictions):
return 1 - np.mean((true - predictions)**2) / np.var(true)
|
"""
Problem Statement
Given an unsorted array of numbers and a target ‘key’, remove all instances of ‘key’ in-place and return the new length of the array.
Example 1:
Input: [3, 2, 3, 6, 3, 10, 9, 3], Key=3
Output: 4
Explanation: The first four elements after removing every 'Key' will be [2, 6, 10, 9].... |
# Reads number and prints basic math operations
number = int(input('Digite um número para ver sua tabuada: '))
for c in range (1, 11):
print('{} x {} = {}'.format(number, c, (number * c)))
|
#!/usr/local/bin/python
import subprocess
def request_to_app():
import urllib
resp = urllib.urlopen('http://localhost:9000/ping')
print("request to http://localhost:9000/ping is " + str(resp.getcode()))
return resp.getcode()
app_pid = subprocess.Popen(["sbt", "-Drun.mode=Stub", "run"])
import time
co... |
from abc import ABC, abstractmethod
class BaseStrategy(ABC):
"""Base class for all document conversion strategies.
This class is separate from the actual converter class so that
the strategy can be chosen without triggering the __enter__
method.
"""
@abstractmethod
def __init__(self, op... |
import Brick
class BrickHandler(object):
def __init__(self):
self._bricks = []
def insert(self, brick: Brick):
self._bricks.append(brick)
|
import operator
import pytest
from ...primitives import Int, Float, Bool
from .._check_valid_binop import check_valid_binop_for
def test_valid():
check_valid_binop_for(operator.add, Int, "While testing", valid_result_types=(Int,))
def test_unsupported():
with pytest.raises(
TypeError, match="Whil... |
from argparse import ArgumentParser
from cline import ArgumentParserCli, RegisteredTasks
import edition.tasks
from edition.presses import keys
class Cli(ArgumentParserCli):
def make_parser(self) -> ArgumentParser:
parser = ArgumentParser(
description="Lightweight documentation generator",
... |
import numpy as np
import math
import pandas as pd
import geopandas as gpd
from metaflow import step
def find_diff_rows_number(df1, df2):
result = f"The number of different rows between 2 df: {len(df1[~df1.apply(tuple,1).isin(df2.apply(tuple,1))])}"
return result
def find_diff_rows_and_cells(df1, df2):
... |
import logging
import os
import pytest
import tempfile
import actions.tree
import actions.drop
import actions.tamper
import actions.duplicate
import actions.utils
import actions.strategy
import engine
import evaluator
import evolve
import netifaces
from scapy.all import IP, TCP
def test_compression_strategy(logger)... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from . import models
# Register your models here.
@admin.register(models.User) # decorator
class CustomUserAdmin(UserAdmin):
""" Custom User Admin """
fieldsets = UserAdmin.fieldsets + (
(
"Custom Profile",
... |
def feb(n):
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a + b
print()
# Print None.
print(feb(2000))
def feb2(n):
"""Return a list containing the Fibonacci series up to n."""
result = []
a, b = 0, 1
while a < n:
... |
import torch
from torch.utils.data import TensorDataset, DataLoader, SequentialSampler
from transformers import BertTokenizer
# Initialize dataset for testing
def initialize(df):
X_val = df.processed_tweet.values
y_val = df.label.values
df['data_type'] = 'val'
return X_val, y... |
from typing import Optional
from arch.univariate.distribution import Normal as N
from scipy.stats import norm
from ._base import DistributionMixin, _format_simulator
class Normal(N, DistributionMixin):
def __init__(self, random_state=None):
DistributionMixin.__init__(self)
N.__init__(self, rando... |
import yaml
import glob
import os
import imp
class Actors(object):
def __init__(self):
pass
pass
# all_actors = Actors()
def isValid(dir):
return dir not in ('__pycache__',)
empty = object()
class Parameter(object):
def __init__(self, name, type, default=empty):
self.name = nam... |
from django.shortcuts import render
from .models import passport_stat
from .forms import passport_stat_form
# Create your views here.
def passport_stat_create_view(request):
form = passport_stat_form(request.POST or None)
if form.is_valid():
form.save()
form = passport_holder_form()
context = {
'form' : form
... |
import warnings
from pyspark.sql.session import SparkSession
from copy import deepcopy
from .validate import validate_settings, _get_default_value
from .case_statements import (
_check_jaro_registered,
sql_gen_case_smnt_strict_equality_2,
sql_gen_case_stmt_levenshtein_rel_3,
sql_gen_case_stmt_levensh... |
import os
import json
import uuid
import boto3
from datetime import datetime
dynamodb = boto3.client('dynamodb')
def lambda_handler(event, context):
print('Received event: ' + json.dumps(event, indent=2))
table_name=os.environ['table_name']
firstname = event['FirstName']
lastname = event['LastName']
... |
from __future__ import absolute_import
from __future__ import print_function
import os
import unittest
from pybufrkit.dataquery import NodePathParser
from pybufrkit.errors import PathExprParsingError
BASE_DIR = os.path.dirname(__file__)
class NodePathParserTests(unittest.TestCase):
def setUp(self):
sel... |
from inqry.system_specs import macdisk
DISKUTIL_OUTPUT = ''' Device Identifier: disk1
Device Node: /dev/disk1
Whole: Yes
Part of Whole: disk1
Device / Media Name: APPLE SSD SM1024G
Volume Name: Macintosh HD
Mounted: ... |
def is_valid_integer(str_value):
try:
return int(str_value) >= 0
except (ValueError, TypeError):
return False |
# Copyright 2014-2020 Scalyr Inc.
#
# 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 writin... |
import dill as pkl
import os
filePath = './output/'
fileNameHead = 'rel_cat_recall_'
def file_name(file_dir):
file_list_r = []
for root, dirs, files in os.walk(file_dir):
file_list=files
for file_i in file_list:
if fileNameHead in file_i:
file_list_r.append(file_i)
return fi... |
"""
Assignment: Random fasta and fastq file generator
Write a python program that generates both fasta and fastq files containing reads with the following characteristics:
-Read id contains a progressive number starting from 0. -Sequences have length 50 bp
-Bases are randomly generated using a A,T,C,G alphabet, but pr... |
"""VeSync integration."""
import logging
from pyvesync import VeSync
import voluptuous as vol
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import async... |
import glob
import os
import json
import configparser
import re
import time
from datetime import date
import pandas as pandas
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import bs4
# Initialize variables
# Windows PC:
PATH = "./drivers/chromedriver.exe"
# LINUX PC:
# PATH = "... |
import unittest
import datetime
from infi.clickhouse_orm import *
import logging
logging.getLogger("requests").setLevel(logging.WARNING)
class _EnginesHelperTestCase(unittest.TestCase):
def setUp(self):
self.database = Database('test-db', log_statements=True)
def tearDown(self):
self.datab... |
from setuptools import setup, find_packages
from slackminion.plugins.state_s3 import version
setup(
name='slackminion-s3',
version=version,
packages=find_packages(exclude=['test_plugins']),
url='https://github.com/arcticfoxnv/slackminion-s3',
license='MIT',
author='Nick... |
"""
Fine-tune and save regression models predicting functioning levels per domain with Simple Transformers.
The script can be customized with the following parameters:
--datapath: data dir
--doms: the domains for which models are trained
--config: json file containing the model args
--model_type: type ... |
# Chapter 5 Compressing Data via Dimensionality Reduction
# Using kernel principal component analysis for nonlinear mappings
'''
Using kernel PCA, we will learn how to transform data that is not linearly spearable
onto a new, lower-dimensional subspace that is suitable for linear classifiers.'''
# Kernel functions and... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Problem 115
Calendar Module
Source : https://www.hackerrank.com/challenges/calendar-module/problem
"""
from calendar import weekday, day_name
m, d, y = map(int, input().split())
print(day_name[weekday(y, m, d)].upper())
|
#!/usr/bin/env python
# encoding: utf-8
# The MIT License (MIT)
# Copyright (c) 2018-2020 CNRS
# 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 limita... |
## Task 0.4
## Modules
class Module:
"""
Attributes:
_modules (dict of name x :class:`Module`): Storage of the child modules
_parameters (dict of name x :class:`Parameter`): Storage of the module's parameters
mode (string): Mode of operation, can be {"train", "eval"}.
"""
def ... |
# -*- coding: utf-8 -*-
"""
Python M1 – INALCO
16/12/2019
Exemple de requête avec pandas
"""
import pandas
df = pandas.read_csv(open('panorama-des-festivals.csv'), sep=';')
rows = df.loc[df.Département.isin(['75', '77', '78', '91', '92', '93', '94', '95']), ['Nom de la manifestation', 'Commune principale']]
print(r... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class CategoryItem(scrapy.Item):
main_menu_title = scrapy.Field()
main_menu_url = scrapy.Field()
main_menu_quantity = scrapy.Field()
clas... |
import mysql.connector
import random
import sys
import string
from flask import Flask
from flask import request, jsonify, Response
import json
db_admin = Flask(__name__)
class DBWrapper():
CONFIG = {
'user': 'root',
'password': 'root',
'host': 'db',
'port': '3306',
'databas... |
d = [4,1,1,1,5,1,3,1,5,3,4,3,3,1,3,3,1,5,3,2,4,4,3,4,1,4,2,2,1,3,5,1,1,3,2,5,1,1,4,2,5,4,3,2,5,3,3,4,5,4,3,5,4,2,5,5,2,2,2,3,5,5,4,2,1,1,5,1,4,3,2,2,1,2,1,5,3,3,3,5,1,5,4,2,2,2,1,4,2,5,2,3,3,2,3,4,4,1,4,4,3,1,1,1,1,1,4,4,5,4,2,5,1,5,4,4,5,2,3,5,4,1,4,5,2,1,1,2,5,4,5,5,1,1,1,1,1,4,5,3,1,3,4,3,3,1,5,4,2,1,4,4,4,1,1,3,1,3... |
import code.book_plots as bp
import code.gh_internal as gh
import matplotlib.pyplot as plt
import numpy as np;
import time
from pylab import *
from drawnow import drawnow, figure
from filterpy.discrete_bayes import normalize
from filterpy.discrete_bayes import predict
from filterpy.discrete_bayes import update
from sc... |
import pytest
from . import AbstractViewsTests
@pytest.mark.usefixtures("test_app")
class TestHome(AbstractViewsTests):
_prefix = "/admin/"
def test_index_rendering(self, test_app):
resp = self.get(test_app, status=302)
assert "http://localhost/admin/layertree" == resp.location
to_l... |
# Author: Oliver Chalkley
# Affiliation: Bristol Centre for Complexity Science (BCCS) and the Bristol Minimal Genome Group (MGG)
# Date of creation: 06/12/2017
# import relavent libraries
import os
import time
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics.cluster import ad... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('confreg', '0011_optout'),
]
operations = [
migrations.RunSQL(
"UPDATE confreg_conferenceregistration SET regtoke... |
import os
import datetime
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
curr_dir = os.getcwd()
project_result_dir = '\\project_result'
full_project_result_dir = curr_dir+project_result_dir+'\\'
input_filename_core = 'disease_model_merged_data_vFinal_p'
output_filename_c... |
from sqlalchemy import (Column, String, DateTime, Float, Integer)
from database import Base
class TaskData(Base):
"""
Create a task data table
"""
__tablename__ = 'task_data'
id = Column(Integer, primary_key=True)
timestamp = Column(DateTime)
temperature = Column(Float)
duration = Col... |
# Objective
# Check out the Tutorial tab for learning materials and an instructional video!
# Task
# A Node class is provided for you in the editor. A Node object has an integer data field,
# , and a Node instance pointer,
# , pointing to another node (i.e.: the next node in a list).
# A removeDuplicates function is... |
import os
import datetime # datetime.datetime.utcnow()
import time
import pymongo
import inspect
import re
import sys, traceback
import mod_misc
import mod_global
import mod_messenger
import mod_woocommerce
import mod_shopcart
import mod_database
from inspect import currentframe, getframeinfo
# Constant variables
# ... |
from project.drink.drink import Drink
class Tea(Drink):
def __init__(self, name: str, portion: float, brand: str):
super().__init__(name, portion, 2.5, brand)
|
from typing import Tuple
from requests import Session
from requests.models import Response
import json
ENV = "docker"
if ENV == "local":
# If you are running the services on the same machine, you need to assign different ports
USERS_API_URL = 'http://localhost:8082/api/users-service'
ORDERS_API_URL = 'http... |
all=['stinfmodel']
|
from irisreader.file_hub import file_hub, ASTROPY_FILE_METHOD
from irisreader.iris_data_cube import iris_data_cube
from irisreader.raster_cube import raster_cube
from irisreader.sji_cube import sji_cube
from irisreader.get_lines import get_lines
from irisreader.has_line import has_line
from irisreader.observation impor... |
#import files which are needed
import numpy as np
import cv2
import os
#filename
fileName = 'captureVideoFile.avi'
#get default capture device to get images
capture = cv2.VideoCapture(0)
#define extension of the video which is being recorded
videoType = cv2.VideoWriter_fourcc(*'XVID')
#get video file... |
import pytest
import os
from helpers.cluster import ClickHouseCluster
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
cluster = ClickHouseCluster(__file__)
node = cluster.add_instance('node')
@pytest.fixture(scope="module", autouse=True)
def started_cluster():
try:
cluster.start()
yield ... |
from typing import List
from rst_lsp.server.datatypes import DocumentSymbol
from rst_lsp.server.workspace import Config, Document, Workspace
from rst_lsp.server.plugin_manager import hookimpl
@hookimpl
def rst_document_symbols(
config: Config, workspace: Workspace, document: Document
) -> List[DocumentSymbol]:
... |
def potencia(n1, n2):
return n1 ** n2
def soma(*args):
soma = 0
for i in args:
soma += i
return soma
# print(__name__)
if __name__ == '__main__': # para quando eu importar este módulo em outro código a parte de baixo não seja executada.
# Todos cógigos python que está sendo executado ... |
unsorted = [456, 456, 4, 89, 4956, 53, 12, 123, 345, 134, 23, 46, 37]
class MafSort:
def __init__(self, lst):
self.lst1 = lst
#self.list2 = list2
"""
bubble sort algorithm
This sorting algorithm is comparison-based algorithm in which each pair of adjacent elements is compared a... |
# -*- coding: utf-8 -*-
'''
This script has been created in the context of the Hotmaps EU project.
@author: Sara Fritz
@Institute: TUW, Austria
@Contact: fritz@eeg.tuwien.ac.at
'''
#This function calculates the levelized costs of heat (LCOH) in �/MWh for one building
def levelized_costs_of_heat(energy_demand, heat_l... |
from configparser import ConfigParser
def config_update(file, section, option, new_value):
"""
Creates and/or updates a configuration flat file.
Args:
file (str): file to change or create
section (str): config file section to target or create
option (str): config file option (unde... |
#!/usr/bin/env python3
#
# Takes a masscan report and
# grabs banners from open services
# using nmap. Then produces a report
# of services. The report is stored
# in CSV format and placed in the
# output directory.
#
# Usage:
# verify_and_report.py [OPTIONS] <scan file> <num concurrent scans> <max packets per second... |
import smartpy as sp
admin_mixin = sp.io.import_script_from_url("file:contracts/Administrable.py")
utils = sp.io.import_script_from_url("file:contracts/Utils.py")
FA2 = sp.io.import_script_from_url("file:contracts/FA2.py")
# TODO: is_fa2_permitted/get_fa2_permitted is probably not needed? maybe for interop...
# TODO:... |
import os
import argparse
import subprocess
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Use this script to start the docker image")
parser.add_argument("--input", help="The directory, which contains all test images")
parser.add_argument("--output", help="Directory where the out... |
from __future__ import print_function
import sys
import tornadoredis
import tornado.httpserver
import tornado.web
import tornado.ioloop
import tornado.gen
import logging
import redis
PY3 = sys.version > '3'
if PY3:
xrange = range
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger('app')
POOL_A... |
import kerastuner
from autokeras.engine import tuner as tuner_module
class Hyperband(tuner_module.AutoTuner, kerastuner.Hyperband):
"""KerasTuner Hyperband with preprocessing layer tuning."""
pass
|
import requests
import json
import sys
from time import sleep
def get_vault_master(port):
r = requests.get('http://127.0.0.1:' + port + '/v1/catalog/service/vault')
if r.status_code == requests.codes.ok:
for node in json.loads(r.text):
if 'active' in node['ServiceTags']:
ret... |
import sys
import random
import time
class FlagChar:
def __init__(self, char, x, y, width, height):
self.char = char
self.x = x
self.y = y
self.width, self.height = width, height
random.seed(int(time.time()))
def move(self, fields):
"""
fields: (0,1,2,... |
import cv2
import numpy
path = r"C:\Python_program\Machine_learning\CNN_model\Allimage\B4\newbad\Base_4_BL_8_7.jpg"
img = cv2.imread(path)
img_to_yuv = cv2.cvtColor(img,cv2.COLOR_BGR2YUV)
img_to_yuv[:,:,0] = cv2.equalizeHist(img_to_yuv[:,:,0])
hist_equalization_result = cv2.cvtColor(img_to_yuv, cv2.COLOR_YUV2B... |
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import abc
import sys
import numpy as np
import pandas as pd
from sklearn import linear_model, preprocessing, cluster
import scipy.linalg as slin
import scipy.sparse.l... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# LICENSE:
# ---------------------------------------------------------------------------
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either v... |
import numpy as np
import nibabel as nib
import os
import sys
import pdb
import glob
def load_data(path):
data_dim, data, data_valid = load_ni(path)
data = data.reshape(data_dim)
data = np.moveaxis(data,1,2)
data = np.moveaxis(data,2,0)
data_dim = data.shape
data = data.reshape((data_dim[0]*da... |
#!/usr/bin/env python3
import argparse, os, sys, time, tqdm
import logging, warnings, json, gzip, pickle
# warning = logging.warning
import torch
from torch.utils import data
from torch.utils.data import Dataset, DataLoader
from collections import defaultdict, OrderedDict
import numpy as np
import epi_models
#import... |
from boost_site.util import htmlencode
# TODO: This is duplicated from other places, should only be set once?
news = pages.match_pages(['feed/news/*.qbk', 'feed/history/*.qbk|released'], 3)
emit('<div class="directory-item" id="important-downloads">\n');
emit('<h2>Downloads</h2>\n');
emit('<div id="downloads">\n');
... |
import numpy as np
import gym
from dm_control import suite
from code_slac.env.dm_control import DmControlEnvForPytorch
from mode_disent.env_wrappers.dmcontrol import MyDmControlEnvForPytorch
def test1():
domain_name = 'cheetah'
task_name = 'run'
env = suite.load(
domain_name=domain_name, task_na... |
import rpc, urllib
def tcpPortOpen(host, port):
"""
Opens a connection to a remote socket at address (host, port) and closes it to open the TCP port.
Parameter *host*:
Host address of the socket
Parameter *port*:
TCP port that will be opened
Return value:
This method returns a boolean which is true, if... |
#!/usr/bin/bash: DO: command not found
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
# fetch values from package.xml
setup_args = generate_distutils_setup(
packages=[
'msg_pkg'
#'msg_pkg2'
],
package_dir={'': 'src'},
)
setup(**setup_args)
|
import tensorflow as tf
class CnnEmbedding(tf.keras.layers.Layer):
def __init__(self, state_shape):
super().__init__()
self.conv0 = tf.keras.layers.Conv2D(filters=32, kernel_size=5, activation='relu', input_shape=state_shape)
self.pool0 = tf.keras.layers.MaxPooling2D((2, 2))
self.c... |
from .Account import Account
from .CallsRepository import CallsRepository
from .ContactsRepository import ContactsRepository
from .EventsRepository import EventsRepository
from .LeadsRepository import LeadsRepository
from .CompaniesRepository import CompaniesRepository
from .TasksRepository import TasksRepository
from ... |
#!/usr/bin/python3
"""
Shows status of extended sensor fusion
Run as module from project root:
python3 -m examples.show_esf_status
"""
import logging
import time
from ubxlib.server import GnssUBlox
from ubxlib.server_tty import GnssUBlox as GnssUBloxTTY # TTY direct backend
from ubxlib.ubx_esf_status import UbxEsf... |
import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
import tensorflow as tf
sess = tf.InteractiveSession()
x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
sess.run(tf.initialize_... |
from imageapp import db
class Image(db.Model):
# Define the properties mapped to database columns
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(100), nullable = False)
image_url = db.Column(db.String(200), nullable = False)
def __init__(self, title, image_url):
self.title = title
... |
import os
import copy
import base64
from http.server import BaseHTTPRequestHandler
from OpenSSL import crypto
from io import BytesIO
from socket import gethostname
import utils.config_handler
class HTTPRequest(BaseHTTPRequestHandler):
def __init__(self, request_text):
self.rfile = BytesIO(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.