content stringlengths 5 1.05M |
|---|
#!/usr/bin/python3
# SPDX-License-Identifier: Apache-2.0
# Copyright © 2020 VMware, Inc.
import os
import sys
import subprocess
import time
import shutil
import configparser
import pytest
import collections
import unittest
networkd_unit_file_path = '/etc/systemd/network'
network_config_manager_ci_path = '/run/networ... |
from project.appliances.appliance import Appliance
class TV(Appliance):
def __init__(self):
self.cost = 1.5
super().__init__(self.cost)
|
# Copyright 2020 The TensorFlow Quantum 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 req... |
from importlib import import_module
from importlib import resources
PLUGINS = dict()
def register_plugin(func):
"""Decorator to register plug-ins"""
name = func.__name__
PLUGINS[name] = func
return func
def __getattr__(name):
"""Return a named plugin"""
try:
return PLUGINS[name]
e... |
# import os
# os.environ["KIVY_WINDOW"] = "sdl2"
# uncomment the above lines to run on raspberrypi like it runs on windows.
import kivy
kivy.require('1.9.1')
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from time import sleep, time
from random import randint
from functo... |
import torch
import unseal.transformers_util as tutil
from unseal.hooks import HookedModel
def test_load_model():
model, tokenizer, config = tutil.load_from_pretrained('gpt2')
assert model is not None
assert tokenizer is not None
assert config is not None
def test_load_model_with_dir():
model, tok... |
import cv2
from image_manipulation import binarize_image, grayscale_image
class Camera(object):
"""
Class to take pictures.
:param width_size: camera's image width
:type width_size: int
:param height_size: camera's image height
:type height_size: int
:param input_cam_device: p... |
#Passing a List
def greet(names):
for name in names:
msg=f"Hello, {name.title()}"
print(msg)
username=['alice','beerus','cyrus']
greet(username) |
# coding:utf-8
# log utils
"""
切记: 不要重复创造日志对象,否则会重复打印
"""
# import os
from logging import (
handlers,
getLogger,)
from logging import Formatter as LoggingFormatter
from logging import StreamHandler as LoggingStreamHandler
from logging import FileHandler as LoggingFileHandler
from logging import ERROR as LOGG... |
# Adapted from https://github.com/openai/triton/blob/master/python/triton/ops/blocksparse/softmax.py
import triton.language as tl
import triton
import torch
from src.models.attention.blocksparse_utils import sparsify_broadcast_tensor
def next_power_of_2(n):
n -= 1
n |= n >> 1
n |= n >> 2
n |= n >> 4
... |
import time
import rich
from hurry.filesize import size
from tabulate import tabulate
class Format:
def __init__(self):
pass
@staticmethod
def cli(**kwargs):
"""
Handle in coming CLI Output Style
"""
if "standard" in kwargs["style"]:
return Format._defa... |
#!/usr/bin/env python2.7
import os
import sys
sys.path.insert(0, os.path.realpath(os.path.join(__file__, '../../../lib')))
import exatest
from exatest.utils import chdir
from exatest import (
useData,
)
class TestParameterized(exatest.TestCase):
@useData((x,) for x in range(10))
def test_pa... |
import sys, getopt
import run
def main(argv):
path_database = ''
path_cnn_trained = ''
path_folder_retrieval = ''
feature_extraction_method = ''
distance = ''
searching_method = ''
number_of_images = 0
list_of_parameters = []
try:
opts, args = getopt.getopt(argv,"h... |
import sys
import torch
sys.path.insert(0, "../")
from linformer_pytorch import Linformer, Visualizer
model = Linformer(
input_size=512,
channels=16,
dim_k=128,
dim_ff=32,
nhead=4,
depth=3,
activation="relu",
checkpoint_level="C0",
parameter_shar... |
from typing import List
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
l, r = 0, len(nums) - 1
while l<=r:
m = (l+r)//2
if nums[m]==target:
return m
elif nums[m]>target:
r=m-1
... |
import heapq
import math
import numpy as np
import nltk.probability
from nltk.classify import SklearnClassifier
from sklearn.svm import SVC
import re
import sys
sys.path.insert(0, '..')
from definitions import *
sys.path.insert(0, '../Wrapper/')
from helper import *
def get_svm_classifier(parameters):
print "Loa... |
# 1-TASK. Matnlardan iborat ro'yxat qabul qilib, ro'yxatdagi har bir matnning birinchi
# harfini katta harfga o'zgatiruvchi funksiya yozing.
def katta_harf(ismlar):
names = []
for i in range(len(ismlar)):
ismlar[i] = ismlar[i].title()
ismlar = ['ali', 'vali', 'hasan', 'husan']
katta_harf(ismlar)
print(... |
import NNRequestHandler.Base
import NNRequestHandler.User
NN_REQUEST_CMD_USER_LOGIN = 1
class DispatchCenter(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(DispatchCenter, cls).__new__(
cls, *args... |
import unittest
from streamlink.plugins.canlitv import Canlitv, _m3u8_re
class TestPluginCanlitv(unittest.TestCase):
def test_m3u8_re(self):
def test_re(text):
m = _m3u8_re.search(text)
self.assertTrue(m and len(m.group("url")) > 0)
test_re('file: "test" ')
test_r... |
"""
Open Orchestrator Cloud Radio Access Network
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... |
from greent.rosetta import Rosetta
import json
from collections import defaultdict
def setup():
rosetta = Rosetta()
neodriver = rosetta.type_graph.driver;
return neodriver
def dumpem(dtype = 'gene'):
driver = setup()
cypher = f'MATCH (a:{dtype})-[r]-(b) return a,r,b'
with driver.session() as s... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
GeometryWrapper
A QGIS plugin
Converts geometry longitude from [-180,180] to [0,360]
-------------------
begin : 2017-03-16
... |
# Generated by Django 3.0.5 on 2020-04-06 15:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('shortner', '0002_auto_20200331_0717'),
]
operations = [
migrations.AlterModelOptions(
name='entry',
options={'verbose_name_p... |
from numpy import diff
def check_sorted(nu___):
di_ = diff(nu___.ravel())
return (di_ <= 0).all() or (0 <= di_).all()
|
'''VGG for CIFAR10. FC layers are removed.
(c) YANG, Wei
'''
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import math
import torch
__all__ = ['vgg19_bn_para']
class VGG(nn.Module):
def __init__(self, features, gpu_num = 2, num_classes=1000, split_size=64):
super(VGG, self).__init__()... |
# variants, kā importēt garākus nosaukumus
import mape.helper as helper
# importē konkrētu funkciju, tā it kā tā būtu lokāli definēta
#from helper import ievadiSkaitli
def main():
sk1 = helper.ievadiSkaitli()
sk2 = helper.ievadiSkaitli()
print("Ievadīto skaitļu summa ir", sk1 + sk2)
helper.pievienotF... |
import six
import time
from collections import defaultdict
import ujson as json
import pandas as pd
from oct.results.models import db, Result, Turret
class ReportResults(object):
"""Represent a report containing all tests results
:param int run_time: the run_time of the script
:param int interval: the ... |
# Code generated by `typeddictgen`. DO NOT EDIT.
"""V1SubjectRulesReviewStatusDict generated type."""
from typing import TypedDict, List
from kubernetes_typed.client import V1NonResourceRuleDict, V1ResourceRuleDict
V1SubjectRulesReviewStatusDict = TypedDict(
"V1SubjectRulesReviewStatusDict",
{
"evalua... |
# Copyright 2021 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
import os
from abc import abstractmethod
from collections import defaultdict
import PIL
import cv2
import math
import numpy as np
import sldc
import torch
from PIL import Image
from cytomine.models import Annotation
from rasterio.features import rasterize
from shapely import wkt
from shapely.affinity import translate,... |
#
# Copyright (c) 2019 UCT Prague.
#
# ec5cbec43ec8_initial_layout.py is part of Invenio Explicit ACLs
# (see https://github.com/oarepo/invenio-explicit-acls).
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to d... |
from language_learner_env import secret_settings
import learner
app = learner.App(secret_settings)
app.listen()
|
from maya import cmds as mc
from maya.api import OpenMaya as om
from dcc.maya.libs import transformutils
from . import transformmixin
import logging
logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
class ConstraintMixin(transformmixin.TransformMixin):
"""
Overload of Transf... |
# encoding=utf8
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys
sys.path.append('../')
# End of fix
import numpy as np
from NiaPy.task import StoppingTask, OptimizationType
from NiaPy.algorithms import BasicStatistics
from NiaPy.algorithms.b... |
# Copyright (c) 2014-2017, iocage
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted providing that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and th... |
"""Anvil is a tool for automating the rigging process in a given DCC."""
from six import itervalues
import config
import utils
import colors
import meta_data
import log
import version
import interfaces
import runtime
import objects
import grouping
import node_types
import sub_rig_templates
import rig_templates
class ... |
import numpy as np
import pandas as pd
import os
from transformers import AutoModel
from inference_schema.schema_decorators import input_schema, output_schema
from inference_schema.parameter_types.pandas_parameter_type import PandasParameterType
from inference_schema.parameter_types.numpy_parameter_type import NumpyP... |
#!/usr/bin/env python3
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BAS... |
####################################################################################################
# ------------------------------------------------------------------------------------------------ #
# Functions for handling pool presence table analysis
# -------------------------------------------------------------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import os
def join_images(images):
rows = len(images[0])
cols = len(images[0][0])
final_image = np.zeros((rows, cols, 1), np.uint8)
print(len(images))
for img in images:
for row in range(0, len(final_image)):
... |
_mod_txt = """
NEURON {
POINT_PROCESS ExpSynMorphforge
RANGE tau, e, i
NONSPECIFIC_CURRENT i
RANGE peak_conductance
}
UNITS {
(nA) = (nanoamp)
(mV) = (millivolt)
(uS) = (microsiemens)
}
PARAMETER {
tau = 0.1 (ms) <1e-9,1e9>
e = 0 (mV)
peak_conductance = -100000 ()
}
ASSIGNED {
v (mV)
i (nA)
... |
##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
# Copyright 2018 Braxton Mckee
#
# 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 t... |
#!/usr/bin/env python
"""
read ntuple produced by Truth_JETMET...
make some validation plots
"""
import ROOT
ROOT.gROOT.SetBatch()
from optparse import OptionParser
def make_plots(file_name, post_fix):
import AtlasStyle
f1 = ROOT.TFile.Open(file_name)
tree = f1.Get("physics")
h_m4l = ROOT.TH1F("h_m4l... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os
cd=os.path.join('LinearRegression','Kidem_ve_Maas_VeriSeti.csv')
dataset = pd.read_csv(cd)
print(dataset.describe())
x=dataset.iloc[:,:-1].values
y=dataset.iloc[:,1].values
from sklearn.cross_validation import train_test_split
x_train,... |
#__BEGIN_LICENSE__
# Copyright (c) 2015, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All rights reserved.
#
# The xGDS platform is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance ... |
__author__ = 'Jeremy'
|
#!/bin/false python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 The SymbiFlow Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
import os
import shutil
from BaseRunner import ... |
class Solution:
def intToRoman(self, num):
def get_representation(num):
symbol_table={
1:"I",
5:"V",
10:"X",
50:"L",
100:"C",
500:"D",
1000 :"M",
}
if num ... |
#py_gui.py
"gui basics"
from tkinter import *
class Application(Frame):
pass
root = Tk()
app = Application(master=root)
app.mainloop()
|
'''
There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for yo... |
"""This acts as a kind of middleware - which has now been whittled down to only providing
logging information"""
import logging
import platform
from .constants import NameSpace
from .config import CLIInputs, ParsedArgs
from .utils import read_sdk_version
logger = logging.getLogger("validate-cli-args")
class Validat... |
# unet.py
#
from __future__ import division
import torch.nn as nn
import torch.nn.functional as F
import torch
from numpy.linalg import svd
from numpy.random import normal
from math import sqrt
class UNet(nn.Module):
def __init__(self, colordim = 1):
super(UNet, self).__init__()
self.conv1_1 = nn.Conv2d(colord... |
# First, we import a tool to allow text to pop up on a plot when the cursor
# hovers over it. Also, we import a data structure used to store arguments
# of what to plot in Bokeh. Finally, we will use numpy for this section as well!
from bokeh.models import HoverTool, ColumnDataSource
from bokeh.plotting import figur... |
from typing import Literal, Optional, Union
class Trust_Region_Options:
border_abstol: float = 1e-10
tol_step: float = 1.0e-10
tol_grad: float = 1.0e-6
abstol_fval: Optional[float] = None
max_stall_iter: Optional[int] = None
init_delta: float = 1.0
max_iter: int
check_rel: float = 1.0e... |
import sqlite3
import os
import MLBProjections.MLBProjections.DB.MLB as MLB
import MLBProjections.MLBProjections.Environ as ENV
from pprint import pprint
################################################################################
################################################################################
... |
#
# Functional Python: The Lambda Lambada (Recursion)
# Python Techdegree
#
# Created by Dulio Denis on 3/22/19.
# Copyright (c) 2019 ddApps. All rights reserved.
# ------------------------------------------------
# Recursion Challenge
# ------------------------------------------------
# Challenge Task 1 of 1
# ... |
#!/usr/bin/env python
import os
import random
import requests
import subprocess
import argparse
import datetime
import time
import sys
"""Based off https://github.com/fogleman/primitive/blob/master/bot/main.py
"""
with open(os.path.expanduser('~/.flickr_api_key'), 'r') as key_file:
FLICKR_API_KEY = key_file.read... |
import multiprocessing as mp
import time
def foo_pool(taskQ, x):
print(x)
taskQ.put(x)
return x*x
result_list = []
def log_result(result):
# This is called whenever foo_pool(i) returns a result.
# result_list is modified only by the main process, not the pool workers.
result_list.append(result... |
# Crie um script Python que leia o nome de uma pessoa e mostre uma mensagem de boas-vindas de acordo com o valor digitado
msg = 'Olá Mundo!'
print(msg) |
import ldap
import json
import socket
from urllib.parse import urlparse
def create_from_env():
import os
auth = LdapAuth(os.environ.get('LDAP_ADDRESS'))
auth.base_dn = os.environ.get('LDAP_BASE_DN')
auth.bind_dn = os.environ.get('LDAP_BIND_DN')
auth.bind_pass = os.environ.get('LDAP_BIND_PASS')
... |
# %% coding=utf-8
import pandas as pd
from atm import ATM
from sklearn.model_selection import train_test_split
beauty_data = pd.read_csv('/data/face/df_input.csv')
select_cols = ['Image', 'label', '0_10_x', '0_10_y', '0_11_x', '0_11_y', '0_12_x', '0_12_y', '0_13_x', '0_13_y',
'0_14_x', '0_14_y', '0_15_x... |
from .descriptor import DescriptorType
from .object_type import ObjectDict
__all__ = ["ObjectDict", "DescriptorType"]
|
from typing import List
class Solution:
# 141, 逆波兰表达式求值, Medium
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for token in tokens:
if token == "+":
oprand2 = stack.pop()
oprand1 = stack.pop()
stack.append(oprand1 +... |
# we are here to get weighted-5-node-subgraph,
# given edge-count/bi-edge-count/strong-tie-count/weak-tie-count only to distinguish
# to leverage on weighte 4 node subgraphs(edge_count, biedge_count, strong_count, weak_count, subNo)
# next to share not edge
import re,sys,random, os
def subg(edges,s4,lf,sf,sfv,ror):
... |
#!/usr/bin/env python
from distutils.core import setup
setup(name="Eng Phys Office Space Tools",
description="A set of scripts to work with the Eng Phys office space committee",
version="0.1dev",
author="Tim van Boxtel",
author_email="vanboxtj@mcmaster.ca",
py_modules=['parse-grad-studen... |
import tweepy #https://github.com/tweepy/tweepy
import csv
import pandas as pd
# Used for progress bar
import time
import sys
#Twitter API credentials
consumer_key = "NBNgPGCBeGv80PcsYU3QWU94d"
consumer_secret = "lvAaoSInlF9mPonoMMldFq5ZE96oAAl30TLh6ynVwK2tauvOQC"
access_key = "1311728151265832961-AaFHXfZtozEgfoVZoFnN... |
#Pygments Tk Text from http://code.google.com/p/pygments-tk-text/
#Original Developer: Jonathon Eunice: jonathan.eunice@gmail.com
__author__ = 'Robert Cope'
__original__author__ = 'Jonathan Eunice'
|
import random
def generatePassword(pwlength):
alphabet = "abcdefghijklmnopqrstuvwxyz"
passwords = []
for i in pwlength:
password = ""
for j in range(i):
next_letter_index = random.randrange(len(alphabet))
password = password + alphabet[next... |
GAME_SIZE = 4
SCORE_TO_WIN1 = 512
SCORE_TO_WIN2 = 1024
SCORE_TO_WIN3 = 2048
SCORE_TO_WIN0 = 256
from game2048.game import Game
from game2048.agents import ExpectiMaxAgent
# save the dataset
f1 = open("dataset_256_3.txt", "w")
f2 = open("dataset_512_3.txt", "w")
f3 = open("dataset_1024_3.txt", "w")
# for i in range(1... |
"""
####################################################################################################
# Copyright Info : Copyright (c) Davar Lab @ Hikvision Research Institute. All rights reserved.
# Filename : embedding.py
# Abstract : torch.nn.Embedding function encapsulation.
# Current Versi... |
from tweepy import Stream
from stream_tweets import StockListener
import get_old_tweets
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
def getTweets(stock_name):
twitter_stream = Stream(get_old_tweets.auth, StockListener(stock_name))
twitter_stream.filter(track=[... |
from painter.config import NAME, PATH, SHELVES
from templates import app
# Painter base
PAINTER = app.App(NAME, PATH, SHELVES)
|
"""Various lower-level functions to support the computation of steady states"""
import warnings
import numpy as np
import scipy.optimize as opt
from numbers import Real
from functools import partial
from ...utilities import misc, solvers
def instantiate_steady_state_mutable_kwargs(dissolve, block_kwargs, solver_kwa... |
from django.db import models
from .book import Book
from .language import Language
class BookLanguage(models.Model):
id = models.AutoField(
primary_key=True,
editable=False)
book = models.ForeignKey(
Book,
db_column='book_id',
blank=False, null=False,
on_delet... |
from __future__ import absolute_import, unicode_literals
from appearance.classes import Icon
icon_acl_list = Icon(driver_name='fontawesome', symbol='lock')
|
#!/usr/bin/env/python3
import os
import sys
import typing
THIS_SCRIPT_DIR = sys.path[0]
INCLUDE_DIR = THIS_SCRIPT_DIR + "/../src/include/cleantype/"
ALL_IN_ONE_FILE = THIS_SCRIPT_DIR + "/include/cleantype/cleantype.hpp"
MAIN_TITLE = """
// CleanType : amalgamated version
//
// This file is part of CleanType: Clean T... |
import datetime
from bs4 import BeautifulSoup
from kik_unofficial.utilities.cryptographic_utilities import CryptographicUtils
from kik_unofficial.datatypes.xmpp.base_elements import XMPPElement, XMPPResponse
class GetMyProfileRequest(XMPPElement):
def __init__(self):
super().__init__()
def seriali... |
import sys
sys.path.append('../../../')
import unittest
import numpy as np
from spiketag.base import ProbeFactory
class TestProbe(unittest.TestCase):
def test_linear_probe(self):
linear_probe = ProbeFactory.genLinearProbe(25e3, 32)
expected_type = 'linear'
expected_n_group = ... |
"""{{cookiecutter.project_description}}"""
import logging
from {{cookiecutter.package_name}}.wsgi import ApplicationLoader
from {{cookiecutter.package_name}}.version import __version__ # noqa: F401
# initialize logging
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : Mar-27-21 01:06
# @Author : Kan HUANG (kan.huang@connect.ust.hk)
# @RefLink : https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html
from __future__ import unicode_literals, print_function, division
import os
import random
import s... |
from . import db
from flask.ext.login import UserMixin, AnonymousUserMixin
from datetime import datetime
class ScrapeCount(db.Model):
__tablename__ = 'scrapecounts'
id = db.Column(db.Integer, primary_key=True)
websitename = db.Column(db.String(200))
count = db.Column(db.Integer)
date = db.Column(d... |
import json
import torchvision
import data as data_module
from examples.NIPS.generate_data_utils import gather_examples
import pandas as pd
preprocessable = pd.read_pickle('/home/roigvilamalam/projects/Urban-Sound-Classification/preprocessable.pkl')
preprocessable = preprocessable[preprocessable['preprocessable']]
... |
from flask import Flask, render_template, url_for, request, redirect, g, jsonify, flash, session, Markup
from bs4 import BeautifulSoup
from pymongo import *
from functools import wraps
from datetime import datetime
import requests
import csv
import boto3
import ckapi
import validation
from settings import *
# FLASK CO... |
# @Author: Leeroy P. Williams
# @Date: 29/09/19
# @Problem: If we list all the natural numbers below 10 that are
# multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000
# @Solution: Correct
def multi(a, b, array):
... |
# -*- coding: utf-8 -*-
"""
===============================================================================
Trajectory class for MD simulations (:mod:`sknano.core.atoms._trajectory`)
===============================================================================
Classes for analyzing the atom trajectories of molecular... |
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import redirect, render, get_object_or_404
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from ranbo.forms import *
from django.core.exc... |
import nltk, re, pprint
from urllib.request import urlopen
url = "http://nrs-projects.humboldt.edu/~st10/s20cs328/328lect15-1/328lect15-1-projected_txt.html"
raw = urlopen(url).read()
print(type(raw))
print(len(raw))
#natural language string
nls = nltk.clean_html(raw)
tokens = nltk.word_tokenize(raw)
print(tokens)
|
import os
from setuptools import (
setup,
find_packages
)
curr_dir = os.path.dirname(os.path.abspath(__file__))
install_requirements = [
"pydantic>=1.8",
"cryptography>=3.4"
]
setup(
name="restless",
version="0.0.1-dev",
description="Just an easy-to-use cryptographic Python module",
long_description=... |
from django.apps import apps
from rest_framework import serializers
from common.constants import models
Profile = apps.get_model(models.PROFILE_MODEL)
User = apps.get_model(models.USER_MODEL)
class ProfileSerializer(serializers.ModelSerializer):
"""
API serializer for :class:`Profile`.
"""
class Me... |
# -*- coding: UTF-8 -*-
# @Author : Chenyang Wang
# @Email : THUwangcy@gmail.com
""" Caser
Reference:
"Personalized Top-N Sequential Recommendation via Convolutional Sequence Embedding"
Jiaxi Tang et al., WSDM'2018.
Reference code:
https://github.com/graytowne/caser_pytorch
Note:
We use a maximum of... |
from pseudo_python.builtin_typed_api import builtin_type_check
from pseudo_python.errors import PseudoPythonTypeCheckError
class Standard:
'''
Standard classes should respond to expand and to return
valid nodes on expand
'''
pass
class StandardCall(Standard):
'''
converts to a standard cal... |
import tensorflow as tf
def MaxAvgPooling2D(m,n, model):
max = tf.keras.layers.MaxPool2D(pool_size=(2,2), strides=1, padding='SAME')(model)
avg = tf.keras.layers.AveragePooling2D(pool_size=(2,2), strides=1, padding='SAME')(model)
model = (max*m + avg*n)/(m+n)
return model
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Preprocessing ZTF database to be saved as a samplesx21x21x3 numpy array in a pickle
TODO: clean_NaN once cropped
TODO: unit tests
ToDo: instead of cascade implement as pipeline, in order to have single call and definition
ToDo: smart way to shut down nans
@author: as... |
import base64
import random
from django.conf import settings
from django.core.cache import caches
from django.core.mail import send_mail
from apps.user.models import User
from libs.yuntongxun.sms import CCP
from meiduoshop.celery import app
@app.task
def async_send_sms(to, datas, template_id):
"""异步发送短信验证码 注意结果... |
import os
from typing import Dict, List, Optional, Union, Callable
from tinydb.storages import MemoryStorage, JSONStorage
from ..custom_typings import DataDict, PathType
class BaseDB(JSONStorage, MemoryStorage):
"""Base storage class that reads which extensions are available to feed the
path handling functio... |
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use ... |
"""
utility functions
"""
import collections
def flatten(d, parent_key="", sep="_"):
"""
flatten nested dictionary, preserving lists
Arguments:
parent_key (str):
sep (str):
"""
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
... |
import tensorflow as tf
import datetime as dt
import pandas as pd
import os
def load_data():
col_names = [
'id', 'event_timestamp', 'course_over_ground', 'machine_id',
'vehicle_weight_type', 'speed_gps_kph', 'latitude', 'longitude']
data = pd.DataFrame(columns=col_names)
files = os.listd... |
from jenkinsapi.jenkins import Jenkins
import xml.etree.ElementTree as ET
J = Jenkins('http://localhost:8080')
EMPTY_JOB_CONFIG = '''
<?xml version='1.0' encoding='UTF-8'?>
<project>
<actions>jkkjjk</actions>
<description></description>
<keepDependencies>false</keepDependencies>
<properties/>
<scm class="hud... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.