code
stringlengths
1
199k
import numpy as np import pandas as pd from gomill import sgf from gomill import ascii_boards from gomill import sgf_moves from IPython.core.debugger import Tracer def sgf_filename_to_game(game_filename): """ Read in sgf game file and convert to gomill Game object """ with open(game_filename, 'r') as my...
def pretty_date(time=False): """ Get a datetime object or a int() Epoch timestamp and return a pretty string like 'an hour ago', 'Yesterday', '3 months ago', 'just now', etc """ from datetime import datetime now = datetime.now() if type(time) is int: diff = now - datetime.fromtim...
''' Pull one page of 100 results from seeclickfix using the global PARAMS value if the parameters are not supplied. If there are more than 100 results, make another pull passing paramters that include the next page to be pulled. Nicole Donnelly 30May2016, updated 21Oct2016 ''' import requests import json def get_seecli...
import os import argparse import tensorflow as tf from gym import wrappers from yarll.environment.registration import make class ModelRunner(object): """ Run an already learned model. Currently only supports one variation of an environment. """ def __init__(self, env, model_directory: str, save_dire...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pages', '0012_auto_20160519_1740'), ] operations = [ migrations.AddField( model_name='formpage', name='button_name', ...
from __future__ import print_function import argparse from collections import OrderedDict import json import os import logging from keras.callbacks import EarlyStopping from sklearn.preprocessing import normalize from sklearn.metrics import roc_curve, auc, roc_auc_score, precision_score, recall_score, f1_score, accurac...
from jinja2 import Template import codecs def render(file, props=None): if props == None: return '404' with codecs.open('./views/' + file + '.html', 'r', encoding='utf8') as f: content = f.read() templated = Template(content).render(props) return templated
from mathbind.types import BasicType class BasicValueType(BasicType): """ Represents a basic pure type that can be passed by value, thus excluding arrays and pointers. Attributes: - typename (str): basic C typename (int, long long, unsigned, bool, etc) - c_math_name (str): corresponding Mathematica ...
import os from setuptools import setup LONG_DESCRIPTION = """ A modular framework for mobile surveys and field data collection via offline-capable mobile web apps. """ def readme(): try: readme = open('README.md') except IOError: return LONG_DESCRIPTION else: return readme.read() set...
import urllib.request import os from bs4 import BeautifulSoup, SoupStrainer proxies = {'http':''} opnr = urllib.request.build_opener(urllib.request.ProxyHandler(proxies)) urllib.request.install_opener( opnr ) with urllib.request.urlopen('http://abu.cnam.fr/BIB/') as response: html = response.read() # Search for...
import math, logging, threading, concurrent.futures import numpy import simplespectral from soapypower import threadpool logger = logging.getLogger(__name__) class PSD: """Compute averaged power spectral density using Welch's method""" def __init__(self, bins, sample_rate, fft_window='hann', fft_overlap=0.5, ...
import logging from logging.handlers import RotatingFileHandler from app import create_app app = create_app() if __name__ == "__main__": # Manage the command line parameters such as: # - python manage.py runserver # - python manage.py db from app import manager manager.run()
from django.conf.urls import patterns, url urlpatterns = patterns('', url(r'^sql/$', 'sqlparser.views.parse_sql'), )
''' Created by auto_sdk on 2015.06.23 ''' from aliyun.api.base import RestApi class Ram20140214GetUserRequest(RestApi): def __init__(self,domain='ram.aliyuncs.com',port=80): RestApi.__init__(self,domain, port) self.AccountSpace = None self.UserName = None def getapiname(self): return 'ram.aliyuncs.com.GetUser...
class Paginator(object): def __init__(self, collection, page_number=0, limit=20, total=-1): self.collection = collection self.page_number = int(page_number) self.limit = int(limit) self.total = int(total) @property def page(self): start = self.page_number * self.limit...
"""Test BIP 9 soft forks. Connect to a single node. regtest lock-in with 108/144 block signalling activation after a further 144 blocks mine 2 block and save coinbases for later use mine 141 blocks to transition from DEFINED to STARTED mine 100 blocks signalling readiness and 44 not in order to fail to change state thi...
from contrib import * import re def tokenize(text): tokens = re.findall('(?u)[\w.-]+',text) tokens = [t for t in tokens if not re.match('[\d.-]+$',t)] #tokens = [t for t in tokens if len(t)>2] # TODO remove stopwords return u' '.join(tokens) text = KO('data/text') tokens = KO('data/tokens') for k,v in text.items()...
from ...plugin import hookimpl from ..custom import CustomBuilder from ..sdist import SdistBuilder from ..wheel import WheelBuilder @hookimpl def hatch_register_builder(): return [CustomBuilder, SdistBuilder, WheelBuilder]
from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated from .models import Submission from .serializers import SubmissionSerializer from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView from django.utils.decorators import method_decora...
""" This programs plots the electronic coupling between two states. It reads all Ham_*_im files and cache them in a tensor saved on disk. Usage: plot_couplings.py -p . -s1 XX -s2 YY -dt 1.0 p = path to the hamiltonian files s1 = state 1 index s2 = state 2 index dt = time step in fs """ import numpy as np import...
import ast import traceback import os import sys userFunctions = {} renames = ['vex.pragma','vex.motor','vex.slaveMotors','vex.motorReversed'] classNames = [] indent = ' ' sameLineBraces = True compiled = {} def module_rename(aNode): if aNode.func.print_c() == 'vex.pragma': asC = '#pragma ' useComma = Fa...
import datetime import math class Funcionario(object): def __init__(self, nome = "Albert", sobrenome = "Einstein", idade = 29, salario = 2000, cargo = "Chefe"): self.nome = nome self.sobrenome = sobrenome self.idade = idade self.salario = salario self.cargo = cargo pr...
""" This module provides a lexical scanner component for the `parser` package. """ class SettingLexer(object): """ Simple lexical scanner that tokenizes a stream of configuration data. See ``SettingParser`` for further information about grammar rules and specifications. Example Usage:: ...
from datetime import date from workalendar.tests import GenericCalendarTest from workalendar.asia import HongKong, Japan, Qatar, Singapore from workalendar.asia import SouthKorea, Taiwan, Malaysia class HongKongTest(GenericCalendarTest): cal_class = HongKong def test_year_2010(self): """ Interesting bec...
import logging from ask import alexa import car_accidents import expected_population logger = logging.getLogger() logger.setLevel(logging.INFO) def lambda_handler(request_obj, context=None): return alexa.route_request(request_obj) @alexa.default def default_handler(request): logger.info('default_handler') r...
def lucky_search(index, ranks, keyword): urls = index.get(keyword) if urls and ranks: return max(urls, key = lambda x: ranks[x]) else: return None def ordered_search(index, ranks, keyword): urls = index.get(keyword) if urls and ranks: return sorted(urls, key = lambda x: ranks[x]) else: return None
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRe...
from django.shortcuts import render from rest_framework import viewsets from basin.models import Task from basin.serializers import TaskSerializer def index(request): context = {} return render(request, 'index.html', context) def display(request): state = 'active' if request.method == 'POST': st...
""" This module allows you to mock the config file as needed. A default fixture that simply returns a safe-to-modify copy of the default value is provided. This can be overridden by parametrizing over the option you wish to mock. e.g. >>> @pytest.mark.parametrize("extension_initial_dot", (True, False)) ... def test_fix...
""" This module defines how cells are stored as tunacell's objects """ from __future__ import print_function import numpy as np import warnings import treelib as tlib from tunacell.base.observable import Observable, FunctionalObservable from tunacell.base.datatools import (Coordinates, compute_rates, ...
import scrapy import numpy import quandl from mykgb import indicator from myapp.models import Quandlset from mykgb.items import MykgbItem quandl.ApiConfig.api_key = "taJyZN8QXqj2Dj8SNr6Z" quandl.ApiConfig.api_version = '2015-04-09' class QuandlDataSpider(scrapy.Spider): name = "quandl_data" allowed_domains = ["...
def settings(request): """ Add settings (or some) to the templates """ from django.conf import settings tags = {} tags['GOOGLE_MAPS_KEY'] = settings.GOOGLE_MAPS_KEY tags['GOOGLE_ANALYTICS_ENABLED'] = getattr(settings, 'GOOGLE_ANALYTICS_ENABLED', True) tags['MAP_PROVIDER'] = settings.MAP_...
from flask import Flask, request, jsonify import random import re import sys app = Flask(__name__) SPEC = re.compile('^(\d+)d(\d+) ?(\w+)?$') HIDDEN = ('hide', 'hidden', 'invisible', 'ephemeral', 'private') USAGE = 'USAGE:\n' \ '`/roll [n]d[x] [options]`\n' \ 'where:\n' \ ' n == number of dice\n' \ ' ...
""" desc: 错误处理handler author: congqing.li date: 2016-10-28 """ from werkzeug.exceptions import HTTPException class CustomError(HTTPException): code = None description = "NIMABI" def __init__(self, description=None, response=None): if isinstance(description, tuple): self.description, ...
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "radiocontrol.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
from __future__ import unicode_literals import json import hashlib from django.utils import six URL_LIST_CACHE = 'powerpages:url_list' SITEMAP_CONTENT = 'powerpages:sitemap' def get_cache_name(prefix, name): """ Cache name constructor. Uses the same methods as django cache system Examples: *) prefix=pro...
__author__ = 'Sergey Sobko' class HashSet(object): _set_dict = None def __init__(self): self._set_dict = dict() def add(self, key, value): self._set_dict[hash(key)] = value def get(self, key): return self._set_dict.get(hash(key)) def __repr__(self): return self._set_d...
import pyglet import tkinter WINDOW_WIDTH = 800 # x WINDOW_HEIGHT = 600 # y LEVEL = 6 # original was 4 X_SIZE = 2 * LEVEL Y_SIZE = 3 * LEVEL def get_resolution(): root = tkinter.Tk() return root.winfo_screenwidth(), root.winfo_screenheight() def get_position(x, y): return ((x // X_SIZE) * X_SIZE, (y // ...
import re import numpy as np from scipy import ndimage, spatial import bresenham import mpl_tools import vtk_tools def load_pdb(name): with open(name+'.pdb') as fp: points = [] conns = [] for line in fp: if line.startswith('HET'): pattern = r'(-?\d+.\d\d\d)' ...
''' This program will learn and predict words and sentences using a Hierarchical Hidden Markov Model (HHMM). Implement a Baum-Welch algorithm (like EM?) to learn parameters Implement a Viterbi algorithm to learn structure. Implement a forward-backward algorithm (like BP) to do inference over the evidence. ''' ''' can ...
from __future__ import absolute_import from __future__ import print_function import os import numpy import matplotlib.pyplot as plt import datetime import clawpack.visclaw.colormaps as colormap import clawpack.visclaw.gaugetools as gaugetools import clawpack.clawutil.data as clawutil import clawpack.amrclaw.data as amr...
""" locally connected implimentation on the lip movement data. Akm Ashiquzzaman 13101002@uap-bd.edu Fall 2016 after 1 epoch , val_acc: 0.0926 """ from __future__ import print_function, division import numpy as np np.random.seed(1337) import time X_train = np.load('videopart43.npy') Y_train = np.load('audiopart43.npy') ...
import datetime import io import boto3 import mock import pytest import requests import testfixtures from botocore.exceptions import ClientError from opentracing.ext import tags from opentracing_instrumentation.client_hooks import boto3 as boto3_hooks DYNAMODB_ENDPOINT_URL = 'http://localhost:4569' S3_ENDPOINT_URL = 'h...
from .file_logger import FileLogger
"""Script to execute CPU and get a best move using Minimax algorithm""" import copy from common import board_full, win OPP = [1, 0] def eval_rc(board, player, glength, roc): """Returns row or column score""" score_sum = 0 clone_board = board if roc == "c": clone_board = [[board[j][i] for j in xr...
def is_leapyear(year): if year%4 == 0 and year%100 != 0 or year%400 == 0: return 1 else: return 0 month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def days_of_month(m, y): return month[m-1] + (is_leapyear(y) if m == 2 else 0) def days_of_year(y): return sum(month) + is_l...
"""Encode and decode Bitcoin addresses. - base58 P2PKH and P2SH addresses. - bech32 segwit v0 P2WPKH and P2WSH addresses. - bech32m segwit v1 P2TR addresses.""" import enum import unittest from .script import ( CScript, OP_0, OP_TRUE, hash160, hash256, sha256, taproot_construct, ) from .segw...
from textx.exceptions import TextXSemanticError def query_processor(query): if not query.condition is None: query.condition.conditionName = adapter_for_query(query) for query in query.parent.queries: if (not hasattr(query, 'property')) and (query.sortBy not in query.parent.properties): ...
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 'User' db.create_table(u'accounts_user', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=...
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ if not s: return True stack = [] for i in xrange(len(s)): # if its opening it, its getting deeper so add to stack if s[i] in "([{": ...
from .base import ScannerBase class WhoisAtiTnScanner(ScannerBase): def __init__(self, *args): super(WhoisAtiTnScanner, self).__init__(*args) self._tokenizer += [ 'skip_empty_line', 'scan_available', 'scan_disclaimer', 'scan_keyvalue' ] def...
import sys from django.core.management.base import BaseCommand, CommandError import nflgame from terminaltables import AsciiTable from ...models import Player, Team, Season, Week, WeeklyStats class Command(BaseCommand): help = 'takes option position, displays top players as table' def add_arguments(self, parser...
from django.apps import AppConfig class PerscriptionsConfig(AppConfig): name = 'prescriptions'
from unittest import TestCase from safeurl.core import getRealURL class MainTestCase(TestCase): def test_decodeUrl(self): self.assertEqual(getRealURL('http://bit.ly/1gaiW96'), 'https://www.yandex.ru/') def test_decodeUrlArray(self): self.assertEqual( getRealU...
from django.core.management import call_command import pytest import septentrion def test_showmigrations_command_override(mocker): mock_django_handle = mocker.patch( 'django.core.management.commands.showmigrations.Command.handle') mock_show_migrations = mocker.patch( 'septentrion.show_migrations...
import unittest import numpy as np from tensorflow.python.client import device_lib # pylint: disable=no-name-in-module from cleverhans.devtools.checks import CleverHansTest HAS_GPU = 'GPU' in {x.device_type for x in device_lib.list_local_devices()} class TestMNISTTutorialKeras(CleverHansTest): def test_mnist_tutorial...
from datetime import datetime from canvas.core.courses import get_courses, get_courses_whitelisted, get_course_people, get_courses_by_account_id from canvas.core.io import write_xlsx_file, tada from canvas.core.assignments import get_assignments def assignments_turnitin_msonline_list(): terms = ['2017-1SP'] pro...
from django.conf.urls import patterns, include, url from django.conf import settings from profile import ProfileView from contacts import ContactsView from authen import Authenticate strid = settings.CONTACT_URL['strid'] user = settings.CONTACT_URL['user'] contact = settings.CONTACT_URL['contact'] auth = settings.CONTA...
import logging import os import urllib.parse import urllib.request import tarfile from tooldog import TMP_DIR from .utils import * LOGGER = logging.getLogger(__name__) class CodeCollector(object): """ Class to download source code from a https://bio.tools entry """ ZIP_NAME = "tool.zip" TAR_NAME = "...
import pytest import os from polyglotdb import CorpusContext acoustic = pytest.mark.skipif( pytest.config.getoption("--skipacoustics"), reason="remove --skipacoustics option to run" ) def test_to_csv(acoustic_utt_config, export_test_dir): export_path = os.path.join(export_test_dir, 'results_export.csv') ...
import sys import socket import os import os.path from optparse import OptionParser import numpy as np import matplotlib.pyplot as plt import pylab import genome_management.kg_file_handling as kgf import math def file_exists(ls,file): for f in ls: if(f==file): return 1 return 0 def mkdir(dir...
import sys import boto3 s3 = boto3.resource('s3') for bucket_name in sys.argv[1:]: # use the bucket name to create a bucket object bucket = s3.Bucket(bucket_name) # delete the bucket's contents and print the response or error for key in bucket.objects.all(): try: response = key.delet...
from data import * from draw import * img, hiden_x = get_img_class() print img.shape print img d_idx = np.random.randint(0, 50) x_x, obs_x, obs_y, obs_tfs, new_ob_x, new_ob_y, new_ob_tf, imgs = gen_data() print show_dim(x_x) print show_dim(obs_x) print show_dim(obs_y) print show_dim(obs_tfs) print show_dim(new_ob_x) pr...
#!/usr/bin/python import catlib ,pagegenerators import wikipedia,urllib,gzip,codecs,re import MySQLdb as mysqldb import config pagetop=u"'''تاریخ آخری تجدید:''''': ~~~~~ '''بذریعہ:''' [[user:{{subst:Currentuser}}|{{subst:Currentuser}}]]''\n\n" pagetop+=u'\nفہرست 100 بلند پایہ صارفین بلحاظ شراکت بدون روبہ جات۔\n' paget...
""" ZetCode PyQt5 tutorial In this example, we create three toggle buttons. They will control the background colour of a QFrame. author: Jan Bodnar website: zetcode.com last edited: January 2015 """ import sys from PyQt5.QtWidgets import (QWidget, QPushButton, QFrame, QApplication) from PyQt5.QtGui import QColor cl...
from django.contrib.auth.models import User from django.db import models from .utils import create_slug class BaseModel(models.Model): created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) class Meta(): abstract = True
from django.views.generic import CreateView, DetailView from .models import TestModel class TestCreateView(CreateView): template_name = 'test_tinymce/create.html' fields = ('content',) model = TestModel class TestDisplayView(DetailView): template_name = 'test_tinymce/display.html' context_object_nam...
from graph.graph_server import GraphServer __all__ = ['GraphServer']
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) relay_pin = 18 GPIO.setup(relay_pin, GPIO.OUT) try: while True: GPIO.output(relay_pin, True) time.sleep(2) GPIO.output(relay_pin, False) time.sleep(2) finally: print("Cleaning up") GPIO.cleanup()
import numpy as np import os from core.lda_engine import model_files from pandas import DataFrame from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from core.keyword_db import keyword_dbs def db_connect(base, model_name='dss'): try: path = 'sqlite:///' + os.path.join(os.getcwd(), ...
import numpy as np import pywt from scipy.misc import imresize from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) X_L = 10 L = 14 N_BATCH = 50 OBS_SIZE = 30 def vectorize(coords): retX, retY = np.zeros([L]), np.zeros([L]) retX[coords[0]] = 1.0 ...
import os from sqlalchemy import create_engine, MetaData from sqlalchemy.orm import scoped_session, sessionmaker metadata = MetaData() def get_sa_db_uri(driver='', username='', password='', host='', port='', database=''): """get SQLAlchemy DB URI: driver://username:password@host:port/database""" assert driver ...
""" Grade API v1 URL specification """ from django.conf.urls import url, patterns import views urlpatterns = patterns( '', url(r'^grades/courses/$', views.CourseGradeList.as_view()), url(r'^grades/courses/(?P<org>[A-Za-z0-9_.-]+)[+](?P<name>[A-Za-z0-9_.-]+)[+](?P<run>[A-Za-z0-9_.-]+)/$', views.CourseGradeDe...
from OpenGLCffi.GLES1 import params @params(api='gles1', prms=['target', 'numAttachments', 'attachments']) def glDiscardFramebufferEXT(target, numAttachments, attachments): pass
import argparse import pandas as pd def get_parser(): # Get the argument parser for this script parser = argparse.ArgumentParser() parser.add_argument('-F', '--filename', help='Filename for grades') return parser class GPACalculator: def __init__(self, fname): # Load file via pandas ...
from numpy import pi, sin, cos, mgrid dphi, dtheta = pi/250.0, pi/250.0 [phi,theta] = mgrid[0:pi+dphi*1.5:dphi,0:2*pi+dtheta*1.5:dtheta] m0 = 4; m1 = 3; m2 = 2; m3 = 3; m4 = 6; m5 = 2; m6 = 6; m7 = 4; r = sin(m0*phi)**m1 + cos(m2*phi)**m3 + sin(m4*theta)**m5 + cos(m6*theta)**m7 x = r*sin(phi)*cos(theta) y = r*cos(phi) ...
"""Bulk importer for manually-prepared tariff CSV. This probably won't be used again following initial data load, so could be deleted after that. """ import csv import logging from datetime import datetime from django.core.management.base import BaseCommand from django.db import transaction from dmd.models import Tarif...
import sublime, sublime_plugin from .. import config from .. import globals from .. import logger from ..debug_client import DebugClient from ..clicks import Clicks log = logger.get('cmd_attach_debugger') def lookup_ref(id, refs): for ref in refs: if id == ref['handle']: return ref return None def open_file(data...
from bokeh.plotting import figure, output_file, show p = figure(width=400, height=400) p.circle(2, 3, radius=.5, alpha=0.5) output_file('out.html') show(p)
from django.conf import settings PIPELINE = getattr(settings, 'PIPELINE', not settings.DEBUG) PIPELINE_ROOT = getattr(settings, 'PIPELINE_ROOT', settings.STATIC_ROOT) PIPELINE_URL = getattr(settings, 'PIPELINE_URL', settings.STATIC_URL) PIPELINE_STORAGE = getattr(settings, 'PIPELINE_STORAGE', 'pipeline.storage.Pipe...
x=10 y=11 print(x+y)
import os import sys from distutils.command.config import config import guzzle_sphinx_theme import tomli from dunamai import Version root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) sys.path.insert(0, root) with open(os.path.join(root, "pyproject.toml"), "rb") as f: config = tomli.load(f) proje...
from celery import shared_task import sync @shared_task def auto_sync_app_models_task(): sync.auto_sync_app_models()
def main(): #Get the filename with the numbers fileName = input("What file are the numbers in? ") #var to contain all the content of the file infile = open(fileName, 'r') #var to keep track of the sum of those numbers sum = 0.0 #var to keep track of the sum count = 0 #var with the first line of the file line ...
import datetime import logging import os from urllib.parse import urljoin from utils import utils, inspector archive = 2008 SPOTLIGHT_REPORTS_URL = "https://www.sigar.mil/Newsroom/spotlight/spotlight.xml" SPEECHES_REPORTS_URL = "https://www.sigar.mil/Newsroom/speeches/speeches.xml" TESTIMONY_REPORTS_URL = "https://www....
import gtk, sys, string class Socket: def __init__(self): window = gtk.Window() window.set_default_size(200, 200) socket = gtk.Socket() window.add(socket) print "Socket ID:", socket.get_id() if len(sys.argv) == 2: socket.add_id(long(sys.argv[1])) w...
import os import traceback from inspect import isfunction import sys import functools O_CLOEXEC = 524288 # cannot use octal because they have different syntax on python2 and 3 NULL_FD = os.open("/dev/null", os.O_WRONLY | os.O_NONBLOCK | O_CLOEXEC) class Args(object): """ Use this class to tell Tracer to extract pos...
sumsquare = 0 sum = 0 for i in range(1, 101): sumsquare = sumsquare + i*i for j in range(1, 101): sum = sum + j print(sum) print(sum*sum) print(sum*sum - sumsquare)
f = open('main_h.tex','w') f.write("""\documentclass[a4paper,5pt,twocolumn,titlepage]{article} \usepackage{mathpazo} \usepackage{xeCJK} \usepackage{pstricks,pst-node,pst-tree} \usepackage{titlesec} \\titleformat*{\section}{\sf} \\titleformat*{\subsection}{\sf} %\setsansfont{DejaVu Sans Mono} \setsansfont{Source Code Pr...
import os import sys import tempfile import shutil if sys.version_info[:2] == (2, 6): import unittest2 as unittest else: import unittest from avocado.utils import process basedir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..') basedir = os.path.abspath(basedir) DEBUG_OUT = """Variant 16: ...
from rest_framework.routers import (Route, DynamicDetailRoute, SimpleRouter, DynamicListRoute) from app.api.account.views import AccountViewSet from app.api.podcast.views import PodcastViewSet, EpisodeViewSet cla...
''' Created on Jun 15, 2014 @author: geraldine ''' import socket import fcntl import struct def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl(s.fileno(),0x8915,struct.pack('256s', ifname[:15]))[20:24])
""" Builds a file that would import all used modules. This way we trick py2exe to include all standard library files and some more packages and modules. """ import os import sys import warnings from os.path import join import builder MODULES_TO_IGNORE = [ "__phello__.foo", "antigravity", "unittest", "wi...
from __future__ import print_function num = 17 test = 2 while test < num: if num % test == 0 and num != test: print(num,'equals',test, '*', num/test) print(num,'is not a prime number') break test = test + 1 else: print(num,'is a prime number!')
class check_privilege_dbadm(): """ check_privilege_dbadm: The DBADM (database administration) role grants the authority to a user to perform administrative tasks on a specific database. It is recommended that dbadm role be granted to authorized users only. """ # References: # https://ben...
from installclass import BaseInstallClass from constants import * from product import * from flags import flags import os, types import iutil import gettext _ = lambda x: gettext.ldgettext("anaconda", x) import installmethod from sabayon import Entropy from sabayon.livecd import LiveCDCopyBackend class InstallClass(Bas...
import os import select fds = os.open("data", os.O_RDONLY) while True: reads, _, _ = select.select(fds, [], [], 2.0) if 0 < len(reads): d = os.read(reads[0], 10) if d: print "-> ", d else: break else: print "timeout"
""" PaStA - Patch Stack Analysis Copyright (c) OTH Regensburg, 2019 Author: Ralf Ramsauer <ralf.ramsauer@oth-regensburg.de> This work is licensed under the terms of the GNU GPL, version 2. See the COPYING file in the top-level directory. """ import os import sys from fuzzywuzzy import fuzz from logging import getLog...
from xml.sax import make_parser from xml.sax.handler import ContentHandler import smallsmilhandler import sys import os class KaraokeLocal(smallsmilhandler.SmallSMILHandler): def __init__(self, fich): parser = make_parser() sHandler = smallsmilhandler.SmallSMILHandler() parser.setContentHand...
import nullGroupSource try: import zodbGroupSource except ImportError: pass