content stringlengths 5 1.05M |
|---|
import os
from grizzly.encoders import numpy_to_weld_type
import numpy_weld as npw
from lazy_result import LazyResult, weld_subset
from pandas_weld.core.utils import get_expression_or_raw, get_weld_type, get_weld_info, \
replace_slice_defaults
from pandas_weld.weld import weld_filter, weld_unique, weld_index_to_va... |
import string
from ciphers.VigenereCipher import VigenereCipher
from crackers.ExtendableStringKeyCracker import ExtendableStringKeyCracker
class VigenereCracker(ExtendableStringKeyCracker):
def __init__(self, alphabet=string.ascii_uppercase, restart_threshold=500, iterations=100, max_key_len=20):
super()... |
"""
Created on Nov 07 15:37 2019
@author: nishit
"""
import datetime
import json
import threading
import os
import numpy as np
from senml import senml
from IO.ConfigParserUtils import ConfigParserUtils
from IO.dataPublisher import DataPublisher
from IO.redisDB import RedisDB
from prediction.predictionDataManager im... |
# Generated by Django 3.1.1 on 2020-09-22 15:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('page', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Feed',
fields=[
('id', models... |
"""
FCP API in Python created by James Axl 2018
For FCP documentation, see https://wiki.freenetproject.org/FCPv2 still under construction
"""
try:
from Fcp.Node import Node
except ModuleNotFoundError:
raise ModuleNotFoundError('Fcp module is required')
try:
import magic
except ModuleNotFoundError:
ra... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Reference https://ebisuke33.hatenablog.com/entry/abc197c
def main():
N = int(input())
array = list(map(int,input().split()))
ans = 10**9+7
if N==1:
print(array[0])
exit()
for i in range(2**(N-1)):
base = 0
or_value = ar... |
from ..common.config import AppConfigReader
class MotdConstants(object):
MODULE = "motd"
class MotdConfig(object):
_config = AppConfigReader.read(MotdConstants.MODULE)
MOTD_ICAL_URL = _config['preferences']['ical_url']
REQUEST_TIMEOUT = int(_config['preferences'].get('request_timeout_seconds', '15'... |
# Copyright 2021 Research Institute of Systems Planning, 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 applica... |
import os
class Payload:
def __init__(self, lhost, lport, filename):
self.lhost = lhost
self.lport = lport
self.filename = filename
def create_payload(self, compile=False):
with open("payload_templates/python_backdoor_base.py", "r") as base:
base_content = base.read... |
#!/usr/bin/env python
# wificonfig.py
# Copyright (C) ContinuumBridge Limited, 2013-2015
# Written by Peter Claydon
#
import sys
import time
import os
import json
import logging
from pprint import pprint
from twisted.internet import reactor
from twisted.application.internet import TCPServer
from twisted.application.ser... |
# -*- coding: utf-8 -*-
__author__ = """Morten Enemark Lund"""
__email__ = 'mel@anybodytech.com'
__version__ = '0.1.0'
from .matplusc3d import combine_files |
import secrets
import string
from hacksport.problem import ProtectedFile, Remote
from hacksport.deploy import flag_fmt
class Problem(Remote):
program_name = "ecb.py"
files = [ProtectedFile("flag"), ProtectedFile("key")]
def initialize(self):
# generate random 32 hexadecimal characters
se... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
''' Title '''
__author__ = 'Hiroshi Kajino <KAJINO@jp.ibm.com>'
__copyright__ = 'Copyright IBM Corp. 2020, 2021'
import torch
def is_2d_tensor(x_tensor):
return isinstance(x_tensor, torch.Tensor) and len(x_tensor.shape) == 2
def is_n_d_tensor(x_tensor, n_dim):
r... |
# Generated by Django 2.2.8 on 2019-12-14 14:43
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('game', '0002_game'),
]
operations = [
migrations.RemoveField(
model_name='game',
name='away_team_errors',
),
... |
import logging
from pathlib import Path
def get_logger(name: str) -> logging.Logger:
""" Gets a logger for the given file. Sets a nice default format.
TODO: figure out if we should add handlers, etc.
"""
try:
p = Path(name)
if p.exists():
name =... |
sequencelength = 0
num = 0
for i in range(1000, 1, -1):
if sequencelength >= i:
break
foundRemainders = [0 for x in range(i)]
value = 1
position = 0
while foundRemainders[value] == 0 and value != 0:
foundRemainders[value] = position
value *= 10
value %= i
position += 1
... |
import os
import argparse
from os.path import expanduser
import numpy as np
import configparser
import shutil
def get_file_names(dataset_path):
"""
get_file_names(str) -> list of HGG files , LGG files
It return the paths of the LGG and HGG files present in BraTS dataset
"""
lgg_dir = []
hgg_... |
from nmigen import *
from nmigen.asserts import *
from nmigen.hdl.ast import *
from nmigen.back import pysim
class EmbeddedThing(object):
def __init__(self):
self.thing = Signal(16)
def ports(self):
ps = [self.thing]
|
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import * # NOQA
from .blockette import Blockette
from ..fields import FixedString, Float, Integer, Loop, VariableString
from ..utils import lookup_code, format_resp... |
from __future__ import unicode_literals
import warnings
from django.apps.registry import Apps
from django.core.exceptions import ValidationError
from django.test import SimpleTestCase
from mutant.contrib.numeric.models import IntegerFieldDefinition
from mutant.contrib.text.models import CharFieldDefinition
from muta... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'han modified by @indonoso'
import argparse
import json
import logging
import os
import torch
import torch.optim as optim
from tqdm import tqdm
from machine_comprehension.dataset.squad_dataset import SquadDataset
from machine_comprehension.models.loss impor... |
"""
link: https://leetcode-cn.com/problems/minimum-moves-to-equal-array-elements-ii
problem: 定义一次操作为对数组任意元素 +1 或 -1,问至少多少次元素后数组所有元素相等
solution: 相等元素为数组中位数
"""
class Solution:
def minMoves2(self, nums: List[int]) -> int:
if not nums:
return 0
nums.sort()
n, res = len(nums), 0
... |
import json
res = json.loads('{"data":[{"timestamp":"2022-01-05T23:17:00.000000Z","hash":"loa3DCjClW2ZUbZNehtdWQuMB7y4ClUXUfTWgAtWl94","gateway":"11u4XLetGNzvkDDe15F74kWzK8Y2eFac1c6bLBtQhkdQzM8RxYp","block":1167694,"amount":183213,"account":"14Rqw67Er4T4mDitRR5hkvDbefXUhVQGiaVV4yzgSF3sVtu6PfU"},{"timestamp":"2022-01-0... |
#!/usr/bin/env python3
# coding=utf-8
#
# Copyright (c) 2020 Huawei Device 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... |
"""
Monkey patches (paramiko support)
"""
import logging
log = logging.getLogger(__name__)
def patch_001_paramiko_deprecation():
"""
Silence an an unhelpful Deprecation Warning triggered by Paramiko.
Not strictly a monkeypatch.
"""
import warnings
warnings.filterwarnings(
category=Dep... |
CONFIG = {
'file_gdb': 'curb_geocoder.gdb',
'input': {
'address_pt': 'ADDRESS_CURB_20141105',
'address_fields': {
'address_id': 'OBJECTID',
'address_full': 'ADDRESS_ID',
'poly_id': 'OBJECTID_1',
},
'streets_lin': 'STREETS_LIN',
'streets_fields': {
'street_name': 'STNAME',
'left_from': 'L_F_... |
"""
Data augmentation with synonyms. A number of adjectives in each text are replaced with some synonyms.
The synonyms are collected by scraping website www.thesaurus.com.
Written by Shira Weissman
"""
import spacy
import json
import pandas as pd
import numpy as np
import requests
from bs4 import BeautifulSoup
import... |
import numpy as np
import matplotlib.pyplot as plt
import time
import glob
from rlkit.misc.asset_loader import load_local_or_remote_file
from skimage import data, color
from skimage.transform import rescale, resize, downscale_local_mean
import cv2
import rlkit.torch.pytorch_util as ptu
def crop(img):
img = resize... |
import math
import random
import numpy as np
import matplotlib.pyplot as plt
from hmm_class import HMM
def hmm04():
n = 200
sigma = 0.7
sample_num = 10
hmm_buf = [HMM(n, sigma, 0.99, 0.97) for i in range(10)]
x_transition = np.empty(sample_num)
#10通りつくる
for i in range(sampl... |
class TrafficStats(object):
"""Represents traffic statistics information for a given interface."""
def __init__(self, bytes_recv, bytes_sent, packets_recv, packets_sent):
self._bytes_recv = bytes_recv
self._bytes_sent = bytes_sent
self._packets_recv = packets_recv
self._packets_... |
import numpy as np
from . import gaussianprocess as gp
import matplotlib.pyplot as plt
#####
def findsmoothvariance(y, filtsig= 0.1, nopts= False):
'''
Estimates and then smooths the variance over replicates of data
Arguments
--
y: data - one column for each replicate
filtsig: sets the size of... |
#-*- coding: utf8 -*-
from flexmock import FlexMock
from flexmock import AlreadyMocked
from flexmock import AndExecuteNotSupportedForClassMocks
from flexmock import AttemptingToMockBuiltin
from flexmock import Expectation
from flexmock import FlexmockContainer
from flexmock import FlexmockException
from flexmock import... |
import json
import requests
import pandas as pd
token = 'c511d32b578b4ec19c3d43c1a3fffb4cad5dc4d2'
api_base = 'https://www.renewables.ninja/api/'
s = requests.session()
# Send token header with each request
s.headers = {'Authorization': 'Token ' + token}
##
# Wind example
##
url = api_base + 'data/wind'
args = {
... |
"""
Recurrent neural network output
"""
import jax
import jax.numpy as np
import jax.experimental.stax as stax
import ctsb
from ctsb.utils.random import generate_key
class RNN_Output(ctsb.Problem):
"""
Produces outputs from a randomly initialized recurrent neural network.
"""
def __init__(self):
... |
# Authors:
# Christian F. Baumgartner (c.f.baumgartner@gmail.com)
# Lisa M. Koch (lisa.margret.koch@gmail.com)
import os
import numpy as np
import logging
import gc
import h5py
from skimage import transform
import math
import utils
import image_utils
import pandas as pd
from sklearn.model_selection import train_test... |
import numpy as np
def calculate_feature_importance_rf(clf):
"""
calculate tree classifier feature importance
Parameters:
argument 1 (model): model object
Return
standard deviation of feature importance, feature indices, mean importance score of all the trees
"""
importances = clf.fea... |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.auth',
'user_streams',
'user_streams.backends.user_streams_single_table_backend',
'user_streams.backends.user_stream... |
from db import db
from models.base_model import BaseModel
from nobiru.nobiru_list import NobiruList
from utils.time import Time
class EmergencyContactModel(BaseModel):
__tablename__ = "emergency_contacts"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False, unique... |
"""Module `diameter_learning.app`
"""
from .datasets import CarotidChallengeDataset
|
import copy
configs = dict()
config = dict(
agent=dict(),
algo=dict(
discount=0.99,
learning_rate=3e-4,
clip_grad_norm=1e6,
entropy_loss_coeff=0.0,
gae_lambda=0.95,
minibatches=32,
epochs=10,
ratio_clip=0.2,
normalize_advantage=True,
... |
# encoding=utf-8
__author__ = 'lance'
import json
import uuid
import time
import tornado.gen
from tornado.options import options
from tornado.httputil import url_concat
from tornado.httpclient import AsyncHTTPClient
from tornado.log import access_log as logger
from base import BaseHandler
from oauth_handler.oauth im... |
import re
import pytest
from fastapi import Response
from fastapi_users.authentication.cookie import CookieAuthentication
from fastapi_users.jwt import SecretType, decode_jwt, generate_jwt
LIFETIME = 3600
COOKIE_NAME = "COOKIE_NAME"
@pytest.fixture(
params=[
("/", None, True, True),
("/arthur",... |
from __future__ import unicode_literals, print_function
import spacy.en
import spacy.matcher
from spacy.attrs import ORTH, TAG, LOWER, IS_ALPHA, FLAG63
import plac
def main():
nlp = spacy.en.English()
example = u"I prefer Siri to Google Now. I'll google now to find out how the google now service works."
... |
from bs4 import BeautifulSoup
import requests
import time
def timeParser(wait_time):
if wait_time == 'Instant' or wait_time == 'No Minimum':
wait_time = None
elif 'minutes' in wait_time:
if '60' in wait_time:
wait_time = time.gmtime(60 * 60)
else:
wait_time = tim... |
# Copyright (C) 2017-2021 by Ivan.
# This file is part of BaseN package.
# BaseN is released under the MIT License (see LICENSE).
import string
from os.path import join, dirname
from basen import BaseN
FULL_ALPHABET = string.ascii_letters + string.digits
BINARY_ALPHABET = '01'
DATA = b"This is a test post, please i... |
# 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... |
import os
import sys
import matplotlib
matplotlib.use('Agg')
from sdirl.experiments import *
from sdirl.model import *
from sdirl.gridworld.model import GridWorldFactory
from sdirl.elfi_utils import BolfiParams
from sdirl.rl.simulator import RLParams
import logging
logger = logging.getLogger(__name__)
def get_model... |
import sys
import logging
import threading
from threaded_exception import RunsInAThread
logger = logging.getLogger(__name__)
logging.basicConfig(filename='simple.log', filemode='w', level=logging.DEBUG)
logger.debug("This is an debug message")
logger.info("This is an info message")
logger.warning("This is an warning... |
#!/usr/bin/python
import os
import sys
import time
import difflib
from os import path
from datetime import datetime
from support.support_variables import AUTO_WELCOME_TEXT, BACKUPS_DIR, CONTRIB_THEMES, DESIRED_AUTO_VER, EXCLUDED_THEMES, IS_AUTO_INSTALL
from support.support_variables import MIN_SIM_THRESHOLD, RESTORE_WE... |
def __main__():
f = open("in.txt", 'r')
o = open("out.txt", 'w')
noOfCases = int(f.readline())
for testNo in range(noOfCases):
counter = 0
data = f.readline().split()
output = solver()
o.write("Case #" + str(testNo + 1) + ": " + str(output) + "\n")
def solver():
r... |
#!/usr/bin/env python
import sys
import re
import numpy as np
import click
from Bio import SeqIO
from flea.util import run_regexp, iter_sample, is_in_frame
from flea.util import parse_copynumbers
from flea.util import handle_codon, replace_stop_codons, replace_gapped_codons
from flea.util import update_record_seq
... |
from rest_framework import serializers
from RestapiManage.restapi.models import Project, Url
class ManyProject(serializers.ModelSerializer):
class Meta:
model = Project
fields = '__all__'
class ManyUrl(serializers.ModelSerializer):
class Meta:
model = Url
fields = '__all__'
|
from .test_server import TestServer
from unittest import TestCase
from tempfile import NamedTemporaryFile
from pathlib import Path
from may import open_may
TESTDATA = "test text."
class TestUploadAndDownload (TestCase):
def test_upload_and_download(self):
with TestServer():
with open_may("l... |
import tensorflow as tf
class MaxAggregation(tf.keras.layers.Layer):
def call(self, inputs, training=None):
"""Runs max aggregation
Parameters
----------
inputs : dict
"value" : tf.Tensor, shape (B, N, F)
"mask" : tf.Tensor, shape (B, N) | None
Returns... |
import streamlit as st
from utils import predict
import os
from PIL import Image
ENDPOINT_NAME = 'sagemaker-pytorch-2021-09-07-01-28-53-421'
BUCKET = 'gan-data'
#ENDPOINT_NAME = os.environ['ENDPOINT_NAME']
#BUCKET = os.environ['BUCKET']
def main():
st.title("Cartoonize your images in seconds !!")
uploaded_f... |
import os
import tensorflow as tf
import source.layers as lay
class CNN(object):
def __init__(self, height, width, channel, num_class, ksize, learning_rate=1e-3, ckpt_dir='./Checkpoint'):
print("\nInitializing Short-ReXNet...")
self.height, self.width, self.channel, self.num_class = height, width... |
from __future__ import absolute_import
# Copyright (c) 2010-2014 openpyxl
#
# 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 u... |
"""
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import copy
import random
import warnings
import numpy as np
import skorch
import torch
from skorch.callbacks import Callback
from dib.util... |
#!/usr/bin/env python
# Lint as: python3
"""This module contains tests for flows-related API handlers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import io
import os
import tarfile
import zipfile
from absl import app
import yaml
from grr_response... |
#django
from django import forms
#models
from posts.models import Post
class PostForm(forms.ModelForm):
"""post model form"""
class Meta:
"""form settings"""
model=Post
fields=('user', 'profile','title','photo')
|
# -*- coding: utf-8 -*-
import re
import scrapy
import json
from locations.items import GeojsonPointItem
class StopAndShopSpider(scrapy.Spider):
#download_delay = 0.2
name = "stop_and_shop"
item_attributes = {'brand': "Stop and Shop"}
allowed_domains = ["stopandshop.com"]
start_urls = (
'... |
from _helper import screenshot
from _mock_data.url import internal_url
from py.path import local
from browserist import Browser
CUSTOM_SCREENSHOT_DIRECTORY = "screenshot"
CUSTOM_SCREENSHOT_FILENAME = "screenshot.png"
def test_get_screenshot_1(browser_headless_screenshot: Browser, tmpdir: local) -> None:
"""Test... |
import os
import yaml
from .test_utils import (
CliShedTestCase,
TEST_REPOS_DIR,
)
TEST_WORKFLOW_PATH = os.path.join(
TEST_REPOS_DIR,
"workflow_1",
"blast_top_hit_species.ga"
)
class ShedInitTestCase(CliShedTestCase):
def test_minimal(self):
with self._isolate() as f:
s... |
print({'one': 1, 'two': 2, 'three': 3}.items())
|
#!/usr/bin/env python3
# Licensed under the terms of http://www.apache.org/licenses/LICENSE-2.0
# Author (©): Alvaro del Castillo
import logging
import unittest
import mcpi
from mcpi.vec3 import Vec3
from mcthings.pyramid import Pyramid, PyramidHollow
from mcthings.world import World
from integration.base import Te... |
"""Module for races service."""
import logging
from typing import Any, List, Optional, Union
import uuid
from race_service.adapters import RacesAdapter
from race_service.models import (
IndividualSprintRace,
IntervalStartRace,
Race,
)
from .exceptions import IllegalValueException
def create_id() -> str: ... |
# -*- coding: utf-8 -*-
from django.db import models, migrations
def add_cache(apps, schema_editor):
Article = apps.get_model("news", "Article")
for article in Article.objects.all():
version_count = article.version_set.count()
if version_count == 0:
article.delete()
... |
from django.shortcuts import render, get_object_or_404
# Create your views here.
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.views import generic
from django.utils import timezone
from .models import Question, Choice
class IndexView(generic.ListView):
templ... |
import torch
import torch.nn.functional as F
import math
def logsumexp(inputs, dim=None, keepdim=False):
return (inputs - F.log_softmax(inputs, dim=dim)).mean(dim, keepdim=keepdim)
def clip(model, C, dim=1):
example_norms = 0
for p in model.parameters():
example_norms += p.grad.data.norm(dim=dim)*... |
# Generated by Django 2.2.1 on 2019-07-21 18:21
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0002_friendship'),
]
operations = [
migrations.DeleteModel(
name='Friendship',
),
]
|
from MarkUP.files import files_list
import unittest
import mock
import os
import shutil
from MarkUP import Source
md_a_filepath = "/Users/rafalkaron/GitHub/MarkUP/tests/data/md/a.md"
md_a_dita_filepath = "/Users/rafalkaron/GitHub/MarkUP/tests/data/md/a.dita"
md_a_html_filepath = "/Users/rafalkaron/GitHub/MarkUP/tests... |
import pprint
from PyObjCTools.Conversion import propertyListFromPythonCollection
input_value = {
"a": [1, 2, 3, 4],
"b": "c",
"d": 3,
"e": None,
"f": [1, {"2": 3, "a": "b"}, [3, 4]],
"g": {"h": "i"},
"j": (1, 2, 3, "k", "l"),
}
print("Converting (Python Collection):")
pprint.pprint(input... |
#!/usr/bin/env python3
import xlrd, openpyxl
from itertools import groupby
from numbers import Number
from os.path import expanduser
from argparse import ArgumentParser
from import_container_data import dictify_sheet, setup_logging, get_logger, ASpace, JM
def old_cell_value(cell):
if str(cell).startswith('xldate... |
import numpy as np
def classify(K,crop_img):
#flag = -1
#classfication
# method and tables
# # 1 line 55
# # 2 lines 30 325
# # 3 lines 20 220 420
# # 4 lines 15 167 318 470
# # 5 lines 12 134 256 378 500
# judge the midline of k lines +-2
#... |
from messagebird.base import Base
from messagebird.webhook import Webhook
class CallData(Base):
def __init__(self):
self.id = None
self.status = None
self.source = None
self.destination = None
self._createdAt = None
self._updatedAt = None
self._endedAt =... |
from pathlib import Path
import ffmpeg
class Encoder:
@staticmethod
def wav_audio_temp(file_path, temp_dir):
temp_audio_format = ".wav"
temp_file_path = Path(temp_dir).joinpath(Path(file_path).with_suffix(temp_audio_format).name)
try:
ffmpeg.input(file_path).output(... |
"""
'Layers' introduces a number of auxiliary lasagne layers that are used throughout AgentNet and examples
"""
import theano
import theano.tensor as T
from lasagne.layers import MergeLayer, Layer
from lasagne.layers import NonlinearityLayer, ElemwiseMergeLayer
from collections import OrderedDict
from .format import... |
from namenode.namenode import Namenode
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--ip', type=str, required=True,
help='IP of the Namenode')
parser.add_argument('--lock_duration', type=int, required=True,
... |
from django.contrib import admin
from .models import Tag, Category, Post, Comment
admin.site.register(Tag)
admin.site.register(Category)
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'pub_date', 'is_active', 'is_published', 'author')
list_filter = ('is_active',)
def ... |
import unittest
from ZTUtils import Batch
class BatchTests(unittest.TestCase):
def testEmpty(self):
'''Test empty Batch'''
b = Batch([], 5)
assert b.previous is None
assert b.next is None
assert len(b) == b.start == b.end == 0, (len(b), b.start, b.end)
def testSingle... |
#/usr/bin/env python
"""
Convert a hammie database to a cdb database.
usage %(prog)s [ -h ] [ -d <file> | -p <file> ] <cdbfile>
-h - Print this usage message and exit.
-d file - Use a database-based classifier named file.
-p file - Use a pickle-based classifier named file.
"""
import sys
import os
import get... |
# Copyright 2013-2020 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 Draco(CMakePackage):
"""Draco is an object-oriented component library geared towards numer... |
# Based on Alexander Kireev's deep learning model:
# https://www.kaggle.com/alexanderkireev/experiments-with-imbalance-nn-architecture?scriptVersionId=3419429/code
import argparse
import numpy as np
import pandas as pd
import gc
import logging
from keras.layers import Input, Embedding, Dense, Flatten, Dropout, conca... |
from pypy.lang.js.jsparser import parse
from pypy.lang.js.astbuilder import ASTBuilder
from pypy.lang.js import operations
from pypy.lang.js.operations import Call
def to_ast(s):
print s
tp = parse(s)
print tp
astb = ASTBuilder()
astb.sourcename = "test"
return astb.dispatch(tp)
def test_simpl... |
from ..lib.service import Service
class AuditLogs(Service):
def list(self, account_id):
"""
Get audit logs for the currently authenticated account.
Args:
account_id (uuid): Account ID you want to get audit logs for.
Example::
client.logs.list(
a... |
from packages import ex41
|
import sys
sys.path.insert(0, '/opt')
import pymysql
import boto3
import botocore
import json
import random
import time
import os
from LambdaRDS_ManageConnections import *
# rds settings
rds_host = os.environ['RDS_HOST']
name = os.environ['RDS_USERNAME']
password = os.environ['RDS_PASSWORD']
db_name = os.environ['RDS... |
from django.contrib import admin
from core.models import Kind, Team, Tournament
@admin.register(Kind)
class KindAdmin(admin.ModelAdmin):
pass
@admin.register(Team)
class TeamAdmin(admin.ModelAdmin):
pass
@admin.register(Tournament)
class TournamentAdmin(admin.ModelAdmin):
filter_horizontal = ("teams"... |
'''
dev import, import from parent folder
'''
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import logging
import leo3ltb
from leo3ltb.scheduler import ProveScheduler, Leo3SchedulerProcess
from leo3ltb import format, ProblemVariant
'''
logging
'''
from leo3ltb.concurrent import ... |
from django import forms
from django.contrib.auth.models import User
from django.core import validators
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
class TypedMultipleChoiceField(forms.MultipleChoiceField):
"""Coerce choices to a specific type and don't va... |
import json
import unittest
from mstrio.utils.parsejson import parsejson
def get_response():
response = '{"id":"E414706011E82EDC08230080EF45A2CD","name":"iris.csv","instanceId":"B929CAF411E84C8BB1B90080EF157039","result":{"definition":{"attributes":[{"name":"ID","id":"D91B4BDE11E82EDC13FC0080EF25E205","type":"At... |
from werkzeug.test import Client
from backend.common.sitevars.firebase_secrets import FirebaseSecrets
from backend.common.sitevars.fms_api_secrets import FMSApiSecrets
from backend.common.sitevars.gcm_server_key import GcmServerKey
from backend.common.sitevars.google_api_secret import GoogleApiSecret
from backend.comm... |
#!/usr/bin/env python
"""
tab2tex.py
dent earl, dearl (a) soe ucsc edu
27 april 2011
python script to take a tab delimited file and format it for latex tables.
"""
##############################
# Copyright (C) 2009-2011 by
# Dent Earl (dearl@soe.ucsc.edu, dent.earl@gmail.com)
# Benedict Paten (benedict@soe.ucsc.edu... |
"""Code to be run on the server. Kept here for easy reference.
Use the %ed command to get a vi interface into iPython, and paste this in.
"""
import csv
from cl.scrapers.models import PACERFreeDocumentRow
def make_csv():
with open('/tmp/out.csv', 'w') as f:
w = csv.writer(f)
items = PACERFreeDoc... |
from __future__ import print_function, absolute_import, division
# importing the Kratos Library
from KratosMultiphysics.StructuralMechanicsApplication import structural_response
def CreateResponseFunction(response_id, response_settings, model):
response_type = response_settings["response_type"].GetString()
i... |
"""Management of OPC-UA client part."""
import asyncio
import logging
from typing import Any
import asyncua
import tenacity
from asyncua import ua
from asyncua.common.subscription import SubscriptionItemData
from asyncua.crypto.security_policies import SecurityPolicyBasic256Sha256
from asyncua.ua.uaerrors import UaSt... |
from botocore.exceptions import ClientError
from botocore.config import Config
from snovault import (
AfterModified,
BeforeModified,
CONNECTION,
calculated_property,
collection,
load_schema,
)
from snovault.schema_utils import schema_validator
from snovault.validation import ValidationFailure
fr... |
from flask import Blueprint
from flask import render_template, redirect, url_for, request, session, jsonify
from flask_login import login_user, logout_user, current_user
from app.master import bp
from app.master.model import Benefit , BenefitSchema
from app import db, ma
# Emp. Cat Master Routes
@bp.route('/get/ben... |
cast = {
"Jerry Seinfeld": "Jerry Seinfeld",
"Julia Louis-Dreyfus": "Elaine Benes",
"Jason Alexander": "George Costanza",
"Michael Richards": "Cosmo Kramer"
}
print("Iterating through keys:")
for key in cast:
print(key)
print("\nIterating through keys and values:... |
from setuptools import setup
import os
# A Function to read the README.rst
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='beeply',
version='1.0.1',
description='A python module that helps you produce musical notes using your computer\'s characteristic bee... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.