content stringlengths 5 1.05M |
|---|
from rest_framework import viewsets, generics
from rest_framework.authentication import BasicAuthentication
from rest_framework.permissions import IsAuthenticated, DjangoModelPermissions
from escola.models import Aluno, Curso, Matricula
from escola.serializer import AlunoSerializer, AlunoSerializerV2, CursoSerializer, ... |
import bbb
class IR_AIN(object):
#by default, travel is on ADC0, pos is on ADC1
def __init__(self, anum):
self.adc = bbb.ADC( anum )
self.ratio = 1 #normalization ratio
self.thresh = 1
def val(self):
# adcs are 12-bit, but report a millivolt value via SysFS
n = 5
samples = [ self.... |
import os
# rename files based on the actual file name, excluding the additional kobocat
# directories from name
files = len(os.listdir('.'))
i = 1
print('This directory has '+str(files)+' files.')
for filename_old in os.listdir('.'):
filename, file_extension = os.path.splitext(filename_old)
if file_extension == ... |
# Time: O(h * p^2), p is the number of patterns
# Space: O(p^2)
# bitmask, backtracking, dp
class Solution(object):
def buildWall(self, height, width, bricks):
"""
:type height: int
:type width: int
:type bricks: List[int]
:rtype: int
"""
MOD = 10**9+7
... |
from html.parser import HTMLParser
from urllib.request import urlopen
from urllib import parse
import time
from datetime import date
import re
# We are going to create a class called LinkParser that inherits some
# methods from HTMLParser which is why it is passed into the definition
class ResultsPrinter:
def... |
"""
Migration script
"""
from pymongo import MongoClient
from tqdm import tqdm
def migrate(target_db, target_coll, new_coll_name='disp_entry', client=None):
"""
Migrate the database to the ODM style
"""
if not client:
client = MongoClient()
database = client[target_db]
col = database[... |
tagcomponent = "disagg"
target_capacity = 2
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 15 21:50:26 2016
save chessboard pattern and image conrners to a file for later calibration (so
as not to do it again for every calibration model)
@author: lilian+sebalander
"""
# %%
import cv2
import glob
import numpy as np
import matplotlib.pyplot as plt
# %%
hayquegr... |
import os
import os.path as osp
import time
import tabulate
import joblib
import numpy as np
import tensorflow as tf
from baselines import logger
from baselines.a2c.utils import Scheduler, find_trainable_variables
from baselines.a2c.utils import cat_entropy
from baselines.a2c.utils import discount_with_dones
from basel... |
from typing import Tuple
from random import shuffle
import numpy as np
from mlpipe.utils import MLPipeLogger, Config
from mlpipe.data_reader.mongodb import MongoDBConnect
def load_ids(
col_details: Tuple[str, str, str],
data_split: Tuple = (60, 40),
sort_by: dict = None,
limit: int = N... |
"""
Given a 2D matrix matrix, find the sum of the elements inside the rectangle
defined by its upper left corner (row1, col1) and lower right corner
(row2, col2).
Range Sum Query 2D
[
[3, 0, 1, 4, 2],
[5, 6, 3, 2, 1],
[1, [2, 0, 1,] 5],
[4, [1, 0, 1,] 7],
[1, [0, 3, ... |
# Copyright 2016 OpenStack Foundation
# 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 requ... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from pathlib import Path
import spacy
import srsly
import typer
from spacy.kb import KnowledgeBase
from spacy_ann.candidate_generator import CandidateGenerator
from spacy_ann.types import kb_type_vs_index
from wasabi import ... |
from django.contrib import admin
# Register your models here.
from .models import Ftwhl
admin.site.register(Ftwhl)
|
import wandb
import logging
from typing import Optional
from pytorch_lightning.loggers import WandbLogger
class SilentWandbLogger(WandbLogger):
"""Wandb logger wrapper that updates the log visibility from the client after initialization.
"""
def __init__(self, *args, **kwargs):
super().__init__(*... |
from django.test import TestCase, Client
from .models import Profile
from django.contrib.auth.models import User
import unittest
from .forms import SignUpForm
from .signals import show_login_message, show_logout_message
from django.contrib.auth.signals import user_logged_out, user_logged_in
from django.contrib i... |
import os
import time
from krgram.tl.base import TLSerializable
from krgram.utils.bytes import Bytes
class MsgId(TLSerializable):
def __init__(self, delta = 0.0):
self.delta = float(delta)
self.curr = self()
def __call__(self):
now = time.time() + self.delta
now_sec = int(now)
frac = int((now - float(no... |
from glob import iglob
from pathlib import Path
from typing import Iterable, Union
def normalize_path(path: Union[str, Iterable[Union[Path, str]]]) -> Iterable[Path]:
# Convert a single instance to an interable
if type(path) is str:
path = [path]
def handle_path(path_obj: Path):
if path_o... |
from .loss import nce_loss, negative_sampling_loss
|
"""Subject definitions for project"""
from __future__ import absolute_import
import seaborn as sns
from six.moves import zip
BEHAVE_SUBJS = ["B979", "B1107", "B1082", "B1218", "B1222", "B1101", "B1088", "B1105"]
BEHAVE_COLORS = [
"nice blue",
"windows blue",
"off blue",
"stormy blue",
"fern",
"... |
from typing import Dict, Any
import numpy as np
import os
class RandomSearch:
@staticmethod
def random_choice(*args):
choices = []
for arg in args:
choices.append(arg)
return lambda: np.random.choice(choices)
@staticmethod
def random_integer(low, high):
re... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^showprofile/$', views.showprofile, name='showprofile'),
url(r'^home/$', views.home, name='home'),
url(r'^homegraph/$', views.homegraph, name='homegraph'),
url(r'^addprofile/$', views.addprofile, name='addprofile'),
url(r'^predict/$', view... |
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.dummy import DummyClassifier
class ModelsHandler:
def __init__(self):
# empty init
pass
@staticmethod
def get_models(classifiers:... |
import asyncio
import json
import logging
import sqlalchemy
import shutil
from flask import request, url_for, jsonify, make_response, Response, send_file
from flask_restful import Api, Resource, fields, marshal, marshal_with
from werkzeug.exceptions import Conflict, UnprocessableEntity
from meltano.core.job import Job... |
def test_import_biopython():
import Bio
|
"""Tag the sandbox for release, make source and doc tarballs.
Requires Python 2.6
Example of invocation (use to test the script):
python makerelease.py --force --retag --platform=msvc6,msvc71,msvc80,mingw -ublep 0.5.0 0.6.0-dev
Example of invocation when doing a release:
python makerelease.py 0.5.0 0.6.0-dev... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="nbspellcheck",
version="0.0.3",
author="Colin Bernet",
author_email="colin.bernet@gmail.com",
description="Spell checker for jupyter notebooks",
long_description=long_description,
... |
import xgboost as xgb
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
def grid_matrix():
param_grid_reg = {
'C': [0.01,0.1,1,10],
}
model_reg = LogisticRegression(solver='liblinear', pen... |
import hyperparameters as h
from rl_botics.common.data_collection import *
from rl_botics.common.policies import *
from rl_botics.common.utils import *
import tensorflow as tf
class REINFORCE:
def __init__(self, args, sess, env):
"""
Initialize REINFORCE agent class
"""
self.se... |
import frappe
from frappe import _
@frappe.whitelist()
def payment_on_submit(self, method):
fwd_uti(self, method)
total_uti(self,method)
@frappe.whitelist()
def payment_on_cancel(self, method):
fwd_uti_cancel(self, method)
total_uti(self,method)
#On Submit Payment
def fwd_uti(self, method):
if self.forward_co... |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# ip.reportvpnstatus
# ---------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# -------------------------------------------------------------... |
import datetime
import django_filters
from rest_framework import filters
from rest_framework import generics
from rest_framework.response import Response
from .models import Posts
from .serializer import PostsSerializer
DATE_FORMAT = "%Y-%m-%d"
START_DATE = "2000-01-01"
class PostsView(generics.ListAPIView):
... |
from nanpy.arduinoboard import arduinomethod, returns, FirmwareClass
from nanpy.classinfo import check4firmware
from nanpy.memo import memoized
@check4firmware
class EepromLib(FirmwareClass):
firmware_id = 'EEPROM'
@arduinomethod
def write(self, address, value):
pass
@returns(int)
@ardui... |
import os
from zipfile import ZipFile
from celery import shared_task
from PIL import Image
from django.conf import settings
from clustalanalysis import run_clustal
@shared_task
def create_tree(inputfile, outputfile):
try:
print("This is clustal function")
result_file = run_clustal.run_clustal(i... |
from rest_framework.authtoken.models import Token
from rest_framework.authentication import TokenAuthentication
from rest_framework.exceptions import AuthenticationFailed
from django.utils import timezone
from django.conf import settings
def expires_in(token):
time_elapsed = timezone.now() - token.cre... |
from posixpath import dirname
from flask import Flask, request, render_template,redirect, url_for,abort,send_from_directory
from werkzeug.utils import secure_filename
import os.path
import tempfile
import io
import os
import base64
from datetime import datetime
from pathlib import Path
import torchvision
from torchvi... |
#! /usr/bin/env python
import urllib2
from xml.dom import minidom, Node
class RSSItem:
def __init__(self,title="",description="", link="",pubDate = ""):
self.title = title
self.description = description
self.link = link
self.pubDate = pubDate
class RSSReader:
name = ""
def __init__(self,R... |
import unittest
from fuzzystring import FuzzyString
class FuzzyStringTests(unittest.TestCase):
"""Tests for FuzzyString."""
def test_constructor(self):
FuzzyString("hello")
def test_equality_and_inequality_with_same_string(self):
hello = FuzzyString("hello")
self.assertEqual(h... |
#
#
# 0=================================0
# | Project Name |
# 0=================================0
#
#
# ----------------------------------------------------------------------------------------------------------------------
#
# Implements: Support Vector Machine
#
# --------------... |
import os
import re
import sys
import time
from threading import Thread
from hive_gns.database.access import write
from hive_gns.database.haf_sync import HafSync
from hive_gns.engine.hook_processor import HookProcessor
from hive_gns.engine.pruner import Pruner
from hive_gns.server import system_status
from hive_gns.se... |
import random
import json
import sys
from paho.mqtt import client as mqtt_client
"""
Test app listening to all SmartSleep topics
"""
broker = 'broker.emqx.io'
port = 1883
topic = "SmartSleep/#" # '#' is a special character, meaning all topics starting with SmartSleep will be covered
# generate client ID with pub prefi... |
from django.conf import settings
from django.contrib import messages
from django.http import JsonResponse, HttpResponseRedirect
from django.urls import reverse_lazy
from django.views import View
from django.views.generic import ListView, CreateView
from django.views.generic.detail import SingleObjectMixin
from django.v... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from matplotlib.animation import FuncAnimation, PillowWriter
import matplotlib.patches as mpatches
from matplotlib.legend_handler import HandlerPatch, HandlerCircleCollection
import pandas as pd
from mpl_toolkits.mplot3d import Ax... |
import logging
import gensim
from docs import config
from optparse import OptionParser
from lib.corpora import corpus_word_count
logging.basicConfig(format="%(asctime)s : %(levelname)s : %(message)s", level=logging.INFO)
# Build this program's option parser
def build_opt_parser():
usage = "usage: %prog [options] ... |
'''
Module:
Set plotting range for axis
'''
def set_range(f, n, d, xbeg, xend):
# sampling point begin and end
sample_beg = float(f)
sample_end = sample_beg + (n - 1) * d
# limit of axis
if xbeg is None:
xbeg = sample_beg
else:
xbeg = float(xbeg)
if xen... |
import time
import os
import pyautogui
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("nwapp=" + os.path.dirname(os.path.abspath(__file__)))
driver = webdriver.Chrome(executable_path=os.environ['CHROMEDRIVER'], chrome_option... |
# This problem was recently asked by Apple:
# Given an integer k and a binary search tree, find the floor (less than or equal to) of k, and the ceiling (larger than or equal to) of k. If either does not exist, then print them as None.
class Node:
def __init__(self, value):
self.left = None
self.ri... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('permissions', '0003_remove_role_name'),
]
operations = [
migrations.AlterField(
model_name='role',
name='label',
field=models.CharField(
h... |
class Solution:
def constructRectangle(self, area):
"""
:type area: int
:rtype: List[int]
"""
primes = 1
n = area
index = int(n ** 0.5)
while index >= 1:
if area % index == 0:
factor = area // index
if fact... |
__author__ = 'Bob'
from django import template
from django.contrib.auth.models import Group
register = template.Library()
@register.filter(name='hasGroup')
def hasGroup(user, group_name):
try:
group = Group.objects.get(name=group_name)
return True if group in user.groups.all() else False
excep... |
from typing import Iterable, List, Optional, Tuple
from plenum.common.messages.node_messages import ViewChangeDone
from plenum.server.router import Route
from stp_core.common.log import getlogger
from plenum.server.primary_decider import PrimaryDecider
from plenum.server.replica import Replica
logger = getlogger()
... |
import os
import warnings
from . import python_aio, python_aio_asyncio
from .abstract import AbstractContext, AbstractOperation
from .version import __author__, __version__
try:
from . import linux_aio
from . import linux_aio_asyncio
except ImportError:
linux_aio = None # type: ignore
linu... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
class AnyCSVException(Exception):
pass
class NoDelimiterException(AnyCSVException):
pass
class FileSizeException(Exception):
pass |
import dash
# contains widgets that can be dropped into app
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from dash.dependencies import Input, Output, State
import pandas as pd
import pickle
# https://dash.plot.ly/dash-core-components
########### Initiate the ap... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# abc 用于实现抽象类
from abc import ABCMeta, abstractmethod
# 过滤器
class Filter:
__metaclass__ = ABCMeta
def __init__(self): pass
@abstractmethod
def filter(self, file_name): pass
|
import glob
import os
import time
from .utils.utils import pickle_read, pickle_dump
from .disk.operations import purge_id_in_cache
def list_keys_to_purge(directory, days_thresh, access_thresh,
include_uncounted=False):
counter_path = os.path.join(directory, 'counter.pkl')
counter = pick... |
import requests
import json
import os
import sys
import pymysql
# Database and table name
mysql_db_name = "checklist"
mysql_db_table = "items"
use_ssl = "yes"
# Format a string to be included in a SQL query as value
def escape_quotes(this_value):
return str(this_value).replace("'", "\\'")
# Get database credenti... |
# Configuration
# [Yoshikawa Taichi]
# version 2.4 (Jan. 29, 2020)
class Configuration():
'''
Configuration
'''
def __init__(self):
# ----- Neural network components -----
## Neuron numbers in input-layer
self.input_size = 4
## Neuron numbers in hidden-layer... |
from django.conf.urls import *
from .api_views import APIShippingArchiveQualitySummaryReportViewSet, APIShippingTripStatusReportViewSet
urlpatterns = [
url(r'^org/quality/summary/(?P<org_slug>[^/]+)/$',
APIShippingArchiveQualitySummaryReportViewSet.as_view(),
name='api-org-quality-summary'),
u... |
# Generated by Django 3.1.7 on 2021-03-23 20:20
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('products', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ProductSize',
fields=[
... |
# -*- coding: utf-8 -*-
#__date__ = 7/26/18
#__time__ = 10:51 AM
#__author__ = isminilourentzou
import logging
from itertools import count
import os
import numpy as np
from config import opt, additional_args
import lib
import time
start_time = time.time()
additional_args(opt)
N_SAMPLES = opt.nsamples
logging.basicCo... |
def _char_value(c):
assert 'A' <= c <= 'Z'
return ord(c) - ord('A') + 1
def _value_of_name(name):
return sum([_char_value(c) for c in name])
def names_scores(names):
names_sorted = sorted(names)
res = 0
for i in xrange(len(names_sorted)):
res += (i + 1) * _value_of_name(names_sorted[... |
# -*- coding: utf-8 -*-
from . import logistic_interface as LI
import os
import sys
from datetime import datetime
def execute(init_x:float = 0.1,
record_num:int = 500,
iterate_num:int = 5000,
a_interval:float = 0.005,
a_min:float = 2.5,
file_name:str= datetime.now... |
from past.builtins import basestring
from snovault import upgrade_step
from .shared import ENCODE2_AWARDS, REFERENCES_UUID
from pyramid.traversal import find_root
import re
def fix_reference(value):
if not isinstance(value, basestring):
raise ValueError(value)
return value.replace('PUBMED:', 'PMID:').... |
# -*- coding: utf-8 -*-
from scrapy.cmdline import execute
import sys
import os
print(os.path.dirname(os.path.abspath(__file__)))
# os.path.abspath(__file__) 获取到main文件的绝对路径, os.path.dirname获取到父目录
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
execute(["scrapy", "crawl", "jobbole"])
|
import logging
import telegram
class TelegramLogsHandler(logging.Handler):
def __init__(self, debug_bot_token, chat_id):
super().__init__()
self.debug_bot = telegram.Bot(debug_bot_token)
self.chat_id = chat_id
def emit(self, record):
log_entry = self.format(record)
sel... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
# Distributed under the MIT licesnse.
# Copyright (c) 2013 Dave McCoy (dave.mccoy@cospandesign.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... |
from .adc import Adc
from .and_ import And
from .asl import Asl
from .eor import Eor
from .lsr import Lsr
from .ora import Ora
from .rol import Rol
from .ror import Ror
from .sbc import Sbc
|
from dnnv.properties import *
N = Network("N")
Forall(
x,
Implies(
(0 <= x <= 1),
And(
abs(N(x)[0, 3] - N(x)[0, 9]) < abs(N(x)[0, 3] - N(x)[0, 2]),
abs(N(x)[0, 3] - N(x)[0, 9]) < abs(N(x)[0, 9] - N(x)[0, 2]),
),
),
)
|
import sys
instructions = 'LOAD STORE IN OUT ADD SUB MUL DIV MOD AND OR XOR JUMP JZ JLZ JGZ'.split()
address = {}
current_address = 0
def assemble_label(words):
address[words[0][:-1]] = current_address
return assemble(words[1:])
def assemble_number(words):
if len(words) > 1 and not words[1].startswith('... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import copy
import os
import json
import cv2
from detectron2.data import DatasetCatalog, MetadataCatalog
from detectron2.structures import Boxes, BoxMode
# from .coco import load_coco_json, load_sem_seg
"""
This file contains functions to registe... |
from django.conf import settings
from django.contrib import auth
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from registration.forms import RegistrationForm
def register(request, nex... |
#!/usr/bin/env python3
import logging
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(name)-15s %(levelname)-8s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S")
logger = logging.getLogger(__name__)
import asyncio
import collections
import json
import os
import aiohttp... |
import socket
import ssl
import time
import threading
import json
from src.server.server_utilities import prepare_message
from src.server.server_strings import *
from src.server import server_data
SERVER_IP = "127.0.0.1"
SERVER_PORT = 9999
PLAYER_NAME = input("Enter a display name: ")
while len(PLAYER_NAME) == 0:
... |
from django.conf.urls import url
from django.urls import path, include
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView, TokenVerifyView
)
from .views import create_user_view, SignupMailSentView, SignupDomainError, create_org_addition_request, RequestOrgAdditionSuccess, \
... |
from dataflow import *
from var import * |
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from collections import Counter
from collections import defaultdict
from sklearn.tree import DecisionTreeClassifier,plot_tree
import time
import matplotlib.pyplot as plt
class CartTree_Category_Lib:
"""
... |
from gamelib import event
from gamelib.util import resources, sound
msges = {}
B_RIGHT = 15 #to 3d
B_LEFT = 29 #to 3a
B_TOP = 6 #to 3e
RED_FOREIGN_KEY = 200
YELLOW_FOREIGN_KEY = 25
GENERATOR = 26
GENERATOR_IN = 7
GENERATOR_OUT = [8, 9]
BOMB = 47
FROM_E_LOC = 43
TANK_L = 250
TANK_M = 23
TANK_R = 24
... |
import numpy as np
import cv2.cv2 as cv2
from digital_image_processing.tools.logger_base import log as log_message
def hough_transform(img_to_hough: np.array, img_original: np.array) -> np.array:
"""Runs the Hough Transform algorithm
Reference:
Coste, Arthur. (2012). Image Processing : Hough Transform. ... |
import numpy as np
#np.random.seed(777)
import chainer
from chainer import cuda
from chainer import serializers
import chainer.functions as F
import argparse
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import PIL
from PIL import ImageDraw
parser = argparse.ArgumentParser()
group = parser.add_mutually_exc... |
import csv
import logging
from pantomime.types import CSV
from collections import OrderedDict
from followthemoney.types import registry
from followthemoney.util import sanitize_text
from ingestors.support.temp import TempFileSupport
from ingestors.support.encoding import EncodingSupport
log = logging.getLogger(__name... |
"""
This module attempts to create a profile detecting the preconditions needed for primitives
Created by Daniel Garijo
"""
from os import listdir
from os.path import isfile, join
import json
import pandas as pd
from d3m import index
import primitive_interfaces
import sys
import numpy as np
#Data: dataset to test (fro... |
from google.colab import drive
drive.mount('/content/drive')
import nltk
nltk.download('stopwords')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models impo... |
from mock import patch, Mock
from simplescraper import SimpleScraper
import os
import codecs
import sys
if sys.version_info[0] < 3:
callableClass = 'urllib2.urlopen'
else:
callableClass = 'urllib.request.urlopen'
def get_request_mock(success=True):
read_data = []
code_status = []
request_mock = Mock()
#set mult... |
"""
Copyright 2020 Jackpine Technologies Corporation
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 ... |
#!/usr/bin/env python
#
# Parser
#
import sys, os
import orio.tool.ply.lex, orio.tool.ply.yacc
import orio.main.util.globals as g
import orio.module.splingo.ast as ast
#----------------------------------------------------------------------------------------------------------------------
# LEXER
class SpLingoLexer:
d... |
#!/usr/bin/python
# Copyright (c) 2020, 2021 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... |
import numpy as np
def weights(X, remove_self_conn=False):
N = len(X[0])
P = len(X)
W_ij = lambda i, j: (1/N)*sum(X[m][i] * X[m][j] for m in range(P))
if remove_self_conn:
W = [[W_ij(i, j) if i != j else 0 for i in range(N)] for j in range(N)]
else:
W = [[W_ij(i, j) for i in range(N... |
def test(a, b, c, *args, **kwargs):
with 1.22:
print 1.2
print {'s', 'e', 't'}
print ['l', 'i', 's', 't']
print ('t', 'u', 'p', 'l', 'e')
print {'d': '1', 'i': '2', 'c': '3', 't': '4'}
print [x for x in []]
print [x for x in [] if x is not None]
print 123456789
print 0x75BCD1... |
from pywingui.windows import *
from pywingui.wtl import *
from ctypes import c_char
try:
LoadLibrary("SciLexer.DLL")
#except Exception, e:
except:# for compatibility with Python 3 version
MessageBox(0, "The Scintilla DLL could not be loaded.", "Error loading Scintilla", MB_OK | MB_ICONERROR)
#~ raise e
from .scint... |
from math import sqrt
class Vector2D:
def __init__(self,x,y):
self.__x = x
self.__y = y
@property
def x(self):
return self.__x
@property
def y(self):
return self.__y
@x.setter
def x(self,new_x):
self.__x = new_x
@y.setter
def y(self,new_y):
... |
from unittest import TestCase
from dispatcher.configuration_helper import ConfigurationHelper
from .common.mock_resources import *
from dispatcher.packagemanager import memory_repo
from dispatcher.dispatcher_exception import DispatcherException
from inbm_lib.xmlhandler import XmlHandler
from mock import patch
import os... |
#!/usr/bin/env python3
"""A simple pythonic unit conversion API.
Title:
Unit Converter
Description:
Develop a program that converts various units between one another.
The user enters the type of unit being entered,
the type of unit they want to convert to
and then the value.
The program will then make the conversion.... |
"""Unittests for the deepblink.cli module."""
# pylint: disable=missing-function-docstring
from unittest import mock
import argparse
import logging
import os
import numpy as np
import pandas as pd
from deepblink.cli._config import HandleConfig
from deepblink.cli._create import HandleCreate
from deepblink.cli._main im... |
"""
Gregory Way 2018
Interpret Compression
5.analyze-weights/interpret-compression.py
Track and visualize gene set activity across compressed features
Usage:
python interpret-compression.py
Output:
Several geneset enrichment scores and many figures describing enrichment across features
"""
import os
import sub... |
from typing import Optional
from pydantic import BaseModel
class UserBase(BaseModel):
first_name: Optional[str] = None
class UserBaseInDB(UserBase):
id: int = None
username: Optional[str] = None
email: Optional[str] = None
is_active: Optional[bool] = True
is_superuser: Optional[bool] = False... |
#!/usr/bin/env python
#
# Copyright 2016 Marcus Furlong <furlongm@gmail.com>
#
# This file is part of Patchman.
#
# Patchman is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 only.
#
# Patchman is dist... |
"""
Data preproc functions:
adjust_to_see: adjust image to better visualize (rotate and transpose)
augmentation: apply variations to a list of images
normalization: apply normalization and variations on images (if required)
preprocess: main function for preprocess.
Make the image:
il... |
from typing import Dict, List, Optional
import os
import random
import torch
import numpy as np
import pandas as pd
from PIL import Image
from .dataset import SegmentationDataset
from theseus.segmentation.augmentations.mosaic import Mosaic
from theseus.utilities.loggers.observer import LoggerObserver
LOGGER = LoggerOb... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.