content
stringlengths
0
894k
type
stringclasses
2 values
import sys import json import twint import threading import lzma import glob import instaloader import os import shutil from datetime import datetime from googleapiclient.discovery import build from facebook_scraper import get_posts from PySide2.QtQml import QQmlApplicationEngine from PySide2.QtCore import QObject, Slo...
python
from _Framework.ButtonSliderElement import ButtonSliderElement SLIDER_MODE_OFF = 0 SLIDER_MODE_TOGGLE = 1 SLIDER_MODE_SLIDER = 2 SLIDER_MODE_PRECISION_SLIDER = 3 SLIDER_MODE_SMALL_ENUM = 4 SLIDER_MODE_BIG_ENUM = 5 #TODO: repeat buttons. # not exact / rounding values in slider and precision slider class DeviceContr...
python
from selenium.webdriver.common.by import By class MainPageLocators(): SEARCH_STRING = (By.ID, 'text') SUGGEST = (By.CSS_SELECTOR, '[role=listbox]') IMAGES = (By.CSS_SELECTOR, '[data-statlog="services_new.item.images.2"]') class ResultPageLocators(): FIRST_RESULT = (By.CSS_SELECTOR, '[data-cid="0"] .organic__path...
python
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function def env_or_default(name, d): from os import environ try: a = environ[name] if a: return type(d)(a) else: return d except Exception: return d def print_stats(steps, t_diff, dl): from time import strf...
python
import glob, os, numpy from music21 import converter, instrument, note, chord from itertools import chain import json import pickle PATH = '../Bach-Two_Part_Inventions_MIDI_Transposed/txt' OUTPUT_PATH = '../Bach-Two_Part_Inventions_MIDI_Transposed/txt_tokenized' CHUNK_SIZE = 4 # MEASURES def write_pickle(filename,...
python
import webbrowser import os import re # Styles and scripting for the page main_page_head = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="Learn To Code Pakistan ...
python
# demo - opencv import cv2 # Black and White (gray scale) img = cv2.imread ('lotus.jpg', 1 ) cv2.imshow('lotus', img) cv2.waitKey(0) # cv2.waitKey(2000) cv2.destroyAllWindows()
python
''' import data here and have utility functions that could help ''' import pandas as pd import pickle from thefuzz import fuzz, process ratings = pd.read_csv('./data/ml-latest-small/ratings.csv') movies = pd.read_csv('./data/ml-latest-small/movies.csv') # import nmf model with open('./nmf_recommender.pkl', 'rb') ...
python
from bs4 import BeautifulSoup import requests import pprint headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'} base_url = 'https://news.ycombinator.com/news' response = requests.get(base_url, headers=headers) soup = Beautiful...
python
#!/usr/bin/env python3 # # __main__.py """ CLI entry point. """ # # Copyright (c) 2020 Dominic Davis-Foster <dominic@davis-foster.co.uk> # # 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...
python
from typing import Any, Union from bot.event import Event, EventType from pydantic.utils import deep_update def event( event_data: Union[str, dict[str, Any]], event_type: EventType = EventType.NEW_MESSAGE, ) -> Event: default = { "chat": {"chatId": "test"}, "from": "someone@mail.ru", ...
python
import cv2 from matplotlib import pyplot as plt img = cv2.imread('open')
python
from pathlib import Path from flask import current_app from flask_marshmallow import Marshmallow from PIL import Image from flask_app.commons.util import pil_to_base64 from flask_app.database.database import Version, Card ma = Marshmallow() class VersionSchema(ma.SQLAlchemyAutoSchema): class Meta: mode...
python
# coding=utf-8 #!/bin/python3 # 这个插件用来去掉Equation的xor系列混淆 # 仅仅支持python 3,只在ida pro 7.7下测试过 # 将本文件放到IDA安装目录的plugins目录下,然后启动ida,在ida View中把光标放在解码函数开始,就可以在 Edit->Plugings->Xor Batch Deobfuscation # 也可以使用快捷键Ctrl+Shift+D进行反混淆 import sys try: import idaapi import idc import idautils import flare_emu # imp...
python
__all__ = ['App'] import control_characters import mdfind import os import plistlib import stat import subprocess import sys from writable_property import writable_property """ path/to/<name>.py class Name(mac_app.App) output: ~/Applications/.mac-app-generator/<name>.app ...
python
from pymongo import MongoClient client = MongoClient() def get_db(): return client['parallel_chat']
python
import numpy as np import os # Readme_2_data_abstracts showed how the data abstracts work. # Technically, they embody all functionality to work with data # This part introduces the dataset class, which is based on a dictseqabstract # This means that you can use it in a similar way. # However it has additional function...
python
from .model import EfficientUnetPlusPlus
python
import machine import time import json # GPIO connections on test fixture gpio_conn = [ { 'out': 2, 'io': (23, 32) }, { 'out': 1, 'io': (33, 34) }, { 'out': 2, 'io': (5, 12, 35) }, { 'out': 2, 'io': (4, 18) }, { 'out': 2, 'io': (13, 15) }, { 'out': 2, 'io': (2, 14) } ] def testGPIO(): # List of problem ...
python
import os import re import sqlite3 import configparser from helpers.logger import Logger from helpers.match import MatchDatabase, MatchSource from helpers.searchwords import Searchwords class File: config = configparser.ConfigParser() config.read("config.ini") non_regex_indicator = config.get("ProgramCo...
python
#!/usr/bin/env python3 """ Interpret all transforms, thereby flattening cairo operations to just a few primitives, such as move_to line_to and curve_to. """ import sys from math import sin, cos, pi from bruhat.argv import argv from bruhat.render import back from bruhat.render.base import Context class Flatten(Cont...
python
"""REPL server for inspecting and hot-patching a running Python process. This module makes your Python app serve up a REPL (read-eval-print-loop) over TCP, somewhat like the Swank server in Common Lisp. In a REPL session, you can inspect and mutate the global state of your running program. You can e.g. replace top-le...
python
# standard from collections import defaultdict, OrderedDict import csv import sys import tempfile import unittest class File: ''' An abstract class simplifying file access through the use of only two functions: - read (file) - write (data, file): ''' @classmethod def read(cls, filename): ...
python
from setuptools import setup, find_packages setup( name="users", version="0.1.0", description="Stoic authentication service", license="Apache", packages=find_packages(), )
python
from __future__ import print_function # for Python 2/3 compatibility try: import queue except ImportError: import Queue as queue import logging import serial import time import threading from binascii import hexlify, unhexlify from uuid import UUID from enum import Enum from collections import defaultdict f...
python
# Problem description: http://www.geeksforgeeks.org/dynamic-programming-set-31-optimal-strategy-for-a-game/ def optimal_strategy(coins): if len(coins) == 1: return coins[0] elif len(coins) == 2: return max(coins[0], coins[1]) else: return max(coins[0] + min(optimal_strategy(coins[2:...
python
import sys from twython import Twython import time import json import os import re import dropbox import subprocess # Secret Keys apiKey = "" apiSecret = "" accessToken = "" accessTokenSecret = "" api = Twython(apiKey,apiSecret,accessToken,accessTokenSecret) tweet = api.get_mentions_timeline() results = api.search(q...
python
# -*- coding: utf-8 -*- # @Author: Sam Zhang # @Date: 2020-04-12 15:36:23 # @Last Modified by: Sam Zhang # @Last Modified time: 2020-04-14 11:27:50 from flask import render_template, request, redirect, url_for from ..utils import google_search from . import google @google.route('/', methods=['GET', 'POST']) def ...
python
""" Merge spotify playlists. """ import argparse import logging from playlist import Playlist def spunify(destination_playlist: str, source_playlists: set[str]): """ Merge the source playlists into the destination playlist. :param destination_playlist: The url of the playlist where the tracks w...
python
#!/usr/bin/python3 import random import math import numpy as np """ Constants """ variance = 0.01 CHECKERBOARD_SIZE = 0.2 """ Functions """ # def get_swiss_roll_dataset(numOfSamples): # sample_list = [] # label_list = [] # for x in range(0, numOfSamples): # # noise_test = random.random() # ...
python
#take1 pre = '581634BED11C647479ED07B47702E21EFE8147CFA57BF08E105A81852F70CF2ADD01B9E8191622AA5CAB3129D7B5F9EB007C2AA98E48E6E4793BD624F94D40B6B07072A17748A96153C6681716D8593261DD8E5CD6ADEE644D432BD282CB521FA4EBF64109D79A60EFA887D7E8EBE5EB9B43F16F84CBC705D12D1CD429B0166B' get = ['7rJ1loTd72z8fyA71JWAYODTEPL1TEIbBSXd0O...
python
# -*- coding: utf-8 -*- """ DEPRECATED """ from __future__ import division, print_function import numpy as np from theano import gof import theano.tensor as tt __all__ = ["tensordotDOp"] class tensordotDOp(tt.Op): def __init__(self, func): self.func = func self._grad_op = tensordotDGradientOp(...
python
# -*- coding: utf-8 -*- """ magic is a wrapper around the libmagic file identification library. See README for more information. Usage: >>> import magic >>> magic.from_file("testdata/test.pdf") 'PDF document, version 1.2' >>> magic.from_file("testdata/test.pdf", mime=True) 'application/pdf' >>> magic.fr...
python
# Copyright 2017 The Bazel 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 applicable la...
python
# -*- coding: utf-8 -*- from __future__ import absolute_import # -- stdlib -- # -- third party -- import gevent # -- own -- # -- code -- def instantiate(cls): return cls() def spawn_autorestart(*args, **kwargs): def restart(g): gevent.sleep(1) spawn_autorestart(*args, **kwargs) gevent...
python
from rest_framework.exceptions import MethodNotAllowed from api.sparse.serializers import SparseNodeSerializer, SparseRegistrationSerializer from api.nodes.views import ( NodeDetail, NodeChildrenList, NodeList, LinkedNodesList, NodeLinkedRegistrationsList, ) from api.registrations.views import Regi...
python
# The sole purpose of this method is to convert the .dbf file that we have # received which contains all addresses in the city to a .csv file import dbfread as dbf #To read our .dbf file import csv #To write to .csv def convert_addresses_to_csv(): with open('addresses.csv', 'wb') as csvfile: headere...
python
# pylint:disable=inconsistent-return-statements """ This module provides a class to visualise Click CLI structures """ import io from contextlib import redirect_stdout from copy import deepcopy from typing import Union, Dict, Any, List import treelib from click import Group, MultiCommand from click_tree_viz.click_...
python
from pprint import pformat import click import py42.sdk.queries.fileevents.filters as f from click import echo from pandas import DataFrame from py42.exceptions import Py42InvalidPageTokenError from py42.sdk.queries.fileevents.file_event_query import FileEventQuery from py42.sdk.queries.fileevents.filters import Inser...
python
import os import sys sys.path.append(".") from Utils.HTMLTestRunner import * from Testcases.test_login import Login from Testcases.test_02 import Test02 # get the directory path to output report file dir = os.getcwd() # get all tests from Login class login1 = unittest.TestLoader().loadTestsFromTestCase(Login) test02...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import dictc class DictCTest(unittest.TestCase): def setUp(self): pass class BaseDictTest(unittest.TestCase): def setUp(self): from DictC.BaseDict import strip_tags self.strip_tags = strip_tags import re se...
python
from .clusterer import Clusterer class ClusterMerge(): def __init__(self, config): self.clusterer = Clusterer(**config) self.pattern_generator = self.clusterer.pattern_generator def merge(self, base_list, other_list): for [reprA, countA, patternA, linesA] in other_list: ex...
python
from setuptools import setup, find_namespace_packages setup(name='sog', version='0.1', description='A creative remake of the 80s MUD', url='', author='Jason Newblanc', author_email='<first>.<last>(at)gmail.com', license='CC0 1.0', packages=find_namespace_packages(include=['sog...
python
''' Util module to initialize SimpleML and configure database management ''' __author__ = 'Elisha Yadgaran' # Import table models to register in DeclaritiveBase from simpleml.persistables.base_persistable import Persistable import simpleml.datasets.base_dataset import simpleml.pipelines.base_pipeline import simpleml...
python
""" Functions and objects describing electro-optic components. """ from arch.block import Block from arch.models.model import Linear, SymbolicModel from sympy import Matrix, sqrt, exp, I, pi import arch.port as port class Switch2x2(Block): """ extinction_ratio: ratio of desired signal to undesired signal from wron...
python
# """ # All operations for the Electricity Spot Market # Based on the role ClearIterativeCO2AndElectricitySpotMarketTwoCountryRole # # Jim Hommes - 25-3-2021 # """ # import json # from modules.marketmodule import MarketModule # from util.repository import Repository # # # class ElectricitySpotMarketSubmitBids(MarketMod...
python
""" Simple integration tests on the API itself. We make actual ajax requests to the running docker container. """ import os import json import unittest import requests from dotenv import load_dotenv load_dotenv('.env') # The URL of the running server from within the docker container url = 'http://web:5000' service_...
python
# -*- coding: utf-8 -*- """ Python File Template """ import os import string from onmt.keyphrase.pke.utils import compute_document_frequency exec('from __future__ import unicode_literals') import os import sys import random module_path = os.path.abspath(os.path.join('../')) if module_path not in sys.path: sys...
python
#!/usr/bin/env python3 # test_app.py import unittest from unittest.mock import patch from snakegame import app from snakegame.player import Player class TestApp(unittest.TestCase): def setUp(self): self.name = "Bob" self.score = 0 self.high_score_name = "John" self.high_score =...
python
"""Add table for datapath Revision ID: ce8079bf4ab7 Revises: None Create Date: 2017-08-26 21:42:40.469444 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'ce8079bf4ab7' down_revision = None branch_labels = None depends_on = None def upgrade(): op.create_t...
python
"""Mock objects for testing""" SUBMISSION_POST_DATA = { "submission": { "_id": "random_string_from_formio", "data": { "project_name": "123 Market St.", "email": "test@test.com", "phone": "415-867-5309", "name": "Jenny" } } }
python
# Python3 import sys import shutil from pathlib import Path # Get the root path to this repo repo_dir = Path(__file__).parent # Get the os dependant kits path if sys.platform == "win32": install_path = Path(r"~\AppData\Roaming\Luxology\Kits").expanduser() elif sys.platform == "darwin": install_path = Path("...
python
from sqlalchemy.ext.asyncio import AsyncSession from app.crud import dialogue_crud from app.service import dialogue_exist async def get_all_dialogues_for_user(db: AsyncSession, user_id: int): """ Get all dialogues for user :param db: DB :type db: AsyncSession :param user_id: User ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_compartmentmodels ---------------------------------- Tests for `compartmentmodels` module. The tests for the individual models are in separate files. """ import pytest #import tempfile import os import numpy as np from compartmentmodels.compartmentmodels imp...
python
from typing import Optional from typing import Union import attr @attr.s class Attachment: content_type = attr.ib(type=str) id = attr.ib(type=str) size = attr.ib(type=int) stored_filename = attr.ib(type=str) @attr.s class Reaction: emoji = attr.ib(type=str) target_author = attr.ib(type=Unio...
python
#!/usr/bin/python # coding: utf-8 # Copyright 2018 AstroLab Software # Author: Chris Arnault # # 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...
python
from ast import literal_eval from database.model_people import ModelPeople from database.model_planet import ModelPlanet from database import base import logging import sys # Load logging configuration log = logging.getLogger(__name__) logging.basicConfig( stream=sys.stdout, level=logging.INFO, format='%(a...
python
import numpy.random as rd import numpy as np from display import * from solver import * def init_list(N): balls = [] r = 10. v = 10. x = 400./float(N+1) for i in range(N): m = r*(1.-0.05*i) vv = [-1.*v, 1.*v] vx = [float(i+1)*x, float(i+1)*x] balls.append(Ball(m, m, ...
python
''' source-directory /etc/network/interfaces.d auto lo iface lo inet loopback auto eth0 iface eth0 inet manual allow-hotplug ppp0 iface ppp0 inet wvdial post-up echo "cellular (ppp0) is online" allow-hotplug wlan0 iface wlan0 inet manual wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf allow-hotplug wlan1 iface w...
python
import torch from PIL import Image import numpy as np from torchvision import datasets, models, transforms import os import glob from models import DoveNetG transformsC = transforms.Compose([transforms.Resize((512, 512)), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) transformsG = tra...
python
""" Desafio 011 Problema: Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área e a quantidade de tinta necessária para pintá-la, sabendo que cada litro de tinta pinta uma área de 2 metros quadrados""" l = float(input('Digite a largura: ')) a = float(i...
python
import torch import torch.nn as nn class FactorizedReduce(nn.Module): """ Reduce feature map size by factorized pointwise(stride=2). """ def __init__(self, C_in, C_out, affine=True): super().__init__() self.relu = nn.ReLU() self.conv1 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, p...
python
from typing import Union, List, Optional from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType # This file is auto-generated by generate_schema so do not edit manually # noinspection PyPep8Naming class DetectedIssueSchema: """ Indicates an actual or potential clinical issue w...
python
# simple no arg function def simple_function(): print 'Hello, function!' simple_function() # simple function with argument def fib(n): a, b = 0, 1 while a < n: print a, a, b = b, a+b fib(10) print '' # example of using documentation string (so-called docstring) def other_function(): """Simple gibbrish print...
python
import pytest from pytest import raises from vyper import compiler from vyper.exceptions import InvalidType, UnknownType fail_list = [ """ x: bat """, """ x: HashMap[int, int128] """, """ x: [bar, baz] """, """ x: [bar(int128), baz(baffle)] """, """ struct A: b: B struct B: ...
python
import os, sys import numpy as np from env_handler import EnvHandler from q_function import Q from logger import Logger from agent import Agent from action_selectors.mbie_eb import MBIE_EB from action_selectors.epsilon_greedy import EpsilonGreedy from action_selectors.boltzmann import Boltzmann from action_selectors.uc...
python
#!/bin/python import sys import yaml import datetime if __name__ == '__main__': filename = sys.argv[1] if len(sys.argv) > 1 else '/Volumes/Kea/devel/MOSSCO/code/external/fabm/code/util/standard_variables/variables.yaml' if not filename: sys.exit(1) with open(filename, 'r') as fid: yml = yaml....
python
import pandas as pd from scholarly import scholarly import plotly.express as px def search_author(name, return_list=False): search_query = scholarly.search_author(name) if not return_list: return next(search_query) else: return list(search_query) def search_author_id(id): try: ...
python
from Tkinter import * from common import Codes from ..controllers import AdminDataController from ..handlers.data import Data class Admin(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.elements = {} title_frame = Frame(self) tit...
python
# Import library(toolkit) for deep learning import numpy as np import os import torch import torch.nn as nn import torchvision.transforms as transforms from torch.utils.data import DataLoader, Dataset import pytorchtools as tools import pandas as pd import time import myfunctions as my # read data workspace_dir = './o...
python
# -*- coding: utf-8 -*- """ Created on Sun Apr 5 04:53:01 2020 @author: Infraestructura 3D """ """ 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 limitatio...
python
from django.core.cache import cache from django.test import Client, TestCase from django.urls import reverse class MoviesTest(TestCase): def setUp(self): self.client = Client() cache.clear() def test_view_movies_correct_template(self): """check if the right template is called""" ...
python
#!usr/env/bin python3 interface = input("enter your interface>>") mac = input("enter new mac>>") print (" ") print ("--------------------------------------------------------------------------") import subprocess subprocess.call("ifconfig " + interface + " down",shell=True) subprocess.call("ifconfig " + i...
python
""" Horizontal boxplot with observations ==================================== _thumb: .7, .45 """ import numpy as np import seaborn as sns sns.set(style="ticks", palette="muted", color_codes=True) # Load the example planets dataset planets = sns.load_dataset("planets") # Plot the orbital period with horizontal boxes...
python
# Generated by Django 3.1 on 2020-08-26 08:48 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('mining', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='match_key', name='MK_key_type', ), ...
python
from flask import Blueprint bp = Blueprint("StCourierServer", __name__, url_prefix="/master") from . import view
python
# # This file is part of the PyMeasure package. # # Copyright (c) 2013-2022 PyMeasure Developers # # 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 limit...
python
"""protected field on Address Revision ID: 427743e76984 Revises: f8c342997aab Create Date: 2021-02-02 11:39:45.955233 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '427743e76984' down_revision = 'f8c342997aab' branch_labels = None depends_on = None def upgr...
python
import binance from config import BINANCE_API_KEY, BINANCE_API_SECRET async def connect(): binance_client = binance.Client(BINANCE_API_KEY, BINANCE_API_SECRET) await binance_client.load() return binance_client
python
#!/usr/bin/python import os import pyopencl as cl import numpy as np # initialize OpenCL def initCl(): PACKAGE_PATH = os.path.dirname( os.path.realpath( __file__ ) ); print(PACKAGE_PATH) #CL_PATH = os.path.normpath( PACKAGE_PATH + '../../cl/' ) CL_PATH = os.path.normpath( PACKAGE_PATH + '/../cl' ) ...
python
# -*- coding: utf-8 -*- import sfml as sf WIDTH = 640 HEIGHT = 480 TITLE = "Python SFML Events" window = sf.RenderWindow(sf.VideoMode(WIDTH, HEIGHT), TITLE) while window.is_open: for event in window.events: if type(event) is sf.CloseEvent: window.close() if type(event) is sf.MouseMov...
python
from flask import Flask, request app = Flask(__name__) def getAllPuppies(): return "Getting All the puppies!" def makeANewPuppy(): return "Creating A New Puppy!" def getPuppy(id): return "Getting Puppy with id {}".format(id) def updatePuppy(id): return "Updating Puppy with id {}".format(i...
python
import numpy as np import matplotlib.pylab as pl pl.rcParams['pdf.fonttype'] = 42 pl.rcParams['ps.fonttype'] = 42 fig = pl.figure(figsize=(12,4)) ax = fig.add_subplot(1,2,1) def plot_perf(nlist, err, color, label, errbar=False, perc=20): pl.loglog(nlist, err.mean(0), label=label, color=color) if errbar: ...
python
from __future__ import unicode_literals __all__ = ['core','util'] import os import warnings import ruamel.yaml as yaml __author__ = "Pymatgen Development Team" __email__ ="pymatgen@googlegroups.com" __maintainer__ = "Shyue Ping Ong" __maintainer_email__ ="shyuep@gmail.com" __version__ = "2017.8.16" SETTINGS_FILE = ...
python
import json import requests import xlrd SOURCES = ( ('awois_wrecks', 'http://wrecks.nauticalcharts.noaa.gov/downloads/AWOIS_Wrecks.xls'), ('enc_wrecks', 'http://wrecks.nauticalcharts.noaa.gov/downloads/ENC_Wrecks.xls'), ) if __name__ == '__main__': for source_item in SOURCES: # Source and URL ...
python
__author__ = 'arjun010' from visObject import * from chartDataFormatter import * from dataFactGenerator import * from itertools import combinations, permutations def getPossibleVisualizations(attributeList, dataList, metadataMap): possibleVisualizations = [] possibleDataFacts = [] itemAttribute = None # i...
python
from __future__ import division # X é o numero no qual queremos a raiz quadrada # I quantidade de interações def calc_raizq(x, chute, i): if i < 1: raise ValueError("É necessário pelo menos uma iteração") if chute < 1: chute = 1 if x < 0: return complex(0, calc_raizq(-x, chute, i)...
python
############################################################################ # Copyright ESIEE Paris (2019) # # # # Contributor(s) : Giovanni Chierchia, Benjamin Perret # # ...
python
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import pytorch_lightning as pl class Net(pl.LightningModule): def __init__(self): super(Net, self).__init__() self.layer1 = nn.Linear(28*28, 1024) self.layer2 = nn.Linear(1024, 128) se...
python
def foo(x): return x*x y = [1,2,3,4,5] z = list(map(foo,y)) for val in z: print(val)
python
# -*- coding: utf-8 -*- __author__ = "Michele Samorani" import pandas as pd import cplex import time import random TIME_LIMIT_SECONDS = 60 def build_scenarios(show_probs, max_scenarios,seed): """ Builds the scenarios :param show_probs: :type show_probs: list[float] :return: a list of (probability,...
python
# This file is part of the Etsin service # # Copyright 2017-2018 Ministry of Education and Culture, Finland # # :author: CSC - IT Center for Science Ltd., Espoo Finland <servicedesk@csc.fi> # :license: MIT """Language and translation utilities""" from flask import request, session from etsin_finder.auth.authenticatio...
python
import pygame; from .drawable import Drawable; # --------------------------------------------------- *\ # [class] Image() # # * Image element * # # --------------------------------------------------- */ class Image(Drawable): # --------------------------------------------------- *\ # [function] __init__(): # # ...
python
""" This file contains all the sales related resources """ # Third party imports from flask import request, json, abort from flask_restplus import Resource from flask_jwt_extended import jwt_required, get_jwt_identity # Local application imports from app.api.v1.models.sales import Sale from app.api.v1.models.db imp...
python
from flask import Flask, render_template,request, session , redirect , url_for , g,flash, jsonify, make_response, json,flash from flask_mail import Mail,Message from flask_cors import CORS from pusher import pusher from flask_wtf import FlaskForm from wtforms import (StringField ,PasswordField,SubmitField) from w...
python
#!/usr/bin/env python3 # ----------------------------------------------------------------------- # VIZPAIRWISESEQ # Copyright 2015, Stephen Gould <stephen.gould@anu.edu.au> # ----------------------------------------------------------------------- # Script to visualize an integer sequence based on the visualization of #...
python
import sys sys.path.append("../bundle_adjustment/ceres-solver/ceres-bin/lib/") # so import PyCeres import numpy as np import scipy.io as sio import cv2 from utils import geo_utils def order_cam_param_for_c(Rs, ts, Ks): """ Orders a [m, 12] matrix for the ceres function as follows: Ps_for_c[i, 0:3] 3 para...
python
"""Turrets and torpedo mpunt data in a useable form""" from schemas import TURRETS class Turret: """Container for the data needed to draw a turret Args: caliber (int): caliber of the gun in inches (urgh) pos (string): the letter of the turret, like "A", "X", etc... positio...
python
# Copyright (c) 2021, Carlos Millett # All rights reserved. # This software may be modified and distributed under the terms # of the Simplified BSD License. See the LICENSE file for details. import abc from pathlib import Path from .types import Types class Media(abc.ABC): def __init__(self, media_type: Type...
python
class Solution(object): def minDistance(self, w1, w2): if w1 == "": return len(w2) if w2 == "": return len(w1) l1 = len(w1) l2 = len(w2) d=[] for i in range(l1+1): d.append([0] * (l2 + 1)) for i in range(0, l1 + 1): ...
python