content stringlengths 5 1.05M |
|---|
# Copyright (c) 2021 - present / Neuralmagic, Inc. 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 b... |
# -*- coding: utf-8 -*-
"""
Bundle of methods for handling images. Rather than manipulating specialized
operations in images methods in this module are used for loading, outputting
and format-converting methods, as well as color manipulation.
SUPPORTED FORMATS
see http://docs.opencv.org/2.4/modules/highgui/doc/readin... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 20 09:02:18 2019
@author: Andrea
"""
def add_frac(zaeler1, nenner1, zaeler2, nenner2):
"""Dieses Programm addiert 2 Brüche miteinander und kürzt sie mit ihrem größten gemeinsamen Teiler (ggt)"""
#Variablen einführen
zaeler=0
nennerg=0
ggt = 1
... |
#
# Demonstrates that the super-class implementation of an overridden method
# can be called in the same way as with normal objects.
#
from Foundation import *
N = 1
class MyObject (NSObject):
def init(self):
global N
if N == 1:
print "Calling super.init"
N = 0
... |
import jsonobject
import jsl
def jsl_field_to_jsonobject_property(prop: jsl.BaseField) -> jsonobject.JsonProperty:
if isinstance(prop, jsl.DateTimeField):
return jsonobject.DateTimeProperty(name=prop.name, required=prop.required)
if isinstance(prop, jsl.StringField):
return jsonobject.StringPr... |
import argparse
import pandas as pd
parser = argparse.ArgumentParser()
parser.add_argument(
'--data-train', type=str, default='./data/original/train.csv',
help='train data path')
parser.add_argument(
'--data-test', type=str, default='./data/original/test.csv',
help='test data path')
parser.add_argumen... |
from mlagents.tf_utils.tf import tf as tf # noqa
from mlagents.tf_utils.tf import set_warnings_enabled # noqa
|
# coding=utf-8
from os import path
from constantes import *
import pickle
from random import choice
from indexer import Indexer
class Zone:
def __init__(self, id_: str, creatures_id: list, level_range: tuple):
self.id = id_ # c'est l'id d'une subCarte
self.creatures_id = creatures_id
sel... |
from django.shortcuts import render_to_response, get_object_or_404, redirect, render
from django.core.paginator import Paginator
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse, Http404, FileResponse
from django.conf import settings
import datetime
from . import models
import ... |
import math
import random
from ..algorithm_common import AlgorithmCommon as AC
from ..algorithm_common import IAlgorithm
class Tabu(IAlgorithm):
def __init__(self,
individual_max,
epsilon=0.1,
tabu_list_size=100,
tabu_range_rate=0.1,
):
self.indivi... |
# SPDX-License-Identifier: Apache-2.0
import os
import sys
import unittest
import keras2onnx
import keras_contrib
import numpy as np
from keras2onnx import set_converter
from keras2onnx.proto import keras
from os.path import dirname, abspath
sys.path.insert(0, os.path.join(dirname(abspath(__file__)), '../../tests/'))
... |
import audio_dspy as adsp
_fs_ = 44100
_num_ = 1000
_dur_ = 1
class SweepsTimeSuite:
"""
Benchmarkng Suite for sweep functions
"""
def setup(self):
self.sweep = adsp.sweep_log(1, _fs_/2, _dur_, _fs_)
self.sweep2 = adsp.sweep_log(1, _fs_/2, _dur_, _fs_)
def time_log_sweep(self):
... |
import torch
import torch.nn as nn
from se3cnn.point.radial import CosineBasisModel
from e3_layer.persistent_point.data_hub import DataHub
from e3_layer.persistent_point.periodic_convolution import PeriodicConvolutionWithKernel
from e3_layer.persistent_point.gate import Gate
class EQLayer(nn.Module):
def __init... |
""" HealthDES - A python library to support discrete event simulation in health and social care """
import simpy
from .Routing import Activity_ID
class DecisionBase:
# TODO: Need to return a function which includes list of next activities
def set_next_activity(self, activity):
return self.get_next_a... |
import json
import time
import graphics
DEBUG = True
class GShape:
"""
A parent class that represents a shape. It is named GShape for "Graphical shape"
since "shape" is such a generic word.
"""
def __init__(self, win: object, name: str, channel: int, x: int, y: int, color: str):
"""
... |
# -*- coding: utf-8 -*-
"""PSF DECONVOLUTION MODULE
This module deconvolves a set of galaxy images with a known object-variant PSF.
:Author: Samuel Farrens <[email protected]>
"""
from __future__ import print_function
from builtins import range, zip
from scipy.linalg import norm
from modopt.math.stats impor... |
import os
import sys
import configparser
import matplotlib
matplotlib.use('Agg') # Don't try to use X forwarding for plots
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import pandas as pd
import numpy as np
from root_pandas import read_root
### Insert path to most rece... |
import os
import copy
import math
import numpy as np
import basis.robot_math as rm
import robot_sim._kinematics.jlchain as jl
import robot_sim.manipulators.manipulator_interface as mi
class IRB14050(mi.ManipulatorInterface):
def __init__(self, pos=np.zeros(3), rotmat=np.eye(3), homeconf=np.zeros(7), name='irb140... |
# -*- coding: utf-8 -*-
from collections import namedtuple
from inspect import isclass
attr_type_to_column = {
int: "ival",
float: "fval",
basestring: "tval",
str: "tval",
# TODO: add other python subtype of basestring.
bool: "bval",
}
_op_val_typecheck = {
"==": [basestring, int, float, ... |
is_valid = True
while is_valid:
password = int(input())
if password == 2002:
print("Acesso Permitido")
is_valid =False
else:
print("Senha Invalida")
|
import torch
from torch import nn
# import torch.nn.functional as F
from train.helpers import *
# inspired by fastai course
class BCE_Loss(nn.Module):
def __init__(self, n_classes, device):
super().__init__()
self.n_classes = n_classes
self.device = device
self.id2idx = {1: 0, 3: ... |
import pytest
from django.core.exceptions import ImproperlyConfigured
from esteid.constants import Languages
@pytest.mark.parametrize(
"lang_code, result",
[
*[(code.upper(), code) for code in Languages.ALL],
*[(code.lower(), code) for code in Languages.ALL],
*[(alpha2.upper(), code)... |
# https://oj.leetcode.com/problems/spiral-matrix-ii/
class Solution:
# @return a list of lists of integer
def generateMatrix(self, n):
matrix = [[0]*n for i in xrange(n)]
next = 1
for k in xrange(n/2):
for j in xrange(k, n-1-k):
matrix[k][j] = next
next += 1
for i in xrange(... |
#writing functions to be called from different notebooks, making the code easier to read
import os
import glob
import pandas as pd
#TODO creat a nice function that saves a file summarizing the data outputs as graphs from cellprofiler
#def DataCheckPlotting():
def ImportData_NUC_CYTO(cp_output_dir):
#use glob to p... |
# http://flask.pocoo.org/docs/1.0/api/#api
# $ export FLASK_APP=flask_demo.py
# $ export FLASK_ENV=development
# $ flask run
# $ flask run -h <ip> -p <port>
# $ python -m flask run
from flask import Flask, request, jsonify, abort
app = Flask(__name__)
@app.errorhandler(400)
def bad_json(error):
return 'Error ... |
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. 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 requir... |
import pandas as pd
import geojson as gj
import plotly.express as px
import urllib.request
import dash
# from dash import dcc
# from dash import html
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash(__name__)
server = app.server
# # # # # DATA # # # # # #
# loading dataframe
# l... |
import numpy as np
print('------------------Aufgabe 1-----------------------')
# strukturiertes Array mit 2 Spalten ( ID int32) und Produktpreis
my_type = [('ID', np.int32), ('Preis', np.float64)]
produkte = np.array([(12345, 670.89),
(34567, 18.99),
(78900, 250.00),
... |
import sed_eval
import utils
import pandas as pd
from sklearn.preprocessing import binarize, MultiLabelBinarizer
import sklearn.metrics as skmetrics
import numpy as np
def get_audio_tagging_df(df):
return df.groupby('filename')['event_label'].unique().reset_index()
def audio_tagging_results(reference, estimated... |
"""
Support for Meteobridge SmartEmbed
This component will read the local weatherstation data
and create Binary sensors for each type defined below.
For a full description, go here: https://github.com/briis/hass-mbweather
Author: Bjarne Riis
"""
import logging
from datetime import timedelta
impor... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import time
import random
from decimal import *
getcontext().prec = 30
def addDot(num):
"""Formats the number into a string and adds a '.' for every thousand (eg. 3000 -> 3.000)
Parameters
----------
num : int
integer number to format
Returns
-------... |
# Copyright (c) 2020 NVIDIA Corporation. All rights reserved.
# This work is licensed under the NVIDIA Source Code License - Non-commercial. Full
# text can be found in LICENSE.md
import sys, os
import numpy as np
import cv2
# This function is modeled off of P/R/F measure as described by Dave et al. (arXiv19)
def mul... |
# -*- coding: utf-8 -*-
"""Unit test package for talklocal_python."""
|
"""A wrapper class that will hold the column values and recreate a model instance when needed."""
class ModelWrapper:
def __init__(self, model_instance):
self._model_instance = model_instance
for key in self._model_instance.__table__.columns.keys():
this_val = getattr(self._model_inst... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 6 18:29:13 2020
@author: Goutam Dadhich
"""
import sys
INT_MAX = sys.maxsize
# print(INT_MAX)
# Finding Minimum Coins using Recursio
def FindMinCoins_rec(coins, n, amt):
if amt == 0:
return 0
if amt < 0:
return INT_MAX
count = INT... |
resp = 's'
cont = soma = 0
list = []
while resp == 's':
num = int(input('digite um número: '))
cont += 1
soma += num
list.append(num)
resp = input('Deseja continuar? [s/n]').lower().strip()
print(f'Você digitou {cont} números\n'
f'A média deles é {soma/cont}\n'
f'O maior número é o {max... |
import streamlit as st
from is_even_nn import *
st.set_page_config(layout="centered", page_icon="🤖", page_title="Is it even?")
st.title("IsEvenNN")
st.write("A neural network that predicts if a number is even!")
left, right = st.columns(2)
form = left.form("input")
number_input = form.text_input("Your number:")
s... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('estore', '0003_auto_20151029_0013'),
]
operations = [
migrations.RenameField(
model_name='event',
ol... |
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe.utils import flt, time_diff_in_hours, get_datetime, getdate, today, cint, add_days, get_link_to_form
from frappe import _
from frappe.utils.xlsxutils import make_xlsx
import json
@frappe.whitelist()
def send_s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AnttechDataServiceBlockchainAccountQueryModel(object):
def __init__(self):
self._account_hash = None
self._account_status = None
self._at_tenant_name = None
self._... |
def minimum_bribes(q):
q = [p - 1 for p in q]
bribes = 0
for i, p in enumerate(q):
if p - i > 2:
return None
for j in range(max(p - 1, 0), i):
if q[j] > p:
bribes += 1
return bribes
|
import collections
import math
import logging
import torch
import copy
import numpy as np
from naslib.optimizers.core.metaclasses import MetaOptimizer
from naslib.search_spaces.core.query_metrics import Metric
from naslib.utils.utils import AttrDict, count_parameters_in_MB
from naslib.utils.logging import log_every_... |
# -*- coding: utf-8 -*-
import os
import json
import unicodedata
from sqlalchemy import func
from cornice import Service
from cornice.resource import resource
from .models import AdminZoneFinance, DBSession, AdminZone, Stats as StatsModel, ADMIN_LEVEL_CITY
from .maps import timemap_registry, MAPS_CONFIG
city_search =... |
import argparse
import json
import logging
import os
import random
import time
import uuid
from kafka import KafkaProducer
CARD_NO= [
"2345796540876432", "7766554433221198", "9856342187654321", "7777744433667790"
, "6538764975321765", "086543226688908"]
TXN_CTRY = [
'SG',
'TH',
'PH',
... |
# Python Assert
def attendance(days):
assert len(days) !=0, "Days should not be empty"
return 8 * days[0]
print("Total number of hours is ",attendance([20]))
print("Total number of hours is ",attendance([]))
# Output
# Traceback (most recent call last):
# File "py-assert.py", line 8, in <module>
# print... |
"""
This Python script executes a series of Python scripts and subroutines that prepare input public use census geography and surname data and constructs the surname-only, georgraphy-only, and BISG proxies for race and ethnicity.
This file is set up to execute the proxy building code sequence on a set of ficitious dat... |
from question_model import Question
from data import question_data
from quiz_brain import QuizBrain
question_bank = []
for x in question_data:
next_question = Question(x['question'], x['correct_answer'])
question_bank.append(next_question)
quiz = QuizBrain(question_bank)
while quiz.has_next():
user_input ... |
# -*- coding: utf-8 -*-
# Program Name: print_cs.py
# Anthony Waldsmith
# 6/13/2016
# Python Version 2.7
# Description: Program to print "CS" ASCII-PUNK style
# Must import print_function because I didn't update to Python 3.x yet.
from __future__ import print_function
# Imports extra utilities that I used to spice up... |
from colorama import init, Fore, Style
class Colors:
def __init__(self):
init()
self.GREEN = Fore.LIGHTGREEN_EX
self.YELLOW = Fore.LIGHTYELLOW_EX
self.RED = Fore.LIGHTRED_EX
self.ENDC = Style.RESET_ALL
class Action:
SCRAPE = 'scrape'
GENERATE = 'generate'
... |
#!/usr/bin/env python3
import dataclasses
import pathlib
import typing
import unittest
from unittest.mock import MagicMock, Mock, patch
import numpy
import torch
import bunkai
import bunkai.algorithm.lbd.predict
from bunkai.algorithm.bunkai_sbd.annotator import MorphAnnotatorJanome
from bunkai.base.annotation import ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:/Users/lukas/PycharmProjects/zd_inventory/ui/zd_mail.ui'
#
# Created by: PyQt5 UI code generator 5.15.6
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you kno... |
# coding=utf-8
# Copyright 2018-2020 EVA
#
# 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 ... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import re
import string
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import PassiveAggressiveClassifier
from flask import Flask, request, redirect, url_for, flash, jsonify
import numpy as np
import json
impor... |
import copy
from dataclasses import replace
from typing import Callable, Sequence, Tuple
import numpy as np
import pytest
from .._evaluation import Evaluation, Quantity
from ..evaluators import SegmentationEvaluator
def get_random_prediction_and_mask(
image_size: Tuple[int, int, int], num_classes: int
) -> Tupl... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
..
---------------------------------------------------------------------
___ __ __ __ ___
/ | \ | \ | \ / the automatic
\__ |__/ |__/ |___| \__ annotation and
\ | | ... |
import numpy as np
class DataClusterAnalysis:
def __init__(self):
pass
def _getNumberOfPointsInCluster(self, data,clusterWidth):
'''
take the first element in the data set and get the next n data points that
are within the cluster. returns n
'''
count = 1;
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-12-09 13:05
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('webui', '0006_dataset_name'),
]
operations = [
migrations.AddField(
... |
import pytest
from JDI.jdi_assert.testing.assertion import Assert
from tests.jdi_uitests_webtests.main.enums.preconditions import Preconditions
from tests.jdi_uitests_webtests.main.page_objects.epam_jdi_site import EpamJDISite
from tests.jdi_uitests_webtests.test.init_tests import InitTests
@pytest.mark.web
class Sm... |
"""A set of classes used to represent Mods in memory."""
# Disable warnings about 'too few class methods'
# pylint: disable=R0903
from typing import List, NamedTuple, Type, Union
def yaml_serializable(cls: Type[NamedTuple]):
"""Make a NamedTuple serializable by PyYAML."""
class Wrapper(object):
"""P... |
"""Test the pyscript component."""
from ast import literal_eval
import asyncio
from datetime import datetime as dt
import time
import homeassistant.components.pyscript.trigger as trigger
from homeassistant.const import EVENT_HOMEASSISTANT_STARTED, EVENT_STATE_CHANGED
from homeassistant.setup import async_setup_compone... |
from django.urls import path, include
from django.contrib.auth import views as auth_views
from . import views
app_name = "users"
urlpatterns = [
path("register", views.register, name="register"),
path("update_profile", views.update_profile, name="update_profile")
]
|
import pandas as pd
from pandas.core.frame import DataFrame
from typing import Tuple
def get_user_secondary_df(name: str, value_column: str) -> DataFrame:
"""
Args:
name (str):
value_column (str):
Returns:
DataFrame:
"""
df = pd.read_csv("data/user" + name + ".csv", enco... |
#!/usr/bin/env python
# Parse the options the user provided from the command line
def option_parser():
parser = OptionParser()
parser.add_option("-v", action="store_true", dest="verbose", default=False)
parser.add_option("--inplace", action="store_true", dest="inplace", default=False)
parser.add_option(... |
import logging
from PySide2 import QtWidgets
from channel_box_plus import widgets
from channel_box_plus import utils
log = logging.getLogger(__name__)
def execute():
"""
Add the search interface and colouring functionality to Maya's main
channel box. If channelBoxPlus is already installed a RuntimeErro... |
word = "banana"
check = "a"
print(word.count(check))
|
import csv
from django.core.management.base import BaseCommand
from gsr_booking.models import GSR
class Command(BaseCommand):
def handle(self, *args, **kwargs):
with open("gsr_booking/data/gsr_data.csv") as data:
reader = csv.reader(data)
for i, row in enumerate(reader):
... |
import pr2hub
import discord
import math
import re
from discord.ext import commands
from cogs.utils import exp
class PR2():
def __init__(self, bot):
self.bot = bot
self.quoted = re.compile(r"\"(.+)\"")
@commands.command(description="returns player information",
aliases=[... |
"""
Helper functions for parsing python code, as required by ScriptTask
"""
import ast
from itertools import chain
import re
import sys
from typing import Container, Iterator, List, Tuple
from ..exceptions import ScriptParseError
_BUILTINS_WHITELIST = {
"abs",
"all",
"any",
"ascii",
"bin",
"c... |
from flask import Flask, render_template_string
from sucuri import rendering
app = Flask(__name__)
@app.route("/")
def index():
template = rendering.template('template.suc',{"text": "Hello! I'm here!", "var":[1, 2, 3, 4]})
return render_template_string(template) |
# Author: Qianru Zhou
# Email: [email protected]
# Magic, do not touch!!
""" generate immature detector, a file with random 96 bits binary strings
"""
from random import randint
def reduce_duplicate(inputPath, outputPath):
""" delete the duplicate strings in the log for efficiency
"""
patterns = []
with open(in... |
DEEPREACH_DIR = '/'.join(__file__.split('/')[:-2])
environment = f'{DEEPREACH_DIR}/environment.yml'
not_installed = f'{DEEPREACH_DIR}/change_env_file/packages_not_found.txt'
not_in_osx = f'{DEEPREACH_DIR}/change_env_file/not_in_osx.txt'
desired_env = f'{DEEPREACH_DIR}/new_environment.yml'
def remove_build(s: str) -> ... |
#-*-coding:utf-8-*-
import numpy as np
import pandas as pd
import time
from bayes_smoothing import *
from sklearn.preprocessing import LabelEncoder
import copy
def roll_browse_fetch(df, column_list):
print("==========================roll_browse_fetch ing==============================")
df = df.sort('context_... |
#!/usr/bin/env python3
# from: http://sam.aiki.info/b/google-images.py
# requires: selenium, chromium-driver, retry
#
# $ pip install webdriver_manager
# $ pip install selenium retry
# $ brew install chromedriver
# install google.com/chrome
from selenium import webdriver
from webdriver_manager.chrome import ChromeDr... |
import json
from asynctest import mock as async_mock, TestCase as AsyncTestCase
from .....cache.base import BaseCache
from .....cache.in_memory import InMemoryCache
from .....connections.models.conn_record import ConnRecord
from .....connections.models.connection_target import ConnectionTarget
from .....connections.m... |
#
# 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... |
# -*- coding: utf-8 -*-
import re
import logging
import warnings
from scrapy import signals
from scrapy.http import Request
from scrapy.utils.httpobj import urlparse_cached
logger = logging.getLogger(__name__)
class DisallowDomainMiddleware(object):
def __init__(self, stats): # type: ignore
self.stats =... |
import unittest
from onedrive_client import od_stringutils
class TestStringUtils(unittest.TestCase):
INCREMENTED_FILE_NAMES = (('Folder', 'Folder 1'), ('Folder 1', 'Folder 2'),
('file.txt', 'file 1.txt'), ('file 1.txt', 'file 2.txt'),
('Folder 0', 'Fol... |
from tf_bodypix.utils.v4l2 import VideoLoopbackImageSink
from .api import T_OutputSink
def get_v4l2_output_sink(device_name: str, **__) -> T_OutputSink:
return VideoLoopbackImageSink(device_name)
OUTPUT_SINK_FACTORY = get_v4l2_output_sink
|
# Copyright 2015 Google Inc. 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 a... |
import numpy as np
import pandas as pd
import pytest
from pandas.testing import assert_frame_equal
def test_str_split():
"Test wrapper for Pandas ``.str.split()`` method."
df = pd.DataFrame(
{"text": ["a_b_c", "c_d_e", np.nan, "f_g_h"], "numbers": range(1, 5)}
)
expected = df.copy()
expe... |
apiAttachAvailable = u'API verf\xfcgbar'
apiAttachNotAvailable = u'Nicht verf\xfcgbar'
apiAttachPendingAuthorization = u'Ausstehende Genehmigungsanfrage'
apiAttachRefused = u'Abgelehnt'
apiAttachSuccess = u'Erfolg'
apiAttachUnknown = u'Unbekannt'
budDeletedFriend = u'Aus Freundesliste gel\xf6scht'
budFriend = u'Freund'... |
# 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, ... |
# Generated by Django 3.0.3 on 2020-10-13 10:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('modelzoo', '0021_auto_20201012_1423'),
]
operations = [
migrations.AddField(
model_name='model',
name='github',
... |
"""
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
"""
def addTwoNumbers(l1, l2):
pass
|
from setuptools import setup
setup(
name='get-bittrex-tick',
version='1.0',
description='A useful module',
author='Shadowist',
author_email='[email protected]',
packages=['.'], #same as name
install_requires=["requests"], #external packages as dependencies
) |
import logging
import tempfile
import time
from ocs_ci.ocs.ui.views import locators, osd_sizes
from ocs_ci.ocs.ui.base_ui import PageNavigator
from ocs_ci.utility.utils import get_ocp_version, TimeoutSampler, run_cmd
from ocs_ci.utility import templating
from ocs_ci.ocs.exceptions import TimeoutExpiredError
from ocs_c... |
'''Spark Configuration
In this file we define the key configuration parameters for submitting Spark jobs. Spark can be run
in a variety of deployment contexts. See the Spark documentation at
https://spark.apache.org/docs/latest/submitting-applications.html for a more in-depth summary of
Spark deployment contexts and c... |
from .models import StreamItem
class ManyToManyDatabaseBackend(object):
def add_stream_item(self, users, content, created_at):
item = StreamItem.objects.create(content=content, created_at=created_at)
item.users.add(*[user.pk for user in users])
def get_stream_items(self, user):
retur... |
# Separa el texto enviado por el usuario en la forma "comando resto"
# Ejemplo:
# "/comando ASDASd"
# regresa ("comando","ASDASd")
#
# "/comando@MemesBot Test - Test , Red"
# regresa ("comando","Test - Test , Red")
#
# "yao ming"
# regresa ("yao ming","")
def extraer_comando(text):
if not text: return ("","")
... |
import traceback
import unittest
from unittest.mock import Mock, patch
from tests import resources
from pyfootball.models.team import Team
from pyfootball.models.fixture import Fixture
from pyfootball.models.player import Player
class TestTeam(unittest.TestCase):
def test_init(self):
try:
Tea... |
def isStringCharsUnique(incoming_string):
for i in range(0, len(incoming_string)):
for j in range(0, len(incoming_string)):
if (i != j) and (incoming_string[i] == incoming_string[j]):
print('Match Found - Positions: ' + str(i + 1) + ' & ' + str(j + 1)) # "+ 1" to avoid 0 position... |
# Add parent folder to path
import sys, os
sys.path.insert(1, os.path.join(sys.path[0], '..'))
import unittest
import numpy as np
from time import perf_counter
from src.Equations.TaitEOS import TaitEOS, TaitEOS_B, TaitEOS_co
class test_numba_taiteos(unittest.TestCase):
def test_vec(self):
rhos = np.linspa... |
# -*- coding: utf8 -*-
import sys
# thank_you 関数を作成する
def thank_you() -> None:
print("""
ありがとう!(∩´∀`)∩
""")
q = input("どういたしまして!")
if q:
sys.exit()
def main() -> None:
thank_you()
if __name__ == '__main__':
main()
|
# Generated by Django 2.2.16 on 2020-10-21 13:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('integration', '0004_gaenotpserversettings'),
]
operations = [
migrations.AddField(
model_name='gaenotpserversettings',
... |
from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq_result_groups import GroupsResultIqProtocolEntity
from ..structs import Group
class ListGroupsResultIqProtocolEntity(GroupsResultIqProtocolEntity):
'''
<iq type="result" from="g.us" id="{{IQ_ID}}">
<group s_t="{{SUBJECT_TIME}}" creatio... |
"""
Utils used by hkp module.
"""
import subprocess
import sys
import os
__all__ = ['cached_property']
class _Missing(object):
def __repr__(self):
return 'no value'
def __reduce__(self):
return '_missing'
_missing = _Missing()
class cached_property(object):
"""A decorator that conve... |
#!/usr/bin/env python3
# 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 errno
import io
import os
import pickle
import select
import stat
import subprocess
import sys
from contextlib i... |
import matplotlib.pyplot as plt
import numpy as np
def record_losses(input):
f=open(input,encoding='utf-8')
re_list=[]
for line in f:
li_str=str(line)
if li_str.find("losses")!=-1:
id=li_str.find("losses")
re_list.append(float(li_str[id+8:-1]))
print(re_list)
... |
import requests
import random
import json
import hashlib
import hmac
import urllib
import uuid
import time
import copy
import math
import sys
from datetime import datetime
import calendar
import os
# Turn off InsecureRequestWarning
from requests.packages.urllib3.exceptions import InsecureRequestWarni... |
# Hello World program in Python
print("Example of Python Tuples\n")
# Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
# You can access tuple items by referring to the index number:
# Return the item in position 1:
print(thistuple[1])
# You can loop through the tuple items by using a for l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.