content stringlengths 5 1.05M |
|---|
#
# (C) Copyright 2000- NOAA.
#
# (C) Copyright 2000- ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of ... |
#!/usr/bin/env python
# encoding: utf-8
"""
@version: v1.0
@author: xag
@license: Apache Licence
@contact: xinganguo@gmail.com
@site: http://www.xingag.top
@software: PyCharm
@file: gps_utils.py
@time: 2019-11-17 10:34
@description:TODO
"""
import math
def gps_to_dms(gps_data):
"""
坐标转为度、分、秒(double)
116... |
from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, func, Table, outerjoin
from sqlalchemy.orm import backref, relationship
from src.database import Base
ass = Table(
'classe_student', Base.metadata,
Column('id', Integer, primary_key=True),
Column('classe_id', Integer, ForeignKey('class... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 25 20:57:10 2022
@author: LiCheng_Xu
"""
import pandas as pd
import numpy as np
from rdkit import Chem
from rdkit.Chem import AllChem,Descriptors
from ase import Atoms as ASE_Atoms
from dscribe.descriptors import MBTR,ACSF,SOAP,LMBTR
from rdkit.ML.Descriptors ... |
# Copyright 2015 Palo Alto Networks, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... |
import json
from GameEnv import GameEnv
game_env = GameEnv(json.load(open("config.json", "r")))
game_env.run()
|
"""TRUTH TABLE GENERATOR
by ANTHONY CURTIS ADLER"""
to_replace = {'=>':'>',
'->':'>',
'<>':'#',
' AND ':'&',
'^':'&',
' V ':'|',
' OR ':'|',
' and ':'&',
... |
import numpy as np
from numpy import exp, eye, log, sqrt
from numpy.linalg import solve, eigh, cholesky, pinv
import PcmPy as pcm
class Model:
"""
Abstract PCM Model Class
"""
def __init__(self,name):
"""
Args:
name ([str]): Name of the the model
"""
sel... |
#!/usr/bin/env python2.7
from __future__ import division
from nltk.book import *
# What percentage of the text is taken up by a word.
print 100 * text4.count('a') / len(text4) |
import simplejson as json
from ppjson import ppjson
def test_empty_dict():
assert json.loads('{}') == ppjson.loads('{}')
|
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015, Alcatel-Lucent Inc
# 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
# no... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-02-19 15:50:09
# @Author : ZubinGou (zebgou@gmail.com)
# @Link : https://github.com/ZubinGou
# @Version : $Id$
import os
import sys
script, input_encoding, error = sys.argv
def main(language_file, encoding, errors):
line = language_file.readline... |
import hashlib
def md5_for_file(path_to_file: str) -> str:
with open(path_to_file, 'rb') as f:
return hashlib.md5(f.read()).hexdigest()
|
input = """
p35 :- p31,p12,p48.
p37 :- p28,p25,not p81.
p11 :- p88,p22,p27.
p42 :- p3,p73,not p6.
p90 :- p53,p75,p65.
p26 :- p96,p7,not p66.
p19 :- not p30,not p5,not p24.
p93 :- p9,not p63,p86.
p1 :- p56,p60,not p26.
p13 :- p34,not p22,p44.
p18 :- not p91,p53,p35.
p23 :- not p62,p32,p25.
p86 :- not p63,no... |
import board
import neopixel
import adafruit_fancyled.adafruit_fancyled as fancy
import math
import random
import time
import Defines
stepHue = 0
def stepStrobe(pixels):
global stepHue
for pixel in range(Defines.NUM_LEDS):
randomValue = random.randint(0,256)
color = fancy.CHSV(stepHue, 255, r... |
import re
import hashlib
import urllib3
import json
import csv
import pandas as pd
import sys
import numpy as np
import math
def round_KFM(x, n):
'''Commercial Rounding'''
posneg = math.copysign(1, x)
z = abs(x)*10**n
z = z + 0.5
z = math.trunc(z)
z = z/10**n
result = z * posneg
return... |
# Copyright (c) Chris Choy (chrischoy@ai.stanford.edu) and Wei Dong (weidong@andrew.cmu.edu)
#
# Please cite the following papers if you use any part of the code.
# - Christopher Choy, Wei Dong, Vladlen Koltun, Deep Global Registration, CVPR 2020
# - Christopher Choy, Jaesik Park, Vladlen Koltun, Fully Convolutional Ge... |
from struct import Struct
from struct import error as struct_error
from ...errors import ColumnTypeMismatchException, StructPackException
from ..io import BufferedReader, BufferedWriter
class Column:
ch_type = None
py_types = None
check_item = None
after_read_items = None
before_write_items = No... |
import re
from difflib import SequenceMatcher
from django.core.validators import RegexValidator
from django.utils.text import format_lazy
from django.utils.translation import ugettext_lazy as _
from rest_auth.registration.serializers import RegisterSerializer
from rest_auth.serializers import LoginSerializer, Password... |
from typing import List, Union
from fastapi import APIRouter, Response
from pydantic import Field
from starlette import status
from starlette.responses import PlainTextResponse
from heksher.api.v1.util import ORJSONModel, application, router as v1_router
from heksher.api.v1.validation import ContextFeatureName
from h... |
# temporal workspace: file to write down temporal programs for quizes and exercises
def multParams(strA, strB):
return (strA + strB)
print(multParams('a','b'))
def mean(*args):
return sum(args)/len(args)
print(mean(1,2,3))
def E(*args):
return sum(args)/len(args)
print(E(1,2,3))
def numString... |
"""Route53ResolverBackend class with methods for supported APIs."""
from collections import defaultdict
from datetime import datetime, timezone
from ipaddress import ip_address, ip_network, IPv4Address
import re
from moto.core import get_account_id
from moto.core import BaseBackend, BaseModel
from moto.core.utils impo... |
# Copyright (c) 2010 Doug Hellmann. All rights reserved.
#
"""
"""
# end_pymotw_header
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-i", metavar="in-file", type=argparse.FileType("rt"))
parser.add_argument("-o", metavar="out-file", type=argparse.FileType("wt"))
try:
results = parser.... |
#!/usr/bin/python
# -*- coding= utf-8 -*-
from ctypes import *
cfg = windll.cfgmgr32
adv = windll.Advapi32
CRVALS = {
0x00000000:"CR_SUCCESS",
0x00000001:"CR_DEFAULT",
0x00000002:"CR_OUT_OF_MEMORY",
0x00000003:"CR_INVALID_POINTER",
0x00000004:"CR_INVALID_FLAG"... |
import subprocess
from subprocess import PIPE, STDOUT
from unittest import TestCase
from testfixtures.mock import call
from testfixtures import ShouldRaise, compare, Replacer
from testfixtures.popen import MockPopen, PopenBehaviour
from testfixtures.compat import BytesLiteral, PY2
import signal
class Tests(TestCas... |
from devices.switch.on_off_switch import OnOffSwitch
class ToggleSwitch(OnOffSwitch):
def get_numeric_value(self, value, device):
if (value == 'toggle'):
return 1 if device.nValue == 0 else 0
else:
return super().get_numeric_value(value, device) |
""" used for packaging this for pypi """
import setuptools
with open("README.md", "r") as fh:
LONG_DESCRIPTION = fh.read()
setuptools.setup(
name="pygoodwe",
version="0.0.15",
author="James Hodgkinson",
author_email="yaleman@ricetek.net",
description="Goodwe Python interface",
long_descri... |
import sys
#import re
def parse(infile, outfile=None):
def escape(string):
#re.sub(r'(?<!\\)"','\\"',string.replace('\\', '\\\\'))
return string.replace('\\', '\\\\').replace('"', '\\"')
keep = ('keep', 'remove', 'optional', 'remove+')
axis = ('vertical', 'positive-x', 'negative-x', 'posi... |
import math
import numpy as np
import torch
import time
from utils.integral import Simpson, normalpdf
def seed_everything(seed=0):
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = Fals... |
def checkio(first, second):
list1=first.split(',')
list2 = second.split(',')
set1=set(list1)
set2=set(list2)
new_set = set1&set2
if len(new_set) == 0:
return ''
else:
return ','.join(sorted(new_set))
|
from udi_interface import Node,LOGGER,Custom,LOG_HANDLER
import logging,re,json,sys,asyncio
from threading import Thread,Event
from node_funcs import get_valid_node_name,get_valid_node_address
#sys.path.insert(0,"pyHS100")
#from pyHS100 import Discover
from kasa import Discover
from nodes import SmartStripPlug... |
import importlib
RUNNER_MODULES = {
'standard': 'training.runner',
'adversarial': 'training.adversarial_runner'
}
def build_runner(conf, runner_type, cuda, mode='train', resume=False):
assert runner_type in RUNNER_MODULES, \
'Unknown runner {}'.format(runner_type)
module = importlib.import_module(... |
# Generated by Django 2.2.6 on 2019-10-17 15:14
from django.db import migrations, models
import django_extensions.db.fields.json
class Migration(migrations.Migration):
dependencies = [
('scanners', '0002_auto_20191017_1257'),
]
operations = [
migrations.AddField(
model_name=... |
# -*- coding: utf-8 -*-
"""Forms encoded in WTForms."""
from flask_wtf import FlaskForm
from wtforms.fields import RadioField, StringField, SubmitField
from wtforms.validators import DataRequired
__all__ = [
'QueryForm',
]
class QueryForm(FlaskForm):
"""Builds the form for querying the model."""
curie... |
"""
CLI to Fetch Specific Google Sheets that have been updated
Accepts a Bean-File and writes a Yaml file of the records.
"""
import argparse
import pathlib
import logging
import datetime
import os
import typing
import json
import yaml
import dateparser
from coolbeans.tools.sheets import fetch_sheet, google_connect
f... |
import json
import boto3
print('Loading function')
ec2 = boto3.client('ec2')
def getEc2List():
ec2List = []
response_instance = ec2.describe_instances(
Filters=[
{
'Name': 'tag-key',
'Values': [
'autostart',
]
... |
import sys
import os
class Task:
task_id = None
p_time = None
p_times = None
r_time = None
d_time = None
w = None
def __init__(self, *args):
"""
:param task_id: Task id
:param p_time: processing time
:param r_time: ready time
:param d_time: due tim... |
from ..AuditRequesters.AuditRequesterBase import AuditRequesterBase
class PythonAuditRequester(AuditRequesterBase):
def __init__(self, packages, user_creds_filepath, auth, creds):
super().__init__(packages, user_creds_filepath, auth, creds)
self.package_manager = "PyPi"
|
# pylint: disable=missing-docstring, invalid-name, too-few-public-methods, redefined-outer-name
value = 10
value2 = 0
value3 = 3
# Positive
if value < 10: # [consider-using-max-builtin]
value = 10
if value >= 10: # [consider-using-min-builtin]
value = 10
if value <= 10: # [consider-using-max-builtin]
... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.13.0
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# # PN Ou 5:... |
#!/usr/bin/env python
#
# Copyright (c) 2018 Intel Labs.
#
# authors: Bernd Gassmann (bernd.gassmann@intel.com)
#
"""
Classes to handle Carla sensors
"""
from abc import abstractmethod
import threading
import rospy
from geometry_msgs.msg import TransformStamped
from carla_ros_bridge.actor import Actor
import carl... |
import os
from config_paths import csvfile
import dlite
csv = dlite.Instance(f'csv:{csvfile}')
print(csv.meta)
print(csv.uuid)
csv.save('csv:newfile.csv')
# Try to use the pandas hdf writer...
csv.save('csv:newfile.h5?pandas_opts=key=group')
# ... or excel writer (requires openpyxl)
try:
import openpyxl
... |
""" Script to create a multi-video media from existing videos
"""
import argparse
import logging
import sys
import tator
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
logger = logging.getLogger(__name__)
def main():
""" Main function of script
"""
args = parse_args()
tator_api = tato... |
# coding=utf-8
# Copyright 2020 The Google Research 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 applicab... |
# Generated by Django 3.0.8 on 2020-07-28 12:49
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('portal', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='cropType',
... |
from pathlib import Path
from fhir.resources.valueset import ValueSet as _ValueSet
from oops_fhir.utils import ValueSet
from oops_fhir.r4.code_system.financial_task_codes import (
FinancialTaskCodes as FinancialTaskCodes_,
)
__all__ = ["FinancialTaskCodes"]
_resource = _ValueSet.parse_file(Path(__file__).wit... |
def binary_gap(N):
if N < 5:
return 0
start = 0
gap_length = 0
max_gap_length = 0
for n in range(32):
if N & 1 == 1:
start = True
max_gap_length = max(max_gap_length, gap_length)
gap_length = 0
elif start:
gap_length += 1
... |
import math
import unittest
from forest.treespecies import TreeSpecies
from forest.tree import Tree
class TestTree(unittest.TestCase):
def setUp(self):
self.species = TreeSpecies("birch", 0.1, 10, 3, 0.8, 79, 2)
def test_create(self):
t = Tree(self.species, 100, 200)
self.assertEqua... |
import argparse
import os
import sys
from ckl.values import (
ValueList,
ValueString,
NULL
)
from ckl.errors import (
CklSyntaxError,
CklRuntimeError
)
from ckl.interpreter import Interpreter
def main():
parser = argparse.ArgumentParser(description="CKL run command")
parser.add_argument("... |
#!/usr/bin/env python
from ncclient import manager
def connect(host, port, user, password):
conn = manager.connect(host=host,
port=port,
username=user,
password=password,
timeout=10,
hostkey_verify=False)
result = conn.get_chassis_inventory()
p... |
"""Test cases for the Github create PR use case."""
from __future__ import annotations
import pytest
from pytest_mock import MockerFixture
import git_portfolio.domain.config as c
import git_portfolio.domain.pull_request as pr
import git_portfolio.request_objects.issue_list as il
import git_portfolio.responses as res
... |
# -*- coding: utf-8 -*-
import json
import os
import shutil
from app.const import *
from app.base.configs import tp_cfg
from app.base.logger import *
from app.model import audit
from app.model import record
from app.base.controller import TPBaseHandler, TPBaseJsonHandler
import tornado.gen
def get_free_space_bytes(... |
from __future__ import print_function
import sys
import logging
from couchdbkit.exceptions import ResourceNotFound
from django.conf import settings
from django.db.models import signals
from requests.exceptions import RequestException
from corehq.apps.callcenter.utils import sync_user_cases, bootstrap_callcenter, get_ca... |
from __future__ import unicode_literals
from django.apps import AppConfig
class BacklogItemsConfig(AppConfig):
name = 'backlog_items'
|
from .none_coalesce import none_coalesce
from .none_assertion import none_assertion, ValueIsNoneError
|
from .base import GnuRecipe
class ByaccRecipe(GnuRecipe):
def __init__(self, *args, **kwargs):
super(ByaccRecipe, self).__init__(*args, **kwargs)
self.sha256 = '27cf801985dc6082b8732522588a7b64' \
'377dd3df841d584ba6150bc86d78d9eb'
self.name = 'byacc'
self.ve... |
from getratings.models.ratings import Ratings
class NA_Zed_Mid_Aatrox(Ratings):
pass
class NA_Zed_Mid_Ahri(Ratings):
pass
class NA_Zed_Mid_Akali(Ratings):
pass
class NA_Zed_Mid_Alistar(Ratings):
pass
class NA_Zed_Mid_Amumu(Ratings):
pass
class NA_Zed_Mid_Anivia(Ratings):
pass
class NA_Z... |
import PySimpleGUI as sg
import json
from os import listdir, path
###
# Contains functions for handling files
###
class Files:
def get(saveLocation=None): # Checks all saved files and returns them as a list
if listdir(saveLocation): # Returns true if there are files in saveLocation
... |
#!/usr/bin/env python
# Add a CSV file as a table into <split>.db and <split>.tables.jsonl
# Call as:
# python add_csv.py <split> <filename.csv>
# For a CSV file called data.csv, the table will be called table_data in the .db
# file, and will be assigned the id 'data'.
# All columns are treated as text - no attempt ... |
"""empty message
Revision ID: 5b1ccae7a4d6
Revises: a4221c978242
Create Date: 2018-08-22 21:27:19.423458
"""
# revision identifiers, used by Alembic.
revision = '5b1ccae7a4d6'
down_revision = 'a4221c978242'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 10 15:31:17 2016
Last update on Saturday 17 March 2018
@author: michielstock
Kruskal's algorithm for finding the maximum spanning tree
"""
from union_set_forest import USF
import heapq
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
blue ... |
'''-------------------------------------------------------------------------------
Tool Name: AddSPTFields.py
Source Name: AddSPTFields
Version: ArcGIS 10.3
Author: Alan D. Snow, US Army ERDC
Updated by:
Description: Add fields to drainage line required for Streamflow Prediciton Tool
History: In... |
for first_num in range(1, 11):
for second_num in range(1, 11):
total = first_num * second_num
print(f'{first_num} * {second_num} = {total}') |
import time
import numpy as np
import pandas as pd
import nilearn as nl
import nilearn.plotting as nlplt
import torch
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
from tqdm import tqdm
from dataset import NeuroimagingDataset
root_path = f'/home/nvme/Kaggle/trends-assessment-prediction'... |
# coding: utf-8
"""Models for the limits extensions."""
from __future__ import unicode_literals
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.functional import cached_property
from django.utils.translation import ugettext... |
import torch
import torchvision
# from util_test import helper_setUp_CIFAR10_same
from pytorchfi.core import fault_injection
import timm
if __name__ == "__main__":
BATCH_SIZE = 4
WORKERS = 1
IMG_SIZE = 224
USE_GPU = False
# model, dataset = helper_setUp_CIFAR10_same(BATCH_SIZE, WORKERS)
# data... |
import asyncio
import webbrowser
import uvicorn
from app.app import app as _app, settings
from app.web_config import WebConfig
from bot.bot import Bot
async def app(loop: asyncio.AbstractEventLoop = None):
_app.add_event_handler("startup", lambda: webbrowser.open("http://localhost"))
config = uvicorn.Confi... |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#---------------------------------------------------... |
#!/bin/python3
import sys
def rotate(A, pos):
A[pos], A[pos+1], A[pos+2] = A[pos+1], A[pos+2], A[pos]
def larrysArray(A):
for _ in range(len(A)):
for ind in range(1, len(A) - 1):
a, b, c = A[ind-1], A[ind], A[ind+1]
#print("ind = {} A = {} B = {} C = {}".format(ind, a, b, c))
... |
# coding=utf-8
"""
本模块提供日志初始化功能
"""
from __future__ import absolute_import
import logging
# from logging.handlers import RotatingFileHandler
# from logging.handlers import TimedRotatingFileHandler
from logging.handlers import WatchedFileHandler
CONF = ""
def setup():
"""日志输出初始化"""
levelmap = {
'DE... |
# This implemented model of EvoRecSys has been designed as a web-based system. This file, which is a minimal endpoint,
# controls the full workflow of the system.
# All necessary libraries and imports from other files.
from src.collaborativefiltering.CollaborativeFiltering import CollaborativeFiltering
from src.genet... |
# iterOverList.py
supplies = ['pens', 'water', 'oakum', 'wampum', 'pemmican']
for i in range(len(supplies)):
print('Index ' + str(i) + ' in supplies is: ' + supplies[i])
|
from sqlalchemy import create_engine, MetaData, Table, Integer, String, \
Column, DateTime, ForeignKey, Numeric, SmallInteger
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from datetime import datetime
engine = create_engine("sqlite:///db1.sqlite")
Base = declarat... |
from typing import Any
from django.db import InterfaceError, OperationalError, ProgrammingError
from conf.exceptions import ConfException
from conf.handler import BaseHandler
class ClusterOptionsHandler(BaseHandler):
def __init__(self):
self._model = None
self._owner = None
@property
de... |
class DependencyInjectionError(Exception):
pass
class DependencyNotFound(DependencyInjectionError):
def __init__(self, protocol):
self.protocol = protocol
|
import logging; logging.basicConfig(level=logging.INFO)
import asyncio, os, json, time
from datetime import datetime
from aiohttp import web
from www.static import orm
from www.static.models import User, Blog, Comment
async def index(request):
logging.info('--->')
text = '<h1>Hello World! %s</h1>' % request.... |
"""This file contains tests to test edge cases relating to the program code text."""
from tests.interpreter import run
def test_empty():
e = run("")
assert e == {}
def test_newlines():
e = run("\n" * 8)
assert e == {}
def test_trailing_newlines():
e = run("a=2" + "\n" * 8)
assert e["a"] ==... |
from rest_framework import serializers
from .models import Tag
class TagSerializer(serializers.HyperlinkedModelSerializer):
study_count = serializers.IntegerField(read_only=True)
question_count = serializers.IntegerField(read_only=True)
total_count = serializers.IntegerField(read_only=True)
class Met... |
from bricks import objects
from bricks.tests.db import base
class TestMortarTaskObject(base.DbTestCase):
def test_setters(self):
foo = objects.MortarTask()
foo.instance_id = 'asdf-1234'
foo.configuration = {'bar': 'baz'}
bar = foo.as_dict()
self.assertEqual(bar['instance_... |
from typing import Any as _Any, Dict, List, Union
from urllib.parse import quote as _quote
from xml.etree import ElementTree as _ElementTree
from . import format as _format
from . import parse as _parse
import pss_data as _pss_data
import pss_lookups as _lookups
from typehints import EntitiesData
# ---------- Typeh... |
"""Implementation of the Colella 2nd order unsplit Godunov scheme. This
is a 2-dimensional implementation only. We assume that the grid is
uniform, but it is relatively straightforward to relax this
assumption.
There are several different options for this solver (they are all
discussed in the Colella paper).
* limi... |
"""Tools for working with design spaces."""
from typing import Any, List, Mapping, Type
from uuid import UUID
from citrine._serialization.polymorphic_serializable import PolymorphicSerializable
from citrine._serialization.serializable import Serializable
class Module(PolymorphicSerializable['Module']):
"""A Citr... |
#------------------Bombermans Team---------------------------------#
#Author : B3mB4m
#Concat : b3mb4m@protonmail.com
#Project : https://github.com/b3mb4m/Shellsploit
#LICENSE : https://github.com/b3mb4m/Shellsploit/blob/master/LICENSE
#------------------------------------------------------------------#
def process(... |
# coding=utf-8
# Copyright 2020 The Trax 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 a... |
# -*- coding:utf-8 -*-
"""
@author: Alden
@email: sunzhenhy@gmail.com
@date: 2018/3/31
@version: 1.0.0.0
"""
class Solution(object):
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0 or len(nums) == 2:
return -1
elif... |
import numpy as np
from .VariableUnitTest import VariableUnitTest
from gwlfe.MultiUse_Fxns.Discharge import AdjUrbanQTotal
class TestAdjUrbanQTotal(VariableUnitTest):
def test_AdjUrbanQTotal(self):
z = self.z
np.testing.assert_array_almost_equal(
AdjUrbanQTotal.AdjUrbanQTotal_f(z.NYr... |
import KratosMultiphysics
from math import *
def Factory(settings, Model):
if(type(settings) != KratosMultiphysics.Parameters):
raise Exception("expected input shall be a Parameters object, encapsulating a json string")
return CheckVectorComponentsToNodesProcess(Model, settings["Parameters"])
# Import... |
# Copyright 2018 Vincent Deuschle. 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://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license" file accompanyin... |
"""
Update wikidata labels based on recently articles connected to wikidata
"""
import datetime
import pywikibot
from pywikibot import pagegenerators
import re
def scan_sitelinks():
local_wiki = pywikibot.Site()
wikidata = local_wiki.data_repository()
wikidata.login()
#st = local_wiki.getcurrenttime()
... |
from pymongo import MongoClient
from pprint import pprint
import yaml
import json
client = MongoClient("mongodb://mongo")
db = client.katana
collection = db.vim
def index(collection_name):
collection = db[collection_name]
return collection.find({})
def get(collection_name, uuid):
collection = db[colle... |
#!/usr/bin/env python
#coding:utf-8
__author__ = 'sws'
import scrapy
from scrapy_practice.items import MeniItem
class ScrapyMeni(scrapy.Spider):
"""
抓取 'http://www.metinfo.cn/demo/res001/342/' 的所有的图片
"""
name = 'meni'
allowed_domains = [
'www.metinfo.cn',
]
start_urls = [
... |
# -*- coding: utf-8 -*-
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
import os
from distutils.sysconfig import get_python_inc
#from distutils import setup, find_packages, Extension
from setuptools import setup, Extension
import platform
import sys
import imp
def system(c... |
from flask import (
Blueprint
)
from flask import (
abort,
request,
jsonify,
redirect,
)
from .db import (
get_db,
)
from .utils import (
make_tiny,
get_parameters,
)
bp = Blueprint('Shorted URL', __name__, url_prefix='/')
@bp.route('/', methods=['POST'])
def add_url():
"""
Th... |
import numpy as np
import os
from sklearn.feature_extraction import DictVectorizer
from autogoal.datasets import datapath, download
def load(representation="numeric"):
"""
Loads corpora from [ABALONE uci dataset](https://archive.ics.uci.edu/ml/datasets/Abalone).
##### Examples
```python
... |
import gdb
class SwitchBreaker(gdb.Command):
def __init__(self):
super().__init__(
'break-switch',
gdb.COMMAND_RUNNING,
gdb.COMPLETE_NONE,
False
)
def invoke(self, arg, from_tty):
frame = gdb.selected_frame()
# TODO make this work if there is no debugging information, where ... |
from __future__ import print_function
from sys import argv
from sys import exit
from sys import stderr
import pandas as pd
USER_ID = 'client_id'
PREDICTION = 'target'
SPLIT = 'split'
CONTACTS = 'contacts'
SALE_FLAG = 'sale_flg'
SALE_AMOUNT = 'sale_amount'
TRUTH_COLUMNS = [USER_ID, SPLIT, CONTACTS, SALE_AMOUNT, SALE_F... |
# Copyright (c) 2014 Juniper Networks, Inc
import argparse
import os
import signal
import sys
import uuid
def import_path_setup():
""" Test environment managed by easy_install """
sys.path.append(os.curdir)
for lsentry in os.listdir(os.curdir):
if not os.path.isdir(lsentry):
continue
... |
from django import forms
from .models import Category, Categorization
class UploadCSVForm(forms.Form):
"""
Handle the upload of the Capitec CSV file
"""
file = forms.FileField()
class CategoryForm(forms.ModelForm):
"""
Handles CRUD operation for the Category models.
"""
class Meta:
... |
import requests
def get_address_from_cep(cep: str):
payload = requests.get('http://viacep.com.br/ws/{cep}/json'.format(cep=cep.replace('-', '')))
try:
payload.raise_for_status()
except requests.HTTPError:
raise requests.HTTPError('Invalid CEP')
address = payload.json()
if address.g... |
from __future__ import absolute_import, unicode_literals
import json
from django.http import JsonResponse
from django.urls import reverse_lazy
from django.views.generic import View
from jwcrypto import jwk
from rest_framework.views import APIView
from ..settings import oauth2_settings
class ConnectDiscoveryInfoVie... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.