text stringlengths 1 927k |
|---|
import json
import copy
import yaml
import sys
import numpy as np
import networkx as nx
from scipy import linalg
def merge_cooccurrence_matrix(number_of_days, origin_directory,result_directory,origin_prefix,result_filename):
postfix='.npy'
for i in range(1,1+number_of_days):#build combine co_occurrence matrix... |
import copy
import unittest
import warnings
from datetime import datetime
from mltrace import (
set_db_uri,
create_component,
log_component_run,
register,
get_history,
get_recent_run_ids,
load,
save,
)
from mltrace.entities import ComponentRun, IOPointer
class TestClient(unittest.Test... |
import io
import os
import re
import attr
import urllib
import logging
import xmljson
import requests
import jsonschema
try:
import ujson as json
except:
import json
from lxml import etree
from datetime import datetime
from requests.adapters import HTTPAdapter
from .io import get_data_dir
from .exceptions impo... |
# Similar to script 1 but with discrete-value actions.
# It uses CompleteEnvironmentA2C2
from sys_simulator import general as gen
from sys_simulator.q_learning.environments.completeEnvironmentA2C2 \
import CompleteEnvironmentA2C2
from sys_simulator.q_learning.rewards import dis_reward_tensor
from sys_simulator.par... |
from yt.fields.field_info_container import FieldInfoContainer
from yt.utilities.physical_constants import kboltz, mh
b_units = "code_magnetic"
pres_units = "code_pressure"
erg_units = "code_mass * (code_length/code_time)**2"
rho_units = "code_mass / code_length**3"
def velocity_field(comp):
def _velocity(field, ... |
from __future__ import annotations
from typing import TypedDict
from ..types.snowflake import Snowflake
class RawActivityAssets(TypedDict):
largeimage: Snowflake
largetext: str
smallimage: Snowflake
smalltext: str |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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 cop... |
"""Sample perturbation file. It trips the 9th generator at t=2"""
def pert(t, system):
if 2.0 <= t <=2.2:
pass |
from utilmeta.utils import *
class UserBase(Schema):
username: str
bio: str
image: str
class UserLogin(Schema):
email: str
password: str
class UserRegister(UserLogin):
username: str
class UserSchema(UserBase):
email: str
password: str = Field(writeonly=True)
token: str = Fiel... |
##############################################################################
# Copyright (c) 2016 ZTE Corporation
# feng.xiaowei@zte.com.cn
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, ... |
from flask import json, django
class Vote_Question(self.):
userUpVotes = self.votequestion('User', blank=True, related_name='questionUpVotes')
userDownVotes = self.votequestion('User', blank=True, related_name='questionDownVotes')
def vote(request):
question_id = int(request.POST.get('id'))
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
from setuptools import find_packages, setup
setup(
name='trending',
packages=find_packages(),
version='0.0.1',
description='Methods for determining trending-ness',
author='Chris Sipola',
license='Apache License 2.0',
install_requires=[],
include_package_data=True,
) |
# Logging hello world
import logging
logging.basicConfig(level=logging.INFO, filename='mylog.log')
logging.info('Starting program')
logging.info('Trying to divide 1 by 0')
print(1/0)
logging.info('The division succeeded')
logging.info('Ending program') |
#RESTFRAMEWORK
from rest_framework import serializers
#MODELS
from orderbook_veinte.orderbook.models import Orders , OrderStatus
class OrdersStatusSerializer(serializers.ModelSerializer):
class Meta:
model = OrderStatus
fields = ('status' ,)
class UserOrderSerializer(serializers.ModelSerializer)... |
from pydantic import BaseModel
from typing import Optional
class UserModel(BaseModel):
username: Optional[str] = ""
passcode: Optional[str] = ""
def is_valid(self):
error = []
if len(self.username) == 0:
error.append("Username cannot be blank")
if len(self.passcode) ==... |
import functools
import hashlib
import os
import sys
from io import BytesIO
from shutil import copy, rmtree
from tempfile import mkdtemp
import pytest
from mock import Mock, patch
import pip
from pip._internal.download import (
CI_ENVIRONMENT_VARIABLES,
MultiDomainBasicAuth,
PipSession,
SafeFileCache,... |
"""Dynamic programming module"""
import numpy as np
from copy import deepcopy
from ._misc import check_params, softmax, pessimism
from warnings import warn
class ValueIteration(object):
"""Q-value iteration algorithm.
Parameters
----------
policy : max | min | softmax | pessimism (default = pessi... |
#
# 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
# "License"); you may not... |
import requests
from lxml import html
from fake_useragent import UserAgent
from io import StringIO, BytesIO
from court_scraper.base.last_date import LastDate
from court_scraper.base.requests_base_page import RequestsBasePage
from court_scraper.base.search_page_mixin import SearchPageMixIn
from .url import OklahomaURLs... |
# Copyright 2020-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 agre... |
from typing import List
class StandardOcr:
"""
StandardOcr is a helper class for the raw "standard" preset config OCR result. Enables easy extraction
of common datapoints into usable objects.
"""
def __init__(self, standardocr: dict):
"""
standardocr dict: standard result object f... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def inorder(self, node: TreeNode) -> None:
if not node:
return
self.inorder(node.left)
... |
from __future__ import absolute_import
import glob
import os
import csv
import click
from ..base import avro_record
from ..cli import from_command
from ..reader import PFBReader
@from_command.command("tsv", short_help="Convert TSV files into a PFB file.")
@click.argument("path", default=".", type=click.Path(exists... |
#!/usr/bin/env python
import itertools
import math
from pathlib import Path
import sys
import collections
import datetime
import enum
import shutil
import htcondor
import click
def get_events(event_log_path):
yield from htcondor.JobEventLog(Path(event_log_path).as_posix()).events(0)
class JobStatus(enum.IntEn... |
"""This module contains the general information for StorageScsiLunRef ManagedObject."""
from ...ucsmo import ManagedObject
from ...ucscoremeta import MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class StorageScsiLunRefConsts:
ID_UNSPECIFIED = "unspecified"
class StorageScsiLunRef(ManagedObject):
... |
# Setting matplotlib layout to match tex settings
import matplotlib
matplotlib.use('pgf')
import matplotlib.pyplot as plt
from os.path import dirname, abspath
import locale
matplotlib.rcParams.update({
'font.family': 'serif',
'text.usetex': True,
'pgf.rcfonts': False,
'pgf.texsystem': 'lualatex',
... |
import sys
sys.path.insert(1, "../../../")
import h2o
from tests import pyunit_utils
import tempfile
def glm_mojo_reproducibility_info():
params = {'family':"fractionalbinomial", 'alpha':[0], 'lambda_':[0],
'standardize':False, "compute_p_values":True}
train = h2o.import_file(pyunit_utils.locate... |
"""This module has various functions inside it that will allow
the processing and handling of covid data, whether from a
CSV file or returned from an API"""
import sched
import time
import logging
import pandas as pd
from typing import List
from uk_covid19 import Cov19API
logging.basicConfig(filename='covid_lo... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: v1.10.6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
from aio... |
from functools import partial
import numpy as np
import theano
import theano.tensor as tt
from scipy import stats
from .dist_math import bound, factln, binomln, betaln, logpow
from .distribution import Discrete, draw_values, generate_samples, reshape_sampled
__all__ = ['Binomial', 'BetaBinomial', 'Bernoulli', 'Di... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... |
#!/pxrpythonsubst
#
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
... |
import openpyxl
import preprocess
from DBGetter import DBGetter
from LoadData import LoadData
from Preference import Pref
place = {1:"한라산@@@자연-숲", 2:"오름@@@자연-숲", 3: "성산일출봉@@@자연-숲", 4 : "섬(우도/마라도 등)@@@자연명소",
5:"올레길@@@기타", 6: "폭포(정방폭포 등)@@@자연명소", 7: "동굴(만장굴 등)@@@자연명소", 8: "해수욕장@@@자연명소",
9:"비자림@@@자연-숲"... |
import torch
import torch.nn as nn
from torchvision import transforms
from DBCNN import DBCNN
from PIL import Image
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
test_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=(0.485, 0.456, 0.406),
... |
from unittest import TestCase
from unittest.mock import patch
with patch('serial.Serial'):
from controls.valloxcontrol import ValloxControl
from valloxserial import vallox_serial
class TestValloxControl(TestCase):
@patch('serial.Serial')
def setUp(self, _):
self.vc = ValloxControl()
@patch.o... |
from rest_framework import serializers as ser
from api.base.utils import absolute_reverse
from api.base.serializers import JSONAPISerializer, LinksField, RelationshipField
class PreprintProviderSerializer(JSONAPISerializer):
filterable_fields = frozenset([
'name',
'description',
'id'
... |
import paddle
import paddle.nn as nn
class DiceLoss(nn.Layer):
def __init__(self, loss_weight=1.0):
super(DiceLoss, self).__init__()
self.loss_weight = loss_weight
def forward(self, input, target, mask, reduce=True):
batch_size = input.shape[0]
input = nn.functional.sigmoid(in... |
from glob import glob
import pandas as pd
import numpy as np # linear algebra
from tensorflow.keras.applications.imagenet_utils import preprocess_input
from tensorflow.keras.callbacks import ModelCheckpoint
from sklearn.model_selection import train_test_split
from models import get_model_classif_nasnet
from utils im... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2020 Red Hat, 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/lice... |
import torch
if torch.cuda.is_available():
import torch_points_kernels.points_cuda as tpcuda
class ChamferFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, xyz1, xyz2):
if not torch.cuda.is_available():
raise NotImplementedError(
"CPU version is not ava... |
import json
import train
import random
import os
from generatebatchsettings import *
import numpy as np
import copy
import hashlib
import glob
import sys
import optparse
import utils
def main(run_dir="rfe_chain", start=None, start_auc=None,
verbose=None, logfile=None):
"""
Main function to run the c... |
"""Unit tests for oseoserver.operations.submit"""
from lxml import etree
import mock
import pytest
from pyxb import BIND
from pyxb.bundles.opengis import oseo_1_0 as oseo
from oseoserver import errors
from oseoserver.operations import submit
from oseoserver import models
from oseoserver.models import Order
from oseos... |
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='requests_httpsproxy',
version='1.0.6',
description='allow http/https requests through https proxy',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'License ::... |
"""fitlive_31937 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class... |
from django.db import models
from blockexplorer.raven import client
from jsonfield import JSONField
from utils import get_client_ip, uri_to_url, is_good_status_code, get_user_agent
import json
import requests
class APICall(models.Model):
"""
To keep track of all our external API calls and aid in debugging... |
# -*- coding: utf-8 -*-
#
# 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
#... |
"""
pygments.formatters.terminal
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Formatter for terminal output with ANSI sequences.
:copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import sys
from pygments.console import ansiformat
from pygments.formatt... |
import subprocess
from os.path import isfile
import hashlib
import os
import random
import re
from tempfile import gettempdir
import os.path
from requests_futures.sessions import FuturesSession
from os.path import dirname, exists, isdir, join
from text2speech.util import get_cache_directory, remove_last_slash
from ovos... |
import os
import tensorflow as tf
from app.storage_service import weights_filepath, dictionaries_dirpath
def test_local_storage():
local_filepaths = [
weights_filepath("local"),
os.path.join(dictionaries_dirpath("local"), "dic.txt"),
os.path.join(dictionaries_dirpath("local"), "dic_s.txt"),
]
for filep... |
import pytest
from nodels.base import BaseGather
def test_to_dict():
b = BaseGather()
assert b.to_dict() == {}
b2 = BaseGather(data={"foo": "bar"})
assert b2.to_dict() == {"foo": "bar"}
def test_json():
b = BaseGather()
assert b.json() == "{}"
b2 = BaseGather(data={"foo": "bar"})
... |
from PIL import Image
from pathlib import Path
def add_watermark(input_path, watermark_path, output_path):
"""Add EU-compliant meme watermark to a supplied image"""
try:
original_image = Image.open(input_path)
_w, h = original_image.size
size = int(round(h * 0.4))
watermark_ima... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Podman(Package):
"""An optionally rootless and daemonless container engine: alias docker=p... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from colorfield.fields import ColorField
class Project(models.Model):
name = models.CharField(max_length=50)
image = models.FileField(upload_to='projects/', null=True, blank=True)
def layouts(self):
return Layout.obje... |
"""
Make connection to MySQL server and gets all config parameters.
######################
Error code handling example,
=> https://dev.mysql.com/doc/connector-python/en/connector-python-api-errors-error.html
MySQL error code,
=> https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html
"""
impor... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
__all__ = ['AlgoMeta']
from typing import Dict, NamedTuple, Optional
class AlgoMeta(NamedTuple):
name: str
class_name: Optional[str]
accept_class_args: bool
class_args: Optional[dict]
validator_class_name: Optional[str]
... |
# =================================================================
#
# Authors: Tom Kralidis <tomkralidis@gmail.com>
#
# Copyright (c) 2021 Tom Kralidis
# Copyright (c) 2021 Francesco Bartoli
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentatio... |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Pershyancoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test transaction signing using the signrawtransaction RPC."""
from test_framework.test_framework ... |
import sublime_plugin
from .statusbar import StatusMessage
class ClassNavigatorBaseCmd(sublime_plugin.TextCommand):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.status = StatusMessage(sublime_view=self.view)
def save_start_position(self):
self.start_po... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
class TestEmployeeIncentive(unittest.TestCase):
pass |
"""
Copyright 2021 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... |
import time
from agbot.services.db_conn import engine, session
from agbot.services.orm import ENTResult, AETResult, BaseModel, Schedule, base
from aitu_data_extractors.site import (
get_aet_streams_links,
get_important_dates,
)
def create_ent_results():
print("ENT REULTS IS RUNNING")
ENTResult.trunca... |
"""Utilities
Some functions were taken from
https://github.com/SimpleJWT/django-rest-framework-simplejwt/blob/master/rest_framework_simplejwt/utils.py
"""
from calendar import timegm
from datetime import datetime
from django.conf import settings
from django.utils.timezone import is_naive, make_aware, utc
from django... |
"""
WSGI config for localsys project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETT... |
import FWCore.ParameterSet.Config as cms
# AlCaReco for muon based alignment using ZMuMu events
OutALCARECOMuAlZMuMu_noDrop = cms.PSet(
SelectEvents = cms.untracked.PSet(
SelectEvents = cms.vstring('pathALCARECOMuAlZMuMu')
),
outputCommands = cms.untracked.vstring(
'keep *_ALCARECOMuAlZMuMu... |
import json
import shlex
import urllib2
import logging
import os
# Mapping CloudFormation status codes to colors for Slack message attachments
# Status codes from http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-describing-stacks.html
STATUS_COLORS = {
'CREATE_COMPLETE': 'good',
'CREATE_... |
'''
Module definition for colab_gdrive
'''
import os
import sys
import logging
from pprint import pformat, pprint
import inspect
#import traceback
#PyDrive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
#google
from google.colab import auth
#oauth2client
from oauth2client.client import Google... |
from datetime import datetime
__author__ = 'zirony'
def takendate(tags):
if ('EXIF DateTimeOriginal' in tags) and (0 < len(tags['EXIF DateTimeOriginal'].values)):
taken = tags['EXIF DateTimeOriginal'].values
elif ('EXIF DateTimeDigitized' in tags) and (0 < len(tags['EXIF DateTimeDigitized'].values)):... |
"""
=====
Words
=====
Words/Ladder Graph
------------------
Generate an undirected graph over the 5757 5-letter words in the
datafile `words_dat.txt.gz`. Two words are connected by an edge
if they differ in one letter, resulting in 14,135 edges. This example
is described in Section 1.1 in Knuth's book (see [1]_ and [... |
# Copyright 2019 Alibaba Cloud 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 la... |
"""Generates template trees on a dataset."""
from ehreact.arguments import TrainArgs
from ehreact.train import train
if __name__ == '__main__':
args = TrainArgs().parse_args()
train(args) |
#!/usr/bin/env python3
#
# This file is part of LiteX-Boards.
#
# Copyright (c) 2021 Nathaniel Lewis <github@nrlewis.dev>
# SPDX-License-Identifier: BSD-2-Clause
# Testing build for HDMI
# - The main trouble with HDMI demos are that they require many SLICEMs, which are a very limited
# resource on the XC6SLX9. Many... |
from django.shortcuts import render
from django.core.paginator import Paginator
from django.http import HttpResponseNotFound
from .models import *
from .utils import get_page_uv, get_subscribe_sites, get_login_user, get_user_sub_feeds, set_user_read_article, \
get_similar_article
from .verify import verify_request
... |
from aiohttp import web
from crawler.forms.config import config_trafaret
from crawler.models.configs import insert_new_config, remove_config
from webapp.helpers import login_required, flash
@login_required
async def save_config(request):
app = request.app
router = app.router
logger = app['logger']
en... |
"""
Panel detection class
"""
import numpy as np
from tensorflow.keras import backend as K
from tensorflow.keras.preprocessing import image
from tensorflow.keras.models import load_model
import cv2
import matplotlib.pyplot as plt
from skimage.transform import hough_line, hough_line_peaks
from matplotlib import cm
impo... |
# Copyright 1999-2020 Alibaba Group Holding 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 a... |
# Copyright (c) 2006,2007,2008 Mitch Garnaat http://garnaat.org/
#
# 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 rights to use, copy,... |
N, K = (int(s) for s in input().split())
x, y = 1, 1
for k in range(1, K+1):
x *= (N-k+1)
y *= k
print(x // y) |
import tkinter
import time
class StopWatch(tkinter.Frame):
"""Simple stopwatch widget"""
def __init__(self, parent=None, **kw):
tkinter.Frame.__init__(self, parent, kw)
self._start = 0.0
self._elapsedtime = 0.0
self._running = 0
self.timestr = tkinter.StringVar... |
from collections import defaultdict
from typing import Union, List, Any, Callable, Dict
import numpy as np
from continual_learning.datasets.base import AbstractDataset, DatasetSplitsContainer
from continual_learning.scenarios.base import TasksGenerator
from continual_learning.scenarios.classification.new_classes imp... |
"""
WSGI config for api_app project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTI... |
################################################################################
# Copyright (c) 2021 ContinualAI. #
# Copyrights licensed under the MIT License. #
# See the accompanying LICENSE file for terms. ... |
import argparse
from dl_training.training import BaseTrainer
from dl_training.testing import OpenBHBTester
import torch
import logging
if __name__=="__main__":
logger = logging.getLogger("SMLvsDL")
parser = argparse.ArgumentParser()
# Data location + saving paths
parser.add_argument("--root", type=s... |
# 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
# "License"); you may not u... |
execfile('ex-3.02.py')
B = (3, 1)
D = (4 * dtype.extent, 0)
newtype = dtype.Create_hindexed(B, D)
dtype.Free()
newtype.Free() |
from django.contrib import admin
from . import models
def _register(model):
if not hasattr(model, 'Admin'):
return admin.site.register(m)
class RssantModelAdmin(admin.ModelAdmin):
if hasattr(model.Admin, 'display_fields'):
list_display = tuple(['id'] + model.Admin.display_fields)... |
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
from tensorflow.keras.callbacks import TensorBoard
import pickle, os, time
DATADIR="data/"
NAME="cachorros-gatos-cnn-128-128-128-{}".format(int(time.time... |
import pickle
def save_obj(obj, name ):
with open( name + '.pkl', 'wb') as f:
pickle.dump(obj, f, protocol=2)
def load_obj(name ):
with open( name + '.pkl', 'rb') as f:
return pickle.load(f)
acro = load_obj("acronymsDict")
# Spit out
# for a in acro.keys():
# print(a + " : " + acro[a])
ac... |
import tkinter as tk
from base import BaseBoard, BaseCard, CardFace, Deck
from Globals import BOARD_WIDTH, BOARD_HEIGHT, CARD_ROOT, MOVE_SPEED
CARD_X = 100
CARD_Y = 100
CARD_OFFSET_X = 90
CARD_OFFSET_Y = 30
SPACE_X = 90
SPACE_Y = 140
STOCK_X = BOARD_WIDTH - 100
STOCK_Y = CARD_Y + 50
ACEHOLDER_X = BOARD_WIDTH - 200
A... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""ooni-pipeline: * -> Analysis
Configured with /etc/analysis.conf
Runs as a system daemon but can also be used from command line in devel mode
Creates and updates unlogged tables.
Shows confirmed correlated by country, ASN, input URL over time.
Inputs: Database table... |
import sys
sys.path.append('../.')
from common.config import *
from methods.BlockMatchingOF import *
from common.Database import *
from methods.GaussianMethods import *
from common.extractPerformance import *
from common.metrics import *
from time import time
from methods.Farneback import *
from methods.LucasKanade im... |
#!/usr/bin/python3
from passlib.context import CryptContext
pwd_ctx = CryptContext(schemes=["bcrypt"], deprecated="auto")
class Hash:
@staticmethod
def bcrypt(password: str):
"""
Generate a bcrypt hashed password
Args:
password (str): The password to hash
Return... |
import requests
from bs4 import BeautifulSoup
from pymorphy2 import MorphAnalyzer
from collections import Counter
from re import split
from operator import itemgetter, attrgetter
from datetime import timedelta
import datetime
morph = MorphAnalyzer()
def isnoun(word):
return 'NOUN' in word.tag.grammemes
def pag... |
# -*- coding: UTF-8 -*-
import argparse
import os
import numpy as np
import time
import sys
import cv2
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
import torchvision
import torch.nn.functional as F
from utils.logger import setup_logger1 as logger
impo... |
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = dict()
for i, num in enumerate(nums):
if (target - num) in d:
return [d[target - num], i]
d[num] = i |
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. 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 requir... |
# Copyright (c) OpenMMLab. All rights reserved.
import copy
import os.path as osp
from collections import defaultdict
from pathlib import Path
from mmcv import scandir
from base_dataset import BaseDataset
IMG_EXTENSIONS = ('.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.ppm',
'.PPM', '.bmp', '.... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distrib... |
import numpy
import time
import math
from .ctng import constructive_neuronal_geometry
from .graphicsPrimitives import Sphere, Cone, Cylinder, SkewCone, Plane, Union, Intersection, SphereCone
from .GeneralizedVoxelization import voxelize
from .simplevolume_helper import simplevolume
from .surface_a import surface_area
... |
import logging
import operator
from .constants import DEBUG
from .undefined import Undefined, undefined
l = logging.getLogger(name=__name__)
class DataSet:
__slots__ = ('data', '_bits', '_mask')
"""
This class represents a set of data.
Addition and subtraction are performed on the cartesian produ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.