content stringlengths 5 1.05M |
|---|
from PyQt6.QtCore import QRunnable, pyqtSlot, QObject, pyqtSignal
from numpy import ndarray
from src.hopfield_nn.hopfield import Hopfield
class WorkerSignals(QObject):
result = pyqtSignal(ndarray)
class Worker(QRunnable):
def __init__(self, network, image_data: ndarray, iterations: int = 100, threshold: f... |
#!/usr/bin/env python2.7
import psycopg2
DATABASE_NAME = "news"
def runquery(query):
"""
Takes a query as parameter, runs against the database
and returns the results
"""
db = psycopg2.connect(database=DATABASE_NAME)
cursor = db.cursor()
cursor.execute(query)
results = curso... |
from tkinter import *
from math import factorial, sqrt
root = Tk()
root.geometry('410x150')
def is_perfect_square(n):
return int(sqrt(n)) ** 2 == n
def callback():
n = int(entry.get())
if is_perfect_square(n):
result.config(text='{} is a perfect square {} = {} ^ {}'.format(n, n, int(sqrt(n)), 2))... |
"""Module implementing GORU Cell.
"""
import tensorflow as tf
import numpy as np
from tensorflow.python.framework import ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import control_flow_ops
from tensorflo... |
import torch
import logging.config
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
__version__ = "0.0.0"
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(asctime)-15s %(message)s'
},
... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021-2022, Geoffrey M. Poore
# All rights reserved.
#
# Licensed under the BSD 3-Clause License:
# http://opensource.org/licenses/BSD-3-Clause
#
from __future__ import annotations
import io
import os
import platform
import sys
from typing import Callable, Optional, TextIO
... |
import unittest
from pybind_class import PybindClass
from pybind_writer import PybindWriter
class TestPybindClass(unittest.TestCase):
def test_context_manager(self):
writer = PybindWriter()
with PybindClass(writer):
writer.write_line('test')
self.assertEqual(writer.t... |
import typing
from creme import base
__all__ = ['StackingClassifier']
class StackingClassifier(base.EnsembleMixin, base.Classifier):
"""Stacking for binary classification.
Parameters:
classifiers
meta_classifier
include_features: Indicates whether or not the original features shoul... |
import collections
import logging
import discord
log = logging.getLogger(__name__)
recently_proxied_messages = collections.deque(maxlen=1)
def new_proxied_message(oldmsg: discord.Message):
"""Add a proxy-causing message to the delete-log cleanup cache."""
global recently_proxied_messages
recently_proxi... |
from nexgddp.routes.api.v1.nexgddp_router import nexgddp_endpoints
|
#! /usr/bin/python3
# --*coding: utf-8*--
import requests
import bs4
import csv
# link to scrap: https://price.ua/catc839t14.html?price[min]=10000&price[max]=20000
def write_page_to_html(content):
with open('index.html', 'w') as file:
file.write(content)
def get_laptops_list(response) -> list:
s... |
import paho.mqtt.client as mqtt
import configparser
import logging
import json
import paho.mqtt.client as mqtt
class Messaging:
def __init__(self, config, subscription = None, on_message = None, clientId = None):
global on_connect
self.config = config
if (clientId):
self.clien... |
import logging
import ply.lex as lex
# # Set up a logging object
# logging.basicConfig(
# level=logging.DEBUG,
# filename="parselog.txt",
# filemode="w",
# format="%(filename)10s:%(lineno)4d:%(message)s"
# )
class LexToken(object):
class LexTokenError(Exception): pass
def __init__(self, debug... |
import mimetypes
import magic
import requests
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.management.base import BaseCommand
from contents.management.commands.crawler import get_url, get_item, get_page_url
from contents.models import Contents, Category, Actor, Director
class Comma... |
"""
Basic deployment script (for Gunicorn or similar tools)
"""
from newsic import create_app
from werkzeug.middleware.proxy_fix import ProxyFix
app = create_app()
# http://flask.pocoo.org/docs/1.0/deploying/wsgi-standalone/#proxy-setups
# fixes possible redirects to localhost:port
app.wsgi_app = ProxyFix(app.wsgi_ap... |
# -*- coding: utf-8 -*-
import scrapy
import microdata
import json
import re
from urllib.parse import urlparse
from claimreview.parser import ClaimReviewParser
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
class ClaimReviewSpider(CrawlSpider):
name = 'claimreview'
... |
# coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import attr
from utils.feishu.dt_enum import PayBuyType, PayPricePlanType, PayStatus
from utils.feishu.dt_help import to_json_decorator
@to_json_decorator
@attr.s
class PayOrder(object):
order_id = attr.ib(type=s... |
#!/usr/bin/env python3
"""
Central script to run the HTPC.
"""
import configparser
import datetime
import io
import json
import subprocess
import syslog
import requests
class HtpcManager(object):
"""
Class used to manage power on and power off times for the HTPC.
"""
def __init__(self, username, pas... |
# Copyright 2022 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# ------------------------------------------------------------------------------
# Copyright (c) 2019 Parallax Inc. -
# -
# Permission is hereby granted, free of charge, to any person obtaining ... |
ikan_bakar = 2567
orang = 190
ikanbakarperoraang =ikan_bakar/orang
print("selamat anda mendapatkan", ikanbakarperoraang) |
'''
Review function to evaluate if message conatains a valid namespace
'''
def HasValidNamespace(reviewer,message):
ns = message.NameSpace
if ns in reviewer.env._socketIONamespaces:
return True
else:
return False
|
def roundRobin(units, sets=None):
""" Generates a schedule of "fair" pairings from a list of units """
if len(units) % 2:
units.append(None)
count = len(units)
sets = sets or (count - 1)
half = count / 2
schedule = []
for turn in range(sets):
pairings = []
... |
from datetime import datetime
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.shortcuts import render
# Create your views here.
from common.access_decorators_mixins import sales_access_required
from .models import Listing
@login_required
@sales_access_required
def... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: alter_word_index.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.pro... |
import logging; logger = logging.getLogger("morse."+ __name__)
import roslib, rospy
from morse_helpers import adapters
from morse.core.blenderapi import mathutils
from morse.core.services import interruptible
from morse.core.exceptions import MorseServiceError
from morse_msgs.srv import PlaceIkTarget
from morse_msgs.... |
class BitQueryLookupWrapper(object):
def __init__(self, alias, column, bit):
self.table_alias = alias
self.column = column
self.bit = bit
def as_sql(self, qn, connection=None):
"""
Create the proper SQL fragment. This inserts something like
"(T0.flags & value) !=... |
import tensorflow as tf
from graphsaint.tensorflow_version.inits import glorot,zeros,trained,ones,xavier,uniform
from graphsaint.globals import *
F_ACT = {'I': lambda x:x,
'relu': tf.nn.relu,
'leaky_relu': tf.nn.leaky_relu}
# global unique layer ID dictionary for layer name assignment
_LAYER_UIDS =... |
# -*- coding: utf-8 -*-
"""Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2016, 2017, 2018, 2019, 2020 Caleb Bell
<Caleb.Andrew.Bell@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (t... |
"""Describe what tasks this Process accomplishes."""
# Order of imported packages should be:
# Standard libraries
from pathlib import Path
from shutil import copy2
# Third party libraries
from plumbum import TEE
# Resolwe
from resolwe.process import (
Process,
SchedulingClass,
Persistence,
Cmd,
St... |
"""Test converter classes."""
class Bar(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
def __call__(self, value, request, *args, **kwargs):
return 'bar'
|
from googletrans import Translator
detector = Translator(service_urls=['translate.googleapis.com'])
string = 'ODEIO'
# 'Porr Fmu eu te odeio, enfia essas aulas "híbridas" presenciais no seu c*...na moral EU NÃO POSSO IR PQ AGR MORO EM… https://t.co/42Cdld2fDX'
frase2 =detector.translate(string,dest='en')
dec_lan = d... |
from tkinter import *
import tkinter as tk
from tkinter import filedialog
from tkinter.filedialog import askopenfilename, asksaveasfilename
import re
import sys
import os.path
filename = "Output"
fileexists = False
root = tk.Tk()
def asmtoint(asm):
import re
asm_split = re.split(" |, |\(|\)", asm)
args... |
from os import getenv
from flask import Flask
import boto3
import botocore
import json
app = Flask(__name__)
@app.route('/')
def call_lambda():
try:
lambda_client = boto3.client('lambda',
endpoint_url="http://host.docker.internal:3001",
... |
"""
:author: Maikel Punie <maikel.punie@gmail.com>
"""
import velbus
COMMAND_CODE = 0xe4
class SetTemperatureMessage(velbus.Message):
"""
send by: VMB4RYLD
received by: VMB6IN
"""
def __init__(self, address=None):
velbus.Message.__init__(self)
self.temp_type = 0x00
self.t... |
"""Main module."""
import json
from collections import defaultdict
import numpy as np
import pandas as pd
from copy import deepcopy
from math import nan, isnan
from .constants import IMAGING_PARAMS
DIRECT_IMAGING_PARAMS = IMAGING_PARAMS - set(["NSliceTimes"])
def check_merging_operations(action_csv, raise_on_error=Fa... |
import sys
from functools import reduce
raw = sys.stdin.read()
rawpoints, rawfolds = raw.split('\n\n')
points = set((int(p.split(',')[0]), int(p.split(',')[1])) for p in rawpoints.split('\n'))
folds = [ (f.split('=')[0][-1], int(f.split('=')[1])) for f in rawfolds.strip().split('\n') ]
def applyFold(points, fold)... |
class DictObjectProxy:
def __init__(self, obj={}):
super().__setattr__("obj",obj)
def __getattr__(self, name):
if not name in super().__getattribute__("obj"):
raise AttributeError
return super().__getattribute__("obj")[name]
def __setattr__(self, key, value):
s... |
from peewee import *
#import sqlite3
baseD = SqliteDatabase('LIBRERIA.db')
class AUTOR(Model):
ID_AUTOR = PrimaryKeyField(null=False)
NOMBRE = TextField()
APELLIDO = TextField()
class Meta:
database = baseD # This model uses the "LIBRERIA.db" database.
def __str__(self):... |
# Copyright 2021 ZBW – Leibniz Information Centre for Economics
#
# 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 b... |
import pytest
import unittest
from sgnlp.models.ufd import (
UFDAdaptorDomainModel,
UFDAdaptorGlobalModel,
UFDCombineFeaturesMapModel,
UFDClassifierModel,
UFDModelBuilder,
UFDModel
)
class TestUFDModelBuilderTestCase(unittest.TestCase):
def setUp(self) -> None:
self.model_map = {
... |
import unittest
import sys
import os
sys.path.append('../')
import torch
import torch.nn as nn
from torchlib import models as md
class TestModel( unittest.TestCase ):
def test_model_resnet( self ):
num_channels=1
num_classes=10
imsize=64
net = md.resnet18( False, num_class... |
import itertools
class Solution(object):
def matrixReshape(self, nums, r, c):
l = len(nums) * len(nums[0])
if l != r * c:
return nums
it = itertools.chain(*nums)
return [list(itertools.islice(it, 0, c)) for i in xrange(0, l, c)]
|
# This is just a simple recursion implementation of the problem.
def maximum_profit(price, start, end):
if end <= start:
return 0
profit = 0
for i in range(start, end):
for j in range(i + 1, end + 1):
if price[j] > price[i]:
curr_profit = price[j] - price[i] + ... |
# 1. new_cut_dataset, num_train_epochs, deixar a correr com dataset grande, lstm com dw=3
# 1. deixar a correr com dataset grande, lstm só com dw=1
# 1. deixar a correr com dataset grande, lstm com média ponderada
import random
import torch
import numpy as np
#from datetime import timedelta
#import pandas as pd
#from... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-02-16 00:50
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('grapher_admin', '0031_auto_20180216_0021'),
]
operations = [
migrations.RemoveField(
... |
import datetime
import unittest
from airflow.models import DAG, DagRun, TaskInstance as TI
from airflow.operators.dummy import DummyOperator
from airflow.utils import timezone
from airflow.utils.session import create_session
from airflow.utils.state import State
from gcp_airflow_foundations.operators.branch.branch_on... |
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
import matplotlib.pyplot as plt
import os
from scipy.interpolate import interp1d
from mpl_toolkits.basemap import Basemap
periods = np.array([8,10,12,14,16,18,20,22,24,26,28,30,32,35,40,45,50])
depth = np.array([0,3,10,15,20,30,40,60,80,100,120... |
# -*- coding: utf-8 -*-
"""
Demonstrate how to synchronize 2 or more MFLI
instruments or 2 or more UHFLI instruments using the MDS capability of LabOne.
It also measures the temporal response of demodulator filters of both
both instruments using the Data Acquisition (DAQ) Module.
Copyright 2008-2018 Zurich Instruments... |
from ..util import slice_
def scopy(N, SX, INCX, SY, INCY):
"""Copies a vector, x, to a vector, y.
Parameters
----------
N : int
Number of elements in input vectors
SX : numpy.ndarray
A single precision real array, dimension (1 + (`N` - 1)*abs(`INCX`))
INCX : int
Stora... |
from BatteryConditionChecks import isBatteryOk
if __name__ == '__main__':
assert(isBatteryOk(25, 70, 0.7) == True)
assert(isBatteryOk(45, 80, 0.8) == True)
assert(isBatteryOk(50 , 95, 0.9) == False)
assert(isBatteryOk(23 , 10, 0.9) == False)
assert(isBat... |
'''
################################################################################################################
Manuscript Title: The evaluation of tools used to predict the impact of missense variants is hindered by two types of circularity
#########################################################################... |
import sys
import os
import logging
from maya import cmds
from jiminy.vendor.Qt import QtCore
from jiminy import api as jiminy
from . import pipeline
self = sys.modules[__name__]
self._menu = "jiminymaya"
log = logging.getLogger(__name__)
global SILO
def install():
def deferred():
cmds.menuItem(
... |
#!/usr/bin/env python3
import argparse
import json
import os
import random
import timeit
from glob import glob
import numpy as np
import _init_path
from spacenet7_model.utils import get_image_paths, get_aoi_from_path
def parse_args():
"""[summary]
Returns:
[type]: [description]
"""
parser ... |
# ===============================================================================
# Copyright 2013 Jake Ross
#
# 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/licens... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__a... |
"""
This script handles the loading of the cleaned metadata into the mongodb.
Data from scraping server is compressed.
server: scraping server
workdir: data/corpus
command: tar -czvf KCP_<list_of_corpus_ids_to_compress_separated_by_underscore>.tar.gz
Send compressed data to gateway:
server: scraping server
workdir: d... |
# coding: utf-8
#
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
# 바이너리를 저장하고 불러온다
# TODO: 클래스 분리할 것
import os
import pickle
import secrets
from lib.log_gongik import Logger
from lib.file_property import FileProp
from lib.file_detect import BackupFileDetector # 파일 탐지
from lib.utils import (
get_today_date_formated,
extract_dir
)
class BackupRestore(object):
def __ini... |
import pytest
from chapter10 import C10, message
from fixtures import SAMPLE
@pytest.fixture
def packet():
for packet in C10(SAMPLE):
if isinstance(packet, message.MessageF0):
return packet
@pytest.fixture
def msg(packet):
return next(packet)
def test_csdw(packet):
assert packet.... |
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
import requests
import json
def count_user(repo):
r = requests.get('https://api.github.com/repos/{}'.format(repo))
if r.ok:
repoItem = json.loads(r.text or r.content)
return repoItem['subscribers_count'], repoI... |
import io
import os
import sys
import unittest
class Test_TestProgram(unittest.TestCase):
def test_discovery_from_dotted_path(self):
loader = unittest.TestLoader()
tests = [self]
expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__))
self.wasRun = False
... |
# Generated by Django 2.1.5 on 2019-01-15 16:11
import django.contrib.gis.db.models.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('property', '0011_property_city'),
]
operations = [
migrations.RemoveField(
model_name='proper... |
"""Module containing models used for server responses"""
class Response:
"""Response indicating successful operation"""
def __init__(self, text, time):
self.text = text
self.time = time
class ErrorResponse:
"""Response indicating failed operation"""
def __init__(self, message):
... |
from ptrlib import ror
hashval = [
0x13e0ff2c,
0xB7D26563,
0x5B9E4069,
0x98AE69CB,
0x96AE69D0,
0x998802F1,
0x7F3EECA7
]
def calc_hash(name, key):
hashval = 0
for c in name:
hashval = ((ord(c) | 0x20) + ror(hashval, 8, bits=32)) ^ key
return hashval
with open("apilist_k... |
# Copyright 2012 Pedro Navarro Perez
# Copyright 2013 Cloudbase Solutions Srl
# 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... |
from brownie import Wei
from helpers.network import network_manager
from helpers.time_utils import days, hours, minutes
# Setts that are not tendable will automatically be skipped
# Lines can be commented out here to skip Setts
setts_to_skip = {
"eth": {
"harvest": [
"native.uniBadgerWbtc",
... |
import unittest
from datetime import datetime, timedelta
from rowboat.util.input import parse_duration
class TestRuleMatcher(unittest.TestCase):
def test_basic_durations(self):
dt = parse_duration('1w2d3h4m5s')
self.assertTrue(dt < (datetime.utcnow() + timedelta(days=10)))
self.assertTru... |
from movies.views import MovieViewSet
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'movies', MovieViewSet)
urlpatterns = router.urls
|
import sys
import os
from mlad.core.default.config import service_config
from mlad.cli import config as config_core
def is_debug_mode():
if '-d' in sys.argv or '--debug' in sys.argv or os.environ.get(
'MLAD_DEBUG', service_config['mlad']['debug']):
return True
return False
|
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... |
checkout_session_signature = 't=1591264652,v1=1f0d3e035d8de956396b1d91727267fbbf483253e7702e46357b4d2bfa078ba4,v0=20d76342f4704d49f8f89db03acff7cf04afa48ca70a22d608b4649b332c1f51'
checkout_session_body = b'{\n "id": "evt_1GqFpHAlCFm536g8NYSLoccF",\n "object": "event",\n "api_version": "2019-05-16",\n "created": 159... |
from django.contrib import admin
from django.urls import path
from core import views
urlpatterns = [
path('', views.index, name='index'),# name é opcional
#path('',views.marcarHorario)
] |
import click
import numpy as np
import re
import tifffile
import xtiff
from pathlib import Path
from .data import anndata_cmd, csv_cmd, fcs_cmd
from .graphs import graphs_cmd
from ..._cli.utils import OrderedClickGroup
from ... import io
@click.group(
name="export",
cls=OrderedClickGroup,
help="Export d... |
from vrtManager.connection import wvmConnect
from xml.etree import ElementTree
class wvmNWFilters(wvmConnect):
def get_nwfilter_info(self, name):
nwfilter = self.get_nwfilter(name)
xml = nwfilter.XMLDesc(0)
uuid = nwfilter.UUIDString()
return {'name': name, 'uuid': uuid, 'xml': xml... |
#
# This file is part of LiteX.
#
# Copyright (c) 2021 Florent Kermarrec <florent@enjoy-digital.fr>
# SPDX-License-Identifier: BSD-2-Clause
import os
from litex.build.generic_platform import GenericPlatform
from litex.build.quicklogic import common, symbiflow
# QuickLogicPlatform ------------------------------------... |
from __future__ import annotations
import logging
import typing
if typing.TYPE_CHECKING:
from .types import (
UserDatabaseConfig, DatabaseConfig, DriverWrapper,
DriverPool, DriverConnection,
)
class DatabaseTransaction(object):
"""
A wrapper around a transaction for your database.
... |
#coding=utf8
"""
Created on Sun Nov 17 16:16:09 2019
@author: Neal LONG
"""
from nltk.stem import WordNetLemmatizer
import nltk
from nltk.corpus import wordnet
def get_wordnet_pos(treebank_tag):
"""
Translate the complext NLTK postag to simplied
wordnet definitions of postag
"""
if... |
import socket
import os
import sys
TARGET_IP = "127.0.0.1"
TARGET_PORT = 5005
BLOCK_SIZE = 1024
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
fileName = "picture.png"
fileSize = os.stat(fileName).st_size
fp = open(fileName, "rb")
payload = fp.read()
sent = 0
for i in range((len(payload)/BLOCK_SIZE) + 1):
... |
from pprint import pprint
import json
class JsonReader:
def heddepts():
f = open('HigherEdDepartments.json')
depts = json.load(f)
deptnames = set()
for item in depts:
printme = item["title"]
deptnames.add(printme)
pprint(deptnames)
pass
JsonReade... |
import unittest
import pandas as pd
from study.ml.trees import NaiveNumericDecisionTree
from test_classifiers import ClassifierBaseTest
class TestNonNumericDecisionTree(ClassifierBaseTest):
data2_df = pd.DataFrame({'one': [1., 2., 3., 4., 5., 6.],
'two': [True, True, False, False, F... |
import json
import logging
import subprocess
import warnings
from pathlib import Path
from typing import Dict, List, NamedTuple, Optional, Union
from contributors_txt.const import (
DEFAULT_TEAM_ROLE,
GIT_SHORTLOG,
NO_SHOW_MAIL,
NO_SHOW_NAME,
)
class Alias(NamedTuple):
mails: List[str]
author... |
from __future__ import print_function
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.view import view_config, view_defaults
from pyramid.response import Response
from github import Github, GithubException
import os
import shutil
from subprocess import call
import log... |
import pandas as pd
from sentimentanalyser import preprocess
## from preprocess import PreProcess
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.externals import joblib
from sklearn import svm
from sklearn.naive_bayes import MultinomialNB
... |
import abc
import re
import tempfile
import traceback
from typing import Tuple, Callable, Union, List, Optional
import kerassurgeon
import numpy as np
import tensorflow as tf
from keras import backend as K
from keras import models, layers
class BasePruning:
_FUZZ_EPSILON = 1e-5
def __init__(self,
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 24 16:24:44 2019
@author: usingh
"""
import pytest
from pyrpipe import assembly
from pyrpipe import pyrpipe_utils as pu
from testingEnvironment import testSpecs
import os
testVars=testSpecs()
def test_assembly():
#create assemble object
ao... |
def PlotLossesKeras(**kwargs):
"""PlotLosses callback for Keras (as a standalone library, not a TensorFlow module).
Args:
**kwargs: key-arguments which are passed to PlotLosses
Notes:
Requires keras to be installed.
"""
from .keras import PlotLossesCallback
return PlotL... |
# Generated by Django 3.1.13 on 2021-10-09 13:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0003_profile'),
]
operations = [
migrations.AlterField(
model_name='user',
name='email',
field... |
from sqlalchemy import create_engine
import tushare as ts
stock_basics = ts.get_stock_basics() #所有股票列表 stock_basic
print(stock_basics) |
import requests, json, time, pickle, argparse
from os import path
# Authentication function
def authenticate(bridge_ip):
auth_req = requests.post("http://"+bridge_ip + "/api", json={"devicetype":"hue_exit_code#linux"})
auth_res = auth_req.json()
if len(auth_res) == 1:
auth_res = auth_res[0]
... |
from flask_login import LoginManager
login = LoginManager()
def login_initializing(app):
login.init_app(app)
login.login_view = 'blue.login'
|
from ipsframework import Component
class Driver(Component):
def step(self, timestamp=0.0):
worker_comp = self.services.get_port('WORKER')
self.services.call(worker_comp, 'step', 0.0)
|
# Copyright (c) OpenMMLab. All rights reserved.
"""Get test image metas on a specific dataset.
Here is an example to run this script.
Example:
python tools/misc/get_image_metas.py ${CONFIG} \
--out ${OUTPUT FILE NAME}
"""
import argparse
import csv
import os.path as osp
from multiprocessing import Pool
impor... |
# * Mathematical Algorithm - Lucky number
|
# from tkinter import *
# from tkinter import ttk
# ventana = Tk()
print("Hola")
# window=Tk()
# window.title("Python")
# window.geometry("600x500")
# window.mainloop()
#--------------- example2---------------
# from tkinter import *
# tkinter.use("Agg")
# from tkinter.ttk import *
# root=Tk()
# label=Label(root, tex... |
__author__ = 'tinglev@kth.se'
import unittest
from test import mock_test_data
from modules.steps.resource_policy_checker import ResourcePolicyChecker
from modules.util import data_defs, exceptions
class TestResourcePolicyChecker(unittest.TestCase):
def test_bad_resource_policy(self):
step = ResourcePolic... |
#!/usr/bin/env python
#coding: utf-8
"""
LeetCode: https://leetcode.com/problems/clone-graph/
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use '#' as a separator for each node, and ','... |
import nltk
import sys , os
FILE_MATCHES = 1
SENTENCE_MATCHES = 1
def main():
# Check command-line arguments
if len(sys.argv) != 2:
sys.exit("Usage: python questions.py corpus")
# Calculate IDF values across files
files = load_files(sys.argv[1])
file_words = {
filename: tokenize... |
"""
("([a-z0-9!#$%&'*+\/=?^_'{|}~-]+(?:\.[a-z0-
9!#$%&'*+\/=?^_'"
"{|}~-]+)*(@|\sat\s)(?:[a-z0-9](?:[a-z0-9-
]*[a-z0-9])?(\.|"
"\sdot\s))+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)")
"""
import urllib.request as ur
import sys,re
url = sys.argv[1]
try:
page_code = ur.urlopen(url).read()
print(page_code.decode())
compiled = r... |
import csv
# with open('Depth Data/KinectDataMinMax.csv', 'r', newline='') as file:
# reader = csv.reader(file)
# fileWriter = open("Depth Data/KinectDataMinMaxWallConfig.csv", "w")
# count = 0
# for row in reader:
# target = row.pop(0) #Remove the target
# if target == "Wall":
# ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.