content stringlengths 5 1.05M |
|---|
if __name__ == '__main__':
import matplotlib
matplotlib.use('Agg')
from matplotlib import rc
rc('font',**{'family':'serif','serif':'Computer Modern Roman','size':12})
rc('text', usetex=True)
import numpy as np
import pylab as plt
def com_shape(fn):
plt.figure(figsize=(4, 4))
plt.clf()
p... |
from .adagrad import Adagrad
from .adgd import Adgd
from .adgd_accel import AdgdAccel
from .gd import Gd
from .ig import Ig
from .nesterov import Nesterov
from .nest_line import NestLine
from .ogm import Ogm
from .polyak import Polyak
from .rest_nest import RestNest
|
#refaça o exercicio 35 acrescentando o recurso de mostrar que tipo de triangulo será mostrado:]
#equilátero: todos os lados são iguais;
#isósceles: dois lados iguais;
#escaleno: todos os lados diferentes
reta1 = float(input('Informe reta1:'))
reta2 = float(input('Informe reta2:'))
reta3 = float(input('Informe reta3:')... |
from starlette.responses import JSONResponse
from starlette.templating import Jinja2Templates
from operator import itemgetter
from pathlib import Path
from ydl_server.config import app_config, get_finished_path
from ydl_server.logdb import JobsDB, Job, Actions, JobType
from datetime import datetime
templates = Jinja... |
import os
import pickle
import pandas as pd
from datetime import datetime
from time import sleep
from tqdm import tqdm
import re
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
def scrape_current_player_stats(url, gameweek, mapper, driver):
... |
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'left_columnjzXejK.ui'
##
## Created by: Qt User Interface Compiler version 6.1.3
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
#########... |
"""
========================================================
Compute real-time evoked responses with FieldTrip client
========================================================
This example demonstrates how to connect the MNE real-time
system to the Fieldtrip buffer using FieldTripClient class.
This example was tested ... |
import os
import base64
import logging
import pickle
import uuid
import import_string
from datetime import timedelta
from django.core.management import call_command, get_commands
from django.core.exceptions import ImproperlyConfigured
from django.core.cache import caches
from django.db import close_old_connections,... |
from ex1 import sum_list_for, sum_list_reduce, sum_list_sum_func
from ex2 import list_comp
from ex3 import boom_7_for, boom_7_list_comprehension, boom_7_map
from ex4 import dict_to_list, dict_to_list_comp
from ex5 import count_number_of_arguments
from ex6 import func
from ex7 import make_adder
print("Test ex1 sum list... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import transaction
def test_displays_list_of_log_entries(browser):
from sw.allotmentclub import Log, User
User.create(id=2, username='sw', vorname='Sebastian',
nachname='Wehrmann')
Log.create(user_id=2, name='u... |
#一
import keyword
print(keyword.kwlist) #打印关键字
#二
a = 'app\nle'
a2 = r'app\nle' #加r是防止字符转义的,加r和不加''r是有区别的,如果路径中出现'\t'(python中是空六格的意思)的话 不加r的话\t就会被转义 而加了'r'之后'\t'就能保留原有的样子
print(a)
print(a2)
#三
#打开一个文件,有两种方法
#方法一:
file = open (r'C:\Users\Administrator\Desktop\PYTHON_LESSON\a.txt','r',encoding='utf-8') #'r,w,a,... |
#
# Copyright(c) 2012-2021 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause
#
import pytest
import subprocess
import unittest.mock as mock
from opencas import casadm
from helpers import get_process_mock
@mock.patch("subprocess.run")
def test_run_cmd_01(mock_run):
mock_run.return_value = get_process_moc... |
import os,signal
out=os.popen("ps -ef").read()
for line in list(out.splitlines())[1:]:
try:
pid = int(line.split()[1])
ppid = int(line.split()[2])
cmd = " ".join(line.split()[7:])
print(pid,ppid,cmd)
if ppid in [0,1] and cmd in ["/usr/local/bin/python3.8 /home/ctf/web/app.p... |
"""[4.2.6-2] Diffusion-reaction PDEs
Implemented with Pytorch.(torch version >= 1.8.1)
* Variable interpretation:
- x: torch.Tensor, (Number of points, dimension)
-
"""
import sys, os
from copy import deepcopy
import random
from random import randint
import json
from tqdm import tqdm
import numpy as np
import torch... |
from django.test import TestCase, tag
from users.models import User
from users.tests.mixin import UserTestMixin
@tag('model')
class TestUserModel(UserTestMixin, TestCase):
@classmethod
def setUpTestData(cls):
pass
@tag('standard')
def test_user_manager_create_success(self):
# given
... |
from Command.Command import Command
from AudioExtraction.AudioExtractor import AudioExtractor
from AudioExtraction.Mp4Video import Mp4Video
from glob import glob
import os
from Utilities import Utilities as util
def validate(args):
if args.file == None:
return False
if args.run == None and args.extra... |
import scipy.stats as st
def NumerosIgualesPornumero(listaaleatoria):
todos = []
for t in (listaaleatoria):
c1=''
lista = [0] * 10
for numero in range (0,10):
lista[numero]=t.count(str(numero))
for l in range (len(lista)):
if (lista[l] == 1):
... |
#!/usr/bin/env python
# Created by MikBac on 2020
import sys
for line in sys.stdin:
line = line.strip()
fields = line.split('\t')
if len(fields) == 1:
print(fields[0])
|
"""
Tests the channel_entrainment derived class
"""
from __future__ import absolute_import
__all__ = ["test"]
from ...._globals import _RECOGNIZED_ELEMENTS_
from .._entrainment import channel_entrainment
from ....testing import moduletest
from ....testing import unittest
@moduletest
def test(run = True):
... |
#https://pyotp.readthedocs.io/en/latest/
# cd D:\2018_working\coding\googleAuthenticator
#https://tools.ietf.org/html/rfc4226
import pyotp
import time
totp = pyotp.TOTP('base32secret3232')
temp = totp.now()
temp
# OTP verified for current time
totp.verify(temp) # => True
time.sleep(30)
totp.verify(temp) # => False
... |
from .manager import ExperimentManager
class ExperimentsMiddleware(object):
"""Experiments middleware.
Binds the convenient :class:`ExperimentManager` to the request.
"""
def process_request(self, request):
assert hasattr(request, 'session'), \
'Django Banana requires session mid... |
# Copyright (c) 2020 PaddlePaddle 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 required by appli... |
from datetime import datetime
import fire
YEAR = 2000
ZODIAC_SIGNS = {
(datetime(YEAR, 1, 20), datetime(YEAR, 2, 18)): "水瓶座",
(datetime(YEAR, 2, 19), datetime(YEAR, 3, 20)): "魚座",
(datetime(YEAR, 3, 21), datetime(YEAR, 4, 19)): "牡羊座",
(datetime(YEAR, 4, 20), datetime(YEAR, 5, 20)): "牡牛座",
(datetim... |
from client_sdk_python import Web3, HTTPProvider
from client_sdk_python.eth import PlatONE
from hexbytes import HexBytes
# get blockNumber
# w3 = Web3(HTTPProvider("http://localhost:6789"))
w3=Web3(HTTPProvider(" http://58.251.94.108:56789")) #含有国密链的节点
platone = PlatONE(w3)
block_number = platone.blockNumber
print(bl... |
#!/usr/bin/env python3
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
import logging
from typing import List, Literal
import aiohttp
from prometheus_api_client import PrometheusConnect
logger = logging.getLogger(__name__)
class Prometheus:
"""A class that represents a running instanc... |
import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer
SiStripBaselineValidator = DQMEDAnalyzer('SiStripBaselineValidator',
srcProcessedRawDigi = cms.InputTag('siStripZeroSuppression','VirginRaw')
)
|
from flask import request, Blueprint, render_template, redirect
from services.user import UserServices
from services.video import VideoServices
video = Blueprint('video', __name__)
@video.route('/play')
def video_play():
uid = request.cookies.get('uid')
if uid is None:
return redirect('/user/login',... |
import sys
import pandas as pd
import os
from yaml import safe_load
import csv
from collections import OrderedDict
import cv2
import numpy as np
from tqdm import tqdm
from subprocess import call
import h5py
from src.data.data_loaders import load_action_data, load_gaze_data
from src.features.feat_utils import transform_... |
from __future__ import with_statement
"""
Test highlevel Group object behavior
"""
import numpy as np
import h5py
from common import TestCasePlus, api_16, api_18, res
from common import dump_warnings
SHAPES = [(), (1,), (10,5), (1,10), (10,1), (100,1,100), (51,2,1025)]
class GroupBase(TestCasePlus):
"""
... |
#!/usr/bin/env python3
from librip.gens import gen_random
from librip.iterators import Unique
data1 = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2]
data2 = ['A', 'a', 'b', 'B']
data3 = ['A', 'a', 'b', 'B']
# Реализация задания 2
for i in Unique(data1):
print(i, end=" ")
print(" ")
for i in Unique(data2):
print(i, end=" ")
p... |
# Generated by Django 2.2.1 on 2019-08-28 09:17
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
import typing
import tensorflow as tf
FEATURES = [
"fixed_acidity", "volatile_acidity", "citric_acid", "residual_sugar",
"chlorides", "free_sulfur_dioxide", "total_sulfur_dioxide", "density",
"pH", "sulphates", "alcohol"
]
LABEL = "quality"
def get_train_eval_datasets(
path: str,
train_fraction:... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: karps/proto/computation.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf impo... |
import os
import math
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.colors as colors
import mpl_toolkits.axisartist.floating_axes as floating_axes
from skimage import io
from matplotlib import cm
from skimage import filters
fr... |
from django.shortcuts import render
from rest_framework import permissions, viewsets
from rest_framework.response import Response
from rest_framework.views import APIView
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
from . import models
from .serializer import Works... |
from warnings import warn
from . import util as mutil
from .latex import LatexFactory
from ._core import (
FCN,
MnContours,
MnHesse,
MnMigrad,
MnMinos,
MnPrint,
MnStrategy,
MnUserParameterState,
)
import numpy as np
__all__ = ["Minuit"]
class Minuit:
LEAST_SQUARES = 1.0
"""Set... |
# Only used for PyTorch open source BUCK build
"""Provides macros for queries type information."""
_SELECT_TYPE = type(select({"DEFAULT": []}))
def is_select(thing):
return type(thing) == _SELECT_TYPE
def is_unicode(arg):
"""Checks if provided instance has a unicode type.
Args:
arg: An instance t... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from abc import abstractmethod
from .abs_shaper import AbsShaper
class StateShaper(AbsShaper):
"""State shaper class.
A state shaper is used to convert a decision event and snapshot list to model input.
"""
@abstractmethod
... |
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import os
import time
import configparser
class InstagramBot:
def __init__(self, username, password):
"""
Initialises Instagram Bot object.
Args:
username: The Instagram Username
... |
# %%
import os, sys
import re
import cv2
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from numpy import linspace, meshgrid
from scipy.interpolate import griddata
import matplotlib.image as mpimg
import matplotlib.style
import matplotlib as mpl
mpl.style.use('default')
from PIL import Image
#... |
import copy
import torch
import torch.nn as nn
import numpy as np
import pytorch_transformers
import utils.io as io
class CapEncoderConstants(io.JsonSerializableClass):
def __init__(self):
super().__init__()
self.model = 'BertModel'
self.tokenizer = 'BertTokenizer'
self.pretrained... |
# Singly-linked lists are already defined with this interface:
# class ListNode(object):
# def __init__(self, x):
# self.value = x
# self.next = None
#
def mergeTwoLinkedLists(l1, l2):
if l1 == None and l2 == None:
return None
merged = ListNode(None)
ret = merged
# prev = merged.valu... |
#!/usr/bin/env python
"""Static site generation for help.rerobots.net
SCL <scott@rerobots.net>
Copyright (C) 2018 rerobots, Inc.
"""
from datetime import datetime
import sys
from markdown.extensions.toc import TocExtension
from markdown import markdown
PREFIX="""<!DOCTYPE html>
<html lang="en">
<head>
<meta charse... |
# -*- coding: utf-8 -*-
"""
colNamedColours.py
Author: SMFSW
Copyright (c) 2016-2021 SMFSW
Description: HTMLrestricted & CSS color space reference & classes
"""
# TODO: add search nearest
# TODO: ajouter la gestion des exceptions lorsque le nom de la couleur n'est pas trouvee
from colHEX import ColHEX as cHEX
class ... |
import intprim.filter.align.dtw
|
URL = 'https://www.dgi.gov.lk/news/press-releases-sri-lanka/covid-19-documents'
GITHUB_URL = 'https://raw.githubusercontent.com/nuuuwan/nopdf_data/main'
GITHUB_TOOL_URL = 'https://github.com/nuuuwan/nopdf_data/blob/main'
|
print((int(input())+11)%24) |
# r1
import json
import logging
from helpers.save.data_saver import DataSaver
logger = logging.getLogger('ddd_site_parse')
class DataSaverJSON(DataSaver):
def __init__(self, params: {}):
super().__init__(params)
self.ext = 'json'
self.newline = params.get('newline', '')
def _save... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import os
from scrapy.pipelines.images import ImagesPipeline
from urllib import request
from trafficsign import settings
impo... |
from common.generic_template_tag import GenericTemplateTag
from ..utils import get_what_teams_called, make_tournament_link
from ..models import PollMap
class DisplayTournamentMenuNode(GenericTemplateTag):
template = 'display_tournament_menu.html'
def __init__(self, tourney, double_br=1, extra_admin=0):
... |
# File: exp.py
# Author: raycp
# Date: 2019-06-08
# Description: exp for EasiestPrintf, trigger malloc by printf
from pwn_debug import *
pdbg=pwn_debug("./EasiestPrintf")
pdbg.context.terminal=['tmux', 'splitw', '-h']
#pdbg.local()
pdbg.debug("2.27")
#pdbg.remote('127.0.0.1', 22)
#p=pdbg.run("local")
#p=pdbg.run(... |
# coding: utf8
"""
All wordforms are extracted from Norsk Ordbank in Norwegian Bokmål 2005, updated 20180627
(CLARINO NB - Språkbanken), Nasjonalbiblioteket, Norway:
https://www.nb.no/sprakbanken/show?serial=oai%3Anb.no%3Asbr-5&lang=en
License:
Creative_Commons-BY (CC-BY) (https://creativecommons.org/licenses/by... |
import socket
import logic
import sys
sock = socket.socket()
server_address = ('localhost', 9080)
print('starting up on{} port {}'.format(*server_address))
sock.bind(server_address)
_logic = logic.Logic('vadik')
sock.listen(1)
while True:
print('waiting for connection')
connection, client_address = sock.acce... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2020-12-09 22:15
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('baza', '0011_auto_20201207_2227'),
]
operations = [
migrations.RemoveField(
... |
#!/bin/python3
import os
# Complete the twoPluses function below.
def twoPluses(grid):
h, w = len(grid), len(grid[0])
mn = min(h, w)
plus = []
is_good = lambda row, col: grid[row][col] == 'G'
how = lambda x: 2 * x - 1
for step in range(1, mn // 2 + (1 if mn % 2 else 0)):
for r in rang... |
from rest_framework import generics
from .models import NewsItem
from .serializers import NewsItemSerializer, NewsItemPreviewSerializer
class NewsItemPreviewList(generics.ListAPIView):
model = NewsItem
serializer_class = NewsItemPreviewSerializer
paginate_by = 5
filter_fields = ('language', )
def... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .forms import SearchForm
import random
from . import util
import markdown as md
def index(request):
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries()
})
def search(request, en... |
# Copyright 2020 gRPC authors.
#
# 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... |
class Adaptee:
def hello(self):
print('hi')
class Adapter:
def __init__(self):
self._adaptee = Adaptee()
def hello(self):
self._adaptee.hello()
# region usage
if __name__ == '__main__':
Adapter().hello()
# endregion
|
from PIL import Image, ImageDraw
import itertools
import random
class generateFlag:
def __init__(self, count, seed):
self.seed = seed
self.flag = Image.new("RGB", (3840, 2160), "white")
self.draw = ImageDraw.Draw(self.flag)
self.last_position = 0
self.count = count
s... |
# Copyright (c) Microsoft Corporation
# All rights reserved.
#
# MIT License
#
# 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 ... |
import connexion
import six
from mcenter_server_api.models.ml_app_pattern import MLAppPattern # noqa: E501
from mcenter_server_api import util
def onboarding_ml_app_patterns_get(): # noqa: E501
"""Get list of all MLApp patterns
# noqa: E501
:rtype: List[MLAppPattern]
"""
return 'do some mag... |
import requests
from requests.api import request
req = requests.get('https://economia.awesomeapi.com.br/json/last/:moedas')
#req = request.json()
print(req)
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 GEO Secretariat.
#
# geo-knowledge-hub is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
from flask import Blueprint
from . import views
def init_bp(app):
bp = Blueprint("ageo_depos... |
from nltk.corpus import stopwords
from nltk import sent_tokenize, word_tokenize
import heapq
from preprocessor import PreProcessor
class ReviewSummarizer:
def generate_summary(self, review):
pp = PreProcessor()
formatted_text = pp.preprocess_review(review, True)
sentences = sent_tokeniz... |
from __future__ import annotations
import json
from pathlib import Path
from typing import Any, Iterator, NamedTuple, Sequence
import astroid
from ._contract import Category
EXTENSION = '.json'
ROOT = Path(__file__).parent / 'stubs'
CPYTHON_ROOT = ROOT / 'cpython'
class StubFile:
__slots__ = ('path', '_conte... |
# Copyright (c) 2020, Huawei Technologies.All rights reserved.
#
# 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 applicable law... |
import numpy as np
from cv2 import cv2
from mss import mss
from PIL import Image
import time
init_time = last_time = time.time()
count = 0
while 1:
with mss() as sct:
monitor = {'top': 40, 'left': 0, 'width': 800, 'height': 450}
img = np.array(sct.grab(monitor))
print('Loop took {} second... |
from tqdm import tqdm
import numpy as np
import random
import itertools
import json
import time
import torch
from torch.autograd import Variable
from torch.utils.data import DataLoader
from rnn.data import DataIterator
from rnn.model import EncoderRNN, DecoderRNN, Attention
def train_model(w2v_model,
... |
import sys
from datetime import timedelta
from unittest import mock
import pytest
from django.contrib.auth import validators as auth_validators
from django.contrib.postgres import validators as postgres_validators
from django.core import validators
from django.urls import path
from rest_framework import serializers
fr... |
'''
Created on May 1, 2011
@author: Mark V Systems Limited
(c) Copyright 2011 Mark V Systems Limited, All rights reserved.
'''
from tkinter import Toplevel, N, S, E, W, messagebox
try:
from tkinter.ttk import Frame, Button
except ImportError:
from ttk import Frame, Button
try:
import regex as re
except Imp... |
# -*- coding:utf-8 -*-
# Copyright (c) 2020 Huawei Technologies Co.,Ltd.
#
# openGauss is licensed under Mulan PSL v2.
# You can use this software according to the terms
# and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#
# http://license.coscl.org.cn/MulanPSL2
#
# THIS SOFTWARE... |
from sleekxmpp.exceptions import IqError
from sleekxmpp.exceptions import IqTimeout
from ConformanceUtils import init_test
from ConformanceUtils import print_test_description
from JoinMUCBot import JoinTestMUCBot
from config import SECOND_BOT
from config import SECOND_BOT_JID
from config import ROOM_JID
#TODO still... |
from MadGraphControl.MadGraphUtils import *
import math
fcard = open('proc_card_mg5.dat','w')
# generate ... QED=0 QCD=3
fcard.write("""
import model DMsimp_s_spin1 -modelname
define p = g u c d s b u~ c~ d~ s~ b~
define j = g u c d s b u~ c~ d~ s~ b~
""")
if "ee" in runArgs.jobConfig[0]:
fcard.write("""
g... |
from django.urls import path
from . import views
urlpatterns =[
path('',views.index, name='index'),
path('homepage',views.homepage, name='homepage'),
path('doneby',views.doneby, name='doneby'),
path('link_1',views.link_1, name='link_1'),
path('link_2',views.link_2, name='link_2'),
pa... |
"""Unit test package for zshpower."""
|
import tkinter as Tkinter
from tkinter import font as tkFont
from docx import Document
import re
Tkinter.Frame().destroy()
chordFont = tkFont.Font(family="Times New Roman", size=8, weight="bold")
textFont = tkFont.Font(family="Times New Roman", size=10)
def isTitle(inputString):
return any(char.isdigit() for char... |
# -*- coding: utf-8 -*-
""""
Setup file.
"""
from setuptools import setup
setup(
use_scm_version=True,
setup_requires=['setuptools_scm'],
)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 25 05:24:19 2018
@author: work
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 24 07:53:43 2018
@author: work
"""
import numpy as np
from preprocess import affine_transform_batch, elastic_transform_batch,\
enhanc... |
# encoding: utf-8
"""
@author: sherlock
@contact: sherlockliao01@gmail.com
"""
import logging
import time
import numpy as np
import torch
import torch.nn as nn
from ignite.engine import Engine, Events
from ignite.handlers import ModelCheckpoint, Timer
from ignite.metrics import RunningAverage
from layers import mak... |
from datetime import timedelta
from airflow import DAG
from airflow.utils.dates import days_ago
from airflow.contrib.operators.mysql_to_gcs import MySqlToGoogleCloudStorageOperator
from airflow.contrib.operators.gcs_to_bq import GoogleCloudStorageToBigQueryOperator
from airflow.contrib.operators.bigquery_operator imp... |
#!/usr/bin/env python
import argparse
import sys
"""
This script generates a source file suitable for compilation. Because our
parser generator (Lemon) always outputs the same symbols, we need a way to
namespace them so that they don't crash. The approach we use will leave the
file as-is, but generate an include wrapp... |
#!/usr/bin/python3.7
"""
API for generating an nForum post following an nLab page edit
---
To use, set up (if it is not already in place) a virtual environment as follows.
python3 -m venv venv
source venv/bin/activate
pip3 install MySQLdb
deactivate
Once the virtual environment has been set up, ... |
from argparse import ArgumentParser
# noinspection PyProtectedMember
class CommandParser(ArgumentParser):
def __init__(
self,
name=None,
aliases=None,
py_function=None,
subcommands=None,
short_description=None,
**kwargs
):
... |
# -*- coding: utf-8 -*-
from openprocurement.tender.core.views.complaint import BaseTenderComplaintResource
from openprocurement.api.utils import get_now
from openprocurement.tender.core.utils import optendersresource
from openprocurement.tender.openua.validation import validate_update_claim_time
from openprocurement.... |
from __future__ import absolute_import, unicode_literals
from django.conf.urls import include, url
from graphene_django.views import GraphQLView
from wagtail.contrib.wagtailsitemaps import views as sitemaps_views
from wagtail.contrib.wagtailsitemaps import Sitemap
from wagtail.wagtailadmin import urls as wagtailadmi... |
import random
a1 = input('Primeiro Aluno:')
a2 = input('Segundo Aluno:')
a3 = input('Terceiro aluno:')
a4 = input('Quarto aluno:')
lista = [a1, a2, a3, a4]
random.shuffle(lista)
print('A ordem sera:')
print(lista)
|
import maglica.request_log
import maglica.util
from termcolor import cprint
import json
def status(args):
options = {
"mandatory": ["id"],
"optional": [],
}
maglica.util.check_args(args, options)
request_log = maglica.request_log.RequestLog()
row = request_log.get_status(args["id... |
from ._version import __version__
from .Azure_Hbase import AzHbaseRestAPI
from .utils import df_to_dict
from .utils import base64_to_string
from .utils import string_to_base64 |
# Generated by Django 3.0.8 on 2020-08-31 16:47
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
... |
import os, sys, struct
import ctypes
import ctypes.util
from functools import wraps
from typing import Callable, TypeVar
import logging
logger = logging.getLogger(__name__)
LibCall = TypeVar("LibCall")
def lookup_dll(prefix):
paths = os.environ.get("PATH", "").split(os.pathsep)
for path in paths:
if n... |
# Copyright 2016-2020, Pulumi Corporation.
#
# 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 t... |
#
# -*- coding: utf-8 -*-
#
# Util/Padding.py : Functions to manage padding
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide,... |
import nel.ntee as ntee
from nel.vocabulary import Vocabulary
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
import nel.dataset as D
from tqdm import tqdm
from nel.abstract_word_entity import load as load_model
from nel.mulrel_ranker import MulRelRanker
from nel.fir... |
# coding=utf-8
# 20160510
# __author__ = 'xhcao'
import numpy as np
import scipy.spatial as sp
# A=self.method.distance_correction_for_one_matrix(X, dimension)\
# B=self.method.distance_correction_for_one_matrix(Y, dimension)\
# corr_matrix[i,j]=self.method.distance_correlation(A,B) "
def distance_c... |
import numpy as np
from collections import OrderedDict
from sklearn import preprocessing
# This file contains the WordVectors class used to load and handle word embeddings
def intersection(*args):
"""
This function returns the intersection between WordVectors objects
I.e.: all words that occur in both obj... |
from tests.utils_testing import *
X = iris.data
y = iris.target
def test_train_then_predict():
gt = GeneticTree(max_iter=10, mutation_prob=0.3)
gt.fit(X, y)
y_pred = gt.predict(X)
assert y_pred.shape[0] == X.shape[0]
unique_classes = set(np.unique(y))
for i in range(y_pred.shape[0]):
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Yolov5TrainGuide.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtC... |
from classes import Produto, Carrinho_Compra
camisa = Produto('Camiseta', 50)
calca = Produto('Tenis', 40)
carrinho = Carrinho_Compra()
carrinho.adiciona(camisa)
carrinho.adiciona(calca)
carrinho.mostra()
print(carrinho.total()) |
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
import os
from io import BytesIO
import pytest
from indico.core... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.