text stringlengths 2 999k |
|---|
import secrets
from datetime import timedelta
from pathlib import Path
from secrets import token_urlsafe
from typing import List, Optional
from atoolbox import BaseSettings
from pydantic import EmailStr, constr
SRC_DIR = Path(__file__).parent
class Settings(BaseSettings):
pg_dsn = 'postgres://postgres@localhost... |
import os,re
from waflib import Task,Errors,Node,TaskGen,Configure,Node,Logs,Context
from brick_general import ChattyBrickTask
def configure(conf):
"""This function gets called by waf upon loading of this module in a configure method"""
conf.load('brick_general')
conf.find_program('calibre',var='CALIBRE_DRC')
co... |
import rlkit.misc.hyperparameter as hyp
from experiments.murtaza.multiworld.skew_fit.reacher.generate_uniform_dataset import generate_uniform_dataset_reacher
from multiworld.envs.mujoco.cameras import sawyer_init_camera_zoomed_in, sawyer_pusher_camera_upright_v2
from rlkit.launchers.launcher_util import run_experiment
... |
#!/usr/bin/env python3
# Need to run this from the directory containing this script and make_rules.py
# Run this script, then check output in the generated file, then run make_rules.py
import argparse
import json
import requests
import sys
import os
import boto3
from slugify import slugify
import common.common_lib ... |
import os
import sys
import time
import optparse
sys.path.insert(0, "../../")
from cbfeeds import CbReport
from cbfeeds import CbFeed
from cbfeeds import CbFeedInfo
from stix.core import STIXPackage
from stix.utils.parser import EntityParser, UnsupportedVersionError
from cybox.bindings.file_object import FileObjectTy... |
# Generated by Django 3.1a1 on 2020-07-07 07:56
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
from flask import Blueprint
auth = Blueprint('auth',__name__)
from . import views,form
|
# testing/engines.py
# Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
import collections
import re
import typing
from typing import Any
from typing im... |
# -------------------------------------------------------------------------------------
# A Bidirectional Focal Atention Network implementation based on
# https://arxiv.org/abs/1909.11416.
# "Focus Your Atention: A Bidirectional Focal Atention Network for Image-Text Matching"
# Chunxiao Liu, Zhendong Mao, An-An Liu, Ti... |
# -*- coding: utf-8 -*-
# Copyright 2020 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... |
#!/usr/bin/env python3
import argparse
from migen import *
from migen.genlib.resetsync import AsyncResetSynchronizer
from litex.soc.integration.soc_core import *
from litex.soc.integration.builder import *
from litex_boards.platforms import arty
from ring import *
# CRG --------------------------------------------... |
import uuid
from django.contrib.contenttypes.models import ContentType
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from wagtail.core.models import Page
from .models import IDMapping
from .serializers import get_model_serializer
def pages_for_export(request, root_page_id):
... |
#!/usr/bin/env python3
# This file is a part of toml++ and is subject to the the terms of the MIT license.
# Copyright (c) Mark Gillard <mark.gillard@outlook.com.au>
# See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
# SPDX-License-Identifier: MIT
import sys
import utils
import... |
import numpy as np
class PeakExtractor(object):
"""Extract peaks from xy-datasets.
:param x: x-values
:param y: y-values
"""
def __init__(self, x, y):
self.x = x
self.y = y
def _locate_peak(self, xfit, yfit):
"""Locate peak by fitting a parabola."""
coeff = n... |
import os
import time
from simple_saga_task_manager.tests.saga_test_case import SagaTestCase
from simple_saga_task_manager.models import Task
from simple_saga_task_manager.saga_interface import SAGATaskInterface
class SagaInterfaceEndToEndLocalTests(SagaTestCase):
def test_end_to_end_local(self):
# Creat... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use("seaborn-whitegird")
def scatter_matrix(df, cagegorical = None):
"""
# 散点图矩阵
"""
if cagegorical:
sns.pairplot(df, hue = cagegorical, size = 2.5)
else:
sns.pairplot(df, size =... |
ignoretagarr = []
for line in urlopen(IGNORETAGFILE):
currline = line.decode('utf-8') #utf-8 or iso8859-1 or whatever the page encoding scheme is
currline = currline.replace('\n','')
ignoretagarr.append(currline.replace('%20%',' '))
blockedaccs = []
for line in urlopen(BLOCKUSERFILE):
currline = line.... |
import cv2
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
import json
import time
import glob
from io import StringIO
from PIL import Image
import matplotlib.pyplot as plt
from object_detection.utils import visualization_utils as vis_ut... |
from unittest import TestCase
from neat.streaming import Stream
class TestStreaming(TestCase):
def test_streaming_empty(self):
s = Stream(['a'])
c = s.collect()
s.push([dict(a=1)])
self.assertEqual([dict(a=1)], c.fetch())
s.push([dict(a=2)])
s.push([dict(a=3)])
... |
# Imports from 3rd party libraries
# Imports from 3rd party libraries
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
# Imports from this application
from app import app, server
from pages import inde... |
#!/usr/bin/python3
from unittest.mock import patch
import unittest
import manager
import job
class TestManager(unittest.TestCase):
def setUp(self):
self.sched_cfg = {
'tmpdir_stagger_phase_major': 3,
'tmpdir_stagger_phase_minor': 0,
'tmpdir_max_jobs': 3 }
... |
### refer Zhizheng and Simon's ICASSP'16 paper for more details
### http://www.zhizheng.org/papers/icassp2016_lstm.pdf
import numpy as np
import theano
import theano.tensor as T
from theano import config
from theano.tensor.shared_randomstreams import RandomStreams
class VanillaRNN(object):
""" This class impleme... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... |
# coding: utf-8
"""
a proof of concept implementation of SQLite FTS tokenizers in Python
"""
import sys
from cffi import FFI # type: ignore
SQLITE_OK = 0
SQLITE_DONE = 101
ffi = FFI()
if sys.platform == "win32":
import sqlite3 # noqa
dll = ffi.dlopen("sqlite3.dll")
else:
from ctypes.util import find_... |
import os
import logging
import claripy
from cle import MetaELF
from cle.address_translator import AT
from archinfo import ArchX86, ArchAMD64, ArchARM, ArchAArch64, ArchMIPS32, ArchMIPS64, ArchPPC32, ArchPPC64
from ..tablespecs import StringTableSpec
from ..procedures import SIM_PROCEDURES as P, SIM_LIBRARIES as L
fr... |
import os
from dotenv import load_dotenv
basedir = os.path.abspath(os.path.dirname(__file__))
load_dotenv(os.path.join(basedir, '.env'))
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', '').replace(
'pos... |
import copy
import typing
from pathlib import Path
from typing import Dict
from deliverable_model.processor_base import ProcessorBase
from deliverable_model.request import Request
from deliverable_model.response import Response
if typing.TYPE_CHECKING:
from nlp_utils.preprocess.lookup_table import LookupTable as ... |
import cv2
import numpy as np
import PIL.Image as Image
from carla.image_converter import labels_to_cityscapes_palette
from erdos.op import Op
from erdos.utils import setup_logging
class SegmentedVideoOperator(Op):
def __init__(self, name, log_file_name=None):
super(SegmentedVideoOperator, self).__init_... |
from direct.fsm.State import State
from direct.fsm.ClassicFSM import ClassicFSM
from direct.showbase.DirectObject import DirectObject
from panda3d.core import PandaNode, PGButton, NodePath, MouseWatcherRegion
class Clickable(PandaNode, DirectObject):
def __init__(self, name):
PandaNode.__init__(self, name... |
class Solution:
def reverse(self, x: int) -> int:
MIN, MAX = -(2 ** 31), (2 ** 31) - 1
if x == 0:
return 0
negative = False
if x < 0:
negative = True
x *= -1
new = 0
while x:
new = (new * 10) + (x % 10)... |
from block import *
from shard import *
from logging import ERROR, WARN, INFO, DEBUG
import time
class categorize_shard(Shard):
@classmethod
def initial_configs(cls, config):
return [config for i in range(config["nodes"])]
@classmethod
def node_type(self):
return {"name": "Categorize", "input_port"... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import openbabel
from ribbonbuilder import translate as t
import pytest
@pytest.fixture()
def mol_and_params():
mol = openbabel.OBMol()
distance = 3.0
border_distance = 1.0
carbon = 6
hydrogen = 1
# Add the 4 "bulk" atoms first
... |
from irctest import cases
class ListTestCase(cases.BaseServerTestCase):
@cases.mark_specifications("RFC1459", "RFC2812")
def testListEmpty(self):
"""<https://tools.ietf.org/html/rfc1459#section-4.2.6>
<https://tools.ietf.org/html/rfc2812#section-3.2.6>
"""
self.connectClient("f... |
from distributed.comm.addressing import (
get_address_host,
get_address_host_port,
get_local_address_for,
normalize_address,
parse_address,
parse_host_port,
resolve_address,
unparse_address,
unparse_host_port,
)
from distributed.comm.core import Comm, CommClosedError, connect, listen... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
import os
__author__ = 'Chia-Jung, Yang'
__email__ = 'jeroyang@gmail.com'
__version__ = '0.1.0' |
from .VAENAR import VAENAR
from .optimizer import ScheduledOptim |
from nextcord.ext import commands
import os
def is_owner():
async def predicate(context) -> bool:
return os.getenv("OWNER_IDS")
return commands.check(predicate) |
import io
from typing import List, Set, Tuple, Optional, Any
from clvm import SExp
from clvm import run_program as default_run_program
from clvm.casts import int_from_bytes
from clvm.EvalError import EvalError
from clvm.operators import OPERATOR_LOOKUP
from clvm.serialize import sexp_from_stream, sexp_to_stream
from c... |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import os, sys
sys.path.append(os.path.dirname(__file__))
from Editor_TestClass import BaseClass
class Editor_C... |
# -*- coding: utf-8 -*-
import os
import appdirs
import errno
import logging
# merge two track lists based on ID
def merge_track_lists(tracks, new_tracks):
track_ids = [t.get('id') for t in tracks]
for t in new_tracks:
if t.get('id') not in track_ids:
tracks.append(t)
return tracks
# ... |
import os
import csv
import cv2
import argparse
def main(args):
crop_size_min = 1000
gt_dict = {}
seq_list = os.listdir(args.data_root)
for seq_name in seq_list:
gt_path = os.path.join(args.data_root, seq_name, 'gt/gt.txt')
with open(gt_path) as gt_file:
... |
# see: https://docs.python.org/3/library/functions.html#eval
import re
def parse_into(line):
while ("+" in line) or ("*" in line):
e = re.findall(r"^(\d+ [\*\+] \d+)", line)[0]
line = str(eval(e)) + line[len(e):]
return int(line)
def parse(line):
while line.count("("):
eval = re.... |
import itertools
from . import (Point, MultiPoint, LineString, MultiLineString,
Polygon, MultiPolygon, GeometryCollection,
FeatureCollection)
def merge(items):
""" Combine a list of GeoJSON objects into the single most specific type
that retains all information.
For example,
... |
class Animals(object):
def __init__(self, type, price, product, productValue, sellValue):
self.__type = type
self.__price = price
self.__product = product
self.__productValue = productValue
self.__sellValue = sellValue
def get_type(self):
return self.__type
... |
from collections import deque
from pathlib import Path
def read_numbers(path: Path, cast=int) -> list[int]:
"""Read numeric data from a text file."""
if cast not in (int, float):
raise ValueError("Can only cast values to int or float")
data = []
with open(path, "r") as file:
for line ... |
'''
RunBundle is a bundle type that is produced by running a program on an input.
Its constructor takes a program target (which must be in a ProgramBundle),
an input target (which can be in any bundle), and a command to run.
When the bundle is executed, it symlinks the program target in to ./program,
symlinks the inp... |
#!/usr/bin/env python
# encoding: utf-8
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
login_manager = LoginManager()
db = SQLAlchemy()
migrate = Migrate()
|
try:
with open("myfile.txt") as fh:
file_data = fh.read()
print(file_data)
except FileNotFoundError as ex:
print("The Data File is missing")
except PermissionError as px:
print("This is not allowed")
except:
print("Some error occured")
|
# -*- coding: utf-8 -*-
# Import Python libs
from __future__ import absolute_import
from distutils.version import LooseVersion # pylint: disable=import-error,no-name-in-module
import copy
# Import Salt Testing libs
from salttesting.unit import skipIf, TestCase
from salttesting.mock import NO_MOCK, NO_MOCK_REASON, pa... |
#!/usr/bin/env python3
"""Alta3 Research | RZFeeser
CHALLENGE 01 - Solution"""
def main():
user_input = input("Please enter an IPv4 IP address: ")
## the line below creates a single string that is passed to print()
# print("You told me the IPv4 address is:" + user_input)
## print() ca... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: gui_overlay_config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflectio... |
class LargeInteger:
def __init__(self, integer_str):
if integer_str[0] == '-':
self.sign = -1
array = [int(c) for c in integer_str[1:]]
elif integer_str[0] == '+':
self.sign = 1
array = [int(c) for c in integer_str[1:]]
else:
self.... |
# coding: utf-8
from conf import settings
print(settings.MYSQL_HOST) # noqa
print(settings.MYSQL_PASSWD) # noqa
print(settings.EXAMPLE) # noqa
print(settings.current_env) # noqa
print(settings.WORKS) # noqa
|
# -*- coding: utf-8 -*-
"""@package set_FEMM_materials
@date Created on août 06 17:04 2018
@author franco_i+
@todo: why is the label "Lamination_Stator_Bore" and not "Lamination_Stator"
"""
import femm
from numpy import exp, pi
from pyleecan.Functions.FEMM import GROUP_FM
from pyleecan.Functions.FEMM.create_FEMM_bar ... |
"""Ttk wrapper.
This module provides classes to allow using Tk themed widget set.
Ttk is based on a revised and enhanced version of
TIP #48 (http://tip.tcl.tk/48) specified style engine.
Its basic idea is to separate, to the extent possible, the code
implementing a widget's behavior from the code implementing its
ap... |
import textwrap
from unittest.mock import Mock
import pytest
import ujson
from irrd.conf import RPKI_IRR_PSEUDO_SOURCE
from irrd.scopefilter.status import ScopeFilterStatus
from irrd.scopefilter.validators import ScopeFilterValidator
from irrd.storage.database_handler import DatabaseHandler
from irrd.utils.test_utils... |
# Generated by Django 3.0.3 on 2020-02-06 13:22
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
import FWCore.ParameterSet.Config as cms
from Configuration.EventContent.EventContent_cff import *
from HiggsAnalysis.Skimming.higgsToInvisible_EventContent_cff import *
higgsToInvisibleOutputModuleRECOSIM = cms.OutputModule("PoolOutputModule",
RECOSIMEventContent,
higgsToInvisibleEventSelection,
dataset =... |
import json
import scrapy
from locations.items import GeojsonPointItem
class PaneraBread(scrapy.Spider):
name = 'panera'
item_attributes = { 'brand': "Panera Bread" }
download_delay = 1.5
allowed_domains = ["panerabread.com"]
start_urls = (
'https://locations.panerabread.com/index.html',... |
from pathlib import Path
import depthai as dai
import numpy as np
import cv2
import sys
# Importing from parent folder
sys.path.insert(0, str(Path(__file__).parent.parent.parent)) # move to parent path
from utils.draw import drawROI, displayFPS
from utils.OakRunner import OakRunner
from utils.compute import to_planar
... |
from datetime import timedelta
import uuid
import logging
import email_normalize
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, AnonymousUser, PermissionsMixin
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
from django.db import models, IntegrityError, transaction
fr... |
from __future__ import absolute_import
import json
import logging
import warnings
try:
from itertools import zip_longest
except ImportError:
from itertools import izip_longest as zip_longest
from pip._vendor import six
from pip.basecommand import Command
from pip.exceptions import CommandError
from pip.index... |
maior = 0
menor = 0
totalPessoas = 10
for pessoa in range(1, 11):
idade = int(input("Digite a idade: "))
if idade >= 18:
maior += 1
else:
menor += 1
print("Quantidade de pessoas maior de idade: ", maior)
print("Quantidade de pessoas menor de idade: ", menor)
print("Porcentagem de pessoas menores de idad... |
#!/usr/bin/env python
import rospy
from inertial_sense_ros.msg import GPS
import gps_common.msg
def callback(data):
x=data.latitude
y=data.longitude
z=data.altitude
# rospy.loginfo('x: {}, y:{}, z:{},' .format(x,y, z))
def convert_msg(data):
x=data.latitude
y=data.longitude
z=data.altitu... |
# -*- coding: utf-8 -*-
"""Tests that disaggregations report the number of indicators assigned to them and can be archived"""
from factories import (
indicators_models as i_factories,
workflow_models as w_factories
)
from indicators.models import DisaggregationType, DisaggregationLabel, DisaggregatedValue
from... |
#!/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
"License");... |
# -*- coding: utf-8 -*-
# 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... |
"""Set up the objects ipython profile."""
import typing as tp
from databroker import Broker
from ophyd.sim import SynAxis, SynSignalWithRegistry, SynSignalRO
from xpdsim.movers import SimFilterBank
from .beamtime import Beamtime
from .beamtimeSetup import start_xpdacq
from .xpdacq import CustomizedRunEngine
from .xpd... |
from flask import Flask
app = Flask(__name__)
app.config.from_object('config')
from app import views
|
"""
Legend
------
The :meth:`pygmt.Figure.legend` method can automatically create a legend for
symbols plotted using :meth:`pygmt.Figure.plot`. Legend entries are only
created when the ``label`` argument is used.
"""
import pygmt
fig = pygmt.Figure()
fig.basemap(projection="x1i", region=[0, 7, 3, 7], frame=True)
fi... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2021 Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free... |
import os
import h5py
import shutil
import sklearn
import tempfile
import numpy as np
import pandas as pd
import sklearn.datasets
import sklearn.linear_model
import matplotlib.pyplot as plt
X, y = sklearn.datasets.make_classification(
n_samples=10000, n_features=4, n_redundant=0, n_informative=2,
n_clusters_p... |
# Copyright (c) 2012-2013 Mitch Garnaat http://garnaat.org/
# Copyright 2012-2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http... |
# Copyright (c) 2020. Lena "Teekeks" During <info@teawork.de>
"""
The Twitch API client
---------------------
This is the base of this library, it handles authentication renewal, error handling and permission management.
Look at the `Twitch API reference <https://dev.twitch.tv/docs/api/reference>`__ for a more detai... |
"""Author: SKHEO, KHU"""
from gym_SBR.envs import sub_phases_batchPID_fbPID as cycle
import numpy as np
#class SBR_model(object):
def run(WV, IV, t_ratio, influent, DO_control_par, x0, DO_setpoints,u_batch_1,u_batch_2,u_batch_3,u_batch_4,u_batch_5,u_batch_8,kla_memory1,kla_memory2,kla_memory3,kla_memory4,kla_... |
# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequen... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: anki_vector/messaging/shared.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import... |
"""
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 use this ... |
# 8.56-9.14,20min
N=int(input())
nums = [int(x) for x in input().split()]
if max(nums)<0:
print(0, nums[0], nums[-1])
exit(0)
if len(nums)==1:
print(nums[0],nums[0],nums[0])
exit(0)
# f[i]=max(f[i-1]+nums[i], nums[i])
f=[0 for _ in nums]
f[0] = nums[0]
s=[0 for __ in nums]
s[0] = nums[0]
for i in range... |
import pybaseball.utils
from .playerid_lookup import playerid_reverse_lookup
from .playerid_lookup import playerid_lookup
from .statcast import statcast, statcast_single_game
from .statcast_pitcher import statcast_pitcher
from .statcast_batter import statcast_batter, statcast_batter_exitvelo_barrels
from .league_battin... |
from django.urls import path, include
from .views import apiOverview
urlpatterns = [
path('', apiOverview, name="api-overview"),
path('accounts/', include('accounts.urls')),
path('rooms/', include('rooms.urls')),
path('university/', include('universities.urls')),
path('notifications... |
# extdiff.py - external diff program support for mercurial
#
# Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
'''command to allow external programs to compare revisions
The ex... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
""" Learning Concurrency in Python - Chapter 01 - sequential calculation """
import time
import random
# This does all of our prime factorization on a given number 'n'
def calculate_prime_factors(n_v):
""" Calculate prime factor. """
prime_factor = []
d_v = 2
while d_v * d_v <= n_v:
while (n_... |
#!/usr/bin/env python3
# Copyright (C) 2017-2020 The btclib developers
#
# This file is part of btclib. It is subject to the license terms in the
# LICENSE file found in the top-level directory of this distribution.
#
# No part of btclib including this file, may be copied, modified, propagated,
# or distributed except... |
"""Utilities file. Takes a given xml document and adds an attribute ID
to each of its paragraph tags"""
import xml.etree.ElementTree
def load(filename):
et = xml.etree.ElementTree.parse(filename)
p_tags = et.iter(tag="{http://www.tei-c.org/ns/1.0}p")
id_num = 0
for tag in p_tags:
tag.set("ID",str(id_num))
id_... |
# PROJECT : kungfucms
# TIME : 19-2-8 下午10:20
# AUTHOR : Younger Shen
# EMAIL : younger.x.shen@gmail.com
# CELL : 13811754531
# WECHAT : 13811754531
# WEB : https://punkcoder.cn
import os
from datetime import datetime
from kungfucms.utils.common import get_env, get_base_path
def get_log_path():
env = get_env()
... |
#!/usr/bin/env python
from datetime import datetime
from collections import Counter
data = [i for i in open('day04.input').read().splitlines()]
parsed = {}
for line in data:
dt, msg = line.split(']')
parsed[dt] = msg
days_sorted = sorted(parsed, key=lambda day: datetime.strptime(day[1:], "%Y-%m-%d %M:%S"))
... |
import numpy as np
from numpy import ma
def fill_between_steps(ax, x, y1, y2=0, step_where='pre', **kwargs):
''' fill between a step plot and
Parameters
----------
ax : Axes
The axes to draw to
x : array-like
Array/vector of index values.
y1 : array-like or float
Arra... |
"""
Django settings for NLPFrontEnd project.
Generated by 'django-admin startproject' using Django 1.9.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import o... |
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
from marshmallow import fields
from azure.ai.ml._schema.core.schema_meta import PatchedSchemaMeta
from azure.ai.ml._restclient.v2021_10_01.m... |
#coding: utf-8
__author__ = "Lário dos Santos Diniz"
from django.views.generic import TemplateView
class IndexView(TemplateView):
template_name = 'core/index.html'
index = IndexView.as_view() |
# Copyright 2020 ponai Consortium
# 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, s... |
# -*- coding: utf-8 -*-
#!/usr/bin/python
import sys
import os.path
import re
class ResidueError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Sequence(object):
def __init__(self, fn=None, ssq=None):
self.seq_=""
self.name_=""
if fn == None and... |
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#
#
# Copyright 2021 mRuggi <mRuggi@PC>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
... |
# Create a function to return the first initial of a name
# Parameters:
# name: name of person
# force_uppercase: indicates if you always want the initial to be in upppercase: default is True
# Return value
# first letter of name passed in
def get_initial(name, force_uppercase=True):
if force_uppercase:
... |
# Given a 2D grid, each cell is either a wall 'W',
# an enemy 'E' or empty '0' (the number zero),
# return the maximum enemies you can kill using one bomb.
# The bomb kills all the enemies in the same row and column from
# the planted point until it hits the wall since the wall is too strong
# to be destroyed.
# Note t... |
"""
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
Pooled supplier molecule design table.
"""
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy imp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.