text string | size int64 | token_count int64 |
|---|---|---|
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""
"""
__version__ = "$Id$"
#end_pymotw_header
import struct
import binascii
s = struct.Struct('I 2s f')
values = (1, 'ab', 2.7)
print 'Original:', values
print
print 'ctypes string buffer'
import ctypes
b = ctypes.... | 716 | 311 |
import pytest
from datetime import datetime
import pytz
from datacube_ows.ows_configuration import OWSProductLayer, TIMERES_RAW, TIMERES_MON, TIMERES_YR
def dummy_timeres_layer(time_res):
prod = product_layer = OWSProductLayer.__new__(OWSProductLayer)
prod.time_resolution = time_res
return prod
class Th... | 2,890 | 1,176 |
from .utils import to_float
from .enums import *
import regex
import sys
from itertools import zip_longest
from collections import defaultdict
class Bool:
@classmethod
def convert(cls, parser, value):
value = parser.get_macro(value)
if isinstance(value, bool):
return value
... | 8,846 | 2,536 |
""" This library supports the TI INA233 current and power monitor
with a Raspberry PI using SMBus/I2C.
By scottvr for 1SimplePhone.com
"""
from smbus2 import SMBus
class INA233:
CLEAR_FAULTS = 0x03
RESTORE_DEFAULT_ALL = 0x12
CAPABILITY = 0x19
IOUT_OC_WARN_LIMIT = 0x4A
VI... | 8,299 | 3,305 |
from rest_framework import serializers
from trades.models import Sell
class SellBaseModelSerializer(serializers.ModelSerializer):
username = serializers.CharField(
source="user.username",
)
class Meta:
model = Sell
fields = (
'pk',
'title',
... | 530 | 134 |
from flask import Flask
from flask_caching import Cache
from prometheus_flask_exporter import PrometheusMetrics
import pandas
import sys
import numpy
## Set up Flask application, attach extensions, and load configuration
def create_app(debug=False):
# pandas debug options
pandas.set_option('display.max_rows',... | 988 | 289 |
import numpy as np
import collections
try:
from scipy.stats import scoreatpercentile
except:
# in case no scipy
scoreatpercentile = False
def _confidence_interval_1d(A, alpha=.05, metric=np.mean, numResamples=10000, interpolate=True):
"""Calculates bootstrap confidence interval along one dimensional ar... | 3,484 | 1,018 |
import datetime
import os
from .models import Log, LogType
from .settings import DEBUG, DIR_DATA, DIR_DATA_DEBUG, DIR_DATA_IMAGES, DIR_DATA_PEOPLE, DIR_DATA_LOG
"""
Writes information about error that occured (like name or image could not be extracted).
@param at: The name of function that this error occured in
@p... | 806 | 279 |
"""
Day 5 challenge
"""
import attr
def solution_part_one(arg):
instructions = arg[:]
n = 0
pos = 0
while pos < len(instructions):
idx = pos
pos += instructions[idx]
instructions[idx] += 1
n += 1
return n
def solution_part_two(arg):
instructions = arg[:]
... | 14,327 | 6,838 |
#!/usr/bin/env python
# This Python file uses the following encoding: utf-8
import logging.config
import signal
import sys
import time
from pathlib import Path
import click
import pygame
from twitchchat import twitch_chat
from .config import get_config, logging_config
from .display import TwitchChatDisplay
logger =... | 2,091 | 611 |
import typing
from typing import Optional, Callable, Iterable, Iterator, Dict, Union
import dataclasses
import argparse
from functools import partial
import yaml
import os
__all__ = [
'confclass',
'confparam'
]
# A sentinel object to detect if a parameter is supplied or not.
# Use an empty class to give it ... | 19,440 | 5,779 |
from functools import lru_cache
from flask import Flask
from flask.ctx import RequestContext
from .config import Option
from .ctx import RequestContextWithSamStatic
from .helper import set_samstatic_default_parm
class FlaskWithSamStatic(Flask):
def __init__(self, *Flask_args, **Flask_kwargs):
super().__i... | 2,469 | 755 |
import time
from deploy.support import Client
class AutoScaling:
def __init__(self, state_file_content):
self.auto_scaling_client = Client.auto_scaling()
self.state_file_content = state_file_content
def enter_standby(self, instances_ids, green_blue):
if not self.state_file_content[g... | 3,334 | 996 |
from django.shortcuts import render, get_object_or_404, get_list_or_404
from django.db.models import Count, Avg, Max, Min
from ts.models import *
from .models import SurveyQuestion, SurveyQuestionChoice, SurveyResponse
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from fpdf import FPDF
cl... | 4,594 | 1,521 |
# -*- coding: utf-8 -*-
"""The Android WebViewCache database event formatter."""
from __future__ import unicode_literals
from plaso.formatters import interface
from plaso.formatters import manager
# TODO: move to android_webview.py.
class AndroidWebViewCacheFormatter(interface.ConditionalEventFormatter):
"""Forma... | 690 | 221 |
from output.models.nist_data.list_pkg.language.schema_instance.nistschema_sv_iv_list_language_length_4_xsd.nistschema_sv_iv_list_language_length_4 import NistschemaSvIvListLanguageLength4
__all__ = [
"NistschemaSvIvListLanguageLength4",
]
| 244 | 91 |
from django.urls import path, re_path
app_name = 'chat'
urlpatterns = [
]
| 78 | 32 |
# Kornpob Bhirombhakdi
# kbhirombhakdi@stsci.edu
import numpy as np
from scipy.interpolate import interp2d
import copy
class GrismApCorr:
"""
GrismApCorr is a class containing tables for aperture correction (i.e., apcorr = f(wavelength, apsize)) in aXe reduction. These tables are from ISRs. Interpolaton model... | 10,556 | 4,336 |
print("Starting Interceptor imports... ")
import sys
import socket
from multiprocessing import Manager, Process
from re import search, sub
from os import getcwd
import io
import pyshark
import pem
from pyshark.capture.capture import Capture
from pyshark.capture.live_capture import LiveCapture
from pyshark.packet.pack... | 15,051 | 4,798 |
"""Define information about the octoprint server"""
class OctoprintServerInfo:
"""Current job information"""
def __init__(self, raw: dict):
self._raw = raw
@property
def safe_mode(self) -> str or None:
return self._raw.get("safemode")
@property
def version(self) -> str:
... | 354 | 111 |
from django.utils.translation import ugettext_lazy as _
NONE = 'None'
UNIFICATION = 'UNIF'
PROJECTION = 'PROJ'
__tuple_list = ((UNIFICATION, _(UNIFICATION)), (PROJECTION, _(PROJECTION)), (NONE, _(NONE)),)
def as_tuple_list():
return __tuple_list
def get_from(id_enum):
for k, v in __tuple_list:
if ... | 538 | 217 |
from music21 import interval, pitch
def transpose_piece(piece, key):
k = piece.analyze('key')
if k.tonicPitchNameWithCase.islower():
return None
i = interval.Interval(k.tonic, pitch.Pitch(key))
new_piece = piece.transpose(i)
return new_piece
def flatten(l):
return [item for sublist ... | 348 | 125 |
# Copyright 2018 Dimitrios Milios, Raffaello Camoriano,
# Pietro Michiardi,Lorenzo Rosasco, Maurizio Filippone
# 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... | 1,932 | 687 |
#!/usr/bin/python3
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | 4,559 | 1,455 |
#!/usr/bin/env python
#
# Protein Engineering Analysis Tool DataBase (PEATDB)
# Copyright (C) 2010 Damien Farrell & Jens Erik Nielsen
#
# 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 ver... | 32,153 | 10,535 |
from netCDF4 import Dataset as dst
import numpy as np
from matplotlib import pyplot as plt
tempnc = dst("../air.mon.mean.nc", mode='r')
zonalnc = dst("../uwnd.mon.mean.nc", mode='r')
#Datasets downloaded 21 Aug 2020
#Time length- 871 ==> 871/12 --> 7/12
def slice_per(source, step):
return [source[i::step] for i in ... | 1,472 | 672 |
from __future__ import annotations
from unittest import mock
import pytest
import babi.buf
from babi.buf import Buf
def test_buf_truthiness():
assert bool(Buf([])) is False
assert bool(Buf(['a', 'b'])) is True
def test_buf_repr():
ret = repr(Buf(['a', 'b', 'c']))
assert ret == "Buf(['a', 'b', 'c'... | 4,609 | 1,854 |
import gc2
gcat = gc2.Gcat()
gcat.checkCommands()
print gcat.pending_tasks
for task in gcat.pending_tasks:
gcat.sendEmail('daskjdajhdagdjhsagdsahdsgajdgashdfaghdasfdhas', task['task_id'])
gcat.delete_pending_task(task['task_id'])
| 236 | 105 |
import networkx as nx
import random, pickle, string
from src.util.gen_files import *
import threading
import time
from src.net.topology import NetTopology
from src.algorithm import *
import os, sys
from random import randint, shuffle, sample
from src.util.utils import *
from src.algorithm.cache import *
from src.util.s... | 18,557 | 5,157 |
# -*- encoding: utf-8 -*-
'''
@File : lr_1d.py.py
@Modify Time @Author @Desciption
------------ ------- -----------
2021/7/5 22:51 Jonas None
'''
import numpy as np
import math
import matplotlib.pyplot as plt
from scipy.stats import norm
train_data = np.loadtxt("lin_reg_tr... | 4,475 | 1,925 |
#!/usr/bin/env
# -*- coding: utf-8 -*-
# Copyright (C) Victor M. Mendiola Lau - All Rights Reserved
# Unauthorized copying of this file, via any medium is strictly prohibited
# Proprietary and confidential
# Written by Victor M. Mendiola Lau <ryuzakyl@gmail.com>, March 2017
import pylab
import numpy as np
from dataset... | 1,252 | 438 |
"""
DCGAN Model to get Generator for DefenseGAN Baseline Implementation.
References:
https://www.coursera.org/learn/build-basic-generative-adversarial-networks-gans
https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html
"""
import torch
from torch import nn
class Generator(nn.Module):
"""Genera... | 3,487 | 1,289 |
# -*- coding: utf-8 -*-
"""
Created on Sat May 9 11:03:34 2020
@author: Abdeljalil
"""
import numpy as np
np.random.seed(10)
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import (RandomTreesEmbedding, Rando... | 3,713 | 1,621 |
import sys
import os
import argparse
import pickle
import ahocorasick
from utils.utils import check_file, ensure_dir
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
def _get_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--infile', type=str, default='../data/synonym', help... | 1,729 | 582 |
from flask_wtf import FlaskForm
from wtforms import StringField, SelectField, TextAreaField, SubmitField,PasswordField,ValidationError
from wtforms.validators import Required, Email, Length, EqualTo
from wtforms.validators import Required
class LoginForm(FlaskForm):
username = StringField("Username:", validators=... | 1,792 | 498 |
# Taken from https://github.com/openai/EPG/blob/master/epg/exploration.py
import numpy as np
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class HashingBonusEvaluator(object):
"""Hash-based count bonus for exploration.
Tang, H., Houthooft, R., Foote, D., Stooke, A., Chen... | 3,368 | 1,198 |
import re
import os
import random
import json
from datetime import datetime
from flask import Flask, render_template
app = Flask(__name__)
# using Flask's app.route decorator to map the URL route / to that function:
@app.route("/")
def home():
no_of_columns=4
image_path='static/index/'
image_list=os.lis... | 1,435 | 458 |
import curses
screen = curses.initscr()
curses.curs_set(0)
screen.addstr(2, 2, "Hello, I disabled the cursor!")
screen.refresh()
screen.getch()
curses.curs_set(1)
screen.addstr(2, 2, "And now it's back on.")
screen.refresh()
screen.getch()
curses.endwin() | 259 | 112 |
# -*- coding: utf-8 -*-
"""
@author: Jayeola Gbenga
"""
from sklearn.metrics import precision_score, recall_score, f1_score, roc_auc_score, accuracy_score, classification_report, confusion_matrix, average_precision_score
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRe... | 3,028 | 1,128 |
import os
import sys
_path = os.path.abspath(os.path.pardir)
if not _path in sys.path:
sys.path = [_path] + sys.path
from a2c.a2c_main import a2c_parser_options
from utils.launcher import main
def vtrace_parser_options(parser):
parser = a2c_parser_options(parser)
parser.add_argument('--c-hat', type=int,... | 1,096 | 377 |
from setuptools import find_packages, setup
from torchprofile import __version__
setup(
name='torchprofile',
version=__version__,
packages=find_packages(exclude=['examples']),
install_requires=[
'numpy>=1.14',
'torch>=1.4',
'torchvision>=0.4',
],
url='https://github.com... | 370 | 129 |
# The power of lambda is better shown when you use them as an anonymous function inside another function
double = lambda x: x * 2
print(double(10))
x = lambda a, b, c: a + b + c
print(x(5, 6, 2))
| 199 | 70 |
"""
File containing all of the run tags in the mlflow. namespace.
"""
MLFLOW_DATABRICKS_NOTEBOOK_ID = "mlflow.databricks.notebookID"
MLFLOW_DATABRICKS_NOTEBOOK_PATH = "mlflow.databricks.notebookPath"
MLFLOW_DATABRICKS_WEBAPP_URL = "mlflow.databricks.webappURL"
MLFLOW_DATABRICKS_RUN_URL = "mlflow.databricks.runURL"
MLFL... | 806 | 373 |
# -*- coding: utf-8 -*-
# * ********************************************************************* *
# * Copyright (C) 2020 by xmz *
# * ********************************************************************* *
"""
JSON Simple Config Tests - Parsing
"""
__author__ = "Marcin Ze... | 1,783 | 423 |
import numpy as np
import qcdanalysistools as tools
Nt = 6
data = np.random.randn(1000,Nt)
# for different analysis style set Jackknife,Bootstrap or Blocking
params = tools.analysis.BootstrapParams(
t_data_size = data.shape[0],
t_num_subdatasets = 1000,
t_with_blocking = True,
t_num_blocks = 50)
#par... | 740 | 306 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import math
import time
import ctypes
import socket
import urllib.request
from threading import Event, Thread
from socketserver import ThreadingMixIn
from http.server import BaseHTTPRequestHandler, HTTPServer
try:
import mss
except:
print('Inst... | 13,096 | 6,021 |
#input of num
num = int(input())
#initial value of reverse
reverse_num = 0
#conditon for entry using while loop
while(num>0):
#remainder of the given no
remainder = num % 10
# formula of the reverse
reverse_num = (reverse_num * 10) + remainder
#floor division of the num
num = num//10
#display th... | 351 | 127 |
from models import Job
from models import History
# class JobRepository:
# @staticmethod
# def get(user_id, task_id, doc_num):
# """ Query a user by name """
# return Job.query.filter_by(user_id=user_id, task_id=task_id, doc_num=doc_num).one()
# @staticmethod
# def create(user_id, task... | 2,079 | 669 |
# !/usr/bin/env python3
# -*- cosing: utf-8 -*-
if __name__ == "__main__":
with open("test.txt", "w", encoding="utf-8") as fileptr:
print(
"UTF-8 is a variable-width character encoding used for electronic communication.",
file=fileptr
)
print(
"UTF-8 is ... | 544 | 165 |
import django
from django.conf import settings
from django.contrib import admin
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from backend.views import IndexView
from rest_framework_jwt.views import obtain_jwt_token, verify_jwt_token
from apps.auth_api import views
router... | 1,153 | 383 |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applic... | 4,536 | 1,594 |
import scrappers
import scrappers.mixins
class ALJazeera(scrappers.mixins.RSSScrapper, scrappers.Scrapper):
"""AL Jazeera RSS feed scrapper.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def should_translate(self):
return False
def encoding(self):
... | 464 | 159 |
#!/usr/bin/env python
'''Instantiate the ENCODE ChIP-seq workflow'''
import sys
import logging
import re
import dxpy
import time
import pprint
EPILOG = '''Notes:
Examples:
# Build blank TF workflow from fastq to peaks
%(prog)s --target tf --name "ENCODE TF ChIP-seq (no reference)" --outf "/ChIP-seq/"
# ... | 49,028 | 15,562 |
# !/usr/bin/env python
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the BSD 3-Clause License (the "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
#
# Unless required by applica... | 5,893 | 2,038 |
ENGINE_PATH = './stockfish-11-linux/src/stockfish'
GAMES_FILENAME = 'lichess_username_2019-12-31.pgn'
DEFAULT_GAMES_ANALYSES_FILENAME = 'scores.pkl'
| 151 | 75 |
UINT64_MAX = 2 ** 64 - 1
UINT64_MIN = 0
INT64_MAX = 2 ** 63 - 1
INT64_MIN = -(2 ** 63)
UINT256_MAX = 2 ** 256 - 1
# Deployed to Ropsten revival on 2017-09-03 from commit f4f8dcbe791b7be8bc15475f79ad9cbbfe15435b
ROPSTEN_REGISTRY_ADDRESS = '0x66eea3159A01d134DD64Bfe36fde4bE9ED9c1695'
ROPSTEN_DISCOVERY_ADDRESS = '0x1E3... | 1,734 | 920 |
#!/usr/bin/env python3
import os
import base64
import argparse
import platform
bit = platform.architecture()[0]
def logo():
print("""
___ ____ _ _ _ _____
/ _ \ _ __ ___ / ___| (_) ___| | __ | ____|_ ____ __
| | | | '_ \ / _ \ | | | |/... | 12,760 | 5,624 |
# CITE http://people.csail.mit.edu/hubert/pyaudio/
import pyaudio, time
class Microphone(object):
"""Sets up an instance of a microphone recording stream using PyAudio."""
def __init__(self, format=None, channels=None, rate=None):
self.format = format or pyaudio.paInt16 # records in WAV format; 16-bit integers
s... | 2,550 | 944 |
import torch
from torch import nn
from pytorch_lightning import Callback
from pl_bolts.models.self_supervised.evaluator import SSLEvaluator
from sklearn.metrics import average_precision_score
from datasets.bigearthnet_datamodule import BigearthnetDataModule
class SSLOnlineEvaluator(Callback):
def __init__(self,... | 2,842 | 905 |
# Generated by Django 2.0 on 2017-12-14 15:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('check_in', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
name='lunch',
unique_together={('employee', 'date... | 342 | 120 |
import db
import ssl
import json
import uuid
from rsa import *
import base64
import antispam
import aes
import time
def message(obj, ip, data):
addr = db.data.find("data", "all")[0]['addr']
msg = data['message']
from_ = data['from']
title = data['title']
to = data['to']
id = data['id']
as_n... | 4,063 | 1,345 |
#This program monitors the 1K pot, sorb, and needle valve
#temperatures. If the temperatures are too high, the program
#will shut down the Keithley that controls the fixed impedance
#heater.
#Python 2 only
#TO DO: Python 3 compatibility
import thread
import time
import datetime
import traceback
import socket
import ... | 15,852 | 4,843 |
import json
import os
import csv
import re
import pickle
import collections
import subprocess
import spacy
import sdi_utils.gensolution as gs
import sdi_utils.set_logging as slog
import sdi_utils.textfield_parser as tfp
import sdi_utils.tprogress as tp
supported_languages = ['DE', 'EN', 'ES', 'FR']
lexicon_language... | 10,111 | 3,103 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------#
# OverRule: Overlap Estimation using Rule Sets #
# @Authors: Dennis Wei, Michael Oberst, #
# Fredrik D. Johansson #
# ----------------------------------------------#
import logging
import ... | 21,371 | 6,873 |
import inspect
import io
import itertools
import os
import struct
import sys
import math
from typing import Any, Optional, IO
from quo.accordance import (
DEFAULT_COLUMNS,
get_winterm_size,
bit_bytes,
isatty,
strip_ansi_colors,
)
from quo.color import ansi_color_codes, _a... | 16,463 | 4,829 |
# Name: Valeria Telles
# Date: 2 March 2020
# Program: biot_square.py
import numpy as np
import matplotlib.pyplot as plt
import time as time
from matplotlib.patches import Circle
def biot(Rvec, wire, I):
mu_4pi = 10
dB = np.zeros((len(wire), 3))
R = Rvec - wire
Rsqr = np.sum( R**2, axis = 1 )
... | 3,026 | 1,318 |
import os
import shutil
import numpy as np
from cv2 import imread
def get_captcha_data_iters(data_dir, test_size, target_data_dir, seed=5):
"""
获取测试图片
:param data_dir: 测试图片文件所在路径
:param test_size: 测试图片张数
:param target_data_dir: 将选出的测试图片放到该路径下
:param seed: 随机种子
:return: test_set
... | 1,612 | 645 |
import math
TICKETS = 250
STUDENTS = 100
MEAN = 2.4
SD = 2
MU = STUDENTS * MEAN
S = math.sqrt(100)*SD
def normal_distribution(x, mu, sd):
return 1/2*(1+math.erf((x-mu)/(sd*math.sqrt(2))))
print(round(normal_distribution(x=TICKETS, mu=MU, sd=S), 4)) | 262 | 137 |
"""empty message
Revision ID: a533873cebfc
Revises: 6a19b5a07897
Create Date: 2016-03-03 17:58:46.629869
"""
# revision identifiers, used by Alembic.
revision = 'a533873cebfc'
down_revision = '6a19b5a07897'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('notes', sa.Column('module_... | 448 | 208 |
import json
from kivy.app import App
from kivy.config import ConfigParser
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.uix.slider import Slider
from kivy.metrics import dp
from ... | 27,550 | 8,669 |
"""
Reads mean squared displacement for a list of trials and saves results to a yaml file
"""
import os
import yaml
from thermof.trajectory import Trajectory
from thermof.read import read_run_info
# --------------------------------------------------------------------------------------------------
main = ''
box1_atoms =... | 3,370 | 1,345 |
import cv2
import numpy as np
class LineFollowing(object):
def __init__(self):
self.polyLeft1 = 450
self.polyRight1 = 320
self.polyLeft2 = 500
self.polyRight2 = 320
self.ignore_mask_color = 255 # White color
def next_action(self, frame, slope=-1):
p_next_action =... | 4,230 | 1,442 |
from flask import Flask
from werkzeug.middleware.proxy_fix import ProxyFix
from .extensions import cache, db, limiter
current_version = "/api/v1/"
def create_app():
app = Flask(__name__)
app.config.from_pyfile("config.py")
db.init_app(app)
cache.init_app(app)
limiter.init_app(app)
from ap... | 760 | 245 |
def load_balance(arr):
"""
:type arr: List[int]
:rtype: bool
"""
if len(arr) < 5:
return False
p_sum = [arr[0]] # Calc prefix sum
for i in range(1, len(arr)):
p_sum.append(p_sum[-1]+arr[i])
low = 1
high = len(arr)-1
while low < high:
lower = p_sum[low-... | 748 | 288 |
'''
Author: Hongxiang Qi
Date: 22/06/2021
Description:
Write a recursive function called fib which accepts a number and returns the nth number in the
Fibonacci sequence. Recall that the Fibonacci sequence is the sequence of whole numbers 0,1,1,2,3,5,8,...
which starts with 0 and 1, and where every number thereafter is ... | 1,058 | 376 |
from abc import ABC, abstractmethod
class SegmentTreeNode(ABC):
@classmethod
@abstractmethod
def create_leaf(cls, start, end, value):
pass
@classmethod
@abstractmethod
def merge(cls, start, end, left, right):
pass
@property
@abstractmethod
def score(self):
... | 472 | 136 |
print("data structs baby!!")
# asdadadadadadad | 46 | 19 |
#!/usr/bin/env python2.6
import os
import sys
from pprint import pprint
from random import randint
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from stream import filter, map, ThreadPool, ProcessPool
## The test data
dataset = []
def alternating(n):
values = []
for i in range(1, n+1):
v... | 1,216 | 467 |
# Generated by Django 3.2.6 on 2021-08-11 11:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('catalog', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='cat',
old_name='liked_gifs',
new... | 502 | 172 |
from Upload import Upload
def config(parser):
parser.add_argument("--upload.method", dest="upload.method", help="Uploader method (default: none)", default='none', choices=['s3', 'none'])
parser.add_argument("--upload.remove_uploaded", dest="upload.remove_uploaded",help="Remove source files after successful up... | 398 | 110 |
from __future__ import division
import sys
import argparse
import torch
import os
import torch.nn as nn
import torch.optim as optim
import numpy as np
import json
import pickle
from sklearn.metrics import average_precision_score
from torch.utils.data import Dataset, DataLoader
from dataloader import Loader
from model ... | 10,977 | 3,874 |
class Video:
def __init__(self, id, title, description, thumb, url_video, category_id, date):
self._id = id
self._title = title
self._description = description
self._thumb = thumb
self._url_video = url_video
self._category_id = category_id
self._likes = 0
... | 1,404 | 426 |
from sagas.ofbiz.entities import OfEntity as e, oc, MetaEntity, all_entities
import resources_pb2 as res
import protobuf_utils
def build_field_index(ents):
field_index={}
for ent_name in ents:
ent=MetaEntity(ent_name)
if not oc.j.Utils.isViewEntity(ent.model):
for fld in ent.model.g... | 2,779 | 887 |
# Faça um programa para imprimir:
# 1
# 2 2
# 3 3 3
# .....
# n n n n n n ... n
def contador(n):
for numero in range(1,n):
string = str(numero) + " "
string *= numero
print(string)
contador(15) | 261 | 103 |
import pandas as pd
import numpy as np
def CC(test_scores,thr=0.5):
count = len([i for i in test_scores if i >= thr])
pos_prop = round(count/len(test_scores),2)
num_predict = count
return pos_prop
| 234 | 90 |
#coding:utf-8
import time,datetime
import os,os.path
import json
import traceback
from threading import Thread,Condition
from Queue import Queue
from collections import OrderedDict
from mantis.fundamental.utils.timeutils import timestamp_current, timestamp_to_str,datetime_to_timestamp,\
current_datetim... | 4,592 | 1,510 |
"""
Defines functions for running AI experiments.
"""
from __future__ import print_function
from ai.ai_app import AI_App
from ai.generation import Generation
from ai.utils import algorithm_id_to_generation_class, \
BEST_BRAIN_FILENAME, LOG_FILENAME, META_FILENAME
from collections import OrderedDict
from dateti... | 14,409 | 4,371 |
import unittest, json
import azure.functions as func
from ddt import ddt, data, unpack
from SpellingResolver.main import main
@ddt
class TestSpellingResolver(unittest.TestCase):
@data( ({"query":"anton marta 123",
"convertnumbers": True,
"convertsymbols": True,
"addit... | 2,655 | 844 |
def leiadinheiro(msg):
validade = False
while not validade:
entrada = str(input(msg)).replace(',', '.').strip()
if entrada.isalpha() or entrada == "":
print(f'Erro! {entrada} não é um preço válido')
else:
validade = True
return float(entrada)
def lei... | 603 | 185 |
import argparse
import struct
from echonetlite.interfaces import monitor
from echonetlite import middleware
from echonetlite.protocol import *
class Temperature(middleware.RemoteDevice):
def __init__(self, eoj, node_id):
super(Temperature, self).__init__(eoj=eoj)
self._node_id = node_id
mo... | 2,105 | 694 |
from pathlib import Path
import cfsiv_utils.filehandling as fh
def test_clean_filename_str():
data = ['qwerty~!@#$%^&*().ext', Path('qwerty~!@#$%^&().ext')]
reslt = fh.clean_filename_str(data[0])
assert data[1] == reslt
def test_new_name_if_exists():
testname = fh.new_name_if_exists(Path('README.m... | 369 | 152 |
"""Utils module for utilities."""
from ._config import get_config
from .utils import _compare_infos, _copy_info, _corr_vectors # noqa: F401
__all__ = ("get_config",)
| 169 | 62 |
NodeName=AdminControl.getNode()
def SetDB2Variables():
WFound=0
WVariables={"DB2UNIVERSAL_JDBC_DRIVER_NATIVEPATH" : "/??????????ult/etc/DB2JDBC",
"MQ_INSTALL_ROOT" : "/?????????",
"DB2UNIVERSAL_JDBC_DRIVER_PATH" : "/?????????lt/etc/DB2JDBC/classes"}
Node=AdminConfig.getid("/Node:"+Node... | 943 | 340 |
from telegram.ext import Updater, CommandHandler
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
import logging
from interpreter import *
import os
import numpy as np
def parse_result(count):
message=[]
for state in count.keys():
message.append(f"P(|{state}〉)={round(count[state]/100,2)... | 6,167 | 2,132 |
def copy_message(src, dst):
"""
Copy the contents of a src proto message to a destination proto message via string serialization
:param src: Source proto
:param dst: Destination proto
:return:
"""
dst.ParseFromString(src.SerializeToString())
return dst
| 285 | 76 |
import logging
logging.basicConfig(
format="[%(asctime)s] >>> %(levelname)s %(name)s: %(message)s", level=logging.INFO)
def GetLoger(Name):
return logging.getLogger(Name) | 180 | 67 |
def convert_wind_to_events(event_series, top_C, start_C):
flag = False
event_start = []
for i in range(len(event_series)):
if not flag:
if event_series[i] > top_C:
event_start.append(i)
flag = True
else:
if event_series[i] < top_C:
... | 859 | 296 |
"""
categories: Core
description: Raw f-strings are not supported
cause: MicroPython is optimised for code space.
workaround: Unknown
"""
rf"hello"
| 149 | 45 |
#!/usr/bin/env python
import rospy
import time
import sys
sys.path.append('/home/ubuntu/RedBoard')
import redboard
from std_msgs.msg import Int16MultiArray
# Servo values, 0 is centre
pan_value = 0
tilt_value = 0
def callback(data):
rospy.loginfo(rospy.get_caller_id() + 'RCVD: %s', data.data)
setservos... | 1,487 | 533 |
from collections import Counter
import operator
import weakref
from broadcasters.environment_score.environment_score_tuning import EnvironmentScoreTuning
import alarms
import clock
import gsi_handlers
import services
import sims4.log
import sims4.reload
logger = sims4.log.Logger('Environment Score')
with sims4.reload.p... | 10,943 | 3,188 |