content stringlengths 5 1.05M |
|---|
class TrieNode:
def __init__(self, character, end=False):
self.children = {}
self.end = end
self.character = character
def is_child(self, child):
return child in self.children
def child(self, character):
return self.children[character]
def add_child(self, chara... |
from lightning.types.base import Base
from lightning.types.decorators import viztype
from lightning.types.utils import array_to_lines, vecs_to_points, \
parse_links, add_property, mat_to_array, list_to_regions, parse_nodes, ndarray
@viztype
class Plot(Base):
_name = 'plot'
_options = dict(Base._options, ... |
"""
The flask application package.
"""
import os
from flask import Flask
def create_app(test_config=None):
app = Flask(__name__, instance_relative_config=True)
if os.getcwd() == '/':
database_path = '/var/www/HCI-DH-Eskimos/FlaskWebProject/FlaskWebProject/FlaskWebProject/database'
upload_path = '/var/www/HCI-D... |
import platform
from setuptools import find_packages, setup
# On Windows, we need pywin32 for CPU pinning
additional_dependencies = ["pywin32==225"] if platform.system() == "Windows" else []
def read_description():
with open("README.rst") as file:
return file.read()
if __name__ == "__main__":
setup... |
import pytest
from depender.graph.structure import StructureGraph
@pytest.fixture
def graph() -> StructureGraph:
r"""Create a Graph objects that represents the following graph:
+-----+
| 1 |
| |
+--+--+
... |
import torch.jit
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import pytorch_lightning as pl
from torchmetrics import Accuracy
from unsupervised_pretraining.utils.disk import load_file
class ClassificationModel(pl.LightningModule):
def __init__(self, model_url, emb_url, embe... |
# -*- coding: iso-8859-1 -*-
import string
import types
from Comandos.ComandoFiscalInterface import ComandoFiscalInterface
from Drivers.FiscalPrinterDriver import PrinterException
from ComandoInterface import formatText, ComandoException
NUMBER = 999990
import logging
logger = logging.getLogger(__name__)
... |
from .f0_tracking_peak_tracking import F0TrackerPeakTrackingAbesserDAFX2014
__author__ = 'Jakob Abesser'
class F0Tracker:
""" Wrapper function for fundamental frequency tracker
"""
def __init__(self):
pass
@staticmethod
def process(samples,
sample_rate,
p... |
from eyelab.dialogs.help.help_dialog import HelpWindow
help_text = """
# Shortcut Sheet
## Annotation
+ Ctrl + X: toggle linked navigation
"""
class ShortcutHelp(HelpWindow):
def __init__(self, parent):
super().__init__(help_text, parent)
|
from pathlib import Path
from typing import Dict, List, Union
import srsly
from recon.types import Example
from spacy.util import ensure_path
class ExampleStore:
def __init__(self, examples: List[Example] = None):
self._map: Dict[int, Example] = {}
if examples is not None:
for e in ex... |
# -*- coding: utf-8 -*-
"""
Created on Nov 13 2019
Last Update Nov 13 2019
Create plots of single model run
@author: Simon van Vliet & Gil Henriques
Department of Zoology
University of Britisch Columbia
vanvliet@zoology.ubc.ca
henriques@zoology.ubc.ca
Plots result of single run
"""
"""============================... |
import numpy as np
def greet():
print("Greet")
def main():
greet()
if __name__ == "__main__":
main()
|
#import use_ngmca as use
import pyfits as pf
import numpy as np
import matplotlib.pyplot as plt
from MuSCADeT import MCA
from MuSCADeT import wave_transform as mw
import scipy.stats as sc
from MuSCADeT import colour_subtraction as cs
import warnings
warnings.simplefilter("ignore")
## Openning data cube
cube = pf.open(... |
from pytest import raises
from exceptbool import except_converter
def test_except_converter_converts_to_false_when_exception_raised():
with except_converter() as converted_exception:
raise Exception()
assert converted_exception.value is False
def test_except_converter_converts_to_true_when_excepti... |
class Pair(object):
def __init__(self, x, y):
super().__init__()
self.x = x
self.y = y
def toList(self):
return [self.x, self.y, 0]
|
import sys
from os import path
from setuptools import setup, find_packages
curdir = path.abspath(path.dirname(__file__))
with open(path.join(curdir, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
name = 'bapiparkinglot'
version = '1.0'
description = 'Parking Lot API dibuat untuk memenuhi syarat... |
import sys
import os
sys.path.append(os.path.join('..', '..', '..'))
import KratosMultiphysics as Kratos
from KratosMultiphysics.GeoMechanicsApplication import *
import KratosMultiphysics.GeoMechanicsApplication.geomechanics_analysis as analysis
def run_stages(project_path,n_stages):
"""
Run all constructio... |
import torch
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
from Data.structure_core import StructureCoreCapturedDataset, StructureCoreRenderedDataset
from Models.ActiveStereoNet import ActiveStereoNet
from Losses.supervise import *
import cv2
import math
import argparse
def main():
... |
import os
import platform
import shutil
import subprocess
import time
import uuid
def get_lines(std_pipe):
"""Generator that yields lines from a standard pipe as they are printed."""
for line in iter(std_pipe.readline, ""):
yield line
class Shell:
def __init__(self, shell_type):
self.pro... |
from .db import db
from .model import *
|
# use if needed to pass args to external modules
import sys
# used for math functions
import math
from statistics import mean
# used to create threads & dynamic loading of modules
import threading
import multiprocessing
import importlib
# used for directory handling
import glob
import os
import numpy as np
from t... |
from flask import render_template, request, redirect
from . import main
from ..requests import get_sources ,get_articles
@main.route('/')
def index():
"""
View root page function that returns index page and the various news sources
"""
title = 'Home- Welcome News Highlights Website'
# Getting... |
from .mplay import MPlay
|
"""
translate.py
Translate between different geometry file formats.
-- psana
extension: .data
format: flat text
units: microns
-- Cheetah
extension: .h5
format: HDF5
units: mm for x/y, microns for z
-- CrystFEL
extension: .geom
format: flat text
units: all CrystFEL units are ... |
#!/usr/bin/python3
# Morgan Butryn
# 2020-1-28
# reset_pickle.py
"""resets pickle file"""
import pickle
# [0] = title
# [1] = genre
# [2] = dev
# [3] = pub
# [4] = release
# [5] = platform
# [6] = purchase date
# [7] = purchase price
# [8] = has SP
# [9] = has MP
# [10] = completed
# [11] = rating
# [12] = notes
gam... |
# This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/core/actions/#custom-actions/
# This is a simple example for a custom action which utters "Hello World!"
# from typing import Any, Text, Dict, Lis... |
import os
from vigra import readImage
import h5py
from progressbar import AnimatedMarker, Bar, BouncingBar, Counter, ETA, \
FileTransferSpeed, FormatLabel, Percentage, \
ProgressBar, ReverseBar, RotatingMarker, \
SimpleProgress, Timer
from colorama import Fore, Back, Style
import os.path
#from termcolor ... |
from credo.customers import Customers
from . import SECRET_KEY, PUBLIC_KEY
class TestCustomers:
instance = Customers(public_key=PUBLIC_KEY, secret_key=SECRET_KEY)
def test_add_customer(self):
status, customer = self.instance.add(full_name='Random Name', email='rando.nam@gmail.co',
... |
# terrascript/data/cobbler.py
__all__ = []
|
# -*- coding: utf-8 -*
"""
Module for handling style options.
"""
import json
from styling.models import Option
KINDS = ['unrooted', 'scenario', 'mapping', 'optscen', 'gene', 'species', 'diagram']
def get_available_options(kind):
assert kind in KINDS, "Wrong tree kind %s" % kind
if kind == 'optscen':
... |
from rest_framework.serializers import ModelSerializer, Serializer, IntegerField, FloatField
from mapper.models import Protein, Peptide, SpanGroup, Region, SpanGroup_Regions, Peptide_SpanGroups
class ProteinSerializer(ModelSerializer):
class Meta:
model = Protein
fields = '__all__'
class Peptide... |
import webapp2
import gaesession.handlers
# this config is shared accross all the application, so use wisely.
config = {}
config['webapp2_extras.sessions'] = {
'secret_key': 'super_super_super_hard_key',
'cookie_name':'name_i_never_use_cookie', # this is the default session name/session id
'cookie_args': ... |
import tensorflow as tf
from model_HLS import Model_HLS
from GMM_para import GaussianMixture_data
from GMM_para import GaussianMixture_data_diag_cov
from GMM_para import cal_KL_symm_diag
from GMM_para import cal_KL_symm
import scipy.io as sio
import numpy as np
import time
import h5py
class Trainer(object... |
class Solution(object):
def isAnagram(self, s, t):
sd, td = {}, {}
for n in s:
sd[n] = sd.get(n, 0) + 1
for n in t:
td[n] = td.get(n, 0) + 1
return sd == td |
""" Test endpoints for API status"""
import pytest
from fastapi import status
from fastapi.logger import logger
from httpx import AsyncClient
from src.api.routers.api_status import APIStatus
@pytest.mark.asyncio
async def test_api_status(client: AsyncClient) -> None:
response = await client.get("/api-status")
... |
#==============================================================================
# node_master.py
# SNAP Master Node code that interacts with other nodes on the SNAP network
# to receive their data and forward it onto a serial-to-Internet gateway for
# remote monitoring purposes. This is part of an Exosite-compatible S... |
# -*- coding: utf-8 -*-
import math
class Vector(object):
@staticmethod
def add(v1, v2, fac1=1.0, fac2=1.0):
"""Calculate vector addition c=p*a+q*b
Args:
v1: tuple, vector a
v2: tuple, vector b
fac1: float, scale of v1
fac2: float scale of v2
... |
"""
Predicting Cannabis Sales with Panel Data
Cannabis Data Science Meetup Group
Copyright (c) 2021 Cannlytics
Authors: Keegan Skeate <keegan@cannlytics.com>
Created: 12/15/2021
Updated: 12/22/2021
License: MIT License <https://opensource.org/licenses/MIT>
"""
# External imports.
from dateutil import relativedelta
imp... |
"""
archive_dot_org.py
Copyright 2006 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af 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 2 of the License.
w3af is distributed in the hope ... |
import sys, os
from glbase3 import *
sys.path.append('../../')
import shared
all_genes = glload('../../transcript_assembly/packed/all_genes.glb')
cds = glload('../../transcript_assembly/get_CDS/coding_genes_with_local_CDS-corrected.glb')
cds = {gene['transcript_id']: gene for gene in cds}
#print(cds)
tes = glload('../... |
# Generated by Django 3.1.1 on 2020-10-02 11:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0011_auto_20201002_1457'),
]
operations = [
migrations.AlterField(
model_name='category',
name='subCateg... |
from django.contrib import admin
from . import models
# Register your models here.
admin.site.register(models.Item)
admin.site.register(models.ResumeBuilder)
admin.site.register(models.Skill)
admin.site.register(models.PersonalDetails)
admin.site.register(models.CareerObjective)
admin.site.register(models.Experience)
a... |
from django.shortcuts import render,redirect, reverse
from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect
from authorize_main.models import Account
from Notifications.views import Notifications
from Notifications.models import NotificationModel
from django.contrib import messa... |
import os
import cv2
import glob
import argparse
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument('--dir', type=str, default='.', help="image files dir")
parser.add_argument('--test', type=str, default=None, help='test image name')
opt = parser.parse_args()
# termination criteria
criteria = (... |
"""
Copyright (C) 2018, MuadDib
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
(at your option) any later version.
This program is distr... |
from pathlib import Path
import mkpy
from mkpy import get_ver
def test_get_ver():
# screen version for updates
get_ver()
|
"""Use this version inside packages and for distribution"""
from __future__ import unicode_literals
VERSION = (0, 0, 1)
__version__ = '.'.join(map(str, VERSION))
|
#!/usr/bin/env python
from setuptools import setup
setup(
setup_requires=['pbr'],
pbr=True,
)
import os
from setuptools import setup
requirements = [
'social-auth-core',
]
def read(filename):
with open(os.path.join(os.path.dirname(__file__), filename)) as f:
return f.read()
setup(
na... |
import cab_scraper
def lambda_handler(event, context):
try:
cab_scraper.run()
except:
return 'error'
return 'success'
|
""" Get type APIs for APIC """
import logging
from genie.metaparser.util.exceptions import SchemaEmptyParserError
from unicon.core.errors import TimeoutError
log = logging.getLogger(__name__)
def get_aci_registered_nodes_in_state(device, state):
""" Returns a list of node IDs that are in the provided state.
... |
from .connect_scan import ConnectScan
from .syn_scan import SynScan
from .ack_scan import AckScan
from .fin_scan import FinScan
from .udp_scan import UdpScan
|
import numpy as np
import math
import networkx as nx
from taxonomyLoadingService import TaxonomyLoadingService
class WuPalmerService:
"""
A service wrapping the data preparation functionality using the Wu-Palmer similarity measure
"""
@classmethod
async def wu_palmer_data_preparation(cls, entitie... |
"""modify users
Revision ID: f2856ed33727
Revises: cd90bb178b55
Create Date: 2021-07-10 23:47:00.133605
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f2856ed33727'
down_revision = 'cd90bb178b55'
branch_labels = None
depends_on = None
def upgrade():
# #... |
import sys
import json
import logging
from os import getenv as env
from os.path import join, dirname, exists
from dotenv import load_dotenv
from urllib.parse import urlparse
import csv
import itertools
from datetime import datetime
# boto imports
import boto3
from botocore.exceptions import ClientError
# google sheet... |
"""
.. module:: pipeline
:platform: Unix
:synopsis: This module handles the automatic generation and deployment of weak lensing simulation pipelines
.. moduleauthor:: Andrea Petri <apetri@phys.columbia.edu>
"""
|
"""PublicJwk API Tests for Version 1.0.
This is a testing template for the generated PublicJwkAPI Class.
"""
import unittest
import requests
import secrets
from py3canvas.apis.public_jwk import PublicJwkAPI
from py3canvas.apis.public_jwk import Developerkey
class TestPublicJwkAPI(unittest.TestCase):
"""Tests for... |
#!/usr/bin/env python
import sphinx_rtd_theme
project = 'GraphIdx'
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
html_logo = "../julia/assets/logo.png"
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.napoleon',
]
source_suffix = {'.rst': 'restructuredtext'}
master... |
#!/usr/bin/env libtbx.python
#
# iotbx.xds.xds_cbf.py
#
# James Parkhurst, Diamond Light Source, 2012/OCT/16
#
# Class to read the CBF files used in XDS
#
from __future__ import absolute_import, division, print_function
class reader:
"""A class to read the CBF files used in XDS"""
def __init__(self):
pass
... |
from slack_sdk import WebClient
from slack_sdk.webhook.client import WebhookClient
from server.service.slack.decorator import is_signature_valid
from server.service.slack.sdk_helper import get_web_client
def monkey_patch_get_web_client(team_id: str) -> WebClient:
return WebClient(token="1234")
def monkey_patch... |
from flask import Flask, request, render_template, url_for, redirect
import datetime
app = Flask(__name__)
@app.route('/')
def my_form():
return render_template('form.html')
@app.route('/', methods=['POST'])
def save_data():
name = request.form['name']
score = request.form['score']
name_u = name.up... |
# -*- coding: utf-8 -*-
"""Test encoding helpers"""
import unittest
from imap_cli import string
class ImapUTF7Test(unittest.TestCase):
encoded_string = (u'&AN8A7A-g '
u'T&AOo-st '
u'&A8kA7g-th spe&AOc-i&AOQ-l ch&AOIDwA-')
decoded_string = u"ßìg Têst ωîth speçiä... |
from google.cloud import bigquery
import configs
import os
def bq_to_dataframe(query_string):
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]=configs.GOOGLE_APPLICATION_CREDENTIALS
table_id = configs.TABLE_ID
bqclient = bigquery.Client()
dataframe = (
bqclient.query(query_string)
.r... |
# coding: utf-8
import tensorflow as tf
#OMP_NUM_THREADS=1
tf.config.threading.set_inter_op_parallelism_threads(0)
tf.config.threading.set_intra_op_parallelism_threads(0)
map_kwargs = {"fn_output_signature" : tf.float32, "parallel_iterations" : 30, "swap_memory" : True}
jit_compile = True
# ---------- No changes be... |
from confluent_kafka import avro
from confluent_kafka.avro import AvroProducer
from connect_test import config
"""
Produces messages with a flat Avro schema
"""
TOPIC_NAME = "complex_schema_test"
most_common_names_usa = [
[1, "James", {"field1": "data", "field2": "data2"}],
[2, "John", {"field1": "data", "f... |
import asyncio
import websockets
import json
import schedule
import datetime
# Connect to this host
ws_host = 'wss://ws-beta.nanoticker.info'
# logging accounts with a certain rep
repCheck = ['nano_1repnode4qpnebqobohfaxcgbrhtumfs6emijugpdkrcxb3jettdaw95xwio','nano_1json51qn9t7cqebcds1b7f9t3cffbki7qanudqpo67xcpowpt1or... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
import json, os
from time import sleep
import sys
import re
import config
import urllib
token_api = config.token
url = 'https://api.telegram.org/bot'+token_api+'/'
class JsonSerializable:
def to_json(self):
raise NotImplementedError
def getUpdates(o... |
import os
def silver(lines):
prev_depth = None
result = 0
for line in lines:
depth = int(line)
if prev_depth is not None:
if depth > prev_depth:
result += 1
prev_depth = depth
return result
def gold(lines):
prev_sum_depth = None
result = ... |
import pytest
from nylas.client.restful_models import Label, Thread, Message
@pytest.mark.usefixtures("mock_labels")
def test_list_labels(api_client):
labels = api_client.labels
labels = [l for l in labels]
assert len(labels) == 5
assert all(isinstance(x, Label) for x in labels)
@pytest.mark.usefixt... |
from python_ml.Ensemble.Selection.BaseSelection import BaseSelection
import numpy as np
class OLA(BaseSelection):
def __init__(self, X_val, y_val, n_neighbors):
super(OLA, self).__init__(X_val, y_val, n_neighbors)
def best_local_accuracy(self, predictions, actual_labels):
num_queries = actual_... |
#!/usr/bin/python3
# Translator App v1.0
#
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.uic import loadUi
import sys,googletrans
class Window(QMainWindow):
def __init__(self):
super(Window,self).__init__()
loadUi("./Form/page.ui",self)
se... |
from typing import List
from pytest_testrail_api_client.modules.category import Base
from pytest_testrail_api_client.modules.plan import Run
from pytest_testrail_api_client.service import split_by_coma, get_dict_from_locals
class RunsApi(Base):
__sub_host = '/api/v2'
def get_run(self, run_id: int) -> Run:
... |
def cadastrar_pessoa():
print(f'{"-"*30}\n{"NOVO CADASTRO": ^30}\n{"-"*30}')
pessoas = open("ex115/pessoas.txt", "a")
temp = list()
temp.append(str(input('Nome: ')).strip().capitalize())
temp.append(';')
while True:
idade = input('Idade: ').strip()
if idade.isnumeric():
... |
from django.urls import path
from .views import *
urlpatterns = [
path('', order_item_list, name="list-order-item"),
path('<int:pk>', order_item_list, name="list-order-item"),
path('list/', OrderItemListJson.as_view(), name="list-order-item-json"),
path('list/<int:pk>', OrderItemListJson.as_view(),
... |
"""
The:mod:`learnalg' module provides learning algorithms.
"""
from bnpy.learnalg.LearnAlg import LearnAlg
from bnpy.learnalg.VBAlg import VBAlg
from bnpy.learnalg.MOVBAlg import MOVBAlg
from bnpy.learnalg.SOVBAlg import SOVBAlg
from bnpy.learnalg.EMAlg import EMAlg
from bnpy.learnalg.MemoVBMovesAlg import MemoVBMov... |
import enum
from .analyzer import *
from . import up_to_down
from . import down_to_up
class AnalysisStrategy(enum.Enum):
UP_TO_DOWN = 0
DOWN_TO_UP = 1
_solvers = {
AnalysisStrategy.UP_TO_DOWN: up_to_down.get_solvers(),
AnalysisStrategy.DOWN_TO_UP: down_to_up.get_solvers()
}
def solve(_type, mode... |
import time
import telebot
from telebot import types
import gd
from gd import GoodreadsBook
from gd import GoodreadsClientException
greeting = """
✋ Welcome to LiberInfo bot 📚
We are a community of book lovers.
This is an inline bot, that make its easy to find a book you are interested in.
Also, we have some more... |
import torch
from layer import Layer
class Nearest_Neighbor(Layer):
def __init__(self, device, file_path=None):
print("init")
self.device = device
self.weights = []
self.file_path = file_path
def save(self):
if self.file_path:
torch.save(self.weights, self... |
import re
import unittest
import ir_datasets
from ir_datasets.formats import GenericDoc, GenericQuery, TrecQrel
from .base import DatasetIntegrationTest
class TestLotte(DatasetIntegrationTest):
def test_docs(self):
self._test_docs('lotte/lifestyle/dev', count=268893, items={
0: GenericDoc('0',... |
# """
# Runs libEnsemble on the 6-hump camel problem. Documented here:
# https://www.sfu.ca/~ssurjano/camel6.html
#
# Execute via the following command:
# mpiexec -np 4 python3 call_6-hump_camel.py
# The number of concurrent evaluations of the objective function will be 4-1=3.
# """
from __future__ import divisi... |
from axial_attention.axial_attention import AxialAttention, AxialPositionalEmbedding, AxialImageTransformer, SelfAttention
|
import pandas as pd
def score_valication(row):
try:
assert 0 <= row.Score <= 100
except:
print(f'#{row.ID}\tstudent {row.Name} has an invalid score {row.Score}')
students = pd.read_excel('C:/Temp/Students.xlsx')
# print(students)
students.apply(score_valication, axis=1)
|
import os
import sys
import pytest
import random
from pathlib import Path
CWD = Path(__file__).resolve().parent
code_dir = CWD / '../serverless'
sys.path.append(str(code_dir))
os.environ.update({
# setting this to zero means all pow are correct
'PYCHAIN_DIFFICULTY_BITS': '0',
'PYCHAIN_REDIS_HOST': 'redi... |
from django.apps import AppConfig
class HealthServicesConfig(AppConfig):
name = 'health_services'
verbose_name = _('Health-Services')
|
"""
Package containing implementations of the database(s) being used in the back-end.
Designed following the open-close principle, allows to decouple the rest of the
application from the database.
"""
from .sqlite_db import SQLite
|
from django.conf import settings
from django.conf.urls import include
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, re_path
from app import views
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('op_trans.urls')),
path('v1/... |
import torch
import torch.optim as optim
import numpy as np
class BaseAgent():
def __init__(self, model, model_target, action_size, seed, replay_size, batch_size,
update_frequency,gamma, lrate, tau, restore):
if restore is not None:
d = 'cuda:0' if torch.cuda.is_available() e... |
from credentials import WifiConfig, MQTTConfig
class Config:
MQTT_CLIENT_ID = 'ds18x20node'
MQTT_TOPIC = 'home/ds18x20'
# onewire
ONEWIRE_PIN = 0 # Pin number for the onewire port
# deepsleep
ENABLE_DEEPSLEEP = True # Enter deepsleep while waiting
SLEEP_TIME_S = 60 ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Rico Sennrich
# Distributed under MIT license
import sys
for line in sys.stdin:
linesplit = line.split(' ||| ')
linesplit[1] = ' '.join(reversed(linesplit[1].split()))
sys.stdout.write(' ||| '.join(linesplit)) |
from mpi4py import MPI
import mpids.MPInumpy as mpi_np
if __name__ == "__main__":
#Capture default communicator and MPI process rank
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
#Arrays elements (values 0-20)
mpi_array = mpi_np.arange(21, dist='b').reshape(7, 3)
#Reshape (Redistribute) Arra... |
import os
from pathlib import Path
from sys import exit
from typing import Iterable, Set
from colorama import Style
from . import DEFAULT_EXCLUDE, DEFAULT_INCLUDE, remove, search
from .config import CONFIG, Verbosity
def output(message: str, *args, verbosity: Verbosity = Verbosity.NORMAL, **kwargs):
if verbosit... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/14_training.language_model.ipynb (unless otherwise specified).
__all__ = ['LanguageModelDatasets', 'LanguageModelTuner']
# Cell
import pandas as pd
from fastcore.basics import mk_class
from fastcore.meta import delegates
from fastcore.xtras import Path, range_of
from f... |
#coding=utf-8
#切片P58 2017.4.12
print("Let's try to slice our list")
lists = ('a','b','c','d','e','f','g')
print('The first three items of the list are:\t'+str(lists[:3]))
count = int(len(lists))
print('The middle three items of the list are:\t'+str(lists[count//2-1:count//2+2]))
#Python 3 中的地板除: A//B 结果为int 而普通除:A/B 结果... |
import pytest
import rcpy.clock as clock
import time
def test1():
class MyAction(clock.Action):
def __init__(self):
self.count = 0
def run(self):
self.count += 1
action = MyAction()
obj = clock.Clock(action)
obj.start()
assert action... |
from cffi import FFI
import os
latCtrl_file = '/data/openpilot/selfdrive/controls/saicmotor/zs11_build/libVLatC.so'
ffi = FFI()
ffi.cdef("""
/*=======================================================================*
* Fixed width word size data types: *
* int... |
'''
Author: Ahmed Badra
Version: 1.0.0
Description: python script for training, evaluating and saving the model in the server's directory
'''
# import required Packages
from sklearn.model_selection import train_test_split as tts
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_clas... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import ctsparsinglib
print ctsparsinglib.findTargetInAllFiles('android.mediastress')
|
"""Test MediationManager."""
import logging
import pytest
from asynctest import mock as async_mock
from .....core.profile import Profile, ProfileSession
from .....connections.models.conn_record import ConnRecord
from .....messaging.request_context import RequestContext
from .....storage.error import StorageNotFoundE... |
from __future__ import annotations
import os
import sys
import time
from pathlib import Path
from threading import Thread, Event
from typing import Callable, Tuple
from PySide2.QtCore import Qt, QObject, Slot, Signal
from PySide2.QtGui import QFontMetrics
from PySide2.QtQml import QQmlApplicationEngine, QQmlProperty
f... |
import requests
def split_s3_pdf(dns_name, input_pdf_uri, bucket_name, endpoint_arn):
if dns_name.endswith("/"):
path = "s3_file"
else:
path = "/s3_file"
queries = f"?bucket_name={bucket_name}&endpoint_arn={endpoint_arn}&input_pdf_uri={input_pdf_uri}"
url = dns_name + path + queries
... |
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import Bookmodel, Reviewmodel, Shelfmodel, Locationmodel
from .forms import UserForm, ShelfForm
from . import bookutil
from . import visualizations
from rest_framework import generics
from .serializers import BookSe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.