function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def test_invoice_line_data_prepares_invoice_line(self):
""" It should prepare invoice line based on sale line """
qty = 20
with mock.patch.object(self.unit, 'binder_for'):
line_id = self.unit.binder_for().to_odoo().sale_line_id
line_id.product_uom_qty = qty
self.unit.invoice_line_data(self.record)
line_id._prepare_invoice_line.assert_called_once_with(qty) | laslabs/odoo-connector-carepoint | [
1,
1,
1,
2,
1449883667
] |
def setUp(self):
super(TestAccountInvoiceLineImporter, self).setUp()
self.Unit = account_invoice_line.AccountInvoiceLineImporter
self.unit = self.Unit(self.mock_env)
self.unit.carepoint_record = self.record | laslabs/odoo-connector-carepoint | [
1,
1,
1,
2,
1449883667
] |
def test_after_import_get_binder_procurement(self):
""" It should get binder for record type """
with mock.patch.object(self.unit, 'binder_for'):
self.unit.binder_for.side_effect = EndTestException
with self.assertRaises(EndTestException):
self.unit._after_import(self.record)
self.unit.binder_for.assert_called_once_with(
'carepoint.procurement.order'
) | laslabs/odoo-connector-carepoint | [
1,
1,
1,
2,
1449883667
] |
def test_after_import_get_binder_sale(self):
""" It should get binder for record type """
with mock.patch.object(self.unit, 'binder_for'):
self.unit.binder_for.side_effect = [mock.MagicMock(),
EndTestException]
with self.assertRaises(EndTestException):
self.unit._after_import(self.record)
self.unit.binder_for.assert_called_with(
'carepoint.sale.order'
) | laslabs/odoo-connector-carepoint | [
1,
1,
1,
2,
1449883667
] |
def test_after_import_gets_proc_unit(self):
""" It should get unit for model """
with mock.patch.multiple(
self.unit, binder_for=mock.DEFAULT, unit_for=mock.DEFAULT
):
self.unit.unit_for.side_effect = EndTestException
with self.assertRaises(EndTestException):
self.unit._after_import(self.record)
self.unit.unit_for.assert_called_with(
account_invoice_line.ProcurementOrderUnit,
model='carepoint.procurement.order',
) | laslabs/odoo-connector-carepoint | [
1,
1,
1,
2,
1449883667
] |
def test_after_import_gets_ref_for_cp_state(self):
""" It should get reference for carepoint state record """
with mock.patch.multiple(
self.unit, binder_for=mock.DEFAULT, unit_for=mock.DEFAULT,
session=mock.DEFAULT, _get_binding=mock.DEFAULT,
):
invoice_id = self.unit._get_binding().invoice_id
self.unit.unit_for()._get_order_line_count.return_value = 1
invoice_id.invoice_line_ids = [True]
self.unit.env.ref.side_effect = EndTestException
with self.assertRaises(EndTestException):
self.unit._after_import(self.record)
self.unit.env.ref.assert_called_with(
'connector_carepoint.state_%d' % (
self.unit.binder_for().to_odoo().sale_line_id.
order_id.carepoint_order_state_cn
)
) | laslabs/odoo-connector-carepoint | [
1,
1,
1,
2,
1449883667
] |
def test_after_import_invoice_create_moves(self):
""" It should create accounting moves for newly paid invoices """
with mock.patch.multiple(
self.unit, binder_for=mock.DEFAULT, unit_for=mock.DEFAULT,
session=mock.DEFAULT, _get_binding=mock.DEFAULT,
):
invoice_id = self.unit._get_binding().invoice_id
self.unit.unit_for()._get_order_line_count.return_value = 1
invoice_id.invoice_line_ids = [True]
self.unit.env.ref().invoice_state = 'paid'
invoice_id.action_move_create.side_effect = EndTestException
with self.assertRaises(EndTestException):
self.unit._after_import(self.record) | laslabs/odoo-connector-carepoint | [
1,
1,
1,
2,
1449883667
] |
def index(request):
"""The main page."""
form = forms.MapSearchForm(request.GET)
job_list = (models.MapRenderingJob.objects.all()
.order_by('-submission_time'))
job_list = (job_list.filter(status=0) |
job_list.filter(status=1))
return render(request,
'maposmatic/index.html',
{ 'form': form,
'queued': job_list.count()
}
) | hholzgra/maposmatic | [
55,
13,
55,
51,
1452704745
] |
def privacy(request):
"""The privacy statement page."""
return render(request,
'maposmatic/privacy.html',
{ }
) | hholzgra/maposmatic | [
55,
13,
55,
51,
1452704745
] |
def documentation_api(request):
"""The api documentation."""
return render(request,
'maposmatic/documentation-api.html',
{ }
) | hholzgra/maposmatic | [
55,
13,
55,
51,
1452704745
] |
def donate_thanks(request):
"""The thanks for donation page."""
return render_to_response('maposmatic/donate-thanks.html') | hholzgra/maposmatic | [
55,
13,
55,
51,
1452704745
] |
def new(request):
"""The map creation page and form."""
papersize_buttons = ''
if request.method == 'POST':
form = forms.MapRenderingJobForm(request.POST, request.FILES)
if form.is_valid():
request.session['new_layout'] = form.cleaned_data.get('layout')
request.session['new_stylesheet'] = form.cleaned_data.get('stylesheet')
request.session['new_overlay'] = form.cleaned_data.get('overlay')
request.session['new_paper_width_mm'] = form.cleaned_data.get('paper_width_mm')
request.session['new_paper_height_mm'] = form.cleaned_data.get('paper_height_mm')
job = form.save(commit=False)
job.administrative_osmid = form.cleaned_data.get('administrative_osmid')
job.stylesheet = form.cleaned_data.get('stylesheet')
job.overlay = ",".join(form.cleaned_data.get('overlay'))
job.layout = form.cleaned_data.get('layout')
job.paper_width_mm = form.cleaned_data.get('paper_width_mm')
job.paper_height_mm = form.cleaned_data.get('paper_height_mm')
job.status = 0 # Submitted
if www.settings.SUBMITTER_IP_LIFETIME != 0:
job.submitterip = request.META['REMOTE_ADDR']
else:
job.submitterip = None
job.submitteremail = form.cleaned_data.get('submitteremail')
job.map_language = form.cleaned_data.get('map_language')
job.index_queue_at_submission = (models.MapRenderingJob.objects
.queue_size())
job.nonce = helpers.generate_nonce(models.MapRenderingJob.NONCE_SIZE)
job.save()
files = request.FILES.getlist('uploadfile')
for file in files:
create_upload_file(job, file)
return HttpResponseRedirect(reverse('map-by-id-and-nonce',
args=[job.id, job.nonce]))
else:
LOG.debug("FORM NOT VALID")
else:
init_vals = request.GET.dict()
oc = ocitysmap.OCitySMap(www.settings.OCITYSMAP_CFG_PATH)
if not 'layout' in init_vals and 'new_layout' in request.session :
init_vals['layout'] = request.session['new_layout']
else:
request.session['new_layout'] = oc.get_all_renderer_names()[0]
if not 'stylesheet' in init_vals and 'new_stylesheet' in request.session:
init_vals['stylesheet'] = request.session['new_stylesheet']
else:
request.session['new_stylesheet'] = oc.get_all_style_names()[0]
if not 'overlay' in init_vals and 'new_overlay' in request.session:
init_vals['overlay'] = request.session['new_overlay']
if not 'paper_width_mm' in init_vals and 'new_paper_width_mm' in request.session:
init_vals['paper_width_mm'] = request.session['new_paper_width_mm']
if not 'paper_height_mm' in init_vals and 'new_paper_width_mm' in request.session:
init_vals['paper_height_mm'] = request.session['new_paper_height_mm']
form = forms.MapRenderingJobForm(initial=init_vals)
_ocitysmap = ocitysmap.OCitySMap(www.settings.OCITYSMAP_CFG_PATH)
# TODO: create tempates for these button lines ...
papersize_buttons += "<p><button id='paper_best_fit' type='button' class='btn btn-primary papersize papersize_best_fit' onclick='set_papersize(0,0);'><i class='fas fa-square fa-2x'></i></button> <b>Best fit</b> (<span id='best_width'>?</span>×<span id='best_height'>?</span>mm²)</p>"
for p in _ocitysmap.get_all_paper_sizes():
if p[1] is not None:
papersize_buttons += "<p>"
if p[1] != p[2]:
papersize_buttons += "<button id='paper_{0}_{1}' type='button' class='btn btn-primary papersize papersize_{0}_{1}' onclick='set_papersize({0}, {1});'><i class='fas fa-portrait fa-2x'></i></button> ".format(p[1], p[2])
papersize_buttons += "<button id='paper_{0}_{1}' type='button' class='btn btn-primary papersize papersize_{0}_{1}' onclick='set_papersize({0}, {1});'><i class='fas fa-image fa-2x'></i></button> ".format(p[2], p[1])
else:
papersize_buttons += "<button id='paper_{0}_{1}' disabled type='button' class='btn btn-primary papersize papersize_{0}_{1}' onclick='set_papersize({0}, {1});'><i class='fas fa-square fa-2x'></i></button> ".format(p[1], p[2])
papersize_buttons += "<b>%s</b> (%s×%smm²)</p>" % (p[0], repr(p[1]), repr(p[2]))
multisize_buttons = ''
for p in _ocitysmap.get_all_paper_sizes('multipage'):
if p[1] is not None:
multisize_buttons += "<p>"
if p[1] != p[2]:
multisize_buttons += "<button id='multipaper_{0}_{1}' type='button' class='btn btn-primary papersize papersize_{0}_{1}' onclick='set_papersize({0}, {1});'><i class='fas fa-portrait fa-2x'></i></button> ".format(p[1], p[2])
multisize_buttons += "<button id='multipaper_{0}_{1}' type='button' class='btn btn-primary papersize papersize_{0}_{1}' onclick='set_papersize({0}, {1});'><i class='fas fa-image fa-2x'></i></button> ".format(p[2], p[1])
else:
multisize_buttons += "<button id='multipaper_{0}_{1}' disabled type='button' class='btn btn-primary papersize papersize_{0}_{1}' onclick='set_papersize({0}, {1});'><i class='fas fa-square fa-2x'></i></button> ".format(p[1], p[2])
multisize_buttons += "<b>%s</b> (%s×%smm²)</p>" % (p[0], repr(p[1]), repr(p[2]))
return render(request, 'maposmatic/new.html',
{ 'form' : form ,
'papersize_suggestions': mark_safe(papersize_buttons),
'multipage_papersize_suggestions': mark_safe(multisize_buttons),
}) | hholzgra/maposmatic | [
55,
13,
55,
51,
1452704745
] |
def maps(request, category=None):
"""Displays all maps and jobs, sorted by submission time, or maps matching
the search terms when provided."""
map_list = None
form = forms.MapSearchForm(request.GET)
if form.is_valid():
map_list = (models.MapRenderingJob.objects
.order_by('-submission_time')
.filter(maptitle__icontains=form.cleaned_data['query']))
if len(map_list) == 1:
return HttpResponseRedirect(reverse('map-by-id',
args=[map_list[0].id]))
else:
form = forms.MapSearchForm()
if map_list is None:
map_list = (models.MapRenderingJob.objects
.order_by('-submission_time'))
if category == 'errors':
map_list = map_list.filter(status=2).exclude(resultmsg='ok')
paginator = Paginator(map_list, www.settings.ITEMS_PER_PAGE)
try:
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
maps = paginator.page(page)
except (EmptyPage, InvalidPage):
maps = paginator.page(paginator.num_pages)
return render(request, 'maposmatic/maps.html',
{ 'maps': maps, 'form': form,
'is_search': form.is_valid(),
'pages': helpers.get_pages_list(maps, paginator) }) | hholzgra/maposmatic | [
55,
13,
55,
51,
1452704745
] |
def cancel(request):
if request.method == 'POST':
form = forms.MapCancelForm(request.POST)
if form.is_valid():
job = get_object_or_404(models.MapRenderingJob,
id=form.cleaned_data['id'],
nonce=form.cleaned_data['nonce'])
job.cancel()
return HttpResponseRedirect(reverse('map-by-id-and-nonce',
args=[job.id, job.nonce]))
return HttpResponseBadRequest("ERROR: Invalid request") | hholzgra/maposmatic | [
55,
13,
55,
51,
1452704745
] |
def api_nominatim_reverse(request, lat, lon):
"""Nominatim reverse geocoding query gateway."""
lat = float(lat)
lon = float(lon)
return HttpResponse(json.dumps(nominatim.reverse_geo(lat, lon)),
content_type='text/json') | hholzgra/maposmatic | [
55,
13,
55,
51,
1452704745
] |
def api_geosearch(request):
"""Simple place name search."""
exclude = request.GET.get('exclude', '')
squery = request.GET.get('q', '')
squery = squery.lower()
contents = { "entries": [] }
cursor = None
if www.settings.MAX_BOUNDING_BOX:
m = www.settings.MAX_BOUNDING_BOX
max_bbox = "ST_GeomFromText('POLYGON((%f %f, %f %f, %f %f, %f %f, %f %f))', 4326)" % (m[1], m[0], m[1], m[2], m[3], m[2], m[3], m[0], m[1], m[0])
pt_bbox = 'AND ST_Contains(ST_Transform(%s, 3857), pt.way)' % max_bbox
poly_bbox = 'AND ST_Contains(ST_Transform(%s, 3857), poly.way)' % max_bbox
else:
pt_bbox = ''
poly_bbox = ''
query = """SELECT p.name
, p.display_name
, p.class
, p.type
, p.osm_type
, p.osm_id
, p.lat
, p.lon
, p.west
, p.east
, p.north
, p.south
, p.place_rank
, p.importance
, p.country_code
FROM place p
LEFT JOIN planet_osm_hstore_point pt
ON p.osm_id = pt.osm_id
%s -- optionally filter by max bbox
LEFT JOIN planet_osm_hstore_polygon poly
ON - p.osm_id = poly.osm_id
%s -- optionally filter by max bbox
WHERE LOWER(p.name) = %%s
AND ( pt.osm_id IS NOT NULL
OR poly.osm_id IS NOT NULL
)
ORDER BY p.place_rank
, p.importance DESC
""" % (pt_bbox, poly_bbox)
try:
cursor = connections['osm'].cursor()
if cursor is None:
raise Http404("postgis: no cursor")
cursor.execute(query, [ squery ])
columns = [col[0] for col in cursor.description]
for row in cursor.fetchall():
values = dict(zip(columns, row))
values["boundingbox"] = "%f,%f,%f,%f" % (values["south"], values["north"], values["west"], values["east"])
bbox = ocitysmap.coords.BoundingBox(values["south"], values["west"], values["north"], values["east"])
(metric_size_lat, metric_size_lon) = bbox.spheric_sizes()
LOG.warning("metric lat/lon %f : %f - %f" % (metric_size_lat, metric_size_lon, www.settings.BBOX_MAXIMUM_LENGTH_IN_METERS))
if values["osm_type"] == "node":
values["icon"] = "../media/img/place-node.png"
values["ocitysmap_params"] = {
"valid": False,
"reason": "no-admin",
"reason_text": "No administrative boundary"
}
else:
values["icon"] = "../media/img/place-polygon.png"
if (metric_size_lat > www.settings.BBOX_MAXIMUM_LENGTH_IN_METERS
or metric_size_lon > www.settings.BBOX_MAXIMUM_LENGTH_IN_METERS):
valid = False
reason = "area-too-big"
reason_text = ugettext("Administrative area too big for rendering")
else:
valid = True
reason = ""
reason_text = ""
values["ocitysmap_params"] = {
"valid": valid,
"table": "polygon",
"id": -values["osm_id"],
"reason": reason,
"reason_text": reason_text
}
contents["entries"].append(values)
cursor.close()
return HttpResponse(content=json.dumps(contents),
content_type='text/json')
except Exception as e:
raise TransactionManagementError(e) | hholzgra/maposmatic | [
55,
13,
55,
51,
1452704745
] |
def api_bbox(request, osm_id):
"""API handler that returns the bounding box from an OSM ID polygon."""
try:
osm_id = int(osm_id)
except ValueError:
return HttpResponseBadRequest("ERROR: Invalid arguments")
renderer = ocitysmap.OCitySMap(www.settings.OCITYSMAP_CFG_PATH)
try:
bbox_wkt, area_wkt = renderer.get_geographic_info(osm_id)
bbox = ocitysmap.coords.BoundingBox.parse_wkt(bbox_wkt)
return HttpResponse(content=json.dumps(bbox.as_json_bounds()),
content_type='text/json')
except:
LOG.exception("Error calculating bounding box for OSM ID %d!" % osm_id)
return HttpResponseBadRequest("ERROR: OSM ID %d not found!" % osm_id) | hholzgra/maposmatic | [
55,
13,
55,
51,
1452704745
] |
def do_work(file,mintime,wayness,lariat_dict):
retval=(None,None,None,None,None)
res=plot.get_data(file,mintime,wayness,lariat_dict) | ubccr/tacc_stats | [
1,
2,
1,
1,
1377871038
] |
def main():
parser = argparse.ArgumentParser(description='Look for imbalance between'
'hosts for a pair of keys')
parser.add_argument('filearg', help='File, directory, or quoted'
' glob pattern', nargs='?',default='jobs')
parser.add_argument('-p', help='Set number of processes',
nargs=1, type=int, default=[1])
n=parser.parse_args()
filelist=tspl_utils.getfilelist(n.filearg)
procs = min(len(filelist),n.p[0])
job=pickle.load(open(filelist[0]))
jid=job.id
epoch=job.end_time
ld=lariat_utils.LariatData(jid,end_epoch=epoch,daysback=3,directory=analyze_conf.lariat_path) | ubccr/tacc_stats | [
1,
2,
1,
1,
1377871038
] |
def __init__(self):
super(MensagemRetorno, self).__init__()
self.Codigo = TagCaracter(nome=u'Codigo', tamanho=[1, 4], raiz=u'/[nfse]')
self.Mensagem = TagCaracter(nome=u'Mensagem', tamanho=[1, 200], raiz=u'/[nfse]')
self.Correcao = TagCaracter(nome=u'Correcao', tamanho=[0, 200], raiz=u'/[nfse]') | thiagopena/PySIGNFe | [
43,
35,
43,
4,
1480611950
] |
def get_xml(self):
xml = XMLNFe.get_xml(self)
xml += ABERTURA
xml += u'<MensagemRetorno>'
xml += self.Codigo.xml
xml += self.Mensagem.xml
xml += self.Correcao.xml | thiagopena/PySIGNFe | [
43,
35,
43,
4,
1480611950
] |
def set_xml(self, arquivo):
if self._le_xml(arquivo):
self.Codigo.xml = arquivo
self.Mensagem.xml = arquivo
self.Correcao.xml = arquivo | thiagopena/PySIGNFe | [
43,
35,
43,
4,
1480611950
] |
def __init__(self):
super(MensagemRetornoLote, self).__init__()
self.IdentificacaoRps = IdentificacaoRps()
self.Codigo = TagCaracter(nome=u'Codigo', tamanho=[1, 4], raiz=u'/[nfse]')
self.Mensagem = TagCaracter(nome=u'Mensagem', tamanho=[1, 200], raiz=u'/[nfse]') | thiagopena/PySIGNFe | [
43,
35,
43,
4,
1480611950
] |
def get_xml(self):
xml = XMLNFe.get_xml(self)
xml += ABERTURA
xml += u'<MensagemRetornoLote>'
xml += self.IdentificacaoRps.xml
xml += self.Codigo.xml
xml += self.Mensagem.xml | thiagopena/PySIGNFe | [
43,
35,
43,
4,
1480611950
] |
def set_xml(self, arquivo):
if self._le_xml(arquivo):
self.IdentificacaoRps.xml = arquivo
self.Codigo.xml = arquivo
self.Mensagem.xml = arquivo | thiagopena/PySIGNFe | [
43,
35,
43,
4,
1480611950
] |
def __init__(self):
super(ListaMensagemRetornoLote, self).__init__()
self.MensagemRetornoLote = [] | thiagopena/PySIGNFe | [
43,
35,
43,
4,
1480611950
] |
def set_xml(self, arquivo):
if self._le_xml(arquivo):
self.MensagemRetornoLote = self.le_grupo('[nfse]//ListaMensagemRetornoLote/MensagemRetornoLote', MensagemRetornoLote) | thiagopena/PySIGNFe | [
43,
35,
43,
4,
1480611950
] |
def __init__(self):
super(ListaMensagemRetorno, self).__init__()
self.MensagemRetorno = [] | thiagopena/PySIGNFe | [
43,
35,
43,
4,
1480611950
] |
def set_xml(self, arquivo):
if self._le_xml(arquivo):
self.MensagemRetorno = self.le_grupo('[nfse]//ListaMensagemRetorno/MensagemRetorno', MensagemRetorno) | thiagopena/PySIGNFe | [
43,
35,
43,
4,
1480611950
] |
def __init__(self):
super(ConsultarSituacaoLoteRpsEnvio, self).__init__()
self.versao = TagDecimal(nome=u'ConsultarSituacaoLoteRpsEnvio', propriedade=u'versao', namespace=NAMESPACE_NFSE, valor=u'1.00', raiz=u'/')
self.Prestador = IdentificacaoPrestador()
self.Protocolo = TagCaracter(nome=u'Protocolo', tamanho=[ 1, 50], raiz=u'/')
self.caminho_esquema = os.path.join(DIRNAME, u'schema/')
self.arquivo_esquema = u'nfse.xsd' | thiagopena/PySIGNFe | [
43,
35,
43,
4,
1480611950
] |
def get_xml(self):
xml = XMLNFe.get_xml(self)
xml += ABERTURA
xml += u'<ConsultarSituacaoLoteRpsEnvio xmlns="'+ NAMESPACE_NFSE + '">'
xml += self.Prestador.xml.replace(ABERTURA, u'')
xml += self.Protocolo.xml | thiagopena/PySIGNFe | [
43,
35,
43,
4,
1480611950
] |
def set_xml(self, arquivo):
if self._le_xml(arquivo):
self.Prestador.xml = arquivo
self.Protocolo.xml = arquivo | thiagopena/PySIGNFe | [
43,
35,
43,
4,
1480611950
] |
def __init__(self):
super(ConsultarSituacaoLoteRpsResposta, self).__init__()
self.NumeroLote = TagInteiro(nome=u'NumeroLote', tamanho=[1, 15], raiz=u'/')
self.Situacao = TagInteiro(nome=u'Situacao', tamanho=[1, 1], raiz=u'/')
self.ListaMensagemRetorno = ListaMensagemRetorno() | thiagopena/PySIGNFe | [
43,
35,
43,
4,
1480611950
] |
def get_xml(self):
xml = XMLNFe.get_xml(self)
xml += ABERTURA
xml += u'<ConsultarSituacaoLoteRpsResposta xmlns="'+ NAMESPACE_NFSE + '">'
xml += self.NumeroLote.xml
xml += self.Situacao.xml
xml += self.ListaMensagemRetorno.xml.replace(ABERTURA, u'') | thiagopena/PySIGNFe | [
43,
35,
43,
4,
1480611950
] |
def set_xml(self, arquivo):
if self._le_xml(arquivo):
self.NumeroLote.xml = arquivo
self.Situacao.xml = arquivo
self.ListaMensagemRetorno.xml = arquivo | thiagopena/PySIGNFe | [
43,
35,
43,
4,
1480611950
] |
def __init__(self, system):
"""
Initialize a hsms linktest response.
:param system: message ID
:type system: integer
**Example**::
>>> import secsgem.hsms
>>>
>>> secsgem.hsms.HsmsLinktestRspHeader(10)
HsmsLinktestRspHeader({sessionID:0xffff, stream:00, function:00, pType:0x00, sType:0x06, \ | bparzella/secsgem | [
119,
67,
119,
20,
1423603517
] |
def _play(input, fs):
if input.ndim == 1:
input = input[np.newaxis, :]
nc = 1
elif input.ndim == 2:
nc = input.shape[0]
else:
raise ValueError, \
"Only input of rank 1 and 2 supported for now."
dev = AlsaDevice(fs=fs, nchannels=nc)
dev.play(input) | cournape/audiolab | [
141,
45,
141,
32,
1237912807
] |
def _play(input, fs):
if input.ndim == 1:
input = input[np.newaxis, :]
nc = 1
elif input.ndim == 2:
nc = input.shape[0]
else:
raise ValueError, \
"Only input of rank 1 and 2 supported for now."
dev = CoreAudioDevice(fs=fs, nchannels=nc)
dev.play(input) | cournape/audiolab | [
141,
45,
141,
32,
1237912807
] |
def _play(input, fs):
raise NotImplementedError, \
"No Backend implemented for your platform " \
"(detected platform is: %s)" % sys.platform | cournape/audiolab | [
141,
45,
141,
32,
1237912807
] |
def __init__(self,user,subuser):
self.subuser = subuser
Service.__init__(self,user,subuser)
self.name = "xpra" | subuser-security/subuser | [
880,
66,
880,
40,
1391987856
] |
def getSubuserSpecificServerPermissions(self):
"""
Get the dictionary of permissions that are specific to this particular subuser and therefore are not packaged in the xpra server image source.
"""
permissions = OrderedDict()
permissions["system-dirs"] = OrderedDict(
[ (self.getXpraHomeDir(),"/home/subuser")
, (self.getServerSideX11Path(),"/tmp/.X11-unix") ])
return permissions | subuser-security/subuser | [
880,
66,
880,
40,
1391987856
] |
def setupServerPermissions(self):
permissions = self.getServerSubuser().permissions
for key,value in self.getSubuserSpecificServerPermissions().items():
permissions[key] = value
permissions.save() | subuser-security/subuser | [
880,
66,
880,
40,
1391987856
] |
def arePermissionsUpToDate(self):
areClientPermissionsUpToDate = isSubDict(self.getSubuserSpecificClientPermissions(),self.getClientSubuser().permissions)
if not areClientPermissionsUpToDate:
self.user.registry.log("Client permissions:\n"+str(self.getClientSubuser().permissions)+ "\n differ from defaults:\n"+str(self.getSubuserSpecificClientPermissions()),verbosityLevel=4)
areServerPermissionsUpToDate = isSubDict(self.getSubuserSpecificServerPermissions(),self.getServerSubuser().permissions)
if not areServerPermissionsUpToDate:
self.user.registry.log("Server permissions:\n"+str(self.getServerSubuser().permissions)+ "\n differ from defaults:\n"+str(self.getSubuserSpecificServerPermissions()),verbosityLevel=4)
return areClientPermissionsUpToDate and areServerPermissionsUpToDate | subuser-security/subuser | [
880,
66,
880,
40,
1391987856
] |
def getXpraVolumePath(self):
return os.path.join(self.user.config["volumes-dir"],"xpra",self.subuser.name) | subuser-security/subuser | [
880,
66,
880,
40,
1391987856
] |
def getXpraHomeDir(self):
return os.path.join(self.getXpraVolumePath(),"xpra-home") | subuser-security/subuser | [
880,
66,
880,
40,
1391987856
] |
def getXpraSocket(self):
return os.path.join(self.getXpraHomeDir(),".xpra",self.getServerSubuserHostname()+"-100") | subuser-security/subuser | [
880,
66,
880,
40,
1391987856
] |
def getServerSubuserName(self):
return "!service-subuser-"+self.subuser.name+"-xpra-server" | subuser-security/subuser | [
880,
66,
880,
40,
1391987856
] |
def _getPermissionsAccepter(self):
from subuserlib.classes.permissionsAccepters.acceptPermissionsAtCLI import AcceptPermissionsAtCLI
return AcceptPermissionsAtCLI(self.user,alwaysAccept=True) | subuser-security/subuser | [
880,
66,
880,
40,
1391987856
] |
def getClientSubuserName(self):
return "!service-subuser-"+self.subuser.name+"-xpra-client" | subuser-security/subuser | [
880,
66,
880,
40,
1391987856
] |
def addClientSubuser(self):
subuserlib.subuser.addFromImageSourceNoVerify(self.user,self.getClientSubuserName(),self.user.registry.repositories["default"]["subuser-internal-xpra-client"])
self.subuser.serviceSubuserNames.append(self.getClientSubuserName())
self.getClientSubuser().createPermissions(self.getClientSubuser().imageSource.permissions) | subuser-security/subuser | [
880,
66,
880,
40,
1391987856
] |
def createAndSetupSpecialVolumes(self,errorCount=0):
def clearAndTryAgain():
if errorCount >= 5:
sys.exit("Failed to setup XPRA bridge volumes. You have some permissions errors with your subuser volumes directory."+self.getXpraVolumePath()+" Look at the output above and try to resolve the problem yourself. Possible causes are simple ownership problems, apparmor, SELinux. If you fail to find a simple explanation for your permissions problems. Please file a bug report.")
self.cleanUp()
self.createAndSetupSpecialVolumes(errorCount=errorCount+1)
def mkdirs(directory):
self.user.registry.log("Creating the "+directory+" directory.",verbosityLevel=4)
try:
self.user.endUser.makedirs(directory)
except OSError as e:
if e.errno == errno.EEXIST or e.errno == errno.EACCES:
self.user.registry.log(str(e),verbosityLevel=3)
self.user.registry.log("Clearing xpra X11 socket.",verbosityLevel=3)
clearAndTryAgain()
else:
raise e
self.user.registry.log("Setting up XPRA bridge volumes.",verbosityLevel=4)
mkdirs(self.getServerSideX11Path())
mkdirs(self.getXpraHomeDir())
mkdirs(self.getXpraTmpDir())
try:
os.chmod(self.getServerSideX11Path(),1023)
except OSError as e:
if e.errno == errno.EPERM:
self.user.registry.log("X11 bridge perm error, clearing a trying again.")
clearAndTryAgain() | subuser-security/subuser | [
880,
66,
880,
40,
1391987856
] |
def waitForContainerToLaunch(self, readyString, process, suppressOutput):
while True:
where = process.stderr_file.tell()
line = process.stderr_file.readline()
while (not line):# or (line[-1:] != '\n'):
time.sleep(0.1)
process.stderr_file.seek(where)
line = process.stderr_file.readline()
if not suppressOutput:
subuserlib.print.printWithoutCrashing(line[:-1])
if readyString in line:
break
process.stderr_file.close() | subuser-security/subuser | [
880,
66,
880,
40,
1391987856
] |
def isRunning(self,serviceStatus):
def isContainerRunning(cid):
container = self.user.dockerDaemon.getContainer(cid)
containerStatus = container.inspect()
if containerStatus is None:
return False
else:
if not containerStatus["State"]["Running"]:
#Clean up left over container
container.remove(force=True)
return False
else:
return True
return isContainerRunning(serviceStatus["xpra-client-service-cid"]) and isContainerRunning(serviceStatus["xpra-server-service-cid"]) | subuser-security/subuser | [
880,
66,
880,
40,
1391987856
] |
def __init__(self):
super(DummyKnittingPlugin, self).__init__() | fashiontec/knitlib | [
1529,
13,
1529,
7,
1432366551
] |
def onknit(self, e):
logging.debug(DummyKnittingPlugin.base_log_string.format("onknit"))
# In order to simulate blocking we make it sleep.
total = 5
for i in range(total):
time.sleep(1)
self.interactive_callbacks["progress"](i / float(total), i, total)
self.finish() | fashiontec/knitlib | [
1529,
13,
1529,
7,
1432366551
] |
def onconfigure(self, e):
logging.debug(DummyKnittingPlugin.base_log_string.format("onconfigure")) | fashiontec/knitlib | [
1529,
13,
1529,
7,
1432366551
] |
def __init__(self):
self._bus = pydbus.SessionBus() | cyanogen/uchroma | [
46,
10,
46,
17,
1481916427
] |
def get_device(self, identifier):
if identifier is None:
return None
use_key = False
if isinstance(identifier, str):
if identifier.startswith(BASE_PATH):
return self._bus.get(SERVICE, identifier)
if re.match(r'\w{4}:\w{4}.\d{2}', identifier):
use_key = True
elif re.match(r'\d+', identifier):
identifier = int(identifier)
else:
return None
for dev_path in self.get_device_paths():
dev = self.get_device(dev_path)
if use_key and identifier == dev.Key:
return dev
elif identifier == dev.DeviceIndex:
return dev
return None | cyanogen/uchroma | [
46,
10,
46,
17,
1481916427
] |
def write(self, msg): pass | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def usage(code, msg=''):
print >> sys.stderr, __doc__ % globals()
if msg:
print >> sys.stderr, msg
sys.exit(code) | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def __init__(self, server, conn, addr):
asynchat.async_chat.__init__(self, conn)
self.__server = server
self.__conn = conn
self.__addr = addr
self.__line = []
self.__state = self.COMMAND
self.__greeting = 0
self.__mailfrom = None
self.__rcpttos = []
self.__data = ''
self.__fqdn = socket.getfqdn()
try:
self.__peer = conn.getpeername()
except socket.error, err:
# a race condition may occur if the other end is closing
# before we can get the peername
self.close()
if err[0] != errno.ENOTCONN:
raise
return
print >> DEBUGSTREAM, 'Peer:', repr(self.__peer)
self.push('220 %s %s' % (self.__fqdn, __version__))
self.set_terminator('\r\n') | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def push(self, msg):
asynchat.async_chat.push(self, msg + '\r\n') | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def collect_incoming_data(self, data):
self.__line.append(data) | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def found_terminator(self):
line = EMPTYSTRING.join(self.__line)
print >> DEBUGSTREAM, 'Data:', repr(line)
self.__line = []
if self.__state == self.COMMAND:
if not line:
self.push('500 Error: bad syntax')
return
method = None
i = line.find(' ')
if i < 0:
command = line.upper()
arg = None
else:
command = line[:i].upper()
arg = line[i+1:].strip()
method = getattr(self, 'smtp_' + command, None)
if not method:
self.push('502 Error: command "%s" not implemented' % command)
return
method(arg)
return
else:
if self.__state != self.DATA:
self.push('451 Internal confusion')
return
# Remove extraneous carriage returns and de-transparency according
# to RFC 821, Section 4.5.2.
data = []
for text in line.split('\r\n'):
if text and text[0] == '.':
data.append(text[1:])
else:
data.append(text)
self.__data = NEWLINE.join(data)
status = self.__server.process_message(self.__peer,
self.__mailfrom,
self.__rcpttos,
self.__data)
self.__rcpttos = []
self.__mailfrom = None
self.__state = self.COMMAND
self.set_terminator('\r\n')
if not status:
self.push('250 Ok')
else:
self.push(status) | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def smtp_HELO(self, arg):
if not arg:
self.push('501 Syntax: HELO hostname')
return
if self.__greeting:
self.push('503 Duplicate HELO/EHLO')
else:
self.__greeting = arg
self.push('250 %s' % self.__fqdn) | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def smtp_QUIT(self, arg):
# args is ignored
self.push('221 Bye')
self.close_when_done() | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def __getaddr(self, keyword, arg):
address = None
keylen = len(keyword)
if arg[:keylen].upper() == keyword:
address = arg[keylen:].strip()
if not address:
pass
elif address[0] == '<' and address[-1] == '>' and address != '<>':
# Addresses can be in the form <person@dom.com> but watch out
# for null address, e.g. <>
address = address[1:-1]
return address | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def smtp_RCPT(self, arg):
print >> DEBUGSTREAM, '===> RCPT', arg
if not self.__mailfrom:
self.push('503 Error: need MAIL command')
return
address = self.__getaddr('TO:', arg) if arg else None
if not address:
self.push('501 Syntax: RCPT TO: <address>')
return
self.__rcpttos.append(address)
print >> DEBUGSTREAM, 'recips:', self.__rcpttos
self.push('250 Ok') | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def smtp_DATA(self, arg):
if not self.__rcpttos:
self.push('503 Error: need RCPT command')
return
if arg:
self.push('501 Syntax: DATA')
return
self.__state = self.DATA
self.set_terminator('\r\n.\r\n')
self.push('354 End data with <CR><LF>.<CR><LF>') | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def __init__(self, localaddr, remoteaddr):
self._localaddr = localaddr
self._remoteaddr = remoteaddr
asyncore.dispatcher.__init__(self)
try:
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
# try to re-use a server port if possible
self.set_reuse_addr()
self.bind(localaddr)
self.listen(5)
except:
# cleanup asyncore.socket_map before raising
self.close()
raise
else:
print >> DEBUGSTREAM, \
'%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % (
self.__class__.__name__, time.ctime(time.time()),
localaddr, remoteaddr) | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def process_message(self, peer, mailfrom, rcpttos, data):
"""Override this abstract method to handle messages from the client.
peer is a tuple containing (ipaddr, port) of the client that made the
socket connection to our smtp port.
mailfrom is the raw address the client claims the message is coming
from.
rcpttos is a list of raw addresses the client wishes to deliver the
message to.
data is a string containing the entire full text of the message,
headers (if supplied) and all. It has been `de-transparencied'
according to RFC 821, Section 4.5.2. In other words, a line
containing a `.' followed by other text has had the leading dot
removed.
This function should return None, for a normal `250 Ok' response;
otherwise it returns the desired response string in RFC 821 format.
"""
raise NotImplementedError | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def process_message(self, peer, mailfrom, rcpttos, data):
inheaders = 1
lines = data.split('\n')
print '---------- MESSAGE FOLLOWS ----------'
for line in lines:
# headers first
if inheaders and not line:
print 'X-Peer:', peer[0]
inheaders = 0
print line
print '------------ END MESSAGE ------------' | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def process_message(self, peer, mailfrom, rcpttos, data):
lines = data.split('\n')
# Look for the last header
i = 0
for line in lines:
if not line:
break
i += 1
lines.insert(i, 'X-Peer: %s' % peer[0])
data = NEWLINE.join(lines)
refused = self._deliver(mailfrom, rcpttos, data)
# TBD: what to do with refused addresses?
print >> DEBUGSTREAM, 'we got some refusals:', refused | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def process_message(self, peer, mailfrom, rcpttos, data):
from cStringIO import StringIO
from Mailman import Utils
from Mailman import Message
from Mailman import MailList
# If the message is to a Mailman mailing list, then we'll invoke the
# Mailman script directly, without going through the real smtpd.
# Otherwise we'll forward it to the local proxy for disposition.
listnames = []
for rcpt in rcpttos:
local = rcpt.lower().split('@')[0]
# We allow the following variations on the theme
# listname
# listname-admin
# listname-owner
# listname-request
# listname-join
# listname-leave
parts = local.split('-')
if len(parts) > 2:
continue
listname = parts[0]
if len(parts) == 2:
command = parts[1]
else:
command = ''
if not Utils.list_exists(listname) or command not in (
'', 'admin', 'owner', 'request', 'join', 'leave'):
continue
listnames.append((rcpt, listname, command))
# Remove all list recipients from rcpttos and forward what we're not
# going to take care of ourselves. Linear removal should be fine
# since we don't expect a large number of recipients.
for rcpt, listname, command in listnames:
rcpttos.remove(rcpt)
# If there's any non-list destined recipients left,
print >> DEBUGSTREAM, 'forwarding recips:', ' '.join(rcpttos)
if rcpttos:
refused = self._deliver(mailfrom, rcpttos, data)
# TBD: what to do with refused addresses?
print >> DEBUGSTREAM, 'we got refusals:', refused
# Now deliver directly to the list commands
mlists = {}
s = StringIO(data)
msg = Message.Message(s)
# These headers are required for the proper execution of Mailman. All
# MTAs in existence seem to add these if the original message doesn't
# have them.
if not msg.getheader('from'):
msg['From'] = mailfrom
if not msg.getheader('date'):
msg['Date'] = time.ctime(time.time())
for rcpt, listname, command in listnames:
print >> DEBUGSTREAM, 'sending message to', rcpt
mlist = mlists.get(listname)
if not mlist:
mlist = MailList.MailList(listname, lock=0)
mlists[listname] = mlist
# dispatch on the type of command
if command == '':
# post
msg.Enqueue(mlist, tolist=1)
elif command == 'admin':
msg.Enqueue(mlist, toadmin=1)
elif command == 'owner':
msg.Enqueue(mlist, toowner=1)
elif command == 'request':
msg.Enqueue(mlist, torequest=1)
elif command in ('join', 'leave'):
# TBD: this is a hack!
if command == 'join':
msg['Subject'] = 'subscribe'
else:
msg['Subject'] = 'unsubscribe'
msg.Enqueue(mlist, torequest=1) | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def parseargs():
global DEBUGSTREAM
try:
opts, args = getopt.getopt(
sys.argv[1:], 'nVhc:d',
['class=', 'nosetuid', 'version', 'help', 'debug'])
except getopt.error, e:
usage(1, e)
options = Options()
for opt, arg in opts:
if opt in ('-h', '--help'):
usage(0)
elif opt in ('-V', '--version'):
print >> sys.stderr, __version__
sys.exit(0)
elif opt in ('-n', '--nosetuid'):
options.setuid = 0
elif opt in ('-c', '--class'):
options.classname = arg
elif opt in ('-d', '--debug'):
DEBUGSTREAM = sys.stderr
# parse the rest of the arguments
if len(args) < 1:
localspec = 'localhost:8025'
remotespec = 'localhost:25'
elif len(args) < 2:
localspec = args[0]
remotespec = 'localhost:25'
elif len(args) < 3:
localspec = args[0]
remotespec = args[1]
else:
usage(1, 'Invalid arguments: %s' % COMMASPACE.join(args))
# split into host/port pairs
i = localspec.find(':')
if i < 0:
usage(1, 'Bad local spec: %s' % localspec)
options.localhost = localspec[:i]
try:
options.localport = int(localspec[i+1:])
except ValueError:
usage(1, 'Bad local port: %s' % localspec)
i = remotespec.find(':')
if i < 0:
usage(1, 'Bad remote spec: %s' % remotespec)
options.remotehost = remotespec[:i]
try:
options.remoteport = int(remotespec[i+1:])
except ValueError:
usage(1, 'Bad remote port: %s' % remotespec)
return options | vFense/vFenseAgent-nix | [
6,
2,
6,
10,
1393869099
] |
def dottedquad_to_num(ip):
"""
Convert decimal dotted quad string IP to long integer
"""
return struct.unpack('!L',socket.inet_aton(ip))[0] | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def unique_match_from_list(list):
"""
Check the list for a potential pattern match
@param list : a list of potential matching groups | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def extract_matching_pattern(regex, group_name, unfiltered_list):
"""
Return the desired group_name from a list of matching patterns
@param regex : a regular expression with named groups
@param group_name : the desired matching group name value
@param unfiltered_list : a list of matches | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def __init__(self, ip, fqdn=''):
self.ip_dottedquad = ip
self.ip_num = dottedquad_to_num(ip)
self.fqdn = fqdn
self.rdns = ''
self.ports = []
self.os = ''
self.mac_address = ''
self.mac_address_vendor = ''
self.network_distance = '' | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def add_port(self, port):
self.ports.append(port) | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def get_ip_num_format(self):
return str(self.ip_num) | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def get_ip_dotted_format(self):
return str(self.ip_dottedquad) | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def get_fqdn(self):
return str(self.fqdn) | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def get_rdns_record(self):
return str(self.rdns) | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def get_port_list(self):
return self.ports | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def get_port_number_list(self):
if not(self.get_port_list()):
return ['']
else:
result = []
for port in self.get_port_list():
result.append(port.get_number())
return result | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def get_port_protocol_list(self):
if not(self.get_port_list()):
return ['']
else:
result = []
for port in self.get_port_list():
result.append(port.get_protocol())
return result | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def get_port_version_list(self):
if not(self.get_port_list()):
return ['']
else:
result = []
for port in self.get_port_list():
result.append(port.get_version())
return result | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def get_os(self):
return str(self.os) | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def get_mac_address(self):
return str(self.mac_address) | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def get_mac_address_vendor(self):
return str(self.mac_address_vendor) | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def get_network_distance(self):
return str(self.network_distance) | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def set_fqdn(self, fqdn):
self.fqdn = fqdn | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def set_rdns_record(self, rdns_record):
self.rdns = rdns_record | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def set_mac(self, mac_address, mac_address_vendor = ''):
self.mac_address = mac_address
self.mac_address_vendor = mac_address_vendor | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def __init__(self, number, protocol, service='', version='', script=''):
self.number = number
self.protocol = protocol
self.service = service
self.version = version
self.script = script | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def get_number(self):
return self.number | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def get_protocol(self):
return self.protocol | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def get_service(self):
return self.service | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
def get_version(self):
return self.version | maaaaz/nmaptocsv | [
350,
93,
350,
5,
1348413900
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.