content stringlengths 5 1.05M |
|---|
# coding=utf-8
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------... |
from flask import Flask
from flask_cors import CORS, cross_origin
import flask
import smbus2
import bme280
import json
bme280_port = 1
bme280_address = 0x76
bus = smbus2.SMBus(bme280_port)
calibration = bme280.load_calibration_params(bus, bme280_address)
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADE... |
import os
from datetime import datetime
from flask import render_template
from flask import flash
from flask import url_for, redirect, send_file
import uuid
from . import app
from cpdlog.forms import FileForm, ActivityForm
from cpdlog.model import Activities
from cpdlog.model import get_cpd_activities, get_cpd... |
#VARIAVEIS COMPOSTAS (TUPLAS)
#REGRA: Tuplas são imutáveis
lanche = 'Hamburguer', 'Suco', 'Pizza', 'Pudim', 'Zinco','Almondega'
print(lanche[1]) #Irá mostrar o Suco, lembrar que [0,1,2,3]
print(lanche[-2]) #Irá mostrar o segundo de trás pra frente, ou seja, pizza.
print(lanche[1:3]) #Irá mostrar lanche de 1 a 3 ou sej... |
#coding=utf-8
from sqlalchemy import (
String,
Enum,
Column,
)
from app.extends import (
db,
TimestampModel,
IdentityModel,
EnumBase,
)
class PetStatus(EnumBase):
avaiable = 'avaiable'
pending = 'pending'
sold = 'sold'
class Pet(db.Model, IdentityModel, TimestampModel):
... |
class Klass(object):
"""A class.
"""
|
import os
import sys
from argparse import ArgumentParser
from collections import OrderedDict
import cv2
import numpy as np
import torch
from RAFT.core.raft import RAFT
from RAFT.core.utils import flow_viz
def frame_preprocess(frame, device):
frame = torch.from_numpy(frame).permute(2, 0, 1).float()
frame = fr... |
import os
import base64
encoded_env_file = os.environ.get("INPUT_ENV_FILE")
if encoded_env_file != None:
decoded_env_file = base64.b64decode(encoded_env_file).decode('utf-8')
with open("/github/workspace/" + str(os.environ.get("INPUT_FILE_NAME", ".env")), "w") as text_file:
text_file.write(decoded_en... |
import time
from flask import Flask, Response
import random
from chunk import Chunk
from trip import Trip
from TripDB import TripDB
from OBDConnection import OBDConnection as connect
import os
import sys
import time
import subprocess
from flask import Flask, request, jsonify
from multiprocessing import Process, Queue... |
import torch
import torch.nn as nn
import torch.nn.functional as functional
from net.RES_FPN.BasicConv2d import BasicConv2d
class Decoder(nn.Module):
def __init__(self, IF_BN=True, leaky_relu=False, is_aspp=False, n_stack=1):
super(Decoder, self).__init__()
self.is_aspp = is_aspp
self.n_sta... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 John Paulett (john -at- paulett.org)
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
"""Python library for serializing any arbitrary object graph into JSON.
It can take a... |
from discord.ext import commands
import discord
import json
import random
import requests
import os
import re
import math
class Fun:
"""Fun commands!"""
def __init__(self, bot):
self.bot = bot
@commands.command(no_pm=True, pass_context=True, aliases=['startvote', 'createvote', 'poll'... |
from unittest.case import TestCase
from django.core.exceptions import ValidationError
from django_test_app.models import Integer, String, TestModel
class CharFieldTest(TestCase):
def setUp(self):
TestModel.objects.create(name='Test Object 1', char=String.VALUE_1)
TestModel.objects.create(name='T... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Update Jamf Patch Policies
Examples:
# Assign "firefox_70.0.1_2019.10.31_rcg.pkg" to patch version "70.0.1"
$> update_patch.py --pkg 70.0.1 firefox_70.0.1_2019.10.31_rcg.pkg "Mozilla Firefox"
# Set Firefox version to "70.0.1" for Tech Branch
$> update_patch.py --te... |
from setuptools import setup, find_packages
from distutils.util import convert_path
import os
from os import listdir
from os.path import isfile, join
main_ns = {}
ver_path = convert_path('pyfy/__version__.py')
with open(ver_path) as ver_file:
exec(ver_file.read(), main_ns)
mypath = os.path.dirname(os.path.abspa... |
"""
Many of the functions in this module simply populate the context object with required key-value pairs.
"""
import sqlite3
from logging import Logger, getLogger
from os import getenv
from os.path import expanduser, isfile
from sqlite3 import Cursor
from typing import Dict, Any
from prompt_toolkit import PromptSess... |
def resolve():
'''
code here
'''
H, W = [int(item) for item in input().split()]
grid = [input() for _ in range(H)]
print('#'*(W+2))
for line in grid:
print('#' + line + '#')
print('#'*(W+2))
if __name__ == "__main__":
resolve()
|
# ***********************************************************************
#
# FILE mesh2d.py
#
# AUTHOR Dr. Vishal Sharma
#
# VERSION 1.0.0-alpha5
#
# WEBSITE https://github.com/vxsharma-14/project-NAnPack
#
# NAnPack Learner's Edition is distributed under the MIT License.
... |
from targets import Customer, CharingStation
import numpy as np
class RoutingProblemConfiguration:
def __init__(self, tank_capacity, payload_capacity, fuel_consumption_rate, charging_rate, velocity):
self.tank_capacity = tank_capacity
self.payload_capacity = payload_capacity
self.fuel_cons... |
import pandas as pd
import numpy as np
import re
import pickle
from io import BytesIO, StringIO
from datetime import datetime
import json
from constants import *
if not LOCAL_DATA:
# Only needed when in running in google cloud
from google.cloud import storage
class DataHandler:
"""Load and save data from... |
import os.path as osp
import shutil
import unittest
import numpy as np
import skrobot
import trimesh
class TestAxis(unittest.TestCase):
def test_init(self):
skrobot.model.Axis()
def from_coords(self):
coords = skrobot.coordinates.Coordinates()
skrobot.model.Axis.from_coords(coords)... |
import sys
sys.setrecursionlimit(10**6)
N = int(input())
visited = [False] * (50 * 20 + 1)
roma = [1, 5, 10, 50]
ans = 0
def dfs(now: int, cnt: int, num: int) :
global ans
if cnt == N :
if not visited[num] :
visited[num] = True
ans += 1
return
for i in range(now, 4)... |
import json
import logging
from pathlib import Path
from ..version import __version__
from typing import Optional
from .versions import clean_version
log = logging.getLogger(__name__)
# logging.basicConfig(level=logging.INFO)
def manifest(
family: str = "micropython",
stubtype: str = "frozen",
machine: ... |
import pygame
from framework.scene import Scene
from framework.text import Text
class MenuScene(Scene):
def __init__(self, director, background=(0, 0, 0)):
super().__init__(director, background)
menu_rect = pygame.Rect(0, 0, 100, 30)
menu_rect.center = director.screen.get_rect().center
... |
"""This solves problem #52 of Project Euler (https://projecteuler.net).
Permuted multiples
Problem 52
It can be seen that the number, 125874, and its double, 251748, contain exactly the same
digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same
di... |
# valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max
# valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo
|
"""
Provide quantilized form of Adder2d, https://arxiv.org/pdf/1912.13200.pdf
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Function
import math
from . import extra as ex
from .number import qsigned
class Adder2d(ex.Adder2d):
def __init__(self,
... |
import re
import json
import hearthbreaker
from hearthbreaker.cards.heroes import hero_from_name
import hearthbreaker.constants
from hearthbreaker.engine import Game, card_lookup, Deck
import hearthbreaker.game_objects
import hearthbreaker.cards
import hearthbreaker.proxies
from hearthbreaker.serialization.move import... |
#!/usr/bin/env python
import logging
from optparse import OptionParser
import progressbar
import numpy as np
import mdp.nodes as nodes
import cpa.util
from .cache import Cache
from .preprocessing import Preprocessor, VariableSelector
logger = logging.getLogger(__name__)
def standardize(a):
mean = np.... |
# Lint as: python3
# Copyright 2019 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... |
"""Handle the arguments"""
import argparse
def parse(args):
"""Use argparse to parse provided command-line arguments"""
# create the parser with the default help formatter
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
epilog="""Sample usage: pyth... |
from ftplib import FTP # used to establish connection between PC and PS4
from ftplib import error_temp # used for error 421 too many connections (when user connects to FTP server)
from os import path # used to test if externa... |
import tensorflow as tf
from tensorflow import keras
import sys
sys.path.insert(0,'..')
from global_vars import n_mels, t, BATCH_SIZE
class CNN(keras.Model):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = keras.layers.Conv2D(64, kernel_size = (3,3), strides = 1,
p... |
from typing import Dict, Any
from logwood.handlers.logging import StderrHandler
class ColoredStderrHandler(StderrHandler):
GRAY, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(30, 38)
COLOR_SEQ = '\033[1;{color:d}m'
RESET_SEQ = '\033[0m'
COLORS = {
'NOTSET': GRAY,
'DEBUG': GRAY,
'INFO': WHITE,
... |
import logging
from typing import Set
from qtpy.QtCore import Qt
from qtpy.QtGui import QColor
from qtpy.QtWidgets import (
QWidget,
QVBoxLayout,
QTabBar,
QScrollArea,
QMessageBox,
QSplitter,
)
from .block_diagrams import BlockDiagramEditorView, BlockDiagramEditor
from .devices import DevicesE... |
# -*- coding: utf-8 -*-
#
# Copyright © 2014-2015 Colin Duquesnoy
# Copyright © 2009- The Spyder Developmet Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
"""
Provides widget classes and functions.
.. warning:: Only PyQt4/PySide QtGui classes compatible with PyQt5.QtWidgets
ar... |
import numpy as np
import scipy.linalg as spla
import scipy.sparse as spsr
def cholesky_tridiagonal(tri: np.ndarray) -> np.ndarray:
"""The special structure of a tridiagonal matrix permits its Cholesky factor to
be computed in linear time instead of cubic time.
Args:
tri: Tridiagonal matrix.
... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# =================================================================
# =================================================================
import logging
from nova import context
from nova.db.sqlalchemy import api as db_session
from paxes_nova.db import api as db_api
from p... |
from pydex.core.designer import Designer
from examples.ode.ode_oed_case_1_pyomo import create_model, simulate, create_simulator
import numpy as np
""" loading only saves states and results, need to redeclare the model, simulate function, and simulator """
model_1 = create_model()
designer_1 = Designer()
designer_1.... |
class Solution(object):
def gcd(self, x, y):
while y:
x, y = y, x % y
return x
def canMeasureWater(self, x, y, z):
"""
:type x: int
:type y: int
:type z: int
:rtype: bool
"""
return not z or (x + y >= z and not z % self.gcd(x... |
#!/usr/bin/env python3
"""Numbers in Strings.
Create a function that takes a list of strings and returns
a list with only the strings that have numbers in them.
If there are no strings containing numbers, return an empty list.
Source:
https://edabit.com/challenge/XYYdtkhGPXXJ3QQNB
"""
import re
def num_in_str(ls... |
"""Macro for generating j2cl_test targets for multiple test files.
Similar to gen_java_tests in third_party/bazel_common/testing/test_defs.bzl,
this macro generates a j2cl_test rule for each test in test_files using
the specified deps.
Example usage:
gen_j2cl_tests(
name = "AllTests",
test_files = glob(["*.j... |
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render, redirect
from django.views.generic.list import ListView
from .models import Article
def home(request):
numbers_list = range(1, 1000)
page = request.GET.get('page', 1)
paginator = Paginator(numb... |
# (C) Copyright 2020 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmenta... |
import csv
import requests
import matplotlib.pyplot as plt
import sqlite3
class DindaAnik(object):
def lagu(self):
with open('kelas_2c/dinda.csv', 'r') as file:
sic = csv.reader(file, delimiter=',')
for row in sic:
print("lagu terpopuler adalah ", row)
def DindaAnik2(se... |
from .number import *
from .posit_activation import *
__all__ = ["FixedPoint", "BlockFloatingPoint", "FloatingPoint", "Posit", "PositTanhModule","PositTanhModuleEnhanced","RefTanhModule"]
|
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
import telebot
import time
import requests
import json
import random
import psutil
### input/preference data ###
token = #enter your telegram bot token here
admin_chat_id = #enter your telegram chat id here
channel_id = #enter your channel id here
bot = telebot.TeleBot(token)
message = "PS5 Available at {}!\nHere's t... |
# -*- coding: utf-8 -*-
"""
This module
"""
import attr
import typing
from ..core.model import (
Property, Resource, Tag, GetAtt, TypeHint, TypeCheck,
)
from ..core.constant import AttrMeta
#--- Property declaration ---
@attr.s
class PropResourceVersionLoggingConfig(Property):
"""
AWS Object Type = "AW... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import json
import numpy as np
#
# Split COCO dataset into random splits
#
def split_dataset(dataset_file, inds_split1, split1_file, split2_file):
print('processin... |
import os
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, optimizers, datasets
def prepare_mnist_features_and_labels(x, y):
x = tf.cast(x, tf.float32) / 255.0
y = tf.cast(y, tf.int64)
return x, y
def mnist_dataset():
(x, y), (x_val, y_val) = datasets.fashion_... |
from auction.utils.generic import get_or_create_bidbasket
def bidbasket(request):
user = request.user
bidbasket = get_or_create_bidbasket(request)
return {'bidbasket':bidbasket}
|
import inspect
# from math import cos, sin, atan2, sqrt, radians, degrees
# from AmapFunctions.GeographicCoding import GeographicCoding
from AmapFunctions.TrafficSituationByBaiduMap import TrafficSituationByBaiduMap
from logrecord.WriteLog import WriteLog
class TrafficSituationOperation:
"""
Class:... |
from gpiozero import MotionSensor, LED
from signal import pause
import time
pir = MotionSensor(4, False, None, 1, 10, 0.75 )
led = LED(16)
pir.when_motion = led.on
pir.when_no_motion = led.off
while True:
if(pir.motion_detected):
print('motion detected')
else:
print('no motion detected')
time.sleep(1)
|
from typing import Optional
import json
from redis.client import Redis
from ..helpers import bulk_of_jsons, delist, nativestr
from .commands import CommandMixin
from ..feature import AbstractFeature
class JSON(CommandMixin, AbstractFeature, object):
"""
Create a client for talking to json.
:param decod... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 VMware, Inc.
# SPDX-License-Identifier: BSD-2-Clause OR GPL-3.0-only
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANT... |
# Copyright (c) 2020 AT&T Intellectual Property.
# All rights reserved.
# SPDX-License-Identifier: GPL-2.0-only
"""
Vyatta VCI component to configure keepalived to provide VRRP functionality.
This file provides functionality for starting and stopping the keepalived
process using dbus controls.
"""
import logging
impo... |
pirate_ship = [int(x) for x in input().split(">")]
war_ship = [int(x) for x in input().split(">")]
max_health = int(input())
command = input()
lost = False
while command != "Retire":
command = command.split(" ")
order = command[0]
if order == "Fire":
index = int(command[1])
damage = int(c... |
"""InPhaDel: Genotypes and phase deletions on a single chromosome using a specific classification model
Trains models for phasing deletions using underlying WGS+HiC data
"""
import sys
import os
import pickle
import pandas as pd
import numpy as np
import warnings
from itertools import izip
from sklearn import svm
f... |
from django.urls import path
from .views import profile, team
urlpatterns = [
path('profile/solves/<str:username>', profile.solves_pie_chart, name='profile-solves-pie-chart'),
path('profile/category/<str:username>', profile.category_pie_chart, name = 'profile-category-pie-chart'),
path('team/solves/<str:tea... |
import asyncio
import websockets
import psutil
import os
import json
from tendo.singleton import SingleInstance
HOST, PORT = 'localhost', 1112
DEFAULT_TIMER = 10
def disc_free(unit):
disc = psutil.disk_usage('/')
return disc[2] / (2 ** 30)
def get_process():
p = psutil.Process(os.getpi... |
from tree.binary_search_tree import BinarySearchTree
import pytest
def test_exists():
assert BinarySearchTree
def test_instantiation():
assert BinarySearchTree()
def test_insert():
bst = BinarySearchTree()
bst.insert(4)
bst.insert(10)
bst.insert(1)
assert bst.root.data == 4
assert bs... |
"""
@file test_command_line.py
@brief unit tests for the CLI
@author Graham Riches
@details
"""
import unittest
from core.command_line import CommandLine
from routing.a_star import AStar
from routing.biased_grid import BiasedGrid
from core.tile import TileState
from core.agent import Agent
from core... |
# import my_lib as lib
#
# print(f'Time: {lib.current_time()}')
# from my_lib import *
# import my_lib as lib
|
#! /usr/bin/env python
import pathogenseq as ps
import argparse
import json
def main(args):
if not args.r1:
ps.log("Please provide at least one fastq file with -1...Exiting")
quit()
else:
ps.filecheck(args.r1)
if args.r2: ps.filecheck(args.r2)
if not args.prefix:
ps.log(... |
from googletrans import Translator
import polib
import sys
translator = Translator()
po = polib.pofile('/home/acneidert/Documentos/workspace/incubator-superset/superset/translations/pt_BR/LC_MESSAGES/pt_BR_clean.pot')
for entry in po.untranslated_entries():
try:
translation = translator.translate(entry.... |
from django.contrib.gis import admin
from .models import Slope
# also register Geo classes
admin.site.register(Slope, admin.OSMGeoAdmin)
|
# -*- encoding: utf-8 -*-
"""List of Linear Models developed using PyTorch"""
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
class LinearQNet(nn.Module):
"""
LinearQNet - A Linear Q-Learning Neural Network
A simplified linear neural network is sufficient to train most
... |
# 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, software
# d... |
#!/usr/bin/env python3
import sys
args = sys.argv
print("Username: " + args[0])
print("Password: " + args[1])
print("IP Address: " + args[2])
print("Gateway: " + args[3])
|
"""
Analysis output from RandomForestRegressor algorithms
"""
import numpy as np
import xarray as xr
import pandas as pd
import glob
import matplotlib.pyplot as plt
# import AC_tools (https://github.com/tsherwen/AC_tools.git)
import AC_tools as AC
# Internal loads within s2s
import sparse2spatial.utils as utils
impo... |
import pytest
import audobject
audobject.config.SIGNATURE_MISMATCH_WARN_LEVEL = \
audobject.define.SignatureMismatchWarnLevel.VERBOSE
class MyObject(audobject.Object):
def __init__(
self,
p: str,
*,
kw: int = 0,
):
self.p = p
self.kw = kw
... |
import argparse
import json
import logging
from the_game.exceptions import NoValidMoveError
from the_game.game import Game
logger = logging.getLogger('sim_game_logger')
logger.setLevel(logging.INFO)
fh = logging.FileHandler('sim.log')
fh.setLevel(logging.INFO)
logger.addHandler(fh)
class SimGame(object):
def ... |
# Generated by Django 3.0 on 2020-11-23 12:39
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AuthToken',
fields=[
('useridentifier',models... |
from setuptools import setup, find_packages
from codecs import open
from os import path
pwd = path.abspath(path.dirname(__file__))
with open(path.join(pwd, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
CLASSIFIERS = [
'Development Status :: 3 - Alpha'
, 'Environment :: Web Environment'
... |
#program to print next number
a=int(input())
print(a+1)
|
from PySide2.QtWidgets import QApplication, QMessageBox, QFileDialog
from PySide2.QtUiTools import QUiLoader
from PySide2.QtGui import QPixmap
from img2braille import *
class Stats:
def __init__(self):
# 从文件中加载UI定义
self.ui = QUiLoader().load('transformGUI.ui')
# 选择图像
... |
from matplotlib import colors
import matplotlib.pyplot as plt
from MagniPy.Analysis.KDE.kde import *
import numpy as np
from MagniPy.Analysis.KDE.kde import KDE_nD
import matplotlib.gridspec as gridspec
class TriPlot(object):
cmap = 'gist_heat'
# default_contour_colors = (colors.cnames['orchid'], colors.cnam... |
from __future__ import unicode_literals
from django.db import models
from django.urls import reverse
class Settings(models.Model):
key = models.CharField(max_length=100, null=False, blank=False, primary_key=True)
value = models.TextField(blank=True, null=True)
class Meta:
ordering = ['key']
... |
import glob
# All DEGs
f1 = glob.glob('Arabidopsis_Cluster_DEG_*.txt')
#file1 = open('Arabidopsis_Cluster_DEG_Comp1_CTvsHL.txt','r')
file1 = open(f1[0], 'r')
line1 = file1.readline()
DEG_transcripts = []; indices = [];
while line1:
line1 = line1.rstrip()
split_line1 = line1.split('\t')
for tids in split_line1:
DE... |
from config import constants
from utils import dbutils
def check_duplicate_document(document):
mongo_connector = dbutils.get_mongodb_connection()
mongo_connector.set_collection(constants.LIBRARYIO_COLLECTION_NAME)
query = dict({'Product': document['Product'], 'Latest Release': document['Latest Release']})... |
import pytest
from sciwing.tokenizers.character_tokenizer import CharacterTokenizer
@pytest.fixture
def setup_character_tokenizer():
tokenizer = CharacterTokenizer()
return tokenizer
class TestCharacterTokenizer:
@pytest.mark.parametrize(
"string, expected_len", [("The", 3), ("The quick brown", ... |
"""
File: /src/SubversionDumpWriter.py
Project: Subversion Dump Editor
By: Tim Oram [[email protected]]
Website: http://www.mitmaro.ca/projects/svneditor/
http://code.google.com/p/svndumpeditor/
Email: [email protected]
Created: June 26, 2009; Updated October 13, 2009
Purpose: The Su... |
#!/usr/bin/env python3
import sys
def main(filename):
with open(filename, "r") as rd:
data = [(l[0], int(l[1:].strip())) for l in rd.readlines()]
wayp = [10, -1]
pos = [0,0]
pos2 = [0,0]
vector = 90
vs = {0: (0, -1),
180: (0, 1),
90: (1, 0),
270: (-1, 0)... |
#!/usr/bin/env python
# md5: 534dac664bada9466dc70acfff63608e
# coding: utf-8
from tmilib import *
import csv
from itertools import izip
@jsonmemoized
def get_user_to_predicted_times_active_our_algorithm():
predictions_csv = csv.reader(sdir_open('catdata_test_insession_second_evaluation_predictions_datav4_modelv6.... |
#!/usr/bin/env python
#
# Medusa Based XMLSocket/JSON WebSocket server
#
RCS_ID = '$Id: InstantXMLJSONServer.py,v 1.1 2012-06-21 12:36:50 steve Exp $'
import sys, string, os, socket, errno, struct
from StringIO import StringIO
import traceback
from hashlib import md5, sha1
import base64
# UUIDs used by HyBi 04 and l... |
n = int(input("Que termo deseja encontrar: "))
ultimo=1
penultimo=1
if (n==1) or (n==2):
print("1")
else:
for count in range(2,n):
termo = ultimo + penultimo
penultimo = ultimo
ultimo = termo
count += 1
print(termo) |
"""User-defined function related data structures."""
from __future__ import absolute_import
from .base import is_all
from . import backend as F
from . import utils
class EdgeBatch(object):
"""The class that can represent a batch of edges.
Parameters
----------
g : DGLGraph
The graph object.
... |
import json
class Task:
TASK_FIELD = 'Task'
NAME_FIELD = 'Name'
DESCRIPTION_FIELD = 'Description'
ACTION_FIELD = 'Action'
CREATED_FIELD = 'Created'
def __init__(self, jsondata):
self.name = ''
self.description = ''
self.action = ''
self.created = None
s... |
# Lint as: python3
# Copyright 2018 The TensorFlow Authors. 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 ... |
import random
import torch
import torchvision
from torchvision.transforms import functional as F
class Compose:
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, img, target):
for t in self.transforms:
img, target = t(img, target)
return img... |
#48) Self powers
#The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.
#Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
#%% Solution
num = sum([x**x for x in range(1, 1000+1)])
int(str(num)[(len(str(num))-10):])
|
from lockdown.logger import Logger
"""
class name: BaseScreen
inherits from: none
purpose : base class for all screens
"""
class BaseScreen:
def __init__(self, name, bg_color, screen, logger):
self.__name = name
self.__bg_color = bg_color
self.__screen = screen
self.__log = logger
... |
from typing import List
import gzip, bz2, tarfile
from zipfile import ZipFile
def compress_gzip(data, out_path:str):
with gzip.open(out_path,'wb') as f:
try:
f.write(data)
except:
return True
finally:
return False
def decompress_gzip(in_path:str):
wi... |
from .WxPandaShell import *
base.app = WxPandaShell()
|
# Copyright 2014-2015 PUNCH Cyber Analytics Group
#
# 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 applica... |
#!usr/bin/env python
#-*- coding:utf-8 -*-
"""
@author: nico
@file: fields.py
@time: 2018/08/03
"""
from rest_framework import serializers
class CategoryParentField(serializers.PrimaryKeyRelatedField):
def get_queryset(self):
queryset = super().get_queryset()
return queryset ... |
"""
Decoding functions callings to human-readable format.
"""
from typing import Dict, List, Any
from sha3 import keccak_256
from evmscript_parser.core.ABI.storage import (
ABI_T, FuncStorage
)
# ============================================================================
# ========================= Utilities =... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.