text string | size int64 | token_count int64 |
|---|---|---|
"""
Geological features
"""
import logging
import numpy as np
logger = logging.getLogger(__name__)
class LambdaGeologicalFeature:
def __init__(self,function = None,name = 'unnamed_lambda', gradient_function = None, model = None):
self.function = function
self.name = name
self.gradient_fu... | 1,185 | 373 |
from typing import Set
import utils
data = utils.getLinesFromFile("day8.input")
# data = ['be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe','edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc','fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdg... | 2,137 | 1,084 |
num1 = 5
num2 = 4
max_num = max(num1,num2)
print("Max between {0} and {1} is {2}".format(num1,num2,max_num)) | 108 | 54 |
# ANOVA example from Sokal & Rohlf (fourth ed.), Box 11.1
import numpy as np
from anova import anova_twoway_balanced
consumption = np.array(
[[[709, 679, 699],
[592, 538, 476]],
[[657, 594, 677],
[508, 505, 539]]])
result = anova_twoway_balanced(consumption)
print(result)
| 298 | 147 |
""" Optimizers class """
import torch
import torch.optim as optim
from torch.nn.utils import clip_grad_norm_
import operator
import functools
from copy import copy
from math import sqrt
def build_torch_optimizer(model, opt):
params = [p for p in model.parameters() if p.requires_grad]
if opt.optim == 'sgd':
... | 4,951 | 1,584 |
import inspect
class MetaComposition(type):
"""Overwrites a target method to behave calling same-type superclasses' implementation orderly"""
def __new__(meta, name, bases, attr, __func__='__call__'):
attr['__run__'] = attr[__func__]
attr[__func__] = meta.__run__
return super(MetaComposition, meta).__new__(... | 3,019 | 1,182 |
from django.contrib import admin
from .models import Product
from .forms import CreateProductForm
# Improves upon the basic admin page functionality by
# displaying the database as a formatted table
class CreateProductAdmin(admin.ModelAdmin):
list_display = ["product_name", "product_quantity"]
form = Creat... | 384 | 96 |
#!/usr/bin/python3
import unittest
from unittest.mock import patch
from keyman_config.gnome_keyboards_util import is_gnome_shell, _reset_gnome_shell
class GnomeKeyboardsUtilTests(unittest.TestCase):
def setUp(self):
_reset_gnome_shell()
@patch('keyman_config.os.system')
def test_IsGnomeShell_Run... | 761 | 257 |
"""This contains all of the forms used by the Users application."""
# Django Imports
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.contrib.auth import forms, get_user_model
from django.contrib.auth.forms import UserChangeForm
from django.contrib.auth.models import Group
from django.core.e... | 4,059 | 1,135 |
import numpy as np
import scipy.linalg as la
from statsmodels.tsa.api import SimpleExpSmoothing, Holt
"""
@desc: From activity probe, calculate spike patterns
"""
def getSpikesFromActivity(self, activityProbes):
# Get number of probes (equals number of used cores)
numProbes = np.shape(activityProbes)[0]
# ... | 5,119 | 1,689 |
lanche = ('Hamburguer', 'Suco', 'Pizza', 'Pudim')
for c in range(0, len(lanche)):
print(lanche[c]) | 102 | 45 |
SOAP_HOST = '127.0.0.1'
SOAP_PORT = 8083
| 43 | 31 |
from visualize import pprint
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def __repr__(self):
ptr = id(self)
ret = f'{ptr}:'
if self.left:
ret = f'{ret} {self.left.val}'
else:
ret = f'{ret... | 6,429 | 1,875 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-12-02 20:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0006_auto_20171126_1433'),
]
operations = [
migrations.AddField(
... | 560 | 207 |
import unittest
from hamcrest import equal_to, assert_that
from structural.adapter.adapter import InvokerTargetAdapter
from structural.adapter.target import InvokerTarget
def target_invoker(target: InvokerTarget):
return target.request()
class TestClient(unittest.TestCase):
def test(self):
target =... | 424 | 117 |
import re
def reverse_str(string):
string = string.strip()
string = re.sub("\s+", " ", string)
result = [word[::-1] for word in string[::-1].split(" ")]
return " ".join(result)
# "degree CS":
print reverse_str(" CS degree")
print reverse_str("CS degree")
print reverse_str("CS degree ")
print re... | 350 | 120 |
"""Unit test package for Design."""
| 36 | 10 |
# Generated by Django 2.1.3 on 2019-05-05 07:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0011_remove_team_position'),
]
operations = [
migrations.AddField(
model_name='team',
name='title',
... | 405 | 136 |
from ..annotation.attribute import Attribute
from ..annotation.relation import Relation
from .knowledge_graph_edge import KnowledgeGraphEdge
from ontology_learning.utils.hash import get_hash
class KnowledgeGraphNode(object):
def __init__(self, label, type_):
self.label = " ".join(sorted(set(label.split(" "))))
se... | 1,926 | 705 |
from neopixel import Color
import time
class ShowRainbowAllLEDs():
def __init__(self, strip, config):
self.strip = strip
self.configuration = config
def wheel(self, pos):
"""Generate rainbow colors across 0-255 positions."""
if pos < 85:
return Color(pos * 3, 255... | 1,023 | 329 |
'''Problem 29 from project Euler: Distinct powers
https://projecteuler.net/problem=29'''
RESULT = 9183
def solve():
'''Main function'''
vals = set()
limit = 100
for i in xrange(2, limit + 1):
for j in xrange(2, limit + 1):
vals.add(i**j)
return len(vals)
if __name__ == '__... | 347 | 135 |
import asyncio
from pyrogram.raw import functions
from pyrogram.types import Message
from tronx import app, gen
app.CMD_HELP.update(
{"group" : (
"group",
{
"bgroup [group name]" : "Creates a basic group.",
"sgroup [group name]" : "Creates a super group.",
"unread" : "Mark a chat as unread in your tele... | 3,337 | 1,389 |
"""Affine tests package"""
| 27 | 9 |
from IPython.display import display, HTML
import time
import math
import re
import sys
import inspect
"""
Original Created at: 23rd October 2018
by: Tolga Atam
v2.1.0 Updated at: 15th March 2021
by: Tolga Atam
Module for drawing classic Turtle figures on Google Colab notebooks.
It uses html capabilit... | 109,366 | 34,328 |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 5,152 | 1,595 |
from ctypes import Structure, sizeof, c_int, c_int32, c_float, c_wchar
# Credits
# https://github.com/dabde/acc_shared_mem_access_python
# https://github.com/rrennoir/PyAccSharedMemory
class Statics(Structure):
_fields_ = [
("smVersion", c_wchar * 15),
("acVersion", c_wchar * 15),
("number... | 5,997 | 2,213 |
import matplotlib.pyplot as plt
import script_util as su
import pandas as pd
import numpy as np
import argparse
def get_score(tsv_file, pA, pB, score_name):
df = pd.read_csv(tsv_file, sep="\t")
df.set_index(["pA", "pB"], inplace=True)
return float(df.loc[(pA, pB), score_name])
def get_N(tsv_file, pA,... | 2,554 | 1,028 |
"""
Minimax algorithm with alpha-beta pruning applied to the Connect 4 game.
Inspired by https://youtu.be/l-hh51ncgDI
"""
import os
import copy
import math
def minimax(game, depth, maximize, alpha=None, beta=None):
"""Minimax algorithm, using (optionally) alpha-beta pruning."""
if depth == 0:
# Max... | 5,466 | 1,657 |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--group")
args = parser.parse_args()
import yaml
import numpy as np
from lfd import registration, tps
import os.path as osp
tps.VERBOSE=False
np.seterr(all='raise')
np.set_printoptions(precision=3)
def axisanglepart(m):
if np.linalg.det(... | 2,346 | 939 |
from argparse import ArgumentParser
from pathlib import Path
import pickle
import os
from tqdm import tqdm
from tokenizers import Tokenizer
from tokenizers.processors import RobertaProcessing
from transformers import AutoTokenizer
def init_tokenizer(lang, n, m):
if n is None and m is None:
print('size no... | 3,397 | 1,070 |
from channels.generic.websocket import WebsocketConsumer
import json
from asgiref.sync import async_to_sync
class NotificationConsumer(WebsocketConsumer):
# Function to connect to the websocket
def connect(self):
# Checking if the User is logged in
if self.scope["user"].is_anonymous:
... | 1,175 | 320 |
co = float(input('Comprimento do cateto oposto: '))
ca = float(input('Comprimento do cateto adjacente: '))
hy = ((co**2 + ca**2) ** (1/2))
print('A hipotenusa mede {:.2f}'.format(hy))
| 185 | 76 |
array = [1,2,3]
for v in array:
print(v)
| 45 | 23 |
#-*- coding: utf-8 -*-
import time
from animations.abstractanimation import AbstractAnimation
from animations.noanimation.noanimation import MultiLineNoAnimation
class VerticalAnimation(AbstractAnimation):
def __init__(self, driver):
# Call super class constructor.
super().__init__(driver)
... | 1,479 | 409 |
"""Viewsets for the 'healthchecks' app"""
# Built-in
import logging
from enum import Enum
from functools import wraps
from secrets import token_urlsafe
# Django
from django.core.cache import cache
from django.core.exceptions import FieldError, ImproperlyConfigured, ObjectDoesNotExist
from django.db import connection
... | 5,056 | 1,383 |
def send_message_to_slack(text):
from urllib import request, parse
import json
post = {"text": "{0}".format(text)}
try:
json_data = json.dumps(post)
req = request.Request("https://hooks.slack.com/services/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",
... | 595 | 208 |
from typing import Any, TypeVar, Generic, Callable, List
import numpy as np
import torch
class Compose(object):
"""
Compose multiple transforms together, applying the first, then the second,
and so on until the last.
"""
def __init__(self, *args):
self.transforms = args
def __call__... | 2,418 | 768 |
# Generated by Django 3.0.6 on 2020-05-09 11:51
import django.contrib.postgres.fields
from django.db import migrations, models
import apps.attachment.models.attachment
class Migration(migrations.Migration):
dependencies = [
('attachment', '0005_auto_20200507_2306'),
]
operations = [
mig... | 1,701 | 521 |
import math
import os
import time
from unittest import TestCase
import mock
from tests.StubTimer import StubTimer
from tests.StubUTime import StubUTime
class TestValve(TestCase):
def setUp(self):
self.mock_machine = mock.Mock()
self.mock_utime = StubUTime()
self.mock_machine.Timer.return... | 2,788 | 1,011 |
#!/usr/local/bin/python
import sys
import Pycluster as pc
from pylab import *
from collections import defaultdict
colors = ('green',
'blue',
'orange',
'cyan',
'magenta',
'red',
'yellow',
'pink',
'purple',
'brown')
def main():
"""docstring fo... | 7,085 | 2,351 |
"""A modified image folder class
We modify the official PyTorch image folder (https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py)
so that this class can load images from both current directory and its subdirectories.
"""
import torch.utils.data as data
from PIL import Image
import nibabel a... | 3,381 | 1,181 |
from pathlib import Path
import pytest
from powrap import powrap
FIXTURE_DIR = Path(__file__).resolve().parent
@pytest.mark.parametrize("po_file", (FIXTURE_DIR / "bad").glob("*.po"))
def test_fail_on_bad_wrapping(po_file):
assert powrap.check_style([po_file]) == [po_file]
@pytest.mark.parametrize("po_file", ... | 448 | 177 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of cryptidy module
"""
The cryptidy module wraps PyCrpytodome(x) functions into simple
symmetric and asymmetric functions
"""
__intname__ = "cryptidy"
__author__ = "Orsiris de Jong"
__copyright__ = "Copyright (C) 2018-2021 Orsiris de Jong"
__descri... | 472 | 188 |
import praw
import ctypes
import shutil
import requests
import requests_cache
from PIL import Image
import os
import io
requests_cache.install_cache('bg_cache')
filepath = "reddit.creds.txt"
with open(filepath, "r") as fin:
client_id = fin.readline().replace("\n", "")
# TODO: update code to accept... | 5,323 | 1,499 |
import json
import faiss
import pickle
import os
import tqdm
import numpy as np
import argparse
import time
from functools import wraps
parser = argparse.ArgumentParser()
parser.add_argument('--d', type=int, default=768, help='dimension size')
parser.add_argument('--buffer_size', type=int, default=50000)
parser.add_ar... | 6,450 | 2,418 |
#Unzip Tuples
#Unzip the cast tuple into two names and heights tuples.
cast = (("Barney", 72), ("Robin", 68), ("Ted", 72), ("Lily", 66), ("Marshall", 76))
# define names and heights here
names, heights = zip(*cast) # unzips cast into two tuples(names and heights)
print(names)
print(heights)
| 295 | 115 |
import djclick as click
from django.contrib.auth.models import User, Group
from django.db import transaction
from django.core.management.base import CommandError
class DryRunFinished(Exception):
pass
def get_or_create_users(email_addresses):
users = []
for email in email_addresses:
if not email... | 2,243 | 628 |
import configargparse
def parse(commands = None):
p = configargparse.ArgParser()
p.add('-c', '--config', is_config_file = True)
p.add('--mode', default='test', type=str)
p.add('--num_cosines', type = int)
p.add('--dim_subspace', type = int)
p.add('--dim_diffspace', type = int)
p.add('--meth... | 544 | 201 |
from typing import List
import numpy as np
from mmhuman3d.utils.path_utils import (
Existence,
check_path_existence,
check_path_suffix,
)
from .human_data import HumanData
class HumanDataCacheReader():
def __init__(self, npz_path: str):
self.npz_path = npz_path
npz_file = np.load(np... | 3,767 | 1,210 |
from typing import List
import math
import configargparse
import numpy as np
import sqlalchemy
import yaml
import sys
import tqdm
from IPython import embed
from celery import group
from angular_solver import solve, bulk_solve
from database import Config, ConfigHolder, Graph, Task, TaskJobs, get_session
from solver im... | 10,174 | 3,010 |
import os
from typing import AnyStr
from run_kotlin_kernel.run_kernel import module_install_path
def detect_jars_location() -> None:
run_kernel_path = module_install_path()
jars_dir: AnyStr = os.path.join(run_kernel_path, "jars")
print(str(jars_dir))
if __name__ == "__main__":
detect_jars_location(... | 322 | 115 |
from .value_function import NNVFunction, NNQFunction, NNDiscriminatorFunction
| 78 | 24 |
"""Generic room model"""
import argparse
import os
from frads import radgeom
from frads import radutil, util
class Room(object):
"""Make a shoebox."""
def __init__(self, width, depth, height, origin=radgeom.Vector()):
self.width = width
self.depth = depth
self.height = height
... | 7,679 | 2,546 |
from django.apps import AppConfig
class WineConfig(AppConfig):
name = 'wine'
| 83 | 28 |
"""
python test.py my-api-key
"""
import ondemand
import sys
od = ondemand.OnDemandClient(api_key=sys.argv[1])
od.debug = True
# Get that Crypto
resp = od.crypto('^BTCUSD,^LTCUSD')
print('')
print(resp)
print('')
# Get a Quote
resp = od.quote('AAPL', 'bid,ask')
print('')
print(resp)
print('')
... | 2,073 | 872 |
from allauth.socialaccount.providers.oauth2.urls import default_urlpatterns
from .provider import CorrectivProvider
urlpatterns = default_urlpatterns(CorrectivProvider)
| 170 | 47 |
import random
def choose_random(values, k=1):
if len(values) < k:
k = len(values)
results = random.choices(values, k=k)
if k == 1:
return results[0]
return results
| 198 | 70 |
import os
import requests
from requests.auth import HTTPBasicAuth
from ..integration.os.process import Command
from ..integration.os.utils import chdir
class RepoClient:
""" The class handles the GIT processes """
def __init__(self, root_dir, token, owner, repo, repo_dir):
""" Git class constructor... | 10,825 | 2,917 |
# Generated by Django 3.0.1 on 2020-08-05 19:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dfa_App', '0019_auto_20200805_2140'),
]
operations = [
migrations.AddField(
model_name='constraint',
name='Constrain... | 4,697 | 1,551 |
#Found stateFile, trying to restore the crawler state.
dictSet_0 = [('das', u'Bearbeiten', u'editing a document'), ('der', u'Politiker', u'politician; centrist'), ('der', u'Januar', u'January'), ('der', u'August', u'August'), ('der', u'Komponist', u'composer'), ('der', u'Mai', u'May'), ('die', u'T\xfcrkei', u'T\xfcrk... | 908,364 | 333,710 |
from tkinter import *
from tkinter.ttk import *
from frontend.gui.widgets import ToggleFrame
from frontend.mod.automaton import *
from frontend.mod.constants import *
from frontend.mod.hyir import *
from frontend.mod.session import Session
class PopupEntry(Toplevel):
def __init__(self, parent):
Toplevel.... | 25,186 | 7,458 |
"""In this code we wanna plot real-time data."""
# import random
from itertools import count
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
plt.style.use('fivethirtyeight')
x_vals = []
y_vals = []
index = count()
def animate(i):
"""Plot the gr... | 749 | 303 |
#!/usr/bin/env python3
import os, sys, re
import logging as L
import shutil
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from pprint import pformat, pprint
DRY_RUN = []
TALLIES = dict( runs = 0,
fastqdirs = 0 )
# Could import this from hesiod/__init__.py but I don't want the deps... | 10,688 | 3,494 |
import audio_visual
import argparse
import sys
if __name__ == "__main__":
parser = argparse.ArgumentParser(prog='Audio visualization', conflict_handler='resolve')
parser.add_argument('-e', '--effect',
help='visualization effect: 1d or 2d or 3d')
parser.add_argument('-f', '--filenam... | 1,478 | 459 |
import logging
from celery import shared_task
from .models import Feed
@shared_task(name='fetch-entries')
def fetch_entries():
"""Fetches and saves all new entries for each RSS feed in the db.
Returns:
int: count of all RSS entries successfully saved
"""
logging.info('Fetching... | 1,091 | 324 |
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: tetration_application_query
short_description: Search the application api for scope id's or details
version_added: '2.9'
description:
- "Search the Application API by ... | 6,816 | 1,917 |
import datetime
import json
import os
import random
import re
import string
import unittest
from mock import patch, Mock
from six import string_types
import payjp
NOW = datetime.datetime.now()
DUMMY_CARD = {
'number': '4242424242424242',
'exp_month': NOW.month,
'exp_year': NOW.year + 4
}
DUMMY_CHARGE ... | 3,831 | 1,300 |
import sublime
import sublime_plugin
import subprocess
import re
import time
import threading
class CommandOnSave(sublime_plugin.EventListener):
def __init__(self):
self.timeout = 2
self.timer = None
def cancel_timer(self):
if self.timer != None:
self.timer.cancel()
de... | 2,473 | 689 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : EXP
# -----------------------------------------------
import os
import re
import numbers
def _parse_dict(conf_dict) :
'''
递归解析字典值中的表达式
:param conf_dict: 原始配置字典
:return: 解析表达式后的配置字典
'''
result_dict = {}
for key, val in conf_dict.it... | 2,736 | 1,036 |
from .extension import MKAutoDocExtension, makeExtension
__version__ = "0.1.0"
__all__ = ["MKAutoDocExtension", "makeExtension"]
| 132 | 46 |
#!/usr/bin/env python
"""
Retrieve intraday stock data from Google Finance.
"""
import csv
import datetime
import re
import pandas as pd
import requests
def intradaystockprices(ticker, period=60, days=1):
"""
Retrieve intraday stock data from Google Finance.
Parameters
----------
ticker : str
... | 3,227 | 1,027 |
#!/usr/bin/env python
import os
import sys
import json
from argparse import ArgumentParser
ROOT = os.path.dirname(os.path.abspath(__file__))
DB_FILE = os.path.join(ROOT, 'problems.json')
def parse_args():
"""Parse CLI tool options.
"""
parser = ArgumentParser()
parser.add_argument('problem_id', type... | 1,750 | 538 |
from __future__ import annotations # Fixes an issue with some annotations
from .ascii_box import Light, LineChar
from .ascii_drawing import DrawingChar
class Item:
"""Represents an item within a Room."""
def __init__(self, x: int, y: int, c: DrawingChar, interact: bool = False):
self.x, self.y = x,... | 6,789 | 2,149 |
import numpy as np
import matplotlib.pyplot as plt
# NTC103F397F datasheet
d_T = np.array(np.arange(-40, 121, 5))
d_R = np.array([333.110, 240.704, 175.794, 129.707, 96.646, 72.691, 55.169, 42.234, 32.6,
25.364, 19.886, 15.705, 12.490, 10.0, 8.0584, 6.5341, 5.3297, 4.3722,
3.6065, 2.990... | 1,216 | 804 |
from abc import ABC, abstractmethod
from collections import defaultdict
from functools import partial
from auxiliary import default
class Edge:
def __init__(self, u, v, *, weight=None, capacity=None):
self.u = u
self.v = v
self.weight = weight
self.capacity = capacity
se... | 3,836 | 1,162 |
from . import anasysfile
from . import anasysdoc
from . import heightmap
from . import irspectra
from . import anasysio
def read(fn):
doc = anasysio.AnasysFileReader(fn)._doc
return anasysdoc.AnasysDoc(doc)
| 216 | 79 |
import os
import sys
import time
import numpy as np
from sklearn.metrics import accuracy_score
from utils.config import TRANSFORMATION
from utils.ensemble import load_models, prediction, ensemble_defenses_util
def testOneData(
datasetFilePath,
models,
nClasses,
transformationList,
... | 5,734 | 2,191 |
from django.shortcuts import render, redirect
from django.contrib.admin.views.decorators import staff_member_required
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse
from ems.models import Score, Level, Judge, Label, T... | 20,716 | 8,225 |
from msedge.selenium_tools import Edge, EdgeOptions
from lxml import html
import time
import curses
stdscr = curses.initscr()
max_y = stdscr.getmaxyx()[0] - 1
if max_y < 16:
raise Exception("Terminal row size must be more then 17, but now it is %d." % (max_y + 1))
# changelog: more OOP.
# class: illust,ill... | 3,117 | 1,127 |
from geo.position import Location
import geo.helper
class RoadNetwork:
'''The primary container class for OSM road networks. (See: simmob.py)
Note that key/value properties are reduced to lowercase for both keys
and values.
'''
def __init__(self):
self.bounds = [] #[Location,Location], min. poin... | 1,181 | 392 |
from django_tables2 import tables, Column
from profiles.models import TeamRoleBinding
class RoleBindingByTeamTable(tables.Table):
object_name = Column(verbose_name='Name')
class Meta:
model = TeamRoleBinding
attrs = {"id": "teams_by_object_table", "class": "table squest-pagination-tables "}
... | 375 | 112 |
# Script: bubble_sort_recursive.py
# Author: Joseph L. Crandal
# Purpose: Demonstrate bubble sort with recursion
# data will be the list to be sorted
data = [ 0, 5, 2, 3, 10, 123, -53, 23, 9, 2 ]
dataOrig = [ 0, 5, 2, 3, 10, 123, -53, 23, 9, 2 ]
# In a bubble sort you will work your way through the dataset
# and move... | 1,441 | 455 |
# Copyright 2015-2016 Mirantis, 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... | 19,260 | 5,745 |
# THIS FILE IS GENERATED FROM NUMPY SETUP.PY
#
# To compare versions robustly, use `numpy_demo.lib.NumpyVersion`
short_version = '1.29.0'
version = '1.29.0'
full_version = '1.29.0'
git_revision = 'dd8e9be4d35e25e795d8d139ff4658715767c211'
release = True
if not release:
version = full_version
| 299 | 144 |
"""
#################
Hammersley Sphere
#################
"""
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def return_point(m, n, p):
"""
m is the index number of the Hammersley point to calculate
n is the maximun number of points
p is the order of the... | 1,385 | 627 |
import enum
import json
import os
import requests
import yaml
import socket
import sqlite3
import traceback
from org.heather.api.tools import Tools
from org.heather.api.log import Log, LogLevel
@enum.unique
class VerifyResult(enum.Enum):
OK = 0
NEED_SETUP = 1
NEED_REPAIR = 2
class Setup():
@stati... | 11,261 | 3,707 |
import math
import sys
import time
from nltk import word_tokenize
import numpy as np
def bp_error_correction(kjv, all_predictions):
start_t = time.time()
# Run belief propagation to correct any words not found in dictionary
print("Setting up word set and tokenizing predictions...")
word_set = set(wor... | 5,421 | 1,766 |
from pwn import *
shellcode = "\x31\xc0\x31\xdb\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\x31\xd2\xb0\x0b\x51\x52\x55\x89\xe5\x0f\x34\x31\xc0\x31\xdb\xfe\xc0\x51\x52\x55\x89\xe5\x0f\x34"
HOST = 'pwn2.jarvisoj.com'
PORT = 9877
def PrettyTommy(ip,port):
con = remote(ip,port)
... | 619 | 347 |
"""Definition for "invalid bot credentials" error."""
from typing import NoReturn
from botx.clients.methods.base import APIErrorResponse, BotXMethod
from botx.clients.types.http import HTTPResponse
from botx.exceptions import BotXAPIError
class InvalidBotCredentials(BotXAPIError):
"""Error for raising when got i... | 1,065 | 297 |
# This file has a lot going on in it because really ties the game together,
# just like The Dude's rug. You can probably read it start to finish, but
# by all means start jumping around from here.
# Dependencies for rendering the UI
from clubsandwich.ui import (
LabelView,
LayoutOptions,
UIScene,
)
# including s... | 16,515 | 5,099 |
import os
import shutil
import argparse
from pathlib import Path
from time import time
from collections import defaultdict
import torch
import numpy as np
import pandas as pd
torch.manual_seed(0)
def allocate(a):
a[a<0] = 0
if a.sum() <= 1:
return a
else:
return a/a.sum()
def ret(output,... | 4,882 | 1,625 |
#
from __future__ import unicode_literals
import frappe, erpnext
from frappe import _
import json
from frappe.utils import flt, cstr, nowdate, nowtime
from six import string_types
class InvalidWarehouseCompany(frappe.ValidationError): pass
@frappe.whitelist()
def get_item_code(scancode=None):
if scancode:
#try ba... | 736 | 260 |
import json
import subprocess
PACMAN_SYNC_DB_COMMAND = 'sudo pacman --noconfirm -Sy'
AUR_HELPER_COMMAND = 'paru --noconfirm -S {}'
PACMAN_COMMAND = 'sudo pacman --noconfirm -S {}'
def run_cmds(array):
subprocess.run('\n'.join(array),shell=True, check=True,executable='/bin/bash')
with open('./config.json') as f:
... | 1,368 | 486 |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, SelectMultipleField, HiddenField
from flask_pagedown.fields import PageDownField
from wtforms import validators
class LoginForm(FlaskForm):
username = StringField('Username*', [validators.InputRequired("Please enter your n... | 2,293 | 609 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/8/18 上午9:50
# @Author : Matrix
# @Github : https://github.com/blackmatrix7/
# @Blog : http://www.cnblogs.com/blackmatrix/
# @File : retry.py
# @Software: PyCharm
import time
from functools import wraps
__author__ = 'blackmatrix'
"""
在函数执行出现异常时自动重试的简单装饰器
""... | 2,508 | 1,435 |
# -*- coding: utf-8 -*-
# @Time : 2021/01/02 16:26
# @Author : lishijie
import torch
from torch.utils import data
from torch.utils.data import DataLoader
import torchvision
from torchvision.transforms.transforms import Resize
from .databases import *
class LUPVisQDataLoader(object):
"""Dataste class for LUPV... | 2,564 | 820 |
import pyeccodes.accessors as _
def load(h):
def wrapped(h):
discipline = h.get_l('discipline')
parameterCategory = h.get_l('parameterCategory')
parameterNumber = h.get_l('parameterNumber')
if discipline == 3 and parameterCategory == 1 and parameterNumber == 19:
retu... | 64,609 | 17,145 |
# apetools Libraries
from apetools.baseclass import BaseClass
from apetools.builders import builder
from apetools.lexicographers.lexicographer import Lexicographer
class SetUp(BaseClass):
"""
The SetUp sets up the infrastructure
"""
def __init__(self, arguments, *args, **kwargs):
"""
... | 1,568 | 441 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Sentence level and Corpus level BLEU score calculation tool
"""
from __future__ import division, print_function
import io
import os
import math
import sys
import argparse
from fractions import Fraction
from collections import Counter
from functools import reduce
from... | 11,423 | 3,830 |
DSN = 'postgresql://edward:edward@postgres:5432/chat'
| 54 | 24 |