content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# Copyright (c) 2021 AccelByte Inc. All Rights Reserved.
# This is licensed software from AccelByte Inc, for limitations
# and restrictions contact your company contract manager.
#
# Code generated. DO NOT EDIT!
# template file: justice_py_sdk_codegen/__main__.py
# justice-platform-service (4.10.0)
# pylint: disabl... | python |
# -*- coding: utf-8 -*-
import unittest
from unittest import mock
from pastepwn.analyzers.awssessiontokenanalyzer import AWSSessionTokenAnalyzer
class TestAWSSessionTokenAnalyzer(unittest.TestCase):
def setUp(self):
self.analyzer = AWSSessionTokenAnalyzer(None)
self.paste = mock.Mock()
def ... | python |
"""app.engagement.utils module"""
from typing import List
from uuid import UUID
from app.engagement.models import Engagement
from app.engagement.repositories import EngagementRepository
def create_engagement(**kwargs) -> Engagement:
"""
Create engagement.
Returns:
Engagement created.
"""
... | python |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import argparse
import datetime
import json
ANDROID = 'android'
IOS = 'ios'
ORIG_ACTION_2 = 'Action2'
ORIG_SEARCH_QUERY_2 = 'SearchQuery2'
ORIG_CAMPAIGN_NAME = 'campaign name'
ORIG_ONLINE_TIME = 'Online time'
ORIG_OFFLINE_TIME = 'Offline time'
DESCRIPTION = 'description'
D... | python |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
from collections import OrderedDict
from functools import reduce
from typing import Tuple, Union
import funsor.ops as ops
from funsor.cnf import Contraction, GaussianMixture
from funsor.constant import Constant
from funsor.delta impor... | python |
import core.cv as cv
def r(one,r1,r2):
r2 = cv.cmd5(r2)[0:16]
return one.replace('"pass"','"'+r1+'"').replace("3c6e0b8a9c15224a", r2)
def get(type,pwd,key):
print("godzilla-v4.0.1 \nhttps://github.com/shack2/skyscorpion\n"+"-"*64)
if type == "jsp":
print(r(jsp,pwd,key))
elif type == "jspx... | python |
from selenium import webdriver
url = "http://www.aozora.gr.jp/cards/000081/files/46268_23911.html"
# PhantomJSのドライバを得る --- (※1)
browser = webdriver.PhantomJS()
# 暗黙的な待機を最大3秒行う --- (※2)
browser.implicitly_wait(3)
# URLを読み込む --- (※3)
browser.get(url)
# 画面をキャプチャしてファイルに保存 --- (※4)
browser.save_screenshot("website.png")
#... | python |
import numpy as np
import tensorflow as tf
import argparse
import time
import os
import cPickle
from mnist_data import *
from model import VAE
'''
vae implementation, alpha version, used with mnist
LOADS of help was taken from:
https://jmetzen.github.io/2015-11-27/vae.html
'''
def main():
parser = argparse.Arg... | python |
from dataContainers import *
import psycopg2
import psycopg2.extras
import datetime
import logging
import pickle
import copy
_logger = logging.getLogger()
class PostgresWrapper():
def __init__(self, connectionString):
self.connection_string = connectionString
def _query_wrapper(self, query, var... | python |
import six
from .base import BasketSerializer
from data_basket.exceptions import *
__all__ = [
'IntSerializer', 'FloatSerializer', 'ComplexSerializer',
'StrSerializer',
'NoneSerializer',
'ListSerializer', 'TupleSerializer', 'DictSerializer',
'BUILTIN_SERIALIZERS'
]
class IntSerializer(BasketSeria... | python |
# 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... | python |
from ursina import *
from shader_builder_manager import ShaderBuilderManager
from panda3d.core import loadPrcFileData
import json
# default config info
config = {
'AntiAliasing' : 1,
'Line Quality' : 26,
'Start Fullscreen' : 0
}
#loading config
try:
with open('config.json', 'r') as f:
config.update(json.load(f)... | python |
#!/usr/bin/env python3
# Please save the doc as docx before delete useless table.
# Check all of table are complete. There are problems if rows are not align in table.
# All tables are saved in variable "tables" using structure "list".
# Rows for each table use structure "dict" and save in variable "tables[index]".
i... | python |
## create flood forecast table for all the COMIDs on CONUS
# Yan Y. Liu <yanliu@illinois.edu>
# 10/31/2016
# input 1: the list of hydro property lookup table for each HUC6 code
# input 2: NOAA NWM forecast data, one timestamp
# input 3: NHDPlus MR geodb, for creating georeferenced anomaly shp files
# output: an inundat... | python |
"""
COCOPanda :: Trash Panda COCO Data Manipulation
The goal of this package is to convert the COCO dataset into the
Trash Panda YOLO format (nested class directories).
The code in this file is based on:
- The official COCO Python API: pycocotools
- https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pyc... | python |
'''
Dictionaries in python
'''
# %%
# create an example dictionary
xDict = {
'firstName': 'Nagasudhir',
'lastname': 'Pulla',
'age': 28,
'hobbies': ['tv', 'playing', 'youtube'],
'metaData': {
'proficiency': 'level 1',
'designation': 'Deputy Manager',
'department': 'IT',
... | python |
import multiprocessing as mproc
import logging
import numpy as np
global_mp_vars = {}
def eval_input(network, input_test_case) -> np.float64:
result = input_test_case.copy()
for comp in network:
if input_test_case[comp[0]] > input_test_case[comp[1]]:
result[[comp[0], comp[1]]] = result[... | python |
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from ... | python |
class Solution:
def equalSubstring(self, s, t, maxCost):
# sliding window
_arr = [abs(ord(s[i])-ord(t[i])) for i in range(len(s))]
i = 0
for j in range(len(_arr)):
maxCost -= _arr[j]
if maxCost < 0:
maxCost += _arr[i]
i += 1
... | python |
import os
from flask import Flask
from flask.ext import restful
from flask.ext.restful import reqparse, Api
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.bcrypt import Bcrypt
from flask.ext.httpauth import HTTPBasicAuth
basedir = os.path.join(os.path.abspath(os.path.dirname(__file__)), '../')
app = Flas... | python |
# Program to send bulk customized messages through Telegram Desktop application
# Author @inforkgodara
import pyautogui
import pandas
import time
excel_data = pandas.read_excel('Recipients data.xlsx', sheet_name='Recipients')
count = 0
time.sleep(3)
for column in excel_data['Username'].tolist():
pyautogui.p... | python |
# -*- coding: future_fstrings -*-
"""
This module defines a single Application Item in the AppsPanel.
"""
from xdgprefs.gui.custom_item import CustomItem
def _get_icon(icon_name):
"""Return the path to an icon."""
theme = 'Adwaita'
size = '256x256'
path = f'/usr/share/icons/{theme}/{size}/mimetypes/... | python |
import os
from datetime import timedelta
import sqlite
import time
import timeutils # self package
import sessions # self package
import mdfactory # self package
import path # self package
from flask import Flask, render_template, request, redirect, url_for, session
from werkzeug.utils import secure_filename
from ... | python |
# -*- coding: utf-8 -*-
# Copyright: 2016-2018, Jens Carroll
# These sources are released under the terms of the MIT license: see LICENSE
import time, os, signal, random, math
from threading import Lock, Thread, Event
from logger import Logger
import RPi.GPIO as GPIO
OPEN_FRONT_DOOR_OUTPUT = 4 # Pin 5
OPEN_APARTM... | python |
"""Provide the helper classes."""
from json import dumps
from typing import TYPE_CHECKING, Generator, List, Optional, Union
from ..const import API_PATH
from .base import PRAWBase
from .reddit.draft import Draft
from .reddit.live import LiveThread
from .reddit.multi import Multireddit, Subreddit
if TYPE_CHECKING: # ... | python |
from typing import Optional
import pystac
from pystac.extensions.eo import EOExtension
from pystac.extensions.projection import ProjectionExtension
from pystac.extensions.view import ViewExtension
from stactools.core.io import ReadHrefModifier
from stactools.landsat.assets import (ANG_ASSET_DEF, COMMON_ASSET_DEFS,
... | python |
import argparse
import random
import sys
import pytest
import imagej.dims as dims
import scyjava as sj
import numpy as np
import xarray as xr
from jpype import JObject, JException, JArray, JInt, JLong
class TestImageJ(object):
def test_frangi(self, ij_fixture):
input_array = np.array(
[[1000... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Florian Scherf <f.scherf@pengutronix.de>
from aiohttp.web import Application
from aiohttp_json_rpc import JsonRpc
import asyncio
@asyncio.coroutine
def ping(request):
return 'pong'
if __name__ == '__main__':
loop = asyncio.get_event_loop()
rpc = J... | python |
"""
Application configuration logic.
"""
import json
default_config_file = 'config.json'
class Config():
"""App configuration."""
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def update(self, key: str, value: str):
"""
Update the app's configuration.
Set ... | python |
from django.test import TestCase
from mock import Mock, sentinel
from morelia.decorators import tags
from tasks.templatetags.tasks_tags import _show_current_tasks, is_visible_for
from tasks.models import Task
@tags(['unit'])
class ShowCurrentTasksTest(TestCase):
""" :py:func:`tasks.templatetags.tasks_tags._show... | python |
#!/usr/bin/python
# script for generating 2 fasta files of 23nt-TRUNCATED 23-28nt reads, forward and reverse, before weblogo analysis
# version 23-5-2012
# Usage trunc_pi23.py <bowtie input> <output1> <output2>
import sys, re, os
def antipara (sequence):
antidict = {"A":"T", "T":"A", "G":"C", "C":"G"}
revseq = se... | python |
# Copyright 2017 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/licenses/LICENSE-2.0
#
# Unless required by... | python |
from django.db import models
from django.conf import settings
class Timestampable(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Authorable(models.Model):
author = models.ForeignKey(settings.AU... | python |
import math
import os
import random
import re
import sys
import pprint
def simpleArraySum(ar):
suma=0
for i in ar:
suma +=1
print("suma = ", suma)
return suma
if __name__ == '__main__':
fptr= open('T3-1.txt', 'w')
ar_count = int(input().strip())
ar = list(map(int, input().... | python |
#
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 Raphael Michel and contributors
# Copyright (C) 2020-2021 rami.io GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by ... | python |
# Endpoint map geodesic on (n-1)-dimensional ellipsoid in Rn
# With Jacobian
from jax import ops, lax, jacfwd, jit, jvp
import jax.numpy as jnp
from scipy import linalg, optimize
from functools import partial
class Locus:
def __init__(self, n,b,T,N,XStart):
self.n = n # dimension of ambient space
self.b = b ... | python |
import random
import pandas as pd
import numpy as np
import cv2
import sklearn
import tensorflow as tf
from PIL import Image
from tqdm import tqdm
from keras.backend.tensorflow_backend import set_session
from keras.models import Sequential, Model, load_model
from keras.layers import Flatten, Dense, Lambda, Dropout
fr... | python |
#!/usr/bin/env python3
# -*- coding: Utf-8 -*
# Author: aurelien.esnard@u-bordeaux.fr
from model import *
from view import *
from keyboard import *
from network import *
import sys
import pygame
import socket
import errno
### python version ###
print("python version: {}.{}.{}".format(sys.version_info[0], sys.version_... | python |
# -*- coding: utf-8 -*-
"""Includes functions for copying the PyNX template files."""
import datetime
import os
from distutils.dir_util import copy_tree
from nxstart.utils.files import get_full_path, replace_in_file
def create_pynx_project(folder_path, name, author):
"""
Copies the files from templates/bas... | python |
import pygame
pygame.mixer.pre_init(frequency=44100, size=-16, channels=1, buffer=4096)
directory = ''
def play_sound(sound, time):
sound = pygame.mixer.Sound(sound)
if time == 0:
sound.play()
else:
sound.play(maxtime = time)
def stop_sound(sound):
sound = pygame.mixer.Sound(sound)
sound.stop()
def ... | python |
"""Command-line interface for wamplius."""
import argparse
import logging
import logging.config
log = logging.getLogger(__name__)
def _setup_logging() -> None:
logging.config.dictConfig({
"version": 1,
"formatters": {
"colored": {
"()": "colorlog.ColoredFormatter",
... | python |
import sys
def input():
return sys.stdin.readline().rstrip()
def isPrime(x):
if x <= 1:
return False
for i in range(2, x):
if i * i > x:
break
if x % i == 0:
return False
return True
def gcd(a, b):
while b:
a, b = b, a % b
return a
def ... | python |
# Generated by Django 3.1.2 on 2022-01-29 07:42
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('catalogo', '... | python |
# -*- coding: utf-8 -*-
from io_utils.read.geo_ts_readers.lprm.base_reader import LPRMTs
from io_utils.read.path_config import PathConfig
path_settings = {}
class GeoSMAPLPRMv6Ts(LPRMTs):
# Reader implementation that uses the PATH configuration from above
# implememted subversion that have a set path configur... | python |
import sys
import os
import json
from enum import Enum
from .mach_o import LC_SYMTAB
from macholib import MachO
from macholib import mach_o
from shutil import copy2
from shutil import SameFileError
class ReplaceType(Enum):
objc_methname = 1
symbol_table = 2
def replace_in_bytes(method_bytes, name_dict, type... | python |
import dsp
class PassThruProcessor(dsp.AudioProcessor):
'''ToDo
'''
def prepare(self, spec: dsp.ProcessorSpec) -> None:
'''ToDo
'''
def process(self, buffer):
'''ToDo
'''
return buffer
def release(self) -> None:
'''ToDo
'''
effect = Pass... | python |
from .pve import PVE, BrainT1PVE, MultichannelPVE, FuzzyCMean, MultichannelFuzzyCMean
from .vem import VEM
from .brain_segmentation import BrainT1Segmentation
from .moment_matching import moment_matching
from nipy.testing import Tester
test = Tester().test
bench = Tester().bench
| python |
from setuptools import setup, find_packages
packages = find_packages()
print(packages)
setup(
name = "testapp",
version = "0.0.1",
packages = packages,
data_files=[('', ['__main__.py', ])]
) | python |
import argparse
from textblob import TextBlob
import smartbot.plugin
from smartbot.formatting import Style
class Plugin(smartbot.plugin.Plugin):
"""Perform a Google translation."""
names = ["translate"]
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("-from", "--from-language",... | python |
# import frappe
# def on_validate(doc, method):
# """
# validate user their should be only one department head
# """
# print "validate in"
# query = """ SELECT name FROM `tabUser` WHERE department='%s' AND
# name IN (SELECT parent FROM `tabUserRole` WHERE role='Department Head')"""%(doc.department)
# recor... | python |
import tensorflow as tf
import numpy as np
import os
from user_ops import ft_pool
#os.environ['CUDA_VISIBLE_DEVICES'] = ''
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
x_train = np.expand_dims(x_train, axis=3)
x_test = np.ex... | python |
import tensorflow as tf
from tensorflow.contrib.layers.python.layers import initializers
from enum import Enum
def dense_block(input_node, layers, name, activation=tf.nn.relu, batch_norm_phase=None, last_layer_activation=False,
detailed_summary=False):
with tf.variable_scope(name):
output = input... | python |
# -*- coding: utf-8 -*-
import locale
from os import chdir, path
import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas as pd
from custom.plots import apply_plot_treatment, get_xticks_labels, palette
from custom.preprocessing_dataframe import (compute_incidence,
... | python |
"""
Created on 17 Dec 2020
@author: si
"""
import os
import tempfile
import unittest
import ayeaye
from ayeaye.connectors.ndjson_connector import NdjsonConnector
PROJECT_TEST_PATH = os.path.dirname(os.path.abspath(__file__))
EXAMPLE_NDJSON_UK_PUBS = os.path.join(PROJECT_TEST_PATH, "data", "uk_pubs.ndjson")
class T... | python |
"""Helper module for linking existing BIBFRAME resources to external data
sources like Library of Congress, DBPedia, VIAF, and others."""
__author__ = "Jeremy Nelson, Mike Stabile"
import os
import rdflib
import sys
BIBCAT_BASE = os.path.abspath(
os.path.split(
os.path.dirname(__file__))[0])
class Linke... | python |
"""
# PROBLEM 28
Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is
formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can be verified that the sum of the numbers on the diagonals is 101.
What is the sum of the numbers on the ... | python |
"""Compute performance standard_bound and write into csv file"""
from typing import List
import pandas as pd
from bound_evaluation.data_frame_to_csv import perform_param_list_to_csv
from nc_arrivals.arrival_distribution import ArrivalDistribution
from nc_arrivals.iid import DM1, MD1
from nc_arrivals.markov_modulated ... | python |
# v3 - Melhoramentos: Retirei "in" em "x in array"; implementei pesquisa binaria; print_array; etc.
# v3 Abordagem Ate as folhas, depois de Baixo-para-Cima, Recursiva
# pai.direcao = return no filho da recursividade
# #### BIBLIOTECAS ####
import sys
# #### CONSTANTES ####
CMD_IN_LINHAS = "LINHAS"
CMD_OUT_NULO = "-... | python |
import logging
import pathlib
import shlex
import subprocess
import time
import argh
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
def is_path_mounted(path):
mount_out = subprocess.check... | python |
# Page ID: C
# The 3rd tab on the menu
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from utils import Header, make_dash_table
import pandas as pd
import pathlib
def create_layout(app, region, region_code, view_style):
####################################... | python |
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
num_dict = {}
for index, value in enumerate(nums):
if target - value in num_dict:
return [num_dict[target - value], in... | python |
"""
At the moment tensor will be a simple
n-dimensional array, later It will
be some more complex object
"""
from numpy import ndarray as Tensor
| python |
from setuptools import setup, find_packages
from codecs import open
from os import path
__version__ = '0.1'
__author__ = 'Ilya Zhivetiev'
__email__ = 'i.zhivetiev@gnss-lab.org'
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read(... | python |
import os
from pathlib import Path
from typing import Dict, Optional
import numpy as np
import torch
from ase.units import Bohr
from torch import Tensor
from torch_dftd.functions.dftd3 import d3_autoang, d3_autoev, edisp
from torch_dftd.functions.distance import calc_distances
from torch_dftd.nn.base_dftd_module impor... | python |
import urllib
from engine import DownloadLink
S = urllib.URLopener()
class Crawler():
baseurl = 'http://romhustler.net/roms/'
splittext = \
[
'''\
<p>Some titles on the list might not have a download link available. This is because these specific titles are <span class="important">ESA pr... | python |
import pytest
pytestmark = [pytest.mark.django_db]
def test_no_anon(anon):
anon.get('/api/v2/notion/materials/0e5693d2173a4f77ae8106813b6e5329/', expected_status_code=401)
@pytest.mark.usefixtures('unpaid_order')
def test_404_for_not_purchased_materials(api, fetch_page_recursively):
api.get('/api/v2/notion... | python |
from collections import defaultdict
from typing import Union
from ariadne import QueryType, MutationType, ScalarType, ObjectType
from flowsaber.server.database.db import DataBase
from flowsaber.server.database.models import *
def ch_id(data: dict) -> dict:
if "_id" in data:
data['id'] = data.pop('_id')
... | python |
import logging
import json
import sys
from functools import partial
import traceback
logger = logging.getLogger(__name__)
class QueryGetter:
def __init__(self, query, **kwargs):
if len(kwargs) != 0:
self.query = partial(query, **kwargs)
else:
self.query = query
def b... | python |
"""
The :mod:`ramp_database.model` defines the database structure which is used for the
RAMP events.
"""
from .base import * # noqa
from .user import * # noqa
from .fold import * # noqa
from .team import * # noqa
from .score import * # noqa
from .event import * # noqa
from .problem import * # noqa
from .workflo... | python |
#!/usr/bin/python3
# Copyright 2016 Canonical 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... | python |
# -*- coding: utf-8 -*-
##### Secuencias
Tupla = (1, 2, 3)
List = [1, 2, 3]
String = '1, 2, 3' # Los strings, como las tuplas son inmutables
## INDEXING - Buscar la posición de un valor en una secuencia
a = List[2]
b = Tupla[2]
c = String[2]
## Acceder al ultimo elemento de list
List[2] = List[len(List)-1] = List[-1... | python |
from __future__ import print_function
import argparse
import atexit
import boto3
import logging
import sys
import time
if sys.argv[0].endswith("__main__.py"):
sys.argv[0] = "python -m appsync_schema_uploader"
@atexit.register
def app_exit():
logging.getLogger().info("Terminating")
def _parse_command_line... | python |
# This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will ... | python |
__author__ = 'Su Lei'
def array_diff(c, d):
return [x for x in c if x not in d]
a = [1, 2, 3]
b = [1, 2]
print array_diff(a, b) | python |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView, DetailView, UpdateView, DeleteView, CreateView,TemplateView
from django.utils import timezone
from django.contrib.auth.decorators import... | python |
from .GridArea import GridArea
class GridColumn:
def __init__(self, position_marker, grid_size):
self.position = position_marker
self.column = []
for i in range(grid_size):
self.column.append(GridArea(i))
def get_position(self):
return self.position
def colu... | python |
import numpy as np
class Solver:
def __init__(self, matrix, vector, initialVector, precision, gamma):
self.initialVector = initialVector
self.precision = precision
self.matrix = matrix
self.bVector = vector
self.gamma = gamma
# lower triangular part
... | python |
# coding=utf-8
class AppError(Exception):
code = 0
http_code = 400
| python |
""" Generating structure graphs for graph convolutional neural networks """
import os
from os.path import isfile
from enum import Enum, auto
import numpy as np
from scipy.spatial.distance import cdist
import networkx as nx
from biopandas.pdb import PandasPdb
import constants
import utils
class GraphType(Enum):
... | python |
"""
passage
i am very tired, but this is very good class i am learning many new things dictionary is amazing
this is very interesting i like this this is new
{
'i': 3,
'am': 4,
'very': 2,
'hello': 2,
'ball': 1
}
"""
passage = input()
words = passage.split()
freq = {}
for word in words:
freq[wo... | python |
import sys
import glob
from scipy.io.wavfile import write
sys.path.insert(0,'lib/build-src-RelDebInfo')
sys.path.insert(0,'library/build-src-Desktop-RelWithDebInfo')
import WaveRNNVocoder
import numpy as np
vocoder=WaveRNNVocoder.Vocoder()
vocoder.loadWeights('model_outputs/model.bin')
# mel_file='../TrainingData... | python |
import requests
url = 'http://localhost:5050/predict'
body = {
"text": "The insurance company is evil!"
}
response = requests.post(url, data=body)
print(response.json()) | python |
"""
Copyright 2016 Brocade Communications Systems, 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 i... | python |
# Copyright 2019 The WPT Dashboard Project. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import contextlib
import gzip
import tempfile
import unittest
import warnings
import test_util
from wptscreenshot import WPTScreenshot
class WPTScree... | python |
import uasyncio as asyncio
from uibbq import iBBQ
def handle_data(d):
print("Result:", d)
async def run():
ibbq = iBBQ(handle_data)
await ibbq.connect()
print("Battery:", await ibbq.battery_level())
await asyncio.sleep(10)
print("Disconnecting")
await ibbq.disconnect()
asyncio.run(run(... | python |
""" Module docstring """
def _output_rule_impl(ctx):
output = ctx.attr.output.short_path.replace("\\", "/")
expected_output = "{}__/some_out.txt".format(ctx.label.name)
if not output.endswith(expected_output):
fail("Expected short path endswith {}, got {}".format(expected_output, output))
if c... | python |
# Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from yacs.config import CfgNode as CN
__C = CN()
cfg = __C
__C.META_ARC = "siamcar_r50"
__C.CUDA = Tru... | python |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
"""
Script to download a QnA Maker knowledge base (KB) from one
QnA Maker resource to a json file.
This script can be run from the command line (or from inside your IDE) using:
python <path_to_this_file> --output <output_file_name> --slot <test... | python |
from typing import List, Optional
from citrine._rest.resource import Resource, ResourceTypeEnum
from citrine._serialization import properties as _properties
from citrine.informatics.data_sources import DataSource
from citrine.informatics.descriptors import Descriptor
from citrine.informatics.predictors import Predicto... | python |
import dbus
bus = dbus.SessionBus()
notif = bus.get_object(
"org.freedesktop.Notifications",
"/org/freedesktop/Notifications"
)
notify_interface = dbus.Interface(notif, "org.freedesktop.Notifications")
last_id = 0
def notify(icon, title, message, progress=None, timeout=0):
global last_id
app_name ... | python |
import os
import random
import numpy as np
import torch
#https://pytorch.org/docs/stable/notes/randomness.html
def set_seed(seed, logger=None):
if logger:
logger.debug(f'seed : {seed}')
os.environ['PYTHONHASHSEED'] = str(seed)
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
... | python |
# The MIT License (MIT)
#
# Copyright (c) 2014-2016 Santoso Wijaya <santoso.wijaya@gmail.com>
#
# 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 limita... | python |
# -*- coding: utf-8 -*-
import asyncio
import discord
import os
import sqlite3
client = discord.Client()
conn = sqlite3.connect('data.db')
c = conn.cursor()
@client.event
async def on_message(message):
if message.author.bot:
return
uname = message.author.id
con = message.content
sql = 'insert i... | python |
temp_module = __import__('vmware.ProducerSnippetBase', globals(), locals(), ["ProducerSnippetBase"], -1)
producer_snippet_base = getattr(temp_module, "ProducerSnippetBase")
setattr(producer_snippet_base, "print_text", lambda(self): "ZZZ")
r1 = file.print_msg()
x = file.ProducerSnippetBase()
x2 = file.ProducerSnippetBa... | python |
from libsaas import http, parsers
from libsaas.services import base
from . import resource
from . import organizations
class UserRepos(resource.GitHubResource):
path = 'repos'
@base.apimethod
def get(self, type='all', page=None, per_page=None):
"""
Fetch repos for this user.
:v... | python |
Comment # unused class (src/mrkup/mrkup.py:87)
Tag # unused class (src/mrkup/mrkup.py:140)
PI # unused class (src/mrkup/mrkup.py:210)
| python |
"""Invariants for value annotations (available as :py:mod:`pybryt.invariants`)"""
import numpy as np
from abc import ABC, abstractmethod
from collections import Iterable
from typing import Any, List, Optional, Union
# from enum import Enum, auto
# TODO: add iterable_type invariant
class invariant(ABC):
"""
... | python |
# -*- coding: utf-8 -*-
"""
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GATConv
from torch.nn import Linear, BatchNorm1d
from torch_geometric.utils import dense_to_sparse
class TemporalAttention(torch.nn.Module):
"""
model imput: (batch_size, nu... | python |
# https://github.com/FedML-AI/FedNLP/blob/master/model/bilstm.py
import torch
from torch import nn
class BiLSTM_TextClassification(nn.Module):
def __init__(self, input_size, hidden_size, output_size, num_layers, embedding_dropout, lstm_dropout,
attention_dropout,embedding_length, attention=False,... | python |
import bs4
from bs4 import BeautifulSoup
import requests
import urllib3
decurl = "https://decsearch.usaid.gov/search?client=dec_pdfs&site=default_collection&emdstyle=true&output=xml_no_dtd&proxystylesheet=dec_pdfs&ie=UTF-8&oe=UTF-8&getfields=*&ulang=en&filter=0&proxyreload=1&as_q=quarterly&num=100&btnG=Google+Search&a... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.