text
string
size
int64
token_count
int64
import argparse from argparse import ArgumentError from libvirt_vm_optimizer.util.utils import Profile class Settings: def __init__(self, libvirt_xml=None, output_xml=None, in_place=False, profile=Profile.DEFAULT, force_multithreaded_pinning=Fal...
3,148
841
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """This module contains class MRT_File. The MRT_File class contains the functionality to load and parse mrt files. This is done through a series of steps, detailed in README. """ __authors__ = ["Justin Furuness", "Matt Jaccino"] __credits__ = ["Justin Furuness", "Matt J...
8,323
2,832
from rcaudio import * import time import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s') def demo1(): CR = CoreRecorder( time = 10, sr = 1000, batch_num = 100, frames_per_buffer...
1,611
626
#!/usr/bin/python3 print("content-type: text/html") print() import subprocess as sp import cgi fs = cgi.FieldStorage() cmd = fs.getvalue("command") output = sp.getoutput("sudo "+cmd) print("<body style='padding: 40px;'>") print('<h1 style="color:#df405a;" >Output</h1>') print("<pre>{}</pre>".format(ou...
346
140
from flask import Flask from flask_restful_swagger.swagger import SwaggerRegistry try: from unittest.mock import patch except ImportError: from mock import patch @patch("flask_restful_swagger.swagger._get_current_registry") @patch("flask_restful_swagger.swagger.render_homepage") def test_get_swagger_registr...
1,334
409
import logging import webapp2 from googleapiclient.errors import HttpError from gcp_census.bigquery.bigquery_client import BigQuery from gcp_census.bigquery.bigquery_task import BigQueryTask class BigQueryBaseClass(webapp2.RequestHandler): def __init__(self, request=None, response=None): super(BigQueryB...
1,921
542
from os import popen def get_output(s): return popen(s).read()
67
25
#!/usr/bin/env python3.6 import argparse import json import sys from typing import Sequence, MutableSequence from dresources import DAction, action from external_services import ExternalServices from gcp import GcpResource class GcpIamServiceAccount(GcpResource): def __init__(self, data: dict, svc: ExternalSer...
3,056
881
#!/usr/bin/python3 import pytest import monitor.monitorshared as m import monitor.consumtodb as con def test_db_connection(tmpdir): "test postgres connection" conf = m.Configuration('configx.ini', "test") # in case the field is empty if conf.db_host == '': pytest.skip("no broker configure...
806
251
import argparse import torch import yaml def load_config(): parser = argparse.ArgumentParser(description='UNet3D training') parser.add_argument('--config', type=str, help='Path to the YAML config file', required=True) args = parser.parse_args() config = _load_config_yaml(args.config) # Get a devi...
542
176
# This codes are referenced from the Github repo (https://github.com/parulnith/Building-a-Simple-Chatbot-in-Python-using-NLTK/blob/master/chatbot.py) # Loading the required packages import nltk import random import string import warnings from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics...
4,630
1,349
#!/usr/bin/env python # encoding: utf-8 import sys LEVEL = { 'NORMAL': 0, 'INFO': 1, 'DEBUG': 2, 'CRITICAl': 0, 'ERROR': 0, 'EXCEPTION': 0, } class Color(object): ESCAPE = '\033[%sm' BOLD = '1;%s' UNDERLINE = '4;%s' BLUE_ARROW = ESCAPE % (BOLD % '34') # Blue Bold DEBUG =...
2,714
1,079
import SocketServer import io import logging import struct import threading import PIL.Image import pika import config logging.basicConfig(level=logging.INFO) class RequestHandler(SocketServer.BaseRequestHandler): def handle(self): print 'Process socket connections thread:', threading.current_thread()....
2,031
572
from pygame import image class ShowFaces(): def __init__(self, filePath, colour = (0, 0, 0), posX = 0, posY = 100, resourcePath = ""): self.filePath = filePath self.colour = colour self.posX = posX self.posY = posY self.resourcePath = resourcePath self.image = image.load(self.resourcePath + "img/faces/" +...
537
212
import os import shutil import build_utils def get_supported_targets(platform): if platform == 'win32': return ['win32'] elif platform == 'darwin': return ['macos'] elif platform == 'linux': return ['linux'] else: return [] def get_dependencies_for_target(target): ...
3,506
1,210
from .explorer import Explorer __version__ = "1.0.2"
53
20
import subprocess import os.path import json import time import urllib.parse from typing import Any, Tuple import config from requests_html import HTMLSession from markdownify import markdownify class Data: def __init__( self, data_file_path: str = config.DATA_FILE_PATH, preload: bool = Fa...
6,192
1,892
import pysdot as ot import numpy as np import matplotlib.pyplot as plt numPts = 100 xbnds = [0.0,1.0] # minimum and maximum x values ybnds = [0.0,1.0] # minimum and maximum y values Ns = [50,50] bbox = ot.BoundingBox(xbnds[0],xbnds[1],ybnds[0],ybnds[1]) grid = ot.RegularGrid(bbox, Ns[0], Ns[1]) dens = np.ones(Ns) f...
1,407
583
#Exercise: Try to make a function that accepts a function of only positional arguments and returns a function that takes the same number of positional arguments and, given they are all iterators, attempts every combination of one arguments from each iterator. #Skills: Partial application, Iteration papplycomboreverse ...
589
154
class Node: """ This object is a generic node, the basic component of a Graph. Fields: data -- the data this node will contain. This data can be any format. """ def __init__(self, data): self.data = data
237
68
import os import sys os.chdir(os.path.dirname(__file__)) sys.path.append(os.path.dirname(__file__)) sys.path.append(os.path.join(sys.path[0], '/var/www/haproxy-wi/app/')) from bottle import route, run, template, hook, response, request, post import sql import funct def return_dict_from_out(id, out): data = {} data...
6,780
3,042
# Copyright [2015] Hewlett-Packard Development Company, L.P. # 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...
27,885
7,465
""" Waymo dataset with votes. Author: Ahmed Bahnasy Date: 2020 """ import os import sys import numpy as np import pickle from torch.utils.data import Dataset import scipy.io as sio # to load .mat files for depth points BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # ROOT_DIR = os.path.dirname(BASE_DIR) sys.pa...
15,179
5,523
import unittest import sin_testing as st import pexpect import os class TestFail(st.SmokeTest): @st.sinan("build") def build(self, child, app_desc): if not os.path.isfile(os.path.join(os.getcwd(), "test", "test_module.erl")): raise "Nome module f...
2,792
846
from budgetportal.models import ( FinancialYear, Sphere, Government, Department, Programme, ) from django.core.management import call_command from django.test import TestCase from tempfile import NamedTemporaryFile from StringIO import StringIO import yaml class BasicPagesTestCase(TestCase): de...
7,362
2,146
import json import logging import ssl import sys from oidcrp.exception import ResponseError logger = logging.getLogger(__name__) def load_json(file_name): with open(file_name) as fp: js = json.load(fp) return js def fed_parse_response(instance, info, sformat="", state="", **kwargs): if sformat...
898
282
from __future__ import unicode_literals import requests import json import os import sys outputs = [] def get_lat_lng(city): try: googleclientSecretFile = open('google_api_key', 'r') GCLIENTSECRET = googleclientSecretFile.read() GCLIENTSECRET = GCLIENTSECRET[:-1] except: print(...
3,884
1,391
#! /usr/bin/python3 # # @(!--#) @(#) swss.py, version 002, 27-july-2018 # # open a series of home pages and take a screen shot of each one # ################################################################################################ # # imports # import sys import os import argparse import glob import shutil im...
6,855
2,038
"""state consumed Revision ID: 0be658f07ac6 Revises: bd1e892d0609 Create Date: 2021-07-18 21:26:04.588007 """ from alembic import op import sqlalchemy as sa from sqlalchemy.sql import table, column from sqlalchemy import String # revision identifiers, used by Alembic. revision = '0be658f07ac6' down_revision = 'bd1e...
1,041
362
from unittest import TestCase, mock from copy import deepcopy from pydantic.error_wrappers import ValidationError from basemodels.pydantic import Manifest from basemodels.pydantic.manifest.data.taskdata import TaskDataEntry SIMPLE = { "job_mode": "batch", "request_type": "image_label_multiple_choice", "r...
2,878
1,281
from os.path import exists def get_next_path(path_frmt: str, start: int = 1) -> str: """Return next available path based on path_frmt (1 positional-placeholder)""" return path_frmt.format(get_next_path_index(path_frmt, start=start)) def get_next_path_index(path_frmt: str, start: int = 1) -> int: """Get ...
1,064
331
from .core import where, old_where __version__ = "2016.02.28"
63
29
from setuptools import setup, find_packages setup( name="QtCompat", version="0.1", packages=find_packages(), scripts=[], # Project uses reStructuredText, so ensure that the docutils get # installed or upgraded on the target machine install_requires=[], package_data={ }, # meta...
681
209
import os from unittest import TestCase from aibolit.patterns.joined_validation.joined_validation import JoinedValidation from pathlib import Path class TestJoinedValidation(TestCase): dir_path = Path(os.path.realpath(__file__)).parent pattern = JoinedValidation() def test_canFindSimpleJoinedValidation(s...
2,730
743
""" Global tuple to avoid make a new one each time a method is called """ my_tuple = ("London", 123, 18.2) def city_tuple_declaration(): city = ("Rome", "London", "Tokyo") return city def tuple_get_element(index: int): try: element = my_tuple[index] print(element) except IndexError: ...
971
336
import django_filters from . models import NerSample class NerSampleListFilter(django_filters.FilterSet): text = django_filters.CharFilter( lookup_expr='icontains', help_text=NerSample._meta.get_field('text').help_text, label=NerSample._meta.get_field('text').verbose_name ) c...
389
121
# TODO Postcode: https://m3o.com/postcode/overview
51
20
import numpy as np class Agent: def __init__(self): self.q_table = np.zeros(shape=(3, )) self.rewards = [] self.averaged_rewards = [] self.total_rewards = 0 self.action_cursor = 1 class HystereticAgentMatrix: def __init__(self, environment, increasing_learning_rate=0.9...
3,016
944
# -*- coding: utf-8 -*- # Copyright 2020 The PsiZ 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 r...
14,581
4,215
# Generated by Django 2.1.7 on 2019-08-04 06:43 import datetime from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('user', '0004_auto_20190804_1438'), ] operations = [ migrations.AlterField( model_name='subjectinfo',...
1,261
458
import platform #check the platform for linux, macos, windows if platform.system() == "Linux": print("manylinux1_x86_64") elif platform.system() == "Windows": print("win-amd64") elif platform.system() == "Darwin": print("macosx_10_15_x86_64") else: print("Unknown")
282
103
# https://leetcode.com/problems/mirror-reflection class Solution: def mirrorReflection(self, p, q): if q == 0: return 0 i = 0 val = 0 while True: val += q i += 1 if (i % 2 == 0) and (val % p == 0): return 2 ...
508
168
# coding=utf-8 # *** WARNING: this file was generated by the Kulado Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import json import warnings import kulado import kulado.runtime from .. import utilities, tables class GetAccountResult: """ A...
4,290
1,149
""" running converferce for finite differences and Taylor-Green vortex """ import os from math import pi import xml.etree.ElementTree as ET import platform_paths as pp import manipulator as ma # load parameter file ma.set_ids('../XML/parameterTGVTime.xml') TREE = ET.parse('../XML/parameterTGVTime.xml') ROOT = TREE.ge...
1,988
781
""" """ import logging import os import random import time import matplotlib import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from helper import loader, utility as util matplotlib.use("agg") INPUT_IMAGE_DIR = "input" INTERPOLATED_IMAGE_DIR = "interpolated" TRUE_IMAGE_DIR = "true" class...
14,617
4,573
from .context import main
27
9
import os.path as osp import numpy as np import math from tqdm import tqdm import torch.nn as nn import torch.backends.cudnn as cudnn import torch.utils.data from torchvision import transforms, datasets from ofa.utils import AverageMeter, accuracy from ofa.model_zoo import ofa_specialized from ofa.imagenet_classifica...
23,149
9,846
# Script is deprecated, as of September 18, 2017. # zoneUnitCount now calculated with LoadData's _get_residential_units() # from pprint import pprint import os import sys import requests from collections import OrderedDict import csv import datetime PYTHON_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__)...
8,713
2,527
""" The `~certbot_dns_cfproxy.dns_cfproxy` plugin automates the process of completing a ``dns-01`` challenge (`~acme.challenges.DNS01`) by creating, and subsequently removing, TXT records using the CFProxy API. Examples -------- .. code-block:: bash :caption: To acquire a certificate for ``example.com`` certbo...
402
140
from flask import Flask, make_response, request from flask_cors import CORS import json from config import * from StudentCard import * from ApiError import * App = Flask(__name__) cors = CORS(App, resources={r'*': {'origins': ENV.ADDR_API_GATEWAY}}, headers='Content-Type: application/json') ...
1,234
371
import logging from smart_home.mqtt_client import MQTTClient from smart_home.utils_lambda import get_utc_timestamp, error_response, success_response, get_request_message_id, get_mqtt_topics_from_request, get_request_name, get_friendly_name_from_request class PowerController(object): @staticmethod def handle_...
2,604
740
from netCDF4 import Dataset import matplotlib import matplotlib.pyplot as plt from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection import matplotlib.cm as cm import numpy as np #------------------------------------------------------------- def plot_subfigure(axis, array, nCells, n...
4,082
1,331
a, b = map(int, input().split()) if a+b >= 10: print("error") else: print(a+b)
87
41
#### import the simple module from the paraview from paraview.simple import * #### disable automatic camera reset on 'Show' paraview.simple._DisableFirstRenderCameraReset() network_number = 2 filename = 'test_network' directory = 'C:\\Users\\leal26\\Documents\\GitHub\\AeroPy\\aeropy\\CST\\' # get active view...
2,278
899
import glob import json import os import subprocess import time import xml.etree.ElementTree as ET from xml.etree.ElementTree import ParseError import geopandas as gpd import rasterio import numpy as np from shapely.geometry import Polygon class PipelineError(RuntimeError): def __init__(self, message): s...
21,804
6,613
#!/usr/bin/env python3 import unittest import sys sys.path.insert(0, '.') from random import choice from PIL import Image from stego.encoder import embed from stego.decoder import extract, _decompress, IncorrectPassword from stego.base import make_array, as_string, extract_metadata images = ['test/rgba.png', 'test/...
1,308
455
import pandas as pd from rpy2 import robjects from epysurv.simulation.utils import add_date_time_index_to_frame, r_list_to_frame def test_add_date_time_index_to_frame(): df = add_date_time_index_to_frame(pd.DataFrame({"a": [1, 2, 3]})) freq = pd.infer_freq(df.index) assert freq == "W-MON" def test_r_li...
638
262
import cmake cmake.buildCmake( 'CodeBlockUnixMake', '../../', '../../assemble/' )
95
37
#!/usr/bin/env python3 # @file cow_pipeline.py # @author Ignacio Vizzo [ivizzo@uni-bonn.de] # # Copyright (c) 2021 Ignacio Vizzo, all rights reserved import argh from datasets import BunnyGeneratedDataset as Dataset from vdbfusion_pipeline import VDBFusionPipeline as Pipeline def main( data_source: s...
655
230
import os import pytest from dashboard_generator import DashboardGenerator def test_generate_widget_ensure_return_value_is_dict(env_variables): response = DashboardGenerator()._generate_widget(y=1, period=60, pipeline='foo') assert type(response) == dict def test_generate_widget_ensure_values_are_used_pro...
1,091
295
""" Tests for opencadd.structure.superposition.engines.mda """ import pytest from opencadd.structure.core import Structure from opencadd.structure.superposition.engines.mda import MDAnalysisAligner def test_mda_instantiation(): aligner = MDAnalysisAligner() def test_mda_calculation(): aligner = MDAnalysisA...
795
267
import engine print("Python: Script 2") class Rotation(metaclass=engine.MetaComponent): def __init__(self): self.trans = 5 result = engine.query(Color) print("Python: Query colors from Script 2") for c in result: c.string() print("--------------------")
274
86
# ##### BEGIN MIT LICENSE BLOCK ##### # # MIT License # # Copyright (c) 2022 Steven Garcia # # 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 limitation ...
4,389
1,374
import gzip, os, struct, zipfile, io class SmartFileReader(object): def __init__(self, file, *args, **kwargs): if file[-3:]=='.gz': with open(file, 'rb') as f: f.seek(-4, 2) self._filesize = struct.unpack('I', f.read(4))[0] self.file = gzip.open(file, *args, **kwargs) elif file[-4:]=='.zip': ...
1,537
664
from __future__ import absolute_import from time import * import datetime import six def get_utctimestamp(mtime=None): # pragma: no cover """ Converts local mtime (timestamp) to integer UTC timestamp. If mtime is None, returns current UTC time. """ if mtime is None: if six.PY2: return int((datetime.datetime.n...
510
170
__version__ = [1, 0, 2] __versionstr__ = '.'.join([str(i) for i in __version__]) if __name__ == '__main__': print(__versionstr__)
135
56
from pathlib import Path from typing import Dict from eodatasets3 import serialise from .common import assert_same, dump_roundtrip def test_valid_document_works(tmp_path: Path, example_metadata: Dict): generated_doc = dump_roundtrip(example_metadata) # Do a serialisation roundtrip and check that it's still ...
572
186
import numpy as np import matplotlib.pyplot as plt #################### def merge_dicts(list_of_dicts): results = {} for d in list_of_dicts: for key in d.keys(): if key in results.keys(): results[key].append(d[key]) else: results[key] = [d[key]]...
4,369
1,727
#!/usr/bin/env python # # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
3,154
1,132
#!/usr/bin/python import httplib import random import argparse import sys #Get options parser = argparse.ArgumentParser( description='Testing vote app') parser.add_argument( '-port', type=int, help='port of server', default=8000) parser.add_argument( '-host', ...
1,136
403
from uuid import UUID import django_rq import logging from datetime import datetime, timezone, timedelta from django.core.mail import mail_managers from django.db.models import Count from django.db.models.functions import TruncDay from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcu...
8,161
2,440
# rename shading group name to material name but with SG ended import pymel.core as pm import re selSG = pm.ls(sl=True,fl=True) for SG in selSG: curMat = pm.listConnections(SG,d=1) for mat in curMat: if pm.nodeType(mat) == 'blinn' or pm.nodeType(mat) == 'lambert': sgNM = re.split("_mat",str(...
365
143
import pytest from common.common import NETTING_ACCOUNT from fixture.application import Application @pytest.fixture(scope="session") def app(request): base_url = request.config.getoption("--base_url") fixture = Application(base_url) fixture.wd.maximize_window() fixture.wd.implicitly_wait(10) yield...
729
255
"""CHAPPS Utilities Tests .. todo:: Write tests for :class:`~chapps.util.VenvDetector` """ import pytest from pprint import pprint as ppr from chapps.util import AttrDict, PostfixPolicyRequest pytestmark = pytest.mark.order(1) class Test_AttrDict: def test_attr_dict_return_int(self, mock_config_dict): ...
3,855
1,216
from django.contrib import admin from .models import Map admin.site.register(Map)
84
25
from . import pwcnet from . import pwcnet_irr from . import pwcnet_occ_joint from . import pwcnet_irr_occ_joint from . import tr_flow from . import tr_features from . import IRR_PWC from . import IRR_PWC_occ_joint from . import STAR PWCNet = pwcnet.PWCNet PWCNet_irr = pwcnet_irr.PWCNet PWCNe...
816
368
import os import re #hack for python2 support try: from .blkdiscoveryutil import * except: from blkdiscoveryutil import * class Blkid(BlkDiscoveryUtil): def parse_line(self,line): details = {} diskline = line.split(':',1) if len(diskline) < 2: return path = disk...
2,386
735
# Copyright 2018 Cristian Mattarei # # Licensed under the modified BSD (3-clause BSD) License. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the ...
6,217
2,111
#!/usr/bin/python3 # # Copyright (c) 2012 Mikkel Schubert <MikkelSch@gmail.com> # # 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 limitation the rights ...
4,623
1,418
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #๋‚ด ๋งฅ๋ถ์—์„œ ๋ฐœ์ƒ๋˜๋Š” ์—๋Ÿฌ๋ฅผ ์—†์• ๊ธฐ ์œ„ํ•œ ์ฝ”๋“œ import tensorflow as tf #using matrix x_data = [[73., 80., 75.], [93., 88., 93.,], [89., 91., 90.], [96., 98., 100.], [73., 66., 70.]] y_data = [[152.], [185.], [180.], [196.], [142.]] X = tf.placeholder(tf.float32, shape=[None, 3]) #n๊ฐœ์˜ ๋ฐ...
976
499
# (c) Copyright 2014,2015 Hewlett-Packard Development Company, L.P. # # 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 ap...
3,291
950
from rubicon.repository.asynchronous import AsynchronousBaseRepository from rubicon.repository.utils import json class S3Repository(AsynchronousBaseRepository): """The asynchronous S3 repository uses `asyncio` to persist Rubicon data to a remote S3 bucket. S3 credentials can be specified via environment ...
1,558
404
""" ================================================== Example on how to plot multiple datasets at a time ================================================== This is an example of how to download and plot multiple datasets at a time. .. image:: ../../multi_ds_plot1.png """ import act import matplotlib.pyplot as plt ...
1,660
603
flat_x = x.flatten() flat_y = y.flatten() flat_z = z.flatten() size = flat_x.shape[0] filename = 'landscapeData.h' open(filename, 'w').close() f = open(filename, 'a') f.write('#include "LinearMath/btScalar.h"\n#define Landscape01VtxCount 4\n#define Landscape01IdxCount 4\nbtScalar Landscape01Vtx[] = {\n') for i in r...
805
391
#### # This script demonstrates how to use the Tableau Server Client # to create new projects, both at the root level and how to nest them using # parent_id. # # # To run the script, you must have installed Python 3.6 or later. #### import argparse import logging import sys import tableauserverclient as TSC def cre...
2,776
770
from threading import Thread import time import unittest import rasterio as rio from rasterio.env import get_gdal_config class TestThreading(unittest.TestCase): def test_multiopen(self): """ Open a file from different threads. Regression test for issue #986 """ def func(...
2,146
674
#!/usr/bin/python # # Copyright 2020 DeepMind Technologies Limited # # 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 a...
4,600
1,465
from tkinter import * ventana = Tk() ventana.geometry("500x500") ventana.title('PythonGuides') img = PhotoImage(file='./logo.png') img = img.subsample(3, 3) Label( ventana, image=img ).pack(fill="both") ventana.mainloop()
225
91
#coding:utf8 #author: yqq #date: 2020/12/15 ไธ‹ๅˆ5:38 #descriptions: from decimal import Decimal, getcontext # getcontext() def htdf_to_satoshi(amount_htdf: [float, int, str]) -> int: return int(Decimal(str(amount_htdf)) * (10 ** 8)) if __name__ == '__main__': assert htdf_to_satoshi(139623.71827296) == 1396...
476
270
from dataclasses import asdict from hanzi_font_deconstructor.common.generate_training_data import ( STROKE_VIEW_BOX, get_training_input_svg_and_masks, ) from os import path, makedirs from pathlib import Path import shutil import argparse PROJECT_ROOT = Path(__file__).parents[2] DEST_FOLDER = PROJECT_ROOT / "da...
1,213
442
from generic_dataset.data_pipeline import DataPipeline from generic_dataset.generic_sample import synchronize_on_fields from generic_dataset.sample_generator import SampleGenerator import numpy as np import generic_dataset.utilities.save_load_methods as slm pipeline_rgb_to_gbr = DataPipeline().add_operation(lambda dat...
1,321
445
from setuptools import setup setup(name='neural_networks_tfw1', version='0.1', description='Implementing Neural Networks with Tensorflow', packages=['neural_networks_tfw1'], author='Dilay Fidan Ercelik', author_email='dilay.ercelik@gmail.com', zip_safe=False)
297
102
# coding=utf8 import re import json.decoder from collections import namedtuple from json.decoder import JSONDecoder from json.scanner import py_make_scanner from json.decoder import py_scanstring class JSONDecodeError(object): def __init__(self, parser, message): self.message = message self.pars...
4,581
1,650
#!/usr/bin/python ##################################################################### # Name : capaSystem.py # Description : Read system data and update db for web display # Environment : Tested under Raspberry Pi Rasbian Jessie Summer 17 # Author : Steve Osteen sosteen@gmail.com #####...
1,963
611
from django.template.loader import render_to_string from django.core.mail import send_mail from django.conf import settings from django.contrib.auth import get_user_model from django.db.models import Q from wagtail.wagtailcore.models import PageRevision, GroupPagePermission from wagtail.wagtailusers.models import User...
3,770
1,118
#Author: Shu Shi #emaiL: shushi@research.att.com from toscalib.tosca_workbook import ToscaWorkBook from toscalib.tosca_builder import ToscaBuilder import getopt, sys, json, logging def usage(): print('OPTIONS:') print('\t-h|--help: print this help message') print('\t-i|--input: The home folder where all ...
3,506
1,125
from django.test import TestCase from rest_framework.test import APIClient class TestShortHand(TestCase): def setUp(self) -> None: self.client = APIClient() def test_get(self): response_json = self.client.post('/api/v1/shorthand/', {'label': 'foo', 'url': 'http://bar.com'}).json() res...
2,872
961
import pandas as pd import dateutil from lusidtools.lpt import lpt from lusidtools.lpt import lse from lusidtools.lpt import stdargs from .either import Either import re import urllib.parse rexp = re.compile(r".*page=([^=']{10,}).*") TOOLNAME = "scopes" TOOLTIP = "List scopes" def parse(extend=None, args=None): ...
1,937
628
๏ปฟ#!/usr/bin/python # -*- coding: utf-8 -*- """ QQBot -- A conversation robot base on Tencent's SmartQQ Website -- https://github.com/pandolia/qqbot/ Author -- pandolia@yeah.net """ import sys, os p = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if p not in sys.path: sys.path.insert(0, p) import...
8,457
2,823
from redgrease import GearsBuilder gb = GearsBuilder() gb.run()
65
23