id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1681990 | from functools import reduce
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.db.models import F, Sum
from . import exceptions
class QuotaLimitField(models.IntegerField):
""" Django virtual model field.
Could be used to manage quotas transparently as model f... |
1682003 | import sqlite3
conn = sqlite3.connect('spider.sqlite')
cur = conn.cursor()
cur.execute('SELECT * FROM Twitter')
count = 0
for row in cur :
print row
count = count + 1
print count, 'rows.'
cur.close()
|
1682012 | from __future__ import division, print_function
from climlab.process.energy_budget import EnergyBudget
from climlab import constants as const
class SimpleAbsorbedShortwave(EnergyBudget):
'''A class for the shortwave radiation process in a one-layer EBM.
The basic assumption is that all the shortwave absorptio... |
1682043 | from PyQt4.QtCore import *
from PyQt4.QtGui import *
class HighscoresDialog(QDialog):
def __init__(self, scorelist, parent=None):
super(HighscoresDialog, self).__init__(parent)
self.setWindowTitle('High Scores')
frame = QFrame(self)
frame.setFrameStyle(QFrame.Pan... |
1682069 | import math
import os
from typing import Tuple, List, Dict
import torch
import sys
import json
import h5py
import numpy as np
import time
def cur_time():
return time.strftime('%Y,%b,%d,%X')
def log_important(message, log_file):
print(message, cur_time())
with open(log_file, 'a') as f:
print(messag... |
1682124 | import tensorflow as tf
from tensorflow import keras
<EMAIL>
def create_ids(ind, bag_size):
ids = ind + bag_size * tf.range(ind.shape[-1], dtype=tf.int32)
return tf.reshape(ids, [ind.shape[0], -1])
<EMAIL>
def unique_with_inverse(x):
y, idx = tf.unique(x)
num_segments = tf.shape(y)[0]
num_elems = tf.shape(x... |
1682132 | import sys
import matplotlib.pyplot
import pandas
import numpy
import struct
import os
data = None
with open(sys.argv[1], "rb") as f:
data = f.read()
data = struct.unpack("{}Q".format(len(data) // 8), data)
data = numpy.array(data, dtype=numpy.uint64)[1:]
data = numpy.array([x for x in data if x < 100000])
rt ... |
1682176 | import pytest
from wemake_python_styleguide.violations.refactoring import (
ImplicitPrimitiveViolation,
)
from wemake_python_styleguide.visitors.ast.functions import (
UselessLambdaDefinitionVisitor,
)
@pytest.mark.parametrize('code', [
'lambda x: 0',
'lambda *x: []',
'lambda **x: ()',
'lambd... |
1682187 | import FWCore.ParameterSet.Config as cms
tauRegionalPixelSeedGenerator = cms.EDProducer("SeedGeneratorFromRegionHitsEDProducer",
OrderedHitsFactoryPSet = cms.PSet(
ComponentName = cms.string('StandardHitPairGenerator'),
SeedingLayers = cms.InputTag('PixelLayerPairs')
),
SeedComparitorPSet =... |
1682202 | import torch
import torch.nn.functional as F
def rot90(x, k=1):
"""rotate batch of images by 90 degrees k times"""
return torch.rot90(x, k, (2, 3))
def hflip(x):
"""flip batch of images horizontally"""
return x.flip(3)
def vflip(x):
"""flip batch of images vertically"""
return x.flip(2)
... |
1682223 | load("@rules_pkg//:pkg.bzl", "pkg_zip")
def copy_file(name, src, out):
native.genrule(
name = name,
srcs = [src],
outs = [out],
cmd = "cp $< $@"
)
def pkg_asset(name, srcs = [], **kwargs):
"""Package MediaPipe assets
This task renames asset files so that they can be added to an... |
1682228 | from buffalo import utils
from playerConsole import PlayerConsole
from playerConsole import EventText
from playerConsole import TextWrapper
import pygame
utils.init()
PlayerConsole.init()
ipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lobortis ac enim vel feugiat. Duis ac metus id est lo... |
1682237 | from django_markup.filter import MarkupFilter
class MarkdownMarkupFilter(MarkupFilter):
"""
Applies Markdown conversion to a string, and returns the HTML.
"""
title = 'Markdown'
kwargs = {'safe_mode': True}
def render(self, text, **kwargs):
if kwargs:
self.kwargs.update(k... |
1682299 | from django.template import TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import TestObj, setup
class IfTagTests(SimpleTestCase):
@setup({'if-tag01': '{% if foo %}yes{% else %}no{% endif %}'})
def test_if_tag01(self):
output = self.engine.render_to_string('if-tag01', {'foo'... |
1682310 | import os
import time
import tensorflow as tf
import numpy as np
from scipy.stats import spearmanr
from sklearn.metrics import r2_score
import mnist_input
import multi_mnist_cnn
from sinkhorn import sinkhorn_operator
import util
import random
os.environ['TF_CUDNN_DETERMINISTIC'] = 'true'
tf.set_random_seed(94305)
ran... |
1682338 | import os
def setup(app):
current_dir = os.path.abspath(os.path.dirname(__file__))
app.add_html_theme(
'python_docs_theme', current_dir)
return {
'parallel_read_safe': True,
'parallel_write_safe': True,
}
|
1682374 | import pytz
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.db.models import Q
from invoices.models import Invoice
from invoices.tasks import (
send_email,
send_invoice_email,
send_invoice_email_cancel,
create_invoice_history,
)
from invoices impo... |
1682378 | import os
import json
import typing as t
from unittest.mock import patch, MagicMock
import jsonlines
from pyfakefs.fake_filesystem_unittest import TestCase
from starwhale.utils.fs import ensure_dir, ensure_file
from starwhale.consts.env import SWEnv
from starwhale.api._impl.model import _RunConfig, PipelineHandler
fr... |
1682396 | import numpy as np
import matplotlib.pyplot as plt
phi = -0.8
times = list(range(16))
y1 = [phi**k / (1 - phi**2) for k in times]
y2 = [np.cos(np.pi * k) for k in times]
y3 = [a * b for a, b in zip(y1, y2)]
num_rows, num_cols = 3, 1
fig, axes = plt.subplots(num_rows, num_cols, figsize=(10, 8))
plt.subplots_adjust(hsp... |
1682397 | import os
from celery.utils.log import get_task_logger
from sqlalchemy import MetaData
from ether_sql.globals import get_current_session
from ether_sql.tasks.worker import app
logger = get_task_logger(__name__)
@app.task()
def export_to_csv(directory='.'):
"""
Export the data in the psql to a csv
:param... |
1682442 | from .utils import Serializable
class CommandLineBinding(Serializable):
"""
The binding behavior when building the command line depends on the data type of the value.
If there is a mismatch between the type described by the input schema and the effective value,
such as resulting from an expression eva... |
1682446 | import numpy as np
import torch
from torch.autograd import Variable
from torch.autograd import Function
import torch.nn.functional as F
import point_utils_cuda
from pytorch3d.loss import chamfer_distance
from pytorch3d.ops import knn_points, knn_gather
from scipy.spatial.transform import Rotation
import random
class ... |
1682449 | import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import VGG
from mmcv.runner import BaseModule, Sequential
from ..builder import BACKBONES
@BACKBONES.register_module()
class SSDVGG(VGG, BaseModule):
"""VGG Backbone network for single-shot-detection.
Args:
... |
1682478 | study='ds102'
f=open(study+'/condition_key.txt')
ckey=f.readlines()
f.close()
f=open(study+'/task_key.txt')
tkey=f.readlines()
f.close()
print '<table border="1">'
print '<caption><EM>Description of tasks and conditions</EM></caption>'
for task in range(len(tkey)):
print '<tr><th colspan="2">%s'%tkey[task].strip... |
1682541 | import random
from typing import Iterable
from unittest import TestCase
import gym
import numpy as np
from envs.connect_four_env import ResultType, Player
from gym_connect_four import ConnectFourEnv, RandomPlayer
BOARD_VALIDATION = np.array([[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, -1, 0, 0, 0],
... |
1682563 | import info
class subinfo(info.infoclass):
def setTargets(self):
self.versionInfo.setDefaultValues()
self.displayName = "JuK"
self.patchToApply["18.08.1"] = [("juk-18.08.1-20181029.diff", 1)]
self.description = "JuK is a simple music player and helps manage your music collection"
... |
1682617 | import cas
from cas.common.config import DefaultValidatingDraft7Validator
from cas.common.models import BuildEnvironment, BuildResult, BuildSubsystem
from cas.common.cache import FileCache
from cas.common.assets.models import (
Asset,
AssetBuildContext,
BaseDriver,
SerialDriver,
BatchedDriver,
)
im... |
1682648 | from ._xxhash import (
xxh32,
xxh32_digest,
xxh32_intdigest,
xxh32_hexdigest,
xxh64,
xxh64_digest,
xxh64_intdigest,
xxh64_hexdigest,
xxh3_64,
xxh3_64_digest,
xxh3_64_intdigest,
xxh3_64_hexdigest,
xxh3_128,
xxh3_128_digest,
xxh3_128_intdigest,
xxh3_128_hexd... |
1682654 | from unittest.mock import patch, Mock
from urllib.parse import urlencode
import django.test
from django.urls import reverse
from rest_framework import status
@django.test.override_settings(OIDC_PIK_CLIENT_ID="TEST_CLIENT_ID")
@patch("social_core.backends.open_id_connect.OpenIdConnectAuth.oidc_config",
Mock(... |
1682662 | import pytest
import numpy as np
import levitate
# Tests created with these air properties
from levitate.materials import air
air.c = 343
air.rho = 1.2
array = levitate.arrays.RectangularArray(shape=(4, 5))
pos_0 = np.array([0.1, 0.2, 0.3])
pos_1 = np.array([-0.15, 1.27, 0.001])
pos_both = np.stack((pos_0, pos_1), ax... |
1682671 | from django.test import TestCase
from corehq.apps.domain.shortcuts import create_domain
from corehq.apps.locations.models import LocationType, make_location
class SiteCodeTest(TestCase):
domain = 'test-site-code'
@classmethod
def setUpClass(cls):
super(SiteCodeTest, cls).setUpClass()
cl... |
1682673 | import tensorflow as tf
class DM_pignistic(tf.keras.layers.Layer):
def __init__(self, num_class):
super(DM_pignistic, self).__init__()
self.num_class=num_class
def call(self, inputs):
aveage_Pignistic=inputs[:,-1]/self.num_class
aveage_Pignistic=tf.expand_dims(av... |
1682686 | import os
import shutil
import subprocess
import sys
from pathlib import Path
URL_PREFIX = "aurin://"
ILLEGAL_PKG_NAME_CONTENTS = (".", "..", "/")
temp_dir = Path("/var", "tmp", "aurin")
def error_out(message: str):
print(f"ERROR: {message}", file=sys.stderr)
sys.exit(1)
def notify(icon: str, title: str, ... |
1682703 | import random
import torch
from torch.utils.data.sampler import Sampler
# Adapted from
# https://github.com/pytorch/pytorch/pull/3062/files
class RandomCycleIter(object):
def __init__(self, data):
self.data_list = list(data)
self.length = len(self.data_list)
self.i = self.length - 1
d... |
1682745 | import argparse
import os
import random
import shutil
import sys
import time
import numpy as np
import torch
import torch.nn.functional as F
import yaml
_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'utils')
sys.path.append(_path)
os.environ["CUDA_VISIBLE_DEVICES"] = "6"
ncentroids = 10
from tqdm ... |
1682754 | class DiachronicVisualizer(object):
@staticmethod
def visualize(display_df):
raise NotImplementedError() |
1682757 | from copy import deepcopy
from functools import lru_cache
import json
from typing import Any, Dict
# from electionguard.serializable import read_json_file
__all__ = ["get_ballot", "get_election_description"]
_DATA_DIRECTORY = "tests/integration/data"
def get_ballot(ballot_id: str) -> Any:
ballot = deepcopy(_ge... |
1682806 | import redis
import utils.config_handler
def create_redis_client():
REDIS_CONFIG = utils.config_handler.load_json_config()['redis_server']
redis_client = redis.Redis(host=REDIS_CONFIG['host'], port=int(REDIS_CONFIG['port']))
return redis_client |
1682810 | from time import sleep
import tellopy
from tellopy._internal.utils import *
prev_flight_data = None
def handler(event, sender, data, **args):
global prev_flight_data
drone = sender
if event is drone.EVENT_CONNECTED:
print('connected')
drone.start_video()
drone.set_exposure(0)
... |
1682836 | import numpy as np
import xarray as xr
from wavespectra.core.attributes import attrs, set_spec_attributes
def spread(dp_matrix, dspr_matrix, dirs):
"""Generic spreading function.
Args:
dp_matrix:
dspr_matrix:
dirs:
Returns:
G1:
Note:
Function defined such th... |
1682974 | import pytest
from nylas.client.restful_models import Folder, Thread, Message
@pytest.mark.usefixtures("mock_folder")
def test_get_change_folder(api_client):
folder = api_client.folders.get("anuep8pe5ug3xrupchwzba2o8")
assert folder is not None
assert isinstance(folder, Folder)
assert folder.display_n... |
1682989 | import logging
import pytest
import sys
import os
import subprocess
import uuid
from contextlib import contextmanager
logger = logging.getLogger(__name__)
@contextmanager
def conda_env(env_name):
# Set env name for shell script
os.environ["JOB_COMPATIBILITY_TEST_TEMP_ENV"] = env_name
# Delete conda env ... |
1683011 | import numpy as np
import mxnet as mx
from mxnet import nd
from mxnet.gluon.data import dataset
from mxnet.gluon.data import dataloader
import collections
import os
class ImageWithMaskDataset(dataset.Dataset):
"""
A dataset for loading images (with masks) stored as `xyz.jpg` and `xyz_mask.png`.
Parameter... |
1683012 | from distutils.core import setup, Extension
CFLAGS=[]
cPolymagic = Extension("cPolymagic", sources = ["gpc.c", "polymagic.m"], extra_compile_args=CFLAGS)
setup (name = "polymagic",
version = "0.1",
author = "<NAME>",
description = "Additional utility functions for NSBezierPath using GPC.",
... |
1683015 | def tail_swap(arr):
fmt = '{}:{}'.format
(head, tail), (head_2, tail_2) = (a.split(':') for a in arr)
return [fmt(head, tail_2), fmt(head_2, tail)]
|
1683026 | from pypy.interpreter.error import OperationError, oefmt
from pypy.interpreter.typedef import (
TypeDef, generic_new_descr, GetSetProperty)
from pypy.interpreter.gateway import interp2app, unwrap_spec
from rpython.rlib.rStringIO import RStringIO
from rpython.rlib.rarithmetic import r_longlong
from rpython.rlib.obje... |
1683031 | import infra.basetest
class TestSysLinuxBase(infra.basetest.BRTest):
x86_toolchain_config = \
"""
BR2_x86_i686=y
BR2_TOOLCHAIN_EXTERNAL=y
BR2_TOOLCHAIN_EXTERNAL_CUSTOM=y
BR2_TOOLCHAIN_EXTERNAL_DOWNLOAD=y
BR2_TOOLCHAIN_EXTERNAL_URL="http://toolchains.bootlin.com/down... |
1683037 | import tensorflow as tf
import tensorflow.contrib as tf_contrib
from tensorflow.python.util import nest
from las.ops import lstm_cell
from las.ops import pyramidal_bilstm
from utils import TrainingSigmoidHelper, ScheduledSigmoidHelper, DenseBinfDecoder,\
TPUScheduledEmbeddingTrainingHelper, decoders_factory
__al... |
1683078 | from torch import nn
from ops.basic_ops import ConsensusModule
from ops.transforms import *
from torch.nn.init import normal_, constant_
import torch.nn.functional as F
from efficientnet_pytorch import EfficientNet
from ops.net_flops_table import feat_dim_dict
from torch.distributions import Categorical
def init_hid... |
1683082 | import torch
import torch.nn as nn
import onqg.dataset.Constants as Constants
from onqg.models.modules.Layers import GGNNEncoderLayer
class GGNNEncoder(nn.Module):
"""Combine GGNN (Gated Graph Neural Network) and GAT (Graph Attention Network)
Input: (1) nodes - [batch_size, node_num, d_model]
(2)... |
1683097 | import glob
import os
from invoke import task
from invoke.exceptions import Exit
from .libs.common.color import color_message
def get_package_path(glob_pattern):
package_paths = glob.glob(glob_pattern)
if len(package_paths) > 1:
raise Exit(code=1, message=color_message(f"Too many files matching {glo... |
1683101 | import json
import psycopg2
import traceback
from colorama import Fore
from toolset.utils.output_helper import log
from toolset.databases.abstract_database import AbstractDatabase
class Database(AbstractDatabase):
@classmethod
def get_connection(cls, config):
db = psycopg2.connect(
ho... |
1683119 | import json
import logging
import os
from smda.Disassembler import Disassembler
def detectBackend():
backend = ""
version = ""
try:
import idaapi
import idautils
backend = "IDA"
version = idaapi.IDA_SDK_VERSION
except:
pass
return (backend, version)
if __... |
1683126 | import torch
import torch.nn as nn
import torch.nn.functional as F
import copy
import torchvision.models as models
def mse_loss(output, target):
loss_ = F.mse_loss(output, target)
return loss_
def smooth_l1_loss(pred, target):
loss_ = F.smooth_l1_loss(pred, target)
return loss_
def gradient_loss(pre... |
1683130 | from pypy.objspace.std import floatobject as fobj
from pypy.objspace.std.objspace import FailedToImplement
import py
class TestW_FloatObject:
def _unwrap_nonimpl(self, func, *args, **kwds):
""" make sure that the expected exception occurs, and unwrap it """
try:
res = func(*args, **kwd... |
1683150 | from datadog_checks.base import ConfigurationError, OpenMetricsBaseCheck
class JfrogPlatformCheck(OpenMetricsBaseCheck):
"""
Collect metrics from JFrog
"""
def __init__(self, name, init_config, instances=None):
instance = instances[0]
instancetype = instance.get('instance_type')
... |
1683170 | import torch
import torch.autograd
from torch import nn
from torch.autograd import Variable
def pairwise(data):
n_obs, dim = data.size()
xk = data.unsqueeze(0).expand(n_obs, n_obs, dim)
xl = data.unsqueeze(1).expand(n_obs, n_obs, dim)
dkl2 = ((xk - xl)**2.0).sum(2).squeeze()
return dkl2
class VT... |
1683206 | from flask import url_for, json
from behave import when, then
@when('the user makes a request to the get planners endpoint')
def the_user_makes_a_request_to_get_planners(context):
with context.app.test_request_context():
url = url_for("planners.list_planners")
res = context.client.get(url)
... |
1683210 | from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
from django.views.generic.base import TemplateView
from browser.views import *
from http_handler.settings import WEBSITE
from registration.backends.default.views import ActivationView
from registration.forms import M... |
1683230 | import convokit
import numpy as np
import matplotlib.pyplot as plt
print("Loading corpus")
corpus = convokit.Corpus(filename=convokit.download("reddit-corpus-small"))
print("Computing hypergraph features")
hc = convokit.HyperConvo()
hc.fit_transform(corpus)
print("Computing low-dimensional embeddings")
te = convokit... |
1683232 | from threading import Event
from time import sleep
from epics import PV, ca
from py4syn.epics.StandardDevice import StandardDevice
class Shutter(StandardDevice):
#CALLBACK FUNCTION FOR THE SHUTTER STATUS PV
#def onStatusChange(self, **kw):
#self._open = not self._open
#CONSTRUCTOR OF SHUTTER CLA... |
1683253 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable as V
from torch import autograd
import numpy as np
class Net(nn.Module):
def __init__(self, args):
super(Net, self).__init__()
#### SELF ARGS ####
self.dropout... |
1683255 | import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
class HTMLVisualizer():
def __init__(self, fn_html):
self.fn_html = fn_html
self.content = '<table>'
self.content += '<style> table, th, td {border: 1px solid black;} </style>'
def add_header(self, elem... |
1683276 | from django.test import TestCase
from rest_framework.test import APIClient
from backend.models import UserModel, RoleModel, TenantModel, AwsEnvironmentModel, Command, Document, Parameter
from backend.models.resource.ec2 import Ec2
from datetime import datetime
from unittest import mock
@mock.patch("backend.vi... |
1683321 | import sys
import os
from datetime import datetime
from typing import List
sys.path.append(os.path.join('..', '..'))
import torch
import numpy as np
from torch.utils.data import Subset
from data import CUB200
from lens.utils.datasets import ImageToConceptDataset, ImageToConceptAndTaskDataset
from lens.utils import me... |
1683438 | from __future__ import absolute_import, division, print_function, unicode_literals
import os
from beast.util import Execute
from beast.util import String
def describe(**kwds):
return String.single_line(Execute.execute('git describe --tags', **kwds))
|
1683447 | from ctypes import c_int, c_char_p, POINTER
from llvmlite.binding import ffi
def link_modules(dst, src):
with ffi.OutputString() as outerr:
err = ffi.lib.LLVMPY_LinkModules(dst, src, outerr)
# The underlying module was destroyed
src.detach()
if err:
raise RuntimeError(s... |
1683524 | import skimage.io as io
import skimage.transform as skt
import numpy as np
from PIL import Image, ImageOps
from src.models.class_patcher import patcher
from src.utils.imgproc import *
class patcher(patcher):
def __init__(self, body='./body/body_ramne.png', **options):
super().__init__(name='ラムネ', body=bod... |
1683537 | import pytest
import numpy as np
from numpy.testing import assert_allclose
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import det_curve
from sklearn.metrics import plot_det_curve
@pytest.fixture(scope="module")
def data():
return load_iris(retu... |
1683540 | import cv2
import myface.face as face
import myface.utils.utils as utils
from myface.classes.test import Face_test
import numpy as np
MODEL_PATH = '../model/'
# openCv video capture : webcam or video
video_capture = cv2.VideoCapture(0)
# video_capture = cv2.VideoCapture('/Users/zane/Movies/video/ET/ET.mp4')
# Load T... |
1683548 | class Symbol():
def __init__(self, id, type_specific, data_type, valor):
self.id = id
self.type_specific = type_specific
self.data_type = data_type
self.valor = valor
|
1683576 | from flask_admin.base import MenuLink
"""
By specifying a category that doesn't exist, a new tab will appear in the webserver, with the menu link objects
specified to it.
"""
pandora_plugin = \
MenuLink(
category='Plugins',
name='Pandora-Plugin',
url='https://github.com/airflow-plugins/pand... |
1683589 | from django.db import models
from db.models import MySQLInst
class QuerySqlLog(models.Model):
"""
sql查询日志表
"""
operator = models.CharField(max_length=64, blank=True,null=True, verbose_name=u"查询人")
mysqlinst = models.ForeignKey(MySQLInst,blank=True,null=True,on_delete=models.SET_NULL,verbose_name=u"... |
1683606 | from os import path
import tempfile, textwrap, webbrowser
import sublime, sublime_plugin
class MermaidViewCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
title = path.splitext(path.basename(view.file_name() or 'untitled'))[0]
name = '{0}-{1}-mermaid-view.html'.format(title, vie... |
1683678 | from Objects.Item import Item
from Objects.Projectile import Projectile
from Engine.World import CreateObject, Object
class Taser(Item):
defName = "Taser"
defSprite = "taser"
def InteractWith(self, object):
if object is None:
return False
if not object.position or object.position == self.position:
retur... |
1683684 | import numpy as np
from dyneusr import DyNeuGraph
from dyneusr.datasets import make_trefoil
from kmapper import KeplerMapper
from sklearn.decomposition import PCA
# Generate synthetic dataset
import tadasets
X = tadasets.sphere(n=500, r=1)
# Sort by first column
inds = np.argsort(X[:, 0])
X = X[inds].copy()
y = np.ar... |
1683695 | urls = []
with open('urls.txt', 'r') as f:
for url in f.readlines():
if url not in urls:
urls.append(url)
with open('urls.txt','w') as f:
f.writelines(urls)
urls = []
with open('archive.txt', 'r') as f:
for url in f.readlines():
if url not in urls:
urls.append(url)
... |
1683707 | import time
from telethon import version
from uniborg.util import beastx_cmd, sudo_cmd
from beastx import ALIVE_NAME, CMD_HELP, Lastupdate
from beastx.Configs import Config
from beastx.modules import currentversion
from beastx import beast
from telethon.tl.functions.users import GetFullUserRequest
from . import OWNER... |
1683727 | import imghdr
import os
import tensorflow as tf
def is_image_valid(filepath):
return imghdr.what(filepath) is not None
def get_image_paths(image_dir):
image_paths = []
for root, directories, filenames in os.walk(image_dir):
image_paths += [os.path.join(root, filename) for filename in filenames]
... |
1683772 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDHarvester import DQMEDHarvester
from Validation.MuonGEMHits.MuonGEMCommonParameters_cfi import GEMValidationCommonParameters
gemDigiHarvesting = DQMEDHarvester("MuonGEMDigisHarvestor",
GEMValidationCommonParameters,
regionIds = cms.untracked.v... |
1683782 | import re
#____________________________________________________________________________
def read_file(file_name):
with open(file_name, 'r') as file:
ret = {}
for line in file.readlines():
if not (line.startswith('*') or line.startswith('C') or line.startswith('c')):
line... |
1683872 | import plotly.graph_objs as go
#import plotly.plotly as py
import plotly.offline as offline
from selenium import webdriver
# from matplotlib import rc
# #==========================
# # use these lines for latex
# #==========================
# rc('text',usetex=True)
# font = {'family' : 'serif',
# 'weight' : ... |
1683917 | import argparse
import os
import torch
from compressai.models import MeanScaleHyperprior
from compressai.zoo.pretrained import load_pretrained
from torchdistill.common import yaml_util
from torchdistill.common.main_util import load_ckpt
from torchdistill.common.module_util import count_params
from torchdistill.models.... |
1683943 | from unittest import TestCase
import json
from fac.utils import JSONDict, JSONList
class TestJSONDict(TestCase):
def setUp(self):
self.orig = {'foo': 42, 'bar': True, 'baz': [1, 2], 'qux': {'lok': 3}}
self.d = JSONDict(self.orig)
def test_json(self):
self.assertDictEqual(json.loads(s... |
1683989 | from keras import backend as K
from keras.engine import Layer
class FusionLayer(Layer):
def call(self, inputs, mask=None):
imgs, embs = inputs
reshaped_shape = imgs.shape[:3].concatenate(embs.shape[1])
embs = K.repeat(embs, imgs.shape[1] * imgs.shape[2])
embs = K.reshape(embs, resh... |
1684006 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from Pruning.utils import prune_rate, arg_nonzero_min
def weight_prune(model, pruning_perc):
'''
Prune pruning_perc% weights globally (not layer-wise)
arXiv: 1606.09274
'''
all_weights = []
for p in mode... |
1684076 | class Instruccion:
'Clase abstracta de instruccion'
def __init__(self, type, line, column):
self.type = type
self.line = line
self.column = column
def execute(self):
return self.val
def __repr__(self):
return str(self.__dict__)
|
1684093 | class Solution:
# @param {integer[]} nums
# @return {string}
def largestNumber(self, nums):
nums = sorted([str(num) for num in nums])
result = ""
while nums:
num = self.pickone(nums, None)
result += num
nums.remove(num)
if result[0] == '0':... |
1684100 | import torch.nn as nn
def my_loss(classifier, regression, points, mode):
#classifier is the predicted class
#regression is an array of predicted coordinates
#points is an array of ground truth coordinates
#mode is the ground truth class
alpha = 0.5
MSE = nn.MSELoss()
MSEl = MSE(regression, ... |
1684103 | import random
from multiprocessing import cpu_count
from transformers import (ConstantLRSchedule, WarmupLinearSchedule, WarmupConstantSchedule)
from modeling.modeling_rn import *
from utils.optimization_utils import OPTIMIZER_CLASSES
from utils.parser_utils import *
from utils.relpath_utils import *
def get_node_fe... |
1684132 | import json
from com.huawei.iotplatform.client.invokeapi.Authentication import Authentication
from com.huawei.iotplatform.client.invokeapi.BatchProcess import BatchProcess
from com.huawei.iotplatform.client.dto.AuthOutDTO import AuthOutDTO
from com.huawei.iotplatform.client.dto.BatchTaskCreateInDTO import BatchTaskCr... |
1684133 | from datetime import datetime
class DBHelper:
def __init__(self):
pass
def initDB(self):
'''
初始化数据库,主要是建表等工作
'''
pass
def writeBars(self, bars:list, period="day"):
'''
将K线存储到数据库中\n
@bars K线序列\n
@period K线周期
... |
1684287 | from flask import Blueprint, g, jsonify
from rowboat.models.guild import Guild
from rowboat.util.decos import authed
users = Blueprint('users', __name__, url_prefix='/api/users')
@users.route('/@me')
@authed
def users_me():
return jsonify(g.user.serialize(us=True))
@users.route('/@me/guilds')
@authed
def user... |
1684300 | from checkmate.lib.models import (Issue,
IssueOccurrence,
IssueCategory,
Diff,
Snapshot,
DiffIssueOccurrence,
Projec... |
1684321 | import numba
import torch
import numpy as np
from .common import check_numpy_to_torch
def limit_period(val, offset=0.5, period=np.pi):
val, is_numpy = check_numpy_to_torch(val)
ans = val - torch.floor(val / period + offset) * period
return ans.numpy() if is_numpy else ans
def rotate_points_along_z(points,... |
1684344 | import numpy as np
class BinaryTree:
root = None
node_index = None
def __init__(self, index, value):
self.root = BinaryTreeNode(index, value)
self.node_index = {index: self.root}
def add_left_descendant(self, index, value, parent_index):
parent = self.node_index[parent_index... |
1684374 | import logging
import pandas as pd
import glob
import os
import sys
utils_path = os.path.join(os.path.abspath(os.getenv('PROCESSING_DIR')),'utils')
if utils_path not in sys.path:
sys.path.append(utils_path)
import util_files
import util_cloud
import util_carto
import requests
from zipfile import ZipFile
import urll... |
1684405 | from src import network
bbj = network.BBJ("192.168.1.137", 7066)
def geterr(obj):
"""
Returns false if there are no errors in a network response,
else a tuple of (code integer, description string)
"""
error = obj.get("error")
if not error:
return False
return (error["code"], erro... |
1684414 | import torch
import torch.autograd as autograd
def gradient_penalty(fake_data, real_data, discriminator):
alpha = torch.cuda.FloatTensor(fake_data.shape[0], 1, 1, 1).uniform_(0, 1).expand(fake_data.shape)
interpolates = alpha * fake_data + (1 - alpha) * real_data
interpolates.requires_grad = True
disc... |
1684437 | import networkx as nx
from networkx.utils.decorators import py_random_state, not_implemented_for
__all__ = ["randomized_partitioning", "one_exchange"]
@not_implemented_for("directed", "multigraph")
@py_random_state(1)
def randomized_partitioning(G, seed=None, p=0.5, weight=None):
"""Compute a random partitioning... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.