content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
""" generated source for module SentenceForm """
# package: org.ggp.base.util.gdl.model
import java.util.List
import org.ggp.base.util.gdl.GdlUtils
import org.ggp.base.util.gdl.grammar.GdlConstant
import org.ggp.base.util.gdl.grammar.GdlSentence
import org.ggp.base.util.gdl.grammar.GdlTerm
# ... |
# forms.py
from django.db import models
from django import forms
from django.forms import ModelForm
from core.models import Question
class AskQuestionForm(ModelForm):
class Meta:
model = Question
fields = [ 'question', 'details', 'tags', 'author', ]
|
import sqlalchemy
from databases import Database
from src.app.settings import settings
db = Database(settings.db_dsn, force_rollback=(settings.environment == "TESTING"))
metadata = sqlalchemy.MetaData()
|
"""Výpočet a vykreslení Wan-Sunova podivného atraktoru."""
# coding: utf-8
# # The Wang - Sun attractor
# Please also see https://hipwallpaper.com/view/9W3CM8
# In[1]:
# import všech potřebných knihoven - Numpy a Matplotlibu
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np... |
# Formatting configuration for locale cs
languages={'gu': u'Gujarat\u0161tina', 'gd': u'Skotsk\xe1 gal\u0161tina', 'ga': u'Ir\u0161tina', 'gn': u'Guaran\u0161tina', 'gl': u'Hali\u010d\u0161tina', 'la': 'Latina', 'ln': u'Lingal\u0161tina', 'lo': u'Lao\u0161tina', 'tt': u'Tatar\u0161tina', 'tr': u'Ture\u010dtina', 'ts':... |
from __future__ import print_function
import argparse
import os
import sys
from .fileio import get_files
from .graphics import match_diagnostic
from .utils import check_boundaries
from .sfh import SFH
def main(argv):
parser = argparse.ArgumentParser(description="Plot match diagnostics")
parser.add_argument(... |
import sys
import os.path
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from Code.MathLib import ecartType
import test_common
import pytest
lower_ecart_type = 5.393
upper_ecart_type = 3694932.426
def test_ecart_type_lower_bound():
assert test_common.isclose(ecartType(test_common.lowerBound), lower... |
# Copyright 2018 ZTE 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 law or agreed to in ... |
#===========================|======================|==================|===========|=======================|========================================================|===============|=============================|=============
# REQ FILE | REQ | TC | PC FILE | MAP FILE ... |
import os
import random
import json
import imgaug
import torch
import numpy as np
import os
import argparse
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
seed = 1234
random.seed(seed)
imgaug.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
torch.backends.cudnn.deterministic = True
to... |
"""POD-NN modeling for 1D Shekel Equation."""
#%% Imports
import sys
import os
import pickle
import meshio
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as plti
from scipy.interpolate import griddata
from scipy.ndimage import map_coordinates
sys.path.append(os.path.join("..", ".."))
from p... |
# OpenWeatherMap API Key
weather_api_key = "your key here"
|
# Copyright 2020 The SODA 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 writin... |
from django.core.management.base import BaseCommand, CommandError
import django.core.management as core_management
from django.db import connection
from device_status import models
from djangoautoconf.model_utils.model_attr_utils import enum_models
class Command(BaseCommand):
args = ''
help = 'Create command... |
class Something:
def __init__(self, stuff):
self.hello = stuff
allthings = [Something(i) for i in range(5)]
many = lambda x: x.hello >= 3
manythings = filter(many, allthings)
for thing in manythings:
print(thing.hello) |
# -*- coding: utf-8 -*-
import os
import re
import codecs
import _pickle as cPickle
from nltk import word_tokenize
from nltk.corpus import stopwords
from sklearn.metrics.pairwise import linear_kernel
from warnings import simplefilter
# ignore all warnings
simplefilter(action='ignore')
domain = ""
locale = ""
intent =... |
import logging
from typing import Tuple, Dict
import gnmi_pb2
VERSION = "0.2.0"
HOST = "localhost"
PORT = 50061
logging.basicConfig(
format='%(asctime)s:%(relativeCreated)s %(levelname)s:%(filename)s:%(lineno)s:%(funcName)s %(message)s [%(threadName)s]',
level=logging.WARNING)
log = logging.getLogger('confd_g... |
from dearpygui.simple import *
from dearpygui.core import *
from assets import properties
from windows.discord import functions
import json
import base
import platform
from mainwindow import webfunc
with open('user/settings.hqs', 'r') as usersettings:
user = json.load(usersettings)
with open(f'languages/{user["la... |
from collections import defaultdict
from commands import SourceSubparser
from models import Variant
from variant_sources import variants_source
from pandas import read_csv
import numpy as np
"""
./snp_parser.py -n -d clinvar_variants clinvar --trait 'Polycystic Kidney Disease'
chrom pos ref alt measure... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = cur = ListNode... |
from enum import Enum
class ColumnTypes(Enum):
Int = 0
String = 1
def to_sql_type(self) -> str:
if self == ColumnTypes.Int:
return "Int"
elif self == ColumnTypes.String:
return "Varchar"
def to_python_type(self) -> type:
if self == ColumnTypes.Int:
... |
# Copyright (c) 2019, The Regents of the University of California
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, thi... |
from unittest import SkipTest
import numpy as np
import pandas as pd
try:
import dask.dataframe as dd
except:
dd = None
from holoviews import Dataset, Curve, Dimension, Scatter, Distribution
from holoviews.core import Apply, Redim
from holoviews.element.comparison import ComparisonTestCase
from holoviews.ope... |
# --------------------------------------------------------------------------------- #
# KNOBCTRL wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 03 Nov 2006
# Latest Revision: 03 Nov 2006, 22.30 CET
#
#
# TODO List
#
# 1. Any idea?
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To M... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright 2015 Pascual Martinez-Gomez
#
# 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
#
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from unittest import TestCase
from itertools import chain
import numpy as np
from numpy.lib import NumpyVersion
import sys
sys.path.append('../')
from fpq.vector import *
import fpq.fp
class TestVector(TestCase):
def test_is_valid_format(self):
... |
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets, decorators, response
from api.permissions import IsSelfOrSuperUser
from rest_framework.permissions import IsAuthenticated, AllowAny
# Serializers define the API representation.
class UserSerializer(serializers.Hyper... |
# Generated by Django 3.0.7 on 2020-08-17 06:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('performance', '0002_auto_20200817_0934'),
]
operations = [
migrations.AlterField(
model_name='departmentkpi',
name='... |
import ad3
import numpy as np
from pystruct.inference.common import _validate_params
class InferenceException(Exception):
pass
def inference_ad3_local(unary_potentials, pairwise_potentials, edges, relaxed=False,
verbose=0, return_energy=False, branch_and_bound=False,
... |
from pyspark.ml.feature import StringIndexer,IndexToString
from pyspark import SparkContext
from pyspark.sql import SQLContext
sc = SparkContext("local", "samp")
sqlContext = SQLContext(sc)
stringDF=sqlContext.createDataFrame([(0, 'a'), (1, 'b'), (2, 'c'), (3, 'a'), (4, 'a'), (5, 'c')], ['id', 'category'])
inde... |
import logging
from slack_bolt.logger import messages
from .constants import (
QUESTIONS_TYPE_EMOJIS_DICT,
QUESTIONS_TYPE_NAMES_DICT,
)
class ConnectCommand:
question_type_names_dict = QUESTIONS_TYPE_NAMES_DICT
question_type_emojis_dict = QUESTIONS_TYPE_EMOJIS_DICT
def __init__(self, client,... |
from yandeley.models.documents import TrashAllDocument, TrashBibDocument, TrashClientDocument, TrashTagsDocument, \
TrashDocument
from yandeley.resources.base_documents import DocumentsBase
class Trash(DocumentsBase):
"""
Top-level resource for accessing trashed documents. These can be:
- trashed do... |
def Sum(value1=1, value2=2):
return value1 + value2
print(Sum())
print(Sum(value1=100))
print(Sum(value2=200))
print(Sum(value1=100, value2=200))
print(Sum(100,200))
print(Sum(100))
|
from test import TestProtocolCase, bad_client_wrong_broadcast, bad_client_output_vector
import random
import time
class TestProtocol(TestProtocolCase):
def test_001_cheat_in_sending_different_keys(self):
good_threads = self.make_clients_threads(with_print = True, number_of_clients = self.number_of_players... |
"""
https://www.codewars.com/kata/578553c3a1b8d5c40300037c/train/python
Given an array of 1s and 0s, return the equivalent binary value to an integer.
binary_array_to_number([0,0,0,1]), 1
binary_array_to_number([0,0,1,0]), 2
binary_array_to_number([1,1,1,1]), 15
binary_array_to_number([0,1,1,0]), 6
"""
from typing im... |
import os
import os.path
import pickle
import re
import sys
from fnmatch import filter
from PIL import Image
class PyRewrite():
def __init__(self):
self.config_path = '/'.join(
[os.getenv('HOME'), '.pyrewrite'])
def check_if_config_file_exists(self):
"""Check if config file exis... |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 2 07:15:26 2022
@author: ACER
"""
# lista en blanco
lista = []
#lista con elementos
ñistElementos = [1,3,4,5]
#acceder a los elementos
listAlumnos = ["adri","rither","jose","juan"]
alumnoPos_1 =listAlumnos[len(listAlumnos)-1] #'juan'
#obtener el tamanio de la lista
ta... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
A routine that implements a K-means routine to cluster similar vectors.
Based on the work of Variational Shape Approximation by Cohen-Steiner and on
the python script developed by Jesus Galvez.
The clustering routing non-overlapping regions according to a specified m... |
from sys import exit
# The number of temperatures to analyse
N = int(raw_input())
# Return 0 and exit if we have no temperatures
if (N <= 0):
print 0
exit()
# The N temperatures expressed as integers ranging from -273 to 5526
temperatures = map(int, raw_input().split(' '))
minValue = min(temperatures, key=lambda x... |
"""Script to run image capture screenshots for state data pages.
"""
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from datetime import datetime
import io
import os
from pytz import timezone
import sys
import time
import boto3
from loguru import logger
from captive_browser import CaptiveBrowser
fr... |
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torch.optim.lr_scheduler import StepLR
from tqdm import tqdm
torch.manual_seed(0)
def p... |
import os
import logging
import re
import random
import requests
from bs4 import BeautifulSoup
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class PatternFinder:
headers = [
{"Accept-Language": "en-US,en;q=0.5", "User-Agent": "Mozilla/5.0"},
{"Accept-L... |
import textwrap
from ...core.model.env_vars import INSTALLATION_NAMESPACE
def get_deployment_yaml(name, image="busybox"):
return textwrap.dedent(
f"""\
apiVersion: apps/v1
kind: Deployment
metadata:
name: {name}
namespace: {INSTALLATION_NAMESPACE}
labels:
app: {name}
spec:
r... |
import http.client
import json
import logging
def fetch_google_first_name_last_name(access_token):
"""
Fetch google first name and google last name from google plus
:return: first name, last name
"""
try:
conn = http.client.HTTPSConnection('www.googleapis.com')
conn.request('GET', ... |
import itertools
while True:
try:
x,y=input().split()
x,y=list(x),int(y)
try:
p=itertools.permutations(x)
for i in range(y-1): p.__next__()
print("".join(x),y,"=","".join(p.__next__()))
except:
print("".join(x),y,"=","No permutation")
... |
from sys import stdout
H, W = map(int, input().split())
a = [input() for _ in range(H)]
h = [all(c == '.' for c in a[i]) for i in range(H)]
w = [True] * W
for i in range(H):
for j in range(W):
w[j] = w[j] and a[i][j] == '.'
for i in range(H):
if h[i]:
continue
for j in range(W):
... |
import pandas as pd
import numpy as np
import os
closing_message = ' < < < \t < < < \n'
def binary_transform(X): return X.astype(bool)*1
def relative_transform(X): return X.apply(lambda x: x/x.sum(), axis=0)
def z_transform(X): return X.apply(lambda x: (x-x.mean())/x.std(), axis=0)
def mean_transform(X): return X.app... |
import sys; sys.path.append('../common')
import mylib as utils # pylint: disable=import-error
# Read args
filename = 'input.txt' if len(sys.argv) == 1 else sys.argv[1]
print(filename, '\n')
###########################
# region COMMON
REMINDER_VALUE = 20201227
def getNextValue(value: int, subjectNumber: int) -> int:... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import json
import os.path
import sys
from datetime import date
def add_worker(staff, name, post, year):
"""
Добавить данные о работнике.
"""
staff.append(
{
"name": name,
"post": post,
... |
import pyautogui
import pydirectinput
import random
import time
import sys
import os
confidence = 0.85 #0.75
def click(loca):
if loca != None:
R = random.randint(2, 8)
C = random.randint(2,7)
pyautogui.moveTo(loca[0]+loca[2]//R,loca[1]+loca[3]//C,duration = 0.1)
pydir... |
import matplotlib.pyplot as plt
from numpy import ones, diff, eye
from RobustLassoFPReg import RobustLassoFPReg
def FitVAR1(X, p=None, nu=10**9, lambda_beta=0, lambda_phi=0, flag_rescale=0):
# This function estimates the 1-step parameters of the VAR[0] process via lasso regression (on first differences)
# I... |
from scraping.api.views import CarViewSet
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'', CarViewSet, base_name='cars')
urlpatterns = router.urls
|
# 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 PyLibensemble(PythonPackage):
"""Library for managing ensemble-like collections of comput... |
# Copyright 2018 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 agreed to in writin... |
from flask import Flask, jsonify, make_response, request
app = Flask(__name__)
@app.route("/score", methods=["POST"])
def score():
features = request.json["X"]
response = make_response(jsonify({"score": features}))
return response
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
|
"""Jahnke
[email protected] / [email protected]
CSCI 160 - Spring 2022
Lab 1 Part A
Using SimpleGraphics, draw a face with a minimum of 2 eyes, 1 nose,
and 1 mouth.
"""
from simple_graphics.SimpleGraphics import *
setSize(400, 300)
# https://trinket.io/docs/colors
setBackground("hot pink")
# no matter the ... |
import os
import glob
import shutil
import re
def main():
g4_list = ['HuTaoLexer.g4', 'HuTaoParser.g4']
out = "cppout"
os.system(f'antlr4 -Dlanguage=Cpp {" ".join(g4_list)} -o {out}')
files = glob.glob("cppout/HuTao*")
for file in files:
if not (file.endswith('.h') or file.endswith('cpp'... |
import yaml
from appium import webdriver
from appium.webdriver.webdriver import WebDriver
class Client(object):
#安装app
driver: WebDriver
platform = "android"
@classmethod
def install_app(cls) -> WebDriver:
# caps = {}
# # 如果有必要,进行第一次安装
# # caps["app"]=''
# caps["pl... |
# Copyright (c) 2020 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 requi... |
# super
class A:
def work(self):
print("A类的work被调用")
class B(A):
def work(self):
print("B类的work被调用")
b = B()
# 调用子类的work方法
b.work()
# 调用父类的work方法
super(B, b).work()
|
"""
author: Antoine Spahr
date : 29.09.2020
----------
TO DO :
"""
import os
import pandas as pd
import numpy as np
import skimage.io as io
import skimage.transform
import skimage.draw
import skimage
import cv2
import torch
from torch.utils import data
import nibabel as nib
import pydicom
import src.dataset.transfo... |
from collections import deque
from dataclasses import dataclass
from typing import Deque, Generic, List, Sequence, Set, TypeVar
from .common import ParserError, ParserErrorWithIndex, ParserTypeError
from .operators import find_binary_operator, find_unary_operator, find_variable, find_set
from .operands imp... |
# Copyright 2015 Google 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 applicable law or ag... |
#!/usr/bin/env python
"""Tests of the geometry package."""
from math import sqrt
from numpy import (
all,
allclose,
arange,
array,
insert,
isclose,
mean,
ones,
sum,
take,
)
from numpy.linalg import inv, norm
from numpy.random import choice, dirichlet
from numpy.testing import as... |
#!/usr/bin/env python
import os
import sys
import subprocess
import linecache
import time
from optparse import OptionParser
import optparse
import time
#=========================
def setupParserOptions():
parser = optparse.OptionParser()
parser.set_usage("awslaunch_cluster --instance=<instanceType>")
parse... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db.models import QuerySet
#from django.utils.encoding import python_2_unicode_compatible
from django.db.models import Q, F
from django.db.models.functions import Substr, Length
from django.db.models import CharField, OuterRef, Subquery
try:
... |
from connect4 import Connect4Board
from connect4 import GameState
from connect4 import Player
import numpy as np
import random
class ForwardSearchAgent:
name = None
depth = None
discount_factor = None
agent_two_val = None
agent_three_val = None
opp_two_val = None
opp_three_val = None
def __init__(sel... |
import tempfile
from dagster import ResourceDefinition, fs_io_manager, mem_io_manager
from dagster_pyspark import pyspark_resource
from hacker_news_assets.pipelines.download_pipeline import download_comments_and_stories_dev
from hacker_news_assets.resources.hn_resource import hn_snapshot_client
from hacker_news_assets... |
import numpy as np
import networkx as nx
import cPickle as cp
import random
import ctypes
import os
import sys
from tqdm import tqdm
sys.path.append( '%s/tsp2d_lib' % os.path.dirname(os.path.realpath(__file__)) )
from tsp2d_lib import Tsp2dLib
n_valid = 100
def find_model_file(opt):
max_n = int(opt['max_n'])
... |
"""
This module is specifically intended for use when in environments where
you're actively trying to share/develop tools across multiple applications
which support PyQt, PySide or PySide2.
The premise is that you can request the main application window using
a common function regardless of the actual application - ... |
# -*- coding: utf-8
"""
Web-Interface for JabRef library.
It lists the entries in a given JabRef library. It provides a simple
search bar to filter for those entries your looking for. Currently, it
provides read-only access to the library without any possibility to modify
existing entries or to add new ones.
"""
from... |
from django.urls import path, include
from django.contrib import admin
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView,
urlpatterns = [
path('admin/', admin.site.urls),
# dj-rest-auth endpoints
path('dj-rest-auth/', include('dj_rest_auth.urls')),
path('dj-rest-auth... |
from __future__ import absolute_import
from pyti import catch_errors
from pyti.exponential_moving_average import (
exponential_moving_average as ema
)
def price_oscillator(data, short_period, long_period):
"""
Price Oscillator.
Formula:
(short EMA - long EMA / long EMA) * 100
"""
catc... |
from copy import deepcopy
from random import randint, uniform, choice
class EAConfig:
"""
This class sets up the parameters for EA
"""
def __init__(self,
mut = 0.30,
cross = 0.30,
cand_size = 10,
max_cand_value = 8, # for real and ... |
# Generated by Django 2.0.2 on 2018-05-02 14:37
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
# 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... |
from flask import Flask, render_template_string, send_from_directory
from modules import stats_db, make_plot
app = Flask(__name__)
@app.route('/<path:filename>')
def send_public_file(filename):
return send_from_directory('public/', filename)
@app.route('/')
def index():
# language=html
template = '''
... |
from django.urls import path
from .views import Registrarse, equipoView
urlpatterns = [
path('signup/',Registrarse.as_view() , name='registrarse'),
path('equipo/',equipoView , name='equipo'),
]
|
import os
import random
from mnist import MNIST
os.chdir(os.path.dirname(os.path.abspath(__file__)))
# rounded_binarized - convert trainig dataset to arrays of 0,1
#mndata = MNIST('mnist_dataset', mode="rounded_binarized")
mndata = MNIST('mnist_dataset')
print('Loading training dataset...')
images, labels = mndata.l... |
"""
Example of using a Decision Tree
to remodel a photograph
"""
from sklearn.tree import DecisionTreeRegressor
from PIL import Image
import numpy as np
import pandas as pd
# Put your own file name here
INPUT_FILE = 'bbtor.jpg'
OUTPUT_FILE = 'output.png'
# Experiment with these parameters
SAMPLE_SIZE = 50000
DEPTH = ... |
import os
def environ_get(key, default=None):
retval = os.environ.get(key, default=default)
if key not in os.environ:
print(
"environ_get: Env Var not defined! Using default! Attempted={}, default={}".format(
key, default
)
)
return retval
def en... |
import string # The random and string libraries are used to generate a random string with flexible criteria
import random
# Random Key Generator
key = ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits + '^!\$%&/()=?{[]}+~#-_.:,;<>|\\') for _ in range(1024))
# the for lo... |
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
import datetime
from .utilities import *
def end_session(request):
if 'auth_token' in request.COOKIES:
end_session_by_token(request.COOKIES['auth_token'])
return HttpResponseRedirect(requ... |
# SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
import os
from typing import Any, Dict
from assemble_workflow.bundle_location import BundleLocation
from manifests.build_manif... |
# Beispielprogramm für das Buch "Python Challenge"
#
# Copyright 2020 by Michael Inden
def fib_rec(n):
if n <= 0:
raise ValueError("n must be >= 1")
if n == 1 or n == 2:
return 1
# rekursiver Abstieg
return fib_rec(n - 1) + fib_rec(n - 2)
def fib_iterative(n):
if n <= 0:
... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
u"""
Created at 2020.10.10 by Zhang Yiming
"""
import os
from glob import glob
from multiprocessing import cpu_count, Pool
from shutil import rmtree
import click
import pybedtools as pb
from src import diff_cluster, diff_segmentReadCounts, diff_ru, diff_test
from src.func... |
a,b,c = input().split(" ")
a,b,c = float(a),float(b),float(c)
if ( abs(b-c) < a and a < (b + c) ) and ( abs(a-c) < b and b < (a+c) ) and (abs(a-b) < c and c < (a+b)):
print("Perimetro = %0.1f" % (a+b+c))
else:
print("Area = %0.1f" % (((a+b)*c) / 2) ) |
# A script that just does the job: checks a sentence:
#
# >> python .\perturbvalidate\visualization\validate_sentence.py 'Пушистые котики мурлыкают и не только'
# Using model C:\Users\Vadim\Documents\prog\perturb-validate\models\half_inflected.pickle
# Perturbed!
# Using model C:\Users\Vadim\Documents\prog\perturb-vali... |
from pathlib import Path
from pyspark.sql.dataframe import DataFrame
from pyspark.sql.session import SparkSession
from pyspark.sql.types import StructType
from tests.conftest import clean_spark_session
from spark_pipeline_framework.transformers.framework_csv_loader.v1.framework_csv_loader import (
FrameworkCsvLoa... |
from rl.envs import SlipEnv
from rl.policies import GaussianMLP
from rl.algos import DAgger
from rl.utils import policyplot
import torch
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--dagger_itr", type=int, default=100,
help="number of iterations of DAgger")
parser.add_a... |
from pkcrypt.cli import cli
if __name__ == '__main__': cli()
|
import numpy as np
import os
import tensorflow as tf
from tagger.data_utils import minibatches, pad_sequences, get_chunks
from tagger.general_utils import Progbar, print_sentence, extract_labels
class NERModel(object):
def __init__(self, config, embeddings, ntags, nchars=None, logger=None):
"""
A... |
import logging
from secpy.core.mixins.base_network_client_mixin import BaseNetworkClientMixin
from secpy.core.ticker_company_exchange_map import TickerCompanyExchangeMap
class BaseEndpointMixin(BaseNetworkClientMixin):
_endpoint = None
def __init__(self, user_agent, **kwargs):
"""
Base class... |
import json
from datetime import datetime
import requests
import datetime
import dateutil
import time
# origination
decimals = 1000000000000000000
time_now = time.time()
contract = "KT1PxkrCckgh5fA5v2cZEE2bX5q2RV1rv8dj"
origination = 1734719
level = 1735011
url = f"https://api.tzkt.io/v1/operations/transactions?sen... |
import sys, os
kActionFrom_AllInOne = 0x0
kActionFrom_BurnOtp = 0x1
kBootDeviceMemBase_FlexspiNor = 0x08000000
kBootDeviceMemBase_FlexcommSpiNor = 0x0
kBootDeviceMemBase_UsdhcSd = 0x0
kBootDeviceMemBase_UsdhcMmc = 0x0
kBootDeviceMemXipSize_FlexspiNor = 0x08000000 #128MB
kBootDeviceMemXipSize_Quads... |
class CustomField(object):
def __init__(self, key, value, tag):
self.key = key
self.value = value
self.tag = tag |
import tensorflow.compat.v1 as tf
from detector.constants import NUM_KEYPOINTS, DATA_FORMAT
from detector.utils import batch_norm_relu, conv2d_same
from detector.fpn import feature_pyramid_network
DEPTH = 128
class KeypointSubnet:
def __init__(self, backbone_features, is_training, params):
"""
A... |
APP_NAME = 'zenkly'
VALID_HC_TYPES = {'articles', 'categories', 'sections'} |
"""
Lasso selection of data points
Draws a simple scatterplot of random data. Drag the mouse to use the lasso
selector, which allows you to circle all the points in a region.
Upon completion of the lasso operation, the indices of the selected points are
printed to the console.
Uncomment 'lasso_selection.incremental... |
from cancontroller.caniot.models import DeviceId
from cancontroller.caniot.device import Device
from cancontroller.controller.nodes import GarageDoorController, AlarmController
node_garage_door = GarageDoorController(DeviceId(DeviceId.Class.CUSTOMPCB, 0x02), "GarageDoorControllerProdPCB")
node_alarm = AlarmController... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.