content stringlengths 5 1.05M |
|---|
"""Individual (semi) operations for data importing.
"""
|
from allennlp_models.pair_classification.dataset_readers.quora_paraphrase import (
QuoraParaphraseDatasetReader,
)
from allennlp_models.pair_classification.dataset_readers.snli import SnliReader
|
"""
Views related to the Custom Courses feature.
"""
import csv
import datetime
import functools
import json
import logging
from copy import deepcopy
import pytz
import six
from ccx_keys.locator import CCXLocator
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.models imp... |
#!/usr/bin/env python
import rospy
import cv2
import sys
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import CompressedImage, Image
#from virtual_mirror_npd22 import util
import numpy as np
import threading
#from std_msgs.msg import String
VERBOSE=False
class mirror:
def __init__(self):
sel... |
#-------------------------------------#
# 对单张图片进行预测
#-------------------------------------#
import glob
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from yolo import YOLO
from PIL import Image
import os
import json
TEST_DIR = "./dataset/test"
yolo = YOLO()
answer = []
... |
import os
from tkinter import N
from ..module import *
def scan_path(path: str, arrow, logger=print) -> None:
logger(f'- scaning path={path}')
listDir = os.listdir(path)
for dir in listDir:
subPath = f"{path}\\{dir}"
arrow(subPath)
if os.path.isdir(subPath):
... |
# -*- coding: utf-8 -*-
"""
:create: 2018/9/23
:copyright: smileboywtu
"""
schemas = {
"get": {
"type": "object",
"properties": {
"name": {"type": "string"},
},
"required": ["name"]
},
"post": {
},
"put": {
},
"delete": {
}
}
|
import torch
import torch.nn as nn
from pytorch_pretrained import BertModel, BertTokenizer
class BertConfig(object):
"""
配置参数
"""
def __init__(self):
self.model_name = 'Bert'
# epoch
self.num_epochs = 10
# batch_size
self.batch_size = 37
# 每句话处理的长度(短填,长切... |
import pytest
from utils import SUCCESS, validate_input, ERRORS, default_fn, default_x_min, default_x_max
x_min_default = default_x_min
x_max_default = default_x_max
# Validation function tests
# Responsible for checking basic functionality of `validate_input`
# =======================================================... |
from disease_spread_model.data_processing.visualisation import *
from disease_spread_model.config import RealDataOptions
# [1] ******************************************************
RealVisualisation.show_real_death_toll(voivodeships=['all'],
last_day=100,
... |
from itertools import (
chain as __it_chain__,
groupby as __it_group__,
islice as __it_slice__,
starmap as __it_star_map__, )
class NamedTuple(object):
''' '''
__slots__ = ()
@classmethod
def __len__(cls):
''' '''
return len(cls.__slots__)
@class... |
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Address
from .models import Profile
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ["usernam... |
import itertools
from . import names
def closest_colors(color_name, metric=None):
metric = metric or euclidean
color = names.to_color(color_name)
mn_list = [(metric(color, c), n) for n, c in names.COLOR_DICT.items()]
mn_list.sort()
min_metric = mn_list[0][0]
result = []
for met, name in m... |
import os
from markdown import markdown as markdown_function
from django import template
from django.urls import reverse
from django.template.defaultfilters import stringfilter
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
from ..utils import get_script_alias
register = ... |
# ./x.py
# -*- coding: utf-8 -*-
# PyXB bindings for NM:e92452c8d3e28a9e27abfc9994d2007779e7f4c9
# Generated 2020-01-06 11:11:22.290106 by PyXB version 1.2.7-DEV using Python 3.7.4.final.0
# Namespace AbsentNamespace0
from __future__ import unicode_literals
import io
import pyxb
import pyxb.binding
# Import binding... |
import numpy as np
import blimpy as bl
import pandas as pd
from astropy import units as u
import sys, os, glob, errno
import csv
import json
import h5py
import time
from astropy.stats import sigma_clip
from scipy.signal import butter, lfilter, filtfilt
import scipy.signal
sys.path.insert(0, "/home/bryanb/setigen/")... |
import sys, yaml, os.path, parse, tag_manager, argparse, itertools
from report_parser import LegatoReport
from clustering import *
from termcolor import colored
review = False
def print_path(p, start, end = 0):
it = start
while it >= end:
if p[it][0] == 'P' or p[it][0] == 'L':
print " +++ ... |
from . import Model, snowflake, unicode
from ..utils import parse_datetime
from .user import User
class DMChannel(Model):
spec = {
'id': snowflake,
'is_private': bool,
'recipient': User,
'last_message_id': snowflake
}
class Overwrite(Model):
spec = {
'id': snowfl... |
# -*- coding: utf-8 -*-
# Builtin Modules
import time
import traceback
# 3rd-party Modules
import six
from celery.exceptions import SoftTimeLimitExceeded, TimeLimitExceeded
import celery.states as celery_status
# Project Modules
from worker import app
from worker.utils import toolkit, yaml_resources
from worker.util... |
"""
Storage configuration
"""
from dotenv import find_dotenv, load_dotenv
import os
"""
|--------------------------------------------------------------------------
| Load Environment Variables
|--------------------------------------------------------------------------
|
| Take environment variables from the .env file... |
# Generated by Django 3.0.3 on 2020-02-06 14:48
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('erp', '0035_auto_20200206_1109'),
]
operations = [
migrations.AlterModelOptions(
name='erp',
options={'ordering': ('nom',), ... |
import app.config_params as cfg
def main(curr_module_string):
print(f"WordHAL v{cfg.ver_maj}.{cfg.ver_min}")
print(curr_module_string)
print("-"*30)
|
import requests
from contextlib import closing
from time import sleep
import xml.etree.ElementTree as ET
from transformers.transformer import Transformer
from openapi_server.models.compound_info import CompoundInfo
from openapi_server.models.compound_info_identifiers import CompoundInfoIdentifiers
from openapi_server... |
import util, exception
class get_alba:
def __init__(self):
self.GET_ALBA_SUCCESS = {"message": "get_alba success!!"}
def get_alba(self, request):
id = request["id"]
no = request["no"]
if id == None or no == None:
return exception.UNLOGINED_USER
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 24 10:36:17 2021
@author: Research_Lab
"""
import numpy as np
from scipy.interpolate import CubicSpline
from scipy.interpolate import interp1d
from matplotlib import pyplot as plt
import seaborn as sns; sns.set_theme()
from scipy.interpolate import interp2d
... |
"""
An adaptation of python-bidi: https://github.com/MeirKriheli/python-bidi
Python 2 compatibility and debugging have been stripped out, and a new option
has been added to return the original logical position of each character after
conversion to display form.
THE ORIGINAL PYTHON-BIDI LICENSE FOLLOWS:
python-bidi ... |
from django.conf import settings
def settings_context(_request):
return {
"settings": settings,
}
|
"""
Pre-train a CNN on the whole dataset for evaluation purpose
"""
import os
import argparse
import shutil
import timeit
import torch
import torchvision
import torchvision.transforms as transforms
import numpy as np
import torch.nn as nn
import torch.backends.cudnn as cudnn
import random
import matplotlib.pyplot as ... |
"""
Module wraps all lookups done by InstaRecon and returns results only.
Raises lookup.NoInternetAccess.
"""
import logging
from random import randint, choice
import re
import socket
import sys
import time
import dns.resolver
import dns.reversename
import ipaddress as ipa # https://docs.python.org/3/library/ipaddr... |
#!/usr/bin/env python3
# This example shows how to make any window that opens on a workspace floating
# All workspaces that start with a string in this list will have their windows
# open floating
FLOATING_WORKSPACES = ['3']
def is_ws_floating(name):
for floating_ws in FLOATING_WORKSPACES:
if name.start... |
# 12 Mar 2014
# in case any of this upsets Python purists it has been converted from an equivalent JRuby program
# this is designed to work with ... ArduinoPC.ino ...
# the purpose of this program and the associated Arduino program is to demonstrate a system for sending
# and receiving data between a PC and an Ar... |
# The difference between cgan.py and cgan_new.py is the training process. In cgan.py, we can add the encoder on top of gan to help the generator generate more realistic images. And the training process is different. In cgan.py, the training step of generator and discriminator change depend the accuray of each neural n... |
""" discovery/seeking_alpha_model.py tests """
import unittest
from unittest import mock
# pylint: disable=unused-import
from gamestonk_terminal.test_helper import ( # noqa: F401
parameterize_from_file,
pytest_generate_tests,
)
from gamestonk_terminal.discovery.seeking_alpha_model import get_next_earnings
a... |
import hashlib
import requests
import sys
import time
# TODO: Implement functionality to search for a proof
def proof_of_work(last_proof):
proof = 46787391
while valid_proof(last_proof, proof) is False:
proof += 1
print("Proof found: " + str(proof))
return proof
def valid_proof(last_proof, proof... |
import paho.mqtt.client as paho
import time
import Queue as queue
import json
import real_time_manipulator_math_utils
import pprint
import dynaban as dnb
import time
import pypot.robot
import pypot.dynamixel
import snoop
import threading
import sys
pp = pprint.PrettyPrinter(indent=4)
# import rbdl
# import manip mot... |
import base64
import hashlib
import hmac
import json
import logging
import os
import time
from json.decoder import JSONDecodeError
import pandas as pd
import requests
from munch import munchify
logger = logging.getLogger(__name__)
class BFXException(Exception):
pass
class BFXClient(object):
"""
Client... |
# -*- coding: utf-8 -*-
"""Command line interface publish (no sub-commands)."""
import os
import sys
import subprocess
from contextlib import contextmanager
from types import SimpleNamespace
from pathlib import Path
import click
import pygit2
from et_micc.project import Project
try:
from __version__ import __vers... |
'''
This bflt can generate the same bflt as the tinyos code
Used to verify the correctness of TOSSIM simulation
'''
FNV_32_PRIME = 0x01000193
FNV_32_INIT = 0x811c9dc5
FNV_64_PRIME = 0x100000001b3
FNV_64_INIT = 0x14650FB0739D0383
L = 128 # the number of bits in the Bloom Filter
H = 3 # the number of hash value... |
"""fips verb to build the oryol samples webpage"""
import os
import yaml
import shutil
import subprocess
import glob
from string import Template
from mod import log, util, project, emscripten, android
from tools import texexport
# what to build
BuildEmscripten = True
BuildWasm = True
ExportAssets = True
ExtensionSa... |
# -*- coding: utf-8 -*-
"""
@author: Yifan Cheng, Skylar Du, Yashash Gaurav, Mark He
"""
import pandas as pd
import helpers as h
import numpy as np
us_state_to_abbrev = {
"Alabama": "AL",
"Alaska": "AK",
"Arizona": "AZ",
"Arkansas": "AR",
"California": "CA",
"Colorado": "CO",
"Connecticut"... |
#!/usr/bin/env python
#author: wowdd1
#mail: developergf@gmail.com
#data: 2014.12.07
from spider import *
class EdxSpider(Spider):
def __init__(self):
Spider.__init__(self)
self.school = "edx"
self.edx_subject = [\
"Architecture",
"Art & Culture",
... |
# -*- coding: utf-8 -*-
###
# (C) Copyright [2019] Hewlett Packard Enterprise Development LP
#
# 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/local/bin/python3
import os
from random import randint
import math
import numpy as np
import argparse
H_PATTERN = 0b1 << 0
V_PATTERN = 0b1 << 1
D_PATTERN = 0b1 << 2
AD_PATTERN = 0b1 << 3
def time_pattern_to_byte_timestamp(time, pattern, dt_units_ps=125):
"""
time in units of ps
retrieve time and ... |
# -*- coding: utf-8 -*-
import re
import decimal
from gsxws import objectify
import babel.numbers
from datetime import timedelta
from django import template
from django.utils import safestring, timezone
from django.utils.translation import ugettext as _
from django.template.defaultfilters import date
from django.co... |
from .message import (
BaseMessage,
DeformableMeshesMessage,
MeshesMessage,
AddRigidBodyPrimitiveMessage,
UpdateRigidBodyPoseMessage,
FinishAnimationMessage,
)
from .server_util import (
AsyncServer,
MeshChunksHandler
)
__all__ = [
'BaseMessage',
'DeformableMeshesMessage',
'... |
import sys, glob, os
path = os.getcwd()
sys.path.insert(0, ".")
from vnpy.trader.database import database_manager
bars = database_manager.get_bar_data_statistics()
for b in bars:
if b['symbol'][0] not in "036":
database_manager.delete_bar_data(b['symbol'], b['exchange'], b['interval'])
print(f"=> D... |
from handlers import Handler
class HCHandler(Handler):
def __init__(self):
print 'HELLO1'
|
from mkultra.inference import GPT2SoftPromptLM
from mkultra.tokenizers import GPT2SPTokenizerFast
from mkultra.soft_prompt import SoftPrompt
def test_instantiate_multiple_objects():
# Act
model_a = GPT2SoftPromptLM.from_pretrained("gpt2")
tokenizer_a = GPT2SPTokenizerFast.from_pretrained("gpt2")
sp_a ... |
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
RAW_DATA_DIR = os.path.join(BASE_DIR, 'raw_data')
TOPIC_PATH = os.path.join(BASE_DIR, 'data/lda/topic.json')
DOC_PATH = os.path.join(BASE_DIR, 'data/lda/doc.json')
TOT_MODEL_PATH = os.path.join(BASE_DIR, 'data/tot/model.json')
LDA_MODEL_PATH = os.path.jo... |
# encoding: utf-8
import argparse
import json
import os.path
import time
from nltk.translate import bleu_score
import numpy
import six
import pickle
import chainer
from chainer import cuda
from chainer.dataset import convert
from chainer import reporter
from chainer import training
from chainer.training import extens... |
'''
Adapted from https://github.com/IntelligentQuadruped, with permission
Description: Module used to interpolate values of depth matrix.
Original paper: https://github.com/sparse-depth-sensing/sparse-depth-sensing
'''
import numpy as np
import time
from scipy.interpolate import Rbf
import matplotlib.pyplot as plt
d... |
# Generated by Django 2.0.5 on 2018-05-08 18:11
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name='Author',
fields=[
('id', models.AutoField(primar... |
from playwright.sync_api import sync_playwright
import database_ops as dbo
import logging
logging.basicConfig(filename="scrape.log", format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S', level=logging.INFO)
def convert_to_int(s) -> int:
"""
Converts a string to int
Args:
... |
# Copyright 2019 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, ... |
# Generated by Django 2.1.7 on 2019-03-09 13:46
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('importCsv', '0004_auto_20190309_1345'),
]
operations = [
migrations.RemoveField(
model_name='manager',
name='city',
... |
import MySQLdb
import MySQLdb.cursors
def get_conn(creds, dict_result=False):
cursor = MySQLdb.cursors.DictCursor if dict_result else MySQLdb.cursors.Cursor
db = MySQLdb.connect(host=creds['HOST'], port=int(creds['PORT']), user=creds['USER'], passwd=creds['PASSWORD'],
db=creds[... |
"""Testing ensembling models on M4 timeseries
"""
from darts import TimeSeries, ModelMode, SeasonalityMode
from darts.models import NaiveSeasonal, ExponentialSmoothing, Theta, FourTheta, LinearRegressionModel
from darts.models.forecasting_model import ForecastingModel
from darts.utils.statistics import check_seasonal... |
__all__ = ["block", "block_linked_list"] |
from django.shortcuts import render
import pickle
import requests
from datetime import date
import pandas as pd
from django.http.response import StreamingHttpResponse
from prediction.camera import VideoCamera
import plotly.graph_objects as go
from plotly.offline import init_notebook_mode,iplot
import plotly.express as ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Rocpy.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui,... |
# Generated by Django 2.1.3 on 2019-04-01 12:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('engine', '0022_labels_color'),
]
operations = [
migrations.AddField(
model_name='labels',
name='catego... |
# Lint as: python3
# Copyright 2020 The IREE Authors
#
# Licensed under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Tests of streamable Keyword Spotting models implemented in Keras."""
import os
... |
BOT_TOKEN="1815166261:AAEM7evbzwfVXIPHdAS4Yi34sKJWMrR80RE"
SECRET_KEY="A long secret key" |
#!/usr/bin/env python3
from pathlib import Path
from mushroom_rl.core import Logger
from mushroom_rl_benchmark import BenchmarkLogger, BenchmarkVisualizer
from mushroom_rl_benchmark.experiment.slurm import read_arguments_aggregate
def aggregate_results(res_dir, res_id, console_log_dir=None):
"""
Function to... |
#for profile appstats
import os
def webapp_add_wsgi_middleware(app):
if os.environ["SERVER_SOFTWARE"].find("Development")!=-1:
#if True:
from google.appengine.ext.appstats import recording
app = recording.appstats_wsgi_middleware(app)
return app
|
"""Simulation of the impact of differential privacy on a block that has
N people all the same age (22)."""
BLOCK_AGE=22
MAX_AGE=110
NUM_TRIALS=10000
TRIALS='trials'
PRIVATIZED_AVERAGE_AGE='privatized_average_age'
PRIVATIZED_AVERAGE_AGES='privatized_average_ages'
PRIVATIZED_COUNT='privatized_count'
PRIVATIZED_COUNTS='p... |
from fairseq import utils, options
from fairseq.tasks.translation import TranslationTask
from fairseq.tasks import register_task
from dataloaders.mle_dataset import MLELanguagePairDataset
from fairseq.data import (IndexedCachedDataset,
IndexedDataset,
IndexedRawTextDataset,
LanguagePairDataset,
ConcatDa... |
import pylibmc
memcached = pylibmc.Client(['127.0.0.1'], binary=True, behaviors={"tcp_nodelay": True})
#Using mapping interface
memcached["First"] = "First Value"
print memcached["First"]
del memcached["First"]
#Using classic style
if memcached.add("Second", "Second Value"):
print memcached.get("Second")
if mem... |
import socketio
import traceback
import time
from app.crud import (
users,
study_rooms,
reports,
my_studies,
statuses,
redis_function
)
from app.database import SessionLocal
fr... |
import asdf
import pytest
from asdf.tests import helpers
purposefully_failing = [
# old-style bounding box fails
# 1D string bound
"""
!transform/shift-1.2.0
offset: 1
bounding_box: [1.0, test]
""",
# 1D only one bound
"""
!transform/shift-1.2.0
offset: 1
boundin... |
print abs(-1)
print abs(1)
print abs(0)
print abs(-0.0)
print abs(-4.6)
print abs(4.6)
|
import logging
from nnimgproc.dataset import Dataset
from nnimgproc.model import BaseModel
from nnimgproc.processor import TargetProcessor, BatchProcessor
from nnimgproc.util.parameters import Parameters
class BaseTrainer(object):
"""
Meta class for training and evaluating a neural network
"""
def __... |
import numpy as np
class Metric():
'''
Metric Class
'''
def __init__(self, fixation_array):
"""Init method
Parameters
----------
fixation_array : numpy float array
array having coordinates x,y, and duration as columns values
... |
import tictactoe as ttt
from hypothesis import given
from hypothesis.strategies import integers, tuples, one_of, just
coordinate = tuples(integers(min_value=0, max_value=2), integers(min_value=0, max_value=2))
any_marker = one_of(just(ttt.X), just(ttt.O))
def test_flatten_board():
init = ttt.initial_state()
... |
#!/usr/bin/env python3
import os
import sys
import hashlib
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed2551... |
import os
import json
from plumbum import local as Cmd
from plumbum import TEE
from functions import enable_logging, interpret_result, write_result_to_debug
class QtlTools:
"""Calls QTL tools to run in docker container"""
def __init__(self):
"""Start docker container end define instance variables"""
... |
#!/usr/bin/env python3
import os
import xmltodict
import argparse
import sys
import psutil
import subprocess
import time
SIVDir = 'C:\Program Files (x86)\Gigabyte\SIV'
ProfileDir = os.path.join(SIVDir, 'Profile')
thermaldPath = os.path.join(SIVDir, 'thermald.exe')
class MyParser(argparse.ArgumentPars... |
# coding: utf-8
"""
Copyright 2017 Square, 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 la... |
"""
Main window for taking input and run functions.
"""
import sys
import os
import time
import numpy as np
from itertools import cycle
from threading import Event, Thread
from multiprocessing import Process, Queue, Pool
# import Visualization as visual # will be deleted after finish updating current one.
from PyQt... |
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import math
RESCALE_COEF = 1 / math.sqrt(2)
def residual_connect(x, y, rescale=False):
out = x + y
if rescale:
out *= RESCALE_COEF
return out
class KeyValAttentio... |
"""
Copyright 2020 The OneFlow Authors. 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 agr... |
from pathlib import Path
from tqdm import tqdm
import click
import dask.dataframe as dd
from dask.distributed import Client
import pandas as pd
import pandas_profiling
client = Client(processes=False)
@click.command()
@click.option('--ext', prompt='Enter file extension (csv, xlsx)', help='File extension you want to l... |
r"""
===============================================================================
throat_normal -- calculate from the normal vector to the throat vertices
===============================================================================
"""
import scipy as sp
from scipy.spatial import ConvexHull
from transforms3d imp... |
import os
import asyncio
from pyxcaptcha import XCaptchaAsyncClient
TEST_TOKEN = os.getenv("test_token")
async def async_fun():
client = XCaptchaAsyncClient(TEST_TOKEN)
balance = await client.api.get_balance()
print(balance)
resp = await client.send_captcha("6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ... |
from django.template.base import Library
from django import template
from django.template.base import Node
class SetVarNode(Node):
def __init__(self, var_name):
self.var_name = var_name
def render(self, context):
page = context['__CACTUS_CURRENT_PAGE__']
context[self.var_name] = page... |
#!/bin/python3
import sys
import datetime
def computeFine(expected, actual):
if actual.year > expected.year:
return 10000
elif actual.year == expected.year:
if actual.month > expected.month:
return 500 * abs(actual.month - expected.month)
elif actual.month == expected.month... |
import sqlalchemy as db
from sqlalchemy import func
def create_engine(path):
if path is None:
raise CreateEngineException('path for engine is empty')
return db.create_engine(path)
def connect(engine):
if engine is None:
raise Exception('Engine is not defined')
return engine.connect()
... |
from talon import Context, actions
ctx = Context()
ctx.matches = r"""
os: linux
tag: user.packager_yay
"""
@ctx.action_class('user')
class UserActions:
# see yay.py for additional actions
def packager(): actions.auto_insert('yay ')
def package_search(): actions.auto_insert('yay -sS ')
def packa... |
#!/usr/bin/env python
from geometry_msgs.msg import PoseStamped, TransformStamped
import rospy
import tf2_ros
if __name__ == '__main__':
rospy.init_node('pose_from_tf')
tfBuffer = tf2_ros.Buffer()
listener = tf2_ros.TransformListener(tfBuffer)
pose_pub = rospy.Publisher("slam_pose", PoseStamped, que... |
#!/usr/bin/python
import logging
import sys
import csv
USAGE = './condition.py demographicFile subcodeQuery'
logging.basicConfig( level=logging.INFO )
logger = logging.getLogger( __name__ )
def conditionToInt(condition):
condition = str(condition)
if condition == "SCZ" or condition == "SCZ-SIB":
return 1
... |
import requests
import re
import html
from bs4 import BeautifulSoup
import unicodedata
import base64
import zlib
import json
import html
from abc import abstractmethod
from lrc_kit.lyrics import Lyrics
import logging
# https://github.com/ddddxxx/LyricsKit/tree/master/Sources/LyricsService/Provider
# https://github.com... |
from setuptools import setup, find_packages
from torch.utils.cpp_extension import BuildExtension, CUDAExtension, CUDA_HOME
modules= []
# TODO WE ASSUME THAT CUDA IS AVAILABLE
# if CUDA_HOME:
modules.append(
CUDAExtension('binarization', [
'pysembles/cuda/binarization/binarization.cpp',
... |
#!/usr/bin/python3
def reconstruct(parts):
keys = set(''.join(parts))
values = [set([]) for i in range(len(keys))]
prevChars = dict(zip(keys, values))
for i in parts:
for j in range(1, len(i)):
prevChars[i[j]].add(i[j - 1])
if (j > 1):
prevChars[i[j]]... |
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# NOTE If scopes are modified you need to delete the file token.json
SCOPES = ['https://www.googleapis.com/auth/drive.file']
def genTokenFromCreds(creds=None):
... |
from flask import Blueprint, make_response, request, jsonify, abort
from flask.views import MethodView
from app.models import Organization, db
org_blueprint = Blueprint('organization', __name__)
class OrganizationView(MethodView):
"""This class-based handles api requests for the organization resource."""
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:
if not root:
return None
... |
t = int(input())
entradas = input()
entradas = entradas.split(' ')
cont = 0
for i in range(5):
if int(entradas[i]) == t:
cont += 1
print(cont) |
import glob
import functools
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pkl
from deepfnf_utils.tf_spatial_transformer import transformer
import deepfnf_utils.utils as ut
import deepfnf_utils.tf_utils as tfu
import time
import jax
import jax.numpy as jnp
with open('./data/exifs.pkl', 'r... |
import configparser
import logging
from pathlib import Path
import sys
def getc(module=None, key=None):
config = configparser.ConfigParser()
config.read(str(Path.home()) + '/ripda/config.ini')
return config[module][key]
def setc(module=None, key=None, value=None):
config = configparser.ConfigParser(... |
"""
.. helpdoc::
"""
"""
<widgetXML>
<name>Convert To Table/Prop Table</name>
<icon>default.png</icon>
<tags>
<tag>Data Manipulation</tag>
</tags>
<summary>Converts a data table of factors to counts of the unique combinations of levels. For exampel if your data table consi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.