text stringlengths 2 999k |
|---|
#!/usr/bin/env python3
# Responder.py
# ~~~~~~~~~~~~
# This file is tasked with compiling a response given a list
# of call items (i.e. a list of results of DataPulls.getInfo)
def xstr(x):
if x is None:
return ''
return str(x)
def xget(source, prop):
if type(source) == dict:
if prop in so... |
# 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
# distributed under the Li... |
from __future__ import unicode_literals
import warnings
from django.db import models
from cms.models import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from filer.fields.folder import FilerFolderField
from .conf import settings
from cmsplugin_filer_utils import FilerPluginManager
class FilerFol... |
"""
Copyright (c) 2022 Intel Corporation
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 writin... |
# -*- coding: utf-8 -*-
""" ymir.schema.data
"""
from voluptuous import Required, Optional
from ymir.schema import validators
AWS_DATA = {
Required("username"): unicode,
Required("pem"): unicode,
Optional("aws_region"): unicode,
Optional("s3_buckets", default=[]): validators.list_of_strings,
Opti... |
"""
test_sgc_input_phaselocking.py
Test phase locking from an input sgc to a target cell type. Runs simulations
with AN input, and plots the results, including PSTH and phase histogram.
usage: test_sgc_input_phaselocking.py [-h]
[-c {bushy,tstellate,octopus,dstellate}]
... |
# 성적 처리 프로그램 함수로 작성
# 총점 - getTotal()
# 평균 - getAverage()
# 학점 - getGrade()
print('-- 성적 처리 프로그램 v2 --')
name = input('이름을 입력하세요')
kor = int(input('국어점수를 입력하세요'))
eng = int(input('영어점수를 입력하세요'))
mat = int(input('수학점수를 입력하세요'))
# 함수만 선언하고 내용작성을 나중에 하고 싶을때 - pass 명령어 사용 (pass - dummy code)
def getTotal():
tot = kor ... |
"""
This module acts as a replacement to some of Python's `shutil` module where the blocking operations are done in a
gevent-friendly manner.
"""
from __future__ import absolute_import
import shutil as _shutil
from .deferred import create_threadpool_executed_func
CONSTS = ['Error']
DEFERRED_FUNCTIONS = [
'copyfi... |
from ... utils.utils import uppercase, strip_non_alphanumeric, convert_brew_number, lowercase
from .. regx import regex_inv
class LastBrew(str):
@classmethod
def __get_validators__(cls):
yield cls.validate
@classmethod
def __modify_schema__(cls, field_schema):
field_schema.update(
... |
from pkgutil import extend_path
__path__= extend_path(__path__, __name__)
__all__=["msg","codec"]
|
import requests
import ntpath
import os
from typing import List, Dict, Union
from ytmusicapi.helpers import *
from ytmusicapi.parsers.library import *
from ytmusicapi.parsers.albums import *
from ytmusicapi.parsers.uploads import *
class UploadsMixin:
def get_library_upload_songs(self, limit: int = 25, order: str... |
################################################################################
#
# Copyright 2021-2022 Rocco Matano
#
# 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, in... |
import cv2
import time
from modules import handtrackingmodule as htm
import math
import urllib
def main():
cam_width, cam_height = 640, 480
cap = cv2.VideoCapture("http://192.168.1.68:81/stream")
cap.set(3, cam_width)
cap.set(4, cam_height)
tracker = htm.HandTracker()
pr_time = 0
cur_tim... |
from flask import render_template, current_app
from flask_babel import _
from app.email import send_email
def send_password_reset_email(user):
token = user.get_reset_password_token()
send_email(_('[Naked Wrestling Club] Reset Your Password'),
sender=current_app.config['ADMINS'][0],
... |
from sklearn.model_selection import train_test_split
data_folder="data_new/"
train_ratio=0.8
test_ratio=0.1
validation_ratio=0.1
titles = []
titles_file = open(data_folder+"titles_all.txt", "r")
titles = titles_file.read().splitlines()
stanzas = []
stanzas_file = open(data_folder+"stanzas_all.txt", "r")
stanzas = s... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
from astropy.tests.helper import pytest
from astropy.coordinates import SkyCoord, Angle
from regions import CircleSkyRegion
from ...datasets import gammapy_extra
from ...data import ObservationList
from ...image import SkyMask
from ...utils.testi... |
# coding: utf-8
"""
Lightly API
Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501
OpenAPI spec version: 1.0.0
Contact: support@lightly... |
import torch as t
from .quantizer import Quantizer
def grad_scale(x, scale):
y = x
y_grad = x * scale
return (y - y_grad).detach() + y_grad
def round_pass(x):
y = x.round()
y_grad = x
return (y - y_grad).detach() + y_grad
class LsqQuan(Quantizer):
def __init__(self, bit, all_positive=... |
import pytest
import tensorflow as tf
from libreco.algorithms import YouTubeRanking
from tests.utils_data import prepare_feat_data
from tests.utils_reco import recommend_in_former_consumed
@pytest.mark.parametrize("task", ["rating", "ranking"])
@pytest.mark.parametrize(
"lr_decay, reg, num_neg, use_bn, dropout_r... |
### decision trees and tree search
### first version is just a binary tree
class binaryTree(object):
def __init__(self, value):
self.value = value
self.leftBranch = None
self.rightBranch = None
self.parent = None
def setLeftBranch(self, node):
self.leftBranch = node
... |
from datetime import date, datetime, time, timedelta, tzinfo
import operator
from typing import Optional
import warnings
import numpy as np
from pandas._libs import NaT, Period, Timestamp, index as libindex, lib, tslib
from pandas._libs.tslibs import Resolution, parsing, timezones, to_offset
from pandas._libs.tslibs.... |
# Copyright 2018 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import unittest
import sys
import os
import time
import threading
import inspect
import pymsgbox
# Note: Yes, PyAutoGUI does have PyMsgBox itself as a dependency, but we won't be using that part of PyAutoGUI for this testing.
import pyautogui # PyAutoGUI simulates key presses on the message boxes.
pyautogui.PAUSE = 0... |
# Identify location
import socket
location = socket.gethostname()
if location == 'Monolith':
dropbox = 'E:\\Users\\Chris\\Dropbox\\'
if location == 'Hobbitslayer':
dropbox = 'C:\\Users\\spx7cjc\\Dropbox\\'
if location == 'saruman':
dropbox = '/home/herdata/spx7cjc/Dropbox/'
# Import smorgasbord
import os
i... |
from ._bounding_box import *
from ._user_IDs import *
from ._user_points import *
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# import models/tasks to register them
from . import dummy_dataset, dummy_lm, dummy_masked_lm, dummy_model, dummy_mt # noqa
|
# coding=utf-8
# Copyright 2018 The Tensor2Tensor 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... |
#!/usr/bin/python3
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# See LICENSE for license information.
import argparse
import collections
import datetime
import re
import sys
cloud_init_pattern = re.compile(r'(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d,\d\d\d) ')
iso8601_pattern = re.compile(r'(\d\d\d\d/\d... |
import os
import io
import sys
from setuptools import setup, find_packages
from pkg_resources import parse_version, get_distribution, DistributionNotFound
import subprocess
import distutils.command.clean
import distutils.spawn
import glob
import shutil
import torch
from torch.utils.cpp_extension import BuildExtension,... |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="PyBingTiles",
version="0.0.1",
install_requires=[
"pandas",
"geopandas",
"numpy",
"shapely",
"contextily"
],
author="Shoichi Yip",... |
# http://www.ster.kuleuven.be/~pieterd/python/html/plotting/mayavi_example.html
import numpy as np
from numpy import sin,cos,pi,sqrt # makes the code more readable
from scipy.optimize import newton
import sys
#mayavi 3d
import pylab as plt
from mayavi import mlab # or from enthought.mayavi import mlab
#matplotlib... |
#!/usr/bin/env python3
import sys
import subprocess
import configparser
import os
def parse_config():
config = configparser.ConfigParser()
config.read('configs.ini')
return config
def main():
print("Starting experiments")
config = parse_config()
os.chdir('CIFAR10')
mode = int(... |
#!/usr/bin/env python
import click
import boto3
import math
import time
from datetime import datetime, timezone
def send_statistics_aggregate(stats, time_window = 3600, max_bounces_rate = 0.04, max_complaints_rate = 0.0007):
now = datetime.now(timezone.utc)
total = {
'DeliveryAttempts': 0,
'Bo... |
#!/usr/bin/python
"""
(C) Copyright 2020-2021 Intel Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent
"""
import time
import random
import threading
import copy
from osa_utils import OSAUtils
from daos_utils import DaosCommand
from dmg_utils import check_system_query_status
from test_utils_pool import Test... |
#
# mDKL
#
# Copyright (c) Siemens AG, 2021
# Authors:
# Zhiliang Wu <zhiliang.wu@siemens.com>
# License-Identifier: MIT
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from yellowbrick.features import JointPlotVisualizer
from yellowbrick.regressor import ResidualsPlot, PredictionError
from skl... |
from setuptools import setup, find_packages
setup(name='reqinstall',
version='0.0.2',
description='',
author='Quali',
license='MIT License',
classifiers=['Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Deskt... |
'''
Copyright <2021> <Thomas Chapman>
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DA... |
# -*- coding: utf-8 -*-
#
# Copyright 2018 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compli... |
import paho.mqtt.publish as pub
import logging
logger = logging.getLogger("mqtt_sender")
def publish(payloads: list, client_id: str, topic: str, hostname: str, port: int, qos: int = 0, retain: bool = False):
# msg = {'topic':"<topic>", 'payload':"<payload>", 'qos':<qos>, 'retain':<retain>}
messages = [{'topi... |
import math
import numpy as np
import datetime as dt
from typing import Dict, Optional
from voltoolbox import BusinessTimeMeasure, longest_increasing_subsequence, bs_implied_volatility
from voltoolbox.fit.option_quotes import OptionSnapshot, OptionQuoteSlice, QuoteSlice
from voltoolbox.fit.fit_utils import act365_time... |
# -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
class AkscanSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy a... |
# encoding: utf-8
from bs4 import BeautifulSoup
import mock
from ckan.lib.helpers import url_for
import pytest
import six
from six.moves.urllib.parse import urlparse
import ckan.model as model
import ckan.model.activity as activity_model
import ckan.plugins as p
import ckan.lib.dictization as dictization
from ckan.lo... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 21 15:37:11 2016
@author: Doppler
"""
from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier
n_features=200
x,y=datasets.make_classification(750,n_features,n_informative=5)
import numpy as np
training = np.random.choice([True,False],p=[.75,.25],s... |
# coding: utf-8
# In[1]:
# %load paste_video_classification.py
# 这个代码每个epoch都跑一遍训练集和验证集
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
from torch.autograd import Variable
import torchvision
from torchvision import datasets, models, transforms
import time
import ... |
# Generated by Django 3.1.5 on 2021-02-12 16:08
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("blog", "0001_initial"),
]
operations = [
migrations.RenameModel(
old_name="Blog",
new_name="MyBlog",
),
]
|
# BSD 3-Clause License; see https://github.com/scikit-hep/uproot4/blob/main/LICENSE
from __future__ import absolute_import
import os
import sys
import numpy
import pytest
import uproot
def tobytes(x):
if hasattr(x, "tobytes"):
return x.tobytes()
else:
return x.tostring()
def test_file(tm... |
from MCSampler import MCSampler
from Sample import Samples, Sample, SampleType, DistributionType
from Sampler import Sampler
|
import logging
log11 = 1
logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s:[%(threadName)-12.12s]:[%(levelname)-5.5s]: %(message)s")
fh = logging.FileHandler('log.log')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logger.addHandler(fh)
ch = logging.Stream... |
from OCC.Core.Bnd import Bnd_Box
class BoundaryBox:
def __init__(self, xl=None, xh=None, yl=None, yh=None, zl=None, zh=None):
if isinstance(xl, Bnd_Box):
self.assign_Bnd_Box(xl)
return
if (xl is None):
self.assign_coords(0, 0, 0, 0, 0, 0)
self.inite... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from setuptools import (
setup,
find_packages,
)
DIR = os.path.dirname(os.path.abspath(__file__))
readme = open(os.path.join(DIR, 'README.md')).read()
install_requires = [
"cytoolz>=0.8.2",
"ethereum-abi-utils>=0.4.3",
"ethereu... |
import os
import re
import logging
from collections import defaultdict
from remus.bio.bed.beds_loading import BedLoader
from remus.bio.bed.beds_operations import BedOperations
def convert_genome_build(genome, hg19_expected="hg19", hg38_expected="GRCh38"):
if re.match("(hg37|hg19|b37)", genome, re.IGNORECASE):
... |
# Reverse first K elements
# Given a queue and an integer k, reverse first k elements. Return the updated queue.
# Do the problem in O(n) complexity.
from sys import setrecursionlimit
import queue
def reverseFirstK(q, k):
# Implement Your Code Here
setrecursionlimit(11000)
n = int(input())
li = [int(ele) fo... |
import sys
# import source files
sys.path.append('../../../src/python/')
from xrt_binding import *
sys.path.append('../')
from utils_binding import *
XSIMPLE_CONTROL_ADDR_AP_CTRL = 0x00
XSIMPLE_CONTROL_ADDR_GIE = 0x04
XSIMPLE_CONTROL_ADDR_IER = 0x08
XSIMPLE_CONTROL_ADDR_ISR = 0x0c
XSIMPLE_CONTROL_ADDR_GROUP_ID_X_DATA ... |
import numpy as np
import matplotlib.pyplot as plt
import abel
import bz2
transforms = [
("basex", abel.basex.basex_transform, '#880000'),
("direct", abel.direct.direct_transform, '#EE0000'),
("hansenlaw", abel.hansenlaw.hansenlaw_transform, '#CCAA00'),
("onio... |
# Checks methods for getting 3d world locations from depth map and from point cloud.
import copy
import numpy as np
import pptk
import time
import carla
import pylot.utils
from pylot.simulation.carla_utils import get_world
import pylot.simulation.messages
import pylot.simulation.utils
from pylot.simulation.utils imp... |
#!/usr/bin/python
# -- Content-Encoding: utf-8 --
"""
Provides functions for reading Java objects serialized by ObjectOutputStream.
This form of object representation is a standard data interchange format in
Java world.
javaobj module exposes an API familiar to users of the standard library
marshal, pickle and json mo... |
# Update the Settings File
import json
import requests
import urllib
def initialize_settings(api_key):
settings={'thermostats':{},'tokens':{'api_key':api_key}}
pretty_settings = json.dumps(settings,indent=4)
settingsfile = open('settings.json', 'w')
settingsfile.write(pretty_settings)
settingsfile.... |
# Copyright 2021 The NPLinker 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
#
# 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
# "License"); you may not... |
import sys
from io import BytesIO
import telegram
from flask import Flask, request, send_file
from fsm import TocMachine
API_TOKEN = '480513885:AAEwQboNf9fJUuE13pBQLl4URAj5F3QCT00'
WEBHOOK_URL = 'https://21684a07.ngrok.io/hook'
app = Flask(__name__)
bot = telegram.Bot(token=API_TOKEN)
machine = TocMachine(
sta... |
# -*- coding: utf-8 -*-
import codecs
import datetime
import glob
import json
import os
import re
import shutil
import subprocess
import base64
CLIENT_VERSION = '1.0.1.1'
NAME = 'spoter.crewExtended'
ADD_LICENSE = True
class Build(object):
OUT_PATH = '.out'
PYC_PATH = os.path.join(OUT_PATH, 'res', 'scripts',... |
# -----------------------------------------------------------------------------
# Functions for parsing args
# -----------------------------------------------------------------------------
import yaml
import os
from ast import literal_eval
import copy
class CfgNode(dict):
"""
CfgNode represents an internal no... |
# Create a list and save it to a variable
hobbies = ["Rock Climbing", "Bug Collecting", "Cooking", "Knitting", "Writing"]
print(hobbies)
# Select the first, second and fifth values from the list
print(hobbies[0])
print(hobbies[1])
print(hobbies[4])
# len() tells us how long the list is (5)
print(len(hobbies))
# Use ... |
# Generated by Django 3.2 on 2021-12-03 11:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tag', '0002_auto_20210922_1104'),
('task', '0002_task_annotated_slide'),
]
operations = [
migrations.AddField(
model_name=... |
# 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
# distributed under t... |
import sys
sys.path.append("..")
from ..Modifiers import WithName,DecoratedBy,WithBody,Append,WithArg
from CodeGenerationCore import Command
from .utils import CommandOn
from ast import FunctionDef
@CommandOn(FunctionDef)
class CloneMethodCommand(Command,WithName.WithName,DecoratedBy.DecoratedBy,WithBody.WithBody,App... |
# -*- coding: utf-8 -*-
"""
Defines unit tests for :mod:`colour.quality.ssi` module.
"""
from __future__ import division, unicode_literals
import unittest
from colour.quality import spectral_similarity_index
from colour.colorimetry import SDS_ILLUMINANTS, SpectralDistribution
__author__ = 'Colour Developers'
__copy... |
# @app.route('/volume', methods=['OPTIONS', 'POST'])
# # Split by year
# for year in range(y["startyear"], y["endyear"] + 1):
# pipeline = [
# {
# "$match": {
# "daypost": {"$gte": datetime(year), 1, 1), "$lte": datetime(year), 12, 31)},
# "location": {
# ... |
#!/usr/bin/env python
# Copyright (C) 2012-2013, The CyanogenMod Project
# Copyright (C) 2012-2015, SlimRoms Project
# Copyright (C) 2016-2017, AOSiP
# Copyright (C) 2021 Stellar OS
# Copyright (C) 2021 Project Materium
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file exce... |
"""
字节串使用示例
所有字符串都能转化为字节串,但不是所有字节串都能转化为字符串。
"""
# 定义一个字节串变量
b = b"hello world" # 用于ASCii
print(type(b))
# 定义一个非ASCII字节串变量
b1 = "你好".encode()
print(b1)
x1 = b'\xe4\xbd\xa0\xe5\xa5\xbd'.decode() # 等同于 x1 = b1.decode()
print(x1)
file = open("file.txt")
file_object = file.read()
file_list = file_object.split("\n... |
import os
import glob
import shutil
from azureml.core import Workspace, Experiment
from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException
from azureml.core import Environment
from azureml.core.conda_dependencies import CondaDependencies
from azureml.cor... |
import pandas
import webbrowser
import os
# Read the dataset into a data table using Pandas
data_table = pandas.read_csv("movies.csv", index_col="movie_id")
# Create a web page view of the data for easy viewing
html = data_table.to_html()
# Save the html to a temporary file
with open("movie_list.html", "w") as f:
... |
import math
import time
from grpc import Call
import torch
from colossalai.utils import MultiTimer
from colossalai.core import global_context as gpc
from colossalai.context import ParallelMode, Config
from typing import List, Dict, Tuple, Callable
def get_time_stamp() -> int:
"""
Return the time stamp for pr... |
r"""
Number fields
"""
#*****************************************************************************
# Copyright (C) 2005 David Kohel <kohel@maths.usyd.edu>
# William Stein <wstein@math.ucsd.edu>
# 2008 Teresa Gomez-Diaz (CNRS) <Teresa.Gomez-Diaz@univ-mlv.fr>
# ... |
"""
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... |
import pytest
from briefcase.commands.base import BaseCommand
from briefcase.config import AppConfig, BaseConfig
class DummyCommand(BaseCommand):
"""
A dummy command to test the BaseCommand interface.
"""
command = 'dummy',
platform = 'tester'
output_format = 'dumdum'
description = 'Dummy... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018-2021, earthobservations developers.
# Distributed under the MIT License. See LICENSE for more info.
import h5py
import pytest
from wetterdienst.provider.dwd.radar import (
DwdRadarDataFormat,
DwdRadarDataSubset,
DwdRadarDate,
DwdRadarParameter,
DwdRadarP... |
# Define count_entries()
def countr_entries(csv_file, c_size, column_name):
"""Return a dictionary with counts of
occurrences as value for each key."""
# Initialize an empty dictionary: counts_dict
counts_dict = {}
# Iterate over the file chunk by chunk
for chunk in pd.read_csv(csv_file, c... |
COPY_GOOGLE_DOC_KEY = '0AiIfOsKv5mKldGF3Um1jekxRMUNra01MVldsU193QUE'
DEPLOY_SLUG = 'doors'
NUM_SLIDES_AFTER_CONTENT = 2 |
'''
>>> Welcome to Hangman!
_ _ _ _ _ _ _ _ _
>>> Guess your letter: S
Incorrect!
>>> Guess your letter: E
E _ _ _ _ _ _ _ E
'''
'''
Psuedocode approach with assignment to objects:
Welcome message [Player]
Choose a random word [Board]
Display the word with _ symbols where no letters are known [Board]
Display how many... |
class AutoCompleteSource(Enum,IComparable,IFormattable,IConvertible):
"""
Specifies the source for System.Windows.Forms.ComboBox and System.Windows.Forms.TextBox automatic completion functionality.
enum AutoCompleteSource,values: AllSystemSources (7),AllUrl (6),CustomSource (64),FileSystem (1),FileSystemDire... |
import torch
import torch.nn as nn
class ConvB(nn.Conv2d):
@staticmethod
def from_conv(module: nn.Conv2d, bias):
module.__class__ = ConvB
module.register_parameter('bf', torch.nn.Parameter(bias))
return module
def forward(self, x):
x = super().forward(x)
return... |
class Solution:
def mctFromLeafValues(self, A):
res, n = 0, len(A)
stack = [float('inf')]
for a in A:
while stack[-1] <= a:
mid = stack.pop()
res += mid * min(stack[-1], a)
stack.append(a)
while len(stack) > 2:
res +... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('requirements.txt') as f:
install_requires = f.read().strip().split('\n')
# get version from __version__ variable in midtrans_payment/__init__.py
from midtrans_payment import __version__ as version
setup(
name='midtrans_payment',
versio... |
#!/usr/bin/env python
#
# ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University of Chicago
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://ge... |
#!/usr/bin/env python3
import argparse
import json
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--output", required=True)
parser.add_argument("ref_nodes")
parser.add_argument("snarls")
args = parser.parse_args()
ref = {}
with open(args.ref_nodes) as infile:
for line in infile:
cols = line... |
import argparse,pydub.silence as sil,os,re
from pydub import AudioSegment
parser = argparse.ArgumentParser(
description='This function gets the silence boundaries given an input audio file in the foll. format fileset,book,chapter,db,sId,sBegin,sEnd')
required_args = parser.add_argument_group('required argument... |
import os
# 设置其他域名,也许需要代理才可以访问, 比如:cordcloud.org
CC_HOST = ""
# 看情况是否开启代理
PROXIES = {
# "http": "http://127.0.0.1:7890",
# "https": "http://127.0.0.1:7890",
}
# 登录CordCloud的帐号密码
LOGIN_FORM = {
"email": os.getenv("CC_EMAIL", ""),
"passwd": os.getenv("CC_PASSWD", ""),
"code": "",
}
# server酱配置(非必填... |
from . import Plugin
class CatchallPlugin(Plugin):
"""
Turns metrics that aren't matched by any other plugin in something a bit more useful (than not having them at all)
Another way to look at it is.. plugin:catchall is the list of targets you can better organize ;)
Note that the assigned tags (i.e. s... |
'''
* Copyright (c) 2021, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
'''
import argparse
import os
import ruamel_yaml as yaml
import numpy as np
import random
impo... |
#!/usr/bin/env python
"""
Written by Reubenur Rahman
Github: https://github.com/rreubenur/
This code is released under the terms of the Apache 2
http://www.apache.org/licenses/LICENSE-2.0.html
Example script to upload a file from host to guest
"""
from __future__ import with_statement
import atexit
import requests
f... |
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import itertools
from dataclasses import dataclass
from pants.backend.experimental.python.lockfile import (
PythonLockfileRequest,
PythonToolLockfileSentinel,
)
from pants.backend... |
# coding: utf-8
"""
OpenAPI
tinkoff.ru/invest OpenAPI. # noqa: E501
The version of the OpenAPI document: 1.0.0
Contact: n.v.melnikov@tinkoff.ru
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class CandleResolution(object):
"""NOTE: This... |
#!/usr/bin/python3
import os
import os.path
import re
import argparse
def cmdline():
parser = argparse.ArgumentParser(description='Show USV values of characters in a file')
parser.add_argument('--count', help='count characters instead of just listing them',
action='store_true')
pa... |
"""
Off Multipage Cheatsheet
https://github.com/daniellewisDL/streamlit-cheat-sheet
@daniellewisDL : https://github.com/daniellewisDL
"""
import streamlit as st
from pathlib import Path
import base64
from modules.toc import *
# Initial page config
st.set_page_config(
page_title='Code Compendium Intro Page',
... |
import math
def point(tick, range, radius): # identical to plotterGui's
angle = tick * (360.0 / range) # but prints points and angle
radiansPerDegree = math.pi / 180
pointX = int( round( radius * math.sin(angle * radiansPerDegree) ))
pointY = int( round( radius * math.cos(angle ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 3 13:46:06 2021
@author: Sebastian
"""
import sys
sys.path.append('..\\src')
import unittest
import common.globalcontainer as glob
from dataobjects.stock import Stock
import engines.scaffold
import engines.analysis
import pandas as pd
import datetime
import logging
i... |
import os
import csv
import datetime
import time
import pickle
import gib_detect_train
model_data = pickle.load(open('gib_model.pki', 'rb'))
csvFile = open("D:\\69M_reddit_accounts.csv")
vFile = open("D:\\AllSus.csv","w")
csvReader = csv.reader(csvFile)
interestingUsers = []
boringUsers = []
totalusers = {}
ratioUse... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
Run a python script, adding extra directories to the python path.
"""
def main(args):
def usage():
pri... |
#!/usr/bin/env python3
#python3 analyze_video.py {path/video_filename.mp4} {ID Folder Name}
# initalize
import sys
import argparse
import tensorflow as tf
import cv2
import dlib
import numpy as np
import detect_and_align
import os
from model import OpenNsfwModel
from image_utils import create_yahoo_image_loader
from ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.