repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
PyIran/website | project/apps/user/models.py | from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey
from project.database import Base
from project.database import db_session
from sqlalchemy.orm import relationship
from sqlalchemy_utils import EmailType
from flask.ext.babel import lazy_gettext as _
# FIXME: move to extensions
from flask.ext... |
dash1291/major | webserver/app.py | import json
import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../scripts'))
from flask import Flask, render_template, request
from py2neo import neo4j
from ollie import pipeline
app = Flask(__name__)
"""@app.route('/render', method=['POST'])
def render():
pairs = json.loads(re... |
shanzhenren/PLE | Classifier/PLSVM.py | from __future__ import division
__author__ = 'wenqihe'
import sys
import random
import math
class PLSVM:
def __init__(self, feature_size, label_size, type_hierarchy, lambda_reg=0.1, max_iter=5000, threshold=0.5, batch_size=100):
self._feature_size = feature_size
self._label_size = label_size
... |
AurelienNioche/MonkeyProject | data_management/data_manager.py | import numpy as np
from data_management.database import Database
from utils.utils import log, today
class DataManager(object):
name = "DataManager"
def __init__(self, monkey, starting_point="2016-12-01", end_point=today(), database_path=None):
self.db = Database(database_path)
self.monkey ... |
RudolfCardinal/crate | crate_anon/preprocess/postcodes.py | #!/usr/bin/env python
"""
crate_anon/preprocess/postcodes.py
===============================================================================
Copyright (C) 2015-2021 Rudolf Cardinal (rudolf@pobox.com).
This file is part of CRATE.
CRATE is free software: you can redistribute it and/or modify
it under... |
DavidCain/mitoc-trips | ws/middleware.py | from django.contrib.auth.models import User
from ws.messages import security
from ws.models import Participant
class PrefetchGroupsMiddleware:
"""Prefetch the user's groups for use in the requset.
We do a lot of group-centric logic - if the user's groups aren't
prefetched, then we can easily have n+1 qu... |
owatte/thecaribfos | apps/thedirectory/migrations/0004_auto_20150529_1416.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
#import tagging_autocomplete.models
import datetime
class Migration(migrations.Migration):
dependencies = [
('thedirectory', '0003_auto_20150525_1515'),
]
operations = [
migrations.Al... |
modelblocks/modelblocks-release | resource-general/scripts/itemmeasures2lineitems.py | import sys
sentid_prev = 0
first_line = True
first_word = True
for line in sys.stdin:
row = line.strip().split()
if first_line:
word_ix = row.index('word')
sentid_ix = row.index('sentid')
first_line = False
else:
word = row[word_ix]
sentid = row[sentid_ix]
i... |
ajylee/gpaw-rtxs | gpaw/test/aluminum_testcell.py | import numpy as np
import sys
import os
import time
from ase import Atom, Atoms
from ase.visualize import view
from ase.units import Bohr
from ase.structure import bulk
from gpaw import GPAW
from gpaw.atom.basis import BasisMaker
from gpaw.response.df import DF
from gpaw.mpi import serial_comm, rank, size
from gpaw.uti... |
opsolutely/flask-nginx-starter | app/config.py | import os
CSRF_ENABLED = True
ENV = os.environ.get('ENVIRONMENT', 'dev')
MODEL_HASH = os.environ.get('MODEL_HASH')
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
ROOT_PATH = BASE_DIR = os.path.join(os.path.dirname(__file__), '..')
SECRET_KEY = os.environ.get('SECRET_KEY')
STATIC_FOLDER = os.path.join(ROOT... |
tshi04/machine-learning-codes | deliberation_network/utils.py | import numpy as np
import torch
import time
from torch.autograd import Variable
'''
fast beam search
'''
def repackage_hidden(h):
"""Wraps hidden states in new Variables, to detach them from their history."""
if type(h) == Variable:
return Variable(h.data)
else:
return tuple(repackage_hidden... |
mais4719/PyLuxafor | pyluxafor/cli.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Simple command line interface to pyluxafor.
"""
from __future__ import division, print_function, absolute_import
import argparse
import sys
import logging
from pyluxafor import Devices
from pyluxafor import Wave, Pattern, Leds
from pyluxafor import __version__
__auth... |
cro-ki/ki-renamer | kir.py | '''
*** Ki Renamer ***
usage: kir <filter> <rule> [-p] [-r]
<filter> Regex - Filter the files to rename
<rule> Renaming rule
Options:
--version Displays the current version of Ki Renamer
-h, --help Show usage and options
-p, --preview Print more info... |
lqe/EconomyCompensation | code.py | # -*- coding:utf-8 -*-
'''Created on 2014-8-7 @author: Administrator '''
from sys import path as sys_path
if not '..' in sys_path:sys_path.append("..") #用于import上级目录的模块
import web
#早起的把一个文件分成多个文件,再把class导入
from login.login import (index,login,loginCheck,In,reset,register,find_password)
from blog.blog imp... |
fernandog/Sick-Beard | sickbeard/postProcessor.py | # Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard 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 3 of the Lice... |
lfalvarez/nouabook | elections/tests/photo_loader_tests.py | # coding=utf-8
from elections.tests import VotaInteligenteTestCase as TestCase
from elections.models import Election
from django.core.urlresolvers import reverse
from candideitorg.models import Candidate
from django.core.management import call_command
class PhotoLoaderCase(TestCase):
def setUp(self):
supe... |
danielrd6/ifscube | cubetools.py | """
Functions for the analysis of integral field spectroscopy.
Author: Daniel Ruschel Dutra
Website: https://github.com/danielrd6/ifscube
"""
from numpy import *
import pyfits as pf
import spectools as st
import matplotlib as mpl
import matplotlib.pyplot as plt
from scipy.integrate import trapz
from copy import deepc... |
tomsilver/nupic | examples/network/network_api_demo.py | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions ... |
cvxgrp/ncvx | ncvx/orthog.py | """
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY 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 3 of the License, or
(at your option) any later version.
CVXPY is distributed i... |
jeanpimentel/contents | tests/functional/test_file_with_long_levels.py | import sure
import tempfile
from contents import contents
def test_file_with_long_levels():
content = '''/**
* Project X
* Author: Jean Pimentel
* Date: August, 2013
*/
/* > Intro */
Toc toc! Penny! Toc toc! Penny! Toc toc! Penny!
/* >> The Big Bang Theory << */
The Big Bang Theory is an American sitcom cr... |
Outernet-Project/librarian | librarian/core/utils/iterables.py | """
Functions and decorators for making sure the parameters they work on are of
iterable types.
Copyright 2014-2015, Outernet Inc.
Some rights reserved.
This software is free software licensed under the terms of GPLv3. See COPYING
file that comes with the source code, or http://www.gnu.org/licenses/gpl.txt.
"""
impor... |
Kaniabi/l5r-character-manager-3 | l5r/dialogs/newrankdlg.py | # -*- coding: utf-8 -*-
# Copyright (C) 2014 Daniele Simonetti
#
# 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.
#
# Thi... |
MariaSolovyeva/inasafe | safe/impact_functions/generic/continuous_hazard_population/impact_function.py | # coding=utf-8
"""
InaSAFE Disaster risk assessment tool by AusAid - **Generic Impact Function
on Population for Continuous Hazard.**
Contact : ole.moller.nielsen@gmail.com
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as publi... |
ligo-cbc/pycbc-glue | pycbc_glue/LDBDClient.py | """
The LDBDClient module provides an API for connecting to and making requests of
a LDBDServer.
This module requires U{pyGlobus<http://www-itg.lbl.gov/gtg/projects/pyGlobus/>}.
This file is part of the Grid LSC User Environment (GLUE)
GLUE is free software: you can redistribute it and/or modify it under the
terms ... |
PennyDreadfulMTG/Penny-Dreadful-Discord-Bot | logsite/views/match_view.py | import html
import inflect
import titlecase
from flask import url_for
from shared.pd_exception import DoesNotExistException
from .. import APP, importing
from ..data import match
from ..view import View
@APP.route('/match/<int:match_id>/')
def show_match(match_id: int) -> str:
view = Match(match.get_match(matc... |
TheGentlemanOctopus/thegentlemanoctopus | octopus_code/core/octopus/patterns/eqPattern.py | from pattern import Pattern
import itertools
import random
import colorsys
import time
class EqPattern(Pattern):
def __init__(self, meter_color=(255,100,50), background_color=(0,50,255)):
self.meter_r = meter_color[0]
self.meter_g = meter_color[1]
self.meter_b = meter_color[2]
self... |
oposs/pkg.oetiker.ch-build | build/samba4/patches/patch-buildtools_wafsamba_samba__conftests.py | $NetBSD: patch-buildtools_wafsamba_samba__conftests.py,v 1.2 2019/11/10 17:01:58 adam Exp $
Ensure defines are strings to avoid assertion failure, some
returned values are unicode.
--- buildtools/wafsamba/samba_conftests.py.orig 2019-07-09 10:08:41.000000000 +0000
+++ buildtools/wafsamba/samba_conftests.py
@@ -97,9 +... |
vprusso/youtube_tutorials | algorithms/recursion/str_len.py | # YouTube Video: https://www.youtube.com/watch?v=RRK0gd77Ln0
# Given a string, calculate the length of the string.
input_str = "LucidProgramming"
# Standard Pythonic way:
# print(len(input_str))
# Iterative length calculation: O(n)
def iterative_str_len(input_str):
input_str_len = 0
for i in range(len(input... |
patrick-winter-knime/deep-learning-on-molecules | smiles-vhts-embedding/train.py | import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import gc
import argparse
from util import learn
def get_arguments():
parser = argparse.ArgumentParser(description='Train a model')
parser.add_argument('data', type=str, help='Training data set')
parser.add_argument('model', type=str, help='Model')
pa... |
zibawa/zibawa | devices/views.py | from builtins import str
from builtins import range
from django.http import HttpResponse,HttpResponseNotFound
from django.template import loader
from django.shortcuts import get_list_or_404
from django.shortcuts import render
from .forms import TestMessageForm
from .models import Device
from django.conf import settings... |
blynn/spelltapper | app/spelltapper.py | import urllib
import logging
import random
from datetime import datetime
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.db import Key
class Move(db.Model):
move = d... |
MieRobot/Blogs | Blog_LinearRegression.py |
# coding: utf-8
# In[2]:
# Import and read the datset
import numpy as np
from sklearn import linear_model
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv("C://Users//Koyel//Desktop/MieRobotAdvert.csv")
dataset.head()
# In[3]:
dataset.describe()
# In[4]:
dataset.columns
# In[5]:
i... |
jjdmol/LOFAR | CEP/GSM/bremen/src/updater.py | #!/usr/bin/python
from src.sqllist import get_sql
_UPDATER_EXTRAS = {
'runningcatalog': ['runcatid'],
'runningcatalog_fluxes': ['runcat_id', 'band', 'stokes'],
}
def _refactor_update(sql):
"""
Special refactoring for MonetDB update..from imitation.
"""
def _get_extra_conditions(tabname):
... |
shubhamgupta123/erpnext | erpnext/hr/doctype/salary_slip/salary_slip.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe, erpnext
import datetime, math
from frappe.utils import add_days, cint, cstr, flt, getdate, rounded, date_diff, money_in_words
from frapp... |
miquelo/caviar | packages/caviar/engine/lb.py | #
# This file is part of CAVIAR.
#
# CAVIAR 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 3 of the License, or
# (at your option) any later version.
#
# CAVIAR is distributed in the hope that ... |
zozo123/buildbot | master/buildbot/schedulers/base.py | # This file is part of Buildbot. Buildbot 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 eve... |
cristhro/Machine-Learning | ejercicio 5/flaskApp/flaskApp.py | from flask import Flask, jsonify, request, render_template, make_response
from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch()
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template(
'index.html'
)
@app.route('/buscar', methods = ["POST"... |
psy0rz/zfs_autobackup | zfs_autobackup/TreeHasher.py | import itertools
import os
class TreeHasher():
"""uses BlockHasher recursively on a directory tree
Input and output generators are in the format: ( relative-filepath, chunk_nr, hexdigest)
"""
def __init__(self, block_hasher):
"""
:type block_hasher: BlockHasher
"""
... |
wojtask/CormenPy | test/test_chapter16/test_problem16_1.py | import io
import math
import random
from contextlib import redirect_stdout
from unittest import TestCase
from hamcrest import *
from array_util import get_random_unique_array
from chapter16.problem16_1 import greedy_make_change, make_change, print_change
from datastructures.array import Array
from util import between... |
davy39/eric | Tools/TRPreviewer.py | # -*- coding: utf-8 -*-
# Copyright (c) 2004 - 2014 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Module implementing the TR Previewer main window.
"""
from __future__ import unicode_literals
import os
from PyQt5.QtCore import QDir, QTimer, QFileInfo, pyqtSignal, QEvent, QSize, \
QTranslator, QObject, Qt, ... |
dpdani/csu | src/core/user.py | # -*- coding: utf-8 -*-
"""
This module implements users.
"""
import os
from persistent import Persistent
import src.core.db as db
import src.core.exc as exc
import src.core.utils as utils
import src.core.security as security
import random
import time
class User(object):
def __init__(self):
self.__set_to_none()... |
gam17/QAD | cmd/qad_array_maptool.py | # -*- coding: utf-8 -*-
"""
/***************************************************************************
QAD Quantum Aided Design plugin ok
classe per gestire il map tool in ambito del comando array
-------------------
begin : 2016-05-31
copyrig... |
Fenugreek/tamarind | functions.py | """
Some useful utility functions missing from numpy/scipy.
Copyright 2016 Deepak Subburam
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 3 of the License, or
(at your option) any la... |
daniel2101/fleosa | fleosa/report/__init__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Desarrollado por rNet Soluciones
# Jefe de Proyecto: Ing. Ulises Tlatoani Vidal Rieder
# Desarrollador: Ing. Salvador Daniel Pelayo Gómez.
# Analista: Lic. David Padilla Bobadilla
#
###################... |
miltondp/ukbrest | tests/test_pheno2sql.py | import os
import tempfile
import unittest
import numpy as np
import pandas as pd
from sqlalchemy import create_engine
from tests.settings import POSTGRESQL_ENGINE, SQLITE_ENGINE
from tests.utils import get_repository_path, DBTest
from ukbrest.common.pheno2sql import Pheno2SQL
class Pheno2SQLTest(DBTest):
@unitt... |
mheap/ansible | lib/ansible/plugins/cache/jsonfile.py | # (c) 2014, Brian Coca, Josh Drake, et al
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
cache: jsonfi... |
t-wissmann/qutebrowser | qutebrowser/extensions/loader.py | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2018-2020 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser 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 S... |
metomi/rose | metomi/rose/task_run.py | # Copyright (C) British Crown (Met Office) & Contributors.
# This file is part of Rose, a framework for meteorological suites.
#
# Rose 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 3 of the L... |
mcallaghan/tmv | BasicBrowser/scoping/migrations/0197_auto_20180528_1537.py | # Generated by Django 2.0.5 on 2018-05-28 15:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('scoping', '0196_auto_20180528_0902'),
]
operations = [
migrations.AddField(
model_name='docpar',
name='endColor',
... |
HumanExposure/factotum | celery_formtask/forms.py | import copy
from decimal import Decimal
import datetime
from celery_formtask.tasks import processform, PROGRESS_STATE
class FormTaskMixin:
def __init__(self, *args, task=None, ignored_kwargs=[], **kwargs):
self._task = task
self._args_bak = args
self._kwargs_bak = copy.copy(kwargs)
... |
Coder-Yu/RecQ | algorithm/ranking/DMF.py | #coding:utf8
from baseclass.DeepRecommender import DeepRecommender
import numpy as np
from random import choice,random,randint,shuffle
from tool import config
import tensorflow as tf
#According to the paper, we only
class DMF(DeepRecommender):
def __init__(self,conf,trainingSet=None,testSet=None,fold='[1]'):
... |
AZQ1994/s4compiler | sr_mult.py | from list_node import ListNode
from instruction import Instruction, Subneg4Instruction
def sr_mult(WM, LM):
namespace_bak = WM.getNamespace(string=False)
WM.setNamespace(["sr","mult"])
c_0 = WM.const(0)
c_1 = WM.const(1)
c_m1 = WM.const(-1)
c_32 = WM.const(32)
a = WM.addDataWord(0, "arg1")
b = W... |
xuqingkuang/tsCloud | tsCloud/ad/management/commands/_private.py | from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
class ADBaseCommand(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--overwrite',
... |
YannickJadoul/Parselmouth | tests/resource_fixtures.py | # Copyright (C) 2018-2022 Yannick Jadoul
#
# This file is part of Parselmouth.
#
# Parselmouth 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 3 of the License, or
# (at your option) any later ... |
park-bench/gpgmailer | test/__init__.py | #!/usr/bin/python3
# Copyright 2017-2021 Joel Allen Luellwitz and Emily Frost
#
# 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 3 of the License, or
# (at your option) any later v... |
RannyeriDev/Solfege | solfege/fpeditor.py | # vim: set fileencoding=utf-8 :
# GNU Solfege - free ear training software
# Copyright (C) 2009, 2011 Tom Cato Amundsen
#
# 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 3 of the... |
marcosfede/algorithms | maths/prime_test.py | """
prime_test(n) returns a True if n is a prime number else it returns False
"""
import unittest
def prime_test(n):
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
j = 5
while j * j <= n:
if n % j == 0 or n % (j + ... |
aleksl05/IS-206 | ex31.py | print "You enter a dark room with two doors. Do you go through door #1 or door #2?"
door = raw_input("> ")
if door == "1":
print "There`s a giant bear here eating a chees cake. What do you do?"
print "1. Take the cake."
print "2. Scream at the bear."
bear = raw_input("> ")
if bear == "1":
print "The bear e... |
fzimmermann89/pyload | module/plugins/internal/Captcha.py | # -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import time
from module.plugins.internal.Plugin import Plugin
from module.plugins.internal.utils import encode
class Captcha(Plugin):
__name__ = "Captcha"
__type__ = "captcha"
__version__ = "0.47"
__status__ = "stable"
... |
z-uo/pixeditor | dock_tools.py | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
from PyQt4 import QtCore
from PyQt4 import QtGui
from widget import Button, Label
class ToolsWidget(QtGui.QWidget):
""" widget cantaining tools buttons """
def __init__(self, project):
QtGui.QWidget.__init__(self)
self.project = project
#... |
opensemanticsearch/open-semantic-etl | src/opensemanticetl/enhance_xmp.py | import xml.etree.ElementTree as ElementTree
import os.path
import sys
#
# is there a xmp sidecar file?
#
def get_xmp_filename(filename):
xmpfilename = False
# some xmp sidecar filenames are based on the original filename without extensions like .jpg or .jpeg
filenamewithoutextension = '.' . join(filena... |
deyvedvm/cederj | urionlinejudge/python/1379.py | """
The mean of three integers A, B and C is (A + B + C)/3. The median of three integers is the one that would be in the
middle if they are sorted in non-decreasing order. Given two integers A and B, return the minimum possible integer C
such that the mean and the median of A, B and C are equal.
Input
Each test case ... |
ic-hep/DIRAC | src/DIRAC/Core/Utilities/test/Test_ExecutorDispatcher.py | """ py.test test of ExecutorDispatcher
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=protected-access
__RCSID__ = "$Id$"
from DIRAC.Core.Utilities.ExecutorDispatcher import (
ExecutorState,
ExecutorQueues,
)
execState = E... |
parpg/parpg | parpg/dialogueprocessor.py | # This file is part of PARPG.
#
# PARPG 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 3 of the License, or
# (at your option) any later version.
#
# PARPG is distributed in the hop... |
YiqunPeng/Leetcode-pyq | solutions/353DesignSnakeGame.py | class SnakeGame:
def __init__(self, width, height, food):
"""
Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1],... |
YJoe/SpaceShips | Desktop/Python/space_scroll/Game.py | from Start_up import*
from Player import Player, HealthBar
from Bullet import Bullet
from Enemy import Enemy
from Stopper import Stopper
from Particle import Particle
from Stars import Star, create_stars
from Package import EnemyDrop, HealthPack
from Notes import NoteController
class Game:
def __init__(self, play... |
JNero/shiyanlou | wenbenjiexiqi/rules.py | class Rule:
'''
规则父类
'''
def action(self,block,handler):
'''
加标记
'''
handler.start(self.type)
handler.feed(block)
handler.end(self.type)
return True
class HeadingRule(Rule):
'''
一号标题规则
'''
type='heading'
def condition(self,block):
'''
判断文本块是否符合规则
'''
return not '\n' in block and len(bloc... |
hiezust/teask | website/migrations/0031_auto_20170601_1502.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-06-01 12:02
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('website', '0030_github_user'),
]
operations = [
migrations.AddField(
... |
DigitalCampus/django-oppia | api/resources/course.py | import json
import os
import re
import shutil
import xmltodict
import zipfile
from django.conf import settings
from django.conf.urls import url
from django.core.exceptions import MultipleObjectsReturned
from django.db.models import Q
from django.http import HttpResponse, Http404
from django.utils.translation import ug... |
pymedusa/Medusa | medusa/session/factory.py | """Session class factory methods."""
from __future__ import unicode_literals
import logging
from cachecontrol import CacheControlAdapter
from cachecontrol.cache import DictCache
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())
def add_cache_control(session, cache_control_config):
"""Add ... |
SANBI-SA/tools-sanbi-uwc | tools/novo_sort/novo_sort.py | #!/usr/bin/env python
from __future__ import print_function
import argparse
from subprocess import check_call, CalledProcessError
import shlex
import sys
import logging
log = logging.getLogger( __name__ )
def novo_sort( bam_filename, output_filename ):
cmdline_str = "novosort -c 8 -m 8G -s -f {} -o {}".format( ba... |
qris/mailer-dye | dye/fablib.py | import os
from os import path
from datetime import datetime
import getpass
import re
import time
from fabric.context_managers import cd, hide, settings
from fabric.operations import require, prompt, get, run, sudo, local
from fabric.state import env
from fabric.contrib import files
from fabric import utils
def _setu... |
JonSteinn/Kattis-Solutions | src/Dacey the Dice/Python 3/main.py | from collections import deque
class Node(tuple):
##### ^ -- backwad
##### v -- forward
##### <-- left
##### --> right
LEFT,RIGHT,TOP,BOTTOM,FORWARD,BACKWARD = range(6)
def __new__(cls, r, c, five):
return tuple.__new__(cls, (r,c,five))
def __init__(self, r, c, five):
... |
napsternxg/gensim | gensim/models/poincare.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Jayant Jain <jayantjain1992@gmail.com>
# Copyright (C) 2017 Radim Rehurek <me@radimrehurek.com>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""Python implementation of Poincaré Embeddings.
These embeddings are better at capturing... |
dagargo/phatty | tests/test_connector.py | # -*- coding: utf-8 -*-
#
# Copyright 2017 David García Goñi
#
# This file is part of Phatty.
#
# Phatty 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 3 of the License, or
# (at your option) a... |
daniestevez/gr-satellites | python/components/deframers/yusat_deframer.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2021-2022 Daniel Estevez <daniel@destevez.net>
#
# This file is part of gr-satellites
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
from gnuradio import gr, digital
import pmt
from ...hier.sync_to_pdu_packed import sync_to_pdu_packed
from ...hdlc_deframer ... |
diegomartin/Telemaco | TelemacoServer/src/api/RegistrationHandler.py | from piston.handler import BaseHandler
from piston.utils import rc
from telemaco.models import User
from django.db.utils import IntegrityError
class RegistrationHandler(BaseHandler):
class _UserProxy(User): pass
allowed_methods = ('POST')
model = _UserProxy
def create(self, request):
... |
mmdg-oxford/papers | Schlipf-PRL-2018/model/step.py | from __future__ import print_function
from bose_einstein import bose_einstein
from constant import htr_to_K, htr_to_meV, htr_to_eV
import argparser
import norm_k
import numpy as np
import scf
import system
args = argparser.read_argument('Evaluate step-like feature in electron-phonon coupling')
thres = args.thres / htr... |
tridc/django_local_library | catalog/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^books/$', views.BookListView.as_view(), name='books'),
url(r'^books/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'),
url(r'^books/(?P<pk>[-\w]+)/renew/$', views.renew_b... |
Yordan92/Pac-man-multiplayer | Ghosts.py | from MakeGraph import MakeGraph
from Moving_pacman import PacMan
import pygame
class Ghost(MakeGraph):
index = 0
def __init__(self,class_graph,x,y):
Ghost.index = Ghost.index + 1
self.all_nodes = class_graph.get_nodes()
self.paths_to_all_nodes = class_graph.get_shortest_path()
self.path = []
self.hunt... |
fsinf/certificate-authority | ca/django_ca/migrations/0002_auto_20151223_1508.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-23 15:08
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('django_ca', '0001_initial'),
]
operations = [
migrations.AlterField(
... |
pattarapol-iamngamsup/projecteuler_python | problem_006.py | """ Copyright 2012, July 31
Written by Pattarapol (Cheer) Iamngamsup
E-mail: IAM.PATTARAPOL@GMAIL.COM
Sum square difference
Problem 6
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + ... |
TheRedLady/codebook | codebook/profiles/restapi/serializers.py | from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from ..models import MyUser, Profile
from ..utils import perform_reputation_check
class CreateUserSerializer(serializers.ModelSerializer):
password = serializers.CharField(
style={'input_type': 'password'}
... |
debomatic/debomatic | docs/conf.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2021 Luca Falavigna
#
# Author: Luca Falavigna <dktrkranz@debian.org>
#
# 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; version 3 of the License.
#... |
amarquand/nispat | pcntoolkit/normative_model/norm_blr.py | from __future__ import print_function
from __future__ import division
import os
import sys
import numpy as np
import pandas as pd
from ast import literal_eval
try: # run as a package if installed
from pcntoolkit.model.bayesreg import BLR
from pcntoolkit.normative_model.norm_base import NormBase
from pcnt... |
Arcanemagus/SickRage | sickbeard/providers/newpct.py | # coding=utf-8
# Author: CristianBB
# Greetings to Mr. Pine-apple
# URL: https://sick-rage.github.io
#
# This file is part of SickRage.
#
# SickRage 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 versi... |
suizokukan/anceps | dchars/languages/lat/symbols.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
################################################################################
# DChars Copyright (C) 2012 Suizokukan
# Contact: suizokukan _A.T._ orange dot fr
#
# This file is part of DChars.
# DChars is free software: you can redistribute it and/or modify
# ... |
romanvm/romans_blog | blog/views.py | from datetime import date
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.conf import settings
from django.utils.translation import ugettext as _
from django.utils.dateformat import format as format_date
from django.shortcuts import get_object_or_404
from dj... |
danielrichman/snowball-ticketing | snowball_ticketing/info.py | # Copyright 2013 Daniel Richman
#
# This file is part of The Snowball Ticketing System.
#
# The Snowball Ticketing System 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 3 of the License,
# or (... |
Guts/isogeo-notifier | web/isogeo_notify/management/commands/api2db.py | # -*- coding: UTF-8 -*-
#!/usr/bin/env python
# ############################################################################
# ########## Libraries #############
# ##################################
# Standard library
import logging
from os import path
# 3rd party modules
import arrow
from isogeo_pysdk import Isogeo
... |
NetworkManager/NetworkManager-ci | run/centos-ci/cico_gitlab_trigger.py | #!/usr/bin/env python
import sys
import json
import os
import datetime
import time
from pprint import pprint
default_os = '8-stream'
##next_os = 'RHEL8.4'
#next_branch_base = 'rhel-8'
jenkins_url = 'https://jenkins-networkmanager.apps.ocp.ci.centos.org/'
class GitlabTrigger(object):
def __init__(self, data):
... |
HaoMood/cs231n | assignment2/assignment2/cs231n/data_utils.py | import cPickle as pickle
import numpy as np
import os
from scipy.misc import imread
def load_CIFAR_batch(filename):
""" load single batch of cifar """
with open(filename, 'rb') as f:
datadict = pickle.load(f)
X = datadict['data']
Y = datadict['labels']
X = X.reshape(10000, 3, 32, 32).transpose(0,2,... |
esitamon/django-skeleton | app/website/api.py | from rest_framework import viewsets, permissions
import models
import serializers
class PageViewSet(viewsets.ModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
"""
queryset = models.Page.objects.all()
serializer_class = seriali... |
SpaceGroupUCL/qgisSpaceSyntaxToolkit | esstoolkit/external/networkx/algorithms/assortativity/tests/test_mixing.py | import pytest
np = pytest.importorskip("numpy")
npt = pytest.importorskip("numpy.testing")
import networkx as nx
from .base_test import BaseTestAttributeMixing, BaseTestDegreeMixing
class TestDegreeMixingDict(BaseTestDegreeMixing):
def test_degree_mixing_dict_undirected(self):
d = nx.degree_mixing_dict... |
BrainTech/pre-pisak | modules/others/symbols.py | #!/bin/env python2.7
# -*- coding: utf-8 -*-
# This file is part of AT-Platform.
#
# AT-Platform 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 3 of the License, or
# (at your option) any late... |
e-democracy/edem.content.logo | setup.py | # -*- coding=utf-8 -*-
import os
from setuptools import setup, find_packages
from version import get_version
version = get_version()
setup(name='edem.content.logo',
version=version,
description="Logos for forums.e-democracy.org",
long_description=open("README.txt").read() + "\n" +
op... |
wehkamp/ansible-modules-extras | network/nmcli.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Chris Long <alcamie@gmail.com> <chlong@redhat.com>
#
# This file is a module for Ansible that interacts with Network Manager
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
#... |
dvarrazzo/arduino | thermo/client/google_api.py | #!/usr/bin/env python
"""Read the Google Weather API and emit data in the usual format.
Write a sample every 5 minutes on stdout, log on stderr.
"""
import sys
import time
from urllib import quote_plus
from urllib2 import urlopen
from datetime import datetime, timedelta
from xml.etree import cElementTree as ET
impor... |
michaelerule/neurotools | graphics/pygame.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
from __future__ import absolute_import
from __future__ import with_statement
from __future__ import division
from __future__ import print_function
'''
Collected utilities for pygame
It is difficult to write pixels directly in python.
There's some way to get a framebuffer bac... |
andrew-lundgren/gwpy | gwpy/plotter/axes.py | # -*- coding: utf-8 -*-
# Copyright (C) Duncan Macleod (2013)
#
# This file is part of GWpy.
#
# GWpy 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 3 of the License, or
# (at your option) any ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.