text
string
size
int64
token_count
int64
print('='*50) print("Olá mundo!") print('='*50)
47
24
#!/usr/bin/env python2 #===- subzero/wasm-run-torture-tests.py - Subzero WASM Torture Test Driver ===// # # The Subzero Code Generator # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. # #===-----------------------------------------...
6,922
3,121
import numpy as np import pygame import sys import math import random from board import Board from ai import Minimax_AI # function to draw the board in pygame def draw_board(board): for c in range(COLUMN_COUNT): for r in range(ROW_COUNT): pygame.draw.rect(screen, colors["blue"], (c*SQUARESIZE,...
4,455
1,409
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-proxy-ssl-header SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") # https://docs.djangoproject.com/en/dev/ref/settings/#secure-ssl-redirect SECURE_SSL_REDIRECT = True # https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-secure SES...
963
394
#!/usr/bin/python # -*-coding: utf-8 -*- # Author: Joses Ho # Email : joseshowh@gmail.com from __future__ import division class bootstrap: '''Computes the summary statistic and a bootstrapped confidence interval. Keywords: x1, x2: array-like The data in a one-dimensional array form. Onl...
12,118
3,767
import math as ma # note all sizes in m^2 # all costs in pounds def get_details(): return {'w': get_value("Width:", float), 'h': get_value("Height:", float), 'cost': get_value("Cost per tile:", float),} def get_value(text = "enter_val", expected_type = None): while True: r_i...
864
312
#!/usr/bin/env python # # pyFlow - a lightweight parallel task engine # # Copyright (c) 2012-2017 Illumina, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source ...
2,579
925
from django.contrib import admin from .models import Coder, Level class CoderAdmin(admin.ModelAdmin): pass class LevelAdmin(admin.ModelAdmin): list_display_links = ('id',) list_display = ('id', 'name', 'starting_xp') list_editable = ('name', 'starting_xp') admin.site.register(Coder, CoderAdmin) admin.site.reg...
345
119
# The `Environment` class represents the dynamic environment of McCarthy's original Lisp. The creation of # this class is actually an interesting story. As many of you probably know, [Paul Graham wrote a paper and # code for McCarthy's original Lisp](http://www.paulgraham.com/rootsoflisp.html) and it was my first e...
4,423
1,258
import subprocess import aiostream import pytest from vdirsyncer.storage.filesystem import FilesystemStorage from vdirsyncer.vobject import Item from . import StorageTests class TestFilesystemStorage(StorageTests): storage_class = FilesystemStorage @pytest.fixture def get_storage_args(self, tmpdir): ...
4,416
1,439
import pandas as pd from datetime import timedelta, date import matplotlib.pyplot as plt def daterange(start_date, end_date): for n in range(int((end_date - start_date).days)): yield start_date + timedelta(n) def getFileByDate(date = 'latest'): url = 'https://raw.githubusercontent.com/pcm-dpc/COVID-19/...
1,635
704
""" Model select class1 single allele models. """ import argparse import os import signal import sys import time import traceback import random from functools import partial from pprint import pprint import numpy import pandas from scipy.stats import kendalltau, percentileofscore, pearsonr from sklearn.metrics import ...
28,698
8,596
import time from adafruit_circuitplayground.express import cpx import simpleio cpx.pixels.auto_write = False cpx.pixels.brightness = 0.3 # Set these based on your ambient temperature for best results! minimum_temp = 24 maximum_temp = 30 while True: # temperature value remapped to pixel position peak = simple...
623
248
class Exercises: def __init__(self, topic, course_name, judge_contest_link, problems): self.topic = topic self.course_name = course_name self.judge_contest_link = judge_contest_link self.problems = [*problems] def get_info(self): info = f'Exercises: {self.topic}\n' \ ...
1,086
371
############################################################ # Copyright 2019 Michael Betancourt # Licensed under the new BSD (3-clause) license: # # https://opensource.org/licenses/BSD-3-Clause ############################################################ ############################################################ # ...
15,037
6,115
#!/usr/bin/env python3 import os import filecmp import tempfile from opendbc.generator.generator import create_all, opendbc_root def test_generator(): with tempfile.TemporaryDirectory() as d: create_all(d) ignore = [f for f in os.listdir(opendbc_root) if not f.endswith('_generated.dbc')] comp = filecmp...
454
161
import vigorish.database as db from vigorish.enums import DataSet, ScrapeCondition from vigorish.scrape.brooks_pitchfx.parse_html import parse_pitchfx_log from vigorish.scrape.scrape_task import ScrapeTaskABC from vigorish.status.update_status_brooks_pitchfx import update_status_brooks_pitchfx_log from vigorish.util.dt...
3,575
1,142
from collections import namedtuple import io import json from furl import furl from django.core.handlers.wsgi import WSGIRequest from django.http.request import QueryDict from django.template import Variable, VariableDoesNotExist from django.test.client import MULTIPART_CONTENT from django.urls import resolve from dj...
10,309
2,586
import numpy as np from torch import nn def layer_init(layer, std=np.sqrt(2), bias_const=0.0): """ Simple function to init layers """ nn.init.orthogonal_(layer.weight, std) nn.init.constant_(layer.bias, bias_const) return layer
254
90
""" Test script for src=9 provisioning Below are some odd examples and notes: Adding a class { 'src': '9', 'uln': 'Githens', 'ufn': 'Steven', 'aid': '56021', 'utp': '2', 'said': '56021', 'fid': '2', 'username': 'swgithen', 'ctl': 'CourseTitleb018b622-b425-4af7-bb3d-d0d2b4deb35c', 'diagnost...
9,414
4,064
print("RUnning!!!") print("Updated!!!")
40
15
input = """ % This is a synthetic example documenting a bug in an early version of DLV's % backjumping algorithm. % The abstract computation tree looks as follows (choice order should be fixed % by disabling heuristics with -OH-): % % o % a / \ -a % / \_..._ % o \ % ...
2,309
811
from __future__ import division from random import * #...(former location of probability as a FN GLOBAL) #OUR SUPERCOOL GENETIC MUTANT NINJA TURTALGORITHM def genetics(sampleList): winLoss = [] #win/loss arrays for each sample for sample in range(sampleList): winLoss.append(isWinSample(sampleList[sampl...
7,189
2,307
import logging from collections import Generator from typing import Dict from spanner import ems_spanner_client from tenacity import retry, stop_after_attempt, wait_fixed class SpannerChecker: STOP_AFTER_ATTEMPT_SECS = 15 WAIT_FIXED = 3 def __init__(self, project_id: str, instance_id: str, db_name: str)...
1,567
501
from typing import Any from click import echo, style def out(message: str, new_line: bool = True, **styles: Any) -> None: if "bold" not in styles: styles["bold"] = True message = style(message, **styles) echo(message, nl=new_line) def err(message: str, new_line: bool = True, **styles: Any) -...
458
151
from django.db.models.signals import m2m_changed from django.dispatch import receiver from .models import Image @receiver(m2m_changed, sender=Image.users_likes.through) def users_like_changed(sender, instance, **kwargs): instance.total_likes = instance.users_likes.count() instance.save()
298
92
import random from typing import List, Union import torch import torchvision.transforms as T import torchvision.transforms.functional as F from PIL import Image class RandomDiscreteRotation(): def __init__(self, angles, resample=0, expand=False): self.angles = angles self.resample = resample ...
4,579
1,447
import pandas as pd # Wczytaj do DataFrame arkusz z narodzinami dzieci # w Polsce dostępny pod adresem df = pd.read_csv('Imiona_dzieci_2000-2019.csv')
154
65
\ import os from keras import applications import keras import tensorflow as tf import time config = tf.ConfigProto() config.gpu_options.allow_growth = True keras.backend.tensorflow_backend.set_session(tf.Session(config=config)) from keras.models import Model from keras.layers import Input, Conv2D, MaxPooling2D, Fl...
5,950
1,269
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the PyMVPA package for the # copyright and license terms. # ### ### ### ### ###...
7,761
2,431
# -*- coding: utf-8 -*- # @Time : 2020/12/1 下午11:24 # @Author : 司云中 # @File : production.py # @Software: Pycharm from configs.default import DefaultConfig class ProductionConfig(DefaultConfig): """the config of production env""" DEBUG = False TESTING = False MONGODB_DB = '' MONGODB_HOST = '' ...
431
169
from unittest import TestCase from glider.modules.glider_radio import GliderRadio class TestGliderRadio(TestCase): def setUp(self): self.radio = GliderRadio(self.test_callback) self.radio.start() def tearDown(self): self.radio.stop() def test_callback(self, msgdict): prin...
426
138
# Generated by Django 2.2.7 on 2019-12-15 12:15 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Warframe', fields=[ ('id', models.AutoField...
1,052
291
#!/pxrpythonsubst # # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # ...
5,290
1,747
#!/usr/bin/python import subprocess import sys import cgi import datetime import re import requests validMac = False ERROR = False form = cgi.FieldStorage() user = "READONLY_USER_HERE" pwd = "PASSWORD" OUI = form.getvalue('OUI') host = form.getvalue('HOST') def formatOUI(OUI): ot=OUI[0:2] ...
4,300
1,398
#!/usr/bin/env python3 import csv import glob import os.path from collections import deque from tqdm import tqdm def read_csv(fnin): with open(fnin) as f: return {tuple(e) for e in csv.reader(f)} def write_tagged_span(fout, buffer, count): b_token = buffer.popleft() print(f'{b_token}\tB', file=f...
1,801
618
# Copyright 2020 Google LLC. # This software is provided as-is, without warranty or representation for any use or purpose. # Your use of it is subject to your agreement with Google. from apache_beam import DoFn, pvalue from apache_beam.metrics import Metrics from ..model import data_classes from ..model.data_classe...
1,691
522
from __future__ import absolute_import from sentry.integrations.client import ApiClient from sentry.models import EventCommon from sentry.api.serializers import serialize, ExternalEventSerializer LEVEL_SEVERITY_MAP = { "debug": "info", "info": "info", "warning": "warning", "error": "error", "fatal...
2,285
634
# coding: utf-8 # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
3,192
864
import bpy import numpy as np import math import mathutils import time import os class Prism: """ ^""" """ / \\""" """ / ^ \\""" """ / | \\""" """ /'alpha'\\ <-- lenght of this side is calculated based on 'width' and 'alpha'""" """/ \\""" """-------...
3,352
1,141
# -*- coding: utf-8 -*- """ Created on Fri Feb 6 17:38:00 2015 @author: dbwrigh3 """
88
51
# -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('requirements.txt') as f: install_requires = f.read().strip().split('\n') # get version from __version__ variable in proceso/__init__.py from proceso import __version__ as version setup( name='proceso', version=version, description='A ...
526
183
# this project is licensed under the WTFPLv2, see COPYING.txt for details import logging from weakref import ref from PyQt5.QtCore import QEventLoop from PyQt5.QtWidgets import QPlainTextEdit, QLabel, QWidget, QRubberBand, QApplication from ..app import qApp from ..qt import Slot, Signal from .helpers import WidgetM...
3,650
1,346
# -*- coding: utf-8 -*- # Copyright (c) 2013 Tomasz Wójcik <tomek@bthlabs.pl> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # ...
10,437
3,221
import types import tkinter import Pmw import sys import collections class OptionMenu(Pmw.MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. INITOPT = Pmw.INITOPT optiondefs = ( ('command', None, None), ('items', ...
4,929
1,354
import os import torch import argparse from util import util def str2bool(b_str): if b_str.lower() in ('yes', 'true', 't', 'y', '1'): return True elif b_str.lower() in ('no', 'false', 'f', 'n', '0'): return False class TrainOptions(): def __init__(self): self.parser = argparse.Argu...
7,614
2,199
import os from pypdflite.pdflite import PDFLite from pypdflite.pdfobjects.pdfcolor import PDFColor def TableTest(test_dir): """ Functional test for text, paragraph, and page splitting. """ data = [["Heading1", "Heading2", "Heading3"], ["Cell a2", "Cell b2", "Cell c2"], ...
1,991
704
from typing import List, Optional from pydantic import BaseModel from pydantic import validator class CrossReferenceSchemaRelated(BaseModel): curie: str pages: Optional[List[str]] = None is_obsolete: Optional[bool] = None @validator('curie') def name_must_contain_space(cls, v): if v.coun...
2,227
664
class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ Max = -float("inf") currMax = -float("inf") for num in nums: currMax = max(num, num + currMax) Max = max(Max, currMax) retur...
325
100
import unittest from a816.parse.ast.expression import eval_expression_str from a816.symbols import Resolver class ResolverTest(unittest.TestCase): def test_math_expr_eval(self) -> None: expr = "0x100+toto & 0xFFFF" resolver = Resolver() resolver.current_scope.add_symbol("toto", 0x108000)...
967
351
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: syft_proto/frameworks/crypten/onnx_model.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf im...
4,445
1,766
import numpy as np import knapsack class Knapsack: def __init__(self, K, max_weight, state_shape = 'flat', penalize_repeat = False): self.K = K self.max_weight = max_weight self.penalize_repeat = penalize_repeat # Not used for now, have to figure out details self.env_name = 'Knapsac...
3,333
1,083
#!/usr/bin/env python # -*- coding: iso-8859-15 -*- ######################## -*- coding: utf-8 -*- """Usage: plotres.py variable INPUTFILE(S) """ import sys from getopt import gnu_getopt as getopt import matplotlib.pyplot as plt import numpy as np import datetime # parse command-line arguments try: optlist,args =...
3,063
1,173
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this ...
14,266
4,580
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 13 12:07:22 2020 @author: medrclaa Stand alone script for testing arc in ARC. simply run pytest arc_test.py To ensure the working environment is suitable for running experiments. If you only wish to run a single experiment then you an easily ha...
2,104
650
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name = "nomics-python", version = "3.1.0", author = "Taylor Facen", author_email = "taylor.facen@gmail.com", description = "A python wrapper for the Nomics API", long_description = long_desc...
646
215
import os from pathlib import Path from typing import List from challenges.day3 import frequency_character def _read_input() -> List[str]: """Read the input file.""" travel_map = [] current_path = Path(os.path.dirname(os.path.realpath(__file__))) image_path = current_path / "resources" / "day3_puzzle_...
2,177
811
#!/usr/bin/env python # coding: utf-8 from msgpack import unpackb def check(src, should, use_list=0, raw=True): assert unpackb(src, use_list=use_list, raw=raw, strict_map_key=False) == should def testSimpleValue(): check(b"\x93\xc0\xc2\xc3", (None, False, True)) def testFixnum(): check(b"\x92\x93\x00...
2,333
1,385
'''tzinfo timezone information for Asia/Brunei.''' from pytz.tzinfo import DstTzInfo from pytz.tzinfo import memorized_datetime as d from pytz.tzinfo import memorized_ttinfo as i class Brunei(DstTzInfo): '''Asia/Brunei timezone definition. See datetime.tzinfo for details''' zone = 'Asia/Brunei' _utc_tran...
519
245
# -*- coding: utf-8 -*- import pytest from raiden.messages import Ping, Ack, decode, Lock, MediatedTransfer from raiden.utils import make_privkey_address, sha3 PRIVKEY, ADDRESS = make_privkey_address() def test_signature(): ping = Ping(nonce=0) ping.sign(PRIVKEY, ADDRESS) assert ping.sender == ADDRESS ...
4,184
1,507
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Jul 5 12:41:09 2017 @author: lracuna """ #!/usr/bin/env python """ This program uses a simple implementation of the ADMM algorithm to solve the circle packing problem. We solve minimize 1 subject to |x_i - x_j| > 2R, R < x_i, ...
6,428
2,324
import os import sys import random sys.path.append(os.path.join(os.environ['ALFRED_ROOT'])) sys.path.append(os.path.join(os.environ['ALFRED_ROOT'], 'models')) import torch import pprint import json from data.preprocess import Dataset from importlib import import_module from argparse import ArgumentDefaultsHelpFormatte...
7,658
2,454
import pytest from billy.utils.search import google_book_search class TestGoogleBookSearch(object): def test_search_returns_200(self, mock): """Ensure a basic search returns a 200 request""" assert google_book_search("Harry Potter")["status"] == 200 def test_search_body_returns_dict(self, moc...
474
149
import math class Config_1: DATASET_ROOT_DIR = '../data/test1/Data' # The data set root directory DATASET_SCALE = 0 # How many users' trajectory data are choosed TRAJACTORY_SCALE = 20 # How many trajectories are choosed per user RANGE = { # To...
2,981
1,061
import sys from sys import exit if len(sys.argv) == 1 : print ("No command line argument" ) sys.exit() #else : # print ("rest of the program ") #numbers = sys.argv[1:] #print (sorted(numbers, key=lambda x: float(x))) numbers = [] i=1 n= len(sys.argv) while ( i < n ): numbers.append(sys.argv[i]) i=i+1 ...
766
278
from . import dbFuncs import sys, os import pkg_resources from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QApplication, qApp, QHBoxLayout, QMainWindow, QAction, QMessageBox, QFileDialog, QPushButton from PyQt5.QtGui import QIcon class MainWindow(QMainWindow): def __init__(self): super(MainWindow,se...
4,553
1,386
import os import psutil import time def process_time(): p = psutil.Process(os.getpid()) return time.time() - p.create_time()
135
47
# ================================================= # SERVER CONFIGURATIONS # ================================================= CLIENT_ID='' CLIENT_SECRET='' REDIRECT_URI='http://ROCKOPY/' # ================================================= # SERVER CONFIGURATIONS # ================================================= S...
544
158
import discord from discord.ext import commands from discord.utils import get class c269(commands.Cog, name="c269"): def __init__(self, bot: commands.Bot): self.bot = bot @commands.command(name='Vir_the_True_Elementalist', aliases=['c269', 'Elementalist_1', 'Distasta_Master_1']) async def exam...
1,356
460
from soad import AsymmetricData as asyd import matplotlib.pyplot as plt # This script is prepared for showing the difference between methods of handling asymmetric errors. class Data: control_variable_parameters = [10.0, 1.0, 1.0] control_variable = [] variable_list = [] def __init__(self, mu, sigm...
6,116
2,118
import scipy.io as scio import numpy as np import matplotlib.pyplot as plt import scipy.optimize as opt from displayData import display_data from costFunction import nn_cost_function from sigmoid import sigmoid_gradient from randInitializeWeights import rand_init_weights from checkNNGradients import check_nn_gradients...
3,211
1,401
""" This example shows some more complex querying Key points are filtering by related names and using Q objects """ import asyncio from tortoise import Tortoise, fields from tortoise.models import Model from tortoise.query_utils import Q class Tournament(Model): id = fields.IntField(pk=True) name = fields.T...
2,432
776
import struct import socket class PacketIpHeader: """ 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |Version| +-+-+-+-+ """ IP_HDR = "! B"...
3,012
1,242
from django.conf import settings from django.core.files.storage import Storage from django.utils.deconstruct import deconstructible from fdfs_client.client import Fdfs_client @deconstructible class FastDFSStorage(Storage): def __init__(self, base_url=None, client_conf=None): """ 初始化 :param...
1,547
577
import gunicorn.app.base from sovereign import asgi_config from sovereign.app import app class StandaloneApplication(gunicorn.app.base.BaseApplication): def __init__(self, application, options=None): self.options = options or {} self.application = application super().__init__() def lo...
664
202
Val = int(input('Digite o valor que você quer sacar:')) c50 = c20 = c10 = c1 = 0 if Val // 50 != 0: c50 = Val // 50 Val = Val % 50 if Val // 20 != 0: c20 = Val // 20 Val = Val % 20 if Val // 10 != 0: c10 = Val // 10 Val = Val % 10 if Val // 1 != 0: c1 = Val // 1 if c50 != 0: print(f'{c50...
495
274
""" Bazel macros for defining proto libraries. """ load("@rules_proto//proto:defs.bzl", "proto_library") # TODO(#4096): Remove this once it's no longer needed. def oppia_proto_library(name, **kwargs): """ Defines a new proto library. Note that the library is defined with a stripped import prefix which en...
801
224
import os from remotepixel import cbers_ndvi CBERS_SCENE = "CBERS_4_MUX_20171121_057_094_L2" CBERS_BUCKET = os.path.join(os.path.dirname(__file__), "fixtures", "cbers-pds") CBERS_PATH = os.path.join( CBERS_BUCKET, "CBERS4/MUX/057/094/CBERS_4_MUX_20171121_057_094_L2/" ) def test_point_valid(monkeypatch): ""...
1,533
738
#!/usr/bin/env python # # __COPYRIGHT__ # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, ...
2,270
805
""" The container to store indexes in active learning. Serve as the basic type of 'set' operation. """ # Authors: Ying-Peng Tang # License: BSD 3 clause from __future__ import division import collections import copy import numpy as np from .multi_label_tools import check_index_multilabel, infer_label_size_multilabe...
25,955
7,634
import platform as p import uuid import hashlib def basic(): sb = [] sb.append(p.node()) sb.append( ''.join([ x for x in p.architecture() ]) ) sb.append(p.machine()) sb.append(p.processor()) sb.append(p.system()) sb.append(str(uuid.getnode())) # MAC address text = '.'.join(sb) retu...
327
115
url = "https://www.delish.com/cooking/recipe-ideas/recipes/a53823/easy-pad-thai-recipe/" url2 = "https://www.allrecipes.com/recipe/92462/slow-cooker-texas-pulled-pork/" # opener = urllib.URLopener() # opener.addheader(('User-Agent', 'Mozilla/5.0')) # f = urllib.urlopen(url) import requests import html2text h = html2...
995
409
#!/usr/bin/env python from __future__ import print_function import inspect import logging import os import platform import sys from time import sleep from flaky import flaky import pytest import requests from jira_test_manager import JiraTestManager # _non_parallel is used to prevent some tests from failing due to ...
21,796
6,972
#!/usr/bin/env python # Goofile v1.5a # by Thomas (G13) Richards # www.g13net.com # Project Page: code.google.com/p/goofile # TheHarvester used for inspiration # A many thanks to the Edge-Security team! # Modified by Lee Baird import getopt import httplib import re import string import sys global result r...
1,761
727
n = int(input('Insira um número e calcule sua raiz: ')) b = 2 while True: p = (b + (n / b)) / 2 res = p ** 2 b = p if abs(n - res) < 0.0001: break print(f'p = {p}') print(f'p² = {res}')
211
104
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import datetime import decimal import platform import sys import types from itertools import chain #stripped version of SIX PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 PY_35 = sys.version_info >= (3, 5...
1,732
576
# coding=utf-8 # pynput # Copyright (C) 2015-2016 Moses Palmér # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later version. ...
3,388
1,094
allData = {'AK': {'Aleutians East': {'pop': 3141, 'tracts': 1}, 'Aleutians West': {'pop': 5561, 'tracts': 2}, 'Anchorage': {'pop': 291826, 'tracts': 55}, 'Bethel': {'pop': 17013, 'tracts': 3}, 'Bristol Bay': {'pop': 997, 'tracts': 1}, 'Denali': {'pop': 1826, 'tracts': 1}, ...
155,379
82,244
# -*- coding: utf-8 -*- """Mock template engine, for use in tests.""" from piecutter.engines import Engine #: Default value used as :py:attr:`MockEngine.render_result` default_render_result = u'RENDER WITH ARGS={args!s} AND KWARGS={kwargs!s}' class MockEngine(Engine): """Template engine mock. Typical usage...
2,259
714
#MCCA (Multiview Canonical Correlation Analysis) import numpy as np from scipy import linalg as lin from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier class CWMVFE: def __init__(self,n_components=2,reg_param=0.01 , L): self.n_components = n_component...
4,276
1,599
import argparse from sklearn.decomposition import LatentDirichletAllocation as LDA import pickle from biom import load_table def main(args): model = LDA(n_components=args.n_latent, max_iter=args.iterations, verbose=1, learning_method='online') table = load_table(args.train_biom) X = table....
1,331
390
''' splitjoin.py sonicskye@2018 The functions are used to split and join files based on: https://stonesoupprogramming.com/2017/09/16/python-split-and-join-file/ with modification by adding natural sort ''' import os import re # https://stackoverflow.com/questions/11150239/python-natural-sorting def natural_s...
2,984
929
# Mark Bundgus 2019 import luigi import logging from yarn_api_client import ResourceManager # https://python-client-for-hadoop-yarn-api.readthedocs.io from datetime import datetime from datetime import timedelta import pandas as pd from tabulate import tabulate import os import configuration log = logging.getLogger("...
9,653
2,937
from bfxhfindicators.indicator import Indicator class WMA(Indicator): def __init__(self, args = []): [ period ] = args d = 0 for i in range(period): d += (i + 1) self._d = d self._p = period self._buffer = [] super().__init__({ 'args': args, 'id': 'wma', 'name'...
1,071
413
import argparse from datetime import datetime import os from catalyst import dl, utils from catalyst.contrib.data import AllTripletsSampler from catalyst.contrib.losses import TripletMarginLossWithSampler from catalyst.data import BatchBalanceClassSampler from torch import nn, optim from torch.utils.data import DataLo...
5,021
1,653
""" Manage AWS Batch jobs, queues, and compute environments. """ from __future__ import absolute_import, division, print_function, unicode_literals import os, sys, argparse, base64, collections, io, subprocess, json, time, re, hashlib, concurrent.futures, itertools from botocore.exceptions import ClientError from ....
22,536
7,088
############################################## # This code is based on samples from pytorch # ############################################## # Writer: Kimin Lee from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import d...
10,897
4,120
#code https://practice.geeksforgeeks.org/problems/swap-and-maximize/0 for _ in range(int(input())): n = int(input()) arr = list(map(int, input().split())) arr.sort() max = 0 for i in range(n//2): max -= 2*arr[i] max += 2*arr[n-i-1] print(max)
302
122
from random import sample, shuffle from ga4stpg.graph import UGraph from ga4stpg.graph.disjointsets import DisjointSets class GenerateBasedPrimRST: def __init__(self, stpg): self.stpg = stpg def __call__(self): result = UGraph() terminals = self.stpg.terminals.copy() ...
2,304
794
import pandas as pd import rapidfuzz import math import numpy as np # ------------------------- # # --------- DATA ---------- # # ------------------------- # # Read in mock census and PES data CEN = pd.read_csv('Data/Mock_Rwanda_Data_Census.csv') PES = pd.read_csv('Data/Mock_Rwanda_Data_Pes.csv') # select ne...
10,284
3,246