content stringlengths 5 1.05M |
|---|
class Matrix:
def __init__(self, matrix_string: str):
lines = matrix_string.splitlines()
self.__matrix = [list(map(int, line.split())) for line in lines]
def row(self, index):
return self.__matrix[index - 1]
def column(self, index):
return [row[index - 1] for row in self.__... |
from __future__ import absolute_import, print_function
from django.db import router
from django.db.models.signals import post_migrate
def create_first_user(app_config, using, interactive, **kwargs):
if app_config and app_config.name != "sentry":
return
try:
User = app_config.get_model("User"... |
import datetime
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pytest
import oscovida as c
import oscovida.plotting_helpers as oph
def assert_oscovida_object(ax, cases, deaths):
assert isinstance(ax, np.ndarray)
assert isinstance(cases, (pd.Series, pd.DataFrame))
assert isin... |
import unittest
from json import loads
from reversedns import Response, ErrorMessage
_json_response_ok_empty = '''{
"result": [],
"size": 0
}'''
_json_response_ok = '''{
"result": [
{
"value": "ac1.nstld.com 1634338343 1800 900 604800 86400",
"name": "abc",
"first... |
from env_Cleaner import EnvCleaner
import random
if __name__ == '__main__':
env = EnvCleaner(2, 13, 0)
max_iter = 1000
for i in range(max_iter):
print("iter= ", i)
env.render()
action_list = [random.randint(0, 3), random.randint(0, 3)]
reward = env.step(action_list)
... |
'''Test the file 'indexengine.py'
Run with `py.test test_indexengine.py`
Author: Noémien Kocher
Licence: MIT
Date: june 2016
'''
import pytest
import indexengine as iengine
from math import log2
def test_settfidf():
# needed for the total number of documents and the norms
# here the number of document is 2
... |
from templeplus.pymod import PythonModifier
from toee import *
import tpdp
import char_class_utils
import d20_action_utils
###################################################
def GetConditionName():
return "Duelist"
print "Registering " + GetConditionName()
classEnum = stat_level_duelist
preciseStrikeEnum = 2400
#... |
from pyhop_anytime import *
global state, goals
state = State('state')
state.calibration_target = Oset([('instrument0','groundstation0'),('instrument1','star3'),('instrument10','star3'),('instrument11','star1'),('instrument12','groundstation0'),('instrument13','star1'),('instrument14','groundstation2'),('instrument15',... |
from flask_restful import Resource
from models.article import ArticleModel
class Articles(Resource):
# GET method
def get(self):
return {'articles': [article.json() for article in ArticleModel.objects()]}
|
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag
def site_name():
return settings.SITE_NAME
@register.simple_tag
def site_root():
return settings.SITE_ROOT
@register.simple_tag
def site_scheme():
parts = settings.SITE_ROOT.split("://")
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 15:56:24 2020
@author: giova
"""
# running stuff with the correct analysis
def run(mesh, bcs, material_lib, parameters):
solverType = parameters["solver"]["type"]
exec("from "+solverType+" import "+solverType)
U,K = eval (solverType+"(mesh, bcs, material... |
import os
from os.path import join
import pandas as pd
import numpy as np
import torch
from Hessian.GAN_hessian_compute import hessian_compute
# from hessian_analysis_tools import scan_hess_npz, plot_spectra, average_H, compute_hess_corr, plot_consistency_example
# from hessian_axis_visualize import vis_eigen_explore,... |
import os.path
import numpy as np
import scipy.io
import pandas as pd
import h5py
DATA_DIR = "/home/fischer/projects/ROC/01_data/"
def load_coexp(file_prefix):
network = np.loadtxt(file_prefix + ".txt.gz")
with open(file_prefix + "_genes.txt") as fp:
genes = fp.read().splitlines()
return network... |
from setuptools import find_packages, setup
requirements = [
'numpy>=1.10.0',
'scipy>=0.18.0',
'xlrd>=1.1.0',
'pandas>=0.23',
]
setup(name='bayesian_benchmarking',
version='alpha',
author="Hugh Salimbeni",
author_email="hrs13@ic.ac.uk",
description=("Bayesian benchmarking"),
... |
"""
dtconv - Date and Time conversion functions
===========================================
The module adapya.base.dtconv contains various routines to convert
datetime values between various formats.
For Gregorian to Julian date conversions and vice versa see
http://en.wikipedia.org/wiki/Julian_day#Calculation
... |
from django.conf import settings as django_settings
ENABLED = getattr(django_settings, 'LOCALIZE_SEO_ENABLED', not django_settings.DEBUG)
IGNORE_URLS = frozenset(getattr(django_settings, 'LOCALIZE_SEO_IGNORE_URLS', ['/sitemap.xml']))
IGNORE_EXTENSIONS = frozenset(getattr(django_settings, 'LOCALIZE_SEO_IGNORE_EXTENSI... |
# using if...elif...else
num = float(input('Enter a number'))
if num > 0:
print('Positive Number')
elif num == 0:
print('Number is Zero')
else:
print('Negative Number')
# using Nested if
if num >= 0:
if num == 0:
print('Number is Zero')
else:
print('Positive Number')
else:
p... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import math, os
from scipy.ndimage import gaussian_filter as gaussian
plt.rcParams["mathtext.fontset"]="cm"
plt.rcParams["axes.formatter.use_mathtext"]=True
algs = {"C-DQN": "CDQN", "DQN": "DQN", "RG": "Residual"}
file_... |
def sol(num):
big = ["", "one thousand", "two thousand", "three thousand", "five thousand"]
hundreds = ["", "one hundred", "two hundred", "three hundred", "four hundred", "five hundred", "six hundred", "seven hundred", "eight hundred", "nine hundred"];
teens = ["", "eleven", "twelve", "thirteen", "forteen", "fifteen... |
# Generated by Django 3.2.3 on 2021-06-15 18:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20210615_1533'),
]
operations = [
migrations.AlterField(
model_name='novacolecaoindex',
name='prec... |
# Start Imports
import os
import re
import time
import shutil
import psutil
import requests
import colorama
import subprocess
import bimpy as bp
import config as cfg
import elevate as elevate
# mysql-connector-python
import mysql.connector
from sys import exit
from os import listdir
from colorama import Fore
from os.p... |
import pytest
import pytz
from django import forms
from django.db import models
from timezone_field import TimeZoneField, TimeZoneFormField
common_tz_names = tuple(tz for tz in pytz.common_timezones)
common_tz_objects = tuple(pytz.timezone(tz) for tz in pytz.common_timezones)
class ChoicesDisplayForm(forms.Form):... |
import Weapon
import WeaponGlobals
from pirates.audio import SoundGlobals
from pirates.audio.SoundGlobals import loadSfx
from pirates.uberdog.UberDogGlobals import InventoryType
from direct.interval.IntervalGlobal import *
from pandac.PandaModules import *
from pirates.inventory import ItemGlobals
import random
def be... |
def binary_classification_metrics(prediction, ground_truth):
'''
Computes metrics for binary classification
Arguments:
prediction, np array of bool (num_samples) - model predictions
ground_truth, np array of bool (num_samples) - true labels
Returns:
precision, recall, f1, accuracy - classi... |
# --------------------------------------------------------------------
from petsc4py import PETSc
import unittest
from sys import getrefcount
# --------------------------------------------------------------------
class BaseMyPC(object):
def setup(self, pc):
pass
def reset(self, pc):
pass
... |
#메뉴처리
from tkinter import *
def openFile():
print('[열기] 선택함.')
def exitFile():
print('[종료] 선택함.')
# def copyFile():
# print('[복사] 선택함.')
# def cutFile():
# print('[잘라내기] 선택함.')
# def pasteFile():
# print('[붙여넣기] 선택함.')
def editFile(num) :
print(str(num)+'선택함.')
window = Tk()
mainMenu = Menu(wi... |
import numpy as np
import pytest
from agents.agents import get_agent
from environments.environments import get_environment
from representations.representations import get_representation
from rl_glue.rl_glue import RLGlue
agent_info = {
"num_states": 5,
"algorithm": "ETD",
"representations": "TA",
"num... |
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog
import time
import algorithms, tools
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1202, 680)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolic... |
"""
Core module Dashboard URLs
"""
from django.conf.urls import patterns, url
from anaf.core.dashboard import views
urlpatterns = patterns('anaf.core.dashboard.views',
url(r'^(\.(?P<response_format>\w+))?$', views.index, name='core_dashboard_index'),
# Widgets
... |
# -*- coding: utf-8 -*-
import signal
from functools import wraps
__author__ = "Grant Hulegaard"
__copyright__ = "Copyright (C) Nginx, Inc. All rights reserved."
__license__ = ""
__maintainer__ = "Grant Hulegaard"
__email__ = "grant.hulegaard@nginx.com"
class TimeoutException(Exception):
description = 'Operatio... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: app/grpc/service1.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from goog... |
from antlr4.tree.Tree import ParseTree
from parser.PlSqlParser import PlSqlParser
from .visitor import Visitor
from .ast.hie_query import HierarchicalQueryNode
from .ast.token import TokenNode
from .ast.table_ref import TableRefNode
from .ast.selected_item import SelectedItemNode
from .ast.dot_id import DotIdNode
fro... |
import sys
import fileinput
import os
import statistics
"""
Steps:
1. Input a directory into the command line
2. Read the first file in the directory
3. Output some stuff from that file
4. Store that stuff
5. Move on to the next file
6. Once the program has seen all the files, print out the stuff
"""
f... |
import scanpy as sc
import pandas as pd
import numpy as np
import scipy
import os
from anndata import AnnData,read_csv,read_text,read_mtx
from scipy.sparse import issparse
def prefilter_cells(adata,min_counts=None,max_counts=None,min_genes=200,max_genes=None):
if min_genes is None and min_counts is None and max_ge... |
#File to load modules |
from nipype import logging
logger = logging.getLogger('workflow')
import nipype.pipeline.engine as pe
import nipype.interfaces.fsl as fsl
import nipype.interfaces.utility as util
from nipype.interfaces.afni import preprocess
# workflow to edit the scan to the proscribed TRs
def create_wf_edit_func(wf_name="edit_fun... |
#!/usr/bin/python
# Philip Tenteromano
# Antonio Segalini
# 2/12/2019
# Big Data Programming
# Lab 1
# Reducer file
# PART 1
# comments added for detailed explaination
from operator import itemgetter
import sys
# nested lists to track ip by time
dict_hours = {}
dict_ip_count = {}
for line in sys.stdin:
line = ... |
from mmap import mmap
from DyldExtractor.structure import Structure
from DyldExtractor.macho.macho_structs import (
segment_command_64,
section_64
)
class SegmentContext(object):
seg: segment_command_64
sects: dict[bytes, section_64]
sectsI: list[section_64]
def __init__(self, file: mmap, segment: segment_... |
# pylint: disable=missing-docstring, no-name-in-module, invalid-name
from behave import then
from nose.tools import assert_is_not_none, assert_in
@then("an error saying \"{message}\" is raised")
def an_error_is_raised(context, message):
assert_is_not_none(context.error, "Expected an error saying {:s}".format(mess... |
# Copyright 2021 The Brax Authors.
#
# 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 wri... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_newMission.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayou... |
"""Script for building an Annoy index of text embeddings."""
import argparse
import itertools
import logging
import sys
import time
from multiprocessing import Process, Manager, cpu_count
import coloredlogs
import numpy as np
from annoy import AnnoyIndex
from gensim.models.keyedvectors import KeyedVectors
from tqdm i... |
from typing import List
from timetrackerctl.model.ticket import Ticket
from timetrackerctl.tasks.source import AbstractSource
class SavedSource(AbstractSource):
@property
def name(self):
return "saved"
def list(self) -> List[Ticket]:
lst = []
for t, msg in zip(
se... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
import AvrService_pb2 as AvrService__pb2
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
class ConnectionServiceStub(object):
"... |
# Generated by Django 3.0.11 on 2020-12-17 09:16
from django.db import migrations, models
import ipapub.contenttyperestrictedfilefield
import ipapub.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='UpFi... |
# -*- coding: utf-8 -*-
import random
import math
import os
import json
import time
import networkx as nx
import scipy
import numpy as np
#import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from tqdm import tqdm
import pathos
#from pathos.multiprocessing import Processing... |
from rest_framework.generics import GenericAPIView as View, get_object_or_404
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.status import HTTP_201_CREATED, HTTP_205_RESET_CONTENT
from ecommerce.permissions import IsObjectOwner
from store.models ... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: Qot_GetUserSecurityGroup.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf imp... |
"""
Copyright © 2020. All rights reserved.
Author: Vyshinsky Ilya <ilyav87@gmail.com>
Licensed under the Apache License, Version 2.0
http://www.apache.org/licenses/LICENSE-2.0
"""
import numpy as np
import copy
from scores.func import *
from scores.FormulaVertex import FormulaVertex
from scores.FormulaTree import Form... |
import json
def user_login(self, name, password):
return self.client.post(
'/api/v1/login',
data=json.dumps({'name': name, 'password': password})
)
|
from django.shortcuts import render
from .models import CustomUser
from posts.models import Post
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import RedirectView
from django.urls... |
from datetime import datetime
import pandas as pd
import numpy as np
from optimization.performance import *
now = datetime.now().date()
# -------------------------------------------------------------------------- #
# Helper Functions #
# ... |
#!/usr/bin/env python3
from random import randint, sample, uniform
from acme import Product
# Useful to use with random.sample to generate names
ADJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved']
NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???']
def generate_products(num_products=30... |
import logging
import os
from glob import glob
from subprocess import CalledProcessError, check_output
from tempfile import TemporaryDirectory
from typing import Dict, List
from zipfile import ZipFile
import rasterio
import requests
from stactools.worldpop.constants import API_URL, TILING_PIXEL_SIZE
from stactools.wo... |
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals, print_function
from django_datawatch.backends.base import BaseBackend
try:
from unittest import mock
except ImportError:
import mock
from django.test.testcases import TestCase, override_settings
from django_datawatch.datawatch import datawatch... |
import unittest
import numpy as np
from parsing.math_encode import tensor_encode, tensor_decode, get_action_tensor, tensor_decode_fen
from parsing.parsing_constant import *
from parsing.data_generation import parse_pgn, sample_intermediate_states, generate_dataset
from parsing.data_generation import save_tensor_data, ... |
import uproot
import os
import pandas as pd
import numpy as np
import awkward
from tqdm import tqdm
def extract_scalar_data(events, branches, entrystop=None, progressbar=False):
data = {}
data["event"] = events.array("event", entrystop=entrystop)
for br in tqdm(branches, disable=not progressbar):
... |
from sstcam_simulation.photoelectrons import Photoelectrons
from sstcam_simulation.camera.noise import GaussianNoise
from sstcam_simulation.camera.pulse import GaussianPulse
from sstcam_simulation.event.acquisition import EventAcquisition
from sstcam_simulation.camera import Camera, SSTCameraMapping
import numpy as np
... |
#!/usr/bin/python3
# requirements:
# pip3 install mwapi mwreverts jsonable mwtypes
# see https://pythonhosted.org/mwreverts/api.html#module-mwreverts.api
import mwapi
import mwreverts.api
import csv
total = 0
reverted = 0
missing = 0
errors = 0
# generate a CSV of revision IDs with revision_ids_for_campaign.rb
wi... |
from claripy import Annotation
__author__ = "Xingwei Lin, Fengguo Wei"
__copyright__ = "Copyright 2018, The Argus-SAF Project"
__license__ = "Apache v2.0"
class JfieldIDAnnotation(Annotation):
"""
This annotation is used to store jfieldID type information.
"""
def __init__(self, class_name=None, fie... |
from Colors import Colors
class WireSequences:
def __init__(self):
self._wireSequences = { Colors.RED: ['C', 'B', 'A', 'AC', 'B', 'AC', 'ABC', 'AB', 'B'],
Colors.BLUE: ['B', 'AC', 'B', 'A', 'B', 'BC', 'C', 'AC', 'A'],
Colors.BLACK: ['A... |
import unittest
import mongomock
from dasbot.db.stats_repo import StatsRepo
class TestStatsRepo(unittest.TestCase):
def setUp(self):
scores_col = mongomock.MongoClient().db.collection
stats_col = mongomock.MongoClient().db.collection
self.stats_repo = StatsRepo(scores_col, stats_col)
... |
# proxy module
from traitsui.wx.constants import *
|
import datetime
from tkapi.stemming import Stemming
from tkapi.besluit import Besluit
from tkapi.zaak import Zaak
from tkapi.zaak import ZaakSoort
from tkapi.persoon import Persoon
from tkapi.fractie import Fractie
from tkapi.util import queries
from .core import TKApiTestCase
class TestStemming(TKApiTestCase):
... |
import math
def finalInstances (instances, averageUtil):
"""
:type instances: int
:type averageUtil: List[int]
:rtype: int
"""
ptr = 0
while ptr < len(averageUtil):
if 25 <= averageUtil[ptr] <= 60:
ptr += 1
elif averageUtil[ptr] < 25 and instances > 1:
... |
import sys, os
sys.path.append(os.path.dirname(__file__))
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import pandas as pd
def MyCodeFile():
return(__file__)
#https://www.guru99.com/pytorch-tutorial.html
#https://nn.readthedocs.io/en/rtd/index.html
class NN_1_1(nn.Module):... |
# %%
import pickle
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.multioutput import MultiOutputClassifier
from sklearn.pipeline import make_pipeline
# %%
CATEGORIES = ["toxic", "severe_toxic", "obscene", "threat", "insult"... |
import sys
import os
import unittest
from nose.plugins.attrib import attr
# To change this, re-run 'build-unittests.py'
from fortranformat._input import input as _input
from fortranformat._lexer import lexer as _lexer
from fortranformat._parser import parser as _parser
import unittest
class ENEditDescriptorBatch3Te... |
sql_locations = [
"/opt/skytools2/share/skytools",
]
package_version = "2.1.13"
|
from unittest import mock
import json
import unittest
from src.backend.vt import manager
import tests
class TestFunctions(unittest.TestCase):
@mock.patch("src.backend.vt.extractor.RequestIP")
def test_get_analysis_of_ip(self, mock_request_ip):
with open(tests.IP_RESPONSE_PATH, "r") as f:
... |
import fileinput
class odor():
def __init__(self, index, name, glom_weights):
self.index = index
self.name = name
self.glom_weights = glom_weights
odors = {} # by name
for line in fileinput.input('input-odors.txt'):
data = line.split('\t')
odors.update({data[0]: odor(fileinput.lineno(), data[0], [f... |
#! /usr/bin/env python
# example of for loop in advance
# example of parallel iteration
names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
for i in range(len(names)):
print names[i], 'is', ages[i], 'years old'
# parallel iteration is the built-in function zip
print "using zip:", zip(names, ages)... |
# --------------------------------------------------------------------------
# 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 cause incor... |
class Solution(object):
def pow(self, n, a):
result = 1
while a > 0:
if a % 2:
result = int((result * n) % 1000000007)
n = int((n ** 2) % 1000000007)
a //= 2
return result
def cuttingRope(self, n):
"""
:type n: int
... |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license.
# Standard imports
import json
import os
from datetime import datetime, timedelta
# Third party imports
import numpy as np
import pandas as pd
import rasterio
import xarray as xr
from statsmodels.nonparametric.smoothers_lowess import lo... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
result = 0
def dfs(node):
nonlocal L, R, resul... |
n=int(input("Enter a number "))
sum=0
for x in range(1,n):
sum=sum+x
print(x,end='+')
print(n,"=",sum+n)
|
# camera
from .camera.CameraSingleFrame import CameraSingleFrame
from .camera.CameraMultiFrame import CameraMultiFrame
from .camera.CameraContinuous import CameraContinuous
# video
from .video.VideoAVI import VideoAVI
from .video.VideoMJPG import VideoMJPG
from .video.VideoH264 import VideoH264
# system
from .Interfa... |
# Copyright 2018 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, s... |
#!/usr/bin/env python
"""
Daemon to run sbt in the background and pass information back/forward over a
port.
"""
import logging
import socket
import subprocess
from daemon import runner # pylint: disable=no-name-in-module
def dispatch(workdir, command):
"""Determine whether we will "foreground" or "backgro... |
from graphviz import Digraph
from torch.autograd import Variable
import torch
def make_dot(var, params=None):
if params is not None:
assert isinstance(params.values()[0], Variable)
param_map = {id(v): k for k, v in params.items()}
node_attr = dict(style="filled", shape="box", align=... |
from utils import detector_utils as detector_utils
from utils import pose_classification_utils as classifier
import cv2
import tensorflow as tf
import multiprocessing
from multiprocessing import Queue, Pool
import time
from utils.detector_utils import WebcamVideoStream
import datetime
import argparse
import os;
os.env... |
'''
*
* Copyright (C) 2020 Universitat Politècnica de Catalunya.
*
* 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 requi... |
"""Test the protocol.application.stacks module."""
# Builtins
# Packages
from phylline.links.loopback import BottomLoopbackLink, TopLoopbackLink
from phylline.pipelines import PipelineBottomCoupler
from phyllo.protocol.application.stacks import make_minimal, make_pubsub
from phyllo.protocol.communication import Aut... |
import copy
import datetime
import functools
import os
import sys
import time
from pathlib import Path
from random import shuffle
import pygame.midi
# import cProfile
# from music21 import *
last_update_time = time.time()
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class Confi... |
import os
import torch
import torch.optim as optim
from confidnet.models import get_model
from confidnet.utils import losses
from confidnet.utils.logger import get_logger
from confidnet.utils.schedulers import get_scheduler
LOGGER = get_logger(__name__, level="DEBUG")
class AbstractLeaner:
def __init__(self, c... |
import os
from PyQt5.QtWidgets import QFileDialog
from app.data.database import DB
from app.editor.data_editor import SingleDatabaseEditor
from app.editor.base_database_gui import DatabaseTab
import app.engine.skill_component_access as SCA
from app.editor.settings import MainSettingsController
from app.editor.skil... |
# 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
# distr... |
from pymongo import MongoClient
__author__ = 'Parry'
from gensim.models import LdaModel
from gensim import corpora
from Constants import Parameters
dictionary = corpora.Dictionary.load(Parameters.Dictionary_path)
corpus = corpora.BleiCorpus(Parameters.Corpus_path)
lda = LdaModel.load(Parameters.Lda_model_path)
c... |
import os
class Config:
STEAM_API_KEY = os.environ.get("STEAM_API_KEY")
|
#!/usr/bin/env python3
from typing import List
from cereal import car, log
from math import fabs
from common.numpy_fast import interp
from common.conversions import Conversions as CV
from selfdrive.car import STD_CARGO_KG, scale_rot_inertia, scale_tire_stiffness, is_ecu_disconnected, gen_empty_fingerprint, get_safety_... |
import io
import os
from typing import List, NamedTuple, Text
from urllib.parse import quote, urljoin
from httpx import Client
from PIL import Image
from bernard.conf import settings
class Size(NamedTuple):
"""
Represents a size
"""
width: int
height: int
class Color(NamedTuple):
"""
8-... |
"""
Word Mover Distance
"""
from collections import Counter
from dataclasses import dataclass, field
from itertools import product
from typing import Dict, List, Tuple
from dataclasses_jsonschema import JsonSchemaMixin
import numpy as np
import pulp
from scipy.spatial.distance import euclidean
from docsim.elas.search... |
"""
A skip list implementation.
Skip list allows search, add, erase operation in O(log(n)) time with high probability (w.h.p.).
"""
import random
class Node:
"""
Attributes:
key: the node's key
next: the next node
prev: the previous node
bottom: the bottom node in skip l... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 4 15:41:40 2020
@author: MBelobraydic
"""
import codecs
from dbf900_formats import pic_yyyymmdd, pic_yyyymm, pic_numeric, pic_any, pic_latlong, pic_coord
def decode_file(file, block_size): ##Requires string for the file location and integer for blocksize
print('ope... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Osman Baskaya"
s10aw = "../data/semeval10/aw/test/English/EnglishAW.test.xml"
s10wsi = "../data/semeval10/wsi"
s07aw = "../data/semeval07/all-words/english-all-words.test.xml"
s3aw = "../data/senseval3/english-all-words.xml"
s2aw = "../data/senseval2/english-al... |
import cPickle as pickle
import codecs
import random
from collections import defaultdict
from itertools import izip
from os.path import dirname, realpath, join
import numpy as np
import torch.optim as optim
import unicodedata
import sys
from editor_code.copy_editor import data
from editor_code.copy_editor.attention_d... |
import pathlib
import re
import sys
from contextlib import contextmanager
from typing import Any, Dict, Generator, Optional, Tuple
from urllib.parse import urlparse
import click
import hypothesis
from .. import utils
def validate_schema(ctx: click.core.Context, param: click.core.Parameter, raw_value: str) -> str:
... |
# IAM policy ARN's list in this variable will be checked against the policies assigned to all IAM
# resources (users, groups, roles) and this rule will fail if any policy ARN in the blacklist is
# assigned to a user
IAM_POLICY_ARN_BLACKLIST = [
'TEST_BLACKLISTED_ARN',
]
def policy(resource):
# Check if the IA... |
import time
def read_file(name):
with open(f"files/input{name}") as f:
content = f.readlines()
return [x.strip() for x in content]
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
print(f"\nTime required: {(time.time() -... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.