filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_31544 | import os
import copy
import time
import asyncio
import logging
from datetime import datetime
from functools import partial
from operator import itemgetter
from collections import defaultdict
from binascii import hexlify, unhexlify
from typing import Dict, Tuple, Type, Iterable, List, Optional, DefaultDict, NamedTuple
... |
the-stack_106_31545 | from PIL import Image, ImageDraw, ImageFont
import numpy as np
import datetime
def get_combined_image(black_image, red_image):
result = np.full((black_image.height, black_image.width, 3), 255, 'uint8')
black = np.array(black_image)
red = np.array(red_image)
blacks = (black == 0)
reds = (red == 0)
... |
the-stack_106_31547 | from Entity import *
from collections import deque
class Explosion(Entity):
pool = deque()
@staticmethod
def spawn(anim, x, y):
asset = Explosion() if len(Explosion.pool) == 0 or Explosion.pool[0].active else Explosion.pool.popleft()
asset.anim = anim
asset.x = x
asset.y = y
asset.looped = F... |
the-stack_106_31548 | """Tests of theoretical results."""
# pylint: disable=redefined-outer-name,cyclic-import
import pytest
import numpy as np
from pathcensus import PathCensus
from tests.utils import get_largest_component
@pytest.fixture(scope="session")
def random_graph_connected(random_graph):
G, _ = random_graph
G = get_large... |
the-stack_106_31549 | # Link: https://leetcode.com/problems/longest-substring-without-repeating-characters/
"""
Problem statement:
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Solution:
Approach... |
the-stack_106_31551 | """
.B.lender .V.ision .P.roject file operation
Gets properties for all skies in a .blend file. Stores properties in a list
of dictionaries (one dict for each sky (group) in the file), and saves that
list in a pickle (.pik) file with the same name as the .blend file.
These .pik files are loaded by the bvpLibrary cl... |
the-stack_106_31552 | """
$url lrt.lt
$type live
"""
import logging
import re
from streamlink.plugin import Plugin, pluginmatcher
from streamlink.stream.hls import HLSStream
log = logging.getLogger(__name__)
@pluginmatcher(re.compile(
r"https?://(?:www\.)?lrt\.lt/mediateka/tiesiogiai/"
))
class LRT(Plugin):
_video_id_re = re.co... |
the-stack_106_31553 | # ------------------------------------------
# --- Author: Bing
# --- Version: 1.0
# --- Description: This python script will update AWS Thing Shadow for a Device/Thing
# ------------------------------------------
# Import package
import paho.mqtt.client as mqtt
import ssl, time, sys
# =====================... |
the-stack_106_31557 | #!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.anjos@idiap.ch>
# Mon 16 Apr 08:18:08 2012 CEST
bob_packages = ['bob.core']
from setuptools import setup, find_packages, dist
dist.Distribution(dict(setup_requires=['bob.extension', 'bob.blitz'] + bob_packages))
from bob.extension.utils import... |
the-stack_106_31558 | """tests rio_tiler.landsat8"""
import os
import pytest
from mock import patch
from rasterio.crs import CRS
from rio_toa import toa_utils
from rio_tiler import landsat8
from rio_tiler.errors import (
TileOutsideBounds,
InvalidBandName,
NoOverviewWarning,
InvalidLandsatSceneId,
)
LANDSAT_SCENE_C1 = "... |
the-stack_106_31561 | # This file is part of the kambpf project (https://github.com/zdule/part_ii_project).
# It is file is offered under two licenses GPLv2 and Apache License Version 2.
# For more information see the LICENSE file at the root of the project.
#
# Copyright 2020 Dusan Zivanovic
import pandas as pd
import sys
import m... |
the-stack_106_31562 | import os
import glob
import torch
import random
import numpy as np
from torch.utils.data import Dataset, DataLoader
from utils.utils import read_wav_np, read_flac_np
def create_dataloader(hp, args, train):
dataset = MelFromDisk(hp, args, train)
if train:
return DataLoader(dataset=dataset, batch_siz... |
the-stack_106_31563 | import datetime
from django import forms
from django.test import TestCase
from django.utils.translation import activate
from institution.models import Institution
from users.forms import CustomUserChangeForm
from users.forms import CustomUserCreationForm
from users.forms import ProfileUpdateForm
from users.forms impo... |
the-stack_106_31564 | # Copyright (c) 2018 PaddlePaddle 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 app... |
the-stack_106_31567 | #!/usr/bin/env python
import re,sys,os,copy
from collections import defaultdict as ddict
class f90depinfo(object):
def __init__(self):
self.uses = ddict()
self.provides = ddict()
def getline( liter ):
line = ""
while len(line.strip()) < 1:
line = liter.next().upper()
line... |
the-stack_106_31568 | """All constants related to the ZHA component."""
from __future__ import annotations
import enum
import logging
import bellows.zigbee.application
import voluptuous as vol
from zigpy.config import CONF_DEVICE_PATH # noqa: F401 # pylint: disable=unused-import
import zigpy_cc.zigbee.application
import zigpy_deconz.zigb... |
the-stack_106_31569 | import rospy
import sys
import json
from interactivespaces_msgs.msg import GenericMessage
"""
This script may be used to send director message.
You just need to supply a json file with director message
in it.
"""
if len(sys.argv) <= 1:
print("Sorry - you need to supply path to json file for emission")
print(... |
the-stack_106_31571 | # -*- coding: utf-8 -*-
"""Public section, including homepage and signup."""
from flask import Blueprint, flash, redirect, render_template, request, url_for
from flask_login import login_required, login_user, logout_user
from tour.extensions import api, login_manager
from tour.public.forms import LoginForm
from tour.... |
the-stack_106_31573 | '''
strates how to use `CNN` model from
`speechemotionrecognition` package
'''
from keras.utils import np_utils
import pulsectl
import serial
import time
import os
import sys
import collections
import webrtcvad
import signal
import subprocess
import socket as sk
import numpy as np
from common import e... |
the-stack_106_31576 | from matplotlib import pyplot as plt
x = []
y = []
for i in range(100):
x.append(i)
y.append(i)
# Mention x and y limits to define their range
plt.xlim(0, 100)
plt.ylim(0, 100)
# Ploting graph
plt.plot(x, y, color = 'green')
plt.pause(0.01)
plt.show()
|
the-stack_106_31578 |
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.preprocessing import LabelEncoder
from pyriemann.classification import MDM
from pyriemann.estimation import ERPCovariances
from braininvaders2012.dataset import BrainInvaders2012
from tqdm impor... |
the-stack_106_31579 | """
Utility functions used across scripts.
"""
__author__ = "Shyue Ping Ong, Dan Gunter"
__copyright__ = "Copyright 2012-2014, The Materials Project"
__version__ = "1.1"
__maintainer__ = "Dan Gunter"
__email__ = "dkgunter@lbl.gov"
__date__ = "2012-12-01"
## Imports
import bson
import datetime
import json
import loggi... |
the-stack_106_31581 | import caffe2onnx.src.c2oObject as Node
##--------------------------------------------------Reshape---------------------------------------------------------##
# Calculate the output dimension
def getReshapeOutShape(layer,input_shape):
try:
# Get the layer's reshape param
re_shape = layer.reshape_par... |
the-stack_106_31582 | '''
MIT License
Copyright (c) 2019 Shunsuke Saito, Zeng Huang, and Ryota Natsume
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 right... |
the-stack_106_31585 | #!/usr/bin/env python3
import pandas as pd
import argparse
import plotly.express as px
import plotly.graph_objects as go
import matplotlib.pyplot as plt
import seaborn as sns
import datetime
class MineRegression:
def __init__(self,
system_information=None,
save_csv=False,
... |
the-stack_106_31586 | import multiprocessing as mp
import torch
from torch.nn.parallel import DistributedDataParallel as DDP
# from torch.nn.parallel import DistributedDataParallelCPU as DDPC # Deprecated
from rlpyt.utils.quick_args import save__init__args
from rlpyt.utils.collections import namedarraytuple
from rlpyt.utils.synchronize im... |
the-stack_106_31587 | import numpy as np
class Geom:
"""
A class for operations regarding simulation geometry and configuration.
Attributes
----------
method : string, either 'random' or 'file'
Method of generating initial state.
**kwargs : See Below
Keyword Arguments
-----------------... |
the-stack_106_31590 | """Integration with the Rachio Iro sprinkler system controller."""
from abc import abstractmethod
from datetime import timedelta
import logging
from homeassistant.components.switch import SwitchDevice
from homeassistant.helpers.dispatcher import dispatcher_connect
from . import (
CONF_MANUAL_RUN_MINS,
DOMAIN ... |
the-stack_106_31592 | from dataclasses import dataclass, field
from typing import Any, Dict, Optional
import torch
from toolbox.callbacks.callback_base import CallBack
from toolbox.utils.progress_bar import ProgressBar
@dataclass
class ProgressBarCB(CallBack):
progress_bar_size: int
_progress_bar: Optional[ProgressBar] = field(i... |
the-stack_106_31593 | import pytest
import json
from web3 import EthereumTesterProvider, Web3
from eth_tester import EthereumTester, PyEVMBackend
import eth_tester.backends.pyevm.main as py_evm_main
from contracts.style_art import StyleArt
py_evm_main.GENESIS_GAS_LIMIT = 10000000
PRIVATE_KEY = "0x00000000000000000000000000000000000000000... |
the-stack_106_31594 | import argparse
import os
import os.path as osp
from collections import defaultdict
import mmcv
from tqdm import tqdm
CLASSES = [
'pedestrian', 'rider', 'car', 'bus', 'truck', 'bicycle', 'motorcycle',
'train'
]
USELESS = ['traffic light', 'traffic sign']
IGNORES = ['trailer', 'other person', 'other vehicle']
... |
the-stack_106_31595 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# =========================================================================== #
# Project : Visualate #
# Version : 0.1.0 #
# File : canvas.py ... |
the-stack_106_31596 |
import warnings
import logging
logging.basicConfig(level=logging.INFO)
def send_warnings_to_log(message, category, filename, lineno, file=None):
logging.warning(
'%s:%s: %s:%s' %
(filename, lineno, category.__name__, message))
old_showwarning = warnings.showwarning
warnings.showwarning = send_w... |
the-stack_106_31597 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 14 02:03:52 2017
@author: Frank
In:
In/*.*
Out:
In/*.JPEG
"""
import os
import init as config
from argparse import ArgumentParser
import cv2
from PIL import Image
#from gooey import Gooey
def gif2png(oldname,newname,ext='png'):
im = Image.open(oldname)
i... |
the-stack_106_31601 |
import numpy as np
import copy
import fns
from sklearn.cross_decomposition import PLSRegression
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import scale
from . import PLSRsave
from . import PLSRwavel... |
the-stack_106_31602 | # coding: utf-8
from configs.stock import stock_list
from engine.base_engine import BaseEngine
from helpers.quotes import get_realtime_quotes, get_realtime_index, get_realtime_class_index
from gevent import monkey
monkey.patch_all()
class DefaultQuotationEngine(BaseEngine):
"""行情推送引擎"""
EventType = 'quotation'... |
the-stack_106_31604 | # Event: LCCS Python Fundamental Skills Workshop
# Date: Dec 2018
# Author: Joe English, PDST
# eMail: computerscience@pdst.ie
# Purpose: A program to find the maximum of 3 values
# A function to find the largest of 3 numbers
def maxOf3(x, y, z):
if (x > y) and (x > z):
return x
elif (y > x... |
the-stack_106_31605 | """
===================================================================
Compute MNE inverse solution on evoked data in a mixed source space
===================================================================
Create a mixed source space and compute MNE inverse solution on an
evoked dataset.
"""
# Author: Annalisa Pasca... |
the-stack_106_31607 | import json
import re
from .utils import get_page
from pyquery import PyQuery as pq
class ProxyMetaclass(type):
def __new__(cls, name, bases, attrs):
count = 0
attrs['__CrawlFunc__'] = []
for k, v in attrs.items():
if 'crawl_' in k:
attrs['__CrawlFunc__'].append... |
the-stack_106_31608 | # pylint: disable=too-many-lines
import os
import errno
import functools
import hashlib
import operator
import posixpath
import warnings
from datetime import timedelta
from itertools import islice, chain
from jinja2 import Undefined, is_undefined
from jinja2.utils import LRUCache
from jinja2.exceptions import Undefin... |
the-stack_106_31611 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012, Red Hat, 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
#
... |
the-stack_106_31612 | import math
from datetime import datetime, timedelta
from typing import List, Optional, Tuple
from fastapi.encoders import jsonable_encoder
from dispatch.config import ANNUAL_COST_EMPLOYEE, BUSINESS_HOURS_YEAR
from dispatch.database import SessionLocal
from dispatch.incident_priority import service as incident_priori... |
the-stack_106_31613 | # Copyright The IETF Trust 2012-2019, All Rights Reserved
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import io
import os
from django import forms
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpRespons... |
the-stack_106_31614 | import operator
import functools
number = str(open("number.txt", "r").read())
numbers = []
for i in range(0, len(number)-13):
n = [int(i) for i in number[i:i+13]]
numbers.append(functools.reduce(operator.mul, n, 1))
print(max(numbers))
|
the-stack_106_31616 | #!/usr/bin/env python
#
# Electrum - lightweight Futurocoin client
# Copyright (C) 2011 thomasv@gitorious
#
# 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 wi... |
the-stack_106_31618 | import json
import random
def dropentities(category, num):
with open("../data/flatontology.json", 'r') as f:
flatontology = json.load(f)
categorypath = flatontology[category]["fullpath"]
with open("../data/" + categorypath + "fileindex.json", 'r') as f:
fileindex = json.load(f)
for k... |
the-stack_106_31619 | import os
import datetime
import json
import logging
from unittest import TestCase
from contextlib import contextmanager
os.environ['REDASH_REDIS_URL'] = os.environ.get('REDASH_REDIS_URL', "redis://localhost:6379/0").replace("/0", "/5")
# Use different url for Celery to avoid DB being cleaned up:
os.environ['REDASH_CE... |
the-stack_106_31620 | import numpy as np
class RingBuffer(object):
def __init__(self, maxlen, shape, dtype='float32'):
self.maxlen = maxlen
self.start = 0
self.length = 0
self.data = np.zeros((maxlen,) + shape).astype(dtype)
def __len__(self):
return self.length
def __getitem__(self, i... |
the-stack_106_31622 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
import torch.nn.functional as F
from pytext.config import ConfigBase
from pytext.config.component import Component, ComponentType
from pytext.utils import loss as loss_utils, precision
from pytext.utils.cuda impo... |
the-stack_106_31626 | #!/usr/bin/env python
import numpy
import scipy.stats
#The Savage-Dickey estimator computation is based on the implementation by Äijö et al. (2016) available at https://github.com/tare/LuxGLM (MIT lisence)
def calculate_savagedickey(prior1_mean,prior1_cov,prior2_mean,prior2_cov,samples1,samples2):
samples1_mean ... |
the-stack_106_31628 | """
Copyright 2020 The OneFlow 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 applicable law or agr... |
the-stack_106_31629 | #!/usr/bin/env python
import doctest
import logging
import math as m
import re
from networkx import DiGraph
import copy
import itertools as it
def load_input():
data = list()
with open('input.txt') as fd:
for line in fd:
value = int(line.strip())
data.append(value)
return ... |
the-stack_106_31630 | import tensorflow as tf
import sys
sys.path.append('../')
print(sys.path)
from algos import construct_classifier
from utils.misc import increment_path
from toyexamples.synthetic_data import SquareBlock, ToyWorld
n_epochs = 10
hparams_list = [
{"classifier_type": "paritynn",
"dpe_scalar": 10**i,
"layersiz... |
the-stack_106_31633 | # // There are A cities numbered from 1 to A. You have already visited M cities, the
# // indices of which are given in an array B of M integers.
# // If a city with index i is visited, you can visit either the city with index i-1
# // (i >= 2) or the city with index i+1 (i < A) if they are not already visited.
#... |
the-stack_106_31637 | # Copyright (c) 2003-2014 CORE Security Technologies
#
# This software is provided under under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# Author: Alberto Solino
#
# Description:
# [MS-RRP] Interface implementation
#
# Best way to learn... |
the-stack_106_31639 | #!/usr/bin/env python3
import googlemaps
import json
#gmaps = googlemaps.Client(key="AIzaSyBm3Vv7k-8DiE_uBvptymYypVtYlGnqF8g")
f = open("hospitals_src.json", "r", encoding = "UTF-8")
hospitals = json.load(f)
f.close()
results = []
result = bytes()
size = 0
for h in hospitals:
#result = gmaps.geocode(h["機構地址"])
#pri... |
the-stack_106_31640 | from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.firefox.launch()
page = browser.new_page()
listalinks = []
# Este range é setado manualmente, significa a quantidade de páginas/imagens que serão baixadas.
# O processo é um pouco lento, então os downloa... |
the-stack_106_31642 | import requests
from PIL import Image,ImageFilter
from PIL import ImageFilter
from PIL import ImageDraw
h = 700
w = 700
name = input("What Name? ")
color = input("What Color Should the back ground be? ")
busthead = input("Bust OR head: ")
r = requests.get(f"https://api.mojang.com/users/profiles/minecraft/{name}")
rd... |
the-stack_106_31643 | '''RegNet in PyTorch.
Paper: "Designing Network Design Spaces".
Reference: https://github.com/keras-team/keras-applications/blob/master/keras_applications/efficientnet.py
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class BlockX(nn.Module):
def __init__(self, w_in, w_out, stride, bottl... |
the-stack_106_31644 | #!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the listtransactions API."""
from decimal import Decimal
from io import BytesIO
from test_framewo... |
the-stack_106_31647 | # Copyright 2011 OpenStack Foundation
# Copyright 2012 Justin Santa Barbara
# 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/l... |
the-stack_106_31648 | # -*- coding: utf-8 -*-
#
# Configuration file for Sphinx builds for the zhmcclient project.
#
# Originally created by sphinx-quickstart, but then manually maintained.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in ... |
the-stack_106_31653 | import simplejson as json
from prettyparse import create_parser
from komprenu.model import Model
usage = '''
Train a new grammar model on the input json data
:data_json str
Data file to load from
:model_json str
Model file to write to
:--latent-len -l int 100
Number ... |
the-stack_106_31654 | """A Link represents the predicate-object portion of a triple."""
import abc
import uuid
from typing import Any, Dict, Iterable, List, Optional, Tuple, Type, Union
from pydantic import validator
from rdflib import BNode, Graph, Literal, Namespace, RDF, URIRef, XSD
from altimeter.core.base_model import BaseImmutableMo... |
the-stack_106_31655 | #!/usr/bin/env python3.6
from os import path
from sklearn import preprocessing
import pandas as pd
import numpy as np
import json
import argparse
try:
import _pickle as pickle
except:
import pickle
import os
import librosa
import collections
from bbn_primitives.time_series import *
from d3m_metadata.container... |
the-stack_106_31656 | from statsmodels.compat.python import iteritems
from statsmodels.compat.pandas import assert_series_equal
from io import StringIO
import warnings
from statsmodels.formula.api import ols
from statsmodels.formula.formulatools import make_hypotheses_matrices
from statsmodels.tools import add_constant
from statsmodels.da... |
the-stack_106_31657 | from collections import defaultdict, deque
class IntComputer:
class Halt(Exception):
pass
def __init__(self, mem, inputs=()):
self.pc = 0
self.rb = 0
self.mem = defaultdict(int, ((i, v) for i, v in enumerate(mem)))
self.input = deque(inputs)
self.output = deque... |
the-stack_106_31658 | #-------------------------------------------------------------------------------
# Name: Subscription Counter
# Purpose: Calculate the number of subscriptions made each month.
#
# Author: Naseela Amboorallee
#
# Created: 13/02/2018
# Copyright: (c) Naseela Amboorallee 2018
# Licence: <your licence>
#----... |
the-stack_106_31659 | import re
valid_re = re.compile('^[\w-]+$')
def validate_feed_id(feed_id):
'''
Validates the input is in the format of user:1
:param feed_id: a feed such as user:1
Raises ValueError if the format doesnt match
'''
feed_id = str(feed_id)
if len(feed_id.split(':')) != 2:
msg = 'Inv... |
the-stack_106_31660 | #!/usr/bin/env python3
"""Acquisition script for HP4194A Impedance Analyzer"""
import argparse
import configparser
import datetime
import os
import subprocess
import sys
import numpy
import pylab
import pyvisa
import scipy.io as scio
import matplotlib.pyplot as pyplot
DEBUG = False
FILE_EXT = '.mat'
def main(filen... |
the-stack_106_31661 | import threading
import os
import time
import codecs
import requests
import json
from ecdsa import SigningKey, SECP256k1
import sha3
import traceback
def getAddress(phrases):
keyList = []
addrList = []
addrStr = ""
try:
for phrase in phrases:
key = sha3.keccak_256(ph... |
the-stack_106_31663 | """
Unit tests for Random CP optimiser on Cartesian product domains.
-- kandasamy@cs.cmu.edu
"""
# pylint: disable=invalid-name
# pylint: disable=abstract-class-little-used
# Local imports
from demos_synthetic.multiobjective_park.multiobjective_park import objectives as moo_park
from demos_synthetic.multiobjecti... |
the-stack_106_31668 | """
The MIT License (MIT)
Copyright (c) 2015-2021 Rapptz
Copyright (c) 2021-present Disnake Development
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 limi... |
the-stack_106_31672 | import collections
import ctypes
import errno
import fcntl
import os
import os.path
import select
import time
class GPIOError(IOError):
"""Base class for GPIO errors."""
pass
class EdgeEvent(collections.namedtuple('EdgeEvent', ['edge', 'timestamp'])):
def __new__(cls, edge, timestamp):
"""EdgeEv... |
the-stack_106_31674 | #!/usr/bin/env python3
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# ... |
the-stack_106_31675 | import torch.nn as nn
import torch
from .model import Model
from IPython import embed
import pdb
class RugE(Model):
"""`Knowledge Graph Embedding with Iterative Guidance from Soft Rules`_ (RugE), which is a novel paradigm of KG embedding with iterative guidance from soft rules.
Attributes:
args: Mode... |
the-stack_106_31678 | from math import ceil
from statistics import mean
def convert_opinion(agent_list): # noqa: C901
num_agents = len(agent_list)
n_comp = ceil(num_agents * 0.3)
O_ave = [0] * num_agents
S_ave = [0] * num_agents
D = [0] * num_agents
F = [0] * num_agents
def get(lis, a):
return lis[a.... |
the-stack_106_31679 | # Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
the-stack_106_31681 | # -*- coding: utf-8 -*-
"""
Test Generic Map
"""
import os
import tempfile
import warnings
import numpy as np
import pytest
import matplotlib.pyplot as plt
import astropy.wcs
import astropy.units as u
from astropy.io import fits
from astropy.time import Time
from astropy.coordinates import SkyCoord
from astropy.tests... |
the-stack_106_31682 | #!/usr/bin/env python
import math
import time
from os.path import join, realpath
import sys; sys.path.insert(0, realpath(join(__file__, "../../../")))
from hummingbot.core.event.event_logger import EventLogger
from hummingbot.core.event.events import (
OrderBookEvent,
OrderBookTradeEvent,
TradeType
)
impor... |
the-stack_106_31683 | # Copyright 2019 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... |
the-stack_106_31684 | #!/usr/bin/env python3
# Copyright 2019-2022 Jean-Luc Vay, Maxence Thevenet, Remi Lehe, Axel Huebl
#
#
# This file is part of WarpX.
#
# License: BSD-3-Clause-LBNL
#
# This is a script that analyses the simulation results from
# the script `inputs.multi.rt`. This simulates a 3D periodic plasma wave.
# The electric fie... |
the-stack_106_31685 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# https://github.com/dandavison/iterm2-dwim/blob/master/iterm2_dwim/parsers/parsers.py
__version__ = "0.0.3"
import sys, os, json, re
global cli_map
cli_map = {
'java': 'idea',
'rb': 'mine',
'ruby': 'mine',
'py': 'charm',
'python': 'charm',
'kt':... |
the-stack_106_31687 | import pytest
from django.urls import resolve, reverse
from termplanner.users.models import User
pytestmark = pytest.mark.django_db
def test_detail(user: User):
assert (
reverse("users:detail", kwargs={"username": user.username})
== f"/users/{user.username}/"
)
assert resolve(f"/users/{u... |
the-stack_106_31689 | # ***************************************************************
# Copyright (c) 2020 Jittor. Authors:
# Guowei Yang <471184555@qq.com>
# Dun Liang <randonlang@gmail.com>.
# All Rights Reserved.
# This file is subject to the terms and conditions defined in
# file 'LICENSE.txt', which is part of this source c... |
the-stack_106_31693 | import time
from datetime import datetime
import discord
from discord import Embed
from discord.ext import commands
from discord_slash import cog_ext
from discord_slash.context import SlashContext
import helpers
class Utilities(commands.Cog):
"""
General Utilities
"""
@cog_ext.cog_slash(name="ping"... |
the-stack_106_31694 | import tensorflow as tf
from utility.tf_utils import tensor2numpy
from core.tf_config import build
from core.decorator import override
from core.mixin import Memory
from algo.ppo.base import PPOBase, collect
def get_data_format(*, env, batch_size, sample_size=None,
store_state=False, state_size=None, **kwarg... |
the-stack_106_31695 | """
This module contains external toolkit wrappers that are required by the
main offpele modules.
"""
import importlib
from distutils.spawn import find_executable
import tempfile
import os
import subprocess
from collections import defaultdict
from pathlib import Path
from copy import deepcopy
import numpy as np
from ... |
the-stack_106_31696 | """
One of the really important features of |jedi| is to have an option to
understand code like this::
def foo(bar):
bar. # completion here
foo(1)
There's no doubt wheter bar is an ``int`` or not, but if there's also a call
like ``foo('str')``, what would happen? Well, we'll just show both. Because
th... |
the-stack_106_31698 | # 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 a... |
the-stack_106_31699 | # Copyright 2016 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 ag... |
the-stack_106_31701 | #!/usr/bin/env python
#
# NLP
# Andrew D'Amico
# MSDS 453 Natural Language Processing
# Northwestern University
# Copyright (c) 2022, Andrew D'Amico. All rights reserved.
# Licenced under BSD Licence.
import datetime
from NLPPrep import tokenization
import math
class NewsArticle(object):
"""
A News Article ... |
the-stack_106_31702 | # -*- coding: utf-8 -*-
import os.path
from ..decorators import linter
from ..parsers.base import ParserBase
from ..util.system import JAVA_SEP, vendored_path
GROOVY_PATH = vendored_path(os.path.join("groovy", "groovy-all-2.4.15.jar"))
SLF4J_PATH = vendored_path(os.path.join("groovy", "slf4j-api-1.7.25.jar"))
CODENA... |
the-stack_106_31705 | from joblib import delayed, Parallel
import os
import sys
import glob
from tqdm import tqdm
import cv2
import matplotlib.pyplot as plt
plt.switch_backend('agg')
def extract_video_opencv(v_path, f_root, dim=240):
'''v_path: single video path;
f_root: root to store frames'''
v_class = v_path.split('/'... |
the-stack_106_31706 | from tkinter import *
from tkinter import filedialog
from styles import *
from downloader import Downloader
class Singleton(type):
"""
Acts as a metaclass to allow other classes to become Singleton classes
"""
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instance... |
the-stack_106_31707 | """
@Author:lichunhui
@Time:
@Description:
"""
from sqlalchemy.exc import IntegrityError as SqlalchemyIntegrityError, InternalError
from pymysql.err import IntegrityError as PymysqlIntegrityError
from sqlalchemy.exc import InvalidRequestError
from ..logger import db_logger
from .basic import get_db_session
__all... |
the-stack_106_31709 | class RiskyExtention:
def RiskyExtention():
from urlparse import urlparse
o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
o.scheme
o.port
print(o)
currentpath=o.path
#splitpath=currentpath.split(".")
testlist=[".pdf",".exe",".mp3",... |
the-stack_106_31710 | import collections
import logging
import threading
import time
import pytest
import six
from kafka import SimpleClient
from kafka.conn import ConnectionStates
from kafka.consumer.group import KafkaConsumer
from kafka.structs import TopicPartition
from test.conftest import version
from test.testutil import random_str... |
the-stack_106_31712 | import tweepy
from site_crawler.twitter.credentials import Credentials
from site_crawler.cleaner.cleaner import Cleaner
import csv
import pandas as pd
from sklearn.externals import joblib
model=joblib.load('model.pkl')
credentials = Credentials()
cleaner = Cleaner()
api = credentials.authentinticate_twitter()
def pre... |
the-stack_106_31719 | #! usr/bin/env python
# -*- coding: utf-8 -*-
import shutil
import urllib.error
import time
import os
import urllib.request
import urllib.parse
from bs4 import BeautifulSoup
from selenium import webdriver
import datetime
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.