repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
monetate/sqlalchemy
test/sql/test_metadata.py
Python
mit
176,328
0
from contextlib import contextmanager import pickle import sqlalchemy as tsa from sqlalchemy import ARRAY from sqlalchemy import bindparam from sqlalchemy import BLANK_SCHEMA from sqlalchemy import Boolean from sqlalchemy import CheckConstraint from sqlalchemy import Column from sqlalchemy import column from sqlalchem...
qlalchemy import Enum from sqlalchemy import event from sqlalchemy import exc from sqlalchemy import ForeignKey from sqlalchemy import ForeignKeyConstraint from sqlalchemy import func from sqlalchemy import Index from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import PrimaryKeyConstraint ...
mport testing from sqlalchemy import text from sqlalchemy import TypeDecorator from sqlalchemy import types as sqltypes from sqlalchemy import Unicode from sqlalchemy import UniqueConstraint from sqlalchemy.engine import default from sqlalchemy.schema import AddConstraint from sqlalchemy.schema import CreateIndex from ...
pcmagic/stokes_flow
try_code/contourAnimation.py
Python
mit
1,468
0.002725
import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np # from sympy import * from src import jeffery_model as jm DoubleletStrength = np.array((1, 0, 0)) alpha = 1 B = np.array((0, 1, 0)) lbd = (alpha ** 2 - 1) / (alpha ** 2 + 1) x, y = np.meshgrid(np.linspace(-1, 1, 100), np.linspa...
200 def fun(zi): location = np.vstack((x.flatten(), y.flatten(), np.ones_like(y.flatten()) * zi)) Jij = problem.J_matrix(location) JijT = Jij.transpose(1, 0, 2) Sij = 1 / 2 * (Jij + JijT) Oij = 1 / 2 * (Jij - JijT) B
ij = Sij + lbd * Oij TrB2 = (Bij[0, 0, :] ** 2 + Bij[1, 1, :] ** 2 + Bij[2, 2, :] ** 2).reshape(x.shape) TrB3 = (Bij[0, 0, :] ** 3 + Bij[1, 1, :] ** 3 + Bij[2, 2, :] ** 3).reshape(x.shape) DtLine = TrB2 ** 3 - 6 * TrB3 ** 2 return DtLine fig, ax = plt.subplots() p = [ax.contourf(x, y, np.log10(fun(1 /...
brianrodri/oppia
scripts/run_lighthouse_tests.py
Python
apache-2.0
7,645
0.000131
# Copyright 2020 The Oppia Authors. 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 ...
or implied. # See the License for the specific language governing permissions and # limitations under the License. """This script performs lighthouse checks and creates lighthouse reports. Any callers must pass in a flag, either --accessibility or --performance. """ from __future__ import annotations import argparse ...
from core.constants import constants from scripts import build from scripts import common from scripts import servers LIGHTHOUSE_MODE_PERFORMANCE = 'performance' LIGHTHOUSE_MODE_ACCESSIBILITY = 'accessibility' SERVER_MODE_PROD = 'dev' SERVER_MODE_DEV = 'prod' GOOGLE_APP_ENGINE_PORT = 8181 LIGHTHOUSE_CONFIG_FILENAMES ...
pandeydivesh15/NER-using-Deep-Learning
Task 3: Hindi data/NER_model.py
Python
mit
3,179
0.038377
# Keras imports from keras.preprocessing import sequence from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers.wrappers import TimeDistributed from keras.layers.wrappers import Bidirectional from keras.layers.core import Dropout from keras.regularizers import...
self.y_train = self.y[split_mask] self.x_test = self.x[~split_mask] self.y_test = self.y[~split_mask] self.model.fit(self.x_train, self.y_train, nb_epoch=epochs, batch_size=batch_size) def evaluate(self): predicted_tags= [] test_data_tags = [] for x,y in zip
(self.x_test, self.y_test): flag = 0 tags = self.model.predict(np.array([x]), batch_size=1)[0] pred_tags = self.data_reader.decode_result(tags) test_tags = self.data_reader.decode_result(y) for i,j in zip(pred_tags, test_tags): if j != self.data_reader.NULL_CLASS: flag = 1 if flag == 1: ...
jmcanterafonseca/fiware-cygnus
test/acceptance/tools/mysql_utils.py
Python
agpl-3.0
7,640
0.010344
# -*- coding: utf-8 -*- # # Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U # # This file is part of fiware-cygnus (FI-WARE project). # # fiware-cygnus is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General # Public License as published by the Free Software Foun...
YSQL_SHOW_DATABASE = u'SHOW DATABASES' MYSQL_SHOW_TABLES = u'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = \'' class Mysql: """ mysql
funcionabilities """ def __init__(self, **kwargs): """ constructor :param host: mysql host (MANDATORY) :param port: mysql port (MANDATORY) :param user: mysql user (MANDATORY) :param password: mysql pass (MANDATORY) :param database: mysql database (OPTIO...
Dev-Cloud-Platform/Dev-Cloud
dev_cloud/cc1/src/cm/settings_ctx.py
Python
apache-2.0
802
0
# -*- coding: utf-8 -*- # @COPYRIGHT_begin # # Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland # # 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 # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ...
limitations under the License. # # @COPYRIGHT_end from cm.settings import * ROOT_URLCONF = 'cm.urls_ctx' WSGI_APPLICATION = 'cm.wsgi_ec2ctx.application'
BassantMorsi/finderApp
users/api/views.py
Python
mit
17,235
0.002379
import json from django.http import HttpResponse from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.generics import ( ListAPIView, RetrieveAPIView, UpdateAPIView, DestroyAPIView, CreateAPIView ) fro...
age_path).convert('L') # Convert the image format into numpy array image = np.array(image_pil, 'uint8') # Detect the face in the image faces = detector.detectMultiScale(image) # If face is detected, append the face to images and the label to labels ...
faces: images.append(image[y: y + h, x: x + w]) labels.append(int(os.path.split(image_path)[1].split(".")[1])) return images, labels, maxreqid def get_images_and_labels(path, extension): # images will contains face images images = [] # labels will contains the label th...
dieterich-lab/dorina
dorina/report.py
Python
gpl-3.0
6,747
0.000148
#!/usr/bin/env python # -*- coding: utf-8 """ Created on 13:48 16/04/2018 2018 This module contains a tools for ploting regulator .bed files distributed with Dorina. """ import multiprocessing from pathlib import Path import numpy as np import pandas as pd import pybedtools from bokeh.layouts import gridplot from bok...
ounts, render_mode='canvas', text_font='helvetica', text_font_size='9pt') p.add_layout(labels) p.toolbar.active_drag = None p.ygrid.grid_line_color = None p.xaxis.axis_label = "Counts" p.yaxis.axis_line_color = None p.yaxis.major_tick_line_color = None p.outline_line_co...
t_font = 'helvetica' p.yaxis.major_label_text_font = 'helvetica' p.title.text_font = 'helvetica' p.xaxis.axis_label_text_font = 'helvetica' return p def add_chr(entry): entry.chrom = 'chr' + entry.chrom return entry def plot_chr_counts(assembly, dataframe): chr_size = pybedtools.chroms...
wangybgit/Chameleon
hostapd-OpenWrt/tests/hwsim/test_suite_b.py
Python
apache-2.0
5,735
0.001918
# Suite B tests # Copyright (c) 2014-2015, Jouni Malinen <[email protected]> # # This software may be distributed under the terms of the BSD license. # See README for more details. import time import logging logger = logging.getLogger() import hostapd from utils import HwsimSkip def test_suite_b(dev, apdev): """WPA2-PSK/G...
"private_key": "auth_serv/ec2-server.key" } hapd = hostapd.add_ap(apdev[0]['if
name'], params) dev[0].connect("test-suite-b", key_mgmt="WPA-EAP-SUITE-B-192", ieee80211w="2", openssl_ciphers="SUITEB192", eap="TLS", identity="tls user", ca_cert="auth_serv/ec2-ca.pem", client_cert="auth_serv/ec2-user....
vertexproject/synapse
synapse/tests/test_cryotank.py
Python
apache-2.0
4,379
0.000457
import synapse.common as s_common import synapse.cryotank as s_cr
yotank import synapse.lib.const as s_const import synapse.tests.utils as s_t_utils from synapse.tests.utils import alist logger = s_cryotank.logger cryodata = (('foo', {'bar': 10}), ('baz', {'faz': 20})) class CryoTest(s_t_utils.SynTest): async def test_cryo_cell_async(self): async with self.getTestCr...
async with cryo.getLocalProxy() as prox: self.true(await prox.init('foo')) self.eq([], await alist(prox.rows('foo', 0, 1))) async def test_cryo_cell(self): with self.getTestDir() as dirn: async with self.getTestCryoAndProxy(dirn=dirn) as (cryo, prox): ...
PrincetonUniversity/AdvNet-OF_Scripts
evaluation/switch/flowmod_test/pox/pox/samples/l2_bell_burst_mod.py
Python
apache-2.0
7,313
0.015315
# Copyright 2011 James McCauley # # This file is part of POX. # # POX 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. # # POX is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; wi...
PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with POX. If not, see <http://www.gnu.org/licenses/>. """ An L2 learning switch. It is derived from one written live for an SDN crash course. It is somwhat similar...
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
orcid_api_v3/models/funding_contributor_v30_rc1.py
Python
mit
6,669
0.00015
# coding: utf-8 """ ORCID Member No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: Latest Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import si...
a: F401,E501 from orcid_api_v3.models.contributor_orcid_v30_rc1 import ContributorOrcidV30Rc1 # noqa: F401,E501 from orcid_api_v3.models.credit_name_v30_rc1 import CreditNameV30Rc1 # noqa: F401,E501 from orcid_api_v3.models.funding_contributor_attributes_v30_rc1 import FundingContributorAttributesV30Rc1 # noqa: F401...
""" """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'contributor...
NablaWebkom/django-wiki
wiki/plugins/macros/settings.py
Python
gpl-3.0
256
0
from __future__ import absolute_import, unicode_literals from django.conf import settings as django_settings SLUG = 'ma
cros' APP_LABEL = 'wiki' METHODS = getattr( django_settings, 'WIKI_PLUGINS_METHODS',
('article_list', 'toc', ))
lituan/tools
leaf/leaf.py
Python
cc0-1.0
6,618
0.008008
#!/usr/bin/env python # -*- coding: utf-8 -*- """ use leaf alogrithm to remove redundancy this algorithm is published in this following paper 1. Bull, S. C., Muldoon, M. R. & Doig, A. J. Maximising the Size of Non-Redundant Protein Datasets Using Graph Theory. PLoS One 8, (2013). Simon Bull gives an implementation for ...
row) for row in similarities] for i in range(len(matrix)): matrix[i][i] = 0 # use igraph to plot the initial network graph = igraph.Graph.Adjacency(matrix, mode='undirected') igraph.plot(graph, filename + '.png', vertex_label=range(len(labels))) adjlist = [[i for i,n in enume...
): print '{0}:{1},'.format(i,a) # transform adjlist to set neighbors = [set(n) for i, n in enumerate(adjlist)] # detect possible max clique max_neighbors = max(len(l) for l in neighbors) # the possible clique size is 2 to max_neighbors+1, so the possible # neighborsize is 1 to max_neighb...
t-wissmann/qutebrowser
qutebrowser/browser/webkit/tabhistory.py
Python
gpl-3.0
3,533
0
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2020 Florian Bruhin (The Compiler) <[email protected]> # # 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...
0.0, # 'referrer': '', # 'scrollPosition': {'x': 0, 'y': 0}, # 'target': '', # 'title': '', # 'urlString': 'about:blank'}]} data = {'currentItemIndex': current_idx, 'history': []} for item in items: data['history']...
ap(data) def _serialize_item(item): data = { 'originalURLString': item.original_url.toString(QUrl.FullyEncoded), 'scrollPosition': {'x': 0, 'y': 0}, 'title': item.title, 'urlString': item.url.toString(QUrl.FullyEncoded), } try: data['scrollPosition']['x'] = item.use...
rwl/muntjac
muntjac/demo/sampler/features/commons/Tooltips.py
Python
apache-2.0
930
0.009677
from muntjac.ui.abstract_component import AbstractComponent from muntjac.demo.sampler.APIResource import APIResource from muntjac.demo.sampler.Feature import Feature, Version class Tooltips(Feature): def getSinceVersion(self): return Version.OLD def getName(self): return 'Tooltips' ...
return None def getRelatedResources(self): # TODO Auto
-generated method stub return None
mitodl/bootcamp-ecommerce
applications/management/utils.py
Python
bsd-3-clause
6,610
0.003177
"""Application management command utility functions""" from collections import defaultdict from django.core.exceptions import ValidationError from django.db import transaction from applications.api import derive_application_state from applications.constants import APPROVED_APP_STATES from applications.models import (...
the run step ids for which a submission has already been created. used_run_step_ids = set() for from_app_step_submission in from_app_step_submissions: submission_type = ( from_app_step_submission.run_application
_step.application_step.submission_type ) to_run_step_id = next( step_id for step_id in to_run_steps[submission_type] if step_id not in used_run_step_ids ) ApplicationStepSubmission.objects.update_or_create( b...
ikalnytskyi/kostyor-openstack-ansible
kostyor_openstack_ansible/upgrades/ref.py
Python
gpl-3.0
6,099
0
# This file is part of OpenStack Ansible driver for Kostyor. # # 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 version. # # This ...
loader=loader, options=options, passwords={} ) # So
me playbooks may rely on current working directory, so better allow # to change it before execution. with _setcwd(cwd): exitcode = executor.run() # Celery treats exceptions from task as way to mark it failed. So let's # throw one to do so in case return code is not zero. if all([not ignore_...
eProsima/Fast-DDS
test/profiling/memory_analysis.py
Python
apache-2.0
483
0.00207
import sys import msparser import csv stack = [] heap = [] msparser_data = mspar
ser.parse_file(sys.argv[1]) for snapshot in msparser_data['snapshots']: if snapshot['mem_heap'] !
= 0: stack.append(snapshot['mem_stack']) heap.append(snapshot['mem_heap']) with open(sys.argv[2], 'w+') as csv_file: csv_writer = csv.writer(csv_file, delimiter=',', quoting=csv.QUOTE_ALL) csv_writer.writerow(['stack', 'heap']) csv_writer.writerow([max(stack), max(heap)])
pierreberthet/local-scripts
reduce_dopa.py
Python
gpl-2.0
4,102
0.024866
import nest import nest.raster_plot import numpy as np import pylab as pl nest.ResetKernel() nest.SetKernelStatus({"overwrite_files": True}) sim_time = 0. weight = [] if (not 'bcpnn_dopamine_synapse' in nest.Models()): #nest.Install('ml_module') nest.Install('/media/backup/temp_milner/save/17.10.14/modu...
son_post, {'rate': post_rate}) nest.SetStatus(poisson_dopa, {'rate': dopa_rate}) global sim_time global weight sim_time+= duration nest.Simulate(duration) weight.append(np.mean([(np.log(a['p_ij']/(a['p_i']*a['p_j']))) for a in nest.GetStatus(conn)])) step=250. simul(1000.,1000.,1000.,step) sim...
s(voltmeter)[0]['events'] t = events['times'] pl.subplot(211) pl.plot(t, events['V_m']) pl.ylabel('Membrane potential [mV]') pl.subplot(212) pl.plot(weight) pl.show() nest.raster_plot.from_device(recorder, hist=True) nest.raster_plot.show() param = [{'C_m': 250.0, 'E_L': -70.0, 'E_ex': 0.0, 'E_in': -85.0, 'I_e': 0...
diegojromerolopez/djanban
src/djanban/apps/journal/migrations/0003_auto_20160926_1851.py
Python
mit
563
0.001776
# -*- coding: utf-8 -*- # Gene
rated by Django 1.10 on 2016-09-26 16:51 from __future__ import unicode_literals import ckeditor_uploader.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('journal', '0002_auto_20160926_0155'), ] opera
tions = [ migrations.AlterField( model_name='journalentry', name='content', field=ckeditor_uploader.fields.RichTextUploadingField(help_text='Content of this journal entry', verbose_name='Content'), ), ]
blaze/distributed
distributed/protocol/tests/test_serialize.py
Python
bsd-3-clause
11,096
0.00027
import copy import pickle import msgpack import numpy as np import pytest from tlz import identity from distributed import wait from distributed.protocol import ( register_serialization, serialize, deserialize, nested_deserialize, Serialize, Serialized, to_serialize, serialize_bytes, ...
= msgpack.loads(frames[1], raw=False) return obj @gen_cluster( client=True, client_kwargs={"serializers": ["my-ser", "pickle"]},
worker_kwargs={"serializers": ["my-ser", "pickle"]}, ) async def test_context_specific_serialization(c, s, a, b): register_serialization_family("my-ser", my_dumps, my_loads) try: # Create the object on A, force communication to B x = c.submit(MyObject, x=1, y=2, workers=a.address) y =...
sgmap/openfisca-web-api
openfisca_web_api/controllers/calculate.py
Python
agpl-3.0
19,065
0.016313
# -*- coding: utf-8 -*- """Calculate controller""" from __future__ import division import collections import copy import itertools import os import time from openfisca_core.legislations import ParameterNotFound from .. import conf, contexts, conv, environment, model, wsgihelpers def N_(message): return mes...
labels = conv.pipe( # Return labels (of enumerations) instead of numeric values. conv.test_isinstance((bool, int)), conv.
anything_to_bool, conv.default(False), ), output_format = conv.pipe( conv.test_isinstance(basestring), conv.test_in(['test_case', 'variables']), conv.default('test_case'), ), reforms = str_list_to_ref...
admetricks/bravado-core
tests/unmarshal/unmarshal_object_test.py
Python
bsd-3-clause
4,494
0
# -*- coding: utf-8 -*- import pytest from bravado_core.exception import
SwaggerMappingError from bravado_core.unmarshal import unmarshal_object from bravado_core.
spec import Spec @pytest.fixture def address_spec(): return { 'type': 'object', 'properties': { 'number': { 'type': 'number' }, 'street_name': { 'type': 'string' }, 'street_type': { 'type': ...
wiki-ai/revscoring
tests/languages/test_greek.py
Python
mit
5,978
0.000469
import pickle from revscoring.datasources import revision_oriented from revscoring.dependencies import solve from revscoring.languages import greek from .util import compare_extraction BAD = [ "αδερφάρα", "αδελφάρα", "αλήτης", "αλητήριος", "αλητήρια", "αλητήριο", "αλητάμπουρας", "άχρηστος", "άχρη...
pickle.loads(pickle.dumps(greek.informals)) def test_dictionary(): cache = {r_text: 'Αυτό είναι γραμμένο λθος. <td>'} assert (solve(greek.dictionary.revision.datasources.dict_words, cache=cache) == ["Αυτό", "είναι", "γραμμένο"]) assert (solve(greek.dictionary.revision.datasources.non_dict_word...
ckle.loads(pickle.dumps(greek.dictionary)) def test_stopwords(): cache = {r_text: 'Αυτό είναι γραμμένο λθος. <td>'} assert (solve(greek.stopwords.revision.datasources.stopwords, cache=cache) == ["Αυτό", "είναι"]) assert (solve(greek.stopwords.revision.datasources.non_stopwords, ...
danielnyga/dnutils
tests/testp3.py
Python
mit
8,270
0.002297
# -*- coding: utf-8 -*- import time from multiprocessing.pool import Pool import colored import numpy as np from dnutils import out, stop, trace, getlogger, ProgressBar, StatusMsg, bf, loggers, newlogger, logs, edict, ifnone, \ ifnot, allnone, allnot, first, sleep, __version__ as version, waitabout import unitt...
linearscale(self): scale = LinearScale([0, 100], [0, 1]) self.assertEqual(scale(50), .5) with self.assertRaises(ValueError): scale(-50) scale(150)
scale.strict = False self.assertEqual(scale(-50), -.5) self.assertEqual(scale(150), 1.5) def exposure_proc(*_): for _ in range(10): waitabout(1) # use the exposure as a file lock with exposure('/vars/myexposure'): n = inspect(expose('/vars/myexposure')) ...
RakshakTalwar/hatchpitchpull
hatchpitchpull/hatchpitchpull.py
Python
apache-2.0
12,244
0.015109
""" Copyright 2016 (c) Rakshak Talwar Released under the Apache 2 License """ import json, pdb, re, time import HTMLParser import sqlite3 as sql import requests import gspread from oauth2client.client import SignedJwtAssertionCredentials ### global variables ### hparse = HTMLParser.HTMLParser() ### gather authentic...
m the F6S API calls and create semi-copies with relevant and corresponding fields for j_object in j_objects: # create a temporary object, will be appended to the cleaned_objs list temp_obj = {} # fill up the temp_obj with the relevant information for index, sql_...
ds[index], str): # if the field is directly present, no nesting temp_obj[sql_field] = j_object[self.json_fields[index]] elif isinstance(self.json_fields[index], list): # handles nested cases nest_list = self.json_fields[index] # for brevity's sake ...
ovresko/erpnext
erpnext/controllers/buying_controller.py
Python
gpl-3.0
29,596
0.025476
# 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 from frappe import _, msgprint from frappe.utils import flt,cint, cstr, getdate from erpnext.accounts.party import get_party_details from...
ult(self): if self.meta.get_field("supplier") and not self.supplier: for d in self.get("items"): supplier = frappe.db.get_value("Item Default", {"parent": d.item_code, "company": self.company}, "default_supplier") if supplier: self.supplier = supplier else: item_group = frappe.db.get_val...
ier: self.supplier = supplier break def validate_stock_or_nonstock_items(self): if self.meta.get_field("taxes") and not self.get_stock_items() and not self.get_asset_items(): tax_for_valuation = [d for d in self.get("taxes") if d.category in ["Valuation", "Valuation and Total"]] if tax_for_val...
stuti-rastogi/leetcodesolutions
234_palindromeLinkedList.py
Python
apache-2.0
1,611
0.004966
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ # stack = [] # if (not head):...
# stack.append(curr.
val) # curr = curr.next # curr = head # while (curr): # if (curr.val != stack.pop()): # return False # curr = curr.next # return True # O(1) space solution if not head or not head.next: return True c...
jrd/pylibsalt
tests/test_execute.py
Python
gpl-2.0
929
0.007535
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: set et ai sta sts=2 sw=2 ts=2 tw=0: from __future__ import print_function, unicode_literals, absolute_import import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import unittest from libsalt import execute as ex import ...
l"), 0) self.assertEqual(ex.execCall("ls -lh | grep -q '[.]'"), 0) self.assertEqual(ex.execCall(['echo', '-n'], shell=False), 0) def test_call_ko(self): self.assertEqual(ex.execCall("xyz 2>/dev/null"), 127) self.assertRaises(subprocess.CalledProcessError, ex.execCheck, "xyz") def test_exec_check(s...
ssertEqual(ex.execGetOutput("pwd")[0].strip(), os.getcwd())
ToonTownInfiniteRepo/ToontownInfinite
toontown/minigame/DistributedTagGame.py
Python
mit
10,955
0.002191
from pandac.PandaModules import * from toontown.to
onbase.ToonBaseGlobal import * from DistributedMinigame import * from direct.interval.IntervalGlobal import * from direct.fsm import ClassicFSM, State from direct.fsm import State from toontown.safezone import Walk from toontown.toonbase import ToontownTimer from direct.gui import OnscreenText import MinigameAvatarScor...
import TTLocalizer from otp.otpbase import OTPGlobals import TagGameGlobals import Trajectory class DistributedTagGame(DistributedMinigame): DURATION = TagGameGlobals.DURATION IT_SPEED_INCREASE = 1.3 IT_ROT_INCREASE = 1.3 def __init__(self, cr): DistributedMinigame.__init__(self, cr) s...
tjcsl/wedge
achievements.py
Python
mit
1,867
0.006427
from db import conn import json #Format "Name":"Desc" achievement_metadata = {} def first_edit(wpusername): first_edit.name = "Your First Edit" achievement_metadata[first_edit.name] = "Awarded for your first edit after signing up for wedge" query = "SELECT score FROM edits WHERE username=%s" cur = co...
rname, ach.name)) return row[0] > score and cur.fetchone() is None return ach ACH_FUNCS = [ first_edit, gen_point_achievement(10, "Ten Points", "Awarded for getting 10 points"), gen_point_achievement(100, "One Hundred Points", "Awarded for acculating 100 points"), gen_point...
y 1,000 points"), gen_point_achievement(9001, "Over 9000", "Get OVER 9000 POINTS")] def check_all_achievements(wpusername): for i in ACH_FUNCS: check(i, wpusername) def check(f, wpusername): result = f(wpusername) if result: name = f.name query = "INSERT INTO achievements...
pandas-dev/pandas
pandas/tests/frame/methods/test_between_time.py
Python
bsd-3-clause
10,811
0.000647
from datetime import ( datetime, time, ) import numpy as np import pytest from pandas._libs.tslibs import timezones import pandas.util._test_decorators as td from pandas import ( DataFrame, Series, date_range, ) import pandas._testing as tm class TestBetweenTime: @td.skip_if_has_locale ...
g) stime, etime = ("08:00:00", "09:00:00") msg = "Index must be DatetimeIndex" if axis in ["columns", 1]: ts.index = mask with pytest.raises(TypeError, match=msg): t
s.between_time(stime, etime) with pytest.raises(TypeError, match=msg): ts.between_time(stime, etime, axis=0) if axis in ["index", 0]: ts.columns = mask with pytest.raises(TypeError, match=msg): ts.between_time(stime, etime, axis=1) def te...
alihanniba/pythonDemo
homePage/polls/models.py
Python
mit
401
0.007481
from __future__ import unicode_literals from django.db import models # Create your models here. class Question(models.Mod
el): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('data published') class Chioce(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(
max_length=200) votes = models.IntegerField(default=0)
killuazhu/vimrc
sources_non_forked/deoplete.nvim/rplugin/python3/deoplete/filter/converter_truncate_menu.py
Python
mit
1,019
0
# ============================================================================ # FILE: converter_truncate_menu.py # AUTHOR: Shougo Matsushita <Shougo.Matsu at gmail.com> # License: MIT license # ============================================
================================ from .base import Base from deoplete.util import truncate_skipping class Filter(Base): def __init__(self, vim): super().__init__(vim) self.name = 'conve
rter_truncate_menu' self.description = 'truncate menu converter' def filter(self, context): max_width = context['max_menu_width'] if not context['candidates'] or 'menu' not in context[ 'candidates'][0] or max_width <= 0: return context['candidates'] foot...
Baseyoyoyo/Higher-or-Lower
tests/score_board_test.py
Python
mit
1,622
0.008015
import unittest import datetime from classes.score_board import ScoreBoard class DateTimeStub(object): def now(self): return "test_date_time" class ScoreBoardTest(uni
ttest.TestCase): def __init__(self, *args, **kwargs): super(ScoreBoardTest, self).__init__(*args, **kwargs) self.score_board = ScoreBoard("testdatabase.db") def seedScores(self): self.score_board.clear() dummy_scores = [ ("player1", 5, datetime.datetime.now() - datetime.timedelta(days=3...
] self.score_board.cursor.executemany( "INSERT INTO scores(name, score, recorded_at) VALUES(?,?,?)", dummy_scores ) self.score_board.db.commit() def testRecorderAt(self): self.assertEqual(type(self.score_board.recordedAt()), datetime.datetime) def testCount(self): self.seedScores...
EricssonResearch/calvin-base
calvin/runtime/south/storage/twistedimpl/securedht/dht_server_commons.py
Python
apache-2.0
21,119
0.00554
# -*- coding: utf-8 -*- # Copyright (c) 2015 Ericsson AB # # 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 ...
to bootstrap %s" % (args)) #reactor.callLater(.5, bootstrap_proxy, addrs) _log.debug("Trying to bootstrap with %s" % (repr(addrs))) d = self.dht_server.bootstrap(addrs) d.addCallback(started) d.addErrback(failed) def start_msearch(args): ...
g.debug("** msearch %s args: %s" % (self, repr(args))) def _later_start(): self._ssdps.start_search(service_discovery_ssdp.SERVICE_UUID, callback=bootstrap_proxy, stop=False) self._ssdps.update_server_params(service_discovery_ssdp.SERVICE_UUID, cert=certstr) serv...
FePhyFoFum/PyPHLAWD
src/choose_one_species_cluster.py
Python
gpl-2.0
1,407
0.002132
import sys import seq import os from logger import Logger """ right now this just chooses the longest BEWARE, this writes over the file """ if __name__ == "__main__": if len(sys.argv) != 4 and len(sys.argv) != 5: print("python "+sys.argv[0]+" table clusterdir fending [logfile]") sys.exit(0) f...
b.close() dirr = sys.argv[2] for o in os.listdir(dirr): if fend != None: if fend not in o: continue seqs = {} for i in seq.read_fasta_file_iter(dirr+"/"+o): if idn[i.name] not in seqs: seqs[idn[i.name]] = [] seqs[idn[i.n...
if len(j.seq) > longestn: longest = j longestn = len(j.seq) seqs[i] = [longest] fn = open(dirr+"/"+o,"w") for i in seqs: for j in seqs[i]: fn.write(j.get_fasta()) fn.close() log.c()
fduraffourg/servo
ports/geckolib/string_cache/regen_atom_macro.py
Python
mpl-2.0
1,335
0.004494
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import re import sys if len(sys.argv) != 2: print "usage: ./%s PATH/TO/OBJDIR" % sys.argv[0] objdir_path = sys.argv...
result = re.match('^GK_ATOM\((.+),\s*"(.*)"\)', line) return (result.group(1), result.group(2)) def symbolify(ident): return "_ZN9nsGkAtoms" + str(len(ident
)) + ident + "E" with open(objdir_path + "/dist/include/nsGkAtomList.h") as f: lines = [line for line in f.readlines() if line.startswith("GK_ATOM")] atoms = [line_to_atom(line) for line in lines] with open("atom_macro.rs", "w") as f: f.write("use gecko_bindings::structs::nsIAtom;\n\n") f.write("use ...
dstaple/z3test
old-regressions/python/z3py.9.py
Python
mit
170
0
# Copyright
(c) 2015 Microsoft Corporation from z3 import * set_option(auto_config=True) p = Bool('p') x = Real('x') solve(Or(x < 5
, x > 10), Or(p, x**2 == 2), Not(p))
xfxf/veyepar
dj/scripts/tsdv.py
Python
mit
4,150
0.005783
#!/usr/bin/python """ tsdv.py - timestamp dv sets start/end times of dv files Gets start from one of: the file name (assumes yy_mm_dd/hh_mm_ss.dv format) the file system time stamp, the first frame of the dv duration (in seconds) based on file size / BBF*FPS last frame """ import os import datetime from fnmatch im...
f.options.client: client = Client.obj
ects.get(slug=self.options.client) show = Show.objects.get( client=client, slug=self.options.show) else: show = Show.objects.get(slug=self.options.show) self.one_show(show) return def add_more_options(self, parser): # parser.add_option('...
vulogov/zq
setup.py
Python
gpl-3.0
3,597
0.0139
from setuptools import setup#, find_packages, Extension import distutils.command.build as _build import setuptools.command.install as _install import sys import os import os.path as op import distutils.spawn as ds import distutils.dir_util as dd import posixpath def run_cmake(arg=""): """ Forcing to run cmak...
, "termcolor", "humanfriendly", "ipaddr", "pyfscache", "Cheetah", "dateparser", "pygithub", ], requires = [], include_package_data = True, url = 'https://github.com/vulogov/zq/', author='Vladimir Ulogov', author_email = '[email protected]', maintainer_email = 'vladimir.u...
, zabbix", platforms = ['GNU/Linux','Unix','Mac OS-X'], classifiers = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', ...
LokiNetworks/empower-runtime
empower/apps/zephyr/zephyr.py
Python
apache-2.0
17,023
0.006814
#!/usr/bin/env python3 # # Copyright (c) 2015, Roberto Riggio # Al
l rights reserved. # # Redistribution and use in source and binary forms, with or without # modification,
are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and th...
nhannv/hasjob
hasjob/twitter.py
Python
agpl-3.0
2,286
0.002189
# -*- coding: utf-8 -*- from flask.ext.rq import job from tweepy import OAuthHandler, API import bitlyapi import urllib2 import json import re from hasjob import app @job('hasjob') def tweet(title, url, location=None, parsed_location=None, username=None): auth = OAuthHandler(app.config['TWITTER_CONSUMER_KEY'], a...
sed_location: locationtags = [] for token in parsed_location.get('tokens', []): if 'geoname' in token and 'token' in token: locname = token['token'].strip() if locname: locationtags.append(u'#' + locname.titl
e().replace(u' ', '')) locationtag = u' '.join(locationtags) if locationtag: maxlength -= len(locationtag) + 1 if not locationtag and location: # Make a hashtag from the first word in the location. This catches # locations like 'Anywhere' which have no geonameid but are s...
SamuelLongchamps/grammalecte
compile_rules.py
Python
gpl-3.0
24,371
0.006309
import re import sys import traceback import copy import json from distutils import file_util from grammalecte.echo import echo DEF = {} FUNCTIONS = [] JSREGEXES = {} WORDLIMITLEFT = r"(?<![\w.,–-])" # r"(?<![-.,—])\b" seems slower WORDLIMITRIGHT = r"(?![\w–-])" # r"\b(?!-—)" seems slower def pre...
onvert Python code to JavaScript code" # Python 2.x
unicode strings sCode = re.sub('\\b[ur]"', '"', sCode) sCode = re.sub("\\b[ur]'", "'", sCode) # operators sCode = sCode.replace(" and ", " && ") sCode = sCode.replace(" or ", " || ") sCode = re.sub("\\bnot\\b", "!", sCode) sCode = re.sub("(.+) if (.+) else (.+)", "\\2 ? \\1 : \\3", sCode) ...
ivankoster/SublimeYouCompleteMe
plugin/settings.py
Python
gpl-3.0
1,137
0.004398
# Copyright (C) 2014 Ivan Koster # # This file is part of SublimeYouCompleteMe. # # SublimeYouCompleteMe 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 ...
per to handle settings for SublimeYouCompleteMe and the YCMD server in the sublime text settings files """ import sublime SETTINGS = sublime.load_settings('SublimeYouCompleteMe.su
blime-settings') # TODO load ycmd defaults into sublime text settings file (not the user settings file!) # TODO when starting the ycmd server, use the sublime text usersettings
jaesivsm/pyAggr3g470r
jarr/controllers/feed_builder.py
Python
agpl-3.0
9,247
0
import html import logging import re import urllib from feedparser import FeedParserDict from feedparser import parse as fp_parse from requests.exceptions import ReadTimeout from jarr.lib.const import FEED_MIMETYPES, GOOGLE_BOT_UA, REQUIRED_JSON_FEED from jarr.lib.enums import FeedType from jarr.lib.html_parsing impo...
@staticmethod def _handle_known_malfunctionning_link(feed): # reddit's subs don't automatically provide rss feed reddit_match = REDDIT_FEED.match(feed['link']) if reddit_match and not reddit_match.group(3): feed['link'] = REDDIT_FEED_PATTERN % reddit_ma
tch.group(2) feed['feed_type'] = FeedType.reddit return feed youtube_match = YOUTUBE_CHANNEL_RE.match(feed['link']) if youtube_match: feed['site_link'] = feed['link'] feed['link'] = YOUTUBE_FEED_PATTERN % youtube_match.group(4) return feed @st...
UCHIC/h2outility
src/GAMUTRawData/odmdata/variable.py
Python
bsd-3-clause
1,443
0.025641
from sqlalchemy import String, Column, Float, Integer, Boolean, ForeignKey from sqlalchemy.orm import relationship from base import Base from unit import Unit class Variable(Base): __tablename__ = 'Variables' id = Column('VariableID', Integer, primary_key=True) code = Column('VariableCode', String, n...
ble=False) value_type = Column('ValueType', String, nullable=False) is_regular = Column('IsRegular', Boolean, nullable=False) time_support = Column('TimeSupport', Float, nullable=False) time_unit_id = Column('TimeUnitsID', Integer, ForeignKey('Units.UnitsID'), nullable=False) data_type = Column('DataT...
= Column('NoDataValue', Float, nullable=False) # relationships variable_unit = relationship(Unit, primaryjoin=("Unit.id==Variable.variable_unit_id")) # <-- Uses class attribute names, not table column names time_unit = relationship(Unit, primaryjoin=("Unit.id==Variable.time_unit_id")) def __repr__(self): ...
andrewpx1/apiai-weather-webhook-sample-master
lovepx.py
Python
apache-2.0
1,716
0.011682
#!/usr/bin/env python from __future__ import print_function from future.standard_library import install_aliases install_aliases() from urllib.parse import urlparse, urlencode from urllib.request import urlopen, Request from urllib.error import HTTPError from os.path import splitext
import json import os import requests from flask import Flask from flask import request from flask import make_response # Flask app should start in global layout app = Flask(__name__) def processRequest(req): result = req.get("result") parameters = result.get("parameters") prt = parame...
name': yurt} put1 = urlencode(mydict1) put2 = urlencode(mydict2) url = baseurl + put1 + '&' + put2 headers = { "X-Mashape-Key": "axWE0J6Hj5mshIyeWhO19vjpSYyxp1k53ohjsnr3rxp4xsIj8I", 'Accept': 'application/json' } r = requests.get(url, headers=headers) gh = r.content p...
oVirt/vdsm
lib/vdsm/storage/sdm/api/reduce_domain.py
Python
gpl-2.0
2,333
0
# # Copyright 2016 Red Hat, Inc. # # 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 distributed in th...
hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program if not, write to t...
iles for full details of the license # from __future__ import absolute_import from vdsm.common import properties from vdsm.storage import exception as se from vdsm.storage.constants import STORAGE from vdsm.storage import resourceManager as rm from vdsm.storage.sdc import sdCache from . import base class Job(base....
ktan2020/legacy-automation
win/Lib/site-packages/wx-3.0-msw/wx/lib/eventwatcher.py
Python
mit
16,311
0.007602
#---------------------------------------------------------------------------- # Name: wx.lib.eventwatcher # Purpose: A widget that allows some or all events for a par
ticular widget # to be captured and displayed. # # Author: Robin Dunn # #
Created: 21-Jan-2009 # RCS-ID: $Id: $ # Copyright: (c) 2009 by Total Control Software # Licence: wxWindows license #---------------------------------------------------------------------------- """ A widget and supporting classes for watching the events sent to some other widget. """ import wx...
sserrot/champion_relationships
venv/Lib/site-packages/win32/test/test_security.py
Python
mit
5,205
0.013449
# Tests for the win32security module. import sys, os import unittest import winerror from pywin32_testutil import testmain, TestSkipped, ob2memory import win32api, win32con, win32security, ntsecuritycon class SecurityTests(unittest.TestCase): def setUp(self): self.pwr_sid=win32security.LookupAccountName('...
itycon.DS_FQDN_1779_NAME name = win32api.GetUserNameEx(fmt_offered) result = win32security.DsCrackNames(h, 0, fmt_offered, fmt_offered, (name,)) self.failUnlessEqual(name, result[0][2]) def testDsCrackNamesSyntax(self): # Do a syntax check only - that allows us to avoid binding. ...
ONICAL_NAME (or _EX) expected = win32api.GetUserNameEx(win32api.NameCanonical) fmt_offered = ntsecuritycon.DS_FQDN_1779_NAME name = win32api.GetUserNameEx(fmt_offered) result = win32security.DsCrackNames(None, ntsecuritycon.DS_NAME_FLAG_SYNTACTICAL_ONLY, ...
andyraib/data-storage
python_scripts/env/lib/python3.6/site-packages/pandas/tests/test_panel4d.py
Python
apache-2.0
35,347
0.000057
# -*- coding: utf-8 -*- from datetime import datetime from pandas.compat import range, lrange import operator import nose import numpy as np from pandas.types.common import is_float_dtype from pandas import Series, Index, isnull, notnull from pandas.core.panel import Panel from pandas.core.panel4d import Panel4D from...
self._check_stat_op('max', np.max)
def test_skew(self): try: from scipy.stats import skew except ImportError: raise nose.SkipTest("no scipy.stats.skew") def this_skew(x): if len(x) < 3: return np.nan return skew(x, bias=False) self._check_stat_op('skew', th...
nijel/weblate
weblate/accounts/migrations/0016_alter_auditlog_activity.py
Python
gpl-3.0
1,470
0
# Generated by Django 3.2.4 on 2021-06-03 07:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("accounts", "0015_auto_20210512_1955"), ] operations = [ migrations.AlterField( model_name="auditlog", name="activity...
choices=[ ("auth-connect", "auth-connect"), ("auth-disconnect", "auth-disconnect"), ("autocreated", "autocreated"), ("blocked", "blocked"), ("connect", "connect"), ("email", "email"), ...
ll_name", "full_name"), ("invited", "invited"), ("locked", "locked"), ("login", "login"), ("login-new", "login-new"), ("password", "password"), ("register", "register"), ("removed"...
adaussy/eclipse-monkey-revival
plugins/python/org.eclipse.eclipsemonkey.lang.python/Lib/test/test_cmd_line_script.py
Python
epl-1.0
9,548
0.00199
# Tests command line execution of scripts import unittest import os import os.path import test.test_support from test.script_helper import (run_python, temp_dir, make_script, compile_script, make_pkg, make_zip_script, make_zip_pkg) from test.test_support ...
,) exit_code, data = run_python(*run_args) if verbose: print 'Output from test script %r:' % script_name pr
int data self.assertEqual(exit_code, 0) printed_file = '__file__==%r' % expected_file printed_argv0 = 'sys.argv[0]==%r' % expected_argv0 printed_package = '__package__==%r' % expected_package if verbose: print 'Expected output:' print printed_file ...
qvazzler/Flexget
flexget/plugins/urlrewrite/iptorrents.py
Python
mit
6,258
0.003356
from __future__ import unicode_literals, division, absolute_import from builtins import * # pylint: disable=unused-import, redefined-builtin from future.moves.urllib.parse import quote_plus import re import logging from flexget import plugin from flexget.config_schema import one_or_more from flexget.entry import Ent...
m': list(CATEGORIES)}, ]}), }, 'required': ['rss_key', 'uid', 'password'], 'additionalProperties': False
} # urlrewriter API def url_rewritable(self, task, entry): url = entry['url'] if url.startswith(BASE_URL + '/download.php/'): return False if url.startswith(BASE_URL + '/'): return True return False # urlrewriter API def url_rewrite(self, task,...
sunj1/my_pyforms
tutorials/1.SimpleExamples/SimpleExample5/SimpleExample5.py
Python
mit
1,700
0.048235
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = "Ricardo Ribeiro" __credits__ = ["Ricardo Ribeiro"] __license__ = "MIT" __version__ = "0.0" __maintainer__ = "Ricardo Ribeiro" __email__ = "[email protected]" __status__
= "Development" from __init__ import * class SimpleExample5(BaseWidget): def __init__(self): super(SimpleExample5,self).__init__('Simple example 5') #Definit
ion of the forms fields self._firstname = ControlText('First name', 'Default value') self._middlename = ControlText('Middle name') self._lastname = ControlText('Lastname name') self._fullname = ControlText('Full name') self._button = ControlButton('Press this button') self._formset = [ { '...
Akuukis/MMO_sim
ships.py
Python
gpl-3.0
599
0.006678
def main(tick, config, q): return # Drafted, TODO
pc = { 'id': 1, 'coords': [0, 0, 0] } ship = { 'coords': [0, 0, 0], 'type': 'freight' or 'settler' or 'corvette' or 'frigate', # Corvette small tank, Frigate big tank, guns similar 'storage': { 'goods': { }, 'solids': 0, # Upkeep ...
t } } pass if __name__ == "__main__": main()
ButterFlyDevs/StudentsManagementSystem
SMS-Back-End/tdbms/appengine_config.py
Python
gpl-3.0
166
0.012121
# -*- coding: utf-8 -*- from google.appengine.ext import vendor #Para que entienda que las librerías de terceros debe buscarlas
en la carpeta lib vendor.a
dd('lib')
dit/dit
dit/shannon/__init__.py
Python
bsd-3-clause
211
0
""" The basic
forms of Shannon's information measures. """ from .shannon import (entropy,
conditional_entropy, mutual_information, entropy_pmf)
jobsafran/mediadrop
mediadrop/model/settings.py
Python
gpl-3.0
4,208
0.002376
# This file is a part of MediaDrop (http://www.mediadrop.net), # Copyright 2009-2015 MediaDrop contributors # For the exact contribution history, see the git revision log. # The source code contained in this file is licensed under the GPLv3 or # (at your option) any later version. # See LICENSE.txt in the main project ...
" inserte
d = [] try: settings_query = DBSession.query(Setting.key)\ .filter(Setting.key.in_([key for key, value in defaults])) existing_settings = set(x[0] for x in settings_query) except ProgrammingError: # If we are running paster setup-app on a fresh database with a # plugi...
RNAer/micronota
micronota/util.py
Python
bsd-3-clause
9,506
0.000316
r''' Utility functionality ===================== .. currentmodule:: micronota.util This module (:mod:`micronota.util`) provides various utility functionality, ''' # ---------------------------------------------------------------------------- # Copyright (c) 2015--, micronota development team. # # Distributed under t...
------------------- from unittest import TestCase from sqlite3 import connect from logging import getLogger from skbio import read, write, Sequence, DNA logger = getLogger(__name__) def convert(in_f, in_fmt, out_f, out_fmt): '''convert between file formats Parameters ---------- in_fmt : str ...
ile format in_f : str input file path out_f: str output file path ''' for obj in read(in_f, format=in_fmt): write(obj, format=out_fmt, into=out_f) def _filter_sequence_ids(in_fp, out_fp, ids, negate=False): '''Filter away the seq with specified IDs.''' with open(out_fp,...
plotly/python-api
packages/python/plotly/plotly/validators/layout/scene/zaxis/title/_text.py
Python
mit
463
0.00216
import _plotly_utils.basevalidators class TextValidator(_plotly_utils.basevalidators.S
tringValidator): def __init__( self, plotly_name="text", parent_name="layout.scene.zaxis.title", **kwargs ): super(Tex
tValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), role=kwargs.pop("role", "info"), **kwargs )
nburn42/tensorflow
tensorflow/python/kernel_tests/spacetodepth_op_test.py
Python
apache-2.0
13,957
0.007881
# Copyright 2015 The TensorFlow Authors. 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 applica...
x_np = [[[[1], [2]], [[3], [4]]]] block_size = 2 x_out = [[[[1, 2, 3, 4]]]] self._testOne(x_np, block_size, x_out) def testBasicFloat16(self): x_np
= [[[[1], [2]], [[3], [4]]]] block_size = 2 x_out = [[[[1, 2, 3, 4]]]] self._testOne(x_np, block_size, x_out, dtype=dtypes.float16) # Tests for larger input dimensions. To make sure elements are # correctly ordered spatially. def testLargerInput2x2(self): x_np = [[[[1], [2], [5], [6]], [[3], [4],...
ygol/odoo
addons/stock/models/product_strategy.py
Python
agpl-3.0
4,217
0.003083
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import _, api, fields, models from odoo.exceptions import UserError class RemovalStrategy(models.Model): _name = 'product.removal' _description = 'Removal Strategy' name = fields.Char('Name', req...
aise UserError(_("Changing the company of this record is forbidden at
this point, you should rather archive it and create a new one.")) return super(StockPutawayRule, self).write(vals)
timm/timmnix
pypy3-v5.5.0-linux64/lib-python/3/email/encoders.py
Python
mit
2,185
0.001831
# Copyright (C) 2001-2006 Python Software Foundation # Author: Barry Warsaw # Contact: [email protected] """Encodings and related functions.""" __all__ = [ 'encode_7or8bit', 'encode_base64', 'encode_noop', 'encode_quopri', ] from base64 import encodebytes as _bencode from quopri import encode...
st be 7bit, otherwise treat it as 8bit. try: if isinstance(orig, str): orig.encode('ascii') else: orig.decode('ascii') except UnicodeError: charset = msg.get_charset() output_cset = charset and chars
et.output_charset # iso-2022-* is non-ASCII but encodes to a 7-bit representation if output_cset and output_cset.lower().startswith('iso-2022-'): msg['Content-Transfer-Encoding'] = '7bit' else: msg['Content-Transfer-Encoding'] = '8bit' else: msg['Content-Trans...
skymyyang/YouDaoWord
MysqlHelper.py
Python
gpl-2.0
913
0.040794
#encoding=utf-8 import pymysql import json class MysqlHelper: """mysql 帮助类""" @staticmethod def insert(word,asymbol,esymbol,explain,cizu,liju,xian
gguancihui,aspoken,espoken): db=pymysql.connect(host="192.168.180.187",user="root",password="123456",db="lytest",charset="utf8") cursor=db.cursor() print(word.encode("utf8")) print("--------------------------------insert into mysql db") cursor.execute("insert into mfg_t_wordtest ...
%s,%s,%s,%s,%s,%s,%s,0,0)",(word,asymbol,esymbol,"{"+json.dumps(explain,ensure_ascii=False,indent=2)+"}",json.dumps(cizu,ensure_ascii=False,indent=2),json.dumps(liju,ensure_ascii=False,indent=2),json.dumps(xiangguancihui,ensure_ascii=False,indent=2),aspoken,espoken)) db.commit() db.close()
Akson/RemoteConsolePlus3
RemoteConsolePlus3/RCP3/DefaultParser.py
Python
lgpl-3.0
2,359
0.009326
#Created by Dmytro Konobrytskyi, 2013 (github.com/Akson) import logging import json import struct import numpy as np def ParseBinaryData(binaryData, binaryDataFormat, dimensions): elementSize = struct.calcsize(binaryDataFormat) elementsNumber = len(binaryData) / elementSize #Single element case if...
ata based on format. String is a default format dataType = message["Info"].get("DataType", "String") if dataType == "String": processedMessage["Data"] = message["Data"] if dataType == "JSON": jsonObj = json.loads(message["Data"]) processedMessage["Data"] = jsonObj.get("_Value", jso...
message["Info"]: logging.warning("Cannot parse binary data, no format data available") return None binaryDataFormat = message["Info"]["BinaryDataFormat"] #We may have multi-dimensional data dimensions = None if "Dimensions" in message["Info"]: ...
jgillis/casadi
test/python/mx.py
Python
lgpl-3.0
61,968
0.049832
# # This file is part of CasADi. # # CasADi -- A symbolic framework for dynamic optimization. # Copyright (C) 2010 by Joel Andersson, Moritz Diehl, K.U.Leuven. All rights reserved. # # CasADi is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Pub...
= MX("x",3,1) p = horzcat([x[0,0],x[1,0],x[2,0]]) z = vertcat([p*i for i in range(8)]) f = MXFunction([x],[ztf(z)]) f.init() L=[1,2,3] f.setInput(L,0) f.evaluate() zt = f.output(0).toArray() zr = array([[L[0]*i,L[1]*i,L[2]*i] for i in range(8)]) checkarray(self,zrf(zr),zt,name) ...
casadiTestCase): def setUp(self): self.pool=FunctionPool() self.pool.append(lambda x: sqrt(x[0]),sqrt,"sqrt") self.pool.append(lambda x: sin(x[0]),sin,"sin") self.pool.append(lambda x: cos(x[0]),cos,"cos") self.pool.append(lambda x: tan(x[0]),tan,"tan") self.pool.append(lambda x: arctan(x[0])...
3DP-Unlimited/3DP-Printrun
printrun/gl/trackball.py
Python
gpl-3.0
2,746
0.004006
#!/usr/bin/env python # This file is part of the Printrun suite. # # Printrun 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. # # Prin...
* (q[2] * q[0] + q[1] * q[3]) m[3] = 0.0 m[4] = 2.0 * (q[0] * q[1] + q[2] * q[3]) m[5] = 1.0 - 2.0 * (q[2] * q[2] + q[0] * q[0]) m[6] = 2.0 * (q[1] * q[2] - q[0] * q[3]) m[7] = 0.0 m[8] = 2.0 * (q[2] * q[0] - q[1] * q[3]) m[9] = 2.0 * (q[1] * q[2] + q[0] * q[3]) m[10
] = 1.0 - 2.0 * (q[1] * q[1] + q[0] * q[0]) m[11] = 0.0 m[12] = 0.0 m[13] = 0.0 m[14] = 0.0 m[15] = 1.0 return m def project_to_sphere(r, x, y): d = math.sqrt(x * x + y * y) if (d < r * 0.70710678118654752440): return math.sqrt(r * r - d * d) else: t = r / 1.414213...
jstraub/bnp
python/testLibhdp.py
Python
mit
163
0.03681
#! /usr/bin/env python import numpy
as np import libhdp as bnp A=np.zeros((4,4), dtype=n
p.uint32) Aa=np.zeros(34) Dir=bnp.Dir(Aa) bnp.HDP_Dir(Dir,10.0,10.0)
acostasg/upload
upload/tests/shared/test_open_file.py
Python
gpl-3.0
642
0.003115
import unittest import upload.injectionContainer as injectionContainer from u
pload.strategy.dummys.injectedContainerDummy import ContainerMock class TestRequestParams(unittest.TestCase): """ Class test for request params class """ def test_open_file_error(self): """ test case secured upload """ injectionContainer.Container.update( Co...
from upload.shared \ import open_file with self.assertRaises(FileNotFoundError): open_file.execute('FailedTest', 'r') if __name__ == '__main__': unittest.main()
scholer/cadnano2.5
cadnano/views/gridview/prexovermanager.py
Python
mit
9,797
0.001633
"""Summary """ from PyQt5.QtWidgets import QGraphicsRectItem from . import gridstyles as styles from .gridextras import PreXoverItemGroup, WEDGE_RECT from . import ( GridNucleicAcidPartItemT, GridVirtualHelixItemT ) _RADIUS = styles.GRID_HELIX_RADIUS class PreXoverManager(QGraphicsRectItem): """Summary ...
n idx: the
base index within the virtual helix per_neighbor_hits: Description pairs: Description """ self.clearPreXoverItemGroups() pxis = self.prexover_item_map neighbor_pxis_dict = self.neighbor_prexover_items # for avoiding duplicates) self.neighbor_pairs = pairs...
OrDuan/cool_commits
cool_commits/api.py
Python
apache-2.0
368
0
from cool_commits.parsers import all_parsers from cool_commits.utils imp
ort git_all_commits def find(path): commits_list = git_all_commits(path) for parser in all_parsers: yield str(parser(commits_list, path)) def info(path): commits_list = git_all_commits(path) for parser in all_parsers:
yield parser(commits_list, path).info()
CtheSky/pycparser
tests/test_c_generator.py
Python
bsd-3-clause
7,444
0.000672
import sys import unittest # Run from the root dir sys.path.insert(0, '.') from pycparser import c_parser, c_generator, c_ast _c_parser = c_parser.CParser( lex_optimize=False, yacc_debug=True, yacc_optimize=False, yacctab='yacctab') def compare_asts(a...
1][1] = { { 1 } }; }''') def test_nest_named_initializer(self): self._assert_ctoc_correct(r'''struct test { int i; struct test_i_t { int k; } test_i; int j; };
struct test test_var = {.i = 0, .test_i = {.k = 1}, .j = 2}; ''') def test_expr_list_in_initializer_list(self): self._assert_ctoc_correct(r''' int main() { int i[1] = { (1, 2) }; }''') def test_issue36(self): self._assert_ctoc_correct(r''' ...
espdev/readthedocs.org
readthedocs/builds/views.py
Python
mit
2,216
0.002256
import logging from django.shortcuts import get_object_or_404 from django.views.generic import ListView, DetailView from django.http import HttpResponsePermanentRedirect from django.conf import settings from django.core.urlresolve
rs import reverse from readthedocs.builds.models import Build, Version from readthedocs.builds.filters import BuildFilter from readthedocs.projects.models import Project from redis import Redis, ConnectionError log = logging.getLogger(__name__)
class BuildBase(object): model = Build def get_queryset(self): self.project_slug = self.kwargs.get('project_slug', None) self.project = get_object_or_404( Project.objects.protected(self.request.user), slug=self.project_slug ) queryset = Build.objects.pub...
mupif/mupif
examples/Example02-distrib/application2.py
Python
lgpl-3.0
3,766
0.002655
import sys import Pyro5 import logging sys.path.extend(['..', '../..']) import mupif as mp log = logging.getLogger() @Pyro5.api.expose class Application2(mp.Model): """ Simple application that computes an arithmetical average of mapped property """ def __init__(self, metadata={}): MD = { ...
nel_cost_EUR': 0.01, 'Required_expertise': 'None', 'Accuracy': 'High', 'Sensitivity': 'High', 'Complexity': 'Low', 'Robustness': 'High' }, 'Inputs': [ {'Type': 'mupif.Property', 'Type_ID': 'mupif.Data...
: True, "Set_at": "timestep", "ValueType": "Scalar"}], 'Outputs': [ {'Type': 'mupif.Property', 'Type_ID': 'mupif.DataID.PID_Time', 'Name': 'Cummulative time', 'Description': 'Cummulative time', 'Units': 's', 'Origin': 'Simulated', "ValueType": "Scalar"}] } su...
aronysidoro/django-livesettings
live/keyedcache/models.py
Python
bsd-3-clause
2,736
0.003289
import keyedcache import logging log = logging.getLogger(__name__) class CachedObjectMixin(object): """Provides basic object keyedcache for any objects using this as a mixin. The class name of the object should be unambiguous. """ def cache_delete(self, *args, **kwargs): key = self.cache_key...
act=key) key
edcache.cache_set(e.key, value=ob) except cls.DoesNotExist: log.debug("No such %s: %s", groupkey, key) if raises: raise return ob def find_by_slug(cls, groupkey, slug, raises=False): """A helper function to look up an object by slug""" ob = None try...
beaker-project/beaker
Client/src/bkr/client/commands/cmd_job_cancel.py
Python
gpl-2.0
2,402
0.003747
# -*- coding: utf-8 -*- # 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. """ bkr job-cancel: Cancel running Beaker jobs...
default=None, help="Optional message to record as to why you cancelled", ) self.parser.usage = "%%prog %s [options] [J:<id> | RS:<id> ...]" % self.normalized_name def run(self, *args, **kwargs): if len(args) < 1: self.parser.error('Please specify a tas...
args, permitted_types=['J', 'RS', 'T']) msg = kwargs.pop("msg", None) self.set_hub(**kwargs) for task in args: self.hub.taskactions.stop(task, 'cancel', msg) print('Cancelled %s' % task)
GeorgiaTechDHLab/TOME
topics/migrations/0012_auto_20170605_1314.py
Python
bsd-3-clause
707
0.001414
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-06-05 13:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('news', '0014_auto_20170605_1314'), ('topics', '0011...
name='corpus', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='new
s.Corpus'), ), ]
demis001/bio_pieces
bio_pieces_old/sequence_concat.py
Python
gpl-2.0
10,368
0.016686
#!/usr/bin/env python ########################################################################## ## Sequence Concat ## Author: Tyghe Vallard ## Release Date: 5/30/2012 ## Version: 1.1 ## Descriptio...
return self._parsed_fasta def get_merged_sequences( self, prune = True, segments_required = [1,2,3,4,5,6,7,8] ): """ Returns a merged fasta formatted file Set prune to false if you don't want to prune out the sequences that don't have the correct amount of segment...
ile__ ) >>> s = SequenceConcat( os.path.join( path, '../example_files/example1.txt' ), 'genbank' ) >>> print s.get_merged_sequences( True, range( 1, 4 ) ) >ident1 AAAAAAAAAAAAAAAAACCCCCCCCCCCCCCCCCTTTTTTTTTTTTTTTTT >ident2 AAAAAAAAAAAAAAAAATTTTTTTT...
DarthMaulware/EquationGroupLeaks
Leak #5 - Lost In Translation/windows/Resources/Dsz/PyScripts/Lib/dsz/mca/file/cmd/strings/type_Params.py
Python
unlicense
3,175
0.00315
# uncompyle6 version 2.9.10 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: type_Params.py from types import * PARAMS_ENCODING_ASCII = 0 PARAMS_ENCODING_UNICODE = 1 PARAMS_MIN_THRESHOLD = 2 class Params: def __init__(se...
pass try: self.__dict__['maximum'] = submsg.FindU32(MSG_KEY_PARAMS_MAXIMUM) except: pass try: self.__dict__['encoding'
] = submsg.FindU8(MSG_KEY_PARAMS_ENCODING) except: pass try: self.__dict__['start'] = submsg.FindU64(MSG_KEY_PARAMS_START) except: pass try: self.__dict__['end'] = submsg.FindU64(MSG_KEY_PARAMS_END) except: pass ...
dsriram/golang
src/pkg/runtime/runtime-gdb.py
Python
bsd-3-clause
11,121
0.029404
# Copyright 2010 The Go Authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. """GDB Pretty printers and convenience functions for Go's runtime structures. This script is loaded by GDB when it finds a .debug_gdb_scripts section in the compi...
n 'string' def to_string(self): if self.val['data'] == 0: return 0x0 try: dtype = iface_dtype(self.val) except: return "<bad dynamic type>" if dtype is None: # trouble looking up, print something reasonable return "(%s)%s" % (iface_dtype_name(self.val), self.val['data']) try: return self.v...
): return IfacePrinter(val) goobjfile.pretty_printers.append(ifacematcher) # # Convenience Functions # class GoLenFunc(gdb.Function): "Length of strings, slices, maps or channels" how = ((StringTypePrinter, 'len'), (SliceTypePrinter, 'len'), (MapTypePrinter, 'count'), (ChanTypePrinter, ...
thnuclub/kandota
spiderserver/crawl/spiderserver/spiders/dotamaxspider.py
Python
apache-2.0
1,374
0.007278
# -*- coding: utf-8 -*- import scrapy from spiderserver.siteparse.parser import parse_dotamax_html from scrapy.http import Request from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from spiderserver.items import DotamaxItem class DotamaxSpider(scrapy....
tem if len(lists) > 0 and self.page < 900: self.page = self.page + 1 base = 'http://dotamax.com/video/users/' for o in ['dota', 'dota2']: href = "%s%s?type=&dm_uid=&p=%s" % (base, o, self.page) yield Request(url=href, cookies={}, callback=self...
.parse_fail) def parse_fail(self, response): pass
jasvir99/LibreHatti
src/librehatti/catalog/lookups.py
Python
gpl-2.0
1,701
0.017637
from django.db.models import Q from django.utils.html import escape from
django.contrib.auth.models import User from ajax_select import LookupChannel class BuyerLookup(LookupChannel): """ This class suggests user names (AJAX Effect) while filling client name for a purchase order """ model = User def get_query(self, q, request): user = User.objects.all() ...
alue) \ | Q(last_name__icontains=value) \ |Q(customer__address__street_address__icontains=value)\ |Q(customer__address__district__icontains=value)\ |Q(customer__address__province__icontains=value) |Q(customer__title__icontains=value) ...
nicolaszein/chat
chat/migrations/0003_userprofile.py
Python
bsd-3-clause
1,161
0.004307
# -*- coding: utf-8 -*- # Generated by Django 1.9.3 on 2016-06-08 11:44 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependen...
Nascimento')), ('sexo', models.IntegerField(choices=[(1, 'Masculino'), (2, 'Feminino')],
verbose_name='Sexo')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='profile_user', to=settings.AUTH_USER_MODEL, verbose_name='Usu\xe1rio')), ], ), ]
lento/cortex
test/IECore/ops/classVectorParameterTest/classVectorParameterTest-2.py
Python
bsd-3-clause
2,288
0.020979
########################################################################## # # Copyright (c) 2010, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modif
ication, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce
the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # * Neither the name of Image Engine Design nor the names of any # other contributors to this software may be used to endorse or # ...
gnperumal/exscript
src/Exscript/util/template.py
Python
gpl-2.0
6,513
0.004299
# Copyright (C) 2007-2010 Samuel Abels. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2, as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANT...
ess. The function raises an exception if the compilation fails, or if the template contains a command that requires a response from the host. @type conn: Exscript.protocols.Protocol @param conn: The connection on which to run the template. @type string: string @param string: The template...
execution of the script. """ return _run(conn, None, string, {'no_prompt': True}, **kwargs) def paste_file(conn, filename, **kwargs): """ Convenience wrapper around paste() that reads the template from a file instead. @type conn: Exscript.protocols.Protocol @param conn: The connection on ...
Alwnikrotikz/epubia
naver_autospacing.py
Python
mit
1,159
0.012942
maxline = 10000 # from web-page qurl = 'http://s.lab.naver.com/autospacing/?' qvalues = { "query": "", "result_type": "paragraph" } qheaders = {"Referer": qurl, "User-Agent": "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)" } import urllib, urllib2 import re de...
values['query'] = txt.encode('utf-8').replace('\n','\r\n') data = urllib.urlencode(qvalues) req = urllib2.Request(qurl, data, qheaders) r = urllib2.urlopen(req) doc = r.read().decode('utf-8') markup = re.compile('<div class="wrap_spacing2" style="clear:both;">(.*?)</div>', re.S).search(doc).group(1)...
naver_autospacing(txt): # warning if #line > maxline return _naver_autospacing(txt) #################################################3 # main if __name__ == "__main__": import sys txt = open(sys.argv[1], 'r').read()[3:].decode('utf-8') txt2 = naver_autospacing(txt) open(sys.argv[2], 'w').write...
hdzierz/Kaka
web/http_data_download_response.py
Python
gpl-2.0
1,477
0.004062
from django.http import QueryDict, HttpResponse, HttpResponseRedirect import gzip class HttpDataDownloadResponse(HttpResponse): fmt = 'csv' gzipped
= True data = None def __init__(self, data, report, fmt='csv', zipit=True): if data: c_type, download = self.get_mime_type(fmt) fn = report + "." + fmt if(zipit): with gzip.open('/tmp/' + fn + '.gz', 'wb') as f: f.write(data) ...
e_type('gzip') with gzip.open('/tmp/' + fn + '.gz', 'wb') as f: data = f.read(fn) super(HttpDataDownloadResponse, self).__init__(data, content_type=c_type) if download: self['Content-Disposition'] = 'attachment; filename="' + fn + '"' ...
factorlibre/carrier-delivery
delivery_carrier_tnt/model/__init__.py
Python
agpl-3.0
95
0
from . import tnt_config fro
m . im
port delivery from . import stock from . import carrier_file
moyogo/vanilla
Lib/vanilla/__init__.py
Python
mit
2,699
0.001853
from vanilla.vanillaBase import VanillaBaseObject, VanillaBaseControl, VanillaError from vanilla.vanillaBox import Box, HorizontalLine, VerticalLine from vanilla.vanillaBrowser import ObjectBrowser from vanilla.vanillaButton import Button, SquareButton, ImageButton, HelpButton from vanilla.vanillaCheckBox import CheckB...
aScrollView import ScrollView from vanilla.vanillaSearchBox import SearchBox from vanilla.vanillaSegmentedButton import Segme
ntedButton from vanilla.vanillaSlider import Slider from vanilla.vanillaSplitView import SplitView, SplitView2 from vanilla.vanillaTabs import Tabs from vanilla.vanillaTextBox import TextBox from vanilla.vanillaTextEditor import TextEditor from vanilla.vanillaWindows import Window, FloatingWindow, HUDFloatingWindow, Sh...
owtf/owtf
owtf/plugins/web/grep/[email protected]
Python
bsd-3-clause
1,830
0.005464
""" GREP Plugin for Credentials transport over an encrypted channel (OWASP-AT-001) https://www.owasp.org/index.php/Testing_for_credentials_transport_%28OWASP-AT-001%29 NOTE: GREP plugins do NOT send traffic to the target and only grep the HTTP Transaction Log """ import logging DESCRIPTION = "Searches transaction DB f...
ing # Content = "This plugin looks for password fields and then checks the URL (i.e. http vs. https)<br />" # Conten
t += "Uniqueness in this case is performed via URL + password field" # # This retrieves all hidden password fields found in the DB response bodies: # Command, RegexpName, Matches = ServiceLocator.get_component("transaction").GrepMultiLineResponseRegexp(ServiceLocator.get_component("config").Get('RESPONSE_REGEXP...
jhurt/dribbble-palettes
dribbble_palettes/__init__.py
Python
bsd-2-clause
21
0
_
_author__ = 'jh
urt'
phlax/translate
translate/lang/data.py
Python
gpl-2.0
21,385
0.000936
# -*- coding: utf-8 -*- # # Copyright 2007-2011 Zuza Software Foundation # # This file is part of translate. # # translate 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 # ...
("Interlingua (International Auxiliary Language Association)", 2, '(n != 1)'), 'id': ('Indonesian', 1, '0'), 'is': ('Icelandic', 2, '(n != 1)'), 'it': ('Italian', 2, '
(n != 1)'), 'ja': ('Japanese', 1, '0'), 'jbo': ('Lojban', 1, '0'), 'jv': ('Javanese', 2, '(n != 1)'), 'ka': ('Georgian', 1, '0'), 'kab': ('Kabyle', 2, '(n != 1)'), 'kk': ('Kazakh', 2, 'n != 1'), 'kl': ('Greenlandic', 2, '(n != 1)'), 'km': ('Central Khmer', 1, '0'), 'kn': ('Kannada', ...
mpurg/qtools
qscripts-cli/q_setprot.py
Python
mit
3,879
0.004383
#!/usr/bin/env python # -*- coding: utf-8 -*- # # MIT License # # Copyright (c) 2018 Miha Purg <mi
ha.p
[email protected]> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, ...
tarthy6/dozer-thesis
scripts/watch-mem-usage.py
Python
gpl-2.0
965
0.041451
# collect data about max memory usage of processes matching some patterns import psutil, re, operator, time, sys sampleTime=.5 # seconds # matching lines will be taken in account #cmdPattern='.*cc1plus.*src/([a-zA-Z0-9_-]\.cpp).*' cmdPattern=r'.*cc1plus.* (\S+/)?([^/ ]+\.cpp).*' # group in the pattern which identifies...
axMem={} while True: try: for p in psutil.process_iter(): m=re.match(cmdPattern,' '.join(p.cmdline)) if not m: continue key=m.group(cmdKeyGroup) mem=p.get_memory_info()[1] # tuple of RSS (resident set size) and VMS (virtual memory size) if key not in maxMem: print 'New process with key',key m...
or k,v in sorted(maxMem.iteritems(),key=operator.itemgetter(1)): print '{:>10.1f} {}'.format(1e-6*v,k) sys.exit(0)
jrmendozat/mtvm
Vehiculo/models.py
Python
gpl-2.0
2,597
0.00154
from django.db import models # Create your models here. class Tipo_Vehiculo(models.Model): """docstring for Tipo_Vehiculo""" def __init__(self, *args, **kwargs): super(Tipo_Vehiculo, self).__init__(*args, **kwargs) tipo_vehiculo = models.CharField(max_length=100, unique=True) adicional1 = mode...
.CharField(max_length=10) #mantenimiento_vehiculo = models.ForeignKey() vehiculo = models.CharField(max_length=100) patente = models.CharField(max_length=100) tipo_vehiculo = models.ForeignKey(Tipo_Vehiculo)
modelo_vehiculo = models.ForeignKey(Modelo_Vehiculo) adicional1 = models.CharField(max_length=250, blank=True) adicional2 = models.CharField(max_length=250, blank=True) adicional3 = models.CharField(max_length=250, blank=True) adicional4 = models.CharField(max_length=250, blank=True) activo = mod...
DedMemez/ODS-August-2017
dna/DNAFlatDoor.py
Python
apache-2.0
561
0.005348
# Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.dna.DNAFlatDoor from panda3d.core import DecalEffect import DNADoor class DNAFlatDoor(DNADoor.DNADoor): COMPONENT_CODE = 17 def traverse(self, nodePath, dnaStorage): node = assetStorage.findNode(self.code, self.getName()) ...
, 1, 1) node.setPosHpr((0.5, 0
, 0), (0, 0, 0)) node.setColor(self.color) node.getNode(0).setEffect(DecalEffect.make()) node.flattenStrong()
moehuster/python
SimpleGUICS2Pygame/script/SimpleGUICS2Pygame_check.py
Python
gpl-2.0
3,377
0
#!/usr/bin/env python # -*- coding: latin-1 -*- """ script/SimpleGUICS2Pygame_check.py (December 15, 2013) Piece of SimpleGUICS2Pygame. https://bitbucket.org/OPiMedia/simpleguics2pygame GPLv3 --- Copyright (C) 2013 Olivier Pirson http://www.opimedia.be/ """ from __future__ import print_function from sys import ve...
md, 'ok') except Exception as e: print(cmd, 'FAILED!', e) try: cmd = 'import SimpleGUICS2Pygame.simplegui_lib_draw' import SimpleGUICS2Pygame.simplegui_lib_draw print(cmd, 'ok') except Exception as e: print(cmd, 'FAILED!', e) try: cmd = 'import SimpleG...
Exception as e: print(cmd, 'FAILED!', e) try: cmd = 'import SimpleGUICS2Pygame.simplegui_lib_keys' import SimpleGUICS2Pygame.simplegui_lib_keys print(cmd, 'ok') except Exception as e: print(cmd, 'FAILED!', e) try: cmd = 'import SimpleGUICS2Pygame.simplegui...