content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
import sys
def isBalanced(expression):
if len(expression) & 1:
return False
parentheses = []
for c in expression:
if c == '(' or c == '{' or c == '[':
parentheses.append(c)
elif c == ')' or c == '}' or c == ']':
offset = 1 if c == ')' else 2
if len(parent... |
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Any, DefaultDict, Optional, Type, TypeVar
from discord import Guild
from commanderbot.lib import FromDataMixin, GuildID, JsonSerializable, LogOptions
from commanderbot.lib.utils import dict_without_ellipsis, dict_without_f... |
from flask_restful import Resource, current_app
from backend.services.campaign_service import CampaignService
from backend.services.organisation_service import OrganisationService
from backend.models.postgis.utils import NotFound
from backend.services.users.authentication_service import token_auth
class Organisation... |
#!/usr/bin/env python
#coding: utf-8
__author__ = 'Toshihiro Kamiya <kamiya@mbj.nifty.com>'
__status__ = 'experimental'
import os.path
import re
import sys
import subprocess
UNIZP_COMMAND = "/usr/bin/unzip"
def get_class_names_from_jar(jar_file):
class_names = []
pat = re.compile(r"^\s*testing:\s*(.+)[.]cla... |
# Copyright 2020 Katteli Inc.
# TestFlows.com Open-Source Software Testing Framework (http://testflows.com)
#
# 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/lice... |
from pathlib import Path
import importlib
import tensorflow as tf
from annoy import AnnoyIndex
DEFAULT_CONFIG = {
"dataset": "Dataset",
"model": "RetreivalModel",
"network": "retrieval_basic_factorization",
"network_args": {
"embedding_dimension": 32,
}
}
class Ret... |
# Generated by Django 2.1.3 on 2018-12-08 07:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('staf', '0010_process_slug'),
('multiplicity', '0023_referencespacetype_process'),
]
operations = [
... |
from __future__ import absolute_import, division, print_function
try:
from threading import local
except ImportError:
from django.utils._threading_local import local
_thread_locals = local()
def get_current_request():
""" returns the request object for this thread """
return getattr(_thr... |
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from rest_framework import serializers
from .models import ListModel
from utils import datasolve
class BinsizeGetSerializer(serializers.ModelSerializer):
bin_size = serializers.CharField(read_only=True, required=False)
bin_size_w = serializers.FloatField(read_only=True, required=False)
bin_size_d = seriali... |
"""
https://leetcode.com/problems/logger-rate-limiter/
Tags: Google; Medium; Stack
"""
from typing import List
from operator import add, sub, mul, floordiv
def div(op1: int, op2: int) -> int:
neg = (op1 < 0 < op2) or (op2 < 0 < op1)
ans = floordiv(abs(op1), abs(op2))
return ans * (-1 if neg el... |
# -*- coding: utf-8 -*-
from .aapt import Aapt
from .minicap import Minicap
from .rotation import Rotation
from .performance.fps import Fps
from .performance.cpu import Cpu
from .performance.meminfo import Meminfo
from .performance import DeviceWatcher
__all__ = ['Aapt', 'Minicap', 'Rotation', 'Fps', 'Cpu', 'Meminfo'... |
import numpy, re
def encode_onehot(index, size):
onehot = numpy.zeros(size, dtype=numpy.int8)
onehot[index] = 1
return onehot
def prettify_string(string, replace_newline_with_space=True):
pretty_string = str(string).strip()
if replace_newline_with_space:
pretty_string = pre... |
from unittest import TestCase
from ddsc.core.consistency import UploadDetails, ProjectChecker, DSResourceNotConsistentError
from mock import Mock, patch, call
class TestUploadDetails(TestCase):
def test_inconsistent_status(self):
mock_dds_file = Mock()
mock_dds_file.name = 'file1.dat'
mock... |
# Global Benchmark Database (GBD)
# Copyright (C) 2020 Markus Iser, Karlsruhe Institute of Technology (KIT)
#
# This program 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, either version 3 of the License, or... |
import pianohat
import time
from pygame import mixer
my_sound_files = [
"/home/pi/Downloads/despacito.wav",
"/home/pi/Downloads/Metal.wav",
"/home/pi/Downloads/Metal.wav",
"/home/pi/Downloads/Metal.wav",
"/home/pi/Downloads/Metal.wav",
"/home/pi/Downloads/despacito.wav",
"/home/pi/Downloads/... |
from django.db import models
# Create your models here.
class Employee(models.Model):
Name = models.CharField(max_length=64)
Email = models.CharField(max_length=64)
Password = models.CharField(max_length=64)
Position = models.CharField(max_length=64)
Salary = models.IntegerField()
def __str__... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup
# Use 2to3 build conversion if required
try:
from distutils.command.build_py import build_py_2to3 as build_py
except ImportError:
# 2.x
from distutils.command.build_py import build_py
setup(
name="snpy",
description="A... |
# Copyright (C) 2021 ServiceNow, Inc.
import pytest
from nrcan_p2.data_processing.preprocessing_str import (
add_newline,
sentence_tokenize_spacy_sm,
sentence_tokenize_spacy_lg,
tokenize_spacy_sm,
tokenize_spacy_lg,
rm_stopwords_spacy,
rm_punct,
rm_newline
)
@pytest.mark.parametrize("i... |
"""
Helper functions and classes around GeoIP lookups, based on Maxmind's
`maxminddb <https://pypi.python.org/pypi/maxminddb>`_ and
`geoip2 <https://pypi.python.org/pypi/geoip2>`_ Python packages.
"""
import logging
import time
import genc
from geoip2.database import Reader
from geoip2.errors import AddressNotFoundEr... |
#define the main() function
def main():
i = 0
x = 119.0
for i in range(120):
if((i%2)==0):
x += 3.
else:
x -= 5.
s = "%3.2e" % x
print(s)
if __name__ == "__main__":
main() |
import asyncio
from userbot import CMD_HELP, StartTime, bot
from userbot.utils import bash, edit_or_reply, zelda_cmd
@zelda_cmd(pattern="sxs (.*)")
async def amireallysxs(sxs):
user = await bot.get_me()
capt = str(sxs.pattern_match.group(1).split(" ", 2)[0])
link = str(sxs.pattern_match.group(1).split(" "... |
#!/usr/bin/env python
from flexbe_core import EventState, Logger
import actionlib
import rospy
from jacobian_control.msg import DoAdaptionAction, DoAdaptionGoal, DoAdaptionResult, DoAdaptionFeedback
class HandoverAdaptionExec(EventState):
''' Calls jacobian-control node for adaption. '''
def __init__(self... |
from .receipt_parser import parse_receipt # noqa
|
import animal
class Bear(animal.Animal):
pass
|
from dataclasses import dataclass
from minsk.analysis.binding.expression import BoundExpression
from minsk.analysis.binding.kind import BoundNodeKind
from minsk.analysis.binding.operators.unary import BoundUnaryOperator
from minsk.analysis.type import MinskType
@dataclass(frozen=True)
class BoundUnaryExpression(Boun... |
from zeit.cms.i18n import MessageFactory as _
import fb
import gocept.form.grouped
import requests
import urllib
import urlparse
import zeit.cms.browser.menu
import zope.app.appsetup.product
import zope.formlib.form
import zope.session.interfaces
class IFacebookApp(zope.interface.Interface):
app_id = zope.schema... |
import FWCore.ParameterSet.Config as cms
from DQMOffline.Trigger.razorHemispheres_cff import *
from DQMOffline.Trigger.RazorMonitor_cfi import hltRazorMonitoring
# HLT_Rsq0p35_v*
Rsq0p35_RazorMonitoring = hltRazorMonitoring.clone()
Rsq0p35_RazorMonitoring.FolderName = cms.string('HLT/SUSY/Rsq0p35/')
Rsq0p35_RazorMon... |
project = 'matador-test'
environments = {
'test': {'dbms': 'oracle', 'connection': 'user@instance'}
}
credentials = {
'test': {'user': 'test_user', 'password': 'test_password'}
}
|
events = ["evt1", "evt2", "evt3"]
def my_pop():
if events:
evt = events.pop(0)
print(evt)
print(events)
my_pop()
my_pop()
my_pop()
my_pop()
|
"Models for managing site sections and ad placements."
from __future__ import unicode_literals
from django.conf import settings
from django.core.cache import cache
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from .conf import SECTION_CACHE_KEY, PLACEMENTS_KEY_FORMAT
from... |
from .base_regularizer import BaseRegularizer
from .center_invariant_regularizer import CenterInvariantRegularizer
from .regular_face_regularizer import RegularFaceRegularizer
from .lp_regularizer import LpRegularizer
from .zero_mean_regularizer import ZeroMeanRegularizer
from .sparse_centers_regularizer import Sp... |
#!/usr/bin/env python
"""circuits Hello World"""
from circuits import Component, Event
class hello(Event):
"""hello Event"""
class App(Component):
def hello(self):
"""Hello Event Handler"""
print("Hello World!")
def started(self, component):
"""Started Event Handler
... |
#!/usr/bin/env python
# Very useful script because I know the DMC steps start from s005
import re
import sys
import argparse
#import numpy as np
import autorunner
@autorunner.dmc_dat()
def common(x):
return x
# this style is not optimal but fine for now regardless
@autorunner.qmcpack_output()
def output_capturer(... |
# Generated by Django 4.0.4 on 2022-04-21 02:30
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Cheese',
fields=[
('slug', models.SlugField... |
import os
from PIL import Image
wnid = 'n03082979'
image_dir = './downloaded_images/{}/{}_urlimages'.format(wnid, wnid)
for filename in os.listdir(image_dir):
# if filename.endswith('.png'):
try:
filepath = os.path.join(image_dir, filename)
img = Image.open(filepath) # open the image file
img.verify() # ... |
# INTERSECTION OF TWO ARRAYS LEETCODE SOLUTION:
# creating a class.
class Solution(object):
# creating a function to solve the problem.
def intersection(self, nums1, nums2):
# returning the intersection between the two arrays.
return list(set(nums1).intersection(set(nums2))) |
import enum
import math
import time
import warnings
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union, cast
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim
from torch import Tensor
from . import functional as rtdlF
ModuleType = Union[str, Callable[..., n... |
#coding: utf8
from rust.core import db as models
class Permission(models.Model):
"""
资源权限
"""
resource = models.CharField(default='', max_length=128) # 资源名
method = models.CharField(default='GET', max_length=32) # 方法名
created_at = models.DateTimeField(auto_now_add=True) # 更新时间
class Meta(obj... |
from phoopy.kernel import Bundle
from os import path
class AppBundle(Bundle):
def service_path(self):
return path.join(self.get_bundle_dir(), 'config', 'services.yml') # pragma: no cover
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Collection of tests for :mod:`orion.core.utils.working_dir`."""
import os
import shutil
from pathlib import Path
import pytest
from orion.core.utils.working_dir import SetupWorkingDir
class ExperimentStub:
def __init__(self, working_dir=None):
self.name =... |
#!/usr/bin/python
import matplotlib.pyplot as plt
from matplotlib import *
import sys, getopt
import copy
import time
import datetime
import random
import sys
import os
import re
def get_data(file_list, type, start, finish, nice):
mapped_reqs, running_reqs, refused_reqs = [], [], []
mapped_requests_dict = di... |
from pyexcel.renderer import Renderer
from pyexcel_echarts.options import MANAGER
DEFAULT_TITLE = 'pyexcel via pyechars'
class Chart(Renderer):
def render_sheet(self, sheet, chart_type='bar', mode='embed',
title=DEFAULT_TITLE,
subtitle="",
width=800... |
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
S = {-1: set()}
for x in sorted(nums):
S[x] = max((S[d] for d in S if x % d == 0), key=len) | {x}
return list(max(S.values(), key=len))
|
# coding=utf-8
"""execution.py - This module provides classes that execute commands.
"""
import os
import sys
import signal
import subprocess
from .config import Config
from .base import PluginManager
from .log import LogManager
class ExecutionManager(PluginManager):
"""This class is used to execute commands for ... |
# -*- encoding: utf-8 -*-
import numpy as np
def get_seq_graph(edge):
dy, dx = np.array([-1,0,1,1,1,0,-1,-1]), np.array([-1,-1,-1,0,1,1,1,0])
def get_neighbors(node):
Y, X = node[0]+dy, node[1]+dx
neighbors = edge[Y, X]
Y, X = Y[neighbors], X[neighbors]
return zip(Y,X)
grap... |
from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.utils as vutils
from torch.aut... |
import numpy as np
# 对一维数组的切片
origin = np.arange(1,100)
print(origin)
print(origin[0:2])
print(origin[:12:4])
print(origin[:12:])
print(origin[5:])
print(origin[::-1]) #倒序
# 二维数组切片
origin = np.random.random((3,4))
print(origin)
print(origin[-2:,:2])
print(origin[::-2,::-1]) |
"""
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
distri... |
#!/usr/bin/python
import aud, sys, time, multiprocessing
device = aud.Device()
hrtf = aud.HRTF().loadLeftHrtfSet(".wav", sys.argv[2])
threadPool = aud.ThreadPool(multiprocessing.cpu_count())
source = aud.Source(0, 0, 0)
sound = aud.Sound.file(sys.argv[1]).rechannel(1).binaural(hrtf, source, threadPool)
handle = device.... |
# coding: utf-8
# flake8: noqa
"""
Velo Payments APIs
## Terms and Definitions Throughout this document and the Velo platform the following terms are used: * **Payor.** An entity (typically a corporation) which wishes to pay funds to one or more payees via a payout. * **Payee.** The recipient of funds paid ... |
from data.mag.build_docs_from_sqlite import generate_papers, UPDATE_GENERATORS, strip_and_dump_from_gen
from solr.instances import get_session
from data import upload_batches_unparsed
from solr.session import SolrSession
from solr.configsets import get_config
from multiprocessing import Pool, cpu_count
import itertools... |
"""
Module to log on screen
====================================
"""
# ============================================================================
# STANDARD IMPORTS
# ============================================================================
import click
from functools import partial
from click.termui import s... |
#
# -------------------------------------------------------------------------
# Copyright (c) 2015-2017 AT&T Intellectual Property
#
# 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
#
# ... |
#!/usr/bin/env python3
import subprocess
import os
import glob
import sys
import time
import argparse
def merge(infile, outfile, id_name_map):
merge_dict = {}
with open(infile, 'r') as f:
content = ""
name = ""
for line in f:
if line[0] == ">":
name = line[1:].strip()
if name n... |
#---------------------------------------
# Import Libraries
#---------------------------------------
import sys
import json
import codecs
import os
#---------------------------------------
# [Required] Script Information
#---------------------------------------
ScriptName = "Queue Display"
Website = "twitch.tv/enc... |
"""Implementation of the StarBound block file v2/3 storage"""
import logging
import struct
from starfuse.fs.mapped_file import MappedFile
log = logging.getLogger(__name__)
class InvalidMagic(Exception):
"""A block file has an invalid magic string"""
def __init__(self, path):
super(InvalidMagic, sel... |
import pandas as pd
import numpy as np
def load_file(filename: str):
"""Load the .xls file and return as a dataframe object."""
df = pd.read_csv(filename, delimiter='\t')
return df
data = load_file('outputs.xls')
print(data.info())
|
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import csv
import sys
import json
import pickle
import logging
from copy import deepcopy
from collections import Counter
from itertools import groupby, chain
from indra.statements import Agent
from indra.da... |
__author__ = 'marcusmorgenstern'
__mail__ = ''
import copy
import os
import unittest
from os.path import join
import numpy as np
from pyfluka.base import InvalidInputError
from pyfluka.reader.UsrbinReader import UsrbinReader as UR
from pyfluka.utils import PhysicsQuantities as PQ
_basedir = os.path.dirname(__file__)
... |
# @lc app=leetcode id=211 lang=python3
#
# [211] Design Add and Search Words Data Structure
#
# https://leetcode.com/problems/design-add-and-search-words-data-structure/description/
#
# algorithms
# Medium (41.04%)
# Likes: 3106
# Dislikes: 130
# Total Accepted: 293.8K
# Total Submissions: 712.7K
# Testcase Examp... |
from django.shortcuts import render
from django.views.generic import TemplateView
from booking.models import Booking
from userprofile.models import userProfile
class IndexPageView(TemplateView):
template_name = 'main/index.html'
class ChangeLanguageView(TemplateView):
template_name = 'main/change_language.... |
from sqlalchemy import (
create_engine, Column, MetaData,
Integer, String, Numeric, DateTime)
from sqlalchemy.orm import class_mapper
from .common import (
generate_sqla_connection_uri,
_insert_entries_from_log_file,
_import_logs_from_folder)
from sqlalchemy.orm import scoped_session, sessionmaker
f... |
from __future__ import print_function, division, absolute_import
import numpy as np
import networkx as nx
from visvis import ssdf
from stentseg.utils.new_pointset import PointSet
from stentseg.stentdirect.stentgraph import (StentGraph, check_path_integrity,
_get_pairs_of_neighbours, add_nodes_at_crossings,
... |
from pyspark import SparkContext
from pyspark.sql.functions import count, lit, col, udf, collect_list, explode, sqrt, mean
from pyspark.sql.types import IntegerType, StringType, MapType, ArrayType, BooleanType, FloatType
from pyspark.sql import SQLContext, HiveContext
import sys
def filter_slot_id(df, slot_ids=[]):
... |
# -*- coding: utf-8 -*-
# Copyright 2015 www.suishouguan.com
#
# Licensed under the Private License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://github.com/samuelbaizg/ssguan/blob/master/LICENSE
#
# Unless ... |
"""
These are utilities for the `/bin` scripts, not for the `cibuildwheel` program.
"""
from io import StringIO
from typing import Dict, List
from .typing import Protocol
__all__ = ("Printable", "dump_python_configurations")
class Printable(Protocol):
def __str__(self) -> str:
...
def dump_python_con... |
# -*- coding: utf-8 -*-
# global
import io
import sys
import json
import logging
import pandas as pd
# core
import core
import core.utils
import core.indexer
from core.DocVocabulary import DocVocabulary
from core.TermVocabulary import TermVocabulary
from core.features import Features
from core.msg import TwitterMessa... |
class Dinosaur:
def __init__(self, name, attack_power):
self.name = name
self.attack_power = int(attack_power)
self.health = 50
self.energy = 100
self.att_list = ["Tail Whip", "Body Slam", "Stomp", "Hyper Beam"]
self.att = "error"
def attack(self, robot):
... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
from lib.core.data import kb
from lib.request.connect import Connect as Request
def getPageTemplate(payload, place):
retVal = (kb.originalPage, kb.errorIsNone)
if pa... |
# def encode_as_bytes(input_file_path: str, output_gif_path: str):
# """
# The practical encoder with optimized GIF assembler and multiprocessing acceleration.
#
# :param input_file_path: input file path
# :param output_gif_path: output gif file path
# :param chunk_string_length: the length of base6... |
# Version: 2020.02.21
#
# MIT License
#
# Copyright (c) 2018 Jiankang Deng and Jia Guo
#
# 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 limitatio... |
n= str(input("digite um valor ")).upper().strip()
d=n.split()
j= ''.join(d)
inver= ''
for i in range(len(j)-1,-1,-1):
inver+=j[i]
if n==inver:
print("o valor é um palindromo")
else:
print("o valor não é um palindromo")
|
import itertools
import random
S = " "
def main():
# init
gophers_count = 100
windmills_count = 18
factors = [17, 13, 11, 7, 5, 3, 2]
seed = 1951
a, b, c = [], [], []
random.seed(seed)
# generate input data for each night
for f in factors:
windmills = [f] * windmills_cou... |
from tensorflow.keras.layers import LSTM, Dense, TimeDistributed, Masking, BatchNormalization, Dropout, Input, \
Bidirectional, ConvLSTM2D, Attention
from tensorflow.keras.models import Model
from lsct.models.cnn_1d import CNN1D
from cnn_lstm.attention_with_context import Attention
def create_cnn_lstm_model(clip... |
"""CFNgin entrypoint."""
import logging
import os
import re
import sys
from yaml.constructor import ConstructorError
from runway._logging import PrefixAdaptor
from runway.util import MutableMap, SafeHaven, cached_property
from .actions import build, destroy, diff
from .config import render_parse_load as load_config
... |
x3 = ('foo'
('bar'<caret> |
import numpy as np
from pymgt import *
from pymgt.metrics import *
from pymgt.ppmt_utils import friedman_index
def test_():
ndata = 1000
np.random.seed(1)
x = np.random.uniform(0.0, 1.0, size=ndata)
metrics = [
("friedman", FRIEDMAN_METRIC, False),
("kstest", KS_METRIC, False),
... |
# -*- coding: utf-8 -*-
#
# Copyright (c) {% now 'utc', '%Y' %}, {{ cookiecutter.author }}
# All rights reserved.
#
import unittest
from cnct import ConnectClient
from connect_processor.app.cancel import Cancel
from unittest.mock import patch, MagicMock
from tests.test_util import TestUtils
client = ConnectClient('Key... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains functions used to convert osm data to json and save to MongoDB.
"""
import xml.etree.cElementTree as ET
import json
#some post on stackoverflow
def elementtree_to_dict(element):
""" Function used to recursively convert a eleme... |
class Solution:
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
productions = []
n = len(nums)
if n == 0:
return None
# def recursiveProductExceptSelf(idx=0, previous_value=1):
# nonlo... |
# Generated by Django 3.0.4 on 2020-03-22 13:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0006_auto_20200322_1440'),
]
operations = [
migrations.AddField(
model_name='violationreport',
name='cont... |
# import the necessary packages
from sklearn.preprocessing import LabelBinarizer
import numpy as np
class CifarGenerator:
"""
Generator class responsible for supplying data to the model.
Attributes
----------
x: np ndarray
array of images
y: np ndarray
array of class labels
... |
"""Functions to assist with remote logging of InVEST usage."""
import logging
import urllib
import urllib2
import json
import Pyro4
LOGGER = logging.getLogger('natcap.invest.remote_logging')
Pyro4.config.SERIALIZER = 'marshal' # lets us pass null bytes in strings
_ENDPOINTS_INDEX_URL = (
'http://data.naturalca... |
from dolfin.fem.problem import LinearVariationalProblem
from dolfin.cpp.fem import LinearVariationalSolver
from fenics_utils.formulation.cfd import IncompressibleNsIpcs
from fenics_utils.formulation.cfd import AdvectionDiffusionScalar
from fenics_utils.solvers.linear import LinearSolver
class AdvectionDiffusionScala... |
from __future__ import print_function
import boto3
import logging
import time
current_session = boto3.session.Session()
current_region = current_session.region_name
logger = logging.getLogger()
logger.setLevel(logging.INFO)
#create a client connection to ec2
ec2_client = boto3.client('ec2', current_region)
... |
"""!
@brief Phase oscillatory network for patten recognition based on modified Kuramoto model.
@details Implementation based on paper @cite article::nnet::syncpr::1.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
"""
import math
import cmath
import numpy
from pyclustering.... |
from api.libs.base import CoreView
from cmdb.models import MachineRoom, DataCenter
from account.models import UserProfile
from django.db.utils import IntegrityError
class MachineRoomView(CoreView):
"""
机房视图类
"""
login_required_action = ["get_list", "post_create", "post_delete", "post_change"]
supe... |
#!"D:\STORE\0-Admin\Desktop\Chatbot-Osiris bkp\python.exe"
import sys
import subprocess
subprocess.call("start cmd /k echo "+sys.argv[1], shell=True) |
from django import template
from django.template.loader import get_template
register = template.Library()
@register.filter(name='is_deploma')
def is_deploma(value):
return value['year'] == '2' and value['course'] == 'BTech'
@register.filter(name='is_first_year')
def is_first_year(value):
return value['year']... |
import discord
from discord.ext import commands
import sqlite3
from helper import utils
class SettingsCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(help= 'Used to set the prefix of the bot in this server, use default to default to the global prefix', usage='pref... |
# coding: utf-8
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
import networkx as nx
import itertools
import pandas
from networkx.readwrite import json_graph
from scipy import spatial
import re
__author__ = "Adrien Guille, Pavel Soriano"
__email__ = "adri... |
import RPi.GPIO as GPIO
import time
import threading
import os
import sys
# constants
SLOWFLASHTIMES = [2,2]
FASTFLASHTIMES = [0.5,0.5]
# class for managing LED
class LEDControl():
class LEDStates():
#states of LED
OFF = 0
ON = 1
FLASH = 2
def __init__(self, gpioPin):
... |
# REQUIRES: bindings_python
# RUN: %PYTHON% %s | FileCheck %s
import circt
from circt.dialects import rtl
from mlir.ir import *
from mlir.dialects import builtin
with Context() as ctx, Location.unknown():
circt.register_dialects(ctx)
i32 = IntegerType.get_signless(32)
m = builtin.ModuleOp()
with In... |
#!/usr/bin/env pytest
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test read functionality for FITS driver.
# Author: Even Rouault <even dot rouault @ mines-paris dot org>
#
########################################################... |
from xml.dom.minidom import Document
from django.shortcuts import redirect, render
def add_file(request):
if request.method == 'POST':
updated_file = request.FILES['document']
print(updated_file.name)
print(updated_file.size)
return render(request, 'base/add_file.html',{}) |
import os
import json
import importlib
from typing import Callable, TypeVar
AnyFunction = Callable
Handler = TypeVar('Handler')
def getClass(modulePath: str, className: str):
mod = importlib.import_module(modulePath)
return getattr(mod, className)
def getAction(fileName: str, actionName: str) -> Callable:... |
# -*- coding: utf-8 -*-
# --------------------------------------------------------
# Licensed under the terms of the BSD 3-Clause License
# (see LICENSE for details).
# Copyright © 2018-2021, A.A Suvorov
# All rights reserved.
# --------------------------------------------------------
"""Tests prototype.py"""
from patt... |
import numpy as np
from scipy.stats import iqr
from ..config import MAX_VAL_AFTER_NORMALIZATION
from ..utils.dataUtils import morphDilation, gaussianFilter, radial_profile, applyRelativeThr, getCoordsWithinSphere
from ..utils.genericException import GenericError
DEFAULT_PERCENTIL = 95
DEFAULT_BINARY_MASK_THR= 0.01
d... |
import pytest
import requests
from log_config import log_, pformat
from core import config
from tests.utils.utils import get_server_api, client
### - - - - - - - - - - - - - - - - - - - - - - - ###
### LOGINS
### - - - - - - - - - - - - - - - - - - - - - - - ###
def client_anonymous_login(
as_test = True... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.