content stringlengths 5 1.05M |
|---|
#! usr/bin/python3.6
"""
Module initially auto generated using V5Automation files from CATIA V5 R28 on 2020-07-06 14:02:20.222384
.. warning::
The notes denoted "CAA V5 Visual Basic Help" are to be used as reference only.
They are there as a guide as to how the visual basic / catscript function... |
import numpy as np
import glob
import os,sys
from skimage import io
from sklearn.model_selection import train_test_split
from tensorflow.keras.optimizers import SGD
from util import preprocess_image, create_model
def get_label_from_image_path(image_path, data_path):
path = image_path.replace(data_path, "");
paths ... |
# multiply a list by a number
def mul(row, num):
return [x * num for x in row]
# subtract one row from another
def sub(row_left, row_right):
return [a - b for (a, b) in zip(row_left, row_right)]
# calculate the row echelon form of the matrix
def echelonify(rw, i, m):
for j, row in enum... |
import os.path
import urllib
import requests
import time
from bs4 import BeautifulSoup
SITE_URL = "http://www.xn--od1bu1t7pcgwb.net/"
BLOG_ID = 'inja0391'
DELAY = 2
BLOG_KEYWORD_PRINT_FORMAT = """------------------------------------
{} 키워드 - 블로그검색
------------------------------------"""
INTEGRATED_KEYWORD_PRINT_FORM... |
#encoding: utf-8
from django.http import JsonResponse, HttpResponse
class HttpCode(object):
ok = 200
paramserror = 400
unauth = 401
methoderror = 405
servererror = 500
# {"code":400,"message":"","data":{}}
def result(code=HttpCode.ok,message="",data=None,kwargs=None):
json_dict =... |
from easydict import EasyDict as edict
import os
import shutil
import yaml
def mkdir_if_not_exists(path):
"""Make a directory if it does not exist.
Args:
path: directory to create
"""
if not os.path.exists(path):
os.makedirs(path)
def read_yaml(filename):
"""Load yaml file as a ... |
#!/usr/bin/env python3
from __future__ import print_function
from __future__ import absolute_import
import sys
import re, botocore
from taw.util import *
import taw.sshlike
import taw.instance
import taw.zone
import taw.bucket
import taw.vpc
import taw.subnet
import taw.list
import taw.sg
import taw.keypair
import taw... |
"""Define tests for the AirVisual config flow."""
from asynctest import patch
from pyairvisual.errors import InvalidKeyError
from homeassistant import data_entry_flow
from homeassistant.components.airvisual import CONF_GEOGRAPHIES, DOMAIN
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER
from homeass... |
from dy01.dy01 import DY01
__version__ = "1.0.0"
|
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin, UserManager
from django.conf import settings
from django.db.models.base import Model
import uuid
import os
def recipe_image_file_path(instance, file_name):
"""
generate file path for new re... |
# Copyright (c) 2018, 2020, Oracle Corporation and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
#
# ------------
# Description:
# ------------
# This is a WDT filter for primordial domain creation. It filters out all resources and
# apps d... |
"""Tests for SunSpec api."""
import pytest
from custom_components.sunspec.api import ConnectionError
from custom_components.sunspec.api import ConnectionTimeoutError
from custom_components.sunspec.api import SunSpecApiClient
from sunspec2.modbus.client import SunSpecModbusClientException
from sunspec2.modbus.client imp... |
"""Forms for Stories and related entities."""
from bootstrap3_datetime.widgets import DateTimePicker
from django import forms
from django.db.models import Q
from django.forms import Textarea, TextInput, Select
from editorial.models import (
Project,
Series,
Story,
)
from editorial.widgets im... |
from typing import List
from src.pc_methods.pc_base import Base
class GeoCNNv2(Base):
def __init__(self):
super().__init__()
def encode(self, orig_pc, enc_pc) -> List[str]:
cmd = ['python3',
self.cfg['encoder'],
'--input_files=' + str(orig_pc),
'--... |
import numpy as np
from MagniPy.LensBuild.Cosmology.cosmology import Cosmo
class TNFW:
def __init__(self,z=None,zsrc=None,c_turnover=True,cosmology=None):
"""
adopting a standard cosmology, other cosmologies not yet implemented
:param z1: lens redshift
:param z2: source redshift
... |
#!/usr/bin/env python
"""
Growatt MQTT Client
--------------------------------------------------------------------------
Based on the "Pymodbus Synchronous Server Example", the synchronous server
will process Growatt Modbus TCP packets using custom Request and Response
handlers.
"""
# ---------------------------------... |
from django.contrib import admin
from .models import Empleado
# Register your models here.
class EmpleadoAdmin(admin.ModelAdmin):
lista = ['nombre_completo', 'email', 'contacto', 'direccion']
admin.site.register(Empleado, EmpleadoAdmin)
|
""" Module contains openapi3 client """
import json
import logging
import urllib.request
from urllib.error import HTTPError
from urllib.error import URLError
from urllib.parse import urlencode
from . import exceptions
logger = logging.getLogger()
DEFAULT_CLIENT_HEADERS = {
'User-Agent': 'Mozilla/5.0',
}
def se... |
import pandas as pd
import networkx as nx
def to_bed(x,out):
x[1] = x[1].astype(int)
x[2] = x[2].astype(int)
x.to_csv(out,sep="\t",header=False,index=False)
def read_bedpe(f):
df = pd.read_csv(f,sep="\t",header=None)
df[1] = df[1].astype(int)
df[2] = df[2].astype(int)
df[4] = df[4].astype(int)
... |
import tensorflow as tf
import os
import sys
import pickle
import I2S_Model_Transformer
import selfies
import numpy as np
import argparse
import efficientnet.tfkeras as efn
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='+')
args = parser.parse_args()
os.environ["CUDA_VISIBLE_DEVICES"]="0"
gpus... |
"""
Python support for notebook I/O on Tiledb Cloud. All notebook JSON content
is assumed to be encoded as UTF-8.
"""
import posixpath
import time
from typing import Optional, Tuple
import numpy
import tiledb
from tiledb.cloud import array
from tiledb.cloud import client
from tiledb.cloud import rest_api
from tiled... |
#!/usr/bin/evn python
# -*- coding: utf-8 -*-
# python version 2.7.6
import gzip,shutil,os
def gzipCompress(fileName):
#生成压缩后的文件名
tarFileName = fileName+".gz"
with gzip.open(tarFileName, 'wb') as f_out,open(fileName,'rb') as f_in:
shutil.copyfileobj(f_in, f_out)
def gzipUnCompress(tarFileName):
fileName = os.p... |
# flake8: noqa
import unittest
from tests.settings.arguments import ArgumentsParserTestCase
if __name__ == '__main__':
unittest.main()
|
#
# 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
# ... |
import bpy
from bpy.props import *
from ..BASE.node_tree import RenderStackNode
from ...utility import *
def update_node(self, context):
if not self.use: return None
task_node = context.space_data.node_tree.nodes.get(bpy.context.window_manager.rsn_viewer_node)
if task_node: task_node.update()
class Vari... |
"""
w1thermsensor
~~~~~~~~~~~~~
A Python package and CLI tool to work with w1 temperature sensors.
:copyright: (c) 2020 by Timo Furrer <tuxtimo@gmail.com>
:license: MIT, see LICENSE for more details.
"""
import os
import time
import pytest
from w1thermsensor.errors import KernelModuleLoadError
from w1thermsensor.k... |
#!/usr/bin/env python3
from clib.mininet_test_util import get_serialno
from clib.mininet_test_topo import FaucetSwitchTopo, SWITCH_START_PORT
class FaucetTopoGenerator(FaucetSwitchTopo):
"""
Generate a Faucet topology for use in the mininet integration tests
FaucetTopoGenerator is able to connect up a n... |
"""A direct copy of a Google Spreadsheet to a postgresql database"""
import psycopg2
import pyiem.cscap_utils as util
from unidecode import unidecode
from six import string_types
config = util.get_config()
pgconn = psycopg2.connect(
database="sustainablecorn", host=config["database"]["host"]
)
ss = util.get_ssclie... |
import json
import os
from urllib.request import urlopen, Request
def sendToPushover(msg):
appToken = os.environ.get('PushoverAppToken')
userKey = os.environ.get('PushoverUserToken')
data = {"token": appToken, "user": userKey, "message": msg}
rq = Request("https://api.pushover.net/1/messages.json"... |
#!/usr/bin/env python
NAME = '(安全宝)anquanbao'
def is_waf(self):
return self.match_header(('X-Powered-By-Anquanbao', '.+'))
|
# OOP with Python
# Tech with Tim
class Dog(object):
def __init__(self, name, age):
# This is an attribute
self.name = name
self.age = age
# This is a method
def speak(self):
print(f"My name is {self.name}, and I am {self.age} years old.")
# (Dog) is the parent of Cat
cl... |
""" +=========================================================================================+
|| Lab04: A* Search ||
|| Name: Rashid Lasker Date: 9/18/14 ||
+===========================... |
# P4 Trigger script that triggers buildkite builds
# Usage:
# my-pipeline change-commit //depot/... "python %//depot/scripts/buildkite-trigger.py% <pipeline> %changelist% %user%"
import sys
import subprocess
try:
from urllib.request import urlopen, Request
except ImportError:
from urllib2 import urlopen, Reques... |
class Vec3:
def __init__(self, *args):
if len(args) == 3:
self.x, self.y, self.z = args[0], args[1], args[2]
elif len(args) == 0:
self.x, self.y, self.z = 0, 0, 0
else:
raise
def __add__(self, v):
if isinstance(v, Vec3):
... |
# Generated by Django 2.2 on 2020-07-28 14:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0002_auto_20200728_1753'),
]
operations = [
migrations.AlterField(
model_name='category',
name='description',
... |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import os, sys
import pprint
from shutil import copy2
import xml.etree.ElementTree as ET
TAG_PREFIX='{http://www.cern.ch/cms/DDL}'
CMSSW_NOT_SET=1
TRACKER_MATERIAL_FILE_MISSING=2
HEADER = """
#ifndef SIMTRACKER_TRACKERMATERIALANALYSIS_LISTGR... |
from bottle import run, get, view, post, request
import json
import jwt
import requests
##############################
@get("/company")
@view("index_company.html")
def do():
return dict(company_name="SUPER")
@get("/company-token")
@view("index_company_token.html")
def do():
return dict(company_name="Token ... |
"""
Decoding pipeline.
"""
import argparse
import cPickle
import logging
import numpy
import os
import pprint
import re
import theano
import time
import importlib
from theano import tensor
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from mcg.models import EncoderDecoder, MultiEncoder, Multi... |
# Generated by Django 2.2.13 on 2020-09-22 19:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("resources_portal", "0001_initial"),
]
operations = [
migrations.AlterField(
model_name="address", name="address_line_2", field=... |
import mnist
from load_data.ILoadSupervised import ILoadSupervised, SupervisedType
__all__ = ["LoadMnist",]
fashion_path = 'train_data/Folder_Images_Supervised/fashionmnist'
kuzushiji_path = 'train_data/Folder_Images_Supervised/kuzushiji'
class LoadMnist(ILoadSupervised):
#fashion: mnist_path='train_data\\Folder... |
'''
Created on Aug 23, 2013
@author: Brad
'''
import unittest
from utils.config import Config
class Test(unittest.TestCase):
conf = None
def setUp(self):
self.conf = Config()
def tearDown(self):
self.conf = None
def test_get_picture_vals_VISUALLY(self):
... |
from onegov.ticket.handler import Handler, HandlerRegistry
handlers = HandlerRegistry() # noqa
from onegov.ticket.model import Ticket
from onegov.ticket.model import TicketPermission
from onegov.ticket.collection import TicketCollection
__all__ = [
'Handler',
'handlers',
'Ticket',
'TicketCollection'... |
import kornia.augmentation as K
import torch.nn as nn
from torch.nn.modules.utils import _pair
from ..common import (crop_and_resize, get_crop_grid, get_random_crop_bbox,
images2video, video2images)
from ..registry import TRACKERS
from .vanilla_tracker import VanillaTracker
@TRACKERS.register_m... |
import argparse
import sys
def get_count(bed):
"""
Get number of lines in the bed file. If the chromosome,
contains any of these substrings, then don't count
"""
ignore_contigs = {'hs', 'GL', 'X', 'Y'}
return len(set([line for line in open(bed).readlines()
if all([ic not in line... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
# 软件设计师上午题
class RkpassItem(scrapy.Item):
question = scrapy.Field() # 题目
questionImg = scrapy.Field() # 题目图片
optiona = scrapy.Field() # 选... |
# Copyright 2020 The TensorFlow 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
import requests
import urllib.request
import time
import discord
from bs4 import BeautifulSoup
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
def get_first_anchor_url(bs_element):
anchor_url = None
anchors = bs_element.select("a")
if len(anchors) > 0:
anchor_url = anchors[0].get("hr... |
def insertionSort(b):
for i in range(1, len(b)):
up = b[i]
j = i - 1
while j >= 0 and b[j] > up:
b[j + 1] = b[j]
j -= 1
b[j + 1] = up
return b
def bucketSort(A):
n = len(A)
arr = []
for i in range(n):
arr.append([])
for i in range... |
import torch
from typing import List, Tuple
from base.base_trainer import BaseTrainer
from utils.logger import setup_logger
from tqdm.auto import tqdm
logger = setup_logger(__name__)
class Trainer(BaseTrainer):
def __init__(
self,
model,
optimizer,
loss,
config,
de... |
"""Basic HTTP Server with dynamic page generation"""
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, HTTPServer
class Content:
"""HTTP Content wrapper"""
def __init__(self, template, mime):
self._template = template
self.content = self._template
self.mime =... |
from classes_and_objects.exe.to_do_list.project.task import Task
class Section:
def __init__(self, name: str):
self.name = name
self.tasks = []
def add_task(self, new_task):
for task in self.tasks:
if task.name == new_task.name:
return f"Task is already Tas... |
from sweepstakes_stack_manager import SweepstakesStackManager
from sweepstakes_queue_manager import SweepstakesQueueManager
import user_interface
class MarketingFirmCreator:
def __init__(self):
self.queue = SweepstakesQueueManager()
self.stack = SweepstakesStackManager()
def choose_manager(s... |
from dataclasses import dataclass
import json
import typing as t
from .ninja import EncryptedImageNinja
@dataclass()
class Password:
name: str
login: str
passphrase: str
def __str__(self) -> str:
return f"{self.name}({self.login})"
class ImageVault:
passwords: t.List[Password]
def... |
# Programação Orientada a Objetos
# AC03 ADS-EaD - Implementação de classes, herança, polimorfismo e lançamento de exceções.
#
# Email Impacta: bruno.rferreira@aluno.faculdadeimpacta.com.br
class Produto:
"""
Classe Produto: deve representar os elementos básicos de um produto.
"""
def __init__(self, ... |
import ants
import antspynet
import tensorflow as tf
import numpy as np
from superiq import super_resolution_segmentation_per_label
from superiq import list_to_string
template = antspynet.get_antsxnet_data( "biobank" )
template = ants.image_read( template )
template = template * antspynet.brain_extraction( template )... |
#!/usr/bin/python
"""
This code will 'score' input against a 'trained'
frequency distribution.
"""
import random
#Trainable model
model_norm = [0.0] * 256
model_raw = [0.0] * 256
model_normalized = False
def resetModel():
global model_norm
global model_raw
global model_normalized
model_norm = [0.0] * 256
... |
from ecellManager import * |
import os
import shutil
from conans import ConanFile, CMake, tools
from future.moves import sys
sys.path.append(
os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
class CAresConan(ConanFile):
from gcc import GCC_VERSIONS, CURRENT_GCC_VERSION
with open(os.path.join(os.path.dirname(os.path.... |
from mamba import description, before, context, it
from doublex import Spy
from expects import expect, be_true, be_false
from doublex_expects import have_been_called, have_been_called_with
from mamba import reporter, runnable
from mamba.example import Example
from mamba.example_group import ExampleGroup
from spec.ob... |
from pytest_bdd import given, when, then
from model.group import Group
@given('a group list', target_fixture="group_list")
# все шаги given рассматриваются как фикстуры, и поэтому можно их передавать как параметры в другие шаги
def group_list(db):
return db.get_group_list()
@given('a new group with <name>, <heade... |
from django.urls import path
from .views import VisualizerView
urlpatterns = [
path('<int:voting_id>/', VisualizerView.as_view()),
]
|
# Generated by Django 2.2.1 on 2019-07-01 17:47
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('prescription', '0001_initial'),
]
operations = [
migrations.AlterField(
mo... |
import datetime
import re
import dateutil.rrule as dr
import dateutil.parser as dp
import dateutil.relativedelta as drel
import OrgExtended.orgduration as orgduration
import calendar
def total_seconds(td):
"""Equivalent to `datetime.timedelta.total_seconds`."""
return float(td.microseconds +
(... |
#!python
import sentinel_api as api
# use username and password for ESA DATA Hub authentication
username = '****YOUR_ESA_DATA_HUB_USERNAME****'
password = '****YOUR_ESA_DATA_HUB_PASSWORD****'
# please also specify the Hub URL:
# All Sentinel-1 and -2 scenes beginning from 15th Nov. 2015: https://scihub.esa.int/apihub... |
#!/usr/bin/env python
"""
Created by howie.hu at 2018/11/21.
"""
from ruia import Request, Spider, Middleware
middleware = Middleware()
@middleware.request
async def print_on_request(request):
request.headers = {
'User-Agent': 'ruia ua'
}
@middleware.response
async def print_on_response(request, ... |
##
## The class SensorReader will read the raw ultrasonic sensor measurements
## and converts them into centimeter. After this, the readings will be filtered by a
## median filter of the size which is specified as a parameter. The function
## getSensorReadings() can be called every timestep and will return ... |
import random
import time
from crawlers.Spider import Spider as SpiderBase
from crawlers.Types import ArticleReturnType
from models.Article import Article
from models.Media import Media
from playwright.sync_api import BrowserContext, Page
from utils import Logger
from utils.crawl import (
cleanhtml,
get_elemen... |
"""
A pytest module to test Reed-Solomon decoding.
"""
import pytest
import numpy as np
import galois
from .helper import random_errors
CODES = [
(15, 13), # GF(2^4) with t=1
(15, 11), # GF(2^4) with t=2
(15, 9), # GF(2^4) with t=3
(15, 7), # GF(2^4) with t=4
(15, 5), # GF(2^4) with t=5
... |
"""Tests for runners."""
import os
import unittest
from ecosystem.runners import PythonTestsRunner, PythonStyleRunner, PythonCoverageRunner
class TestPythonRunner(unittest.TestCase):
"""Tests for Python runner."""
def setUp(self) -> None:
current_directory = os.path.dirname(os.path.abspath(__file__)... |
"""The test project for the draw_rect interface.
Command examples:
$ python test_projects/draw_rect/main.py
"""
import sys
sys.path.append('./')
import os
from types import ModuleType
import apysc as ap
from apysc._file import file_util
this_module: ModuleType = sys.modules[__name__]
_DEST_DIR_... |
"""
.. module: lemur.plugins.lemur_aws.s3
:platform: Unix
:synopsis: Contains helper functions for interactive with AWS S3 Apis.
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
from flas... |
import numpy as np
from math import sqrt
def str2bit(s):
return s.strip().replace('/', '').replace('.', '0').replace('#', '1')
def str2val(s):
return int(str2bit(s), 2)
def str2arr(s):
return (np.array([list(row) for row in s.strip().split('/')]) == '#').astype(np.uint8)
def arr2val(a):
return int('... |
#!/usr/bin/env python
import rospy
import threading
import time
from robot_sim.msg import RobotState
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
from math import sin
from math import cos
from math import pi
class CartPoleGUI(object):
def __init__(self):
self.sub = rospy.Subscriber("... |
"""
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY 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.
CVXPY is distributed ... |
import re
import os
import sys
import time
import random
import subprocess
from PyQt5 import QtGui
from PyQt5 import QtCore, QtGui, QtWidgets
def open_file(filename):
if sys.platform == "win32":
os.startfile(filename)
else:
opener = "open" if sys.platform == "darwin" else "xdg-open"
sub... |
from shapely.geometry import Point, LineString, Polygon
def createPointGeom(x_cord, y_cord):
return Point(x_cord, y_cord)
def createLineGeom(lst_points):
line = []
for elem in lst_points:
if (isinstance(elem, Point)):
line.append(elem)
return LineString(line)
... |
import pytest
import numpy as np
from numpy.testing import assert_array_equal, assert_array_almost_equal_nulp
from sklearn.datasets import make_regression
try:
from mpi4py import MPI
except ImportError:
MPI = None
from pyuoi.datasets import make_classification, make_poisson_regression
from pyuoi.linear_model i... |
__all__ = ['ev3dev', 'lego','mindsensors'] |
import os
import pickle
import sys
import time
import traceback
import numpy as np
if __name__ == '__main__':
# insert this project in path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import sys
sys.path.insert(0, "/home/blankjul/workspace/pymop/... |
from checkmatelib import CheckmateClient, CheckmateException
from pyramid.httpexceptions import HTTPTemporaryRedirect
class ViaCheckmateClient(CheckmateClient):
def __init__(self, request):
super().__init__(
host=request.registry.settings["checkmate_url"],
api_key=request.registry.... |
from glob import glob
import os
import pandas as pd
import numpy as np
from pathlib import Path
import unittest
import shutil
import matplotlib.pyplot as plt
from clouds.preprocess import Preprocessor
from clouds.inference import Inference
from clouds.experiments import GeneralInferExperiment
from clouds.experiments.u... |
# 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
# d... |
# stdlib
import os
from io import StringIO
# 3rd party
import coverage # type: ignore
import pytest
from coincidence import only_version
from coincidence.regressions import check_file_regression
from coverage.python import PythonParser # type: ignore
from domdf_python_tools.paths import PathPlus
from pytest_regressi... |
# This is a test.
|
import errno
import functools
import numpy as np
import os
from osgeo import gdal, gdalnumeric
class RasterFile(object):
def __init__(self, filename, band_number=1):
self.file = str(filename)
self._band_number = band_number
self._geotransform = None
self._extent = None
sel... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2019-07-14 12:40
from __future__ import unicode_literals
import bluebottle.utils.fields
from decimal import Decimal
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('funding', '0013_auto_20190711_0927'),
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from netests.workers.device_ssh import DeviceSSH
from netests.exceptions.netests_exceptions import NetestsFunctionNotPossible
from netests.converters.bgp.juniper.ssh import _juniper_bgp_ssh_converter
from netests.converters.facts.juniper.ssh import _juniper_facts_ssh_conv... |
from . import jalali
from django.utils import timezone
def converter(time):
jmonth=["January","February","March","April","May","June","July","August","September","October","November","December"]
time = timezone.localtime(time)
time_to_str= f"{time.year},{time.month},{time.day}"
time_to_tuple=jala... |
import numpy as np
__all__ = [
"calcTisserandParameter"
]
# This code generates the dictionary of semi-major axes for the
# third body needed for the Tisserand parameter
#
#
# from astropy.time import Time
# from thor.utils import getHorizonsElements
#
# ids = ["199", "299", "399", "499", "599", "699", "799", "89... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
import getpass
import os
import db_utils as dbutils
import fixture_utils as fixutils
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
def before_all(context):
os... |
import pymysql
from config import host, port, user, password, db, sessions_dir
import datetime
import os
def get_db():
try:
# return pymysql.connect(host=host, port=port, user=user, password=password, db=db)
return pymysql.connect(host=host, port=port, user=user, password=password, db=db, use_unic... |
# coding: utf-8
# In[1]:
#Boolean / logical values:
# In[2]:
#True
# In[3]:
#False
# In[4]:
4<5
# In[5]:
10>100
# In[6]:
4 == 5
# In[7]:
# == equals
# != or <>
# <
# >
# <=
# >=
# and (in R its &)
# or (in R its /)
# not
# ---
# In[8]:
result=4<5
# In[9]:
result
# In[10]:
type(r... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.db import models
# from .utilidades import ESTADO,TIPO_CANCHA,TIPOUSR,ESTADO_CUOTA,TRIBUTO_CUOTA,TIPO_LOGIN
from django.contrib.auth.models import User
from datetime import datetime,date
from dateuti... |
from dataclasses import dataclass
from typing import TYPE_CHECKING, Optional
import re
from pyquery import PyQuery
from utils import url_is_broken
if TYPE_CHECKING:
from entities.page import Page
@dataclass
class Link:
html: str
page: "Page"
@property
def href(self) -> str:
return PyQuer... |
# -*- coding: utf-8 -*-
"""Data Access Objects for diseasescope REST server"""
import os
import logging
import shutil
import json
import glob
logger = logging.getLogger(__name__)
TASK_JSON = 'task.json'
TMP_RESULT = 'result.tmp'
RESULT = 'result.json'
STATUS_RESULT_KEY = 'status'
NOTFOUND_STATUS = 'notfound'
UNKNO... |
from flask import Flask, request
from flask_restful import Resource, Api
import base64
app = Flask(__name__)
app.secret_key = 'Abhi1234'
api = Api(app)
class Picture(Resource):
# @jwt_required()
def post(self):
req_data = request.get_json()
f = open('C:/Users/prasanna/PycharmProjects/Aut... |
import sys
import c
VAL = 20
print("The real value of c.func is: {}".format(c.func(VAL)))
# ideally, you would have never imported this module
sys.modules.pop("c")
# create reference to real import so we don't lose it
a_real_import = __import__("a")
a_fake_import = __import__("b")
# fake the import
sys.modules["a"... |
"""model for text2sql
03.11.2020 - @yashbonde"""
import numpy as np
from tabulate import tabulate
from types import SimpleNamespace
import torch
import torch.nn as nn
from torch.nn import functional as F
from transformers.modeling_utils import find_pruneable_heads_and_indices, prune_conv1d_layer
from transformers.act... |
#use groupby to count the sum of each unique value in the fuel unit column
fuel_data.groupby('fuel_unit')['fuel_unit'].count()
fuel_data[['fuel_unit']] = fuel_data[['fuel_unit']].fillna(value='mcf')
#check if missing values have been filled
fuel_data.isnull().sum()
fuel_data.groupby('report_year')['report_year'].cou... |
from pysam import FastaFile
import re
from tqdm import tqdm
import string
import os
from collections import defaultdict
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) + '/'
DATA_DIR = os.path.join(CURRENT_DIR, '..', 'data/')
MM10_FASTQ = DATA_DIR + 'mm10.fa'
MOUSE_GTF = DATA_DIR + 'Mus_musculus.GRCm38.91.ch... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.