code
stringlengths
1
199k
from flask import jsonify, request, Blueprint import json from random import choice, sample from werkzeug.exceptions import BadRequest api = Blueprint('api', __name__, url_prefix='/api') with open('weapons.json') as fh: weapons = json.load(fh) with open('properties.json') as fh: attributes = json.load(fh) def m...
from os import listdir, path import random import csv import re import natsort import numpy import theano from skimage.io import imread from block_designer import BlockDesigner from sampler import Sampler import pdb class ImageFlipOracle(object): """ *_flip methods should take an image_name """ def __in...
from django import template from django.core.urlresolvers import reverse from Teams.models import Team register = template.Library() @register.inclusion_tag('partials/nav.html', takes_context=True) def nav(context): links = [{'name': 'Home', 'url': reverse('home')}, {'name': 'Teams', 'url': reverse('te...
alien_0 = { "cor": "verde", "pontos": 10 } print(alien_0) print(alien_0.items()) print("----") print(alien_0["cor"]) print(alien_0["pontos"]) print("----") linguagem_favorita = {} linguagem_favorita.__setitem__("paulo", "python") linguagem_favorita.__setitem__("sara", "c") linguagem_favorita.__setitem__("marcio...
import zmq class PROTOCOL: VERSION = "ZCS01" # FLAGS OK = "OK" ERR = "NOK" # COMMANDS GET = "GET" SET = "SET" QUIT = "QUIT" COMMANDS = [ GET, SET, QUIT ] @classmethod def validate(cls, frames): return ( type(...
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HSS1_if_CompleteLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HSS1_if_CompleteLHS. """ # Flag thi...
import os import re import json import shutil import subprocess from io import StringIO from tempfile import mkdtemp, mktemp from distutils.spawn import find_executable import frappe from frappe.utils.minify import JavascriptMinify import click import psutil from urllib.parse import urlparse from simple_chalk import gr...
import json import logging import ryutest from webob import Response from ryu.controller import ofp_event from ryu.controller.handler import CONFIG_DISPATCHER from ryu.controller.handler import set_ev_cls from ryu.app.wsgi import ControllerBase, WSGIApplication, route from ryu.lib import dpid as dpid_lib simple_switch_...
"""Create freedesktop.org-compliant thumnails for album folders This plugin is POSIX-only. Spec: standards.freedesktop.org/thumbnail-spec/latest/index.html """ from __future__ import (division, absolute_import, print_function, unicode_literals) from hashlib import md5 import os import shutil fro...
class Node: # Constructor to initialise node def __init__(self, data): self.data = data self.left = None self.right = None def make_minimal_bst(arr, start, end): if end < start: return None mid = int((start + end) / 2) root = Node(arr[mid]) root.left = make_minima...
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pip...
from __future__ import print_function, division, absolute_import from fontTools.misc.py23 import * from .otBase import BaseTTXConverter class table_V_V_A_R_(BaseTTXConverter): pass
from django.test import TestCase from polling.models import CANDIDATE_CLINTON from polling.models import CANDIDATE_JOHNSON from polling.models import CANDIDATE_STEIN from polling.models import CANDIDATE_TRUMP from polling.tests.factories import StateFactory from users.models import PairProposal from users.tests.factori...
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pip...
"""Console functionality for command line tools.""" import codecs import getpass import shutil import sys import textwrap from django.core.exceptions import ValidationError from django.core.management.color import color_style, no_style from django.utils import termcolors _console = None class Console(object): """Ut...
import sys from msct_base_classes import BaseScript, Algorithm from msct_parser import Parser from msct_image import Image import os import sct_utils as sct import numpy as np from sct_straighten_spinalcord import smooth_centerline def smooth_minimal_path(img, nb_pixels=3): """ Function intended to smooth the m...
class JuliaSet(): def __init__(self, c, n=100): # This is the data for the class - self.c = c self.n = n self._d = 0.001 self.set = [ ] self._complexplane = [ ] def juliamap(self, z) : # This is the method for the class return (z**2 + self.c) def iterate(self...
from requests import get import json import folium import os import webbrowser url = 'https://apex.oracle.com/pls/apex/raspberrypi/weatherstation/getallstations' stations = get(url).json() lons = [station['weather_stn_long'] for station in stations['items']] lats = [station['weather_stn_lat'] for station in stations['i...
import unittest class TestJobDependencyDecorator(unittest.TestCase): def test_job_dep_dec(self): from treetl import Job class JobA(Job): pass @Job.dependency(a_data=JobA) class JobB(Job): pass self.assertEqual(first={}, second=JobA.ETL_SIGNATURE) ...
""" Usage: python newleet.py --pkg="addtwonumers" """ import optparse import os class Solution(object): def __init__(self, pkg_name): root_fd = os.path.split(os.path.dirname(os.path.realpath(__file__)))[0] src_fd = os.path.join(root_fd, ('src/main/java/org/hfeng/leet' + ...
"""Problems views""" from zipfile import ZipFile from flask import render_template, g, flash, redirect, url_for, request, Blueprint, Response from flask_babel import gettext from pysistem import db, redirect_url from pysistem.problems.model import Problem from pysistem.problems.decorators import yield_problem, guard_pr...
from __future__ import unicode_literals from django.db import models, migrations import cloudinary.models class Migration(migrations.Migration): dependencies = [ ('photo_editor', '0007_auto_20160927_1058'), ] operations = [ migrations.CreateModel( name='ImageProcessor', ...
from django.conf.urls import url from users import views from users.views import MyPasswordResetConfirm, MyPasswordResetDone from django.contrib.auth.views import LogoutView from django.conf.urls import include,url app_name = 'users' urlpatterns = [ url(r'^$', views.HomePageView.as_view(), name='index'), url(r'...
import os import json try: import configparser except ImportError: import ConfigParser as configparser import arrow import click import requests from .config import ConfigParser from .frames import Frames from .version import version as __version__ # noqa class WatsonError(RuntimeError): pass class Configu...
from setuptools import setup, find_packages setup( name = 'port_dashboard', version = '1.0', packages = find_packages(), package_data = { '': ['LICENSE', 'README.md'], }, # PyPI metadata description = 'generate a port to-do list from C preprocessor macros', author = 'Michael Labb...
""" Current report shared resources """ from datetime import date from typing import List, Optional, Tuple, Union from avwx.base import AVWXBase from avwx.service import get_service, NOAA_ADDS from avwx.static.core import NA_UNITS, WX_TRANSLATIONS from avwx.structs import Code, ReportData, ReportTrans, Units def wx_cod...
import click from textkit.utils import read_tokens, output @click.command() @click.argument('tokens', type=click.File('r'), default=click.open_file('-')) def tokens2upper(tokens): '''Transform all tokens to uppercase.''' content = read_tokens(tokens) [output(token.upper()) for token in content]
from django.contrib import admin from .models import CourseOrg, Teacher, CityDict class CourseOrgAdmin(admin.ModelAdmin): '''课程机构管理Model''' list_display = ['name', 'category', 'desc', 'address', 'city', 'add_time'] search_fields = ['name', 'category', 'address', 'city'] list_filter = ['name', 'category'...
from django.conf.urls import patterns, include, url from django.contrib import admin from rest_framework import routers from todo.views import TodoViewSet, UserListApiView, UserDetailView admin.autodiscover() router = routers.DefaultRouter() router.register('todos', TodoViewSet, 'todo') urlpatterns = patterns('', #...
import re import unicodedata from django.core.exceptions import ImproperlyConfigured from django.core.validators import validate_email, ValidationError from django.core import urlresolvers from django.db.models import EmailField, FieldDoesNotExist from django.utils import importlib, six try: from django.utils.encod...
import pxlBuffer as pxb import random from time import sleep import time from collections import deque def wheel(pos, brightness): """Generate rainbow colors across 0-255 positions.""" if pos < 85: return pxb.Color(pos * 3 * brightness, (255 - pos * 3) * brightness, 0) elif pos < 170: pos -= 85 return pxb.Colo...
import requests from random import choice from urllib.parse import quote as urlquote from sazabi.types import SazabiBotPlugin class Cat(SazabiBotPlugin): async def parse(self, client, message, *args, **kwargs): if message.content == "~cat": self.logger.debug('Processing cat command') ...
import numpy as np import pandas as pd pd.options.mode.chained_assignment = None # default='warn' def kml2slu(file, write=False): """Converts Polygons drawn in Google Earth to slu used by GeoClaw flag_regions :param str file: path to .kml file downloaded from Google Earth - there must not be any th...
from __future__ import print_function import sys if sys.version_info < (3,): input = raw_input from iterm2_tools.shell_integration import Prompt, Output def run_command(text): if text: print("I got the text", text) return 1 if ' ' in text else 0 if __name__ == '__main__': print(""" Welcome to an...
"""Code to support homekit_controller tests.""" from __future__ import annotations from dataclasses import dataclass from datetime import timedelta import json import logging import os from typing import Any, Final from unittest import mock from aiohomekit.model import Accessories, Accessory from aiohomekit.testing imp...
''' Options Options ------- - jugdir: main jug directory. - jugfile: filesystem name for the Jugfile - cmd: command to run. - aggressive_unload: --aggressive-unload - invalid_name: --invalid - argv: Arguments not captured by jug (for script use) - print_out: Print function to be used for output (behaves like Python3's ...
from odin.fuel.image_data._base import ImageDataset from odin.fuel.image_data.all_mnist import * from odin.fuel.image_data.celeba import * from odin.fuel.image_data.cifar import * from odin.fuel.image_data.lego_faces import LegoFaces from odin.fuel.image_data.shapes import * from odin.fuel.image_data.omniglot import * ...
import random from twitter import * import time text = "" file = open('input.poder') for line in file: for word in line: text += word def count_followers(text): old_word = "" following_frequencies = {} text.lower() for word in text.split(): if (old_word in following_frequencies): ...
""" Copyright (c) 2020 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, ...
import os import sys import shutil import json import numpy as np import pandas as pd def rebuild_folder(dataset_dir): # delete and rebuild dataset directory if os.path.exists(dataset_dir): shutil.rmtree(dataset_dir) os.makedirs(dataset_dir) def write_data(cols, dataset_dir, df, includes_any): i...
from os import path import matplotlib.pyplot as plt from wordcloud import WordCloud def main(): d = path.dirname(__file__) # Catherine's Letters file text = open(path.join(d, 'all_the_letters.txt')).read() # Stopwords file stopwords = open(path.join(d, 'stopwords.txt')).read() # Word Cloud attri...
import re import sys from django.conf import settings from django.core import urlresolvers from django.core.exceptions import ImproperlyConfigured from django.template import loader from . import rjsmin from .js_reverse_settings import (JS_EXCLUDE_NAMESPACES, JS_GLOBAL_OBJECT_NAME, JS_...
from __future__ import unicode_literals class FieldPermissionMixin(object): """Adds simple functionality to check the permissions for the fields""" fields_permissions = {} fields_permissions_read_only = False def get_fieldsets(self, request, obj=None): fieldsets = super(FieldPermissionMixin, sel...
import pytest @pytest.mark.parametrize(('x', 'y', ), [(0, [1]), (0, [1]), (str(0), str([1]))]) def test_foo(x, y): assert str([int(x) + 1]) == y
"""Base class for command handlers.""" __author__ = 'pramodg@room77.com (Pramod Gupta)' __copyright__ = 'Copyright 2012 Room77, Inc.' import json import os from collections import OrderedDict from pylib.base.flags import Flags from pylib.base.term_color import TermColor from pylib.file.file_utils import FileUtils from ...
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'django_summernote.db', } } MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django....
from decimal import Decimal from django.conf import settings from django.core.validators import MinValueValidator from django.db import models from openslides.agenda.mixins import AgendaItemWithListOfSpeakersMixin from openslides.agenda.models import Speaker from openslides.core.config import config from openslides.cor...
if __name__ == "__main__": import time try: import wink except ImportError as e: import sys sys.path.insert(0, "..") import wink w = wink.init("../config.cfg") if "cloud_clock" not in w.device_types(): raise RuntimeError( "you do not have a cloud_c...
print("Hello.")
import logging from bot.bot import command from bot.globals import ADD_AUTOPLAYLIST, DELETE_AUTOPLAYLIST, AUTOPLAYLIST from bot.globals import Auth from cogs.cog import Cog from utils.utilities import read_lines, empty_file, write_playlist, test_url terminal = logging.getLogger('terminal') class BotMod(Cog): def __...
""" Code skeleton for Pygame examples. """ import pygame as pyg import random as rand MAX_LINES = 555 rand_int = rand.randint draw_line = pyg.draw.line class PygView(object): """A Basic Pygame Window. """ def __init__(self, width=800, height=600, max_lines= 222, fps=200): """Standard Initialisation ...
from data import operator_overloading from spec.mamba import * with description('operator_overloading'): with before.all: def overloaded(op, rop): def fn(self, other): return op(self.value, other) return fn @operator_overloading.overload_with_fn(overloaded) class Overloaded(object): ...
""" MindLink API sample. This module exposes methods to perform authentication and basic collaboration operations, like getting, sending messages and streaming messages event from channels. For more information, visit our developer wiki @https://wiki.mindlinksoft.com/tiki-index.php?page=MindLink+API and our engineering...
# -*- coding: utf-8 -*- from .util import Throttle class ThrottleMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): return Throttle(request, view_func, view_args, view_kwargs).check() #return throttle_check(request, view_func, view_args, view_kwargs)
from __future__ import print_function import os import sys from pyspark import SparkContext, SQLContext import pyspark.sql.functions as sql import pyspark.sql.types as types import unicodecsv from dateutil.parser import parse sc = SparkContext(appName="BHLParquet") sqlContext = SQLContext(sc) def as_int(s): return ...
import iris from iris.unit import Unit from iris.cube import CubeList from iris.exceptions import CoordinateNotFoundError, CoordinateMultiDimError iris.FUTURE.netcdf_promote = True iris.FUTURE.cell_datetime_objects = True def time_coord(cube): """Return the variable attached to time axis and rename it to time.""" ...
""" api.py provides an opaque entry point to the Snapchat API. It backs all the requests we will issue to the Snapchat service. """ import hashlib, requests, time from Crypto.Cipher import AES import constants from friend import Friend from snaps import Snap, SentSnap, ReceivedSnap __author__ = "Alex Clemmer, Chad Brub...
import unittest """ A vertex in an undirected connected graph is an articulation point iff removing it (and the edges through it) disconnects the graph. Articulation points represent vulnerabilities in a connected network. A naive approach to find articulation points would be to one by one remove each vertex, and see i...
import numpy from chainer.functions.connection import linear from chainer import link class Linear(link.Link): """Linear layer (a.k.a. fully-connected layer). This is a link that wraps the :func:`~chainer.functions.linear` function, and holds a weight matrix ``W`` and optionally a bias vector ``b`` as p...
from __future__ import print_function from docfly import Docfly import shutil try: shutil.rmtree(r"source\canbeAny") except Exception as e: print(e) docfly = Docfly("canbeAny", dst="source") docfly.fly()
from django.utils import timezone from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from feincms.content.application.models import app_reverse from gtag.models import Tag # , TaggedItem from ask.models import Post from ask.forms import QuestionForm, AnswerForm, Comm...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Messages', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=Fal...
""" Datastreams are identified by the address that publishes them, and referenced in transaction outputs. For CFD leverage, 1x = 5040, 2x = 10080, etc.: 5040 is a superior highly composite number and a colossally abundant number, and has 1-10, 12 as factors. All wagers are in XLT. Expiring a bet match doesn’t re‐open t...
"""Remap Remaps Python keyboard mapping files between OSX and Windows Usage: remap.py remap.py to_osx <osx_file> <win_file> remap.py to_windows <osx_file> <win_file> Options: -h --help Show this screen. --version Show version. """ __author__ = "Indika Piyasena" import os import sys import glob ...
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Group' db.create_table('groups_group', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=Tr...
""" Development of Further Patterns of Enterprise Application Architecture https://martinfowler.com/eaaDev/ https://martinfowler.com/eaaDev/EventSourcing.html """ import re from mobify.source import MultiChapterSource, MobifySource class MartinFowlerSource(MultiChapterSource): BASE = 'https://martinfowler.com/eaaDe...
''' Production Configurations - Use djangosecure - Use whitenoise for storing static files and uploaded media - Use mailgun to send emails - Use Redis for cache ''' from __future__ import absolute_import, unicode_literals from django.utils import six import logging from .common import * # noqa SECRET_KEY = env('DJANGO...
import twitter import time import json import csv import sys reload(sys) sys.setdefaultencoding('utf-8') csv_has_head = False wanted_keys = ['statuses_count', 'followers_count', 'friends_count', 'screen_name', 'created_at', 'location', 'lang', 'profile_image_url_https'] def readList(fileName): with open (fileName, ...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('links', '0001_initial'), ] operations = [ migrations.AlterField( model_name='link', name='create_date', field=models....
from LibicalWrap import * from Property import Property from types import DictType, StringType, IntType class Duration(Property): """ Represent a length of time, like 3 minutes, or 6 days, 20 seconds. """ def __init__(self, arg, name="DURATION"): """ Create a new duration from an RFC2445...
import sys import os import time def now(): return time.asctime(time.localtime(time.time())) print os.getcwd() print now() while True: line = sys.stdin.read() if len(line) == 0: break print line,
from openerp import models,fields,api from openerp.tools.translate import _ from openerp.exceptions import Warning modele_mail=u""" <html> <head> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> </head> <body> <p>Bonjour, </p> <p>Veuille...
import argparse, sys from src.parse_tex import render_math, TEX_MODE import bs4 desc = '''Transforms github with LaTeX as $$ into images'''.strip() parser = argparse.ArgumentParser(description=desc) parser.add_argument('markdown', nargs="?", default="README.md", ...
# number of digits after period # int >= 0 or 'unlimited' # decimal separator # generalize auto_attributes to use it with the other modules # mix-in? class decorator? class Amount: constant_defaults = dict(symbol = '€', precision = 2, symbol_side = 'right') dynamic_defaults = dict(l ...
""" Example Usage: $ INVENTORY_DRIVER=openstack ansible -i inventory machinename -m ping ** Roadmap ** - AWS Support such as (https://github.com/ansible/ansible/blob/devel/contrib/inventory/ec2.py) - Vagrant Support """ from __future__ import print_function from novaclient import client import os, sys, argparse, su...
import requests import datetime import time import json import web.service.github.api.v3.Response import web.log.Log class Users: def __init__(self, reqp, response): self.__reqp = reqp self.__response = response def Get(self): method = 'GET' endpoint = 'users/:username' p...
import flask class Backwards(object): def __init__(self, document): self.document = document def __getattr__(self, attrname): if hasattr(self.document, attrname): val = getattr(self.document,attrname) if type(val) in (string, unicode): return reversed(val)...
from cPickle import loads import collections import logging import os import tempfile import leveldb logger = logging.getLogger('mapreduce') def group_by_key(iterator): '''Group identical keys together. Given a sorted iterator of (key, value) pairs, returns an iterator of (key1, values), (key2, values). ''' l...
from unittest import TestCase from regparser.grammar.tokens import Paragraph class ParagraphTests(TestCase): def test_constructor(self): """Constructor's API gives a few equivalences""" self.assertEqual(Paragraph(part='111', section='22', paragraph='a'), Paragraph(['111', No...
import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import ssl ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = 'https://www.nytimes.com/interactive/2017/06/23/opinion/trumps-lies.html' html = urllib.request.urlopen(url, context=ctx).read() ...
import socket descriptor=socket.socket(socket.AF_INET, socket.SOCK_STREAM) descriptor.connect( ("10.14.0.60", 9876)) descriptor.send(b'+\n') descriptor.send(b'42\n') descriptor.send(b'42\n') descriptor.close()
import importlib from operator import itemgetter import warnings def load_model(model_cls_path, model_cls_name, model_load_args): """Get an instance of the described model. Args: model_cls_path: Path to the module in which the model class is defined. model_cls_name: Name of the model...
import socket, sys, os, subprocess import rwjson punter_args = ['target/debug/punter'] if len(sys.argv) > 1: punter_args = sys.argv[1:] BUFFER_SIZE = 1024*1024 def offline_call(args, inp): print 'calling', args, 'with', inp x = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) data =...
import copy from random import randint import player import ai import mapgrid import mech_types import btlib print '\n- - - - - - -\nWelcome to the Rats in the Walls AI Battletech Simulator!\n- - - - - -\n' World = mapgrid.Map(15,15) Pan = mech_types.M_Panther('Callington', randint(3,5), randint(3,5)) Spid = mech_types...
'''A Python Tkinter Twitter Client''' import sys from os.path import dirname, join, abspath try: sys.path.append(join(abspath(dirname(__file__)), 'twclient')) except: sys.path.append(join(abspath(dirname(sys.path[0])), 'twclient')) __author__ = 'Pierre-Jean Coudert <coudert@free.fr>' __version__ = '0.8' APP_NAM...
""" Affiche un rectangle """ import sys import pygame from pygame.locals import * def main(): pygame.init() SURFACE_AFFICHAGE=pygame.display.set_mode((400,300)) WHITE=(255,255,255) BLUE=(0,0,255) SURFACE_AFFICHAGE.fill(WHITE) pygame.draw.rect(SURFACE_AFFICHAGE,BLUE,(200,150,100,50)) while Tr...
import sys, os sys.path.append('../../../libs/') import os.path import IO_class from IO_class import FileOperator from sklearn import cross_validation import sklearn import numpy as np import csv from dateutil import parser from datetime import timedelta from sklearn import svm import numpy as np import pandas as pd im...
""" This demo program solves a hyperelastic problem. It is implemented in Python by Johan Hake following the C++ demo by Harish Narayanan""" from dolfin import * parameters["form_compiler"]["cpp_optimize"] = True ffc_options = {"optimize": True, \ "eliminate_zeros": True, \ "precompute_bas...
from django import forms class EmailForm(forms.Form): name = forms.CharField(required=False) email = forms.EmailField()
__author__ = "Mario Lukas" __copyright__ = "Copyright 2016" __license__ = "GPL v2" __maintainer__ = "Mario Lukas" __email__ = "info@mariolukas.de" from pykka import ThreadingActor class FSCalibrationMode(object): MODE_AUTO_CALIBRATION = "MODE_AUTO_CALIBRATION" MODE_AUTO_CAMERA_CALIBRATION = "MODE_AUTO_CAMERA_CA...
from collections import OrderedDict from constants import * def print_weights(bias, weights): weight_labels = ['age'] + AGENTS + REFERERS + LANGUAGES + ['price','productid'] + COLOR_TYPES + AD_TYPES + HEADER_TYPES + ['price_sq'] weight_labels = [str(x) for x in weight_labels] for i, x in enumerate(weight_la...
import random from pyromaths.outils import Arithmetique from pyromaths.outils.Priorites3 import texify, priorites def fractions_egales(): exo = ["\\exercice", u"Compléter :", "\\begin{multicols}{4}", " \\begin{enumerate}"] cor = ["\\exercice*", u"Compléter :", "\\begin{multicols}{4}", " ...
from ventana import Ventana from formularios import utils import pygtk pygtk.require('2.0') import gtk, time from framework import pclases import mx.DateTime from informes import geninformes import pango from lib import charting from collections import defaultdict class ConsultaOfertas(Ventana): def __init__(self, ...
import sys reload(sys) sys.setdefaultencoding('utf8') import socket import os import re import select import time import paramiko import struct import fcntl import signal import textwrap import getpass import fnmatch import readline import datetime from multiprocessing import Pool os.environ['DJANGO_SETTINGS_MODULE'] =...
import base64 from datetime import datetime, timedelta import os import string import time import dns from dnsdisttests import DNSDistTest class TestAdvancedAllow(DNSDistTest): _config_template = """ addAction(makeRule("allowed.advanced.tests.powerdns.com."), AllowAction()) addAction(AllRule(), DropAction()...
""" Copyright (C) 2015 Stuart W.D Grieve 2015 Developer can be contacted by s.grieve _at_ ed.ac.uk This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) ...
""" Topic: 使用迭代器重写while无限循环 Desc : """ import sys def reader(s, size): while True: data = s.recv(size) if data == b'': break # process_data(data) def reader2(s, size): for chunk in iter(lambda: s.recv(size), b''): pass # process_data(data) def iterate_whil...
""" MetPX Copyright (C) 2004-2006 Environment Canada MetPX comes with ABSOLUTELY NO WARRANTY; For details type see the file named COPYING in the root of the source directory tree. """ """ """ import PDSPaths, re class CompositePDSClient: """ #######################################################################...
def foo(bar, result, index): print 'hello {0}'.format(bar) result[index] = "foo" from threading import Thread threads = [None] * 10 results = [None] * 10 for i in range(len(threads)): threads[i] = Thread(target=foo, args=('world!', results, i)) threads[i].start() for i in range(len(threads)): thread...
import unittest import math import numpy from PyFoam.Basics.SpreadsheetData import SpreadsheetData theSuite=unittest.TestSuite() names1=['t','p1','p2'] data1=[[(k+1)*i for k in range(len(names1))] for i in range(len(names1)*2)] names2=['t','p1','p3','p4'] data2=[[(k+1)*i for k in range(len(names2))] for i in range(len(...