content
stringlengths
0
894k
type
stringclasses
2 values
import re import json import requests import time from urllib.parse import unquote import os headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36', 'referer': 'https://youtube.com'} class Caption: def __init__(self, url, l...
python
import torch from torch.autograd import Function from torch.autograd.function import once_differentiable from torch._thnn import type2backend from .thnn.auto import function_by_name import torch.backends.cudnn as cudnn MODE_ZEROS = 0 MODE_BORDER = 1 class GridSampler(Function): @staticmethod def forward(ctx...
python
from unittest import TestCase from starmie import AStarProblem class Maze(AStarProblem): WALL = 'O' START = 'S' GOAL = 'G' ROAD = ' ' PATH = '*' def __init__(self, map_data, allow_slant=True): self.map = [] self.start = None self.goal = None for x, line in enum...
python
"""cmlkit exceptions.""" class DependencyMissing(Exception): """Raised when an optional dependency is needed.""" ...
python
#!/usr/bin/env python __description__ = \ """ compareAncestor.py """ __author__ = "Michael J. Harms" __usage__ = "comapreAncestors.py ancestor_file1 ancestor_file2" __date__ = "100726" import sys, phyloBase class CompareAncestorError(Exception): """ General error class for this module. """ pass ...
python
conv_encoder = km.Sequential(name="ConvEncoderModel") conv_encoder.add(kl.Conv2D(16, (3,3) , activation='relu', input_shape=(28,28,1) , padding='same' )) conv_encoder.add(kl.MaxPooling2D((2, 2), padding='same')) conv_encoder.add(kl.Conv2D(8, (3, 3), activation='relu', padding='same')) conv_encoder.add(kl.MaxPooling2D((...
python
"""Tests for appname application.""" from unittest import TestCase from django.test import TestCase as DjangoTestCase class TestSuiteTestCase(TestCase): """General test to make sure that the setup works.""" def test_test_suite_can_be_run(self): self.assertTrue(True) class ExampleTestCase(DjangoTest...
python
# # PySNMP MIB module EXPAND-NETWORKS-SMI (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EXPAND-NETWORKS-SMI # Produced by pysmi-0.3.4 at Wed May 1 13:07:01 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
python
''' 思路: 位图1,用于判断是否存在该词。对于每次读进来的词,计算哈希值,相应比特位置1。 位图2,用于标志是否重复。对于读进来的并且是被位图1标志过存在的词,则置1 队列,用于保存不重复词。队尾保留最新不重复词,每次push都是在队尾,pop则不一定 (改用队列,主要是为了防止大文件都是不相同词时,要遍历整个hashmap,相当于遍历大文件两遍) ''' # 伪码 # 遍历文件 for word in largeFile: if bitmap1.isExist(word): bitmap2.add(word) pop word from dueue else: ...
python
import datetime from django.conf import settings from rest_framework.settings import APISettings from .utils import hash_string USER_SETTINGS = getattr(settings, 'JWT2FA_AUTH', None) DEFAULTS = { # Length of the verification code (digits) 'CODE_LENGTH': 7, # Characters used in the verification code ...
python
from __future__ import unicode_literals from django.core.exceptions import ObjectDoesNotExist from django.forms.models import ModelForm, model_to_dict from .constants import (MODERATION_STATUS_PENDING, MODERATION_STATUS_REJECTED) from .utils import django_17 class BaseModeratedObjectForm(ModelForm): class Meta:...
python
"""Lightly modified build_ext which captures stderr. isort:skip_file """ # IMPORTANT: `import setuptools` MUST come before any module imports `distutils` # background: https://bugs.python.org/issue23102 import setuptools # noqa: F401 import distutils.command.build_ext import distutils.core import io import os impor...
python
import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.init import numpy as np from unet import * from utils import * def weight_init(m): if isinstance(m, nn.Conv3d) or isinstance(m, nn.Conv2d): torch.nn.init.kaiming_normal_(m.weight.data) if m.bias is not None: m.bias.data.fill_(...
python
# modified jetbot physical implementation import atexit import subprocess import traitlets from traitlets.config.configurable import Configurable class Motor(Configurable): value = traitlets.Float() # config alpha = traitlets.Float(default_value=1.0).tag(config=True) beta = traitlets.Float(defau...
python
from gui.contract import IView, IPresenter from gui.presenter import Presenter import time from tkinter import * from command.queue.buildthread import BuildThread from command.queue.properties import QueueProperties from utils.context import Context from utils.travian_utils import login_to_account, create_browser fro...
python
#!/usr/bin/env python3 # # Given a configuration executes p2rank and all components. # import json import os import logging import requests import shutil import subprocess import conservation_wrapper from model import * from output_prankweb import prepare_output_prankweb from output_p2rank import prepare_output_p2rank...
python
import ConfigParser def readConfig(): config = ConfigParser.ConfigParser() config.readfp(open("sharenet.ini")) binDir = config.get("Import", "bin") inDir = config.get("Import", "in") workDir = config.get("Import", "work") doneDir = config.get("Import", "done") dbHost = config.get("Database", "host") dbName = c...
python
import bpy from ..sollumz_properties import SollumType, SOLLUMZ_UI_NAMES, BOUND_POLYGON_TYPES from ..ybn.collision_materials import create_collision_material_from_index from ..tools.meshhelper import create_box, create_sphere, create_capsule, create_cylinder from mathutils import Vector, Matrix def create_bound_shap...
python
import asyncio from netschoolapi import NetSchoolAPI async def main(): login_data = { "login": "Иван", "password": "Иван228", "school": "МАОУ многопрофильный лицей №20" } async with NetSchoolAPI("http://sgo.cit73.ru/", **login_data) as api: print(await api.get_announcement...
python
import datetime import unittest from search.ql import Query, Q, GeoQueryArguments from search.fields import TextField, GeoField, DateField from search.indexes import DocumentModel class FakeDocument(DocumentModel): foo = TextField() bar = DateField() class FakeGeoDocument(DocumentModel): my_loc = GeoFi...
python
import copy import random import math import numpy as np from Higashi_backend.utils import * from Higashi_backend.Functions import * import multiprocessing import time from torch.nn.utils.rnn import pad_sequence from sklearn.decomposition import PCA from sklearn.preprocessing import normalize from scipy.sparse import...
python
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, api class RemovalStrategy(models.Model): _name = 'product.removal' _description = 'Removal Strategy' name = fields.Char('Name', required=True) method = fields.Char("Met...
python
# AUTOGENERATED! DO NOT EDIT! File to edit: 01c_grad_utils.ipynb (unless otherwise specified). __all__ = ['cg', 'cat_list_to_tensor', 'reverse_unroll', 'reverse', 'fixed_point', 'CG', 'CG_normaleq', 'neumann', 'exact', 'grd', 'list_dot', 'jvp', 'get_outer_gradients', 'cat_list_to_tensor', 'update_tensor_gra...
python
import bisect import keyword import rope.base.simplify MINIMAL_LEN_FOR_AS = 5 def get_name_at(resource, offset): source_code = resource.read() word_finder = Worder(source_code) return word_finder.get_word_at(offset) class Worder(object): """A class for finding boundaries of words and expressions ...
python
def main(): import RPi.GPIO as GPIO try: print('UNKNOWN:%d' % GPIO.UNKNOWN) print('SERIAL:%d' % GPIO.SERIAL) print('SPI:%d' % GPIO.SPI) print('I2C:%d' % GPIO.I2C) print('HARD_PWM:%d' % GPIO.HARD_PWM) GPIO.setmode(GPIO.BOARD) GPIO.setup(3, GPIO.OUT) ...
python
""" .. module:: Facemovie :platform: Unix, Windows :synopsis: Main class of the application. Contains the core image processing functions, and contains API methods. .. moduleauthor:: Julien Lengrand-Lambert <jlengrand@gmail.com> """ import os import sys import logging import cv from util import exif import G...
python
# # copyright_notice # """smap wrappers """ __all__ = () from opengltk.extent import smaplib, utillib
python
import pytest from lj506.skeleton import fib, main __author__ = "Eric Busboom" __copyright__ = "Eric Busboom" __license__ = "MIT" def test_access(): """API Tests"""
python
import logging import uuid from assistant.orders.models import LineItem from .models import Stock from .exceptions import InsufficientStock logger = logging.getLogger(__name__) def process_simple_stock_allocation(**data): stocks = Stock.objects.filter(product_variant=data.get("variant")) line_items = data....
python
from flask import request, render_template, make_response from datetime import datetime import psycopg2 import os #__ Configure access to .env file from dotenv import load_dotenv from pathlib import Path # python3 only def get_query_by_id(id_to_update): """ Get all ranks from pathogen table """ #L...
python
## ## Copyright (C) 2017, Amit Aides, all rights reserved. ## ## This file is part of Camera Network ## (see https://bitbucket.org/amitibo/cameranetwork_git). ## ## Redistribution and use in source and binary forms, with or without modification, ## are permitted provided that the following conditions are met: ## ## ...
python
"""Module for the main SqsTestPrefix Construct.""" # Standard library imports import json # Third party imports from aws_cdk import core as cdk, aws_sqs as sqs, aws_lambda as lambda_ # Local application/library specific imports from filter_dynamodb_event_streams_sent_to_lambda.lambda_function import LambdaFunction ...
python
from com.sun.star.style.ParagraphAdjust import CENTER, LEFT, RIGHT, BLOCK, STRETCH from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK, APPEND_PARAGRAPH, LINE_BREAK def populateTopText(cursor, doc, text, practice): styles = doc.StyleFamilies page_styles = styles.getByName("PageStyles") oDefault...
python
#!/usr/bin/env python """ This script computes the features necessary to achieve the results on the SHS training set reported in the paper: Humphrey, E. J., Nieto, O., & Bello, J. P. (2013). Data Driven and Discriminative Projections for Large-Scale Cover Song Identification. In Proc. of the 14th International Socie...
python
import json import pika #create client class,since we want to connect to different cloudamqp instances class CloudAMQPClient: def __init__(self, cloud_amqp_url, queue_name): self.cloud_amqp_url = cloud_amqp_url self.queue_name = queue_name self.params = pika.URLParameters(cloud_amqp_url) ...
python
# -*- coding: utf-8 -*- """ Class Piece: The shapes of tetrimonos each of them was a tuple of tuples containing the rotations PIECES is a dict containing all the shapes where number as a key. {1: I, 2: J, 3: L, 4: O, 5: S, 6:T, 7:Z} @author: Chens https://github.com/ChenSunMac """ class Piece: ...
python
import sys,os keywords = ['PLPS_path', 'PDB2PQR_path', 'APBS_path', 'XLOGP3_path', 'ligand_file', 'BABEL_path',\ 'n_conf', 'OMEGA_path'] def read_input(input_file): file = open(input_file, 'r') lig_file = [] for line in file: key = line.split()[0] if(key == keywords[0]): ...
python
from featurechart import * from treeview import * def demo(): cp = load_earley('gazdar6.cfg', trace=2) trees = cp.parse('the man who chased Fido returned') for tree in trees: print tree #run_profile() if __name__ == '__main__': demo()
python
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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 appl...
python
import operator class MultiMapping: def __init__(self, *stores): self.stores = list(stores) def __getitem__(self, key): for store in self.stores: if key in store: return store[key] raise KeyError(key) _marker = [] def get(self, key, default=_marker): ...
python
import logging import shutil from pathlib import Path from typing import List, Tuple, Union import numpy as np import pandas as pd from genomics_data_index.storage.SampleSet import SampleSet from genomics_data_index.storage.index.KmerSearchManager import KmerSearchManagerSourmash from genomics_data_index.storage.mode...
python
import numpy as np class SimulationGoal: """ A class that tracks whether the simulation has reached its global goal. """ def __init__(self): """ We set the self.is_done to False as a start. """ self.is_done = False def goal_reached(self, grid_world): """ ...
python
# -*- coding: utf-8 -*- import os import stat serverScript="dnsserver.py" serverScriptFolder="modules" dbFolder="databases" dbFile="storage.sqlite" server_script_path=os.path.join(request.folder,"modules","dnsserver.py") st = os.stat(server_script_path) os.chmod(server_script_path, st.st_mode | stat.S_IEXEC) server_pa...
python
import matplotlib.pyplot as plt f = open("../data/train_small.csv", 'r') g = open("../data/test_small.csv", 'r') #Skip the head line f.readline() g.readline() ################################################ train_label_data, train_feature_data = [], [] for line in f: labels = line.split(',') labels = map(str.st...
python
from naive_bayes import NaiveBayesClassifier def test_evaluate_algorithm(): classifier = NaiveBayesClassifier() dataset = [[3.393533211, 2.331273381, 0], [3.110073483, 1.781539638, 0], [1.343808831, 3.368360954, 0], [3.582294042, 4.67917911, 0], ...
python
# ************************************* # |docname| - Misc CLI tools for Docker # ************************************* # This files provides most of the subcommands for `docker_tools.py`. # # If you want to add a new subcommand you must add it to the list in the add_commands # function. That command ensures that dock...
python
import os import io import base64 from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend #from cryptography.hazmat.primitives import padding from cryptography.hazmat.backends.o...
python
from pathlib import Path import unittest import re from unittest.mock import patch from typer.testing import CliRunner from plotly.graph_objects import Figure from tempfile import NamedTemporaryFile from ausdex import main class TestMain(unittest.TestCase): def setUp(self): self.runner = CliRunner() ...
python
''' Created on Feb 9, 2019 @author: NOOK ''' from abc import ABC from numpy import array, zeros from math import sqrt, sin, cos, atan2, pi def POW(a, b): return a**b; class RadarCoordinatesTemplate(ABC): ''' classdocs ''' def __init__(self): ''' Constructor ''' ...
python
#!/usr/bin/env python3 # # Copyright (c) 2015 - 2021, Intel Corporation # # 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, th...
python
import path_utils import os import Sample import gym_raas replot_dir = "" dir = os.path.join(path_utils.get_output_dir(), replot_dir) s = Sample.replot_sample_dict_from_dir(dir)
python
__author__ = 'Przemyslaw "Blasto" Wentrys' @app.route('/mysql/testt') def mysql_test(): execute = MySQL_Connection().execute_query query = MySQL_Functions() server = 'Naboo' database = 'jira' table = 'jiraissue' columns = '*' return str(execute(server, query.check_for_existence(database...
python
#!/usr/bin/env python3 """ See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a list of status code """ from .rfc7285 import mimetypes import logging import traceback import bottle def is_error(code): return not code in [200, 204] def format_error(response = bottle.response, message='', exception = ...
python
############################################################################## # # Copyright (c) 2003-2018 by The University of Queensland # http://www.uq.edu.au # # Primary Business: Queensland, Australia # Licensed under the Apache License, version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # # Development unt...
python
''' File: dict_merge.py Project: 01-DataSturcture =========== File Created: Tuesday, 21st July 2020 4:49:05 pm Author: <<LanLing>> (<<lanlingrock@gmail.com>>) =========== Last Modified: Tuesday, 21st July 2020 4:49:09 pm Modified By: <<LanLing>> (<<lanlingrock@gmail.com>>>) =========== Description: 字典合并 Copyright <<202...
python
""" A module for (non-TS) species conformer generation Note: variables that contain atom indices such as torsions and tops are 1-indexed, while atoms in Molecules are 0-indexed. Todo: * Consider boat-chair conformers (https://en.wikipedia.org/wiki/Cyclohexane_conformation) * finally, consider h-bonds ...
python
class FibonacciCode: def fib_sequence(self, n, decode=False): l = [] a = 0 b = 1 if decode: for _ in range(n + 2): l.append(a) a, b = b, a + b else: while a <= n: l.append(a) a, b = b, a ...
python
#!/usr/bin/env python3 import pandas as pd import numpy as np import matplotlib.pyplot as plt def split_date(df): # Remove the empty lines df = df.dropna(how="all") # Create a new dateframe for only the date and time date = df.Päivämäärä.str.split(expand=True) # Change column names d...
python
class CSVNoDupPlugin: def input(self, infile): inputcsv = open(infile, 'r') self.lines = [] for line in inputcsv: self.lines.append(line.strip().split(',')) def run(self): # Find dups in first line names = [] dups = [] for element in self.lines[0]...
python
# Dependencies from bs4 import BeautifulSoup import pandas as pd import datetime as dt from splinter import Browser import time import re # Define a function called `scrape` that will execute all of your scraping code from the `mission_to_mars.ipynb` notebook and return one Python dictionary containing all of the scr...
python
import json from django.conf import settings from django.core.urlresolvers import reverse from django.test import TestCase from rest_framework.test import APIClient import annotator from annotator import models class RootTestCase(TestCase): """ See the documentation for the `root <http://docs.annotator...
python
try: # detect if concurrent.futures is available as a Python # stdlib or Python 2.7 backport from ..futures import patch as wrap_futures from ..futures import unpatch as unwrap_futures futures_available = True except ImportError: def wrap_futures(): pass def unwrap_futures(): ...
python
# proxy module from __future__ import absolute_import from apptools.naming.binding import *
python
from datetime import date import boundaries boundaries.register('Halifax districts', domain='Halifax, NS', last_updated=date(2012, 11, 6), name_func=boundaries.attr('DISTNAME'), id_func=boundaries.attr('DIST_ID'), authority='Halifax Regional Municipality', notes='We use a shapefile received vi...
python
import os from pathlib import Path import quickfix as fix from dotenv import load_dotenv from fixit.application import Application _ = load_dotenv() def main(path): try: settings = fix.SessionSettings(path.name) application = Application( username=os.environ['FIX_USERNAME'], ...
python
from collections import defaultdict class Graph(): def __init__(self,vertices): self.graph = defaultdict(list) self.V = vertices def addEdge(self,u,v): self.graph[u].append(v) def isCyclicUtil(self, v, visited, recStack): visited[v] = True recStack[v] = True for neighbour in self.graph[v]: if vi...
python
#!/usr/bin/env python """Classes that provide abstractions of different image source manifests.""" import json import re from typing import List, Set, Union from docker_registry_client_async import FormattedSHA256, ImageName, JsonBytes from .manifest import Manifest class ArchiveChangeset(JsonBytes): """ ...
python
from Chef import Chef from ChineseChef import ChineseChef myChef = Chef() myChef.make_special_dish() myChineseChef = ChineseChef() myChineseChef.make_fried_rice()
python
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** 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...
python
""" This file implements a deep neural network that tries to predict the next position of the laser spot from the current position of the laser spot. """ import numpy as np import observations_set from keras import Sequential from keras.layers import Dense from keras.models import Model, model_from_json from keras.opt...
python
"""Top-level {{cookiecutter.package_slug}} package.""" import logging from logging import NullHandler __author__ = '{{cookiecutter.full_name}}' __email__ = '{{cookiecutter.email}}' __version__ = '{{cookiecutter.version}}' logging.getLogger(__name__).addHandler(NullHandler())
python
"""polysearch URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-ba...
python
import random shapes = [ [ (1, 1, 1, 1) ], [ (1, 0), (1, 0), (1, 1) ], [ (0, 1), (0, 1), (1, 1) ], [ (0, 1), (1, 1), (1, 0) ], [ (1, 1), (1, 1) ] ] class Block: def __init__(self): self.shape = random.choice(shapes) s...
python
from image_match.goldberg import ImageSignature gis = ImageSignature() a = gis.generate_signature('MonaLisa_Wikipedia.jpg') b = gis.generate_signature('MonaLisa_WikiImages.jpg') c = gis.generate_signature('Caravaggio_Wikipedia.jpg') print('a = MonaLisa_Wikipedia.jpg\n','b = MonaLisa_WikiImages.jpg\n','c = Caravaggio_Wi...
python
#!/usr/bin/env python from distutils.core import setup setup(name='XUnit2HTML', version='1.0.1', description='A tool for converting xunit generated xml files into an html report', author='Gudni Olafsson', author_email='gudni.olafsson@gmail.com', py_modules=['xunit2html'], scripts=[...
python
#!/usr/bin/envthon # coding: utf-8 import requests from bs4 import BeautifulSoup import re import sys import os, shutil #from internal_processing import get_job_details, get_name_and_loc, get_posted_and_applicants from internal_processing import get_job_title, get_job_id, get_job_description from helpers import s...
python
# Source https://github.com/NVlabs/PWC-Net/blob/master/PyTorch/models/PWCNet.py import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from matplotlib.pyplot import imread import matplotlib.pyplot as plt import os # os.environ['PYTHON_EGG_CACHE'] = 'tmp/' # a writable ...
python
import pytest import tensorflow as tf from doctr.models import backbones @pytest.mark.parametrize( "arch_name, input_shape, output_size", [ ["vgg16_bn", (224, 224, 3), (7, 56, 512)], ["resnet31", (32, 128, 3), (4, 32, 512)], ["magc_resnet31", (32, 128, 3), (4, 32, 512)], ["mob...
python
from fsm.models import ActivityLog def quit_edge(self, edge, fsmStack, request, **kwargs): """ Edge method that terminates this live-session. """ for studentState in fsmStack.state.linkChildren.all(): studentState.linkState = None # detach from our state studentState.save() return...
python
from core import Bot from templates import Template template = Template() class Message: def message(self): @Bot.bot.message_handler(content_types=['text']) def text_message(message): if message.text == "/start": Bot.bot.reply_to(message, template.start(), parse_mode='H...
python
from django.conf.urls import include, url from tumblelog.views import ( PostIndexView, AddPostView, PostDetailView, UpdatePostView, DeletePostView, ImageFileView, TestSessionView, ) from django_mongoengine import mongo_admin post_patterns = [ url(r'^$', PostDetailView.as_view(), name="post"), url...
python
#!/usr/bin/python3 # ============================================================================= # CrowdTangle Utils # ============================================================================= # # Miscellaneous utility functions to be used with CrowdTangle Link. # @Author: Brayan Rodriguez <bradrd2009jp@gmail.co...
python
# -*- coding: utf-8 -*- ############################################################################# # # Copyright © Dragon Dollar Limited # contact: contact@dragondollar.com # # This software is a collection of webservices designed to provide a secure # and scalable framework to build e-commerce websites. # # This s...
python
# import numpy as np # r= [1.0,1.0,1.0,-1.0,1.0,1.0] # gamma = 0.5 # # r = np.array(r) # discounted_r = np.zeros_like(r) # running_add = 0 # # we go from last reward to first one so we don't have to do exponentiations # for t in reversed(range(0, r.size)): # if r[t] != 0: # running_add = 0 # if the game end...
python
from django.shortcuts import render from project.models import Project def project_index(request): p1 = Project( title='My First Project', description='A web development project.', technology='Django', image='img/project1.png' ) p2 = Project( title='My Second Pro...
python
import ephem manen = ((ephem.Io(), 'i'), (ephem.Europa(), 'e'), (ephem.Ganymede(), 'g'), (ephem.Callisto(), 'c')) nu = ephem.now() interval = ephem.minute m = ephem.Europa() t = nu lengte = 80 jupiterIndex = int(lengte / 2) + 1 while True: regel = lengte * [' '] regel[jupiterIndex...
python
# 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
python
# Copyright (c) 2016-present, Facebook, Inc. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unittest from unittest.mock import ( MagicMock, patch, ) from ... import commands from ...commands import restart from .command_test...
python
from django.template import Engine _dirs_undefined = object() class JsEngine(Engine): def __init__(self, dirs=None, app_dirs=False, allowed_include_roots=None, context_processors=None, debug=False, loaders=None, string_if_invalid='', file_charset='utf-8'): ...
python
# -*- coding: utf-8 -*- from ffmpymedia import __author__, __version__, __version_info__, __copyright__ video_codecs = {'mpeg2video': 'MPEG-2 video', 'h264': 'H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10', 'vp8': 'On2 VP8', 'mpeg4': 'MPEG-4 part 2', 'theora...
python
# -*- coding: utf-8 -*- #障碍跑 #使用时请将ip改成需要连接的机器人 #winxos 2012-07-14 import time,math import wsNaoVisionMT as wsnv import wsNaoMotion as wsnm import numpy as np import obstacleState as state ground=np.array([[0,0,80],[180,220,255]]) if __name__ == '__main__': ip="192.168.1.103" #修改此处ip地址为机器人实际连接ip nv=wsnv.wsNaoV...
python
import argparse import os import shutil import stat if __name__ == "__main__": if os.getuid() != 0: print("This script is intended to be run as root!") print("By doing this, we isolate the commands that truly need privilege.") print("This script runs: cp, chmod (on only the input/output fil...
python
import json import pygame from ceEntity import CEEntity import ceSprite import ceColor import ceText import ceGame def rowToInts(row): return [int(s) for s in row.split()] def clamp(val, mn, mx): if val<mn: return mn elif val>mx: return mx else: return val class CEStage(CEEnti...
python
# Generated by Django 3.0 on 2021-03-20 12:17 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('udaan_app', '0001_initial'), ] operations = [ migrations.CreateModel( name='QuizResponse', ...
python
"""Stock feature generation including momentum indicators and volatility Currently RSI (Relative Strength Index), volatility, and price return rank are successfully calculated for each stock and for each day based on the basic price data ingested from yahoo. To Run the program, the stock_price_and_returns.c...
python
#!/usr/bin/env python import pika def on_request(ch, method, props, body): n = int(body) response = n*n print(" [.] Calculando %s * %s = %s" % (n, n, response)) ch.basic_publish(exchange='', routing_key=props.reply_to, properties=pika.BasicProperties(correlat...
python
from datetime import datetime, timedelta from django.conf import settings from django.contrib import messages from django.http import HttpResponseRedirect from django.utils.http import is_safe_url from django.utils.translation import override from django.views.generic import View from pretalx.common.phrases import ph...
python
from numba import jit @jit def fibo(n): if n < 2: return n return fibo(n-1) + fibo(n-2) print(fibo(45))
python
# Training script with LazyLoader # # Instead of dumping all input into memory, we lazy load on the fly. # This can create an IO bound where slow training down but helping to training large dataset such as MetaVideoLazy import os from tqdm.auto import tqdm from opt import config_parser import logging import ruamel....
python
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from django.test import TestCase from accountsynchr.trumba_gws import TrumbaToGws from accountsynchr.tests import fdao_gws_override @fdao_gws_override class TestTrumbaToGws(TestCase): def test_group_manager(self): tg ...
python