text
stringlengths 2
100k
| meta
dict |
---|---|
add_subdirectory(SharpLang.Runtime)
| {
"pile_set_name": "Github"
} |
--
-- Licensed to the Apache Software Foundation (ASF) under one or more
-- contributor license agreements. See the NOTICE file distributed with
-- this work for additional information regarding copyright ownership.
-- The ASF licenses this file to You 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 ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
CREATE TEMPORARY VIEW t AS SELECT 'aa' as a;
-- casting to data types which are unable to represent the string input returns NULL
select cast(a as byte) from t;
select cast(a as short) from t;
select cast(a as int) from t;
select cast(a as long) from t;
select cast(a as float) from t;
select cast(a as double) from t;
select cast(a as decimal) from t;
select cast(a as boolean) from t;
select cast(a as timestamp) from t;
select cast(a as date) from t;
-- casting to binary works correctly
select cast(a as binary) from t;
-- casting to array, struct or map throws exception
select cast(a as array<string>) from t;
select cast(a as struct<s:string>) from t;
select cast(a as map<string, string>) from t;
-- all timestamp/date expressions return NULL if bad input strings are provided
select to_timestamp(a) from t;
select to_timestamp('2018-01-01', a) from t;
select to_unix_timestamp(a) from t;
select to_unix_timestamp('2018-01-01', a) from t;
select unix_timestamp(a) from t;
select unix_timestamp('2018-01-01', a) from t;
select from_unixtime(a) from t;
select from_unixtime('2018-01-01', a) from t;
select next_day(a, 'MO') from t;
select next_day('2018-01-01', a) from t;
select trunc(a, 'MM') from t;
select trunc('2018-01-01', a) from t;
-- some functions return NULL if bad input is provided
select unhex('-123');
select sha2(a, a) from t;
select get_json_object(a, a) from t;
select json_tuple(a, a) from t;
select from_json(a, 'a INT') from t;
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2005 Massachusetts Institute of Technology
* Copyright (c) 2007 Secure Endpoints Inc.
*
* 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, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/* $Id$ */
/* Include the OEMRESOURCE constants for locating standard icon
resources. */
#define OEMRESOURCE
#include<khmapp.h>
#if _WIN32_WINNT >= 0x0501
#include<uxtheme.h>
#endif
#include<assert.h>
ATOM khui_newcredwnd_cls;
/* forward dcl */
static void
nc_position_credtext(khui_nc_wnd_data * d);
/* Common dialog procedure used by the main credential panel
(IDD_NC_NEWCRED) and the button bar (IDC_NC_BBAR). */
static void
nc_layout_main_panel(khui_nc_wnd_data * d);
static void
nc_layout_new_cred_window(khui_nc_wnd_data * d);
static INT_PTR CALLBACK
nc_common_dlg_proc(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
switch(uMsg) {
case WM_INITDIALOG:
{
khui_nc_wnd_data * d;
d = (khui_nc_wnd_data *) lParam;
#pragma warning(push)
#pragma warning(disable: 4244)
SetWindowLongPtr(hwnd, DWLP_USER, lParam);
#pragma warning(pop)
if (d->nc->subtype == KMSG_CRED_PASSWORD) {
ShowWindow(GetDlgItem(hwnd, IDC_NC_ADVANCED),
SW_HIDE);
}
}
return TRUE;
case WM_COMMAND:
{
int ctrl_id;
ctrl_id = LOWORD(wParam);
if (ctrl_id < KHUI_CW_ID_MIN ||
ctrl_id > KHUI_CW_ID_MAX) {
/* pump it to the parent */
PostMessage(GetParent(hwnd), WM_COMMAND, wParam, lParam);
return TRUE;
} /* else we allow the message to fall through and get
passed into the identity provider's message
handler. */
}
break;
case KHUI_WM_NC_NOTIFY:
{
khui_nc_wnd_data * d;
d = (khui_nc_wnd_data *)(LONG_PTR)
GetWindowLongPtr(hwnd, DWLP_USER);
if (d == NULL)
break;
/* message sent by parent to notify us of something */
switch(HIWORD(wParam)) {
case WMNC_DIALOG_EXPAND:
/* fallthrough */
case WMNC_UPDATE_LAYOUT:
if(hwnd == d->dlg_main) {
nc_layout_main_panel(d);
return TRUE;
}
break; /* nop */
}
}
return TRUE;
}
/* check if we have a wnd_data, and if so pass the message on to
the identity provider callback. */
{
khui_nc_wnd_data * d;
d = (khui_nc_wnd_data *) (LONG_PTR)
GetWindowLongPtr(hwnd, DWLP_USER);
/* TODO: filter out and forward only the messages that
originated or pertain to the identity selection
controls. */
if (d && d->nc && d->nc->ident_cb) {
return d->nc->ident_cb(d->nc, WMNC_IDENT_WMSG, hwnd, uMsg,
wParam, lParam);
}
}
return FALSE;
}
static void
nc_notify_clear(khui_nc_wnd_data * d) {
if (d->notif_type == NC_NOTIFY_NONE)
/* there are no notifications anyway. */
return;
if (d->hwnd_notif_label)
DestroyWindow(d->hwnd_notif_label);
if (d->hwnd_notif_aux)
DestroyWindow(d->hwnd_notif_aux);
d->hwnd_notif_label = NULL;
d->hwnd_notif_aux = NULL;
SetRectEmpty(&d->r_notif);
d->notif_type = NC_NOTIFY_NONE;
/* Note that we must call nc_layout_main_panel() after calling
this to adjust the layout of the main panel. However we aren't
calling it here since we might want to add another set of
notifications or make other changes to the main panel content
before calling nc_layout_main_panel(). */
}
static void
nc_notify_marquee(khui_nc_wnd_data * d, const wchar_t * label) {
#if (_WIN32_IE >= 0x0600)
HDC hdc;
size_t length;
SIZE label_size;
#endif
RECT r_label;
RECT r_mq;
RECT r_row;
HFONT hfont;
HWND hwnd;
HDWP hdefer;
/* Clear the notification area. We only support one notification
at a time. */
nc_notify_clear(d);
#ifdef DEBUG
assert(d->dlg_main);
#endif
#if (_WIN32_IE >= 0x0600)
/* We can only show the marquee control if the comctl32 DLL is
version 6.0 or later. Otherwise we only show the label. */
if (FAILED(StringCchLength(label, KHUI_MAXCCH_SHORT_DESC, &length))) {
#ifdef DEBUG
assert(FALSE);
#endif
length = KHUI_MAXCCH_SHORT_DESC;
}
/* See how big the notification control needs to be. */
hdc = GetDC(d->dlg_main);
#ifdef DEBUG
assert(hdc != NULL);
#endif
GetTextExtentPoint32(hdc, label, (int) length, &label_size);
ReleaseDC(d->dlg_main, hdc);
CopyRect(&r_row, &d->r_row);
if (label_size.cx > d->r_e_label.right - d->r_e_label.left) {
/* using an entire row */
CopyRect(&r_label, &d->r_row);
CopyRect(&r_mq, &d->r_n_input);
OffsetRect(&r_mq, 0, r_row.bottom - r_row.top);
r_row.bottom += r_row.bottom - r_row.top;
} else if (label_size.cx > d->r_n_label.right - d->r_n_label.left) {
/* using large labels */
CopyRect(&r_label, &d->r_e_label);
CopyRect(&r_mq, &d->r_e_input);
} else {
/* normal labels */
CopyRect(&r_label, &d->r_n_label);
CopyRect(&r_mq, &d->r_n_input);
}
InflateRect(&r_mq, 0, - ((r_mq.bottom - r_mq.top) / 4));
#else /* _WIN32_IE < 0x0600 */
/* We are just showing the label */
CopyRect(&r_row, &d->r_row);
CopyRect(&r_label, &r_row);
SetRectEmpty(&r_mq);
#endif /* _WIN32_IE >= 0x0600 */
{
long y;
if (IsRectEmpty(&d->r_custprompt)) {
y = d->r_idspec.bottom;
} else {
y = d->r_custprompt.bottom;
}
OffsetRect(&r_row, d->r_area.left, y);
OffsetRect(&r_label, r_row.left, r_row.top);
OffsetRect(&r_mq, r_row.left, r_row.top);
}
hfont = (HFONT) SendMessage(d->dlg_main, WM_GETFONT, 0, 0);
hdefer = BeginDeferWindowPos(2);
/* the label */
hwnd = CreateWindowEx(0,
L"STATIC",
label,
WS_CHILD | SS_ENDELLIPSIS,
r_label.left, r_label.top,
r_label.right - r_label.left,
r_label.bottom - r_label.top,
d->dlg_main,
NULL, NULL, NULL);
#ifdef DEBUG
assert(hwnd != NULL);
#endif
SendMessage(hwnd, WM_SETFONT, (WPARAM) hfont, (LPARAM) TRUE);
DeferWindowPos(hdefer, hwnd, NULL,
0, 0, 0, 0,
SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER |
SWP_NOSIZE | SWP_SHOWWINDOW);
d->hwnd_notif_label = hwnd;
/* and the marquee */
#if (_WIN32_IE >= 0x0600)
/* unfortunately, the marquee is only available on comctl32
version 6.0 or later. On previous versions, we only display
the message label. */
hwnd = CreateWindowEx(0,
PROGRESS_CLASS,
L"",
WS_CHILD | PBS_MARQUEE,
r_mq.left, r_mq.top,
r_mq.right - r_mq.left,
r_mq.bottom - r_mq.top,
d->dlg_main,
NULL, NULL, NULL);
#ifdef DEBUG
assert(hwnd != NULL);
#endif
SendMessage(hwnd, PBM_SETMARQUEE, TRUE, 100);
DeferWindowPos(hdefer, hwnd, NULL,
0, 0, 0, 0,
SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER |
SWP_NOSIZE | SWP_SHOWWINDOW);
d->hwnd_notif_aux = hwnd;
#endif /* _WIN32_IE >= 0x0600 */
EndDeferWindowPos(hdefer);
CopyRect(&d->r_notif, &r_row);
d->notif_type = NC_NOTIFY_MARQUEE;
/* Note that we must call nc_layout_main_panel() after calling
this to adjust the layout of the main panel. However we aren't
calling it here since we might want to add another set of
notifications or make other changes to the main panel content
before calling nc_layout_main_panel(). */
}
static void
nc_notify_message(khui_nc_wnd_data * d,
kherr_severity severity,
const wchar_t * message) {
SIZE icon_size;
LPCTSTR icon_res;
HICON h_icon;
HWND hwnd;
HFONT hfont;
HDWP hdefer;
RECT r_row;
RECT r_label;
RECT r_icon;
nc_notify_clear(d);
icon_size.cx = GetSystemMetrics(SM_CXSMICON);
icon_size.cy = GetSystemMetrics(SM_CYSMICON);
switch(severity) {
case KHERR_INFO:
icon_res = MAKEINTRESOURCE(OIC_INFORMATION);
break;
case KHERR_WARNING:
icon_res = MAKEINTRESOURCE(OIC_WARNING);
break;
case KHERR_ERROR:
icon_res = MAKEINTRESOURCE(OIC_ERROR);
break;
default:
icon_res = NULL;
}
if (icon_res != NULL) {
h_icon = (HICON) LoadImage(NULL,
icon_res,
IMAGE_ICON,
icon_size.cx,
icon_size.cy,
LR_DEFAULTCOLOR | LR_SHARED);
} else {
h_icon = NULL;
}
CopyRect(&r_row, &d->r_row);
#define CENTERVALUE(w,v) ((w)/2 - (v)/2)
SetRect(&r_icon,
0, CENTERVALUE(r_row.bottom - r_row.top, icon_size.cy),
icon_size.cx,
CENTERVALUE(r_row.bottom - r_row.top, icon_size.cy) + icon_size.cy);
#undef CENTERVALUE
CopyRect(&r_label, &r_row);
OffsetRect(&r_label, -r_label.left, -r_label.top);
r_label.left += (icon_size.cx * 3) / 2;
{
long y;
if (IsRectEmpty(&d->r_custprompt)) {
y = d->r_idspec.bottom;
} else {
y = d->r_custprompt.bottom;
}
OffsetRect(&r_row, d->r_area.left, y);
OffsetRect(&r_label, r_row.left, r_row.top);
OffsetRect(&r_icon, r_row.left, r_row.top);
}
hfont = (HFONT) SendMessage(d->dlg_main, WM_GETFONT, 0, 0);
hdefer = BeginDeferWindowPos(2);
hwnd = CreateWindowEx(0,
L"STATIC",
message,
WS_CHILD | SS_ENDELLIPSIS | SS_CENTER,
r_label.left, r_label.top,
r_label.right - r_label.left,
r_label.bottom - r_label.top,
d->dlg_main,
NULL, NULL, NULL);
#ifdef DEBUG
assert(hwnd != NULL);
#endif
SendMessage(hwnd, WM_SETFONT, (WPARAM) hfont, (LPARAM) TRUE);
DeferWindowPos(hdefer, hwnd, NULL,
0, 0, 0, 0,
SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER |
SWP_NOSIZE | SWP_SHOWWINDOW);
d->hwnd_notif_label = hwnd;
hwnd = CreateWindowEx(0,
L"STATIC",
NULL,
WS_CHILD | SS_ICON |
#if (_WIN32_IE >= 0x0600)
SS_REALSIZECONTROL
#else
0
#endif
,
r_icon.left, r_icon.top,
r_icon.right - r_icon.left,
r_icon.bottom - r_icon.top,
d->dlg_main,
NULL, NULL, NULL);
#ifdef DEBUG
assert(hwnd != NULL);
#endif
if (h_icon && hwnd)
SendMessage(hwnd, STM_SETICON, (WPARAM) h_icon, 0);
DeferWindowPos(hdefer, hwnd, NULL,
0, 0, 0, 0,
SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER |
SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOZORDER);
d->hwnd_notif_aux = hwnd;
EndDeferWindowPos(hdefer);
CopyRect(&d->r_notif, &r_row);
d->notif_type = NC_NOTIFY_MESSAGE;
/* Note that we must call nc_layout_main_panel() after calling
this to adjust the layout of the main panel. However we aren't
calling it here since we might want to add another set of
notifications or make other changes to the main panel content
before calling nc_layout_main_panel(). */
}
static void
nc_layout_main_panel(khui_nc_wnd_data * d)
{
RECT r_main;
HWND hw_ct;
HWND hw_ct_label;
HDWP hdwp;
RECT r_used; /* extent used by identity specifiers,
custom prompts and notificaiton
controls. */
RECT r_wmain; /* extents of the main window in screen
coordinates. */
r_main.left = 0;
r_main.top = 0;
r_main.bottom = NCDLG_HEIGHT;
r_main.right = NCDLG_WIDTH;
MapDialogRect(d->dlg_main, &r_main);
CopyRect(&r_used, &d->r_idspec);
GetWindowRect(d->dlg_main, &r_wmain);
hdwp = BeginDeferWindowPos(7);
/* check if the notification area and the custom prompt area are
overlapping. */
if (d->notif_type != NC_NOTIFY_NONE) {
long delta_y = 0;
RECT r;
CopyRect(&r, &d->r_custprompt);
if (IsRectEmpty(&d->r_custprompt)) {
/* if there are no custom prompts, then the notification
area should be immediately below the identitify
specifers. */
delta_y = d->r_idspec.bottom - d->r_notif.top;
} else {
/* otherwise, the notification area should be immediately
below the custom prompt area */
delta_y = d->r_custprompt.bottom - d->r_notif.top;
}
if (delta_y != 0) {
RECT r_lbl;
RECT r_aux;
if (d->hwnd_notif_label) {
GetWindowRect(d->hwnd_notif_label, &r_lbl);
OffsetRect(&r_lbl, -r_wmain.left, delta_y - r_wmain.top);
DeferWindowPos(hdwp, d->hwnd_notif_label, NULL,
r_lbl.left, r_lbl.top, 0, 0,
SWP_NOACTIVATE | SWP_NOOWNERZORDER |
SWP_NOZORDER | SWP_NOSIZE);
}
if (d->hwnd_notif_aux) {
GetWindowRect(d->hwnd_notif_aux, &r_aux);
OffsetRect(&r_aux, -r_wmain.left, delta_y - r_wmain.top);
DeferWindowPos(hdwp, d->hwnd_notif_aux, NULL,
r_aux.left, r_aux.top, 0, 0,
SWP_NOACTIVATE | SWP_NOOWNERZORDER |
SWP_NOZORDER | SWP_NOSIZE);
}
OffsetRect(&d->r_notif, 0, delta_y);
}
}
if (!IsRectEmpty(&d->r_custprompt)) {
r_used.bottom = max(d->r_custprompt.bottom,
r_used.bottom);
}
if (!IsRectEmpty(&d->r_notif)) {
r_used.bottom = max(d->r_notif.bottom,
r_used.bottom);
}
if (d->nc->mode == KHUI_NC_MODE_MINI) {
RECT r_ok;
RECT r_cancel;
RECT r_advanced;
HWND hw;
hw = GetDlgItem(d->dlg_main, IDOK);
#ifdef DEBUG
assert(hw != NULL);
#endif
GetWindowRect(hw, &r_ok);
OffsetRect(&r_ok, -r_wmain.left, -r_ok.top + r_used.bottom);
DeferWindowPos(hdwp, hw, NULL,
r_ok.left, r_ok.top, 0, 0,
SWP_NOACTIVATE | SWP_NOOWNERZORDER |
SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW);
hw = GetDlgItem(d->dlg_main, IDCANCEL);
#ifdef DEBUG
assert(hw != NULL);
#endif
GetWindowRect(hw, &r_cancel);
OffsetRect(&r_cancel, -r_wmain.left, -r_cancel.top + r_used.bottom);
DeferWindowPos(hdwp, hw, NULL,
r_cancel.left, r_cancel.top, 0, 0,
SWP_NOACTIVATE | SWP_NOOWNERZORDER |
SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW);
hw = GetDlgItem(d->dlg_main, IDC_NC_ADVANCED);
#ifdef DEBUG
assert(hw != NULL);
#endif
GetWindowRect(hw, &r_advanced);
OffsetRect(&r_advanced, -r_wmain.left, -r_advanced.top + r_used.bottom);
DeferWindowPos(hdwp, hw, NULL,
r_advanced.left, r_advanced.top, 0, 0,
SWP_NOACTIVATE | SWP_NOOWNERZORDER |
SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW);
/* and now update the extents of the main panel */
r_main.bottom = r_used.bottom + (r_ok.bottom - r_ok.top) + d->r_area.top;
CopyRect(&d->r_main, &r_main);
} else {
HWND hw;
hw = GetDlgItem(d->dlg_main, IDOK);
#ifdef DEBUG
assert(hw != NULL);
#endif
if (IsWindowVisible(hw))
DeferWindowPos(hdwp, hw, NULL,
0, 0, 0, 0,
SWP_HIDEWINDOW | SWP_NOMOVE | SWP_NOSIZE |
SWP_NOOWNERZORDER | SWP_NOZORDER);
hw = GetDlgItem(d->dlg_main, IDCANCEL);
#ifdef DEBUG
assert(hw != NULL);
#endif
if (IsWindowVisible(hw))
DeferWindowPos(hdwp, hw, NULL,
0, 0, 0, 0,
SWP_HIDEWINDOW | SWP_NOMOVE | SWP_NOSIZE |
SWP_NOOWNERZORDER | SWP_NOZORDER);
hw = GetDlgItem(d->dlg_main, IDC_NC_ADVANCED);
#ifdef DEBUG
assert(hw != NULL);
#endif
if (IsWindowVisible(hw))
DeferWindowPos(hdwp, hw, NULL,
0, 0, 0, 0,
SWP_HIDEWINDOW | SWP_NOMOVE | SWP_NOSIZE |
SWP_NOOWNERZORDER | SWP_NOZORDER);
d->r_credtext.top = r_used.bottom;
CopyRect(&d->r_main, &r_main);
}
/* now update the layout of the credentials text window */
hw_ct = GetDlgItem(d->dlg_main, IDC_NC_CREDTEXT);
hw_ct_label = GetDlgItem(d->dlg_main, IDC_NC_CREDTEXT_LABEL);
#ifdef DEBUG
assert(hw_ct != NULL);
assert(hw_ct_label != NULL);
#endif
if (d->nc->mode == KHUI_NC_MODE_MINI ||
d->r_credtext.bottom < d->r_credtext.top + d->r_row.bottom * 2) {
/* either we aren't supposed to show the credentials text
window, or we don't have enough room. */
if (IsWindowVisible(hw_ct) || IsWindowVisible(hw_ct_label)) {
DeferWindowPos(hdwp, hw_ct, NULL,
0, 0, 0, 0,
SWP_HIDEWINDOW | SWP_NOOWNERZORDER |
SWP_NOZORDER | SWP_NOMOVE | SWP_NOSIZE);
DeferWindowPos(hdwp, hw_ct_label, NULL,
0, 0, 0, 0,
SWP_HIDEWINDOW | SWP_NOOWNERZORDER |
SWP_NOZORDER | SWP_NOMOVE | SWP_NOSIZE);
}
} else {
DeferWindowPos(hdwp,
hw_ct, NULL,
d->r_credtext.left + d->r_n_input.left, /* x */
d->r_credtext.top, /* y */
d->r_n_input.right - d->r_n_input.left, /* width */
d->r_credtext.bottom - d->r_credtext.top, /* height */
SWP_NOACTIVATE | SWP_NOOWNERZORDER |
SWP_NOZORDER | SWP_SHOWWINDOW);
DeferWindowPos(hdwp,
hw_ct_label, NULL,
d->r_credtext.left + d->r_n_label.left, /* x */
d->r_credtext.top, /* y */
d->r_n_label.right - d->r_n_label.left, /* width */
d->r_n_label.bottom - d->r_n_label.top, /* height */
SWP_NOACTIVATE | SWP_NOOWNERZORDER |
SWP_NOZORDER | SWP_SHOWWINDOW);
}
EndDeferWindowPos(hdwp);
/* NOTE: although we updated d->r_main, if the new credentials
window is in mini mode, we must call
nc_layout_new_cred_window() to adjust the size of the new
credentials window to fit the main panel. We don't do it here
because we need to keep these two operations separate. */
}
/* Credential type panel comparison function. Tabs are sorted based
on the following criteria:
1) By ordinal - Panels with ordinal -1 will be ranked after panels
whose ordinal is not -1.
2) By name - Case insensitive comparison of the name. If the panel
does not have a name (i.e. the ->name member is NULL, it will be
ranked after panels which have a name.
*/
static int __cdecl
nc_tab_sort_func(const void * v1, const void * v2)
{
/* v1 and v2 and of type : khui_new_creds_by_type ** */
khui_new_creds_by_type *t1, *t2;
t1 = *((khui_new_creds_by_type **) v1);
t2 = *((khui_new_creds_by_type **) v2);
if(t1->ordinal != -1) {
if(t2->ordinal != -1) {
if(t1->ordinal == t2->ordinal) {
if (t1->name && t2->name)
return _wcsicmp(t1->name, t2->name);
else if (t1->name)
return -1;
else if (t2->name)
return 1;
else
return 0;
} else {
/* safe to convert to an int here */
return (int) (t1->ordinal - t2->ordinal);
}
} else
return -1;
} else {
if(t2->ordinal != -1)
return 1;
else if (t1->name && t2->name)
return wcscmp(t1->name, t2->name);
else if (t1->name)
return -1;
else if (t2->name)
return 1;
else
return 0;
}
}
static void
nc_notify_types(khui_new_creds * c, UINT uMsg,
WPARAM wParam, LPARAM lParam, BOOL sync)
{
khm_size i;
for(i=0; i<c->n_types; i++) {
if (c->types[i]->hwnd_panel == NULL)
continue;
if (sync)
SendMessage(c->types[i]->hwnd_panel, uMsg, wParam, lParam);
else
PostMessage(c->types[i]->hwnd_panel, uMsg, wParam, lParam);
}
}
static void
nc_clear_password_fields(khui_nc_wnd_data * d)
{
khm_size i;
khm_boolean need_sync = FALSE;
khui_cw_lock_nc(d->nc);
for (i=0; i < d->nc->n_prompts; i++) {
if ((d->nc->prompts[i]->flags & KHUI_NCPROMPT_FLAG_HIDDEN) &&
d->nc->prompts[i]->hwnd_edit) {
SetWindowText(d->nc->prompts[i]->hwnd_edit,
L"");
need_sync = TRUE;
}
}
khui_cw_unlock_nc(d->nc);
if (need_sync) {
khui_cw_sync_prompt_values(d->nc);
}
}
/* used by nc_enable_controls */
struct nc_enum_wnd_data {
khui_nc_wnd_data * d;
khm_boolean enable;
};
static
BOOL CALLBACK
nc_enum_wnd_proc(HWND hwnd,
LPARAM lParam)
{
struct nc_enum_wnd_data * wd;
wd = (struct nc_enum_wnd_data *) lParam;
EnableWindow(hwnd, wd->enable);
return TRUE;
}
static void
nc_enable_controls(khui_nc_wnd_data * d, khm_boolean enable)
{
struct nc_enum_wnd_data wd;
ZeroMemory(&wd, sizeof(wd));
wd.d = d;
wd.enable = enable;
EnumChildWindows(d->dlg_main, nc_enum_wnd_proc, (LPARAM) &wd);
}
#define NC_MAXCCH_CREDTEXT 16384
#define NC_MAXCB_CREDTEXT (NC_MAXCCH_CREDTEXT * sizeof(wchar_t))
static void
nc_update_credtext(khui_nc_wnd_data * d)
{
wchar_t * ctbuf = NULL;
wchar_t * buf;
BOOL okEnable = FALSE;
BOOL validId = FALSE;
HWND hw = NULL;
size_t cch = 0;
ctbuf = PMALLOC(NC_MAXCB_CREDTEXT);
assert(ctbuf != NULL);
LoadString(khm_hInstance, IDS_NC_CREDTEXT_TABS, ctbuf, NC_MAXCCH_CREDTEXT);
StringCchLength(ctbuf, NC_MAXCCH_CREDTEXT, &cch);
buf = ctbuf + cch;
nc_notify_types(d->nc, KHUI_WM_NC_NOTIFY,
MAKEWPARAM(0, WMNC_UPDATE_CREDTEXT), (LPARAM) d->nc, TRUE);
/* hopefully all the types have updated their credential texts */
/* if the dialog is in the mini mode, we have to display
exceptions using a notification. */
if (d->nc->mode == KHUI_NC_MODE_MINI) {
BOOL need_layout = FALSE;
if (d->nc->n_identities == 0) {
/* There are no identities selected. We don't show any
notifications here. */
if (d->notif_type != NC_NOTIFY_NONE) {
nc_notify_clear(d);
need_layout = TRUE;
}
} else {
wchar_t id_name[KCDB_IDENT_MAXCCH_NAME];
wchar_t format[256];
wchar_t msg[ARRAYLENGTH(format) + ARRAYLENGTH(id_name)];
khm_size cbbuf;
khm_int32 flags;
kcdb_identity_get_flags(d->nc->identities[0], &flags);
cbbuf = sizeof(id_name);
kcdb_identity_get_name(d->nc->identities[0], id_name, &cbbuf);
if (flags & KCDB_IDENT_FLAG_INVALID) {
/* identity is invalid */
LoadString(khm_hInstance, IDS_NCN_IDENT_INVALID,
format, ARRAYLENGTH(format));
StringCbPrintf(msg, sizeof(msg), format, id_name);
nc_notify_message(d, KHERR_ERROR, msg);
need_layout = TRUE;
} else if ((flags & KCDB_IDENT_FLAG_VALID) ||
d->nc->subtype == KMSG_CRED_PASSWORD) {
/* special case: If we are going to change the
password, we don't expect the identity provider to
validate the identity in real time. As such, we
assume that the identity is valid. */
/* identity is valid */
if (d->notif_type != NC_NOTIFY_NONE) {
nc_notify_clear(d);
need_layout = TRUE;
}
} else if (flags & KCDB_IDENT_FLAG_UNKNOWN) {
/* unknown state */
LoadString(khm_hInstance, IDS_NCN_IDENT_UNKNOWN,
format, ARRAYLENGTH(format));
StringCbPrintf(msg, sizeof(msg), format, id_name);
nc_notify_message(d, KHERR_WARNING, msg);
need_layout = TRUE;
} else {
/* still checking */
LoadString(khm_hInstance, IDS_NCN_IDENT_CHECKING,
format, ARRAYLENGTH(format));
StringCbPrintf(msg, sizeof(msg), format, id_name);
nc_notify_marquee(d, msg);
need_layout = TRUE;
}
}
if (need_layout) {
nc_layout_main_panel(d);
nc_layout_new_cred_window(d);
}
}
if(d->nc->n_identities == 1) {
wchar_t main_fmt[256];
wchar_t id_fmt[256];
wchar_t id_name[KCDB_IDENT_MAXCCH_NAME];
wchar_t id_string[KCDB_IDENT_MAXCCH_NAME + 256];
khm_size cbbuf;
khm_int32 flags;
LoadString(khm_hInstance, IDS_NC_CREDTEXT_ID_ONE,
main_fmt, (int) ARRAYLENGTH(main_fmt));
cbbuf = sizeof(id_name);
kcdb_identity_get_name(d->nc->identities[0], id_name, &cbbuf);
kcdb_identity_get_flags(d->nc->identities[0], &flags);
if (flags & KCDB_IDENT_FLAG_INVALID) {
LoadString(khm_hInstance, IDS_NC_CREDTEXT_ID_INVALID,
id_fmt, (int) ARRAYLENGTH(id_fmt));
} else if(flags & KCDB_IDENT_FLAG_VALID) {
LoadString(khm_hInstance, IDS_NC_CREDTEXT_ID_VALID,
id_fmt, (int) ARRAYLENGTH(id_fmt));
} else if(flags & KCDB_IDENT_FLAG_UNKNOWN) {
LoadString(khm_hInstance, IDS_NC_CREDTEXT_ID_UNCHECKED,
id_fmt, (int) ARRAYLENGTH(id_fmt));
} else if(d->nc->subtype == KMSG_CRED_NEW_CREDS) {
LoadString(khm_hInstance, IDS_NC_CREDTEXT_ID_CHECKING,
id_fmt, (int) ARRAYLENGTH(id_fmt));
} else {
LoadString(khm_hInstance, IDS_NC_CREDTEXT_ID_UNCHECKED,
id_fmt, (int) ARRAYLENGTH(id_fmt));
}
StringCbPrintf(id_string, sizeof(id_string), id_fmt, id_name);
StringCbPrintf(buf, NC_MAXCB_CREDTEXT - cch*sizeof(wchar_t),
main_fmt, id_string);
if (flags & KCDB_IDENT_FLAG_VALID) {
if (flags & KCDB_IDENT_FLAG_DEFAULT)
LoadString(khm_hInstance, IDS_NC_ID_DEF,
id_string, ARRAYLENGTH(id_string));
else if (d->nc->set_default)
LoadString(khm_hInstance, IDS_NC_ID_WDEF,
id_string, ARRAYLENGTH(id_string));
else
LoadString(khm_hInstance, IDS_NC_ID_NDEF,
id_string, ARRAYLENGTH(id_string));
StringCbCat(buf, NC_MAXCB_CREDTEXT - cch * sizeof(wchar_t),
id_string);
}
} else if(d->nc->n_identities > 1) {
wchar_t *ids_string;
khm_size cb_ids_string;
wchar_t id_name[KCDB_IDENT_MAXCCH_NAME];
wchar_t id_fmt[256];
wchar_t id_string[KCDB_IDENT_MAXCCH_NAME + 256];
wchar_t main_fmt[256];
khm_size cbbuf;
LoadString(khm_hInstance, IDS_NC_CREDTEXT_ID_MANY,
main_fmt, (int) ARRAYLENGTH(main_fmt));
/* we are going to concatenate all the identity names into
a comma separated string */
/* d->nc->n_identities is at least 2 */
ids_string = PMALLOC((KCDB_IDENT_MAXCB_NAME + sizeof(id_fmt)) *
(d->nc->n_identities - 1));
cb_ids_string =
(KCDB_IDENT_MAXCB_NAME + sizeof(id_fmt)) *
(d->nc->n_identities - 1);
assert(ids_string != NULL);
ids_string[0] = 0;
{
khm_size i;
khm_int32 flags;
for(i=1; i<d->nc->n_identities; i++) {
if(i>1) {
StringCbCat(ids_string, cb_ids_string, L",");
}
flags = 0;
cbbuf = sizeof(id_name);
kcdb_identity_get_name(d->nc->identities[i], id_name, &cbbuf);
kcdb_identity_get_flags(d->nc->identities[i], &flags);
if(flags & KCDB_IDENT_FLAG_INVALID) {
LoadString(khm_hInstance, IDS_NC_CREDTEXT_ID_INVALID,
id_fmt, (int) ARRAYLENGTH(id_fmt));
} else if(flags & KCDB_IDENT_FLAG_VALID) {
LoadString(khm_hInstance, IDS_NC_CREDTEXT_ID_VALID,
id_fmt, (int) ARRAYLENGTH(id_fmt));
} else {
LoadString(khm_hInstance, IDS_NC_CREDTEXT_ID_UNCHECKED,
id_fmt, (int) ARRAYLENGTH(id_fmt));
}
StringCbPrintf(id_string, sizeof(id_string), id_fmt, id_name);
StringCbCat(ids_string, cb_ids_string, id_string);
}
cbbuf = sizeof(id_name);
kcdb_identity_get_name(d->nc->identities[0], id_name, &cbbuf);
kcdb_identity_get_flags(d->nc->identities[0], &flags);
if(flags & KCDB_IDENT_FLAG_INVALID) {
LoadString(khm_hInstance, IDS_NC_CREDTEXT_ID_INVALID,
id_fmt, (int) ARRAYLENGTH(id_fmt));
} else if(flags & KCDB_IDENT_FLAG_VALID) {
LoadString(khm_hInstance, IDS_NC_CREDTEXT_ID_VALID,
id_fmt, (int) ARRAYLENGTH(id_fmt));
} else {
LoadString(khm_hInstance, IDS_NC_CREDTEXT_ID_UNCHECKED,
id_fmt, (int) ARRAYLENGTH(id_fmt));
}
StringCbPrintf(id_string, sizeof(id_string), id_fmt, id_name);
StringCbPrintf(buf, NC_MAXCB_CREDTEXT - cch*sizeof(wchar_t),
main_fmt, id_string, ids_string);
PFREE(ids_string);
}
} else {
LoadString(khm_hInstance, IDS_NC_CREDTEXT_ID_NONE,
buf, (int)(NC_MAXCCH_CREDTEXT - cch));
}
/* now, append the credtext string from each of the cred types */
{
khm_size i;
size_t cb;
wchar_t * buf;
cb = NC_MAXCB_CREDTEXT;
buf = ctbuf;
for(i=0; i<d->nc->n_types; i++) {
if(d->nc->types[i]->credtext != NULL) {
StringCbCatEx(buf, cb,
d->nc->types[i]->credtext,
&buf, &cb,
0);
}
}
}
SetDlgItemText(d->dlg_main, IDC_NC_CREDTEXT, ctbuf);
PFREE(ctbuf);
/* so depending on whether the primary identity was found to be
invalid, we need to disable the Ok button and set the title to
reflect this */
if(d->nc->n_identities > 0) {
khm_int32 flags = 0;
if(KHM_SUCCEEDED(kcdb_identity_get_flags(d->nc->identities[0],
&flags)) &&
(flags & KCDB_IDENT_FLAG_VALID)) {
validId = TRUE;
}
}
if (d->nc->window_title == NULL) {
if(validId) {
wchar_t wpostfix[256];
wchar_t wtitle[KCDB_IDENT_MAXCCH_NAME + 256];
khm_size cbsize;
cbsize = sizeof(wtitle);
kcdb_identity_get_name(d->nc->identities[0], wtitle, &cbsize);
if (d->nc->subtype == KMSG_CRED_PASSWORD)
LoadString(khm_hInstance, IDS_WTPOST_PASSWORD,
wpostfix, (int) ARRAYLENGTH(wpostfix));
else
LoadString(khm_hInstance, IDS_WTPOST_NEW_CREDS,
wpostfix, (int) ARRAYLENGTH(wpostfix));
StringCbCat(wtitle, sizeof(wtitle), wpostfix);
SetWindowText(d->nc->hwnd, wtitle);
} else {
wchar_t wtitle[256];
if (d->nc->subtype == KMSG_CRED_PASSWORD)
LoadString(khm_hInstance, IDS_WT_PASSWORD,
wtitle, (int) ARRAYLENGTH(wtitle));
else
LoadString(khm_hInstance, IDS_WT_NEW_CREDS,
wtitle, (int) ARRAYLENGTH(wtitle));
SetWindowText(d->nc->hwnd, wtitle);
}
}
if (!(d->nc->response & KHUI_NC_RESPONSE_PROCESSING)) {
if(validId ||
d->nc->subtype == KMSG_CRED_PASSWORD) {
/* TODO: check if all the required fields have valid values
before enabling the Ok button */
okEnable = TRUE;
}
hw = GetDlgItem(d->dlg_main, IDOK);
EnableWindow(hw, okEnable);
hw = GetDlgItem(d->dlg_bb, IDOK);
EnableWindow(hw, okEnable);
}
}
static void
nc_layout_new_cred_window(khui_nc_wnd_data * ncd) {
khui_new_creds * c;
RECT r_main;
RECT r_ncdialog;
HDWP hdefer;
c = ncd->nc;
r_main.left = 0;
r_main.top = 0;
r_main.right = NCDLG_WIDTH;
r_main.bottom = NCDLG_HEIGHT;
MapDialogRect(ncd->dlg_main, &r_main);
hdefer = BeginDeferWindowPos(5);
if (c->mode == KHUI_NC_MODE_MINI) {
if (IsWindowVisible(ncd->tab_wnd)) {
DeferWindowPos(hdefer,
ncd->tab_wnd, NULL,
0, 0, 0, 0,
SWP_HIDEWINDOW |
SWP_NOMOVE | SWP_NOOWNERZORDER |
SWP_NOSIZE | SWP_NOZORDER);
}
if (IsWindowVisible(ncd->dlg_bb)) {
DeferWindowPos(hdefer,
ncd->dlg_bb, NULL,
0, 0, 0, 0,
SWP_HIDEWINDOW |
SWP_NOMOVE | SWP_NOOWNERZORDER |
SWP_NOSIZE | SWP_NOZORDER);
}
DeferWindowPos(hdefer, ncd->dlg_main, NULL,
r_main.left, r_main.top,
r_main.right - r_main.left,
r_main.bottom - r_main.top,
SWP_NOACTIVATE | SWP_NOOWNERZORDER |
SWP_NOZORDER | SWP_SHOWWINDOW);
/* note that the ncd->r_main.bottom may not be the same as
r_main.bottom because ncd->r_main.bottom is set dynamically
depending on custom controls. ncd->r_main is valid only
once nc_layout_main_panel() is called.*/
CopyRect(&ncd->r_required, &ncd->r_main);
} else {
RECT r_tabctrl;
RECT r_displayarea;
RECT r_bbar;
khm_size i;
/* calculate the size of the tab control so that it fits
snugly around the expanded main panel. */
CopyRect(&r_tabctrl, &r_main);
TabCtrl_AdjustRect(ncd->tab_wnd, TRUE, &r_tabctrl);
if (r_tabctrl.left < 0 ||
r_tabctrl.top < 0) {
OffsetRect(&r_tabctrl,
(r_tabctrl.left < 0)? -r_tabctrl.left : 0,
(r_tabctrl.top < 0)? -r_tabctrl.top : 0);
}
#ifdef DEBUG
assert(r_tabctrl.left == 0);
assert(r_tabctrl.top == 0);
#endif
OffsetRect(&r_tabctrl, 0, ncd->r_area.top);
/* and now calculate the rectangle where the main panel should
be inside the tab control. */
CopyRect(&r_displayarea, &r_tabctrl);
TabCtrl_AdjustRect(ncd->tab_wnd, FALSE, &r_displayarea);
DeferWindowPos(hdefer,
ncd->tab_wnd, HWND_BOTTOM,
r_tabctrl.left, r_tabctrl.top,
r_tabctrl.right - r_tabctrl.left,
r_tabctrl.bottom - r_tabctrl.top,
SWP_NOACTIVATE | SWP_NOOWNERZORDER |
SWP_SHOWWINDOW);
/* we have to place the button bar just to the right of the
tab panel. */
r_bbar.left = 0;
r_bbar.top = 0;
r_bbar.right = NCDLG_BBAR_WIDTH;
r_bbar.bottom = NCDLG_BBAR_HEIGHT;
MapDialogRect(ncd->dlg_main, &r_bbar);
OffsetRect(&r_bbar, r_tabctrl.right, 0);
DeferWindowPos(hdefer,
ncd->dlg_bb, NULL,
r_bbar.left, r_bbar.top,
r_bbar.right - r_bbar.left,
r_bbar.bottom - r_bbar.top,
SWP_NOACTIVATE | SWP_NOOWNERZORDER |
SWP_NOZORDER | SWP_SHOWWINDOW);
/* move the main panel inside the tab control... */
DeferWindowPos(hdefer,
ncd->dlg_main, NULL,
r_displayarea.left, r_displayarea.top,
r_displayarea.right - r_displayarea.left,
r_displayarea.bottom - r_displayarea.top,
SWP_NOACTIVATE | SWP_NOOWNERZORDER |
SWP_NOZORDER |
(ncd->current_panel == 0 ? SWP_SHOWWINDOW : SWP_HIDEWINDOW));
/* and also move all the credential type panels (if they have
been created) inside the tab control too. */
khui_cw_lock_nc(c);
for (i=0; i < c->n_types; i++) {
if (c->types[i]->hwnd_panel != NULL) {
DeferWindowPos(hdefer,
c->types[i]->hwnd_panel, NULL,
r_displayarea.left, r_displayarea.top,
r_displayarea.right - r_displayarea.left,
r_displayarea.bottom - r_displayarea.top,
SWP_NOACTIVATE | SWP_NOOWNERZORDER |
SWP_NOZORDER |
(ncd->current_panel == c->types[i]->ordinal ?
SWP_SHOWWINDOW : SWP_HIDEWINDOW));
}
}
khui_cw_unlock_nc(c);
/* then update the required size of the new credentials
dialog. */
ncd->r_required.left = 0;
ncd->r_required.top = 0;
ncd->r_required.right = r_bbar.right;
ncd->r_required.bottom = max(r_tabctrl.bottom, r_bbar.bottom) + ncd->r_area.top;
}
/* commit all the window moves, resizes and hides/shows we did*/
EndDeferWindowPos(hdefer);
/* now we have to see if the client area of the new credentials
window is the right size. */
GetClientRect(c->hwnd, &r_ncdialog);
if (
((r_ncdialog.right - r_ncdialog.left !=
ncd->r_required.right - ncd->r_required.left)
||
(r_ncdialog.bottom - r_ncdialog.top !=
ncd->r_required.bottom - ncd->r_required.top))
&&
/* we don't bother if the new creds window is already in the
process of changing the size. */
!ncd->size_changing) {
/* if not, notify the window that the size needs adjusting. */
if (IsWindowVisible(c->hwnd))
PostMessage(c->hwnd, KHUI_WM_NC_NOTIFY,
MAKEWPARAM(0, WMNC_UPDATE_LAYOUT), 0);
else
SendMessage(c->hwnd, KHUI_WM_NC_NOTIFY,
MAKEWPARAM(0, WMNC_UPDATE_LAYOUT), 0);
}
}
#define CW_PARAM DWLP_USER
static LRESULT
nc_handle_wm_create(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
LPCREATESTRUCT lpc;
khui_new_creds * c;
khui_nc_wnd_data * ncd;
int x, y;
int width, height;
RECT r;
HFONT hf_main;
lpc = (LPCREATESTRUCT) lParam;
ncd = PMALLOC(sizeof(*ncd));
ZeroMemory(ncd, sizeof(*ncd));
c = (khui_new_creds *) lpc->lpCreateParams;
ncd->nc = c;
c->hwnd = hwnd;
#ifdef DEBUG
assert(c->subtype == KMSG_CRED_NEW_CREDS ||
c->subtype == KMSG_CRED_PASSWORD);
#endif
#pragma warning(push)
#pragma warning(disable: 4244)
SetWindowLongPtr(hwnd, CW_PARAM, (LONG_PTR) ncd);
#pragma warning(pop)
/* first, create the tab control that will house the main dialog
panel as well as the plug-in specific panels */
ncd->tab_wnd = CreateWindowEx(0, /* extended style */
WC_TABCONTROL,
L"TabControloxxrz", /* window name */
TCS_HOTTRACK | TCS_RAGGEDRIGHT |
TCS_SINGLELINE | TCS_TABS |
WS_CHILD | WS_TABSTOP | WS_CLIPSIBLINGS,
0, 0, 100, 100, /* x,y,width height.
We'll be changing
these later
anyway. */
hwnd,
(HMENU) IDC_NC_TABS,
NULL,
0);
#ifdef DEBUG
assert(ncd->tab_wnd != NULL);
#endif
/* try to create the main dialog panel */
ncd->dlg_main = CreateDialogParam(khm_hInstance,
MAKEINTRESOURCE(IDD_NC_NEWCRED),
hwnd,
nc_common_dlg_proc,
(LPARAM) ncd);
#ifdef DEBUG
assert(ncd->dlg_main != NULL);
#endif
hf_main = (HFONT) SendMessage(ncd->dlg_main, WM_GETFONT, 0, 0);
if (hf_main)
SendMessage(ncd->tab_wnd, WM_SETFONT, (WPARAM) hf_main, FALSE);
#if _WIN32_WINNT >= 0x0501
EnableThemeDialogTexture(ncd->dlg_main,
ETDT_ENABLETAB);
#endif
{
RECT r_main;
RECT r_area;
RECT r_row;
HWND hw;
/* During the operation of the new credentials window, we will
need to dynamically change the layout of the controls as a
result of custom prompting from credentials providers and
identity selectors from identity providers. In order to
guide the dynamic layout, we pick out a few metrics from
the dialog template for the main panel. The metrics come
from hidden STATIC controls in the dialog template. */
GetWindowRect(ncd->dlg_main, &r_main);
/* IDC_NC_TPL_PANEL spans the full extent of the dialog that
we can populate with custom controls. */
hw = GetDlgItem(ncd->dlg_main, IDC_NC_TPL_PANEL);
#ifdef DEBUG
assert(hw);
#endif
GetWindowRect(hw, &r_area);
OffsetRect(&r_area,-r_main.left, -r_main.top);
CopyRect(&ncd->r_area, &r_area);
/* IDC_NC_TPL_ROW spans the extent of a row of normal sized
custom controls. A row of custom controls typicall consist
of a text label and an input control. */
hw = GetDlgItem(ncd->dlg_main, IDC_NC_TPL_ROW);
#ifdef DEBUG
assert(hw);
#endif
GetWindowRect(hw, &r);
CopyRect(&r_row, &r);
OffsetRect(&r,-r.left, -r.top);
CopyRect(&ncd->r_row, &r);
/* IDC_NC_TPL_LABEL spans the extent that a normal sized
label. The control overlaps IDC_NC_TPL_ROW so we can get
coordinates relative to the row extents. */
hw = GetDlgItem(ncd->dlg_main, IDC_NC_TPL_LABEL);
#ifdef DEBUG
assert(hw);
#endif
GetWindowRect(hw, &r);
OffsetRect(&r,-r_row.left, -r_row.top);
CopyRect(&ncd->r_n_label, &r);
/* IDC_NC_TPL_INPUT spans the extent of a normal sized input
control in a custom control row. The control overlaps
IDC_NC_TPL_ROW so we can get relative coordinates. */
hw = GetDlgItem(ncd->dlg_main, IDC_NC_TPL_INPUT);
#ifdef DEBUG
assert(hw);
#endif
GetWindowRect(hw, &r);
OffsetRect(&r, -r_row.left, -r_row.top);
CopyRect(&ncd->r_n_input, &r);
/* IDC_NC_TPL_ROW_LG spans the extent of a row of large sized
controls. */
hw = GetDlgItem(ncd->dlg_main, IDC_NC_TPL_ROW_LG);
#ifdef DEBUG
assert(hw);
#endif
GetWindowRect(hw, &r_row);
/* IDC_NC_TPL_LABEL_LG is a large sized label. The control
overlaps IDC_NC_TPL_ROW_LG. */
hw = GetDlgItem(ncd->dlg_main, IDC_NC_TPL_LABEL_LG);
#ifdef DEBUG
assert(hw);
#endif
GetWindowRect(hw, &r);
OffsetRect(&r, -r_row.left, -r_row.top);
CopyRect(&ncd->r_e_label, &r);
/* IDC_NC_TPL_INPUT_LG is a large sized input control.
Overlaps IDC_NC_TPL_ROW_LG. */
hw = GetDlgItem(ncd->dlg_main, IDC_NC_TPL_INPUT_LG);
#ifdef DEBUG
assert(hw);
#endif
GetWindowRect(hw, &r);
OffsetRect(&r, -r_row.left, -r_row.top);
CopyRect(&ncd->r_e_input, &r);
CopyRect(&ncd->r_credtext, &ncd->r_area);
CopyRect(&ncd->r_idspec, &ncd->r_area);
ncd->r_idspec.bottom = ncd->r_idspec.top;
/* And finally the credential text window. The only metric we
take from here is the Y coordinate of the bottom of the
control since the actual size and position of the
credentials window will change depending on the custom
controls being displayed. */
hw = GetDlgItem(ncd->dlg_main, IDC_NC_CREDTEXT);
#ifdef DEBUG
assert(hw);
#endif
GetWindowRect(hw, &r);
OffsetRect(&r, -r_main.left, -r_main.top);
ncd->r_credtext.bottom = r.bottom;
}
/* if the mode is 'mini'*/
r.left = 0;
r.top = 0;
if(c->mode == KHUI_NC_MODE_MINI) {
r.right = NCDLG_WIDTH;
r.bottom = NCDLG_HEIGHT;
} else {
r.right = NCDLG_WIDTH + NCDLG_BBAR_WIDTH;
r.bottom = NCDLG_BBAR_HEIGHT;
}
MapDialogRect(ncd->dlg_main, &r);
/* position the new credentials dialog */
width = r.right - r.left;
height = r.bottom - r.top;
/* adjust width and height to accomodate NC area */
{
RECT wr,cr;
GetWindowRect(hwnd, &wr);
GetClientRect(hwnd, &cr);
/* the non-client and client areas have already been calculated
at this point. We just use the difference to adjust the width
and height */
width += (wr.right - wr.left) - (cr.right - cr.left);
height += (wr.bottom - wr.top) - (cr.bottom - cr.top);
}
/* if the parent window is visible, we center the new credentials
dialog over the parent. Otherwise, we center it on the primary
display. */
if (IsWindowVisible(lpc->hwndParent)) {
GetWindowRect(lpc->hwndParent, &r);
} else {
if(!SystemParametersInfo(SPI_GETWORKAREA, 0, (PVOID) &r, 0)) {
/* failover to the window coordinates */
GetWindowRect(lpc->hwndParent, &r);
}
}
x = (r.right + r.left)/2 - width / 2;
y = (r.top + r.bottom)/2 - height / 2;
/* we want to check if the entire rect is visible on the screen.
If the main window is visible and in basic mode, we might end
up with a rect that is partially outside the screen. */
{
RECT r;
SetRect(&r, x, y, x + width, y + height);
khm_adjust_window_dimensions_for_display(&r, 0);
x = r.left;
y = r.top;
width = r.right - r.left;
height = r.bottom - r.top;
}
MoveWindow(hwnd, x, y, width, height, FALSE);
ncd->dlg_bb = CreateDialogParam(khm_hInstance,
MAKEINTRESOURCE(IDD_NC_BBAR),
hwnd,
nc_common_dlg_proc,
(LPARAM) ncd);
#ifdef DEBUG
assert(ncd->dlg_bb);
#endif
/* Call the identity provider callback to set the identity
selector controls. These controls need to be there before we
layout the main panel. */
c->ident_cb(c, WMNC_IDENT_INIT, NULL, 0, 0, (LPARAM) ncd->dlg_main);
if (c->mode == KHUI_NC_MODE_EXPANDED) {
SendMessage(ncd->dlg_main, KHUI_WM_NC_NOTIFY,
MAKEWPARAM(0, WMNC_DIALOG_EXPAND), 0);
} else {
/* we don't call nc_layout_main_panel() if the dialog is
expanded because posting WMNC_DIALOG_EXPAND to the main
panel results in it getting called anyway. */
nc_layout_main_panel(ncd);
}
nc_layout_new_cred_window(ncd);
/* add this to the dialog chain */
khm_add_dialog(hwnd);
return TRUE;
}
/* add a control row supplied by an identity provider */
static void
nc_add_control_row(khui_nc_wnd_data * d,
HWND label,
HWND input,
khui_control_size size)
{
RECT r_row;
RECT r_label;
RECT r_input;
HFONT hf;
HDWP hdefer;
hf = (HFONT) SendMessage(d->dlg_main, WM_GETFONT, 0, 0);
SendMessage(label, WM_SETFONT, (WPARAM) hf, FALSE);
SendMessage(input, WM_SETFONT, (WPARAM) hf, FALSE);
CopyRect(&r_row, &d->r_row);
OffsetRect(&r_row, d->r_idspec.left, d->r_idspec.bottom);
if (size == KHUI_CTRLSIZE_SMALL) {
CopyRect(&r_label, &d->r_n_label);
CopyRect(&r_input, &d->r_n_input);
OffsetRect(&r_label, r_row.left, r_row.top);
OffsetRect(&r_input, r_row.left, r_row.top);
} else if (size == KHUI_CTRLSIZE_HALF) {
CopyRect(&r_label, &d->r_e_label);
CopyRect(&r_input, &d->r_e_input);
OffsetRect(&r_label, r_row.left, r_row.top);
OffsetRect(&r_input, r_row.left, r_row.top);
} else if (size == KHUI_CTRLSIZE_FULL) {
CopyRect(&r_label, &d->r_n_label);
r_label.right = d->r_row.right;
CopyRect(&r_input, &d->r_n_input);
OffsetRect(&r_input, r_row.left, r_row.top);
OffsetRect(&r_input, 0, r_input.bottom);
r_row.bottom += r_input.bottom;
OffsetRect(&r_label, r_row.left, r_row.top);
} else {
SetRectEmpty(&r_label);
SetRectEmpty(&r_input);
#ifdef DEBUG
assert(FALSE);
#endif
return;
}
hdefer = BeginDeferWindowPos(2);
if (label)
DeferWindowPos(hdefer, label,
((d->hwnd_last_idspec != NULL)?
d->hwnd_last_idspec:
HWND_TOP),
r_label.left, r_label.top,
r_label.right - r_label.left,
r_label.bottom - r_label.top,
SWP_NOACTIVATE | SWP_NOOWNERZORDER);
if (input)
DeferWindowPos(hdefer, input,
(label ? label : ((d->hwnd_last_idspec != NULL)?
d->hwnd_last_idspec:
HWND_TOP)),
r_input.left, r_input.top,
r_input.right - r_input.left,
r_input.bottom - r_input.top,
SWP_NOACTIVATE | SWP_NOOWNERZORDER);
EndDeferWindowPos(hdefer);
d->hwnd_last_idspec = (input ? input : label);
d->r_idspec.bottom = r_row.bottom;
/* we don't update the layout of the main panel yet, since these
control additions happen before the main panel is displayed. A
call to nc_layout_main_panel() will be made before the main
panel is shown anyway. */
}
static LRESULT
nc_handle_wm_destroy(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
khui_nc_wnd_data * d;
/* remove self from dialog chain */
khm_del_dialog(hwnd);
d = (khui_nc_wnd_data *)(LONG_PTR) GetWindowLongPtr(hwnd, CW_PARAM);
if (d == NULL)
return TRUE;
d->nc->ident_cb(d->nc, WMNC_IDENT_EXIT, NULL, 0, 0, 0);
if (d->hwnd_notif_label)
DestroyWindow(d->hwnd_notif_label);
if (d->hwnd_notif_aux)
DestroyWindow(d->hwnd_notif_aux);
if(d->dlg_bb)
DestroyWindow(d->dlg_bb);
if(d->dlg_main)
DestroyWindow(d->dlg_main);
d->dlg_bb = NULL;
d->dlg_main = NULL;
PFREE(d);
SetWindowLongPtr(hwnd, CW_PARAM, 0);
return TRUE;
}
static LRESULT
nc_handle_wm_command(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
khui_nc_wnd_data * d;
d = (khui_nc_wnd_data *)(LONG_PTR) GetWindowLongPtr(hwnd, CW_PARAM);
if (d == NULL)
return 0;
switch(HIWORD(wParam)) {
case BN_CLICKED:
switch(LOWORD(wParam)) {
case IDOK:
d->nc->result = KHUI_NC_RESULT_PROCESS;
/* fallthrough */
case IDCANCEL:
/* the default value for d->nc->result is set to
KHUI_NC_RESULT_CANCEL */
d->nc->response = KHUI_NC_RESPONSE_PROCESSING;
nc_enable_controls(d, FALSE);
nc_notify_types(d->nc,
KHUI_WM_NC_NOTIFY,
MAKEWPARAM(0,WMNC_DIALOG_PREPROCESS),
(LPARAM) d->nc,
TRUE);
khui_cw_sync_prompt_values(d->nc);
khm_cred_dispatch_process_message(d->nc);
/* we won't know whether to abort or not until we get
feedback from the plugins, even if the command was
to cancel */
{
HWND hw;
hw = GetDlgItem(d->dlg_main, IDOK);
EnableWindow(hw, FALSE);
hw = GetDlgItem(d->dlg_main, IDCANCEL);
EnableWindow(hw, FALSE);
hw = GetDlgItem(d->dlg_main, IDC_NC_ADVANCED);
EnableWindow(hw, FALSE);
hw = GetDlgItem(d->dlg_bb, IDOK);
EnableWindow(hw, FALSE);
hw = GetDlgItem(d->dlg_bb, IDCANCEL);
EnableWindow(hw, FALSE);
}
return FALSE;
case IDC_NC_HELP:
khm_html_help(hwnd, NULL, HH_HELP_CONTEXT, IDH_ACTION_NEW_ID);
return FALSE;
case IDC_NC_BASIC:
case IDC_NC_ADVANCED:
/* the Options button in the main window was clicked. we
respond by expanding the dialog. */
PostMessage(hwnd, KHUI_WM_NC_NOTIFY,
MAKEWPARAM(0, WMNC_DIALOG_EXPAND), 0);
return FALSE;
case IDC_NC_CREDTEXT: /* credtext link activated */
{
khui_htwnd_link * l;
wchar_t sid[KHUI_MAXCCH_HTLINK_FIELD];
wchar_t sparam[KHUI_MAXCCH_HTLINK_FIELD];
wchar_t * colon;
l = (khui_htwnd_link *) lParam;
/* do we have a valid link? */
if(l->id == NULL || l->id_len >= ARRAYLENGTH(sid))
return TRUE; /* nope */
StringCchCopyN(sid, ARRAYLENGTH(sid), l->id, l->id_len);
sid[l->id_len] = L'\0'; /* just make sure */
if(l->param != NULL &&
l->param_len < ARRAYLENGTH(sparam) &&
l->param_len > 0) {
StringCchCopyN(sparam, ARRAYLENGTH(sparam),
l->param, l->param_len);
sparam[l->param_len] = L'\0';
} else {
sparam[0] = L'\0';
}
/* If the ID is of the form '<credtype>:<link_tag>'
and <credtype> is a valid name of a credentials
type that is participating in the credentials
acquisition process, then we forward the message to
the panel that is providing the UI for that cred
type. We also switch to that panel first, unless
the link is of the form '<credtype>:!<link_tag>'. */
colon = wcschr(sid, L':');
if (colon != NULL) {
khm_int32 credtype;
khui_new_creds_by_type * t;
*colon = L'\0';
if (KHM_SUCCEEDED(kcdb_credtype_get_id(sid, &credtype)) &&
KHM_SUCCEEDED(khui_cw_find_type(d->nc, credtype, &t))){
*colon = L':';
if (t->ordinal != d->current_panel &&
*(colon + 1) != L'!')
PostMessage(hwnd,
KHUI_WM_NC_NOTIFY,
MAKEWPARAM(t->ordinal,
WMNC_DIALOG_SWITCH_PANEL),
0);
return SendMessage(t->hwnd_panel,
KHUI_WM_NC_NOTIFY,
MAKEWPARAM(0, WMNC_CREDTEXT_LINK),
lParam);
} else {
*colon = L':';
}
}
/* if it was for us, then we need to process the message */
if(!_wcsicmp(sid, CTLINKID_SWITCH_PANEL)) {
khm_int32 credtype;
khui_new_creds_by_type * t;
if (KHM_SUCCEEDED(kcdb_credtype_get_id(sparam,
&credtype)) &&
KHM_SUCCEEDED(khui_cw_find_type(d->nc,
credtype, &t))) {
if (t->ordinal != d->current_panel)
PostMessage(hwnd,
KHUI_WM_NC_NOTIFY,
MAKEWPARAM(t->ordinal,
WMNC_DIALOG_SWITCH_PANEL),
0);
}
} else if (!_wcsicmp(sid, L"NotDef")) {
d->nc->set_default = FALSE;
nc_update_credtext(d);
} else if (!_wcsicmp(sid, L"MakeDef")) {
d->nc->set_default = TRUE;
nc_update_credtext(d);
}
}
return FALSE;
#if 0
case NC_BN_SET_DEF_ID:
{
d->nc->set_default =
(IsDlgButtonChecked(d->dlg_main, NC_BN_SET_DEF_ID)
== BST_CHECKED);
}
return FALSE;
#endif
}
break;
}
return TRUE;
}
static LRESULT nc_handle_wm_moving(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
khui_nc_wnd_data * d;
d = (khui_nc_wnd_data *)(LONG_PTR) GetWindowLongPtr(hwnd, CW_PARAM);
if (d == NULL)
return FALSE;
nc_notify_types(d->nc, KHUI_WM_NC_NOTIFY,
MAKEWPARAM(0, WMNC_DIALOG_MOVE), (LPARAM) d->nc, TRUE);
return FALSE;
}
static LRESULT nc_handle_wm_nc_notify(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
khui_nc_wnd_data * d;
int id;
d = (khui_nc_wnd_data *)(LONG_PTR) GetWindowLongPtr(hwnd, CW_PARAM);
if (d == NULL)
return FALSE;
switch(HIWORD(wParam)) {
case WMNC_DIALOG_SWITCH_PANEL:
id = LOWORD(wParam);
if(id >= 0 && id <= (int) d->nc->n_types) {
/* one of the tab buttons were pressed */
if(d->current_panel == id) {
return TRUE; /* nothing to do */
}
d->current_panel = id;
TabCtrl_SetCurSel(d->tab_wnd, id);
}
if(d->nc->mode == KHUI_NC_MODE_EXPANDED) {
nc_layout_new_cred_window(d);
return TRUE;
}
/*else*/
/* fallthrough */
case WMNC_DIALOG_EXPAND:
/* we are switching from basic to advanced or vice versa */
if (d->nc->mode == KHUI_NC_MODE_EXPANDED) {
if (d->current_panel != 0) {
d->current_panel = 0;
TabCtrl_SetCurSel(d->tab_wnd, 0);
nc_layout_new_cred_window(d);
}
d->nc->mode = KHUI_NC_MODE_MINI;
} else {
d->nc->mode = KHUI_NC_MODE_EXPANDED;
}
/* if we are switching to the advanced mode, we clear any
notifications because we now have a credential text area
for that. */
if (d->nc->mode == KHUI_NC_MODE_EXPANDED)
nc_notify_clear(d);
nc_layout_main_panel(d);
nc_layout_new_cred_window(d);
break;
case WMNC_DIALOG_SETUP:
if(d->nc->n_types > 0) {
khm_size i;
for(i=0; i < d->nc->n_types;i++) {
if (d->nc->types[i]->dlg_proc == NULL) {
d->nc->types[i]->hwnd_panel = NULL;
} else {
/* Create the dialog panel */
d->nc->types[i]->hwnd_panel =
CreateDialogParam(d->nc->types[i]->h_module,
d->nc->types[i]->dlg_template,
d->nc->hwnd,
d->nc->types[i]->dlg_proc,
(LPARAM) d->nc);
#ifdef DEBUG
assert(d->nc->types[i]->hwnd_panel);
#endif
#if _WIN32_WINNT >= 0x0501
if (d->nc->types[i]->hwnd_panel) {
EnableThemeDialogTexture(d->nc->types[i]->hwnd_panel,
ETDT_ENABLETAB);
}
#endif
}
}
}
break;
case WMNC_DIALOG_ACTIVATE:
{
wchar_t wname[KCDB_MAXCCH_NAME];
TCITEM tabitem;
khm_int32 t;
/* About to activate the window. We should add all the
panels to the tab control. */
#ifdef DEBUG
assert(d->tab_wnd != NULL);
#endif
ZeroMemory(&tabitem, sizeof(tabitem));
tabitem.mask = TCIF_PARAM | TCIF_TEXT;
LoadString(khm_hInstance, IDS_NC_IDENTITY,
wname, ARRAYLENGTH(wname));
tabitem.pszText = wname;
tabitem.lParam = 0; /* ordinal */
TabCtrl_InsertItem(d->tab_wnd, 0, &tabitem);
khui_cw_lock_nc(d->nc);
if(d->nc->n_types > 0) {
khm_size i;
/* We should sort the tabs first. See
nc_tab_sort_func() for sort criteria. */
qsort(d->nc->types,
d->nc->n_types,
sizeof(*(d->nc->types)),
nc_tab_sort_func);
for(i=0; i < d->nc->n_types;i++) {
d->nc->types[i]->ordinal = i + 1;
if(d->nc->types[i]->name)
tabitem.pszText = d->nc->types[i]->name;
else {
khm_size cbsize;
cbsize = sizeof(wname);
if(KHM_FAILED
(kcdb_credtype_describe
(d->nc->types[i]->type,
wname,
&cbsize,
KCDB_TS_SHORT))) {
#ifdef DEBUG
assert(FALSE);
#endif
wname[0] = L'\0';
}
tabitem.pszText = wname;
}
tabitem.lParam = d->nc->types[i]->ordinal;
TabCtrl_InsertItem(d->tab_wnd, d->nc->types[i]->ordinal,
&tabitem);
}
}
khui_cw_unlock_nc(d->nc);
nc_update_credtext(d);
TabCtrl_SetCurSel(d->tab_wnd, 0); /* the first selected
tab is the main
panel. */
/* we don't enable animations until a specific timeout
elapses after showing the window. We don't need to
animate any size changes if the user has barely had a
chance to notice the original size. This prevents the
new cred window from appearing in an animated state. */
SetTimer(hwnd, NC_TIMER_ENABLEANIMATE, ENABLEANIMATE_TIMEOUT, NULL);
ShowWindow(hwnd, SW_SHOWNORMAL);
/* bring the window to the top, if necessary */
if (KHM_SUCCEEDED(khc_read_int32(NULL,
L"CredWindow\\Windows\\NewCred\\ForceToTop",
&t)) &&
t != 0) {
BOOL sfw = FALSE;
/* it used to be that the above condition also called
!khm_is_dialog_active() to find out whether there
was a dialog active. If there was, we wouldn't try
to bring the new cred window to the foreground. But
that was not the behavior we want. */
/* if the main window is not visible, then the SetWindowPos()
call is sufficient to bring the new creds window to the
top. However, if the main window is visible but not
active, the main window needs to be activated before a
child window can be activated. */
SetActiveWindow(hwnd);
sfw = SetForegroundWindow(hwnd);
if (!sfw) {
FLASHWINFO fi;
ZeroMemory(&fi, sizeof(fi));
fi.cbSize = sizeof(fi);
fi.hwnd = hwnd;
fi.dwFlags = FLASHW_ALL;
fi.uCount = 3;
fi.dwTimeout = 0; /* use the default cursor blink rate */
FlashWindowEx(&fi);
d->flashing_enabled = TRUE;
}
} else {
SetFocus(hwnd);
}
if (d->nc->n_identities == 0)
break;
/* else */
/* fallthrough */
}
case WMNC_IDENTITY_CHANGE:
{
BOOL okEnable = FALSE;
nc_notify_types(d->nc, KHUI_WM_NC_NOTIFY,
MAKEWPARAM(0, WMNC_IDENTITY_CHANGE), (LPARAM) d->nc,
TRUE);
if (d->nc->subtype == KMSG_CRED_NEW_CREDS &&
d->nc->n_identities > 0 &&
d->nc->identities[0]) {
khm_int32 f = 0;
kcdb_identity_get_flags(d->nc->identities[0], &f);
if (!(f & KCDB_IDENT_FLAG_DEFAULT)) {
d->nc->set_default = FALSE;
}
}
nc_update_credtext(d);
}
break;
case WMNC_TYPE_STATE:
/* fallthrough */
case WMNC_UPDATE_CREDTEXT:
nc_update_credtext(d);
break;
case WMNC_CLEAR_PROMPTS:
{
khm_size i;
khui_cw_lock_nc(d->nc);
if(d->hwnd_banner != NULL) {
DestroyWindow(d->hwnd_banner);
d->hwnd_banner = NULL;
}
if(d->hwnd_name != NULL) {
DestroyWindow(d->hwnd_name);
d->hwnd_name = NULL;
}
for(i=0;i<d->nc->n_prompts;i++) {
if(!(d->nc->prompts[i]->flags &
KHUI_NCPROMPT_FLAG_STOCK)) {
if(d->nc->prompts[i]->hwnd_static != NULL)
DestroyWindow(d->nc->prompts[i]->hwnd_static);
if(d->nc->prompts[i]->hwnd_edit != NULL)
DestroyWindow(d->nc->prompts[i]->hwnd_edit);
}
d->nc->prompts[i]->hwnd_static = NULL;
d->nc->prompts[i]->hwnd_edit = NULL;
}
khui_cw_unlock_nc(d->nc);
SetRectEmpty(&d->r_custprompt);
nc_layout_main_panel(d);
nc_layout_new_cred_window(d);
}
break;
case WMNC_SET_PROMPTS:
{
khm_size i;
int y;
HWND hw, hw_prev;
HFONT hf, hfold;
HDC hdc;
BOOL use_large_lables = FALSE;
/* we assume that WMNC_CLEAR_PROMPTS has already been
received */
#ifdef DEBUG
assert(IsRectEmpty(&d->r_custprompt));
#endif
khui_cw_lock_nc(d->nc);
#if 0
/* special case, we have one prompt and it is a password
prompt. very common */
if(d->nc->n_prompts == 1 &&
d->nc->prompts[0]->type == KHUI_NCPROMPT_TYPE_PASSWORD) {
hw = GetDlgItem(d->dlg_main, IDC_NC_PASSWORD);
EnableWindow(hw, TRUE);
d->nc->prompts[0]->flags |= KHUI_NCPROMPT_FLAG_STOCK;
d->nc->prompts[0]->hwnd_edit = hw;
d->nc->prompts[0]->hwnd_static = NULL; /* don't care */
khui_cw_unlock_nc(d->nc);
break;
}
#endif
/* for everything else */
y = d->r_idspec.bottom;
d->r_custprompt.left = d->r_area.left;
d->r_custprompt.right = d->r_area.right;
d->r_custprompt.top = y;
hf = (HFONT) SendMessage(d->dlg_main, WM_GETFONT, 0, 0);
if (d->nc->pname != NULL) {
hw =
CreateWindowEx
(0,
L"STATIC",
d->nc->pname,
SS_SUNKEN | WS_CHILD,
d->r_area.left, y,
d->r_row.right,
d->r_n_label.bottom - d->r_n_label.top,
d->dlg_main,
NULL,
khm_hInstance,
NULL);
#ifdef DEBUG
assert(hw);
#endif
d->hwnd_name = hw;
SendMessage(hw, WM_SETFONT, (WPARAM)hf, (LPARAM) TRUE);
ShowWindow(hw, SW_SHOW);
y += d->r_n_label.bottom - d->r_n_label.top;
}
if (d->nc->banner != NULL) {
hw =
CreateWindowEx
(0,
L"STATIC",
d->nc->banner,
WS_CHILD,
d->r_area.left, y,
d->r_row.right, d->r_row.bottom,
d->dlg_main,
NULL,
khm_hInstance,
NULL);
#ifdef DEBUG
assert(hw);
#endif
d->hwnd_banner = hw;
SendMessage(hw, WM_SETFONT, (WPARAM)hf, (LPARAM)TRUE);
ShowWindow(hw, SW_SHOW);
y += d->r_row.bottom;
}
hw_prev = d->hwnd_last_idspec;
hdc = GetWindowDC(d->dlg_main);
hfold = SelectObject(hdc,hf);
/* first do a trial run and see if we should use the
larger text labels or not. This is so that all the
labels and input controls align properly. */
for (i=0; i < d->nc->n_prompts; i++) {
if (d->nc->prompts[i]->prompt != NULL) {
SIZE s;
GetTextExtentPoint32(hdc,
d->nc->prompts[i]->prompt,
(int) wcslen(d->nc->prompts[i]->prompt),
&s);
if(s.cx >= d->r_n_label.right - d->r_n_label.left) {
use_large_lables = TRUE;
break;
}
}
}
for(i=0; i<d->nc->n_prompts; i++) {
RECT pr, er;
SIZE s;
int dy;
if(d->nc->prompts[i]->prompt != NULL) {
GetTextExtentPoint32(hdc,
d->nc->prompts[i]->prompt,
(int) wcslen(d->nc->prompts[i]->prompt),
&s);
if(s.cx < d->r_n_label.right - d->r_n_label.left &&
!use_large_lables) {
CopyRect(&pr, &d->r_n_label);
CopyRect(&er, &d->r_n_input);
dy = d->r_row.bottom;
} else if(s.cx <
d->r_e_label.right - d->r_e_label.left) {
CopyRect(&pr, &d->r_e_label);
CopyRect(&er, &d->r_e_input);
dy = d->r_row.bottom;
} else {
/* oops. the prompt doesn't fit in our
controls. we need to use up two lines */
pr.left = 0;
pr.right = d->r_row.right;
pr.top = 0;
pr.bottom = d->r_n_label.bottom -
d->r_n_label.top;
CopyRect(&er, &d->r_n_input);
OffsetRect(&er, 0, pr.bottom);
dy = er.bottom + (d->r_row.bottom -
d->r_n_input.bottom);
}
} else {
SetRectEmpty(&pr);
CopyRect(&er, &d->r_n_input);
dy = d->r_row.bottom;
}
if(IsRectEmpty(&pr)) {
d->nc->prompts[i]->hwnd_static = NULL;
} else {
OffsetRect(&pr, d->r_area.left, y);
hw = CreateWindowEx
(0,
L"STATIC",
d->nc->prompts[i]->prompt,
WS_CHILD,
pr.left, pr.top,
pr.right - pr.left, pr.bottom - pr.top,
d->dlg_main,
NULL,
khm_hInstance,
NULL);
#ifdef DEBUG
assert(hw);
#endif
SendMessage(hw, WM_SETFONT,
(WPARAM) hf, (LPARAM) TRUE);
SetWindowPos(hw, hw_prev,
0, 0, 0, 0,
SWP_NOACTIVATE | SWP_NOMOVE |
SWP_NOOWNERZORDER | SWP_NOSIZE |
SWP_SHOWWINDOW);
d->nc->prompts[i]->hwnd_static = hw;
hw_prev = hw;
}
OffsetRect(&er, d->r_area.left, y);
hw = CreateWindowEx
(0,
L"EDIT",
(d->nc->prompts[i]->def ?
d->nc->prompts[i]->def : L""),
WS_CHILD | WS_TABSTOP |
WS_BORDER | ES_AUTOHSCROLL |
((d->nc->prompts[i]->flags &
KHUI_NCPROMPT_FLAG_HIDDEN)? ES_PASSWORD:0),
er.left, er.top,
er.right - er.left, er.bottom - er.top,
d->dlg_main,
NULL,
khm_hInstance,
NULL);
#ifdef DEBUG
assert(hw);
#endif
SendMessage(hw, WM_SETFONT,
(WPARAM) hf, (LPARAM) TRUE);
SetWindowPos(hw, hw_prev,
0, 0, 0, 0,
SWP_NOACTIVATE | SWP_NOMOVE |
SWP_NOOWNERZORDER | SWP_NOSIZE |
SWP_SHOWWINDOW);
SendMessage(hw, EM_SETLIMITTEXT,
KHUI_MAXCCH_PROMPT_VALUE -1,
0);
d->nc->prompts[i]->hwnd_edit = hw;
hw_prev = hw;
y += dy;
}
if (d->nc->n_prompts > 0 &&
d->nc->prompts[0]->hwnd_edit) {
PostMessage(d->dlg_main, WM_NEXTDLGCTL,
(WPARAM) d->nc->prompts[0]->hwnd_edit,
MAKELPARAM(TRUE, 0));
}
SelectObject(hdc, hfold);
ReleaseDC(d->dlg_main, hdc);
khui_cw_unlock_nc(d->nc);
d->r_custprompt.bottom = y;
if (d->r_custprompt.bottom == d->r_custprompt.top)
SetRectEmpty(&d->r_custprompt);
nc_layout_main_panel(d);
nc_layout_new_cred_window(d);
}
break;
case WMNC_DIALOG_PROCESS_COMPLETE:
{
khui_new_creds * nc;
nc = d->nc;
nc->response &= ~KHUI_NC_RESPONSE_PROCESSING;
if(nc->response & KHUI_NC_RESPONSE_NOEXIT) {
HWND hw;
nc_enable_controls(d, TRUE);
/* reset state */
nc->result = KHUI_NC_RESULT_CANCEL;
hw = GetDlgItem(d->dlg_main, IDOK);
EnableWindow(hw, TRUE);
hw = GetDlgItem(d->dlg_main, IDCANCEL);
EnableWindow(hw, TRUE);
hw = GetDlgItem(d->dlg_main, IDC_NC_ADVANCED);
EnableWindow(hw, TRUE);
hw = GetDlgItem(d->dlg_bb, IDOK);
EnableWindow(hw, TRUE);
hw = GetDlgItem(d->dlg_bb, IDCANCEL);
EnableWindow(hw, TRUE);
nc_clear_password_fields(d);
return TRUE;
}
DestroyWindow(hwnd);
kmq_post_message(KMSG_CRED, KMSG_CRED_END, 0, (void *) nc);
}
break;
/* MUST be called with SendMessage */
case WMNC_ADD_CONTROL_ROW:
{
khui_control_row * row;
row = (khui_control_row *) lParam;
#ifdef DEBUG
assert(row->label);
assert(row->input);
#endif
nc_add_control_row(d, row->label, row->input, row->size);
}
break;
case WMNC_UPDATE_LAYOUT:
{
RECT r_client;
khm_int32 animate;
khm_int32 steps;
khm_int32 timeout;
/* We are already adjusting the size of the window. The
next time the timer fires, it will notice if the target
size has changed. */
if (d->size_changing)
return TRUE;
GetClientRect(hwnd, &r_client);
if ((r_client.right - r_client.left ==
d->r_required.right - d->r_required.left) &&
(r_client.bottom - r_client.top ==
d->r_required.bottom - d->r_required.top)) {
/* the window is already at the right size */
return TRUE;
}
if (!IsWindowVisible(hwnd)) {
/* The window is not visible yet. There's no need to
animate anything. */
animate = FALSE;
} else if (KHM_FAILED(khc_read_int32(NULL,
L"CredWindow\\Windows\\NewCred\\AnimateSizeChanges",
&animate))) {
#ifdef DEBUG
assert(FALSE);
#endif
animate = TRUE;
}
/* if we aren't animating the window resize, then we just
do it in one call. */
if (!animate || !d->animation_enabled) {
RECT r_window;
CopyRect(&r_window, &d->r_required);
AdjustWindowRectEx(&r_window, NC_WINDOW_STYLES, FALSE,
NC_WINDOW_EX_STYLES);
SetWindowPos(hwnd, NULL, 0, 0,
r_window.right - r_window.left,
r_window.bottom - r_window.top,
SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER |
SWP_NOZORDER);
return TRUE;
}
if (KHM_FAILED(khc_read_int32(NULL,
L"CredWindow\\Windows\\NewCred\\AnimationSteps",
&steps))) {
#ifdef DEBUG
assert(FALSE);
#endif
steps = NC_SZ_STEPS_DEF;
} else {
if (steps < NC_SZ_STEPS_MIN)
steps = NC_SZ_STEPS_MIN;
else if (steps > NC_SZ_STEPS_MAX)
steps = NC_SZ_STEPS_MAX;
}
if (KHM_FAILED(khc_read_int32(NULL,
L"CredWindow\\Windows\\NewCred\\AnimationStepTimeout",
&timeout))) {
#ifdef DEBUG
assert(FALSE);
#endif
timeout = NC_SZ_TIMEOUT_DEF;
} else {
if (timeout < NC_SZ_TIMEOUT_MIN)
timeout = NC_SZ_TIMEOUT_MIN;
else if (timeout > NC_SZ_TIMEOUT_MAX)
timeout = NC_SZ_TIMEOUT_MAX;
}
CopyRect(&d->sz_ch_source, &r_client);
OffsetRect(&d->sz_ch_source, -d->sz_ch_source.left, -d->sz_ch_source.top);
CopyRect(&d->sz_ch_target, &d->r_required);
OffsetRect(&d->sz_ch_target, -d->sz_ch_target.left, -d->sz_ch_target.top);
d->sz_ch_increment = 0;
d->sz_ch_max = steps;
d->sz_ch_timeout = timeout;
d->size_changing = TRUE;
SetTimer(hwnd, NC_TIMER_SIZER, timeout, NULL);
}
break;
} /* switch(HIWORD(wParam)) */
return TRUE;
}
static LRESULT nc_handle_wm_timer(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam) {
khui_nc_wnd_data * d;
d = (khui_nc_wnd_data *)(LONG_PTR) GetWindowLongPtr(hwnd, CW_PARAM);
if (d == NULL)
return FALSE;
if (wParam == NC_TIMER_SIZER) {
RECT r_now;
/* are we done with this sizing operation? */
if (!d->size_changing ||
d->sz_ch_increment >= d->sz_ch_max) {
d->size_changing = FALSE;
KillTimer(hwnd, NC_TIMER_SIZER);
return 0;
}
/* have the requirements changed while we were processing the
sizing operation? */
if ((d->r_required.right - d->r_required.left !=
d->sz_ch_target.right)
||
(d->r_required.bottom - d->r_required.top !=
d->sz_ch_target.bottom)) {
/* the target size has changed. we need to restart the
sizing operation. */
RECT r_client;
GetClientRect(hwnd, &r_client);
CopyRect(&d->sz_ch_source, &r_client);
OffsetRect(&d->sz_ch_source, -d->sz_ch_source.left, -d->sz_ch_source.top);
CopyRect(&d->sz_ch_target, &d->r_required);
OffsetRect(&d->sz_ch_target, -d->sz_ch_target.left, -d->sz_ch_target.top);
d->sz_ch_increment = 0;
/* leave the other fields alone */
#ifdef DEBUG
assert(d->sz_ch_max >= NC_SZ_STEPS_MIN);
assert(d->sz_ch_max <= NC_SZ_STEPS_MAX);
assert(d->sz_ch_timeout >= NC_SZ_TIMEOUT_MIN);
assert(d->sz_ch_timeout <= NC_SZ_TIMEOUT_MAX);
assert(d->size_changing);
#endif
}
/* we are going to do the next increment */
d->sz_ch_increment ++;
/* now, figure out the size of the client area for this
step */
r_now.left = 0;
r_now.top = 0;
#define PROPORTION(v1, v2, i, s) (((v1) * ((s) - (i)) + (v2) * (i)) / (s))
r_now.right = PROPORTION(d->sz_ch_source.right, d->sz_ch_target.right,
d->sz_ch_increment, d->sz_ch_max);
r_now.bottom = PROPORTION(d->sz_ch_source.bottom, d->sz_ch_target.bottom,
d->sz_ch_increment, d->sz_ch_max);
#undef PROPORTION
#ifdef DEBUG
{
long dx = ((r_now.right - r_now.left) - d->sz_ch_target.right) *
(d->sz_ch_source.right - d->sz_ch_target.right);
long dy = ((r_now.bottom - r_now.top) - d->sz_ch_target.bottom) *
(d->sz_ch_source.bottom - d->sz_ch_target.bottom);
if (dx < 0 || dy < 0) {
KillTimer(hwnd, NC_TIMER_SIZER);
assert(dx >= 0);
assert(dy >= 0);
SetTimer(hwnd, NC_TIMER_SIZER, d->sz_ch_timeout, NULL);
}
}
#endif
AdjustWindowRectEx(&r_now, NC_WINDOW_STYLES, FALSE,
NC_WINDOW_EX_STYLES);
{
RECT r;
GetWindowRect(hwnd, &r);
OffsetRect(&r_now, r.left - r_now.left, r.top - r_now.top);
}
khm_adjust_window_dimensions_for_display(&r_now, 0);
SetWindowPos(hwnd, NULL,
r_now.left, r_now.top,
r_now.right - r_now.left,
r_now.bottom - r_now.top,
SWP_NOACTIVATE | SWP_NOOWNERZORDER |
SWP_NOZORDER);
/* and now we wait for the next timer message */
return 0;
} else if (wParam == NC_TIMER_ENABLEANIMATE) {
d->animation_enabled = TRUE;
KillTimer(hwnd, NC_TIMER_ENABLEANIMATE);
}
return 0;
}
static LRESULT nc_handle_wm_notify(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam) {
LPNMHDR nmhdr;
khui_nc_wnd_data * d;
d = (khui_nc_wnd_data *)(LONG_PTR) GetWindowLongPtr(hwnd, CW_PARAM);
if (d == NULL)
return FALSE;
nmhdr = (LPNMHDR) lParam;
if (nmhdr->code == TCN_SELCHANGE) {
/* the current tab has changed. */
int idx;
TCITEM tcitem;
idx = TabCtrl_GetCurSel(d->tab_wnd);
ZeroMemory(&tcitem, sizeof(tcitem));
tcitem.mask = TCIF_PARAM;
TabCtrl_GetItem(d->tab_wnd, idx, &tcitem);
d->current_panel = (int) tcitem.lParam;
nc_layout_new_cred_window(d);
return TRUE;
}
return FALSE;
}
static LRESULT nc_handle_wm_help(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam) {
static DWORD ctxids[] = {
NC_TS_CTRL_ID_MIN, IDH_NC_TABMAIN,
NC_TS_CTRL_ID_MIN + 1, IDH_NC_TABBUTTON,
NC_TS_CTRL_ID_MIN + 2, IDH_NC_TABBUTTON,
NC_TS_CTRL_ID_MIN + 3, IDH_NC_TABBUTTON,
NC_TS_CTRL_ID_MIN + 4, IDH_NC_TABBUTTON,
NC_TS_CTRL_ID_MIN + 5, IDH_NC_TABBUTTON,
NC_TS_CTRL_ID_MIN + 6, IDH_NC_TABBUTTON,
NC_TS_CTRL_ID_MIN + 7, IDH_NC_TABBUTTON,
IDOK, IDH_NC_OK,
IDCANCEL, IDH_NC_CANCEL,
IDC_NC_HELP, IDH_NC_HELP,
IDC_NC_ADVANCED, IDH_NC_ADVANCED,
IDC_NC_CREDTEXT, IDH_NC_CREDWND,
0
};
HELPINFO * hlp;
HWND hw = NULL;
HWND hw_ctrl;
khui_nc_wnd_data * d;
d = (khui_nc_wnd_data *)(LONG_PTR) GetWindowLongPtr(hwnd, CW_PARAM);
if (d == NULL)
return FALSE;
hlp = (HELPINFO *) lParam;
if (d->nc->subtype != KMSG_CRED_NEW_CREDS &&
d->nc->subtype != KMSG_CRED_PASSWORD)
return TRUE;
if (hlp->iContextType != HELPINFO_WINDOW)
return TRUE;
if (hlp->hItemHandle != NULL &&
hlp->hItemHandle != hwnd) {
DWORD id;
int i;
hw_ctrl =hlp->hItemHandle;
id = GetWindowLong(hw_ctrl, GWL_ID);
for (i=0; ctxids[i] != 0; i += 2)
if (ctxids[i] == id)
break;
if (ctxids[i] != 0)
hw = khm_html_help(hw_ctrl,
((d->nc->subtype == KMSG_CRED_NEW_CREDS)?
L"::popups_newcreds.txt":
L"::popups_password.txt"),
HH_TP_HELP_WM_HELP,
(DWORD_PTR) ctxids);
}
if (hw == NULL) {
khm_html_help(hwnd, NULL, HH_HELP_CONTEXT,
((d->nc->subtype == KMSG_CRED_NEW_CREDS)?
IDH_ACTION_NEW_ID: IDH_ACTION_PASSWD_ID));
}
return TRUE;
}
static LRESULT nc_handle_wm_activate(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam) {
if (uMsg == WM_MOUSEACTIVATE ||
wParam == WA_ACTIVE || wParam == WA_CLICKACTIVE) {
FLASHWINFO fi;
khui_nc_wnd_data * d;
DWORD_PTR ex_style;
d = (khui_nc_wnd_data *)(LONG_PTR) GetWindowLongPtr(hwnd, CW_PARAM);
if (d && d->flashing_enabled) {
ZeroMemory(&fi, sizeof(fi));
fi.cbSize = sizeof(fi);
fi.hwnd = hwnd;
fi.dwFlags = FLASHW_STOP;
FlashWindowEx(&fi);
d->flashing_enabled = FALSE;
}
ex_style = GetWindowLongPtr(hwnd, GWL_EXSTYLE);
if (ex_style & WS_EX_TOPMOST) {
SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
}
}
return (uMsg == WM_MOUSEACTIVATE)? MA_ACTIVATE : 0;
}
static LRESULT CALLBACK nc_window_proc(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
switch(uMsg) {
case WM_MOUSEACTIVATE:
case WM_ACTIVATE:
return nc_handle_wm_activate(hwnd, uMsg, wParam, lParam);
case WM_CREATE:
return nc_handle_wm_create(hwnd, uMsg, wParam, lParam);
case WM_DESTROY:
return nc_handle_wm_destroy(hwnd, uMsg, wParam, lParam);
case WM_COMMAND:
return nc_handle_wm_command(hwnd, uMsg, wParam, lParam);
case WM_NOTIFY:
return nc_handle_wm_notify(hwnd, uMsg, wParam, lParam);
case WM_MOVE:
case WM_MOVING:
return nc_handle_wm_moving(hwnd, uMsg, wParam, lParam);
case WM_TIMER:
return nc_handle_wm_timer(hwnd, uMsg, wParam, lParam);
case WM_HELP:
return nc_handle_wm_help(hwnd, uMsg, wParam, lParam);
case KHUI_WM_NC_NOTIFY:
return nc_handle_wm_nc_notify(hwnd, uMsg, wParam, lParam);
}
/* Note that this is technically a dialog box */
return DefDlgProc(hwnd, uMsg, wParam, lParam);
}
void khm_register_newcredwnd_class(void)
{
WNDCLASSEX wcx;
wcx.cbSize = sizeof(wcx);
wcx.style = CS_DBLCLKS | CS_OWNDC;
wcx.lpfnWndProc = nc_window_proc;
wcx.cbClsExtra = 0;
wcx.cbWndExtra = DLGWINDOWEXTRA + sizeof(LONG_PTR);
wcx.hInstance = khm_hInstance;
wcx.hIcon = LoadIcon(khm_hInstance, MAKEINTRESOURCE(IDI_MAIN_APP));
wcx.hCursor = LoadCursor((HINSTANCE) NULL, IDC_ARROW);
wcx.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1);
wcx.lpszMenuName = NULL;
wcx.lpszClassName = KHUI_NEWCREDWND_CLASS;
wcx.hIconSm = NULL;
khui_newcredwnd_cls = RegisterClassEx(&wcx);
}
void khm_unregister_newcredwnd_class(void)
{
UnregisterClass(MAKEINTATOM(khui_newcredwnd_cls), khm_hInstance);
}
HWND khm_create_newcredwnd(HWND parent, khui_new_creds * c)
{
wchar_t wtitle[256];
HWND hwnd;
khm_int32 force_topmost = 0;
if (c->window_title == NULL) {
if (c->subtype == KMSG_CRED_PASSWORD)
LoadString(khm_hInstance,
IDS_WT_PASSWORD,
wtitle,
ARRAYLENGTH(wtitle));
else
LoadString(khm_hInstance,
IDS_WT_NEW_CREDS,
wtitle,
ARRAYLENGTH(wtitle));
}
khc_read_int32(NULL, L"CredWindow\\Windows\\NewCred\\ForceToTop", &force_topmost);
hwnd = CreateWindowEx(NC_WINDOW_EX_STYLES | (force_topmost ? WS_EX_TOPMOST : 0),
MAKEINTATOM(khui_newcredwnd_cls),
((c->window_title)?c->window_title: wtitle),
NC_WINDOW_STYLES,
0,0,400,400, /* bogus values. the window
is going to resize and
reposition itself
anyway */
parent,
NULL,
khm_hInstance,
(LPVOID) c);
#ifdef DEBUG
assert(hwnd != NULL);
#endif
/* note that the window is not visible yet. That's because, at
this point we don't know what the panels are */
return hwnd;
}
void khm_prep_newcredwnd(HWND hwnd)
{
SendMessage(hwnd, KHUI_WM_NC_NOTIFY,
MAKEWPARAM(0, WMNC_DIALOG_SETUP), 0);
}
void khm_show_newcredwnd(HWND hwnd)
{
/* add all the panels in and prep UI */
PostMessage(hwnd, KHUI_WM_NC_NOTIFY,
MAKEWPARAM(0, WMNC_DIALOG_ACTIVATE), 0);
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
#import <UIKit/UIKit.h>
//! Project version number for Chisel.
FOUNDATION_EXPORT double ChiselVersionNumber;
//! Project version string for Chisel.
FOUNDATION_EXPORT const unsigned char ChiselVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <Chisel/PublicHeader.h>
| {
"pile_set_name": "Github"
} |
#define __CLC_ATOMIC_OP or
#define __CLC_ATOMIC_ADDRESS_SPACE local
#include "../atom_int32_binary.inc"
| {
"pile_set_name": "Github"
} |
alert('hello web-webpack-plugin from' + NAME);
| {
"pile_set_name": "Github"
} |
# to-regex-range [](https://www.npmjs.com/package/to-regex-range) [](https://npmjs.org/package/to-regex-range) [](https://npmjs.org/package/to-regex-range) [](https://travis-ci.org/micromatch/to-regex-range)
> Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions.
## Install
Install with [npm](https://www.npmjs.com/):
```sh
$ npm install --save to-regex-range
```
Install with [yarn](https://yarnpkg.com):
```sh
$ yarn add to-regex-range
```
<details>
<summary><strong>What does this do?</strong></summary>
<br>
This libary generates the `source` string to be passed to `new RegExp()` for matching a range of numbers.
**Example**
```js
var toRegexRange = require('to-regex-range');
var regex = new RegExp(toRegexRange('15', '95'));
```
A string is returned so that you can do whatever you need with it before passing it to `new RegExp()` (like adding `^` or `$` boundaries, defining flags, or combining it another string).
<br>
</details>
<details>
<summary><strong>Why use this library?</strong></summary>
<br>
### Convenience
Creating regular expressions for matching numbers gets deceptively complicated pretty fast.
For example, let's say you need a validation regex for matching part of a user-id, postal code, social security number, tax id, etc:
* regex for matching `1` => `/1/` (easy enough)
* regex for matching `1` through `5` => `/[1-5]/` (not bad...)
* regex for matching `1` or `5` => `/(1|5)/` (still easy...)
* regex for matching `1` through `50` => `/([1-9]|[1-4][0-9]|50)/` (uh-oh...)
* regex for matching `1` through `55` => `/([1-9]|[1-4][0-9]|5[0-5])/` (no prob, I can do this...)
* regex for matching `1` through `555` => `/([1-9]|[1-9][0-9]|[1-4][0-9]{2}|5[0-4][0-9]|55[0-5])/` (maybe not...)
* regex for matching `0001` through `5555` => `/(0{3}[1-9]|0{2}[1-9][0-9]|0[1-9][0-9]{2}|[1-4][0-9]{3}|5[0-4][0-9]{2}|55[0-4][0-9]|555[0-5])/` (okay, I get the point!)
The numbers are contrived, but they're also really basic. In the real world you might need to generate a regex on-the-fly for validation.
**Learn more**
If you're interested in learning more about [character classes](http://www.regular-expressions.info/charclass.html) and other regex features, I personally have always found [regular-expressions.info](http://www.regular-expressions.info/charclass.html) to be pretty useful.
### Heavily tested
As of April 27, 2017, this library runs [2,783,483 test assertions](./test/test.js) against generated regex-ranges to provide brute-force verification that results are indeed correct.
Tests run in ~870ms on my MacBook Pro, 2.5 GHz Intel Core i7.
### Highly optimized
Generated regular expressions are highly optimized:
* duplicate sequences and character classes are reduced using quantifiers
* smart enough to use `?` conditionals when number(s) or range(s) can be positive or negative
* uses fragment caching to avoid processing the same exact string more than once
<br>
</details>
## Usage
Add this library to your javascript application with the following line of code
```js
var toRegexRange = require('to-regex-range');
```
The main export is a function that takes two integers: the `min` value and `max` value (formatted as strings or numbers).
```js
var source = toRegexRange('15', '95');
//=> 1[5-9]|[2-8][0-9]|9[0-5]
var re = new RegExp('^' + source + '$');
console.log(re.test('14')); //=> false
console.log(re.test('50')); //=> true
console.log(re.test('94')); //=> true
console.log(re.test('96')); //=> false
```
## Options
### options.capture
**Type**: `boolean`
**Deafault**: `undefined`
Wrap the returned value in parentheses when there is more than one regex condition. Useful when you're dynamically generating ranges.
```js
console.log(toRegexRange('-10', '10'));
//=> -[1-9]|-?10|[0-9]
console.log(toRegexRange('-10', '10', {capture: true}));
//=> (-[1-9]|-?10|[0-9])
```
### options.shorthand
**Type**: `boolean`
**Deafault**: `undefined`
Use the regex shorthand for `[0-9]`:
```js
console.log(toRegexRange('0', '999999'));
//=> [0-9]|[1-9][0-9]{1,5}
console.log(toRegexRange('0', '999999', {shorthand: true}));
//=> \d|[1-9]\d{1,5}
```
### options.relaxZeros
**Type**: `boolean`
**Default**: `true`
This option only applies to **negative zero-padded ranges**. By default, when a negative zero-padded range is defined, the number of leading zeros is relaxed using `-0*`.
```js
console.log(toRegexRange('-001', '100'));
//=> -0*1|0{2}[0-9]|0[1-9][0-9]|100
console.log(toRegexRange('-001', '100', {relaxZeros: false}));
//=> -0{2}1|0{2}[0-9]|0[1-9][0-9]|100
```
<details>
<summary><strong>Why are zeros relaxed for negative zero-padded ranges by default?</strong></summary>
Consider the following.
```js
var regex = toRegexRange('-001', '100');
```
_Note that `-001` and `100` are both three digits long_.
In most zero-padding implementations, only a single leading zero is enough to indicate that zero-padding should be applied. Thus, the leading zeros would be "corrected" on the negative range in the example to `-01`, instead of `-001`, to make total length of each string no greater than the length of the largest number in the range (in other words, `-001` is 4 digits, but `100` is only three digits).
If zeros were not relaxed by default, you might expect the resulting regex of the above pattern to match `-001` - given that it's defined that way in the arguments - _but it wouldn't_. It would, however, match `-01`. This gets even more ambiguous with large ranges, like `-01` to `1000000`.
Thus, we relax zeros by default to provide a more predictable experience for users.
</details>
## Examples
| **Range** | **Result** | **Compile time** |
| --- | --- | --- |
| `toRegexRange('5, 5')` | `5` | _33μs_ |
| `toRegexRange('5, 6')` | `5\|6` | _53μs_ |
| `toRegexRange('29, 51')` | `29\|[34][0-9]\|5[01]` | _699μs_ |
| `toRegexRange('31, 877')` | `3[1-9]\|[4-9][0-9]\|[1-7][0-9]{2}\|8[0-6][0-9]\|87[0-7]` | _711μs_ |
| `toRegexRange('111, 555')` | `11[1-9]\|1[2-9][0-9]\|[2-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _62μs_ |
| `toRegexRange('-10, 10')` | `-[1-9]\|-?10\|[0-9]` | _74μs_ |
| `toRegexRange('-100, -10')` | `-1[0-9]\|-[2-9][0-9]\|-100` | _49μs_ |
| `toRegexRange('-100, 100')` | `-[1-9]\|-?[1-9][0-9]\|-?100\|[0-9]` | _45μs_ |
| `toRegexRange('001, 100')` | `0{2}[1-9]\|0[1-9][0-9]\|100` | _158μs_ |
| `toRegexRange('0010, 1000')` | `0{2}1[0-9]\|0{2}[2-9][0-9]\|0[1-9][0-9]{2}\|1000` | _61μs_ |
| `toRegexRange('1, 2')` | `1\|2` | _10μs_ |
| `toRegexRange('1, 5')` | `[1-5]` | _24μs_ |
| `toRegexRange('1, 10')` | `[1-9]\|10` | _23μs_ |
| `toRegexRange('1, 100')` | `[1-9]\|[1-9][0-9]\|100` | _30μs_ |
| `toRegexRange('1, 1000')` | `[1-9]\|[1-9][0-9]{1,2}\|1000` | _52μs_ |
| `toRegexRange('1, 10000')` | `[1-9]\|[1-9][0-9]{1,3}\|10000` | _47μs_ |
| `toRegexRange('1, 100000')` | `[1-9]\|[1-9][0-9]{1,4}\|100000` | _44μs_ |
| `toRegexRange('1, 1000000')` | `[1-9]\|[1-9][0-9]{1,5}\|1000000` | _49μs_ |
| `toRegexRange('1, 10000000')` | `[1-9]\|[1-9][0-9]{1,6}\|10000000` | _63μs_ |
## Heads up!
**Order of arguments**
When the `min` is larger than the `max`, values will be flipped to create a valid range:
```js
toRegexRange('51', '29');
```
Is effectively flipped to:
```js
toRegexRange('29', '51');
//=> 29|[3-4][0-9]|5[0-1]
```
**Steps / increments**
This library does not support steps (increments). A pr to add support would be welcome.
## History
### v2.0.0 - 2017-04-21
**New features**
Adds support for zero-padding!
### v1.0.0
**Optimizations**
Repeating ranges are now grouped using quantifiers. rocessing time is roughly the same, but the generated regex is much smaller, which should result in faster matching.
## Attribution
Inspired by the python library [range-regex](https://github.com/dimka665/range-regex).
## About
### Related projects
* [expand-range](https://www.npmjs.com/package/expand-range): Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. See… [more](https://github.com/jonschlinkert/expand-range) | [homepage](https://github.com/jonschlinkert/expand-range "Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. See the benchmarks. Used by micromatch.")
* [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`")
* [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.")
* [repeat-element](https://www.npmjs.com/package/repeat-element): Create an array by repeating the given value n times. | [homepage](https://github.com/jonschlinkert/repeat-element "Create an array by repeating the given value n times.")
* [repeat-string](https://www.npmjs.com/package/repeat-string): Repeat the given string n times. Fastest implementation for repeating a string. | [homepage](https://github.com/jonschlinkert/repeat-string "Repeat the given string n times. Fastest implementation for repeating a string.")
### Contributing
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
### Building docs
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```
### Running tests
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
$ npm install && npm test
```
### Author
**Jon Schlinkert**
* [github/jonschlinkert](https://github.com/jonschlinkert)
* [twitter/jonschlinkert](https://twitter.com/jonschlinkert)
### License
Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).
***
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on April 27, 2017._ | {
"pile_set_name": "Github"
} |
<launch>
<node pkg="nodelet" type="nodelet" name="standalone_nodelet" args="manager"/>
<node pkg="nodelet" type="nodelet" name="Points" args="load velodyne/Points standalone_nodelet" output="screen"/>
<include file="$(find dgccompat)/launch/playback.launch" args="$(arg args)">
<arg name="args" value="/home/pnk2si/data/seq/good_run_with_traffic_late_stop-09-01-2010_15-55-43.log.gz"/>
</include>
<node name="rviz" pkg="rviz" type="rviz" args="-d $(find velodyne)/launch/velodyne_view.vcg"/>
</launch>
| {
"pile_set_name": "Github"
} |
#!/bin/bash
USER=HTTP_USER
PASSWORD=HTTP_PASSWORD
API_URI=https://remote.example.com/rm/
DOWNLOAD_DIR="YOUR_DOWNLOAD_DIR" # e.g. /mnt/usb/download
SORT_DIR="YOUR_SORT_DIR" #e.g. /mnt/usb/complete
OUTOUT="/tmp/aria2-complete.txt"
echo "$3" >>$OUTOUT
# remove file from server
FILENAME=$(basename "$3")
curl -s -v --user $USER:$PASSWORD $API_URI -X POST --data-urlencode "files=$FILENAME" --capath /etc/ssl/certs/ >>/tmp/aria2.txt 2>&1
# sort out files (mp4/m4a/tar/zip)
if [ ! -f "$DOWNLOAD_DIR/$FILENAME" ];then
echo "$DOWNLOAD_DIR/$FILENAME not exists, exit." >>$OUTOUT
exit 0
fi
# wait for other sort jobs done.
while [ -f /tmp/.sort ]
do
echo "wait other job exit" >>$OUTOUT
#sleep 2
sleep $[ ( $RANDOM % 10 ) + 1 ]
done
umask 000
touch /tmp/.sort
EXT="${FILENAME##*.}"
MON="$(date +%m)"
DAY="$(date +%m%d)"
if [ "$EXT" = "zip" ];then
echo "unzip" >>$OUTOUT
mkdir -p "$SORT_DIR/archives/$DAY"
mv "$DOWNLOAD_DIR/$FILENAME" "$SORT_DIR/archives/$DAY"
TARGET_DIR="$SORT_DIR/$MON/$DAY"
if [ $(unzip -l "$SORT_DIR/archives/$DAY/$FILENAME"|grep -E '.mp4$|.wmv$|.avi$'|wc -l) -gt 0 ];then
TARGET_DIR="$SORT_DIR/$MON/$DAY-2"
fi
mkdir -p "$TARGET_DIR"
unzip "$SORT_DIR/archives/$DAY/$FILENAME" -d "$TARGET_DIR" >>$OUTOUT 2>&1
elif [ "$EXT" = "tar" ];then
echo "tar xvf \"$FILENAME\" -C \"$SORT_DIR/$MON/$DAY\"" >>$OUTOUT
mkdir -p "$SORT_DIR/archives/$DAY"
mv "$DOWNLOAD_DIR/$FILENAME" "$SORT_DIR/archives/$DAY"
TARGET_DIR="$SORT_DIR/$MON/$DAY"
if [ $(tar tvf "$SORT_DIR/archives/$DAY/$FILENAME"|grep -E '.mp4$|.wmv$|.avi$'|wc -l) -gt 0 ];then
TARGET_DIR="$SORT_DIR/$MON/$DAY-2"
fi
mkdir -p "$TARGET_DIR"
tar xvf "$SORT_DIR/archives/$DAY/$FILENAME" -C "$TARGET_DIR" >>$OUTOUT 2>&1
elif [ "$EXT" = "mp4" -o "$EXT" = "m4a" ];then
SUBDIR=""
if [ $(echo "$FILENAME"|grep "\.f[0-9]...mp4"|wc -l) -eq 1 ];then
SUBDIR="video"
fi
if [ $(echo "$FILENAME"|grep "\.f[0-9]...m4a"|wc -l) -eq 1 ];then
SUBDIR="audio"
fi
if [ $(echo "$FILENAME"|grep "MMD"|wc -l) -eq 1 ];then
echo "mv \"$FILENAME\" \"$SORT_DIR/MMD/$DAY/$SUBDIR\"" >>$OUTOUT
mkdir -p "$SORT_DIR/MMD/$DAY/$SUBDIR"
mv "$DOWNLOAD_DIR/$FILENAME" "$SORT_DIR/MMD/$DAY/$SUBDIR"
elif [ $(echo "$FILENAME"|grep "AMV"|wc -l) -eq 1 ];then
echo "mv \"$FILENAME\" \"$SORT_DIR/AMV/$DAY/$SUBDIR\"" >>$OUTOUT
mkdir -p "$SORT_DIR/AMV/$DAY/$SUBDIR"
mv "$DOWNLOAD_DIR/$FILENAME" "$SORT_DIR/AMV/$DAY/$SUBDIR"
else
echo "mv \"$FILENAME\" \"$SORT_DIR/TV/$DAY/$SUBDIR\"" >>$OUTOUT
mkdir -p "$SORT_DIR/TV/$DAY/$SUBDIR"
mv "$DOWNLOAD_DIR/$FILENAME" "$SORT_DIR/TV/$DAY/$SUBDIR"
fi
else
echo "unknown file type: $EXT" >>$OUTOUT
fi
sync
rm /tmp/.sort
sync
rm /tmp/.sort
| {
"pile_set_name": "Github"
} |
{
"activePlaceCount": 0,
"birth": {
"place": {
"name": "Warszawa, Polska",
"placeName": "Warszawa",
"placeType": "inhabited_place"
},
"time": {
"startYear": 1907
}
},
"birthYear": 1907,
"date": "1907\u20131989",
"death": {
"time": {
"startYear": 1989
}
},
"fc": "Feliks Topolski",
"gender": "Male",
"id": 2056,
"mda": "Topolski, Feliks",
"movements": [],
"startLetter": "T",
"totalWorks": 12,
"url": "http://www.tate.org.uk/art/artists/feliks-topolski-2056"
} | {
"pile_set_name": "Github"
} |
<mjml>
<mj-body background-color="#fff">
<mj-section>
<mj-column>
<mj-image
width="100px"
src="{{host}}/assets/images/logos/logo_Gauzy.svg"
></mj-image>
<mj-divider
border-color="#1B005D"
border-width="1px"
></mj-divider>
<mj-text font-size="20px" font-family="helvetica"
><bold>Новая задача {{task_update_status}}</bold></mj-text
>
<mj-text padding="20px 0px 20px 50px" font-size="16px" font-family="helvetica">
<p><bold>заглавие:</bold> {{task_update_title}}</p>
<p><bold>Описание:</bold> {{task_update_description}}</p>
<p><bold>Оценить:</bold> {{task_update_estimate}}</p>
<p><bold>Срок:</bold> {{task_update_due_date}}</p>
<p><bold>Положение дел:</bold> {{task_status}}</p>
<p><bold>название проекта:</bold> {{task_update_project}}</p>
<p><bold>Назначить:</bold> {{task_update_assign_by}}</p>
</mj-text>
<mj-text font-size="12px" font-family="helvetica"
>** URL задачи: {{task_update_url}}</mj-text
>
<mj-divider
border-color="#1B005D"
border-width="1px"
></mj-divider>
<mj-text align="center" font-size="12px" font-family="helvetica"
>© 2019,
<a href="https://app.gauzy.co/." style="color:#598bff"
>Gauzy</a
>
by
<a href="https://ever.co/" style="color:#598bff"
>Ever Co. LTD.</a
>
All rights reserved.
</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml>
| {
"pile_set_name": "Github"
} |
import mongoose from 'mongoose'
import bluebird from 'bluebird'
import config from 'config'
export default () => {
// Set mongoose promise
mongoose.Promise = bluebird
// Function to create url connection
const _connection = ({
MONGO_USERNAME = config.mongo.username,
MONGO_PASSWORD = config.mongo.password,
MONGO_HOST = config.mongo.host,
MONGO_PORT = config.mongo.port,
MONGO_DATABASE = config.mongo.database
}) => {
const AUTH = MONGO_USERNAME ? `${MONGO_USERNAME}:${MONGO_PASSWORD}@` : ''
return `mongodb://${AUTH}${MONGO_HOST}:${MONGO_PORT}/${MONGO_DATABASE}`
}
const _urlConnection = _connection(process.env)
// Init connection
mongoose.connect(_urlConnection, {
useMongoClient: true,
promiseLibrary: bluebird
})
const database = mongoose.connection
database.on('error', () => console.log(`Failed to connect : ${_urlConnection}`))
database.once('open', () => console.log(`Connected : ${_urlConnection}`))
}
| {
"pile_set_name": "Github"
} |
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Preprocessed version of "boost/mpl/list.hpp" header
// -- DO NOT modify by hand!
namespace boost { namespace mpl {
template<
typename T0 = na, typename T1 = na, typename T2 = na, typename T3 = na
, typename T4 = na, typename T5 = na, typename T6 = na, typename T7 = na
, typename T8 = na, typename T9 = na, typename T10 = na, typename T11 = na
, typename T12 = na, typename T13 = na, typename T14 = na
, typename T15 = na, typename T16 = na, typename T17 = na
, typename T18 = na, typename T19 = na
>
struct list;
template<
>
struct list<
na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na
, na, na, na
>
: list0< >
{
typedef list0< >::type type;
};
template<
typename T0
>
struct list<
T0, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na
, na, na, na
>
: list1<T0>
{
typedef typename list1<T0>::type type;
};
template<
typename T0, typename T1
>
struct list<
T0, T1, na, na, na, na, na, na, na, na, na, na, na, na, na, na, na
, na, na, na
>
: list2< T0,T1 >
{
typedef typename list2< T0,T1 >::type type;
};
template<
typename T0, typename T1, typename T2
>
struct list<
T0, T1, T2, na, na, na, na, na, na, na, na, na, na, na, na, na, na
, na, na, na
>
: list3< T0,T1,T2 >
{
typedef typename list3< T0,T1,T2 >::type type;
};
template<
typename T0, typename T1, typename T2, typename T3
>
struct list<
T0, T1, T2, T3, na, na, na, na, na, na, na, na, na, na, na, na, na
, na, na, na
>
: list4< T0,T1,T2,T3 >
{
typedef typename list4< T0,T1,T2,T3 >::type type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
>
struct list<
T0, T1, T2, T3, T4, na, na, na, na, na, na, na, na, na, na, na, na
, na, na, na
>
: list5< T0,T1,T2,T3,T4 >
{
typedef typename list5< T0,T1,T2,T3,T4 >::type type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5
>
struct list<
T0, T1, T2, T3, T4, T5, na, na, na, na, na, na, na, na, na, na, na
, na, na, na
>
: list6< T0,T1,T2,T3,T4,T5 >
{
typedef typename list6< T0,T1,T2,T3,T4,T5 >::type type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6
>
struct list<
T0, T1, T2, T3, T4, T5, T6, na, na, na, na, na, na, na, na, na, na
, na, na, na
>
: list7< T0,T1,T2,T3,T4,T5,T6 >
{
typedef typename list7< T0,T1,T2,T3,T4,T5,T6 >::type type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7
>
struct list<
T0, T1, T2, T3, T4, T5, T6, T7, na, na, na, na, na, na, na, na, na
, na, na, na
>
: list8< T0,T1,T2,T3,T4,T5,T6,T7 >
{
typedef typename list8< T0,T1,T2,T3,T4,T5,T6,T7 >::type type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8
>
struct list<
T0, T1, T2, T3, T4, T5, T6, T7, T8, na, na, na, na, na, na, na, na
, na, na, na
>
: list9< T0,T1,T2,T3,T4,T5,T6,T7,T8 >
{
typedef typename list9< T0,T1,T2,T3,T4,T5,T6,T7,T8 >::type type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
>
struct list<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, na, na, na, na, na, na, na
, na, na, na
>
: list10< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9 >
{
typedef typename list10< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9 >::type type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10
>
struct list<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, na, na, na, na, na, na
, na, na, na
>
: list11< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10 >
{
typedef typename list11< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10 >::type type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11
>
struct list<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, na, na, na, na
, na, na, na, na
>
: list12< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11 >
{
typedef typename list12< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11 >::type type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12
>
struct list<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, na, na, na
, na, na, na, na
>
: list13< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12 >
{
typedef typename list13< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12 >::type type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13
>
struct list<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, na, na
, na, na, na, na
>
: list14< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13 >
{
typedef typename list14< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13 >::type type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
>
struct list<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, na
, na, na, na, na
>
: list15<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14
>
{
typedef typename list15< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14 >::type type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15
>
struct list<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14
, T15, na, na, na, na
>
: list16<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14
, T15
>
{
typedef typename list16< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15 >::type type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16
>
struct list<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14
, T15, T16, na, na, na
>
: list17<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14
, T15, T16
>
{
typedef typename list17< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16 >::type type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17
>
struct list<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14
, T15, T16, T17, na, na
>
: list18<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14
, T15, T16, T17
>
{
typedef typename list18< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17 >::type type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18
>
struct list<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14
, T15, T16, T17, T18, na
>
: list19<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14
, T15, T16, T17, T18
>
{
typedef typename list19< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18 >::type type;
};
/// primary template (not a specialization!)
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct list
: list20<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14
, T15, T16, T17, T18, T19
>
{
typedef typename list20< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19 >::type type;
};
}}
| {
"pile_set_name": "Github"
} |
namespace Server.Items
{
public class Feathernock : BaseQuiver
{
public override bool IsArtifact => true;
[Constructable]
public Feathernock()
: base()
{
SetHue = 0x594;
Attributes.WeaponDamage = 10;
WeightReduction = 30;
SetAttributes.AttackChance = 15;
SetAttributes.BonusDex = 8;
SetAttributes.WeaponSpeed = 30;
SetAttributes.WeaponDamage = 20;
}
public Feathernock(Serial serial)
: base(serial)
{
}
public override int LabelNumber => 1074324;// Feathernock (Marksman Set)
public override SetItem SetID => SetItem.Marksman;
public override int Pieces => 2;
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write(0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
} | {
"pile_set_name": "Github"
} |
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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 ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.data;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "person-object")
@XmlAccessorType(XmlAccessType.FIELD)
public class Person implements java.io.Serializable {
private String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
| {
"pile_set_name": "Github"
} |
using System;
using System.Threading;
using Microsoft.Kusto.ServiceLayer.LanguageServices;
using Microsoft.Kusto.ServiceLayer.LanguageServices.Contracts;
using NUnit.Framework;
namespace Microsoft.Kusto.ServiceLayer.UnitTests.LanguageServices
{
public class BindingQueueTests
{
[Test]
public void QueueBindingOperation_Returns_Null_For_NullBindOperation()
{
var bindingQueue = new BindingQueue<ConnectedBindingContext>();
var queueItem = bindingQueue.QueueBindingOperation("", null);
Assert.IsNull(queueItem);
}
[Test]
public void QueueBindingOperation_Returns_QueueItem()
{
var key = "key";
var bindOperation = new Func<IBindingContext, CancellationToken, object>((context, token) => new Hover());
Func<IBindingContext, object> timeoutOperation = (context) => LanguageService.HoverTimeout;
Func<Exception, object> errorHandler = exception => new Exception();
var bindingTimeout = 30;
var waitForLockTimeout = 45;
var bindingQueue = new BindingQueue<ConnectedBindingContext>();
var queueItem = bindingQueue.QueueBindingOperation(key,
bindOperation,
timeoutOperation,
errorHandler,
bindingTimeout,
waitForLockTimeout);
Assert.AreEqual(key, queueItem.Key);
Assert.AreEqual(bindOperation, queueItem.BindOperation);
Assert.AreEqual(timeoutOperation, queueItem.TimeoutOperation);
Assert.AreEqual(errorHandler, queueItem.ErrorHandler);
Assert.AreEqual(bindingTimeout, queueItem.BindingTimeout);
Assert.AreEqual(waitForLockTimeout, queueItem.WaitForLockTimeout);
}
}
} | {
"pile_set_name": "Github"
} |
.help-page h1,
.help-page .h1,
.help-page h2,
.help-page .h2,
.help-page h3,
.help-page .h3,
#body.help-page,
.help-page-table th,
.help-page-table pre,
.help-page-table p {
font-family: "Segoe UI Light", Frutiger, "Frutiger Linotype", "Dejavu Sans", "Helvetica Neue", Arial, sans-serif;
}
.help-page pre.wrapped {
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
white-space: pre-wrap;
}
.help-page .warning-message-container {
margin-top: 20px;
padding: 0 10px;
color: #525252;
background: #EFDCA9;
border: 1px solid #CCCCCC;
}
.help-page-table {
width: 100%;
border-collapse: collapse;
text-align: left;
margin: 0px 0px 20px 0px;
border-top: 1px solid #D4D4D4;
}
.help-page-table th {
text-align: left;
font-weight: bold;
border-bottom: 1px solid #D4D4D4;
padding: 5px 6px 5px 6px;
}
.help-page-table td {
border-bottom: 1px solid #D4D4D4;
padding: 10px 8px 10px 8px;
vertical-align: top;
}
.help-page-table pre,
.help-page-table p {
margin: 0px;
padding: 0px;
font-family: inherit;
font-size: 100%;
}
.help-page-table tbody tr:hover td {
background-color: #F3F3F3;
}
.help-page a:hover {
background-color: transparent;
}
.help-page .sample-header {
border: 2px solid #D4D4D4;
background: #00497E;
color: #FFFFFF;
padding: 8px 15px;
border-bottom: none;
display: inline-block;
margin: 10px 0px 0px 0px;
}
.help-page .sample-content {
display: block;
border-width: 0;
padding: 15px 20px;
background: #FFFFFF;
border: 2px solid #D4D4D4;
margin: 0px 0px 10px 0px;
}
.help-page .api-name {
width: 40%;
}
.help-page .api-documentation {
width: 60%;
}
.help-page .parameter-name {
width: 20%;
}
.help-page .parameter-documentation {
width: 40%;
}
.help-page .parameter-type {
width: 20%;
}
.help-page .parameter-annotations {
width: 20%;
}
.help-page h1,
.help-page .h1 {
font-size: 36px;
line-height: normal;
}
.help-page h2,
.help-page .h2 {
font-size: 24px;
}
.help-page h3,
.help-page .h3 {
font-size: 20px;
}
#body.help-page {
font-size: 14px;
line-height: 143%;
color: #333;
}
.help-page a {
color: #0000EE;
text-decoration: none;
}
| {
"pile_set_name": "Github"
} |
<?xml version='1.0' encoding='UTF-8'?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gu.identity</groupId>
<artifactId>identity-model_2.9.2</artifactId>
<packaging>jar</packaging>
<description>identity-model</description>
<version>3.40</version>
<name>identity-model</name>
<organization>
<name>com.gu.identity</name>
</organization>
<dependencies>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.novocode</groupId>
<artifactId>junit-interface</artifactId>
<version>0.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>1.6.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.6.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>0.9.28</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.liftweb</groupId>
<artifactId>lift-json_2.9.2</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.joda</groupId>
<artifactId>joda-convert</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.scalatest</groupId>
<artifactId>scalatest_2.9.2</artifactId>
<version>1.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>ScalaToolsRepository</id>
<name>Scala Tools Repository</name>
<url>https://oss.sonatype.org/content/groups/scala-tools/</url>
<layout>default</layout>
</repository>
<repository>
<id>GuardianNexusReleases</id>
<name>Guardian Nexus Releases</name>
<url>http://nexus.gudev.gnl:8081/nexus/content/repositories/releases/</url>
<layout>default</layout>
</repository>
<repository>
<id>GuardianPublicReleases</id>
<name>Guardian Public Releases</name>
<url>http://guardian.github.com/maven/repo-releases/</url>
<layout>default</layout>
</repository>
<repository>
<id>GuardianSnapshotReleases</id>
<name>Guardian Snapshot Releases</name>
<url>http://guardian.github.com/maven/repo-snapshots/</url>
<layout>default</layout>
</repository>
<repository>
<id>GuardianNexusThirdParty</id>
<name>Guardian Nexus Third Party</name>
<url>http://nexus.gudev.gnl:8081/nexus/content/repositories/thirdparty/</url>
<layout>default</layout>
</repository>
<repository>
<id>Asualrepository</id>
<name>Asual repository</name>
<url>http://www.asual.com/maven/content/repositories/releases/</url>
<layout>default</layout>
</repository>
<repository>
<id>BryanJSwiftRepository</id>
<name>Bryan J Swift Repository</name>
<url>http://repos.bryanjswift.com/maven2/</url>
<layout>default</layout>
</repository>
</repositories>
</project> | {
"pile_set_name": "Github"
} |
// Copyright 2014 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.
// +build darwin dragonfly freebsd linux netbsd openbsd
package test
import (
"bytes"
"testing"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
func TestAgentForward(t *testing.T) {
server := newServer(t)
defer server.Shutdown()
conn := server.Dial(clientConfig())
defer conn.Close()
keyring := agent.NewKeyring()
if err := keyring.Add(agent.AddedKey{PrivateKey: testPrivateKeys["dsa"]}); err != nil {
t.Fatalf("Error adding key: %s", err)
}
if err := keyring.Add(agent.AddedKey{
PrivateKey: testPrivateKeys["dsa"],
ConfirmBeforeUse: true,
LifetimeSecs: 3600,
}); err != nil {
t.Fatalf("Error adding key with constraints: %s", err)
}
pub := testPublicKeys["dsa"]
sess, err := conn.NewSession()
if err != nil {
t.Fatalf("NewSession: %v", err)
}
if err := agent.RequestAgentForwarding(sess); err != nil {
t.Fatalf("RequestAgentForwarding: %v", err)
}
if err := agent.ForwardToAgent(conn, keyring); err != nil {
t.Fatalf("SetupForwardKeyring: %v", err)
}
out, err := sess.CombinedOutput("ssh-add -L")
if err != nil {
t.Fatalf("running ssh-add: %v, out %s", err, out)
}
key, _, _, _, err := ssh.ParseAuthorizedKey(out)
if err != nil {
t.Fatalf("ParseAuthorizedKey(%q): %v", out, err)
}
if !bytes.Equal(key.Marshal(), pub.Marshal()) {
t.Fatalf("got key %s, want %s", ssh.MarshalAuthorizedKey(key), ssh.MarshalAuthorizedKey(pub))
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2009 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.
// Linux system calls.
// This file is compiled as ordinary Go code,
// but it is also input to mksyscall,
// which parses the //sys lines and generates system call stubs.
// Note that sometimes we use a lowercase //sys name and
// wrap it in our own nicer implementation.
package unix
import (
"syscall"
"unsafe"
)
/*
* Wrapped
*/
func Access(path string, mode uint32) (err error) {
return Faccessat(AT_FDCWD, path, mode, 0)
}
func Chmod(path string, mode uint32) (err error) {
return Fchmodat(AT_FDCWD, path, mode, 0)
}
func Chown(path string, uid int, gid int) (err error) {
return Fchownat(AT_FDCWD, path, uid, gid, 0)
}
func Creat(path string, mode uint32) (fd int, err error) {
return Open(path, O_CREAT|O_WRONLY|O_TRUNC, mode)
}
//sys fchmodat(dirfd int, path string, mode uint32) (err error)
func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) {
// Linux fchmodat doesn't support the flags parameter. Mimick glibc's behavior
// and check the flags. Otherwise the mode would be applied to the symlink
// destination which is not what the user expects.
if flags&^AT_SYMLINK_NOFOLLOW != 0 {
return EINVAL
} else if flags&AT_SYMLINK_NOFOLLOW != 0 {
return EOPNOTSUPP
}
return fchmodat(dirfd, path, mode)
}
//sys ioctl(fd int, req uint, arg uintptr) (err error)
// ioctl itself should not be exposed directly, but additional get/set
// functions for specific types are permissible.
// IoctlSetInt performs an ioctl operation which sets an integer value
// on fd, using the specified request number.
func IoctlSetInt(fd int, req uint, value int) error {
return ioctl(fd, req, uintptr(value))
}
func IoctlSetWinsize(fd int, req uint, value *Winsize) error {
return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
}
func IoctlSetTermios(fd int, req uint, value *Termios) error {
return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
}
// IoctlGetInt performs an ioctl operation which gets an integer value
// from fd, using the specified request number.
func IoctlGetInt(fd int, req uint) (int, error) {
var value int
err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
return value, err
}
func IoctlGetWinsize(fd int, req uint) (*Winsize, error) {
var value Winsize
err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
return &value, err
}
func IoctlGetTermios(fd int, req uint) (*Termios, error) {
var value Termios
err := ioctl(fd, req, uintptr(unsafe.Pointer(&value)))
return &value, err
}
//sys Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error)
func Link(oldpath string, newpath string) (err error) {
return Linkat(AT_FDCWD, oldpath, AT_FDCWD, newpath, 0)
}
func Mkdir(path string, mode uint32) (err error) {
return Mkdirat(AT_FDCWD, path, mode)
}
func Mknod(path string, mode uint32, dev int) (err error) {
return Mknodat(AT_FDCWD, path, mode, dev)
}
func Open(path string, mode int, perm uint32) (fd int, err error) {
return openat(AT_FDCWD, path, mode|O_LARGEFILE, perm)
}
//sys openat(dirfd int, path string, flags int, mode uint32) (fd int, err error)
func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) {
return openat(dirfd, path, flags|O_LARGEFILE, mode)
}
//sys ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error)
func Ppoll(fds []PollFd, timeout *Timespec, sigmask *Sigset_t) (n int, err error) {
if len(fds) == 0 {
return ppoll(nil, 0, timeout, sigmask)
}
return ppoll(&fds[0], len(fds), timeout, sigmask)
}
//sys Readlinkat(dirfd int, path string, buf []byte) (n int, err error)
func Readlink(path string, buf []byte) (n int, err error) {
return Readlinkat(AT_FDCWD, path, buf)
}
func Rename(oldpath string, newpath string) (err error) {
return Renameat(AT_FDCWD, oldpath, AT_FDCWD, newpath)
}
func Rmdir(path string) error {
return Unlinkat(AT_FDCWD, path, AT_REMOVEDIR)
}
//sys Symlinkat(oldpath string, newdirfd int, newpath string) (err error)
func Symlink(oldpath string, newpath string) (err error) {
return Symlinkat(oldpath, AT_FDCWD, newpath)
}
func Unlink(path string) error {
return Unlinkat(AT_FDCWD, path, 0)
}
//sys Unlinkat(dirfd int, path string, flags int) (err error)
//sys utimes(path string, times *[2]Timeval) (err error)
func Utimes(path string, tv []Timeval) error {
if tv == nil {
err := utimensat(AT_FDCWD, path, nil, 0)
if err != ENOSYS {
return err
}
return utimes(path, nil)
}
if len(tv) != 2 {
return EINVAL
}
var ts [2]Timespec
ts[0] = NsecToTimespec(TimevalToNsec(tv[0]))
ts[1] = NsecToTimespec(TimevalToNsec(tv[1]))
err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
if err != ENOSYS {
return err
}
return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
}
//sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error)
func UtimesNano(path string, ts []Timespec) error {
if ts == nil {
err := utimensat(AT_FDCWD, path, nil, 0)
if err != ENOSYS {
return err
}
return utimes(path, nil)
}
if len(ts) != 2 {
return EINVAL
}
err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
if err != ENOSYS {
return err
}
// If the utimensat syscall isn't available (utimensat was added to Linux
// in 2.6.22, Released, 8 July 2007) then fall back to utimes
var tv [2]Timeval
for i := 0; i < 2; i++ {
tv[i] = NsecToTimeval(TimespecToNsec(ts[i]))
}
return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
}
func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error {
if ts == nil {
return utimensat(dirfd, path, nil, flags)
}
if len(ts) != 2 {
return EINVAL
}
return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags)
}
//sys futimesat(dirfd int, path *byte, times *[2]Timeval) (err error)
func Futimesat(dirfd int, path string, tv []Timeval) error {
pathp, err := BytePtrFromString(path)
if err != nil {
return err
}
if tv == nil {
return futimesat(dirfd, pathp, nil)
}
if len(tv) != 2 {
return EINVAL
}
return futimesat(dirfd, pathp, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
}
func Futimes(fd int, tv []Timeval) (err error) {
// Believe it or not, this is the best we can do on Linux
// (and is what glibc does).
return Utimes("/proc/self/fd/"+itoa(fd), tv)
}
const ImplementsGetwd = true
//sys Getcwd(buf []byte) (n int, err error)
func Getwd() (wd string, err error) {
var buf [PathMax]byte
n, err := Getcwd(buf[0:])
if err != nil {
return "", err
}
// Getcwd returns the number of bytes written to buf, including the NUL.
if n < 1 || n > len(buf) || buf[n-1] != 0 {
return "", EINVAL
}
return string(buf[0 : n-1]), nil
}
func Getgroups() (gids []int, err error) {
n, err := getgroups(0, nil)
if err != nil {
return nil, err
}
if n == 0 {
return nil, nil
}
// Sanity check group count. Max is 1<<16 on Linux.
if n < 0 || n > 1<<20 {
return nil, EINVAL
}
a := make([]_Gid_t, n)
n, err = getgroups(n, &a[0])
if err != nil {
return nil, err
}
gids = make([]int, n)
for i, v := range a[0:n] {
gids[i] = int(v)
}
return
}
func Setgroups(gids []int) (err error) {
if len(gids) == 0 {
return setgroups(0, nil)
}
a := make([]_Gid_t, len(gids))
for i, v := range gids {
a[i] = _Gid_t(v)
}
return setgroups(len(a), &a[0])
}
type WaitStatus uint32
// Wait status is 7 bits at bottom, either 0 (exited),
// 0x7F (stopped), or a signal number that caused an exit.
// The 0x80 bit is whether there was a core dump.
// An extra number (exit code, signal causing a stop)
// is in the high bits. At least that's the idea.
// There are various irregularities. For example, the
// "continued" status is 0xFFFF, distinguishing itself
// from stopped via the core dump bit.
const (
mask = 0x7F
core = 0x80
exited = 0x00
stopped = 0x7F
shift = 8
)
func (w WaitStatus) Exited() bool { return w&mask == exited }
func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != exited }
func (w WaitStatus) Stopped() bool { return w&0xFF == stopped }
func (w WaitStatus) Continued() bool { return w == 0xFFFF }
func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 }
func (w WaitStatus) ExitStatus() int {
if !w.Exited() {
return -1
}
return int(w>>shift) & 0xFF
}
func (w WaitStatus) Signal() syscall.Signal {
if !w.Signaled() {
return -1
}
return syscall.Signal(w & mask)
}
func (w WaitStatus) StopSignal() syscall.Signal {
if !w.Stopped() {
return -1
}
return syscall.Signal(w>>shift) & 0xFF
}
func (w WaitStatus) TrapCause() int {
if w.StopSignal() != SIGTRAP {
return -1
}
return int(w>>shift) >> 8
}
//sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error)
func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) {
var status _C_int
wpid, err = wait4(pid, &status, options, rusage)
if wstatus != nil {
*wstatus = WaitStatus(status)
}
return
}
func Mkfifo(path string, mode uint32) error {
return Mknod(path, mode|S_IFIFO, 0)
}
func Mkfifoat(dirfd int, path string, mode uint32) error {
return Mknodat(dirfd, path, mode|S_IFIFO, 0)
}
func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) {
if sa.Port < 0 || sa.Port > 0xFFFF {
return nil, 0, EINVAL
}
sa.raw.Family = AF_INET
p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
p[0] = byte(sa.Port >> 8)
p[1] = byte(sa.Port)
for i := 0; i < len(sa.Addr); i++ {
sa.raw.Addr[i] = sa.Addr[i]
}
return unsafe.Pointer(&sa.raw), SizeofSockaddrInet4, nil
}
func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) {
if sa.Port < 0 || sa.Port > 0xFFFF {
return nil, 0, EINVAL
}
sa.raw.Family = AF_INET6
p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
p[0] = byte(sa.Port >> 8)
p[1] = byte(sa.Port)
sa.raw.Scope_id = sa.ZoneId
for i := 0; i < len(sa.Addr); i++ {
sa.raw.Addr[i] = sa.Addr[i]
}
return unsafe.Pointer(&sa.raw), SizeofSockaddrInet6, nil
}
func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) {
name := sa.Name
n := len(name)
if n >= len(sa.raw.Path) {
return nil, 0, EINVAL
}
sa.raw.Family = AF_UNIX
for i := 0; i < n; i++ {
sa.raw.Path[i] = int8(name[i])
}
// length is family (uint16), name, NUL.
sl := _Socklen(2)
if n > 0 {
sl += _Socklen(n) + 1
}
if sa.raw.Path[0] == '@' {
sa.raw.Path[0] = 0
// Don't count trailing NUL for abstract address.
sl--
}
return unsafe.Pointer(&sa.raw), sl, nil
}
// SockaddrLinklayer implements the Sockaddr interface for AF_PACKET type sockets.
type SockaddrLinklayer struct {
Protocol uint16
Ifindex int
Hatype uint16
Pkttype uint8
Halen uint8
Addr [8]byte
raw RawSockaddrLinklayer
}
func (sa *SockaddrLinklayer) sockaddr() (unsafe.Pointer, _Socklen, error) {
if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
return nil, 0, EINVAL
}
sa.raw.Family = AF_PACKET
sa.raw.Protocol = sa.Protocol
sa.raw.Ifindex = int32(sa.Ifindex)
sa.raw.Hatype = sa.Hatype
sa.raw.Pkttype = sa.Pkttype
sa.raw.Halen = sa.Halen
for i := 0; i < len(sa.Addr); i++ {
sa.raw.Addr[i] = sa.Addr[i]
}
return unsafe.Pointer(&sa.raw), SizeofSockaddrLinklayer, nil
}
// SockaddrNetlink implements the Sockaddr interface for AF_NETLINK type sockets.
type SockaddrNetlink struct {
Family uint16
Pad uint16
Pid uint32
Groups uint32
raw RawSockaddrNetlink
}
func (sa *SockaddrNetlink) sockaddr() (unsafe.Pointer, _Socklen, error) {
sa.raw.Family = AF_NETLINK
sa.raw.Pad = sa.Pad
sa.raw.Pid = sa.Pid
sa.raw.Groups = sa.Groups
return unsafe.Pointer(&sa.raw), SizeofSockaddrNetlink, nil
}
// SockaddrHCI implements the Sockaddr interface for AF_BLUETOOTH type sockets
// using the HCI protocol.
type SockaddrHCI struct {
Dev uint16
Channel uint16
raw RawSockaddrHCI
}
func (sa *SockaddrHCI) sockaddr() (unsafe.Pointer, _Socklen, error) {
sa.raw.Family = AF_BLUETOOTH
sa.raw.Dev = sa.Dev
sa.raw.Channel = sa.Channel
return unsafe.Pointer(&sa.raw), SizeofSockaddrHCI, nil
}
// SockaddrL2 implements the Sockaddr interface for AF_BLUETOOTH type sockets
// using the L2CAP protocol.
type SockaddrL2 struct {
PSM uint16
CID uint16
Addr [6]uint8
AddrType uint8
raw RawSockaddrL2
}
func (sa *SockaddrL2) sockaddr() (unsafe.Pointer, _Socklen, error) {
sa.raw.Family = AF_BLUETOOTH
psm := (*[2]byte)(unsafe.Pointer(&sa.raw.Psm))
psm[0] = byte(sa.PSM)
psm[1] = byte(sa.PSM >> 8)
for i := 0; i < len(sa.Addr); i++ {
sa.raw.Bdaddr[i] = sa.Addr[len(sa.Addr)-1-i]
}
cid := (*[2]byte)(unsafe.Pointer(&sa.raw.Cid))
cid[0] = byte(sa.CID)
cid[1] = byte(sa.CID >> 8)
sa.raw.Bdaddr_type = sa.AddrType
return unsafe.Pointer(&sa.raw), SizeofSockaddrL2, nil
}
// SockaddrCAN implements the Sockaddr interface for AF_CAN type sockets.
// The RxID and TxID fields are used for transport protocol addressing in
// (CAN_TP16, CAN_TP20, CAN_MCNET, and CAN_ISOTP), they can be left with
// zero values for CAN_RAW and CAN_BCM sockets as they have no meaning.
//
// The SockaddrCAN struct must be bound to the socket file descriptor
// using Bind before the CAN socket can be used.
//
// // Read one raw CAN frame
// fd, _ := Socket(AF_CAN, SOCK_RAW, CAN_RAW)
// addr := &SockaddrCAN{Ifindex: index}
// Bind(fd, addr)
// frame := make([]byte, 16)
// Read(fd, frame)
//
// The full SocketCAN documentation can be found in the linux kernel
// archives at: https://www.kernel.org/doc/Documentation/networking/can.txt
type SockaddrCAN struct {
Ifindex int
RxID uint32
TxID uint32
raw RawSockaddrCAN
}
func (sa *SockaddrCAN) sockaddr() (unsafe.Pointer, _Socklen, error) {
if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
return nil, 0, EINVAL
}
sa.raw.Family = AF_CAN
sa.raw.Ifindex = int32(sa.Ifindex)
rx := (*[4]byte)(unsafe.Pointer(&sa.RxID))
for i := 0; i < 4; i++ {
sa.raw.Addr[i] = rx[i]
}
tx := (*[4]byte)(unsafe.Pointer(&sa.TxID))
for i := 0; i < 4; i++ {
sa.raw.Addr[i+4] = tx[i]
}
return unsafe.Pointer(&sa.raw), SizeofSockaddrCAN, nil
}
// SockaddrALG implements the Sockaddr interface for AF_ALG type sockets.
// SockaddrALG enables userspace access to the Linux kernel's cryptography
// subsystem. The Type and Name fields specify which type of hash or cipher
// should be used with a given socket.
//
// To create a file descriptor that provides access to a hash or cipher, both
// Bind and Accept must be used. Once the setup process is complete, input
// data can be written to the socket, processed by the kernel, and then read
// back as hash output or ciphertext.
//
// Here is an example of using an AF_ALG socket with SHA1 hashing.
// The initial socket setup process is as follows:
//
// // Open a socket to perform SHA1 hashing.
// fd, _ := unix.Socket(unix.AF_ALG, unix.SOCK_SEQPACKET, 0)
// addr := &unix.SockaddrALG{Type: "hash", Name: "sha1"}
// unix.Bind(fd, addr)
// // Note: unix.Accept does not work at this time; must invoke accept()
// // manually using unix.Syscall.
// hashfd, _, _ := unix.Syscall(unix.SYS_ACCEPT, uintptr(fd), 0, 0)
//
// Once a file descriptor has been returned from Accept, it may be used to
// perform SHA1 hashing. The descriptor is not safe for concurrent use, but
// may be re-used repeatedly with subsequent Write and Read operations.
//
// When hashing a small byte slice or string, a single Write and Read may
// be used:
//
// // Assume hashfd is already configured using the setup process.
// hash := os.NewFile(hashfd, "sha1")
// // Hash an input string and read the results. Each Write discards
// // previous hash state. Read always reads the current state.
// b := make([]byte, 20)
// for i := 0; i < 2; i++ {
// io.WriteString(hash, "Hello, world.")
// hash.Read(b)
// fmt.Println(hex.EncodeToString(b))
// }
// // Output:
// // 2ae01472317d1935a84797ec1983ae243fc6aa28
// // 2ae01472317d1935a84797ec1983ae243fc6aa28
//
// For hashing larger byte slices, or byte streams such as those read from
// a file or socket, use Sendto with MSG_MORE to instruct the kernel to update
// the hash digest instead of creating a new one for a given chunk and finalizing it.
//
// // Assume hashfd and addr are already configured using the setup process.
// hash := os.NewFile(hashfd, "sha1")
// // Hash the contents of a file.
// f, _ := os.Open("/tmp/linux-4.10-rc7.tar.xz")
// b := make([]byte, 4096)
// for {
// n, err := f.Read(b)
// if err == io.EOF {
// break
// }
// unix.Sendto(hashfd, b[:n], unix.MSG_MORE, addr)
// }
// hash.Read(b)
// fmt.Println(hex.EncodeToString(b))
// // Output: 85cdcad0c06eef66f805ecce353bec9accbeecc5
//
// For more information, see: http://www.chronox.de/crypto-API/crypto/userspace-if.html.
type SockaddrALG struct {
Type string
Name string
Feature uint32
Mask uint32
raw RawSockaddrALG
}
func (sa *SockaddrALG) sockaddr() (unsafe.Pointer, _Socklen, error) {
// Leave room for NUL byte terminator.
if len(sa.Type) > 13 {
return nil, 0, EINVAL
}
if len(sa.Name) > 63 {
return nil, 0, EINVAL
}
sa.raw.Family = AF_ALG
sa.raw.Feat = sa.Feature
sa.raw.Mask = sa.Mask
typ, err := ByteSliceFromString(sa.Type)
if err != nil {
return nil, 0, err
}
name, err := ByteSliceFromString(sa.Name)
if err != nil {
return nil, 0, err
}
copy(sa.raw.Type[:], typ)
copy(sa.raw.Name[:], name)
return unsafe.Pointer(&sa.raw), SizeofSockaddrALG, nil
}
// SockaddrVM implements the Sockaddr interface for AF_VSOCK type sockets.
// SockaddrVM provides access to Linux VM sockets: a mechanism that enables
// bidirectional communication between a hypervisor and its guest virtual
// machines.
type SockaddrVM struct {
// CID and Port specify a context ID and port address for a VM socket.
// Guests have a unique CID, and hosts may have a well-known CID of:
// - VMADDR_CID_HYPERVISOR: refers to the hypervisor process.
// - VMADDR_CID_HOST: refers to other processes on the host.
CID uint32
Port uint32
raw RawSockaddrVM
}
func (sa *SockaddrVM) sockaddr() (unsafe.Pointer, _Socklen, error) {
sa.raw.Family = AF_VSOCK
sa.raw.Port = sa.Port
sa.raw.Cid = sa.CID
return unsafe.Pointer(&sa.raw), SizeofSockaddrVM, nil
}
func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) {
switch rsa.Addr.Family {
case AF_NETLINK:
pp := (*RawSockaddrNetlink)(unsafe.Pointer(rsa))
sa := new(SockaddrNetlink)
sa.Family = pp.Family
sa.Pad = pp.Pad
sa.Pid = pp.Pid
sa.Groups = pp.Groups
return sa, nil
case AF_PACKET:
pp := (*RawSockaddrLinklayer)(unsafe.Pointer(rsa))
sa := new(SockaddrLinklayer)
sa.Protocol = pp.Protocol
sa.Ifindex = int(pp.Ifindex)
sa.Hatype = pp.Hatype
sa.Pkttype = pp.Pkttype
sa.Halen = pp.Halen
for i := 0; i < len(sa.Addr); i++ {
sa.Addr[i] = pp.Addr[i]
}
return sa, nil
case AF_UNIX:
pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
sa := new(SockaddrUnix)
if pp.Path[0] == 0 {
// "Abstract" Unix domain socket.
// Rewrite leading NUL as @ for textual display.
// (This is the standard convention.)
// Not friendly to overwrite in place,
// but the callers below don't care.
pp.Path[0] = '@'
}
// Assume path ends at NUL.
// This is not technically the Linux semantics for
// abstract Unix domain sockets--they are supposed
// to be uninterpreted fixed-size binary blobs--but
// everyone uses this convention.
n := 0
for n < len(pp.Path) && pp.Path[n] != 0 {
n++
}
bytes := (*[10000]byte)(unsafe.Pointer(&pp.Path[0]))[0:n]
sa.Name = string(bytes)
return sa, nil
case AF_INET:
pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
sa := new(SockaddrInet4)
p := (*[2]byte)(unsafe.Pointer(&pp.Port))
sa.Port = int(p[0])<<8 + int(p[1])
for i := 0; i < len(sa.Addr); i++ {
sa.Addr[i] = pp.Addr[i]
}
return sa, nil
case AF_INET6:
pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
sa := new(SockaddrInet6)
p := (*[2]byte)(unsafe.Pointer(&pp.Port))
sa.Port = int(p[0])<<8 + int(p[1])
sa.ZoneId = pp.Scope_id
for i := 0; i < len(sa.Addr); i++ {
sa.Addr[i] = pp.Addr[i]
}
return sa, nil
case AF_VSOCK:
pp := (*RawSockaddrVM)(unsafe.Pointer(rsa))
sa := &SockaddrVM{
CID: pp.Cid,
Port: pp.Port,
}
return sa, nil
}
return nil, EAFNOSUPPORT
}
func Accept(fd int) (nfd int, sa Sockaddr, err error) {
var rsa RawSockaddrAny
var len _Socklen = SizeofSockaddrAny
nfd, err = accept(fd, &rsa, &len)
if err != nil {
return
}
sa, err = anyToSockaddr(&rsa)
if err != nil {
Close(nfd)
nfd = 0
}
return
}
func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error) {
var rsa RawSockaddrAny
var len _Socklen = SizeofSockaddrAny
nfd, err = accept4(fd, &rsa, &len, flags)
if err != nil {
return
}
if len > SizeofSockaddrAny {
panic("RawSockaddrAny too small")
}
sa, err = anyToSockaddr(&rsa)
if err != nil {
Close(nfd)
nfd = 0
}
return
}
func Getsockname(fd int) (sa Sockaddr, err error) {
var rsa RawSockaddrAny
var len _Socklen = SizeofSockaddrAny
if err = getsockname(fd, &rsa, &len); err != nil {
return
}
return anyToSockaddr(&rsa)
}
func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error) {
vallen := _Socklen(4)
err = getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen)
return value, err
}
func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error) {
var value IPMreq
vallen := _Socklen(SizeofIPMreq)
err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
return &value, err
}
func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) {
var value IPMreqn
vallen := _Socklen(SizeofIPMreqn)
err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
return &value, err
}
func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error) {
var value IPv6Mreq
vallen := _Socklen(SizeofIPv6Mreq)
err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
return &value, err
}
func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error) {
var value IPv6MTUInfo
vallen := _Socklen(SizeofIPv6MTUInfo)
err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
return &value, err
}
func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error) {
var value ICMPv6Filter
vallen := _Socklen(SizeofICMPv6Filter)
err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
return &value, err
}
func GetsockoptUcred(fd, level, opt int) (*Ucred, error) {
var value Ucred
vallen := _Socklen(SizeofUcred)
err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
return &value, err
}
func GetsockoptTCPInfo(fd, level, opt int) (*TCPInfo, error) {
var value TCPInfo
vallen := _Socklen(SizeofTCPInfo)
err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
return &value, err
}
// GetsockoptString returns the string value of the socket option opt for the
// socket associated with fd at the given socket level.
func GetsockoptString(fd, level, opt int) (string, error) {
buf := make([]byte, 256)
vallen := _Socklen(len(buf))
err := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
if err != nil {
if err == ERANGE {
buf = make([]byte, vallen)
err = getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
}
if err != nil {
return "", err
}
}
return string(buf[:vallen-1]), nil
}
func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) {
return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq))
}
// Keyctl Commands (http://man7.org/linux/man-pages/man2/keyctl.2.html)
// KeyctlInt calls keyctl commands in which each argument is an int.
// These commands are KEYCTL_REVOKE, KEYCTL_CHOWN, KEYCTL_CLEAR, KEYCTL_LINK,
// KEYCTL_UNLINK, KEYCTL_NEGATE, KEYCTL_SET_REQKEY_KEYRING, KEYCTL_SET_TIMEOUT,
// KEYCTL_ASSUME_AUTHORITY, KEYCTL_SESSION_TO_PARENT, KEYCTL_REJECT,
// KEYCTL_INVALIDATE, and KEYCTL_GET_PERSISTENT.
//sys KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) = SYS_KEYCTL
// KeyctlBuffer calls keyctl commands in which the third and fourth
// arguments are a buffer and its length, respectively.
// These commands are KEYCTL_UPDATE, KEYCTL_READ, and KEYCTL_INSTANTIATE.
//sys KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) = SYS_KEYCTL
// KeyctlString calls keyctl commands which return a string.
// These commands are KEYCTL_DESCRIBE and KEYCTL_GET_SECURITY.
func KeyctlString(cmd int, id int) (string, error) {
// We must loop as the string data may change in between the syscalls.
// We could allocate a large buffer here to reduce the chance that the
// syscall needs to be called twice; however, this is unnecessary as
// the performance loss is negligible.
var buffer []byte
for {
// Try to fill the buffer with data
length, err := KeyctlBuffer(cmd, id, buffer, 0)
if err != nil {
return "", err
}
// Check if the data was written
if length <= len(buffer) {
// Exclude the null terminator
return string(buffer[:length-1]), nil
}
// Make a bigger buffer if needed
buffer = make([]byte, length)
}
}
// Keyctl commands with special signatures.
// KeyctlGetKeyringID implements the KEYCTL_GET_KEYRING_ID command.
// See the full documentation at:
// http://man7.org/linux/man-pages/man3/keyctl_get_keyring_ID.3.html
func KeyctlGetKeyringID(id int, create bool) (ringid int, err error) {
createInt := 0
if create {
createInt = 1
}
return KeyctlInt(KEYCTL_GET_KEYRING_ID, id, createInt, 0, 0)
}
// KeyctlSetperm implements the KEYCTL_SETPERM command. The perm value is the
// key handle permission mask as described in the "keyctl setperm" section of
// http://man7.org/linux/man-pages/man1/keyctl.1.html.
// See the full documentation at:
// http://man7.org/linux/man-pages/man3/keyctl_setperm.3.html
func KeyctlSetperm(id int, perm uint32) error {
_, err := KeyctlInt(KEYCTL_SETPERM, id, int(perm), 0, 0)
return err
}
//sys keyctlJoin(cmd int, arg2 string) (ret int, err error) = SYS_KEYCTL
// KeyctlJoinSessionKeyring implements the KEYCTL_JOIN_SESSION_KEYRING command.
// See the full documentation at:
// http://man7.org/linux/man-pages/man3/keyctl_join_session_keyring.3.html
func KeyctlJoinSessionKeyring(name string) (ringid int, err error) {
return keyctlJoin(KEYCTL_JOIN_SESSION_KEYRING, name)
}
//sys keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) = SYS_KEYCTL
// KeyctlSearch implements the KEYCTL_SEARCH command.
// See the full documentation at:
// http://man7.org/linux/man-pages/man3/keyctl_search.3.html
func KeyctlSearch(ringid int, keyType, description string, destRingid int) (id int, err error) {
return keyctlSearch(KEYCTL_SEARCH, ringid, keyType, description, destRingid)
}
//sys keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) = SYS_KEYCTL
// KeyctlInstantiateIOV implements the KEYCTL_INSTANTIATE_IOV command. This
// command is similar to KEYCTL_INSTANTIATE, except that the payload is a slice
// of Iovec (each of which represents a buffer) instead of a single buffer.
// See the full documentation at:
// http://man7.org/linux/man-pages/man3/keyctl_instantiate_iov.3.html
func KeyctlInstantiateIOV(id int, payload []Iovec, ringid int) error {
return keyctlIOV(KEYCTL_INSTANTIATE_IOV, id, payload, ringid)
}
//sys keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) = SYS_KEYCTL
// KeyctlDHCompute implements the KEYCTL_DH_COMPUTE command. This command
// computes a Diffie-Hellman shared secret based on the provide params. The
// secret is written to the provided buffer and the returned size is the number
// of bytes written (returning an error if there is insufficient space in the
// buffer). If a nil buffer is passed in, this function returns the minimum
// buffer length needed to store the appropriate data. Note that this differs
// from KEYCTL_READ's behavior which always returns the requested payload size.
// See the full documentation at:
// http://man7.org/linux/man-pages/man3/keyctl_dh_compute.3.html
func KeyctlDHCompute(params *KeyctlDHParams, buffer []byte) (size int, err error) {
return keyctlDH(KEYCTL_DH_COMPUTE, params, buffer)
}
func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) {
var msg Msghdr
var rsa RawSockaddrAny
msg.Name = (*byte)(unsafe.Pointer(&rsa))
msg.Namelen = uint32(SizeofSockaddrAny)
var iov Iovec
if len(p) > 0 {
iov.Base = &p[0]
iov.SetLen(len(p))
}
var dummy byte
if len(oob) > 0 {
var sockType int
sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE)
if err != nil {
return
}
// receive at least one normal byte
if sockType != SOCK_DGRAM && len(p) == 0 {
iov.Base = &dummy
iov.SetLen(1)
}
msg.Control = &oob[0]
msg.SetControllen(len(oob))
}
msg.Iov = &iov
msg.Iovlen = 1
if n, err = recvmsg(fd, &msg, flags); err != nil {
return
}
oobn = int(msg.Controllen)
recvflags = int(msg.Flags)
// source address is only specified if the socket is unconnected
if rsa.Addr.Family != AF_UNSPEC {
from, err = anyToSockaddr(&rsa)
}
return
}
func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) {
_, err = SendmsgN(fd, p, oob, to, flags)
return
}
func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) {
var ptr unsafe.Pointer
var salen _Socklen
if to != nil {
var err error
ptr, salen, err = to.sockaddr()
if err != nil {
return 0, err
}
}
var msg Msghdr
msg.Name = (*byte)(ptr)
msg.Namelen = uint32(salen)
var iov Iovec
if len(p) > 0 {
iov.Base = &p[0]
iov.SetLen(len(p))
}
var dummy byte
if len(oob) > 0 {
var sockType int
sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE)
if err != nil {
return 0, err
}
// send at least one normal byte
if sockType != SOCK_DGRAM && len(p) == 0 {
iov.Base = &dummy
iov.SetLen(1)
}
msg.Control = &oob[0]
msg.SetControllen(len(oob))
}
msg.Iov = &iov
msg.Iovlen = 1
if n, err = sendmsg(fd, &msg, flags); err != nil {
return 0, err
}
if len(oob) > 0 && len(p) == 0 {
n = 0
}
return n, nil
}
// BindToDevice binds the socket associated with fd to device.
func BindToDevice(fd int, device string) (err error) {
return SetsockoptString(fd, SOL_SOCKET, SO_BINDTODEVICE, device)
}
//sys ptrace(request int, pid int, addr uintptr, data uintptr) (err error)
func ptracePeek(req int, pid int, addr uintptr, out []byte) (count int, err error) {
// The peek requests are machine-size oriented, so we wrap it
// to retrieve arbitrary-length data.
// The ptrace syscall differs from glibc's ptrace.
// Peeks returns the word in *data, not as the return value.
var buf [sizeofPtr]byte
// Leading edge. PEEKTEXT/PEEKDATA don't require aligned
// access (PEEKUSER warns that it might), but if we don't
// align our reads, we might straddle an unmapped page
// boundary and not get the bytes leading up to the page
// boundary.
n := 0
if addr%sizeofPtr != 0 {
err = ptrace(req, pid, addr-addr%sizeofPtr, uintptr(unsafe.Pointer(&buf[0])))
if err != nil {
return 0, err
}
n += copy(out, buf[addr%sizeofPtr:])
out = out[n:]
}
// Remainder.
for len(out) > 0 {
// We use an internal buffer to guarantee alignment.
// It's not documented if this is necessary, but we're paranoid.
err = ptrace(req, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0])))
if err != nil {
return n, err
}
copied := copy(out, buf[0:])
n += copied
out = out[copied:]
}
return n, nil
}
func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error) {
return ptracePeek(PTRACE_PEEKTEXT, pid, addr, out)
}
func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error) {
return ptracePeek(PTRACE_PEEKDATA, pid, addr, out)
}
func PtracePeekUser(pid int, addr uintptr, out []byte) (count int, err error) {
return ptracePeek(PTRACE_PEEKUSR, pid, addr, out)
}
func ptracePoke(pokeReq int, peekReq int, pid int, addr uintptr, data []byte) (count int, err error) {
// As for ptracePeek, we need to align our accesses to deal
// with the possibility of straddling an invalid page.
// Leading edge.
n := 0
if addr%sizeofPtr != 0 {
var buf [sizeofPtr]byte
err = ptrace(peekReq, pid, addr-addr%sizeofPtr, uintptr(unsafe.Pointer(&buf[0])))
if err != nil {
return 0, err
}
n += copy(buf[addr%sizeofPtr:], data)
word := *((*uintptr)(unsafe.Pointer(&buf[0])))
err = ptrace(pokeReq, pid, addr-addr%sizeofPtr, word)
if err != nil {
return 0, err
}
data = data[n:]
}
// Interior.
for len(data) > sizeofPtr {
word := *((*uintptr)(unsafe.Pointer(&data[0])))
err = ptrace(pokeReq, pid, addr+uintptr(n), word)
if err != nil {
return n, err
}
n += sizeofPtr
data = data[sizeofPtr:]
}
// Trailing edge.
if len(data) > 0 {
var buf [sizeofPtr]byte
err = ptrace(peekReq, pid, addr+uintptr(n), uintptr(unsafe.Pointer(&buf[0])))
if err != nil {
return n, err
}
copy(buf[0:], data)
word := *((*uintptr)(unsafe.Pointer(&buf[0])))
err = ptrace(pokeReq, pid, addr+uintptr(n), word)
if err != nil {
return n, err
}
n += len(data)
}
return n, nil
}
func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error) {
return ptracePoke(PTRACE_POKETEXT, PTRACE_PEEKTEXT, pid, addr, data)
}
func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error) {
return ptracePoke(PTRACE_POKEDATA, PTRACE_PEEKDATA, pid, addr, data)
}
func PtracePokeUser(pid int, addr uintptr, data []byte) (count int, err error) {
return ptracePoke(PTRACE_POKEUSR, PTRACE_PEEKUSR, pid, addr, data)
}
func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error) {
return ptrace(PTRACE_GETREGS, pid, 0, uintptr(unsafe.Pointer(regsout)))
}
func PtraceSetRegs(pid int, regs *PtraceRegs) (err error) {
return ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs)))
}
func PtraceSetOptions(pid int, options int) (err error) {
return ptrace(PTRACE_SETOPTIONS, pid, 0, uintptr(options))
}
func PtraceGetEventMsg(pid int) (msg uint, err error) {
var data _C_long
err = ptrace(PTRACE_GETEVENTMSG, pid, 0, uintptr(unsafe.Pointer(&data)))
msg = uint(data)
return
}
func PtraceCont(pid int, signal int) (err error) {
return ptrace(PTRACE_CONT, pid, 0, uintptr(signal))
}
func PtraceSyscall(pid int, signal int) (err error) {
return ptrace(PTRACE_SYSCALL, pid, 0, uintptr(signal))
}
func PtraceSingleStep(pid int) (err error) { return ptrace(PTRACE_SINGLESTEP, pid, 0, 0) }
func PtraceAttach(pid int) (err error) { return ptrace(PTRACE_ATTACH, pid, 0, 0) }
func PtraceDetach(pid int) (err error) { return ptrace(PTRACE_DETACH, pid, 0, 0) }
//sys reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error)
func Reboot(cmd int) (err error) {
return reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, cmd, "")
}
func ReadDirent(fd int, buf []byte) (n int, err error) {
return Getdents(fd, buf)
}
//sys mount(source string, target string, fstype string, flags uintptr, data *byte) (err error)
func Mount(source string, target string, fstype string, flags uintptr, data string) (err error) {
// Certain file systems get rather angry and EINVAL if you give
// them an empty string of data, rather than NULL.
if data == "" {
return mount(source, target, fstype, flags, nil)
}
datap, err := BytePtrFromString(data)
if err != nil {
return err
}
return mount(source, target, fstype, flags, datap)
}
// Sendto
// Recvfrom
// Socketpair
/*
* Direct access
*/
//sys Acct(path string) (err error)
//sys AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error)
//sys Adjtimex(buf *Timex) (state int, err error)
//sys Chdir(path string) (err error)
//sys Chroot(path string) (err error)
//sys ClockGettime(clockid int32, time *Timespec) (err error)
//sys Close(fd int) (err error)
//sys CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error)
//sys Dup(oldfd int) (fd int, err error)
//sys Dup3(oldfd int, newfd int, flags int) (err error)
//sysnb EpollCreate(size int) (fd int, err error)
//sysnb EpollCreate1(flag int) (fd int, err error)
//sysnb EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error)
//sys Eventfd(initval uint, flags int) (fd int, err error) = SYS_EVENTFD2
//sys Exit(code int) = SYS_EXIT_GROUP
//sys Faccessat(dirfd int, path string, mode uint32, flags int) (err error)
//sys Fallocate(fd int, mode uint32, off int64, len int64) (err error)
//sys Fchdir(fd int) (err error)
//sys Fchmod(fd int, mode uint32) (err error)
//sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)
//sys fcntl(fd int, cmd int, arg int) (val int, err error)
//sys Fdatasync(fd int) (err error)
//sys Flock(fd int, how int) (err error)
//sys Fsync(fd int) (err error)
//sys Getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64
//sysnb Getpgid(pid int) (pgid int, err error)
func Getpgrp() (pid int) {
pid, _ = Getpgid(0)
return
}
//sysnb Getpid() (pid int)
//sysnb Getppid() (ppid int)
//sys Getpriority(which int, who int) (prio int, err error)
//sys Getrandom(buf []byte, flags int) (n int, err error)
//sysnb Getrusage(who int, rusage *Rusage) (err error)
//sysnb Getsid(pid int) (sid int, err error)
//sysnb Gettid() (tid int)
//sys Getxattr(path string, attr string, dest []byte) (sz int, err error)
//sys InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error)
//sysnb InotifyInit1(flags int) (fd int, err error)
//sysnb InotifyRmWatch(fd int, watchdesc uint32) (success int, err error)
//sysnb Kill(pid int, sig syscall.Signal) (err error)
//sys Klogctl(typ int, buf []byte) (n int, err error) = SYS_SYSLOG
//sys Lgetxattr(path string, attr string, dest []byte) (sz int, err error)
//sys Listxattr(path string, dest []byte) (sz int, err error)
//sys Llistxattr(path string, dest []byte) (sz int, err error)
//sys Lremovexattr(path string, attr string) (err error)
//sys Lsetxattr(path string, attr string, data []byte, flags int) (err error)
//sys Mkdirat(dirfd int, path string, mode uint32) (err error)
//sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error)
//sys Nanosleep(time *Timespec, leftover *Timespec) (err error)
//sys PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT
//sysnb prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) = SYS_PRLIMIT64
//sys Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error)
//sys Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) = SYS_PSELECT6
//sys read(fd int, p []byte) (n int, err error)
//sys Removexattr(path string, attr string) (err error)
//sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error)
//sys RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error)
//sys Setdomainname(p []byte) (err error)
//sys Sethostname(p []byte) (err error)
//sysnb Setpgid(pid int, pgid int) (err error)
//sysnb Setsid() (pid int, err error)
//sysnb Settimeofday(tv *Timeval) (err error)
//sys Setns(fd int, nstype int) (err error)
// issue 1435.
// On linux Setuid and Setgid only affects the current thread, not the process.
// This does not match what most callers expect so we must return an error
// here rather than letting the caller think that the call succeeded.
func Setuid(uid int) (err error) {
return EOPNOTSUPP
}
func Setgid(uid int) (err error) {
return EOPNOTSUPP
}
//sys Setpriority(which int, who int, prio int) (err error)
//sys Setxattr(path string, attr string, data []byte, flags int) (err error)
//sys Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error)
//sys Sync()
//sys Syncfs(fd int) (err error)
//sysnb Sysinfo(info *Sysinfo_t) (err error)
//sys Tee(rfd int, wfd int, len int, flags int) (n int64, err error)
//sysnb Tgkill(tgid int, tid int, sig syscall.Signal) (err error)
//sysnb Times(tms *Tms) (ticks uintptr, err error)
//sysnb Umask(mask int) (oldmask int)
//sysnb Uname(buf *Utsname) (err error)
//sys Unmount(target string, flags int) (err error) = SYS_UMOUNT2
//sys Unshare(flags int) (err error)
//sys Ustat(dev int, ubuf *Ustat_t) (err error)
//sys write(fd int, p []byte) (n int, err error)
//sys exitThread(code int) (err error) = SYS_EXIT
//sys readlen(fd int, p *byte, np int) (n int, err error) = SYS_READ
//sys writelen(fd int, p *byte, np int) (n int, err error) = SYS_WRITE
// mmap varies by architecture; see syscall_linux_*.go.
//sys munmap(addr uintptr, length uintptr) (err error)
var mapper = &mmapper{
active: make(map[*byte][]byte),
mmap: mmap,
munmap: munmap,
}
func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
return mapper.Mmap(fd, offset, length, prot, flags)
}
func Munmap(b []byte) (err error) {
return mapper.Munmap(b)
}
//sys Madvise(b []byte, advice int) (err error)
//sys Mprotect(b []byte, prot int) (err error)
//sys Mlock(b []byte) (err error)
//sys Mlockall(flags int) (err error)
//sys Msync(b []byte, flags int) (err error)
//sys Munlock(b []byte) (err error)
//sys Munlockall() (err error)
// Vmsplice splices user pages from a slice of Iovecs into a pipe specified by fd,
// using the specified flags.
func Vmsplice(fd int, iovs []Iovec, flags int) (int, error) {
n, _, errno := Syscall6(
SYS_VMSPLICE,
uintptr(fd),
uintptr(unsafe.Pointer(&iovs[0])),
uintptr(len(iovs)),
uintptr(flags),
0,
0,
)
if errno != 0 {
return 0, syscall.Errno(errno)
}
return int(n), nil
}
/*
* Unimplemented
*/
// AfsSyscall
// Alarm
// ArchPrctl
// Brk
// Capget
// Capset
// ClockGetres
// ClockNanosleep
// ClockSettime
// Clone
// CreateModule
// DeleteModule
// EpollCtlOld
// EpollPwait
// EpollWaitOld
// Execve
// Fgetxattr
// Flistxattr
// Fork
// Fremovexattr
// Fsetxattr
// Futex
// GetKernelSyms
// GetMempolicy
// GetRobustList
// GetThreadArea
// Getitimer
// Getpmsg
// IoCancel
// IoDestroy
// IoGetevents
// IoSetup
// IoSubmit
// IoprioGet
// IoprioSet
// KexecLoad
// LookupDcookie
// Mbind
// MigratePages
// Mincore
// ModifyLdt
// Mount
// MovePages
// MqGetsetattr
// MqNotify
// MqOpen
// MqTimedreceive
// MqTimedsend
// MqUnlink
// Mremap
// Msgctl
// Msgget
// Msgrcv
// Msgsnd
// Nfsservctl
// Personality
// Pselect6
// Ptrace
// Putpmsg
// QueryModule
// Quotactl
// Readahead
// Readv
// RemapFilePages
// RestartSyscall
// RtSigaction
// RtSigpending
// RtSigprocmask
// RtSigqueueinfo
// RtSigreturn
// RtSigsuspend
// RtSigtimedwait
// SchedGetPriorityMax
// SchedGetPriorityMin
// SchedGetparam
// SchedGetscheduler
// SchedRrGetInterval
// SchedSetparam
// SchedYield
// Security
// Semctl
// Semget
// Semop
// Semtimedop
// SetMempolicy
// SetRobustList
// SetThreadArea
// SetTidAddress
// Shmat
// Shmctl
// Shmdt
// Shmget
// Sigaltstack
// Signalfd
// Swapoff
// Swapon
// Sysfs
// TimerCreate
// TimerDelete
// TimerGetoverrun
// TimerGettime
// TimerSettime
// Timerfd
// Tkill (obsolete)
// Tuxcall
// Umount2
// Uselib
// Utimensat
// Vfork
// Vhangup
// Vserver
// Waitid
// _Sysctl
| {
"pile_set_name": "Github"
} |
//---------------------------------------------------------------------------
// E L E N A P r o j e c t: ELENA Compiler
//
// This file contains ELENA Executive Linker class implementation
// Supported platforms: Linux32
// (C)2015-2020, by Alexei Rakov
//---------------------------------------------------------------------------
#include "elena.h"
// --------------------------------------------------------------------------
#include "linker.h"
#include "errors.h"
#include <elf.h>
#include <limits.h>
#include <sys/stat.h>
#define MAGIC_NUMBER "\x07F""ELF"
#define FILE_ALIGNMENT 0x0010
#define SECTION_ALIGNMENT 0x1000
#define IMAGE_BASE 0x08048000
#define HEADER_SIZE 0x0200
//#define TEXT_SECTION ".text"
//#define RDATA_SECTION ".rdata"
//#define DATA_SECTION ".data"
//#define BSS_SECTION ".bss"
//#define IMPORT_SECTION ".import"
//#define TLS_SECTION ".tls"
//#define DEBUG_SECTION ".debug"
#define ELF_HEADER_SIZE 0x34
#define ELF_PH_SIZE 0x20
#define INTERPRETER_PATH "/lib/ld-linux.so.2"
using namespace _ELENA_;
inline int getSize(Section* section)
{
return section ? section->Length() : 0;
}
// --- Reallocate ---
ref_t reallocate(ref_t pos, ref_t key, ref_t disp, void* map)
{
int base = ((ImageBaseMap*)map)->base + (key & ~mskAnyRef);
switch(key & mskImageMask) {
case mskCodeRef:
return ((ImageBaseMap*)map)->code + base + disp;
case mskRelCodeRef:
return (key & ~mskAnyRef) + disp - pos - 4;
case mskRDataRef:
return ((ImageBaseMap*)map)->rdata + base + disp;
case mskStatRef:
return ((ImageBaseMap*)map)->stat + base + disp;
case mskDataRef:
return ((ImageBaseMap*)map)->bss + base + disp;
// case mskTLSRef:
// return ((ImageBaseMap*)map)->tls + base + disp;
case mskImportRef:
{
int address = ((ImageBaseMap*)map)->base + ((ImageBaseMap*)map)->importMapping.get(key);
int v = ((ImageBaseMap*)map)->import + address + disp;
return ((ImageBaseMap*)map)->import + address + disp;
}
case mskMetaRef:
switch (key) {
case mskMessageTableRef:
return ((ImageBaseMap*)map)->mdata + ((ImageBaseMap*)map)->base;
case mskMetaAttributes:
return ((ImageBaseMap*)map)->adata + ((ImageBaseMap*)map)->base;
}
default:
return disp;
}
}
ref_t reallocateImport(ref_t pos, ref_t key, ref_t disp, void* map)
{
if ((key & mskImageMask)==mskImportRef) {
int base = ((ImageBaseMap*)map)->base + ((ImageBaseMap*)map)->importMapping.get(key);
return base + ((ImageBaseMap*)map)->import + disp;
}
else if ((key & mskImageMask)==mskRDataRef) {
int base = ((ImageBaseMap*)map)->base + (key & ~mskAnyRef);
return ((ImageBaseMap*)map)->rdata + base + disp;
}
else if ((key & mskImageMask)==mskCodeRef) {
int base = ((ImageBaseMap*)map)->base + (key & ~mskAnyRef);
return ((ImageBaseMap*)map)->code + base + disp;
}
else return disp;
}
// --- Linker ---
void Linker32 :: mapImage(ImageInfo& info)
{
int alignment = info.project->IntSetting(opSectionAlignment, SECTION_ALIGNMENT);
info.map.base = info.project->IntSetting(opImageBase, IMAGE_BASE);
info.ph_length = 4; // header + text + rdata + data
if (info.dynamic > 0) {
info.ph_length += 2; // if import table is not empty, append interpreter / dynamic
}
int adataSize = align(getSize(info.image->getADataSection()), 4);
int mdataSize = align(getSize(info.image->getMDataSection()), 4);
info.rdataOffset = adataSize + mdataSize;
info.headerSize = align(HEADER_SIZE, FILE_ALIGNMENT);
info.textSize = align(getSize(info.image->getTextSection()), FILE_ALIGNMENT);
info.rdataSize = align(getSize(info.image->getRDataSection()) + adataSize + mdataSize, FILE_ALIGNMENT);
info.importSize = align(getSize(info.image->getImportSection()), FILE_ALIGNMENT);
info.bssSize = align(getSize(info.image->getStatSection()), 4);
info.bssSize += align(getSize(info.image->getBSSSection()), 4);
// text segment
info.map.code = info.headerSize; // code section should always be first
// rodata segment
info.map.adata = align(info.map.code + getSize(info.image->getTextSection()), alignment);
// due to loader requirement, adjust offset
info.map.adata += ((info.headerSize + info.textSize) & (alignment - 1));
info.map.mdata = info.map.adata + adataSize;
info.map.rdata = info.map.mdata + mdataSize;
// data segment
info.map.import = align(info.map.rdata + getSize(info.image->getRDataSection()), alignment);
// due to loader requirement, adjust offset
if (info.importSize != 0)
info.map.import += ((info.headerSize + info.textSize + info.rdataSize) & (alignment - 1));
info.map.stat = align(info.map.import + getSize(info.image->getImportSection()), FILE_ALIGNMENT);
info.map.bss = align(info.map.stat + getSize(info.image->getStatSection()), FILE_ALIGNMENT);
/*
info.map.tls = align(info.map.stat + getSize(info.image->getStatSection()), alignment);
info.imageSize = align(info.map.debug + getSize(info.image->getDebugSection()), alignment);
*/
}
int Linker32 :: fillImportTable(ImageInfo& info)
{
int count = 0;
ReferenceMap::Iterator it = info.image->getExternalIt();
while (!it.Eof()) {
String<char, PATH_MAX> external(it.key());
int dotPos = ident_t(external).findLast('.') + 1;
ident_t function = external + dotPos;
IdentifierString dll(external + getlength(DLL_NAMESPACE) + 1, getlength(external) - getlength(DLL_NAMESPACE) - getlength(function) - 2);
if (dll.ident().compare(RTDLL_FORWARD)) {
dll.copy(info.project->resolvePrimitive(RTDLL_FORWARD));
}
info.functions.add(function.clone(), *it);
if (!retrieve(info.libraries.start(), dll.ident(), (char*)NULL)) {
info.libraries.add(dll.clone());
}
it++;
count++;
}
return count;
}
void Linker32 :: createImportData(ImageInfo& info)
{
size_t count = fillImportTable(info);
if (count == 0)
return;
Section* import = info.image->getImportSection();
// dynamic table
MemoryWriter dynamicWriter(info.image->getRDataSection());
dynamicWriter.align(FILE_ALIGNMENT, 0);
info.dynamic = dynamicWriter.Position();
// reference to GOT
ref_t importRef = (count + 1) | mskImportRef;
info.map.importMapping.add(importRef, 0);
// reserve got table
MemoryWriter gotWriter(import);
gotWriter.writeRef(mskRDataRef, info.dynamic);
gotWriter.writeDWord(0);
gotWriter.writeDWord(0);
size_t gotStart = gotWriter.Position();
gotWriter.writeBytes(0, count * 4);
gotWriter.seek(gotStart);
// reserve relocation table
MemoryWriter reltabWriter(import);
size_t reltabOffset = reltabWriter.Position();
reltabWriter.writeBytes(0, count * 8);
reltabWriter.seek(reltabOffset);
// reserve symbol table
MemoryWriter symtabWriter(import);
size_t symtabOffset = symtabWriter.Position();
symtabWriter.writeBytes(0, (count + 1) * 16);
symtabWriter.seek(symtabOffset + 16);
// string table
MemoryWriter strWriter(import);
int strOffset = strWriter.Position();
strWriter.writeChar('\0');
// code writer
MemoryWriter codeWriter(info.image->getTextSection());
writePLTStartEntry(codeWriter, importRef);
ImportReferences::Iterator fun = info.functions.start();
int symbolIndex = 1;
int pltIndex = 1;
while (!fun.Eof()) {
int gotPosition = gotWriter.Position();
// map import reference
info.map.importMapping.add(*fun, gotWriter.Position());
int strIndex = strWriter.Position() - strOffset;
// symbol table entry
symtabWriter.writeDWord(strIndex);
symtabWriter.writeDWord(0);
symtabWriter.writeDWord(0);
symtabWriter.writeDWord(0x12);
// relocation table entry
size_t relPosition = reltabWriter.Position() - reltabOffset;
reltabWriter.writeRef(importRef, gotPosition);
reltabWriter.writeDWord((symbolIndex << 8) + R_386_JMP_SLOT);
// string table entry
strWriter.writeLiteral(fun.key());
// got / plt entry
ref_t position = writePLTEntry(codeWriter, relPosition, importRef, gotPosition, pltIndex);
gotWriter.writeRef(mskCodeRef, position);
fun++;
symbolIndex++;
pltIndex++;
}
// write dynamic segment
// write libraries needed to be loaded
List<char*>::Iterator dll = info.libraries.start();
while (!dll.Eof()) {
dynamicWriter.writeDWord(DT_NEEDED);
dynamicWriter.writeDWord(strWriter.Position() - strOffset);
strWriter.writeLiteral(*dll);
dll++;
}
strWriter.writeChar('\0');
int strLength = strWriter.Position() - strOffset;
dynamicWriter.writeDWord(DT_STRTAB);
dynamicWriter.writeRef(importRef, strOffset);
dynamicWriter.writeDWord(DT_SYMTAB);
dynamicWriter.writeRef(importRef, symtabOffset);
dynamicWriter.writeDWord(DT_STRSZ);
dynamicWriter.writeDWord(strLength);
dynamicWriter.writeDWord(DT_SYMENT);
dynamicWriter.writeDWord(16);
dynamicWriter.writeDWord(DT_PLTGOT);
dynamicWriter.writeRef(importRef, /*gotStart*/0);
dynamicWriter.writeDWord(DT_PLTRELSZ);
dynamicWriter.writeDWord(count * 8);
dynamicWriter.writeDWord(DT_PLTREL);
dynamicWriter.writeDWord(DT_REL);
dynamicWriter.writeDWord(DT_JMPREL);
dynamicWriter.writeRef(importRef, reltabOffset);
dynamicWriter.writeDWord(DT_REL);
dynamicWriter.writeRef(importRef, reltabOffset);
dynamicWriter.writeDWord(DT_RELSZ);
dynamicWriter.writeDWord(count * 8);
dynamicWriter.writeDWord(DT_RELENT);
dynamicWriter.writeDWord(8);
dynamicWriter.writeDWord(0);
dynamicWriter.writeDWord(0);
// write interpreter path
dynamicWriter.align(FILE_ALIGNMENT, 0);
info.interpreter = dynamicWriter.Position();
dynamicWriter.writeLiteral(INTERPRETER_PATH, getlength(INTERPRETER_PATH) + 1);
}
void Linker32 :: fixImage(ImageInfo& info)
{
Section* text = info.image->getTextSection();
Section* rdata = info.image->getRDataSection();
Section* import = info.image->getImportSection();
Section* stat = info.image->getStatSection();
Section* bss = info.image->getBSSSection();
Section* adata = info.image->getADataSection();
Section* mdata = info.image->getMDataSection();
// Section* tls = info.image->getTLSSection();
// fix up text reallocate
text->fixupReferences(&info.map, reallocate);
// fix up rdata section
rdata->fixupReferences(&info.map, reallocate);
// fix up mdata section
mdata->fixupReferences(&info.map, reallocate);
// fix up adata section
adata->fixupReferences(&info.map, reallocate);
// fix up bss section
bss->fixupReferences(&info.map, reallocate);
// fix up stat section
stat->fixupReferences(&info.map, reallocate);
// // fix up tls section
// tls->fixupReferences(&info.map, reallocate);
// fix up import section
import->fixupReferences(&info.map, reallocateImport);
// fix up debug info if enabled
if (info.withDebugInfo) {
Section* debug = info.image->getDebugSection();
debug->fixupReferences(&info.map, reallocate);
}
}
void Linker32 :: writeSection(FileWriter* file, Section* section, int alignment)
{
MemoryReader reader(section);
file->read(&reader, section->Length());
file->align(alignment);
}
void Linker32 :: writeELFHeader(ImageInfo& info, FileWriter* file)
{
Elf32_Ehdr header;
// e_ident
memset(header.e_ident, 0, EI_NIDENT);
memcpy(header.e_ident, MAGIC_NUMBER, 4);
header.e_ident[EI_CLASS] = ELFCLASS32;
header.e_ident[EI_DATA] = ELFDATA2LSB;
header.e_ident[EI_VERSION] = EV_CURRENT;
header.e_type = ET_EXEC;
header.e_machine = EM_386;
header.e_version = EV_CURRENT;
header.e_entry = info.map.base + info.map.code + info.entryPoint;
header.e_phoff = ELF_HEADER_SIZE;
header.e_shoff = 0;
header.e_flags = 0;
header.e_ehsize = 0;
header.e_phentsize = ELF_PH_SIZE;
header.e_phnum = info.ph_length;
header.e_shentsize = 0x28;
header.e_shnum = 0;
header.e_shstrndx = SHN_UNDEF;
file->write((char*)&header, ELF_HEADER_SIZE);
}
void Linker32 :: writePHTable(ImageInfo& info, FileWriter* file)
{
int alignment = info.project->IntSetting(opSectionAlignment, SECTION_ALIGNMENT);
Elf32_Phdr ph_header;
// Program header
ph_header.p_type = PT_PHDR;
ph_header.p_offset = ELF_HEADER_SIZE;
ph_header.p_vaddr = info.map.base + ELF_HEADER_SIZE;
ph_header.p_paddr = info.map.base + ELF_HEADER_SIZE;
ph_header.p_filesz = info.ph_length * ELF_PH_SIZE;
ph_header.p_memsz = info.ph_length * ELF_PH_SIZE;
ph_header.p_flags = PF_R;
ph_header.p_align = 4;
file->write((char*)&ph_header, ELF_PH_SIZE);
if (info.interpreter > 0) {
// Interpreter
ph_header.p_type = PT_INTERP;
ph_header.p_offset = info.textSize + info.headerSize + info.interpreter + info.rdataOffset;
ph_header.p_paddr = ph_header.p_vaddr = info.map.base + info.map.rdata + info.interpreter;
ph_header.p_memsz = ph_header.p_filesz = getlength(INTERPRETER_PATH) + 1;
ph_header.p_flags = PF_R;
ph_header.p_align = 1;
file->write((char*)&ph_header, ELF_PH_SIZE);
}
// Text Segment
ph_header.p_type = PT_LOAD;
ph_header.p_offset = 0;
ph_header.p_vaddr = info.map.base;
ph_header.p_paddr = info.map.base;
ph_header.p_memsz = ph_header.p_filesz = info.headerSize + info.textSize;
ph_header.p_flags = PF_R + PF_X;
ph_header.p_align = alignment;
file->write((char*)&ph_header, ELF_PH_SIZE);
// RData Segment
ph_header.p_type = PT_LOAD;
ph_header.p_offset = info.headerSize + info.textSize;
ph_header.p_vaddr = info.map.base + info.map.adata;
ph_header.p_paddr = info.map.base + info.map.adata;
ph_header.p_memsz = ph_header.p_filesz = info.rdataSize;
ph_header.p_flags = PF_R;
ph_header.p_align = alignment;
file->write((char*)&ph_header, ELF_PH_SIZE);
// Data Segment
ph_header.p_type = PT_LOAD;
if (info.importSize != 0) {
ph_header.p_offset = info.headerSize + info.textSize + info.rdataSize;
}
else ph_header.p_offset = 0;
ph_header.p_paddr = ph_header.p_vaddr = info.map.base + info.map.import;
ph_header.p_memsz = info.importSize + info.bssSize;
ph_header.p_filesz = info.importSize;
ph_header.p_flags = PF_R + PF_W;
ph_header.p_align = alignment;
file->write((char*)&ph_header, ELF_PH_SIZE);
if (info.dynamic > 0) {
// Dynamic
ph_header.p_type = PT_DYNAMIC;
ph_header.p_offset = info.headerSize + info.textSize + info.dynamic + info.rdataOffset;
ph_header.p_paddr = ph_header.p_vaddr = info.map.base + info.map.rdata + info.dynamic;
ph_header.p_filesz = ph_header.p_memsz = align(info.interpreter - info.dynamic, 8);
ph_header.p_flags = PF_R;
ph_header.p_align = 8;
file->write((char*)&ph_header, ELF_PH_SIZE);
}
}
void Linker32 :: writeSegments(ImageInfo& info, FileWriter* file)
{
// text section
writeSection(file, info.image->getTextSection(), FILE_ALIGNMENT);
// rdata section
writeSection(file, info.image->getADataSection(), 4);
writeSection(file, info.image->getMDataSection(), 4);
writeSection(file, info.image->getRDataSection(), FILE_ALIGNMENT);
// import section
writeSection(file, info.image->getImportSection(), FILE_ALIGNMENT);
}
bool Linker32 :: createExecutable(ImageInfo& info, const char* exePath/*, ref_t tls_directory*/)
{
// create a full path (including none existing directories)
Path dirPath;
dirPath.copySubPath(exePath);
Path::create(NULL, exePath);
FileWriter executable(exePath, feRaw, false);
if (!executable.isOpened())
return false;
writeELFHeader(info, &executable);
writePHTable(info, &executable);
//int p = executable.Position();
if (info.headerSize >= executable.Position()) {
executable.writeBytes(0, info.headerSize - executable.Position());
}
else throw InternalError(errFatalLinker);
writeSegments(info, &executable);
return true;
}
bool Linker32 :: createDebugFile(ImageInfo& info, const char* debugFilePath)
{
FileWriter debugFile(debugFilePath, feRaw, false);
if (!debugFile.isOpened())
return false;
Section* debugInfo = info.image->getDebugSection();
// signature
debugFile.write(DEBUG_MODULE_SIGNATURE, strlen(DEBUG_MODULE_SIGNATURE));
// save entry point
ref_t imageBase = info.project->IntSetting(opImageBase, IMAGE_BASE);
ref_t entryPoint = info.map.code + info.map.base + info.image->getDebugEntryPoint();
debugFile.writeDWord(debugInfo->Length());
debugFile.writeDWord(entryPoint);
// save DebugInfo
MemoryReader reader(debugInfo);
debugFile.read(&reader, debugInfo->Length());
return true;
}
void Linker32 :: run(Project& project, Image& image/*, ref_t tls_directory*/)
{
ImageInfo info(&project, &image);
info.entryPoint = image.getEntryPoint();
createImportData(info);
mapImage(info);
fixImage(info);
Path path(project.StrSetting(opTarget));
if (emptystr(path))
throw InternalError(errEmptyTarget);
if (!createExecutable(info, path/*, tls_directory*/))
project.raiseError(errCannotCreate, path.c_str());
chmod(path, S_IXOTH | S_IXUSR | S_IRUSR | S_IWUSR | S_IROTH | S_IWOTH);
if (info.withDebugInfo) {
Path debugPath(path);
debugPath.changeExtension("dn");
if (!createDebugFile(info, debugPath.c_str())) {
ident_t target = project.StrSetting(opTarget);
IdentifierString fileNameArg(target);
fileNameArg.truncate(target.findLast('.', fileNameArg.Length()));
fileNameArg.append(".dn");
project.raiseError(errCannotCreate, fileNameArg.c_str());
}
}
}
// --- I386Linjer32 ---
void I386Linker32 :: writePLTStartEntry(MemoryWriter& codeWriter, ref_t gotReference)
{
codeWriter.writeWord(0x35FF);
codeWriter.writeRef(gotReference, 4);
codeWriter.writeWord(0x25FF);
codeWriter.writeRef(gotReference, 8);
codeWriter.writeDWord(0);
}
size_t I386Linker32 :: writePLTEntry(MemoryWriter& codeWriter, int symbolIndex, ref_t gotReference, int gotOffset, int entryIndex)
{
codeWriter.writeWord(0x25FF);
codeWriter.writeRef(gotReference, gotOffset);
size_t position = codeWriter.Position();
codeWriter.writeByte(0x68);
codeWriter.writeDWord(symbolIndex);
codeWriter.writeByte(0xE9);
codeWriter.writeDWord(0x10*(-1-entryIndex));
return position;
}
| {
"pile_set_name": "Github"
} |
//Apache2, 2014-present, WinterDev
using System;
using PixelFarm.Drawing;
using LayoutFarm.RenderBoxes;
namespace LayoutFarm
{
public abstract partial class RenderElement : IRenderElement
{
//------
//TODO: check if we can remove the _rootGfx here or not ***
//check if all rendering should occur on a single thread?
//------
IParentLink _parentLink;
object _controller;
internal int _propFlags;
public RenderElement(int width, int height)
{
_b_width = width;
_b_height = height;
NeedClipArea = true;
#if DEBUG
dbug_totalObjectId++;
dbug_obj_id = dbug_totalObjectId;
#endif
}
#if DEBUG
/// <summary>
/// on hardware-rendering backing, the system will try to provide a software rendering surface for this element
/// </summary>
public bool dbugPreferSoftwareRenderer { get; set; }
#endif
public bool NeedClipArea { get; set; }
//
protected virtual RootGraphic Root => null;
public RootGraphic GetRoot()
{
//recursive
RootGraphic root = Root;//local root
if (root != null) return root;
return _parentLink?.ParentRenderElement?.GetRoot();//recursive
}
//
public IContainerRenderElement GetTopWindowRenderBox()
{
if (_parentLink == null) { return null; }
return GetRoot()?.TopWindowRenderBox as IContainerRenderElement;
}
//==============================================================
//controller-listener
public object GetController() => _controller;
public void SetController(object controller)
{
_controller = controller;
}
public bool TransparentForMouseEvents
{
get => (_propFlags & RenderElementConst.TRANSPARENT_FOR_MOUSE_INPUT) != 0;
set
{
_propFlags = value ?
_propFlags | RenderElementConst.TRANSPARENT_FOR_MOUSE_INPUT :
_propFlags & ~RenderElementConst.TRANSPARENT_FOR_MOUSE_INPUT;
}
}
internal static void TrackBubbleUpdateLocalStatus(RenderElement renderE)
{
renderE._propFlags |= RenderElementConst.TRACKING_GFX;
}
internal static void ResetBubbleUpdateLocalStatus(RenderElement renderE)
{
#if DEBUG
if (RenderElement.IsBubbleGfxUpdateTrackedTip(renderE))
{
if (!dbugTrackingTipElems.ContainsKey(renderE))
{
throw new NotSupportedException();
}
dbugTrackingTipElems.Remove(renderE);
}
#endif
renderE._propFlags &= ~(RenderElementConst.TRACKING_GFX | RenderElementConst.TRACKING_GFX_TIP | RenderElementConst.TRACKING_GFX_In_UPDATE_RGN_QUEUE);
//renderE._propFlags &= ~(RenderElementConst.TRACKING_GFX);
//renderE._propFlags &= ~(RenderElementConst.TRACKING_GFX_TIP);
}
#if DEBUG
internal static int dbugUpdateTrackingCount => dbugTrackingTipElems.Count;
readonly static System.Collections.Generic.Dictionary<RenderElement, bool> dbugTrackingTipElems = new System.Collections.Generic.Dictionary<RenderElement, bool>();
#endif
internal static void MarkAsGfxUpdateTip(RenderElement renderE)
{
#if DEBUG
if (dbugTrackingTipElems.ContainsKey(renderE))
{
//throw new NotSupportedException();
}
dbugTrackingTipElems[renderE] = true;
#endif
renderE._propFlags |= RenderElementConst.TRACKING_GFX_TIP;
}
internal static void MarkAsInUpdateRgnQueue(RenderElement renderE)
{
renderE._propFlags |= RenderElementConst.TRACKING_GFX_In_UPDATE_RGN_QUEUE;
}
internal static bool IsBubbleGfxUpdateTracked(RenderElement re) => (re._propFlags & RenderElementConst.TRACKING_GFX) != 0;
internal static bool IsBubbleGfxUpdateTrackedTip(RenderElement re) => (re._propFlags & RenderElementConst.TRACKING_GFX_TIP) != 0;
internal static bool IsInUpdateRgnQueue(RenderElement re) => (re._propFlags & RenderElementConst.TRACKING_GFX_In_UPDATE_RGN_QUEUE) != 0;
//==============================================================
protected bool HasParentLink => _parentLink != null;
public RenderElement ParentRenderElement
{
get
{
if (_parentLink == null)
{
return null;
}
#if DEBUG
if (_parentLink.ParentRenderElement == this)
{
throw new NotSupportedException();
}
#endif
return _parentLink.ParentRenderElement;
}
}
public static void RemoveParentLink(RenderElement childElement)
{
childElement._parentLink = null;
}
public static void SetParentLink(RenderElement childElement, IParentLink parentLink)
{
childElement._parentLink = parentLink;
#if DEBUG
if (childElement.ParentRenderElement == childElement)
{
//error!
throw new NotSupportedException();
}
#endif
}
public bool MayHasChild
{
get => (_propFlags & RenderElementConst.MAY_HAS_CHILD) != 0;
protected set
{
_propFlags = value ?
_propFlags | RenderElementConst.MAY_HAS_CHILD :
_propFlags & ~RenderElementConst.MAY_HAS_CHILD;
}
}
public bool MayHasViewport
{
get => (_propFlags & RenderElementConst.MAY_HAS_VIEWPORT) != 0;
protected set
{
_propFlags = value ?
_propFlags | RenderElementConst.MAY_HAS_VIEWPORT :
_propFlags & ~RenderElementConst.MAY_HAS_VIEWPORT;
}
}
public bool NeedPreRenderEval
{
get => (_propFlags & RenderElementConst.NEED_PRE_RENDER_EVAL) != 0;
protected set
{
_propFlags = value ?
_propFlags | RenderElementConst.NEED_PRE_RENDER_EVAL :
_propFlags & ~RenderElementConst.NEED_PRE_RENDER_EVAL;
}
}
public virtual void ChildrenHitTestCore(HitChain hitChain)
{
}
//==============================================================
//
public bool Visible => (_propFlags & RenderElementConst.HIDDEN) == 0;
//
public void SetVisible(bool value)
{
//check if visible change?
if (this.Visible != value)
{
_propFlags = value ?
_propFlags & ~RenderElementConst.HIDDEN :
_propFlags | RenderElementConst.HIDDEN;
if (_parentLink != null)
{
if (this.NeedClipArea)
{
this.InvalidateParentGraphics(this.RectBounds);
}
else
{
RenderElement firstClipRenderElemParent = GetFirstClipParentRenderElement(this);
if (firstClipRenderElemParent != null)
{
firstClipRenderElemParent.InvalidateGraphics();
}
}
}
}
}
static RenderElement GetFirstClipParentRenderElement(RenderElement re)
{
RenderElement p = re.ParentRenderElement;
if (p != null)
{
while (!p.NeedClipArea)
{
RenderElement parent = p.ParentRenderElement;
if (parent == null)
{
return p;
}
p = parent;
}
return p;
}
return re;
}
public bool IsTopWindow
{
get => (_propFlags & RenderElementConst.IS_TOP_RENDERBOX) != 0;
protected set => _propFlags = value ?
_propFlags | RenderElementConst.IS_TOP_RENDERBOX :
_propFlags & ~RenderElementConst.IS_TOP_RENDERBOX;
}
internal bool HasDoubleScrollableSurface
{
get => (_propFlags & RenderElementConst.HAS_DOUBLE_SCROLL_SURFACE) != 0;
set => _propFlags = value ?
_propFlags | RenderElementConst.HAS_DOUBLE_SCROLL_SURFACE :
_propFlags & ~RenderElementConst.HAS_DOUBLE_SCROLL_SURFACE;
}
//==============================================================
//hit test
public virtual bool HasCustomHitTest => false;
protected virtual bool CustomHitTest(HitChain hitChain) => false;
public bool HitTestCore(HitChain hitChain)
{
#if DEBUG
if (hitChain.dbugHitPhase == dbugHitChainPhase.MouseDown)
{
}
#endif
if ((_propFlags & RenderElementConst.HIDDEN) != 0)
{
return false;
}
hitChain.GetTestPoint(out int testX, out int testY);
if ((testY >= _b_top && testY <= (_b_top + _b_height)
&& (testX >= _b_left && testX <= (_b_left + _b_width))))
{
if (this.MayHasViewport)
{
hitChain.OffsetTestPoint(
-_b_left + this.ViewportLeft,
-_b_top + this.ViewportTop);
}
else
{
hitChain.OffsetTestPoint(-_b_left, -_b_top);
}
bool customHit = false;
bool customHitResult = false;
if (HasCustomHitTest)
{
customHit = true;
customHitResult = CustomHitTest(hitChain);
}
else
{
hitChain.AddHitObject(this);
if (this.MayHasChild)
{
this.ChildrenHitTestCore(hitChain);
}
}
if (this.MayHasViewport)
{
hitChain.OffsetTestPoint(
_b_left - this.ViewportLeft,
_b_top - this.ViewportTop);
}
else
{
hitChain.OffsetTestPoint(_b_left, _b_top);
}
if (customHit) return customHitResult;
if ((_propFlags & RenderElementConst.TRANSPARENT_FOR_MOUSE_INPUT) != 0 &&
hitChain.Exclude_TransparentMouse_Element &&
hitChain.TopMostElement == this)
{
hitChain.RemoveCurrentHit();
return false;
}
else
{
return true;
}
}
else
{
//not visual hit on this object..
if (NeedClipArea)
{
return false;
}
//---
//if this RenderElement not need clip area
//we should test on its child
int preTestCount = hitChain.Count;
if (this.MayHasViewport)
{
hitChain.OffsetTestPoint(
-_b_left + this.ViewportLeft,
-_b_top + this.ViewportTop);
}
else
{
hitChain.OffsetTestPoint(-_b_left, -_b_top);
}
bool customHit = false;
bool customHitResult = false;
if (HasCustomHitTest)
{
customHit = true;
customHitResult = CustomHitTest(hitChain);
}
else
{
if (this.MayHasChild)
{
this.ChildrenHitTestCore(hitChain);
}
}
if (this.MayHasViewport)
{
hitChain.OffsetTestPoint(
_b_left - this.ViewportLeft,
_b_top - this.ViewportTop);
}
else
{
hitChain.OffsetTestPoint(_b_left, _b_top);
}
if (customHit) return customHitResult;
return this.TransparentForMouseEvents ?
false : //by-pass this element and go to next underlying sibling
hitChain.Count > preTestCount;
}
}
//==============================================================
//RenderClientContent()...
//if we set MayHasViewport = true, the root graphics will be offset the proper position
//if we set MayHasViewport= false, we need to offset the root graphics manually.
protected abstract void RenderClientContent(DrawBoard d, UpdateArea updateArea);
protected virtual void PreRenderEvaluation(DrawBoard d)
{
//need to set flags RenderElementConst.NEED_PRE_RENDER_EVAL to _propFlags
}
public static void InvokePreRenderEvaluation(RenderElement r)
{
r.PreRenderEvaluation(null);
}
void IRenderElement.Render(DrawBoard d, UpdateArea updateArea) => Render(this, d, updateArea);
public static void Render(RenderElement renderE, DrawBoard d, UpdateArea updateArea)
{
//TODO: rename Canvas to Drawboard ?
#if DEBUG
if (renderE.dbugBreak)
{
}
#endif
if ((renderE._propFlags & RenderElementConst.HIDDEN) == RenderElementConst.HIDDEN)
{
return;
}
if (WaitForStartRenderElement)
{
//special
if (!RenderElement.IsBubbleGfxUpdateTracked(renderE))
{
//special mode***
//in this mode if this elem is not tracked
//then return
#if DEBUG
System.Diagnostics.Debug.WriteLine("skip_render:" + renderE.Width + "x" + renderE.Height);
#endif
return;
}
else
{
UnlockForStartRenderElement(renderE);
}
}
#if DEBUG
renderE.dbugVRoot.dbug_drawLevel++;
#endif
if ((renderE._propFlags & RenderElementConst.NEED_PRE_RENDER_EVAL) == RenderElementConst.NEED_PRE_RENDER_EVAL)
{
//pre render evaluation before any clip
//eg. content size may be invalid,
renderE.PreRenderEvaluation(d);
}
if (renderE.NeedClipArea)
{
//some elem may need clip for its child
//some may not need
if (d.PushClipAreaRect(renderE._b_width, renderE._b_height, updateArea))
{
//backup ***, new clip is applied to renderE's children node only,
//it will be restored later, for other renderE's sibling
Rectangle prev_rect = updateArea.PreviousRect;
#if DEBUG
if (renderE.dbugVRoot.dbug_RecordDrawingChain)
{
renderE.dbugVRoot.dbug_AddDrawElement(renderE, d);
}
#endif
if ((renderE._propFlags & RenderElementConst.MAY_HAS_VIEWPORT) != 0)
{
int viewportLeft = renderE.ViewportLeft;
int viewportTop = renderE.ViewportTop;
if (viewportLeft == 0 && viewportTop == 0)
{
renderE.RenderClientContent(d, updateArea);
}
else
{
int enterCanvasX = d.OriginX;
int enterCanvasY = d.OriginY;
d.SetCanvasOrigin(enterCanvasX - viewportLeft, enterCanvasY - viewportTop);
updateArea.Offset(viewportLeft, viewportTop);
//---------------
renderE.RenderClientContent(d, updateArea);
//---------------
#if DEBUG
//for debug
// canvas.dbug_DrawCrossRect(Color.Red,updateArea);
#endif
d.SetCanvasOrigin(enterCanvasX, enterCanvasY); //restore
updateArea.Offset(-viewportLeft, -viewportTop);
}
}
else
{
//------------------------------------------
renderE.RenderClientContent(d, updateArea);
//------------------------------------------
}
#if DEBUG
renderE.debug_RecordPostDrawInfo(d);
#endif
d.PopClipAreaRect();
updateArea.CurrentRect = prev_rect; //restore for other renderE sibling
}
}
else
{
#if DEBUG
if (renderE.dbugVRoot.dbug_RecordDrawingChain)
{
renderE.dbugVRoot.dbug_AddDrawElement(renderE, d);
}
#endif
//------------------------------------------
if ((renderE._propFlags & RenderElementConst.MAY_HAS_VIEWPORT) != 0)
{
int viewportLeft = renderE.ViewportLeft;
int viewportTop = renderE.ViewportTop;
if (viewportLeft == 0 && viewportTop == 0)
{
renderE.RenderClientContent(d, updateArea);
}
else
{
int enterCanvasX = d.OriginX;
int enterCanvasY = d.OriginY;
d.SetCanvasOrigin(enterCanvasX - viewportLeft, enterCanvasY - viewportTop);
updateArea.Offset(viewportLeft, viewportTop);
//---------------
renderE.RenderClientContent(d, updateArea);
//---------------
#if DEBUG
//for debug
// canvas.dbug_DrawCrossRect(Color.Red,updateArea);
#endif
d.SetCanvasOrigin(enterCanvasX, enterCanvasY); //restore
updateArea.Offset(-viewportLeft, -viewportTop);
}
}
else
{
renderE.RenderClientContent(d, updateArea);
}
//------------------------------------------
#if DEBUG
renderE.debug_RecordPostDrawInfo(d);
#endif
}
#if DEBUG
renderE.dbugVRoot.dbug_drawLevel--;
#endif
}
}
} | {
"pile_set_name": "Github"
} |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Diagnostics.ContractsLight;
namespace BuildXL.Cache.ContentStore.Stores
{
/// <summary>
/// Provide transaction semantics for a reservation request.
/// </summary>
public sealed class ReserveTransaction
{
private readonly ReserveSpaceRequest _request;
private readonly Action<ReserveSpaceRequest> _commitAction;
/// <nodoc />
internal ReserveTransaction(ReserveSpaceRequest request, Action<ReserveSpaceRequest> commitAction)
{
Contract.Requires(request != null);
Contract.Requires(commitAction != null);
_request = request;
_commitAction = commitAction;
}
/// <summary>
/// Finalize reservation on successful content addition.
/// </summary>
public void Commit()
{
_commitAction?.Invoke(_request);
}
}
}
| {
"pile_set_name": "Github"
} |
// Code generated by smithy-go-codegen DO NOT EDIT.
package cloudtrail
import (
"context"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/retry"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
smithy "github.com/awslabs/smithy-go"
"github.com/awslabs/smithy-go/middleware"
smithyhttp "github.com/awslabs/smithy-go/transport/http"
"time"
)
// Returns a JSON-formatted list of information about the specified trail. Fields
// include information on delivery errors, Amazon SNS and Amazon S3 errors, and
// start and stop logging times for each trail. This operation returns trail status
// from a single region. To return trail status from all regions, you must call the
// operation on each region.
func (c *Client) GetTrailStatus(ctx context.Context, params *GetTrailStatusInput, optFns ...func(*Options)) (*GetTrailStatusOutput, error) {
stack := middleware.NewStack("GetTrailStatus", smithyhttp.NewStackRequest)
options := c.options.Copy()
for _, fn := range optFns {
fn(&options)
}
addawsAwsjson11_serdeOpGetTrailStatusMiddlewares(stack)
awsmiddleware.AddRequestInvocationIDMiddleware(stack)
smithyhttp.AddContentLengthMiddleware(stack)
AddResolveEndpointMiddleware(stack, options)
v4.AddComputePayloadSHA256Middleware(stack)
retry.AddRetryMiddlewares(stack, options)
addHTTPSignerV4Middleware(stack, options)
awsmiddleware.AddAttemptClockSkewMiddleware(stack)
addClientUserAgent(stack)
smithyhttp.AddErrorCloseResponseBodyMiddleware(stack)
smithyhttp.AddCloseResponseBodyMiddleware(stack)
addOpGetTrailStatusValidationMiddleware(stack)
stack.Initialize.Add(newServiceMetadataMiddleware_opGetTrailStatus(options.Region), middleware.Before)
addRequestIDRetrieverMiddleware(stack)
addResponseErrorMiddleware(stack)
for _, fn := range options.APIOptions {
if err := fn(stack); err != nil {
return nil, err
}
}
handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack)
result, metadata, err := handler.Handle(ctx, params)
if err != nil {
return nil, &smithy.OperationError{
ServiceID: ServiceID,
OperationName: "GetTrailStatus",
Err: err,
}
}
out := result.(*GetTrailStatusOutput)
out.ResultMetadata = metadata
return out, nil
}
// The name of a trail about which you want the current status.
type GetTrailStatusInput struct {
// Specifies the name or the CloudTrail ARN of the trail for which you are
// requesting status. To get the status of a shadow trail (a replication of the
// trail in another region), you must specify its ARN. The format of a trail ARN
// is: arn:aws:cloudtrail:us-east-2:123456789012:trail/MyTrail
Name *string
}
// Returns the objects or data listed below if successful. Otherwise, returns an
// error.
type GetTrailStatusOutput struct {
// Displays any CloudWatch Logs error that CloudTrail encountered when attempting
// to deliver logs to CloudWatch Logs.
LatestCloudWatchLogsDeliveryError *string
// This field is no longer in use.
TimeLoggingStopped *string
// This field is no longer in use.
TimeLoggingStarted *string
// This field is no longer in use.
LatestNotificationAttemptTime *string
// This field is no longer in use.
LatestNotificationAttemptSucceeded *string
// This field is no longer in use.
LatestDeliveryAttemptSucceeded *string
// This field is no longer in use.
LatestDeliveryAttemptTime *string
// Specifies the most recent date and time when CloudTrail started recording API
// calls for an AWS account.
StartLoggingTime *time.Time
// Specifies the date and time that CloudTrail last delivered log files to an
// account's Amazon S3 bucket.
LatestDeliveryTime *time.Time
// Displays any Amazon SNS error that CloudTrail encountered when attempting to
// send a notification. For more information about Amazon SNS errors, see the
// Amazon SNS Developer Guide
// (https://docs.aws.amazon.com/sns/latest/dg/welcome.html).
LatestNotificationError *string
// Displays the most recent date and time when CloudTrail delivered logs to
// CloudWatch Logs.
LatestCloudWatchLogsDeliveryTime *time.Time
// Displays any Amazon S3 error that CloudTrail encountered when attempting to
// deliver a digest file to the designated bucket. For more information see the
// topic Error Responses
// (https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html) in the
// Amazon S3 API Reference. This error occurs only when there is a problem with the
// destination S3 bucket and will not occur for timeouts. To resolve the issue,
// create a new bucket and call UpdateTrail to specify the new bucket, or fix the
// existing objects so that CloudTrail can again write to the bucket.
LatestDigestDeliveryError *string
// Specifies the most recent date and time when CloudTrail stopped recording API
// calls for an AWS account.
StopLoggingTime *time.Time
// Whether the CloudTrail is currently logging AWS API calls.
IsLogging *bool
// Displays any Amazon S3 error that CloudTrail encountered when attempting to
// deliver log files to the designated bucket. For more information see the topic
// Error Responses
// (https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html) in the
// Amazon S3 API Reference. This error occurs only when there is a problem with the
// destination S3 bucket and will not occur for timeouts. To resolve the issue,
// create a new bucket and call UpdateTrail to specify the new bucket, or fix the
// existing objects so that CloudTrail can again write to the bucket.
LatestDeliveryError *string
// Specifies the date and time of the most recent Amazon SNS notification that
// CloudTrail has written a new log file to an account's Amazon S3 bucket.
LatestNotificationTime *time.Time
// Specifies the date and time that CloudTrail last delivered a digest file to an
// account's Amazon S3 bucket.
LatestDigestDeliveryTime *time.Time
// Metadata pertaining to the operation's result.
ResultMetadata middleware.Metadata
}
func addawsAwsjson11_serdeOpGetTrailStatusMiddlewares(stack *middleware.Stack) {
stack.Serialize.Add(&awsAwsjson11_serializeOpGetTrailStatus{}, middleware.After)
stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetTrailStatus{}, middleware.After)
}
func newServiceMetadataMiddleware_opGetTrailStatus(region string) awsmiddleware.RegisterServiceMetadata {
return awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
SigningName: "cloudtrail",
OperationName: "GetTrailStatus",
}
}
| {
"pile_set_name": "Github"
} |
from typing import List, Pattern, Dict
import regex
from recognizers_text.utilities import RegExpUtility
from ...resources.french_date_time import FrenchDateTime
from ..base_time import TimeParserConfiguration, AdjustParams
from ..base_configs import BaseDateParserConfiguration, DateTimeUtilityConfiguration
from .time_extractor_config import FrenchTimeExtractorConfiguration
from ..parsers import DateTimeParser
class FrenchTimeParserConfiguration(TimeParserConfiguration):
@property
def time_token_prefix(self) -> str:
return self._time_token_prefix
@property
def at_regex(self) -> Pattern:
return self._at_regex
@property
def time_regexes(self) -> List[Pattern]:
return self._time_regexes
@property
def numbers(self) -> Dict[str, int]:
return self._numbers
@property
def utility_configuration(self) -> DateTimeUtilityConfiguration:
return self._utility_configuration
@property
def time_zone_parser(self) -> DateTimeParser:
return self._time_zone_parser
def __init__(self, config: BaseDateParserConfiguration):
self._time_token_prefix: str = FrenchDateTime.TimeTokenPrefix
self._at_regex: Pattern = RegExpUtility.get_safe_reg_exp(
FrenchDateTime.AtRegex)
self._time_regexes: List[Pattern] = FrenchTimeExtractorConfiguration.get_time_regex_list(
)
self.less_than_one_hour = RegExpUtility.get_safe_reg_exp(
FrenchDateTime.LessThanOneHour)
self.time_suffix = RegExpUtility.get_safe_reg_exp(
FrenchDateTime.TimeSuffix)
self._utility_configuration = config.utility_configuration
self._numbers: Dict[str, int] = config.numbers
self._time_zone_parser = config.time_zone_parser
def adjust_by_prefix(self, prefix: str, adjust: AdjustParams):
delta_min = 0
trimmed_prefix = prefix.strip().lower()
if trimmed_prefix.endswith('demie'):
delta_min = 30
elif trimmed_prefix.endswith('un quart') or trimmed_prefix.endswith('quart'):
delta_min = 15
elif trimmed_prefix.endswith('trois quarts'):
delta_min = 45
else:
match = regex.search(self.less_than_one_hour, trimmed_prefix)
if match:
min_str = RegExpUtility.get_group(match, 'deltamin')
if min_str:
delta_min = int(min_str)
else:
min_str = RegExpUtility.get_group(
match, 'deltaminnum').lower()
delta_min = self.numbers.get(min_str)
if trimmed_prefix.endswith('à'):
delta_min = delta_min * -1
adjust.minute += delta_min
if adjust.minute < 0:
adjust.minute += 60
adjust.hour -= 1
adjust.has_minute = True
def adjust_by_suffix(self, suffix: str, adjust: AdjustParams):
suffix = suffix.strip().lower()
delta_hour = 0
match = regex.match(self.time_suffix, suffix)
if match and match.group() == suffix:
oclock_str = RegExpUtility.get_group(match, 'heures')
if not oclock_str:
am_str = RegExpUtility.get_group(match, 'am')
if am_str:
if adjust.hour >= 12:
delta_hour -= 12
adjust.has_am = True
pm_str = RegExpUtility.get_group(match, 'pm')
if pm_str:
if adjust.hour < 12:
delta_hour = 12
adjust.has_pm = True
adjust.hour = (adjust.hour + delta_hour) % 24
| {
"pile_set_name": "Github"
} |
# Time-stamp: <03/10/17 19:29:26 ptr>
# $Id$
install-static: install-release-static install-dbg-static install-stldbg-static
install-release-static: release-static $(INSTALL_STATIC_BIN_DIR)
$(INSTALL_A) $(PRG_A) $(INSTALL_STATIC_BIN_DIR)
@if exist $(A_PDB_NAME_OUT) $(INSTALL_A) $(A_PDB_NAME_OUT) $(INSTALL_STATIC_BIN_DIR)
install-dbg-static: dbg-static $(INSTALL_STATIC_BIN_DIR_DBG)
$(INSTALL_A) $(PRG_A_DBG) $(INSTALL_STATIC_BIN_DIR_DBG)
@if exist $(A_PDB_NAME_OUT_DBG) $(INSTALL_A) $(A_PDB_NAME_OUT_DBG) $(INSTALL_STATIC_BIN_DIR_DBG)
install-stldbg-static: stldbg-static $(INSTALL_STATIC_BIN_DIR_STLDBG)
$(INSTALL_A) $(PRG_A_STLDBG) $(INSTALL_STATIC_BIN_DIR_STLDBG)
@if exist $(A_PDB_NAME_OUT_STLDBG) $(INSTALL_A) $(A_PDB_NAME_OUT_STLDBG) $(INSTALL_STATIC_BIN_DIR_STLDBG)
| {
"pile_set_name": "Github"
} |
[Desktop Entry]
Icon=cs-fonts
Exec=cinnamon-settings fonts
Type=Application
OnlyShowIn=X-Cinnamon;
Categories=Settings;
Name=Font Selection
Name[af]=Kies lettertipe
Name[am]=የ ፊደል ምርጫዎች
Name[ar]=تحديد الخط
Name[ast]=Esbilla de fonte
Name[az]=Yazı biçiminin Seçimi
Name[be]=Выбар шрыфта
Name[bg]=Избор на шрифт
Name[bs]=Izbor fonta
Name[ca]=Selecció de la lletra
Name[ca@valencia]=Selecció de la lletra
Name[cs]=Výběr písma
Name[cy]=Dewis Ffont
Name[da]=Valg af skrifttype
Name[de]=Schriftauswahl
Name[el]=Επιλογή Γραμματοσειράς
Name[eo]=Tiparelekto
Name[es]=Selección de tipografías
Name[es_AR]=Selección de tipografías
Name[et]=Kirjatüübi valik
Name[eu]=Letra-tipoen hautapena
Name[fa]=انتخاب فونت
Name[fi]=Fonttien valinta
Name[fr]=Sélection de polices
Name[fr_CA]=Sélection de police
Name[gd]=Taghadh a' chrutha-chlò
Name[gl]=Selección de tipos de letra
Name[he]=בחירת גופן
Name[hr]=Odabir slova
Name[hu]=Betűkészlet kiválasztása
Name[ia]=Selection del typo de characteres
Name[id]=Pilihan Fonta
Name[ie]=Selection de fonde
Name[is]=Velja letur
Name[it]=Selezione carattere
Name[ja]=フォントの選択
Name[kab]=Tafrayt n tsefsit
Name[ko]=글꼴 선택
Name[ku]=Hilbijartina Curetîpan
Name[lo]=ການເລືອກຟອນ
Name[lt]=Šriftų pasirinkimas
Name[lv]=Fontu izvēle
Name[ms]=Pemilihan Font
Name[nb]=Skriftvalg
Name[nds]=Schriftart auswählen
Name[nl]=Lettertypeselectie
Name[oc]=Selector de poliças
Name[pl]=Wybór czcionki
Name[pt]=Seleção do tipo de letra
Name[pt_BR]=Seleção de fonte
Name[ro]=Selecție fonturi
Name[ru]=Выбор шрифтов
Name[sc]=Seletzione caràteres
Name[sk]=Výber písma
Name[sl]=Izbira pisave
Name[sq]=Zgjedhja e shkronjave
Name[sr]=Избор фонта
Name[sr@ijekavianlatin]=Избор фонта
Name[sr@latin]=Izbor fontova
Name[sv]=Typsnittsval
Name[ta]=எழுத்துரு தேர்வு
Name[th]=การเลือกแบบอักษร
Name[tr]=Yazıtipi Seçimi
Name[uk]=Вибір шрифту
Name[ur]=فونٹ انتخاب
Name[uz]=Шрифтларни танлаш
Name[vi]=Chọn Kiểu chữ
Name[zh_CN]=选择字体
Name[zh_HK]=字型選擇
Name[zh_TW]=字型選擇
Comment=Configure system fonts
Comment[af]=Instellings vir stelsel-lettertipe
Comment[am]=የ ስርአቱን ፊደል ማሰናጃ
Comment[ar]=تكوين خطوط النظام
Comment[ast]=Configura les fontes del sistema
Comment[az]=Qurmaca yazı biçimlərini qur
Comment[be]=Наладзіць сістэмныя шрыфты
Comment[bg]=Конфигуриране на системни шрифтове
Comment[bs]=Konfigurišite sistemke fontove
Comment[ca]=Configureu les lletres del sistema
Comment[ca@valencia]=Configureu les lletres del sistema
Comment[cs]=Nastavení systémových písem
Comment[cy]=Ffurfweddwch ffontiau'r system
Comment[da]=Konfigurér systemskrifttyper
Comment[de]=Systemschriften konfigurieren
Comment[el]=Ρύθμιση γραμματοσειράς συστήματος
Comment[eo]=Agordi sistemtiparojn
Comment[es]=Configurar las tipografías del sistema
Comment[es_AR]=Configurar las tipografías del sistema
Comment[et]=Süsteemsete kirjatüüpide sätted
Comment[eu]=Konfiguratu sistemaren letra-tipoak
Comment[fa]=تنظیم فونتهای سیستم
Comment[fi]=Hallitse järjestelmän fontteja
Comment[fr]=Configurer les polices du système
Comment[fr_CA]=Configurer les polices du système
Comment[gd]=Rèitich cruthan-clò an t-siostaim
Comment[gl]=Configura os tipos de letra do sistema
Comment[he]=שנה את גופני המערכת
Comment[hr]=Prilagodite slova sustava
Comment[hu]=Rendszer betűtípusok beállítása
Comment[ia]=Configura le typos de characteres de systema
Comment[id]=Pengaturan fonta sistem
Comment[is]=Stilla kerfisletur
Comment[it]=Configura il carattere di sistema
Comment[kab]=Seɣwer tisefsa n unagraw
Comment[ko]=시스템 글꼴 설정
Comment[lo]=ປັບແຕ່ງຟອນຂອງລະບົບ
Comment[lt]=Konfigūruoti sistemos šriftus
Comment[lv]=Konfigurēt sistēmas fontus
Comment[ms]=Konfigur sistem Font
Comment[nb]=Konfigurer systemskrifter
Comment[nds]=Systemschriftarten konfigurieren
Comment[nl]=Systeemlettertypen instellen
Comment[pl]=Konfiguracja czcionek systemu
Comment[pt]=Configurar tipo de letra
Comment[pt_BR]=Configurar fontes do sistema
Comment[ro]=Configurează fonturile sistemului
Comment[ru]=Настроить системные шрифты
Comment[sc]=Cunfigura caràteres de sistema
Comment[sk]=Nastaviť systémové písma
Comment[sl]=Nastavljajte sistemske pisave
Comment[sq]=Konfiguro shkronjat e sistemit
Comment[sr]=Подешавање слова система
Comment[sr@ijekavianlatin]=Подешавање слова система
Comment[sr@latin]=Postavke sistemskih fontova
Comment[sv]=Konfigurera systemets typsnitt
Comment[tg]=Танзимоти шрифтҳои низомвӣ
Comment[th]=กำหนดแบบอักษรของระบบ
Comment[tr]=Sistem yazı tiplerini yapılandır
Comment[uk]=Налаштування системних шрифтів
Comment[ur]=نظام کے فونٹ کو تشکیل دیں
Comment[uz]=Тизим шрифтларини созлаш
Comment[vi]=Cấu hình kiểu chữ hệ thống
Comment[zh_CN]=配置系统字体
Comment[zh_HK]=設定系統字型組態
Comment[zh_TW]=設定系統字型組態
Keywords=font;size;small;large;
Keywords[af]=lettertipe;grootte;klein;groot;
Keywords[am]=የ ፊደል መጠን: ትንሽ: ትልቅ;
Keywords[ar]=الخط، الحجم، صغير، كبير;
Keywords[ast]=fonte;tamañu;pequeñu;grande;lletra;lletres;fontes;
Keywords[az]=yazı biçimi;kiçik;geniş;
Keywords[be]=шрыфт;памер;маленькі;вялікі;
Keywords[bg]=шрифт;размер;малък;голям;
Keywords[bs]=font;veličina;malo;veliko;
Keywords[ca]=lletra;mida;petita;gran;
Keywords[ca@valencia]=lletra;mida;petita;gran;
Keywords[cs]=písmo;font;velikost;malé;velké;
Keywords[cy]=ffont;maint;bach;mawr;
Keywords[da]=skrifttype;størrelse;lille;stor;
Keywords[de]=Schriftart;Font;Größe;Klein;Groß;
Keywords[el]=γραμματοσειρά;μέγεθος;μικρά;μεγάλα;
Keywords[eo]=tiparo;grando;malgranda;granda;
Keywords[es]=tipografía;tamaño;pequeño;grande;
Keywords[es_AR]=tipografía;tamaño;pequeño;grande;
Keywords[et]=font;suurus;väike;suur;
Keywords[eu]=letra-tipoa;tamaina;txikia;handia;
Keywords[fa]=فونت، اندازه، کوچک، بزرگ;
Keywords[fi]=fontti;koko;pieni;iso;
Keywords[fr]=police;taille;petit;grand;
Keywords[fr_CA]=police;taille;petit;grand;
Keywords[ga]=clófhoireann;méid;beag;mór;
Keywords[gd]=cruth-clò;meud;beag;mòr;font;size;small;large;
Keywords[gl]=tipo de letra;tamaño;pequena;grande;
Keywords[he]=גופן;גודל;קטן;גדול;
Keywords[hr]=slovo;veličina;malo;veliko;
Keywords[hu]=betűtípus;méret;kicsi;nagy;
Keywords[ia]=typo de characteres;dimension;parve;grande;
Keywords[id]=fonta;ukuran;kecil;besar;
Keywords[is]=letur;stærð;lítið;stórt;
Keywords[it]=carattere;dimensione;piccolo;grande;
Keywords[ja]=フォント、サイズ、小さく、大きく;
Keywords[kab]=tasefsit;tiddi;tamecṭuḥt;tahrawnant;
Keywords[ko]=글꼴;크기;작게;크게;
Keywords[lo]=ຟອນ;ຂະໜາດ;ນ້ອຍ;ໃຫຍ່;
Keywords[lt]=šriftas;dydis;didelis;mažas;
Keywords[lv]=fonts;izmērs;mazi;lieli;
Keywords[ms]=fon;saiz;kecil;besar;
Keywords[nb]=skrifttype;størrelse;liten;stor;
Keywords[nds]=Schriftart;Größe;klein;groß;
Keywords[nl]=lettertype;grootte;klein;groot;
Keywords[pl]=czcionka;wielkość;mała;duża;
Keywords[pt]=letra;tamanho;grande;pequena;
Keywords[pt_BR]=fonte;tamanho;pequena;grande;
Keywords[ro]=font;dimensiune;mic;mare;
Keywords[ru]=шрифт;размер;маленький;большой;
Keywords[sc]=caràtere;mannària;minore;mannu;
Keywords[sk]=písmo;veľkosť;malé;veľké;
Keywords[sl]=pisava;velikost;majhna;velika;
Keywords[sq]=shkronjat;madhësia;i vogël;i madh;
Keywords[sr]=писмо;слова;фонт;величина;мало;велико;
Keywords[sr@ijekavianlatin]=писмо;слова;фонт;величина;мало;велико;
Keywords[sr@latin]=font;veličina;mali;veliki;
Keywords[sv]=typsnitt;storlek;små;stort;
Keywords[ta]=எழுத்துரு;அளவு;சிறிய;பெரிய;
Keywords[tg]=шрифт;андоза;хурд;калон;
Keywords[th]=แบบอักษร;ขนาด;เล็ก;ใหญ่;
Keywords[tr]=font;boyut;küçük;büyük;
Keywords[uk]=шрифт;розмір;маленький;великий;
Keywords[ur]=فونٹ، سائز، چھوٹا، بڑا;
Keywords[uz]=шрифт;ўлчам;кичкина;катта;
Keywords[vi]=phông;cỡ;nhỏ;to;
Keywords[zh_CN]=font;size;small;large;字体;字号;大小;放大;缩小;
Keywords[zh_HK]=font;size;small;large;字型;大小;小;大;
Keywords[zh_TW]=字型;尺寸;小;大;
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" systemVersion="17A277" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>
| {
"pile_set_name": "Github"
} |
// ***************************************************************************
// *
// * Copyright (C) 2013 International Business Machines
// * Corporation and others. All Rights Reserved.
// * Tool: com.ibm.icu.dev.tool.cldr.LDML2ICUConverter.java
// * Source File:<path>/icu-config.xml & build.xml
// *
// ***************************************************************************
/**
* validSubLocale of "en"
*/
en_MP{
/**
* so genrb doesn't issue warnings
*/
___{""}
}
| {
"pile_set_name": "Github"
} |
client
dev tun
proto udp
remote 45.12.220.45 1194
resolv-retry infinite
remote-random
nobind
tun-mtu 1500
tun-mtu-extra 32
mssfix 1450
persist-key
persist-tun
ping 15
ping-restart 0
ping-timer-rem
reneg-sec 0
comp-lzo no
remote-cert-tls server
auth-user-pass ../Own_VPN_Config/nordvpnauth.txt
verb 3
pull
fast-io
cipher AES-256-CBC
auth SHA512
<ca>
-----BEGIN CERTIFICATE-----
MIIFCjCCAvKgAwIBAgIBATANBgkqhkiG9w0BAQ0FADA5MQswCQYDVQQGEwJQQTEQ
MA4GA1UEChMHTm9yZFZQTjEYMBYGA1UEAxMPTm9yZFZQTiBSb290IENBMB4XDTE2
MDEwMTAwMDAwMFoXDTM1MTIzMTIzNTk1OVowOTELMAkGA1UEBhMCUEExEDAOBgNV
BAoTB05vcmRWUE4xGDAWBgNVBAMTD05vcmRWUE4gUm9vdCBDQTCCAiIwDQYJKoZI
hvcNAQEBBQADggIPADCCAgoCggIBAMkr/BYhyo0F2upsIMXwC6QvkZps3NN2/eQF
kfQIS1gql0aejsKsEnmY0Kaon8uZCTXPsRH1gQNgg5D2gixdd1mJUvV3dE3y9FJr
XMoDkXdCGBodvKJyU6lcfEVF6/UxHcbBguZK9UtRHS9eJYm3rpL/5huQMCppX7kU
eQ8dpCwd3iKITqwd1ZudDqsWaU0vqzC2H55IyaZ/5/TnCk31Q1UP6BksbbuRcwOV
skEDsm6YoWDnn/IIzGOYnFJRzQH5jTz3j1QBvRIuQuBuvUkfhx1FEwhwZigrcxXu
MP+QgM54kezgziJUaZcOM2zF3lvrwMvXDMfNeIoJABv9ljw969xQ8czQCU5lMVmA
37ltv5Ec9U5hZuwk/9QO1Z+d/r6Jx0mlurS8gnCAKJgwa3kyZw6e4FZ8mYL4vpRR
hPdvRTWCMJkeB4yBHyhxUmTRgJHm6YR3D6hcFAc9cQcTEl/I60tMdz33G6m0O42s
Qt/+AR3YCY/RusWVBJB/qNS94EtNtj8iaebCQW1jHAhvGmFILVR9lzD0EzWKHkvy
WEjmUVRgCDd6Ne3eFRNS73gdv/C3l5boYySeu4exkEYVxVRn8DhCxs0MnkMHWFK6
MyzXCCn+JnWFDYPfDKHvpff/kLDobtPBf+Lbch5wQy9quY27xaj0XwLyjOltpiST
LWae/Q4vAgMBAAGjHTAbMAwGA1UdEwQFMAMBAf8wCwYDVR0PBAQDAgEGMA0GCSqG
SIb3DQEBDQUAA4ICAQC9fUL2sZPxIN2mD32VeNySTgZlCEdVmlq471o/bDMP4B8g
nQesFRtXY2ZCjs50Jm73B2LViL9qlREmI6vE5IC8IsRBJSV4ce1WYxyXro5rmVg/
k6a10rlsbK/eg//GHoJxDdXDOokLUSnxt7gk3QKpX6eCdh67p0PuWm/7WUJQxH2S
DxsT9vB/iZriTIEe/ILoOQF0Aqp7AgNCcLcLAmbxXQkXYCCSB35Vp06u+eTWjG0/
pyS5V14stGtw+fA0DJp5ZJV4eqJ5LqxMlYvEZ/qKTEdoCeaXv2QEmN6dVqjDoTAo
k0t5u4YRXzEVCfXAC3ocplNdtCA72wjFJcSbfif4BSC8bDACTXtnPC7nD0VndZLp
+RiNLeiENhk0oTC+UVdSc+n2nJOzkCK0vYu0Ads4JGIB7g8IB3z2t9ICmsWrgnhd
NdcOe15BincrGA8avQ1cWXsfIKEjbrnEuEk9b5jel6NfHtPKoHc9mDpRdNPISeVa
wDBM1mJChneHt59Nh8Gah74+TM1jBsw4fhJPvoc7Atcg740JErb904mZfkIEmojC
VPhBHVQ9LHBAdM8qFI2kRK0IynOmAZhexlP/aT/kpEsEPyaZQlnBn3An1CRz8h0S
PApL8PytggYKeQmRhl499+6jLxcZ2IegLfqq41dzIjwHwTMplg+1pKIOVojpWA==
-----END CERTIFICATE-----
</ca>
key-direction 1
<tls-auth>
#
# 2048 bit OpenVPN static key
#
-----BEGIN OpenVPN Static key V1-----
e685bdaf659a25a200e2b9e39e51ff03
0fc72cf1ce07232bd8b2be5e6c670143
f51e937e670eee09d4f2ea5a6e4e6996
5db852c275351b86fc4ca892d78ae002
d6f70d029bd79c4d1c26cf14e9588033
cf639f8a74809f29f72b9d58f9b8f5fe
fc7938eade40e9fed6cb92184abb2cc1
0eb1a296df243b251df0643d53724cdb
5a92a1d6cb817804c4a9319b57d53be5
80815bcfcb2df55018cc83fc43bc7ff8
2d51f9b88364776ee9d12fc85cc7ea5b
9741c4f598c485316db066d52db4540e
212e1518a9bd4828219e24b20d88f598
a196c9de96012090e333519ae18d3509
9427e7b372d348d352dc4c85e18cd4b9
3f8a56ddb2e64eb67adfc9b337157ff4
-----END OpenVPN Static key V1-----
</tls-auth>
| {
"pile_set_name": "Github"
} |
/*
* Plugin: Full Calendar
* ---------------------
*/
// Import variables and mixins as a reference for separate plugins version
@import (reference) "../../bower_components/bootstrap/less/mixins";
@import (reference) "../../bower_components/bootstrap/less/variables";
@import (reference) "variables";
@import (reference) "mixins";
// Fullcalendar buttons
.fc-button {
background: #f4f4f4;
background-image: none;
color: #444;
border-color: #ddd;
border-bottom-color: #ddd;
&:hover,
&:active,
&.hover {
background-color: #e9e9e9;
}
}
// Calendar title
.fc-header-title h2 {
font-size: 15px;
line-height: 1.6em;
color: #666;
margin-left: 10px;
}
.fc-header-right {
padding-right: 10px;
}
.fc-header-left {
padding-left: 10px;
}
// Calendar table header cells
.fc-widget-header {
background: #fafafa;
}
.fc-grid {
width: 100%;
border: 0;
}
.fc-widget-header:first-of-type,
.fc-widget-content:first-of-type {
border-left: 0;
border-right: 0;
}
.fc-widget-header:last-of-type,
.fc-widget-content:last-of-type {
border-right: 0;
}
.fc-toolbar {
padding: @box-padding;
margin: 0;
}
.fc-day-number {
font-size: 20px;
font-weight: 300;
padding-right: 10px;
}
.fc-color-picker {
list-style: none;
margin: 0;
padding: 0;
> li {
float: left;
font-size: 30px;
margin-right: 5px;
line-height: 30px;
.fa {
.transition-transform(linear .3s);
&:hover {
.rotate(30deg);
}
}
}
}
#add-new-event {
.transition(all linear .3s);
}
.external-event {
padding: 5px 10px;
font-weight: bold;
margin-bottom: 4px;
box-shadow: @box-boxshadow;
text-shadow: @box-boxshadow;
border-radius: @box-border-radius;
cursor: move;
&:hover {
box-shadow: inset 0 0 90px rgba(0, 0, 0, 0.2);
}
}
| {
"pile_set_name": "Github"
} |
use std::ops::{Index, IndexMut};
struct Foo {
x: isize,
y: isize,
}
impl Index<String> for Foo {
type Output = isize;
fn index(&self, z: String) -> &isize {
if z == "x" {
&self.x
} else {
&self.y
}
}
}
impl IndexMut<String> for Foo {
fn index_mut(&mut self, z: String) -> &mut isize {
if z == "x" {
&mut self.x
} else {
&mut self.y
}
}
}
struct Bar {
x: isize,
}
impl Index<isize> for Bar {
type Output = isize;
fn index<'a>(&'a self, z: isize) -> &'a isize {
&self.x
}
}
fn main() {
let mut f = Foo {
x: 1,
y: 2,
};
let mut s = "hello".to_string();
let rs = &mut s;
println!("{}", f[s]);
//~^ ERROR cannot move out of `s` because it is borrowed
f[s] = 10;
//~^ ERROR cannot move out of `s` because it is borrowed
//~| ERROR use of moved value: `s`
let s = Bar {
x: 1,
};
let i = 2;
let _j = &i;
println!("{}", s[i]); // no error, i is copy
println!("{}", s[i]);
use_mut(rs);
}
fn use_mut<T>(_: &mut T) { }
| {
"pile_set_name": "Github"
} |
[profile testing]
aws_access_key_id = PROFILE_ACCESS_KEY
aws_secret_access_key = PROFILE_SECRET_KEY
| {
"pile_set_name": "Github"
} |
/* gzio.c -- IO on .gz files
* Copyright (C) 1995-2005 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h
*
* Compile this file with -DNO_GZCOMPRESS to avoid the compression code.
*/
/* @(#) $Id$ */
#include <stdio.h>
#include "zutil.h"
#ifdef NO_DEFLATE /* for compatibility with old definition */
# define NO_GZCOMPRESS
#endif
#ifndef NO_DUMMY_DECL
struct internal_state {int dummy;}; /* for buggy compilers */
#endif
#ifndef Z_BUFSIZE
# ifdef MAXSEG_64K
# define Z_BUFSIZE 4096 /* minimize memory usage for 16-bit DOS */
# else
# define Z_BUFSIZE 16384
# endif
#endif
#ifndef Z_PRINTF_BUFSIZE
# define Z_PRINTF_BUFSIZE 4096
#endif
#ifdef __MVS__
# pragma map (fdopen , "\174\174FDOPEN")
FILE *fdopen(int, const char *);
#endif
#ifndef STDC
extern voidp malloc OF((uInt size));
extern void free OF((voidpf ptr));
#endif
#define ALLOC(size) malloc(size)
#define TRYFREE(p) {if (p) free(p);}
static int const gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
/* gzip flag byte */
#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */
#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
#define ORIG_NAME 0x08 /* bit 3 set: original file name present */
#define COMMENT 0x10 /* bit 4 set: file comment present */
#define RESERVED 0xE0 /* bits 5..7: reserved */
typedef struct gz_stream {
z_stream stream;
int z_err; /* error code for last stream operation */
int z_eof; /* set if end of input file */
FILE *file; /* .gz file */
Byte *inbuf; /* input buffer */
Byte *outbuf; /* output buffer */
uLong crc; /* crc32 of uncompressed data */
char *msg; /* error message */
char *path; /* path name for debugging only */
int transparent; /* 1 if input file is not a .gz file */
char mode; /* 'w' or 'r' */
z_off_t start; /* start of compressed data in file (header skipped) */
z_off_t in; /* bytes into deflate or inflate */
z_off_t out; /* bytes out of deflate or inflate */
int back; /* one character push-back */
int last; /* true if push-back is last character */
} gz_stream;
local gzFile gz_open OF((const char *path, const char *mode, int fd));
local int do_flush OF((gzFile file, int flush));
local int get_byte OF((gz_stream *s));
local void check_header OF((gz_stream *s));
local int destroy OF((gz_stream *s));
local void putLong OF((FILE *file, uLong x));
local uLong getLong OF((gz_stream *s));
/* ===========================================================================
Opens a gzip (.gz) file for reading or writing. The mode parameter
is as in fopen ("rb" or "wb"). The file is given either by file descriptor
or path name (if fd == -1).
gz_open returns NULL if the file could not be opened or if there was
insufficient memory to allocate the (de)compression state; errno
can be checked to distinguish the two cases (if errno is zero, the
zlib error is Z_MEM_ERROR).
*/
local gzFile gz_open (path, mode, fd)
const char *path;
const char *mode;
int fd;
{
int err;
int level = Z_DEFAULT_COMPRESSION; /* compression level */
int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */
char *p = (char*)mode;
gz_stream *s;
char fmode[80]; /* copy of mode, without the compression level */
char *m = fmode;
if (!path || !mode) return Z_NULL;
s = (gz_stream *)ALLOC(sizeof(gz_stream));
if (!s) return Z_NULL;
s->stream.zalloc = (alloc_func)0;
s->stream.zfree = (free_func)0;
s->stream.opaque = (voidpf)0;
s->stream.next_in = s->inbuf = Z_NULL;
s->stream.next_out = s->outbuf = Z_NULL;
s->stream.avail_in = s->stream.avail_out = 0;
s->file = NULL;
s->z_err = Z_OK;
s->z_eof = 0;
s->in = 0;
s->out = 0;
s->back = EOF;
s->crc = crc32(0L, Z_NULL, 0);
s->msg = NULL;
s->transparent = 0;
s->path = (char*)ALLOC(strlen(path)+1);
if (s->path == NULL) {
return destroy(s), (gzFile)Z_NULL;
}
strcpy(s->path, path); /* do this early for debugging */
s->mode = '\0';
do {
if (*p == 'r') s->mode = 'r';
if (*p == 'w' || *p == 'a') s->mode = 'w';
if (*p >= '0' && *p <= '9') {
level = *p - '0';
} else if (*p == 'f') {
strategy = Z_FILTERED;
} else if (*p == 'h') {
strategy = Z_HUFFMAN_ONLY;
} else if (*p == 'R') {
strategy = Z_RLE;
} else {
*m++ = *p; /* copy the mode */
}
} while (*p++ && m != fmode + sizeof(fmode));
if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL;
if (s->mode == 'w') {
#ifdef NO_GZCOMPRESS
err = Z_STREAM_ERROR;
#else
err = deflateInit2(&(s->stream), level,
Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy);
/* windowBits is passed < 0 to suppress zlib header */
s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
#endif
if (err != Z_OK || s->outbuf == Z_NULL) {
return destroy(s), (gzFile)Z_NULL;
}
} else {
s->stream.next_in = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE);
err = inflateInit2(&(s->stream), -MAX_WBITS);
/* windowBits is passed < 0 to tell that there is no zlib header.
* Note that in this case inflate *requires* an extra "dummy" byte
* after the compressed stream in order to complete decompression and
* return Z_STREAM_END. Here the gzip CRC32 ensures that 4 bytes are
* present after the compressed stream.
*/
if (err != Z_OK || s->inbuf == Z_NULL) {
return destroy(s), (gzFile)Z_NULL;
}
}
s->stream.avail_out = Z_BUFSIZE;
errno = 0;
s->file = fd < 0 ? F_OPEN(path, fmode) : (FILE*)fdopen(fd, fmode);
if (s->file == NULL) {
return destroy(s), (gzFile)Z_NULL;
}
if (s->mode == 'w') {
/* Write a very simple .gz header:
*/
fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1],
Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE);
s->start = 10L;
/* We use 10L instead of ftell(s->file) to because ftell causes an
* fflush on some systems. This version of the library doesn't use
* start anyway in write mode, so this initialization is not
* necessary.
*/
} else {
check_header(s); /* skip the .gz header */
s->start = ftell(s->file) - s->stream.avail_in;
}
return (gzFile)s;
}
/* ===========================================================================
Opens a gzip (.gz) file for reading or writing.
*/
gzFile ZEXPORT gzopen (path, mode)
const char *path;
const char *mode;
{
return gz_open (path, mode, -1);
}
/* ===========================================================================
Associate a gzFile with the file descriptor fd. fd is not dup'ed here
to mimic the behavio(u)r of fdopen.
*/
gzFile ZEXPORT gzdopen (fd, mode)
int fd;
const char *mode;
{
char name[46]; /* allow for up to 128-bit integers */
if (fd < 0) return (gzFile)Z_NULL;
sprintf(name, "<fd:%d>", fd); /* for debugging */
return gz_open (name, mode, fd);
}
/* ===========================================================================
* Update the compression level and strategy
*/
int ZEXPORT gzsetparams (file, level, strategy)
gzFile file;
int level;
int strategy;
{
gz_stream *s = (gz_stream*)file;
if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
/* Make room to allow flushing */
if (s->stream.avail_out == 0) {
s->stream.next_out = s->outbuf;
if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
s->z_err = Z_ERRNO;
}
s->stream.avail_out = Z_BUFSIZE;
}
return deflateParams (&(s->stream), level, strategy);
}
/* ===========================================================================
Read a byte from a gz_stream; update next_in and avail_in. Return EOF
for end of file.
IN assertion: the stream s has been sucessfully opened for reading.
*/
local int get_byte(s)
gz_stream *s;
{
if (s->z_eof) return EOF;
if (s->stream.avail_in == 0) {
errno = 0;
s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file);
if (s->stream.avail_in == 0) {
s->z_eof = 1;
if (ferror(s->file)) s->z_err = Z_ERRNO;
return EOF;
}
s->stream.next_in = s->inbuf;
}
s->stream.avail_in--;
return *(s->stream.next_in)++;
}
/* ===========================================================================
Check the gzip header of a gz_stream opened for reading. Set the stream
mode to transparent if the gzip magic header is not present; set s->err
to Z_DATA_ERROR if the magic header is present but the rest of the header
is incorrect.
IN assertion: the stream s has already been created sucessfully;
s->stream.avail_in is zero for the first time, but may be non-zero
for concatenated .gz files.
*/
local void check_header(s)
gz_stream *s;
{
int method; /* method byte */
int flags; /* flags byte */
uInt len;
int c;
/* Assure two bytes in the buffer so we can peek ahead -- handle case
where first byte of header is at the end of the buffer after the last
gzip segment */
len = s->stream.avail_in;
if (len < 2) {
if (len) s->inbuf[0] = s->stream.next_in[0];
errno = 0;
len = (uInt)fread(s->inbuf + len, 1, Z_BUFSIZE >> len, s->file);
if (len == 0 && ferror(s->file)) s->z_err = Z_ERRNO;
s->stream.avail_in += len;
s->stream.next_in = s->inbuf;
if (s->stream.avail_in < 2) {
s->transparent = s->stream.avail_in;
return;
}
}
/* Peek ahead to check the gzip magic header */
if (s->stream.next_in[0] != gz_magic[0] ||
s->stream.next_in[1] != gz_magic[1]) {
s->transparent = 1;
return;
}
s->stream.avail_in -= 2;
s->stream.next_in += 2;
/* Check the rest of the gzip header */
method = get_byte(s);
flags = get_byte(s);
if (method != Z_DEFLATED || (flags & RESERVED) != 0) {
s->z_err = Z_DATA_ERROR;
return;
}
/* Discard time, xflags and OS code: */
for (len = 0; len < 6; len++) (void)get_byte(s);
if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */
len = (uInt)get_byte(s);
len += ((uInt)get_byte(s))<<8;
/* len is garbage if EOF but the loop below will quit anyway */
while (len-- != 0 && get_byte(s) != EOF) ;
}
if ((flags & ORIG_NAME) != 0) { /* skip the original file name */
while ((c = get_byte(s)) != 0 && c != EOF) ;
}
if ((flags & COMMENT) != 0) { /* skip the .gz file comment */
while ((c = get_byte(s)) != 0 && c != EOF) ;
}
if ((flags & HEAD_CRC) != 0) { /* skip the header crc */
for (len = 0; len < 2; len++) (void)get_byte(s);
}
s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK;
}
/* ===========================================================================
* Cleanup then free the given gz_stream. Return a zlib error code.
Try freeing in the reverse order of allocations.
*/
local int destroy (s)
gz_stream *s;
{
int err = Z_OK;
if (!s) return Z_STREAM_ERROR;
TRYFREE(s->msg);
if (s->stream.state != NULL) {
if (s->mode == 'w') {
#ifdef NO_GZCOMPRESS
err = Z_STREAM_ERROR;
#else
err = deflateEnd(&(s->stream));
#endif
} else if (s->mode == 'r') {
err = inflateEnd(&(s->stream));
}
}
if (s->file != NULL && fclose(s->file)) {
#ifdef ESPIPE
if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */
#endif
err = Z_ERRNO;
}
if (s->z_err < 0) err = s->z_err;
TRYFREE(s->inbuf);
TRYFREE(s->outbuf);
TRYFREE(s->path);
TRYFREE(s);
return err;
}
/* ===========================================================================
Reads the given number of uncompressed bytes from the compressed file.
gzread returns the number of bytes actually read (0 for end of file).
*/
int ZEXPORT gzread (file, buf, len)
gzFile file;
voidp buf;
unsigned len;
{
gz_stream *s = (gz_stream*)file;
Bytef *start = (Bytef*)buf; /* starting point for crc computation */
Byte *next_out; /* == stream.next_out but not forced far (for MSDOS) */
if (s == NULL || s->mode != 'r') return Z_STREAM_ERROR;
if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1;
if (s->z_err == Z_STREAM_END) return 0; /* EOF */
next_out = (Byte*)buf;
s->stream.next_out = (Bytef*)buf;
s->stream.avail_out = len;
if (s->stream.avail_out && s->back != EOF) {
*next_out++ = s->back;
s->stream.next_out++;
s->stream.avail_out--;
s->back = EOF;
s->out++;
start++;
if (s->last) {
s->z_err = Z_STREAM_END;
return 1;
}
}
while (s->stream.avail_out != 0) {
if (s->transparent) {
/* Copy first the lookahead bytes: */
uInt n = s->stream.avail_in;
if (n > s->stream.avail_out) n = s->stream.avail_out;
if (n > 0) {
zmemcpy(s->stream.next_out, s->stream.next_in, n);
next_out += n;
s->stream.next_out = next_out;
s->stream.next_in += n;
s->stream.avail_out -= n;
s->stream.avail_in -= n;
}
if (s->stream.avail_out > 0) {
s->stream.avail_out -=
(uInt)fread(next_out, 1, s->stream.avail_out, s->file);
}
len -= s->stream.avail_out;
s->in += len;
s->out += len;
if (len == 0) s->z_eof = 1;
return (int)len;
}
if (s->stream.avail_in == 0 && !s->z_eof) {
errno = 0;
s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file);
if (s->stream.avail_in == 0) {
s->z_eof = 1;
if (ferror(s->file)) {
s->z_err = Z_ERRNO;
break;
}
}
s->stream.next_in = s->inbuf;
}
s->in += s->stream.avail_in;
s->out += s->stream.avail_out;
s->z_err = inflate(&(s->stream), Z_NO_FLUSH);
s->in -= s->stream.avail_in;
s->out -= s->stream.avail_out;
if (s->z_err == Z_STREAM_END) {
/* Check CRC and original size */
s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
start = s->stream.next_out;
if (getLong(s) != s->crc) {
s->z_err = Z_DATA_ERROR;
} else {
(void)getLong(s);
/* The uncompressed length returned by above getlong() may be
* different from s->out in case of concatenated .gz files.
* Check for such files:
*/
check_header(s);
if (s->z_err == Z_OK) {
inflateReset(&(s->stream));
s->crc = crc32(0L, Z_NULL, 0);
}
}
}
if (s->z_err != Z_OK || s->z_eof) break;
}
s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
if (len == s->stream.avail_out &&
(s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO))
return -1;
return (int)(len - s->stream.avail_out);
}
/* ===========================================================================
Reads one byte from the compressed file. gzgetc returns this byte
or -1 in case of end of file or error.
*/
int ZEXPORT gzgetc(file)
gzFile file;
{
unsigned char c;
return gzread(file, &c, 1) == 1 ? c : -1;
}
/* ===========================================================================
Push one byte back onto the stream.
*/
int ZEXPORT gzungetc(c, file)
int c;
gzFile file;
{
gz_stream *s = (gz_stream*)file;
if (s == NULL || s->mode != 'r' || c == EOF || s->back != EOF) return EOF;
s->back = c;
s->out--;
s->last = (s->z_err == Z_STREAM_END);
if (s->last) s->z_err = Z_OK;
s->z_eof = 0;
return c;
}
/* ===========================================================================
Reads bytes from the compressed file until len-1 characters are
read, or a newline character is read and transferred to buf, or an
end-of-file condition is encountered. The string is then terminated
with a null character.
gzgets returns buf, or Z_NULL in case of error.
The current implementation is not optimized at all.
*/
char * ZEXPORT gzgets(file, buf, len)
gzFile file;
char *buf;
int len;
{
char *b = buf;
if (buf == Z_NULL || len <= 0) return Z_NULL;
while (--len > 0 && gzread(file, buf, 1) == 1 && *buf++ != '\n') ;
*buf = '\0';
return b == buf && len > 0 ? Z_NULL : b;
}
#ifndef NO_GZCOMPRESS
/* ===========================================================================
Writes the given number of uncompressed bytes into the compressed file.
gzwrite returns the number of bytes actually written (0 in case of error).
*/
int ZEXPORT gzwrite (file, buf, len)
gzFile file;
voidpc buf;
unsigned len;
{
gz_stream *s = (gz_stream*)file;
if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
s->stream.next_in = (Bytef*)buf;
s->stream.avail_in = len;
while (s->stream.avail_in != 0) {
if (s->stream.avail_out == 0) {
s->stream.next_out = s->outbuf;
if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
s->z_err = Z_ERRNO;
break;
}
s->stream.avail_out = Z_BUFSIZE;
}
s->in += s->stream.avail_in;
s->out += s->stream.avail_out;
s->z_err = deflate(&(s->stream), Z_NO_FLUSH);
s->in -= s->stream.avail_in;
s->out -= s->stream.avail_out;
if (s->z_err != Z_OK) break;
}
s->crc = crc32(s->crc, (const Bytef *)buf, len);
return (int)(len - s->stream.avail_in);
}
/* ===========================================================================
Converts, formats, and writes the args to the compressed file under
control of the format string, as in fprintf. gzprintf returns the number of
uncompressed bytes actually written (0 in case of error).
*/
#ifdef STDC
#include <stdarg.h>
int ZEXPORTVA gzprintf (gzFile file, const char *format, /* args */ ...)
{
char buf[Z_PRINTF_BUFSIZE];
va_list va;
int len;
buf[sizeof(buf) - 1] = 0;
va_start(va, format);
#ifdef NO_vsnprintf
# ifdef HAS_vsprintf_void
(void)vsprintf(buf, format, va);
va_end(va);
for (len = 0; len < sizeof(buf); len++)
if (buf[len] == 0) break;
# else
len = vsprintf(buf, format, va);
va_end(va);
# endif
#else
# ifdef HAS_vsnprintf_void
(void)vsnprintf(buf, sizeof(buf), format, va);
va_end(va);
len = strlen(buf);
# else
len = vsnprintf(buf, sizeof(buf), format, va);
va_end(va);
# endif
#endif
if (len <= 0 || len >= (int)sizeof(buf) || buf[sizeof(buf) - 1] != 0)
return 0;
return gzwrite(file, buf, (unsigned)len);
}
#else /* not ANSI C */
int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)
gzFile file;
const char *format;
int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
a11, a12, a13, a14, a15, a16, a17, a18, a19, a20;
{
char buf[Z_PRINTF_BUFSIZE];
int len;
buf[sizeof(buf) - 1] = 0;
#ifdef NO_snprintf
# ifdef HAS_sprintf_void
sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8,
a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
for (len = 0; len < sizeof(buf); len++)
if (buf[len] == 0) break;
# else
len = sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8,
a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
# endif
#else
# ifdef HAS_snprintf_void
snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8,
a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
len = strlen(buf);
# else
len = snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8,
a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
# endif
#endif
if (len <= 0 || len >= sizeof(buf) || buf[sizeof(buf) - 1] != 0)
return 0;
return gzwrite(file, buf, len);
}
#endif
/* ===========================================================================
Writes c, converted to an unsigned char, into the compressed file.
gzputc returns the value that was written, or -1 in case of error.
*/
int ZEXPORT gzputc(file, c)
gzFile file;
int c;
{
unsigned char cc = (unsigned char) c; /* required for big endian systems */
return gzwrite(file, &cc, 1) == 1 ? (int)cc : -1;
}
/* ===========================================================================
Writes the given null-terminated string to the compressed file, excluding
the terminating null character.
gzputs returns the number of characters written, or -1 in case of error.
*/
int ZEXPORT gzputs(file, s)
gzFile file;
const char *s;
{
return gzwrite(file, (char*)s, (unsigned)strlen(s));
}
/* ===========================================================================
Flushes all pending output into the compressed file. The parameter
flush is as in the deflate() function.
*/
local int do_flush (file, flush)
gzFile file;
int flush;
{
uInt len;
int done = 0;
gz_stream *s = (gz_stream*)file;
if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
s->stream.avail_in = 0; /* should be zero already anyway */
for (;;) {
len = Z_BUFSIZE - s->stream.avail_out;
if (len != 0) {
if ((uInt)fwrite(s->outbuf, 1, len, s->file) != len) {
s->z_err = Z_ERRNO;
return Z_ERRNO;
}
s->stream.next_out = s->outbuf;
s->stream.avail_out = Z_BUFSIZE;
}
if (done) break;
s->out += s->stream.avail_out;
s->z_err = deflate(&(s->stream), flush);
s->out -= s->stream.avail_out;
/* Ignore the second of two consecutive flushes: */
if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK;
/* deflate has finished flushing only when it hasn't used up
* all the available space in the output buffer:
*/
done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END);
if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break;
}
return s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
}
int ZEXPORT gzflush (file, flush)
gzFile file;
int flush;
{
gz_stream *s = (gz_stream*)file;
int err = do_flush (file, flush);
if (err) return err;
fflush(s->file);
return s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
}
#endif /* NO_GZCOMPRESS */
/* ===========================================================================
Sets the starting position for the next gzread or gzwrite on the given
compressed file. The offset represents a number of bytes in the
gzseek returns the resulting offset location as measured in bytes from
the beginning of the uncompressed stream, or -1 in case of error.
SEEK_END is not implemented, returns error.
In this version of the library, gzseek can be extremely slow.
*/
z_off_t ZEXPORT gzseek (file, offset, whence)
gzFile file;
z_off_t offset;
int whence;
{
gz_stream *s = (gz_stream*)file;
if (s == NULL || whence == SEEK_END ||
s->z_err == Z_ERRNO || s->z_err == Z_DATA_ERROR) {
return -1L;
}
if (s->mode == 'w') {
#ifdef NO_GZCOMPRESS
return -1L;
#else
if (whence == SEEK_SET) {
offset -= s->in;
}
if (offset < 0) return -1L;
/* At this point, offset is the number of zero bytes to write. */
if (s->inbuf == Z_NULL) {
s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); /* for seeking */
if (s->inbuf == Z_NULL) return -1L;
zmemzero(s->inbuf, Z_BUFSIZE);
}
while (offset > 0) {
uInt size = Z_BUFSIZE;
if (offset < Z_BUFSIZE) size = (uInt)offset;
size = gzwrite(file, s->inbuf, size);
if (size == 0) return -1L;
offset -= size;
}
return s->in;
#endif
}
/* Rest of function is for reading only */
/* compute absolute position */
if (whence == SEEK_CUR) {
offset += s->out;
}
if (offset < 0) return -1L;
if (s->transparent) {
/* map to fseek */
s->back = EOF;
s->stream.avail_in = 0;
s->stream.next_in = s->inbuf;
if (fseek(s->file, offset, SEEK_SET) < 0) return -1L;
s->in = s->out = offset;
return offset;
}
/* For a negative seek, rewind and use positive seek */
if (offset >= s->out) {
offset -= s->out;
} else if (gzrewind(file) < 0) {
return -1L;
}
/* offset is now the number of bytes to skip. */
if (offset != 0 && s->outbuf == Z_NULL) {
s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
if (s->outbuf == Z_NULL) return -1L;
}
if (offset && s->back != EOF) {
s->back = EOF;
s->out++;
offset--;
if (s->last) s->z_err = Z_STREAM_END;
}
while (offset > 0) {
int size = Z_BUFSIZE;
if (offset < Z_BUFSIZE) size = (int)offset;
size = gzread(file, s->outbuf, (uInt)size);
if (size <= 0) return -1L;
offset -= size;
}
return s->out;
}
/* ===========================================================================
Rewinds input file.
*/
int ZEXPORT gzrewind (file)
gzFile file;
{
gz_stream *s = (gz_stream*)file;
if (s == NULL || s->mode != 'r') return -1;
s->z_err = Z_OK;
s->z_eof = 0;
s->back = EOF;
s->stream.avail_in = 0;
s->stream.next_in = s->inbuf;
s->crc = crc32(0L, Z_NULL, 0);
if (!s->transparent) (void)inflateReset(&s->stream);
s->in = 0;
s->out = 0;
return fseek(s->file, s->start, SEEK_SET);
}
/* ===========================================================================
Returns the starting position for the next gzread or gzwrite on the
given compressed file. This position represents a number of bytes in the
uncompressed data stream.
*/
z_off_t ZEXPORT gztell (file)
gzFile file;
{
return gzseek(file, 0L, SEEK_CUR);
}
/* ===========================================================================
Returns 1 when EOF has previously been detected reading the given
input stream, otherwise zero.
*/
int ZEXPORT gzeof (file)
gzFile file;
{
gz_stream *s = (gz_stream*)file;
/* With concatenated compressed files that can have embedded
* crc trailers, z_eof is no longer the only/best indicator of EOF
* on a gz_stream. Handle end-of-stream error explicitly here.
*/
if (s == NULL || s->mode != 'r') return 0;
if (s->z_eof) return 1;
return s->z_err == Z_STREAM_END;
}
/* ===========================================================================
Returns 1 if reading and doing so transparently, otherwise zero.
*/
int ZEXPORT gzdirect (file)
gzFile file;
{
gz_stream *s = (gz_stream*)file;
if (s == NULL || s->mode != 'r') return 0;
return s->transparent;
}
/* ===========================================================================
Outputs a long in LSB order to the given file
*/
local void putLong (file, x)
FILE *file;
uLong x;
{
int n;
for (n = 0; n < 4; n++) {
fputc((int)(x & 0xff), file);
x >>= 8;
}
}
/* ===========================================================================
Reads a long in LSB order from the given gz_stream. Sets z_err in case
of error.
*/
local uLong getLong (s)
gz_stream *s;
{
uLong x = (uLong)get_byte(s);
int c;
x += ((uLong)get_byte(s))<<8;
x += ((uLong)get_byte(s))<<16;
c = get_byte(s);
if (c == EOF) s->z_err = Z_DATA_ERROR;
x += ((uLong)c)<<24;
return x;
}
/* ===========================================================================
Flushes all pending output if necessary, closes the compressed file
and deallocates all the (de)compression state.
*/
int ZEXPORT gzclose (file)
gzFile file;
{
gz_stream *s = (gz_stream*)file;
if (s == NULL) return Z_STREAM_ERROR;
if (s->mode == 'w') {
#ifdef NO_GZCOMPRESS
return Z_STREAM_ERROR;
#else
if (do_flush (file, Z_FINISH) != Z_OK)
return destroy((gz_stream*)file);
putLong (s->file, s->crc);
putLong (s->file, (uLong)(s->in & 0xffffffff));
#endif
}
return destroy((gz_stream*)file);
}
#ifdef STDC
# define zstrerror(errnum) strerror(errnum)
#else
# define zstrerror(errnum) ""
#endif
/* ===========================================================================
Returns the error message for the last error which occurred on the
given compressed file. errnum is set to zlib error number. If an
error occurred in the file system and not in the compression library,
errnum is set to Z_ERRNO and the application may consult errno
to get the exact error code.
*/
const char * ZEXPORT gzerror (file, errnum)
gzFile file;
int *errnum;
{
char *m;
gz_stream *s = (gz_stream*)file;
if (s == NULL) {
*errnum = Z_STREAM_ERROR;
return (const char*)ERR_MSG(Z_STREAM_ERROR);
}
*errnum = s->z_err;
if (*errnum == Z_OK) return (const char*)"";
m = (char*)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg);
if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err);
TRYFREE(s->msg);
s->msg = (char*)ALLOC(strlen(s->path) + strlen(m) + 3);
if (s->msg == Z_NULL) return (const char*)ERR_MSG(Z_MEM_ERROR);
strcpy(s->msg, s->path);
strcat(s->msg, ": ");
strcat(s->msg, m);
return (const char*)s->msg;
}
/* ===========================================================================
Clear the error and end-of-file flags, and do the same for the real file.
*/
void ZEXPORT gzclearerr (file)
gzFile file;
{
gz_stream *s = (gz_stream*)file;
if (s == NULL) return;
if (s->z_err != Z_STREAM_END) s->z_err = Z_OK;
s->z_eof = 0;
clearerr(s->file);
}
| {
"pile_set_name": "Github"
} |
using System.Runtime.InteropServices;
using CoreFoundation;
using IOBluetooth;
using ObjCRuntime;
using Foundation;
using System;
namespace IOBluetoothUI
{
[Native]
[Flags]
public enum ServiceBrowserControllerOptions : ulong
{
None = 0,
//automatically start an inquiry when the panel is displayed. This has been deprecated in 10.5
//AutoStartInquiry = (1 << 0),
DisconnectWhenDone = (1 << 1)
}
public enum IOBluetoothUI
{
Success = (-1000),
UserCanceledErr = (-1001)
}
/*static class CFunctions
{
// extern IOReturn IOBluetoothValidateHardwareWithDescription (CFStringRef cancelButtonTitle, CFStringRef descriptionText) __attribute__((availability(macos, introduced=10.7)));
[Introduced(PlatformName.MacOSX, 10, 7)]
[DllImport("__Internal")]
static extern int IOBluetoothValidateHardwareWithDescription(NSString cancelButtonTitle, NSString descriptionText);
// extern IOBluetoothPairingControllerRef IOBluetoothGetPairingController ();
[DllImport("__Internal")]
static extern BluetoothPairingController IOBluetoothGetPairingController();
// extern IOBluetoothDeviceSelectorControllerRef IOBluetoothGetDeviceSelectorController ();
[DllImport("__Internal")]
static extern DeviceSelectorController IOBluetoothGetDeviceSelectorController();
}*/
/*public enum BluetoothKeyboardReturnType : uint
{
AnsiReturn,
IsoReturn,
JisReturn,
NoReturn
}*/
} | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<style xmlns="http://purl.org/net/xbiblio/csl" version="1.0" default-locale="en-US">
<!-- Elsevier, generated from "elsevier" metadata at https://github.com/citation-style-language/journals -->
<info>
<title>Egyptian Informatics Journal</title>
<id>http://www.zotero.org/styles/egyptian-informatics-journal</id>
<link href="http://www.zotero.org/styles/egyptian-informatics-journal" rel="self"/>
<link href="http://www.zotero.org/styles/elsevier-vancouver" rel="independent-parent"/>
<category citation-format="numeric"/>
<issn>1110-8665</issn>
<updated>2018-02-16T12:00:00+00:00</updated>
<rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
</info>
</style>
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2011, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
[
Conditional=WEB_AUDIO,
JSGenerateToJSObject
] interface DynamicsCompressorNode : AudioNode {
readonly attribute AudioParam threshold; // in Decibels
readonly attribute AudioParam knee; // in Decibels
readonly attribute AudioParam ratio; // unit-less
readonly attribute AudioParam reduction; // in Decibels
readonly attribute AudioParam attack; // in Seconds
readonly attribute AudioParam release; // in Seconds
};
| {
"pile_set_name": "Github"
} |
/*
* OS includes and handling of OS dependencies
*
* This header exists to pull in some common system headers that
* most code in QEMU will want, and to fix up some possible issues with
* it (missing defines, Windows weirdness, and so on).
*
* To avoid getting into possible circular include dependencies, this
* file should not include any other QEMU headers, with the exceptions
* of config-host.h, config-target.h, qemu/compiler.h,
* sysemu/os-posix.h, sysemu/os-win32.h, glib-compat.h and
* qemu/typedefs.h, all of which are doing a similar job to this file
* and are under similar constraints.
*
* This header also contains prototypes for functions defined in
* os-*.c and util/oslib-*.c; those would probably be better split
* out into separate header files.
*
* In an ideal world this header would contain only:
* (1) things which everybody needs
* (2) things without which code would work on most platforms but
* fail to compile or misbehave on a minority of host OSes
*
* This work is licensed under the terms of the GNU GPL, version 2 or later.
* See the COPYING file in the top-level directory.
*/
#ifndef QEMU_OSDEP_H
#define QEMU_OSDEP_H
#include "config-host.h"
#ifdef NEED_CPU_H
#include "config-target.h"
#else
#include "exec/poison.h"
#endif
#ifdef __COVERITY__
/* Coverity does not like the new _Float* types that are used by
* recent glibc, and croaks on every single file that includes
* stdlib.h. These typedefs are enough to please it.
*
* Note that these fix parse errors so they cannot be placed in
* scripts/coverity-model.c.
*/
typedef float _Float32;
typedef double _Float32x;
typedef double _Float64;
typedef __float80 _Float64x;
typedef __float128 _Float128;
#endif
#include "qemu/compiler.h"
/* Older versions of C++ don't get definitions of various macros from
* stdlib.h unless we define these macros before first inclusion of
* that system header.
*/
#ifndef __STDC_CONSTANT_MACROS
#define __STDC_CONSTANT_MACROS
#endif
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
/* The following block of code temporarily renames the daemon() function so the
* compiler does not see the warning associated with it in stdlib.h on OSX
*/
#ifdef __APPLE__
#define daemon qemu_fake_daemon_function
#include <stdlib.h>
#undef daemon
extern int daemon(int, int);
#endif
#ifdef _WIN32
/* as defined in sdkddkver.h */
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0600 /* Vista */
#endif
/* reduces the number of implicitly included headers */
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#endif
#include <stdarg.h>
#include <stddef.h>
#include <stdbool.h>
#include <stdint.h>
#include <sys/types.h>
#include <stdlib.h>
/* enable C99/POSIX format strings (needs mingw32-runtime 3.15 or later) */
#ifdef __MINGW32__
#define __USE_MINGW_ANSI_STDIO 1
#endif
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <inttypes.h>
#include <limits.h>
/* Put unistd.h before time.h as that triggers localtime_r/gmtime_r
* function availability on recentish Mingw-w64 platforms. */
#include <unistd.h>
#include <time.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <assert.h>
/* setjmp must be declared before sysemu/os-win32.h
* because it is redefined there. */
#include <setjmp.h>
#include <signal.h>
#ifdef __OpenBSD__
#include <sys/signal.h>
#endif
#ifndef _WIN32
#include <sys/wait.h>
#else
#define WIFEXITED(x) 1
#define WEXITSTATUS(x) (x)
#endif
#ifdef _WIN32
#include "sysemu/os-win32.h"
#endif
#ifdef CONFIG_POSIX
#include "sysemu/os-posix.h"
#endif
#include "glib-compat.h"
#include "qemu/typedefs.h"
/*
* For mingw, as of v6.0.0, the function implementing the assert macro is
* not marked as noreturn, so the compiler cannot delete code following an
* assert(false) as unused. We rely on this within the code base to delete
* code that is unreachable when features are disabled.
* All supported versions of Glib's g_assert() satisfy this requirement.
*/
#ifdef __MINGW32__
#undef assert
#define assert(x) g_assert(x)
#endif
/*
* According to waitpid man page:
* WCOREDUMP
* This macro is not specified in POSIX.1-2001 and is not
* available on some UNIX implementations (e.g., AIX, SunOS).
* Therefore, enclose its use inside #ifdef WCOREDUMP ... #endif.
*/
#ifndef WCOREDUMP
#define WCOREDUMP(status) 0
#endif
/*
* We have a lot of unaudited code that may fail in strange ways, or
* even be a security risk during migration, if you disable assertions
* at compile-time. You may comment out these safety checks if you
* absolutely want to disable assertion overhead, but it is not
* supported upstream so the risk is all yours. Meanwhile, please
* submit patches to remove any side-effects inside an assertion, or
* fixing error handling that should use Error instead of assert.
*/
#ifdef NDEBUG
#error building with NDEBUG is not supported
#endif
#ifdef G_DISABLE_ASSERT
#error building with G_DISABLE_ASSERT is not supported
#endif
#ifndef O_LARGEFILE
#define O_LARGEFILE 0
#endif
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef MAP_ANONYMOUS
#define MAP_ANONYMOUS MAP_ANON
#endif
#ifndef ENOMEDIUM
#define ENOMEDIUM ENODEV
#endif
#if !defined(ENOTSUP)
#define ENOTSUP 4096
#endif
#if !defined(ECANCELED)
#define ECANCELED 4097
#endif
#if !defined(EMEDIUMTYPE)
#define EMEDIUMTYPE 4098
#endif
#if !defined(ESHUTDOWN)
#define ESHUTDOWN 4099
#endif
/* time_t may be either 32 or 64 bits depending on the host OS, and
* can be either signed or unsigned, so we can't just hardcode a
* specific maximum value. This is not a C preprocessor constant,
* so you can't use TIME_MAX in an #ifdef, but for our purposes
* this isn't a problem.
*/
/* The macros TYPE_SIGNED, TYPE_WIDTH, and TYPE_MAXIMUM are from
* Gnulib, and are under the LGPL v2.1 or (at your option) any
* later version.
*/
/* True if the real type T is signed. */
#define TYPE_SIGNED(t) (!((t)0 < (t)-1))
/* The width in bits of the integer type or expression T.
* Padding bits are not supported.
*/
#define TYPE_WIDTH(t) (sizeof(t) * CHAR_BIT)
/* The maximum and minimum values for the integer type T. */
#define TYPE_MAXIMUM(t) \
((t) (!TYPE_SIGNED(t) \
? (t)-1 \
: ((((t)1 << (TYPE_WIDTH(t) - 2)) - 1) * 2 + 1)))
#ifndef TIME_MAX
#define TIME_MAX TYPE_MAXIMUM(time_t)
#endif
/* HOST_LONG_BITS is the size of a native pointer in bits. */
#if UINTPTR_MAX == UINT32_MAX
# define HOST_LONG_BITS 32
#elif UINTPTR_MAX == UINT64_MAX
# define HOST_LONG_BITS 64
#else
# error Unknown pointer size
#endif
/* Mac OSX has a <stdint.h> bug that incorrectly defines SIZE_MAX with
* the wrong type. Our replacement isn't usable in preprocessor
* expressions, but it is sufficient for our needs. */
#if defined(HAVE_BROKEN_SIZE_MAX) && HAVE_BROKEN_SIZE_MAX
#undef SIZE_MAX
#define SIZE_MAX ((size_t)-1)
#endif
#ifndef MIN
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#endif
#ifndef MAX
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#endif
/* Minimum function that returns zero only iff both values are zero.
* Intended for use with unsigned values only. */
#ifndef MIN_NON_ZERO
#define MIN_NON_ZERO(a, b) ((a) == 0 ? (b) : \
((b) == 0 ? (a) : (MIN(a, b))))
#endif
/* Round number down to multiple */
#define QEMU_ALIGN_DOWN(n, m) ((n) / (m) * (m))
/* Round number up to multiple. Safe when m is not a power of 2 (see
* ROUND_UP for a faster version when a power of 2 is guaranteed) */
#define QEMU_ALIGN_UP(n, m) QEMU_ALIGN_DOWN((n) + (m) - 1, (m))
/* Check if n is a multiple of m */
#define QEMU_IS_ALIGNED(n, m) (((n) % (m)) == 0)
/* n-byte align pointer down */
#define QEMU_ALIGN_PTR_DOWN(p, n) \
((typeof(p))QEMU_ALIGN_DOWN((uintptr_t)(p), (n)))
/* n-byte align pointer up */
#define QEMU_ALIGN_PTR_UP(p, n) \
((typeof(p))QEMU_ALIGN_UP((uintptr_t)(p), (n)))
/* Check if pointer p is n-bytes aligned */
#define QEMU_PTR_IS_ALIGNED(p, n) QEMU_IS_ALIGNED((uintptr_t)(p), (n))
/* Round number up to multiple. Requires that d be a power of 2 (see
* QEMU_ALIGN_UP for a safer but slower version on arbitrary
* numbers); works even if d is a smaller type than n. */
#ifndef ROUND_UP
#define ROUND_UP(n, d) (((n) + (d) - 1) & -(0 ? (n) : (d)))
#endif
#ifndef DIV_ROUND_UP
#define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d))
#endif
/*
* &(x)[0] is always a pointer - if it's same type as x then the argument is a
* pointer, not an array.
*/
#define QEMU_IS_ARRAY(x) (!__builtin_types_compatible_p(typeof(x), \
typeof(&(x)[0])))
#ifndef ARRAY_SIZE
#define ARRAY_SIZE(x) ((sizeof(x) / sizeof((x)[0])) + \
QEMU_BUILD_BUG_ON_ZERO(!QEMU_IS_ARRAY(x)))
#endif
int qemu_daemon(int nochdir, int noclose);
void *qemu_try_memalign(size_t alignment, size_t size);
void *qemu_memalign(size_t alignment, size_t size);
void *qemu_anon_ram_alloc(size_t size, uint64_t *align, bool shared);
void qemu_vfree(void *ptr);
void qemu_anon_ram_free(void *ptr, size_t size);
#define QEMU_MADV_INVALID -1
#if defined(CONFIG_MADVISE)
#define QEMU_MADV_WILLNEED MADV_WILLNEED
#define QEMU_MADV_DONTNEED MADV_DONTNEED
#ifdef MADV_DONTFORK
#define QEMU_MADV_DONTFORK MADV_DONTFORK
#else
#define QEMU_MADV_DONTFORK QEMU_MADV_INVALID
#endif
#ifdef MADV_MERGEABLE
#define QEMU_MADV_MERGEABLE MADV_MERGEABLE
#else
#define QEMU_MADV_MERGEABLE QEMU_MADV_INVALID
#endif
#ifdef MADV_UNMERGEABLE
#define QEMU_MADV_UNMERGEABLE MADV_UNMERGEABLE
#else
#define QEMU_MADV_UNMERGEABLE QEMU_MADV_INVALID
#endif
#ifdef MADV_DODUMP
#define QEMU_MADV_DODUMP MADV_DODUMP
#else
#define QEMU_MADV_DODUMP QEMU_MADV_INVALID
#endif
#ifdef MADV_DONTDUMP
#define QEMU_MADV_DONTDUMP MADV_DONTDUMP
#else
#define QEMU_MADV_DONTDUMP QEMU_MADV_INVALID
#endif
#ifdef MADV_HUGEPAGE
#define QEMU_MADV_HUGEPAGE MADV_HUGEPAGE
#else
#define QEMU_MADV_HUGEPAGE QEMU_MADV_INVALID
#endif
#ifdef MADV_NOHUGEPAGE
#define QEMU_MADV_NOHUGEPAGE MADV_NOHUGEPAGE
#else
#define QEMU_MADV_NOHUGEPAGE QEMU_MADV_INVALID
#endif
#ifdef MADV_REMOVE
#define QEMU_MADV_REMOVE MADV_REMOVE
#else
#define QEMU_MADV_REMOVE QEMU_MADV_INVALID
#endif
#elif defined(CONFIG_POSIX_MADVISE)
#define QEMU_MADV_WILLNEED POSIX_MADV_WILLNEED
#define QEMU_MADV_DONTNEED POSIX_MADV_DONTNEED
#define QEMU_MADV_DONTFORK QEMU_MADV_INVALID
#define QEMU_MADV_MERGEABLE QEMU_MADV_INVALID
#define QEMU_MADV_UNMERGEABLE QEMU_MADV_INVALID
#define QEMU_MADV_DODUMP QEMU_MADV_INVALID
#define QEMU_MADV_DONTDUMP QEMU_MADV_INVALID
#define QEMU_MADV_HUGEPAGE QEMU_MADV_INVALID
#define QEMU_MADV_NOHUGEPAGE QEMU_MADV_INVALID
#define QEMU_MADV_REMOVE QEMU_MADV_INVALID
#else /* no-op */
#define QEMU_MADV_WILLNEED QEMU_MADV_INVALID
#define QEMU_MADV_DONTNEED QEMU_MADV_INVALID
#define QEMU_MADV_DONTFORK QEMU_MADV_INVALID
#define QEMU_MADV_MERGEABLE QEMU_MADV_INVALID
#define QEMU_MADV_UNMERGEABLE QEMU_MADV_INVALID
#define QEMU_MADV_DODUMP QEMU_MADV_INVALID
#define QEMU_MADV_DONTDUMP QEMU_MADV_INVALID
#define QEMU_MADV_HUGEPAGE QEMU_MADV_INVALID
#define QEMU_MADV_NOHUGEPAGE QEMU_MADV_INVALID
#define QEMU_MADV_REMOVE QEMU_MADV_INVALID
#endif
#ifdef _WIN32
#define HAVE_CHARDEV_SERIAL 1
#elif defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
|| defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) \
|| defined(__GLIBC__)
#define HAVE_CHARDEV_SERIAL 1
#endif
#if defined(__linux__) || defined(__FreeBSD__) || \
defined(__FreeBSD_kernel__) || defined(__DragonFly__)
#define HAVE_CHARDEV_PARPORT 1
#endif
#if defined(CONFIG_LINUX)
#ifndef BUS_MCEERR_AR
#define BUS_MCEERR_AR 4
#endif
#ifndef BUS_MCEERR_AO
#define BUS_MCEERR_AO 5
#endif
#endif
#if defined(__linux__) && \
(defined(__x86_64__) || defined(__arm__) || defined(__aarch64__) \
|| defined(__powerpc64__))
/* Use 2 MiB alignment so transparent hugepages can be used by KVM.
Valgrind does not support alignments larger than 1 MiB,
therefore we need special code which handles running on Valgrind. */
# define QEMU_VMALLOC_ALIGN (512 * 4096)
#elif defined(__linux__) && defined(__s390x__)
/* Use 1 MiB (segment size) alignment so gmap can be used by KVM. */
# define QEMU_VMALLOC_ALIGN (256 * 4096)
#elif defined(__linux__) && defined(__sparc__)
#include <sys/shm.h>
# define QEMU_VMALLOC_ALIGN MAX(getpagesize(), SHMLBA)
#else
# define QEMU_VMALLOC_ALIGN getpagesize()
#endif
#ifdef CONFIG_POSIX
struct qemu_signalfd_siginfo {
uint32_t ssi_signo; /* Signal number */
int32_t ssi_errno; /* Error number (unused) */
int32_t ssi_code; /* Signal code */
uint32_t ssi_pid; /* PID of sender */
uint32_t ssi_uid; /* Real UID of sender */
int32_t ssi_fd; /* File descriptor (SIGIO) */
uint32_t ssi_tid; /* Kernel timer ID (POSIX timers) */
uint32_t ssi_band; /* Band event (SIGIO) */
uint32_t ssi_overrun; /* POSIX timer overrun count */
uint32_t ssi_trapno; /* Trap number that caused signal */
int32_t ssi_status; /* Exit status or signal (SIGCHLD) */
int32_t ssi_int; /* Integer sent by sigqueue(2) */
uint64_t ssi_ptr; /* Pointer sent by sigqueue(2) */
uint64_t ssi_utime; /* User CPU time consumed (SIGCHLD) */
uint64_t ssi_stime; /* System CPU time consumed (SIGCHLD) */
uint64_t ssi_addr; /* Address that generated signal
(for hardware-generated signals) */
uint8_t pad[48]; /* Pad size to 128 bytes (allow for
additional fields in the future) */
};
int qemu_signalfd(const sigset_t *mask);
void sigaction_invoke(struct sigaction *action,
struct qemu_signalfd_siginfo *info);
#endif
int qemu_madvise(void *addr, size_t len, int advice);
int qemu_mprotect_rwx(void *addr, size_t size);
int qemu_mprotect_none(void *addr, size_t size);
int qemu_open(const char *name, int flags, ...);
int qemu_close(int fd);
#ifndef _WIN32
int qemu_dup(int fd);
#endif
int qemu_lock_fd(int fd, int64_t start, int64_t len, bool exclusive);
int qemu_unlock_fd(int fd, int64_t start, int64_t len);
int qemu_lock_fd_test(int fd, int64_t start, int64_t len, bool exclusive);
bool qemu_has_ofd_lock(void);
#if defined(__HAIKU__) && defined(__i386__)
#define FMT_pid "%ld"
#elif defined(WIN64)
#define FMT_pid "%" PRId64
#else
#define FMT_pid "%d"
#endif
bool qemu_write_pidfile(const char *pidfile, Error **errp);
int qemu_get_thread_id(void);
#ifndef CONFIG_IOVEC
struct iovec {
void *iov_base;
size_t iov_len;
};
/*
* Use the same value as Linux for now.
*/
#define IOV_MAX 1024
ssize_t readv(int fd, const struct iovec *iov, int iov_cnt);
ssize_t writev(int fd, const struct iovec *iov, int iov_cnt);
#else
#include <sys/uio.h>
#endif
#ifdef _WIN32
static inline void qemu_timersub(const struct timeval *val1,
const struct timeval *val2,
struct timeval *res)
{
res->tv_sec = val1->tv_sec - val2->tv_sec;
if (val1->tv_usec < val2->tv_usec) {
res->tv_sec--;
res->tv_usec = val1->tv_usec - val2->tv_usec + 1000 * 1000;
} else {
res->tv_usec = val1->tv_usec - val2->tv_usec;
}
}
#else
#define qemu_timersub timersub
#endif
void qemu_set_cloexec(int fd);
/* Starting on QEMU 2.5, qemu_hw_version() returns "2.5+" by default
* instead of QEMU_VERSION, so setting hw_version on MachineClass
* is no longer mandatory.
*
* Do NOT change this string, or it will break compatibility on all
* machine classes that don't set hw_version.
*/
#define QEMU_HW_VERSION "2.5+"
/* QEMU "hardware version" setting. Used to replace code that exposed
* QEMU_VERSION to guests in the past and need to keep compatibility.
* Do not use qemu_hw_version() in new code.
*/
void qemu_set_hw_version(const char *);
const char *qemu_hw_version(void);
void fips_set_state(bool requested);
bool fips_get_state(void);
/* Return a dynamically allocated pathname denoting a file or directory that is
* appropriate for storing local state.
*
* @relative_pathname need not start with a directory separator; one will be
* added automatically.
*
* The caller is responsible for releasing the value returned with g_free()
* after use.
*/
char *qemu_get_local_state_pathname(const char *relative_pathname);
/* Find program directory, and save it for later usage with
* qemu_get_exec_dir().
* Try OS specific API first, if not working, parse from argv0. */
void qemu_init_exec_dir(const char *argv0);
/* Get the saved exec dir.
* Caller needs to release the returned string by g_free() */
char *qemu_get_exec_dir(void);
/**
* qemu_getauxval:
* @type: the auxiliary vector key to lookup
*
* Search the auxiliary vector for @type, returning the value
* or 0 if @type is not present.
*/
unsigned long qemu_getauxval(unsigned long type);
void qemu_set_tty_echo(int fd, bool echo);
void os_mem_prealloc(int fd, char *area, size_t sz, int smp_cpus,
Error **errp);
/**
* qemu_get_pmem_size:
* @filename: path to a pmem file
* @errp: pointer to a NULL-initialized error object
*
* Determine the size of a persistent memory file. Besides supporting files on
* DAX file systems, this function also supports Linux devdax character
* devices.
*
* Returns: the size or 0 on failure
*/
uint64_t qemu_get_pmem_size(const char *filename, Error **errp);
/**
* qemu_get_pid_name:
* @pid: pid of a process
*
* For given @pid fetch its name. Caller is responsible for
* freeing the string when no longer needed.
* Returns allocated string on success, NULL on failure.
*/
char *qemu_get_pid_name(pid_t pid);
/**
* qemu_fork:
*
* A version of fork that avoids signal handler race
* conditions that can lead to child process getting
* signals that are otherwise only expected by the
* parent. It also resets all signal handlers to the
* default settings.
*
* Returns 0 to child process, pid number to parent
* or -1 on failure.
*/
pid_t qemu_fork(Error **errp);
/* Using intptr_t ensures that qemu_*_page_mask is sign-extended even
* when intptr_t is 32-bit and we are aligning a long long.
*/
extern uintptr_t qemu_real_host_page_size;
extern intptr_t qemu_real_host_page_mask;
extern int qemu_icache_linesize;
extern int qemu_icache_linesize_log;
extern int qemu_dcache_linesize;
extern int qemu_dcache_linesize_log;
/*
* After using getopt or getopt_long, if you need to parse another set
* of options, then you must reset optind. Unfortunately the way to
* do this varies between implementations of getopt.
*/
static inline void qemu_reset_optind(void)
{
#ifdef HAVE_OPTRESET
optind = 1;
optreset = 1;
#else
optind = 0;
#endif
}
#endif
| {
"pile_set_name": "Github"
} |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Server
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* Zend_Server_Reflection_Node
*/
require_once 'Zend/Server/Reflection/Node.php';
/**
* Zend_Server_Reflection_Parameter
*/
require_once 'Zend/Server/Reflection/Parameter.php';
/**
* Zend_Server_Reflection_Prototype
*/
require_once 'Zend/Server/Reflection/Prototype.php';
/**
* Function/Method Reflection
*
* Decorates a ReflectionFunction. Allows setting and retrieving an alternate
* 'service' name (i.e., the name to be used when calling via a service),
* setting and retrieving the description (originally set using the docblock
* contents), retrieving the callback and callback type, retrieving additional
* method invocation arguments, and retrieving the
* method {@link Zend_Server_Reflection_Prototype prototypes}.
*
* @category Zend
* @package Zend_Server
* @subpackage Reflection
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
abstract class Zend_Server_Reflection_Function_Abstract
{
/**
* @var ReflectionFunction
*/
protected $_reflection;
/**
* Additional arguments to pass to method on invocation
* @var array
*/
protected $_argv = array();
/**
* Used to store extra configuration for the method (typically done by the
* server class, e.g., to indicate whether or not to instantiate a class).
* Associative array; access is as properties via {@link __get()} and
* {@link __set()}
* @var array
*/
protected $_config = array();
/**
* Declaring class (needed for when serialization occurs)
* @var string
*/
protected $_class;
/**
* Function/method description
* @var string
*/
protected $_description = '';
/**
* Namespace with which to prefix function/method name
* @var string
*/
protected $_namespace;
/**
* Prototypes
* @var array
*/
protected $_prototypes = array();
private $_return;
private $_returnDesc;
private $_paramDesc;
private $_sigParams;
private $_sigParamsDepth;
/**
* Constructor
*
* @param ReflectionFunction $r
*/
public function __construct(Reflector $r, $namespace = null, $argv = array())
{
// In PHP 5.1.x, ReflectionMethod extends ReflectionFunction. In 5.2.x,
// both extend ReflectionFunctionAbstract. So, we can't do normal type
// hinting in the prototype, but instead need to do some explicit
// testing here.
if ((!$r instanceof ReflectionFunction)
&& (!$r instanceof ReflectionMethod)) {
require_once 'Zend/Server/Reflection/Exception.php';
throw new Zend_Server_Reflection_Exception('Invalid reflection class');
}
$this->_reflection = $r;
// Determine namespace
if (null !== $namespace){
$this->setNamespace($namespace);
}
// Determine arguments
if (is_array($argv)) {
$this->_argv = $argv;
}
// If method call, need to store some info on the class
if ($r instanceof ReflectionMethod) {
$this->_class = $r->getDeclaringClass()->getName();
}
// Perform some introspection
$this->_reflect();
}
/**
* Create signature node tree
*
* Recursive method to build the signature node tree. Increments through
* each array in {@link $_sigParams}, adding every value of the next level
* to the current value (unless the current value is null).
*
* @param Zend_Server_Reflection_Node $parent
* @param int $level
* @return void
*/
protected function _addTree(Zend_Server_Reflection_Node $parent, $level = 0)
{
if ($level >= $this->_sigParamsDepth) {
return;
}
foreach ($this->_sigParams[$level] as $value) {
$node = new Zend_Server_Reflection_Node($value, $parent);
if ((null !== $value) && ($this->_sigParamsDepth > $level + 1)) {
$this->_addTree($node, $level + 1);
}
}
}
/**
* Build the signature tree
*
* Builds a signature tree starting at the return values and descending
* through each method argument. Returns an array of
* {@link Zend_Server_Reflection_Node}s.
*
* @return array
*/
protected function _buildTree()
{
$returnTree = array();
foreach ((array) $this->_return as $value) {
$node = new Zend_Server_Reflection_Node($value);
$this->_addTree($node);
$returnTree[] = $node;
}
return $returnTree;
}
/**
* Build method signatures
*
* Builds method signatures using the array of return types and the array of
* parameters types
*
* @param array $return Array of return types
* @param string $returnDesc Return value description
* @param array $params Array of arguments (each an array of types)
* @param array $paramDesc Array of parameter descriptions
* @return array
*/
protected function _buildSignatures($return, $returnDesc, $paramTypes, $paramDesc)
{
$this->_return = $return;
$this->_returnDesc = $returnDesc;
$this->_paramDesc = $paramDesc;
$this->_sigParams = $paramTypes;
$this->_sigParamsDepth = count($paramTypes);
$signatureTrees = $this->_buildTree();
$signatures = array();
$endPoints = array();
foreach ($signatureTrees as $root) {
$tmp = $root->getEndPoints();
if (empty($tmp)) {
$endPoints = array_merge($endPoints, array($root));
} else {
$endPoints = array_merge($endPoints, $tmp);
}
}
foreach ($endPoints as $node) {
if (!$node instanceof Zend_Server_Reflection_Node) {
continue;
}
$signature = array();
do {
array_unshift($signature, $node->getValue());
$node = $node->getParent();
} while ($node instanceof Zend_Server_Reflection_Node);
$signatures[] = $signature;
}
// Build prototypes
$params = $this->_reflection->getParameters();
foreach ($signatures as $signature) {
$return = new Zend_Server_Reflection_ReturnValue(array_shift($signature), $this->_returnDesc);
$tmp = array();
foreach ($signature as $key => $type) {
$param = new Zend_Server_Reflection_Parameter($params[$key], $type, (isset($this->_paramDesc[$key]) ? $this->_paramDesc[$key] : null));
$param->setPosition($key);
$tmp[] = $param;
}
$this->_prototypes[] = new Zend_Server_Reflection_Prototype($return, $tmp);
}
}
/**
* Use code reflection to create method signatures
*
* Determines the method help/description text from the function DocBlock
* comment. Determines method signatures using a combination of
* ReflectionFunction and parsing of DocBlock @param and @return values.
*
* @param ReflectionFunction $function
* @return array
*/
protected function _reflect()
{
$function = $this->_reflection;
$helpText = '';
$signatures = array();
$returnDesc = '';
$paramCount = $function->getNumberOfParameters();
$paramCountRequired = $function->getNumberOfRequiredParameters();
$parameters = $function->getParameters();
$docBlock = $function->getDocComment();
if (!empty($docBlock)) {
// Get help text
if (preg_match(':/\*\*\s*\r?\n\s*\*\s(.*?)\r?\n\s*\*(\s@|/):s', $docBlock, $matches))
{
$helpText = $matches[1];
$helpText = preg_replace('/(^\s*\*\s)/m', '', $helpText);
$helpText = preg_replace('/\r?\n\s*\*\s*(\r?\n)*/s', "\n", $helpText);
$helpText = trim($helpText);
}
// Get return type(s) and description
$return = 'void';
if (preg_match('/@return\s+(\S+)/', $docBlock, $matches)) {
$return = explode('|', $matches[1]);
if (preg_match('/@return\s+\S+\s+(.*?)(@|\*\/)/s', $docBlock, $matches))
{
$value = $matches[1];
$value = preg_replace('/\s?\*\s/m', '', $value);
$value = preg_replace('/\s{2,}/', ' ', $value);
$returnDesc = trim($value);
}
}
// Get param types and description
if (preg_match_all('/@param\s+([^\s]+)/m', $docBlock, $matches)) {
$paramTypesTmp = $matches[1];
if (preg_match_all('/@param\s+\S+\s+(\$\S+)\s+(.*?)(?=@|\*\/)/s', $docBlock, $matches))
{
$paramDesc = $matches[2];
foreach ($paramDesc as $key => $value) {
$value = preg_replace('/\s?\*\s/m', '', $value);
$value = preg_replace('/\s{2,}/', ' ', $value);
$paramDesc[$key] = trim($value);
}
}
}
} else {
$helpText = $function->getName();
$return = 'void';
// Try and auto-determine type, based on reflection
$paramTypesTmp = array();
foreach ($parameters as $i => $param) {
$paramType = 'mixed';
if ($param->isArray()) {
$paramType = 'array';
}
$paramTypesTmp[$i] = $paramType;
}
}
// Set method description
$this->setDescription($helpText);
// Get all param types as arrays
if (!isset($paramTypesTmp) && (0 < $paramCount)) {
$paramTypesTmp = array_fill(0, $paramCount, 'mixed');
} elseif (!isset($paramTypesTmp)) {
$paramTypesTmp = array();
} elseif (count($paramTypesTmp) < $paramCount) {
$start = $paramCount - count($paramTypesTmp);
for ($i = $start; $i < $paramCount; ++$i) {
$paramTypesTmp[$i] = 'mixed';
}
}
// Get all param descriptions as arrays
if (!isset($paramDesc) && (0 < $paramCount)) {
$paramDesc = array_fill(0, $paramCount, '');
} elseif (!isset($paramDesc)) {
$paramDesc = array();
} elseif (count($paramDesc) < $paramCount) {
$start = $paramCount - count($paramDesc);
for ($i = $start; $i < $paramCount; ++$i) {
$paramDesc[$i] = '';
}
}
if (count($paramTypesTmp) != $paramCount) {
require_once 'Zend/Server/Reflection/Exception.php';
throw new Zend_Server_Reflection_Exception(
'Variable number of arguments is not supported for services (except optional parameters). '
. 'Number of function arguments in ' . $function->getDeclaringClass()->getName() . '::'
. $function->getName() . '() must correspond to actual number of arguments described in the '
. 'docblock.');
}
$paramTypes = array();
foreach ($paramTypesTmp as $i => $param) {
$tmp = explode('|', $param);
if ($parameters[$i]->isOptional()) {
array_unshift($tmp, null);
}
$paramTypes[] = $tmp;
}
$this->_buildSignatures($return, $returnDesc, $paramTypes, $paramDesc);
}
/**
* Proxy reflection calls
*
* @param string $method
* @param array $args
* @return mixed
*/
public function __call($method, $args)
{
if (method_exists($this->_reflection, $method)) {
return call_user_func_array(array($this->_reflection, $method), $args);
}
require_once 'Zend/Server/Reflection/Exception.php';
throw new Zend_Server_Reflection_Exception('Invalid reflection method ("' .$method. '")');
}
/**
* Retrieve configuration parameters
*
* Values are retrieved by key from {@link $_config}. Returns null if no
* value found.
*
* @param string $key
* @return mixed
*/
public function __get($key)
{
if (isset($this->_config[$key])) {
return $this->_config[$key];
}
return null;
}
/**
* Set configuration parameters
*
* Values are stored by $key in {@link $_config}.
*
* @param string $key
* @param mixed $value
* @return void
*/
public function __set($key, $value)
{
$this->_config[$key] = $value;
}
/**
* Set method's namespace
*
* @param string $namespace
* @return void
*/
public function setNamespace($namespace)
{
if (empty($namespace)) {
$this->_namespace = '';
return;
}
if (!is_string($namespace) || !preg_match('/[a-z0-9_\.]+/i', $namespace)) {
require_once 'Zend/Server/Reflection/Exception.php';
throw new Zend_Server_Reflection_Exception('Invalid namespace');
}
$this->_namespace = $namespace;
}
/**
* Return method's namespace
*
* @return string
*/
public function getNamespace()
{
return $this->_namespace;
}
/**
* Set the description
*
* @param string $string
* @return void
*/
public function setDescription($string)
{
if (!is_string($string)) {
require_once 'Zend/Server/Reflection/Exception.php';
throw new Zend_Server_Reflection_Exception('Invalid description');
}
$this->_description = $string;
}
/**
* Retrieve the description
*
* @return void
*/
public function getDescription()
{
return $this->_description;
}
/**
* Retrieve all prototypes as array of
* {@link Zend_Server_Reflection_Prototype Zend_Server_Reflection_Prototypes}
*
* @return array
*/
public function getPrototypes()
{
return $this->_prototypes;
}
/**
* Retrieve additional invocation arguments
*
* @return array
*/
public function getInvokeArguments()
{
return $this->_argv;
}
/**
* Wakeup from serialization
*
* Reflection needs explicit instantiation to work correctly. Re-instantiate
* reflection object on wakeup.
*
* @return void
*/
public function __wakeup()
{
if ($this->_reflection instanceof ReflectionMethod) {
$class = new ReflectionClass($this->_class);
$this->_reflection = new ReflectionMethod($class->newInstance(), $this->getName());
} else {
$this->_reflection = new ReflectionFunction($this->getName());
}
}
}
| {
"pile_set_name": "Github"
} |
From b42ab8e1aca951dd06c113159491b3fd5cf06f2e Mon Sep 17 00:00:00 2001
From: Haiqing Bai <[email protected]>
Date: Thu, 24 Oct 2019 09:39:04 +0800
Subject: [PATCH] Add "listen" action for a tcp socket which does not call
'listen' after 'bind'
It is found that /usr/bin/unfsd customus 100% cpu after starting qemu with 'nfs'
option, and below lots of error messages shows when strace the process:
poll([{fd=3, events=POLLIN|POLLPRI|POLLRDNORM|POLLRDBAND},{fd=4, events=POLLIN|POLLPRI|POLLRDNORM|POLLRDBAND},
{fd=5, events=POLLIN|POLLPRI|POLLRDNORM|POLLRDBAND},{fd=6, events =POLLIN|POLLPRI|POLLRDNORM|POLLRDBAND}],
4, 2000) = 2 ([{fd=4, revents=POLLHUP},{fd=6, revents=POLLHUP}])
accept(4, 0x7ffd5e6dddc0, [128]) = -1 EINVAL (Invalid argument)
accept(6, 0x7ffd5e6dddc0, [128]) = -1 EINVAL (Invalid argument)
% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------
70.87 0.005392 0 513886 513886 accept
29.13 0.002216 0 256943 poll
0.00 0.000000 0 4 read
The root cause is that 'listen' is not called for the binded
socket. The depended libtipc does not call 'listen' if found
the incomming socket is binded, so 'accept' reports the error
in the 'for' loop and cpu consumed.
Upstream-Status: Pending
Signed-off-by: Haiqing Bai <[email protected]>
---
daemon.c | 7 +++++++
1 file changed, 7 insertions(+)
diff --git a/daemon.c b/daemon.c
index 028a181..4c85903 100644
--- a/daemon.c
+++ b/daemon.c
@@ -814,6 +814,13 @@ static SVCXPRT *create_tcp_transport(unsigned int port)
fprintf(stderr, "Couldn't bind to tcp port %d\n", port);
exit(1);
}
+
+ if (listen(sock, SOMAXCONN) < 0) {
+ perror("listen");
+ fprintf(stderr, "Couldn't listen on the address \n");
+ close(sock);
+ exit(1);
+ }
}
transp = svctcp_create(sock, 0, 0);
--
1.9.1
| {
"pile_set_name": "Github"
} |
! iso_c_wrap.f90 --
! Mimick the IOS_C_BINDING module that is standard with Fortran 2003
! This way we can easily prepare for Fortran 2003
!
module iso_c_binding
implicit none
integer, parameter :: c_int = kind(1)
integer, parameter :: c_long = kind(1) ! Requires adjustment for 64-bits?
integer, parameter :: c_float = kind(1.0)
integer, parameter :: c_double = kind(1.0d0)
type c_ptr
integer, dimension(2) :: ptr ! Two integers to cater for 64-bits platforms
end type c_ptr
end module
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:this="http://xmlns.opennms.org/xsd/config/qosd"
targetNamespace="http://xmlns.opennms.org/xsd/config/qosd"
elementFormDefault="qualified">
<element name="QoSDConfiguration">
<complexType>
<sequence>
<element ref="this:setting" minOccurs="0" maxOccurs="unbounded"/>
<element ref="this:eventlist" minOccurs="1" maxOccurs="1"/>
</sequence>
</complexType>
</element>
<element name="setting">
<complexType>
<attribute name="name" type="string" use="required"/>
<attribute name="value" type="string" use="required"/>
</complexType>
</element>
<element name="eventlist">
<complexType>
<sequence>
<element name="uei" type="string" minOccurs="0" maxOccurs="unbounded"/>
</sequence>
</complexType>
</element>
</schema>
| {
"pile_set_name": "Github"
} |
#ifndef __FLOCK_HXX
#define __FLOCK_HXX
#include <wininetp.h>
#include <mainwin.h>
extern void ShowReadOnlyCacheDialog(char* pszHostName);
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#if defined(UNIX) && defined(ux10)
#undef M
#include <net/if.h>
#define M * 1048576
#else
#include <net/if.h>
#endif
#include <netinet/if_ether.h>
#include <netdb.h>
#define LF "lf"
#define LOCKDBF "lockdbf"
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
#define read_lock(fd, offset, whence, len) \
lock_reg(fd, F_SETLK, F_RDLCK, offset, whence, len)
#define readw_lock(fd, offset, whence, len) \
lock_reg(fd, F_SETLKW, F_RDLCK, offset, whence, len)
#define write_lock(fd, offset, whence, len) \
lock_reg(fd, F_SETLK, F_WRLCK, offset, whence, len)
#define writew_lock(fd, offset, whence, len) \
lock_reg(fd, F_SETLKW, F_WRLCK, offset, whence, len)
#define un_lock(fd, offset, whence, len) \
lock_reg(fd, F_SETLK, F_UNLCK, offset, whence, len)
#define can_readlock(fd, offset, whence, len) \
lock_test(fd, F_RDLCK, offset, whence, len)
#define can_writelock(fd, offset, whence, len) \
lock_test(fd, F_WRLCK, offset, whence, len)
#endif /* __FLOCK_HXX */
| {
"pile_set_name": "Github"
} |
// Copyright 2011 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.
package html
import (
"strings"
)
func adjustAttributeNames(aa []Attribute, nameMap map[string]string) {
for i := range aa {
if newName, ok := nameMap[aa[i].Key]; ok {
aa[i].Key = newName
}
}
}
func adjustForeignAttributes(aa []Attribute) {
for i, a := range aa {
if a.Key == "" || a.Key[0] != 'x' {
continue
}
switch a.Key {
case "xlink:actuate", "xlink:arcrole", "xlink:href", "xlink:role", "xlink:show",
"xlink:title", "xlink:type", "xml:base", "xml:lang", "xml:space", "xmlns:xlink":
j := strings.Index(a.Key, ":")
aa[i].Namespace = a.Key[:j]
aa[i].Key = a.Key[j+1:]
}
}
}
func htmlIntegrationPoint(n *Node) bool {
if n.Type != ElementNode {
return false
}
switch n.Namespace {
case "math":
if n.Data == "annotation-xml" {
for _, a := range n.Attr {
if a.Key == "encoding" {
val := strings.ToLower(a.Val)
if val == "text/html" || val == "application/xhtml+xml" {
return true
}
}
}
}
case "svg":
switch n.Data {
case "desc", "foreignObject", "title":
return true
}
}
return false
}
func mathMLTextIntegrationPoint(n *Node) bool {
if n.Namespace != "math" {
return false
}
switch n.Data {
case "mi", "mo", "mn", "ms", "mtext":
return true
}
return false
}
// Section 12.2.6.5.
var breakout = map[string]bool{
"b": true,
"big": true,
"blockquote": true,
"body": true,
"br": true,
"center": true,
"code": true,
"dd": true,
"div": true,
"dl": true,
"dt": true,
"em": true,
"embed": true,
"h1": true,
"h2": true,
"h3": true,
"h4": true,
"h5": true,
"h6": true,
"head": true,
"hr": true,
"i": true,
"img": true,
"li": true,
"listing": true,
"menu": true,
"meta": true,
"nobr": true,
"ol": true,
"p": true,
"pre": true,
"ruby": true,
"s": true,
"small": true,
"span": true,
"strong": true,
"strike": true,
"sub": true,
"sup": true,
"table": true,
"tt": true,
"u": true,
"ul": true,
"var": true,
}
// Section 12.2.6.5.
var svgTagNameAdjustments = map[string]string{
"altglyph": "altGlyph",
"altglyphdef": "altGlyphDef",
"altglyphitem": "altGlyphItem",
"animatecolor": "animateColor",
"animatemotion": "animateMotion",
"animatetransform": "animateTransform",
"clippath": "clipPath",
"feblend": "feBlend",
"fecolormatrix": "feColorMatrix",
"fecomponenttransfer": "feComponentTransfer",
"fecomposite": "feComposite",
"feconvolvematrix": "feConvolveMatrix",
"fediffuselighting": "feDiffuseLighting",
"fedisplacementmap": "feDisplacementMap",
"fedistantlight": "feDistantLight",
"feflood": "feFlood",
"fefunca": "feFuncA",
"fefuncb": "feFuncB",
"fefuncg": "feFuncG",
"fefuncr": "feFuncR",
"fegaussianblur": "feGaussianBlur",
"feimage": "feImage",
"femerge": "feMerge",
"femergenode": "feMergeNode",
"femorphology": "feMorphology",
"feoffset": "feOffset",
"fepointlight": "fePointLight",
"fespecularlighting": "feSpecularLighting",
"fespotlight": "feSpotLight",
"fetile": "feTile",
"feturbulence": "feTurbulence",
"foreignobject": "foreignObject",
"glyphref": "glyphRef",
"lineargradient": "linearGradient",
"radialgradient": "radialGradient",
"textpath": "textPath",
}
// Section 12.2.6.1
var mathMLAttributeAdjustments = map[string]string{
"definitionurl": "definitionURL",
}
var svgAttributeAdjustments = map[string]string{
"attributename": "attributeName",
"attributetype": "attributeType",
"basefrequency": "baseFrequency",
"baseprofile": "baseProfile",
"calcmode": "calcMode",
"clippathunits": "clipPathUnits",
"contentscripttype": "contentScriptType",
"contentstyletype": "contentStyleType",
"diffuseconstant": "diffuseConstant",
"edgemode": "edgeMode",
"externalresourcesrequired": "externalResourcesRequired",
"filterunits": "filterUnits",
"glyphref": "glyphRef",
"gradienttransform": "gradientTransform",
"gradientunits": "gradientUnits",
"kernelmatrix": "kernelMatrix",
"kernelunitlength": "kernelUnitLength",
"keypoints": "keyPoints",
"keysplines": "keySplines",
"keytimes": "keyTimes",
"lengthadjust": "lengthAdjust",
"limitingconeangle": "limitingConeAngle",
"markerheight": "markerHeight",
"markerunits": "markerUnits",
"markerwidth": "markerWidth",
"maskcontentunits": "maskContentUnits",
"maskunits": "maskUnits",
"numoctaves": "numOctaves",
"pathlength": "pathLength",
"patterncontentunits": "patternContentUnits",
"patterntransform": "patternTransform",
"patternunits": "patternUnits",
"pointsatx": "pointsAtX",
"pointsaty": "pointsAtY",
"pointsatz": "pointsAtZ",
"preservealpha": "preserveAlpha",
"preserveaspectratio": "preserveAspectRatio",
"primitiveunits": "primitiveUnits",
"refx": "refX",
"refy": "refY",
"repeatcount": "repeatCount",
"repeatdur": "repeatDur",
"requiredextensions": "requiredExtensions",
"requiredfeatures": "requiredFeatures",
"specularconstant": "specularConstant",
"specularexponent": "specularExponent",
"spreadmethod": "spreadMethod",
"startoffset": "startOffset",
"stddeviation": "stdDeviation",
"stitchtiles": "stitchTiles",
"surfacescale": "surfaceScale",
"systemlanguage": "systemLanguage",
"tablevalues": "tableValues",
"targetx": "targetX",
"targety": "targetY",
"textlength": "textLength",
"viewbox": "viewBox",
"viewtarget": "viewTarget",
"xchannelselector": "xChannelSelector",
"ychannelselector": "yChannelSelector",
"zoomandpan": "zoomAndPan",
}
| {
"pile_set_name": "Github"
} |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mlsdev.rximagepicker">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application android:label="@string/app_name" />
</manifest>
| {
"pile_set_name": "Github"
} |
// Copyright 2012 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.
/*
Package agent implements a client to an ssh-agent daemon.
References:
[PROTOCOL.agent]: http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.agent?rev=HEAD
*/
package agent // import "golang.org/x/crypto/ssh/agent"
import (
"bytes"
"crypto/dsa"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rsa"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"io"
"math/big"
"sync"
"golang.org/x/crypto/ssh"
)
// Agent represents the capabilities of an ssh-agent.
type Agent interface {
// List returns the identities known to the agent.
List() ([]*Key, error)
// Sign has the agent sign the data using a protocol 2 key as defined
// in [PROTOCOL.agent] section 2.6.2.
Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error)
// Add adds a private key to the agent.
Add(key AddedKey) error
// Remove removes all identities with the given public key.
Remove(key ssh.PublicKey) error
// RemoveAll removes all identities.
RemoveAll() error
// Lock locks the agent. Sign and Remove will fail, and List will empty an empty list.
Lock(passphrase []byte) error
// Unlock undoes the effect of Lock
Unlock(passphrase []byte) error
// Signers returns signers for all the known keys.
Signers() ([]ssh.Signer, error)
}
// AddedKey describes an SSH key to be added to an Agent.
type AddedKey struct {
// PrivateKey must be a *rsa.PrivateKey, *dsa.PrivateKey or
// *ecdsa.PrivateKey, which will be inserted into the agent.
PrivateKey interface{}
// Certificate, if not nil, is communicated to the agent and will be
// stored with the key.
Certificate *ssh.Certificate
// Comment is an optional, free-form string.
Comment string
// LifetimeSecs, if not zero, is the number of seconds that the
// agent will store the key for.
LifetimeSecs uint32
// ConfirmBeforeUse, if true, requests that the agent confirm with the
// user before each use of this key.
ConfirmBeforeUse bool
}
// See [PROTOCOL.agent], section 3.
const (
agentRequestV1Identities = 1
// 3.2 Requests from client to agent for protocol 2 key operations
agentAddIdentity = 17
agentRemoveIdentity = 18
agentRemoveAllIdentities = 19
agentAddIdConstrained = 25
// 3.3 Key-type independent requests from client to agent
agentAddSmartcardKey = 20
agentRemoveSmartcardKey = 21
agentLock = 22
agentUnlock = 23
agentAddSmartcardKeyConstrained = 26
// 3.7 Key constraint identifiers
agentConstrainLifetime = 1
agentConstrainConfirm = 2
)
// maxAgentResponseBytes is the maximum agent reply size that is accepted. This
// is a sanity check, not a limit in the spec.
const maxAgentResponseBytes = 16 << 20
// Agent messages:
// These structures mirror the wire format of the corresponding ssh agent
// messages found in [PROTOCOL.agent].
// 3.4 Generic replies from agent to client
const agentFailure = 5
type failureAgentMsg struct{}
const agentSuccess = 6
type successAgentMsg struct{}
// See [PROTOCOL.agent], section 2.5.2.
const agentRequestIdentities = 11
type requestIdentitiesAgentMsg struct{}
// See [PROTOCOL.agent], section 2.5.2.
const agentIdentitiesAnswer = 12
type identitiesAnswerAgentMsg struct {
NumKeys uint32 `sshtype:"12"`
Keys []byte `ssh:"rest"`
}
// See [PROTOCOL.agent], section 2.6.2.
const agentSignRequest = 13
type signRequestAgentMsg struct {
KeyBlob []byte `sshtype:"13"`
Data []byte
Flags uint32
}
// See [PROTOCOL.agent], section 2.6.2.
// 3.6 Replies from agent to client for protocol 2 key operations
const agentSignResponse = 14
type signResponseAgentMsg struct {
SigBlob []byte `sshtype:"14"`
}
type publicKey struct {
Format string
Rest []byte `ssh:"rest"`
}
// Key represents a protocol 2 public key as defined in
// [PROTOCOL.agent], section 2.5.2.
type Key struct {
Format string
Blob []byte
Comment string
}
func clientErr(err error) error {
return fmt.Errorf("agent: client error: %v", err)
}
// String returns the storage form of an agent key with the format, base64
// encoded serialized key, and the comment if it is not empty.
func (k *Key) String() string {
s := string(k.Format) + " " + base64.StdEncoding.EncodeToString(k.Blob)
if k.Comment != "" {
s += " " + k.Comment
}
return s
}
// Type returns the public key type.
func (k *Key) Type() string {
return k.Format
}
// Marshal returns key blob to satisfy the ssh.PublicKey interface.
func (k *Key) Marshal() []byte {
return k.Blob
}
// Verify satisfies the ssh.PublicKey interface, but is not
// implemented for agent keys.
func (k *Key) Verify(data []byte, sig *ssh.Signature) error {
return errors.New("agent: agent key does not know how to verify")
}
type wireKey struct {
Format string
Rest []byte `ssh:"rest"`
}
func parseKey(in []byte) (out *Key, rest []byte, err error) {
var record struct {
Blob []byte
Comment string
Rest []byte `ssh:"rest"`
}
if err := ssh.Unmarshal(in, &record); err != nil {
return nil, nil, err
}
var wk wireKey
if err := ssh.Unmarshal(record.Blob, &wk); err != nil {
return nil, nil, err
}
return &Key{
Format: wk.Format,
Blob: record.Blob,
Comment: record.Comment,
}, record.Rest, nil
}
// client is a client for an ssh-agent process.
type client struct {
// conn is typically a *net.UnixConn
conn io.ReadWriter
// mu is used to prevent concurrent access to the agent
mu sync.Mutex
}
// NewClient returns an Agent that talks to an ssh-agent process over
// the given connection.
func NewClient(rw io.ReadWriter) Agent {
return &client{conn: rw}
}
// call sends an RPC to the agent. On success, the reply is
// unmarshaled into reply and replyType is set to the first byte of
// the reply, which contains the type of the message.
func (c *client) call(req []byte) (reply interface{}, err error) {
c.mu.Lock()
defer c.mu.Unlock()
msg := make([]byte, 4+len(req))
binary.BigEndian.PutUint32(msg, uint32(len(req)))
copy(msg[4:], req)
if _, err = c.conn.Write(msg); err != nil {
return nil, clientErr(err)
}
var respSizeBuf [4]byte
if _, err = io.ReadFull(c.conn, respSizeBuf[:]); err != nil {
return nil, clientErr(err)
}
respSize := binary.BigEndian.Uint32(respSizeBuf[:])
if respSize > maxAgentResponseBytes {
return nil, clientErr(err)
}
buf := make([]byte, respSize)
if _, err = io.ReadFull(c.conn, buf); err != nil {
return nil, clientErr(err)
}
reply, err = unmarshal(buf)
if err != nil {
return nil, clientErr(err)
}
return reply, err
}
func (c *client) simpleCall(req []byte) error {
resp, err := c.call(req)
if err != nil {
return err
}
if _, ok := resp.(*successAgentMsg); ok {
return nil
}
return errors.New("agent: failure")
}
func (c *client) RemoveAll() error {
return c.simpleCall([]byte{agentRemoveAllIdentities})
}
func (c *client) Remove(key ssh.PublicKey) error {
req := ssh.Marshal(&agentRemoveIdentityMsg{
KeyBlob: key.Marshal(),
})
return c.simpleCall(req)
}
func (c *client) Lock(passphrase []byte) error {
req := ssh.Marshal(&agentLockMsg{
Passphrase: passphrase,
})
return c.simpleCall(req)
}
func (c *client) Unlock(passphrase []byte) error {
req := ssh.Marshal(&agentUnlockMsg{
Passphrase: passphrase,
})
return c.simpleCall(req)
}
// List returns the identities known to the agent.
func (c *client) List() ([]*Key, error) {
// see [PROTOCOL.agent] section 2.5.2.
req := []byte{agentRequestIdentities}
msg, err := c.call(req)
if err != nil {
return nil, err
}
switch msg := msg.(type) {
case *identitiesAnswerAgentMsg:
if msg.NumKeys > maxAgentResponseBytes/8 {
return nil, errors.New("agent: too many keys in agent reply")
}
keys := make([]*Key, msg.NumKeys)
data := msg.Keys
for i := uint32(0); i < msg.NumKeys; i++ {
var key *Key
var err error
if key, data, err = parseKey(data); err != nil {
return nil, err
}
keys[i] = key
}
return keys, nil
case *failureAgentMsg:
return nil, errors.New("agent: failed to list keys")
}
panic("unreachable")
}
// Sign has the agent sign the data using a protocol 2 key as defined
// in [PROTOCOL.agent] section 2.6.2.
func (c *client) Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error) {
req := ssh.Marshal(signRequestAgentMsg{
KeyBlob: key.Marshal(),
Data: data,
})
msg, err := c.call(req)
if err != nil {
return nil, err
}
switch msg := msg.(type) {
case *signResponseAgentMsg:
var sig ssh.Signature
if err := ssh.Unmarshal(msg.SigBlob, &sig); err != nil {
return nil, err
}
return &sig, nil
case *failureAgentMsg:
return nil, errors.New("agent: failed to sign challenge")
}
panic("unreachable")
}
// unmarshal parses an agent message in packet, returning the parsed
// form and the message type of packet.
func unmarshal(packet []byte) (interface{}, error) {
if len(packet) < 1 {
return nil, errors.New("agent: empty packet")
}
var msg interface{}
switch packet[0] {
case agentFailure:
return new(failureAgentMsg), nil
case agentSuccess:
return new(successAgentMsg), nil
case agentIdentitiesAnswer:
msg = new(identitiesAnswerAgentMsg)
case agentSignResponse:
msg = new(signResponseAgentMsg)
default:
return nil, fmt.Errorf("agent: unknown type tag %d", packet[0])
}
if err := ssh.Unmarshal(packet, msg); err != nil {
return nil, err
}
return msg, nil
}
type rsaKeyMsg struct {
Type string `sshtype:"17"`
N *big.Int
E *big.Int
D *big.Int
Iqmp *big.Int // IQMP = Inverse Q Mod P
P *big.Int
Q *big.Int
Comments string
Constraints []byte `ssh:"rest"`
}
type dsaKeyMsg struct {
Type string `sshtype:"17"`
P *big.Int
Q *big.Int
G *big.Int
Y *big.Int
X *big.Int
Comments string
Constraints []byte `ssh:"rest"`
}
type ecdsaKeyMsg struct {
Type string `sshtype:"17"`
Curve string
KeyBytes []byte
D *big.Int
Comments string
Constraints []byte `ssh:"rest"`
}
// Insert adds a private key to the agent.
func (c *client) insertKey(s interface{}, comment string, constraints []byte) error {
var req []byte
switch k := s.(type) {
case *rsa.PrivateKey:
if len(k.Primes) != 2 {
return fmt.Errorf("agent: unsupported RSA key with %d primes", len(k.Primes))
}
k.Precompute()
req = ssh.Marshal(rsaKeyMsg{
Type: ssh.KeyAlgoRSA,
N: k.N,
E: big.NewInt(int64(k.E)),
D: k.D,
Iqmp: k.Precomputed.Qinv,
P: k.Primes[0],
Q: k.Primes[1],
Comments: comment,
Constraints: constraints,
})
case *dsa.PrivateKey:
req = ssh.Marshal(dsaKeyMsg{
Type: ssh.KeyAlgoDSA,
P: k.P,
Q: k.Q,
G: k.G,
Y: k.Y,
X: k.X,
Comments: comment,
Constraints: constraints,
})
case *ecdsa.PrivateKey:
nistID := fmt.Sprintf("nistp%d", k.Params().BitSize)
req = ssh.Marshal(ecdsaKeyMsg{
Type: "ecdsa-sha2-" + nistID,
Curve: nistID,
KeyBytes: elliptic.Marshal(k.Curve, k.X, k.Y),
D: k.D,
Comments: comment,
Constraints: constraints,
})
default:
return fmt.Errorf("agent: unsupported key type %T", s)
}
// if constraints are present then the message type needs to be changed.
if len(constraints) != 0 {
req[0] = agentAddIdConstrained
}
resp, err := c.call(req)
if err != nil {
return err
}
if _, ok := resp.(*successAgentMsg); ok {
return nil
}
return errors.New("agent: failure")
}
type rsaCertMsg struct {
Type string `sshtype:"17"`
CertBytes []byte
D *big.Int
Iqmp *big.Int // IQMP = Inverse Q Mod P
P *big.Int
Q *big.Int
Comments string
Constraints []byte `ssh:"rest"`
}
type dsaCertMsg struct {
Type string `sshtype:"17"`
CertBytes []byte
X *big.Int
Comments string
Constraints []byte `ssh:"rest"`
}
type ecdsaCertMsg struct {
Type string `sshtype:"17"`
CertBytes []byte
D *big.Int
Comments string
Constraints []byte `ssh:"rest"`
}
// Insert adds a private key to the agent. If a certificate is given,
// that certificate is added instead as public key.
func (c *client) Add(key AddedKey) error {
var constraints []byte
if secs := key.LifetimeSecs; secs != 0 {
constraints = append(constraints, agentConstrainLifetime)
var secsBytes [4]byte
binary.BigEndian.PutUint32(secsBytes[:], secs)
constraints = append(constraints, secsBytes[:]...)
}
if key.ConfirmBeforeUse {
constraints = append(constraints, agentConstrainConfirm)
}
if cert := key.Certificate; cert == nil {
return c.insertKey(key.PrivateKey, key.Comment, constraints)
} else {
return c.insertCert(key.PrivateKey, cert, key.Comment, constraints)
}
}
func (c *client) insertCert(s interface{}, cert *ssh.Certificate, comment string, constraints []byte) error {
var req []byte
switch k := s.(type) {
case *rsa.PrivateKey:
if len(k.Primes) != 2 {
return fmt.Errorf("agent: unsupported RSA key with %d primes", len(k.Primes))
}
k.Precompute()
req = ssh.Marshal(rsaCertMsg{
Type: cert.Type(),
CertBytes: cert.Marshal(),
D: k.D,
Iqmp: k.Precomputed.Qinv,
P: k.Primes[0],
Q: k.Primes[1],
Comments: comment,
Constraints: constraints,
})
case *dsa.PrivateKey:
req = ssh.Marshal(dsaCertMsg{
Type: cert.Type(),
CertBytes: cert.Marshal(),
X: k.X,
Comments: comment,
})
case *ecdsa.PrivateKey:
req = ssh.Marshal(ecdsaCertMsg{
Type: cert.Type(),
CertBytes: cert.Marshal(),
D: k.D,
Comments: comment,
})
default:
return fmt.Errorf("agent: unsupported key type %T", s)
}
// if constraints are present then the message type needs to be changed.
if len(constraints) != 0 {
req[0] = agentAddIdConstrained
}
signer, err := ssh.NewSignerFromKey(s)
if err != nil {
return err
}
if bytes.Compare(cert.Key.Marshal(), signer.PublicKey().Marshal()) != 0 {
return errors.New("agent: signer and cert have different public key")
}
resp, err := c.call(req)
if err != nil {
return err
}
if _, ok := resp.(*successAgentMsg); ok {
return nil
}
return errors.New("agent: failure")
}
// Signers provides a callback for client authentication.
func (c *client) Signers() ([]ssh.Signer, error) {
keys, err := c.List()
if err != nil {
return nil, err
}
var result []ssh.Signer
for _, k := range keys {
result = append(result, &agentKeyringSigner{c, k})
}
return result, nil
}
type agentKeyringSigner struct {
agent *client
pub ssh.PublicKey
}
func (s *agentKeyringSigner) PublicKey() ssh.PublicKey {
return s.pub
}
func (s *agentKeyringSigner) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) {
// The agent has its own entropy source, so the rand argument is ignored.
return s.agent.Sign(s.pub, data)
}
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 85187c2149c549c5b33f0cdb02836b17
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
.gg-arrow-right-o {
box-sizing: border-box;
position: relative;
display: block;
width: 22px;
height: 22px;
border: 2px solid;
transform: scale(var(--ggs,1));
border-radius: 20px
}
.gg-arrow-right-o::after,
.gg-arrow-right-o::before {
content: "";
display: block;
box-sizing: border-box;
position: absolute;
right: 4px
}
.gg-arrow-right-o::after {
width: 6px;
height: 6px;
border-top: 2px solid;
border-right: 2px solid;
transform: rotate(45deg);
bottom: 6px
}
.gg-arrow-right-o::before {
width: 10px;
height: 2px;
bottom: 8px;
background: currentColor
} | {
"pile_set_name": "Github"
} |
if (event.preview === 'disappearKeyboard') {
const payload = {
type: 'custom',
module: 'custom-component',
component: 'DisappearingText',
myrandomproperty:
'This text will disappear when the timer expires. You can add any component, buttons, etc as a keyboard',
wrapped: {
// We can wrap an existing component
...event.payload
}
}
bp.events.replyToEvent(event, [payload])
}
if (event.preview === 'feedbackKeyboard') {
const payload = {
type: 'custom',
module: 'custom-component',
component: 'FeedbackButtons',
wrapped: {
// Wrap an existing event...
...event.payload,
// Or create a new one
type: 'text',
text: 'bla'
}
}
bp.events.replyToEvent(event, [payload])
}
if (event.preview === 'multiLineKeyboard') {
const payload = {
type: 'text',
text: 'how can i help you?',
quick_replies: [
[
{ label: 'row 1, button 1', payload: 'something' },
{ label: 'row 1, button 2', payload: 'something' }
],
[{ label: 'row 2, button 1', payload: 'something' }],
[{ label: 'row 3, button 1', payload: 'something' }]
]
}
bp.events.replyToEvent(event, [payload])
}
if (event.preview === 'wrapperExample') {
const payload = {
type: 'custom',
module: 'custom-component',
component: 'ColorText',
color: '#ff0000',
wrapped: {
type: 'custom',
module: 'custom-component',
component: 'UpperCase',
wrapped: {
type: 'text',
text: 'this will be colored red & in uppercase '
}
}
}
bp.events.replyToEvent(event, [payload])
}
if (event.payload && event.payload.type === 'user_satisfied') {
bp.logger.info(`User is satisfied!`)
}
if (event.payload && event.payload.type === 'more_info') {
bp.logger.info(`User would like more info...`)
}
| {
"pile_set_name": "Github"
} |
[
{
"date": "2018-01-01 00:00:00",
"start": "2018-01-01T03:00:00.000Z",
"end": "2018-01-02T03:00:00.000Z",
"name": "Ano Novo",
"type": "public",
"rule": "01-01",
"_weekday": "Mon"
},
{
"date": "2018-02-10 00:00:00",
"start": "2018-02-10T03:00:00.000Z",
"end": "2018-02-14T17:00:00.000Z",
"name": "Carnaval",
"type": "optional",
"rule": "easter -50 PT110H",
"_weekday": "Sat"
},
{
"date": "2018-03-30 00:00:00",
"start": "2018-03-30T03:00:00.000Z",
"end": "2018-03-31T03:00:00.000Z",
"name": "Sexta-Feira Santa",
"type": "public",
"rule": "easter -2",
"_weekday": "Fri"
},
{
"date": "2018-04-01 00:00:00",
"start": "2018-04-01T03:00:00.000Z",
"end": "2018-04-02T03:00:00.000Z",
"name": "Páscoa",
"type": "observance",
"rule": "easter",
"_weekday": "Sun"
},
{
"date": "2018-04-21 00:00:00",
"start": "2018-04-21T03:00:00.000Z",
"end": "2018-04-22T03:00:00.000Z",
"name": "Dia de Tiradentes",
"type": "public",
"rule": "04-21",
"_weekday": "Sat"
},
{
"date": "2018-05-01 00:00:00",
"start": "2018-05-01T03:00:00.000Z",
"end": "2018-05-02T03:00:00.000Z",
"name": "Dia do trabalhador",
"type": "public",
"rule": "05-01",
"_weekday": "Tue"
},
{
"date": "2018-05-13 00:00:00",
"start": "2018-05-13T03:00:00.000Z",
"end": "2018-05-14T03:00:00.000Z",
"name": "Dia das Mães",
"type": "observance",
"rule": "2nd sunday in May",
"_weekday": "Sun"
},
{
"date": "2018-05-31 00:00:00",
"start": "2018-05-31T03:00:00.000Z",
"end": "2018-06-01T03:00:00.000Z",
"name": "Corpo de Deus",
"type": "optional",
"rule": "easter 60",
"_weekday": "Thu"
},
{
"date": "2018-06-12 00:00:00",
"start": "2018-06-12T03:00:00.000Z",
"end": "2018-06-13T03:00:00.000Z",
"name": "Dia dos Namorados",
"type": "public",
"rule": "06-12",
"_weekday": "Tue"
},
{
"date": "2018-08-12 00:00:00",
"start": "2018-08-12T03:00:00.000Z",
"end": "2018-08-13T03:00:00.000Z",
"name": "Dia dos Pais",
"type": "observance",
"rule": "2nd sunday in August",
"_weekday": "Sun"
},
{
"date": "2018-09-07 00:00:00",
"start": "2018-09-07T03:00:00.000Z",
"end": "2018-09-08T03:00:00.000Z",
"name": "Dia da Independência",
"type": "public",
"rule": "09-07",
"_weekday": "Fri"
},
{
"date": "2018-10-07 00:00:00",
"start": "2018-10-07T03:00:00.000Z",
"end": "2018-10-08T03:00:00.000Z",
"name": "Dia de Eleição",
"type": "public",
"rule": "1st sunday in October in even years",
"_weekday": "Sun"
},
{
"date": "2018-10-12 00:00:00",
"start": "2018-10-12T03:00:00.000Z",
"end": "2018-10-13T03:00:00.000Z",
"name": "Nossa Senhora Aparecida",
"type": "public",
"rule": "10-12",
"_weekday": "Fri"
},
{
"date": "2018-10-19 00:00:00",
"start": "2018-10-19T03:00:00.000Z",
"end": "2018-10-20T03:00:00.000Z",
"name": "Dia do Piauí",
"type": "public",
"rule": "10-19",
"_weekday": "Fri"
},
{
"date": "2018-10-28 00:00:00",
"start": "2018-10-28T03:00:00.000Z",
"end": "2018-10-29T03:00:00.000Z",
"name": "Dia de Eleição",
"type": "public",
"rule": "1st sunday before 11-01 in even years",
"_weekday": "Sun"
},
{
"date": "2018-11-02 00:00:00",
"start": "2018-11-02T03:00:00.000Z",
"end": "2018-11-03T03:00:00.000Z",
"name": "Dia de Finados",
"type": "public",
"rule": "11-02",
"_weekday": "Fri"
},
{
"date": "2018-11-15 00:00:00",
"start": "2018-11-15T03:00:00.000Z",
"end": "2018-11-16T03:00:00.000Z",
"name": "Proclamação da República",
"type": "public",
"rule": "11-15",
"_weekday": "Thu"
},
{
"date": "2018-12-24 14:00:00",
"start": "2018-12-24T17:00:00.000Z",
"end": "2018-12-25T03:00:00.000Z",
"name": "Noite de Natal",
"type": "optional",
"rule": "12-24 14:00",
"_weekday": "Mon"
},
{
"date": "2018-12-25 00:00:00",
"start": "2018-12-25T03:00:00.000Z",
"end": "2018-12-26T03:00:00.000Z",
"name": "Natal",
"type": "public",
"rule": "12-25",
"_weekday": "Tue"
},
{
"date": "2018-12-31 14:00:00",
"start": "2018-12-31T17:00:00.000Z",
"end": "2019-01-01T03:00:00.000Z",
"name": "Véspera de Ano Novo",
"type": "optional",
"rule": "12-31 14:00",
"_weekday": "Mon"
}
] | {
"pile_set_name": "Github"
} |
# $OpenBSD: Makefile,v 1.29 2019/09/07 13:16:47 naddy Exp $
COMMENT = enlightenment DBus component
DISTNAME = e_dbus-1.7.10
EPOCH = 1
REVISION = 5
SO_VERSION = 5.0 # 8.10
.for _lib in edbus enotify econnman0_7x ehal eofono ebluez eukit
SHARED_LIBS += ${_lib} ${SO_VERSION}
.endfor
# BSD
PERMIT_PACKAGE = Yes
WANTLIB = X11 Xcomposite Xcursor Xdamage Xext Xfixes Xi Xinerama Xrandr
WANTLIB += Xrender Xss Xtst c cares crypto curl dbus-1 ecore ecore_con
WANTLIB += ecore_evas ecore_input ecore_input_evas ecore_ipc ecore_x eet
WANTLIB += eina evas expat fontconfig freetype fribidi glib-2.0
WANTLIB += graphite2 harfbuzz iconv intl jpeg m nghttp2 pcre pthread ssl
WANTLIB += xcb z
LIB_DEPENDS = x11/dbus \
devel/fribidi \
x11/e17/ecore>=1.7.10v2
CONFIGURE_ARGS = --disable-doc
CONFIGURE_ENV = CPPFLAGS="${CFLAGS} -I${LOCALBASE}/include" \
LDFLAGS="${LDFLAGS} -L${LOCALBASE}/lib"
.include <bsd.port.mk>
| {
"pile_set_name": "Github"
} |
#! /bin/sh
# Configuration validation subroutine script.
# Copyright 1992-2013 Free Software Foundation, Inc.
timestamp='2013-08-10'
# This file 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 program is distributed in the 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, see <http://www.gnu.org/licenses/>.
#
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that
# program. This Exception is an additional permission under section 7
# of the GNU General Public License, version 3 ("GPLv3").
# Please send patches with a ChangeLog entry to [email protected].
#
# Configuration subroutine to validate and canonicalize a configuration type.
# Supply the specified configuration type as an argument.
# If it is invalid, we print an error message on stderr and exit with code 1.
# Otherwise, we print the canonical config type on stdout and succeed.
# You can get the latest version of this script from:
# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
# This file is supposed to be the same for all GNU packages
# and recognize all the CPU types, system types and aliases
# that are meaningful with *any* GNU software.
# Each package is responsible for reporting which valid configurations
# it does not support. The user should be able to distinguish
# a failure to support a valid configuration from a meaningless
# configuration.
# The goal of this file is to map all the various variations of a given
# machine specification into a single specification in the form:
# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
# or in some cases, the newer four-part form:
# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
# It is wrong to echo any other type of specification.
me=`echo "$0" | sed -e 's,.*/,,'`
usage="\
Usage: $0 [OPTION] CPU-MFR-OPSYS
$0 [OPTION] ALIAS
Canonicalize a configuration name.
Operation modes:
-h, --help print this help, then exit
-t, --time-stamp print date of last modification, then exit
-v, --version print version number, then exit
Report bugs and patches to <[email protected]>."
version="\
GNU config.sub ($timestamp)
Copyright 1992-2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
help="
Try \`$me --help' for more information."
# Parse command line
while test $# -gt 0 ; do
case $1 in
--time-stamp | --time* | -t )
echo "$timestamp" ; exit ;;
--version | -v )
echo "$version" ; exit ;;
--help | --h* | -h )
echo "$usage"; exit ;;
-- ) # Stop option processing
shift; break ;;
- ) # Use stdin as input.
break ;;
-* )
echo "$me: invalid option $1$help"
exit 1 ;;
*local*)
# First pass through any local machine types.
echo $1
exit ;;
* )
break ;;
esac
done
case $# in
0) echo "$me: missing argument$help" >&2
exit 1;;
1) ;;
*) echo "$me: too many arguments$help" >&2
exit 1;;
esac
# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any).
# Here we must recognize all the valid KERNEL-OS combinations.
maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
case $maybe_os in
nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \
linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \
knetbsd*-gnu* | netbsd*-gnu* | \
kopensolaris*-gnu* | \
storm-chaos* | os2-emx* | rtmk-nova*)
os=-$maybe_os
basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
;;
android-linux)
os=-linux-android
basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown
;;
*)
basic_machine=`echo $1 | sed 's/-[^-]*$//'`
if [ $basic_machine != $1 ]
then os=`echo $1 | sed 's/.*-/-/'`
else os=; fi
;;
esac
### Let's recognize common machines as not being operating systems so
### that things like config.sub decstation-3100 work. We also
### recognize some manufacturers as not being operating systems, so we
### can provide default operating systems below.
case $os in
-sun*os*)
# Prevent following clause from handling this invalid input.
;;
-dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \
-att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \
-unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \
-convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
-c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
-harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
-apple | -axis | -knuth | -cray | -microblaze*)
os=
basic_machine=$1
;;
-bluegene*)
os=-cnk
;;
-sim | -cisco | -oki | -wec | -winbond)
os=
basic_machine=$1
;;
-scout)
;;
-wrs)
os=-vxworks
basic_machine=$1
;;
-chorusos*)
os=-chorusos
basic_machine=$1
;;
-chorusrdb)
os=-chorusrdb
basic_machine=$1
;;
-hiux*)
os=-hiuxwe2
;;
-sco6)
os=-sco5v6
basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
;;
-sco5)
os=-sco3.2v5
basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
;;
-sco4)
os=-sco3.2v4
basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
;;
-sco3.2.[4-9]*)
os=`echo $os | sed -e 's/sco3.2./sco3.2v/'`
basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
;;
-sco3.2v[4-9]*)
# Don't forget version if it is 3.2v4 or newer.
basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
;;
-sco5v6*)
# Don't forget version if it is 3.2v4 or newer.
basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
;;
-sco*)
os=-sco3.2v2
basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
;;
-udk*)
basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
;;
-isc)
os=-isc2.2
basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
;;
-clix*)
basic_machine=clipper-intergraph
;;
-isc*)
basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
;;
-lynx*178)
os=-lynxos178
;;
-lynx*5)
os=-lynxos5
;;
-lynx*)
os=-lynxos
;;
-ptx*)
basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'`
;;
-windowsnt*)
os=`echo $os | sed -e 's/windowsnt/winnt/'`
;;
-psos*)
os=-psos
;;
-mint | -mint[0-9]*)
basic_machine=m68k-atari
os=-mint
;;
esac
# Decode aliases for certain CPU-COMPANY combinations.
case $basic_machine in
# Recognize the basic CPU types without company name.
# Some are omitted here because they have special meanings below.
1750a | 580 \
| a29k \
| aarch64 | aarch64_be \
| alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
| alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
| am33_2.0 \
| arc | arceb \
| arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \
| avr | avr32 \
| be32 | be64 \
| bfin \
| c4x | c8051 | clipper \
| d10v | d30v | dlx | dsp16xx \
| epiphany \
| fido | fr30 | frv \
| h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
| hexagon \
| i370 | i860 | i960 | ia64 \
| ip2k | iq2000 \
| le32 | le64 \
| lm32 \
| m32c | m32r | m32rle | m68000 | m68k | m88k \
| maxq | mb | microblaze | microblazeel | mcore | mep | metag \
| mips | mipsbe | mipseb | mipsel | mipsle \
| mips16 \
| mips64 | mips64el \
| mips64octeon | mips64octeonel \
| mips64orion | mips64orionel \
| mips64r5900 | mips64r5900el \
| mips64vr | mips64vrel \
| mips64vr4100 | mips64vr4100el \
| mips64vr4300 | mips64vr4300el \
| mips64vr5000 | mips64vr5000el \
| mips64vr5900 | mips64vr5900el \
| mipsisa32 | mipsisa32el \
| mipsisa32r2 | mipsisa32r2el \
| mipsisa64 | mipsisa64el \
| mipsisa64r2 | mipsisa64r2el \
| mipsisa64sb1 | mipsisa64sb1el \
| mipsisa64sr71k | mipsisa64sr71kel \
| mipsr5900 | mipsr5900el \
| mipstx39 | mipstx39el \
| mn10200 | mn10300 \
| moxie \
| mt \
| msp430 \
| nds32 | nds32le | nds32be \
| nios | nios2 | nios2eb | nios2el \
| ns16k | ns32k \
| open8 \
| or1k | or32 \
| pdp10 | pdp11 | pj | pjl \
| powerpc | powerpc64 | powerpc64le | powerpcle \
| pyramid \
| rl78 | rx \
| score \
| sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
| sh64 | sh64le \
| sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \
| sparcv8 | sparcv9 | sparcv9b | sparcv9v \
| spu \
| tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \
| ubicom32 \
| v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \
| we32k \
| x86 | xc16x | xstormy16 | xtensa \
| z8k | z80)
basic_machine=$basic_machine-unknown
;;
c54x)
basic_machine=tic54x-unknown
;;
c55x)
basic_machine=tic55x-unknown
;;
c6x)
basic_machine=tic6x-unknown
;;
m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | picochip)
basic_machine=$basic_machine-unknown
os=-none
;;
m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
;;
ms1)
basic_machine=mt-unknown
;;
strongarm | thumb | xscale)
basic_machine=arm-unknown
;;
xgate)
basic_machine=$basic_machine-unknown
os=-none
;;
xscaleeb)
basic_machine=armeb-unknown
;;
xscaleel)
basic_machine=armel-unknown
;;
# We use `pc' rather than `unknown'
# because (1) that's what they normally are, and
# (2) the word "unknown" tends to confuse beginning users.
i*86 | x86_64)
basic_machine=$basic_machine-pc
;;
# Object if more than one company name word.
*-*-*)
echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
exit 1
;;
# Recognize the basic CPU types with company name.
580-* \
| a29k-* \
| aarch64-* | aarch64_be-* \
| alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
| alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
| alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \
| arm-* | armbe-* | armle-* | armeb-* | armv*-* \
| avr-* | avr32-* \
| be32-* | be64-* \
| bfin-* | bs2000-* \
| c[123]* | c30-* | [cjt]90-* | c4x-* \
| c8051-* | clipper-* | craynv-* | cydra-* \
| d10v-* | d30v-* | dlx-* \
| elxsi-* \
| f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
| h8300-* | h8500-* \
| hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
| hexagon-* \
| i*86-* | i860-* | i960-* | ia64-* \
| ip2k-* | iq2000-* \
| le32-* | le64-* \
| lm32-* \
| m32c-* | m32r-* | m32rle-* \
| m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
| m88110-* | m88k-* | maxq-* | mcore-* | metag-* \
| microblaze-* | microblazeel-* \
| mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
| mips16-* \
| mips64-* | mips64el-* \
| mips64octeon-* | mips64octeonel-* \
| mips64orion-* | mips64orionel-* \
| mips64r5900-* | mips64r5900el-* \
| mips64vr-* | mips64vrel-* \
| mips64vr4100-* | mips64vr4100el-* \
| mips64vr4300-* | mips64vr4300el-* \
| mips64vr5000-* | mips64vr5000el-* \
| mips64vr5900-* | mips64vr5900el-* \
| mipsisa32-* | mipsisa32el-* \
| mipsisa32r2-* | mipsisa32r2el-* \
| mipsisa64-* | mipsisa64el-* \
| mipsisa64r2-* | mipsisa64r2el-* \
| mipsisa64sb1-* | mipsisa64sb1el-* \
| mipsisa64sr71k-* | mipsisa64sr71kel-* \
| mipsr5900-* | mipsr5900el-* \
| mipstx39-* | mipstx39el-* \
| mmix-* \
| mt-* \
| msp430-* \
| nds32-* | nds32le-* | nds32be-* \
| nios-* | nios2-* | nios2eb-* | nios2el-* \
| none-* | np1-* | ns16k-* | ns32k-* \
| open8-* \
| orion-* \
| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \
| pyramid-* \
| rl78-* | romp-* | rs6000-* | rx-* \
| sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \
| shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
| sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \
| sparclite-* \
| sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \
| tahoe-* \
| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
| tile*-* \
| tron-* \
| ubicom32-* \
| v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \
| vax-* \
| we32k-* \
| x86-* | x86_64-* | xc16x-* | xps100-* \
| xstormy16-* | xtensa*-* \
| ymp-* \
| z8k-* | z80-*)
;;
# Recognize the basic CPU types without company name, with glob match.
xtensa*)
basic_machine=$basic_machine-unknown
;;
# Recognize the various machine names and aliases which stand
# for a CPU type and a company and sometimes even an OS.
386bsd)
basic_machine=i386-unknown
os=-bsd
;;
3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)
basic_machine=m68000-att
;;
3b*)
basic_machine=we32k-att
;;
a29khif)
basic_machine=a29k-amd
os=-udi
;;
abacus)
basic_machine=abacus-unknown
;;
adobe68k)
basic_machine=m68010-adobe
os=-scout
;;
alliant | fx80)
basic_machine=fx80-alliant
;;
altos | altos3068)
basic_machine=m68k-altos
;;
am29k)
basic_machine=a29k-none
os=-bsd
;;
amd64)
basic_machine=x86_64-pc
;;
amd64-*)
basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
amdahl)
basic_machine=580-amdahl
os=-sysv
;;
amiga | amiga-*)
basic_machine=m68k-unknown
;;
amigaos | amigados)
basic_machine=m68k-unknown
os=-amigaos
;;
amigaunix | amix)
basic_machine=m68k-unknown
os=-sysv4
;;
apollo68)
basic_machine=m68k-apollo
os=-sysv
;;
apollo68bsd)
basic_machine=m68k-apollo
os=-bsd
;;
aros)
basic_machine=i386-pc
os=-aros
;;
aux)
basic_machine=m68k-apple
os=-aux
;;
balance)
basic_machine=ns32k-sequent
os=-dynix
;;
blackfin)
basic_machine=bfin-unknown
os=-linux
;;
blackfin-*)
basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'`
os=-linux
;;
bluegene*)
basic_machine=powerpc-ibm
os=-cnk
;;
c54x-*)
basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
c55x-*)
basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
c6x-*)
basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
c90)
basic_machine=c90-cray
os=-unicos
;;
cegcc)
basic_machine=arm-unknown
os=-cegcc
;;
convex-c1)
basic_machine=c1-convex
os=-bsd
;;
convex-c2)
basic_machine=c2-convex
os=-bsd
;;
convex-c32)
basic_machine=c32-convex
os=-bsd
;;
convex-c34)
basic_machine=c34-convex
os=-bsd
;;
convex-c38)
basic_machine=c38-convex
os=-bsd
;;
cray | j90)
basic_machine=j90-cray
os=-unicos
;;
craynv)
basic_machine=craynv-cray
os=-unicosmp
;;
cr16 | cr16-*)
basic_machine=cr16-unknown
os=-elf
;;
crds | unos)
basic_machine=m68k-crds
;;
crisv32 | crisv32-* | etraxfs*)
basic_machine=crisv32-axis
;;
cris | cris-* | etrax*)
basic_machine=cris-axis
;;
crx)
basic_machine=crx-unknown
os=-elf
;;
da30 | da30-*)
basic_machine=m68k-da30
;;
decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn)
basic_machine=mips-dec
;;
decsystem10* | dec10*)
basic_machine=pdp10-dec
os=-tops10
;;
decsystem20* | dec20*)
basic_machine=pdp10-dec
os=-tops20
;;
delta | 3300 | motorola-3300 | motorola-delta \
| 3300-motorola | delta-motorola)
basic_machine=m68k-motorola
;;
delta88)
basic_machine=m88k-motorola
os=-sysv3
;;
dicos)
basic_machine=i686-pc
os=-dicos
;;
djgpp)
basic_machine=i586-pc
os=-msdosdjgpp
;;
dpx20 | dpx20-*)
basic_machine=rs6000-bull
os=-bosx
;;
dpx2* | dpx2*-bull)
basic_machine=m68k-bull
os=-sysv3
;;
ebmon29k)
basic_machine=a29k-amd
os=-ebmon
;;
elxsi)
basic_machine=elxsi-elxsi
os=-bsd
;;
encore | umax | mmax)
basic_machine=ns32k-encore
;;
es1800 | OSE68k | ose68k | ose | OSE)
basic_machine=m68k-ericsson
os=-ose
;;
fx2800)
basic_machine=i860-alliant
;;
genix)
basic_machine=ns32k-ns
;;
gmicro)
basic_machine=tron-gmicro
os=-sysv
;;
go32)
basic_machine=i386-pc
os=-go32
;;
h3050r* | hiux*)
basic_machine=hppa1.1-hitachi
os=-hiuxwe2
;;
h8300hms)
basic_machine=h8300-hitachi
os=-hms
;;
h8300xray)
basic_machine=h8300-hitachi
os=-xray
;;
h8500hms)
basic_machine=h8500-hitachi
os=-hms
;;
harris)
basic_machine=m88k-harris
os=-sysv3
;;
hp300-*)
basic_machine=m68k-hp
;;
hp300bsd)
basic_machine=m68k-hp
os=-bsd
;;
hp300hpux)
basic_machine=m68k-hp
os=-hpux
;;
hp3k9[0-9][0-9] | hp9[0-9][0-9])
basic_machine=hppa1.0-hp
;;
hp9k2[0-9][0-9] | hp9k31[0-9])
basic_machine=m68000-hp
;;
hp9k3[2-9][0-9])
basic_machine=m68k-hp
;;
hp9k6[0-9][0-9] | hp6[0-9][0-9])
basic_machine=hppa1.0-hp
;;
hp9k7[0-79][0-9] | hp7[0-79][0-9])
basic_machine=hppa1.1-hp
;;
hp9k78[0-9] | hp78[0-9])
# FIXME: really hppa2.0-hp
basic_machine=hppa1.1-hp
;;
hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893)
# FIXME: really hppa2.0-hp
basic_machine=hppa1.1-hp
;;
hp9k8[0-9][13679] | hp8[0-9][13679])
basic_machine=hppa1.1-hp
;;
hp9k8[0-9][0-9] | hp8[0-9][0-9])
basic_machine=hppa1.0-hp
;;
hppa-next)
os=-nextstep3
;;
hppaosf)
basic_machine=hppa1.1-hp
os=-osf
;;
hppro)
basic_machine=hppa1.1-hp
os=-proelf
;;
i370-ibm* | ibm*)
basic_machine=i370-ibm
;;
i*86v32)
basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
os=-sysv32
;;
i*86v4*)
basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
os=-sysv4
;;
i*86v)
basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
os=-sysv
;;
i*86sol2)
basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
os=-solaris2
;;
i386mach)
basic_machine=i386-mach
os=-mach
;;
i386-vsta | vsta)
basic_machine=i386-unknown
os=-vsta
;;
iris | iris4d)
basic_machine=mips-sgi
case $os in
-irix*)
;;
*)
os=-irix4
;;
esac
;;
isi68 | isi)
basic_machine=m68k-isi
os=-sysv
;;
m68knommu)
basic_machine=m68k-unknown
os=-linux
;;
m68knommu-*)
basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'`
os=-linux
;;
m88k-omron*)
basic_machine=m88k-omron
;;
magnum | m3230)
basic_machine=mips-mips
os=-sysv
;;
merlin)
basic_machine=ns32k-utek
os=-sysv
;;
microblaze*)
basic_machine=microblaze-xilinx
;;
mingw64)
basic_machine=x86_64-pc
os=-mingw64
;;
mingw32)
basic_machine=i686-pc
os=-mingw32
;;
mingw32ce)
basic_machine=arm-unknown
os=-mingw32ce
;;
miniframe)
basic_machine=m68000-convergent
;;
*mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*)
basic_machine=m68k-atari
os=-mint
;;
mips3*-*)
basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`
;;
mips3*)
basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
;;
monitor)
basic_machine=m68k-rom68k
os=-coff
;;
morphos)
basic_machine=powerpc-unknown
os=-morphos
;;
msdos)
basic_machine=i386-pc
os=-msdos
;;
ms1-*)
basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
;;
msys)
basic_machine=i686-pc
os=-msys
;;
mvs)
basic_machine=i370-ibm
os=-mvs
;;
nacl)
basic_machine=le32-unknown
os=-nacl
;;
ncr3000)
basic_machine=i486-ncr
os=-sysv4
;;
netbsd386)
basic_machine=i386-unknown
os=-netbsd
;;
netwinder)
basic_machine=armv4l-rebel
os=-linux
;;
news | news700 | news800 | news900)
basic_machine=m68k-sony
os=-newsos
;;
news1000)
basic_machine=m68030-sony
os=-newsos
;;
news-3600 | risc-news)
basic_machine=mips-sony
os=-newsos
;;
necv70)
basic_machine=v70-nec
os=-sysv
;;
next | m*-next )
basic_machine=m68k-next
case $os in
-nextstep* )
;;
-ns2*)
os=-nextstep2
;;
*)
os=-nextstep3
;;
esac
;;
nh3000)
basic_machine=m68k-harris
os=-cxux
;;
nh[45]000)
basic_machine=m88k-harris
os=-cxux
;;
nindy960)
basic_machine=i960-intel
os=-nindy
;;
mon960)
basic_machine=i960-intel
os=-mon960
;;
nonstopux)
basic_machine=mips-compaq
os=-nonstopux
;;
np1)
basic_machine=np1-gould
;;
neo-tandem)
basic_machine=neo-tandem
;;
nse-tandem)
basic_machine=nse-tandem
;;
nsr-tandem)
basic_machine=nsr-tandem
;;
op50n-* | op60c-*)
basic_machine=hppa1.1-oki
os=-proelf
;;
openrisc | openrisc-*)
basic_machine=or32-unknown
;;
os400)
basic_machine=powerpc-ibm
os=-os400
;;
OSE68000 | ose68000)
basic_machine=m68000-ericsson
os=-ose
;;
os68k)
basic_machine=m68k-none
os=-os68k
;;
pa-hitachi)
basic_machine=hppa1.1-hitachi
os=-hiuxwe2
;;
paragon)
basic_machine=i860-intel
os=-osf
;;
parisc)
basic_machine=hppa-unknown
os=-linux
;;
parisc-*)
basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'`
os=-linux
;;
pbd)
basic_machine=sparc-tti
;;
pbb)
basic_machine=m68k-tti
;;
pc532 | pc532-*)
basic_machine=ns32k-pc532
;;
pc98)
basic_machine=i386-pc
;;
pc98-*)
basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
pentium | p5 | k5 | k6 | nexgen | viac3)
basic_machine=i586-pc
;;
pentiumpro | p6 | 6x86 | athlon | athlon_*)
basic_machine=i686-pc
;;
pentiumii | pentium2 | pentiumiii | pentium3)
basic_machine=i686-pc
;;
pentium4)
basic_machine=i786-pc
;;
pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)
basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
pentiumpro-* | p6-* | 6x86-* | athlon-*)
basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*)
basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
pentium4-*)
basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
pn)
basic_machine=pn-gould
;;
power) basic_machine=power-ibm
;;
ppc | ppcbe) basic_machine=powerpc-unknown
;;
ppc-* | ppcbe-*)
basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
ppcle | powerpclittle | ppc-le | powerpc-little)
basic_machine=powerpcle-unknown
;;
ppcle-* | powerpclittle-*)
basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
ppc64) basic_machine=powerpc64-unknown
;;
ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
ppc64le | powerpc64little | ppc64-le | powerpc64-little)
basic_machine=powerpc64le-unknown
;;
ppc64le-* | powerpc64little-*)
basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
ps2)
basic_machine=i386-ibm
;;
pw32)
basic_machine=i586-unknown
os=-pw32
;;
rdos | rdos64)
basic_machine=x86_64-pc
os=-rdos
;;
rdos32)
basic_machine=i386-pc
os=-rdos
;;
rom68k)
basic_machine=m68k-rom68k
os=-coff
;;
rm[46]00)
basic_machine=mips-siemens
;;
rtpc | rtpc-*)
basic_machine=romp-ibm
;;
s390 | s390-*)
basic_machine=s390-ibm
;;
s390x | s390x-*)
basic_machine=s390x-ibm
;;
sa29200)
basic_machine=a29k-amd
os=-udi
;;
sb1)
basic_machine=mipsisa64sb1-unknown
;;
sb1el)
basic_machine=mipsisa64sb1el-unknown
;;
sde)
basic_machine=mipsisa32-sde
os=-elf
;;
sei)
basic_machine=mips-sei
os=-seiux
;;
sequent)
basic_machine=i386-sequent
;;
sh)
basic_machine=sh-hitachi
os=-hms
;;
sh5el)
basic_machine=sh5le-unknown
;;
sh64)
basic_machine=sh64-unknown
;;
sparclite-wrs | simso-wrs)
basic_machine=sparclite-wrs
os=-vxworks
;;
sps7)
basic_machine=m68k-bull
os=-sysv2
;;
spur)
basic_machine=spur-unknown
;;
st2000)
basic_machine=m68k-tandem
;;
stratus)
basic_machine=i860-stratus
os=-sysv4
;;
strongarm-* | thumb-*)
basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'`
;;
sun2)
basic_machine=m68000-sun
;;
sun2os3)
basic_machine=m68000-sun
os=-sunos3
;;
sun2os4)
basic_machine=m68000-sun
os=-sunos4
;;
sun3os3)
basic_machine=m68k-sun
os=-sunos3
;;
sun3os4)
basic_machine=m68k-sun
os=-sunos4
;;
sun4os3)
basic_machine=sparc-sun
os=-sunos3
;;
sun4os4)
basic_machine=sparc-sun
os=-sunos4
;;
sun4sol2)
basic_machine=sparc-sun
os=-solaris2
;;
sun3 | sun3-*)
basic_machine=m68k-sun
;;
sun4)
basic_machine=sparc-sun
;;
sun386 | sun386i | roadrunner)
basic_machine=i386-sun
;;
sv1)
basic_machine=sv1-cray
os=-unicos
;;
symmetry)
basic_machine=i386-sequent
os=-dynix
;;
t3e)
basic_machine=alphaev5-cray
os=-unicos
;;
t90)
basic_machine=t90-cray
os=-unicos
;;
tile*)
basic_machine=$basic_machine-unknown
os=-linux-gnu
;;
tx39)
basic_machine=mipstx39-unknown
;;
tx39el)
basic_machine=mipstx39el-unknown
;;
toad1)
basic_machine=pdp10-xkl
os=-tops20
;;
tower | tower-32)
basic_machine=m68k-ncr
;;
tpf)
basic_machine=s390x-ibm
os=-tpf
;;
udi29k)
basic_machine=a29k-amd
os=-udi
;;
ultra3)
basic_machine=a29k-nyu
os=-sym1
;;
v810 | necv810)
basic_machine=v810-nec
os=-none
;;
vaxv)
basic_machine=vax-dec
os=-sysv
;;
vms)
basic_machine=vax-dec
os=-vms
;;
vpp*|vx|vx-*)
basic_machine=f301-fujitsu
;;
vxworks960)
basic_machine=i960-wrs
os=-vxworks
;;
vxworks68)
basic_machine=m68k-wrs
os=-vxworks
;;
vxworks29k)
basic_machine=a29k-wrs
os=-vxworks
;;
w65*)
basic_machine=w65-wdc
os=-none
;;
w89k-*)
basic_machine=hppa1.1-winbond
os=-proelf
;;
xbox)
basic_machine=i686-pc
os=-mingw32
;;
xps | xps100)
basic_machine=xps100-honeywell
;;
xscale-* | xscalee[bl]-*)
basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'`
;;
ymp)
basic_machine=ymp-cray
os=-unicos
;;
z8k-*-coff)
basic_machine=z8k-unknown
os=-sim
;;
z80-*-coff)
basic_machine=z80-unknown
os=-sim
;;
none)
basic_machine=none-none
os=-none
;;
# Here we handle the default manufacturer of certain CPU types. It is in
# some cases the only manufacturer, in others, it is the most popular.
w89k)
basic_machine=hppa1.1-winbond
;;
op50n)
basic_machine=hppa1.1-oki
;;
op60c)
basic_machine=hppa1.1-oki
;;
romp)
basic_machine=romp-ibm
;;
mmix)
basic_machine=mmix-knuth
;;
rs6000)
basic_machine=rs6000-ibm
;;
vax)
basic_machine=vax-dec
;;
pdp10)
# there are many clones, so DEC is not a safe bet
basic_machine=pdp10-unknown
;;
pdp11)
basic_machine=pdp11-dec
;;
we32k)
basic_machine=we32k-att
;;
sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele)
basic_machine=sh-unknown
;;
sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v)
basic_machine=sparc-sun
;;
cydra)
basic_machine=cydra-cydrome
;;
orion)
basic_machine=orion-highlevel
;;
orion105)
basic_machine=clipper-highlevel
;;
mac | mpw | mac-mpw)
basic_machine=m68k-apple
;;
pmac | pmac-mpw)
basic_machine=powerpc-apple
;;
*-unknown)
# Make sure to match an already-canonicalized machine name.
;;
*)
echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
exit 1
;;
esac
# Here we canonicalize certain aliases for manufacturers.
case $basic_machine in
*-digital*)
basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'`
;;
*-commodore*)
basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'`
;;
*)
;;
esac
# Decode manufacturer-specific aliases for certain operating systems.
if [ x"$os" != x"" ]
then
case $os in
# First match some system type aliases
# that might get confused with valid system types.
# -solaris* is a basic system type, with this one exception.
-auroraux)
os=-auroraux
;;
-solaris1 | -solaris1.*)
os=`echo $os | sed -e 's|solaris1|sunos4|'`
;;
-solaris)
os=-solaris2
;;
-svr4*)
os=-sysv4
;;
-unixware*)
os=-sysv4.2uw
;;
-gnu/linux*)
os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`
;;
# First accept the basic system types.
# The portable systems comes first.
# Each alternative MUST END IN A *, to match a version number.
# -sysv* is not here because it comes later, after sysvr4.
-gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
| -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\
| -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \
| -sym* | -kopensolaris* | -plan9* \
| -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
| -aos* | -aros* \
| -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
| -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
| -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
| -bitrig* | -openbsd* | -solidbsd* \
| -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
| -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
| -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
| -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
| -chorusos* | -chorusrdb* | -cegcc* \
| -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
| -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \
| -linux-newlib* | -linux-musl* | -linux-uclibc* \
| -uxpv* | -beos* | -mpeix* | -udk* \
| -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
| -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
| -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
| -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
| -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
| -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
| -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es*)
# Remember, each alternative MUST END IN *, to match a version number.
;;
-qnx*)
case $basic_machine in
x86-* | i*86-*)
;;
*)
os=-nto$os
;;
esac
;;
-nto-qnx*)
;;
-nto*)
os=`echo $os | sed -e 's|nto|nto-qnx|'`
;;
-sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
| -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \
| -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
;;
-mac*)
os=`echo $os | sed -e 's|mac|macos|'`
;;
-linux-dietlibc)
os=-linux-dietlibc
;;
-linux*)
os=`echo $os | sed -e 's|linux|linux-gnu|'`
;;
-sunos5*)
os=`echo $os | sed -e 's|sunos5|solaris2|'`
;;
-sunos6*)
os=`echo $os | sed -e 's|sunos6|solaris3|'`
;;
-opened*)
os=-openedition
;;
-os400*)
os=-os400
;;
-wince*)
os=-wince
;;
-osfrose*)
os=-osfrose
;;
-osf*)
os=-osf
;;
-utek*)
os=-bsd
;;
-dynix*)
os=-bsd
;;
-acis*)
os=-aos
;;
-atheos*)
os=-atheos
;;
-syllable*)
os=-syllable
;;
-386bsd)
os=-bsd
;;
-ctix* | -uts*)
os=-sysv
;;
-nova*)
os=-rtmk-nova
;;
-ns2 )
os=-nextstep2
;;
-nsk*)
os=-nsk
;;
# Preserve the version number of sinix5.
-sinix5.*)
os=`echo $os | sed -e 's|sinix|sysv|'`
;;
-sinix*)
os=-sysv4
;;
-tpf*)
os=-tpf
;;
-triton*)
os=-sysv3
;;
-oss*)
os=-sysv3
;;
-svr4)
os=-sysv4
;;
-svr3)
os=-sysv3
;;
-sysvr4)
os=-sysv4
;;
# This must come after -sysvr4.
-sysv*)
;;
-ose*)
os=-ose
;;
-es1800*)
os=-ose
;;
-xenix)
os=-xenix
;;
-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
os=-mint
;;
-aros*)
os=-aros
;;
-zvmoe)
os=-zvmoe
;;
-dicos*)
os=-dicos
;;
-nacl*)
;;
-none)
;;
*)
# Get rid of the `-' at the beginning of $os.
os=`echo $os | sed 's/[^-]*-//'`
echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2
exit 1
;;
esac
else
# Here we handle the default operating systems that come with various machines.
# The value should be what the vendor currently ships out the door with their
# machine or put another way, the most popular os provided with the machine.
# Note that if you're going to try to match "-MANUFACTURER" here (say,
# "-sun"), then you have to tell the case statement up towards the top
# that MANUFACTURER isn't an operating system. Otherwise, code above
# will signal an error saying that MANUFACTURER isn't an operating
# system, and we'll never get to this point.
case $basic_machine in
score-*)
os=-elf
;;
spu-*)
os=-elf
;;
*-acorn)
os=-riscix1.2
;;
arm*-rebel)
os=-linux
;;
arm*-semi)
os=-aout
;;
c4x-* | tic4x-*)
os=-coff
;;
c8051-*)
os=-elf
;;
hexagon-*)
os=-elf
;;
tic54x-*)
os=-coff
;;
tic55x-*)
os=-coff
;;
tic6x-*)
os=-coff
;;
# This must come before the *-dec entry.
pdp10-*)
os=-tops20
;;
pdp11-*)
os=-none
;;
*-dec | vax-*)
os=-ultrix4.2
;;
m68*-apollo)
os=-domain
;;
i386-sun)
os=-sunos4.0.2
;;
m68000-sun)
os=-sunos3
;;
m68*-cisco)
os=-aout
;;
mep-*)
os=-elf
;;
mips*-cisco)
os=-elf
;;
mips*-*)
os=-elf
;;
or1k-*)
os=-elf
;;
or32-*)
os=-coff
;;
*-tti) # must be before sparc entry or we get the wrong os.
os=-sysv3
;;
sparc-* | *-sun)
os=-sunos4.1.1
;;
*-be)
os=-beos
;;
*-haiku)
os=-haiku
;;
*-ibm)
os=-aix
;;
*-knuth)
os=-mmixware
;;
*-wec)
os=-proelf
;;
*-winbond)
os=-proelf
;;
*-oki)
os=-proelf
;;
*-hp)
os=-hpux
;;
*-hitachi)
os=-hiux
;;
i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)
os=-sysv
;;
*-cbm)
os=-amigaos
;;
*-dg)
os=-dgux
;;
*-dolphin)
os=-sysv3
;;
m68k-ccur)
os=-rtu
;;
m88k-omron*)
os=-luna
;;
*-next )
os=-nextstep
;;
*-sequent)
os=-ptx
;;
*-crds)
os=-unos
;;
*-ns)
os=-genix
;;
i370-*)
os=-mvs
;;
*-next)
os=-nextstep3
;;
*-gould)
os=-sysv
;;
*-highlevel)
os=-bsd
;;
*-encore)
os=-bsd
;;
*-sgi)
os=-irix
;;
*-siemens)
os=-sysv4
;;
*-masscomp)
os=-rtu
;;
f30[01]-fujitsu | f700-fujitsu)
os=-uxpv
;;
*-rom68k)
os=-coff
;;
*-*bug)
os=-coff
;;
*-apple)
os=-macos
;;
*-atari*)
os=-mint
;;
*)
os=-none
;;
esac
fi
# Here we handle the case where we know the os, and the CPU type, but not the
# manufacturer. We pick the logical manufacturer.
vendor=unknown
case $basic_machine in
*-unknown)
case $os in
-riscix*)
vendor=acorn
;;
-sunos*)
vendor=sun
;;
-cnk*|-aix*)
vendor=ibm
;;
-beos*)
vendor=be
;;
-hpux*)
vendor=hp
;;
-mpeix*)
vendor=hp
;;
-hiux*)
vendor=hitachi
;;
-unos*)
vendor=crds
;;
-dgux*)
vendor=dg
;;
-luna*)
vendor=omron
;;
-genix*)
vendor=ns
;;
-mvs* | -opened*)
vendor=ibm
;;
-os400*)
vendor=ibm
;;
-ptx*)
vendor=sequent
;;
-tpf*)
vendor=ibm
;;
-vxsim* | -vxworks* | -windiss*)
vendor=wrs
;;
-aux*)
vendor=apple
;;
-hms*)
vendor=hitachi
;;
-mpw* | -macos*)
vendor=apple
;;
-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
vendor=atari
;;
-vos*)
vendor=stratus
;;
esac
basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`
;;
esac
echo $basic_machine$os
exit
# Local variables:
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "timestamp='"
# time-stamp-format: "%:y-%02m-%02d"
# time-stamp-end: "'"
# End:
| {
"pile_set_name": "Github"
} |
// +build amd64
// errorcheck -0 -m
// Copyright 2018 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.
// Test that inlining of math/bits.RotateLeft* treats those calls as intrinsics.
package p
import "math/bits"
var (
x8 uint8
x16 uint16
x32 uint32
x64 uint64
x uint
)
func f() { // ERROR "can inline f"
x8 = bits.RotateLeft8(x8, 1)
x16 = bits.RotateLeft16(x16, 1)
x32 = bits.RotateLeft32(x32, 1)
x64 = bits.RotateLeft64(x64, 1)
x = bits.RotateLeft(x, 1)
}
| {
"pile_set_name": "Github"
} |
/*
* Chinese AVS video (AVS1-P2, JiZhun profile) decoder.
* Copyright (c) 2006 Stefan Gehrer <[email protected]>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_CAVS_H
#define AVCODEC_CAVS_H
#include "cavsdsp.h"
#include "blockdsp.h"
#include "h264chroma.h"
#include "idctdsp.h"
#include "get_bits.h"
#include "videodsp.h"
#define SLICE_MAX_START_CODE 0x000001af
#define EXT_START_CODE 0x000001b5
#define USER_START_CODE 0x000001b2
#define CAVS_START_CODE 0x000001b0
#define PIC_I_START_CODE 0x000001b3
#define PIC_PB_START_CODE 0x000001b6
#define A_AVAIL 1
#define B_AVAIL 2
#define C_AVAIL 4
#define D_AVAIL 8
#define NOT_AVAIL -1
#define REF_INTRA -2
#define REF_DIR -3
#define ESCAPE_CODE 59
#define FWD0 0x01
#define FWD1 0x02
#define BWD0 0x04
#define BWD1 0x08
#define SYM0 0x10
#define SYM1 0x20
#define SPLITH 0x40
#define SPLITV 0x80
#define MV_BWD_OFFS 12
#define MV_STRIDE 4
enum cavs_mb {
I_8X8 = 0,
P_SKIP,
P_16X16,
P_16X8,
P_8X16,
P_8X8,
B_SKIP,
B_DIRECT,
B_FWD_16X16,
B_BWD_16X16,
B_SYM_16X16,
B_8X8 = 29
};
enum cavs_sub_mb {
B_SUB_DIRECT,
B_SUB_FWD,
B_SUB_BWD,
B_SUB_SYM
};
enum cavs_intra_luma {
INTRA_L_VERT,
INTRA_L_HORIZ,
INTRA_L_LP,
INTRA_L_DOWN_LEFT,
INTRA_L_DOWN_RIGHT,
INTRA_L_LP_LEFT,
INTRA_L_LP_TOP,
INTRA_L_DC_128
};
enum cavs_intra_chroma {
INTRA_C_LP,
INTRA_C_HORIZ,
INTRA_C_VERT,
INTRA_C_PLANE,
INTRA_C_LP_LEFT,
INTRA_C_LP_TOP,
INTRA_C_DC_128,
};
enum cavs_mv_pred {
MV_PRED_MEDIAN,
MV_PRED_LEFT,
MV_PRED_TOP,
MV_PRED_TOPRIGHT,
MV_PRED_PSKIP,
MV_PRED_BSKIP
};
enum cavs_block {
BLK_16X16,
BLK_16X8,
BLK_8X16,
BLK_8X8
};
enum cavs_mv_loc {
MV_FWD_D3 = 0,
MV_FWD_B2,
MV_FWD_B3,
MV_FWD_C2,
MV_FWD_A1,
MV_FWD_X0,
MV_FWD_X1,
MV_FWD_A3 = 8,
MV_FWD_X2,
MV_FWD_X3,
MV_BWD_D3 = MV_BWD_OFFS,
MV_BWD_B2,
MV_BWD_B3,
MV_BWD_C2,
MV_BWD_A1,
MV_BWD_X0,
MV_BWD_X1,
MV_BWD_A3 = MV_BWD_OFFS+8,
MV_BWD_X2,
MV_BWD_X3
};
DECLARE_ALIGNED(8, typedef, struct) {
int16_t x;
int16_t y;
int16_t dist;
int16_t ref;
} cavs_vector;
struct dec_2dvlc {
int8_t rltab[59][3];
int8_t level_add[27];
int8_t golomb_order;
int inc_limit;
int8_t max_run;
};
typedef struct AVSFrame {
AVFrame *f;
int poc;
} AVSFrame;
typedef struct AVSContext {
AVCodecContext *avctx;
BlockDSPContext bdsp;
H264ChromaContext h264chroma;
IDCTDSPContext idsp;
VideoDSPContext vdsp;
CAVSDSPContext cdsp;
GetBitContext gb;
AVSFrame cur; ///< currently decoded frame
AVSFrame DPB[2]; ///< reference frames
int dist[2]; ///< temporal distances from current frame to ref frames
int low_delay;
int profile, level;
int aspect_ratio;
int mb_width, mb_height;
int width, height;
int stream_revision; ///<0 for samples from 2006, 1 for rm52j encoder
int progressive;
int pic_structure;
int skip_mode_flag; ///< select between skip_count or one skip_flag per MB
int loop_filter_disable;
int alpha_offset, beta_offset;
int ref_flag;
int mbx, mby, mbidx; ///< macroblock coordinates
int flags; ///< availability flags of neighbouring macroblocks
int stc; ///< last start code
uint8_t *cy, *cu, *cv; ///< current MB sample pointers
int left_qp;
uint8_t *top_qp;
/** mv motion vector cache
0: D3 B2 B3 C2
4: A1 X0 X1 -
8: A3 X2 X3 -
X are the vectors in the current macroblock (5,6,9,10)
A is the macroblock to the left (4,8)
B is the macroblock to the top (1,2)
C is the macroblock to the top-right (3)
D is the macroblock to the top-left (0)
the same is repeated for backward motion vectors */
cavs_vector mv[2*4*3];
cavs_vector *top_mv[2];
cavs_vector *col_mv;
/** luma pred mode cache
0: -- B2 B3
3: A1 X0 X1
6: A3 X2 X3 */
int pred_mode_Y[3*3];
int *top_pred_Y;
ptrdiff_t l_stride, c_stride;
int luma_scan[4];
int qp;
int qp_fixed;
int pic_qp_fixed;
int cbp;
ScanTable scantable;
/** intra prediction is done with un-deblocked samples
they are saved here before deblocking the MB */
uint8_t *top_border_y, *top_border_u, *top_border_v;
uint8_t left_border_y[26], left_border_u[10], left_border_v[10];
uint8_t intern_border_y[26];
uint8_t topleft_border_y, topleft_border_u, topleft_border_v;
void (*intra_pred_l[8])(uint8_t *d, uint8_t *top, uint8_t *left, ptrdiff_t stride);
void (*intra_pred_c[7])(uint8_t *d, uint8_t *top, uint8_t *left, ptrdiff_t stride);
uint8_t *col_type_base;
/* scaling factors for MV prediction */
int sym_factor; ///< for scaling in symmetrical B block
int direct_den[2]; ///< for scaling in direct B block
int scale_den[2]; ///< for scaling neighbouring MVs
uint8_t *edge_emu_buffer;
int got_keyframe;
int16_t *block;
} AVSContext;
extern const uint8_t ff_cavs_chroma_qp[64];
extern const uint8_t ff_cavs_partition_flags[30];
extern const cavs_vector ff_cavs_intra_mv;
extern const cavs_vector ff_cavs_dir_mv;
static inline void set_mvs(cavs_vector *mv, enum cavs_block size) {
switch(size) {
case BLK_16X16:
mv[MV_STRIDE ] = mv[0];
mv[MV_STRIDE+1] = mv[0];
case BLK_16X8:
mv[1] = mv[0];
break;
case BLK_8X16:
mv[MV_STRIDE] = mv[0];
break;
}
}
void ff_cavs_filter(AVSContext *h, enum cavs_mb mb_type);
void ff_cavs_load_intra_pred_luma(AVSContext *h, uint8_t *top, uint8_t **left,
int block);
void ff_cavs_load_intra_pred_chroma(AVSContext *h);
void ff_cavs_modify_mb_i(AVSContext *h, int *pred_mode_uv);
void ff_cavs_inter(AVSContext *h, enum cavs_mb mb_type);
void ff_cavs_mv(AVSContext *h, enum cavs_mv_loc nP, enum cavs_mv_loc nC,
enum cavs_mv_pred mode, enum cavs_block size, int ref);
void ff_cavs_init_mb(AVSContext *h);
int ff_cavs_next_mb(AVSContext *h);
int ff_cavs_init_pic(AVSContext *h);
int ff_cavs_init_top_lines(AVSContext *h);
int ff_cavs_init(AVCodecContext *avctx);
int ff_cavs_end (AVCodecContext *avctx);
#endif /* AVCODEC_CAVS_H */
| {
"pile_set_name": "Github"
} |
# Fun with WebGL 2.0 - 021 - Htc Vive Controller
**Description**:
Today we learn how to track Vive Controllers and check the state of all its buttons. We then create a simple gun with a shooting projectile and even create a sword. For extra fun we get an OBJ Mesh Model of the Vive controller to load up and use in our 3D canvas.
### Links
* [Lesson on Youtube](https://youtu.be/Px3kgAx3Sjg)
* [Youtube Series PlayList](https://www.youtube.com/playlist?list=PLMinhigDWz6emRKVkVIEAaePW7vtIkaIF)
### Reference Links
* [Chromium Beta with WebVR Support](https://webvr.rocks/chromium)
* [WebVR Documentation](https://w3c.github.io/webvr/)
* [WebVR Samples](https://webvr.info/samples/)
* [AFrame's Vive Controller OBJ File](https://aframe.io/docs/0.5.0/components/vive-controls.html)
| {
"pile_set_name": "Github"
} |
libgee is a collection library providing GObject-based interfaces and classes
for commonly used data structures.
libgee provides the following interfaces:
* Iterable
o Collection
+ List
+ Set
* Iterator
* Map
The ArrayList, HashSet, and HashMap classes provide a reasonable sample
implementation of the List, Set, and Map interfaces. ReadOnlyCollection,
ReadOnlyList, ReadOnlySet, and ReadOnlyMap are read-only wrapper classes that
prevent modification of the underlying collection.
libgee is written in Vala and can be used like any GObject-based C library.
It's planned to provide bindings for further languages.
| {
"pile_set_name": "Github"
} |
// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2013 Alec Jacobson <[email protected]>
//
// 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/.
#ifndef IGL_VIEWPORT_H
#define IGL_VIEWPORT_H
namespace igl
{
// Simple Viewport class for an opengl context. Handles reshaping and mouse.
struct Viewport
{
int x,y,width,height;
// Constructors
Viewport(
const int x=0,
const int y=0,
const int width=0,
const int height=0):
x(x),
y(y),
width(width),
height(height)
{
};
virtual ~Viewport(){}
void reshape(
const int x,
const int y,
const int width,
const int height)
{
this->x = x;
this->y = y;
this->width = width;
this->height = height;
};
// Given mouse_x,mouse_y on the entire window return mouse_x, mouse_y in
// this viewport.
//
// Inputs:
// my mouse y-coordinate
// wh window height
// Returns y-coordinate in viewport
int mouse_y(const int my,const int wh)
{
return my - (wh - height - y);
}
// Inputs:
// mx mouse x-coordinate
// Returns x-coordinate in viewport
int mouse_x(const int mx)
{
return mx - x;
}
// Returns whether point (mx,my) is in extend of Viewport
bool inside(const int mx, const int my) const
{
return
mx >= x && my >= y &&
mx < x+width && my < y+height;
}
};
}
#endif
| {
"pile_set_name": "Github"
} |
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
package com.cloud.utils.xmlobject;
import org.junit.Test;
public class TestXmlObject {
void p(String str) {
System.out.println(str);
}
@Test
public void test() {
// deprecated, since we no longer use component.xml.in any more
/*
XmlObject xo = XmlObjectParser.parseFromFile("z:/components.xml.in");
p(xo.getTag());
p((String) xo.get("system-integrity-checker.checker").toString());
List<XmlObject> lst = xo.get("management-server.adapters");
for (XmlObject x : lst) {
List<XmlObject> lst1 = x.getAsList("adapter");
for (XmlObject y : lst1) {
p(y.toString());
}
}
*/
XmlObject xml = new XmlObject("vlan").putElement("vlan-id", String.valueOf(19)).putElement("tagged",
new XmlObject("teng").putElement("name", "0/0")
).putElement("shutdown", "false");
System.out.println(xml.toString());
}
}
| {
"pile_set_name": "Github"
} |
function inArray(arr) {
return x => arr.includes(x);
}
function inBetween(a, b) {
return x => (x >= a && x <= b);
} | {
"pile_set_name": "Github"
} |
import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Observable } from 'rxjs';
import { configureTestSuite } from './../../util-test/util-expect.spec';
import { PoTagBaseComponent } from './po-tag-base.component';
import { PoTagComponent } from './po-tag.component';
import { PoTagIcon } from './enums/po-tag-icon.enum';
import { PoTagOrientation } from './enums/po-tag-orientation.enum';
import { PoTagType } from './enums/po-tag-type.enum';
@Component({
template: ` <po-tag p-label="Mock" (p-click)="onClick()"></po-tag> `
})
class PoTagClickableComponent {
onClick() {}
}
describe('PoTagComponent:', () => {
const fakeEvent = { preventDefault: () => {}, stopPropagation: () => {} };
let component: PoTagComponent;
let fixture: ComponentFixture<PoTagComponent>;
let fixtureClickable: ComponentFixture<PoTagClickableComponent>;
let nativeElement: any;
configureTestSuite(() => {
TestBed.configureTestingModule({
declarations: [PoTagComponent, PoTagClickableComponent]
});
});
beforeEach(() => {
fixture = TestBed.createComponent(PoTagComponent);
component = fixture.componentInstance;
fixtureClickable = TestBed.createComponent(PoTagClickableComponent);
nativeElement = fixture.debugElement.nativeElement;
});
it('should be created.', () => {
expect(component instanceof PoTagBaseComponent).toBeTruthy();
expect(component instanceof PoTagComponent).toBeTruthy();
});
describe('Methods:', () => {
it('ngOnInit: should set `isClickable` with `true` if `p-click` @Output is wire up', () => {
component.click.observers.push(<any>[new Observable()]);
component.ngOnInit();
expect(component.isClickable).toBe(true);
});
it('ngOnInit: should set `isClickable` with `false` if `p-click` @Output isn`t wire up', () => {
component.click.observers.length = 0;
component.ngOnInit();
expect(component.isClickable).toBe(false);
});
it('iconFromType: should update property with valid values', () => {
component.type = PoTagType.Danger;
expect(component.iconFromType).toBe(PoTagIcon.Danger);
component.type = PoTagType.Info;
expect(component.iconFromType).toBe(PoTagIcon.Info);
component.type = PoTagType.Success;
expect(component.iconFromType).toBe(PoTagIcon.Success);
component.type = PoTagType.Warning;
expect(component.iconFromType).toBe(PoTagIcon.Warning);
});
it('iconTypeString: should return `true` if is string value.', () => {
component.icon = 'po-icon-news';
expect(component.iconTypeString).toBe(true);
});
it('iconTypeString: should return `false` if isn`t string value.', () => {
component.icon = false;
expect(component.iconTypeString).toBe(false);
});
it('tagColor: should return tag type without `inverse`.', () => {
component.type = PoTagType.Danger;
component.inverse = false;
expect(component.tagColor).toBe('po-tag-danger');
});
it('tagColor: should return tag type with `inverse`.', () => {
component.type = PoTagType.Danger;
component.inverse = true;
expect(component.tagColor).toBe('po-tag-danger-inverse');
});
it('tagColor: should return tag color without `text`.', () => {
component.color = 'color-07';
component.type = undefined;
component.inverse = false;
expect(component.tagColor).toBe('po-color-07');
});
it('tagColor: should return tag color with `text`.', () => {
component.color = 'color-07';
component.type = undefined;
component.inverse = true;
expect(component.tagColor).toBe('po-text-color-07');
});
it('tagColor: should return tag type default without `inverse`.', () => {
component.color = undefined;
component.type = undefined;
component.inverse = false;
expect(component.tagColor).toBe('po-tag-info');
});
it('tagColor: should return tag type default with `inverse`.', () => {
component.color = undefined;
component.type = undefined;
component.inverse = true;
expect(component.tagColor).toBe('po-tag-info-inverse');
});
it('tagOrientation: should return true if orientation is horizontal.', () => {
component.orientation = PoTagOrientation.Horizontal;
expect(component.tagOrientation).toBe(true);
});
it('tagOrientation: should return false if orientation isn`t horizontal.', () => {
component.orientation = PoTagOrientation.Vertical;
expect(component.tagOrientation).toBe(false);
});
it('onClick: click should emit submittedTagItem value', () => {
component.value = 'value';
component.type = PoTagType.Danger;
spyOn(component.click, <any>'emit');
component.onClick();
expect(component.click.emit).toHaveBeenCalledWith({ 'value': component.value, 'type': component.type });
});
it('onKeyPressed: should call `onClick` if the event `keydown` is used with `enter` key.', () => {
fixture.detectChanges();
const tagElement = fixture.debugElement.query(By.css('.po-tag'));
const spyOnClick = spyOn(component, 'onClick');
tagElement.triggerEventHandler('keydown.enter', fakeEvent);
expect(spyOnClick).toHaveBeenCalled();
});
it('onKeyPressed: shouldn`t call `onClick` if the event `keyup` is used with other key than `enter`.', () => {
fixture.detectChanges();
const tagElement = fixture.debugElement.query(By.css('.po-tag'));
const spyOnClick = spyOn(component, 'onClick');
tagElement.triggerEventHandler('keydown.space', fakeEvent);
expect(spyOnClick).not.toHaveBeenCalled();
});
it('onKeyPressed: should call `onClick` if the event `keyup` is used with `space` key.', () => {
fixture.detectChanges();
const tagElement = fixture.debugElement.query(By.css('.po-tag'));
const spyOnClick = spyOn(component, 'onClick');
tagElement.triggerEventHandler('keyup.space', fakeEvent);
expect(spyOnClick).toHaveBeenCalled();
});
it('onKeyPressed: shouldn`t call `onClick` if the event `keyup` is used with other key than `space`.', () => {
fixture.detectChanges();
const tagElement = fixture.debugElement.query(By.css('.po-tag'));
const spyOnClick = spyOn(component, 'onClick');
tagElement.triggerEventHandler('keyup.enter', fakeEvent);
expect(spyOnClick).not.toHaveBeenCalled();
});
});
describe('Templates:', () => {
it('should only start with default classes, shouldn`t have variations.', () => {
const value = 'Po Tag';
component.value = value;
fixture.detectChanges();
expect(nativeElement.querySelector('.po-tag-container')).toBeTruthy();
expect(nativeElement.querySelector('.po-tag')).toBeTruthy();
expect(nativeElement.querySelector('.po-tag-value').innerHTML).toContain(value);
expect(nativeElement.querySelector('.po-icon')).toBeFalsy();
expect(nativeElement.querySelector('.po-tag-title')).toBeFalsy();
expect(nativeElement.querySelector('.po-tag-label')).toBeFalsy();
});
it('should add `po-tag-container-horizontal` class if orientation is `PoTagOrientation.Horizontal`.', () => {
component.orientation = PoTagOrientation.Horizontal;
fixture.detectChanges();
expect(nativeElement.querySelector('.po-tag-container-horizontal')).toBeTruthy();
});
it('shouldn`t add `po-tag-container-horizontal` class if orientation is `PoTagOrientation.Vertical`.', () => {
component.orientation = PoTagOrientation.Vertical;
fixture.detectChanges();
expect(nativeElement.querySelector('.po-tag-container-horizontal')).toBeFalsy();
});
it('should show `po-tag-label` and `po-tag-title` classes if has label.', () => {
const label = 'Label';
component.label = label;
fixture.detectChanges();
expect(nativeElement.querySelector('.po-tag-title')).toBeTruthy();
expect(nativeElement.querySelector('.po-tag-label').innerHTML).toContain(label);
});
it('should add `:` to `po-tag-label` if orientation is PoTagOrientation.Horizontal.', () => {
const label = 'Label';
component.label = label;
component.orientation = PoTagOrientation.Horizontal;
fixture.detectChanges();
expect(nativeElement.querySelector('.po-tag-label').innerHTML).toContain(':');
});
it('shouldn`t add `:` to `po-tag-label` if orientation is PoTagOrientation.Vertical.', () => {
const label = 'Label';
component.label = label;
component.orientation = PoTagOrientation.Vertical;
fixture.detectChanges();
expect(nativeElement.querySelector('.po-tag-label').innerHTML).not.toContain(':');
});
it('should add `po-tag-info` as default.', () => {
fixture.detectChanges();
expect(nativeElement.querySelector('.po-tag-info')).toBeTruthy();
});
it('should add `po-tag-danger` if type is `PoTagType.Danger`.', () => {
component.type = PoTagType.Danger;
fixture.detectChanges();
expect(nativeElement.querySelector('.po-tag-danger')).toBeTruthy();
});
it('should add `po-tag-info` class if type is `PoTagType.Info`.', () => {
component.type = PoTagType.Info;
fixture.detectChanges();
expect(nativeElement.querySelector('.po-tag-info')).toBeTruthy();
});
it('should add `po-tag-success` class if type is `PoTagType.Success`.', () => {
component.type = PoTagType.Success;
fixture.detectChanges();
expect(nativeElement.querySelector('.po-tag-success')).toBeTruthy();
});
it('should add `po-tag-warning` class if type is `PoTagType.Warning`.', () => {
component.type = PoTagType.Warning;
fixture.detectChanges();
expect(nativeElement.querySelector('.po-tag-warning')).toBeTruthy();
});
it('should add `PoTagIcon.Danger` if type is `PoTagType.Danger and `icon` is true`.', () => {
component.type = PoTagType.Danger;
component.icon = true;
fixture.detectChanges();
expect(nativeElement.querySelector(`.${PoTagIcon.Danger}`)).toBeTruthy();
});
it('should add `PoTagIcon.Info` if type is `PoTagType.Info and `icon` is true`.', () => {
component.type = PoTagType.Info;
component.icon = true;
fixture.detectChanges();
expect(nativeElement.querySelector(`.${PoTagIcon.Info}`)).toBeTruthy();
});
it('should add `PoTagIcon.Success` if type is `PoTagType.Success and `icon` is true`.', () => {
component.type = PoTagType.Success;
component.icon = true;
fixture.detectChanges();
expect(nativeElement.querySelector(`.${PoTagIcon.Success}`)).toBeTruthy();
});
it('should add `PoTagIcon.Warning` if type is `PoTagType.Warning and `icon` is true`.', () => {
component.type = PoTagType.Warning;
component.icon = true;
fixture.detectChanges();
expect(nativeElement.querySelector(`.${PoTagIcon.Warning}`)).toBeTruthy();
});
it('should add `po-clickable` if `p-click` @Output is wire up`.', () => {
fixtureClickable.detectChanges();
expect(fixtureClickable.debugElement.nativeElement.querySelector('.po-clickable')).toBeTruthy();
});
it('shouldn`t add `po-clickable` if `p-click` @Output isn`t wire up`.', () => {
component.isClickable = false;
fixture.detectChanges();
expect(nativeElement.querySelector('.po-clickable')).toBeFalsy();
});
it('should add `po-tag-inverse` if `inverse` is true.', () => {
component.inverse = true;
fixture.detectChanges();
expect(nativeElement.querySelector('.po-tag-inverse')).toBeTruthy();
});
it('shouldn`t add `po-tag-inverse` if `inverse` is false.', () => {
component.inverse = false;
fixture.detectChanges();
expect(nativeElement.querySelector('.po-tag-inverse')).toBeFalsy();
});
});
});
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you 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 ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<kryo.version>2.24.0</kryo.version>
</properties>
<name>samoa-flink</name>
<description>Flink engine for SAMOA</description>
<artifactId>samoa-flink</artifactId>
<parent>
<groupId>org.apache.samoa</groupId>
<artifactId>samoa</artifactId>
<version>0.5.0-incubating-SNAPSHOT</version>
</parent>
<repositories>
<repository>
<id>apache.snapshots</id>
<name>Apache Development Snapshot Repository</name>
<url>https://repository.apache.org/content/repositories/snapshots/</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.apache.samoa</groupId>
<artifactId>samoa-api</artifactId>
<version>${project.version}</version>
<exclusions>
<exclusion>
<groupId>com.esotericsoftware.kryo</groupId>
<artifactId>kryo</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j-log4j12.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-streaming-java</artifactId>
<version>${flink.version}</version>
<!--<scope>provided</scope>-->
</dependency>
<dependency>
<groupId>com.esotericsoftware.kryo</groupId>
<artifactId>kryo</artifactId>
<version>${kryo.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Flink assembly -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>${maven-assembly-plugin.version}</version>
<configuration>
<finalName>SAMOA-Flink-${project.version}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<attach>false</attach>
<outputDirectory>../target</outputDirectory>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifestEntries>
<!--<Bundle-Version>${parsedVersion.osgiVersion}</Bundle-Version>-->
<Bundle-Description>${project.description}</Bundle-Description>
<Implementation-Version>${project.version}</Implementation-Version>
<Implementation-Vendor>Yahoo Labs</Implementation-Vendor>
<Implementation-Vendor-Id>SAMOA</Implementation-Vendor-Id>
</manifestEntries>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>org.apache.samoa.flink.FlinkDoTask</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id> <!-- this is used for inheritance merges -->
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<argLine>-Xmx1G</argLine>
<redirectTestOutputToFile>false</redirectTestOutputToFile>
</configuration>
</plugin>
</plugins>
</build>
</project>
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2009--2015 Red Hat ; see COPYRIGHT for license
*/
#ifndef _LD_LOG_H_
#define _LD_LOG_H_
#include <isc/error.h>
#include <dns/log.h>
#include <dns/result.h>
#define fatal_error(...) isc_error_fatal(__FILE__, __LINE__, __VA_ARGS__)
#define log_error_r(fmt, ...) \
log_error(fmt ": %s", ##__VA_ARGS__, dns_result_totext(result))
#define log_error(format, ...) log_write(ISC_LOG_ERROR, format, ##__VA_ARGS__)
#define log_info(format, ...) log_write(ISC_LOG_INFO, format, ##__VA_ARGS__)
void
log_write(int level, const char *format, ...) ISC_FORMAT_PRINTF(2, 3);
#endif /* !_LD_LOG_H_ */
| {
"pile_set_name": "Github"
} |
package authentication
import (
"fmt"
"log"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/hashicorp/go-multierror"
)
type managedServiceIdentityAuth struct {
msiEndpoint string
clientID string
}
func (a managedServiceIdentityAuth) build(b Builder) (authMethod, error) {
msiEndpoint := b.MsiEndpoint
if msiEndpoint == "" {
ep, err := adal.GetMSIVMEndpoint()
if err != nil {
return nil, fmt.Errorf("Error determining MSI Endpoint: ensure the VM has MSI enabled, or configure the MSI Endpoint. Error: %s", err)
}
msiEndpoint = ep
}
log.Printf("[DEBUG] Using MSI msiEndpoint %q", msiEndpoint)
auth := managedServiceIdentityAuth{
msiEndpoint: msiEndpoint,
clientID: b.ClientID,
}
return auth, nil
}
func (a managedServiceIdentityAuth) isApplicable(b Builder) bool {
return b.SupportsManagedServiceIdentity
}
func (a managedServiceIdentityAuth) name() string {
return "Managed Service Identity"
}
func (a managedServiceIdentityAuth) getAuthorizationToken(sender autorest.Sender, oauth *OAuthConfig, endpoint string) (autorest.Authorizer, error) {
log.Printf("[DEBUG] getAuthorizationToken with MSI msiEndpoint %q, ClientID %q for msiEndpoint %q", a.msiEndpoint, a.clientID, endpoint)
if oauth.OAuth == nil {
return nil, fmt.Errorf("Error getting Authorization Token for MSI auth: an OAuth token wasn't configured correctly; please file a bug with more details")
}
var spt *adal.ServicePrincipalToken
var err error
if a.clientID == "" {
spt, err = adal.NewServicePrincipalTokenFromMSI(a.msiEndpoint, endpoint)
if err != nil {
return nil, err
}
} else {
spt, err = adal.NewServicePrincipalTokenFromMSIWithUserAssignedID(a.msiEndpoint, endpoint, a.clientID)
if err != nil {
return nil, fmt.Errorf("failed to get an oauth token from MSI for user assigned identity from MSI endpoint %q with client ID %q for endpoint %q: %v", a.msiEndpoint, a.clientID, endpoint, err)
}
}
spt.SetSender(sender)
auth := autorest.NewBearerAuthorizer(spt)
return auth, nil
}
func (a managedServiceIdentityAuth) populateConfig(c *Config) error {
// nothing to populate back
return nil
}
func (a managedServiceIdentityAuth) validate() error {
var err *multierror.Error
if a.msiEndpoint == "" {
err = multierror.Append(err, fmt.Errorf("An MSI Endpoint must be configured"))
}
return err.ErrorOrNil()
}
| {
"pile_set_name": "Github"
} |
architecture: arm
battery: {removable: False, capacity: 2390, tech: 'Li-Ion'}
bluetooth: {spec: '4.0'}
cameras:
- {flash: '', info: '5 MP'}
- {flash: '', info: 'VGA'}
codename: surnia
cpu: Cortex-A53
cpu_cores: '4'
cpu_freq: 1.2 GHz
current_branch: 17.1
download_boot: With the device powered off, hold <kbd>Volume Down</kbd> + <kbd>Power</kbd>.
On the next screen use <kbd>Volume Down</kbd> to scroll and then press <kbd>Volume Up</kbd> to select.
gpu: Adreno 306
image: otus.png
install_method: fastboot_motorola
kernel: android_kernel_motorola_msm8916
maintainers: [althafvly, theimpulson]
models: [XT1514, XT1521, XT1523, XT1524, XT1526, XT1527]
name: Moto E 2015 LTE
peripherals: [Accelerometer, Proximity sensor]
ram: 1 GB
recovery_boot: With the device powered off, hold <kbd>Volume Down</kbd> + <kbd>Power</kbd>.
On the next screen use <kbd>Volume Down</kbd> to scroll to recovery and then press <kbd>Volume Up</kbd> to select.
release: 2015-02
screen: 114 mm (4.5 in)
screen_ppi: ~245
screen_res: 540 x 960 pixels
screen_tech: IPS LCD
sdcard: up to 32 GB
soc: Qualcomm MSM8916 Snapdragon 410
storage: 8 GB
tree: android_device_motorola_surnia
type: phone
vendor: Motorola
vendor_short: motorola
versions: [14.1, 17.1]
wifi: Wi-Fi 802.11 b/g/n
| {
"pile_set_name": "Github"
} |
//
// SealedMemberInSealedClassIssue.cs
//
// Author:
// Mike Krüger <[email protected]>
//
// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
//
// 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, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using ICSharpCode.NRefactory.PatternMatching;
using System.Collections.Generic;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.Refactoring;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription("Sealed member in sealed class",
Description = "'sealed' modifier is redundant in sealed classes",
Category = IssueCategories.RedundanciesInDeclarations,
Severity = Severity.Warning,
AnalysisDisableKeyword = "SealedMemberInSealedClass")]
public class SealedMemberInSealedClassIssue : GatherVisitorCodeIssueProvider
{
protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context)
{
return new GatherVisitor(context);
}
class GatherVisitor : GatherVisitorBase<SealedMemberInSealedClassIssue>
{
public GatherVisitor (BaseRefactoringContext ctx) : base (ctx)
{
}
void CheckNode(EntityDeclaration node)
{
if (!node.HasModifier(Modifiers.Override))
return;
var type = node.Parent as TypeDeclaration;
if (type == null || !type.HasModifier(Modifiers.Sealed))
return;
foreach (var token_ in node.ModifierTokens) {
var token = token_;
if (token.Modifier == Modifiers.Sealed) {
AddIssue(new CodeIssue(
token,
ctx.TranslateString("Keyword 'sealed' is redundant in sealed classes."),
ctx.TranslateString("Remove redundant 'sealed' modifier"),
script => script.ChangeModifier(node, node.Modifiers & ~Modifiers.Sealed)
) { IssueMarker = IssueMarker.GrayOut });
}
}
}
public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
{
base.VisitMethodDeclaration(methodDeclaration);
CheckNode(methodDeclaration);
}
public override void VisitFieldDeclaration(FieldDeclaration fieldDeclaration)
{
base.VisitFieldDeclaration(fieldDeclaration);
CheckNode(fieldDeclaration);
}
public override void VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration)
{
base.VisitPropertyDeclaration(propertyDeclaration);
CheckNode(propertyDeclaration);
}
public override void VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration)
{
base.VisitIndexerDeclaration(indexerDeclaration);
CheckNode(indexerDeclaration);
}
public override void VisitEventDeclaration(EventDeclaration eventDeclaration)
{
base.VisitEventDeclaration(eventDeclaration);
CheckNode(eventDeclaration);
}
public override void VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration)
{
base.VisitCustomEventDeclaration(eventDeclaration);
CheckNode(eventDeclaration);
}
public override void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
{
base.VisitConstructorDeclaration(constructorDeclaration);
CheckNode(constructorDeclaration);
}
public override void VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration)
{
base.VisitOperatorDeclaration(operatorDeclaration);
CheckNode(operatorDeclaration);
}
public override void VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration)
{
base.VisitFixedFieldDeclaration(fixedFieldDeclaration);
CheckNode(fixedFieldDeclaration);
}
public override void VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration)
{
// SKIP
}
public override void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
{
if (typeDeclaration.Parent is TypeDeclaration) {
CheckNode(typeDeclaration);
}
base.VisitTypeDeclaration(typeDeclaration);
}
}
}
}
| {
"pile_set_name": "Github"
} |
#
# @copyright@
# Copyright (c) 2006 - 2019 Teradata
# All rights reserved. Stacki(r) v5.x stacki.com
# https://github.com/Teradata/stacki/blob/master/LICENSE.txt
# @copyright@
#
import stack.commands
class Implementation(stack.commands.Implementation):
def run(self, args):
(switch, hosts) = args
list_switch_mac = self.owner.call('list.switch.mac', [ switch ])
for h in self.owner.call('list.host.interface', hosts):
if h['interface'] == 'ipmi':
continue
for m in list_switch_mac:
if h['host'] == m['host'] and h['interface'] == m['interface']:
params = [ switch, 'host=%s' % h['host'],
'interface=%s' % m['interface'],
'port=%s' % m['port'] ]
self.owner.call('add.switch.host', params)
break
| {
"pile_set_name": "Github"
} |
class RemoveSkillFieldsFromMentor < ActiveRecord::Migration
def up
remove_column :mentors, :first_skill
remove_column :mentors, :first_skill_expertise
remove_column :mentors, :second_skill
remove_column :mentors, :second_skill_expertise
remove_column :mentors, :third_skill
remove_column :mentors, :third_skill_expertise
end
def down
add_column :mentors, :first_skill, :string
add_column :mentors, :first_skill_expertise, :string
add_column :mentors, :second_skill, :string
add_column :mentors, :second_skill_expertise, :string
add_column :mentors, :third_skill, :string
add_column :mentors, :third_skill_expertise, :string
end
end
| {
"pile_set_name": "Github"
} |
#import <Quick/Quick.h>
#import <Nimble/Nimble.h>
#import <OCMock/OCMock.h>
#import "SDLDynamicMenuUpdateRunScore.h"
QuickSpecBegin(SDLMenuRunScoreSpec)
describe(@"menuRunScore", ^{
__block SDLDynamicMenuUpdateRunScore *runScore = nil;
beforeEach(^{
NSArray<NSNumber *> *oldMenuStatus = @[@1, @2, @3];
NSArray<NSNumber *> *updatedMenuStatus = @[@3, @2, @1];
NSUInteger numberOfAdds = 5;
runScore = [[SDLDynamicMenuUpdateRunScore alloc] initWithOldStatus:oldMenuStatus updatedStatus:updatedMenuStatus score:numberOfAdds];
});
it(@"should instantiate correctly", ^{
expect(runScore.oldStatus).to(equal(@[@1, @2, @3]));
expect(runScore.updatedStatus).to(equal(@[@3, @2, @1]));
expect(runScore.score).to(equal(5));
});
});
QuickSpecEnd
| {
"pile_set_name": "Github"
} |
/* */
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.stratos.cloud.controller.statistics.publisher;
import org.apache.stratos.common.statistics.publisher.ThriftStatisticsPublisher;
import org.wso2.carbon.databridge.commons.StreamDefinition;
/**
* Member Status Publisher Interface.
*/
public abstract class MemberStatusPublisher extends ThriftStatisticsPublisher {
public MemberStatusPublisher(StreamDefinition streamDefinition, String thriftClientName) {
super(streamDefinition, thriftClientName);
}
/**
* Publishing member status.
*
* @param timestamp Status changed time
* @param applicationId Application Id
* @param clusterId Cluster Id
* @param clusterAlias Cluster Alias
* @param clusterInstanceId Cluster Instance Id
* @param serviceName Service Name
* @param networkPartitionId Network Partition Id
* @param partitionId Partition Id
* @param memberId Member Id
* @param status Member Status
*/
public abstract void publish(Long timestamp, String applicationId, String clusterId,
String clusterAlias, String clusterInstanceId, String serviceName,
String networkPartitionId, String partitionId, String memberId, String status);
}
| {
"pile_set_name": "Github"
} |
{
"bundles": {
"Wandi\\MailerBundle\\WandiMailerBundle": ["all"]
},
"copy-from-recipe": {
"config/": "%CONFIG_DIR%/"
},
"env": {
"WANDI_MAILER_SENDER_NAME": "Example",
"WANDI_MAILER_SENDER_ADDRESS": "[email protected]"
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://www.netbeans.org/ns/project/1">
<type>com.microchip.mplab.nbide.embedded.makeproject</type>
<configuration>
<data xmlns="http://www.netbeans.org/ns/make-project/1">
<name>zlib</name>
<creation-uuid>8eef651d-e634-46ae-9183-39443c98e390</creation-uuid>
<make-project-type>0</make-project-type>
<c-extensions>c</c-extensions>
<cpp-extensions/>
<header-extensions/>
<sourceEncoding>ISO-8859-1</sourceEncoding>
<make-dep-projects/>
</data>
</configuration>
</project>
| {
"pile_set_name": "Github"
} |
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_SPHERE_MINKOWSKI_H
#define BT_SPHERE_MINKOWSKI_H
#include "btConvexInternalShape.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types
///The btSphereShape implements an implicit sphere, centered around a local origin with radius.
ATTRIBUTE_ALIGNED16(class) btSphereShape : public btConvexInternalShape
{
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btSphereShape (btScalar radius) : btConvexInternalShape ()
{
m_shapeType = SPHERE_SHAPE_PROXYTYPE;
m_implicitShapeDimensions.setX(radius);
m_collisionMargin = radius;
}
virtual btVector3 localGetSupportingVertex(const btVector3& vec)const;
virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const;
//notice that the vectors should be unit length
virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const;
virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const;
virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const;
btScalar getRadius() const { return m_implicitShapeDimensions.getX() * m_localScaling.getX();}
void setUnscaledRadius(btScalar radius)
{
m_implicitShapeDimensions.setX(radius);
btConvexInternalShape::setMargin(radius);
}
//debugging
virtual const char* getName()const {return "SPHERE";}
virtual void setMargin(btScalar margin)
{
btConvexInternalShape::setMargin(margin);
}
virtual btScalar getMargin() const
{
//to improve gjk behaviour, use radius+margin as the full margin, so never get into the penetration case
//this means, non-uniform scaling is not supported anymore
return getRadius();
}
};
#endif //BT_SPHERE_MINKOWSKI_H
| {
"pile_set_name": "Github"
} |
/**
* Radio Button Inputs
* --------------------------------------------------
*/
.item-radio {
padding: 0;
&:hover {
cursor: pointer;
}
}
.item-radio .item-content {
/* give some room to the right for the checkmark icon */
padding-right: $item-padding * 4;
}
.item-radio .radio-icon {
/* checkmark icon will be hidden by default */
position: absolute;
top: 0;
right: 0;
z-index: $z-index-item-radio;
visibility: hidden;
padding: $item-padding - 2;
height: 100%;
font-size: 24px;
}
.item-radio input {
/* hide any radio button inputs elements (the ugly circles) */
position: absolute;
left: -9999px;
&:checked + .radio-content .item-content {
/* style the item content when its checked */
background: #f7f7f7;
}
&:checked + .radio-content .radio-icon {
/* show the checkmark icon when its checked */
visibility: visible;
}
}
| {
"pile_set_name": "Github"
} |
<===> no_todo/input.scss
p {
color: #ff8000;
}
<===> no_todo/output.css
input: ["--precision", "10", "-t", "expanded", "input.scss"]
file: p {
color: #ff8000;
}
<===>
=============================================================
<===> todo/options.yml
---
:todo:
- sass/sass#0000
<===> todo/input.scss
p {
color: #ff8000;
}
<===> todo/output.css
input: ["--precision", "10", "-t", "expanded", "input.scss"]
file: p {
color: #ff8000;
}
| {
"pile_set_name": "Github"
} |
if not 'X86' in config.root.targets:
config.unsupported = True
| {
"pile_set_name": "Github"
} |
///////////////////////////////////////////////////////////////////////////////
// Name: wx/private/fdiohandler.h
// Purpose: declares wxFDIOHandler class
// Author: Vadim Zeitlin
// Created: 2009-08-17
// Copyright: (c) 2009 Vadim Zeitlin <[email protected]>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifndef _WX_PRIVATE_FDIOHANDLER_H_
#define _WX_PRIVATE_FDIOHANDLER_H_
// ----------------------------------------------------------------------------
// wxFDIOHandler: interface used to process events on file descriptors
// ----------------------------------------------------------------------------
class wxFDIOHandler
{
public:
wxFDIOHandler() { m_regmask = 0; }
// called when descriptor is available for non-blocking read
virtual void OnReadWaiting() = 0;
// called when descriptor is available for non-blocking write
virtual void OnWriteWaiting() = 0;
// called when there is exception on descriptor
virtual void OnExceptionWaiting() = 0;
// called to check if the handler is still valid, only used by
// wxSocketImplUnix currently
virtual bool IsOk() const { return true; }
// get/set the mask of events for which we're currently registered for:
// it's a combination of wxFDIO_{INPUT,OUTPUT,EXCEPTION}
int GetRegisteredEvents() const { return m_regmask; }
void SetRegisteredEvent(int flag) { m_regmask |= flag; }
void ClearRegisteredEvent(int flag) { m_regmask &= ~flag; }
// virtual dtor for the base class
virtual ~wxFDIOHandler() { }
private:
int m_regmask;
wxDECLARE_NO_COPY_CLASS(wxFDIOHandler);
};
#endif // _WX_PRIVATE_FDIOHANDLER_H_
| {
"pile_set_name": "Github"
} |
package soot.jimple.toolkits.thread.mhp.stmt;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.SootMethod;
import soot.Unit;
import soot.toolkits.graph.UnitGraph;
// *** USE AT YOUR OWN RISK ***
// May Happen in Parallel (MHP) analysis by Lin Li.
// This code should be treated as beta-quality code.
// It was written in 2003, but not incorporated into Soot until 2006.
// As such, it may contain incorrect assumptions about the usage
// of certain Soot classes.
// Some portions of this MHP analysis have been quality-checked, and are
// now used by the Transactions toolkit.
//
// -Richard L. Halpert, 2006-11-30
public class NotifyStmt extends JPegStmt
{
public NotifyStmt(String obj, String ca, Unit un, UnitGraph ug, SootMethod sm) {
this.object = obj;
this.name = "notify";
this.caller = ca;
this.unit = un;
this.unitGraph = ug;
this.sootMethod = sm;
}
}
| {
"pile_set_name": "Github"
} |
#! /usr/bin/env python
# Copyright 2016, 2017 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Validate phonology.json files.
Reads phonology.json file and validates the phoneme inventory.
"""
import io
import json
import sys
STDERR = io.open(2, mode='wt', encoding='utf-8', closefd=False)
def main(argv):
with io.open(argv[1], mode='rt', encoding='utf-8') as reader:
contents = reader.read()
phonology = json.loads(contents)
feature_types = {}
features = {}
is_valid = True
for feature in phonology['features']:
features.update({feature[0]: feature[1:]})
for feat_type in phonology['feature_types']:
for feat in feat_type[1:]:
if not features.get(feat):
STDERR.write('Feature %s not in %s\n' % (feat, str(features)))
is_valid = False
feature_types.update({feat_type[0]: feat_type[1:]})
for phone in phonology['phones']:
feature_list = feature_types.get(phone[1])
phoneme = phone[0]
expected_feature_list = len(feature_list) + 2
if len(phone) != len(feature_list) + 2:
STDERR.write(
'Phoneme %s does not match its feature types, expected features %s\n'
% (phoneme, expected_feature_list))
is_valid = False
for x in range(2, len(phone)):
feature_type = feature_list[x - 2]
feature_options = features.get(feature_type)
if phone[x] not in feature_options:
STDERR.write(
'Phoneme "%s" given feature "%s" value "%s" not found in list %s\n'
% (phoneme, feature_type, phone[x], str(feature_options)))
is_valid = False
sys.exit(0 if is_valid else 1)
return
if __name__ == '__main__':
main(sys.argv)
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Using the JSON dumped by the dump-dependency-json generator,
generate input suitable for graphviz to render a dependency graph of
targets."""
from __future__ import print_function
import collections
import json
import sys
def ParseTarget(target):
target, _, suffix = target.partition('#')
filename, _, target = target.partition(':')
return filename, target, suffix
def LoadEdges(filename, targets):
"""Load the edges map from the dump file, and filter it to only
show targets in |targets| and their depedendents."""
file = open('dump.json')
edges = json.load(file)
file.close()
# Copy out only the edges we're interested in from the full edge list.
target_edges = {}
to_visit = targets[:]
while to_visit:
src = to_visit.pop()
if src in target_edges:
continue
target_edges[src] = edges[src]
to_visit.extend(edges[src])
return target_edges
def WriteGraph(edges):
"""Print a graphviz graph to stdout.
|edges| is a map of target to a list of other targets it depends on."""
# Bucket targets by file.
files = collections.defaultdict(list)
for src, dst in edges.items():
build_file, target_name, toolset = ParseTarget(src)
files[build_file].append(src)
print('digraph D {')
print(' fontsize=8') # Used by subgraphs.
print(' node [fontsize=8]')
# Output nodes by file. We must first write out each node within
# its file grouping before writing out any edges that may refer
# to those nodes.
for filename, targets in files.items():
if len(targets) == 1:
# If there's only one node for this file, simplify
# the display by making it a box without an internal node.
target = targets[0]
build_file, target_name, toolset = ParseTarget(target)
print(' "%s" [shape=box, label="%s\\n%s"]' % (target, filename,
target_name))
else:
# Group multiple nodes together in a subgraph.
print(' subgraph "cluster_%s" {' % filename)
print(' label = "%s"' % filename)
for target in targets:
build_file, target_name, toolset = ParseTarget(target)
print(' "%s" [label="%s"]' % (target, target_name))
print(' }')
# Now that we've placed all the nodes within subgraphs, output all
# the edges between nodes.
for src, dsts in edges.items():
for dst in dsts:
print(' "%s" -> "%s"' % (src, dst))
print('}')
def main():
if len(sys.argv) < 2:
print(__doc__, file=sys.stderr)
print(file=sys.stderr)
print('usage: %s target1 target2...' % (sys.argv[0]), file=sys.stderr)
return 1
edges = LoadEdges('dump.json', sys.argv[1:])
WriteGraph(edges)
return 0
if __name__ == '__main__':
sys.exit(main())
| {
"pile_set_name": "Github"
} |
/*
* 练习7.42:对于你在练习7.40(参见7.5.1节,第261页)中编写的类,确定哪些构造
* 函数可以使用委托。如果可以的话,编写委托构造函数。如果不可以,从抽象概念列表
* 中重新选择一个你认为可以使用委托构造函数的,为挑选出的这个概念编写类定义。
*/
/*
* 比如选择Book
*/
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::cin;
class Book
{
public:
Book(unsigned no, const std::string &name, const std::string &auther, const std::string &pubdate) : m_no(no), m_name(name), m_auther(auther), m_pubdate(pubdate) {}
Book() : Book(0, "", "", "") {}
Book(std::istream &is) : Book() { is >> m_no >> m_name >> m_auther >> m_pubdate; }
void print() { std::cout << m_no << " " << m_name << " " << m_auther << " " << m_pubdate << std::endl; }
operator bool() const { return m_no != 0; }
private:
unsigned m_no = 0;
std::string m_name;
std::string m_auther;
std::string m_pubdate;
};
int main()
{
Book b1; // 默认构造函数,使用类内初始值初始化成员
b1.print();
Book b2(1, "c--primer", "someone", "2017.11.8"); // 需要使用一个构造函数来初始化所有成员
b2.print();
Book b3(std::cin); // 需要使用一个构造函数从标准输入读入数据来初始化类对象
b3.print();
if (!b3)
{
cout << "b3 is invalid" << endl;
}
return 0;
}
| {
"pile_set_name": "Github"
} |
/**
* A specialized version of `_.sum` for arrays without support for callback
* shorthands and `this` binding..
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the sum.
*/
function arraySum(array, iteratee) {
var length = array.length,
result = 0;
while (length--) {
result += +iteratee(array[length]) || 0;
}
return result;
}
module.exports = arraySum;
| {
"pile_set_name": "Github"
} |
package org.zstack.network.l3;
import org.zstack.core.db.Q;
import org.zstack.core.db.SQL;
import org.zstack.header.network.l3.*;
import org.zstack.utils.network.IPv6Constants;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class IpRangeHelper {
public static List<IpRangeInventory> getNormalIpRanges(L3NetworkInventory l3inv) {
if (l3inv.getIpRanges().isEmpty()) {
return new ArrayList<>();
}
List<String> uuids = l3inv.getIpRanges().stream().map(IpRangeInventory::getUuid).collect(Collectors.toList());
return NormalIpRangeInventory.valueOf1(Q.New(NormalIpRangeVO.class).in(NormalIpRangeVO_.uuid, uuids).list());
}
public static List<IpRangeInventory> getNormalIpRanges(L3NetworkInventory l3inv, int ipVersion) {
if (l3inv.getIpRanges().isEmpty()) {
return new ArrayList<>();
}
List<String> uuids = l3inv.getIpRanges().stream().filter(ipr -> ipr.getIpVersion() == ipVersion).map(IpRangeInventory::getUuid).collect(Collectors.toList());
if (uuids.isEmpty()) {
return new ArrayList<>();
}
return NormalIpRangeInventory.valueOf1(Q.New(NormalIpRangeVO.class).in(NormalIpRangeVO_.uuid, uuids).list());
}
public static List<IpRangeInventory> getNormalIpRanges(L3NetworkVO vo) {
if (vo.getIpRanges().isEmpty()) {
return new ArrayList<>();
}
List<String> uuids = vo.getIpRanges().stream().map(IpRangeVO::getUuid).collect(Collectors.toList());
return NormalIpRangeInventory.valueOf1(Q.New(NormalIpRangeVO.class).in(NormalIpRangeVO_.uuid, uuids).list());
}
public static List<IpRangeInventory> getNormalIpRanges(L3NetworkVO vo, int ipVersion) {
if (vo.getIpRanges().isEmpty()) {
return new ArrayList<>();
}
List<String> uuids = vo.getIpRanges().stream().filter(ipr -> ipr.getIpVersion() == ipVersion).map(IpRangeVO::getUuid).collect(Collectors.toList());
if (uuids.isEmpty()) {
return new ArrayList<>();
}
return NormalIpRangeInventory.valueOf1(Q.New(NormalIpRangeVO.class).in(NormalIpRangeVO_.uuid, uuids).list());
}
public static List<IpRangeInventory> getAddressPools(L3NetworkInventory l3inv) {
if (l3inv.getIpRanges().isEmpty()) {
return new ArrayList<>();
}
List<String> uuids = l3inv.getIpRanges().stream().map(IpRangeInventory::getUuid).collect(Collectors.toList());
return AddressPoolInventory.valueOf1(Q.New(AddressPoolVO.class).in(NormalIpRangeVO_.uuid, uuids).list());
}
public static List<IpRangeInventory> getAddressPools(L3NetworkVO vo) {
if (vo.getIpRanges().isEmpty()) {
return new ArrayList<>();
}
List<String> uuids = vo.getIpRanges().stream().map(IpRangeVO::getUuid).collect(Collectors.toList());
return AddressPoolInventory.valueOf1(Q.New(AddressPoolVO.class).in(NormalIpRangeVO_.uuid, uuids).list());
}
public static void updateL3NetworkIpversion(IpRangeVO ipr) {
updateL3NetworkIpversion(IpRangeInventory.valueOf(ipr));
}
public static void updateL3NetworkIpversion(IpRangeInventory ipr) {
L3NetworkVO l3VO = Q.New(L3NetworkVO.class).eq(L3NetworkVO_.uuid, ipr.getL3NetworkUuid()).find();
boolean ipv4 = false;
boolean ipv6 = false;
for (IpRangeVO vo : l3VO.getIpRanges()) {
if (vo.getIpVersion() == IPv6Constants.IPv4) {
ipv4 = true;
} else if (vo.getIpVersion() == IPv6Constants.IPv6) {
ipv6 = true;
}
}
Integer ipVersion = IPv6Constants.NONE;
if (ipv4 && ipv6) {
ipVersion = IPv6Constants.DUAL_STACK;
} else if (ipv4) {
ipVersion = IPv6Constants.IPv4;
} else if (ipv6) {
ipVersion = IPv6Constants.IPv6;
}
if (l3VO.getIpVersion() != ipVersion) {
SQL.New(L3NetworkVO.class).set(L3NetworkVO_.ipVersion, ipVersion).eq(L3NetworkVO_.uuid, l3VO.getUuid()).update();
}
}
}
| {
"pile_set_name": "Github"
} |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.15.11
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from kubernetes_asyncio.client.configuration import Configuration
class V1NetworkPolicySpec(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_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.
"""
openapi_types = {
'egress': 'list[V1NetworkPolicyEgressRule]',
'ingress': 'list[V1NetworkPolicyIngressRule]',
'pod_selector': 'V1LabelSelector',
'policy_types': 'list[str]'
}
attribute_map = {
'egress': 'egress',
'ingress': 'ingress',
'pod_selector': 'podSelector',
'policy_types': 'policyTypes'
}
def __init__(self, egress=None, ingress=None, pod_selector=None, policy_types=None, local_vars_configuration=None): # noqa: E501
"""V1NetworkPolicySpec - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._egress = None
self._ingress = None
self._pod_selector = None
self._policy_types = None
self.discriminator = None
if egress is not None:
self.egress = egress
if ingress is not None:
self.ingress = ingress
self.pod_selector = pod_selector
if policy_types is not None:
self.policy_types = policy_types
@property
def egress(self):
"""Gets the egress of this V1NetworkPolicySpec. # noqa: E501
List of egress rules to be applied to the selected pods. Outgoing traffic is allowed if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic matches at least one egress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy limits all outgoing traffic (and serves solely to ensure that the pods it selects are isolated by default). This field is beta-level in 1.8 # noqa: E501
:return: The egress of this V1NetworkPolicySpec. # noqa: E501
:rtype: list[V1NetworkPolicyEgressRule]
"""
return self._egress
@egress.setter
def egress(self, egress):
"""Sets the egress of this V1NetworkPolicySpec.
List of egress rules to be applied to the selected pods. Outgoing traffic is allowed if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic matches at least one egress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy limits all outgoing traffic (and serves solely to ensure that the pods it selects are isolated by default). This field is beta-level in 1.8 # noqa: E501
:param egress: The egress of this V1NetworkPolicySpec. # noqa: E501
:type: list[V1NetworkPolicyEgressRule]
"""
self._egress = egress
@property
def ingress(self):
"""Gets the ingress of this V1NetworkPolicySpec. # noqa: E501
List of ingress rules to be applied to the selected pods. Traffic is allowed to a pod if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic source is the pod's local node, OR if the traffic matches at least one ingress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy does not allow any traffic (and serves solely to ensure that the pods it selects are isolated by default) # noqa: E501
:return: The ingress of this V1NetworkPolicySpec. # noqa: E501
:rtype: list[V1NetworkPolicyIngressRule]
"""
return self._ingress
@ingress.setter
def ingress(self, ingress):
"""Sets the ingress of this V1NetworkPolicySpec.
List of ingress rules to be applied to the selected pods. Traffic is allowed to a pod if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic source is the pod's local node, OR if the traffic matches at least one ingress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy does not allow any traffic (and serves solely to ensure that the pods it selects are isolated by default) # noqa: E501
:param ingress: The ingress of this V1NetworkPolicySpec. # noqa: E501
:type: list[V1NetworkPolicyIngressRule]
"""
self._ingress = ingress
@property
def pod_selector(self):
"""Gets the pod_selector of this V1NetworkPolicySpec. # noqa: E501
:return: The pod_selector of this V1NetworkPolicySpec. # noqa: E501
:rtype: V1LabelSelector
"""
return self._pod_selector
@pod_selector.setter
def pod_selector(self, pod_selector):
"""Sets the pod_selector of this V1NetworkPolicySpec.
:param pod_selector: The pod_selector of this V1NetworkPolicySpec. # noqa: E501
:type: V1LabelSelector
"""
if self.local_vars_configuration.client_side_validation and pod_selector is None: # noqa: E501
raise ValueError("Invalid value for `pod_selector`, must not be `None`") # noqa: E501
self._pod_selector = pod_selector
@property
def policy_types(self):
"""Gets the policy_types of this V1NetworkPolicySpec. # noqa: E501
List of rule types that the NetworkPolicy relates to. Valid options are \"Ingress\", \"Egress\", or \"Ingress,Egress\". If this field is not specified, it will default based on the existence of Ingress or Egress rules; policies that contain an Egress section are assumed to affect Egress, and all policies (whether or not they contain an Ingress section) are assumed to affect Ingress. If you want to write an egress-only policy, you must explicitly specify policyTypes [ \"Egress\" ]. Likewise, if you want to write a policy that specifies that no egress is allowed, you must specify a policyTypes value that include \"Egress\" (since such a policy would not include an Egress section and would otherwise default to just [ \"Ingress\" ]). This field is beta-level in 1.8 # noqa: E501
:return: The policy_types of this V1NetworkPolicySpec. # noqa: E501
:rtype: list[str]
"""
return self._policy_types
@policy_types.setter
def policy_types(self, policy_types):
"""Sets the policy_types of this V1NetworkPolicySpec.
List of rule types that the NetworkPolicy relates to. Valid options are \"Ingress\", \"Egress\", or \"Ingress,Egress\". If this field is not specified, it will default based on the existence of Ingress or Egress rules; policies that contain an Egress section are assumed to affect Egress, and all policies (whether or not they contain an Ingress section) are assumed to affect Ingress. If you want to write an egress-only policy, you must explicitly specify policyTypes [ \"Egress\" ]. Likewise, if you want to write a policy that specifies that no egress is allowed, you must specify a policyTypes value that include \"Egress\" (since such a policy would not include an Egress section and would otherwise default to just [ \"Ingress\" ]). This field is beta-level in 1.8 # noqa: E501
:param policy_types: The policy_types of this V1NetworkPolicySpec. # noqa: E501
:type: list[str]
"""
self._policy_types = policy_types
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1NetworkPolicySpec):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1NetworkPolicySpec):
return True
return self.to_dict() != other.to_dict()
| {
"pile_set_name": "Github"
} |
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'list', 'bs', {
bulletedlist: 'Lista',
numberedlist: 'Numerisana lista'
} );
| {
"pile_set_name": "Github"
} |
/*
* Driver for GE FPGA based GPIO
*
* Author: Martyn Welch <[email protected]>
*
* 2008 (c) GE Intelligent Platforms Embedded Systems, Inc.
*
* This file is licensed under the terms of the GNU General Public License
* version 2. This program is licensed "as is" without any warranty of any
* kind, whether express or implied.
*/
/* TODO
*
* Configuration of output modes (totem-pole/open-drain)
* Interrupt configuration - interrupts are always generated the FPGA relies on
* the I/O interrupt controllers mask to stop them propergating
*/
#include <linux/kernel.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/of_device.h>
#include <linux/of_gpio.h>
#include <linux/of_address.h>
#include <linux/module.h>
#include <linux/gpio/driver.h>
#define GEF_GPIO_DIRECT 0x00
#define GEF_GPIO_IN 0x04
#define GEF_GPIO_OUT 0x08
#define GEF_GPIO_TRIG 0x0C
#define GEF_GPIO_POLAR_A 0x10
#define GEF_GPIO_POLAR_B 0x14
#define GEF_GPIO_INT_STAT 0x18
#define GEF_GPIO_OVERRUN 0x1C
#define GEF_GPIO_MODE 0x20
static const struct of_device_id gef_gpio_ids[] = {
{
.compatible = "gef,sbc610-gpio",
.data = (void *)19,
}, {
.compatible = "gef,sbc310-gpio",
.data = (void *)6,
}, {
.compatible = "ge,imp3a-gpio",
.data = (void *)16,
},
{ }
};
MODULE_DEVICE_TABLE(of, gef_gpio_ids);
static int __init gef_gpio_probe(struct platform_device *pdev)
{
const struct of_device_id *of_id =
of_match_device(gef_gpio_ids, &pdev->dev);
struct gpio_chip *gc;
void __iomem *regs;
int ret;
gc = devm_kzalloc(&pdev->dev, sizeof(*gc), GFP_KERNEL);
if (!gc)
return -ENOMEM;
regs = of_iomap(pdev->dev.of_node, 0);
if (!regs)
return -ENOMEM;
ret = bgpio_init(gc, &pdev->dev, 4, regs + GEF_GPIO_IN,
regs + GEF_GPIO_OUT, NULL, NULL,
regs + GEF_GPIO_DIRECT, BGPIOF_BIG_ENDIAN_BYTE_ORDER);
if (ret) {
dev_err(&pdev->dev, "bgpio_init failed\n");
goto err0;
}
/* Setup pointers to chip functions */
gc->label = devm_kstrdup(&pdev->dev, pdev->dev.of_node->full_name,
GFP_KERNEL);
if (!gc->label) {
ret = -ENOMEM;
goto err0;
}
gc->base = -1;
gc->ngpio = (u16)(uintptr_t)of_id->data;
gc->of_gpio_n_cells = 2;
gc->of_node = pdev->dev.of_node;
/* This function adds a memory mapped GPIO chip */
ret = devm_gpiochip_add_data(&pdev->dev, gc, NULL);
if (ret)
goto err0;
return 0;
err0:
iounmap(regs);
pr_err("%s: GPIO chip registration failed\n",
pdev->dev.of_node->full_name);
return ret;
};
static struct platform_driver gef_gpio_driver = {
.driver = {
.name = "gef-gpio",
.of_match_table = gef_gpio_ids,
},
};
module_platform_driver_probe(gef_gpio_driver, gef_gpio_probe);
MODULE_DESCRIPTION("GE I/O FPGA GPIO driver");
MODULE_AUTHOR("Martyn Welch <[email protected]");
MODULE_LICENSE("GPL");
| {
"pile_set_name": "Github"
} |
var Configuration = require('./configuration');
function wrap(result) {
if (Configuration.autoPromiseWrap &&
(result === undefined || typeof result.then != 'function')) {
return Promise.resolve(result);
}
return result;
}
var utility = {
autoWrapInitializationResult: (result) => {
return wrap(result);
},
autoWrapRulesResult: (result) => {
if (Configuration.autoPromiseWrap) {
if (Array.isArray(result)) {
result = Promise.resolve(result);
}
if (result === undefined) {
result = Promise.resolve([]);
}
if (typeof result.then != 'function') {
result = Promise.resolve(result);
}
}
return result;
},
autoWrapValidationCompleteResult: (result) => {
return wrap(result);
},
autoWrapValidationResult: (result) => {
return wrap(result);
},
autoWrapRuleValidationCompleteResult: (result) => {
return wrap(result);
},
};
module.exports = utility;
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
"""
werkzeug._internal
~~~~~~~~~~~~~~~~~~
This module provides internally used helpers and constants.
:copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import re
import string
import inspect
from weakref import WeakKeyDictionary
from datetime import datetime, date
from itertools import chain
from werkzeug._compat import iter_bytes, text_type, BytesIO, int_to_byte, \
range_type, integer_types
_logger = None
_empty_stream = BytesIO()
_signature_cache = WeakKeyDictionary()
_epoch_ord = date(1970, 1, 1).toordinal()
_cookie_params = set((b'expires', b'path', b'comment',
b'max-age', b'secure', b'httponly',
b'version'))
_legal_cookie_chars = (string.ascii_letters +
string.digits +
u"/=!#$%&'*+-.^_`|~:").encode('ascii')
_cookie_quoting_map = {
b',': b'\\054',
b';': b'\\073',
b'"': b'\\"',
b'\\': b'\\\\',
}
for _i in chain(range_type(32), range_type(127, 256)):
_cookie_quoting_map[int_to_byte(_i)] = ('\\%03o' % _i).encode('latin1')
_octal_re = re.compile(br'\\[0-3][0-7][0-7]')
_quote_re = re.compile(br'[\\].')
_legal_cookie_chars_re = br'[\w\d!#%&\'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=]'
_cookie_re = re.compile(br"""
(?P<key>[^=;]+)
(?:\s*=\s*
(?P<val>
"(?:[^\\"]|\\.)*" |
(?:.*?)
)
)?
\s*;
""", flags=re.VERBOSE)
class _Missing(object):
def __repr__(self):
return 'no value'
def __reduce__(self):
return '_missing'
_missing = _Missing()
def _get_environ(obj):
env = getattr(obj, 'environ', obj)
assert isinstance(env, dict), \
'%r is not a WSGI environment (has to be a dict)' % type(obj).__name__
return env
def _log(type, message, *args, **kwargs):
"""Log into the internal werkzeug logger."""
global _logger
if _logger is None:
import logging
_logger = logging.getLogger('werkzeug')
# Only set up a default log handler if the
# end-user application didn't set anything up.
if not logging.root.handlers and _logger.level == logging.NOTSET:
_logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
_logger.addHandler(handler)
getattr(_logger, type)(message.rstrip(), *args, **kwargs)
def _parse_signature(func):
"""Return a signature object for the function."""
if hasattr(func, 'im_func'):
func = func.im_func
# if we have a cached validator for this function, return it
parse = _signature_cache.get(func)
if parse is not None:
return parse
# inspect the function signature and collect all the information
if hasattr(inspect, 'getfullargspec'):
tup = inspect.getfullargspec(func)
else:
tup = inspect.getargspec(func)
positional, vararg_var, kwarg_var, defaults = tup[:4]
defaults = defaults or ()
arg_count = len(positional)
arguments = []
for idx, name in enumerate(positional):
if isinstance(name, list):
raise TypeError('cannot parse functions that unpack tuples '
'in the function signature')
try:
default = defaults[idx - arg_count]
except IndexError:
param = (name, False, None)
else:
param = (name, True, default)
arguments.append(param)
arguments = tuple(arguments)
def parse(args, kwargs):
new_args = []
missing = []
extra = {}
# consume as many arguments as positional as possible
for idx, (name, has_default, default) in enumerate(arguments):
try:
new_args.append(args[idx])
except IndexError:
try:
new_args.append(kwargs.pop(name))
except KeyError:
if has_default:
new_args.append(default)
else:
missing.append(name)
else:
if name in kwargs:
extra[name] = kwargs.pop(name)
# handle extra arguments
extra_positional = args[arg_count:]
if vararg_var is not None:
new_args.extend(extra_positional)
extra_positional = ()
if kwargs and kwarg_var is None:
extra.update(kwargs)
kwargs = {}
return new_args, kwargs, missing, extra, extra_positional, \
arguments, vararg_var, kwarg_var
_signature_cache[func] = parse
return parse
def _date_to_unix(arg):
"""Converts a timetuple, integer or datetime object into the seconds from
epoch in utc.
"""
if isinstance(arg, datetime):
arg = arg.utctimetuple()
elif isinstance(arg, integer_types + (float,)):
return int(arg)
year, month, day, hour, minute, second = arg[:6]
days = date(year, month, 1).toordinal() - _epoch_ord + day - 1
hours = days * 24 + hour
minutes = hours * 60 + minute
seconds = minutes * 60 + second
return seconds
class _DictAccessorProperty(object):
"""Baseclass for `environ_property` and `header_property`."""
read_only = False
def __init__(self, name, default=None, load_func=None, dump_func=None,
read_only=None, doc=None):
self.name = name
self.default = default
self.load_func = load_func
self.dump_func = dump_func
if read_only is not None:
self.read_only = read_only
self.__doc__ = doc
def __get__(self, obj, type=None):
if obj is None:
return self
storage = self.lookup(obj)
if self.name not in storage:
return self.default
rv = storage[self.name]
if self.load_func is not None:
try:
rv = self.load_func(rv)
except (ValueError, TypeError):
rv = self.default
return rv
def __set__(self, obj, value):
if self.read_only:
raise AttributeError('read only property')
if self.dump_func is not None:
value = self.dump_func(value)
self.lookup(obj)[self.name] = value
def __delete__(self, obj):
if self.read_only:
raise AttributeError('read only property')
self.lookup(obj).pop(self.name, None)
def __repr__(self):
return '<%s %s>' % (
self.__class__.__name__,
self.name
)
def _cookie_quote(b):
buf = bytearray()
all_legal = True
_lookup = _cookie_quoting_map.get
_push = buf.extend
for char in iter_bytes(b):
if char not in _legal_cookie_chars:
all_legal = False
char = _lookup(char, char)
_push(char)
if all_legal:
return bytes(buf)
return bytes(b'"' + buf + b'"')
def _cookie_unquote(b):
if len(b) < 2:
return b
if b[:1] != b'"' or b[-1:] != b'"':
return b
b = b[1:-1]
i = 0
n = len(b)
rv = bytearray()
_push = rv.extend
while 0 <= i < n:
o_match = _octal_re.search(b, i)
q_match = _quote_re.search(b, i)
if not o_match and not q_match:
rv.extend(b[i:])
break
j = k = -1
if o_match:
j = o_match.start(0)
if q_match:
k = q_match.start(0)
if q_match and (not o_match or k < j):
_push(b[i:k])
_push(b[k + 1:k + 2])
i = k + 2
else:
_push(b[i:j])
rv.append(int(b[j + 1:j + 4], 8))
i = j + 4
return bytes(rv)
def _cookie_parse_impl(b):
"""Lowlevel cookie parsing facility that operates on bytes."""
i = 0
n = len(b)
while i < n:
match = _cookie_re.search(b + b';', i)
if not match:
break
key = match.group('key').strip()
value = match.group('val') or b''
i = match.end(0)
# Ignore parameters. We have no interest in them.
if key.lower() not in _cookie_params:
yield _cookie_unquote(key), _cookie_unquote(value)
def _encode_idna(domain):
# If we're given bytes, make sure they fit into ASCII
if not isinstance(domain, text_type):
domain.decode('ascii')
return domain
# Otherwise check if it's already ascii, then return
try:
return domain.encode('ascii')
except UnicodeError:
pass
# Otherwise encode each part separately
parts = domain.split('.')
for idx, part in enumerate(parts):
parts[idx] = part.encode('idna')
return b'.'.join(parts)
def _decode_idna(domain):
# If the input is a string try to encode it to ascii to
# do the idna decoding. if that fails because of an
# unicode error, then we already have a decoded idna domain
if isinstance(domain, text_type):
try:
domain = domain.encode('ascii')
except UnicodeError:
return domain
# Decode each part separately. If a part fails, try to
# decode it with ascii and silently ignore errors. This makes
# most sense because the idna codec does not have error handling
parts = domain.split(b'.')
for idx, part in enumerate(parts):
try:
parts[idx] = part.decode('idna')
except UnicodeError:
parts[idx] = part.decode('ascii', 'ignore')
return '.'.join(parts)
def _make_cookie_domain(domain):
if domain is None:
return None
domain = _encode_idna(domain)
if b':' in domain:
domain = domain.split(b':', 1)[0]
if b'.' in domain:
return domain
raise ValueError(
'Setting \'domain\' for a cookie on a server running locally (ex: '
'localhost) is not supported by complying browsers. You should '
'have something like: \'127.0.0.1 localhost dev.localhost\' on '
'your hosts file and then point your server to run on '
'\'dev.localhost\' and also set \'domain\' for \'dev.localhost\''
)
def _easteregg(app=None):
"""Like the name says. But who knows how it works?"""
def bzzzzzzz(gyver):
import base64
import zlib
return zlib.decompress(base64.b64decode(gyver)).decode('ascii')
gyver = u'\n'.join([x + (77 - len(x)) * u' ' for x in bzzzzzzz(b'''
eJyFlzuOJDkMRP06xRjymKgDJCDQStBYT8BCgK4gTwfQ2fcFs2a2FzvZk+hvlcRvRJD148efHt9m
9Xz94dRY5hGt1nrYcXx7us9qlcP9HHNh28rz8dZj+q4rynVFFPdlY4zH873NKCexrDM6zxxRymzz
4QIxzK4bth1PV7+uHn6WXZ5C4ka/+prFzx3zWLMHAVZb8RRUxtFXI5DTQ2n3Hi2sNI+HK43AOWSY
jmEzE4naFp58PdzhPMdslLVWHTGUVpSxImw+pS/D+JhzLfdS1j7PzUMxij+mc2U0I9zcbZ/HcZxc
q1QjvvcThMYFnp93agEx392ZdLJWXbi/Ca4Oivl4h/Y1ErEqP+lrg7Xa4qnUKu5UE9UUA4xeqLJ5
jWlPKJvR2yhRI7xFPdzPuc6adXu6ovwXwRPXXnZHxlPtkSkqWHilsOrGrvcVWXgGP3daXomCj317
8P2UOw/NnA0OOikZyFf3zZ76eN9QXNwYdD8f8/LdBRFg0BO3bB+Pe/+G8er8tDJv83XTkj7WeMBJ
v/rnAfdO51d6sFglfi8U7zbnr0u9tyJHhFZNXYfH8Iafv2Oa+DT6l8u9UYlajV/hcEgk1x8E8L/r
XJXl2SK+GJCxtnyhVKv6GFCEB1OO3f9YWAIEbwcRWv/6RPpsEzOkXURMN37J0PoCSYeBnJQd9Giu
LxYQJNlYPSo/iTQwgaihbART7Fcyem2tTSCcwNCs85MOOpJtXhXDe0E7zgZJkcxWTar/zEjdIVCk
iXy87FW6j5aGZhttDBoAZ3vnmlkx4q4mMmCdLtnHkBXFMCReqthSGkQ+MDXLLCpXwBs0t+sIhsDI
tjBB8MwqYQpLygZ56rRHHpw+OAVyGgaGRHWy2QfXez+ZQQTTBkmRXdV/A9LwH6XGZpEAZU8rs4pE
1R4FQ3Uwt8RKEtRc0/CrANUoes3EzM6WYcFyskGZ6UTHJWenBDS7h163Eo2bpzqxNE9aVgEM2CqI
GAJe9Yra4P5qKmta27VjzYdR04Vc7KHeY4vs61C0nbywFmcSXYjzBHdiEjraS7PGG2jHHTpJUMxN
Jlxr3pUuFvlBWLJGE3GcA1/1xxLcHmlO+LAXbhrXah1tD6Ze+uqFGdZa5FM+3eHcKNaEarutAQ0A
QMAZHV+ve6LxAwWnXbbSXEG2DmCX5ijeLCKj5lhVFBrMm+ryOttCAeFpUdZyQLAQkA06RLs56rzG
8MID55vqr/g64Qr/wqwlE0TVxgoiZhHrbY2h1iuuyUVg1nlkpDrQ7Vm1xIkI5XRKLedN9EjzVchu
jQhXcVkjVdgP2O99QShpdvXWoSwkp5uMwyjt3jiWCqWGSiaaPAzohjPanXVLbM3x0dNskJsaCEyz
DTKIs+7WKJD4ZcJGfMhLFBf6hlbnNkLEePF8Cx2o2kwmYF4+MzAxa6i+6xIQkswOqGO+3x9NaZX8
MrZRaFZpLeVTYI9F/djY6DDVVs340nZGmwrDqTCiiqD5luj3OzwpmQCiQhdRYowUYEA3i1WWGwL4
GCtSoO4XbIPFeKGU13XPkDf5IdimLpAvi2kVDVQbzOOa4KAXMFlpi/hV8F6IDe0Y2reg3PuNKT3i
RYhZqtkQZqSB2Qm0SGtjAw7RDwaM1roESC8HWiPxkoOy0lLTRFG39kvbLZbU9gFKFRvixDZBJmpi
Xyq3RE5lW00EJjaqwp/v3EByMSpVZYsEIJ4APaHmVtpGSieV5CALOtNUAzTBiw81GLgC0quyzf6c
NlWknzJeCsJ5fup2R4d8CYGN77mu5vnO1UqbfElZ9E6cR6zbHjgsr9ly18fXjZoPeDjPuzlWbFwS
pdvPkhntFvkc13qb9094LL5NrA3NIq3r9eNnop9DizWOqCEbyRBFJTHn6Tt3CG1o8a4HevYh0XiJ
sR0AVVHuGuMOIfbuQ/OKBkGRC6NJ4u7sbPX8bG/n5sNIOQ6/Y/BX3IwRlTSabtZpYLB85lYtkkgm
p1qXK3Du2mnr5INXmT/78KI12n11EFBkJHHp0wJyLe9MvPNUGYsf+170maayRoy2lURGHAIapSpQ
krEDuNoJCHNlZYhKpvw4mspVWxqo415n8cD62N9+EfHrAvqQnINStetek7RY2Urv8nxsnGaZfRr/
nhXbJ6m/yl1LzYqscDZA9QHLNbdaSTTr+kFg3bC0iYbX/eQy0Bv3h4B50/SGYzKAXkCeOLI3bcAt
mj2Z/FM1vQWgDynsRwNvrWnJHlespkrp8+vO1jNaibm+PhqXPPv30YwDZ6jApe3wUjFQobghvW9p
7f2zLkGNv8b191cD/3vs9Q833z8t''').splitlines()])
def easteregged(environ, start_response):
def injecting_start_response(status, headers, exc_info=None):
headers.append(('X-Powered-By', 'Werkzeug'))
return start_response(status, headers, exc_info)
if app is not None and environ.get('QUERY_STRING') != 'macgybarchakku':
return app(environ, injecting_start_response)
injecting_start_response('200 OK', [('Content-Type', 'text/html')])
return [(u'''
<!DOCTYPE html>
<html>
<head>
<title>About Werkzeug</title>
<style type="text/css">
body { font: 15px Georgia, serif; text-align: center; }
a { color: #333; text-decoration: none; }
h1 { font-size: 30px; margin: 20px 0 10px 0; }
p { margin: 0 0 30px 0; }
pre { font: 11px 'Consolas', 'Monaco', monospace; line-height: 0.95; }
</style>
</head>
<body>
<h1><a href="http://werkzeug.pocoo.org/">Werkzeug</a></h1>
<p>the Swiss Army knife of Python web development.</p>
<pre>%s\n\n\n</pre>
</body>
</html>''' % gyver).encode('latin1')]
return easteregged
| {
"pile_set_name": "Github"
} |
FROM golang:1.13-alpine
RUN apk add -U python py-pip python-dev musl-dev gcc git bash
RUN pip install pre-commit
COPY --from=golangci/golangci-lint:v1.24.0 /usr/bin/golangci-lint /usr/bin/golangci-lint
WORKDIR /go/src/github.com/dnephin/dobi
COPY .pre-commit-config.yaml ./
RUN git init && pre-commit install-hooks
ENV CGO_ENABLED=0
CMD ["pre-commit", "run", "-a", "-v"]
| {
"pile_set_name": "Github"
} |
## Docker pipelines to prepare other callers output for Ensemble mode
NeuSomatic can be used universally as a stand-alone somatic mutation detection method or with an ensemble of existing methods. In the ensemble mode NeuSomatic currently supports outputs from MuTect2, MuSE, Strelka2, SomaticSniper, VarDict, and VarScan2. For ensemble mode, the ensembled outputs of different somatic callers (as a single `.tsv` file) should be prepared and inputed using `--ensemble_tsv` argument in `preprocess.py`.
The following steps use docker pipelines to prepare the ensemble `.tsv` file.
This is an adaptation of SomaticSeq's [scripts](https://github.com/bioinform/somaticseq/tree/master/utilities/dockered_pipelines).
### Requirements
* Have internet connection and docker daemon. Be able to pull and run docker images from Docker Hub.
* **Highly recommended**: Have cluster management system with valid `qsub` command, such as Sun Grid Engine.
### 1. Prepare run scripts
To run the individual somatic callers (MuTect2, MuSE, Strelka2, SomaticSniper, VarDict, and VarScan2), you can use the following command that create 10 (if we set `splits` to 10) equal-size regions in 10 bed files, and parallelize the jobs into 10 regions.
```
prepare_callers_scripts.sh \
--normal-bam /ABSOLUTE/PATH/TO/normal_sample.bam \
--tumor-bam /ABSOLUTE/PATH/TO/tumor_sample.bam \
--human-reference /ABSOLUTE/PATH/TO/ref.fa \
--output-dir /ABSOLUTE/PATH/TO/output \
--dbsnp /ABSOLUTE/PATH/TO/dbSNP.vcf \
--splits 10 \
--selector /ABSOLUTE/PATH/TO/region.bed \
--mutect2 --somaticsniper --vardict --varscan2 --muse --strelka --wrapper
```
**NOTE:** If you want to use Singulariy instead of Docker, please use `--singularity` argument.
This command will create sub-folders with the following sctructure for the split regions:
```
output
├── genome.bed
├── 1
├── 2
├── .
├── .
├── .
├── i # i'th folder
│ ├── i.bed # i'th sub-region
│ ├── logs
│ │ ├── strelka.cmd # Strelka2 run script for region i.bed
│ │ ├── muse.cmd # MuSE run script for region i.bed
│ │ ├── mutect2.cmd # MuTect2 run script for region i.bed
│ │ ├── vardict.cmd # VarDict run script for region i.bed
│ │ └── varscan2.cm # VarScan2 run script for region i.bed
│ └── Wrapper
│ └── logs
│ └── wrapper.cmd # Wrapper script to combine results
├── .
├── .
├── .
├── 10
└── logs
└── somaticsniper.cmd # SomaticSniper run script for whole region genome.bed
```
### 2. Run all individual callers scripts
You should first run all individual callers `.cmd` run scripts for all regions. For instance with `qsub` command:
```
for tool in strelka muse mutect2 vardict varscan2
do
for i in {1..10}
do
for script in output/${i}/logs/${tool}.cmd
do
qsub $script
done
done
done
qsub output/logs/somaticsniper.cmd
```
### 3. Combine individual callers outputs
Once all these scripts finished successfully, the respective VCF files for each tool will be available under each region sub-folder.
Then, you can run wrapper.cmd scripts to combine calls made by each caller:
```
for i in {1..10}
do
qsub output/${i}/Wrapper/logs/wrapper.cmd
done
```
This will generate "Ensemble.sSNV.tsv" and "Ensemble.sINDEL.tsv" under each region subfolder (e.g. under 'output/{1,2,3,...}/Wrapper/').
Now you can combine these files to generate `ensemble_ann.tsv` file.
```
cat <(cat output/*/Wrapper/Ensemble.s*.tsv |grep CHROM|head -1) \
<(cat output/*/Wrapper/Ensemble.s*.tsv |grep -v CHROM) | sed "s/nan/0/g" > ensemble_ann.tsv
```
and provide `ensemble_ann.tsv` as `--ensemble_tsv` argument in `preprocess.py`.
## Options and Parameters
**prepare_callers_scripts.sh** can prepare dockerized somatic mutation calling jobs. The following options are available:
* `--normal-bam` /ABSOLUTE/PATH/TO/normal_sample.bam (Required)
* `--tumor-bam` /ABSOLUTE/PATH/TO/tumor_sample.bam (Required)
* `--output-dir` /ABSOLUTE/PATH/TO/OUTPUT_DIRECTORY (Required)
* `--human-reference` /ABSOLUTE/PATH/TO/human_reference.fa (Required)
* `--dbsnp` /ABSOLUTE/PATH/TO/dbsnp.vcf (Required for MuSE and LoFreq)
* `--cosmic` /ABSOLUTE/PATH/TO/cosmic.vcf (Optional)
* `--selector` /ABSOLUTE/PATH/TO/Capture_region.bed (Optional. Will create genome.bed from the .fa.fai file when not specified.)
* `--exclude` /ABSOLUTE/PATH/TO/Blacklist_Region.bed (Optional)
* `--min-af` (Optional. The minimum VAF cutoff for VarDict. Defulat is 0.05.)
* `--splits` N (Optional: evenly split the genome into N BED files. Default = 12).
* `--mutect2` (Optional flag to invoke MuTect2)
* `--varscan2` (Optional flag to invoke VarScan2)
* `--somaticsniper` (Optional flag to invoke SomaticSniper)
* `--vardict` (Optional flag to invoke VarDict)
* `--muse` (Optional flag to invoke MuSE)
* `--strelka` (Optional flag to invoke Strelka)
* `--wrapper` (Optional flag to invoke wrapper to combine outputs of all callers).
* `--exome` (Optional flag for Strelka and MuSE when data is WES)
* `--mutect2-arguments` (Extra parameters to pass onto Mutect2, e.g., --mutect2-arguments '--initial_tumor_lod 3.0 --log_somatic_prior -5.0 --min_base_quality_score 20')
* `--mutect2-filter-arguments` (Extra parameters to pass onto FilterMutectCalls)
* `--varscan-arguments` (Extra parameters to pass onto VarScan2)
* `--varscan-pileup-arguments` (Extra parameters to pass onto samtools mpileup that creates pileup files for VarScan)
* `--somaticsniper-arguments` (Extra parameters to pass onto SomaticSniper)
* `--vardict-arguments` (Extra parameters to pass onto VarDict)
* `--muse-arguments` (Extra parameters to pass onto MuSE)
* `--strelka-config-arguments` (Extra parameters to pass onto Strelka's config command)
* `--strelka-run-arguments` (Extra parameters to pass onto Strekla's run command)
* `--wrapper-arguments` (Extra parameters to pass onto SomaticSeq.Wrapper.sh)
* `--singularity` (Optional flag to use Singulariy instead of Docker)
### NOTES
* If you want to use Singulariy instead of Docker, please use `--singularity` argument in `prepare_callers_scripts`.
* Due to the way those run scripts are written, the Sun Grid Engine's standard error log will record the time the task completes (i.e., `Done at 2017/10/30 29:03:02`), and it will only do so when the task is completed with an exit code of 0. It can be a quick way to check if a task is done, by looking at the final line of the standard error log file.
* If you don't provide a region file, each split BED file represents 1/N (For N splits) of the total base pairs in the human genome (obtained from the .fa.fai file, but only including 1, 2, 3, ..., MT, or chr1, chr2, ..., chrM contigs).
* Parallelization (i.e., splitting) is not turned on for SomaticSniper because 1) it's manageable on a single split (even for WGS), and 2) it doesn't support partial processing with BED file, so it may not be worth the time to split the BAM. After SomaticSniper finishes, the result VCF files will be split into each of the regions sub-folders `output/{1,2,3,...}`.
* After specifying the reference fasta (must have extensions of .fa or .fasta), it must also include the .dict and .fa.fai (or .fasta.fai) files in the same directory.
* When specifying `/ABSOLUTE/PATH/TO/dbSNP.vcf`, there also needs to be `dbSNP.vcf.idx`, `dbSNP.vcf.gz`, and `dbSNP.vcf.gz.tbi` present at the same directory because MuSE and LoFreq are expecting them.
* We also have no distribution rights for VarScan2, so our script points to a 3rd-party version. Only run it if you are licensed to do so.
| {
"pile_set_name": "Github"
} |
import distutils, os
from setuptools import Command
from setuptools.command.setopt import edit_config, option_base
class saveopts(option_base):
"""Save command-line options to a file"""
description = "save supplied options to setup.cfg or other config file"
def run(self):
dist = self.distribution
commands = dist.command_options.keys()
settings = {}
for cmd in commands:
if cmd=='saveopts':
continue # don't save our own options!
for opt,(src,val) in dist.get_option_dict(cmd).items():
if src=="command line":
settings.setdefault(cmd,{})[opt] = val
edit_config(self.filename, settings, self.dry_run)
| {
"pile_set_name": "Github"
} |
### 长江截流22年 戴晴:三峡大坝弊端渐引国人质疑中共决策
------------------------
#### [首页](https://github.com/gfw-breaker/banned-news/blob/master/README.md) | [手把手翻墙教程](https://github.com/gfw-breaker/guides/wiki) | [禁闻聚合安卓版](https://github.com/gfw-breaker/bn-android) | [网门安卓版](https://github.com/oGate2/oGate) | [神州正道安卓版](https://github.com/SzzdOgate/update)
<div class="zhidingtu">
<div class="ar-wrap-3x2">
<img alt="今年7月下旬以来,长江中下游地区出现了近40年来最严重的一次乾旱。(AP图片)" class="ar-wrap-inside-fill" src="http://img.soundofhope.org/2019/11/sanxiaganhe-800x534-600x401.jpg"/>
</div>
<div class="caption">
今年7月下旬以来,长江中下游地区出现了近40年来最严重的一次乾旱。(AP图片)
</div>
</div>
<hr/>
#### [翻墙必看视频(文昭、江峰、法轮功、八九六四、香港反送中...)](https://github.com/gfw-breaker/banned-news/blob/master/pages/links.md)
<div class="content">
<p>
<span class="content-info-date">
【希望之声2019年11月10日】
</span>
<span class="content-info-type">
(本台记者王倩采访报导)
</span>
22年前(1997年)的11月8日,中共当局举行“长江三峡工程大江截流仪式”,三峡二期工程正式在巨大争议声中强行上马。事实证明,中共宣传的三峡工程“具有防洪抗旱、发电、航运、环保等巨大的综合利用效益”并没有实现,相反,今年7月下旬以来,长江中下游地区出现了近40年来最严重的一次乾旱,鄱阳湖更提前出现枯水期。中共已故元老叶剑英养女、中国政治和社会观察家戴晴表示,三峡工程给中国百姓带来的灾害近年来不断显现,这渐渐引起了国人对中共决策的思索和质疑。
</p>
<div class="widget ad-300x250 ad-ecf">
<!-- ZW30 Post Embed 300x250 1 -->
<ins class="adsbygoogle" data-ad-client="ca-pub-1519518652909441" data-ad-slot="9768754376" style="display:inline-block;width:300px;height:250px">
</ins>
</div>
<p>
戴晴女士8日接受本台采访时指出,中共强行上马的三峡工程,实际上给长江沿岸居民乃至所有中国人带来了太多的危害。
</p>
<p>
【录音】好像是从1980年代算起,那一步一步(危害)实际上太多了。最需要去关注的应该是整个三峡工程造成的环境灾害,包括三峡工程对环境的污染、对移民的补偿,我们应该弄清楚。从三峡工程的上游一直到三峡工程的下游到上海口,实际上都有影响,这么大一个大坝对它的环境、它的生态都有很大的影响;所有出现的洪灾、出现的旱涝、出现的乾涸、出现的船舶的碍航、出现的上海海岸线的挪移、出现的比如说一些生物的灭绝等等等等,因为它涉及的领域太广了,涉及的人数就主要是沿着长江的。第三个就是移民(问题),这些三峡移民他们实际上就像黄河上的三文峡移民一样,他们一直离乡别井,得不到一个正常的生活条件。
</p>
<div class="soh-audio-player status-published">
<div class="jp-jplayer" id="audio-player-0">
</div>
<div aria-label="media player" class="jp-audio" data-url-h="http://media.soundofhope.org/audio03/2019/11/1-113.mp3" data-url-l="http://media.soundofhope.org/16K-mp3/audio03/2019/11/1-113_16K.mp3" id="audio-player-container-0" role="application">
<div class="panel">
<div class="control">
<div class="button pnp">
<i aria-hidden="true" class="fa fa-play">
</i>
</div>
<div class="slider-progress">
</div>
<div class="button mute">
<i aria-hidden="true" class="fa fa-volume-up">
</i>
</div>
<div class="slider-vol">
</div>
<div class="button download">
<span href="http://media.soundofhope.org/16K-mp3/audio03/2019/11/1-113_16K.mp3">
<i aria-hidden="true" class="fa fa-cloud-download">
</i>
</span>
</div>
<div aria-label="..." class="btn-group bps" role="group">
<button class="btn btn-default bps-l active" type="button">
16K
</button>
<button class="btn btn-default bps-h" type="button">
128K
</button>
</div>
</div>
</div>
</div>
</div>
<p>
戴晴表示,近年,三峡大坝所带来的种种弊端,也让一些中国学者开始对中共的各项决策产生思索和质疑。
</p>
<p>
【录音】再有一部分就是知识分子,无论是研究政治学和社会科学的知识分子,他们最需要知道的就是,一个这么重大的工程,你(中共)的决策过程是什么?你的决策出现了失误,你在决策过程中不允许反对意见发表出来,那么整个对中国,不仅仅是一个工程、一条长江,而全中国这么多事情、这么多年、这么多错误的决策,这个(决策)过程实际上是政治学和比如说社会学者、经济学家和所有的知识分子都关注的问题。我觉得再有就是科学家,现在科学家分成更注重工程的挣钱,和更注重保护我们的生态环境这样的两大派。科学家就是从整个地球的生存、人类的生存、地球的平衡这个角度上来讲,说我们人类把自己的能力估计的过高了,我们并不能这样“人定胜天”,我们并不能改变自然,我们一定要和自然还是一种和谐的态度,尊敬自然的规律,然后怎么来保护我们整个地球的生态。
</p>
<div class="soh-audio-player status-published">
<div class="jp-jplayer" id="audio-player-1">
</div>
<div aria-label="media player" class="jp-audio" data-url-h="http://media.soundofhope.org/audio03/2019/11/2-101.mp3" data-url-l="http://media.soundofhope.org/16K-mp3/audio03/2019/11/2-101_16K.mp3" id="audio-player-container-1" role="application">
<div class="panel">
<div class="control">
<div class="button pnp">
<i aria-hidden="true" class="fa fa-play">
</i>
</div>
<div class="slider-progress">
</div>
<div class="button mute">
<i aria-hidden="true" class="fa fa-volume-up">
</i>
</div>
<div class="slider-vol">
</div>
<div class="button download">
<span href="http://media.soundofhope.org/16K-mp3/audio03/2019/11/2-101_16K.mp3">
<i aria-hidden="true" class="fa fa-cloud-download">
</i>
</span>
</div>
<div aria-label="..." class="btn-group bps" role="group">
<button class="btn btn-default bps-l active" type="button">
16K
</button>
<button class="btn btn-default bps-h" type="button">
128K
</button>
</div>
</div>
</div>
</div>
</div>
<p>
戴晴认为,至今,中共不但拒绝对三峡工程出现的危机承担责任,还将三峡工程列入所谓的“敏感问题”而禁止讨论,这都是中共一党独裁、忽视民意所招致的灾祸。
</p>
<p>
【录音】比如说98年的时候大洪水,就说洪水并不大,但是洪灾很大,为什么呢?就是三峡工程造成的;后来的洞庭湖和鄱阳湖都乾涸了,再接着长江的航运都出现了这些事情,这个他们(中共当局)讲的很少,就是整个对地质的影响。这是三峡工程他们内部的人最担心的问题,他们不敢说,现在也没有公共的讨论。这是第一个。第二个就是最近出现的变形,出现比如说垮坝什么的这样的事情。这个呢,三峡工程(官方)他们就是非常原则上的、又非常严厉的语言说“胡说!你们胡说!不会有这样的事情”什么什么的,但是更细致的分析没有出来。所以这个也是一个很大的问题,他们还这么遮著、掩著。现在看起来这个问题就等于是三文峡工程和三峡工程,就是国家(中共政府)以“领袖”,前一个是毛泽东,后一个是邓小平,以他们“一言九鼎”这样的权力说干就干了,那么实际上给中国的国土留下了这么严重的灾难。我觉得确实是值得我们这代人、特别是后代人,真的要认真的研究并且吸取教训。现在三峡工程也是破天荒地被列为了不可以说的“敏感问题”。我觉得就是有严重的问题,他们才把它列到“谁也不许说(的禁忌话题)”。
</p>
<div class="soh-audio-player status-published">
<div class="jp-jplayer" id="audio-player-2">
</div>
<div aria-label="media player" class="jp-audio" data-url-h="http://media.soundofhope.org/audio03/2019/11/3-72.mp3" data-url-l="http://media.soundofhope.org/16K-mp3/audio03/2019/11/3-72_16K.mp3" id="audio-player-container-2" role="application">
<div class="panel">
<div class="control">
<div class="button pnp">
<i aria-hidden="true" class="fa fa-play">
</i>
</div>
<div class="slider-progress">
</div>
<div class="button mute">
<i aria-hidden="true" class="fa fa-volume-up">
</i>
</div>
<div class="slider-vol">
</div>
<div class="button download">
<span href="http://media.soundofhope.org/16K-mp3/audio03/2019/11/3-72_16K.mp3">
<i aria-hidden="true" class="fa fa-cloud-download">
</i>
</span>
</div>
<div aria-label="..." class="btn-group bps" role="group">
<button class="btn btn-default bps-l active" type="button">
16K
</button>
<button class="btn btn-default bps-h" type="button">
128K
</button>
</div>
</div>
</div>
</div>
</div>
<p>
事实上,20世纪80年代,赵紫阳就曾向邓小平谏言三峡工程对中国的诸多不利因素,也有一些民主党派人士对此持反对态度。但邓小平却认为,这是一个具有政治意义的工程,正因为民主党派人士的反对才要修建,以此来显示共产党“绝对权威”的政治统治地位。而中共前任党魁江泽民为捞取政绩,直接推动了三峡的修建。
</p>
<p>
希望之声国际广播电台记者 王倩 萧晴 采访报导
</p>
<div class="content-info-btm">
<p class="content-info-zerenbianji">
<span class="content-info-title">
责任编辑:
</span>
<span class="content-info-content">
元明清
</span>
</p>
<p class="content-info-refernote">
(希望之声版权所有,未经希望之声书面允许,不得转载,违者必究。)
</p>
</div>
</div>
<hr/>
手机上长按并复制下列链接或二维码分享本文章:<br/>
https://github.com/gfw-breaker/banned-news/blob/master/pages/soh_zgxw/n3324174.md <br/>
<a href='https://github.com/gfw-breaker/banned-news/blob/master/pages/soh_zgxw/n3324174.md'><img src='https://github.com/gfw-breaker/banned-news/blob/master/pages/soh_zgxw/n3324174.md.png'/></a> <br/>
原文地址(需翻墙访问):http://www.soundofhope.org/gb/2019/11/10/n3324174.html
------------------------
#### [首页](https://github.com/gfw-breaker/banned-news/blob/master/README.md) | [一键翻墙软件](https://github.com/gfw-breaker/nogfw/blob/master/README.md) | [《九评共产党》](https://github.com/gfw-breaker/9ping.md/blob/master/README.md#九评之一评共产党是什么) | [《解体党文化》](https://github.com/gfw-breaker/jtdwh.md/blob/master/README.md) | [《共产主义的终极目的》](https://github.com/gfw-breaker/gczydzjmd.md/blob/master/README.md)
<img src='http://gfw-breaker.win/banned-news/pages/soh_zgxw/n3324174.md' width='0px' height='0px'/> | {
"pile_set_name": "Github"
} |
.TH XScreenSaver 1 "10-May-97" "X Version 11"
.SH NAME
lightning - draws fractal lightning bolts
.SH SYNOPSIS
.B lightning
[\-display \fIhost:display.screen\fP] [\-foreground \fIcolor\fP] [\-background \fIcolor\fP] [\-window] [\-root] [\-mono] [\-install] [\-visual \fIvisual\fP] [\-ncolors \fIinteger\fP] [\-delay \fImicroseconds\fP]
[\-fps]
.SH DESCRIPTION
The \fIlightning\fP program draws fractal lightning bolts
.SH OPTIONS
.I lightning
accepts the following options:
.TP 8
.B \-window
Draw on a newly-created window. This is the default.
.TP 8
.B \-root
Draw on the root window.
.TP 8
.B \-mono
If on a color display, pretend we're on a monochrome display.
.TP 8
.B \-install
Install a private colormap for the window.
.TP 8
.B \-visual \fIvisual\fP
Specify which visual to use. Legal values are the name of a visual class,
or the id number (decimal or hex) of a specific visual.
.TP 8
.B \-ncolors \fIinteger\fP
How many colors should be used (if possible). Default 64.
The colors are chosen randomly.
.TP 8
.B \-fps
Display the current frame rate and CPU load.
.SH ENVIRONMENT
.PP
.TP 8
.B DISPLAY
to get the default host and display number.
.TP 8
.B XENVIRONMENT
to get the name of a resource file that overrides the global resources
stored in the RESOURCE_MANAGER property.
.SH SEE ALSO
.BR X (1),
.BR xscreensaver (1),
.BR xlock (1)
.SH COPYRIGHT
Copyright \(co 1996 by Keith Romberg.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation.
.SH AUTHOR
Keith Romberg <[email protected]>, 27-Jun-96.
Ability to run standalone or with \fIxscreensaver\fP added by
Jamie Zawinski <[email protected]>, 10-May-97.
| {
"pile_set_name": "Github"
} |
{
"css": {
"properties": {
"box-lines": {
"__compat": {
"mdn_url": "https://developer.mozilla.org/docs/Web/CSS/box-lines",
"support": {
"chrome": {
"version_added": "1",
"version_removed": "67",
"prefix": "-webkit-"
},
"chrome_android": {
"version_added": "18",
"version_removed": "67",
"prefix": "-webkit-"
},
"edge": {
"version_added": false
},
"firefox": {
"version_added": false
},
"firefox_android": {
"version_added": false
},
"ie": {
"version_added": false
},
"opera": {
"version_added": "15",
"version_removed": "54",
"prefix": "-webkit-"
},
"opera_android": {
"version_added": "14",
"version_removed": "48",
"prefix": "-webkit-"
},
"safari": [
{
"version_added": "3",
"prefix": "-webkit-"
},
{
"version_added": "1.1",
"version_removed": "3",
"prefix": "-khtml-"
}
],
"safari_ios": {
"version_added": "1",
"prefix": "-webkit-"
},
"samsunginternet_android": {
"version_added": "1.0",
"version_removed": "9.0",
"prefix": "-webkit-"
},
"webview_android": {
"version_added": "≤37",
"version_removed": "67",
"prefix": "-webkit-"
}
},
"status": {
"experimental": false,
"standard_track": false,
"deprecated": true
}
}
}
}
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<model ref="r:f272d0cc-a1f0-4f70-8316-377a652766ba(com.mbeddr.core.statements.actions)">
<persistence version="9" />
<languages>
<use id="83888646-71ce-4f1c-9c53-c54016f6ad4f" name="jetbrains.mps.baseLanguage.collections" version="1" />
<use id="13744753-c81f-424a-9c1b-cf8943bf4e86" name="jetbrains.mps.lang.sharedConcepts" version="0" />
<use id="7866978e-a0f0-4cc7-81bc-4d213d9375e1" name="jetbrains.mps.lang.smodel" version="17" />
<use id="ceab5195-25ea-4f22-9b92-103b95ca8c0c" name="jetbrains.mps.lang.core" version="2" />
<use id="aee9cad2-acd4-4608-aef2-0004f6a1cdbd" name="jetbrains.mps.lang.actions" version="4" />
<use id="9d69e719-78c8-4286-90db-fb19c107d049" name="com.mbeddr.mpsutil.grammarcells" version="1" />
<use id="18bc6592-03a6-4e29-a83a-7ff23bde13ba" name="jetbrains.mps.lang.editor" version="14" />
<use id="f3061a53-9226-4cc5-a443-f952ceaf5816" name="jetbrains.mps.baseLanguage" version="11" />
<devkit ref="fbc25dd2-5da4-483a-8b19-70928e1b62d7(jetbrains.mps.devkit.general-purpose)" />
</languages>
<imports>
<import index="c4fa" ref="r:9f0e84b6-2ec7-4f9e-83e0-feedc77b63a3(com.mbeddr.core.statements.structure)" />
<import index="mj1l" ref="r:c371cf98-dcc8-4a43-8eb8-8a8096de18b2(com.mbeddr.core.expressions.structure)" />
<import index="vs0r" ref="r:f7764ca4-8c75-4049-922b-08516400a727(com.mbeddr.core.base.structure)" />
<import index="tpck" ref="r:00000000-0000-4000-0000-011c89590288(jetbrains.mps.lang.core.structure)" />
<import index="tpce" ref="r:00000000-0000-4000-0000-011c89590292(jetbrains.mps.lang.structure.structure)" />
<import index="hwgx" ref="r:fd2980c8-676c-4b19-b524-18c70e02f8b7(com.mbeddr.core.base.behavior)" />
<import index="mhfm" ref="3f233e7f-b8a6-46d2-a57f-795d56775243/java:org.jetbrains.annotations(Annotations/)" />
<import index="cj4x" ref="1ed103c3-3aa6-49b7-9c21-6765ee11f224/java:jetbrains.mps.openapi.editor(MPS.Editor/)" />
<import index="zce0" ref="1ed103c3-3aa6-49b7-9c21-6765ee11f224/java:jetbrains.mps.smodel.action(MPS.Editor/)" />
<import index="f4zo" ref="1ed103c3-3aa6-49b7-9c21-6765ee11f224/java:jetbrains.mps.openapi.editor.cells(MPS.Editor/)" />
<import index="wcxw" ref="r:b9f36c08-4a75-4513-9277-a390d3426e0f(jetbrains.mps.editor.runtime.impl.cellActions)" />
<import index="j4gk" ref="r:44b6f9b4-bfdb-4b99-b104-960ec485d777(com.mbeddr.core.statements.editor)" />
</imports>
<registry>
<language id="f3061a53-9226-4cc5-a443-f952ceaf5816" name="jetbrains.mps.baseLanguage">
<concept id="1215693861676" name="jetbrains.mps.baseLanguage.structure.BaseAssignmentExpression" flags="nn" index="d038R">
<child id="1068498886297" name="rValue" index="37vLTx" />
<child id="1068498886295" name="lValue" index="37vLTJ" />
</concept>
<concept id="1197027756228" name="jetbrains.mps.baseLanguage.structure.DotExpression" flags="nn" index="2OqwBi">
<child id="1197027771414" name="operand" index="2Oq$k0" />
<child id="1197027833540" name="operation" index="2OqNvi" />
</concept>
<concept id="1145552977093" name="jetbrains.mps.baseLanguage.structure.GenericNewExpression" flags="nn" index="2ShNRf">
<child id="1145553007750" name="creator" index="2ShVmc" />
</concept>
<concept id="1137021947720" name="jetbrains.mps.baseLanguage.structure.ConceptFunction" flags="in" index="2VMwT0">
<child id="1137022507850" name="body" index="2VODD2" />
</concept>
<concept id="1068431474542" name="jetbrains.mps.baseLanguage.structure.VariableDeclaration" flags="ng" index="33uBYm">
<child id="1068431790190" name="initializer" index="33vP2m" />
</concept>
<concept id="1068498886296" name="jetbrains.mps.baseLanguage.structure.VariableReference" flags="nn" index="37vLTw">
<reference id="1068581517664" name="variableDeclaration" index="3cqZAo" />
</concept>
<concept id="1068498886294" name="jetbrains.mps.baseLanguage.structure.AssignmentExpression" flags="nn" index="37vLTI" />
<concept id="4972933694980447171" name="jetbrains.mps.baseLanguage.structure.BaseVariableDeclaration" flags="ng" index="19Szcq">
<child id="5680397130376446158" name="type" index="1tU5fm" />
</concept>
<concept id="1068580123155" name="jetbrains.mps.baseLanguage.structure.ExpressionStatement" flags="nn" index="3clFbF">
<child id="1068580123156" name="expression" index="3clFbG" />
</concept>
<concept id="1068580123136" name="jetbrains.mps.baseLanguage.structure.StatementList" flags="sn" stub="5293379017992965193" index="3clFbS">
<child id="1068581517665" name="statement" index="3cqZAp" />
</concept>
<concept id="1068581242878" name="jetbrains.mps.baseLanguage.structure.ReturnStatement" flags="nn" index="3cpWs6">
<child id="1068581517676" name="expression" index="3cqZAk" />
</concept>
<concept id="1068581242864" name="jetbrains.mps.baseLanguage.structure.LocalVariableDeclarationStatement" flags="nn" index="3cpWs8">
<child id="1068581242865" name="localVariableDeclaration" index="3cpWs9" />
</concept>
<concept id="1068581242863" name="jetbrains.mps.baseLanguage.structure.LocalVariableDeclaration" flags="nr" index="3cpWsn" />
</language>
<language id="aee9cad2-acd4-4608-aef2-0004f6a1cdbd" name="jetbrains.mps.lang.actions">
<concept id="1221135252814" name="jetbrains.mps.lang.actions.structure.PasteWrappers" flags="ig" index="1hljLi">
<child id="1221135321084" name="wrapper" index="1hl$rw" />
</concept>
<concept id="1221135315536" name="jetbrains.mps.lang.actions.structure.PasteWrapper" flags="lg" index="1hlzdc">
<reference id="1221135563864" name="sourceConcept" index="1hmvP4" />
<reference id="1221137152191" name="targetConcept" index="1hszAz" />
<child id="1221137217490" name="wrapperFunction" index="1hsNre" />
</concept>
<concept id="1221137268788" name="jetbrains.mps.lang.actions.structure.ConceptFunctionParameter_nodeToPasteWrap" flags="nn" index="1ht04C" />
<concept id="1221137293320" name="jetbrains.mps.lang.actions.structure.QueryFunction_PasteWrapper" flags="in" index="1ht64k" />
</language>
<language id="7866978e-a0f0-4cc7-81bc-4d213d9375e1" name="jetbrains.mps.lang.smodel">
<concept id="1180636770613" name="jetbrains.mps.lang.smodel.structure.SNodeCreator" flags="nn" index="3zrR0B">
<child id="1180636770616" name="createdType" index="3zrR0E" />
</concept>
<concept id="1138055754698" name="jetbrains.mps.lang.smodel.structure.SNodeType" flags="in" index="3Tqbb2">
<reference id="1138405853777" name="concept" index="ehGHo" />
</concept>
<concept id="1138056143562" name="jetbrains.mps.lang.smodel.structure.SLinkAccess" flags="nn" index="3TrEf2">
<reference id="1138056516764" name="link" index="3Tt5mk" />
</concept>
</language>
<language id="ceab5195-25ea-4f22-9b92-103b95ca8c0c" name="jetbrains.mps.lang.core">
<concept id="1169194658468" name="jetbrains.mps.lang.core.structure.INamedConcept" flags="ng" index="TrEIO">
<property id="1169194664001" name="name" index="TrG5h" />
</concept>
</language>
</registry>
<node concept="1hljLi" id="20McjG53wS7">
<property role="TrG5h" value="pasteExpressionIntoStatement" />
<node concept="1hlzdc" id="20McjG53wS8" role="1hl$rw">
<ref role="1hmvP4" to="mj1l:7FQByU3CrCM" resolve="Expression" />
<ref role="1hszAz" to="c4fa:3CmSUB7FmO3" resolve="Statement" />
<node concept="1ht64k" id="20McjG53wS9" role="1hsNre">
<node concept="3clFbS" id="20McjG53wSa" role="2VODD2">
<node concept="3cpWs8" id="20McjG53wSb" role="3cqZAp">
<node concept="3cpWsn" id="20McjG53wSc" role="3cpWs9">
<property role="TrG5h" value="exs" />
<node concept="3Tqbb2" id="20McjG53wSd" role="1tU5fm">
<ref role="ehGHo" to="c4fa:6iIoqg1yCmi" resolve="ExpressionStatement" />
</node>
<node concept="2ShNRf" id="20McjG53wSf" role="33vP2m">
<node concept="3zrR0B" id="20McjG53wSg" role="2ShVmc">
<node concept="3Tqbb2" id="20McjG53wSh" role="3zrR0E">
<ref role="ehGHo" to="c4fa:6iIoqg1yCmi" resolve="ExpressionStatement" />
</node>
</node>
</node>
</node>
</node>
<node concept="3clFbF" id="20McjG53wSj" role="3cqZAp">
<node concept="37vLTI" id="20McjG53wSq" role="3clFbG">
<node concept="1ht04C" id="20McjG53wSt" role="37vLTx" />
<node concept="2OqwBi" id="20McjG53wSl" role="37vLTJ">
<node concept="37vLTw" id="5HxjapweqaH" role="2Oq$k0">
<ref role="3cqZAo" node="20McjG53wSc" resolve="exs" />
</node>
<node concept="3TrEf2" id="20McjG53wSp" role="2OqNvi">
<ref role="3Tt5mk" to="c4fa:6iIoqg1yCmj" resolve="expr" />
</node>
</node>
</node>
</node>
<node concept="3cpWs6" id="20McjG53wSv" role="3cqZAp">
<node concept="37vLTw" id="20McjG53wS$" role="3cqZAk">
<ref role="3cqZAo" node="20McjG53wSc" resolve="exs" />
</node>
</node>
</node>
</node>
</node>
<node concept="1hlzdc" id="4yC$DtH1I2N" role="1hl$rw">
<ref role="1hmvP4" to="c4fa:6iIoqg1yCmi" resolve="ExpressionStatement" />
<ref role="1hszAz" to="mj1l:7FQByU3CrCM" resolve="Expression" />
<node concept="1ht64k" id="4yC$DtH1I2O" role="1hsNre">
<node concept="3clFbS" id="4yC$DtH1I2P" role="2VODD2">
<node concept="3cpWs6" id="4yC$DtH1I2Q" role="3cqZAp">
<node concept="2OqwBi" id="4yC$DtH1I3d" role="3cqZAk">
<node concept="1ht04C" id="4yC$DtH1I2S" role="2Oq$k0" />
<node concept="3TrEf2" id="4yC$DtH1I3i" role="2OqNvi">
<ref role="3Tt5mk" to="c4fa:6iIoqg1yCmj" resolve="expr" />
</node>
</node>
</node>
</node>
</node>
</node>
</node>
</model>
| {
"pile_set_name": "Github"
} |
path: "tensorflow.metrics.MeanSquaredLogarithmicError"
tf_class {
is_instance: "<class \'tensorflow.python.keras.metrics.MeanSquaredLogarithmicError\'>"
is_instance: "<class \'tensorflow.python.keras.metrics.MeanMetricWrapper\'>"
is_instance: "<class \'tensorflow.python.keras.metrics.Mean\'>"
is_instance: "<class \'tensorflow.python.keras.metrics.Reduce\'>"
is_instance: "<class \'tensorflow.python.keras.metrics.Metric\'>"
is_instance: "<class \'tensorflow.python.keras.engine.base_layer.Layer\'>"
is_instance: "<class \'tensorflow.python.module.module.Module\'>"
is_instance: "<class \'tensorflow.python.training.tracking.tracking.AutoTrackable\'>"
is_instance: "<class \'tensorflow.python.training.tracking.base.Trackable\'>"
is_instance: "<type \'object\'>"
member {
name: "activity_regularizer"
mtype: "<type \'property\'>"
}
member {
name: "dtype"
mtype: "<type \'property\'>"
}
member {
name: "dynamic"
mtype: "<type \'property\'>"
}
member {
name: "inbound_nodes"
mtype: "<type \'property\'>"
}
member {
name: "input"
mtype: "<type \'property\'>"
}
member {
name: "input_mask"
mtype: "<type \'property\'>"
}
member {
name: "input_shape"
mtype: "<type \'property\'>"
}
member {
name: "input_spec"
mtype: "<type \'property\'>"
}
member {
name: "losses"
mtype: "<type \'property\'>"
}
member {
name: "metrics"
mtype: "<type \'property\'>"
}
member {
name: "name"
mtype: "<type \'property\'>"
}
member {
name: "name_scope"
mtype: "<type \'property\'>"
}
member {
name: "non_trainable_variables"
mtype: "<type \'property\'>"
}
member {
name: "non_trainable_weights"
mtype: "<type \'property\'>"
}
member {
name: "outbound_nodes"
mtype: "<type \'property\'>"
}
member {
name: "output"
mtype: "<type \'property\'>"
}
member {
name: "output_mask"
mtype: "<type \'property\'>"
}
member {
name: "output_shape"
mtype: "<type \'property\'>"
}
member {
name: "submodules"
mtype: "<type \'property\'>"
}
member {
name: "trainable"
mtype: "<type \'property\'>"
}
member {
name: "trainable_variables"
mtype: "<type \'property\'>"
}
member {
name: "trainable_weights"
mtype: "<type \'property\'>"
}
member {
name: "updates"
mtype: "<type \'property\'>"
}
member {
name: "variables"
mtype: "<type \'property\'>"
}
member {
name: "weights"
mtype: "<type \'property\'>"
}
member_method {
name: "__init__"
argspec: "args=[\'self\', \'name\', \'dtype\'], varargs=None, keywords=None, defaults=[\'mean_squared_logarithmic_error\', \'None\'], "
}
member_method {
name: "add_loss"
argspec: "args=[\'self\', \'losses\', \'inputs\'], varargs=None, keywords=None, defaults=[\'None\'], "
}
member_method {
name: "add_metric"
argspec: "args=[\'self\', \'value\', \'aggregation\', \'name\'], varargs=None, keywords=None, defaults=[\'None\', \'None\'], "
}
member_method {
name: "add_update"
argspec: "args=[\'self\', \'updates\', \'inputs\'], varargs=None, keywords=None, defaults=[\'None\'], "
}
member_method {
name: "add_variable"
argspec: "args=[\'self\'], varargs=args, keywords=kwargs, defaults=None"
}
member_method {
name: "add_weight"
argspec: "args=[\'self\', \'name\', \'shape\', \'aggregation\', \'synchronization\', \'initializer\', \'dtype\'], varargs=None, keywords=None, defaults=[\'()\', \'VariableAggregation.SUM\', \'VariableSynchronization.ON_READ\', \'None\', \'None\'], "
}
member_method {
name: "apply"
argspec: "args=[\'self\', \'inputs\'], varargs=args, keywords=kwargs, defaults=None"
}
member_method {
name: "build"
argspec: "args=[\'self\', \'input_shape\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "call"
argspec: "args=[\'self\', \'inputs\'], varargs=None, keywords=kwargs, defaults=None"
}
member_method {
name: "compute_mask"
argspec: "args=[\'self\', \'inputs\', \'mask\'], varargs=None, keywords=None, defaults=[\'None\'], "
}
member_method {
name: "compute_output_shape"
argspec: "args=[\'self\', \'input_shape\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "compute_output_signature"
argspec: "args=[\'self\', \'input_signature\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "count_params"
argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "from_config"
argspec: "args=[\'cls\', \'config\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "get_config"
argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "get_input_at"
argspec: "args=[\'self\', \'node_index\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "get_input_mask_at"
argspec: "args=[\'self\', \'node_index\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "get_input_shape_at"
argspec: "args=[\'self\', \'node_index\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "get_losses_for"
argspec: "args=[\'self\', \'inputs\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "get_output_at"
argspec: "args=[\'self\', \'node_index\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "get_output_mask_at"
argspec: "args=[\'self\', \'node_index\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "get_output_shape_at"
argspec: "args=[\'self\', \'node_index\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "get_updates_for"
argspec: "args=[\'self\', \'inputs\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "get_weights"
argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "reset_states"
argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "result"
argspec: "args=[\'self\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "set_weights"
argspec: "args=[\'self\', \'weights\'], varargs=None, keywords=None, defaults=None"
}
member_method {
name: "update_state"
argspec: "args=[\'self\', \'y_true\', \'y_pred\', \'sample_weight\'], varargs=None, keywords=None, defaults=[\'None\'], "
}
member_method {
name: "with_name_scope"
argspec: "args=[\'cls\', \'method\'], varargs=None, keywords=None, defaults=None"
}
}
| {
"pile_set_name": "Github"
} |
package restful
import "strings"
// Copyright 2013 Ernest Micklei. All rights reserved.
// Use of this source code is governed by a license
// that can be found in the LICENSE file.
// OPTIONSFilter is a filter function that inspects the Http Request for the OPTIONS method
// and provides the response with a set of allowed methods for the request URL Path.
// As for any filter, you can also install it for a particular WebService within a Container.
// Note: this filter is not needed when using CrossOriginResourceSharing (for CORS).
func (c *Container) OPTIONSFilter(req *Request, resp *Response, chain *FilterChain) {
if "OPTIONS" != req.Request.Method {
chain.ProcessFilter(req, resp)
return
}
resp.AddHeader(HEADER_Allow, strings.Join(c.computeAllowedMethods(req), ","))
}
// OPTIONSFilter is a filter function that inspects the Http Request for the OPTIONS method
// and provides the response with a set of allowed methods for the request URL Path.
// Note: this filter is not needed when using CrossOriginResourceSharing (for CORS).
func OPTIONSFilter() FilterFunction {
return DefaultContainer.OPTIONSFilter
}
| {
"pile_set_name": "Github"
} |
<div class="step">
<div class="mui-container-fluid">
<div class="mui-row after-signin-pwd" style="display: none">
<p>
<span class="fa fa-check-square" aria-hidden="true" style="font-size:1.5em;color:#03A43E;"></span> You've
successfully signed in. You can now play with any of the interactive samples from the sidebar.
</p>
</div>
<div class="mui-row after-signin-error-pwd" style="display: none">
<p>
<span class="fa fa-exclamation-circle" aria-hidden="true" style="font-size:1.5em;color:#03A43E;"></span> There was an error signing you in. Please try again or try with a different authentication mode.
</p>
</div>
<div class="mui-row before-signin-pwd">
<div class="mui-col-md-8">
<zero-md file="">
<div class="md-html"></div>
</zero-md>
</div>
<div class="mui-col-md-4">
<div class="mui--text-display2">Preview</div>
<br/>
<div class="mui-panel mui--z3">
<div class="mui-textfield">
<input type="text" class="username" placeholder="[email protected]" data-enter-bind="signin">
<label>Username</label>
</div>
<div class="mui-textfield">
<input type="password" class="password" placeholder="********" data-enter-bind="signin">
<label>Password</label>
</div>
<button class="mui-btn mui-btn--raised mui-btn--primary signin">Sign-In</button>
</div>
</div>
</div>
</div>
</div> | {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2016 FUJITSU LIMITED
* Author: Wen Congyang <[email protected]>
* Yang Hongyang <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the 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 Lesser General Public License for more details.
*/
#include "libxl_osdeps.h" /* must come before any other headers */
#include "libxl_internal.h"
extern const libxl__checkpoint_device_instance_ops colo_save_device_nic;
extern const libxl__checkpoint_device_instance_ops colo_save_device_qdisk;
static const libxl__checkpoint_device_instance_ops *colo_ops[] = {
&colo_save_device_nic,
&colo_save_device_qdisk,
NULL,
};
/* ================= helper functions ================= */
static int init_device_subkind(libxl__checkpoint_devices_state *cds)
{
/* init device subkind-specific state in the libxl ctx */
int rc;
STATE_AO_GC(cds->ao);
rc = init_subkind_colo_nic(cds);
if (rc) goto out;
rc = init_subkind_qdisk(cds);
if (rc) {
cleanup_subkind_colo_nic(cds);
goto out;
}
rc = 0;
out:
return rc;
}
static void cleanup_device_subkind(libxl__checkpoint_devices_state *cds)
{
/* cleanup device subkind-specific state in the libxl ctx */
STATE_AO_GC(cds->ao);
cleanup_subkind_colo_nic(cds);
cleanup_subkind_qdisk(cds);
}
/* ================= colo: setup save environment ================= */
static void colo_save_setup_done(libxl__egc *egc,
libxl__checkpoint_devices_state *cds,
int rc);
static void colo_save_setup_failed(libxl__egc *egc,
libxl__checkpoint_devices_state *cds,
int rc);
/*
* checkpoint callbacks are called in the following order:
* 1. suspend
* 2. checkpoint
* 3. resume
* 4. wait checkpoint
*/
static void libxl__colo_save_domain_suspend_callback(void *data);
static void libxl__colo_save_domain_checkpoint_callback(void *data);
static void libxl__colo_save_domain_resume_callback(void *data);
static void libxl__colo_save_domain_wait_checkpoint_callback(void *data);
void libxl__colo_save_setup(libxl__egc *egc, libxl__colo_save_state *css)
{
libxl__domain_save_state *dss = CONTAINER_OF(css, *dss, css);
/* Convenience aliases */
libxl__checkpoint_devices_state *const cds = &dss->cds;
libxl__srm_save_autogen_callbacks *const callbacks =
&dss->sws.shs.callbacks.save.a;
STATE_AO_GC(dss->ao);
if (dss->type != LIBXL_DOMAIN_TYPE_HVM) {
LOGD(ERROR, dss->domid, "COLO only supports hvm now");
goto out;
}
css->send_fd = dss->fd;
css->recv_fd = dss->recv_fd;
css->svm_running = false;
css->paused = true;
css->qdisk_setuped = false;
css->qdisk_used = false;
libxl__ev_child_init(&css->child);
css->cps.is_userspace_proxy =
libxl_defbool_val(dss->remus->userspace_colo_proxy);
if (dss->remus->netbufscript)
css->colo_proxy_script = libxl__strdup(gc, dss->remus->netbufscript);
else
css->colo_proxy_script = GCSPRINTF("%s/colo-proxy-setup",
libxl__xen_script_dir_path());
cds->ops = colo_ops;
cds->callback = colo_save_setup_done;
cds->ao = ao;
cds->domid = dss->domid;
cds->concrete_data = css;
/* If enable userspace proxy mode, we don't need VIF */
if (css->cps.is_userspace_proxy) {
cds->device_kind_flags = (1 << LIBXL__DEVICE_KIND_VBD);
/* Use this args we can connect to qemu colo-compare */
cds->nics = libxl__device_list(gc, &libxl__nic_devtype,
cds->domid, &cds->num_nics);
if (cds->num_nics > 0) {
css->cps.checkpoint_host = cds->nics[0].colo_checkpoint_host;
css->cps.checkpoint_port = cds->nics[0].colo_checkpoint_port;
}
} else {
cds->device_kind_flags = (1 << LIBXL__DEVICE_KIND_VIF) |
(1 << LIBXL__DEVICE_KIND_VBD);
}
css->srs.ao = ao;
css->srs.fd = css->recv_fd;
css->srs.back_channel = true;
libxl__stream_read_start(egc, &css->srs);
css->cps.ao = ao;
if (colo_proxy_setup(&css->cps)) {
LOGD(ERROR, cds->domid, "COLO: failed to setup colo proxy for guest");
goto out;
}
if (init_device_subkind(cds))
goto out;
callbacks->suspend = libxl__colo_save_domain_suspend_callback;
callbacks->checkpoint = libxl__colo_save_domain_checkpoint_callback;
callbacks->postcopy = libxl__colo_save_domain_resume_callback;
callbacks->wait_checkpoint = libxl__colo_save_domain_wait_checkpoint_callback;
libxl__checkpoint_devices_setup(egc, &dss->cds);
return;
out:
dss->callback(egc, dss, ERROR_FAIL);
}
static void colo_save_setup_done(libxl__egc *egc,
libxl__checkpoint_devices_state *cds,
int rc)
{
libxl__colo_save_state *css = cds->concrete_data;
libxl__domain_save_state *dss = CONTAINER_OF(css, *dss, css);
EGC_GC;
if (!rc) {
libxl__domain_save(egc, dss);
return;
}
LOGD(ERROR, dss->domid, "COLO: failed to setup device for guest");
cds->callback = colo_save_setup_failed;
libxl__checkpoint_devices_teardown(egc, cds);
}
static void colo_save_setup_failed(libxl__egc *egc,
libxl__checkpoint_devices_state *cds,
int rc)
{
libxl__colo_save_state *css = cds->concrete_data;
libxl__domain_save_state *dss = CONTAINER_OF(css, *dss, css);
STATE_AO_GC(cds->ao);
if (rc)
LOGD(ERROR, cds->domid,
"COLO: failed to teardown device after setup failed"
" for guest, rc %d", rc);
cleanup_device_subkind(cds);
dss->callback(egc, dss, rc);
}
/* ================= colo: teardown save environment ================= */
static void colo_teardown_done(libxl__egc *egc,
libxl__checkpoint_devices_state *cds,
int rc);
void libxl__colo_save_teardown(libxl__egc *egc,
libxl__colo_save_state *css,
int rc)
{
libxl__domain_save_state *dss = CONTAINER_OF(css, *dss, css);
EGC_GC;
LOGD(WARN, dss->domid,
"COLO: Domain suspend terminated with rc %d,"
" teardown COLO devices...", rc);
libxl__stream_read_abort(egc, &css->srs, 1);
if (css->qdisk_setuped) {
libxl__qmp_stop_replication(gc, dss->domid, true);
css->qdisk_setuped = false;
}
dss->cds.callback = colo_teardown_done;
libxl__checkpoint_devices_teardown(egc, &dss->cds);
return;
}
static void colo_teardown_done(libxl__egc *egc,
libxl__checkpoint_devices_state *cds,
int rc)
{
libxl__colo_save_state *css = cds->concrete_data;
libxl__domain_save_state *dss = CONTAINER_OF(css, *dss, css);
cleanup_device_subkind(cds);
colo_proxy_teardown(&css->cps);
dss->callback(egc, dss, rc);
}
static void colo_common_write_stream_done(libxl__egc *egc,
libxl__stream_write_state *stream,
int rc);
static void colo_common_read_stream_done(libxl__egc *egc,
libxl__stream_read_state *stream,
int rc);
/* ===================== colo: suspend primary vm ===================== */
static void colo_read_svm_suspended_done(libxl__egc *egc,
libxl__colo_save_state *css,
int id);
/*
* Do the following things when suspending primary vm:
* 1. suspend primary vm
* 2. do postsuspend
* 3. read CHECKPOINT_SVM_SUSPENDED
* 4. read secondary vm's dirty pages
*/
static void colo_suspend_primary_vm_done(libxl__egc *egc,
libxl__domain_suspend_state *dsps,
int ok);
static void colo_postsuspend_cb(libxl__egc *egc,
libxl__checkpoint_devices_state *cds,
int rc);
static void libxl__colo_save_domain_suspend_callback(void *data)
{
libxl__save_helper_state *shs = data;
libxl__egc *egc = shs->egc;
libxl__stream_write_state *sws = CONTAINER_OF(shs, *sws, shs);
libxl__domain_save_state *dss = sws->dss;
/* Convenience aliases */
libxl__domain_suspend_state *dsps = &dss->dsps;
dsps->callback_common_done = colo_suspend_primary_vm_done;
libxl__domain_suspend(egc, dsps);
}
static void colo_suspend_primary_vm_done(libxl__egc *egc,
libxl__domain_suspend_state *dsps,
int rc)
{
libxl__domain_save_state *dss = CONTAINER_OF(dsps, *dss, dsps);
EGC_GC;
if (rc) {
LOGD(ERROR, dss->domid, "cannot suspend primary vm");
goto out;
}
/* Convenience aliases */
libxl__checkpoint_devices_state *const cds = &dss->cds;
cds->callback = colo_postsuspend_cb;
libxl__checkpoint_devices_postsuspend(egc, cds);
return;
out:
dss->rc = rc;
libxl__xc_domain_saverestore_async_callback_done(egc, &dss->sws.shs, !rc);
}
static void colo_postsuspend_cb(libxl__egc *egc,
libxl__checkpoint_devices_state *cds,
int rc)
{
libxl__colo_save_state *css = cds->concrete_data;
libxl__domain_save_state *dss = CONTAINER_OF(css, *dss, css);
EGC_GC;
if (rc) {
LOGD(ERROR, dss->domid, "postsuspend fails");
goto out;
}
if (!css->svm_running) {
rc = 0;
goto out;
}
/*
* read CHECKPOINT_SVM_SUSPENDED
*/
css->callback = colo_read_svm_suspended_done;
css->srs.checkpoint_callback = colo_common_read_stream_done;
libxl__stream_read_checkpoint_state(egc, &css->srs);
return;
out:
libxl__xc_domain_saverestore_async_callback_done(egc, &dss->sws.shs, !rc);
}
static void colo_read_svm_suspended_done(libxl__egc *egc,
libxl__colo_save_state *css,
int id)
{
int ok = 0;
libxl__domain_save_state *dss = CONTAINER_OF(css, *dss, css);
EGC_GC;
if (id != CHECKPOINT_SVM_SUSPENDED) {
LOGD(ERROR, dss->domid, "invalid section: %d, expected: %d", id,
CHECKPOINT_SVM_SUSPENDED);
goto out;
}
if (!css->paused &&
libxl__qmp_query_xen_replication_status(gc, dss->domid)) {
LOGD(ERROR, dss->domid,
"replication error occurs when primary vm is running");
goto out;
}
ok = 1;
out:
libxl__xc_domain_saverestore_async_callback_done(egc, &dss->sws.shs, ok);
}
/* ===================== colo: send tailbuf ========================== */
static void libxl__colo_save_domain_checkpoint_callback(void *data)
{
libxl__save_helper_state *shs = data;
libxl__stream_write_state *sws = CONTAINER_OF(shs, *sws, shs);
libxl__domain_save_state *dss = sws->dss;
/* Convenience aliases */
libxl__colo_save_state *const css = &dss->css;
/* write emulator xenstore data, emulator context, and checkpoint end */
css->callback = NULL;
dss->sws.checkpoint_callback = colo_common_write_stream_done;
libxl__stream_write_start_checkpoint(shs->egc, &dss->sws);
}
/* ===================== colo: resume primary vm ===================== */
/*
* Do the following things when resuming primary vm:
* 1. read CHECKPOINT_SVM_READY
* 2. do preresume
* 3. resume primary vm
* 4. read CHECKPOINT_SVM_RESUMED
*/
static void colo_read_svm_ready_done(libxl__egc *egc,
libxl__colo_save_state *css,
int id);
static void colo_preresume_cb(libxl__egc *egc,
libxl__checkpoint_devices_state *cds,
int rc);
static void colo_read_svm_resumed_done(libxl__egc *egc,
libxl__colo_save_state *css,
int id);
static void libxl__colo_save_domain_resume_callback(void *data)
{
libxl__save_helper_state *shs = data;
libxl__egc *egc = shs->egc;
libxl__stream_write_state *sws = CONTAINER_OF(shs, *sws, shs);
libxl__domain_save_state *dss = sws->dss;
/* Convenience aliases */
libxl__colo_save_state *const css = &dss->css;
EGC_GC;
/* read CHECKPOINT_SVM_READY */
css->callback = colo_read_svm_ready_done;
css->srs.checkpoint_callback = colo_common_read_stream_done;
libxl__stream_read_checkpoint_state(egc, &css->srs);
}
static void colo_read_svm_ready_done(libxl__egc *egc,
libxl__colo_save_state *css,
int id)
{
libxl__domain_save_state *dss = CONTAINER_OF(css, *dss, css);
EGC_GC;
if (id != CHECKPOINT_SVM_READY) {
LOGD(ERROR, dss->domid, "invalid section: %d, expected: %d", id,
CHECKPOINT_SVM_READY);
goto out;
}
colo_proxy_preresume(&css->cps);
css->svm_running = true;
dss->cds.callback = colo_preresume_cb;
libxl__checkpoint_devices_preresume(egc, &dss->cds);
return;
out:
libxl__xc_domain_saverestore_async_callback_done(egc, &dss->sws.shs, 0);
}
static void colo_preresume_cb(libxl__egc *egc,
libxl__checkpoint_devices_state *cds,
int rc)
{
libxl__colo_save_state *css = cds->concrete_data;
libxl__domain_save_state *dss = CONTAINER_OF(css, *dss, css);
EGC_GC;
if (rc) {
LOGD(ERROR, dss->domid, "preresume fails");
goto out;
}
if (css->qdisk_used && !css->qdisk_setuped) {
if (libxl__qmp_start_replication(gc, dss->domid, true)) {
LOGD(ERROR, dss->domid, "starting replication fails");
goto out;
}
css->qdisk_setuped = true;
}
if (!css->paused) {
if (libxl__qmp_colo_do_checkpoint(gc, dss->domid)) {
LOGD(ERROR, dss->domid, "doing checkpoint fails");
goto out;
}
}
/* Resumes the domain and the device model */
if (libxl__domain_resume_deprecated(gc, dss->domid, /* Fast Suspend */1)) {
LOGD(ERROR, dss->domid, "cannot resume primary vm");
goto out;
}
/*
* The guest should be paused before doing colo because there is
* no disk migration.
*/
if (css->paused) {
rc = libxl__domain_unpause_deprecated(gc, dss->domid);
if (rc) {
LOGD(ERROR, dss->domid, "cannot unpause primary vm");
goto out;
}
css->paused = false;
}
/* read CHECKPOINT_SVM_RESUMED */
css->callback = colo_read_svm_resumed_done;
css->srs.checkpoint_callback = colo_common_read_stream_done;
libxl__stream_read_checkpoint_state(egc, &css->srs);
return;
out:
libxl__xc_domain_saverestore_async_callback_done(egc, &dss->sws.shs, 0);
}
static void colo_read_svm_resumed_done(libxl__egc *egc,
libxl__colo_save_state *css,
int id)
{
int ok = 0;
libxl__domain_save_state *dss = CONTAINER_OF(css, *dss, css);
EGC_GC;
if (id != CHECKPOINT_SVM_RESUMED) {
LOGD(ERROR, dss->domid, "invalid section: %d, expected: %d", id,
CHECKPOINT_SVM_RESUMED);
goto out;
}
colo_proxy_postresume(&css->cps);
ok = 1;
out:
libxl__xc_domain_saverestore_async_callback_done(egc, &dss->sws.shs, ok);
}
/* ===================== colo: wait new checkpoint ===================== */
static void colo_start_new_checkpoint(libxl__egc *egc,
libxl__checkpoint_devices_state *cds,
int rc);
static void colo_proxy_async_wait_for_checkpoint(libxl__colo_save_state *css);
static void colo_proxy_async_call_done(libxl__egc *egc,
libxl__ev_child *child,
int pid,
int status);
static void colo_proxy_wait_for_checkpoint(libxl__egc *egc,
libxl__colo_save_state *css)
{
libxl__domain_save_state *dss = CONTAINER_OF(css, *dss, css);
ASYNC_CALL(egc, dss->cds.ao, &css->child, css,
colo_proxy_async_wait_for_checkpoint,
colo_proxy_async_call_done);
}
static void colo_proxy_async_wait_for_checkpoint(libxl__colo_save_state *css)
{
int req;
req = colo_proxy_checkpoint(&css->cps, COLO_PROXY_CHECKPOINT_TIMEOUT);
if (req < 0) {
/* some error happens */
_exit(1);
} else {
/* req == 0: no checkpoint is needed, do a checkpoint every 5s */
/* req > 0: net packets is not consistent, we need to start a
* checkpoint
*/
_exit(0);
}
}
static void colo_proxy_async_call_done(libxl__egc *egc,
libxl__ev_child *child,
int pid,
int status)
{
libxl__colo_save_state *css = CONTAINER_OF(child, *css, child);
libxl__domain_save_state *dss = CONTAINER_OF(css, *dss, css);
EGC_GC;
if (status) {
LOGD(ERROR, dss->domid, "failed to wait for new checkpoint");
colo_start_new_checkpoint(egc, &dss->cds, ERROR_FAIL);
return;
}
colo_start_new_checkpoint(egc, &dss->cds, 0);
}
/*
* Do the following things:
* 1. do commit
* 2. wait for a new checkpoint
* 3. write CHECKPOINT_NEW
*/
static void colo_device_commit_cb(libxl__egc *egc,
libxl__checkpoint_devices_state *cds,
int rc);
static void libxl__colo_save_domain_wait_checkpoint_callback(void *data)
{
libxl__save_helper_state *shs = data;
libxl__stream_write_state *sws = CONTAINER_OF(shs, *sws, shs);
libxl__domain_save_state *dss = sws->dss;
libxl__egc *egc = dss->sws.shs.egc;
/* Convenience aliases */
libxl__checkpoint_devices_state *const cds = &dss->cds;
cds->callback = colo_device_commit_cb;
libxl__checkpoint_devices_commit(egc, cds);
}
static void colo_device_commit_cb(libxl__egc *egc,
libxl__checkpoint_devices_state *cds,
int rc)
{
libxl__colo_save_state *css = cds->concrete_data;
libxl__domain_save_state *dss = CONTAINER_OF(css, *dss, css);
EGC_GC;
if (rc) {
LOGD(ERROR, dss->domid, "commit fails");
goto out;
}
colo_proxy_wait_for_checkpoint(egc, css);
return;
out:
libxl__xc_domain_saverestore_async_callback_done(egc, &dss->sws.shs, 0);
}
static void colo_start_new_checkpoint(libxl__egc *egc,
libxl__checkpoint_devices_state *cds,
int rc)
{
libxl__colo_save_state *css = cds->concrete_data;
libxl__domain_save_state *dss = CONTAINER_OF(css, *dss, css);
libxl_sr_checkpoint_state srcs = { .id = CHECKPOINT_NEW };
if (rc)
goto out;
/* write CHECKPOINT_NEW */
css->callback = NULL;
dss->sws.checkpoint_callback = colo_common_write_stream_done;
libxl__stream_write_checkpoint_state(egc, &dss->sws, &srcs);
return;
out:
libxl__xc_domain_saverestore_async_callback_done(egc, &dss->sws.shs, 0);
}
/* ===================== colo: common callback ===================== */
static void colo_common_write_stream_done(libxl__egc *egc,
libxl__stream_write_state *stream,
int rc)
{
libxl__domain_save_state *dss = CONTAINER_OF(stream, *dss, sws);
int ok;
/* Convenience aliases */
libxl__colo_save_state *const css = &dss->css;
EGC_GC;
if (rc < 0) {
/* TODO: it may be a internal error, but we don't know */
LOGD(ERROR, dss->domid, "sending data fails");
ok = 0;
goto out;
}
if (!css->callback) {
/* Everythins is OK */
ok = 1;
goto out;
}
css->callback(egc, css, 0);
return;
out:
libxl__xc_domain_saverestore_async_callback_done(egc, &dss->sws.shs, ok);
}
static void colo_common_read_stream_done(libxl__egc *egc,
libxl__stream_read_state *stream,
int rc)
{
libxl__colo_save_state *css = CONTAINER_OF(stream, *css, srs);
libxl__domain_save_state *dss = CONTAINER_OF(css, *dss, css);
int ok;
EGC_GC;
if (rc < 0) {
/* TODO: it may be a internal error, but we don't know */
LOGD(ERROR, dss->domid, "reading data fails");
ok = 0;
goto out;
}
if (!css->callback) {
/* Everythins is OK */
ok = 1;
goto out;
}
/* rc contains the id */
css->callback(egc, css, rc);
return;
out:
libxl__xc_domain_saverestore_async_callback_done(egc, &dss->sws.shs, ok);
}
| {
"pile_set_name": "Github"
} |
#include <stdio.h>
#include "../../../▲课本算法实现/▲10 内部排序/00 SequenceListType/SequenceListType.c"//**▲10 内部排序**//
/* 函数原型 */
void Algo_10_28(SqList_sort *L);
void PrintKey(KeyType e);
int main(int argc, char *argv[])
{
FILE *fp;
SqList_sort L;
printf("创建并输出一个任意序列...\n");
fp = fopen("Data/Algo_10_28.txt", "r");
CreateSortList(fp, &L);
Traverse(L, PrintKey);
printf("\n");
printf("将关键字按递增顺序排列...\n");
Algo_10_28(&L);
Traverse(L, PrintKey);
printf("\n");
return 0;
}
/*━━━━━━━━━━━┓
┃题10.28:双向起泡排序 ┃
┗━━━━━━━━━━━*/
void Algo_10_28(SqList_sort *L)
{
int k, start, end, cache, dir;
RcdType tmp;
Status tag;
dir = 1;
start = 1;
end = (*L).length;
while(1)
{
tag = FALSE;
for(k=start; k!=end; k=k+dir)
{
if(LT((*L).r[k+1].key, (*L).r[k].key))
{
tmp = (*L).r[k+1];
(*L).r[k+1] = (*L).r[k];
(*L).r[k] = tmp;
tag = TRUE;
}
}
if(!tag) //若遍历不发生交换,说明序列已经有序
break;
dir = -dir; //改变方向
cache = start;
start = end + 2*dir; //当前遍历起点与上次遍历终点的关系
end = cache + dir; //当前遍历终点与上次遍历起点的关系
}
}
void PrintKey(KeyType e)
{
printf("%d ", e);
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.