src
stringlengths
721
1.04M
import cPickle import numpy as np import pandas as pd import re import sys from collections import defaultdict def build_data_cv(data_folder, cv=10, clean_string=True): """ Loads data. """ revs = [] pos_file = data_folder[0] # train file neg_file = data_folder[1] # test file devel_file = d...
import unittest from acsmx2.search import Matcher, MatchedWord class MatchTestCase(unittest.TestCase): def setUp(self): self.matcher = Matcher(1024) def test_abc(self): for i, pattern in enumerate([ b'hello', b'world', b'ld', ]): ...
# Copyright 2015 Fortinet, Inc. # # 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 law or...
# coding: utf-8 import os from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.core import urlresolvers from django.db import models from django.utils.translation import ugettext as _ from core.utils import get_...
#!/usr/bin/env python import socket from http_handler import Handler_thread MAX_CONNECTIONS = 5 class HTTPserver(object): def __init__(self, localOnly=False, port=80, max_connections=MAX_CONNECTIONS): self.port = port self.max_connections = max_connections if localOnly: self.hostname = '127.0.0.1' else: ...
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2018 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Nathan Fluckiger <nathan.fluckiger@hotmail.ch> # # The licence is in the file __m...
from __future__ import unicode_literals __author__ = 'hz' import nltk class DataFormat: def __init__(self): pass def dataFormat( self, _sentence ): """ format the input data and save it in the tmp file :param _sentence: :return: """ if isinstance( _sente...
from multiprocessing.connection import Client from random import random from time import sleep from multiprocessing.connection import Listener from multiprocessing import Process local_listener = (('127.0.0.1', 5003),'secret client 3 password') def client_listener(): cl = Listener(address=local_listener[0], auth...
# -*- coding: utf-8 -*- """ Reconstruction angles example comparison """ import numpy as np from sensbiotk.algorithms import martin_ahrs from sensbiotk.algorithms.basic import find_static_periods from sensbiotk.io.iofox import load_foxcsvfile from sensbiotk.io.ahrs import save_ahrs_csvfile import sensbiotk...
import os from dna.middleware.util.format import ConfigurationFormatFactory class ConfigurationException(Exception): pass class Configuration(object): # file write formats: json, yaml, xml... FORMAT_JSON = ConfigurationFormatFactory.FORMAT_JSON ERROR_READING_CONFIG = "Error reading configuration" ...
from functools import partial from tremendous.api import ( apply_color, apply_256, apply_256_bg, apply_256_hl, ) from tremendous.bindings import lib as __lib from tremendous.bindings import ffi colors_16 = dict( bold=__lib.BOLD, italic=__lib.ITALIC, under=__lib.UNDER, under2=__lib.UNDE...
# Copyright 2013 OpenStack Foundation # 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 requ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from common import get_regs, get_compile_regs import re REGS = get_compile_regs(get_regs('startup')) def get_startup(document): """ 抽取项目名 @document: Document对象 chunk @rtype: str 项目名 """ global REGS startup = '' ...
# -*- coding: utf-8 -*- from django.conf import settings from django.core.management.base import BaseCommand from plataforma.constants import ETHER_DIVISOR from plataforma.models import Saldo import requests def buscar_saldo(carteira): try: r = requests.get("https://api.etherscan.io/api?module=account&a...
import pygame from pygame.locals import * import os, sys # set SDL to use the dummy NULL video driver, # so it doesn't need a windowing system. os.environ["SDL_VIDEODRIVER"] = "dummy" # init pygame pygame.init() # create a 1x1 pixel screen, its not used screen = pygame.display.set_mode((1, 1)) # i...
#!/usr/bin/env python #****************************************************************************** # $Id$ # # Name: gdalimport # Project: GDAL Python Interface # Purpose: Import a GDAL supported file to Tiled GeoTIFF, and build overviews # Author: Frank Warmerdam, warmerdam@pobox.com # #**************...
from django.db import models from django.contrib.gis.db import models as geomodels from django.core.urlresolvers import reverse from django.utils import translation from django.contrib.auth.models import User from django.db.models import Avg, Count from django.core.mail import send_mail from django.conf import settings...
''' Udacity: - Software Defined Networking (SDN) course -- Assignment 7 Programming Assignment Professor: Nick Feamster ''' from pox.core import core import pox.openflow.libopenflow_01 as of from pox.lib.revent import * from pox.lib.util import dpidToStr from pox.lib.addresses import EthAddr from collections import n...
from __future__ import generator_stop import os import subprocess import shutil def _check_heroku_cmd_found(): command = 'heroku' if not shutil.which(command): from psiturk.psiturk_exceptions import HerokuCmdNotFound raise HerokuCmdNotFound() def _check_heroku_logged_in(): if subprocess....
#!/usr/bin/python """ Reflash the wemo image using sam-ba bootloader **requires 99-atmel_samba.rules in udev** **requires samba_64** John Donnal """ import serial import subprocess import time import os BOARD="at91sam4s4-wemo" WEMO_DEVICE="/dev/serial/by-id/usb-MIT_WEMO_Control_Board-if00" SAMBA_DEVICE="/dev/serial/...
# -*- coding: utf-8 -*- # Written by Jonathan Saewitz, released May 24th, 2016 for Statisti.ca # Released under the MIT License (https://opensource.org/licenses/MIT) import csv, plotly.plotly as plotly, plotly.graph_objs as go, requests from collections import Counter from bs4 import BeautifulSoup #the following cand...
# This program is an machine learning experiment with the FindS concept learning algorithm # Based on an excercise from Machine Learning by Thomas Mitchell (1997) # By: Jacob Rockland # # The attribute EnjoySport indicates whether or not Aldo enjoys his favorite # water sport on this day # # For all possible days with ...
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
# !/usr/bin/env python3 # -*- encoding: utf-8 -*- """ ERP+ """ __author__ = 'António Anacleto' __credits__ = [] __version__ = "1.0" __maintainer__ = "António Anacleto" __status__ = "Development" __model_name__ = 'linha_entrega.LinhaEntrega' import auth, base_models from orm import * from form import * try: from my_...
############################################################################### ## ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## "Redistribution and use in source and binary forms, with or without ## modification, ...
import time import json import random from moebius.utils import sleep_async from moebius.errors import \ ConnectionSendError, \ HandlerProcessingError from moebius.server import Handler class StartHandler(Handler): @staticmethod def run(client, data): for i in range(10): try: ...
""" Test package caching. """ from rez.tests.util import TestBase, TempdirMixin, restore_os_environ, \ install_dependent from rez.packages import get_package from rez.package_cache import PackageCache from rez.resolved_context import ResolvedContext from rez.exceptions import PackageCacheError from rez.utils.filesy...
""" the main entry point of utils Parameters ---------- Attributes ---------- Methods ------- See Also -------- Notes ----- Examples -------- """ from .mfreadnam import parsenamefile from .util_array import Util3d, Util2d, Transient2d...
# This file is part of PyEMMA. # # Copyright (c) 2015, 2014 Computational Molecular Biology Group, Freie Universitaet Berlin (GER) # # PyEMMA is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either vers...
import time import os import numpy as np import matplotlib.pyplot as plt from sklearn import cluster, datasets from sklearn.neighbors import kneighbors_graph from sklearn.preprocessing import StandardScaler from joblib import Memory memory = Memory('./output', verbose=0) from ..utils import sliding_window as window...
# -*- coding: utf-8 -*- from south.utils import datetime_utils as 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 'Stratum' db.create_table('cvmfsmon_stratum', ( ...
# Copyright (C) 2010, 2011, 2013 Linaro # # This file is part of Linaro Image Tools. # # Linaro Image Tools 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...
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
from typing import Tuple import pp from pp.drc import check_width def test_wmin_failing(layer: Tuple[int, int] = (1, 0)) -> None: w = 50 min_width = 50 + 10 # component edges are smaller than min_width c = pp.components.rectangle(size=(w, w), layer=layer) gdspath = c.write_gds("wmin.gds") # r =...
# Copyright 2021 Google LLC # # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd from django.core.exceptions import EmptyResultSet from django.db.utils import DatabaseError from django_spanner.compiler impo...
# =============================================================================== # Copyright 2015 Jake Ross # # 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...
# -*- coding: utf-8 -*- # http://pyrocko.org - GPLv3 # # The Pyrocko Developers, 21st Century # ---|P------/S----------~Lg---------- '''Lightweight declarative YAML and XML data binding for Python.''' from __future__ import absolute_import, print_function import datetime import calendar import re import sys import typ...
"""Install exception handler for process crash.""" import os import sys import threading import capnp from selfdrive.version import version, dirty from selfdrive.swaglog import cloudlog from common.hardware import PC if os.getenv("NOLOG") or os.getenv("NOCRASH") or PC: def capture_exception(*args, **kwargs): pa...
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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) any later version. # # This program is distrib...
#!/usr/bin/python # -*- coding: utf-8 -*- from scrapy.spider import Spider from scrapy.selector import Selector from scrapy.crawler import Crawler from scrapy.http import Request from scrapy import signals from scrapy.utils.project import get_project_settings from my_settings import name_file, test_mode, diff...
# -*- coding: UTF-8 -*- from glob import glob from os import listdir from os.path import isdir, isfile import os import site import sys import subprocess this_dir = os.path.dirname(os.path.abspath(__file__)) sys.path = [os.path.join(this_dir, "lib")] + sys.path msi = False if sys.argv[-1] == "bdist_msi": try: ...
__author__ = 'guorongxu' import os import sys ## To process JSON files and append an id for each document. def process_louvain_cluster_json(workspace, data_set): root_json_dir = workspace + "/" + data_set + "/louvain_json_files" ##id number rule: # the first digital "2" is the cluster index id; # the ...
from __future__ import division import numpy as np #--- To handle math processing import scipy.ndimage as ndi #--- To handle image processing from scipy import misc import os #--- To handle OS callbacks import xml.etree.ElementTree as et #--- To handle XML data import gc #--- To handle garbage collection import time t...
#!/usr/bin/env python ############################################################################### # Copyright Kitware Inc. # # 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 # # ht...
import json import requests import logging from backend.kubernetes.namespace import Namespace from backend.kubernetes.replicationcontroller import Controller from backend.kubernetes.service import Service from backend.kubernetes.volume import PersistentVolume, PersistentVolumeClaim from backend.kubernetes.autoscaler i...
import httplib2 import urllib import sys from utils import Error try: from urlparse import parse_qs, parse_qsl, urljoin except ImportError: from urlparse import urljoin from cgi import parse_qs, parse_qsl REQUEST_TOKEN, AUTHORIZE, AUTHENTICATE, ACCESS_TOKEN = 0, 1, 2, 3 class Client(object): """Client...
import re import logging from optparse import make_option from django.db import transaction, connections, DEFAULT_DB_ALIAS from django.core.management.base import BaseCommand from vdw.genes.models import Gene, GenePhenotype from vdw.literature.models import PubMed from vdw.phenotypes.models import Phenotype from vdw.va...
import gtk import pango class NextActionsView(gtk.VBox): """Simple class for display of Next Actions""" def __init__(self): super(NextActionsView, self).__init__() self._liststore = gtk.ListStore(bool, str, int, str) self._treeview = gtk.TreeView() self._treeview.g...
""" NOTES AND DEFINITIONS round: each time an affection token is given, one round has ended game: each time a player reaches AFFECTION_GOAL, one game has ended match: a set of games, ending at a given number of wins deck = [CARD_RANK, CARD_RANK, ..., CARD_RANK] # burner is not separate, is just the last card player_...
# Copyright 2017 Capital One Services, LLC # Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 from boto3 import Session from .utils import ( get_message_subject, get_resource_tag_targets, get_rendered_jinja) class SnsDelivery: def __init__(self, config, session, logger): ...
#!/usr/bin/env python # ********************************************************************* # * Copyright (C) 2015 Luca Baldini (luca.baldini@pi.infn.it) * # * * # * For the license terms see the file LICENSE, distributed * # * along ...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pref_help.ui' # # Created: Sun Mar 8 18:17:55 2015 # by: PyQt4 UI code generator 4.10.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except Attr...
# Copyright 2017 Battelle Energy Alliance, 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 t...
# -*- coding: utf-8 -*- from django.db import models class DetalleMovimientoManager(models.Manager): def guardar_detalles_con_referencia(self, objs, orden): requerimiento = None if orden.cotizacion is not None: requerimiento = orden.cotizacion.requerimiento for detalle in obj...
__author__="tite" __date__ ="$Jul 18, 2014 7:48:18 AM$" import os import sys import string import datetime import traceback from types import * import ConfigParser import smtplib import logging import logging.config import extractors import formatters from email.MIMEMultipart import MIMEMultipart from email.MIMETex...
# -*- coding: utf-8 -*- ############################################################################### # # FinalizeOAuth # Completes the OAuth process by retrieving a Dropbox access token and access token secret for a user, after they have visited the authorization URL returned by the InitializeOAuth choreo and click...
#-*- coding: UTF-8 -*- from learningobjects.utils.search import * from learningobjects.utils.parsers import * from django.core.management.base import BaseCommand, CommandError from learningobjects.models import * from optparse import make_option from learningobjects.utils import feedfinder from learningobjects.manageme...
#!/usr/bin/env python3.7 from math import floor from typing import Tuple from functools import reduce from itertools import combinations_with_replacement def factors( n: int # Number to factorize ) -> Tuple[int]: return tuple( reduce( list.__add__, ( [i, f...
# Copyright 2015 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Common brick related utilities.""" from __future__ import print_function import os from chromite.lib import osutils from chromite.lib import workspa...
import os import platform from logging.handlers import SysLogHandler from os.path import abspath, dirname, join from sys import path from corsheaders.defaults import default_headers as corsheaders_default_headers here = lambda *x: join(abspath(dirname(__file__)), *x) PROJECT_ROOT = here('..') root = lambda *x: abspat...
# genetic algorithm from collision_detect import collision_detect import random from math import sqrt from random import randint import os from xmlreader import XMLReader import numpy as np from numpy import array, cos, dot, fabs, lexsort, pi, sin, sqrt, vstack def individual (length, start, goal, range_min = None, ra...
""" Greedy Algorithm https://community.topcoder.com/stat?c=problem_statement&pm=1957&rd=4650 Discussion: https://www.topcoder.com/community/data-science/data-science-tutorials/greedy-is-good/ "[T]he [expected] profit of allocating an extra worker to a mine is always higher or equal with the [expected] profit of alloc...
from __future__ import absolute_import from six.moves import queue import threading class DummyReply: """ A reply object that does nothing. Useful when we need an object to seem like it has a channel, and during testing. """ def __init__(self): self.acked = False def __call_...
""" Tests the password gpg_data logic """ from os.path import join from unittest.mock import patch, MagicMock from teensy_pass.data.gpg_data import save, load, list_db, remove @patch('teensy_pass.data.gpg_data.check_output') @patch('teensy_pass.data.gpg_data.dumps') @patch('builtins.open') def test_save(open, dumps, c...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from ..person import Provider as PersonProvider class Provider(PersonProvider): formats = ( '{{first_name}} {{last_name}}', '{{first_name}} {{last_name}}', '{{last_name}}, {{first_name}}' ) first_names = ( ...
#!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import time, ...
# This file is part of Codeface. Codeface 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even...
import unittest from typing import List import utils def lowest_bit(val): return val & (-val) # O(n) space. Binary indexed tree, prefix. class NumArray: # O(nlog(n)) time. O(1) space. def __init__(self, nums: List[int]): self.nums = nums self.tree = [0] * (len(nums) + 1) for i,...
import time import openravepy import sys import numpy as np from numpy import sin,cos import matplotlib.mlab as mlab import matplotlib.pyplot as plt # import random import transformationFunction as tf import kdtree import scipy.spatial as spatial import cgkit.all as cg # weight of quaternion in distance QWEIGHT = 0...
"""Code for updating reports""" import logging import click from flask.cli import with_appcontext from scout.load.report import ( load_cnv_report, load_coverage_qc_report, load_delivery_report, load_gene_fusion_report, ) from scout.server.extensions import store LOG = logging.getLogger(__name__) @c...
#!/usr/bin/env python3 import json import mq from sys import argv from time import sleep def pull(filename): with open(filename, 'r') as fp: return json.load(fp) def check(tweets): assert len(tweets) > 0 first_batch = tweets[0] assert len(first_batch) > 0 first_tweet = first_batch[0] ...
import glob import os from math import ceil rawFolder = os.getcwd() + os.path.sep picturesFolder = rawFolder + 'stimulis' + os.path.sep picturesExamplesFolder = rawFolder + 'stimulisExample' + os.path.sep dataFolder = rawFolder + 'data' + os.path.sep mouseButton = 1 windowMode = True # if False use FullScreen wind...
# pylint: disable=too-many-lines from unittest import TestCase from pcs.common import report_codes from pcs.lib import reports from pcs.lib.commands import resource from pcs.lib.errors import ( LibraryError, ReportItemSeverity as severities, ) from pcs.test.tools import fixture from pcs.test.tools.command_env ...
# call_THINCARB_py27_from_file.py # # (c)2015 S. King # # Example of how to run THINCARB_py27.py using input values stored in an external SPACE-DELIMITED file # Run this module from the Python command shell or IDLE. # # A text file will be created containing all the input data and the computed values from the model # #...
# # @file TestUnit_newSetters.py # @brief Unit unit tests for new set function API # # @author Akiya Jouraku (Python conversion) # @author Sarah Keating # # ====== WARNING ===== WARNING ===== WARNING ===== WARNING ===== WARNING ====== # # DO NOT EDIT THIS FILE. # # This file was generated automatically by conv...
class Node: """Node for Python Trie Implementation""" def __init__(self): self.word = None self.nodes = {} # dict of nodes def __get_all__(self): """Get all of the words in the trie""" x = [] for key, node in self.nodes.iteritems() : ...
# -*- coding: utf-8 -*- # Copyright © 2013-2017 Red Hat, Inc. and others. # # This file is part of Bodhi. # # 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 ...
# -*- coding: utf-8 -*- #Created on Sun Aug 10 11:28:42 2014 # # Private references: # [1] https://docs.python.org/2/library/itertools.html """ A module for manipulating PTV analyses saved as HDF5 files in the flowtracks format. Allows reading the data by iterating over frames or over trajectories. Main design goals:...
# Python test set -- part 1, grammar. # This just tests whether the parser accepts them all. # NOTE: When you run this test as a script from the command line, you # get warnings about certain hex/oct constants. Since those are # issued by the parser, you can't suppress them by adding a # filterwarnings() call t...
"""PostgreSQL check Collects database-wide metrics and optionally per-relation metrics, custom metrics. """ # stdlib import socket # 3rd party try: import psycopg2 except ImportError: psycopg2 = None import pg8000 # project from checks import AgentCheck, CheckException from config import _is_affirmative M...
# -*- coding: utf-8 -*- class EnvManager(object): """ Коллекция переменных окружения. """ def __init__(self): # внутренне коллекция self.vars = dict() def expandvars(self, path: str): """ Заменяет переменные окружения в пути на значения. """ resul...
#!/usr/bin/env python import os, sys import filecmp import re import shutil holderlist=[] def compareme(dir1, dir2): dircomp=filecmp.dircmp(dir1,dir2) only_in_one=dircomp.left_only diff_in_one=dircomp.diff_files dirpath=os.path.abspath(dir1) [holderlist.append(os.path.abspath( os.path.join(dir1,x)...
#!/usr/bin/env python ''' Run this script to update all the copyright headers of files that were changed this year. For example: // Copyright (c) 2009-2012 The Flurbo Core developers it will change it to // Copyright (c) 2009-2015 The Flurbo Core developers ''' import os import time import re year = time.gmtime()[...
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2009, 2010, 2011, 2013, 2014 CERN. ## ## Invenio 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 ## Licens...
import re import json import tweepy from config import * from tweepy import OAuthHandler from textblob import TextBlob class TwitterClient(object): ''' Generic Twitter Class for sentiment analysis. ''' def __init__(self): ''' Class constructor or initialization method. ''' ...
""" [2016-08-18] Challenge #279 [Intermediate] Text Reflow https://www.reddit.com/r/dailyprogrammer/comments/4ybbcz/20160818_challenge_279_intermediate_text_reflow/ #Description: Text reflow means to break up lines of text so that they fit within a certain width. It is useful in e.g. mobile browsers. When you zoom in...
import ConfigParser import os.path class check_user_access_denied(): """ check_user_access_denied: Access denied events for user, these should be reviewed for malicious activity. """ # References: # https://www.percona.com/blog/2012/12/28/auditing-login-attempts-in-mysql/ TITLE = 'User...
import bricolage.core as T import cPickle as pickle import pathlib import numpy def make_target1(a, b, c): f1 = 0.5 if a and b or not c else 1.0 f2 = 1 if ((a or c) and not (a and b)) and b else 0 return f1, f2 def make_target2(a, b, c): f1 = 0.25 if (a or b) and (not a and not c) else 1.0 f2 = ...
#!/usr/bin/env python #coding=utf-8 import serial, time #===========================================================# # RASPBERRY PI (tested with Raspbian Jan 2012): # - Ensure that ttyAMA0 is not used for serial console access: # edit /boot/cmdline.txt (remove all name-value pairs containing # ttyAMA0) and comment o...
""" IfExp astroid node An if statement written in an expression form. (IfExp node represents an expression, not a statement.) Attributes: - test (NodeNG) - Holds a single node such as Compare to evaluate the truth condition of. - body (NodeNG) - A Node representing the suite to be ex...
import os, time, datetime, sys from PIL import Image path = '../test_files' def get_minimum_creation_time(exif_data): mtime = '?' if 306 in exif_data and exif_data[306] < mtime: # 306 = DateTime mtime = exif_data[306] if 36867 in exif_data and exif_data[36867] < mtime: # 36867 = DateTimeOriginal ...
from marabunta import BaseRobot from math import * class PerimeterDefenseRobot(BaseRobot): """Robot model for perimeter defense. By iteratively calling the update() method, this robot will communicate with the rest of the swarm and move away from the others as far as possible. Takes a *threshold* ...
import flextls from flextls.protocol.handshake import Handshake, ServerCertificate, DTLSv10Handshake from sslscan import modules from sslscan._helper.openssl import version_openssl, version_pyopenssl from sslscan.module import STATUS_OK, STATUS_ERROR from sslscan.module.scan import BaseScan openssl_enabled = False ve...
from __future__ import unicode_literals import datetime import django from django.test import TestCase from django.utils.timezone import now import job.test.utils as job_test_utils from job.tasks.base_task import Task from job.tasks.manager import TaskManager from job.tasks.node_task import NodeTask from job.tasks.u...
import taichi as ti def archs_support_bitmasked(func): return ti.archs_excluding(ti.opengl, ti.cc)(func) @archs_support_bitmasked def test_basic(): x = ti.field(ti.i32) c = ti.field(ti.i32) s = ti.field(ti.i32) bm = ti.root.bitmasked(ti.ij, (3, 6)).bitmasked(ti.i, 5) bm.place(x) ti.root...
# vim: fdm=marker ''' author: Fabio Zanini date: 08/12/14 content: Plot tree of haplotypes. ''' # Modules from __future__ import print_function import os import argparse import numpy as np import seaborn as sns import matplotlib.pyplot as plt # Functions def tree_from_json(json_file): '''Convert JS...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org) # 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 witho...
# Copyright 2015 OpenStack Foundation # 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 requ...
import datetime import decimal import traceback try: from django.conf import settings from django.utils import timezone except ImportError: settings = None timezone = None try: import json except ImportError: import simplejson as json class MoreTypesJSONEncoder(json.JSONEncoder): """ ...
""" Base of the securable (ie. directly accessible through the web), translatable and full-featured TN object. A twist-able object in TN is an object which can be accessed safely from a view. Normally, everything a view manipulates must be taken from a TN object. Content, Accounts, MenuItems, ... are all Twistable ob...