content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
"""
Copyright Tiyab KONLAMBIGUE
Licensed under the BSD 3-Clause "New" or "Revised" license;
you may not use this file except in compliance with the License.
You may obtain a copy of the License at : https://opensource.org/licenses/BSD-3-Clause
"""
from google.appengine.ext import ndb
class Job(ndb.Model):
creati... | python |
#!/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
# "... | python |
# tuples are lists but immutable
# the syntax is ( parenthesis )
# list
l = [1,2,3]
l[0] = 5 # you can do this
print(type(l))
print(l)
# tuple
t = (1,2,3)
# t[0] = 5 # you can't do this
print(type(t))
print(t)
# tuples only have two methods, a lot less than lists
t = ('a', 'a', 'b', 'b', 'c', 'c')
print(f"the amount... | python |
import sys
import re
from functools import partial
def flush_print(st, *args, **kwargs):
end = kwargs.pop('end', '\n')
if args:
st = st % args
print(st, end=end)
if sys.stdout.isatty():
sys.stdout.flush()
def cprint(color_fn, st, *args):
if args:
st = st % args
print(... | python |
#!/usr/bin/env python
print("hi from Python 3")
| python |
"""Background job to perform a DNS lookup and insert into or update in the db.
Attributes:
DNS_SERVERS: A list of strs representing which DNS servers to use
DNS_BLOCKLIST: A str representing the blocklist to send a DNS lookup to
"""
import dns.resolver
from models import IPDetails, ResponseCode
# Spamhaus w... | python |
from scrapy import cmdline
if __name__ == '__main__':
# cmdline.execute('scrapy crawl xinFang'.split())
# cmdline.execute('scrapy crawl erShouFang'.split())
cmdline.execute('scrapy crawl zuFang'.split()) | python |
from .build_model import add_weights, build_model
| python |
#!/usr/bin/env python3
# _*_ coding:utf-8 _*_
import requests
from Config.config_requests import ua
requests.packages.urllib3.disable_warnings()
# 脚本信息
######################################################
NAME = 'pentaho_bruteforce'
AUTHOR = "Trans"
REMARK = 'pentaho密码爆破'
FOFA_RULE = 'app="pentaho"'
##############... | python |
# Copyright (c) 2019, Palo Alto Networks
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS... | python |
import pycountry
from matcher.server.main.elastic_utils import get_analyzers, get_char_filters, get_filters, get_index_name, get_mappings
from matcher.server.main.logger import get_logger
from matcher.server.main.my_elastic import MyElastic
SOURCE = 'country'
logger = get_logger(__name__)
def download_country_data... | python |
#--------------#
# Look Away! #
# By: Santo C. #
#--------------#
# Created October 26, 2006 (c) Santo C.
# Import the modules needed.
import random
from time import sleep
# Rules Document
Rules = """==========
Rules of the game:
------------------
Standing in front of you is your game host.
He will point in on... | python |
from django.db import models
# model to store incoming unpaid cheque details
class UnpaidCheque(models.Model):
raw_string = models.CharField(max_length=100)
voucher_code = models.CharField(max_length=3)
cheque_number = models.CharField(max_length=100)
reason_code = models.CharField(max_length=3)
ch... | python |
# Copyright 2019 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 applicable law or agr... | python |
from django.contrib import admin
from activities.models import *
# Register your models here.
admin.site.register(Activity)
| python |
from django.contrib import admin
from .models import GoogleAuthUser
class GoogleAuthUserOption(admin.ModelAdmin):
"""GoogleAuthUser options"""
list_display = ('user', 'refresh_token')
search_fields = ('user',)
admin.site.register(GoogleAuthUser, GoogleAuthUserOption)
| python |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""Translate a glob-style pattern to a regular expression.
"""
__version__ = "$Id$"
#end_pymotw_header
import fnmatch
pattern = 'fnmatch_*.py'
print 'Pattern :', pattern
print 'Regex :', fnmatch.translate(pattern) | python |
#!/usr/bin/env python
from icecube import icetray, dataclasses
def ConvertToLinearizedMCTree(frame):
if 'I3MCTree' in frame:
try:
tree = dataclasses.I3LinearizedMCTree(frame['I3MCTree'])
except:
icecube.icetray.logging.log_error('cannot convert to I3LinearizedMCTree')
... | python |
import json
from unittest import mock
from routemaster.db import Label, History
def test_root(client, version):
response = client.get('/')
assert response.json == {
'status': 'ok',
'state-machines': '/state-machines',
'version': version,
}
def test_root_error_state(client, versi... | python |
"""A `WorkItem` carries information about potential and completed work in the
Cosmic Ray system.
`WorkItem` is one of the central structures in CR. It can describe both work
to be done and work that has been done, and it indicates how test sessions have
completed.
"""
def make_record(name, fields=(), docstring=""):
... | python |
import sys, os
sys.path.append(os.pardir)
import numpy as np
from dataset.mnist import load_mnist
(x_train, t_train), (x_test, t_test) = \
load_mnist(normalize=True, one_hot_label=True)
train_size = x_train.shape[0]
batch_size = 10
batch_mask = np.random.choice(train_size, batch_size)
x_batch = x_train[batch_mask]
... | python |
import requests
from src.mercadolibre.OAuth import OAuth
from src.mercadolibre.enums import paths
from src.mercadolibre.enums.HttpMethods import HttpMethods
class Client:
def __init__(self, access_token=None, refresh_token=None):
self.access_token = access_token
self.refresh_token = refresh_token... | python |
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
# Create your views here.
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
username = for... | python |
""""""
__all__ = ['Pipeline']
# Standard library modules.
import asyncio
# Third party modules.
from loguru import logger
import tqdm
# Local modules.
# Globals and constants variables.
class Pipeline:
def __init__(self, tasks, stop_on_failure=False):
self.tasks = tuple(tasks)
self.stop_on_fa... | python |
class Solution:
def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:
| python |
#!/usr/bin/env python
#
import os, unittest
here = os.path.abspath(os.path.dirname(__file__))
class TestCase(unittest.TestCase):
def test(self):
"neutron_storage: no neutron saved"
workdir = 'NeutronStorage-zero-neutrons'
saved = os.path.abspath('.')
os.chdir(workdir)
... | python |
import re
#source: https://en.wiktionary.org/wiki/Category:English_abbreviations
ABBREVIATIONS_COMMON = [(re.compile(r'\b%s\.?(,?)\b' % x[0]), r'%s\1 ' % x[1]) for x in [
("abbr", "abbreviation"),
("abbrev", "abbreviation"),
#("abr", "abridged"),
("abstr", "abstract"),
("AI", "artificial intelligence"),
#... | python |
def insertionSort(arr):
for x in range(1, len(arr)):
item = arr[x]
i = x - 1
while i >= 0 and item < arr[i]:
arr[i + 1] = arr[i]
i -= 1
arr[i + 1] = item
return arr
print(insertionSort([1,9,8,4,6,7,3,12,5,18,2,22])) | python |
"""Originally Adapted from sphinxcontrib.details.directive
"""
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx.util.docutils import SphinxDirective
from sphinx.transforms.post_transforms import SphinxPostTransform
from sphinx.util.nodes import NodeMatcher
def setup_dropdown(app):
... | python |
from robocorp_code.protocols import IRcc, IRccRobotMetadata
import py.path
def test_rcc_template_names(rcc: IRcc):
result = rcc.get_template_names()
assert result.success
assert result.result
assert "standard" in result.result
def test_rcc_cloud(rcc: IRcc, ci_credentials: str, tmpdir: py.path.local)... | python |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
lookup = {1:[TreeNode(0)]}
def allPossibleFBT(self, N):
if N%2 == 0:
return None
if N n... | python |
import unittest
from preset import ActionTypes, Step, Preset
class TestStep(unittest.TestCase):
def test_01_constructor_and_properties(self):
temp_name = "name"
temp_value = "value"
temp_executable = lambda x: x
temp_action_type = ActionTypes.filter
temp_instance = Step(t... | python |
import logging
import os
import pickle
from typing import Generator, List, Tuple, Dict
from gensim.models import Word2Vec
from gensim.test.utils import common_texts
from wbtools.db.dbmanager import WBDBManager
from wbtools.lib.nlp.common import PaperSections
from wbtools.lib.nlp.text_preprocessing import preprocess
f... | python |
# game.py (c) 2017 D.J.Whale 22/01/2017
# Star-Wars 'Use the Force, Luke' game
# Using many moving parts provided by Martin O'Hanlon
#----- CONFIGURATION ----------------------------------------------------------
DEATHSTAR_CENTRE_POS = (100,100,10)
TARGET_POS = (100,100,10)
IN_RANGE = ((100,1... | python |
from toontown.coghq.SpecImports import *
GlobalEntities = {1000: {'type': 'levelMgr', 'name': 'LevelMgr', 'comment': '',
'parentEntId': 0,
'cogLevel': 0,
'farPlaneDistance': 1500,
'modelFilename': 'phase_11/models/lawbotHQ/LB_Zone7a',
'wantDoors': 1},
1001: {'t... | python |
__author__ = "The One & Only Javi"
__version__ = "1.0.0"
__start_date__ = "25th July 2020"
__end_date__ = "5th August 2020"
__maintainer__ = "me"
__email__ = "little_kh@hotmail.com"
__requirements__ = "SQL-Alchemy, MySQL," \
" Flask-SQLAlchemy, database.py, " \
"models.py, video_op... | python |
from .PZT import PZTMountedGrounded
| python |
from robofab.world import CurrentGlyph
from robofab.pens.filterPen import thresholdGlyph
d = 10
thresholdGlyph(CurrentGlyph(), d) | python |
# Two-sided notes
create_table_notes_ab = """
create table if not exists notes_ab
(
id text,
front text,
back text,
PRIMARY KEY(id)
)
"""
# One-sided notes
create_table_notes_qa = """
create table if not exists notes_qa
(
id text,
front text,
back text,
PRIMARY KEY(id)
)
"""
# Th... | python |
import pysftp
server_host = "demo.wftpserver.com"
username = "demo"
password = "demo"
with pysftp.Connection(server_host, username=username, password=password,port=2222)as sftp:
print(sftp.pwd)
# with sftp.cd('public'): # temporarily chdir to public
# sftp.put('/my/local/filename') # upl... | python |
# -*- coding: utf-8 -*-
"""
netvisor.responses.products
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2013-2016 by Fast Monkeys Oy.
:license: MIT, see LICENSE for more details.
"""
from ..schemas import GetProductSchema, ProductListSchema
from .base import Response
class ProductListResponse(Response):
... | python |
#
# Copyright 2015 BMC Software, 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 agreed to in ... | python |
#!/usr/bin/python3
from venus.stock_base import StockEventBase
class EventStockFlag(StockEventBase):
def flag_quit_stock(self, stock_code):
import datetime
import pandas as pd
from datetime import date
from dev_global.env import TIME_FMT
result = self.mysql.select_values(st... | python |
class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
if len(matchsticks) < 4:
return False
perimeter = sum(matchsticks)
if perimeter % 4 != 0:
return False
A = sorted(matchsticks)[::-1]
def dfs(selected: int, edges: List[int]) -> bool:
if selected == len(A):
... | python |
#!/usr/bin/env python
tuple= ["Juan", 5, 20.80, "HOLA"]
tuple2= [1,2,3]
lista3= [[1,2,3], [1, 3, 6], "HOLA"]
print tuple[0]
print tuple[1:2]
print tuple[2:]
print tuple *2
print tuple+tuple2
print lista3
| python |
# Copyright 2016-2017 Curtis Sand <curtissand@gmail.com>
#
# 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 l... | python |
from plenum.common.constants import ALIAS, SERVICES, VALIDATOR
from plenum.test.helper import sendReqsToNodesAndVerifySuffReplies
from plenum.test.node_catchup.helper import waitNodeDataEquality, \
checkNodeDataForInequality
from plenum.test.pool_transactions.helper import \
updateNodeData
from stp_core.common.... | python |
#!/usr/bin/python
"""
Commander.py - Python Backend for the WiFi Pineapple Commander module.
Version 2 Codename: Electric Boogaloo
Thanks to: sebkinne & tesla
Foxtrot (C) 2016 <foxtrotnull@gmail.com>
"""
import os
import ConfigParser
import sys
import socket
import time
import string
import select
import errno
cla... | python |
# Copyright (c) 2016-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
from freeswitch import... | python |
from scrapy.selector import Selector
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from scrapy.utils.url import urljoin_rfc
from sitegraph.items import SitegraphItem
class GraphspiderSpider(CrawlSpider):
name = 'graphspider'
allowed_domains = ['sastra.edu']
st... | python |
from ocean_spark.hooks import OceanSparkHook
from unittest.mock import MagicMock
def test_get_app(successful_get_app: None, get_connection_mock: None) -> None:
hook = OceanSparkHook()
app_dict = hook.get_app("test-app-name")
assert app_dict is not None
assert app_dict["displayName"] == "test app name"... | python |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 26 15:13:29 2022
@author: jasy9
"""
from .topsis import TOPSIS | python |
# Author: Ackerley Cheng
# file encoding: utf-8
def sameList(listA, listB):
return (len(listA) == len(listB)) and (set(listA) == set(listB))
def listInListSet(list, listSet):
for idx, ls in enumerate(listSet):
if sameList(list, ls):
return idx
return -1
# check if listA is a subset ... | python |
from django import forms
from consent.models import Privilege
class PrivilegeForm(forms.ModelForm):
class Meta:
model = Privilege
class ConsentForm(forms.Form):
consents = forms.ModelMultipleChoiceField(Privilege.objects,
widget=forms.CheckboxSelectMultiple, required=False)
| python |
import numpy as np
from qm_2019_sss_6.NobleGasModel import NobleGasModel
from qm_2019_sss_6.scf import scf
from qm_2019_sss_6.mp2 import MP2
atomic_coordinates = np.array([[0.0, 0.0, 0.0], [3.0, 4.0, 5.0]])
# Derived from user input
number_of_atoms = len(atomic_coordinates)
# Argon parameters - these would change for... | python |
#!/usr/bin/env python3
import os
import random
from collections import namedtuple, defaultdict
dir_path = os.path.dirname(os.path.realpath(__file__))
file = open(dir_path + "/input.txt", "r")
lines = [l.strip() for l in file.readlines()]
"""
acc increases or decreases a single global value called the accumulator by... | python |
import os
import pytz
from tweepy import OAuthHandler, API, TweepError
from . import Data
from abc import ABC, abstractmethod
import datetime
def check_if_datetime_offset_aware(date):
return date.tzinfo is not None and date.tzinfo.utcoffset(date) is not None
class SocialMediaDataFetch(ABC):
_start_date =... | python |
import sys
import traceback
from django.core.management.base import BaseCommand
from django.conf import settings
from optparse import make_option
from cripts.config.config import CRIPTsConfig
from cripts.core.mongo_tools import mongo_find_one
from cripts.events.event import Event
from prep import prep_database
cla... | python |
from d20.Manual.Facts import (Fact,
registerFact)
from d20.Manual.Facts.Fields import StringField
@registerFact('hash')
class MD5HashFact(Fact):
_type_ = 'md5'
value = StringField()
@registerFact('hash')
class SHA1HashFact(Fact):
_type_ = 'sha1'
value = StringField()
... | python |
"""Module contains the pydvdid package definition.
"""
from setuptools import setup
with open('README.rst') as readme_file:
README = readme_file.read()
setup(
name="pydvdid",
version="1.1",
description="A pure Python implementation of the Windows API IDvdInfo2::GetDiscID method, as used by Windows... | python |
import pygame
from .math_helpers import *
def draw(surface, p1,p2, shading_function, section_length,section_offset):
#Adapted Bresenham's line algorithm from
#http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
x0,y0 = p1
x1,y1 = p2
dx = abs(x1 - x0)
dy = abs(y1 - y0)
i... | python |
from flask_pyoidc.flask_pyoidc import OIDCAuthentication
from tenacity import retry
@retry
def get_auth(app):
auth = OIDCAuthentication(
app,
issuer=app.config['OIDC_ISSUER'],
client_registration_info=app.config['OIDC_CLIENT_CONFIG'],
)
return auth
| python |
"""Functions to calculate signal-to-noise ratio in four different cases"""
import numpy as np
from legwork import strain, psd, utils, evol
import astropy.units as u
__all__ = ['snr_circ_stationary', 'snr_ecc_stationary',
'snr_circ_evolving', 'snr_ecc_evolving']
def snr_circ_stationary(m_c, f_orb, dist, t... | python |
"""
QUESTION:
This is an interview question asked by Amazon.
There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time.
Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters.
For example, if N is 4, then there are 5 ... | python |
#!/usr/bin/env python
from setuptools import setup
setup(name='dvaclient',
version='1.0',
description='Deep Video Analytics Client',
author='Akshay Bhat',
author_email='dvaclient@deepvideoanalytics.com',
url='https://www.deepvideoanalytics.com/',
packages=['dvaclient'],
packa... | python |
from chainer.backends import cuda
import numpy as np
def mask_to_bbox(mask):
"""Compute the bounding boxes around the masked regions.
This function accepts both :obj:`numpy.ndarray` and :obj:`cupy.ndarray` as
inputs.
Args:
mask (array): An array whose shape is :math:`(R, H, W)`.
... | python |
from draco.programs import constraints, definitions, generate, hard, helpers
def test_has_definitions():
assert len(definitions.program)
assert len(definitions.blocks)
def test_definitions_has_marktype():
assert "mark_type" in definitions.blocks
def test_has_constraints():
assert len(constraints.p... | python |
from wpilib import DigitalInput
import robotmap
gear_mech_switch = None
def init():
"""
Initialize switch objects.
"""
global gear_mech_switch
gear_mech_switch = DigitalInput(robotmap.switches.gear_switch_channel)
| python |
class Solution:
def multiply(self, T, M):
a = (T[0][0] * M[0][0] + T[0][1] * M[1][0] + T[0][2] * M[2][0])
b = (T[0][0] * M[0][1] + T[0][1] * M[1][1] + T[0][2] * M[2][1])
c = (T[0][0] * M[0][2] + T[0][1] * M[1][2] + T[0][2] * M[2][2])
d = (T[1][0] * M[0][0] + T[1][1] * M[1][0] + T[1][... | python |
# [START method_one]
# [START method_two]
def _bar():
return 'Underscores in method names denote helper methods.'
# [END method_one]
# [END method_two]
# [START method_one]
def return_one():
return 1
# [END method_one]
# [START method_two]
def return_two():
return 2
# [END method_two] | python |
class Song:
"""Class to represent a song
Attributes:
title (str): The title of the song
artist (Artist): An artist object representing the songs creator.
duration (int): The duration of the song in seconds. May be zero
"""
def __init__(self, title, artist, duration=0):
... | python |
# uncompyle6 version 3.2.0
# Python bytecode 2.4 (62061)
# Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
# Embedded file name: pirates.piratesgui.BarSelectionMenu
from direct.gui.DirectGui import *
from pandac.PandaModules import *
from direct.directnotify import... | python |
import argparse
from paz.pipelines import SSD300FAT, SSD300VOC, SSD512COCO, SSD512YCBVideo
from paz.backend.camera import VideoPlayer, Camera
import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(gpus[0], True)
parser = argparse.ArgumentParser(d... | python |
#!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2013, SRI International
# 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 ... | python |
import os
import urllib.request
import zipfile
from random import shuffle
from math import floor
def download_dataset():
print('Beginning dataset download with urllib2')
url = "http://cs231n.stanford.edu/tiny-imagenet-200.zip"
path = "%s/tiny-imagenet-200.zip" % os.getcwd()
urllib.request.urlretrieve(url, path)
p... | python |
from behaviors.button import ButtonBehavior, ToggleButtonBehavior
from behaviors.touch_effecs import EffectBehavior
from kivy.uix.image import Image
from kivy.uix.anchorlayout import AnchorLayout
from kivy.properties import (
ListProperty, ObjectProperty,
)
from kivy.graphics import Color, Rectangle
from kivy.c... | python |
import os
from sys import argv
tobs = int(argv[1])
for i in range(6):
if i != 4:
for j in range(10):
if j==0:
os.system('tail -10000 tobs%d/window%d/hb_list_tobs_%d_task_%d.dat > tobs%d/window%d/window%d.dat'%(tobs,i,tobs,j,tobs,i,i))
else:
os.system('tail -10000 tobs%d/window%d/hb_l... | python |
from binaryninja import *
from binaryninja.binaryview import BinaryView
from binaryninja.platform import Platform
from .browser import ImagePickerDialog
# binja doesn't want to load mods in a plugin's dir
# so hopefully we can just hack that in manually
# We do this after importing binaryninja, because in my local... | 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"); you may not u... | python |
import argparse
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from dp_autoencoder import Autoencoder
import mimic_dataset
import dp_optimizer
import sampling
import analysis
# Deterministic output
torch.manual_seed(0)
np.random.seed(0)
class Generator(nn.Module):
... | python |
# Generated by Django 3.0.1 on 2020-01-06 22:04
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('chat', '0008_message_front_key'),
]
operations =... | python |
# the first import can't be removed
import scripted_rest_sys_path
from dbx2.dbx_logger import logger
import splunk, os, json
from json import loads
from dbx2.simple_rest import SimpleRest
from dbx2.java_home_detector import JavaHomeDetector
from dbx2.splunk_client.splunk_service_factory import SplunkServiceFactory
imp... | python |
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# a ^ 0 == a
# a ^ a == 0
# a ^ b ^ a = a ^ a ^ b = 0 ^ b = b
a = 0
for i in nums:
a ^= i
print(a)
return a
print(... | python |
# This software is open source software available under the BSD-3 license.
#
# Copyright (c) 2020 Triad National Security, LLC. All rights reserved.
# Copyright (c) 2020 Lawrence Livermore National Security, LLC. All rights
# reserved.
# Copyright (c) 2020 UT-Battelle, LLC. All rights reserved.
#
# Additional copyright... | python |
from typing import Tuple, Type, List, Dict, Union
from pyfileconf.main import PipelineManager, SpecificClassConfigDict
def get_pipeline_dict_path_and_specific_class_config_dicts_from_manager(manager: PipelineManager
) -> Tuple[
... | python |
"""
Task-Specific consistency training on downstream task (BreastPathQ)
"""
import argparse
import os
import time
import random
import numpy as np
from PIL import Image
import cv2
import copy
import pingouin as pg
import statsmodels.api as sm
import pandas as pd
from tqdm import tqdm
import torch.backends.cudnn as cudn... | python |
from __future__ import absolute_import
import datetime
from .config import get_config_file_paths
from .util import *
# config file path
GOALS_CONFIG_FILE_PATH = get_config_file_paths()['GOALS_CONFIG_FILE_PATH']
GOALS_CONFIG_FOLDER_PATH = get_folder_path_from_file_path(
GOALS_CONFIG_FILE_PATH)
def strike(text):... | python |
from __future__ import absolute_import
import argparse
import os
import sys
# sys.path.append(".")
import time
import torch
from tensorboardX import SummaryWriter
from metrics.evaluation import evaluate
from metrics.vae_metrics import VaeEvaluator
from struct_self.dataset import Dataset
from struct_self.dataset impo... | python |
# coding= UTF-8
### Command line of python <filename> was getting angry till I added the line above. I think ### it needs to know what types of characters to expect (i.e. latin, korean, etc..)
import datetime
### I needed to switch to single quotes instead of double. I’m not sure why...
name = raw_input('Yo what y... | python |
# -*- coding: utf-8 -*-
# type: ignore
"""Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2019 Caleb Bell <Caleb.Andrew.Bell@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Softw... | python |
""" QLayouted module. """
# ISC License
#
# Copyright (c) 2020–2022, Paul Wilhelm, M. Sc. <anfrage@paulwilhelm.de>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice app... | python |
#import json
def parse(command):
#split = json.loads(command)
#parsedCommand = split
return command
def main():
pass
if __name__ == "__main__":
main()
| python |
from happy_bittorrent.algorithms.torrent_manager import *
| python |
import pytest
import shutil
import zipfile
from pathlib import Path
from squirrel.settings import AddonInstallerSettings
from squirrel.addons import ZipAddon
from test_addon_install import test_addon_install_path
from test_addon_install import test_addon_backup_path
from test_addon_install import settings
from fixt... | python |
#!/usr/bin/python
import csv
import hashlib
import os
import sys
idx = 1
IGNORED_DIRECTORIES = {'.git', '.svn'}
def walk(version_root, app, version):
if type(version) == type(bytes):
version = version.decode("utf8")
if version in IGNORED_DIRECTORIES:
return
global idx
print('av %d %s... | python |
import logging
from pathlib import Path
import whoosh
from whoosh import qparser
from whoosh.filedb.filestore import FileStorage
from whoosh.index import EmptyIndexError
from whoosh.query import Every
from django.conf import settings
from mayan.apps.common.utils import any_to_bool, parse_range
from mayan.apps.lock_m... | python |
from __future__ import absolute_import
# Copyright (c) 2010-2018 openpyxl
from collections import defaultdict
class BoundDictionary(defaultdict):
"""
A default dictionary where elements are tightly coupled.
The factory method is responsible for binding the parent object to the child.
If a reference... | python |
import os
import random
import numpy as np
import pickle as pkl
import networkx as nx
import scipy.sparse as sp
from utils import loadWord2Vec
from math import log
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from sklearn im... | python |
# Clase 4. Curso Píldoras Informáticas.
print(5 + 6)
print(10 % 3)
print(5 ** 3)
print(9 / 2)
print(9 // 2)
Nombre = 5
print(type(Nombre))
Nombre = 5.4
print(type(Nombre))
Nombre = "John"
print(type(Nombre))
Mensaje = """ Esto es un
mensaje utilizando comilla
triple. Sirve para da... | python |
#
# @lc app=leetcode.cn id=382 lang=python3
#
# [382] 链表随机节点
#
# https://leetcode-cn.com/problems/linked-list-random-node/description/
#
# algorithms
# Medium (57.03%)
# Likes: 66
# Dislikes: 0
# Total Accepted: 6K
# Total Submissions: 10.6K
# Testcase Example: '["Solution","getRandom"]\n[[[1,2,3]],[]]'
#
# 给定一个... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.