text
stringlengths 2
100k
| meta
dict |
---|---|
<?xml version="1.0"?>
<root>
<item>
<name>For Dvorak Users</name>
<item>
<name>──────────────────────────────</name>
<appendix>For Dvorak Input Source</appendix>
</item>
<item>
<name>Dvorak's Control+PNBF to Up/Down/Left/Right</name>
<appendix>(except Emacs, Terminal, Virtual, RDC, X11, Eclipse)</appendix>
<identifier>option.dvorak_emacsmode_controlPNBF</identifier>
<not>EMACS, TERMINAL, VIRTUALMACHINE, REMOTEDESKTOPCONNECTION, X11, ECLIPSE</not>
<autogen>__KeyToKey__ KeyCode::R, MODIFIERFLAG_EITHER_LEFT_OR_RIGHT_CONTROL, KeyCode::CURSOR_UP</autogen>
<autogen>__KeyToKey__ KeyCode::Y, MODIFIERFLAG_EITHER_LEFT_OR_RIGHT_CONTROL, KeyCode::CURSOR_RIGHT</autogen>
<autogen>__KeyToKey__ KeyCode::L, MODIFIERFLAG_EITHER_LEFT_OR_RIGHT_CONTROL, KeyCode::CURSOR_DOWN</autogen>
<autogen>__KeyToKey__ KeyCode::N, MODIFIERFLAG_EITHER_LEFT_OR_RIGHT_CONTROL, KeyCode::CURSOR_LEFT</autogen>
</item>
<item>
<name>Dvorak's Control+H to Delete</name>
<identifier>remap.dvorak_controlJ</identifier>
<autogen>__KeyToKey__ KeyCode::J, ModifierFlag::CONTROL_L, KeyCode::DELETE</autogen>
</item>
<item>
<name>Dvorak's Control+D to Forward Delete</name>
<identifier>remap.dvorak_controlH</identifier>
<autogen>__KeyToKey__ KeyCode::H, ModifierFlag::CONTROL_L, KeyCode::FORWARD_DELETE</autogen>
</item>
<item>
<name>Dvorak's Control+W to Option+Delete</name>
<appendix>(except Emacs, Terminal, X11, virtual machine, RDC, Eclipse)</appendix>
<identifier>option.dvorak_emacsmode_ex_controlW</identifier>
<not>EMACS, TERMINAL, VIRTUALMACHINE, REMOTEDESKTOPCONNECTION, X11, ECLIPSE</not>
<autogen>__KeyToKey__ KeyCode::COMMA, MODIFIERFLAG_EITHER_LEFT_OR_RIGHT_CONTROL, KeyCode::DELETE, ModifierFlag::OPTION_L</autogen>
</item>
<item>
<name>Swap U and I (== Swap Qwerty::F and Qwerty::G)</name>
<identifier>remap.dvorak_u2i</identifier>
<!-- Dvorak:U == Qwerty:F, Dvorak:I == Qwerty:G -->
<autogen>__KeyToKey__ KeyCode::F, KeyCode::G</autogen>
<autogen>__KeyToKey__ KeyCode::G, KeyCode::F</autogen>
</item>
<item>
<name>Make Cut, Quit work on Mac OS X using Dvorak layout in the same position as on QWERTY</name>
<appendix>Change Command_L+Q to Command_L+X (X in DV - i.e. Cut) </appendix>
<appendix>Change Command_L+' to Command_L+Q (Q in DV - i.e. Quit) </appendix>
<identifier>remap.cut_quit_dvorak_as_QWERTY</identifier>
<autogen>__KeyToKey__ KeyCode::X, ModifierFlag::COMMAND_L, KeyCode::B, ModifierFlag::COMMAND_L</autogen>
<autogen>__KeyToKey__ KeyCode::Q, ModifierFlag::COMMAND_L, KeyCode::X, ModifierFlag::COMMAND_L</autogen>
</item>
<item>
<name>Make Undo work on Mac OS X using Dvorak layout in the same position as on QWERTY (;)</name>
<appendix>Change Command_L+; to Command_L+Z (Z in DV - i.e. Undo) </appendix>
<identifier>remap.undo_dvorak_as_QWERTY</identifier>
<autogen>__KeyToKey__ KeyCode::Z, ModifierFlag::COMMAND_L, KeyCode::SLASH, ModifierFlag::COMMAND_L</autogen>
</item>
<item>
<name>Make Cut, Copy, Paste, Quit and Undo work on Mac OS X using Dvorak layout</name>
<appendix>in the same position as on QWERTY</appendix>
<appendix></appendix>
<appendix>Change Command_L+Q to Command_L+X (X in DV - i.e. Cut) </appendix>
<appendix>Change Command_L+J to Command_L+C (C in DV - i.e. Copy) </appendix>
<appendix>Change Command_L+K to Command_L+V (V in DV - i.e. Paste) </appendix>
<appendix>Change Command_L+; to Command_L+Z (Z in DV - i.e. Undo) </appendix>
<appendix>Change Command_L+' to Command_L+Q (Q in DV - i.e. Quit) </appendix>
<identifier>remap.cut_copy_paste_quit_undo_dvorak_as_QWERTY</identifier>
<autogen>__KeyToKey__ KeyCode::X, ModifierFlag::COMMAND_L, KeyCode::B, ModifierFlag::COMMAND_L</autogen>
<autogen>__KeyToKey__ KeyCode::C, ModifierFlag::COMMAND_L, KeyCode::I, ModifierFlag::COMMAND_L</autogen>
<autogen>__KeyToKey__ KeyCode::V, ModifierFlag::COMMAND_L, KeyCode::DOT, ModifierFlag::COMMAND_L</autogen>
<autogen>__KeyToKey__ KeyCode::Q, ModifierFlag::COMMAND_L, KeyCode::X, ModifierFlag::COMMAND_L</autogen>
<autogen>__KeyToKey__ KeyCode::Z, ModifierFlag::COMMAND_L, KeyCode::SLASH, ModifierFlag::COMMAND_L</autogen>
</item>
<item>
<name>──────────────────────────────</name>
<appendix>For U.S. Input Source</appendix>
</item>
<!-- ============================================================ -->
<!-- We must put "Use Dvorak Keyboard Layout" in the tail of Dvorak settings. -->
<item>
<name>Use Dvorak Keyboard Layout</name>
<appendix>(QWERTY to Dvorak)</appendix>
<identifier>remap.qwerty2dvorak</identifier>
<include path="snippets/dvorak.xml" />
</item>
<item>
<name>Use Dvorak (No Yubikeys)</name>
<appendix>(QWERTY to Dvorak)</appendix>
<appendix>(ignores Yubikeys)</appendix>
<identifier>remap.dvorak2qwerty_qwerty2dvoraknoyubico</identifier>
<device_not>DeviceVendor::YUBICO</device_not>
<include path="snippets/dvorak.xml" />
</item>
<item>
<name>Use Dvorak-Qwerty⌘</name>
<appendix>(QWERTY to Dvorak)</appendix>
<appendix>(+ Command+Keys to Qwerty)</appendix>
<identifier>remap.dvorak2qwerty_qwertycommand</identifier>
<modifier_not>
ModifierFlag::COMMAND_L,
ModifierFlag::COMMAND_R
</modifier_not>
<include path="snippets/dvorak.xml" />
</item>
<item>
<name>Use Dvorak - Qwerty Keyboard Layout</name>
<appendix>(QWERTY to Dvorak)</appendix>
<appendix>(+ Command,Control,Option+Keys to Qwerty)</appendix>
<identifier>remap.qwerty2dvorak_qwerty</identifier>
<modifier_not>
ModifierFlag::COMMAND_L,
ModifierFlag::COMMAND_R,
ModifierFlag::CONTROL_L,
ModifierFlag::CONTROL_R,
ModifierFlag::OPTION_L,
ModifierFlag::OPTION_R
</modifier_not>
<include path="snippets/dvorak.xml" />
</item>
<item>
<name>Use Dvorak Keyboard Layout</name>
<appendix>(QWERTY to Dvorak, except in password dialogue boxes)</appendix>
<identifier>remap.qwerty2dvorak_ex_password</identifier>
<not>PASSWORD</not>
<include path="snippets/dvorak.xml" />
</item>
<item>
<name>Use Dvorak - Qwerty Keyboard Layout</name>
<appendix>(QWERTY to Dvorak)</appendix>
<appendix>(+ Command,Control,Option+Keys to Qwerty)</appendix>
<appendix>(Except in password dialogue boxes)</appendix>
<identifier>remap.qwerty2dvorak_qwerty_ex_password</identifier>
<modifier_not>
ModifierFlag::COMMAND_L,
ModifierFlag::COMMAND_R,
ModifierFlag::CONTROL_L,
ModifierFlag::CONTROL_R,
ModifierFlag::OPTION_L,
ModifierFlag::OPTION_R,
ModifierFlag::FN
</modifier_not>
<not>PASSWORD</not>
<include path="snippets/dvorak.xml" />
</item>
<item>
<name>Use Dvorak Keyboard Layout</name>
<appendix>(QWERTY to Dvorak)</appendix>
<appendix>(+ Swap U and I)</appendix>
<identifier>remap.qwerty2dvorak_swap_ui</identifier>
<autogen>__KeyToKey__ KeyCode::Q, KeyCode::QUOTE</autogen>
<autogen>__KeyToKey__ KeyCode::W, KeyCode::COMMA</autogen>
<autogen>__KeyToKey__ KeyCode::E, KeyCode::DOT</autogen>
<autogen>__KeyToKey__ KeyCode::R, KeyCode::P</autogen>
<autogen>__KeyToKey__ KeyCode::T, KeyCode::Y</autogen>
<autogen>__KeyToKey__ KeyCode::Y, KeyCode::F</autogen>
<autogen>__KeyToKey__ KeyCode::U, KeyCode::G</autogen>
<autogen>__KeyToKey__ KeyCode::I, KeyCode::C</autogen>
<autogen>__KeyToKey__ KeyCode::O, KeyCode::R</autogen>
<autogen>__KeyToKey__ KeyCode::P, KeyCode::L</autogen>
<autogen>__KeyToKey__ KeyCode::BRACKET_LEFT, KeyCode::SLASH</autogen>
<autogen>__KeyToKey__ KeyCode::BRACKET_RIGHT, KeyCode::EQUAL</autogen>
<autogen>__KeyToKey__ KeyCode::S, KeyCode::O</autogen>
<autogen>__KeyToKey__ KeyCode::D, KeyCode::E</autogen>
<autogen>__KeyToKey__ KeyCode::F, KeyCode::I</autogen>
<autogen>__KeyToKey__ KeyCode::G, KeyCode::U</autogen>
<autogen>__KeyToKey__ KeyCode::H, KeyCode::D</autogen>
<autogen>__KeyToKey__ KeyCode::J, KeyCode::H</autogen>
<autogen>__KeyToKey__ KeyCode::K, KeyCode::T</autogen>
<autogen>__KeyToKey__ KeyCode::L, KeyCode::N</autogen>
<autogen>__KeyToKey__ KeyCode::SEMICOLON, KeyCode::S</autogen>
<autogen>__KeyToKey__ KeyCode::QUOTE, KeyCode::MINUS</autogen>
<autogen>__KeyToKey__ KeyCode::Z, KeyCode::SEMICOLON</autogen>
<autogen>__KeyToKey__ KeyCode::X, KeyCode::Q</autogen>
<autogen>__KeyToKey__ KeyCode::C, KeyCode::J</autogen>
<autogen>__KeyToKey__ KeyCode::V, KeyCode::K</autogen>
<autogen>__KeyToKey__ KeyCode::B, KeyCode::X</autogen>
<autogen>__KeyToKey__ KeyCode::N, KeyCode::B</autogen>
<autogen>__KeyToKey__ KeyCode::COMMA, KeyCode::W</autogen>
<autogen>__KeyToKey__ KeyCode::DOT, KeyCode::V</autogen>
<autogen>__KeyToKey__ KeyCode::SLASH, KeyCode::Z</autogen>
<autogen>__KeyToKey__ KeyCode::MINUS, KeyCode::BRACKET_LEFT</autogen>
<autogen>__KeyToKey__ KeyCode::EQUAL, KeyCode::BRACKET_RIGHT</autogen>
</item>
<item>
<name>Use Programmer Dvorak Keyboard Layout</name>
<appendix>(Change QWERTY to Programmer Dvorak)</appendix>
<identifier>remap.qwerty_to_programmer_dvorak</identifier>
<include path="snippets/programmer_dvorak.xml" />
</item>
<item>
<name>Use Programmer Dvorak - Qwerty Keyboard Layout</name>
<appendix>(Change QWERTY to Programmer Dvorak)</appendix>
<appendix>(+ Command, Control, Option + Keys to QWERTY)</appendix>
<identifier>remap.qwerty_to_programmer_dvorak_qwerty</identifier>
<modifier_not>
ModifierFlag::COMMAND_L,
ModifierFlag::COMMAND_R,
ModifierFlag::CONTROL_L,
ModifierFlag::CONTROL_R,
ModifierFlag::OPTION_L,
ModifierFlag::OPTION_R
</modifier_not>
<include path="snippets/programmer_dvorak.xml" />
</item>
</item>
</root>
| {
"pile_set_name": "Github"
} |
2
| {
"pile_set_name": "Github"
} |
#
# fontconfig/fc-lang/is.orth
#
# Copyright © 2002 Keith Packard
#
# Permission to use, copy, modify, distribute, and sell this software and its
# documentation for any purpose is hereby granted without fee, provided that
# the above copyright notice appear in all copies and that both that
# copyright notice and this permission notice appear in supporting
# documentation, and that the name of the author(s) not be used in
# advertising or publicity pertaining to distribution of the software without
# specific, written prior permission. The authors make no
# representations about the suitability of this software for any purpose. It
# is provided "as is" without express or implied warranty.
#
# THE AUTHOR(S) DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
# EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY SPECIAL, INDIRECT OR
# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
# DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
# TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
#
# Icelandic (IS)
#
# Sources:
# www.evertype.com
# www.eki.ee/letter
#
0041-005a
0061-007a
00c1
#00C4 # LATIN CAPITAL LETTER A WITH DIAERESIS evertype.com
#00C5 # LATIN CAPITAL LETTER A WITH RING ABOVE evertype.com
00c6
00c9
#00CB # LATIN CAPITAL LETTER E WITH DIAERESIS evertype.com
00cd
00d0
00d3
#00D6 # LATIN CAPITAL LETTER O WITH DIAERESIS eki.ee
#00D8 # LATIN CAPITAL LETTER O WITH STROKE evertype.com
00da
#00DC # LATIN CAPITAL LETTER U WITH DIAERESIS evertype.com
00dd
00de
00e1
#00E4 # LATIN SMALL LETTER A WITH DIAERESIS evertype.com
#00E5 # LATIN SMALL LETTER A WITH RING ABOVE evertype.com
00e6
00e9
00ed
00f0
00f3
#00F6 # LATIN SMALL LETTER O WITH DIAERESIS eki.ee
#00F8 # LATIN SMALL LETTER O WITH STROKE evertype.com
00fa
#00FC # LATIN SMALL LETTER U WITH DIAERESIS evertype.com
00fd
00fe
#2018 # single quote
#201a # single quote
#201c # double quote
#201e # double quote
| {
"pile_set_name": "Github"
} |
// Copyright 2008, 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:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 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 THE COPYRIGHT
// OWNER OR 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.
//
// Author: [email protected] (Preston Jackson)
//
// Google Test - FrameworkSample
// widget.cc
//
// Widget is a very simple class used for demonstrating the use of gtest
#include "widget.h"
Widget::Widget(int number, const std::string& name)
: number_(number),
name_(name) {}
Widget::~Widget() {}
float Widget::GetFloatValue() const {
return number_;
}
int Widget::GetIntValue() const {
return static_cast<int>(number_);
}
std::string Widget::GetStringValue() const {
return name_;
}
void Widget::GetCharPtrValue(char* buffer, size_t max_size) const {
// Copy the char* representation of name_ into buffer, up to max_size.
strncpy(buffer, name_.c_str(), max_size-1);
buffer[max_size-1] = '\0';
return;
}
| {
"pile_set_name": "Github"
} |
import { shareReplay as higherOrder } from '../operators/shareReplay';
/**
* @method shareReplay
* @owner Observable
*/
export function shareReplay(bufferSize, windowTime, scheduler) {
return higherOrder(bufferSize, windowTime, scheduler)(this);
}
;
//# sourceMappingURL=shareReplay.js.map | {
"pile_set_name": "Github"
} |
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8; c-indent-level: 8 -*- */
/*
* Copyright (C) 2004 Anders Carlsson <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <config.h>
#include "ev-utils.h"
#include "ev-file-helpers.h"
#include <string.h>
#include <math.h>
#include <glib/gi18n.h>
typedef struct
{
int size;
double *data;
} ConvFilter;
static double
gaussian (double x, double y, double r)
{
return ((1 / (2 * M_PI * r)) *
exp ((- (x * x + y * y)) / (2 * r * r)));
}
static ConvFilter *
create_blur_filter (int radius)
{
ConvFilter *filter;
int x, y;
double sum;
filter = g_new0 (ConvFilter, 1);
filter->size = radius * 2 + 1;
filter->data = g_new (double, filter->size * filter->size);
sum = 0.0;
for (y = 0 ; y < filter->size; y++)
{
for (x = 0 ; x < filter->size; x++)
{
sum += filter->data[y * filter->size + x] = gaussian (x - (filter->size >> 1),
y - (filter->size >> 1),
radius);
}
}
for (y = 0; y < filter->size; y++)
{
for (x = 0; x < filter->size; x++)
{
filter->data[y * filter->size + x] /= sum;
}
}
return filter;
}
static GdkPixbuf *
create_shadow (GdkPixbuf *src, int blur_radius,
int x_offset, int y_offset, double opacity)
{
int x, y, i, j;
int width, height;
GdkPixbuf *dest;
static ConvFilter *filter = NULL;
int src_rowstride, dest_rowstride;
int src_bpp, dest_bpp;
guchar *src_pixels, *dest_pixels;
if (!filter)
filter = create_blur_filter (blur_radius);
if (x_offset < 0)
x_offset = (blur_radius * 4) / 5;
if (y_offset < 0)
y_offset = (blur_radius * 4) / 5;
width = gdk_pixbuf_get_width (src) + blur_radius * 2 + x_offset;
height = gdk_pixbuf_get_height (src) + blur_radius * 2 + y_offset;
dest = gdk_pixbuf_new (gdk_pixbuf_get_colorspace (src), TRUE,
gdk_pixbuf_get_bits_per_sample (src),
width, height);
gdk_pixbuf_fill (dest, 0);
src_pixels = gdk_pixbuf_get_pixels (src);
src_rowstride = gdk_pixbuf_get_rowstride (src);
src_bpp = gdk_pixbuf_get_has_alpha (src) ? 4 : 3;
dest_pixels = gdk_pixbuf_get_pixels (dest);
dest_rowstride = gdk_pixbuf_get_rowstride (dest);
dest_bpp = gdk_pixbuf_get_has_alpha (dest) ? 4 : 3;
for (y = 0; y < height; y++)
{
for (x = 0; x < width; x++)
{
int sumr = 0, sumg = 0, sumb = 0, suma = 0;
for (i = 0; i < filter->size; i++)
{
for (j = 0; j < filter->size; j++)
{
int src_x, src_y;
src_y = -(blur_radius + x_offset) + y - (filter->size >> 1) + i;
src_x = -(blur_radius + y_offset) + x - (filter->size >> 1) + j;
if (src_y < 0 || src_y > gdk_pixbuf_get_height (src) ||
src_x < 0 || src_x > gdk_pixbuf_get_width (src))
continue;
sumr += src_pixels [src_y * src_rowstride +
src_x * src_bpp + 0] *
filter->data [i * filter->size + j];
sumg += src_pixels [src_y * src_rowstride +
src_x * src_bpp + 1] *
filter->data [i * filter->size + j];
sumb += src_pixels [src_y * src_rowstride +
src_x * src_bpp + 2] *
filter->data [i * filter->size + j];
if (src_bpp == 4)
suma += src_pixels [src_y * src_rowstride +
src_x * src_bpp + 3] *
filter->data [i * filter->size + j];
else
suma += 0xff;
}
}
if (dest_bpp == 4)
dest_pixels [y * dest_rowstride +
x * dest_bpp + 3] = (suma * opacity) / (filter->size * filter->size);
}
}
return dest;
}
GdkPixbuf *
ev_pixbuf_add_shadow (GdkPixbuf *src, int size,
int x_offset, int y_offset, double opacity)
{
GdkPixbuf *dest;
dest = create_shadow (src, size, x_offset, y_offset, opacity);
gdk_pixbuf_composite (src, dest,
size, size,
gdk_pixbuf_get_width (src),
gdk_pixbuf_get_height (src),
size, size,
1.0, 1.0,
GDK_INTERP_NEAREST, 255);
return dest;
}
/* Simple function to output the contents of a region. Used solely for testing
* the region code.
*/
void
ev_print_region_contents (cairo_region_t *region)
{
gint n_rectangles, i;
if (region == NULL) {
g_print ("<empty region>\n");
return;
}
g_print ("<region %p>\n", region);
n_rectangles = cairo_region_num_rectangles (region);
for (i = 0; i < n_rectangles; i++) {
GdkRectangle rect;
cairo_region_get_rectangle (region, i, &rect);
g_print ("\t(%d %d, %d %d) [%dx%d]\n",
rect.x,
rect.y,
rect.x + rect.width,
rect.y + rect.height,
rect.width,
rect.height);
}
}
/**
* ev_gui_menu_popup_at_tree_view_selection:
* @menu: a #GtkMenu to show
* @tree_view: a #GtkTreeView
*
* Opens a popup menu positioned at the currently selected row of @tree_view.
*/
void
ev_gui_menu_popup_at_tree_view_selection (GtkMenu *menu,
GtkTreeView *tree_view)
{
GtkTreeSelection *selection;
GList *selected_rows;
selection = gtk_tree_view_get_selection (tree_view);
selected_rows = gtk_tree_selection_get_selected_rows (selection, NULL);
if (selected_rows) {
GdkWindow *window;
GdkRectangle rect;
GtkAllocation allocation;
window = gtk_widget_get_window (GTK_WIDGET (tree_view));
gtk_tree_view_get_cell_area (tree_view, selected_rows->data,
NULL, &rect);
gtk_tree_view_convert_bin_window_to_widget_coords (tree_view, 0, rect.y,
NULL, &rect.y);
gtk_widget_get_allocation (GTK_WIDGET (tree_view), &allocation);
rect.width = allocation.width;
gtk_menu_popup_at_rect (menu, window, &rect,
GDK_GRAVITY_SOUTH_WEST,
GDK_GRAVITY_NORTH_WEST,
NULL);
g_list_free_full (selected_rows, (GDestroyNotify)gtk_tree_path_free);
} else {
gtk_menu_popup_at_widget (menu, GTK_WIDGET (tree_view),
GDK_GRAVITY_CENTER,
GDK_GRAVITY_CENTER,
NULL);
}
}
static void
file_filter_add_mime_types (GdkPixbufFormat *format, GtkFileFilter *filter,
GtkFileFilter *supported_filter)
{
gchar **mime_types;
gint i;
mime_types = gdk_pixbuf_format_get_mime_types (format);
for (i = 0; mime_types[i] != 0; i++) {
gtk_file_filter_add_mime_type (filter, mime_types[i]);
gtk_file_filter_add_mime_type (supported_filter, mime_types[i]);
}
g_strfreev (mime_types);
}
void
file_chooser_dialog_add_writable_pixbuf_formats (GtkFileChooser *chooser)
{
GSList *pixbuf_formats = NULL;
GSList *iter;
GtkFileFilter *filter, *supported_filter;
supported_filter = gtk_file_filter_new ();
gtk_file_filter_set_name (supported_filter, _("Supported Image Files"));
gtk_file_chooser_add_filter (chooser, supported_filter);
filter = gtk_file_filter_new ();
gtk_file_filter_set_name (filter, _("All Files"));
gtk_file_filter_add_pattern (filter, "*");
gtk_file_chooser_add_filter (chooser, filter);
pixbuf_formats = gdk_pixbuf_get_formats ();
for (iter = pixbuf_formats; iter; iter = iter->next) {
GdkPixbufFormat *format = iter->data;
gchar *name;
if (gdk_pixbuf_format_is_disabled (format) ||
!gdk_pixbuf_format_is_writable (format))
continue;
filter = gtk_file_filter_new ();
name = gdk_pixbuf_format_get_description (format);
gtk_file_filter_set_name (filter, name);
file_filter_add_mime_types (format, filter, supported_filter);
g_object_set_data (G_OBJECT(filter), "pixbuf-format", format);
gtk_file_chooser_add_filter (chooser, filter);
}
g_slist_free (pixbuf_formats);
}
GdkPixbufFormat*
get_gdk_pixbuf_format_by_extension (const gchar *uri)
{
GSList *pixbuf_formats = NULL;
GSList *iter;
int i;
pixbuf_formats = gdk_pixbuf_get_formats ();
for (iter = pixbuf_formats; iter; iter = iter->next) {
gchar **extension_list;
GdkPixbufFormat *format = iter->data;
if (gdk_pixbuf_format_is_disabled (format) ||
!gdk_pixbuf_format_is_writable (format))
continue;
extension_list = gdk_pixbuf_format_get_extensions (format);
for (i = 0; extension_list[i] != 0; i++) {
if (g_str_has_suffix (uri, extension_list[i])) {
g_slist_free (pixbuf_formats);
g_strfreev (extension_list);
return format;
}
}
g_strfreev (extension_list);
}
g_slist_free (pixbuf_formats);
return NULL;
}
/*
* Replace all occurrences of substr in str with repl
*
* @param str a string
* @param substr some string to replace
* @param repl a replacement string
*
* @return a newly allocated string with the substr replaced by repl; free with g_free
*/
gchar*
ev_str_replace (const char *str, const char *substr, const char *repl)
{
GString *gstr;
const char *cur;
if (str == NULL || substr == NULL || repl == NULL)
return NULL;
gstr = g_string_sized_new (2 * strlen (str));
for (cur = str; *cur; ++cur) {
if (g_str_has_prefix (cur, substr)) {
g_string_append (gstr, repl);
cur += strlen (substr) - 1;
} else
g_string_append_c (gstr, *cur);
}
return g_string_free (gstr, FALSE);
}
| {
"pile_set_name": "Github"
} |
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"WebMarkupMin": {
"Samples": {
"TextContentDirectoryPath": "../SharedData/text-content"
}
}
}
| {
"pile_set_name": "Github"
} |
POM_NAME=logback-ext-loggly
POM_ARTIFACT_ID=logback-ext-loggly
POM_PACKAGING=jar
POM_DESCRIPTION="Logback Extensions :: Loggly"
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2005-2011 Atheros Communications Inc.
* Copyright (c) 2011-2013 Qualcomm Atheros, Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef _HIF_H_
#define _HIF_H_
#include <linux/kernel.h>
#include "core.h"
struct ath10k_hif_cb {
int (*tx_completion)(struct ath10k *ar,
struct sk_buff *wbuf,
unsigned transfer_id);
int (*rx_completion)(struct ath10k *ar,
struct sk_buff *wbuf,
u8 pipe_id);
};
struct ath10k_hif_ops {
/* Send the head of a buffer to HIF for transmission to the target. */
int (*send_head)(struct ath10k *ar, u8 pipe_id,
unsigned int transfer_id,
unsigned int nbytes,
struct sk_buff *buf);
/*
* API to handle HIF-specific BMI message exchanges, this API is
* synchronous and only allowed to be called from a context that
* can block (sleep)
*/
int (*exchange_bmi_msg)(struct ath10k *ar,
void *request, u32 request_len,
void *response, u32 *response_len);
int (*start)(struct ath10k *ar);
void (*stop)(struct ath10k *ar);
int (*map_service_to_pipe)(struct ath10k *ar, u16 service_id,
u8 *ul_pipe, u8 *dl_pipe,
int *ul_is_polled, int *dl_is_polled);
void (*get_default_pipe)(struct ath10k *ar, u8 *ul_pipe, u8 *dl_pipe);
/*
* Check if prior sends have completed.
*
* Check whether the pipe in question has any completed
* sends that have not yet been processed.
* This function is only relevant for HIF pipes that are configured
* to be polled rather than interrupt-driven.
*/
void (*send_complete_check)(struct ath10k *ar, u8 pipe_id, int force);
void (*init)(struct ath10k *ar,
struct ath10k_hif_cb *callbacks);
u16 (*get_free_queue_number)(struct ath10k *ar, u8 pipe_id);
};
static inline int ath10k_hif_send_head(struct ath10k *ar, u8 pipe_id,
unsigned int transfer_id,
unsigned int nbytes,
struct sk_buff *buf)
{
return ar->hif.ops->send_head(ar, pipe_id, transfer_id, nbytes, buf);
}
static inline int ath10k_hif_exchange_bmi_msg(struct ath10k *ar,
void *request, u32 request_len,
void *response, u32 *response_len)
{
return ar->hif.ops->exchange_bmi_msg(ar, request, request_len,
response, response_len);
}
static inline int ath10k_hif_start(struct ath10k *ar)
{
return ar->hif.ops->start(ar);
}
static inline void ath10k_hif_stop(struct ath10k *ar)
{
return ar->hif.ops->stop(ar);
}
static inline int ath10k_hif_map_service_to_pipe(struct ath10k *ar,
u16 service_id,
u8 *ul_pipe, u8 *dl_pipe,
int *ul_is_polled,
int *dl_is_polled)
{
return ar->hif.ops->map_service_to_pipe(ar, service_id,
ul_pipe, dl_pipe,
ul_is_polled, dl_is_polled);
}
static inline void ath10k_hif_get_default_pipe(struct ath10k *ar,
u8 *ul_pipe, u8 *dl_pipe)
{
ar->hif.ops->get_default_pipe(ar, ul_pipe, dl_pipe);
}
static inline void ath10k_hif_send_complete_check(struct ath10k *ar,
u8 pipe_id, int force)
{
ar->hif.ops->send_complete_check(ar, pipe_id, force);
}
static inline void ath10k_hif_init(struct ath10k *ar,
struct ath10k_hif_cb *callbacks)
{
ar->hif.ops->init(ar, callbacks);
}
static inline u16 ath10k_hif_get_free_queue_number(struct ath10k *ar,
u8 pipe_id)
{
return ar->hif.ops->get_free_queue_number(ar, pipe_id);
}
#endif /* _HIF_H_ */
| {
"pile_set_name": "Github"
} |
# ansible-galaxy
> Crea e gestisci ruoli di Ansible.
> Maggiori informazioni: <https://docs.ansible.com/ansible/latest/cli/ansible-galaxy.html>.
- Installa un ruolo:
`ansible-galaxy install {{utente.ruolo}}`
- Rimuovi un ruolo:
`ansible-galaxy remove {{utente.ruolo}}`
- Elenca i ruoli installati:
`ansible-galaxy list`
- Cerca un determinato ruolo:
`ansible-galaxy search {{nome_ruolo}}`
- Crea un nuovo ruolo:
`ansible-galaxy init {{nome_nuovo_ruolo}}`
| {
"pile_set_name": "Github"
} |
require 'guard'
require 'guard/guard'
module Guard
class ForgeConfig < ::Guard::Guard
def initialize(watchers=[], options={})
super
end
# Called on Ctrl-Z signal
# This method should be mainly used for "reload" (really!) actions like reloading passenger/spork/bundler/...
def reload
UI.info "Reloading project config"
::Forge::Guard.project.load_config
end
# Called on Ctrl-\ signal
# This method should be principally used for long action like running all specs/tests/...
def run_all
UI.info "Reloading project config"
::Forge::Guard.project.load_config
true
end
# Called on file(s) modifications
def run_on_change(paths)
UI.info "Project config changed, reloading"
::Forge::Guard.project.load_config
::Forge::Guard.builder = ::Forge::Builder.new(::Forge::Guard.project)
# Rebuild everything if the config changes
::Forge::Guard.builder.build
end
end
end
| {
"pile_set_name": "Github"
} |
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
deinit {
println( {
extension NSData {
let a = [ {
class d {
func b {
for {
let d {
enum b {
class
case ,
| {
"pile_set_name": "Github"
} |
# cookie-signature
Sign and unsign cookies.
## Example
```js
var cookie = require('cookie-signature');
var val = cookie.sign('hello', 'tobiiscool');
val.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI');
var val = cookie.sign('hello', 'tobiiscool');
cookie.unsign(val, 'tobiiscool').should.equal('hello');
cookie.unsign(val, 'luna').should.be.false;
```
## License
(The MIT License)
Copyright (c) 2012 LearnBoost <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, 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. | {
"pile_set_name": "Github"
} |
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
nativeMin = Math.min;
/**
* Gets the view, applying any `transforms` to the `start` and `end` positions.
*
* @private
* @param {number} start The start of the view.
* @param {number} end The end of the view.
* @param {Array} transforms The transformations to apply to the view.
* @returns {Object} Returns an object containing the `start` and `end`
* positions of the view.
*/
function getView(start, end, transforms) {
var index = -1,
length = transforms.length;
while (++index < length) {
var data = transforms[index],
size = data.size;
switch (data.type) {
case 'drop': start += size; break;
case 'dropRight': end -= size; break;
case 'take': end = nativeMin(end, start + size); break;
case 'takeRight': start = nativeMax(start, end - size); break;
}
}
return { 'start': start, 'end': end };
}
module.exports = getView;
| {
"pile_set_name": "Github"
} |
/** Copyright 2019 Jakob Krude, Benjamin Worpitz
*
* This file is part of alpaka.
*
* 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/.
*/
#include "Defines.hpp"
#include "Buffer.hpp"
#include "Functor.hpp"
#include "DataGen.hpp"
#include <alpaka/test/acc/TestAccs.hpp>
#include <alpaka/test/queue/Queue.hpp>
#include <alpaka/test/KernelExecutionFixture.hpp>
#include <catch2/catch.hpp>
using TestAccs = alpaka::test::acc::EnabledAccs<
alpaka::dim::DimInt< 1u >,
std::size_t
>;
using Functors =
alpaka::meta::Concatenate<
alpaka::test::unit::math::UnaryFunctors,
alpaka::test::unit::math::BinaryFunctors
>;
using TestAccFunctorTuples =
alpaka::meta::CartesianProduct<
std::tuple,
TestAccs,
Functors
>;
using DataTypes = std::tuple<
float,
double
>;
struct TestKernel
{
//! @tparam TAcc Accelerator.
//! @tparam TFunctor Functor defined in Functor.hpp.
//! @param acc Accelerator given from alpaka.
//! @param functor Accessible with operator().
ALPAKA_NO_HOST_ACC_WARNING
template<typename TAcc,
typename TResults,
typename TFunctor,
typename TArgs>
ALPAKA_FN_ACC auto operator()(
TAcc const & acc,
TResults const & results,
TFunctor const & functor,
TArgs const & args) const noexcept
-> void
{
for( size_t i = 0; i < TArgs::capacity; ++i )
{
results(i, acc) = functor(args(i, acc), acc);
}
}
};
//#############################################################################
template<
typename TAcc,
typename TFunctor>
struct TestTemplate
{
template<
typename TData>
auto operator()() -> void
{
std::random_device rd{};
auto const seed = rd();
std::cout << "testing"
<< " acc:" << typeid(TAcc).name()
<< " data type:" << typeid(TData).name()
<< " functor:" << typeid(TFunctor).name()
<< " seed:" << seed
<< std::endl;
// SETUP (defines and initialising)
// DevAcc and DevHost are defined in Buffer.hpp too.
using DevAcc = alpaka::dev::Dev< TAcc >;
using DevHost = alpaka::dev::DevCpu;
using PltfAcc = alpaka::pltf::Pltf< DevAcc >;
using PltfHost = alpaka::pltf::Pltf< DevHost >;
using Dim = alpaka::dim::DimInt< 1u >;
using Idx = std::size_t;
using WorkDiv = alpaka::workdiv::WorkDivMembers<Dim, Idx>;
using QueueAcc = alpaka::test::queue::DefaultQueue< DevAcc >;
using TArgsItem = alpaka::test::unit::math::ArgsItem<TData, TFunctor::arity>;
static constexpr auto capacity = 1000;
using Args = alpaka::test::unit::math::Buffer<
TAcc,
TArgsItem,
capacity
>;
using Results = alpaka::test::unit::math::Buffer<
TAcc,
TData,
capacity
>;
// Every functor is executed individual on one kernel.
static constexpr size_t elementsPerThread = 1u;
static constexpr size_t sizeExtent = 1u;
DevAcc const devAcc{ alpaka::pltf::getDevByIdx< PltfAcc >( 0u ) };
DevHost const devHost{ alpaka::pltf::getDevByIdx< PltfHost >( 0u ) };
QueueAcc queue{ devAcc };
TestKernel kernel;
TFunctor functor;
Args args{ devAcc };
Results results{ devAcc };
WorkDiv const workDiv{
alpaka::workdiv::getValidWorkDiv< TAcc >(
devAcc,
sizeExtent,
elementsPerThread,
false,
alpaka::workdiv::GridBlockExtentSubDivRestrictions::Unrestricted
)};
// SETUP COMPLETED.
// Fill the buffer with random test-numbers.
alpaka::test::unit::math::fillWithRndArgs<TData>( args, functor, seed );
for( size_t i = 0; i < Results::capacity; ++i )
results(i) = static_cast<TData>(std::nan( "" ));
// Copy both buffer to the device
args.copyToDevice(queue);
results.copyToDevice(queue);
auto const taskKernel(
alpaka::kernel::createTaskKernel< TAcc >(
workDiv,
kernel,
results,
functor,
args
)
);
// Enqueue the kernel execution task.
alpaka::queue::enqueue( queue, taskKernel );
// Copy back the results (encapsulated in the buffer class).
results.copyFromDevice( queue );
alpaka::wait::wait( queue );
std::cout.precision( std::numeric_limits<TData>::digits10 + 1 );
INFO("Operator: " << functor)
INFO("Type: " << typeid( TData ).name() ) // Compiler specific.
#if ALPAKA_DEBUG_FULL
INFO("The args buffer: \n" << std::setprecision(
std::numeric_limits<TData>::digits10 + 1)
<< args << "\n")
#endif
for( size_t i = 0; i < Args::capacity; ++i )
{
INFO("Idx i: " << i)
TData std_result = functor(args(i));
REQUIRE( results(i) == Approx(std_result) );
}
}
};
TEMPLATE_LIST_TEST_CASE("mathOps", "[math] [operator]", TestAccFunctorTuples)
{
/*
* All alpaka::math:: functions are tested here except sincos.
* The function will be called with a buffer from the custom Buffer class.
* This argument Buffer contains ArgsItems from Defines.hpp and can be
* accessed with the overloaded operator().
* The args Buffer looks similar like [[0, 1], [2, 3], [4, 5]],
* where every sub-list makes one functor-call so the result Buffer would be:
* [f(0, 1), f(2, 3), f(4, 5)].
* The results are saved in a different Buffer witch contains plain data.
* The results are than compared to the result of a std:: implementation.
* The default result is nan and should fail a test.
*
* BE AWARE that:
* - ALPAKA_CUDA_FAST_MATH should be disabled
* - not all casts between float and double can be detected.
* - no explicit edge cases are tested, rather than 0, maximum and minimum
* - but it is easy to add a new Range:: enum-type with custom edge cases
* - some tests may fail if ALPAKA_CUDA_FAST_MATH is turned on
* - nan typically fails every test, but could be normal defined behaviour
* - inf/-inf typically dont fail a test
* - for easy debugging the << operator is overloaded for Buffer objects
* - arguments are generated between 0 and 1000
* and the default argument-buffer-extent is 1000
* The arguments are generated in DataGen.hpp and can easily be modified.
* The arguments depend on the Range:: enum-type specified for each functor.
* ----------------------------------------------------------------------
* - each functor has an arity and a array of ranges
* - there is one args Buffer and one results Buffer
* - each buffer encapsulated the host/device communication
* - as well as the data access and the initialisation
* - all operators are tested independent, one per kernel
* - tests the results against the std implementation ( catch REQUIRES)
*
* TestKernel
* - uses the alpaka::math:: option from the functor
* - uses the device-buffer option from the args
*
* EXTENSIBILITY:
* - Add new operators in Functor.hpp and add them to the ...Functors tuple.
* - Add a new Range:: enum-type in Defines.hpp
* - specify a fill-method in DataGen.hpp
* - Add a new Arity:: enum-type in Defines.hpp
* - add a matching operator() function in Functor.hpp,
* - add a new ...Functors tuple
* - call alpaka::meta::forEachType with the tuple in ForEachFunctor
*/
using Acc = std::tuple_element_t<0u, TestType>;
using Functor = std::tuple_element_t<1u, TestType>;
alpaka::meta::forEachType< DataTypes >(
TestTemplate< Acc, Functor >());
}
| {
"pile_set_name": "Github"
} |
.container-fluid,
.container {
margin-right: auto;
margin-left: auto;
}
.container-fluid {
padding-right: 2rem;
padding-left: 2rem;
}
.row {
box-sizing: border-box;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-flex: 0;
-webkit-flex: 0 1 auto;
-ms-flex: 0 1 auto;
flex: 0 1 auto;
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-flex-wrap: wrap;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
margin-right: -0.5rem;
margin-left: -0.5rem;
}
.row.reverse {
-webkit-box-orient: horizontal;
-webkit-box-direction: reverse;
-webkit-flex-direction: row-reverse;
-ms-flex-direction: row-reverse;
flex-direction: row-reverse;
}
.col.reverse {
-webkit-box-orient: vertical;
-webkit-box-direction: reverse;
-webkit-flex-direction: column-reverse;
-ms-flex-direction: column-reverse;
flex-direction: column-reverse;
}
.col-xs,
.col-xs-1,
.col-xs-2,
.col-xs-3,
.col-xs-4,
.col-xs-5,
.col-xs-6,
.col-xs-7,
.col-xs-8,
.col-xs-9,
.col-xs-10,
.col-xs-11,
.col-xs-12,
.col-xs-offset-1,
.col-xs-offset-2,
.col-xs-offset-3,
.col-xs-offset-4,
.col-xs-offset-5,
.col-xs-offset-6,
.col-xs-offset-7,
.col-xs-offset-8,
.col-xs-offset-9,
.col-xs-offset-10,
.col-xs-offset-11,
.col-xs-offset-12 {
box-sizing: border-box;
-webkit-box-flex: 0;
-webkit-flex: 0 0 auto;
-ms-flex: 0 0 auto;
flex: 0 0 auto;
padding-right: 0.5rem;
padding-left: 0.5rem;
}
.col-xs {
-webkit-box-flex: 1;
-webkit-flex-grow: 1;
-ms-flex-positive: 1;
flex-grow: 1;
-webkit-flex-basis: 0;
-ms-flex-preferred-size: 0;
flex-basis: 0;
max-width: 100%;
}
.col-xs-1 {
-webkit-flex-basis: 8.333%;
-ms-flex-preferred-size: 8.333%;
flex-basis: 8.333%;
max-width: 8.333%;
}
.col-xs-2 {
-webkit-flex-basis: 16.667%;
-ms-flex-preferred-size: 16.667%;
flex-basis: 16.667%;
max-width: 16.667%;
}
.col-xs-3 {
-webkit-flex-basis: 25%;
-ms-flex-preferred-size: 25%;
flex-basis: 25%;
max-width: 25%;
}
.col-xs-4 {
-webkit-flex-basis: 33.333%;
-ms-flex-preferred-size: 33.333%;
flex-basis: 33.333%;
max-width: 33.333%;
}
.col-xs-5 {
-webkit-flex-basis: 41.667%;
-ms-flex-preferred-size: 41.667%;
flex-basis: 41.667%;
max-width: 41.667%;
}
.col-xs-6 {
-webkit-flex-basis: 50%;
-ms-flex-preferred-size: 50%;
flex-basis: 50%;
max-width: 50%;
}
.col-xs-7 {
-webkit-flex-basis: 58.333%;
-ms-flex-preferred-size: 58.333%;
flex-basis: 58.333%;
max-width: 58.333%;
}
.col-xs-8 {
-webkit-flex-basis: 66.667%;
-ms-flex-preferred-size: 66.667%;
flex-basis: 66.667%;
max-width: 66.667%;
}
.col-xs-9 {
-webkit-flex-basis: 75%;
-ms-flex-preferred-size: 75%;
flex-basis: 75%;
max-width: 75%;
}
.col-xs-10 {
-webkit-flex-basis: 83.333%;
-ms-flex-preferred-size: 83.333%;
flex-basis: 83.333%;
max-width: 83.333%;
}
.col-xs-11 {
-webkit-flex-basis: 91.667%;
-ms-flex-preferred-size: 91.667%;
flex-basis: 91.667%;
max-width: 91.667%;
}
.col-xs-12 {
-webkit-flex-basis: 100%;
-ms-flex-preferred-size: 100%;
flex-basis: 100%;
max-width: 100%;
}
.col-xs-offset-1 {
margin-left: 8.333%;
}
.col-xs-offset-2 {
margin-left: 16.667%;
}
.col-xs-offset-3 {
margin-left: 25%;
}
.col-xs-offset-4 {
margin-left: 33.333%;
}
.col-xs-offset-5 {
margin-left: 41.667%;
}
.col-xs-offset-6 {
margin-left: 50%;
}
.col-xs-offset-7 {
margin-left: 58.333%;
}
.col-xs-offset-8 {
margin-left: 66.667%;
}
.col-xs-offset-9 {
margin-left: 75%;
}
.col-xs-offset-10 {
margin-left: 83.333%;
}
.col-xs-offset-11 {
margin-left: 91.667%;
}
.start-xs {
-webkit-box-pack: start;
-webkit-justify-content: flex-start;
-ms-flex-pack: start;
justify-content: flex-start;
text-align: start;
}
.center-xs {
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
text-align: center;
}
.end-xs {
-webkit-box-pack: end;
-webkit-justify-content: flex-end;
-ms-flex-pack: end;
justify-content: flex-end;
text-align: end;
}
.top-xs {
-webkit-box-align: start;
-webkit-align-items: flex-start;
-ms-flex-align: start;
align-items: flex-start;
}
.middle-xs {
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
}
.bottom-xs {
-webkit-box-align: end;
-webkit-align-items: flex-end;
-ms-flex-align: end;
align-items: flex-end;
}
.around-xs {
-webkit-justify-content: space-around;
-ms-flex-pack: distribute;
justify-content: space-around;
}
.between-xs {
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
}
.first-xs {
-webkit-box-ordinal-group: 0;
-webkit-order: -1;
-ms-flex-order: -1;
order: -1;
}
.last-xs {
-webkit-box-ordinal-group: 2;
-webkit-order: 1;
-ms-flex-order: 1;
order: 1;
}
@media only screen and (min-width: 48em) {
.container {
width: 49rem;
}
.col-sm,
.col-sm-1,
.col-sm-2,
.col-sm-3,
.col-sm-4,
.col-sm-5,
.col-sm-6,
.col-sm-7,
.col-sm-8,
.col-sm-9,
.col-sm-10,
.col-sm-11,
.col-sm-12,
.col-sm-offset-1,
.col-sm-offset-2,
.col-sm-offset-3,
.col-sm-offset-4,
.col-sm-offset-5,
.col-sm-offset-6,
.col-sm-offset-7,
.col-sm-offset-8,
.col-sm-offset-9,
.col-sm-offset-10,
.col-sm-offset-11,
.col-sm-offset-12 {
box-sizing: border-box;
-webkit-box-flex: 0;
-webkit-flex: 0 0 auto;
-ms-flex: 0 0 auto;
flex: 0 0 auto;
padding-right: 0.5rem;
padding-left: 0.5rem;
}
.col-sm {
-webkit-box-flex: 1;
-webkit-flex-grow: 1;
-ms-flex-positive: 1;
flex-grow: 1;
-webkit-flex-basis: 0;
-ms-flex-preferred-size: 0;
flex-basis: 0;
max-width: 100%;
}
.col-sm-1 {
-webkit-flex-basis: 8.333%;
-ms-flex-preferred-size: 8.333%;
flex-basis: 8.333%;
max-width: 8.333%;
}
.col-sm-2 {
-webkit-flex-basis: 16.667%;
-ms-flex-preferred-size: 16.667%;
flex-basis: 16.667%;
max-width: 16.667%;
}
.col-sm-3 {
-webkit-flex-basis: 25%;
-ms-flex-preferred-size: 25%;
flex-basis: 25%;
max-width: 25%;
}
.col-sm-4 {
-webkit-flex-basis: 33.333%;
-ms-flex-preferred-size: 33.333%;
flex-basis: 33.333%;
max-width: 33.333%;
}
.col-sm-5 {
-webkit-flex-basis: 41.667%;
-ms-flex-preferred-size: 41.667%;
flex-basis: 41.667%;
max-width: 41.667%;
}
.col-sm-6 {
-webkit-flex-basis: 50%;
-ms-flex-preferred-size: 50%;
flex-basis: 50%;
max-width: 50%;
}
.col-sm-7 {
-webkit-flex-basis: 58.333%;
-ms-flex-preferred-size: 58.333%;
flex-basis: 58.333%;
max-width: 58.333%;
}
.col-sm-8 {
-webkit-flex-basis: 66.667%;
-ms-flex-preferred-size: 66.667%;
flex-basis: 66.667%;
max-width: 66.667%;
}
.col-sm-9 {
-webkit-flex-basis: 75%;
-ms-flex-preferred-size: 75%;
flex-basis: 75%;
max-width: 75%;
}
.col-sm-10 {
-webkit-flex-basis: 83.333%;
-ms-flex-preferred-size: 83.333%;
flex-basis: 83.333%;
max-width: 83.333%;
}
.col-sm-11 {
-webkit-flex-basis: 91.667%;
-ms-flex-preferred-size: 91.667%;
flex-basis: 91.667%;
max-width: 91.667%;
}
.col-sm-12 {
-webkit-flex-basis: 100%;
-ms-flex-preferred-size: 100%;
flex-basis: 100%;
max-width: 100%;
}
.col-sm-offset-1 {
margin-left: 8.333%;
}
.col-sm-offset-2 {
margin-left: 16.667%;
}
.col-sm-offset-3 {
margin-left: 25%;
}
.col-sm-offset-4 {
margin-left: 33.333%;
}
.col-sm-offset-5 {
margin-left: 41.667%;
}
.col-sm-offset-6 {
margin-left: 50%;
}
.col-sm-offset-7 {
margin-left: 58.333%;
}
.col-sm-offset-8 {
margin-left: 66.667%;
}
.col-sm-offset-9 {
margin-left: 75%;
}
.col-sm-offset-10 {
margin-left: 83.333%;
}
.col-sm-offset-11 {
margin-left: 91.667%;
}
.start-sm {
-webkit-box-pack: start;
-webkit-justify-content: flex-start;
-ms-flex-pack: start;
justify-content: flex-start;
text-align: start;
}
.center-sm {
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
text-align: center;
}
.end-sm {
-webkit-box-pack: end;
-webkit-justify-content: flex-end;
-ms-flex-pack: end;
justify-content: flex-end;
text-align: end;
}
.top-sm {
-webkit-box-align: start;
-webkit-align-items: flex-start;
-ms-flex-align: start;
align-items: flex-start;
}
.middle-sm {
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
}
.bottom-sm {
-webkit-box-align: end;
-webkit-align-items: flex-end;
-ms-flex-align: end;
align-items: flex-end;
}
.around-sm {
-webkit-justify-content: space-around;
-ms-flex-pack: distribute;
justify-content: space-around;
}
.between-sm {
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
}
.first-sm {
-webkit-box-ordinal-group: 0;
-webkit-order: -1;
-ms-flex-order: -1;
order: -1;
}
.last-sm {
-webkit-box-ordinal-group: 2;
-webkit-order: 1;
-ms-flex-order: 1;
order: 1;
}
}
@media only screen and (min-width: 64em) {
.container {
width: 65rem;
}
.col-md,
.col-md-1,
.col-md-2,
.col-md-3,
.col-md-4,
.col-md-5,
.col-md-6,
.col-md-7,
.col-md-8,
.col-md-9,
.col-md-10,
.col-md-11,
.col-md-12,
.col-md-offset-1,
.col-md-offset-2,
.col-md-offset-3,
.col-md-offset-4,
.col-md-offset-5,
.col-md-offset-6,
.col-md-offset-7,
.col-md-offset-8,
.col-md-offset-9,
.col-md-offset-10,
.col-md-offset-11,
.col-md-offset-12 {
box-sizing: border-box;
-webkit-box-flex: 0;
-webkit-flex: 0 0 auto;
-ms-flex: 0 0 auto;
flex: 0 0 auto;
padding-right: 0.5rem;
padding-left: 0.5rem;
}
.col-md {
-webkit-box-flex: 1;
-webkit-flex-grow: 1;
-ms-flex-positive: 1;
flex-grow: 1;
-webkit-flex-basis: 0;
-ms-flex-preferred-size: 0;
flex-basis: 0;
max-width: 100%;
}
.col-md-1 {
-webkit-flex-basis: 8.333%;
-ms-flex-preferred-size: 8.333%;
flex-basis: 8.333%;
max-width: 8.333%;
}
.col-md-2 {
-webkit-flex-basis: 16.667%;
-ms-flex-preferred-size: 16.667%;
flex-basis: 16.667%;
max-width: 16.667%;
}
.col-md-3 {
-webkit-flex-basis: 25%;
-ms-flex-preferred-size: 25%;
flex-basis: 25%;
max-width: 25%;
}
.col-md-4 {
-webkit-flex-basis: 33.333%;
-ms-flex-preferred-size: 33.333%;
flex-basis: 33.333%;
max-width: 33.333%;
}
.col-md-5 {
-webkit-flex-basis: 41.667%;
-ms-flex-preferred-size: 41.667%;
flex-basis: 41.667%;
max-width: 41.667%;
}
.col-md-6 {
-webkit-flex-basis: 50%;
-ms-flex-preferred-size: 50%;
flex-basis: 50%;
max-width: 50%;
}
.col-md-7 {
-webkit-flex-basis: 58.333%;
-ms-flex-preferred-size: 58.333%;
flex-basis: 58.333%;
max-width: 58.333%;
}
.col-md-8 {
-webkit-flex-basis: 66.667%;
-ms-flex-preferred-size: 66.667%;
flex-basis: 66.667%;
max-width: 66.667%;
}
.col-md-9 {
-webkit-flex-basis: 75%;
-ms-flex-preferred-size: 75%;
flex-basis: 75%;
max-width: 75%;
}
.col-md-10 {
-webkit-flex-basis: 83.333%;
-ms-flex-preferred-size: 83.333%;
flex-basis: 83.333%;
max-width: 83.333%;
}
.col-md-11 {
-webkit-flex-basis: 91.667%;
-ms-flex-preferred-size: 91.667%;
flex-basis: 91.667%;
max-width: 91.667%;
}
.col-md-12 {
-webkit-flex-basis: 100%;
-ms-flex-preferred-size: 100%;
flex-basis: 100%;
max-width: 100%;
}
.col-md-offset-1 {
margin-left: 8.333%;
}
.col-md-offset-2 {
margin-left: 16.667%;
}
.col-md-offset-3 {
margin-left: 25%;
}
.col-md-offset-4 {
margin-left: 33.333%;
}
.col-md-offset-5 {
margin-left: 41.667%;
}
.col-md-offset-6 {
margin-left: 50%;
}
.col-md-offset-7 {
margin-left: 58.333%;
}
.col-md-offset-8 {
margin-left: 66.667%;
}
.col-md-offset-9 {
margin-left: 75%;
}
.col-md-offset-10 {
margin-left: 83.333%;
}
.col-md-offset-11 {
margin-left: 91.667%;
}
.start-md {
-webkit-box-pack: start;
-webkit-justify-content: flex-start;
-ms-flex-pack: start;
justify-content: flex-start;
text-align: start;
}
.center-md {
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
text-align: center;
}
.end-md {
-webkit-box-pack: end;
-webkit-justify-content: flex-end;
-ms-flex-pack: end;
justify-content: flex-end;
text-align: end;
}
.top-md {
-webkit-box-align: start;
-webkit-align-items: flex-start;
-ms-flex-align: start;
align-items: flex-start;
}
.middle-md {
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
}
.bottom-md {
-webkit-box-align: end;
-webkit-align-items: flex-end;
-ms-flex-align: end;
align-items: flex-end;
}
.around-md {
-webkit-justify-content: space-around;
-ms-flex-pack: distribute;
justify-content: space-around;
}
.between-md {
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
}
.first-md {
-webkit-box-ordinal-group: 0;
-webkit-order: -1;
-ms-flex-order: -1;
order: -1;
}
.last-md {
-webkit-box-ordinal-group: 2;
-webkit-order: 1;
-ms-flex-order: 1;
order: 1;
}
}
@media only screen and (min-width: 75em) {
.container {
width: 76rem;
}
.col-lg,
.col-lg-1,
.col-lg-2,
.col-lg-3,
.col-lg-4,
.col-lg-5,
.col-lg-6,
.col-lg-7,
.col-lg-8,
.col-lg-9,
.col-lg-10,
.col-lg-11,
.col-lg-12,
.col-lg-offset-1,
.col-lg-offset-2,
.col-lg-offset-3,
.col-lg-offset-4,
.col-lg-offset-5,
.col-lg-offset-6,
.col-lg-offset-7,
.col-lg-offset-8,
.col-lg-offset-9,
.col-lg-offset-10,
.col-lg-offset-11,
.col-lg-offset-12 {
box-sizing: border-box;
-webkit-box-flex: 0;
-webkit-flex: 0 0 auto;
-ms-flex: 0 0 auto;
flex: 0 0 auto;
padding-right: 0.5rem;
padding-left: 0.5rem;
}
.col-lg {
-webkit-box-flex: 1;
-webkit-flex-grow: 1;
-ms-flex-positive: 1;
flex-grow: 1;
-webkit-flex-basis: 0;
-ms-flex-preferred-size: 0;
flex-basis: 0;
max-width: 100%;
}
.col-lg-1 {
-webkit-flex-basis: 8.333%;
-ms-flex-preferred-size: 8.333%;
flex-basis: 8.333%;
max-width: 8.333%;
}
.col-lg-2 {
-webkit-flex-basis: 16.667%;
-ms-flex-preferred-size: 16.667%;
flex-basis: 16.667%;
max-width: 16.667%;
}
.col-lg-3 {
-webkit-flex-basis: 25%;
-ms-flex-preferred-size: 25%;
flex-basis: 25%;
max-width: 25%;
}
.col-lg-4 {
-webkit-flex-basis: 33.333%;
-ms-flex-preferred-size: 33.333%;
flex-basis: 33.333%;
max-width: 33.333%;
}
.col-lg-5 {
-webkit-flex-basis: 41.667%;
-ms-flex-preferred-size: 41.667%;
flex-basis: 41.667%;
max-width: 41.667%;
}
.col-lg-6 {
-webkit-flex-basis: 50%;
-ms-flex-preferred-size: 50%;
flex-basis: 50%;
max-width: 50%;
}
.col-lg-7 {
-webkit-flex-basis: 58.333%;
-ms-flex-preferred-size: 58.333%;
flex-basis: 58.333%;
max-width: 58.333%;
}
.col-lg-8 {
-webkit-flex-basis: 66.667%;
-ms-flex-preferred-size: 66.667%;
flex-basis: 66.667%;
max-width: 66.667%;
}
.col-lg-9 {
-webkit-flex-basis: 75%;
-ms-flex-preferred-size: 75%;
flex-basis: 75%;
max-width: 75%;
}
.col-lg-10 {
-webkit-flex-basis: 83.333%;
-ms-flex-preferred-size: 83.333%;
flex-basis: 83.333%;
max-width: 83.333%;
}
.col-lg-11 {
-webkit-flex-basis: 91.667%;
-ms-flex-preferred-size: 91.667%;
flex-basis: 91.667%;
max-width: 91.667%;
}
.col-lg-12 {
-webkit-flex-basis: 100%;
-ms-flex-preferred-size: 100%;
flex-basis: 100%;
max-width: 100%;
}
.col-lg-offset-1 {
margin-left: 8.333%;
}
.col-lg-offset-2 {
margin-left: 16.667%;
}
.col-lg-offset-3 {
margin-left: 25%;
}
.col-lg-offset-4 {
margin-left: 33.333%;
}
.col-lg-offset-5 {
margin-left: 41.667%;
}
.col-lg-offset-6 {
margin-left: 50%;
}
.col-lg-offset-7 {
margin-left: 58.333%;
}
.col-lg-offset-8 {
margin-left: 66.667%;
}
.col-lg-offset-9 {
margin-left: 75%;
}
.col-lg-offset-10 {
margin-left: 83.333%;
}
.col-lg-offset-11 {
margin-left: 91.667%;
}
.start-lg {
-webkit-box-pack: start;
-webkit-justify-content: flex-start;
-ms-flex-pack: start;
justify-content: flex-start;
text-align: start;
}
.center-lg {
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
text-align: center;
}
.end-lg {
-webkit-box-pack: end;
-webkit-justify-content: flex-end;
-ms-flex-pack: end;
justify-content: flex-end;
text-align: end;
}
.top-lg {
-webkit-box-align: start;
-webkit-align-items: flex-start;
-ms-flex-align: start;
align-items: flex-start;
}
.middle-lg {
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
}
.bottom-lg {
-webkit-box-align: end;
-webkit-align-items: flex-end;
-ms-flex-align: end;
align-items: flex-end;
}
.around-lg {
-webkit-justify-content: space-around;
-ms-flex-pack: distribute;
justify-content: space-around;
}
.between-lg {
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
}
.first-lg {
-webkit-box-ordinal-group: 0;
-webkit-order: -1;
-ms-flex-order: -1;
order: -1;
}
.last-lg {
-webkit-box-ordinal-group: 2;
-webkit-order: 1;
-ms-flex-order: 1;
order: 1;
}
} | {
"pile_set_name": "Github"
} |
/**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable 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.
*/
import { MessageToWorker, MessageType, ResizeSyncToWorker } from '../transfer/Messages';
import { TransferrableKeys } from '../transfer/TransferrableKeys';
import { WorkerDOMGlobalScope } from './WorkerDOMGlobalScope';
export function propagate(global: WorkerDOMGlobalScope): void {
const document = global.document;
if (!document.addGlobalEventListener) {
return;
}
document.addGlobalEventListener('message', ({ data }: { data: MessageToWorker }) => {
if (data[TransferrableKeys.type] !== MessageType.RESIZE) {
return;
}
const sync = (data as ResizeSyncToWorker)[TransferrableKeys.sync];
if (sync) {
global.innerWidth = sync[0];
global.innerHeight = sync[1];
}
});
}
| {
"pile_set_name": "Github"
} |
# Copyright (C) 2017 Christopher M. Biwer
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3 of the License, or (at your
# option) any later version.
#
# This 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import numpy
import unittest
from pycbc import transforms
from utils import parse_args_cpu_only
from utils import simple_exit
# list of transforms without an inverse function and to ignore
IGNORE = [t.name for t in transforms.common_cbc_transforms
if t.inverse is None]
# ranges to draw random numbers for each parameter
RANGES = {
"mass1" : (1.0, 100.0),
"mass2" : (1.0, 100.0),
"mchirp" : (1.0, 20.0),
"q" : (1.0, 10.0),
"spin1_a" : (0.0, 1.0),
"spin1_polar" : (0, numpy.pi),
"spin1_azimuthal" : (0.0, 2 * numpy.pi),
"spin2_a" : (0.0, 1.0),
"spin2_polar" : (0, numpy.pi),
"spin2_azimuthal" : (0.0, 2 * numpy.pi),
"chi_eff" : (-1.0, 1.0),
"chi_a" : (0.0, 1.0),
"chi_p" : (0.0, 1.0),
"phi_s" : (0.0, 2 * numpy.pi),
"phi_a" : (0.0, 2 * numpy.pi),
"xi1" : (0.0, 1.0),
"xi2" : (0.0, 1.0),
"chirp_distance" : (2.0, 10.0),
}
# tests only need to happen on the CPU
parse_args_cpu_only("Transforms")
class TestTransforms(unittest.TestCase):
def setUp(self):
# set random seed
numpy.random.seed(1024)
def test_inverse(self):
# set threshold how similar values must be
threshold = 0.001
# loop over forward CBC transforms
for trans in transforms.common_cbc_forward_transforms:
# check if inverse exists
if trans.name in IGNORE:
continue
if trans.name == 'spherical_to_cartesian':
# spherical to cartesian requires the cartesian and spherical
# parameter names to be specified, which we can get from
# the inputs and outputs
inv = trans.inverse(*trans._outputs+trans._inputs)
else:
inv = trans.inverse()
# generate some random points
in_map = {p : numpy.random.uniform(*RANGES[p])
for p in trans.inputs}
# transforms to and back from inverse transform
intermediate_map = trans.transform(in_map)
out_map = inv.transform(intermediate_map)
# check that input equals outputs to some threshold
in_arr = numpy.array([in_map[p] for p in trans.inputs])
out_arr = numpy.array([out_map[p] for p in trans.inputs])
if not numpy.all(1.0 - in_arr / out_arr < threshold):
raise ValueError(
"Transform {} does not map back to itself.".format(trans.name))
suite = unittest.TestSuite()
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestTransforms))
if __name__ == "__main__":
results = unittest.TextTestRunner(verbosity=2).run(suite)
simple_exit(results)
| {
"pile_set_name": "Github"
} |
// +build linux,386 linux,arm linux,mips linux,mipsle
// 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.
package unix
func init() {
// On 32-bit Linux systems, the fcntl syscall that matches Go's
// Flock_t type is SYS_FCNTL64, not SYS_FCNTL.
fcntl64Syscall = SYS_FCNTL64
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* <p>
* WSO2 Inc. 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.wso2.carbon.esb.mediators.enrich;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.commons.lang3.CharEncoding;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.esb.integration.common.utils.ESBIntegrationTest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class EI2084EnrichNamespaceAdditionTestCase extends ESBIntegrationTest {
private static final String API_NAME = "EI2084";
@BeforeClass(alwaysRun = true)
public void setEnvironment() throws Exception {
super.init();
String api = "<api xmlns=\"http://ws.apache.org/ns/synapse\" name=\"" + API_NAME + "\" context=\"/" + API_NAME + "\">\n" +
" <resource methods=\"POST\" uri-template=\"/test_with_pf\">\n" +
" <inSequence>\n" +
" <enrich>\n" +
" <source type=\"body\" clone=\"true\"/>\n" +
" <target type=\"property\" property=\"INPUT_MESSAGE\"/>\n" +
" </enrich>\n" +
" <payloadFactory media-type=\"xml\">\n" +
" <format>\n" +
" <inline xmlns=\"\">\n" +
" <payload>$1</payload>\n" +
" </inline>\n" +
" </format>\n" +
" <args>\n" +
" <arg evaluator=\"xml\" expression=\"get-property('INPUT_MESSAGE')\"/>\n" +
" </args>\n" +
" </payloadFactory>\n" +
" <property name=\"messageType\" value=\"text/xml\" scope=\"axis2\"/>\n" +
" <respond/>\n" +
" </inSequence>\n" +
" <outSequence/>\n" +
" <faultSequence/>\n" +
" </resource>\n" +
"</api>\n";
OMElement omAPI = AXIOMUtil.stringToOM(api);
addApi(omAPI);
Assert.assertTrue(esbUtils.isApiDeployed(contextUrls.getBackEndUrl(), sessionCookie, API_NAME));
}
@Test(groups = "wso2.esb", description = "Enrich / Payload Factory mediators,soap namespace is added when soap is not in use")
public void testEnrichNamespaceAdditionTestCase() throws Exception {
String endpoint = getApiInvocationURL(API_NAME) + "/test_with_pf";
String requestXml = "<MetaData><DateTimeSent/></MetaData>";
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(endpoint);
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/xml;charset=UTF-8");
HttpEntity stringEntity = new StringEntity(requestXml, CharEncoding.UTF_8);
httpPost.setEntity(stringEntity);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
BufferedReader rd = new BufferedReader(new InputStreamReader(resEntity.getContent()));
String result = "";
String line;
while ((line = rd.readLine()) != null) {
result += line;
}
Assert.assertTrue(!result.contains("http://schemas.xmlsoap.org/soap/envelope/") , "unnessary namespaces present in message");
}
@AfterClass(alwaysRun = true)
public void close() throws Exception {
super.cleanup();
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<LangFile>
<info>
<property name="program">freac</property>
<property name="version">1.1</property>
<property name="language">Bulgarian / Български</property>
<property name="righttoleft">false</property>
<property name="encoding">UTF-8</property>
<property name="template">freac.xml</property>
<property name="author">KalinM</property>
<property name="url">https://www.freac.org/</property>
</info>
<data>
<entry id="100" string="OK">OK</entry>
<entry id="101" string="Cancel">Отказ</entry>
<entry id="102" string="Close">Затваряне</entry>
<entry id="200" string="Error">Грешка</entry>
<entry id="201" string="Warning">Предупреждение</entry>
<entry id="202" string="Info">Информация</entry>
<entry id="210" string="Do not display this warning again">Не показвай отново това предупреждение</entry>
<entry id="211" string="Do not display this note again">Не показвай отново тази забележка</entry>
<entry id="300" string="Artist">Изпълнител</entry>
<entry id="301" string="Title">Заглавие</entry>
<entry id="302" string="Album">Албум</entry>
<entry id="303" string="Track">Песен №</entry>
<entry id="304" string="Genre">Жанр</entry>
<entry id="305" string="Comment">Коментар</entry>
<entry id="306" string="Year">Година</entry>
<entry id="307" string="Disc">Диск</entry>
<entry id="308" string="Rating">Оценка</entry>
<entry id="309" string="File name">Име на файл</entry>
<entry id="310" string="File type">Тип файл</entry>
<entry id="311" string="Album artist">Изпълнител на албума</entry>
<entry id="350" string="unknown artist">неизвестен изпълнител</entry>
<entry id="351" string="unknown title">неизвестно заглавие</entry>
<entry id="352" string="unknown album">неизвестен албум</entry>
<entry id="353" string="unknown genre">неизвестен жанр</entry>
<entry id="354" string="unknown year">неизвестна година</entry>
<entry id="355" string="unknown conductor">неизвестен диригент</entry>
<entry id="356" string="unknown composer">неизвестен композитор</entry>
<entry id="357" string="unknown album artist">неизвестен изпълнител на албума</entry>
<entry id="380" string="hidden track">скрит запис/песен/</entry>
<section name="Characters">
<entry id="500" string="%1:">%1:</entry>
<entry id="501" string="%1...">%1...</entry>
<entry id="502" string="%1 (%2)">%1 (%2)</entry>
</section>
<section name="Technical">
<entry id="510" string="%1 kbps">%1 kbps</entry>
<entry id="511" string="%1 Hz">%1 Hz</entry>
<entry id="512" string="%1 kHz">%1 kHz</entry>
<entry id="513" string="%1 ms">%1 ms</entry>
<entry id="514" string="%1 min">%1 мин</entry>
<entry id="515" string="%1 bit">%1 bit</entry>
<entry id="516" string="%1 bytes">%1 bytes</entry>
<entry id="517" string="%1 kB">%1 kB</entry>
<entry id="518" string="%1%">%1%</entry>
</section>
<section name="Menu">
<entry id="1000" string="File">Файл</entry>
<entry id="1001" string="Options">Настройки</entry>
<entry id="1002" string="Database">База Данни</entry>
<entry id="1003" string="Processing">Обработка</entry>
<entry id="1004" string="Encode">Кодиране</entry>
<entry id="1005" string="Help">Помощ</entry>
<section name="File">
<entry id="1100" string="Add">Добавяне</entry>
<entry id="1101" string="Remove">Премахване</entry>
<entry id="1102" string="Load joblist">Зареждане на списък със задачи</entry>
<entry id="1103" string="Save joblist">Запис на списъка със задачи</entry>
<entry id="1104" string="Clear joblist">Изчистване на списъка със задачи</entry>
<entry id="1105" string="Exit">Изход</entry>
<entry id="1106" string="Audio file(s)">Аудио файл(ове)</entry>
<entry id="1107" string="Audio CD contents">Съдържание на аудио CD</entry>
<entry id="1108" string="By pattern">От шаблон</entry>
<entry id="1109" string="From folder">От папка</entry>
</section>
<section name="Database">
<entry id="1200" string="Query CDDB database">Заявка към CDDB база данни</entry>
<entry id="1201" string="Submit CDDB data">Изпращане на CDDB данни</entry>
<entry id="1202" string="Query CDDB database later">Заявка към CDDB база данни по-късно</entry>
<entry id="1203" string="Show queued CDDB entries">Показване на чакащите CDDB запис</entry>
<entry id="1204" string="Show queued CDDB queries">Показване на чакащите CDDB заявки</entry>
<entry id="1205" string="Enable CDDB cache">Включено CDDB кеш</entry>
<entry id="1206" string="Manage CDDB cache entries">Управление на кеша със записи на CDDB</entry>
<entry id="1207" string="Automatic CDDB queries">Автоматични заявки към CDDB</entry>
</section>
<section name="Options">
<entry id="1300" string="General settings">Основни настройки</entry>
<entry id="1301" string="Configure signal processing">Конфигуриране обработката на сигнала</entry>
<entry id="1302" string="Configure selected encoder">Конфигуриране на избрания енкодер</entry>
<entry id="1303" string="Active CD-ROM drive">Активно CD-ROM устройство</entry>
<entry id="1304" string="Active configuration">Активна конфигурация</entry>
<entry id="1305" string="Default configuration">Конфигурация по подразбиране</entry>
</section>
<section name="Processing">
<entry id="1400" string="Enable signal processing">Разрешаване обработката на сигнала</entry>
<entry id="1401" string="Enable processing during playback">Разрешаване обработката при възпроизвеждане</entry>
<entry id="1402" string="Selected signal processors">Избиране процесор на сигнала</entry>
</section>
<section name="Encode">
<entry id="1500" string="Start encoding">Старт на кодирането</entry>
<entry id="1501" string="Start encoding (deleting original files)">Старт на кодирането (Изтриване на ориг. файлове)</entry>
<entry id="1502" string="Start encoding with">Старт на кодирането с</entry>
<entry id="1503" string="Pause/resume encoding">Пауза/Продължаване на кодирането</entry>
<entry id="1504" string="Stop encoding">Стоп на кодирането</entry>
<entry id="1505" string="Encoder options">Настройки на енкодера</entry>
<entry id="1506" string="Encode to a single file">Кодиране в един файл</entry>
<entry id="1507" string="Encode to input file folder if possible">Кодиране в папката на входящия файл (ако е възможно)</entry>
<entry id="1508" string="Allow overwriting input file">Разрешаване на презаписването на входящия файл</entry>
<entry id="1509" string="Delete original files after encoding">Изтриване на оригиналните файлове след кодирането</entry>
<entry id="1510" string="Shutdown after encoding">Изключване след кодирането</entry>
</section>
<section name="Help">
<entry id="1600" string="Help topics">Ръководство за употреба</entry>
<entry id="1601" string="Show Tip of the Day">Показване на Съвети за деня</entry>
<entry id="1602" string="Check for updates now">Проверка за обновяване сега</entry>
<entry id="1603" string="Check for updates at startup">Проверка за обновяване при стартиране</entry>
<entry id="1604" string="About %1">Относно %1</entry>
<entry id="1605" string="index_en.html">index_en.html</entry>
<entry id="1606" string="Report an issue">Докладвайте за проблем</entry>
<entry id="1607" string="Suggest a feature">Предложете функция</entry>
</section>
</section>
<section name="Toolbar">
<entry id="2000" string="Add audio file(s) to the joblist">Добавяне на аудио файл(ове) към списъка със задачи</entry>
<entry id="2001" string="Add audio CD contents to the joblist">Добавяне аудио CD съдържанието към списъка със задачи</entry>
<entry id="2002" string="Remove the selected entry from the joblist">Премахване на избраните от списъка със задачи</entry>
<entry id="2003" string="Clear the entire joblist">Изтриване целия списък със задачи</entry>
<entry id="2004" string="Query CDDB database">Заявка към CDDB база данни</entry>
<entry id="2005" string="Submit CDDB data">Изпращане на CDDB данни</entry>
<entry id="2006" string="Configure general settings">Конфигуриране на основните настройки</entry>
<entry id="2007" string="Configure signal processing">Конфигуриране обработката на сигнала</entry>
<entry id="2008" string="Configure the selected audio encoder">Конфигуриране на избрания аудио енкодер</entry>
<entry id="2009" string="Start the encoding process">Старт на процеса кодиране</entry>
<entry id="2010" string="Start the encoding process (deleting original files)">Старт на процеса кодиране (Изтриване на ориг. файлове)</entry>
<entry id="2011" string="Pause/resume encoding">Пауза/Продължаване на кодирането</entry>
<entry id="2012" string="Stop encoding">Стоп на кодирането</entry>
</section>
<section name="Joblist">
<entry id="3000" string="Time left">Оставащо време</entry>
<entry id="3001" string="File progress">Прогрес</entry>
<entry id="3002" string="Output folder">Изходна папка</entry>
<entry id="3003" string="%1 file(s) in joblist">%1 файл(ове) в списъка със задачи</entry>
<entry id="3004" string="Show title info">Показване на заглавието</entry>
<entry id="3005" string="Play">Възпроизвеждане</entry>
<entry id="3006" string="Stop">Стоп</entry>
<entry id="3007" string="Select all">Избиране на всичко</entry>
<entry id="3008" string="Select none">Празен избор</entry>
<entry id="3009" string="Toggle selection">Превключване на избора</entry>
<entry id="3010" string="ripping/decoding">извличане/декодиране</entry>
<entry id="3011" string="encoding">кодиране</entry>
<entry id="3012" string="Create playlist">Създаване на плейлист</entry>
<entry id="3013" string="Create cue sheet">Създаване на CUE лист</entry>
<entry id="3014" string="Select">Избиране...</entry>
<entry id="3015" string="Encode to a single file">Кодиране в един файл</entry>
<entry id="3016" string="Remove">Премахване</entry>
<entry id="3017" string="Clear joblist">Изчистване на списъка със задачи</entry>
<entry id="3018" string="Use for all selected tracks">Използвай за всички избрани песни</entry>
<entry id="3019" string="Interpret string as">Интерпретиране на реда като</entry>
<entry id="3020" string="selected tracks">избрани песни</entry>
<entry id="3021" string="Adjust upper/lower case">Настройване на главни/малки букви</entry>
<entry id="3022" string="all words upper case">всички думи с главни букви</entry>
<entry id="3023" string="long words upper case">дълги думи с главни букви</entry>
<entry id="3024" string="first letter upper case">първата буква с главна буква</entry>
<entry id="3025" string="all lower case">всичко с малки букви</entry>
<entry id="3026" string="all upper case">всичко с главни букви</entry>
<entry id="3027" string="Select the folder in which the encoded files will be placed">Изберете папка, където кодираните файлове ще бъдат поставени</entry>
<entry id="3028" string="Sampling rate">Семплираща честота</entry>
<entry id="3029" string="Sample resolution">Семплираща резолюция</entry>
<entry id="3030" string="Number of samples">Брой семпли</entry>
<entry id="3031" string="Channels">Канали</entry>
<entry id="3032" string="Mono">Моно</entry>
<entry id="3033" string="Stereo">Стерео</entry>
<entry id="3034" string="Length">Времетраене</entry>
<entry id="3035" string="File">Файл</entry>
<entry id="3036" string="Size">Размер</entry>
<entry id="3037" string="Bitrate">Bitrate</entry>
<entry id="3038" string="Audio Files">Аудио файлове</entry>
<entry id="3039" string="All Files">Всички файлове</entry>
<entry id="3040" string="Playlist Files">Плейлист файлове</entry>
<entry id="3041" string="Joblist">Списък със задачи</entry>
<entry id="3042" string="Other">Друг</entry>
<entry id="3043" string="Output file name">Име на изходния файл</entry>
<entry id="3044" string="verifying">проверка</entry>
<entry id="3045" string="Open">Отвори</entry>
<entry id="3046" string="CD drive">CD устройство</entry>
<entry id="3047" string="Disc ID">Диск ID</entry>
<section name="File">
<entry id="3050" string="Current file">Кодиране на файл</entry>
<entry id="3051" string="none">празно</entry>
<entry id="3052" string="Skip current file">Пропускане</entry>
</section>
<section name="Decoder">
<entry id="3060" string="Active decoder">Активен декодер</entry>
<entry id="3061" string="none">неизвестно</entry>
</section>
<section name="Filters">
<entry id="3070" string="Selected filters">Избрани филтри</entry>
<entry id="3071" string="none">празно</entry>
<entry id="3072" string="disabled">изключено</entry>
<entry id="3073" string="Configure signal processing">Конфигуриране обработката на сигнала</entry>
</section>
<section name="Encoder">
<entry id="3080" string="Selected encoder">Избран енкодер</entry>
<entry id="3081" string="Configure selected encoder">Конфигуриране на избрания енкодер</entry>
</section>
<section name="Add folder">
<entry id="3100" string="Folder">Папка</entry>
<entry id="3101" string="Add folder">Добавяне на папка</entry>
<entry id="3102" string="Choose folder">Изберете папка</entry>
<entry id="3103" string="Select the folder to add to the joblist">Изберете папка за добавяне към списъка със задачи</entry>
</section>
<section name="Add by pattern">
<entry id="3200" string="Add files by pattern">Добавяне на файлове по шаблон</entry>
<entry id="3201" string="Pattern">Шаблон</entry>
<entry id="3202" string="Start folder">Начална папка</entry>
<entry id="3203" string="Filename pattern">Шаблон за име на файла</entry>
<entry id="3204" string="Search subfolders">Търсене на подпапки</entry>
<entry id="3205" string="Select the folder to add to the joblist">Изберете папка за добавяне към списъка със задачи</entry>
</section>
<section name="Character set">
<entry id="3300" string="Character set">Кодова таблица</entry>
<entry id="3301" string="Choose character set">Изберете кодова таблица</entry>
</section>
<section name="Errors">
<entry id="3400" string="You did not select a track!">Не сте избрали песен!</entry>
<entry id="3401" string="No files found matching pattern: %1">Няма открити файлове отговарящи на шаблона: %1</entry>
</section>
</section>
<section name="Jobs">
<entry id="3500" string="Jobs">Задачи</entry>
<entry id="3501" string="Progress">Прогрес</entry>
<entry id="3502" string="Errors / Warnings">Грешки / Предупреждения</entry>
<entry id="3503" string="Details">Детайли</entry>
<entry id="3504" string="Error details">Детайли за грешката</entry>
<entry id="3505" string="Time left">Оставащо време</entry>
<entry id="3506" string="Waiting for other jobs to finish">Изчаква се да завършат други задания</entry>
<section name="Joblist">
<entry id="3600" string="Reading folders">Четене на папки</entry>
<entry id="3601" string="Filtering duplicates">Филтриране на дубликати</entry>
<entry id="3602" string="Adding files">Добавяне на файлове</entry>
<entry id="3603" string="Adding tracks">Добавяне на песни</entry>
<entry id="3604" string="Added %1 files, %2 errors occurred">Добавени са %1 файлове, възникнаха %2 грешки</entry>
<entry id="3605" string="Added %1 tracks, %2 errors occurred">Добавени са %1 песни, възникнаха %2 грешки</entry>
<entry id="3606" string="Removing all tracks">Премахнати са всички песни</entry>
<entry id="3607" string="Removing tracks of disc in drive %1">Премахнати са песните на диска в устройство %1</entry>
<entry id="3608" string="Removed all tracks from joblist">Премахнати са всички песни от списъка със задачи</entry>
<entry id="3609" string="Removed tracks of disc in drive %1 from joblist">Премахнати са песните на диска в устройство %1 от списъка със задачи</entry>
</section>
<section name="Convert">
<entry id="3700" string="Checking sample formats">Проверка на примерни формати</entry>
<entry id="3701" string="Checking for lossy to lossless conversion">Проверка за загуба при преобразуване без загуба</entry>
<entry id="3702" string="Checking output file names">Проверка на имената на изходните файлове</entry>
<entry id="3703" string="Converting %1">Конвертиране на %1</entry>
<entry id="3704" string="Verifying %1">Проверка на %1</entry>
<entry id="3705" string="Conversion cancelled">Преобразуването е отменено</entry>
<entry id="3706" string="Conversion finished">Преобразуването е завършено</entry>
<entry id="3707" string="Conversion finished with %1 warnings">Преобразуването завърши с %1 предупреждения</entry>
<entry id="3708" string="Conversion finished with %1 errors">Преобразуването завърши с %1 грешки</entry>
</section>
<section name="Update">
<entry id="3800" string="Preparing update check">Подготовка за проверка на актуализация</entry>
<entry id="3801" string="Contacting update server">Свързване със сървъра за актуализиране</entry>
<entry id="3802" string="Updates found">Открити са актуализации</entry>
<entry id="3803" string="No updates found">Няма намерени актуализации</entry>
</section>
</section>
<section name="CDDB">
<section name="Submit">
<entry id="4000" string="CDDB data">CDDB данни</entry>
<entry id="4001" string="Submit">Изпращане</entry>
<entry id="4002" string="No audio CD in drive!">Няма аудио CD в устройството!</entry>
<entry id="4003" string="Submitting CD information">Изпращане на информация за CD</entry>
<entry id="4004" string="Update joblist with this information">Обновяване на списъка със задачи с тази информация</entry>
<entry id="4005" string="Status">Състояние</entry>
<entry id="4006" string="Successfully read CD!">Успешно прочетено CD!</entry>
<entry id="4007" string="Save entry">Запазване</entry>
<entry id="4008" string="Various artists">Разни изпълнители</entry>
<entry id="4009" string="Data track">Пътечка с данни</entry>
<entry id="4010" string="Submit to online database later">Изпращане към онлайн базата с данни по-късно</entry>
<entry id="4011" string="Active CD-ROM drive">Активно CD-ROM устройство</entry>
<section name="Errors">
<entry id="4050" string="Some error occurred trying to connect to the freedb server.">Възникна грешка при опит за свързване към freedb сървъра.</entry>
<entry id="4051" string="Please fill all fields and track titles before submitting.">Попълнете всички полета и заглавията на песните преди изпращане.</entry>
</section>
</section>
<section name="Query">
<entry id="4100" string="CDDB query">Заявка към CDDB</entry>
<entry id="4101" string="No freedb entry for this disk.">Няма записи в freedb за този диск</entry>
<entry id="4102" string="Connecting to freedb server at">Свързване към freedb сървъра</entry>
<entry id="4103" string="Requesting CD information">Заявка на информация за CD</entry>
<entry id="4104" string="No exact matches found">Няма открити точни съответствия</entry>
<entry id="4105" string="Multiple matches found">Намерени са множество съответствия</entry>
<entry id="4106" string="Matches">Съответствия</entry>
<entry id="4107" string="Select the entry that best fits your CD">Изберете записа който най-добре отговаря на вашия CD</entry>
<entry id="4108" string="Would you like to perform this query again later?">Искате ли да изпълните тази заявка отново по-късно?</entry>
<entry id="4109" string="Would you like to perform the remaining queries again later?">Искате ли да изпълните останалите заявки отново по-късно?</entry>
<entry id="4110" string="none">празно</entry>
<entry id="4111" string="Preview">Преглед</entry>
<entry id="4112" string="loading preview">зареждане на преглед</entry>
<section name="Errors">
<entry id="4150" string="Some error occurred trying to connect to the freedb server.">Възникна грешка при опит за свързване към freedb сървъра.</entry>
</section>
</section>
<section name="Manage queries">
<entry id="4200" string="Remove entry">Премахване</entry>
<entry id="4201" string="CDDB queries">CDDB заявки</entry>
<entry id="4202" string="Query">Заявка</entry>
<entry id="4203" string="Query all">Заявка на вс.</entry>
<entry id="4204" string="Query string">Заявка на ред</entry>
<entry id="4205" string="CDDB queries to perform">CDDB заявки за изпълнение</entry>
<entry id="4206" string="Querying CD information">Заявка на информация за CD</entry>
</section>
<section name="Manage submits">
<entry id="4300" string="Remove entry">Премахване</entry>
<entry id="4301" string="CDDB entries to submit">CDDB записи за изпращане</entry>
<entry id="4302" string="Submit all">Изпращане на вс.</entry>
<entry id="4303" string="CDDB data">CDDB данни</entry>
<entry id="4304" string="Submit">Изпращане</entry>
<entry id="4305" string="Disc name">Име на диска</entry>
<entry id="4306" string="Preview">Преглед</entry>
<entry id="4307" string="Category">Категория</entry>
<entry id="4308" string="Submitting CD information">Изпращане на информация за CD</entry>
</section>
<section name="Manage cache">
<entry id="4400" string="CDDB data">CDDB данни</entry>
<entry id="4401" string="Update joblist with this information">Обновяване на списъка със задачи с тази информация</entry>
<entry id="4402" string="Charset">Набор символи</entry>
<entry id="4403" string="Downloaded CDDB entries">Изтеглени CDDB записи</entry>
<entry id="4404" string="Disc name">Име на диск</entry>
<entry id="4405" string="Preview">Преглед</entry>
<entry id="4406" string="Remove entry">Премахване</entry>
<entry id="4407" string="Save entry">Запазване</entry>
</section>
</section>
<section name="Configuration">
<entry id="5000" string="General settings setup">Основни настройки</entry>
<entry id="5001" string="Encoders">Енкодери</entry>
<entry id="5002" string="Playlists">Плейлисти</entry>
<entry id="5003" string="Language">Език</entry>
<entry id="5004" string="CDDB">CDDB</entry>
<entry id="5005" string="Interface">Интерфейс</entry>
<entry id="5006" string="Tags">Тагове</entry>
<entry id="5007" string="Components">Компоненти</entry>
<entry id="5008" string="Decoders">Декодери</entry>
<entry id="5009" string="Output">Изходен</entry>
<entry id="5010" string="DSP">DSP</entry>
<entry id="5011" string="Extensions">Разширения</entry>
<entry id="5012" string="Other">Друг</entry>
<entry id="5013" string="Active configuration">Активна конфигурация</entry>
<entry id="5014" string="New">Нова</entry>
<entry id="5015" string="Delete">Изтриване</entry>
<entry id="5016" string="Command line arguments">Аргументи на командния ред</entry>
<entry id="5017" string="Resulting arguments string">Резултат на поредицата от аргументи</entry>
<entry id="5018" string="Default configuration">Конфигурация по подразбиране</entry>
<entry id="5019" string="New configuration">Нова конфигурация</entry>
<entry id="5020" string="Ripper">Рипър</entry>
<entry id="5021" string="Settings">Настройки</entry>
<entry id="5022" string="Resources">Ресурси</entry>
<entry id="5023" string="Verifiers">Проверка</entry>
<entry id="5024" string="Taggers">Тагери</entry>
<entry id="5025" string="Processing">Обработка</entry>
<entry id="5026" string="Additional arguments"/>
<section name="Encoders">
<entry id="5100" string="Configure encoder">Конфигурация на енкодера</entry>
<entry id="5101" string="Encoder">Енкодер</entry>
<entry id="5102" string="Output folder">Изходна папка</entry>
<entry id="5103" string="Select">Избиране...</entry>
<entry id="5104" string="Select the folder in which the encoded files will be placed">Изберете папка, където кодираните файлове ще бъдат поставени</entry>
<entry id="5105" string="Use input file folder if possible">Папката на входящия файл (ако е възможно)</entry>
<entry id="5106" string="Allow overwriting input file">Презаписване на входящия файл</entry>
<entry id="5107" string="Options">Опции</entry>
<entry id="5108" string="Filename pattern">Шаблон за име на файла</entry>
<entry id="5109" string="Encode 'On-The-Fly'">Паралелно Кодиране (в движение)</entry>
<entry id="5110" string="Keep ripped Wave files">Запазване на Wave файловете</entry>
<entry id="5111" string="Encode to a single file">Кодиране в един файл</entry>
<entry id="5112" string="Output filenames">Имена на изходните файлове</entry>
<entry id="5113" string="Allow Unicode characters">Разрешаване на Unicode символи</entry>
<entry id="5114" string="Replace spaces with underscores">Замяна на интервалите</entry>
<entry id="5115" string="Remove processed tracks from joblist">Премахване обработените песни от задачите</entry>
<entry id="5116" string="Add encoded files to joblist">Добавяне кодираните файлове в задачите</entry>
<entry id="5117" string="Append sequential numbers to otherwise identical filenames">Добавяне последователни номера към файловете с еднакви имена</entry>
<entry id="5118" string="Keep time stamps of source files">Запазване времето на оригиналните файлове</entry>
<section name="Errors">
<entry id="5150" string="The output folder does not exist! Do you want to create it?">Изходната папка не съществува! Искате ли да я създадете?</entry>
</section>
</section>
<section name="Playlists">
<entry id="5200" string="Create playlists">Създаване на плейлисти</entry>
<entry id="5201" string="Create cue sheets">Създаване на CUE листи</entry>
<entry id="5202" string="Output folder">Изходна папка</entry>
<entry id="5203" string="Select">Избиране...</entry>
<entry id="5204" string="Use encoder output folder">Изходната папка на енкодера</entry>
<entry id="5205" string="Filename pattern">Шаблон за име на файла</entry>
<entry id="5206" string="Select the folder in which the playlist files will be placed">Изберете папка, където плейлистите ще бъдат поставени</entry>
<entry id="5207" string="Output filenames">Имена на изходните файлове</entry>
<entry id="5208" string="Configure plugin">Конфигуриране plugin</entry>
<entry id="5209" string="Create only a single playlist and/or cue sheet file per conversion">Създаване само на един плейлист и/или файл с CUE лист за преобразуване</entry>
</section>
<section name="CDDB">
<entry id="5300" string="Enable local CDDB database">Включване на местна CDDB база данни</entry>
<entry id="5301" string="Enable remote CDDB database">Включване на отдалечена CDDB база данни</entry>
<entry id="5302" string="CDDB path">Път към CDDB</entry>
<entry id="5303" string="Select">Избиране...</entry>
<entry id="5304" string="Select the folder of the CDDB database">Изберете папката на CDDB базата данни</entry>
<entry id="5305" string="CDDB access mode">Режим за достъп до CDDB</entry>
<entry id="5306" string="CDDB server">CDDB сървър</entry>
<entry id="5307" string="Port">Порт</entry>
<entry id="5308" string="eMail address">eMail адрес</entry>
<entry id="5309" string="HTTP settings">HTTP настройки</entry>
<entry id="5310" string="Proxy settings">Прокси настройки</entry>
<entry id="5311" string="Options">Опции</entry>
<entry id="5312" string="Automatic CDDB queries">Автом. заявки към CDDB</entry>
<entry id="5313" string="Prefer CDDB over CD Text">Предпоч. CDDB пред CD Текст</entry>
<entry id="5314" string="Enable CDDB cache">Включване на CDDB кеш</entry>
<entry id="5315" string="Automatization">Автоматизация</entry>
<entry id="5316" string="Always select first entry">Винаги избор на 1-вия запис</entry>
<section name="Extended">
<entry id="5330" string="Extended CDDB settings">Разширени настройки на CDDB</entry>
<entry id="5331" string="CGI scripts">CGI скриптове</entry>
<entry id="5332" string="CDDB query script">Скрипт за CDDB заявка</entry>
<entry id="5333" string="CDDB submit script">Скрипт за CDDB изпращане</entry>
<entry id="5334" string="no proxy">без прокси</entry>
<entry id="5335" string="Proxy type">Тип прокси</entry>
<entry id="5336" string="Proxy server">Прокси сървър</entry>
<entry id="5337" string="User name">Потребителско име</entry>
<entry id="5338" string="Password">Парола</entry>
</section>
<section name="Errors">
<entry id="5350" string="Please enter a valid eMail address.">Въведете валиден eMail адрес.</entry>
<entry id="5351" string="The freedb CDDBP protocol cannot be used over HTTP Forward proxies! Would you like to change the protocol to HTTP?">Протокола freedb CDDBP не може да бъде използван с HTTP пренасочващи проксита! Желаете ли да промените протокола на HTTP?</entry>
</section>
</section>
<section name="Language">
<entry id="5400" string="Select language">Изберете език</entry>
<entry id="5401" string="Edit language file">Редакция на езиковия файл</entry>
<entry id="5402" string="Information">Информация</entry>
<entry id="5403" string="Encoding">Кодиране</entry>
<entry id="5404" string="Author">Автор</entry>
<entry id="5405" string="URL">Адрес</entry>
</section>
<section name="Tags">
<entry id="5500" string="Tags">Тагове</entry>
<entry id="5501" string="Tag formats">Таг формати</entry>
<entry id="5502" string="Default comment string">Подразбираем коментар</entry>
<entry id="5503" string="Replace existing comments with default comment">Замяна на съществуващите коментари с подразбираемия</entry>
<entry id="5504" string="Filename pattern">Шаблон за име на файла</entry>
<entry id="5505" string="Encoding">Кодиране</entry>
<entry id="5506" string="Comments">Коментари</entry>
<entry id="5507" string="Cover art">Обложка</entry>
<entry id="5508" string="Read cover art">Прочитане на обложка</entry>
<entry id="5509" string="Read cover art from tags">Прочитане на обложка от тагове</entry>
<entry id="5510" string="Read cover art from files">Прочитане на обложка от файлове</entry>
<entry id="5511" string="Write cover art">Записване на обложка</entry>
<entry id="5512" string="Write cover art to tags">Записване на обложката в таговете</entry>
<entry id="5513" string="Write cover art to files">Записване на обложката във файловете</entry>
<entry id="5514" string="Add reference to audio file tag">Препратка към таг на аудио файл</entry>
<entry id="5515" string="Other">Други</entry>
<entry id="5516" string="Chapters">Глави</entry>
<entry id="5517" string="Read chapters from files">Четене на глави от файлове</entry>
<entry id="5518" string="Write chapters to files">Записване на главата във файловете</entry>
<entry id="5519" string="Special fields">Специални полета</entry>
<entry id="5520" string="Write CD table of contents">Записване на CD таблица със съдържание</entry>
<entry id="5521" string="Preserve Replay Gain information">Запазване информацията за сила на звука</entry>
<entry id="5522" string="Cue sheets">CUE листи</entry>
<entry id="5523" string="Read cue sheets embedded in metadata">Предпочитам CUE листи вградени в метаданните</entry>
<entry id="5524" string="Prefer cue sheets over chapter information">Предпочитам CUE листи с информация за страницата</entry>
<entry id="5525" string="Prepend zero to track numbers below 10">Добавяне нула за проследяване номера на песен под 10</entry>
<entry id="5526" string="File size limit">Ограничение за размер на файла</entry>
<entry id="5527" string="unlimited">Без ограничение</entry>
</section>
<section name="Joblist">
<entry id="5600" string="Joblist">Списък със задачи</entry>
<entry id="5601" string="Columns">Колони</entry>
<entry id="5602" string="Name">Име</entry>
<entry id="5603" string="Description">Описание</entry>
<entry id="5604" string="Up">Нагоре</entry>
<entry id="5605" string="Down">Надолу</entry>
<entry id="5606" string="Jobs">Задачи</entry>
<entry id="5607" string="Show Jobs tab">Показване на раздел "Задачи"</entry>
<section name="Columns">
<entry id="5650" string="Track artist">Изпълнител</entry>
<entry id="5651" string="Track title">Заглавие</entry>
<entry id="5652" string="Track genre">Жанр</entry>
<entry id="5653" string="Album title">Албум заглавие</entry>
<entry id="5654" string="Disc number">Диск №</entry>
<entry id="5655" string="Track number">№</entry>
<entry id="5656" string="Track rating">Оценка</entry>
<entry id="5657" string="Track length">Продължителност</entry>
<entry id="5658" string="Track size">Размер</entry>
<entry id="5659" string="File name">Име файл</entry>
<entry id="5660" string="File type">Тип файл</entry>
<entry id="5661" string="Output file name">Име на изходния файл</entry>
<entry id="5662" string="Bitrate">Bitrate</entry>
<entry id="5663" string="Sampling rate">Семплираща честота</entry>
<entry id="5664" string="Channels">Канали</entry>
<entry id="5665" string="Sample resolution">Семплираща резолюция</entry>
<entry id="5666" string="CD drive">CD устройство</entry>
<entry id="5667" string="Disc ID">Диск ID</entry>
</section>
</section>
<section name="Resources">
<entry id="5700" string="Parallel processing">Паралелна обработка</entry>
<entry id="5701" string="Enable parallel processing">Включена паралелна обработка</entry>
<entry id="5702" string="Enable SuperFast mode">Активиране Супер бърз режим</entry>
<entry id="5703" string="Number of conversion threads">Брой теми за преобразуване</entry>
<entry id="5704" string="auto">автоматично</entry>
<entry id="5705" string="Process priority">Приоритет на процеса</entry>
<entry id="5706" string="lowest">най-нисък</entry>
<entry id="5707" string="lower">нисък</entry>
<entry id="5708" string="normal">нормален</entry>
<entry id="5709" string="higher">висок</entry>
<entry id="5710" string="highest">най-висок</entry>
</section>
<section name="Verification">
<entry id="5800" string="Verification">Проверка</entry>
<entry id="5801" string="Enable input verification">Включена входяща проверка</entry>
<entry id="5802" string="Verify that lossless inputs decode to exactly the data they were originally created from.">Уверете се, че входящите Lossless данни се декодират точно в данните, от които първоначално са създадени.</entry>
<entry id="5803" string="Enable output verification">Включена проверка на изхода</entry>
<entry id="5804" string="Verify that lossless outputs decode to exactly the data used when encoding them.">Уверете се, че изходните Lossless данни се декодират точно, като данните използвани при кодирането им.</entry>
</section>
<section name="Processing">
<entry id="5900" string="Signal processing">Обработка на сигнала</entry>
<entry id="5901" string="Enable signal processing">Разрешаване обработката на сигнала</entry>
<entry id="5902" string="Enable processing during playback">Разрешаване обработката при възпроизвеждане</entry>
<entry id="5903" string="Components">Компоненти</entry>
<entry id="5904" string="Available">Налични</entry>
<entry id="5905" string="Selected">Избрани</entry>
<entry id="5906" string="Configure component">Конфигуриране на компонент</entry>
<entry id="5907" string="Conversion to a single output file">Преобразуване в един изходен файл</entry>
<entry id="5908" string="Process each track individually">Обработване на всяка песен поотделно</entry>
<entry id="5909" string="Treat the combined tracks like a single track">Третирайте комбинираните песни като една песен</entry>
</section>
</section>
<section name="About">
<entry id="6000" string="About %1">Относно %1</entry>
<entry id="6001" string="Translated by %1.">Превод %1.</entry>
<entry id="6002" string="This program is being distributed under the terms of the GNU General Public License (GPL).">Тази програма се разпространява под условията на GNU General Public License (GPL).</entry>
</section>
<section name="Updates">
<entry id="6100" string="There are new updates for %1 available online! Would you like to see a list of available updates now?">Налични са обновления за %1 Желаете ли да разгледате списък с наличните обновления сега?</entry>
<entry id="6101" string="There are no updates available at the moment!">Няма налични обновления в момента!</entry>
<entry id="6102" string="Check for updates at startup">Проверка за обновления при стартиране</entry>
<entry id="6103" string="%1 can perform an automatic check for online program updates at startup. Would you like %1 to look for updates at startup?">%1 може да извърши автоматична проверка онлайн за обновяване на програмата при стартиране. Желаете ли %1 да потърси обновления при стартиране?</entry>
</section>
<section name="Messages">
<entry id="7000" string="Currently converting">В момента се конвертира</entry>
<entry id="7001" string="A conversion process is still active! Do you really want to quit?">Процесът на конвертиране все още е активен! Наистина ли искате да затворите програмата?</entry>
<entry id="7002" string="Delete original files after encoding">Изтриване на оригиналните файлове след кодирането</entry>
<entry id="7003" string="This option will remove the original files from your computer after the encoding process! Are you sure you want to activate this function?">Тази опция ще изтрие оригиналните файлове от вашия компютър след процеса по кодиране! Сигурни ли сте, че искате да активирате тази функция?</entry>
<entry id="7004" string="Keep this option enabled even after restarting %1">Запазете тази опция включена дори след рестартиране %1</entry>
<entry id="7005" string="File already exists">Файлът вече съществува</entry>
<entry id="7006" string="The output file %1 already exists! Do you want to overwrite it?">Изходния файл %1 вече съществува! Искате ли да го презапишете?</entry>
<entry id="7007" string="Overwrite all further files">Презаписване на всички следващи файлове</entry>
<entry id="7008" string="You seem to be converting from a lossy to a lossless format. Please be aware that quality loss cannot be undone, so this process will not improve quality in any way, and most likely increase file size. Would you like to continue anyway?">Изглежда, че конвертирате от формат lossy(със загуба) в lossless(без загуба). Имайте предвид, че загубата на качеството не може да се отмени, така че този процес няма да подобри качеството по никакъв начин, и най-вероятно ще увеличи размера на файла. Искате ли да продължите?</entry>
</section>
<section name="Errors">
<entry id="7100" string="Could not create decoder component: %1 File: %1 Path: %2">Не може да се създаде компонент за декодер: %1 Файл: %1 Път: %2</entry>
<entry id="7101" string="Could not create encoder component: %1">Не може да се създаде компонент за енкодер: %1</entry>
<entry id="7102" string="Could not set up decoder for input file: %1 File: %1 Path: %2 Error: %3">Не може да се създаде декодер за входящия файл: %1 Файл: %1 Път: %2</entry>
<entry id="7103" string="Could not set up encoder for output file: %1 File: %1 Path: %2 Error: %3">Не може да се създаде енкодер за изходния файл: %1 Файл: %1 Път: %2</entry>
<entry id="7104" string="Could not set up DSP processor: %1 Error: %2">Не може да се създаде DSP процесор: %1 Грешка: %2</entry>
<entry id="7105" string="Unable to access input file: %1 File: %1 Path: %2">Няма достъп до входящия файл: %1 Файл: %1 Папка: %2</entry>
<entry id="7106" string="Unable to create output file: %1 File: %1 Path: %2">Не може да се създаде изходен файл: %1 Файл: %1 Папка: %2</entry>
<entry id="7107" string="Failed to verify input file: %1">Неуспешна проверка на входящия файл: %1</entry>
<entry id="7108" string="Failed to verify input track: %1">Неуспешна проверка на входящата песен: %1</entry>
<entry id="7109" string="Checksum mismatch verifying output file: %1 Encode checksum: %2 Verify checksum: %3">Несъответствие в контролна сума за проверка на изходния файл: %1 Кодираща сума: %2 Проверка на контролна сума: %3</entry>
<entry id="7110" string="File not found">Файлът не е открит</entry>
<entry id="7111" string="Unknown file type">Неизвестен тип файл</entry>
<entry id="7112" string="Invalid file format">Невалиден файлов формат</entry>
<entry id="7113" string="Unsupported audio format">Неподдържан аудио формат</entry>
<entry id="7114" string="Unknown error">Неизвестна грешка</entry>
<entry id="7115" string="Unable to load NT SCSI drivers! CD ripping disabled!">Невъзможно е да се заредят NT SCSI драйверите! CD извличането е изключено!</entry>
<entry id="7116" string="Unable to open file: %1 Error: %2">Невъзможно е да се отвари файл: %1 Грешка: %2</entry>
<entry id="7117" string="Cannot play a CD track while ripping from the same drive!">Не може да се възпроизвежда песен от CD, докато се извлича от същото устройство!</entry>
<entry id="7118" string="Cannot start ripping while playing a track from the same drive!">Не може да се стартира извличане, докато се възпроизвежда песен от същото устройство!</entry>
<entry id="7119" string="CDDB support is disabled! Please enable local or remote CDDB support in the configuration dialog.">Поддръжката за CDDB е изключена! Включете поддръжка за местна или отдалечена CDDB в конфигурационния прозорец.</entry>
<entry id="7120" string="Remote CDDB support is disabled! Please enable remote CDDB support in the configuration dialog.">Отдалечената поддръжка за CDDB е изключена! Включете поддръжка за отдалечена CDDB в конфигурационния прозорец.</entry>
<entry id="7121" string="Access to CD-ROM drives was denied by Windows. Please contact your system administrator in order to be granted the right to access the CD-ROM drive.">Достъпът до CD-ROM устройствата е отказан от Windows. Свържете се с вашия системен администратор за да получите достъп до CD-ROM устройството.</entry>
<entry id="7122" string="No configuration dialog available for: %1">Не е наличен конфигурационен прозорец за: %1</entry>
<entry id="7123" string="The selected folder does not exist anymore!">Избраната папка вече не съществува!</entry>
<entry id="7124" string="Access denied"/>
</section>
<section name="Dialogs">
<section name="Overwrite">
<entry id="8000" string="Confirm overwrite">Потвърждаване на презаписа</entry>
<entry id="8001" string="Confirm">Потвърди</entry>
<entry id="8002" string="Skip all">Пропусни всички</entry>
<entry id="8003" string="The following %1 files already exist or have duplicate file names">Следните %1 файлове вече съществуват или имат дублиращи се имена на файловете</entry>
<entry id="8004" string="Action">Действие</entry>
<entry id="8005" string="Overwrite">Презапис</entry>
<entry id="8006" string="Skip">Пропускане</entry>
</section>
<section name="Format">
<entry id="8100" string="Select sample format">Избиране семплиращ формат</entry>
<entry id="8101" string="The selected tracks have different sample formats. Please select the desired sample format of the output file:">Избраните песни имат различни семплиращи формати. Изберете желаният семплиращ формат на изходния файл:</entry>
<entry id="8102" string="Select">Избиране...</entry>
</section>
<section name="Errors">
<entry id="8200" string="Errors">Грешки</entry>
<entry id="8201" string="%1 errors while processing job">%1 грешки при обработката на задачата</entry>
<entry id="8202" string="select an entry for details">избиране на запис за подробни данни</entry>
</section>
</section>
<section name="Ripper">
<entry id="9000" string="Active CD-ROM drive">Активно CD-ROM устройство</entry>
<entry id="9001" string="Set drive speed limit">Пределна скорост</entry>
<entry id="9002" string="CD information">CD информация</entry>
<entry id="9003" string="Read CD Text">Четене на CD Текст</entry>
<entry id="9004" string="Read cdplayer.ini">Четене на cdplayer.ini</entry>
<entry id="9005" string="Ripper settings">Ripper настройки</entry>
<entry id="9006" string="Activate cdparanoia mode">CD параноя режим</entry>
<entry id="9007" string="Overlap only">Само препокриване</entry>
<entry id="9008" string="No verify">Без проверка</entry>
<entry id="9009" string="No scratch repair">Без поправка за надраскване</entry>
<entry id="9010" string="Full cdparanoia mode">Пълен cdparanoia режим</entry>
<entry id="9011" string="Activate jitter correction">Корекция на колебанията</entry>
<entry id="9012" string="Switch stereo channels">Превключване стерео каналите</entry>
<entry id="9013" string="Automatization">Автоматизация</entry>
<entry id="9014" string="Read CD contents on insert">Четене на CD при поставяне</entry>
<entry id="9015" string="Start ripping automatically">Авт. старт на извличането</entry>
<entry id="9016" string="Eject disk after ripping">Извади CD след извличането</entry>
<entry id="9017" string="CD options">CD настройки</entry>
<entry id="9018" string="Use read offset">Изместване при четене</entry>
<entry id="9019" string="samples">образец</entry>
<entry id="9020" string="Read ISRC when adding tracks to joblist">Четене на ISRC при добавяне на песни към задачите</entry>
<entry id="9021" string="Spin up before ripping">Завъртане преди извличане</entry>
<entry id="9022" string="%1 seconds">%1 секунди</entry>
</section>
<section name="Components">
<section name="Decoders">
<entry id="10000" string="Cue Sheet Reader">Cue лист четец</entry>
</section>
<section name="Encoders">
<entry id="11000" string="meh! - multi encoder hub">meh! - мулти енкодер хъб</entry>
<entry id="11001" string="SndFile Output Component">SndFile изходен компонент</entry>
</section>
<section name="DSP">
<entry id="12000" string="Channel Converter">Конвертор Канали</entry>
<entry id="12001" string="Sample Format Converter">Конвертор примерни формати</entry>
<entry id="12002" string="Sample Rate Converter">Конвертор Честота (Hz)</entry>
<entry id="12003" string="RNNoise Noise Reduction">Намаляване шума RNNoise</entry>
<entry id="12004" string="Rubber Band Tempo/Pitch Changer">Промяна Темпо/Тоналност на звука</entry>
</section>
<section name="Extensions">
<entry id="15000" string="Notifications">Съобщение за Преобразуване</entry>
<entry id="15001" string="Logging">Протокол</entry>
<entry id="15002" string="YouTube Video Downloader">YouTube видео изтегляне</entry>
</section>
</section>
<section name="Decoders">
<section name="MAD">
<entry id="20000" string="Decoding">Декодиране</entry>
<entry id="20001" string="Enable 24 bit decoding">Включено 24 битово декодиране</entry>
</section>
<section name="mpg123">
<entry id="21000" string="Decoder">Декодер</entry>
<entry id="21001" string="Active decoder">Активен декодер</entry>
<entry id="21002" string="auto select">Автоматичен избор</entry>
</section>
<section name="CueSheet">
<entry id="22000" string="Title information">Информация за заглавието</entry>
<entry id="22001" string="Read tags from referenced files">Четене на етикетите от референтни файлове</entry>
<entry id="22002" string="Prefer cue sheet metadata over referenced files' tags">Предпочитане CUE лист с метаданни пред файлове с тагове</entry>
<entry id="22003" string="Alternative files">Алтернативни файлове</entry>
<entry id="22004" string="Look for compressed alternatives if referenced Wave files cannot be located">Търсене на компресирани алтернативи, ако не се намерят Wave файлове</entry>
<entry id="22005" string="Error handling">Обработка на грешките</entry>
<entry id="22006" string="Ignore errors during cue sheet processing">Игнориране на грешките при обработката на CUE лист</entry>
</section>
</section>
<section name="Encoders">
<section name="BladeEnc">
<entry id="30000" string="Bitrate">Bitrate</entry>
<entry id="30001" string="Copyright bit">Авторско право</entry>
<entry id="30002" string="CRC">CRC</entry>
<entry id="30003" string="Original bit">Оригинал</entry>
<entry id="30004" string="Channels">Канали</entry>
<entry id="30005" string="Private bit">Личен право</entry>
<entry id="30006" string="Set Copyright bit">Задаване Авторско право</entry>
<entry id="30007" string="Enable CRC">Включен CRC</entry>
<entry id="30008" string="Set Original bit">Зад. Ориг. bit</entry>
<entry id="30009" string="Dual channel encoding">Кодиране на два канала</entry>
<entry id="30010" string="Set Private bit">Задаване Лично право</entry>
</section>
<section name="Bonk">
<entry id="31000" string="Encoder mode">Режим на кодиране</entry>
<entry id="31001" string="Stereo mode">Стерео режим</entry>
<entry id="31002" string="Quantization">Квантуване</entry>
<entry id="31003" string="Downsampling ratio">Коефициент на понижено семплиране</entry>
<entry id="31004" string="Predictor size">Предсказване на размера</entry>
<entry id="31005" string="Enable lossless encoding">Кодиране без загуба</entry>
<entry id="31006" string="Enable Joint Stereo">Включено Joint Stereo</entry>
</section>
<section name="LAME">
<entry id="32000" string="Basic">Основни</entry>
<entry id="32001" string="Misc">Разни</entry>
<entry id="32002" string="Expert">Експертни</entry>
<entry id="32003" string="Audio processing">Аудио обработка</entry>
<section name="Basic">
<entry id="32100" string="Presets">Предварителна настройки</entry>
<entry id="32101" string="Use preset">Използване предв. настройка</entry>
<entry id="32102" string="Custom settings">Собствени настройки</entry>
<entry id="32103" string="Medium">Средно</entry>
<entry id="32104" string="Standard">Стандартно</entry>
<entry id="32105" string="Extreme">Пределно</entry>
<entry id="32106" string="Bitrate">Bitrate</entry>
<entry id="32107" string="Quality">Качество</entry>
<entry id="32108" string="Set bitrate">Зад. bitrate</entry>
<entry id="32109" string="Set ratio">Зад. съотношение</entry>
<entry id="32110" string="Set quality">Зададено качество</entry>
<entry id="32111" string="worse">лошо</entry>
<entry id="32112" string="better">добро</entry>
<entry id="32113" string="VBR mode">VBR режим</entry>
<entry id="32114" string="no VBR">без VBR</entry>
<entry id="32115" string="VBR quality">VBR качество</entry>
<entry id="32116" string="ABR target bitrate">ABR целеви bitrate</entry>
</section>
<section name="Misc">
<entry id="32200" string="Control bits">Контролни маркери</entry>
<entry id="32201" string="Set Copyright bit">Зад.Авторско право</entry>
<entry id="32202" string="Set Original bit">Зад. Оригинал</entry>
<entry id="32203" string="Set Private bit">Зад. Лично право</entry>
<entry id="32204" string="CRC">CRC</entry>
<entry id="32205" string="Enable CRC">Включено CRC</entry>
<entry id="32206" string="Stereo mode">Стерео режим</entry>
<entry id="32207" string="auto">автоматично</entry>
<entry id="32208" string="Stereo">Стерео</entry>
<entry id="32209" string="Joint Stereo">Joint Stereo</entry>
<entry id="32210" string="Force Joint Stereo">Принудително Joint Stereo</entry>
<entry id="32211" string="VBR bitrate range">Диапазон на VBR bitrate</entry>
<entry id="32212" string="Set minimum VBR bitrate">Зад. миним. VBR bitrate</entry>
<entry id="32213" string="Set maximum VBR bitrate">Максимален VBR bitrate</entry>
</section>
<section name="Expert">
<entry id="32300" string="ATH">ATH</entry>
<entry id="32301" string="Enable ATH">Включ. ATH</entry>
<entry id="32302" string="Use default setting">Използване на настройка по подразбиране</entry>
<entry id="32303" string="Psycho acoustic model">Психо акустичен модел</entry>
<entry id="32304" string="Use Temporal Masking Effect">Използване времеви маскиращ ефект</entry>
<entry id="32305" string="Stream format">Формат на потока</entry>
<entry id="32306" string="Enforce strict ISO compliance">Стриктно прилагане спазването на ISO</entry>
</section>
<section name="Audio processing">
<entry id="32400" string="Highpass filter">Филтър за ВИСОКИ честоти</entry>
<entry id="32401" string="Set Highpass frequency (Hz)">Зададена висока честота (Hz)</entry>
<entry id="32402" string="Set Highpass width (Hz)">Зад.ширина висока честота(Hz)</entry>
<entry id="32403" string="Lowpass filter">Филтър за ниски честоти</entry>
<entry id="32404" string="Set Lowpass frequency (Hz)">Зададена ниска честота (Hz)</entry>
<entry id="32405" string="Set Lowpass width (Hz)">Зад.ширина ниска честота (Hz)</entry>
<entry id="32406" string="Misc settings">Разни настройки</entry>
<entry id="32407" string="Disable all filtering">Изкл. всички филтри</entry>
</section>
</section>
<section name="AAC">
<entry id="33000" string="Codec">Кодек</entry>
<entry id="33001" string="Quality">Качество</entry>
<entry id="33002" string="Format">Формат</entry>
<section name="Codec">
<entry id="33100" string="Audio codec">Аудио кодек</entry>
</section>
<section name="Quality">
<entry id="33200" string="Bitrate">Bitrate</entry>
<entry id="33201" string="Bitrate / Quality">Bitrate / Качество</entry>
<entry id="33202" string="Bitrate per channel">Bitrate на канал</entry>
<entry id="33203" string="Set quality">Зададено качество</entry>
<entry id="33204" string="Stereo mode">Стерео режим</entry>
<entry id="33205" string="Allow Joint Stereo">Позволено Joint Stereo</entry>
<entry id="33206" string="Temporal Noise Shaping">Временно ограничение на шума</entry>
<entry id="33207" string="Use Temporal Noise Shaping">Използв.вр.огранич.на шума</entry>
<entry id="33208" string="Maximum bandwidth">Макс. широколентова честота</entry>
<entry id="33209" string="Maximum AAC frequency bandwidth to use (Hz)">Макс. използв. широколентова честота на AAC (Hz)</entry>
</section>
<section name="Format">
<entry id="33300" string="MPEG version">MPEG версия</entry>
<entry id="33301" string="AAC object type">Тип AAC обект</entry>
<entry id="33302" string="File format">Файлов формат</entry>
<entry id="33303" string="File extension">Разширение файл</entry>
<entry id="33304" string="Tags">Тагове</entry>
<entry id="33305" string="Allow ID3v2 tags in AAC files">Позволено ID3v2 тагове в AAC файлове</entry>
<entry id="33306" string="Note">Забележка</entry>
<entry id="33307" string="Some players may have problems playing AAC files with ID3 tags attached. Please use this option only if you are sure that your player can handle these tags.">Някои устройства могат да имат проблем с AAC файлове с ID3 тагове. Използвайте само ако сте сигурни, че вашия плеър може да прочете тези тагове.</entry>
</section>
</section>
<section name="FLAC">
<entry id="34000" string="Basic">Основни</entry>
<entry id="34001" string="Format">Формат</entry>
<entry id="34002" string="Expert">Експертни</entry>
<section name="Basic">
<entry id="34100" string="Presets">Предварителна настройки</entry>
<entry id="34101" string="Use preset">Използване предв.настройка</entry>
<entry id="34102" string="Custom settings">Собствени настройки</entry>
<entry id="34103" string="Fastest encoding">Бързо кодиране</entry>
<entry id="34104" string="Best compression">Добра компресия</entry>
<entry id="34105" string="Stereo mode">Стерео режим</entry>
<entry id="34106" string="Joint Stereo">Joint Stereo</entry>
<entry id="34107" string="Adaptive Joint Stereo">Адаптивно Joint Stereo</entry>
<entry id="34108" string="File format">Файлов формат</entry>
<entry id="34109" string="Default">По подразбиране</entry>
</section>
<section name="Format">
<entry id="34200" string="Use streamable subset">Използване поточна поднастройка</entry>
<entry id="34201" string="Blocksize">Размер на блока</entry>
<entry id="34202" string="%1 samples">%1 образец</entry>
</section>
<section name="Expert">
<entry id="34300" string="Signal processing">Обработка на сигнала</entry>
<entry id="34301" string="Window function(s)">Функция(и) на прозореца</entry>
<entry id="34302" string="Note">Забележка</entry>
<entry id="34303" string="You can specify multiple functions separated by semicolons.">Може да посочите повече функции разделени с ;</entry>
<entry id="34304" string="Linear predictor">Линейно предсказване</entry>
<entry id="34305" string="Maximum LPC order">Максимално LPC подреждане</entry>
<entry id="34306" string="disabled">изключено</entry>
<entry id="34307" string="Exhaustive model search">Пълен модел за търсене</entry>
<entry id="34308" string="Quantized LPC precision">Квантувана точност на LPC</entry>
<entry id="34309" string="auto">автоматично</entry>
<entry id="34310" string="Optimize LPC quantization">Оптимизиране на LPC квантуването</entry>
<entry id="34311" string="Residual coding">Остатъчно кодиране</entry>
<entry id="34312" string="Minimum partition order">Миним. подреждане на дяловете</entry>
<entry id="34313" string="Maximum partition order">Макс. подреждане на дяловете</entry>
</section>
</section>
<section name="Vorbis">
<entry id="35000" string="Encoding Mode">Режим на кодиране</entry>
<entry id="35001" string="Variable Bitrate">Променлив Bitrate</entry>
<entry id="35002" string="Average Bitrate">Среден Bitrate</entry>
<entry id="35003" string="Quality">Качество</entry>
<entry id="35004" string="Bitrate">Bitrate</entry>
<entry id="35005" string="Minimum bitrate">Миним. bitrate</entry>
<entry id="35006" string="Average bitrate">Среден bitrate</entry>
<entry id="35007" string="Maximum bitrate">Макс. bitrate</entry>
<entry id="35008" string="File extension">Разширение файл</entry>
</section>
<section name="WMA">
<entry id="36000" string="Select codec">Избор на кодек</entry>
<entry id="36001" string="Select codec format">Избор формат на кодека</entry>
<entry id="36002" string="Codec settings">Настройки на кодека</entry>
<entry id="36003" string="Use codec">Използван кодек</entry>
<entry id="36004" string="Use format">Използван формат</entry>
<entry id="36005" string="Write uncompressed WMA files">Записване на некомпресирани WMA файлове</entry>
<entry id="36006" string="Automatically select format based on settings and input format">Авт. избор въз основа на настройките и входящия формат</entry>
<entry id="36007" string="Use VBR encoding">VBR кодиране</entry>
<entry id="36008" string="Quality">Качество</entry>
<entry id="36009" string="Target bitrate">Целеви bitrate</entry>
<entry id="36010" string="Use 2-pass encoding">Кодиране на 2 етапа</entry>
</section>
<section name="TwinVQ">
<entry id="37000" string="Bitrate">Bitrate</entry>
<entry id="37001" string="Bitrate per channel">Bitrate на канал</entry>
<entry id="37002" string="Preselection">Предвар. избор</entry>
<entry id="37003" string="Number of preselection candidates">Брой предвар. избрани варианти</entry>
</section>
<section name="Monkey's Audio">
<entry id="38000" string="Compression">Компресия</entry>
<entry id="38001" string="Compression mode">Режим на компресия</entry>
<entry id="38002" string="Fast">Бързо</entry>
<entry id="38003" string="Normal">Нормално</entry>
<entry id="38004" string="High">Високо</entry>
<entry id="38005" string="Extra high">Много високо</entry>
<entry id="38006" string="Insane">Безумно</entry>
</section>
<section name="Speex">
<entry id="39000" string="Profile">Профил</entry>
<entry id="39001" string="Select encoding profile">Избор профил на кодиране</entry>
<entry id="39002" string="auto">автоматично</entry>
<entry id="39003" string="Narrowband (8 kHz)">Теснолентов (8 kHz)</entry>
<entry id="39004" string="Wideband (16 kHz)">Широколентов (16 kHz)</entry>
<entry id="39005" string="Ultra-Wideband (32 kHz)">Ултра-Широколентов (32 kHz)</entry>
<entry id="39006" string="VBR mode">VBR режим</entry>
<entry id="39007" string="CBR (no VBR)">CBR (без VBR)</entry>
<entry id="39008" string="VBR">VBR</entry>
<entry id="39009" string="ABR">ABR</entry>
<entry id="39010" string="Options">Опции</entry>
<entry id="39011" string="Voice Activity Detection">Засичане Гласова активност</entry>
<entry id="39012" string="Discontinuous Transmission">Прекъсване на Трансфера</entry>
<entry id="39013" string="Algorithm complexity">Сложност на алгоритъма</entry>
<entry id="39014" string="Complexity">Сложност</entry>
<entry id="39015" string="CBR quality">CBR качество</entry>
<entry id="39016" string="VBR quality">VBR качество</entry>
<entry id="39017" string="ABR target bitrate">ABR целеви bitrate</entry>
<entry id="39018" string="Bitrate">Bitrate</entry>
<entry id="39019" string="Quality">Качество</entry>
<entry id="39020" string="Max. bitrate">Макс. bitrate</entry>
</section>
<section name="Opus">
<entry id="40000" string="Basic settings">Основни настройки</entry>
<entry id="40001" string="Encoding mode">Режим на кодиране</entry>
<entry id="40002" string="auto">автоматично</entry>
<entry id="40003" string="Voice">Глас</entry>
<entry id="40004" string="Music">Музика</entry>
<entry id="40005" string="Bandwidth">Широколентова честота</entry>
<entry id="40006" string="Narrowband">Теснолентова честота</entry>
<entry id="40007" string="Mediumband">Среднолентова честота</entry>
<entry id="40008" string="Wideband">Обширна чест.лента</entry>
<entry id="40009" string="Superwideband">Супер обширна чест.лента</entry>
<entry id="40010" string="Fullband">Пълна чест. лента</entry>
<entry id="40011" string="File extension">Разширение файл</entry>
<entry id="40012" string="Variable bitrate">Променлив bitrate</entry>
<entry id="40013" string="Enable variable bitrate encoding">Включено кодиране в променлив bitrate</entry>
<entry id="40014" string="Constrain bitrate to target value">Ограничение на bitrate до целевата стойност</entry>
<entry id="40015" string="Quality">Качество</entry>
<entry id="40016" string="Bitrate">Bitrate</entry>
<entry id="40017" string="Complexity">Сложност</entry>
<entry id="40018" string="Stream">Поток</entry>
<entry id="40019" string="Frame length">Времетраене</entry>
<entry id="40020" string="Options">Опции</entry>
<entry id="40021" string="Enable discontinous transmission">Включен непрекъснат трансфер</entry>
<entry id="40022" string="Expected packet loss">Очакван пакет loss(със загуба)</entry>
</section>
<section name="SndFile">
<entry id="41000" string="Output format">Изходен формат</entry>
<entry id="41001" string="File format">Файлов формат</entry>
<entry id="41002" string="Audio format">Аудио формат</entry>
<entry id="41003" string="mono">моно</entry>
<entry id="41004" string="auto select">Автоматичен избор</entry>
<section name="Errors">
<entry id="41100" string="Could not find suitable audio format.">Не може да се намери подходящ аудио формат.</entry>
<entry id="41101" string="Unable to use selected audio format.">Не може да се използва избраният аудио формат.</entry>
</section>
</section>
<section name="meh!">
<entry id="42000" string="Encoders">Енкодери</entry>
<entry id="42001" string="Available">Налични</entry>
<entry id="42002" string="Selected">Избрани</entry>
<entry id="42003" string="Configure encoder">Конфигуриране на енкодера</entry>
<entry id="42004" string="Options">Опции</entry>
<entry id="42005" string="Create a separate folder for each output format">Създаване отделна папка за всеки изходен формат</entry>
</section>
</section>
<section name="DSP">
<section name="Format">
<entry id="50000" string="Sample format">Семплиращ формат</entry>
<entry id="50001" string="Number format">Номер на формата</entry>
<entry id="50002" string="Sample resolution">Семплираща резолюция</entry>
<entry id="50003" string="bit">bit</entry>
<entry id="50004" string="unsigned">неподписан</entry>
<entry id="50005" string="Integer">цяло число</entry>
<entry id="50006" string="Float">Плаващо</entry>
</section>
<section name="Channels">
<entry id="50100" string="Output channels">Изходни канали</entry>
<entry id="50101" string="Channel configuration">Конфигурация на канала</entry>
<entry id="50102" string="Mono">Моно</entry>
<entry id="50103" string="Stereo">Стерео</entry>
<entry id="50104" string="Switch stereo channels">Превключване стерео каналите</entry>
</section>
<section name="Resample">
<entry id="50200" string="Converter">Конвертор</entry>
<entry id="50201" string="Sampling rate">Семплираща честота</entry>
<entry id="50202" string="Output sampling rate">Изходна семплираща честота</entry>
</section>
<section name="RubberBand">
<entry id="50300" string="Basic controls">Основни елементи за управление</entry>
<entry id="50301" string="Tempo">Темпо</entry>
<entry id="50302" string="Pitch">Стъпка</entry>
<entry id="50303" string="%1 Semitones">%1 полутонове</entry>
<entry id="50304" string="Advanced options">Допълнителни опции</entry>
<entry id="50305" string="Transient detection">Временно откриване</entry>
<entry id="50306" string="Compound">Сложно</entry>
<entry id="50307" string="Percussive">Ударно</entry>
<entry id="50308" string="Soft">Меко</entry>
<entry id="50309" string="Transient handling">Временна обработка</entry>
<entry id="50310" string="Crisp">Чисто</entry>
<entry id="50311" string="Mixed">Смесено</entry>
<entry id="50312" string="Smooth">Гладко</entry>
<entry id="50313" string="Transformation window">Трансформация на прозореца</entry>
<entry id="50314" string="Standard">Стандартен</entry>
<entry id="50315" string="Short">Кратък</entry>
<entry id="50316" string="Long">Дълъг</entry>
<entry id="50317" string="Use time-domain smoothing">Включ. време-домейн изглаждане</entry>
<entry id="50318" string="Phase handling">Фаза обработка</entry>
<entry id="50319" string="Laminar">Ламинарно</entry>
<entry id="50320" string="Independent">Независимо</entry>
<entry id="50321" string="Formant handling">Формантна обработка</entry>
<entry id="50322" string="Shift">Променлива</entry>
<entry id="50323" string="Preserve">Постоянна</entry>
<entry id="50324" string="Pitch processing">Обработка на процеса</entry>
<entry id="50325" string="High quality">Високо качество</entry>
<entry id="50326" string="High speed">Висока скорост</entry>
<entry id="50327" string="High consistency">Висока плътност</entry>
<entry id="50328" string="Stereo processing">Стерео обработка</entry>
<entry id="50329" string="Separate">Поотделно</entry>
<entry id="50330" string="Combined">Комбинирано</entry>
</section>
<section name="RNNoise">
<entry id="50400" string="Signal/noise type">Тип - Сигнал/Шум</entry>
<entry id="50401" string="Signal type">Тип сигнал</entry>
<entry id="50402" string="Noise type">Тип шум</entry>
<entry id="50403" string="General">Общо</entry>
<entry id="50404" string="Recording">Запис</entry>
<entry id="50405" string="Voice (incl. laughter etc.)">Глас (вкл. смях и др.)</entry>
<entry id="50406" string="Speech">Говор</entry>
</section>
</section>
<section name="Taggers">
<section name="MP4">
<entry id="60000" string="Chapter format">Формат на главата</entry>
<entry id="60001" string="both">и двете</entry>
</section>
</section>
<section name="External">
<entry id="80000" string="Downmix multi-channel audio to stereo">Низходящ микс многоканално аудио към стерео</entry>
<section name="Musepack Audio Encoder">
<entry id="80100" string="Quality">Качество</entry>
<entry id="80101" string="poor">лошо</entry>
<entry id="80102" string="excellent">отлично</entry>
<entry id="80103" string="Mid/Side stereo mode">Среден/Страничен стерео режим</entry>
<entry id="80104" string="off">слабо</entry>
<entry id="80105" string="reduced">ограничено</entry>
<entry id="80106" string="on">крайно</entry>
<entry id="80107" string="decoupled">отделено</entry>
<entry id="80108" string="enhanced 1.5/3 dB">подобрено 1.5/3 dB</entry>
<entry id="80109" string="enhanced 2/6 dB">подобрено 2/6 dB</entry>
<entry id="80110" string="enhanced 2.5/9 dB">подобрено 2.5/9 dB</entry>
<entry id="80111" string="enhanced 3/12 dB">подобрено 3/12 dB</entry>
<entry id="80112" string="enhanced 3/inf dB">подобрено 3/безкрайно dB</entry>
<entry id="80113" string="Adaptive noise shaping order">Ред за адаптивно оформяне на шума</entry>
<entry id="80114" string="high">високо</entry>
<entry id="80115" string="Clear Voice Detection">Ясно разпознаване на глас</entry>
<entry id="80116" string="dual">двойно</entry>
</section>
<section name="OptimFROG Lossless Encoder">
<entry id="80200" string="Encoding mode">Режим на кодиране</entry>
<entry id="80201" string="fast">бързо</entry>
<entry id="80202" string="normal">нормално</entry>
<entry id="80203" string="high">високо</entry>
<entry id="80204" string="extra">екстра</entry>
<entry id="80205" string="best">най-добро</entry>
<entry id="80206" string="high, new">високо, ново</entry>
<entry id="80207" string="extra, new">екстра, ново</entry>
<entry id="80208" string="best, new">най-добро, ново</entry>
<entry id="80209" string="Add MD5 checksum">Съхраняване MD5 на оригиналните PCM данни</entry>
<entry id="80210" string="Seeking">Търсене</entry>
<entry id="80211" string="slow">бавно</entry>
<entry id="80212" string="minimum">минимално</entry>
<entry id="80213" string="Optimization">Оптимизация</entry>
<entry id="80214" string="disabled">изключено</entry>
<entry id="80215" string="low">ниско</entry>
</section>
<section name="Tom's Audiokompressor">
<entry id="80300" string="Encoder preset">Предварителна настройка на енкодера</entry>
<entry id="80301" string="fastest">най-бързо</entry>
<entry id="80302" string="strongest">най-силно</entry>
<entry id="80303" string="Frame size limit">Ограничение за размера на оформянето</entry>
<entry id="80304" string="Add MD5 checksum">Добавяне на MD5 контролна сума</entry>
</section>
<section name="WavPack Audio Encoder">
<entry id="80400" string="Enable lossy compression">Включена компресия със загуби</entry>
<entry id="80401" string="Compression mode">Режим на компресия</entry>
<entry id="80402" string="fast">бърза</entry>
<entry id="80403" string="high quality">високо качество</entry>
<entry id="80404" string="very high quality">много високо качество</entry>
<entry id="80405" string="Extra encode processing">Допълнителна обработка на кодиране</entry>
<entry id="80406" string="faster">по-бързо</entry>
<entry id="80407" string="better">по-добро</entry>
<entry id="80408" string="%1 kbps">%1 kbps</entry>
</section>
<section name="Nero AAC Encoder">
<entry id="80500" string="Encoding mode">Режим на кодиране</entry>
<entry id="80501" string="auto">автоматично</entry>
<entry id="80502" string="Quality">Качество</entry>
<entry id="80503" string="worse">лошо</entry>
<entry id="80504" string="better">добро</entry>
<entry id="80505" string="Bitrate">Bitrate</entry>
<entry id="80506" string="Bitrate (Streaming)">Bitrate (Поточно)</entry>
<entry id="80507" string="%1 kbps">%1 kbps</entry>
</section>
<section name="Windows Media Audio Encoder">
<entry id="80600" string="Bitrate">Bitrate</entry>
<entry id="80601" string="%1 kbps">%1 kbps</entry>
</section>
</section>
<section name="Extensions">
<section name="Donate">
<entry id="100000" string="Support this project">Подкрепа за този проект</entry>
<entry id="100001" string="Please support this project!">Моля, подкрепете този проект!</entry>
<entry id="100002" string="Please help keep this software free by supporting the %1 project with a donation.">Помогнете за развитието на този безплатен софтуер, като подкрепите проекта %1 с дарение.</entry>
<entry id="100003" string="Please write to %1 if you would like to mail a check or send money by mail.">Пишете до %1, ако желаете да направите дарение, използвайки електронното разплащане, изпращане на чек или пари по пощата.</entry>
<entry id="100004" string="Thank you very much!">Много Ви благодаря!</entry>
<entry id="100005" string="Remind me later">Напомни ми по-късно</entry>
<entry id="100006" string="paypal,donorbox,bitcoin,ethereum">paypal,donorbox,sepa,bitcoin,ethereum</entry>
<entry id="100007" string="Donate to the %1 project">Дарете за проекта %1</entry>
<section name="PayPal">
<entry id="100100" string="Choose an amount and click the button to make a donation with PayPal:">Щракнете един от бутоните по-долу за да направите дарение през PayPal:</entry>
<entry id="100101" string="You can also send money directly to %1 with PayPal.">Можете също да пратите пари директно до %1 през PayPal.</entry>
<entry id="100102" string="usd">bgn</entry>
<entry id="100103" string="$%1">%1 лв.</entry>
<entry id="100104" string="5,10,20,other amount">5,10,20,друга сума</entry>
<entry id="100105" string="monthly recurring">ежемесечно повтарящи се</entry>
<entry id="100106" string="Donate">Дарете</entry>
</section>
<section name="Donorbox">
<entry id="100200" string="Donorbox enables quick and simple donations by credit card. Click this button to make a donation with Donorbox:">Donorbox позволява бързо и лесно дарения с кредитна карта. Щракнете върху този бутон, за да направите дарение с Donorbox:</entry>
<entry id="100201" string="Donate">Дарете</entry>
<entry id="100202" string="usd">eur</entry>
</section>
<section name="Bitcoin">
<entry id="100300" string="Please scan or click the QR code or copy the following address to donate Bitcoin:">Моля, сканирайте или кликнете върху QR кода или копирайте следния адрес, за да дарите с Bitcoin:</entry>
<entry id="100301" string="This address also accepts Bitcoin Cash and other forks.">Този адрес приема също Bitcoin кеш и други.</entry>
</section>
<section name="Ethereum">
<entry id="100400" string="Please scan or click the QR code or copy the following address to donate Ethereum:">Моля, сканирайте или кликнете върху QR кода или копирайте следния адрес, за да дарите с Ethereum:</entry>
<entry id="100401" string="This address also accepts Ether Classic and ERC20 tokens.">Този адрес също приема Ether Classic и ERC20 tokens.</entry>
</section>
<section name="SEPA">
<entry id="100500" string="You can donate by making an electronic transfer to the following account:">Можете да направите дарение, чрез електронен превод на следната сметка:</entry>
<entry id="100501" string="Account holder:">Титуляр на сметката:</entry>
<entry id="100502" string="IBAN:">IBAN:</entry>
<entry id="100503" string="BIC:">BIC:</entry>
</section>
</section>
<section name="Winamp Adapter">
<entry id="101000" string="Configure">Конфигурация</entry>
<entry id="101001" string="About">Относно</entry>
</section>
<section name="Video Downloader">
<entry id="102000" string="Video">Видео</entry>
<entry id="102001" string="Enter video URL here">Въведете адреса на видеото тук</entry>
<entry id="102002" string="Download">Изтегляне</entry>
<entry id="102003" string="Automatically download URLs copied to clipboard">Автоматично изтегляне адресите копирани в буфера</entry>
<entry id="102004" string="Save downloaded video files">Запис на изтеглените видео файлове</entry>
<entry id="102005" string="Video downloads">Видео изтегляния</entry>
<entry id="102006" string="Downloaded tracks">Изтеглени песни</entry>
<entry id="102007" string="Uploader">Качване</entry>
<entry id="102008" string="Video URL">URL адрес на видеото</entry>
<entry id="102009" string="Video title">Заглавие на видеото</entry>
<entry id="102010" string="Video description">Описание на видеото</entry>
<entry id="102011" string="Site name">Име на сайта</entry>
<entry id="102012" string="Uploaded by">Качено от</entry>
<entry id="102013" string="Uploaded on">Качено на</entry>
<entry id="102014" string="Length">Времетраене</entry>
<entry id="102015" string="Size">Размер</entry>
<entry id="102016" string="Cancel download">Отмяна изтегляне</entry>
<entry id="102017" string="unknown">неизвестно</entry>
<entry id="102018" string="Note">Забележка</entry>
<section name="Configuration">
<entry id="102101" string="Automatization">Автоматизация</entry>
<entry id="102102" string="Video files">Видео файлове</entry>
<entry id="102103" string="Select">Избиране...</entry>
<entry id="102104" string="Select the folder to save downloaded video files to">Изберете папка за записване на изтеглените файлове</entry>
<entry id="102105" string="Downloads">Изтегляния</entry>
<entry id="102106" string="Maximum number of simultaneous downloads">Макс. брой на паралелните изтегляния</entry>
<entry id="102107" string="Output format">Изходен формат</entry>
<entry id="102108" string="keep original format">запазване на ориг. формат</entry>
</section>
<section name="Errors">
<entry id="102201" string="This URL is not supported or not a video page URL!">Този URL адрес не е поддържан или не е URL адрес на видео страница!</entry>
<entry id="102202" string="Error downloading video!">Грешка при изтегляне на видеото!</entry>
<entry id="102203" string="You are already downloading this video!">Вече изтегляте това видео!</entry>
<entry id="102204" string="Some required video decoders could not be found. Video files cannot be added to the joblist for conversion to audio files. Please install FFmpeg or avconv to fix this problem!">Някои нужни видео декодери не могат да бъдат открити. Видео файловете не могат да бъдат добавени към списъка със задачи за преобразуване в аудио файлове. Инсталирайте FFmpeg или avconv за отстраняване проблема!</entry>
</section>
</section>
<section name="Tag Editor">
<entry id="103000" string="Tags">Тагове</entry>
<entry id="103001" string="Length">Времетраене</entry>
<entry id="103002" string="Size">Размер</entry>
<entry id="103003" string="Albums">Албуми</entry>
<entry id="103004" string="Files">Файлове</entry>
<entry id="103005" string="File">Файл</entry>
<entry id="103006" string="Tracks">Песни</entry>
<entry id="103007" string="Save">Запис</entry>
<entry id="103008" string="Save all">Запис всички</entry>
<entry id="103009" string="no audio files found">няма открити аудио файлове</entry>
<section name="Basic">
<entry id="103100" string="Basic">Основни</entry>
<entry id="103101" string="Title information">Информация за заглавието</entry>
<entry id="103102" string="Disc">Диск</entry>
<entry id="103103" string="Cover art">Обложка</entry>
<entry id="103104" string="Covers">Обложки</entry>
<entry id="103105" string="Type">Тип</entry>
<entry id="103106" string="Description">Описание</entry>
<entry id="103107" string="Add">Добавяне</entry>
<entry id="103108" string="Remove">Премахване</entry>
</section>
<section name="Details">
<entry id="103200" string="Details">Детайли</entry>
<entry id="103201" string="Detailed information">Детайлна информация</entry>
<entry id="103202" string="Band / orchestra">Група / Оркестър</entry>
<entry id="103203" string="Conductor">Аранжимент</entry>
<entry id="103204" string="Composer">Композитор</entry>
<entry id="103205" string="Lyrics writer">Текст</entry>
<entry id="103206" string="Modified / remixed by">Преработено / ремиксирано от</entry>
<entry id="103207" string="Publisher information">Инфо за издателя</entry>
<entry id="103208" string="Publisher / label">Издател / етикет</entry>
<entry id="103209" string="ISRC">ISRC</entry>
<entry id="103210" string="Tempo">Темпо</entry>
<entry id="103211" string="BPM">BPM</entry>
</section>
<section name="Other">
<entry id="103300" string="Other">Друго</entry>
<entry id="103301" string="Original information">Инфо за оригинала</entry>
<entry id="103302" string="Original artist">Ориг. изпълнител</entry>
<entry id="103303" string="Original album">Ориг. албум</entry>
<entry id="103304" string="Original lyrics writer">Ориг. текст</entry>
<entry id="103305" string="Original release year">Ориг. година на издаване</entry>
<entry id="103306" string="Webpage URLs">URL адреси на уебстраници</entry>
<entry id="103307" string="Artist webpage">Уебстраница-изпълнител</entry>
<entry id="103308" string="Publisher webpage">Уебстраница-издател</entry>
<entry id="103309" string="Internet radio station">Интернет радиостанция</entry>
<entry id="103310" string="Audio source webpage">Уебстраниц-аудио източник</entry>
<entry id="103311" string="Copyright information">Инфо за авторски права</entry>
<entry id="103312" string="Commercial information">Търговска информация</entry>
</section>
<section name="Errors">
<entry id="103400" string="Unable to open file: %1 Error: %2">Не може да се отвари файл: %1 Грешка: %2</entry>
<entry id="103401" string="Unable to update tag: %1 Error: %2">Не може да се обнови таг: %1 Грешка: %2</entry>
</section>
</section>
<section name="Logging">
<entry id="104000" string="Logs">Протоколи</entry>
<entry id="104001" string="Log">Протокол</entry>
<entry id="104002" string="Save as">Запиши като</entry>
<entry id="104003" string="Log Files">Лог файлове</entry>
<entry id="104004" string="Time">Време</entry>
<entry id="104005" string="Message">Съобщение</entry>
<section name="Configuration">
<entry id="104100" string="User interface">Потребителски интерфейс</entry>
<entry id="104101" string="Show Logs tab in main window">Показване раздел «Протоколи» в главния прозорец</entry>
<entry id="104102" string="Log files">Лог файлове</entry>
<entry id="104103" string="Archive log files">Архив на лог файлове</entry>
<entry id="104104" string="Log file folder">Папка за лог файлове</entry>
<entry id="104105" string="Select">Избиране...</entry>
<entry id="104106" string="Select the folder for saving log files">Изберете папка за записване на лог файлове</entry>
<entry id="104107" string="Delete old log files after">Изтриване стари лог файлове след</entry>
<entry id="104108" string="days">дни</entry>
<entry id="104109" string="Conversion logs">Дневници (лог файлове) за конвертиране</entry>
<entry id="104110" string="Save conversion logs with audio files">Запазване на дневниците за конвертиране с аудио файлове</entry>
<entry id="104111" string="Audio CD ripping logs only">Само за извличане на Аудио CD</entry>
<entry id="104112" string="Filename pattern">Шаблон за име на файла</entry>
</section>
</section>
<section name="Notifier">
<entry id="105000" string="Conversion process finished!">Процесът на конвертиране е завършен!</entry>
<section name="Configuration">
<entry id="105100" string="Notifications">Съобщение</entry>
<entry id="105101" string="Notify on finished conversion">Съобщение при завършено конвертиране</entry>
<entry id="105102" string="Play sound">Пусни звук</entry>
<entry id="105103" string="Display message">Показване съобщение</entry>
<entry id="105104" string="Select">Избиране...</entry>
<entry id="105105" string="Only for conversions running longer than">Само за конвертирания, работещи по-дълго от</entry>
<entry id="105106" string="second(s)">секунда(и)</entry>
<entry id="105107" string="minute(s)">минута(и)</entry>
</section>
</section>
</section>
</data>
</LangFile>
| {
"pile_set_name": "Github"
} |
/* 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 PKIM_H
#include "pkim.h"
#endif /* PKIM_H */
#ifndef PKIT_H
#include "pkit.h"
#endif /* PKIT_H */
#ifndef NSSPKI_H
#include "nsspki.h"
#endif /* NSSPKI_H */
#ifndef PKI_H
#include "pki.h"
#endif /* PKI_H */
#ifndef NSSBASE_H
#include "nssbase.h"
#endif /* NSSBASE_H */
#ifndef BASE_H
#include "base.h"
#endif /* BASE_H */
#include "cert.h"
#include "dev.h"
#include "pki3hack.h"
#ifdef DEBUG_CACHE
static PRLogModuleInfo *s_log = NULL;
#endif
#ifdef DEBUG_CACHE
static void
log_item_dump(const char *msg, NSSItem *it)
{
char buf[33];
int i, j;
for (i = 0; i < 10 && i < it->size; i++) {
sprintf(&buf[2 * i], "%02X", ((PRUint8 *)it->data)[i]);
}
if (it->size > 10) {
sprintf(&buf[2 * i], "..");
i += 1;
for (j = it->size - 1; i <= 16 && j > 10; i++, j--) {
sprintf(&buf[2 * i], "%02X", ((PRUint8 *)it->data)[j]);
}
}
PR_LOG(s_log, PR_LOG_DEBUG, ("%s: %s", msg, buf));
}
#endif
#ifdef DEBUG_CACHE
static void
log_cert_ref(const char *msg, NSSCertificate *c)
{
PR_LOG(s_log, PR_LOG_DEBUG, ("%s: %s", msg,
(c->nickname) ? c->nickname : c->email));
log_item_dump("\tserial", &c->serial);
log_item_dump("\tsubject", &c->subject);
}
#endif
/* Certificate cache routines */
/* XXX
* Locking is not handled well at all. A single, global lock with sub-locks
* in the collection types. Cleanup needed.
*/
/* should it live in its own arena? */
struct nssTDCertificateCacheStr {
PZLock *lock; /* Must not be held when calling nssSlot_IsTokenPresent. See bug 1625791. */
NSSArena *arena;
nssHash *issuerAndSN;
nssHash *subject;
nssHash *nickname;
nssHash *email;
};
struct cache_entry_str {
union {
NSSCertificate *cert;
nssList *list;
void *value;
} entry;
PRUint32 hits;
PRTime lastHit;
NSSArena *arena;
NSSUTF8 *nickname;
};
typedef struct cache_entry_str cache_entry;
static cache_entry *
new_cache_entry(NSSArena *arena, void *value, PRBool ownArena)
{
cache_entry *ce = nss_ZNEW(arena, cache_entry);
if (ce) {
ce->entry.value = value;
ce->hits = 1;
ce->lastHit = PR_Now();
if (ownArena) {
ce->arena = arena;
}
ce->nickname = NULL;
}
return ce;
}
/* this should not be exposed in a header, but is here to keep the above
* types/functions static
*/
NSS_IMPLEMENT PRStatus
nssTrustDomain_InitializeCache(
NSSTrustDomain *td,
PRUint32 cacheSize)
{
NSSArena *arena;
nssTDCertificateCache *cache = td->cache;
#ifdef DEBUG_CACHE
s_log = PR_NewLogModule("nss_cache");
PR_ASSERT(s_log);
#endif
PR_ASSERT(!cache);
arena = nssArena_Create();
if (!arena) {
return PR_FAILURE;
}
cache = nss_ZNEW(arena, nssTDCertificateCache);
if (!cache) {
nssArena_Destroy(arena);
return PR_FAILURE;
}
cache->lock = PZ_NewLock(nssILockCache);
if (!cache->lock) {
nssArena_Destroy(arena);
return PR_FAILURE;
}
/* Create the issuer and serial DER --> certificate hash */
cache->issuerAndSN = nssHash_CreateCertificate(arena, cacheSize);
if (!cache->issuerAndSN) {
goto loser;
}
/* Create the subject DER --> subject list hash */
cache->subject = nssHash_CreateItem(arena, cacheSize);
if (!cache->subject) {
goto loser;
}
/* Create the nickname --> subject list hash */
cache->nickname = nssHash_CreateString(arena, cacheSize);
if (!cache->nickname) {
goto loser;
}
/* Create the email --> list of subject lists hash */
cache->email = nssHash_CreateString(arena, cacheSize);
if (!cache->email) {
goto loser;
}
cache->arena = arena;
td->cache = cache;
#ifdef DEBUG_CACHE
PR_LOG(s_log, PR_LOG_DEBUG, ("Cache initialized."));
#endif
return PR_SUCCESS;
loser:
PZ_DestroyLock(cache->lock);
nssArena_Destroy(arena);
td->cache = NULL;
#ifdef DEBUG_CACHE
PR_LOG(s_log, PR_LOG_DEBUG, ("Cache initialization failed."));
#endif
return PR_FAILURE;
}
/* The entries of the hashtable are currently dependent on the certificate(s)
* that produced them. That is, the entries will be freed when the cert is
* released from the cache. If there are certs in the cache at any time,
* including shutdown, the hash table entries will hold memory. In order for
* clean shutdown, it is necessary for there to be no certs in the cache.
*/
extern const NSSError NSS_ERROR_INTERNAL_ERROR;
extern const NSSError NSS_ERROR_BUSY;
NSS_IMPLEMENT PRStatus
nssTrustDomain_DestroyCache(NSSTrustDomain *td)
{
if (!td->cache) {
nss_SetError(NSS_ERROR_INTERNAL_ERROR);
return PR_FAILURE;
}
if (nssHash_Count(td->cache->issuerAndSN) > 0) {
nss_SetError(NSS_ERROR_BUSY);
return PR_FAILURE;
}
PZ_DestroyLock(td->cache->lock);
nssHash_Destroy(td->cache->issuerAndSN);
nssHash_Destroy(td->cache->subject);
nssHash_Destroy(td->cache->nickname);
nssHash_Destroy(td->cache->email);
nssArena_Destroy(td->cache->arena);
td->cache = NULL;
#ifdef DEBUG_CACHE
PR_LOG(s_log, PR_LOG_DEBUG, ("Cache destroyed."));
#endif
return PR_SUCCESS;
}
static PRStatus
remove_issuer_and_serial_entry(
nssTDCertificateCache *cache,
NSSCertificate *cert)
{
/* Remove the cert from the issuer/serial hash */
nssHash_Remove(cache->issuerAndSN, cert);
#ifdef DEBUG_CACHE
log_cert_ref("removed issuer/sn", cert);
#endif
return PR_SUCCESS;
}
static PRStatus
remove_subject_entry(
nssTDCertificateCache *cache,
NSSCertificate *cert,
nssList **subjectList,
NSSUTF8 **nickname,
NSSArena **arena)
{
PRStatus nssrv;
cache_entry *ce;
*subjectList = NULL;
*arena = NULL;
/* Get the subject list for the cert's subject */
ce = (cache_entry *)nssHash_Lookup(cache->subject, &cert->subject);
if (ce) {
/* Remove the cert from the subject hash */
nssList_Remove(ce->entry.list, cert);
*subjectList = ce->entry.list;
*nickname = ce->nickname;
*arena = ce->arena;
nssrv = PR_SUCCESS;
#ifdef DEBUG_CACHE
log_cert_ref("removed cert", cert);
log_item_dump("from subject list", &cert->subject);
#endif
} else {
nssrv = PR_FAILURE;
}
return nssrv;
}
static PRStatus
remove_nickname_entry(
nssTDCertificateCache *cache,
NSSUTF8 *nickname,
nssList *subjectList)
{
PRStatus nssrv;
if (nickname) {
nssHash_Remove(cache->nickname, nickname);
nssrv = PR_SUCCESS;
#ifdef DEBUG_CACHE
PR_LOG(s_log, PR_LOG_DEBUG, ("removed nickname %s", nickname));
#endif
} else {
nssrv = PR_FAILURE;
}
return nssrv;
}
static PRStatus
remove_email_entry(
nssTDCertificateCache *cache,
NSSCertificate *cert,
nssList *subjectList)
{
PRStatus nssrv = PR_FAILURE;
cache_entry *ce;
/* Find the subject list in the email hash */
if (cert->email) {
ce = (cache_entry *)nssHash_Lookup(cache->email, cert->email);
if (ce) {
nssList *subjects = ce->entry.list;
/* Remove the subject list from the email hash */
if (subjects) {
nssList_Remove(subjects, subjectList);
#ifdef DEBUG_CACHE
log_item_dump("removed subject list", &cert->subject);
PR_LOG(s_log, PR_LOG_DEBUG, ("for email %s", cert->email));
#endif
if (nssList_Count(subjects) == 0) {
/* No more subject lists for email, delete list and
* remove hash entry
*/
(void)nssList_Destroy(subjects);
nssHash_Remove(cache->email, cert->email);
/* there are no entries left for this address, free space
* used for email entries
*/
nssArena_Destroy(ce->arena);
#ifdef DEBUG_CACHE
PR_LOG(s_log, PR_LOG_DEBUG, ("removed email %s", cert->email));
#endif
}
}
nssrv = PR_SUCCESS;
}
}
return nssrv;
}
NSS_IMPLEMENT void
nssTrustDomain_RemoveCertFromCacheLOCKED(
NSSTrustDomain *td,
NSSCertificate *cert)
{
nssList *subjectList;
cache_entry *ce;
NSSArena *arena;
NSSUTF8 *nickname = NULL;
#ifdef DEBUG_CACHE
log_cert_ref("attempt to remove cert", cert);
#endif
ce = (cache_entry *)nssHash_Lookup(td->cache->issuerAndSN, cert);
if (!ce || ce->entry.cert != cert) {
/* If it's not in the cache, or a different cert is (this is really
* for safety reasons, though it shouldn't happen), do nothing
*/
#ifdef DEBUG_CACHE
PR_LOG(s_log, PR_LOG_DEBUG, ("but it wasn't in the cache"));
#endif
return;
}
(void)remove_issuer_and_serial_entry(td->cache, cert);
(void)remove_subject_entry(td->cache, cert, &subjectList,
&nickname, &arena);
if (nssList_Count(subjectList) == 0) {
(void)remove_nickname_entry(td->cache, nickname, subjectList);
(void)remove_email_entry(td->cache, cert, subjectList);
(void)nssList_Destroy(subjectList);
nssHash_Remove(td->cache->subject, &cert->subject);
/* there are no entries left for this subject, free the space used
* for both the nickname and subject entries
*/
if (arena) {
nssArena_Destroy(arena);
}
}
}
NSS_IMPLEMENT void
nssTrustDomain_LockCertCache(NSSTrustDomain *td)
{
PZ_Lock(td->cache->lock);
}
NSS_IMPLEMENT void
nssTrustDomain_UnlockCertCache(NSSTrustDomain *td)
{
PZ_Unlock(td->cache->lock);
}
struct token_cert_dtor {
NSSToken *token;
nssTDCertificateCache *cache;
NSSCertificate **certs;
PRUint32 numCerts, arrSize;
};
static void
remove_token_certs(const void *k, void *v, void *a)
{
NSSCertificate *c = (NSSCertificate *)k;
nssPKIObject *object = &c->object;
struct token_cert_dtor *dtor = a;
PRUint32 i;
nssPKIObject_AddRef(object);
nssPKIObject_Lock(object);
for (i = 0; i < object->numInstances; i++) {
if (object->instances[i]->token == dtor->token) {
nssCryptokiObject_Destroy(object->instances[i]);
object->instances[i] = object->instances[object->numInstances - 1];
object->instances[object->numInstances - 1] = NULL;
object->numInstances--;
dtor->certs[dtor->numCerts++] = c;
if (dtor->numCerts == dtor->arrSize) {
dtor->arrSize *= 2;
dtor->certs = nss_ZREALLOCARRAY(dtor->certs,
NSSCertificate *,
dtor->arrSize);
}
break;
}
}
nssPKIObject_Unlock(object);
nssPKIObject_Destroy(object);
return;
}
/*
* Remove all certs for the given token from the cache. This is
* needed if the token is removed.
*/
NSS_IMPLEMENT PRStatus
nssTrustDomain_RemoveTokenCertsFromCache(
NSSTrustDomain *td,
NSSToken *token)
{
NSSCertificate **certs;
PRUint32 i, arrSize = 10;
struct token_cert_dtor dtor;
certs = nss_ZNEWARRAY(NULL, NSSCertificate *, arrSize);
if (!certs) {
return PR_FAILURE;
}
dtor.cache = td->cache;
dtor.token = token;
dtor.certs = certs;
dtor.numCerts = 0;
dtor.arrSize = arrSize;
PZ_Lock(td->cache->lock);
nssHash_Iterate(td->cache->issuerAndSN, remove_token_certs, &dtor);
for (i = 0; i < dtor.numCerts; i++) {
if (dtor.certs[i]->object.numInstances == 0) {
nssTrustDomain_RemoveCertFromCacheLOCKED(td, dtor.certs[i]);
dtor.certs[i] = NULL; /* skip this cert in the second for loop */
} else {
/* make sure it doesn't disappear on us before we finish */
nssCertificate_AddRef(dtor.certs[i]);
}
}
PZ_Unlock(td->cache->lock);
for (i = 0; i < dtor.numCerts; i++) {
if (dtor.certs[i]) {
STAN_ForceCERTCertificateUpdate(dtor.certs[i]);
nssCertificate_Destroy(dtor.certs[i]);
}
}
nss_ZFreeIf(dtor.certs);
return PR_SUCCESS;
}
NSS_IMPLEMENT PRStatus
nssTrustDomain_UpdateCachedTokenCerts(
NSSTrustDomain *td,
NSSToken *token)
{
NSSCertificate **cp, **cached = NULL;
nssList *certList;
PRUint32 count;
certList = nssList_Create(NULL, PR_FALSE);
if (!certList)
return PR_FAILURE;
(void)nssTrustDomain_GetCertsFromCache(td, certList);
count = nssList_Count(certList);
if (count > 0) {
cached = nss_ZNEWARRAY(NULL, NSSCertificate *, count + 1);
if (!cached) {
nssList_Destroy(certList);
return PR_FAILURE;
}
nssList_GetArray(certList, (void **)cached, count);
for (cp = cached; *cp; cp++) {
nssCryptokiObject *instance;
NSSCertificate *c = *cp;
nssTokenSearchType tokenOnly = nssTokenSearchType_TokenOnly;
instance = nssToken_FindCertificateByIssuerAndSerialNumber(
token,
NULL,
&c->issuer,
&c->serial,
tokenOnly,
NULL);
if (instance) {
nssPKIObject_AddInstance(&c->object, instance);
STAN_ForceCERTCertificateUpdate(c);
}
}
nssCertificateArray_Destroy(cached);
}
nssList_Destroy(certList);
return PR_SUCCESS;
}
static PRStatus
add_issuer_and_serial_entry(
NSSArena *arena,
nssTDCertificateCache *cache,
NSSCertificate *cert)
{
cache_entry *ce;
ce = new_cache_entry(arena, (void *)cert, PR_FALSE);
#ifdef DEBUG_CACHE
log_cert_ref("added to issuer/sn", cert);
#endif
return nssHash_Add(cache->issuerAndSN, cert, (void *)ce);
}
static PRStatus
add_subject_entry(
NSSArena *arena,
nssTDCertificateCache *cache,
NSSCertificate *cert,
NSSUTF8 *nickname,
nssList **subjectList)
{
PRStatus nssrv;
nssList *list;
cache_entry *ce;
*subjectList = NULL; /* this is only set if a new one is created */
ce = (cache_entry *)nssHash_Lookup(cache->subject, &cert->subject);
if (ce) {
ce->hits++;
ce->lastHit = PR_Now();
/* The subject is already in, add this cert to the list */
nssrv = nssList_AddUnique(ce->entry.list, cert);
#ifdef DEBUG_CACHE
log_cert_ref("added to existing subject list", cert);
#endif
} else {
NSSDER *subject;
/* Create a new subject list for the subject */
list = nssList_Create(arena, PR_FALSE);
if (!list) {
return PR_FAILURE;
}
ce = new_cache_entry(arena, (void *)list, PR_TRUE);
if (!ce) {
return PR_FAILURE;
}
if (nickname) {
ce->nickname = nssUTF8_Duplicate(nickname, arena);
}
nssList_SetSortFunction(list, nssCertificate_SubjectListSort);
/* Add the cert entry to this list of subjects */
nssrv = nssList_AddUnique(list, cert);
if (nssrv != PR_SUCCESS) {
return nssrv;
}
/* Add the subject list to the cache */
subject = nssItem_Duplicate(&cert->subject, arena, NULL);
if (!subject) {
return PR_FAILURE;
}
nssrv = nssHash_Add(cache->subject, subject, ce);
if (nssrv != PR_SUCCESS) {
return nssrv;
}
*subjectList = list;
#ifdef DEBUG_CACHE
log_cert_ref("created subject list", cert);
#endif
}
return nssrv;
}
static PRStatus
add_nickname_entry(
NSSArena *arena,
nssTDCertificateCache *cache,
NSSUTF8 *certNickname,
nssList *subjectList)
{
PRStatus nssrv = PR_SUCCESS;
cache_entry *ce;
ce = (cache_entry *)nssHash_Lookup(cache->nickname, certNickname);
if (ce) {
/* This is a collision. A nickname entry already exists for this
* subject, but a subject entry didn't. This would imply there are
* two subjects using the same nickname, which is not allowed.
*/
return PR_FAILURE;
} else {
NSSUTF8 *nickname;
ce = new_cache_entry(arena, subjectList, PR_FALSE);
if (!ce) {
return PR_FAILURE;
}
nickname = nssUTF8_Duplicate(certNickname, arena);
if (!nickname) {
return PR_FAILURE;
}
nssrv = nssHash_Add(cache->nickname, nickname, ce);
#ifdef DEBUG_CACHE
log_cert_ref("created nickname for", cert);
#endif
}
return nssrv;
}
static PRStatus
add_email_entry(
nssTDCertificateCache *cache,
NSSCertificate *cert,
nssList *subjectList)
{
PRStatus nssrv = PR_SUCCESS;
nssList *subjects;
cache_entry *ce;
ce = (cache_entry *)nssHash_Lookup(cache->email, cert->email);
if (ce) {
/* Already have an entry for this email address, but not subject */
subjects = ce->entry.list;
nssrv = nssList_AddUnique(subjects, subjectList);
ce->hits++;
ce->lastHit = PR_Now();
#ifdef DEBUG_CACHE
log_cert_ref("added subject to email for", cert);
#endif
} else {
NSSASCII7 *email;
NSSArena *arena;
arena = nssArena_Create();
if (!arena) {
return PR_FAILURE;
}
/* Create a new list of subject lists, add this subject */
subjects = nssList_Create(arena, PR_TRUE);
if (!subjects) {
nssArena_Destroy(arena);
return PR_FAILURE;
}
/* Add the new subject to the list */
nssrv = nssList_AddUnique(subjects, subjectList);
if (nssrv != PR_SUCCESS) {
nssArena_Destroy(arena);
return nssrv;
}
/* Add the new entry to the cache */
ce = new_cache_entry(arena, (void *)subjects, PR_TRUE);
if (!ce) {
nssArena_Destroy(arena);
return PR_FAILURE;
}
email = nssUTF8_Duplicate(cert->email, arena);
if (!email) {
nssArena_Destroy(arena);
return PR_FAILURE;
}
nssrv = nssHash_Add(cache->email, email, ce);
if (nssrv != PR_SUCCESS) {
nssArena_Destroy(arena);
return nssrv;
}
#ifdef DEBUG_CACHE
log_cert_ref("created email for", cert);
#endif
}
return nssrv;
}
extern const NSSError NSS_ERROR_CERTIFICATE_IN_CACHE;
static void
remove_object_instances(
nssPKIObject *object,
nssCryptokiObject **instances,
int numInstances)
{
int i;
for (i = 0; i < numInstances; i++) {
nssPKIObject_RemoveInstanceForToken(object, instances[i]->token);
}
}
static SECStatus
merge_object_instances(
nssPKIObject *to,
nssPKIObject *from)
{
nssCryptokiObject **instances, **ci;
int i;
SECStatus rv = SECSuccess;
instances = nssPKIObject_GetInstances(from);
if (instances == NULL) {
return SECFailure;
}
for (ci = instances, i = 0; *ci; ci++, i++) {
nssCryptokiObject *instance = nssCryptokiObject_Clone(*ci);
if (instance) {
if (nssPKIObject_AddInstance(to, instance) == PR_SUCCESS) {
continue;
}
nssCryptokiObject_Destroy(instance);
}
remove_object_instances(to, instances, i);
rv = SECFailure;
break;
}
nssCryptokiObjectArray_Destroy(instances);
return rv;
}
static NSSCertificate *
add_cert_to_cache(
NSSTrustDomain *td,
NSSCertificate *cert)
{
NSSArena *arena = NULL;
nssList *subjectList = NULL;
PRStatus nssrv;
PRUint32 added = 0;
cache_entry *ce;
NSSCertificate *rvCert = NULL;
NSSUTF8 *certNickname = nssCertificate_GetNickname(cert, NULL);
/* Set cc->trust and cc->nssCertificate before taking td->cache->lock.
* Otherwise, the sorter in add_subject_entry may eventually call
* nssSlot_IsTokenPresent, which must not occur while the cache lock
* is held. See bugs 1625791 and 1651564 for details. */
if (cert->type == NSSCertificateType_PKIX) {
(void)STAN_GetCERTCertificate(cert);
}
PZ_Lock(td->cache->lock);
/* If it exists in the issuer/serial hash, it's already in all */
ce = (cache_entry *)nssHash_Lookup(td->cache->issuerAndSN, cert);
if (ce) {
ce->hits++;
ce->lastHit = PR_Now();
rvCert = nssCertificate_AddRef(ce->entry.cert);
#ifdef DEBUG_CACHE
log_cert_ref("attempted to add cert already in cache", cert);
#endif
PZ_Unlock(td->cache->lock);
nss_ZFreeIf(certNickname);
/* collision - somebody else already added the cert
* to the cache before this thread got around to it.
*/
/* merge the instances of the cert */
if (merge_object_instances(&rvCert->object, &cert->object) != SECSuccess) {
nssCertificate_Destroy(rvCert);
return NULL;
}
STAN_ForceCERTCertificateUpdate(rvCert);
nssCertificate_Destroy(cert);
return rvCert;
}
/* create a new cache entry for this cert within the cert's arena*/
nssrv = add_issuer_and_serial_entry(cert->object.arena, td->cache, cert);
if (nssrv != PR_SUCCESS) {
goto loser;
}
added++;
/* create an arena for the nickname and subject entries */
arena = nssArena_Create();
if (!arena) {
goto loser;
}
/* create a new subject list for this cert, or add to existing */
nssrv = add_subject_entry(arena, td->cache, cert,
certNickname, &subjectList);
if (nssrv != PR_SUCCESS) {
goto loser;
}
added++;
/* If a new subject entry was created, also need nickname and/or email */
if (subjectList != NULL) {
#ifdef nodef
PRBool handle = PR_FALSE;
#endif
if (certNickname) {
nssrv = add_nickname_entry(arena, td->cache,
certNickname, subjectList);
if (nssrv != PR_SUCCESS) {
goto loser;
}
#ifdef nodef
handle = PR_TRUE;
#endif
added++;
}
if (cert->email) {
nssrv = add_email_entry(td->cache, cert, subjectList);
if (nssrv != PR_SUCCESS) {
goto loser;
}
#ifdef nodef
handle = PR_TRUE;
#endif
added += 2;
}
#ifdef nodef
/* I think either a nickname or email address must be associated
* with the cert. However, certs are passed to NewTemp without
* either. This worked in the old code, so it must work now.
*/
if (!handle) {
/* Require either nickname or email handle */
nssrv = PR_FAILURE;
goto loser;
}
#endif
} else {
/* A new subject entry was not created. arena is unused. */
nssArena_Destroy(arena);
}
rvCert = cert;
PZ_Unlock(td->cache->lock);
nss_ZFreeIf(certNickname);
return rvCert;
loser:
nss_ZFreeIf(certNickname);
certNickname = NULL;
/* Remove any handles that have been created */
subjectList = NULL;
if (added >= 1) {
(void)remove_issuer_and_serial_entry(td->cache, cert);
}
if (added >= 2) {
(void)remove_subject_entry(td->cache, cert, &subjectList,
&certNickname, &arena);
}
if (added == 3 || added == 5) {
(void)remove_nickname_entry(td->cache, certNickname, subjectList);
}
if (added >= 4) {
(void)remove_email_entry(td->cache, cert, subjectList);
}
if (subjectList) {
nssHash_Remove(td->cache->subject, &cert->subject);
nssList_Destroy(subjectList);
}
if (arena) {
nssArena_Destroy(arena);
}
PZ_Unlock(td->cache->lock);
return NULL;
}
NSS_IMPLEMENT PRStatus
nssTrustDomain_AddCertsToCache(
NSSTrustDomain *td,
NSSCertificate **certs,
PRUint32 numCerts)
{
PRUint32 i;
NSSCertificate *c;
for (i = 0; i < numCerts && certs[i]; i++) {
c = add_cert_to_cache(td, certs[i]);
if (c == NULL) {
return PR_FAILURE;
} else {
certs[i] = c;
}
}
return PR_SUCCESS;
}
static NSSCertificate **
collect_subject_certs(
nssList *subjectList,
nssList *rvCertListOpt)
{
NSSCertificate *c;
NSSCertificate **rvArray = NULL;
PRUint32 count;
nssCertificateList_AddReferences(subjectList);
if (rvCertListOpt) {
nssListIterator *iter = nssList_CreateIterator(subjectList);
if (!iter) {
return (NSSCertificate **)NULL;
}
for (c = (NSSCertificate *)nssListIterator_Start(iter);
c != (NSSCertificate *)NULL;
c = (NSSCertificate *)nssListIterator_Next(iter)) {
nssList_Add(rvCertListOpt, c);
}
nssListIterator_Finish(iter);
nssListIterator_Destroy(iter);
} else {
count = nssList_Count(subjectList);
rvArray = nss_ZNEWARRAY(NULL, NSSCertificate *, count + 1);
if (!rvArray) {
return (NSSCertificate **)NULL;
}
nssList_GetArray(subjectList, (void **)rvArray, count);
}
return rvArray;
}
/*
* Find all cached certs with this subject.
*/
NSS_IMPLEMENT NSSCertificate **
nssTrustDomain_GetCertsForSubjectFromCache(
NSSTrustDomain *td,
NSSDER *subject,
nssList *certListOpt)
{
NSSCertificate **rvArray = NULL;
cache_entry *ce;
#ifdef DEBUG_CACHE
log_item_dump("looking for cert by subject", subject);
#endif
PZ_Lock(td->cache->lock);
ce = (cache_entry *)nssHash_Lookup(td->cache->subject, subject);
if (ce) {
ce->hits++;
ce->lastHit = PR_Now();
#ifdef DEBUG_CACHE
PR_LOG(s_log, PR_LOG_DEBUG, ("... found, %d hits", ce->hits));
#endif
rvArray = collect_subject_certs(ce->entry.list, certListOpt);
}
PZ_Unlock(td->cache->lock);
return rvArray;
}
/*
* Find all cached certs with this label.
*/
NSS_IMPLEMENT NSSCertificate **
nssTrustDomain_GetCertsForNicknameFromCache(
NSSTrustDomain *td,
const NSSUTF8 *nickname,
nssList *certListOpt)
{
NSSCertificate **rvArray = NULL;
cache_entry *ce;
#ifdef DEBUG_CACHE
PR_LOG(s_log, PR_LOG_DEBUG, ("looking for cert by nick %s", nickname));
#endif
PZ_Lock(td->cache->lock);
ce = (cache_entry *)nssHash_Lookup(td->cache->nickname, nickname);
if (ce) {
ce->hits++;
ce->lastHit = PR_Now();
#ifdef DEBUG_CACHE
PR_LOG(s_log, PR_LOG_DEBUG, ("... found, %d hits", ce->hits));
#endif
rvArray = collect_subject_certs(ce->entry.list, certListOpt);
}
PZ_Unlock(td->cache->lock);
return rvArray;
}
/*
* Find all cached certs with this email address.
*/
NSS_IMPLEMENT NSSCertificate **
nssTrustDomain_GetCertsForEmailAddressFromCache(
NSSTrustDomain *td,
NSSASCII7 *email,
nssList *certListOpt)
{
NSSCertificate **rvArray = NULL;
cache_entry *ce;
nssList *collectList = NULL;
nssListIterator *iter = NULL;
nssList *subjectList;
#ifdef DEBUG_CACHE
PR_LOG(s_log, PR_LOG_DEBUG, ("looking for cert by email %s", email));
#endif
PZ_Lock(td->cache->lock);
ce = (cache_entry *)nssHash_Lookup(td->cache->email, email);
if (ce) {
ce->hits++;
ce->lastHit = PR_Now();
#ifdef DEBUG_CACHE
PR_LOG(s_log, PR_LOG_DEBUG, ("... found, %d hits", ce->hits));
#endif
/* loop over subject lists and get refs for certs */
if (certListOpt) {
collectList = certListOpt;
} else {
collectList = nssList_Create(NULL, PR_FALSE);
if (!collectList) {
PZ_Unlock(td->cache->lock);
return NULL;
}
}
iter = nssList_CreateIterator(ce->entry.list);
if (!iter) {
PZ_Unlock(td->cache->lock);
if (!certListOpt) {
nssList_Destroy(collectList);
}
return NULL;
}
for (subjectList = (nssList *)nssListIterator_Start(iter);
subjectList != (nssList *)NULL;
subjectList = (nssList *)nssListIterator_Next(iter)) {
(void)collect_subject_certs(subjectList, collectList);
}
nssListIterator_Finish(iter);
nssListIterator_Destroy(iter);
}
PZ_Unlock(td->cache->lock);
if (!certListOpt && collectList) {
PRUint32 count = nssList_Count(collectList);
rvArray = nss_ZNEWARRAY(NULL, NSSCertificate *, count);
if (rvArray) {
nssList_GetArray(collectList, (void **)rvArray, count);
}
nssList_Destroy(collectList);
}
return rvArray;
}
/*
* Look for a specific cert in the cache
*/
NSS_IMPLEMENT NSSCertificate *
nssTrustDomain_GetCertForIssuerAndSNFromCache(
NSSTrustDomain *td,
NSSDER *issuer,
NSSDER *serial)
{
NSSCertificate certkey;
NSSCertificate *rvCert = NULL;
cache_entry *ce;
certkey.issuer.data = issuer->data;
certkey.issuer.size = issuer->size;
certkey.serial.data = serial->data;
certkey.serial.size = serial->size;
#ifdef DEBUG_CACHE
log_item_dump("looking for cert by issuer/sn, issuer", issuer);
log_item_dump(" serial", serial);
#endif
PZ_Lock(td->cache->lock);
ce = (cache_entry *)nssHash_Lookup(td->cache->issuerAndSN, &certkey);
if (ce) {
ce->hits++;
ce->lastHit = PR_Now();
rvCert = nssCertificate_AddRef(ce->entry.cert);
#ifdef DEBUG_CACHE
PR_LOG(s_log, PR_LOG_DEBUG, ("... found, %d hits", ce->hits));
#endif
}
PZ_Unlock(td->cache->lock);
return rvCert;
}
/*
* Look for a specific cert in the cache
*/
NSS_IMPLEMENT NSSCertificate *
nssTrustDomain_GetCertByDERFromCache(
NSSTrustDomain *td,
NSSDER *der)
{
PRStatus nssrv = PR_FAILURE;
NSSDER issuer, serial;
NSSCertificate *rvCert;
nssrv = nssPKIX509_GetIssuerAndSerialFromDER(der, &issuer, &serial);
if (nssrv != PR_SUCCESS) {
return NULL;
}
#ifdef DEBUG_CACHE
log_item_dump("looking for cert by DER", der);
#endif
rvCert = nssTrustDomain_GetCertForIssuerAndSNFromCache(td,
&issuer, &serial);
PORT_Free(issuer.data);
PORT_Free(serial.data);
return rvCert;
}
static void
cert_iter(const void *k, void *v, void *a)
{
nssList *certList = (nssList *)a;
NSSCertificate *c = (NSSCertificate *)k;
nssList_Add(certList, nssCertificate_AddRef(c));
}
NSS_EXTERN NSSCertificate **
nssTrustDomain_GetCertsFromCache(
NSSTrustDomain *td,
nssList *certListOpt)
{
NSSCertificate **rvArray = NULL;
nssList *certList;
if (certListOpt) {
certList = certListOpt;
} else {
certList = nssList_Create(NULL, PR_FALSE);
if (!certList) {
return NULL;
}
}
PZ_Lock(td->cache->lock);
nssHash_Iterate(td->cache->issuerAndSN, cert_iter, (void *)certList);
PZ_Unlock(td->cache->lock);
if (!certListOpt) {
PRUint32 count = nssList_Count(certList);
rvArray = nss_ZNEWARRAY(NULL, NSSCertificate *, count);
nssList_GetArray(certList, (void **)rvArray, count);
/* array takes the references */
nssList_Destroy(certList);
}
return rvArray;
}
NSS_IMPLEMENT void
nssTrustDomain_DumpCacheInfo(
NSSTrustDomain *td,
void (*cert_dump_iter)(const void *, void *, void *),
void *arg)
{
PZ_Lock(td->cache->lock);
nssHash_Iterate(td->cache->issuerAndSN, cert_dump_iter, arg);
PZ_Unlock(td->cache->lock);
}
| {
"pile_set_name": "Github"
} |
// 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.
// CPU affinity functions
package unix
import (
"math/bits"
"unsafe"
)
const cpuSetSize = _CPU_SETSIZE / _NCPUBITS
// CPUSet represents a CPU affinity mask.
type CPUSet [cpuSetSize]cpuMask
func schedAffinity(trap uintptr, pid int, set *CPUSet) error {
_, _, e := RawSyscall(trap, uintptr(pid), uintptr(unsafe.Sizeof(*set)), uintptr(unsafe.Pointer(set)))
if e != 0 {
return errnoErr(e)
}
return nil
}
// SchedGetaffinity gets the CPU affinity mask of the thread specified by pid.
// If pid is 0 the calling thread is used.
func SchedGetaffinity(pid int, set *CPUSet) error {
return schedAffinity(SYS_SCHED_GETAFFINITY, pid, set)
}
// SchedSetaffinity sets the CPU affinity mask of the thread specified by pid.
// If pid is 0 the calling thread is used.
func SchedSetaffinity(pid int, set *CPUSet) error {
return schedAffinity(SYS_SCHED_SETAFFINITY, pid, set)
}
// Zero clears the set s, so that it contains no CPUs.
func (s *CPUSet) Zero() {
for i := range s {
s[i] = 0
}
}
func cpuBitsIndex(cpu int) int {
return cpu / _NCPUBITS
}
func cpuBitsMask(cpu int) cpuMask {
return cpuMask(1 << (uint(cpu) % _NCPUBITS))
}
// Set adds cpu to the set s.
func (s *CPUSet) Set(cpu int) {
i := cpuBitsIndex(cpu)
if i < len(s) {
s[i] |= cpuBitsMask(cpu)
}
}
// Clear removes cpu from the set s.
func (s *CPUSet) Clear(cpu int) {
i := cpuBitsIndex(cpu)
if i < len(s) {
s[i] &^= cpuBitsMask(cpu)
}
}
// IsSet reports whether cpu is in the set s.
func (s *CPUSet) IsSet(cpu int) bool {
i := cpuBitsIndex(cpu)
if i < len(s) {
return s[i]&cpuBitsMask(cpu) != 0
}
return false
}
// Count returns the number of CPUs in the set s.
func (s *CPUSet) Count() int {
c := 0
for _, b := range s {
c += bits.OnesCount64(uint64(b))
}
return c
}
| {
"pile_set_name": "Github"
} |
require('./check-versions')()
var config = require('../config')
if (!process.env.NODE_ENV) process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)
var path = require('path')
var express = require('express')
var webpack = require('webpack')
var opn = require('opn')
var proxyMiddleware = require('http-proxy-middleware')
var webpackConfig = require('./webpack.dev.conf')
// default port where dev server listens for incoming traffic
var port = process.env.PORT || config.dev.port
// Define HTTP proxies to your custom API backend
// https://github.com/chimurai/http-proxy-middleware
var proxyTable = config.dev.proxyTable
var app = express()
var appData = require('../data.json');
var seller = appData.seller;
var goods = appData.goods;
var ratings = appData.ratings;
var apiRoutes = express.Router();
apiRoutes.get('/seller', function (req, res) {
res.json({
errno: 0,
data: seller
});
});
apiRoutes.get('/goods', function (req, res) {
res.json({
errno: 0,
data: goods
});
});
apiRoutes.get('/ratings', function (req, res) {
res.json({
errno: 0,
data: ratings
});
});
app.use('/api', apiRoutes);
var compiler = webpack(webpackConfig)
var devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
stats: {
colors: true,
chunks: false
}
})
var hotMiddleware = require('webpack-hot-middleware')(compiler)
// force page reload when html-webpack-plugin template changes
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
hotMiddleware.publish({ action: 'reload' })
cb()
})
})
// proxy api requests
Object.keys(proxyTable).forEach(function (context) {
var options = proxyTable[context]
if (typeof options === 'string') {
options = { target: options }
}
app.use(proxyMiddleware(context, options))
})
// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())
// serve webpack bundle output
app.use(devMiddleware)
// enable hot-reload and state-preserving
// compilation error display
app.use(hotMiddleware)
// serve pure static assets
var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)
app.use(staticPath, express.static('./static'))
module.exports = app.listen(port, function (err) {
if (err) {
console.log(err)
return
}
var uri = 'http://localhost:' + port
console.log('Listening at ' + uri + '\n')
// when env is testing, don't need open it
if (process.env.NODE_ENV !== 'testing') {
opn(uri)
}
})
| {
"pile_set_name": "Github"
} |
package org.dddjava.jig.domain.model.jigdocument.specification;
import org.dddjava.jig.domain.model.jigdocument.documentformat.DocumentName;
import org.dddjava.jig.domain.model.jigdocument.documentformat.JigDocument;
import org.dddjava.jig.domain.model.jigdocument.stationery.*;
import org.dddjava.jig.domain.model.jigmodel.lowmodel.alias.AliasFinder;
import org.dddjava.jig.domain.model.jigmodel.lowmodel.alias.PackageAlias;
import org.dddjava.jig.domain.model.jigmodel.lowmodel.declaration.package_.PackageDepth;
import org.dddjava.jig.domain.model.jigmodel.lowmodel.declaration.package_.PackageIdentifier;
import org.dddjava.jig.domain.model.jigmodel.lowmodel.declaration.package_.PackageIdentifierFormatter;
import org.dddjava.jig.domain.model.jigmodel.lowmodel.declaration.package_.PackageIdentifiers;
import org.dddjava.jig.domain.model.jigmodel.lowmodel.relation.class_.ClassRelation;
import org.dddjava.jig.domain.model.jigmodel.lowmodel.relation.class_.ClassRelations;
import org.dddjava.jig.domain.model.jigmodel.lowmodel.relation.packages.BidirectionalRelation;
import org.dddjava.jig.domain.model.jigmodel.lowmodel.relation.packages.BidirectionalRelations;
import org.dddjava.jig.domain.model.jigmodel.lowmodel.relation.packages.PackageRelation;
import org.dddjava.jig.domain.model.jigmodel.lowmodel.relation.packages.PackageRelations;
import java.util.*;
import static java.util.stream.Collectors.joining;
/**
* パッケージ関連図
*
* 浅い階層は仕様化、深い階層は実装に使用します。
*/
public class PackageRelationDiagram {
PackageIdentifiers packageIdentifiers;
PackageRelations packageRelations;
ClassRelations classRelations;
PackageDepth appliedDepth;
BidirectionalRelations bidirectionalRelations;
public PackageRelationDiagram(PackageIdentifiers packageIdentifiers, ClassRelations classRelations) {
this(packageIdentifiers, PackageRelations.fromClassRelations(classRelations), classRelations, new PackageDepth(-1));
}
private PackageRelationDiagram(PackageIdentifiers packageIdentifiers, PackageRelations packageRelations, ClassRelations classRelations, PackageDepth appliedDepth) {
this.packageIdentifiers = packageIdentifiers;
this.packageRelations = packageRelations.filterBothMatch(packageIdentifiers);
this.classRelations = classRelations;
this.appliedDepth = appliedDepth;
this.bidirectionalRelations = BidirectionalRelations.from(this.packageRelations);
}
public static PackageRelationDiagram empty() {
return new PackageRelationDiagram(
new PackageIdentifiers(Collections.emptyList()),
new PackageRelations(Collections.emptyList()),
null,
new PackageDepth(-1)
);
}
public PackageIdentifiers allPackages() {
return packageIdentifiers;
}
public PackageRelations packageDependencies() {
return packageRelations;
}
public PackageRelationDiagram applyDepth(PackageDepth depth) {
return new PackageRelationDiagram(
packageIdentifiers.applyDepth(depth),
packageRelations.applyDepth(depth),
this.classRelations,
depth
);
}
public PackageDepth appliedDepth() {
return appliedDepth;
}
public boolean available() {
return packageDependencies().available();
}
public PackageDepth maxDepth() {
return packageIdentifiers.maxDepth();
}
public BidirectionalRelations bidirectionalRelations() {
return bidirectionalRelations;
}
public DiagramSource dependencyDotText(JigDocumentContext jigDocumentContext, PackageIdentifierFormatter formatter) {
if (!available()) {
return DiagramSource.emptyUnit();
}
PackageRelations packageRelations = packageDependencies();
BidirectionalRelations bidirectionalRelations = bidirectionalRelations();
RelationText unidirectionalRelation = new RelationText("edge [color=black];");
for (PackageRelation packageRelation : packageRelations.list()) {
if (bidirectionalRelations.notContains(packageRelation)) {
unidirectionalRelation.add(packageRelation.from(), packageRelation.to());
}
}
PackageDepth maxDepth = allPackages().maxDepth();
// 最下層を一つ上でグルーピング
Map<PackageIdentifier, List<PackageIdentifier>> groupingPackages = new HashMap<>();
// 最下層以外
List<PackageIdentifier> standalonePackages = new ArrayList<>();
for (PackageIdentifier packageIdentifier : allPackages().list()) {
if (packageIdentifier.depth().just(maxDepth)) {
groupingPackages.computeIfAbsent(packageIdentifier.parent(), k -> new ArrayList<>())
.add(packageIdentifier);
} else {
standalonePackages.add(packageIdentifier);
}
}
// 1つにグルーピングされていたら剥がす
if (standalonePackages.isEmpty() && groupingPackages.size() == 1) {
for (List<PackageIdentifier> value : groupingPackages.values()) {
standalonePackages.addAll(value);
}
groupingPackages.clear();
}
Labeler labeler = new Labeler(jigDocumentContext, formatter);
StringJoiner stringJoiner = new StringJoiner("\n");
for (Map.Entry<PackageIdentifier, List<PackageIdentifier>> entry : groupingPackages.entrySet()) {
PackageIdentifier parent = entry.getKey();
String labelsText = entry.getValue().stream()
.map(packageIdentifier -> Node.packageOf(packageIdentifier)
.label(labeler.label(packageIdentifier, parent))
.url(packageIdentifier, jigDocumentContext).asText())
.collect(joining("\n"));
Subgraph subgraph = new Subgraph(parent.asText())
.add(labelsText)
.label(labeler.label(parent))
.fillColor("lemonchiffon").color("lightgoldenrod").borderWidth(2);
stringJoiner.add(subgraph.toString());
}
String labelsText = standalonePackages.stream()
.map(packageIdentifier -> Node.packageOf(packageIdentifier)
.label(labeler.label(packageIdentifier))
.url(packageIdentifier, jigDocumentContext).asText())
.collect(joining("\n"));
stringJoiner.add(labelsText);
String summaryText = "summary[shape=note,label=\""
+ jigDocumentContext.label("number_of_packages") + ": " + allPackages().number().asText() + "\\l"
+ jigDocumentContext.label("number_of_relations") + ": " + packageRelations.number().asText() + "\\l"
+ "\"]";
DocumentName documentName = jigDocumentContext.documentName(JigDocument.PackageRelationDiagram);
String text = new StringJoiner("\n", "digraph \"" + documentName.label() + "\" {", "}")
.add("label=\"" + documentName.label() + "\";")
.add(summaryText)
.add(Node.DEFAULT)
.add(unidirectionalRelation.asText())
.add(bidirectionalRelations.dotRelationText())
.add(stringJoiner.toString())
.toString();
PackageDepth packageDepth = appliedDepth();
return DiagramSource.createDiagramSourceUnit(documentName.withSuffix("-depth" + packageDepth.value()), text, additionalText());
}
private AdditionalText additionalText() {
if (bidirectionalRelations().none()) {
return AdditionalText.empty();
}
return new AdditionalText(bidirectionalRelationReasonText());
}
private String bidirectionalRelationReasonText() {
StringJoiner sj = new StringJoiner("\n");
for (BidirectionalRelation bidirectionalRelation : bidirectionalRelations().list()) {
sj.add("# " + bidirectionalRelation.toString());
String package1 = bidirectionalRelation.packageRelation().from().asText();
String package2 = bidirectionalRelation.packageRelation().to().asText();
for (ClassRelation classRelation : classRelations.list()) {
String from = classRelation.from().fullQualifiedName();
String to = classRelation.to().fullQualifiedName();
if ((from.startsWith(package1) && to.startsWith(package2))
|| (from.startsWith(package2) && to.startsWith(package1))) {
sj.add("- " + classRelation.toString());
}
}
}
return sj.toString();
}
static class Labeler {
AliasFinder aliasFinder;
PackageIdentifierFormatter packageIdentifierFormatter;
Labeler(JigDocumentContext jigDocumentContext, PackageIdentifierFormatter packageIdentifierFormatter) {
this.aliasFinder = jigDocumentContext.aliasFinder();
this.packageIdentifierFormatter = packageIdentifierFormatter;
}
private String label(PackageIdentifier packageIdentifier, PackageIdentifier parent) {
if (!packageIdentifier.asText().startsWith(parent.asText() + '.')) {
// TODO 通常は起こらないけれど起こらない実装にできてないので保険の実装。無くしたい。
return label(packageIdentifier);
}
// parentでくくる場合にパッケージ名をの重複を省く
String labelText = packageIdentifier.asText().substring(parent.asText().length() + 1);
return addAliasIfExists(packageIdentifier, labelText, aliasFinder);
}
private String label(PackageIdentifier packageIdentifier) {
String labelText = packageIdentifier.format(packageIdentifierFormatter);
return addAliasIfExists(packageIdentifier, labelText, aliasFinder);
}
private String addAliasIfExists(PackageIdentifier packageIdentifier, String labelText, AliasFinder aliasFinder) {
PackageAlias packageAlias = aliasFinder.find(packageIdentifier);
if (packageAlias.exists()) {
return packageAlias.asText() + "\\n" + labelText;
}
return labelText;
}
}
}
| {
"pile_set_name": "Github"
} |
{
"network": [
[
"probeNetwork - default - end",
0,
0
],
[
"probeNetwork - default - start",
0,
0
]
],
"gfx": [
[
"probeGFX - default - end",
3,
3,
9,
1,
[
32768,
32768
],
[
130,
130
],
[
224,
224
]
]
]
} | {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import <CalendarPersistence/CalDAVEntityQueueableOperation.h>
@class CALEntity, CoreEvent, NSString;
@interface CalDAVScheduleEventQueueableOperation : CalDAVEntityQueueableOperation
{
NSString *_meAddress;
NSString *_recipients;
NSString *_scheduleData;
NSString *_localUID;
CoreEvent *_event;
CALEntity *_parentEvent;
long long _attachmentsSent;
int _originalStatus;
NSString *_outboxPath;
int _method;
NSString *_etag;
BOOL _scheduleIsAnUpdate;
}
- (void)configureOperationDependencies;
- (void)performSchedule;
- (void)task:(id)arg1 didFinishWithError:(id)arg2;
- (void)_setErrorWithFakeStatus:(id)arg1;
- (void)_sendMessageForInvalidAttendees:(id)arg1;
- (void)_checkHeadETag:(id)arg1;
- (void)performOperation;
- (void)dealloc;
- (id)readableDescription;
- (id)initWithChangeRequest:(id)arg1 entity:(id)arg2 meAddress:(id)arg3 recipients:(id)arg4 scheduleData:(id)arg5 outboxPath:(id)arg6 fromSource:(id)arg7 principal:(id)arg8 etag:(id)arg9 serverFilename:(id)arg10;
@end
| {
"pile_set_name": "Github"
} |
{
"batch": true,
"integrations": ["AM", "GA"],
"events": [
{
"name": "Product Clicked",
"GANet": {
"url": "https://www.google-analytics.com/collect",
"type": "KV"
},
"AMNet": {
"url": "https://api.amplitude.com/httpapi",
"type": "KV"
},
"GAMapping": {
"message.context.traits.anonymous_id": "cid",
"message.properties.url": "dl",
"message.properties.product_id": "pr1id",
"message.properties.name": "pr1nm",
"message.properties.sku": "pr1id",
"message.properties.category": "pr1ca",
"message.properties.brand": "pr1br",
"message.properties.variant": "pr1va",
"message.properties.coupon": "pr1cc",
"message.properties.price": "pr1pr",
"message.properties.dimensions.0": "pr1cd0",
"message.properties.dimensions.1": "pr1cd1"
},
"AMMapping": {
"message.context.traits.anonymous_id": "event.0.user_id",
"message.event": "event.0.event_type",
"message.properties.product_id": "event.0.productId",
"message.properties.price": "event.0.price",
"message.properties.quantity": "event.0.quantity"
},
"rudder": {
"message": {
"channel": "Test Channel",
"context": {
"app": {
"build": "0",
"name": "com.rudderlabs.android.library.test",
"namespace": "com.rudderlabs.android.library.test",
"version": "1.0.0"
},
"traits": {
"anonymous_id": "23d7cbff-15b5-43ee-bfde-65282ed5fdf6"
},
"library": {
"name": "com.rudderlabs.android.library",
"version": "1.0"
},
"os": {
"name": "Android",
"version": "9"
},
"screen": {
"density": 1,
"width": 470,
"height": 320
},
"user_agent": "",
"locale": "en-US",
"device": {
"id": "23d7cbff-15b5-43ee-bfde-65282ed5fdf6",
"manufacturer": "unknown",
"model": "robolectric",
"name": "robolectric"
},
"network": {
"carrier": ""
}
},
"type": "track",
"message_id": "d6a75a2d-43a2-4d0c-9bcc-5f6e6705299b",
"timestamp": "2019-07-19 10:38:03+0000",
"anonymous_id": "23d7cbff-15b5-43ee-bfde-65282ed5fdf6",
"event": "Product Clicked",
"properties": {
"product_id": "507f1f77bcf86cd799439011",
"sku": "45790-32",
"category": "Games",
"name": "Monopoly: 3rd Edition",
"brand": "Monopoly",
"variant": "Single User",
"price": 19.0,
"quantity": 1,
"coupon": "MAY_DEALS_3",
"position": 1,
"url": "https://www.example.com/product/path",
"image_url": "https://www.example.com/product/path.jpg"
},
"integrations": ["rudderlabs"]
}
},
"GA": {
"t": "event",
"tid": "UA-143161493-2",
"v": 1,
"pa": "click",
"ec": "Product Clicked",
"ea": "Product Clicked",
"pr1ps": 1,
"pr1qt": 1
},
"AM": {
"api_key": "b718269870595f4ceed44609d3de5cdc"
}
},
{
"name": "Track",
"GANet": {
"url": "https://www.google-analytics.com/collect",
"type": "KV"
},
"AMNet": {
"url": "https://api.amplitude.com/httpapi",
"type": "KV"
},
"GAMapping": {
"message.context.traits.anonymous_id": "cid",
"message.properties.category": "ec",
"message.properties.label": "el",
"message.properties.value": "ev"
},
"AMMapping": {
"message.context.traits.anonymous_id": "event.0.user_id",
"message.event": "event.0.event_type"
},
"rudder": {
"message": {
"channel": "Test Channel",
"context": {
"app": {
"build": "0",
"name": "com.rudderlabs.android.library.test",
"namespace": "com.rudderlabs.android.library.test",
"version": "1.0.0"
},
"traits": {
"anonymous_id": "19702fee-6184-482e-aa05-8ab21402e1f3"
},
"library": {
"name": "com.rudderlabs.android.library",
"version": "1.0"
},
"os": {
"name": "Android",
"version": "9"
},
"screen": {
"density": 1,
"width": 470,
"height": 320
},
"user_agent": "",
"locale": "en-US",
"device": {
"id": "19702fee-6184-482e-aa05-8ab21402e1f3",
"manufacturer": "unknown",
"model": "robolectric",
"name": "robolectric"
},
"network": {
"carrier": ""
}
},
"type": "track",
"message_id": "6def71bd-eae8-4cb1-bfe7-0b5e7eaf89fd",
"timestamp": "2019-07-19 10:12:22+0000",
"anonymous_id": "19702fee-6184-482e-aa05-8ab21402e1f3",
"event": "Test Track",
"properties": {
"category": "Test Category",
"label": "Test Label",
"value": 5
},
"integrations": ["rudderlabs"]
}
},
"GA": {
"t": "event",
"tid": "UA-143161493-2",
"ea": "clicked",
"v": 1
},
"AM": {
"api_key": "b718269870595f4ceed44609d3de5cdc"
}
}
]
}
| {
"pile_set_name": "Github"
} |
const Command = require('../../structures/Command');
module.exports = class RepeatCommand extends Command {
constructor(client) {
super(client, {
name: 'repeat',
group: 'edit-text',
memberName: 'repeat',
description: 'Repeat text over and over and over and over (etc).',
args: [
{
key: 'amount',
prompt: 'How many times do you want to repeat your text?',
type: 'integer',
min: 1,
max: 2000
},
{
key: 'text',
prompt: 'What text would you like to repeat over and over and over and over?',
type: 'string',
validate: text => {
if (!text.includes('@everyone') && !text.includes('@here')) return true;
return 'Invalid text, please do not repeat everyone or here mentions.';
}
}
]
});
}
run(msg, { amount, text }) {
return msg.say(text.repeat(amount).substr(0, 2000));
}
};
| {
"pile_set_name": "Github"
} |
-- Registering some dummy items and recipes for the crafting tests
minetest.register_craftitem("unittests:torch", {
description = "Crafting Test Item: Torch",
inventory_image = "unittests_torch.png",
groups = { dummy = 1 },
})
minetest.register_craftitem("unittests:coal_lump", {
description = "Crafting Test Item: Coal Lump",
inventory_image = "unittests_coal_lump.png",
groups = { dummy = 1 },
})
minetest.register_craftitem("unittests:stick", {
description = "Crafting Test Item: Stick",
inventory_image = "unittests_stick.png",
groups = { dummy = 1 },
})
minetest.register_craftitem("unittests:iron_lump", {
description = "Crafting Test Item: Iron Lump",
inventory_image = "unittests_iron_lump.png",
groups = { dummy = 1 },
})
minetest.register_craftitem("unittests:steel_ingot", {
description = "Crafting Test Item: Steel Ingot",
inventory_image = "unittests_steel_ingot.png",
groups = { dummy = 1 },
})
-- Recipes for tests: Normal crafting, cooking and fuel
minetest.register_craft({
output = 'unittests:torch 4',
recipe = {
{'unittests:coal_lump'},
{'unittests:stick'},
}
})
minetest.register_craft({
type = "cooking",
output = "unittests:steel_ingot",
recipe = "unittests:iron_lump",
})
minetest.register_craft({
type = "fuel",
recipe = "unittests:coal_lump",
burntime = 40,
})
-- Test tool repair
minetest.register_craft({
type = "toolrepair",
additional_wear = -0.05,
})
-- Test the disable_repair=1 group
minetest.register_tool("unittests:unrepairable_tool", {
description = "Crafting Test Item: Unrepairable Tool",
inventory_image = "unittests_unrepairable_tool.png",
tool_capabilities = {
groupcaps = {
cracky = {
times = {3, 2, 1},
}
}
},
groups = { disable_repair = 1, dummy = 1 }
})
minetest.register_tool("unittests:repairable_tool", {
description = "Crafting Test Item: Repairable Tool",
inventory_image = "unittests_repairable_tool.png",
tool_capabilities = {
groupcaps = {
cracky = {
times = {3, 2, 1},
}
}
},
groups = { dummy = 1 },
})
| {
"pile_set_name": "Github"
} |
// Copyright Aleksey Gurtovoy 2001-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/aux_/full_lambda.hpp" header
// -- DO NOT modify by hand!
namespace boost { namespace mpl {
namespace aux {
template<
bool C1 = false, bool C2 = false, bool C3 = false, bool C4 = false
, bool C5 = false
>
struct lambda_or
: true_
{
};
template<>
struct lambda_or< false,false,false,false,false >
: false_
{
};
} // namespace aux
template<
typename T
, typename Tag
, typename Arity
>
struct lambda
{
typedef false_ is_le;
typedef T result_;
typedef T type;
};
template<
typename T
>
struct is_lambda_expression
: lambda<T>::is_le
{
};
template< int N, typename Tag >
struct lambda< arg<N>,Tag, int_< -1 > >
{
typedef true_ is_le;
typedef mpl::arg<N> result_; // qualified for the sake of MIPSpro 7.41
typedef mpl::protect<result_> type;
};
template<
typename F
, typename Tag
>
struct lambda<
bind0<F>
, Tag
, int_<1>
>
{
typedef false_ is_le;
typedef bind0<
F
> result_;
typedef result_ type;
};
namespace aux {
template<
typename IsLE, typename Tag
, template< typename P1 > class F
, typename L1
>
struct le_result1
{
typedef F<
typename L1::type
> result_;
typedef result_ type;
};
template<
typename Tag
, template< typename P1 > class F
, typename L1
>
struct le_result1< true_,Tag,F,L1 >
{
typedef bind1<
quote1< F,Tag >
, typename L1::result_
> result_;
typedef mpl::protect<result_> type;
};
} // namespace aux
template<
template< typename P1 > class F
, typename T1
, typename Tag
>
struct lambda<
F<T1>
, Tag
, int_<1>
>
{
typedef lambda< T1,Tag > l1;
typedef typename l1::is_le is_le1;
typedef typename aux::lambda_or<
is_le1::value
>::type is_le;
typedef aux::le_result1<
is_le, Tag, F, l1
> le_result_;
typedef typename le_result_::result_ result_;
typedef typename le_result_::type type;
};
template<
typename F, typename T1
, typename Tag
>
struct lambda<
bind1< F,T1 >
, Tag
, int_<2>
>
{
typedef false_ is_le;
typedef bind1<
F
, T1
> result_;
typedef result_ type;
};
namespace aux {
template<
typename IsLE, typename Tag
, template< typename P1, typename P2 > class F
, typename L1, typename L2
>
struct le_result2
{
typedef F<
typename L1::type, typename L2::type
> result_;
typedef result_ type;
};
template<
typename Tag
, template< typename P1, typename P2 > class F
, typename L1, typename L2
>
struct le_result2< true_,Tag,F,L1,L2 >
{
typedef bind2<
quote2< F,Tag >
, typename L1::result_, typename L2::result_
> result_;
typedef mpl::protect<result_> type;
};
} // namespace aux
template<
template< typename P1, typename P2 > class F
, typename T1, typename T2
, typename Tag
>
struct lambda<
F< T1,T2 >
, Tag
, int_<2>
>
{
typedef lambda< T1,Tag > l1;
typedef lambda< T2,Tag > l2;
typedef typename l1::is_le is_le1;
typedef typename l2::is_le is_le2;
typedef typename aux::lambda_or<
is_le1::value, is_le2::value
>::type is_le;
typedef aux::le_result2<
is_le, Tag, F, l1, l2
> le_result_;
typedef typename le_result_::result_ result_;
typedef typename le_result_::type type;
};
template<
typename F, typename T1, typename T2
, typename Tag
>
struct lambda<
bind2< F,T1,T2 >
, Tag
, int_<3>
>
{
typedef false_ is_le;
typedef bind2<
F
, T1, T2
> result_;
typedef result_ type;
};
namespace aux {
template<
typename IsLE, typename Tag
, template< typename P1, typename P2, typename P3 > class F
, typename L1, typename L2, typename L3
>
struct le_result3
{
typedef F<
typename L1::type, typename L2::type, typename L3::type
> result_;
typedef result_ type;
};
template<
typename Tag
, template< typename P1, typename P2, typename P3 > class F
, typename L1, typename L2, typename L3
>
struct le_result3< true_,Tag,F,L1,L2,L3 >
{
typedef bind3<
quote3< F,Tag >
, typename L1::result_, typename L2::result_, typename L3::result_
> result_;
typedef mpl::protect<result_> type;
};
} // namespace aux
template<
template< typename P1, typename P2, typename P3 > class F
, typename T1, typename T2, typename T3
, typename Tag
>
struct lambda<
F< T1,T2,T3 >
, Tag
, int_<3>
>
{
typedef lambda< T1,Tag > l1;
typedef lambda< T2,Tag > l2;
typedef lambda< T3,Tag > l3;
typedef typename l1::is_le is_le1;
typedef typename l2::is_le is_le2;
typedef typename l3::is_le is_le3;
typedef typename aux::lambda_or<
is_le1::value, is_le2::value, is_le3::value
>::type is_le;
typedef aux::le_result3<
is_le, Tag, F, l1, l2, l3
> le_result_;
typedef typename le_result_::result_ result_;
typedef typename le_result_::type type;
};
template<
typename F, typename T1, typename T2, typename T3
, typename Tag
>
struct lambda<
bind3< F,T1,T2,T3 >
, Tag
, int_<4>
>
{
typedef false_ is_le;
typedef bind3<
F
, T1, T2, T3
> result_;
typedef result_ type;
};
namespace aux {
template<
typename IsLE, typename Tag
, template< typename P1, typename P2, typename P3, typename P4 > class F
, typename L1, typename L2, typename L3, typename L4
>
struct le_result4
{
typedef F<
typename L1::type, typename L2::type, typename L3::type
, typename L4::type
> result_;
typedef result_ type;
};
template<
typename Tag
, template< typename P1, typename P2, typename P3, typename P4 > class F
, typename L1, typename L2, typename L3, typename L4
>
struct le_result4< true_,Tag,F,L1,L2,L3,L4 >
{
typedef bind4<
quote4< F,Tag >
, typename L1::result_, typename L2::result_, typename L3::result_
, typename L4::result_
> result_;
typedef mpl::protect<result_> type;
};
} // namespace aux
template<
template< typename P1, typename P2, typename P3, typename P4 > class F
, typename T1, typename T2, typename T3, typename T4
, typename Tag
>
struct lambda<
F< T1,T2,T3,T4 >
, Tag
, int_<4>
>
{
typedef lambda< T1,Tag > l1;
typedef lambda< T2,Tag > l2;
typedef lambda< T3,Tag > l3;
typedef lambda< T4,Tag > l4;
typedef typename l1::is_le is_le1;
typedef typename l2::is_le is_le2;
typedef typename l3::is_le is_le3;
typedef typename l4::is_le is_le4;
typedef typename aux::lambda_or<
is_le1::value, is_le2::value, is_le3::value, is_le4::value
>::type is_le;
typedef aux::le_result4<
is_le, Tag, F, l1, l2, l3, l4
> le_result_;
typedef typename le_result_::result_ result_;
typedef typename le_result_::type type;
};
template<
typename F, typename T1, typename T2, typename T3, typename T4
, typename Tag
>
struct lambda<
bind4< F,T1,T2,T3,T4 >
, Tag
, int_<5>
>
{
typedef false_ is_le;
typedef bind4<
F
, T1, T2, T3, T4
> result_;
typedef result_ type;
};
namespace aux {
template<
typename IsLE, typename Tag
, template< typename P1, typename P2, typename P3, typename P4, typename P5 > class F
, typename L1, typename L2, typename L3, typename L4, typename L5
>
struct le_result5
{
typedef F<
typename L1::type, typename L2::type, typename L3::type
, typename L4::type, typename L5::type
> result_;
typedef result_ type;
};
template<
typename Tag
, template< typename P1, typename P2, typename P3, typename P4, typename P5 > class F
, typename L1, typename L2, typename L3, typename L4, typename L5
>
struct le_result5< true_,Tag,F,L1,L2,L3,L4,L5 >
{
typedef bind5<
quote5< F,Tag >
, typename L1::result_, typename L2::result_, typename L3::result_
, typename L4::result_, typename L5::result_
> result_;
typedef mpl::protect<result_> type;
};
} // namespace aux
template<
template<
typename P1, typename P2, typename P3, typename P4
, typename P5
>
class F
, typename T1, typename T2, typename T3, typename T4, typename T5
, typename Tag
>
struct lambda<
F< T1,T2,T3,T4,T5 >
, Tag
, int_<5>
>
{
typedef lambda< T1,Tag > l1;
typedef lambda< T2,Tag > l2;
typedef lambda< T3,Tag > l3;
typedef lambda< T4,Tag > l4;
typedef lambda< T5,Tag > l5;
typedef typename l1::is_le is_le1;
typedef typename l2::is_le is_le2;
typedef typename l3::is_le is_le3;
typedef typename l4::is_le is_le4;
typedef typename l5::is_le is_le5;
typedef typename aux::lambda_or<
is_le1::value, is_le2::value, is_le3::value, is_le4::value
, is_le5::value
>::type is_le;
typedef aux::le_result5<
is_le, Tag, F, l1, l2, l3, l4, l5
> le_result_;
typedef typename le_result_::result_ result_;
typedef typename le_result_::type type;
};
template<
typename F, typename T1, typename T2, typename T3, typename T4
, typename T5
, typename Tag
>
struct lambda<
bind5< F,T1,T2,T3,T4,T5 >
, Tag
, int_<6>
>
{
typedef false_ is_le;
typedef bind5<
F
, T1, T2, T3, T4, T5
> result_;
typedef result_ type;
};
/// special case for 'protect'
template< typename T, typename Tag >
struct lambda< mpl::protect<T>,Tag, int_<1> >
{
typedef false_ is_le;
typedef mpl::protect<T> result_;
typedef result_ type;
};
/// specializations for the main 'bind' form
template<
typename F, typename T1, typename T2, typename T3, typename T4
, typename T5
, typename Tag
>
struct lambda<
bind< F,T1,T2,T3,T4,T5 >
, Tag
, int_<6>
>
{
typedef false_ is_le;
typedef bind< F,T1,T2,T3,T4,T5 > result_;
typedef result_ type;
};
template<
typename F
, typename Tag1
, typename Tag2
, typename Arity
>
struct lambda<
lambda< F,Tag1,Arity >
, Tag2
, int_<3>
>
{
typedef lambda< F,Tag2 > l1;
typedef lambda< Tag1,Tag2 > l2;
typedef typename l1::is_le is_le;
typedef bind1< quote1<aux::template_arity>, typename l1::result_ > arity_;
typedef lambda< typename if_< is_le,arity_,Arity >::type, Tag2 > l3;
typedef aux::le_result3<is_le, Tag2, mpl::lambda, l1, l2, l3> le_result_;
typedef typename le_result_::result_ result_;
typedef typename le_result_::type type;
};
BOOST_MPL_AUX_NA_SPEC2(2, 3, lambda)
}}
| {
"pile_set_name": "Github"
} |
#ifndef METASHELL_RAPID_JSON_WRITER_HPP
#define METASHELL_RAPID_JSON_WRITER_HPP
// Metashell - Interactive C++ template metaprogramming shell
// Copyright (C) 2014, Abel Sinkovics ([email protected])
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This 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/>.
#include <metashell/iface/json_writer.hpp>
#include <metashell/core/rapid_ostream_wrapper.hpp>
#include <rapidjson/writer.h>
#include <iosfwd>
namespace metashell
{
namespace core
{
class rapid_json_writer : public iface::json_writer
{
public:
explicit rapid_json_writer(std::ostream& out_);
virtual void string(const std::string& value_) override;
virtual void int_(int value_) override;
virtual void double_(double value_) override;
virtual void bool_(bool value_) override;
virtual void start_object() override;
virtual void key(const std::string& key_) override;
virtual void end_object() override;
virtual void start_array() override;
virtual void end_array() override;
virtual void end_document() override;
private:
rapid_ostream_wrapper _os;
rapidjson::Writer<rapid_ostream_wrapper> _writer;
};
}
}
#endif
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: af3204d26eb657c488705f273dd4d3bb
AudioImporter:
externalObjects: {}
serializedVersion: 6
defaultSettings:
loadType: 2
sampleRateSetting: 0
sampleRateOverride: 44100
compressionFormat: 1
quality: 1
conversionMode: 0
platformSettingOverrides: {}
forceToMono: 0
normalize: 1
preloadAudioData: 1
loadInBackground: 0
ambisonic: 0
3D: 1
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
/*
* ApplicationInsights-Java
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
* 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.
*/
package com.microsoft.applicationinsights.internal.quickpulse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by gupele on 12/14/2016.
*/
final class DefaultQuickPulseCoordinator implements QuickPulseCoordinator, Runnable {
private static final Logger logger = LoggerFactory.getLogger(DefaultQuickPulseCoordinator.class);
private volatile boolean stopped = false;
private volatile boolean pingMode = true;
private final QuickPulsePingSender pingSender;
private final QuickPulseDataFetcher dataFetcher;
private final QuickPulseDataSender dataSender;
private final long waitBetweenPingsInMS;
private final long waitBetweenPostsInMS;
private final long waitOnErrorInMS;
public DefaultQuickPulseCoordinator(QuickPulseCoordinatorInitData initData) {
dataSender = initData.dataSender;
pingSender = initData.pingSender;
dataFetcher = initData.dataFetcher;
waitBetweenPingsInMS = initData.waitBetweenPingsInMS;
waitBetweenPostsInMS = initData.waitBetweenPostsInMS;
waitOnErrorInMS = initData.waitBetweenPingsInMS;
}
@Override
public void run() {
try {
while (!stopped) {
long sleepInMS;
if (pingMode) {
sleepInMS = ping();
} else {
sleepInMS = sendData();
}
Thread.sleep(sleepInMS);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ThreadDeath td) {
throw td;
} catch (Throwable t) {
// chomp
}
}
private long sendData() {
dataFetcher.prepareQuickPulseDataForSend();
final QuickPulseStatus currentQPStatus = dataSender.getQuickPulseStatus();
switch (currentQPStatus) {
case ERROR:
pingMode = true;
return waitOnErrorInMS;
case QP_IS_OFF:
pingMode = true;
return waitBetweenPingsInMS;
case QP_IS_ON:
return waitBetweenPostsInMS;
default:
logger.error( "Critical error while sending QP data: unknown status, aborting");
QuickPulseDataCollector.INSTANCE.disable();
stopped = true;
return 0;
}
}
private long ping() {
QuickPulseStatus pingResult = pingSender.ping();
switch (pingResult) {
case ERROR:
return waitOnErrorInMS;
case QP_IS_ON:
pingMode = false;
dataSender.startSending();
return waitBetweenPostsInMS;
case QP_IS_OFF:
return waitBetweenPingsInMS;
default:
logger.error( "Critical error while ping QP: unknown status, aborting");
QuickPulseDataCollector.INSTANCE.disable();
stopped = true;
return 0;
}
}
public void stop() {
stopped = true;
}
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* PHPExcel
*
* Copyright (c) 2006 - 2014 PHPExcel
*
* This library 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 library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel
* @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version 1.8.0, 2014-03-02
*/
PHPExcel_Autoloader::Register();
// As we always try to run the autoloader before anything else, we can use it to do a few
// simple checks and initialisations
//PHPExcel_Shared_ZipStreamWrapper::register();
// check mbstring.func_overload
if (ini_get('mbstring.func_overload') & 2) {
throw new PHPExcel_Exception('Multibyte function overloading in PHP must be disabled for string functions (2).');
}
PHPExcel_Shared_String::buildCharacterSets();
/**
* PHPExcel_Autoloader
*
* @category PHPExcel
* @package PHPExcel
* @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
*/
class PHPExcel_Autoloader
{
/**
* Register the Autoloader with SPL
*
*/
public static function Register() {
if (function_exists('__autoload')) {
// Register any existing autoloader function with SPL, so we don't get any clashes
spl_autoload_register('__autoload');
}
// Register ourselves with SPL
return spl_autoload_register(array('PHPExcel_Autoloader', 'Load'));
} // function Register()
/**
* Autoload a class identified by name
*
* @param string $pClassName Name of the object to load
*/
public static function Load($pClassName){
if ((class_exists($pClassName,FALSE)) || (strpos($pClassName, 'PHPExcel') !== 0)) {
// Either already loaded, or not a PHPExcel class request
return FALSE;
}
$pClassFilePath = PHPEXCEL_ROOT .
str_replace('_',DIRECTORY_SEPARATOR,$pClassName) .
'.php';
if ((file_exists($pClassFilePath) === FALSE) || (is_readable($pClassFilePath) === FALSE)) {
// Can't load
return FALSE;
}
require($pClassFilePath);
} // function Load()
}
| {
"pile_set_name": "Github"
} |
.shops-container {
display: flex;
justify-content: space-between;
align-items: center;
margin: 16rpx;
}
.shops-container .l {
display: flex;
align-items: center;
}
.shops-container .l text {
color: #666;
margin-left: 16rpx;
}
.shops-container .l image {
width: 40rpx;
height: 40rpx;
}
.shops-container .r {
display: flex;
align-items: center;
}
.shops-container .r text {
color: #666;
}
.shops-container .r image {
width: 40rpx;
height: 40rpx;
}
.search {
position: absolute;
top: 32rpx;
left: 25rpx;
width: 700rpx;
height: 66rpx;
display: block;
box-sizing: border-box;
}
.search input {
display: block;
box-sizing: border-box;
background: rgba(255, 255, 255, 0.8);
border: 1rpx solid #e3e3e3;
width: 700rpx;
height: 66rpx;
border-radius: 30rpx;
padding-left: 32rpx;
}
.search image {
width: 35rpx;
height: 35rpx;
position: absolute;
top: 16rpx;
right: 32rpx;
z-index: 99;
}
.goodsDynamic {
position: absolute;
top: 110rpx;
left: 25rpx;
width: 650rpx;
background: rgba(0, 0, 0, 0.6);
color: #fff;
padding: 8rpx 16rpx;
border-radius: 32rpx;
font-size: 24rpx;
}
.goodsDynamic .swiper2 {
width: 100%;
height: 32rpx;
}
.goodsDynamic-item {
width: 100%;
display: flex;
align-items: center;
}
.goodsDynamic-item image {
width: 32rpx;
height: 32rpx;
border-radius: 50%;
flex-shrink: 0;
}
.goodsDynamic-item text {
margin-left: 8rpx;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
.notice-box {
display: flex;
box-sizing: border-box;
width: 100vw;
height: 88rpx;
line-height: 88rpx;
justify-content: space-between;
align-items: center;
padding-right: 32rpx;
border-bottom: 1rpx solid #efeff4;
}
.notice{
display: flex;
justify-content: space-between;
align-items: center;
width: 600rpx;
}
.notice_icon {
margin-left:20rpx;
width:30rpx;
height:30rpx;
}
.notice_swiper{
height: 88rpx;
width: 600rpx;
}
.notice_itemr {
padding-left: 16rpx;
font-size: 24rpx;
overflow: hidden;
color: #e64340;
}
.notice-box .more {
color: #666;
font-size: 24rpx;
}
.container {
background-color: #fff;
min-height: 100%;
display: block;
}
.category-box {
background-color: #fff;
display: flex;
flex-wrap: wrap;
}
.category-list{
width:150rpx;
margin-top:20rpx;
text-align: center;
display: inline-block;
overflow: hidden;
}
.category-column{
width:100%;
margin-top:20rpx;
overflow: hidden;
}
.category-imgbox{
width:80rpx;
height:80rpx;
}
.category-title{
font-size: 24rpx;
text-align:center;
margin-top:10rpx;
}
.swiper-container{
width: 750rpx;
height: 375rpx;
position: relative;
}
.swiper-container .swiper1 {
width: 750rpx;
height: 375rpx;
}
.swiper-container .swiper1 image {
width: 750rpx;
height: 375rpx;
}
::-webkit-scrollbar {
width: 0;
height: 0;
color: transparent;
}
.type-item-on{
color:#e64340;
border-bottom: 1rpx solid #e64340;
}
.weui-loadmore {
margin-bottom: 0px;
}
.goods-container{
display: flex;
justify-content: space-between;
flex-wrap:wrap;
box-sizing: content-box;
padding: 24rpx;
background-color: #F2f2f2;
}
.goods-box{
width: 339rpx;
height: 472rpx;
background-color: #fff;
overflow: hidden;
margin-bottom: 24rpx;
border-radius:5px;
}
.goods-box .img-box{
width: 339rpx;
height: 339rpx;
overflow: hidden;
}
.goods-box .img-box image{
width: 339rpx;
height: 339rpx;
}
.goods-box .goods-title{
width: 280rpx;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
font-size: 24rpx;
padding: 24rpx 0 0rpx 0;
color:#000;
margin-left: 24rpx;
}
.goods-box .goods-price{
width: 280rpx;
overflow: hidden;
font-size: 24rpx;
padding: 24rpx 0;
color:#e64340;
margin-left: 24rpx;
}
.pos-fiexd{
position: fixed;
top: 0;
left: 0;
}
.coupons{
margin-top:10rpx;
width: 100%;
height: 180rpx;
overflow: hidden;
}
.coupons-scroll{
white-space: nowrap;
height: 180rpx;
width: 100%;
background-color: #fff;
}
.coupons-item{
width:300rpx;
height: 180rpx;
margin: 10rpx;
padding-top: 20rpx;
padding-left: 15rpx;
background-color: #f1a83b;
box-sizing: content-box;
font-size: 20rpx;
line-height: 35rpx;
overflow: hidden;
color: #fff;
display: inline-block;
}
.coupons-float {
position: fixed;
right:15rpx;
bottom:80rpx;
width:80rpx;
height:80rpx;
background-color: #fff;
text-align: center;
border-radius:50%;
border: 1rpx solid #ddd;
}
.coupons-float image {
width:60rpx;
height:60rpx;
margin-top: 10rpx;
}
.tuan {
width:750rpx;
background-color: #F2f2f2;
padding-top:10rpx;
}
.tuan-item {
width:720rpx;
margin: auto;
margin-top: 20rpx;
background-color: #FFF;
position: relative;
}
.tuan-goods-pic {
width:720rpx;
height: 250rpx;
overflow: hidden;
}
.tuan-goods-pic image {
width:720rpx;
}
.tuan-title {
margin-top: 20rpx;
margin-left: 20rpx;
font-size:30rpx;
font-weight: 400;
}
.tuan-profile {
margin-left: 20rpx;
font-size:28rpx;
color:#999;
}
.tuan-price {
margin-left: 20rpx;
}
.tuan-price .now {
font-size:36rpx;
color:#e64340;
}
.tuan-price .original {
margin-left: 20rpx;
font-size:26rpx;
color:#999;
text-decoration:line-through;
}
.tuan-btn {
position: absolute;
right:30rpx;
bottom: 10rpx;
}
.category-goods-title {
width: 100vw;
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8rpx;
border-bottom: 1rpx solid #efeff4;
}
.category-goods-title .more {
color: #666;
font-size: 24rpx;
margin-right: 32rpx;
}
.weui-media-box {
padding-bottom: 0rpx;
}
.progress {
width: 686rpx;
padding: 0 32rpx;
margin-bottom: 16rpx;
}
/*秒杀*/
.miaosha-container {
padding: 0;
}
.miaosha-goods-list {
margin: 20rpx;
background: #f6f6f6;
border-radius: 16rpx;
display: flex;
padding: 20rpx;
}
.miaosha-goods-list .image {
width: 260rpx;
height: 260rpx;
flex-shrink: 0;
border-radius: 16rpx;
}
.miaosha-goods-list .r {
margin-left: 32rpx;
}
.miaosha-goods-list .r .goods-title {
color: #333;
font-size: 28rpx;
}
.miaosha-goods-list .r .label {
color: #e64340;
font-size: 24rpx;
display: flex;
align-items: flex-start;
margin-top: 8rpx;
}
.miaosha-goods-list .r .label text {
margin-left: 8rpx;
}
.miaosha-goods-list .count-down {
background: #e64340;
padding: 8rpx 16rpx;
border-radius: 16rpx;
margin-top: 12rpx;
}
.van-count-down {
color: #fff !important;
}
.miaosha-price-btn {
display: flex;
justify-content: space-between;
align-items: center;
}
.miaosha-price-btn .price {
color: #e64340;
font-size: 40rpx;
margin-top: 12rpx;
}
.miaosha-price-btn .price text {
color: #666666;
font-size: 26rpx;
text-decoration:line-through;
}
.live-banner {
width: 100vw;
margin-top: 32rpx;
} | {
"pile_set_name": "Github"
} |
<?php
/*
pRadar - class to draw radar charts
Version : 2.1.4
Made by : Jean-Damien POGOLOTTI
Last Update : 19/01/2014
This file can be distributed under the license you can find at :
http://www.pchart.net/license
You can find the whole class documentation on the pChart web site.
*/
define("SEGMENT_HEIGHT_AUTO" , 690001);
define("RADAR_LAYOUT_STAR" , 690011);
define("RADAR_LAYOUT_CIRCLE" , 690012);
define("RADAR_LABELS_ROTATED" , 690021);
define("RADAR_LABELS_HORIZONTAL" , 690022);
/* pRadar class definition */
class pRadar
{
var $pChartObject;
/* Class creator */
function pRadar()
{ }
/* Draw a radar chart */
function drawRadar($Object,$Values,$Format="")
{
$this->pChartObject = $Object;
$FixedMax = isset($Format["FixedMax"]) ? $Format["FixedMax"] : VOID;
$AxisR = isset($Format["AxisR"]) ? $Format["AxisR"] : 60;
$AxisG = isset($Format["AxisG"]) ? $Format["AxisG"] : 60;
$AxisB = isset($Format["AxisB"]) ? $Format["AxisB"] : 60;
$AxisAlpha = isset($Format["AxisAlpha"]) ? $Format["AxisAlpha"] : 50;
$AxisRotation = isset($Format["AxisRotation"]) ? $Format["AxisRotation"] : 0;
$DrawTicks = isset($Format["DrawTicks"]) ? $Format["DrawTicks"] : TRUE;
$TicksLength = isset($Format["TicksLength"]) ? $Format["TicksLength"] : 2;
$DrawAxisValues = isset($Format["DrawAxisValues"]) ? $Format["DrawAxisValues"] : TRUE;
$AxisBoxRounded = isset($Format["AxisBoxRounded"]) ? $Format["AxisBoxRounded"] : TRUE;
$AxisFontName = isset($Format["AxisFontName"]) ? $Format["AxisFontName"] : $this->pChartObject->FontName;
$AxisFontSize = isset($Format["AxisFontSize"]) ? $Format["AxisFontSize"] : $this->pChartObject->FontSize;
$WriteValues = isset($Format["WriteValues"]) ? $Format["WriteValues"] : FALSE;
$WriteValuesInBubble = isset($Format["WriteValuesInBubble"]) ? $Format["WriteValuesInBubble"] : TRUE;
$ValueFontName = isset($Format["ValueFontName"]) ? $Format["ValueFontName"] : $this->pChartObject->FontName;
$ValueFontSize = isset($Format["ValueFontSize"]) ? $Format["ValueFontSize"] : $this->pChartObject->FontSize;
$ValuePadding = isset($Format["ValuePadding"]) ? $Format["ValuePadding"] : 4;
$OuterBubbleRadius = isset($Format["OuterBubbleRadius"]) ? $Format["OuterBubbleRadius"] : 2;
$OuterBubbleR = isset($Format["OuterBubbleR"]) ? $Format["OuterBubbleR"] : VOID;
$OuterBubbleG = isset($Format["OuterBubbleG"]) ? $Format["OuterBubbleG"] : VOID;
$OuterBubbleB = isset($Format["OuterBubbleB"]) ? $Format["OuterBubbleB"] : VOID;
$OuterBubbleAlpha = isset($Format["OuterBubbleAlpha"]) ? $Format["OuterBubbleAlpha"] : 100;
$InnerBubbleR = isset($Format["InnerBubbleR"]) ? $Format["InnerBubbleR"] : 255;
$InnerBubbleG = isset($Format["InnerBubbleG"]) ? $Format["InnerBubbleG"] : 255;
$InnerBubbleB = isset($Format["InnerBubbleB"]) ? $Format["InnerBubbleB"] : 255;
$InnerBubbleAlpha = isset($Format["InnerBubbleAlpha"]) ? $Format["InnerBubbleAlpha"] : 100;
$DrawBackground = isset($Format["DrawBackground"]) ? $Format["DrawBackground"] : TRUE;
$BackgroundR = isset($Format["BackgroundR"]) ? $Format["BackgroundR"] : 255;
$BackgroundG = isset($Format["BackgroundG"]) ? $Format["BackgroundG"] : 255;
$BackgroundB = isset($Format["BackgroundB"]) ? $Format["BackgroundB"] : 255;
$BackgroundAlpha = isset($Format["BackgroundAlpha"]) ? $Format["BackgroundAlpha"] : 50;
$BackgroundGradient= isset($Format["BackgroundGradient"]) ? $Format["BackgroundGradient"] : NULL;
$Layout = isset($Format["Layout"]) ? $Format["Layout"] : RADAR_LAYOUT_STAR;
$SegmentHeight = isset($Format["SegmentHeight"]) ? $Format["SegmentHeight"] : SEGMENT_HEIGHT_AUTO;
$Segments = isset($Format["Segments"]) ? $Format["Segments"] : 4;
$WriteLabels = isset($Format["WriteLabels"]) ? $Format["WriteLabels"] : TRUE;
$SkipLabels = isset($Format["SkipLabels"]) ? $Format["SkipLabels"] : 1;
$LabelMiddle = isset($Format["LabelMiddle"]) ? $Format["LabelMiddle"] : FALSE;
$LabelsBackground = isset($Format["LabelsBackground"]) ? $Format["LabelsBackground"] : TRUE;
$LabelsBGR = isset($Format["LabelsBGR"]) ? $Format["LabelsBGR"] : 255;
$LabelsBGG = isset($Format["LabelsBGR"]) ? $Format["LabelsBGG"] : 255;
$LabelsBGB = isset($Format["LabelsBGR"]) ? $Format["LabelsBGB"] : 255;
$LabelsBGAlpha = isset($Format["LabelsBGAlpha"]) ? $Format["LabelsBGAlpha"] : 50;
$LabelPos = isset($Format["LabelPos"]) ? $Format["LabelPos"] : RADAR_LABELS_ROTATED;
$LabelPadding = isset($Format["LabelPadding"]) ? $Format["LabelPadding"] : 4;
$DrawPoints = isset($Format["DrawPoints"]) ? $Format["DrawPoints"] : TRUE;
$PointRadius = isset($Format["PointRadius"]) ? $Format["PointRadius"] : 4;
$PointSurrounding = isset($Format["PointRadius"]) ? $Format["PointRadius"] : -30;
$DrawLines = isset($Format["DrawLines"]) ? $Format["DrawLines"] : TRUE;
$LineLoopStart = isset($Format["LineLoopStart"]) ? $Format["LineLoopStart"] : TRUE;
$DrawPoly = isset($Format["DrawPoly"]) ? $Format["DrawPoly"] : FALSE;
$PolyAlpha = isset($Format["PolyAlpha"]) ? $Format["PolyAlpha"] : 40;
$FontSize = $Object->FontSize;
$X1 = $Object->GraphAreaX1;
$Y1 = $Object->GraphAreaY1;
$X2 = $Object->GraphAreaX2;
$Y2 = $Object->GraphAreaY2;
$RecordImageMap = isset($Format["RecordImageMap"]) ? $Format["RecordImageMap"] : FALSE;
/* Cancel default tick length if ticks not enabled */
if ( $DrawTicks == FALSE ) { $TicksLength = 0; }
/* Data Processing */
$Data = $Values->getData();
$Palette = $Values->getPalette();
/* Catch the number of required axis */
$LabelSerie = $Data["Abscissa"];
if ( $LabelSerie != "" )
{ $Points = count($Data["Series"][$LabelSerie]["Data"]); }
else
{
$Points = 0;
foreach($Data["Series"] as $SerieName => $DataArray)
{ if ( count($DataArray["Data"]) > $Points ) { $Points = count($DataArray["Data"]); } }
}
/* Draw the axis */
$CenterX = ($X2-$X1)/2 + $X1;
$CenterY = ($Y2-$Y1)/2 + $Y1;
$EdgeHeight = min(($X2-$X1)/2,($Y2-$Y1)/2);
if ( $WriteLabels )
$EdgeHeight = $EdgeHeight - $FontSize - $LabelPadding - $TicksLength;
/* Determine the scale if set to automatic */
if ( $SegmentHeight == SEGMENT_HEIGHT_AUTO)
{
if ( $FixedMax != VOID )
$Max = $FixedMax;
else
{
$Max = 0;
foreach($Data["Series"] as $SerieName => $DataArray)
{
if ( $SerieName != $LabelSerie )
{
if ( max($DataArray["Data"]) > $Max ) { $Max = max($DataArray["Data"]); }
}
}
}
$MaxSegments = $EdgeHeight/20;
$Scale = $Object->computeScale(0,$Max,$MaxSegments,array(1,2,5));
$Segments = $Scale["Rows"];
$SegmentHeight = $Scale["RowHeight"];
}
if ( $LabelMiddle && $SkipLabels == 1 )
{ $Axisoffset = (360/$Points)/2; }
elseif ( $LabelMiddle && $SkipLabels != 1 )
{ $Axisoffset = (360/($Points/$SkipLabels))/2; }
elseif ( !$LabelMiddle )
{ $Axisoffset = 0; }
/* Background processing */
if ( $DrawBackground )
{
$RestoreShadow = $Object->Shadow;
$Object->Shadow = FALSE;
if ($BackgroundGradient == NULL)
{
if ( $Layout == RADAR_LAYOUT_STAR )
{
$Color = array("R"=>$BackgroundR,"G"=>$BackgroundG,"B"=>$BackgroundB,"Alpha"=>$BackgroundAlpha);
$PointArray = "";
for($i=0;$i<=360;$i=$i+(360/$Points))
{
$PointArray[] = cos(deg2rad($i+$AxisRotation)) * $EdgeHeight + $CenterX;
$PointArray[] = sin(deg2rad($i+$AxisRotation)) * $EdgeHeight + $CenterY;
}
$Object->drawPolygon($PointArray,$Color);
}
elseif ( $Layout == RADAR_LAYOUT_CIRCLE )
{
$Color = array("R"=>$BackgroundR,"G"=>$BackgroundG,"B"=>$BackgroundB,"Alpha"=>$BackgroundAlpha);
$Object->drawFilledCircle($CenterX,$CenterY,$EdgeHeight,$Color);
}
}
else
{
$GradientROffset = ($BackgroundGradient["EndR"] - $BackgroundGradient["StartR"]) / $Segments;
$GradientGOffset = ($BackgroundGradient["EndG"] - $BackgroundGradient["StartG"]) / $Segments;
$GradientBOffset = ($BackgroundGradient["EndB"] - $BackgroundGradient["StartB"]) / $Segments;
$GradientAlphaOffset = ($BackgroundGradient["EndAlpha"] - $BackgroundGradient["StartAlpha"]) / $Segments;
if ( $Layout == RADAR_LAYOUT_STAR )
{
for($j=$Segments;$j>=1;$j--)
{
$Color = array("R"=>$BackgroundGradient["StartR"]+$GradientROffset*$j,"G"=>$BackgroundGradient["StartG"]+$GradientGOffset*$j,"B"=>$BackgroundGradient["StartB"]+$GradientBOffset*$j,"Alpha"=>$BackgroundGradient["StartAlpha"]+$GradientAlphaOffset*$j);
$PointArray = "";
for($i=0;$i<=360;$i=$i+(360/$Points))
{
$PointArray[] = cos(deg2rad($i+$AxisRotation)) * ($EdgeHeight/$Segments)*$j + $CenterX;
$PointArray[] = sin(deg2rad($i+$AxisRotation)) * ($EdgeHeight/$Segments)*$j + $CenterY;
}
$Object->drawPolygon($PointArray,$Color);
}
}
elseif ( $Layout == RADAR_LAYOUT_CIRCLE )
{
for($j=$Segments;$j>=1;$j--)
{
$Color = array("R"=>$BackgroundGradient["StartR"]+$GradientROffset*$j,"G"=>$BackgroundGradient["StartG"]+$GradientGOffset*$j,"B"=>$BackgroundGradient["StartB"]+$GradientBOffset*$j,"Alpha"=>$BackgroundGradient["StartAlpha"]+$GradientAlphaOffset*$j);
$Object->drawFilledCircle($CenterX,$CenterY,($EdgeHeight/$Segments)*$j,$Color);
}
}
}
$Object->Shadow = $RestoreShadow;
}
/* Axis to axis lines */
$Color = array("R"=>$AxisR,"G"=>$AxisG,"B"=>$AxisB,"Alpha"=>$AxisAlpha);
$ColorDotted = array("R"=>$AxisR,"G"=>$AxisG,"B"=>$AxisB,"Alpha"=>$AxisAlpha*.8, "Ticks"=>2);
if ( $Layout == RADAR_LAYOUT_STAR )
{
for($j=1;$j<=$Segments;$j++)
{
for($i=0;$i<360;$i=$i+(360/$Points))
{
$EdgeX1 = cos(deg2rad($i+$AxisRotation)) * ($EdgeHeight/$Segments)*$j + $CenterX;
$EdgeY1 = sin(deg2rad($i+$AxisRotation)) * ($EdgeHeight/$Segments)*$j + $CenterY;
$EdgeX2 = cos(deg2rad($i+$AxisRotation+(360/$Points))) * ($EdgeHeight/$Segments)*$j + $CenterX;
$EdgeY2 = sin(deg2rad($i+$AxisRotation+(360/$Points))) * ($EdgeHeight/$Segments)*$j + $CenterY;
$Object->drawLine($EdgeX1,$EdgeY1,$EdgeX2,$EdgeY2,$Color);
}
}
}
elseif ( $Layout == RADAR_LAYOUT_CIRCLE )
{
for($j=1;$j<=$Segments;$j++)
{
$Radius = ($EdgeHeight/$Segments)*$j;
$Object->drawCircle($CenterX,$CenterY,$Radius,$Radius,$Color);
}
}
if ( $DrawAxisValues )
{
if ( $LabelsBackground )
$Options = array("DrawBox"=>TRUE, "Align"=>TEXT_ALIGN_MIDDLEMIDDLE,"BoxR"=>$LabelsBGR,"BoxG"=>$LabelsBGG,"BoxB"=>$LabelsBGB,"BoxAlpha"=>$LabelsBGAlpha);
else
$Options = array("Align"=>TEXT_ALIGN_MIDDLEMIDDLE);
if ( $AxisBoxRounded ) { $Options["BoxRounded"] = TRUE; }
$Options["FontName"] = $AxisFontName;
$Options["FontSize"] = $AxisFontSize;
$Angle = 360 / ($Points*2);
for($j=1;$j<=$Segments;$j++)
{
$Label = $j * $SegmentHeight;
if ( $Layout == RADAR_LAYOUT_CIRCLE )
{
$EdgeX1 = cos(deg2rad($Angle+$AxisRotation)) * ($EdgeHeight/$Segments)*$j + $CenterX;
$EdgeY1 = sin(deg2rad($Angle+$AxisRotation)) * ($EdgeHeight/$Segments)*$j + $CenterY;
}
elseif ( $Layout == RADAR_LAYOUT_STAR )
{
$EdgeX1 = cos(deg2rad($AxisRotation)) * ($EdgeHeight/$Segments)*$j + $CenterX;
$EdgeY1 = sin(deg2rad($AxisRotation)) * ($EdgeHeight/$Segments)*$j + $CenterY;
$EdgeX2 = cos(deg2rad((360 / $Points) + $AxisRotation)) * ($EdgeHeight/$Segments)*$j + $CenterX;
$EdgeY2 = sin(deg2rad((360 / $Points) + $AxisRotation)) * ($EdgeHeight/$Segments)*$j + $CenterY;
$EdgeX1 = ($EdgeX2 - $EdgeX1)/2 + $EdgeX1;
$EdgeY1 = ($EdgeY2 - $EdgeY1)/2 + $EdgeY1;
}
$Object->drawText($EdgeX1,$EdgeY1,$Label,$Options);
}
}
/* Axis lines */
$ID = 0;
for($i=0;$i<360;$i=$i+(360/$Points))
{
$EdgeX = cos(deg2rad($i+$AxisRotation)) * ($EdgeHeight+$TicksLength) + $CenterX;
$EdgeY = sin(deg2rad($i+$AxisRotation)) * ($EdgeHeight+$TicksLength) + $CenterY;
if ($ID % $SkipLabels == 0)
{ $Object->drawLine($CenterX,$CenterY,$EdgeX,$EdgeY,$Color); }
else
{ $Object->drawLine($CenterX,$CenterY,$EdgeX,$EdgeY,$ColorDotted); }
if ( $WriteLabels )
{
$LabelX = cos(deg2rad($i+$AxisRotation+$Axisoffset)) * ($EdgeHeight+$LabelPadding+$TicksLength) + $CenterX;
$LabelY = sin(deg2rad($i+$AxisRotation+$Axisoffset)) * ($EdgeHeight+$LabelPadding+$TicksLength) + $CenterY;
if ( $LabelSerie != "" )
{ $Label = isset($Data["Series"][$LabelSerie]["Data"][$ID]) ? $Data["Series"][$LabelSerie]["Data"][$ID] : ""; }
else
$Label = $ID;
if ($ID % $SkipLabels == 0)
{
if ( $LabelPos == RADAR_LABELS_ROTATED )
$Object->drawText($LabelX,$LabelY,$Label,array("Angle"=>(360-($i+$AxisRotation+$Axisoffset))-90,"Align"=>TEXT_ALIGN_BOTTOMMIDDLE));
else
{
if ( (floor($LabelX) == floor($CenterX)) && (floor($LabelY) < floor($CenterY)) ) { $Object->drawText($LabelX,$LabelY,$Label,array("Align"=>TEXT_ALIGN_BOTTOMMIDDLE)); }
if ( (floor($LabelX) > floor($CenterX)) && (floor($LabelY) < floor($CenterY)) ) { $Object->drawText($LabelX,$LabelY,$Label,array("Align"=>TEXT_ALIGN_BOTTOMLEFT)); }
if ( (floor($LabelX) > floor($CenterX)) && (floor($LabelY) == floor($CenterY)) ) { $Object->drawText($LabelX,$LabelY,$Label,array("Align"=>TEXT_ALIGN_MIDDLELEFT)); }
if ( (floor($LabelX) > floor($CenterX)) && (floor($LabelY) > floor($CenterY)) ) { $Object->drawText($LabelX,$LabelY,$Label,array("Align"=>TEXT_ALIGN_TOPLEFT)); }
if ( (floor($LabelX) < floor($CenterX)) && (floor($LabelY) < floor($CenterY)) ) { $Object->drawText($LabelX,$LabelY,$Label,array("Align"=>TEXT_ALIGN_BOTTOMRIGHT)); }
if ( (floor($LabelX) < floor($CenterX)) && (floor($LabelY) == floor($CenterY)) ) { $Object->drawText($LabelX,$LabelY,$Label,array("Align"=>TEXT_ALIGN_MIDDLERIGHT)); }
if ( (floor($LabelX) < floor($CenterX)) && (floor($LabelY) > floor($CenterY)) ) { $Object->drawText($LabelX,$LabelY,$Label,array("Align"=>TEXT_ALIGN_TOPRIGHT)); }
if ( (floor($LabelX) == floor($CenterX)) && (floor($LabelY) > floor($CenterY)) ) { $Object->drawText($LabelX,$LabelY,$Label,array("Align"=>TEXT_ALIGN_TOPMIDDLE)); }
}
}
}
$ID++;
}
/* Compute the plots position */
$ID = 0; $Plot = "";
foreach($Data["Series"] as $SerieName => $DataS)
{
if ( $SerieName != $LabelSerie )
{
$Color = array("R"=>$Palette[$ID]["R"],"G"=>$Palette[$ID]["G"],"B"=>$Palette[$ID]["B"],"Alpha"=>$Palette[$ID]["Alpha"],"Surrounding"=>$PointSurrounding);
foreach($DataS["Data"] as $Key => $Value)
{
$Angle = (360/$Points) * $Key;
$Length = ($EdgeHeight/($Segments*$SegmentHeight))*$Value;
$X = cos(deg2rad($Angle+$AxisRotation)) * $Length + $CenterX;
$Y = sin(deg2rad($Angle+$AxisRotation)) * $Length + $CenterY;
$Plot[$ID][] = array($X,$Y,$Value);
if ( $RecordImageMap ) { $this->pChartObject->addToImageMap("CIRCLE",floor($X).",".floor($Y).",".floor($PointRadius),$this->pChartObject->toHTMLColor($Palette[$ID]["R"],$Palette[$ID]["G"],$Palette[$ID]["B"]),$DataS["Description"],$Data["Series"][$LabelSerie]["Data"][$Key]." = ".$Value); }
}
$ID++;
}
}
/* Draw all that stuff! */
foreach($Plot as $ID => $Points)
{
$Color = array("R"=>$Palette[$ID]["R"],"G"=>$Palette[$ID]["G"],"B"=>$Palette[$ID]["B"],"Alpha"=>$Palette[$ID]["Alpha"],"Surrounding"=>$PointSurrounding);
/* Draw the polygons */
if ( $DrawPoly )
{
if ($PolyAlpha != NULL)
$Color = array("R"=>$Palette[$ID]["R"],"G"=>$Palette[$ID]["G"],"B"=>$Palette[$ID]["B"],"Alpha"=>$PolyAlpha,"Surrounding"=>$PointSurrounding);
$PointsArray = "";
for($i=0; $i<count($Points);$i++)
{ $PointsArray[] = $Points[$i][0]; $PointsArray[] = $Points[$i][1]; }
$Object->drawPolygon($PointsArray,$Color);
}
$Color = array("R"=>$Palette[$ID]["R"],"G"=>$Palette[$ID]["G"],"B"=>$Palette[$ID]["B"],"Alpha"=>$Palette[$ID]["Alpha"],"Surrounding"=>$PointSurrounding);
/* Bubble and labels settings */
$TextSettings = array("Align"=>TEXT_ALIGN_MIDDLEMIDDLE,"FontName"=>$ValueFontName,"FontSize"=>$ValueFontSize,"R"=>$Palette[$ID]["R"],"G"=>$Palette[$ID]["G"],"B"=>$Palette[$ID]["B"]);
$InnerColor = array("R"=>$InnerBubbleR,"G"=>$InnerBubbleG,"B"=>$InnerBubbleB,"Alpha"=>$InnerBubbleAlpha);
if ( $OuterBubbleR != VOID )
$OuterColor = array("R"=>$OuterBubbleR,"G"=>$OuterBubbleG,"B"=>$OuterBubbleB,"Alpha"=>$OuterBubbleAlpha);
else
$OuterColor = array("R"=>$Palette[$ID]["R"]+20,"G"=>$Palette[$ID]["G"]+20,"B"=>$Palette[$ID]["B"]+20,"Alpha"=>$Palette[$ID]["Alpha"]);
/* Loop to the starting points if asked */
if ( $LineLoopStart && $DrawLines )
$Object->drawLine($Points[count($Points)-1][0],$Points[count($Points)-1][1],$Points[0][0],$Points[0][1],$Color);
/* Draw the lines & points */
for($i=0; $i<count($Points);$i++)
{
if ( $DrawLines && $i < count($Points)-1)
$Object->drawLine($Points[$i][0],$Points[$i][1],$Points[$i+1][0],$Points[$i+1][1],$Color);
if ( $DrawPoints )
$Object->drawFilledCircle($Points[$i][0],$Points[$i][1],$PointRadius,$Color);
if ( $WriteValuesInBubble && $WriteValues )
{
$TxtPos = $this->pChartObject->getTextBox($Points[$i][0],$Points[$i][1],$ValueFontName,$ValueFontSize,0,$Points[$i][2]);
$Radius = floor(($TxtPos[1]["X"] - $TxtPos[0]["X"] + $ValuePadding*2)/2);
$this->pChartObject->drawFilledCircle($Points[$i][0],$Points[$i][1],$Radius+$OuterBubbleRadius,$OuterColor);
$this->pChartObject->drawFilledCircle($Points[$i][0],$Points[$i][1],$Radius,$InnerColor);
}
if ( $WriteValues )
$this->pChartObject->drawText($Points[$i][0]-1,$Points[$i][1]-1,$Points[$i][2],$TextSettings);
}
}
}
/* Draw a radar chart */
function drawPolar($Object,$Values,$Format="")
{
$this->pChartObject = $Object;
$FixedMax = isset($Format["FixedMax"]) ? $Format["FixedMax"] : VOID;
$AxisR = isset($Format["AxisR"]) ? $Format["AxisR"] : 60;
$AxisG = isset($Format["AxisG"]) ? $Format["AxisG"] : 60;
$AxisB = isset($Format["AxisB"]) ? $Format["AxisB"] : 60;
$AxisAlpha = isset($Format["AxisAlpha"]) ? $Format["AxisAlpha"] : 50;
$AxisRotation = isset($Format["AxisRotation"]) ? $Format["AxisRotation"] : -90;
$DrawTicks = isset($Format["DrawTicks"]) ? $Format["DrawTicks"] : TRUE;
$TicksLength = isset($Format["TicksLength"]) ? $Format["TicksLength"] : 2;
$DrawAxisValues = isset($Format["DrawAxisValues"]) ? $Format["DrawAxisValues"] : TRUE;
$AxisBoxRounded = isset($Format["AxisBoxRounded"]) ? $Format["AxisBoxRounded"] : TRUE;
$AxisFontName = isset($Format["FontName"]) ? $Format["FontName"] : $this->pChartObject->FontName;
$AxisFontSize = isset($Format["FontSize"]) ? $Format["FontSize"] : $this->pChartObject->FontSize;
$WriteValues = isset($Format["WriteValues"]) ? $Format["WriteValues"] : FALSE;
$WriteValuesInBubble = isset($Format["WriteValuesInBubble"]) ? $Format["WriteValuesInBubble"] : TRUE;
$ValueFontName = isset($Format["ValueFontName"]) ? $Format["ValueFontName"] : $this->pChartObject->FontName;
$ValueFontSize = isset($Format["ValueFontSize"]) ? $Format["ValueFontSize"] : $this->pChartObject->FontSize;
$ValuePadding = isset($Format["ValuePadding"]) ? $Format["ValuePadding"] : 4;
$OuterBubbleRadius = isset($Format["OuterBubbleRadius"]) ? $Format["OuterBubbleRadius"] : 2;
$OuterBubbleR = isset($Format["OuterBubbleR"]) ? $Format["OuterBubbleR"] : VOID;
$OuterBubbleG = isset($Format["OuterBubbleG"]) ? $Format["OuterBubbleG"] : VOID;
$OuterBubbleB = isset($Format["OuterBubbleB"]) ? $Format["OuterBubbleB"] : VOID;
$OuterBubbleAlpha = isset($Format["OuterBubbleAlpha"]) ? $Format["OuterBubbleAlpha"] : 100;
$InnerBubbleR = isset($Format["InnerBubbleR"]) ? $Format["InnerBubbleR"] : 255;
$InnerBubbleG = isset($Format["InnerBubbleG"]) ? $Format["InnerBubbleG"] : 255;
$InnerBubbleB = isset($Format["InnerBubbleB"]) ? $Format["InnerBubbleB"] : 255;
$InnerBubbleAlpha = isset($Format["InnerBubbleAlpha"]) ? $Format["InnerBubbleAlpha"] : 100;
$DrawBackground = isset($Format["DrawBackground"]) ? $Format["DrawBackground"] : TRUE;
$BackgroundR = isset($Format["BackgroundR"]) ? $Format["BackgroundR"] : 255;
$BackgroundG = isset($Format["BackgroundG"]) ? $Format["BackgroundG"] : 255;
$BackgroundB = isset($Format["BackgroundB"]) ? $Format["BackgroundB"] : 255;
$BackgroundAlpha = isset($Format["BackgroundAlpha"]) ? $Format["BackgroundAlpha"] : 50;
$BackgroundGradient= isset($Format["BackgroundGradient"]) ? $Format["BackgroundGradient"] : NULL;
$AxisSteps = isset($Format["AxisSteps"]) ? $Format["AxisSteps"] : 20;
$SegmentHeight = isset($Format["SegmentHeight"]) ? $Format["SegmentHeight"] : SEGMENT_HEIGHT_AUTO;
$Segments = isset($Format["Segments"]) ? $Format["Segments"] : 4;
$WriteLabels = isset($Format["WriteLabels"]) ? $Format["WriteLabels"] : TRUE;
$LabelsBackground = isset($Format["LabelsBackground"]) ? $Format["LabelsBackground"] : TRUE;
$LabelsBGR = isset($Format["LabelsBGR"]) ? $Format["LabelsBGR"] : 255;
$LabelsBGG = isset($Format["LabelsBGR"]) ? $Format["LabelsBGG"] : 255;
$LabelsBGB = isset($Format["LabelsBGR"]) ? $Format["LabelsBGB"] : 255;
$LabelsBGAlpha = isset($Format["LabelsBGAlpha"]) ? $Format["LabelsBGAlpha"] : 50;
$LabelPos = isset($Format["LabelPos"]) ? $Format["LabelPos"] : RADAR_LABELS_ROTATED;
$LabelPadding = isset($Format["LabelPadding"]) ? $Format["LabelPadding"] : 4;
$DrawPoints = isset($Format["DrawPoints"]) ? $Format["DrawPoints"] : TRUE;
$PointRadius = isset($Format["PointRadius"]) ? $Format["PointRadius"] : 4;
$PointSurrounding = isset($Format["PointRadius"]) ? $Format["PointRadius"] : -30;
$DrawLines = isset($Format["DrawLines"]) ? $Format["DrawLines"] : TRUE;
$LineLoopStart = isset($Format["LineLoopStart"]) ? $Format["LineLoopStart"] : FALSE;
$DrawPoly = isset($Format["DrawPoly"]) ? $Format["DrawPoly"] : FALSE;
$PolyAlpha = isset($Format["PolyAlpha"]) ? $Format["PolyAlpha"] : NULL;
$FontSize = $Object->FontSize;
$X1 = $Object->GraphAreaX1;
$Y1 = $Object->GraphAreaY1;
$X2 = $Object->GraphAreaX2;
$Y2 = $Object->GraphAreaY2;
$RecordImageMap = isset($Format["RecordImageMap"]) ? $Format["RecordImageMap"] : FALSE;
if ( $AxisBoxRounded ) { $DrawAxisValues = TRUE; }
/* Cancel default tick length if ticks not enabled */
if ( $DrawTicks == FALSE ) { $TicksLength = 0; }
/* Data Processing */
$Data = $Values->getData();
$Palette = $Values->getPalette();
/* Catch the number of required axis */
$LabelSerie = $Data["Abscissa"];
if ( $LabelSerie != "" )
{ $Points = count($Data["Series"][$LabelSerie]["Data"]); }
else
{
$Points = 0;
foreach($Data["Series"] as $SerieName => $DataArray)
{ if ( count($DataArray["Data"]) > $Points ) { $Points = count($DataArray["Data"]); } }
}
/* Draw the axis */
$CenterX = ($X2-$X1)/2 + $X1;
$CenterY = ($Y2-$Y1)/2 + $Y1;
$EdgeHeight = min(($X2-$X1)/2,($Y2-$Y1)/2);
if ( $WriteLabels )
$EdgeHeight = $EdgeHeight - $FontSize - $LabelPadding - $TicksLength;
/* Determine the scale if set to automatic */
if ( $SegmentHeight == SEGMENT_HEIGHT_AUTO)
{
if ( $FixedMax != VOID )
$Max = $FixedMax;
else
{
$Max = 0;
foreach($Data["Series"] as $SerieName => $DataArray)
{
if ( $SerieName != $LabelSerie )
{
if ( max($DataArray["Data"]) > $Max ) { $Max = max($DataArray["Data"]); }
}
}
}
$MaxSegments = $EdgeHeight/20;
$Scale = $Object->computeScale(0,$Max,$MaxSegments,array(1,2,5));
$Segments = $Scale["Rows"];
$SegmentHeight = $Scale["RowHeight"];
}
/* Background processing */
if ( $DrawBackground )
{
$RestoreShadow = $Object->Shadow;
$Object->Shadow = FALSE;
if ($BackgroundGradient == NULL)
{
$Color = array("R"=>$BackgroundR,"G"=>$BackgroundG,"B"=>$BackgroundB,"Alpha"=>$BackgroundAlpha);
$Object->drawFilledCircle($CenterX,$CenterY,$EdgeHeight,$Color);
}
else
{
$GradientROffset = ($BackgroundGradient["EndR"] - $BackgroundGradient["StartR"]) / $Segments;
$GradientGOffset = ($BackgroundGradient["EndG"] - $BackgroundGradient["StartG"]) / $Segments;
$GradientBOffset = ($BackgroundGradient["EndB"] - $BackgroundGradient["StartB"]) / $Segments;
$GradientAlphaOffset = ($BackgroundGradient["EndAlpha"] - $BackgroundGradient["StartAlpha"]) / $Segments;
for($j=$Segments;$j>=1;$j--)
{
$Color = array("R"=>$BackgroundGradient["StartR"]+$GradientROffset*$j,"G"=>$BackgroundGradient["StartG"]+$GradientGOffset*$j,"B"=>$BackgroundGradient["StartB"]+$GradientBOffset*$j,"Alpha"=>$BackgroundGradient["StartAlpha"]+$GradientAlphaOffset*$j);
$Object->drawFilledCircle($CenterX,$CenterY,($EdgeHeight/$Segments)*$j,$Color);
}
}
$Object->Shadow = $RestoreShadow;
}
/* Axis to axis lines */
$Color = array("R"=>$AxisR,"G"=>$AxisG,"B"=>$AxisB,"Alpha"=>$AxisAlpha);
for($j=1;$j<=$Segments;$j++)
{
$Radius = ($EdgeHeight/$Segments)*$j;
$Object->drawCircle($CenterX,$CenterY,$Radius,$Radius,$Color);
}
if ( $DrawAxisValues )
{
if ( $LabelsBackground )
$Options = array("DrawBox"=>TRUE, "Align"=>TEXT_ALIGN_MIDDLEMIDDLE,"BoxR"=>$LabelsBGR,"BoxG"=>$LabelsBGG,"BoxB"=>$LabelsBGB,"BoxAlpha"=>$LabelsBGAlpha);
else
$Options = array("Align"=>TEXT_ALIGN_MIDDLEMIDDLE);
if ( $AxisBoxRounded ) { $Options["BoxRounded"] = TRUE; }
$Options["FontName"] = $AxisFontName;
$Options["FontSize"] = $AxisFontSize;
$Angle = 360 / ($Points*2);
for($j=1;$j<=$Segments;$j++)
{
$EdgeX1 = cos(deg2rad($Angle+$AxisRotation)) * ($EdgeHeight/$Segments)*$j + $CenterX;
$EdgeY1 = sin(deg2rad($Angle+$AxisRotation)) * ($EdgeHeight/$Segments)*$j + $CenterY;
$Label = $j*$SegmentHeight;
$Object->drawText($EdgeX1,$EdgeY1,$Label,$Options);
}
}
/* Axis lines */
$ID = 0;
for($i=0;$i<=359;$i=$i+$AxisSteps)
{
$EdgeX = cos(deg2rad($i+$AxisRotation)) * ($EdgeHeight+$TicksLength) + $CenterX;
$EdgeY = sin(deg2rad($i+$AxisRotation)) * ($EdgeHeight+$TicksLength) + $CenterY;
$Object->drawLine($CenterX,$CenterY,$EdgeX,$EdgeY,$Color);
if ( $WriteLabels )
{
$LabelX = cos(deg2rad($i+$AxisRotation)) * ($EdgeHeight+$LabelPadding+$TicksLength) + $CenterX;
$LabelY = sin(deg2rad($i+$AxisRotation)) * ($EdgeHeight+$LabelPadding+$TicksLength) + $CenterY;
$Label = $i."°";
if ( $LabelPos == RADAR_LABELS_ROTATED )
$Object->drawText($LabelX,$LabelY,$Label,array("Angle"=>(360-$i),"Align"=>TEXT_ALIGN_BOTTOMMIDDLE));
else
{
if ( (floor($LabelX) == floor($CenterX)) && (floor($LabelY) < floor($CenterY)) ) { $Object->drawText($LabelX,$LabelY,$Label,array("Align"=>TEXT_ALIGN_BOTTOMMIDDLE)); }
if ( (floor($LabelX) > floor($CenterX)) && (floor($LabelY) < floor($CenterY)) ) { $Object->drawText($LabelX,$LabelY,$Label,array("Align"=>TEXT_ALIGN_BOTTOMLEFT)); }
if ( (floor($LabelX) > floor($CenterX)) && (floor($LabelY) == floor($CenterY)) ) { $Object->drawText($LabelX,$LabelY,$Label,array("Align"=>TEXT_ALIGN_MIDDLELEFT)); }
if ( (floor($LabelX) > floor($CenterX)) && (floor($LabelY) > floor($CenterY)) ) { $Object->drawText($LabelX,$LabelY,$Label,array("Align"=>TEXT_ALIGN_TOPLEFT)); }
if ( (floor($LabelX) < floor($CenterX)) && (floor($LabelY) < floor($CenterY)) ) { $Object->drawText($LabelX,$LabelY,$Label,array("Align"=>TEXT_ALIGN_BOTTOMRIGHT)); }
if ( (floor($LabelX) < floor($CenterX)) && (floor($LabelY) == floor($CenterY)) ) { $Object->drawText($LabelX,$LabelY,$Label,array("Align"=>TEXT_ALIGN_MIDDLERIGHT)); }
if ( (floor($LabelX) < floor($CenterX)) && (floor($LabelY) > floor($CenterY)) ) { $Object->drawText($LabelX,$LabelY,$Label,array("Align"=>TEXT_ALIGN_TOPRIGHT)); }
if ( (floor($LabelX) == floor($CenterX)) && (floor($LabelY) > floor($CenterY)) ) { $Object->drawText($LabelX,$LabelY,$Label,array("Align"=>TEXT_ALIGN_TOPMIDDLE)); }
}
}
$ID++;
}
/* Compute the plots position */
$ID = 0; $Plot = "";
foreach($Data["Series"] as $SerieName => $DataSet)
{
if ( $SerieName != $LabelSerie )
{
$Color = array("R"=>$Palette[$ID]["R"],"G"=>$Palette[$ID]["G"],"B"=>$Palette[$ID]["B"],"Alpha"=>$Palette[$ID]["Alpha"],"Surrounding"=>$PointSurrounding);
foreach($DataSet["Data"] as $Key => $Value)
{
$Angle = $Data["Series"][$LabelSerie]["Data"][$Key];
$Length = ($EdgeHeight/($Segments*$SegmentHeight))*$Value;
$X = cos(deg2rad($Angle+$AxisRotation)) * $Length + $CenterX;
$Y = sin(deg2rad($Angle+$AxisRotation)) * $Length + $CenterY;
if ( $RecordImageMap ) { $this->pChartObject->addToImageMap("CIRCLE",floor($X).",".floor($Y).",".floor($PointRadius),$this->pChartObject->toHTMLColor($Palette[$ID]["R"],$Palette[$ID]["G"],$Palette[$ID]["B"]),$DataSet["Description"],$Data["Series"][$LabelSerie]["Data"][$Key]."° = ".$Value); }
$Plot[$ID][] = array($X,$Y,$Value);
}
$ID++;
}
}
/* Draw all that stuff! */
foreach($Plot as $ID => $Points)
{
$Color = array("R"=>$Palette[$ID]["R"],"G"=>$Palette[$ID]["G"],"B"=>$Palette[$ID]["B"],"Alpha"=>$Palette[$ID]["Alpha"],"Surrounding"=>$PointSurrounding);
/* Draw the polygons */
if ( $DrawPoly )
{
if ($PolyAlpha != NULL)
$Color = array("R"=>$Palette[$ID]["R"],"G"=>$Palette[$ID]["G"],"B"=>$Palette[$ID]["B"],"Alpha"=>$PolyAlpha,"Surrounding"=>$PointSurrounding);
$PointsArray = "";
for($i=0; $i<count($Points);$i++)
{ $PointsArray[] = $Points[$i][0]; $PointsArray[] = $Points[$i][1]; }
$Object->drawPolygon($PointsArray,$Color);
}
$Color = array("R"=>$Palette[$ID]["R"],"G"=>$Palette[$ID]["G"],"B"=>$Palette[$ID]["B"],"Alpha"=>$Palette[$ID]["Alpha"],"Surrounding"=>$PointSurrounding);
/* Bubble and labels settings */
$TextSettings = array("Align"=>TEXT_ALIGN_MIDDLEMIDDLE,"FontName"=>$ValueFontName,"FontSize"=>$ValueFontSize,"R"=>$Palette[$ID]["R"],"G"=>$Palette[$ID]["G"],"B"=>$Palette[$ID]["B"]);
$InnerColor = array("R"=>$InnerBubbleR,"G"=>$InnerBubbleG,"B"=>$InnerBubbleB,"Alpha"=>$InnerBubbleAlpha);
if ( $OuterBubbleR != VOID )
$OuterColor = array("R"=>$OuterBubbleR,"G"=>$OuterBubbleG,"B"=>$OuterBubbleB,"Alpha"=>$OuterBubbleAlpha);
else
$OuterColor = array("R"=>$Palette[$ID]["R"]+20,"G"=>$Palette[$ID]["G"]+20,"B"=>$Palette[$ID]["B"]+20,"Alpha"=>$Palette[$ID]["Alpha"]);
/* Loop to the starting points if asked */
if ( $LineLoopStart && $DrawLines )
$Object->drawLine($Points[count($Points)-1][0],$Points[count($Points)-1][1],$Points[0][0],$Points[0][1],$Color);
/* Draw the lines & points */
for($i=0; $i<count($Points);$i++)
{
if ( $DrawLines && $i < count($Points)-1)
$Object->drawLine($Points[$i][0],$Points[$i][1],$Points[$i+1][0],$Points[$i+1][1],$Color);
if ( $DrawPoints )
$Object->drawFilledCircle($Points[$i][0],$Points[$i][1],$PointRadius,$Color);
if ( $WriteValuesInBubble && $WriteValues )
{
$TxtPos = $this->pChartObject->getTextBox($Points[$i][0],$Points[$i][1],$ValueFontName,$ValueFontSize,0,$Points[$i][2]);
$Radius = floor(($TxtPos[1]["X"] - $TxtPos[0]["X"] + $ValuePadding*2)/2);
$this->pChartObject->drawFilledCircle($Points[$i][0],$Points[$i][1],$Radius+$OuterBubbleRadius,$OuterColor);
$this->pChartObject->drawFilledCircle($Points[$i][0],$Points[$i][1],$Radius,$InnerColor);
}
if ( $WriteValues )
$this->pChartObject->drawText($Points[$i][0]-1,$Points[$i][1]-1,$Points[$i][2],$TextSettings);
}
}
}
}
?> | {
"pile_set_name": "Github"
} |
{
"viewport-fit-descriptor": [
{
"engines": [],
"filename": "css/at-rules/viewport.json",
"name": "viewport-fit",
"slug": "CSS/@viewport/viewport-fit",
"summary": "The viewport-fit CSS @viewport descriptor controls how a document's viewport fills the screen.",
"support": {
"chrome": {
"version_added": false
},
"chrome_android": {
"version_added": false
},
"edge": {
"version_added": false
},
"firefox": {
"version_added": false
},
"firefox_android": {
"version_added": false
},
"ie": {
"version_added": false
},
"opera": {
"version_added": false
},
"opera_android": {
"version_added": false
},
"safari": {
"version_added": false
},
"safari_ios": {
"version_added": false
},
"samsunginternet_android": {
"version_added": false
},
"webview_android": {
"version_added": false
},
"edge_blink": {
"version_added": false
}
},
"title": "viewport-fit"
}
],
"extending-viewport-rule": [
{
"engines": [],
"filename": "css/at-rules/viewport.json",
"name": "viewport",
"slug": "CSS/@viewport",
"summary": "The @viewport CSS at-rule lets you configure the viewport through which the document is viewed. It's primarily used for mobile devices, but is also used by desktop browsers that support features like \"snap to edge\" (such as Microsoft Edge).",
"support": {
"chrome": {
"version_removed": "84",
"version_added": "29",
"flags": [
{
"type": "runtime_flag",
"name": "--enable-experimental-webkit-features"
},
{
"type": "runtime_flag",
"name": "--enable-viewport"
}
],
"notes": "See Chromium <a href='https://crbug.com/235457'>bug 235457</a>."
},
"chrome_android": {
"version_removed": "84",
"version_added": "29",
"flags": [
{
"type": "runtime_flag",
"name": "--enable-experimental-webkit-features"
},
{
"type": "runtime_flag",
"name": "--enable-viewport"
}
],
"notes": "See Chromium <a href='https://crbug.com/235457'>bug 235457</a>."
},
"edge": {
"version_added": "12"
},
"firefox": {
"version_added": false,
"notes": "See Firefox <a href='https://bugzil.la/747754'>bug 747754</a>."
},
"firefox_android": {
"version_added": false,
"notes": "See Firefox <a href='https://bugzil.la/747754'>bug 747754</a>."
},
"ie": {
"prefix": "-ms-",
"version_added": "10"
},
"opera": [
{
"version_added": "16",
"flags": [
{
"type": "runtime_flag",
"name": "--enable-experimental-webkit-features"
},
{
"type": "runtime_flag",
"name": "--enable-viewport"
}
]
},
{
"prefix": "-o-",
"version_added": "11.1",
"version_removed": "15"
}
],
"opera_android": [
{
"version_added": "16",
"flags": [
{
"type": "runtime_flag",
"name": "--enable-experimental-webkit-features"
},
{
"type": "runtime_flag",
"name": "--enable-viewport"
}
]
},
{
"prefix": "-o-",
"version_added": "11.1",
"version_removed": "14"
}
],
"safari": {
"version_added": false,
"notes": "See WebKit <a href='https://webkit.org/b/95959'>bug 95959</a>."
},
"safari_ios": {
"version_added": false,
"notes": "See WebKit <a href='https://webkit.org/b/95959'>bug 95959</a>."
},
"samsunginternet_android": {
"version_added": "2.0"
},
"webview_android": {
"version_removed": "37",
"version_added": "4.4"
},
"edge_blink": {
"version_removed": "84",
"version_added": false,
"flags": [
{
"type": "runtime_flag",
"name": "--enable-experimental-webkit-features"
},
{
"type": "runtime_flag",
"name": "--enable-viewport"
}
],
"notes": "See Chromium <a href='https://crbug.com/235457'>bug 235457</a>."
}
},
"title": "@viewport"
}
]
}
| {
"pile_set_name": "Github"
} |
package org.ovirt.engine.core.bll.hostdeploy;
import org.ovirt.engine.core.bll.NonTransactiveCommandAttribute;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.action.LockProperties;
import org.ovirt.engine.core.common.action.hostdeploy.ApproveVdsParameters;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.errors.EngineMessage;
@NonTransactiveCommandAttribute
public class ApproveVdsCommand<T extends ApproveVdsParameters> extends InstallVdsInternalCommand<T> {
public ApproveVdsCommand(T parameters, CommandContext commandContext) {
super(parameters, commandContext);
}
@Override
protected LockProperties applyLockProperties(LockProperties lockProperties) {
return lockProperties;
}
@Override
protected boolean validate() {
boolean returnValue = true;
if (getVds() == null) {
addValidationMessage(EngineMessage.VDS_APPROVE_VDS_NOT_FOUND);
returnValue = false;
} else if (getVds().getStatus() != VDSStatus.PendingApproval
&& getVds().getStatus() != VDSStatus.InstallFailed
&& getVds().getStatus() != VDSStatus.InstallingOS) {
addValidationMessage(EngineMessage.VDS_APPROVE_VDS_IN_WRONG_STATUS);
returnValue = false;
}
return returnValue ? super.validate() : false;
}
@Override
public AuditLogType getAuditLogTypeValue() {
if (getSucceeded()) {
return AuditLogType.VDS_APPROVE;
} else {
return super.getAuditLogTypeValue();
}
}
@Override
protected void executeCommand() {
if (Config.<Boolean> getValue(ConfigValues.AutoInstallCertificateOnApprove)) {
super.executeCommand();
} else {
setSucceeded(true);
}
if (getSucceeded()) {
if (getParameters().getActivateHost()) {
setVdsStatus(VDSStatus.Unassigned);
} else {
setVdsStatus(VDSStatus.Maintenance);
}
} else if (getParameters().isApprovedByRegister()) {
// In case of Approval of oVirt host process, the status of the host is re-initialized to PendingApproval
setVdsStatus(VDSStatus.PendingApproval);
}
}
}
| {
"pile_set_name": "Github"
} |
package abi
import (
"context"
"fmt"
"io"
"io/ioutil"
"net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"github.com/containers/common/pkg/config"
"github.com/containers/image/v5/docker"
"github.com/containers/image/v5/docker/reference"
"github.com/containers/image/v5/manifest"
"github.com/containers/image/v5/signature"
"github.com/containers/image/v5/transports"
"github.com/containers/image/v5/transports/alltransports"
"github.com/containers/image/v5/types"
"github.com/containers/podman/v2/libpod/define"
"github.com/containers/podman/v2/libpod/image"
libpodImage "github.com/containers/podman/v2/libpod/image"
"github.com/containers/podman/v2/pkg/domain/entities"
domainUtils "github.com/containers/podman/v2/pkg/domain/utils"
"github.com/containers/podman/v2/pkg/rootless"
"github.com/containers/podman/v2/pkg/trust"
"github.com/containers/podman/v2/pkg/util"
"github.com/containers/storage"
imgspecv1 "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// SignatureStoreDir defines default directory to store signatures
const SignatureStoreDir = "/var/lib/containers/sigstore"
func (ir *ImageEngine) Exists(_ context.Context, nameOrID string) (*entities.BoolReport, error) {
_, err := ir.Libpod.ImageRuntime().NewFromLocal(nameOrID)
if err != nil && errors.Cause(err) != define.ErrNoSuchImage {
return nil, err
}
return &entities.BoolReport{Value: err == nil}, nil
}
func (ir *ImageEngine) Prune(ctx context.Context, opts entities.ImagePruneOptions) (*entities.ImagePruneReport, error) {
return ir.pruneImagesHelper(ctx, opts.All, opts.Filter)
}
func (ir *ImageEngine) pruneImagesHelper(ctx context.Context, all bool, filters []string) (*entities.ImagePruneReport, error) {
results, err := ir.Libpod.ImageRuntime().PruneImages(ctx, all, filters)
if err != nil {
return nil, err
}
report := entities.ImagePruneReport{
Report: entities.Report{
Id: results,
Err: nil,
},
}
return &report, nil
}
func (ir *ImageEngine) History(ctx context.Context, nameOrID string, opts entities.ImageHistoryOptions) (*entities.ImageHistoryReport, error) {
image, err := ir.Libpod.ImageRuntime().NewFromLocal(nameOrID)
if err != nil {
return nil, err
}
results, err := image.History(ctx)
if err != nil {
return nil, err
}
history := entities.ImageHistoryReport{
Layers: make([]entities.ImageHistoryLayer, len(results)),
}
for i, layer := range results {
history.Layers[i] = ToDomainHistoryLayer(layer)
}
return &history, nil
}
func (ir *ImageEngine) Mount(ctx context.Context, nameOrIDs []string, opts entities.ImageMountOptions) ([]*entities.ImageMountReport, error) {
var (
images []*image.Image
err error
)
if os.Geteuid() != 0 {
if driver := ir.Libpod.StorageConfig().GraphDriverName; driver != "vfs" {
// Do not allow to mount a graphdriver that is not vfs if we are creating the userns as part
// of the mount command.
return nil, errors.Errorf("cannot mount using driver %s in rootless mode", driver)
}
became, ret, err := rootless.BecomeRootInUserNS("")
if err != nil {
return nil, err
}
if became {
os.Exit(ret)
}
}
if opts.All {
allImages, err := ir.Libpod.ImageRuntime().GetImages()
if err != nil {
return nil, err
}
for _, img := range allImages {
if !img.IsReadOnly() {
images = append(images, img)
}
}
} else {
for _, i := range nameOrIDs {
img, err := ir.Libpod.ImageRuntime().NewFromLocal(i)
if err != nil {
return nil, err
}
images = append(images, img)
}
}
reports := make([]*entities.ImageMountReport, 0, len(images))
for _, img := range images {
report := entities.ImageMountReport{Id: img.ID()}
if img.IsReadOnly() {
report.Err = errors.Errorf("mounting readonly %s image not supported", img.ID())
} else {
report.Path, report.Err = img.Mount([]string{}, "")
}
reports = append(reports, &report)
}
if len(reports) > 0 {
return reports, nil
}
images, err = ir.Libpod.ImageRuntime().GetImages()
if err != nil {
return nil, err
}
for _, i := range images {
mounted, path, err := i.Mounted()
if err != nil {
if errors.Cause(err) == storage.ErrLayerUnknown {
continue
}
return nil, err
}
if mounted {
tags, err := i.RepoTags()
if err != nil {
return nil, err
}
reports = append(reports, &entities.ImageMountReport{
Id: i.ID(),
Name: string(i.Digest()),
Repositories: tags,
Path: path,
})
}
}
return reports, nil
}
func (ir *ImageEngine) Unmount(ctx context.Context, nameOrIDs []string, options entities.ImageUnmountOptions) ([]*entities.ImageUnmountReport, error) {
var images []*image.Image
if options.All {
allImages, err := ir.Libpod.ImageRuntime().GetImages()
if err != nil {
return nil, err
}
for _, img := range allImages {
if !img.IsReadOnly() {
images = append(images, img)
}
}
} else {
for _, i := range nameOrIDs {
img, err := ir.Libpod.ImageRuntime().NewFromLocal(i)
if err != nil {
return nil, err
}
images = append(images, img)
}
}
reports := []*entities.ImageUnmountReport{}
for _, img := range images {
report := entities.ImageUnmountReport{Id: img.ID()}
mounted, _, err := img.Mounted()
if err != nil {
// Errors will be caught in Unmount call below
// Default assumption to mounted
mounted = true
}
if !mounted {
continue
}
if err := img.Unmount(options.Force); err != nil {
if options.All && errors.Cause(err) == storage.ErrLayerNotMounted {
logrus.Debugf("Error umounting image %s, storage.ErrLayerNotMounted", img.ID())
continue
}
report.Err = errors.Wrapf(err, "error unmounting image %s", img.ID())
}
reports = append(reports, &report)
}
return reports, nil
}
func ToDomainHistoryLayer(layer *libpodImage.History) entities.ImageHistoryLayer {
l := entities.ImageHistoryLayer{}
l.ID = layer.ID
l.Created = *layer.Created
l.CreatedBy = layer.CreatedBy
copy(l.Tags, layer.Tags)
l.Size = layer.Size
l.Comment = layer.Comment
return l
}
func pull(ctx context.Context, runtime *image.Runtime, rawImage string, options entities.ImagePullOptions, label *string) (*entities.ImagePullReport, error) {
var writer io.Writer
if !options.Quiet {
writer = os.Stderr
}
dockerPrefix := fmt.Sprintf("%s://", docker.Transport.Name())
imageRef, err := alltransports.ParseImageName(rawImage)
if err != nil {
imageRef, err = alltransports.ParseImageName(fmt.Sprintf("%s%s", dockerPrefix, rawImage))
if err != nil {
return nil, errors.Wrapf(err, "invalid image reference %q", rawImage)
}
}
var registryCreds *types.DockerAuthConfig
if len(options.Username) > 0 && len(options.Password) > 0 {
registryCreds = &types.DockerAuthConfig{
Username: options.Username,
Password: options.Password,
}
}
dockerRegistryOptions := image.DockerRegistryOptions{
DockerRegistryCreds: registryCreds,
DockerCertPath: options.CertDir,
OSChoice: options.OverrideOS,
ArchitectureChoice: options.OverrideArch,
VariantChoice: options.OverrideVariant,
DockerInsecureSkipTLSVerify: options.SkipTLSVerify,
}
if !options.AllTags {
newImage, err := runtime.New(ctx, rawImage, options.SignaturePolicy, options.Authfile, writer, &dockerRegistryOptions, image.SigningOptions{}, label, options.PullPolicy)
if err != nil {
return nil, err
}
return &entities.ImagePullReport{Images: []string{newImage.ID()}}, nil
}
// --all-tags requires the docker transport
if imageRef.Transport().Name() != docker.Transport.Name() {
return nil, errors.New("--all-tags requires docker transport")
}
// Trim the docker-transport prefix.
rawImage = strings.TrimPrefix(rawImage, docker.Transport.Name())
// all-tags doesn't work with a tagged reference, so let's check early
namedRef, err := reference.Parse(rawImage)
if err != nil {
return nil, errors.Wrapf(err, "error parsing %q", rawImage)
}
if _, isTagged := namedRef.(reference.Tagged); isTagged {
return nil, errors.New("--all-tags requires a reference without a tag")
}
systemContext := image.GetSystemContext("", options.Authfile, false)
tags, err := docker.GetRepositoryTags(ctx, systemContext, imageRef)
if err != nil {
return nil, errors.Wrapf(err, "error getting repository tags")
}
foundIDs := []string{}
for _, tag := range tags {
name := rawImage + ":" + tag
newImage, err := runtime.New(ctx, name, options.SignaturePolicy, options.Authfile, writer, &dockerRegistryOptions, image.SigningOptions{}, nil, util.PullImageAlways)
if err != nil {
logrus.Errorf("error pulling image %q", name)
continue
}
foundIDs = append(foundIDs, newImage.ID())
}
if len(tags) != len(foundIDs) {
return nil, err
}
return &entities.ImagePullReport{Images: foundIDs}, nil
}
func (ir *ImageEngine) Pull(ctx context.Context, rawImage string, options entities.ImagePullOptions) (*entities.ImagePullReport, error) {
return pull(ctx, ir.Libpod.ImageRuntime(), rawImage, options, nil)
}
func (ir *ImageEngine) Inspect(ctx context.Context, namesOrIDs []string, opts entities.InspectOptions) ([]*entities.ImageInspectReport, []error, error) {
reports := []*entities.ImageInspectReport{}
errs := []error{}
for _, i := range namesOrIDs {
img, err := ir.Libpod.ImageRuntime().NewFromLocal(i)
if err != nil {
// This is probably a no such image, treat as nonfatal.
errs = append(errs, err)
continue
}
result, err := img.Inspect(ctx)
if err != nil {
// This is more likely to be fatal.
return nil, nil, err
}
report := entities.ImageInspectReport{}
if err := domainUtils.DeepCopy(&report, result); err != nil {
return nil, nil, err
}
reports = append(reports, &report)
}
return reports, errs, nil
}
func (ir *ImageEngine) Push(ctx context.Context, source string, destination string, options entities.ImagePushOptions) error {
var writer io.Writer
if !options.Quiet {
writer = os.Stderr
}
var manifestType string
switch options.Format {
case "":
// Default
case "oci":
manifestType = imgspecv1.MediaTypeImageManifest
case "v2s1":
manifestType = manifest.DockerV2Schema1SignedMediaType
case "v2s2", "docker":
manifestType = manifest.DockerV2Schema2MediaType
default:
return errors.Errorf("unknown format %q. Choose on of the supported formats: 'oci', 'v2s1', or 'v2s2'", options.Format)
}
var registryCreds *types.DockerAuthConfig
if len(options.Username) > 0 && len(options.Password) > 0 {
registryCreds = &types.DockerAuthConfig{
Username: options.Username,
Password: options.Password,
}
}
dockerRegistryOptions := image.DockerRegistryOptions{
DockerRegistryCreds: registryCreds,
DockerCertPath: options.CertDir,
DockerInsecureSkipTLSVerify: options.SkipTLSVerify,
}
signOptions := image.SigningOptions{
RemoveSignatures: options.RemoveSignatures,
SignBy: options.SignBy,
}
newImage, err := ir.Libpod.ImageRuntime().NewFromLocal(source)
if err != nil {
return err
}
return newImage.PushImageToHeuristicDestination(
ctx,
destination,
manifestType,
options.Authfile,
options.DigestFile,
options.SignaturePolicy,
writer,
options.Compress,
signOptions,
&dockerRegistryOptions,
nil)
}
// func (r *imageRuntime) Delete(ctx context.Context, nameOrID string, opts entities.ImageDeleteOptions) (*entities.ImageDeleteReport, error) {
// image, err := r.libpod.ImageEngine().NewFromLocal(nameOrID)
// if err != nil {
// return nil, err
// }
//
// results, err := r.libpod.RemoveImage(ctx, image, opts.Force)
// if err != nil {
// return nil, err
// }
//
// report := entities.ImageDeleteReport{}
// if err := domainUtils.DeepCopy(&report, results); err != nil {
// return nil, err
// }
// return &report, nil
// }
//
// func (r *imageRuntime) Prune(ctx context.Context, opts entities.ImagePruneOptions) (*entities.ImagePruneReport, error) {
// // TODO: map FilterOptions
// id, err := r.libpod.ImageEngine().PruneImages(ctx, opts.All, []string{})
// if err != nil {
// return nil, err
// }
//
// // TODO: Determine Size
// report := entities.ImagePruneReport{}
// copy(report.Report.ID, id)
// return &report, nil
// }
func (ir *ImageEngine) Tag(ctx context.Context, nameOrID string, tags []string, options entities.ImageTagOptions) error {
newImage, err := ir.Libpod.ImageRuntime().NewFromLocal(nameOrID)
if err != nil {
return err
}
for _, tag := range tags {
if err := newImage.TagImage(tag); err != nil {
return err
}
}
return nil
}
func (ir *ImageEngine) Untag(ctx context.Context, nameOrID string, tags []string, options entities.ImageUntagOptions) error {
newImage, err := ir.Libpod.ImageRuntime().NewFromLocal(nameOrID)
if err != nil {
return err
}
// If only one arg is provided, all names are to be untagged
if len(tags) == 0 {
tags = newImage.Names()
}
for _, tag := range tags {
if err := newImage.UntagImage(tag); err != nil {
return err
}
}
return nil
}
func (ir *ImageEngine) Load(ctx context.Context, opts entities.ImageLoadOptions) (*entities.ImageLoadReport, error) {
var (
writer io.Writer
)
if !opts.Quiet {
writer = os.Stderr
}
name, err := ir.Libpod.LoadImage(ctx, opts.Name, opts.Input, writer, opts.SignaturePolicy)
if err != nil {
return nil, err
}
names := strings.Split(name, ",")
if len(names) <= 1 {
newImage, err := ir.Libpod.ImageRuntime().NewFromLocal(name)
if err != nil {
return nil, errors.Wrap(err, "image loaded but no additional tags were created")
}
if len(opts.Name) > 0 {
if err := newImage.TagImage(fmt.Sprintf("%s:%s", opts.Name, opts.Tag)); err != nil {
return nil, errors.Wrapf(err, "error adding %q to image %q", opts.Name, newImage.InputName)
}
}
}
return &entities.ImageLoadReport{Names: names}, nil
}
func (ir *ImageEngine) Import(ctx context.Context, opts entities.ImageImportOptions) (*entities.ImageImportReport, error) {
id, err := ir.Libpod.Import(ctx, opts.Source, opts.Reference, opts.SignaturePolicy, opts.Changes, opts.Message, opts.Quiet)
if err != nil {
return nil, err
}
return &entities.ImageImportReport{Id: id}, nil
}
func (ir *ImageEngine) Save(ctx context.Context, nameOrID string, tags []string, options entities.ImageSaveOptions) error {
if options.MultiImageArchive {
nameOrIDs := append([]string{nameOrID}, tags...)
return ir.Libpod.ImageRuntime().SaveImages(ctx, nameOrIDs, options.Format, options.Output, options.Quiet)
}
newImage, err := ir.Libpod.ImageRuntime().NewFromLocal(nameOrID)
if err != nil {
return err
}
return newImage.Save(ctx, nameOrID, options.Format, options.Output, tags, options.Quiet, options.Compress)
}
func (ir *ImageEngine) Diff(_ context.Context, nameOrID string, _ entities.DiffOptions) (*entities.DiffReport, error) {
changes, err := ir.Libpod.GetDiff("", nameOrID)
if err != nil {
return nil, err
}
return &entities.DiffReport{Changes: changes}, nil
}
func (ir *ImageEngine) Search(ctx context.Context, term string, opts entities.ImageSearchOptions) ([]entities.ImageSearchReport, error) {
filter, err := image.ParseSearchFilter(opts.Filters)
if err != nil {
return nil, err
}
searchOpts := image.SearchOptions{
Authfile: opts.Authfile,
Filter: *filter,
Limit: opts.Limit,
NoTrunc: opts.NoTrunc,
InsecureSkipTLSVerify: opts.SkipTLSVerify,
}
searchResults, err := image.SearchImages(term, searchOpts)
if err != nil {
return nil, err
}
// Convert from image.SearchResults to entities.ImageSearchReport. We don't
// want to leak any low-level packages into the remote client, which
// requires converting.
reports := make([]entities.ImageSearchReport, len(searchResults))
for i := range searchResults {
reports[i].Index = searchResults[i].Index
reports[i].Name = searchResults[i].Name
reports[i].Description = searchResults[i].Description
reports[i].Stars = searchResults[i].Stars
reports[i].Official = searchResults[i].Official
reports[i].Automated = searchResults[i].Automated
}
return reports, nil
}
// GetConfig returns a copy of the configuration used by the runtime
func (ir *ImageEngine) Config(_ context.Context) (*config.Config, error) {
return ir.Libpod.GetConfig()
}
func (ir *ImageEngine) Build(ctx context.Context, containerFiles []string, opts entities.BuildOptions) (*entities.BuildReport, error) {
id, _, err := ir.Libpod.Build(ctx, opts.BuildOptions, containerFiles...)
if err != nil {
return nil, err
}
return &entities.BuildReport{ID: id}, nil
}
func (ir *ImageEngine) Tree(ctx context.Context, nameOrID string, opts entities.ImageTreeOptions) (*entities.ImageTreeReport, error) {
img, err := ir.Libpod.ImageRuntime().NewFromLocal(nameOrID)
if err != nil {
return nil, err
}
results, err := img.GenerateTree(opts.WhatRequires)
if err != nil {
return nil, err
}
return &entities.ImageTreeReport{Tree: results}, nil
}
// removeErrorsToExitCode returns an exit code for the specified slice of
// image-removal errors. The error codes are set according to the documented
// behaviour in the Podman man pages.
func removeErrorsToExitCode(rmErrors []error) int {
var (
// noSuchImageErrors indicates that at least one image was not found.
noSuchImageErrors bool
// inUseErrors indicates that at least one image is being used by a
// container.
inUseErrors bool
// otherErrors indicates that at least one error other than the two
// above occurred.
otherErrors bool
)
if len(rmErrors) == 0 {
return 0
}
for _, e := range rmErrors {
switch errors.Cause(e) {
case define.ErrNoSuchImage:
noSuchImageErrors = true
case define.ErrImageInUse, storage.ErrImageUsedByContainer:
inUseErrors = true
default:
otherErrors = true
}
}
switch {
case inUseErrors:
// One of the specified images has child images or is
// being used by a container.
return 2
case noSuchImageErrors && !(otherErrors || inUseErrors):
// One of the specified images did not exist, and no other
// failures.
return 1
default:
return 125
}
}
// Remove removes one or more images from local storage.
func (ir *ImageEngine) Remove(ctx context.Context, images []string, opts entities.ImageRemoveOptions) (report *entities.ImageRemoveReport, rmErrors []error) {
report = &entities.ImageRemoveReport{}
// Set the exit code at very end.
defer func() {
report.ExitCode = removeErrorsToExitCode(rmErrors)
}()
// deleteImage is an anonymous function to conveniently delete an image
// without having to pass all local data around.
deleteImage := func(img *image.Image) error {
results, err := ir.Libpod.RemoveImage(ctx, img, opts.Force)
if err != nil {
return err
}
report.Deleted = append(report.Deleted, results.Deleted)
report.Untagged = append(report.Untagged, results.Untagged...)
return nil
}
// Delete all images from the local storage.
if opts.All {
previousImages := 0
// Remove all images one-by-one.
for {
storageImages, err := ir.Libpod.ImageRuntime().GetRWImages()
if err != nil {
rmErrors = append(rmErrors, err)
return
}
// No images (left) to remove, so we're done.
if len(storageImages) == 0 {
return
}
// Prevent infinity loops by making a delete-progress check.
if previousImages == len(storageImages) {
rmErrors = append(rmErrors, errors.New("unable to delete all images, check errors and re-run image removal if needed"))
break
}
previousImages = len(storageImages)
// Delete all "leaves" (i.e., images without child images).
for _, img := range storageImages {
isParent, err := img.IsParent(ctx)
if err != nil {
rmErrors = append(rmErrors, err)
continue
}
// Skip parent images.
if isParent {
continue
}
if err := deleteImage(img); err != nil {
rmErrors = append(rmErrors, err)
}
}
}
return
}
// Delete only the specified images.
for _, id := range images {
img, err := ir.Libpod.ImageRuntime().NewFromLocal(id)
if err != nil {
rmErrors = append(rmErrors, err)
continue
}
err = deleteImage(img)
if err != nil {
rmErrors = append(rmErrors, err)
}
}
return //nolint
}
// Shutdown Libpod engine
func (ir *ImageEngine) Shutdown(_ context.Context) {
shutdownSync.Do(func() {
_ = ir.Libpod.Shutdown(false)
})
}
func (ir *ImageEngine) Sign(ctx context.Context, names []string, options entities.SignOptions) (*entities.SignReport, error) {
mech, err := signature.NewGPGSigningMechanism()
if err != nil {
return nil, errors.Wrap(err, "error initializing GPG")
}
defer mech.Close()
if err := mech.SupportsSigning(); err != nil {
return nil, errors.Wrap(err, "signing is not supported")
}
sc := ir.Libpod.SystemContext()
sc.DockerCertPath = options.CertDir
systemRegistriesDirPath := trust.RegistriesDirPath(sc)
registryConfigs, err := trust.LoadAndMergeConfig(systemRegistriesDirPath)
if err != nil {
return nil, errors.Wrapf(err, "error reading registry configuration")
}
for _, signimage := range names {
srcRef, err := alltransports.ParseImageName(signimage)
if err != nil {
return nil, errors.Wrapf(err, "error parsing image name")
}
rawSource, err := srcRef.NewImageSource(ctx, sc)
if err != nil {
return nil, errors.Wrapf(err, "error getting image source")
}
err = rawSource.Close()
if err != nil {
logrus.Errorf("unable to close new image source %q", err)
}
getManifest, _, err := rawSource.GetManifest(ctx, nil)
if err != nil {
return nil, errors.Wrapf(err, "error getting getManifest")
}
dockerReference := rawSource.Reference().DockerReference()
if dockerReference == nil {
return nil, errors.Errorf("cannot determine canonical Docker reference for destination %s", transports.ImageName(rawSource.Reference()))
}
var sigStoreDir string
if options.Directory != "" {
sigStoreDir = options.Directory
}
if sigStoreDir == "" {
if rootless.IsRootless() {
sigStoreDir = filepath.Join(filepath.Dir(ir.Libpod.StorageConfig().GraphRoot), "sigstore")
} else {
var sigStoreURI string
registryInfo := trust.HaveMatchRegistry(rawSource.Reference().DockerReference().String(), registryConfigs)
if registryInfo != nil {
if sigStoreURI = registryInfo.SigStoreStaging; sigStoreURI == "" {
sigStoreURI = registryInfo.SigStore
}
}
if sigStoreURI == "" {
return nil, errors.Errorf("no signature storage configuration found for %s", rawSource.Reference().DockerReference().String())
}
sigStoreDir, err = localPathFromURI(sigStoreURI)
if err != nil {
return nil, errors.Wrapf(err, "invalid signature storage %s", sigStoreURI)
}
}
}
manifestDigest, err := manifest.Digest(getManifest)
if err != nil {
return nil, err
}
repo := reference.Path(dockerReference)
if path.Clean(repo) != repo { // Coverage: This should not be reachable because /./ and /../ components are not valid in docker references
return nil, errors.Errorf("Unexpected path elements in Docker reference %s for signature storage", dockerReference.String())
}
// create signature
newSig, err := signature.SignDockerManifest(getManifest, dockerReference.String(), mech, options.SignBy)
if err != nil {
return nil, errors.Wrapf(err, "error creating new signature")
}
// create the signstore file
signatureDir := fmt.Sprintf("%s@%s=%s", filepath.Join(sigStoreDir, repo), manifestDigest.Algorithm(), manifestDigest.Hex())
if err := os.MkdirAll(signatureDir, 0751); err != nil {
// The directory is allowed to exist
if !os.IsExist(err) {
logrus.Errorf("error creating directory %s: %s", signatureDir, err)
continue
}
}
sigFilename, err := getSigFilename(signatureDir)
if err != nil {
logrus.Errorf("error creating sigstore file: %v", err)
continue
}
err = ioutil.WriteFile(filepath.Join(signatureDir, sigFilename), newSig, 0644)
if err != nil {
logrus.Errorf("error storing signature for %s", rawSource.Reference().DockerReference().String())
continue
}
}
return nil, nil
}
func getSigFilename(sigStoreDirPath string) (string, error) {
sigFileSuffix := 1
sigFiles, err := ioutil.ReadDir(sigStoreDirPath)
if err != nil {
return "", err
}
sigFilenames := make(map[string]bool)
for _, file := range sigFiles {
sigFilenames[file.Name()] = true
}
for {
sigFilename := "signature-" + strconv.Itoa(sigFileSuffix)
if _, exists := sigFilenames[sigFilename]; !exists {
return sigFilename, nil
}
sigFileSuffix++
}
}
func localPathFromURI(sigStoreDir string) (string, error) {
url, err := url.Parse(sigStoreDir)
if err != nil {
return sigStoreDir, errors.Wrapf(err, "invalid directory %s", sigStoreDir)
}
if url.Scheme != "file" {
return sigStoreDir, errors.Errorf("writing to %s is not supported. Use a supported scheme", sigStoreDir)
}
sigStoreDir = url.Path
return sigStoreDir, nil
}
| {
"pile_set_name": "Github"
} |
#-------------------------------------------------
#
# Project created by QtCreator 2014-07-09T10:41:26
#
#-------------------------------------------------
QT += core gui network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = MEGAlogger
TEMPLATE = app
SOURCES += main.cpp \
MegaDebugServer.cpp
HEADERS += \
MegaDebugServer.h
FORMS += \
MegaDebugServer.ui
win32 {
RC_FILE = icon.rc
}
| {
"pile_set_name": "Github"
} |
import React, {Component, Fragment} from 'react';
import {withAITracking} from '@microsoft/applicationinsights-react-js';
import {ai} from '../../services/telemetryService';
import {withRouter} from 'react-router-dom';
import { constants } from '../../common/constants';
/**
* This Component provides telemetry with Azure App Insights
*
* NOTE: the package '@microsoft/applicationinsights-react-js' has a HOC withAITracking that requires this to be a Class Component rather than a Functional Component
*/
class TelemetryProvider extends Component {
state = {
initialized: false
};
componentDidMount() {
const {history} = this.props;
const { initialized } = this.state;
const AppInsightsInstrumentationKey = constants.insightsKey; // <-Paste your AppInsightsInstrumentationKey here
if (!Boolean(initialized) && Boolean(AppInsightsInstrumentationKey) && Boolean(history)) {
ai.initialize(AppInsightsInstrumentationKey, history);
this.setState({initialized: true});
}
this.props.after();
}
render() {
const {children} = this.props;
return (
<Fragment >
{children}
</Fragment>
);
}
}
export default withRouter(withAITracking(ai.reactPlugin, TelemetryProvider));
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* 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.
*/
package android.camera.mediaeffects.tests.functional;
import android.media.filterfw.samples.CameraEffectsRecordingSample;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;
import android.view.KeyEvent;
import android.util.Log;
import android.content.Intent;
import android.os.Environment;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import java.io.File;
public class EffectsVideoCapture extends ActivityInstrumentationTestCase2
<CameraEffectsRecordingSample> {
private static final String TAG = "EffectsVideoCaptureTest";
private static final long WAIT_FOR_PREVIEW = 4 * 1000; // 4 seconds
public EffectsVideoCapture() {
super(CameraEffectsRecordingSample.class);
}
private void captureVideos(String reportTag, Instrumentation inst) throws Exception{
int total_num_of_videos = 1;
int video_duration = 4 * 1000; // 4 seconds
Log.v(TAG, reportTag);
for (int i = 0; i < total_num_of_videos; i++) {
Thread.sleep(WAIT_FOR_PREVIEW);
// record a video
inst.sendCharacterSync(KeyEvent.KEYCODE_CAMERA);
Thread.sleep(video_duration);
inst.sendCharacterSync(KeyEvent.KEYCODE_CAMERA);
}
}
@LargeTest
public void testBackEffectsVideoCapture() throws Exception {
Instrumentation inst = getInstrumentation();
Intent intent = new Intent();
intent.setClass(getInstrumentation().getTargetContext(),
CameraEffectsRecordingSample.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("OUTPUT_FILENAME", Environment.getExternalStorageDirectory().toString()
+ "/CameraEffectsRecordingTest.mp4");
Activity act = inst.startActivitySync(intent);
captureVideos("Back Camera Video Capture\n", inst);
act.finish();
// Verification
File file = new File(Environment.getExternalStorageDirectory(),
"CameraEffectsRecordingTest.mp4");
Uri uri = Uri.fromFile(file);
verify(getActivity(), uri);
}
// Verify result code, result data, and the duration.
private void verify(CameraEffectsRecordingSample activity, Uri uri) throws Exception {
assertNotNull(uri);
// Verify the video file
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(activity, uri);
String duration = retriever.extractMetadata(
MediaMetadataRetriever.METADATA_KEY_DURATION);
assertNotNull(duration);
int durationValue = Integer.parseInt(duration);
Log.v(TAG, "Video duration is " + durationValue);
assertTrue(durationValue > 0);
}
}
| {
"pile_set_name": "Github"
} |
#coding:utf-8
from __future__ import unicode_literals
import os
import shutil
from six.moves import http_client, urllib
from cactus.site import Site
from cactus.plugin.manager import PluginManager
from cactus.utils.helpers import CaseInsensitiveDict
from cactus.utils.parallel import PARALLEL_DISABLED
from cactus.tests import BaseBootstrappedTestCase
class DummyPluginManager(PluginManager):
"""
Doesn't do anything
"""
def call(self, method, *args, **kwargs):
"""
Trap the call
"""
pass
class IntegrationTestCase(BaseBootstrappedTestCase):
def setUp(self):
super(IntegrationTestCase, self).setUp()
self.site = Site(self.path,
PluginManagerClass=DummyPluginManager, DeploymentEngineClass=self.get_deployment_engine_class())
self.site._parallel = PARALLEL_DISABLED
self.site.config.set('site-url', 'http://example.com/')
# Clean up the site paths
for path in (self.site.page_path, self.site.static_path):
shutil.rmtree(path)
os.mkdir(path)
def get_deployment_engine_class(self):
"""
Should return a deployment engine in tests.
"""
pass
class BaseTestHTTPConnection(object):
last_request = None
def __init__(self, host, *args, **kwargs):
self.host = host
self.requests = []
def connect(self):
pass
def close(self):
pass
def request(self, method, url, body=b'', headers=None):
"""
Send a full request at once
"""
if headers is None:
headers = {}
self.last_request = TestHTTPRequest(self, method, url, body, headers)
def putrequest(self, method, url, *args, **kwargs):
"""
Create a new request, but add more things to it later
"""
self.current_request = TestHTTPRequest(self, method, url, b'', {})
self.current_request.state = "headers"
def putheader(self, header, value):
"""
Add an header to a request that's in progress
"""
self.current_request.headers[header] = value
def endheaders(self, data=None):
"""
End the headers of a request that's in progress
"""
self.current_request.state = "body"
self.last_request = self.current_request
if data is not None:
self.send(data)
def send(self, data):
"""
Add data to a request that's in progress
"""
self.current_request.body += data
def getresponse(self):
request = self.last_request
self.requests.append(request)
return self.handle_request(request)
def handle_request(self, request):
"""
:param request: The request to handle
"""
raise NotImplementedError("handle_request should be implemented by subclasses")
def set_debuglevel(self, level):
pass
class DebugHTTPSConnectionFactory(object):
def __init__(self, conn_cls):
self.conn_cls = conn_cls
self.connections = []
@property
def requests(self):
"""
:returns: A dictionary of the calls made through this connection factory (method -> list of calls)
"""
out = []
for connection in self.connections:
out.extend(connection.requests)
return out
def __call__(self, *args, **kwargs):
"""
Create a new connection from our connection class
"""
connection = self.conn_cls(*args, **kwargs)
self.connections.append(connection)
return connection
class TestHTTPRequest(object):
state = None
def __init__(self, connection, method, url, body, headers):
self.connection = connection
self.method = method
self.url = url
self.body = body
self.headers = CaseInsensitiveDict(headers)
u = urllib.parse.urlparse(url)
self.path = u.path
self.params = urllib.parse.parse_qs(u.query, keep_blank_values=True)
class TestHTTPResponse(object):
def __init__(self, status, reason=None, headers=None, body=''):
if reason is None:
reason = http_client.responses[status]
if headers is None:
headers = {}
self.status = status
self.reason = reason
self.headers = CaseInsensitiveDict(headers)
self.body = body
def getheader(self, header, default=None):
return self.headers.get(header, default)
def getheaders(self):
return self.headers
def read(self):
return self.body
| {
"pile_set_name": "Github"
} |
// Copyright (C) 2014 Yasuhiro Matsumoto <[email protected]>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package sqlite3
import "C"
type ErrNo int
const ErrNoMask C.int = 0xff
type ErrNoExtended int
type Error struct {
Code ErrNo /* The error code returned by SQLite */
ExtendedCode ErrNoExtended /* The extended error code returned by SQLite */
err string /* The error string returned by sqlite3_errmsg(),
this usually contains more specific details. */
}
// result codes from http://www.sqlite.org/c3ref/c_abort.html
var (
ErrError = ErrNo(1) /* SQL error or missing database */
ErrInternal = ErrNo(2) /* Internal logic error in SQLite */
ErrPerm = ErrNo(3) /* Access permission denied */
ErrAbort = ErrNo(4) /* Callback routine requested an abort */
ErrBusy = ErrNo(5) /* The database file is locked */
ErrLocked = ErrNo(6) /* A table in the database is locked */
ErrNomem = ErrNo(7) /* A malloc() failed */
ErrReadonly = ErrNo(8) /* Attempt to write a readonly database */
ErrInterrupt = ErrNo(9) /* Operation terminated by sqlite3_interrupt() */
ErrIoErr = ErrNo(10) /* Some kind of disk I/O error occurred */
ErrCorrupt = ErrNo(11) /* The database disk image is malformed */
ErrNotFound = ErrNo(12) /* Unknown opcode in sqlite3_file_control() */
ErrFull = ErrNo(13) /* Insertion failed because database is full */
ErrCantOpen = ErrNo(14) /* Unable to open the database file */
ErrProtocol = ErrNo(15) /* Database lock protocol error */
ErrEmpty = ErrNo(16) /* Database is empty */
ErrSchema = ErrNo(17) /* The database schema changed */
ErrTooBig = ErrNo(18) /* String or BLOB exceeds size limit */
ErrConstraint = ErrNo(19) /* Abort due to constraint violation */
ErrMismatch = ErrNo(20) /* Data type mismatch */
ErrMisuse = ErrNo(21) /* Library used incorrectly */
ErrNoLFS = ErrNo(22) /* Uses OS features not supported on host */
ErrAuth = ErrNo(23) /* Authorization denied */
ErrFormat = ErrNo(24) /* Auxiliary database format error */
ErrRange = ErrNo(25) /* 2nd parameter to sqlite3_bind out of range */
ErrNotADB = ErrNo(26) /* File opened that is not a database file */
ErrNotice = ErrNo(27) /* Notifications from sqlite3_log() */
ErrWarning = ErrNo(28) /* Warnings from sqlite3_log() */
)
func (err ErrNo) Error() string {
return Error{Code: err}.Error()
}
func (err ErrNo) Extend(by int) ErrNoExtended {
return ErrNoExtended(int(err) | (by << 8))
}
func (err ErrNoExtended) Error() string {
return Error{Code: ErrNo(C.int(err) & ErrNoMask), ExtendedCode: err}.Error()
}
func (err Error) Error() string {
if err.err != "" {
return err.err
}
return errorString(err)
}
// result codes from http://www.sqlite.org/c3ref/c_abort_rollback.html
var (
ErrIoErrRead = ErrIoErr.Extend(1)
ErrIoErrShortRead = ErrIoErr.Extend(2)
ErrIoErrWrite = ErrIoErr.Extend(3)
ErrIoErrFsync = ErrIoErr.Extend(4)
ErrIoErrDirFsync = ErrIoErr.Extend(5)
ErrIoErrTruncate = ErrIoErr.Extend(6)
ErrIoErrFstat = ErrIoErr.Extend(7)
ErrIoErrUnlock = ErrIoErr.Extend(8)
ErrIoErrRDlock = ErrIoErr.Extend(9)
ErrIoErrDelete = ErrIoErr.Extend(10)
ErrIoErrBlocked = ErrIoErr.Extend(11)
ErrIoErrNoMem = ErrIoErr.Extend(12)
ErrIoErrAccess = ErrIoErr.Extend(13)
ErrIoErrCheckReservedLock = ErrIoErr.Extend(14)
ErrIoErrLock = ErrIoErr.Extend(15)
ErrIoErrClose = ErrIoErr.Extend(16)
ErrIoErrDirClose = ErrIoErr.Extend(17)
ErrIoErrSHMOpen = ErrIoErr.Extend(18)
ErrIoErrSHMSize = ErrIoErr.Extend(19)
ErrIoErrSHMLock = ErrIoErr.Extend(20)
ErrIoErrSHMMap = ErrIoErr.Extend(21)
ErrIoErrSeek = ErrIoErr.Extend(22)
ErrIoErrDeleteNoent = ErrIoErr.Extend(23)
ErrIoErrMMap = ErrIoErr.Extend(24)
ErrIoErrGetTempPath = ErrIoErr.Extend(25)
ErrIoErrConvPath = ErrIoErr.Extend(26)
ErrLockedSharedCache = ErrLocked.Extend(1)
ErrBusyRecovery = ErrBusy.Extend(1)
ErrBusySnapshot = ErrBusy.Extend(2)
ErrCantOpenNoTempDir = ErrCantOpen.Extend(1)
ErrCantOpenIsDir = ErrCantOpen.Extend(2)
ErrCantOpenFullPath = ErrCantOpen.Extend(3)
ErrCantOpenConvPath = ErrCantOpen.Extend(4)
ErrCorruptVTab = ErrCorrupt.Extend(1)
ErrReadonlyRecovery = ErrReadonly.Extend(1)
ErrReadonlyCantLock = ErrReadonly.Extend(2)
ErrReadonlyRollback = ErrReadonly.Extend(3)
ErrReadonlyDbMoved = ErrReadonly.Extend(4)
ErrAbortRollback = ErrAbort.Extend(2)
ErrConstraintCheck = ErrConstraint.Extend(1)
ErrConstraintCommitHook = ErrConstraint.Extend(2)
ErrConstraintForeignKey = ErrConstraint.Extend(3)
ErrConstraintFunction = ErrConstraint.Extend(4)
ErrConstraintNotNull = ErrConstraint.Extend(5)
ErrConstraintPrimaryKey = ErrConstraint.Extend(6)
ErrConstraintTrigger = ErrConstraint.Extend(7)
ErrConstraintUnique = ErrConstraint.Extend(8)
ErrConstraintVTab = ErrConstraint.Extend(9)
ErrConstraintRowId = ErrConstraint.Extend(10)
ErrNoticeRecoverWAL = ErrNotice.Extend(1)
ErrNoticeRecoverRollback = ErrNotice.Extend(2)
ErrWarningAutoIndex = ErrWarning.Extend(1)
)
| {
"pile_set_name": "Github"
} |
//
// AIGradientTransitionAnimation.h
// AIAnimationDemo
//
// Created by 艾泽鑫 on 2016/11/3.
// Copyright © 2016年 艾泽鑫. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface AIGradientTransitionAnimation : NSObject
@end
| {
"pile_set_name": "Github"
} |
<?php
/*
* Copyright © 2010 - 2013 Modo Labs Inc. All rights reserved.
*
* The license governing the contents of this file is located in the LICENSE
* file located at the root directory of this distribution. If the LICENSE file
* is missing, please contact [email protected].
*
*/
class PhoneFormatter
{
public static function formatPhone($value) {
// add the local area code if missing
if (preg_match('/^\d{3}-\d{4}/', $value)) {
$phone = Kurogo::getSiteVar('LOCAL_AREA_CODE').$value;
}
$phone = str_replace('-', '-­', str_replace('.', '-', $value));
return $phone;
}
public static function getPhoneURL($value) {
// add the local area code if missing
if (preg_match('/^\d{3}-?\d{4}/', $value)) {
$phone = Kurogo::getSiteVar('LOCAL_AREA_CODE').$value;
}
// remove all non-digit characters except the character '+' for international phone numbers
$phone = 'tel:'.preg_replace('/[^0-9\+]/', '', $value);
return $phone;
}
}
| {
"pile_set_name": "Github"
} |
#ifndef NMAP_NSE_UTILITY_H
#define NMAP_NSE_UTILITY_H
class Port;
class Target;
#ifdef HAVE_CONFIG_H
#include "nmap_config.h"
#else
#ifdef WIN32
#include "nmap_winconfig.h"
#endif /* WIN32 */
#endif /* HAVE_CONFIG_H */
#if HAVE_STDINT_H
#include <stdint.h>
#endif
/* int nseU_checkinteger (lua_State *L, int arg)
*
* Replacement for luaL_checkinteger that does a floor operation first
*/
int nseU_checkinteger (lua_State *L, int arg);
/* int nseU_traceback (lua_State *L)
*
* Traceback C Lua function.
*/
int nseU_traceback (lua_State *L);
/* int nseU_placeholder (lua_State *L)
*
* Placeholder C Lua function that simply throws a nil error.
*/
int nseU_placeholder (lua_State *L);
/* void nseU_tablen (lua_State *L, int idx) [-0, +0, -]
*
* Calculates the number of entries in the table by iterating over
* each key/value pair.
*/
size_t nseU_tablen (lua_State *L, int idx);
/* void nseU_setsfield (lua_State *L, int idx, [-0, +0, e]
* const char *field, const char *value)
*
* Sets the field for table at index idx to string value.
* (t[field] = value).
*/
void nseU_setsfield (lua_State *L, int idx, const char *field, const char *value);
/* void nseU_setnfield (lua_State *L, int idx, [-0, +0, e]
* const char *field, lua_Number value)
*
* Sets the field for table at index idx to numerical value.
* (t[field] = value).
*/
void nseU_setnfield (lua_State *L, int idx, const char *field, lua_Number value);
/* void nseU_setifield (lua_State *L, int idx, [-0, +0, e]
* const char *field, lua_Integer value)
*
* Sets the field for table at index idx to numerical value.
* (t[field] = value).
*/
void nseU_setifield (lua_State *L, int idx, const char *field, lua_Integer value);
/* void nseU_setbfield (lua_State *L, int idx, [-0, +0, e]
* const char *field, int value)
*
* Sets the field for table at index idx to boolean value.
* (t[field] = value).
*/
void nseU_setbfield (lua_State *L, int idx, const char *field, int value);
/* void nseU_appendfstr (lua_State *L, int idx, [-0, +0, m]
* const char *fmt, ...)
*
* Appends the formatted string to the table at index idx.
*/
void nseU_appendfstr (lua_State *L, int idx, const char *fmt, ...);
/* void nseU_weaktable (lua_State *L, int narr, int nrec, [-0, +1, e]
* const char *mode)
*
* Creates a table using lua_createtable with sizes narr and nrec. Creates
* a metatable with its __mode field set to mode.
*/
void nseU_weaktable (lua_State *L, int narr, int nrec, const char *mode);
/* int nseU_success (lua_State *L) [-0, +1, -]
*
* Indicates successful return of the running function by pushing
* boolean true and returning 1. Use as a tail call:
* return nseU_success(L);
*/
int nseU_success (lua_State *L);
/* int nseU_safeerror (lua_State *L, const char *fmt, ...) [-0, +1, -]
*
* Indicates unsuccessful return of the running function by pushing
* boolean false and and a formatted error message. Use as a tail call:
* return nseU_safeerror(L, "%s", "a generic error");
*/
int nseU_safeerror (lua_State *L, const char *fmt, ...);
/* void nseU_typeerror (lua_State *L, int idx, [-0, +1, v]
* const char *err)
*
* Raises a type error. Same as Lua 5.1.
*/
void nseU_typeerror (lua_State *L, int idx, const char *err);
/* void *nseU_checkudata (lua_State *L, int idx, [-0, +0, v]
* int upvalue, const char *name)
*
* Checks that value at index idx is a full userdata which a metatable
* equal to upvalue. name is the name of your object for error message
* purposes.
*/
void *nseU_checkudata (lua_State *L, int idx, int upvalue, const char *name);
/* void nseU_checktarget (lua_State *L, int idx, [-0, +0, v]
* const char **address,
* const char **targetname)
*
* Check for a valid target specification at index idx. This function checks
* for a string at idx or a table containing the typical host table fields,
* 'ip' and 'targetname' in particular.
*
* The address and targetname string pointers are only valid if the target
* specification persists.
*/
void nseU_checktarget (lua_State *L, int idx, const char **address, const char **targetname);
/* void nseU_opttarget (lua_State *L, int idx, [-0, +0, v]
* const char **address,
* const char **targetname)
*
* Like nseU_checktarget, but sets *address and *targetname to NULL and returns
* success if the argument at idx is none or nil.
*/
void nseU_opttarget (lua_State *L, int idx, const char **address, const char **targetname);
/* uint16_t nseU_checkport (lua_State *L, int idx, [-0, +0, v]
* const char **protocol)
*
* Check for a valid port specification at index idx.
*
* The protocol string pointer is only valid if the port specification
* persists.
*/
uint16_t nseU_checkport (lua_State *L, int idx, const char **protocol);
/* Target *nseU_gettarget (lua_State *L, int idx) [-0, +0, v]
*
* This function checks the value at index for a valid host table. It locates
* the associated Target (C++) class object associated with the host and
* returns it. If the Target is not being scanned then an error will be raised.
*/
Target *nseU_gettarget (lua_State *L, int idx);
/* Port *nseU_getport (lua_State *L, Target *target, [-0, +0, v]
* Port *port, int idx)
*
* This function checks the value at index for a valid port table. It locates
* the associated Port (C++) class object associated with the host and
* returns it.
*/
Port *nseU_getport (lua_State *L, Target *target, Port *port, int idx);
#endif
| {
"pile_set_name": "Github"
} |
.content * {
margin: 0;
padding: 0;
/* font-weight: normal; */
font-style: inherit;
font-size: 100%;
font-family: inherit;
/* vertical-align: baseline; */
list-style: none;
}
.content img,
.content fieldset,
.content legend,
.content table,
.content tr,
.content td,
.content th {
border: 0;
}
.content {
/* color: #000;
background: #fff; */
font: 13px arial,helvetica,clean,sans-serif;
font-style: normal;
line-height: 150%;
}
.content h1,
.content h2,
.content h3,
.content h4,
.content h5,
.content h6,
.content pre,
.content table,
.content blockquote {
clear: both;
}
.content input,
.content textarea,
.content select {
font:13px/1.22 arial,helvetica,clean,sans-serif;
}
.content table {
font-size:inherit;
}
.content pre,
.content code,
.content kbd,
.content samp,
.content tt {
font-family:monospace;
line-height:99%;
background-color: #eee;
}
/* Tables still need 'cellspacing="0"' in the markup. */
.content table {
font-size:100%;
table-layout: fixed;
border-collapse: collapse;
border-spacing: 0;
empty-cells: show;
}
.content caption,
.content th,
.content td {
text-align: left;
vertical-align: top;
font-weight: normal;
}
.content blockquote:before,
.content blockquote:after,
.content q:before,
.content q:after {
content: "";
}
.content blockquote,
.content q {
quotes: "" "";
}
.content h1 {
/*18px via YUI Fonts CSS foundation*/
font-size:138.5%;
}
.content h2 {
/*16px via YUI Fonts CSS foundation*/
font-size:123.1%;
}
.content h3 {
/*14px via YUI Fonts CSS foundation*/
font-size:108%;
}
.content h1,
.content h2,
.content h3 {
margin:1em 0;
}
.content h1,
.content h2,
.content h3,
.content h4,
.content h5,
.content h6,
.content strong {
font-weight:bold;
}
.content abbr,
.content acronym {
border-bottom:1px dotted #000;
cursor:help;
}
.content sup,
.content sub {
line-height:-1px;
vertical-align: text-top;
font-size: 80%;
}
.content sub {
vertical-align:text-bottom;
}
.content ins {
color: green;
text-decoration: underline;
}
.content del {
color: red;
text-decoration: line-through;
}
.content em,
.content i {
font-style: italic;
}
.content strong,
.content b {
font-weight: bold;
}
.content blockquote.blockquote {
font-family: Georgia, "Times New Roman", Times, serif;
font-style: italic;
color: #111;
}
.content pre.content-pre {
background: #eee;
padding: .5em;
border: 0;
}
.content pre {
margin-bottom: 1em;
}
.content blockquote,
.content ul,
.content ol,
.content dl {
margin:1em;
}
.content ol,
.content ul,
.content dl {
margin-left:2em;
}
.content li ol,
.content li ul,
.content li dl {
margin-top: 0;
margin-bottom: 0;
}
.content ol li {
list-style: decimal outside;
}
.content ul li {
list-style: disc outside;
}
.content dl dd {
margin-left:1em;
}
/*** TABLE ***/
.content table {
border-collapse: separate;
border-spacing: 0;
/* table-layout: fixed; */
}
.content caption {
margin-bottom:.5em;
text-align:center;
}
/* TABLE BLACK */
.content table.table-black {
border-left:1px solid #000;
border-top:1px solid #000;
border-collapse: separate;
border-spacing: 0;
margin-bottom:1em;
}
.content table.table-black th,
.content table.table-black td {
border-bottom:1px solid #000;
border-right:1px solid #000;
padding:.5em;
}
.content table.table-black th,
.content table.table-black td.table-th {
background: #000;
color: #FFFFFF;
font-weight: bold;
}
.content table.table-black tr.row-0 {
background: #fff;
}
.content table.table-black tr.row-1 {
background: #eee;
}
.content table.table-black tr.row-2 {
background: #ddd;
}
/* TABLE RED */
.content table.table-red {
border-left:1px solid red;
border-top:1px solid red;
border-collapse: separate;
border-spacing: 0;
margin-bottom:1em;
}
.content table.table-red th,
.content table.table-red td {
border-bottom:1px solid red;
border-right:1px solid red;
padding:.5em;
}
.content table.table-red th,
.content table.table-red td.table-th {
background: red;
color: #FFFFFF;
font-weight: bold;
}
.content table.table-red tr.row-0 {
background: #fff;
}
.content table.table-red tr.row-1 {
background-color: #FFDDDD;
}
.content table.table-red tr.row-2 {
background-color: #FFBBBB;
}
/* TABLE RED */
.content table.table-blue {
border-left:1px solid blue;
border-top:1px solid blue;
border-collapse: separate;
border-spacing: 0;
margin-bottom:1em;
}
.content table.table-blue th,
.content table.table-blue td {
border-bottom:1px solid blue;
border-right:1px solid blue;
padding:.5em;
}
.content table.table-blue th,
.content table.table-blue td.table-th {
background: blue;
color: #FFFFFF;
font-weight: bold;
}
.content table.table-blue tr.row-0 {
background: #fff;
}
.content table.table-blue tr.row-1 {
background-color: #DDDDFF;
}
.content table.table-blue tr.row-2 {
background-color: #BBBBFF;
}
/* The above separated solution is a workaround for Firefox who
draws the left border 1�x outside of the box */
* html .content table.table-black,
* html .content table.table-red,
* html .content table.table-blue {
border-collapse: collapse;
}
/*
* html .content th,
* html .content td {
border: 1px solid #000;
}
*/
.content p,
.content fieldset {
margin-bottom:1em;
}
.content img.align-right {
margin-left: 0.5em;
margin-bottom: 0.5em;
}
/* .content img[align=left] */
.content img.align-left {
margin-right: 0.5em;
margin-bottom: 0.5em;
}
/* Helpers */
.content .readonly {
background: #eee;
}
.content hr {
background: #000;
color: #000;
clear: both;
float: none;
width: 100%;
height: 0.1em;
margin: 0 0 1.4em 0;
border: none;
}
* html .content hr {
margin: 0 0 1.2em 0;
}
.content label,
.content .label {
display: block;
margin-top: 1em;
margin-bottom: 0.25em;
font-weight: bold;
}
.content fieldset legend {
display: none;
}
.content fieldset label {
font-weight: normal;
margin: 0;
}
.content .highlight {
background: yellow;
}
/*** COLUMNS ***/
div.col-left {
float: left;
clear: both;
width: 48%;
padding-right: 0.5em;
overflow-x: hidden;
}
div.col-right {
float: right;
width: 48%;
padding-left: 0.5em;
overflow-x: hidden;
}
.content .clear {
clear: both;
}
/*** EDIT ***/
.content-edit {
margin: 0 !important;
padding: 1em !important;
width: auto !important;
}
/* Ob das so Sinn macht, wegen Margin Collapse
.content-edit div,
.content-edit iframe,
.content-edit blockquote,
.content-edit fieldset,
.content-edit pre {
border: 1px dotted #ccc;
}
*/
.content-edit table {
border-left: 1px dotted #ccc;
border-top: 1px dotted #ccc;
}
.content-edit td,
.content-edit th {
border-bottom: 1px dotted #ccc;
border-right: 1px dotted #ccc;
} | {
"pile_set_name": "Github"
} |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading;
using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace Microsoft.EntityFrameworkCore.ValueGeneration.Internal
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class TemporaryDecimalValueGenerator : TemporaryNumberValueGenerator<decimal>
{
private int _current = int.MinValue + 1000;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override decimal Next(EntityEntry entry)
=> Interlocked.Increment(ref _current);
}
}
| {
"pile_set_name": "Github"
} |
import os.path as osp
import sys
import torch
from torch.autograd import gradcheck
sys.path.append(osp.abspath(osp.join(__file__, '../../')))
from roi_pool import RoIPool # noqa: E402, isort:skip
feat = torch.randn(4, 16, 15, 15, requires_grad=True).cuda()
rois = torch.Tensor([[0, 0, 0, 50, 50], [0, 10, 30, 43, 55],
[1, 67, 40, 110, 120]]).cuda()
inputs = (feat, rois)
print('Gradcheck for roi pooling...')
test = gradcheck(RoIPool(4, 1.0 / 8), inputs, eps=1e-5, atol=1e-3)
print(test)
| {
"pile_set_name": "Github"
} |
// Don't take these too seriously -- the expected results appear to be
// based on the results of actual runs without any serious manual
// verification. If a change you made causes them to fail, the test is
// as likely to wrong as the code.
(function() {
var mode = CodeMirror.getMode({tabSize: 4}, "xquery");
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
MT("eviltest",
"[keyword xquery] [keyword version] [variable "1][keyword .][atom 0][keyword -][variable ml"][def&variable ;] [comment (: this is : a \"comment\" :)]",
" [keyword let] [variable $let] [keyword :=] [variable <x] [variable attr][keyword =][variable "value">"test"<func>][def&variable ;function]() [variable $var] {[keyword function]()} {[variable $var]}[variable <][keyword /][variable func><][keyword /][variable x>]",
" [keyword let] [variable $joe][keyword :=][atom 1]",
" [keyword return] [keyword element] [variable element] {",
" [keyword attribute] [variable attribute] { [atom 1] },",
" [keyword element] [variable test] { [variable 'a'] }, [keyword attribute] [variable foo] { [variable "bar"] },",
" [def&variable fn:doc]()[[ [variable foo][keyword /][variable @bar] [keyword eq] [variable $let] ]],",
" [keyword //][variable x] } [comment (: a more 'evil' test :)]",
" [comment (: Modified Blakeley example (: with nested comment :) ... :)]",
" [keyword declare] [keyword private] [keyword function] [def&variable local:declare]() {()}[variable ;]",
" [keyword declare] [keyword private] [keyword function] [def&variable local:private]() {()}[variable ;]",
" [keyword declare] [keyword private] [keyword function] [def&variable local:function]() {()}[variable ;]",
" [keyword declare] [keyword private] [keyword function] [def&variable local:local]() {()}[variable ;]",
" [keyword let] [variable $let] [keyword :=] [variable <let>let] [variable $let] [keyword :=] [variable "let"<][keyword /let][variable >]",
" [keyword return] [keyword element] [variable element] {",
" [keyword attribute] [variable attribute] { [keyword try] { [def&variable xdmp:version]() } [keyword catch]([variable $e]) { [def&variable xdmp:log]([variable $e]) } },",
" [keyword attribute] [variable fn:doc] { [variable "bar"] [variable castable] [keyword as] [atom xs:string] },",
" [keyword element] [variable text] { [keyword text] { [variable "text"] } },",
" [def&variable fn:doc]()[[ [qualifier child::][variable eq][keyword /]([variable @bar] [keyword |] [qualifier attribute::][variable attribute]) [keyword eq] [variable $let] ]],",
" [keyword //][variable fn:doc]",
" }");
MT("testEmptySequenceKeyword",
"[string \"foo\"] [keyword instance] [keyword of] [keyword empty-sequence]()");
MT("testMultiAttr",
"[tag <p ][attribute a1]=[string \"foo\"] [attribute a2]=[string \"bar\"][tag >][variable hello] [variable world][tag </p>]");
MT("test namespaced variable",
"[keyword declare] [keyword namespace] [variable e] [keyword =] [string \"http://example.com/ANamespace\"][variable ;declare] [keyword variable] [variable $e:exampleComThisVarIsNotRecognized] [keyword as] [keyword element]([keyword *]) [variable external;]");
MT("test EQName variable",
"[keyword declare] [keyword variable] [variable $\"http://www.example.com/ns/my\":var] [keyword :=] [atom 12][variable ;]",
"[tag <out>]{[variable $\"http://www.example.com/ns/my\":var]}[tag </out>]");
MT("test EQName function",
"[keyword declare] [keyword function] [def&variable \"http://www.example.com/ns/my\":fn] ([variable $a] [keyword as] [atom xs:integer]) [keyword as] [atom xs:integer] {",
" [variable $a] [keyword +] [atom 2]",
"}[variable ;]",
"[tag <out>]{[def&variable \"http://www.example.com/ns/my\":fn]([atom 12])}[tag </out>]");
MT("test EQName function with single quotes",
"[keyword declare] [keyword function] [def&variable 'http://www.example.com/ns/my':fn] ([variable $a] [keyword as] [atom xs:integer]) [keyword as] [atom xs:integer] {",
" [variable $a] [keyword +] [atom 2]",
"}[variable ;]",
"[tag <out>]{[def&variable 'http://www.example.com/ns/my':fn]([atom 12])}[tag </out>]");
MT("testProcessingInstructions",
"[def&variable data]([comment&meta <?target content?>]) [keyword instance] [keyword of] [atom xs:string]");
MT("testQuoteEscapeDouble",
"[keyword let] [variable $rootfolder] [keyword :=] [string \"c:\\builds\\winnt\\HEAD\\qa\\scripts\\\"]",
"[keyword let] [variable $keysfolder] [keyword :=] [def&variable concat]([variable $rootfolder], [string \"keys\\\"])");
})();
| {
"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 openpgp
import "hash"
// NewCanonicalTextHash reformats text written to it into the canonical
// form and then applies the hash h. See RFC 4880, section 5.2.1.
func NewCanonicalTextHash(h hash.Hash) hash.Hash {
return &canonicalTextHash{h, 0}
}
type canonicalTextHash struct {
h hash.Hash
s int
}
var newline = []byte{'\r', '\n'}
func (cth *canonicalTextHash) Write(buf []byte) (int, error) {
start := 0
for i, c := range buf {
switch cth.s {
case 0:
if c == '\r' {
cth.s = 1
} else if c == '\n' {
cth.h.Write(buf[start:i])
cth.h.Write(newline)
start = i + 1
}
case 1:
cth.s = 0
}
}
cth.h.Write(buf[start:])
return len(buf), nil
}
func (cth *canonicalTextHash) Sum(in []byte) []byte {
return cth.h.Sum(in)
}
func (cth *canonicalTextHash) Reset() {
cth.h.Reset()
cth.s = 0
}
func (cth *canonicalTextHash) Size() int {
return cth.h.Size()
}
func (cth *canonicalTextHash) BlockSize() int {
return cth.h.BlockSize()
}
| {
"pile_set_name": "Github"
} |
import * as actions from '../actions'
const initialState = {
ethernautAddress: undefined,
activeLevel: undefined,
levels: []
}
export default function(state = initialState, action) {
switch(action.type) {
case actions.LOAD_GAME_DATA:
return {
...state,
levels: action.levels,
ethernautAddress: action.ethernautAddress
}
case actions.ACTIVATE_LEVEL:
return {
...state,
activeLevel: action.activeLevel
}
case actions.DEACTIVATE_LEVEL:
return {
...state,
activeLevel: undefined
}
default:
return state
}
} | {
"pile_set_name": "Github"
} |
## [未完待续] PostgreSQL 区块链(blockchain) 插件 pg_blkchain , pg_credereum
### 作者
digoal
### 日期
2018-03-12
### 标签
PostgreSQL , 区块链 , blockchain , pg_credereum , pg_blkchain
----
## 背景
https://github.com/blkchain/pg_blkchain
[《PostgreSQL 区块链条管理举例》](../201703/20170310_01.md)
https://github.com/postgrespro/pg_credereum
#### [PostgreSQL 许愿链接](https://github.com/digoal/blog/issues/76 "269ac3d1c492e938c0191101c7238216")
您的愿望将传达给PG kernel hacker、数据库厂商等, 帮助提高数据库产品质量和功能, 说不定下一个PG版本就有您提出的功能点. 针对非常好的提议,奖励限量版PG文化衫、纪念品、贴纸、PG热门书籍等,奖品丰富,快来许愿。[开不开森](https://github.com/digoal/blog/issues/76 "269ac3d1c492e938c0191101c7238216").
#### [9.9元购买3个月阿里云RDS PostgreSQL实例](https://www.aliyun.com/database/postgresqlactivity "57258f76c37864c6e6d23383d05714ea")
#### [PostgreSQL 解决方案集合](https://yq.aliyun.com/topic/118 "40cff096e9ed7122c512b35d8561d9c8")
#### [德哥 / digoal's github - 公益是一辈子的事.](https://github.com/digoal/blog/blob/master/README.md "22709685feb7cab07d30f30387f0a9ae")

| {
"pile_set_name": "Github"
} |
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
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)
==============================================================================*/
#ifndef BOOST_PP_IS_ITERATING
#if !defined(FUSION_TUPLE_TIE_10032005_0846)
#define FUSION_TUPLE_TIE_10032005_0846
#include <boost/preprocessor/iterate.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/fusion/tuple/detail/tuple.hpp>
#if !defined(BOOST_FUSION_DONT_USE_PREPROCESSED_FILES)
#include <boost/fusion/tuple/detail/preprocessed/tuple_tie.hpp>
#else
#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 2, line: 0, output: "preprocessed/tuple_tie" FUSION_MAX_VECTOR_SIZE_STR ".hpp")
#endif
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
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)
This is an auto-generated file. Do not edit!
==============================================================================*/
#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 1)
#endif
namespace boost { namespace fusion
{
#define BOOST_FUSION_REF(z, n, data) BOOST_PP_CAT(T, n)&
#define BOOST_PP_FILENAME_1 <boost/fusion/tuple/detail/tuple_tie.hpp>
#define BOOST_PP_ITERATION_LIMITS (1, FUSION_MAX_VECTOR_SIZE)
#include BOOST_PP_ITERATE()
#undef BOOST_FUSION_REF
}}
#if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES)
#pragma wave option(output: null)
#endif
#endif // BOOST_FUSION_DONT_USE_PREPROCESSED_FILES
#endif
#else // defined(BOOST_PP_IS_ITERATING)
///////////////////////////////////////////////////////////////////////////////
//
// Preprocessor vertical repetition code
//
///////////////////////////////////////////////////////////////////////////////
#define N BOOST_PP_ITERATION()
template <BOOST_PP_ENUM_PARAMS(N, typename T)>
BOOST_FUSION_GPU_ENABLED
inline tuple<BOOST_PP_ENUM(N, BOOST_FUSION_REF, _)>
tie(BOOST_PP_ENUM_BINARY_PARAMS(N, T, & arg))
{
return tuple<BOOST_PP_ENUM(N, BOOST_FUSION_REF, _)>(
BOOST_PP_ENUM_PARAMS(N, arg));
}
#undef N
#endif // defined(BOOST_PP_IS_ITERATING)
| {
"pile_set_name": "Github"
} |
namespace AggregateSource.EventStore.Stubs
{
public class StubbedStreamNameResolver : IStreamNameResolver
{
public static readonly IStreamNameResolver Instance = new StubbedStreamNameResolver();
StubbedStreamNameResolver() {}
public string Resolve(string identifier)
{
return null;
}
}
} | {
"pile_set_name": "Github"
} |
/*
* Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
* Copyright (C) 2006-2008 - INRIA - Allan CORNET
*
* Copyright (C) 2012 - 2016 - Scilab Enterprises
*
* This file is hereby licensed under the terms of the GNU GPL v2.0,
* pursuant to article 5.3.4 of the CeCILL v.2.1.
* This file was originally licensed under the terms of the CeCILL v2.1,
* and continues to be available under such terms.
* For more information, see the COPYING file which you should have received
* along with this program.
*
*/
/*--------------------------------------------------------------------------*/
#include <string.h>
#include "gw_polynomials.h"
#include "machine.h"
/*--------------------------------------------------------------------------*/
extern int C2F(intptriu)(int *job, int *id);
/*--------------------------------------------------------------------------*/
int sci_ptril(char *fname, unsigned long fname_len)
{
static int id[6];
int job = 0;
C2F(intptriu)(&job, id);
return 0;
}
/*--------------------------------------------------------------------------*/
| {
"pile_set_name": "Github"
} |
/*
ChibiOS/RT - Copyright (C) 2006-2013 Giovanni Di Sirio
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.
*/
/*
Concepts and parts of this file have been contributed by Uladzimir Pylinsky
aka barthess.
*/
/**
* @file chrtclib.h
* @brief RTC time conversion utilities header.
*
* @addtogroup chrtclib
* @{
*/
#ifndef CHRTCLIB_H_
#define CHRTCLIB_H_
#include <time.h>
#if HAL_USE_RTC || defined(__DOXYGEN__)
/*===========================================================================*/
/* External declarations. */
/*===========================================================================*/
#ifdef __cplusplus
extern "C" {
#endif
#if !STM32_RTC_IS_CALENDAR
uint32_t rtcGetTimeFat(RTCDriver *rtcp);
#endif
void rtcGetTimeTm(RTCDriver *rtcp, struct tm *timp);
void rtcSetTimeTm(RTCDriver *rtcp, struct tm *timp);
time_t rtcGetTimeUnixSec(RTCDriver *rtcp);
uint64_t rtcGetTimeUnixUsec(RTCDriver *rtcp);
void rtcSetTimeUnixSec(RTCDriver *rtcp, time_t tv_sec);
#ifdef __cplusplus
}
#endif
#endif /* HAL_USE_RTC */
#endif /* CHRTCLIB_H_ */
/** @} */
| {
"pile_set_name": "Github"
} |
/* trees.c -- output deflated data using Huffman coding
* Copyright (C) 1995-1998 Jean-loup Gailly
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/*
* ALGORITHM
*
* The "deflation" process uses several Huffman trees. The more
* common source values are represented by shorter bit sequences.
*
* Each code tree is stored in a compressed form which is itself
* a Huffman encoding of the lengths of all the code strings (in
* ascending order by source values). The actual code strings are
* reconstructed from the lengths in the inflate process, as described
* in the deflate specification.
*
* REFERENCES
*
* Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
* Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
*
* Storer, James A.
* Data Compression: Methods and Theory, pp. 49-50.
* Computer Science Press, 1988. ISBN 0-7167-8156-5.
*
* Sedgewick, R.
* Algorithms, p290.
* Addison-Wesley, 1983. ISBN 0-201-06672-6.
*/
/* @(#) $Id: trees.c,v 1.1 2003/05/14 23:52:17 mccloskey Exp $ */
/* #define GEN_TREES_H */
#include "deflate.h"
#ifdef DEBUG
# include <ctype.h>
#endif
/* ===========================================================================
* Constants
*/
#define MAX_BL_BITS 7
/* Bit length codes must not exceed MAX_BL_BITS bits */
#define END_BLOCK 256
/* end of block literal code */
#define REP_3_6 16
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
#define REPZ_3_10 17
/* repeat a zero length 3-10 times (3 bits of repeat count) */
#define REPZ_11_138 18
/* repeat a zero length 11-138 times (7 bits of repeat count) */
local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
= {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
local const int extra_dbits[D_CODES] /* extra bits for each distance code */
= {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
local const uch bl_order[BL_CODES]
= {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
#define Buf_size (8 * 2*sizeof(char))
/* Number of bits used within bi_buf. (bi_buf might be implemented on
* more than 16 bits on some systems.)
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
#define DIST_CODE_LEN 512 /* see definition of array dist_code below */
#if defined(GEN_TREES_H) || !defined(STDC)
/* non ANSI compilers may not accept trees.h */
local ct_data static_ltree[L_CODES+2];
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
local ct_data static_dtree[D_CODES];
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
uch _dist_code[DIST_CODE_LEN];
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
uch _length_code[MAX_MATCH-MIN_MATCH+1];
/* length code for each normalized match length (0 == MIN_MATCH) */
local int base_length[LENGTH_CODES];
/* First normalized length for each code (0 = MIN_MATCH) */
local int base_dist[D_CODES];
/* First normalized distance for each code (0 = distance of 1) */
#else
# include "trees.h"
#endif /* GEN_TREES_H */
struct static_tree_desc_s {
const ct_data *static_tree; /* static tree or NULL */
const intf *extra_bits; /* extra bits for each code or NULL */
int extra_base; /* base index for extra_bits */
int elems; /* max number of elements in the tree */
int max_length; /* max bit length for the codes */
};
local static_tree_desc static_l_desc =
{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
local static_tree_desc static_d_desc =
{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
local static_tree_desc static_bl_desc =
{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
/* ===========================================================================
* Local (static) routines in this file.
*/
local void tr_static_init OF((void));
local void init_block OF((deflate_state *s));
local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
local void build_tree OF((deflate_state *s, tree_desc *desc));
local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
local int build_bl_tree OF((deflate_state *s));
local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
int blcodes));
local void compress_block OF((deflate_state *s, ct_data *ltree,
ct_data *dtree));
local void set_data_type OF((deflate_state *s));
local unsigned bi_reverse OF((unsigned value, int length));
local void bi_windup OF((deflate_state *s));
local void bi_flush OF((deflate_state *s));
local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
int header));
#ifdef GEN_TREES_H
local void gen_trees_header OF((void));
#endif
#ifndef DEBUG
# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
/* Send a code of the given tree. c and tree must not have side effects */
#else /* DEBUG */
# define send_code(s, c, tree) \
{ if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
send_bits(s, tree[c].Code, tree[c].Len); }
#endif
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
#define put_short(s, w) { \
put_byte(s, (uch)((w) & 0xff)); \
put_byte(s, (uch)((ush)(w) >> 8)); \
}
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
#ifdef DEBUG
local void send_bits OF((deflate_state *s, int value, int length));
local void send_bits(s, value, length)
deflate_state *s;
int value; /* value to send */
int length; /* number of bits */
{
Tracevv((stderr," l %2d v %4x ", length, value));
Assert(length > 0 && length <= 15, "invalid length");
s->bits_sent += (ulg)length;
/* If not enough room in bi_buf, use (valid) bits from bi_buf and
* (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
* unused bits in value.
*/
if (s->bi_valid > (int)Buf_size - length) {
s->bi_buf |= (value << s->bi_valid);
put_short(s, s->bi_buf);
s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
s->bi_valid += length - Buf_size;
} else {
s->bi_buf |= value << s->bi_valid;
s->bi_valid += length;
}
}
#else /* !DEBUG */
#define send_bits(s, value, length) \
{ int len = length;\
if (s->bi_valid > (int)Buf_size - len) {\
int val = value;\
s->bi_buf |= (val << s->bi_valid);\
put_short(s, s->bi_buf);\
s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
s->bi_valid += len - Buf_size;\
} else {\
s->bi_buf |= (value) << s->bi_valid;\
s->bi_valid += len;\
}\
}
#endif /* DEBUG */
#define MAX(a,b) (a >= b ? a : b)
/* the arguments must not have side effects */
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
local void tr_static_init()
{
#if defined(GEN_TREES_H) || !defined(STDC)
static int static_init_done = 0;
int n; /* iterates over tree elements */
int bits; /* bit counter */
int length; /* length value */
int code; /* code value */
int dist; /* distance index */
ush bl_count[MAX_BITS+1];
/* number of codes at each bit length for an optimal tree */
if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
static_l_desc.static_tree = static_ltree;
static_l_desc.extra_bits = extra_lbits;
static_d_desc.static_tree = static_dtree;
static_d_desc.extra_bits = extra_dbits;
static_bl_desc.extra_bits = extra_blbits;
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES-1; code++) {
base_length[code] = length;
for (n = 0; n < (1<<extra_lbits[code]); n++) {
_length_code[length++] = (uch)code;
}
}
Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length-1] = (uch)code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0 ; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < (1<<extra_dbits[code]); n++) {
_dist_code[dist++] = (uch)code;
}
}
Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7; /* from now on, all distances are divided by 128 */
for ( ; code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
_dist_code[256 + dist++] = (uch)code;
}
}
Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
n = 0;
while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
static_dtree[n].Len = 5;
static_dtree[n].Code = bi_reverse((unsigned)n, 5);
}
static_init_done = 1;
# ifdef GEN_TREES_H
gen_trees_header();
# endif
#endif /* defined(GEN_TREES_H) || !defined(STDC) */
}
/* ===========================================================================
* Genererate the file trees.h describing the static trees.
*/
#ifdef GEN_TREES_H
# ifndef DEBUG
# include <stdio.h>
# endif
# define SEPARATOR(i, last, width) \
((i) == (last)? "\n};\n\n" : \
((i) % (width) == (width)-1 ? ",\n" : ", "))
void gen_trees_header()
{
FILE *header = fopen("trees.h", "w");
int i;
Assert (header != NULL, "Can't open trees.h");
fprintf(header,
"/* header created automatically with -DGEN_TREES_H */\n\n");
fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
for (i = 0; i < L_CODES+2; i++) {
fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
}
fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
for (i = 0; i < D_CODES; i++) {
fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
}
fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
for (i = 0; i < DIST_CODE_LEN; i++) {
fprintf(header, "%2u%s", _dist_code[i],
SEPARATOR(i, DIST_CODE_LEN-1, 20));
}
fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
fprintf(header, "%2u%s", _length_code[i],
SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
}
fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
for (i = 0; i < LENGTH_CODES; i++) {
fprintf(header, "%1u%s", base_length[i],
SEPARATOR(i, LENGTH_CODES-1, 20));
}
fprintf(header, "local const int base_dist[D_CODES] = {\n");
for (i = 0; i < D_CODES; i++) {
fprintf(header, "%5u%s", base_dist[i],
SEPARATOR(i, D_CODES-1, 10));
}
fclose(header);
}
#endif /* GEN_TREES_H */
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
void _tr_init(s)
deflate_state *s;
{
tr_static_init();
s->l_desc.dyn_tree = s->dyn_ltree;
s->l_desc.stat_desc = &static_l_desc;
s->d_desc.dyn_tree = s->dyn_dtree;
s->d_desc.stat_desc = &static_d_desc;
s->bl_desc.dyn_tree = s->bl_tree;
s->bl_desc.stat_desc = &static_bl_desc;
s->bi_buf = 0;
s->bi_valid = 0;
s->last_eob_len = 8; /* enough lookahead for inflate */
#ifdef DEBUG
s->compressed_len = 0L;
s->bits_sent = 0L;
#endif
/* Initialize the first block of the first file: */
init_block(s);
}
/* ===========================================================================
* Initialize a new block.
*/
local void init_block(s)
deflate_state *s;
{
int n; /* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
s->dyn_ltree[END_BLOCK].Freq = 1;
s->opt_len = s->static_len = 0L;
s->last_lit = s->matches = 0;
}
#define SMALLEST 1
/* Index within the heap array of least frequent node in the Huffman tree */
/* ===========================================================================
* Remove the smallest element from the heap and recreate the heap with
* one less element. Updates heap and heap_len.
*/
#define pqremove(s, tree, top) \
{\
top = s->heap[SMALLEST]; \
s->heap[SMALLEST] = s->heap[s->heap_len--]; \
pqdownheap(s, tree, SMALLEST); \
}
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
#define smaller(tree, n, m, depth) \
(tree[n].Freq < tree[m].Freq || \
(tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
local void pqdownheap(s, tree, k)
deflate_state *s;
ct_data *tree; /* the tree to restore */
int k; /* node to move down */
{
int v = s->heap[k];
int j = k << 1; /* left son of k */
while (j <= s->heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s->heap_len &&
smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s->heap[j], s->depth)) break;
/* Exchange v with the smallest son */
s->heap[k] = s->heap[j]; k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s->heap[k] = v;
}
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
local void gen_bitlen(s, desc)
deflate_state *s;
tree_desc *desc; /* the tree descriptor */
{
ct_data *tree = desc->dyn_tree;
int max_code = desc->max_code;
const ct_data *stree = desc->stat_desc->static_tree;
const intf *extra = desc->stat_desc->extra_bits;
int base = desc->stat_desc->extra_base;
int max_length = desc->stat_desc->max_length;
int h; /* heap index */
int n, m; /* iterate over the tree elements */
int bits; /* bit length */
int xbits; /* extra bits */
ush f; /* frequency */
int overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
n = s->heap[h];
bits = tree[tree[n].Dad].Len + 1;
if (bits > max_length) bits = max_length, overflow++;
tree[n].Len = (ush)bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) continue; /* not a leaf node */
s->bl_count[bits]++;
xbits = 0;
if (n >= base) xbits = extra[n-base];
f = tree[n].Freq;
s->opt_len += (ulg)f * (bits + xbits);
if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
}
if (overflow == 0) return;
Trace((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length-1;
while (s->bl_count[bits] == 0) bits--;
s->bl_count[bits]--; /* move one leaf down the tree */
s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
s->bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits != 0; bits--) {
n = s->bl_count[bits];
while (n != 0) {
m = s->heap[--h];
if (m > max_code) continue;
if (tree[m].Len != (unsigned) bits) {
Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s->opt_len += ((long)bits - (long)tree[m].Len)
*(long)tree[m].Freq;
tree[m].Len = (ush)bits;
}
n--;
}
}
}
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
local void gen_codes (tree, max_code, bl_count)
ct_data *tree; /* the tree to decorate */
int max_code; /* largest code with non zero frequency */
ushf *bl_count; /* number of codes at each bit length */
{
ush next_code[MAX_BITS+1]; /* next code value for each bit length */
ush code = 0; /* running code value */
int bits; /* bit index */
int n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (code + bl_count[bits-1]) << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
"inconsistent bit counts");
Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
int len = tree[n].Len;
if (len == 0) continue;
/* Now reverse the bits */
tree[n].Code = bi_reverse(next_code[len]++, len);
Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
}
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
local void build_tree(s, desc)
deflate_state *s;
tree_desc *desc; /* the tree descriptor */
{
ct_data *tree = desc->dyn_tree;
const ct_data *stree = desc->stat_desc->static_tree;
int elems = desc->stat_desc->elems;
int n, m; /* iterate over heap elements */
int max_code = -1; /* largest code with non zero frequency */
int node; /* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s->heap_len = 0, s->heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n].Freq != 0) {
s->heap[++(s->heap_len)] = max_code = n;
s->depth[n] = 0;
} else {
tree[n].Len = 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s->heap_len < 2) {
node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
tree[node].Freq = 1;
s->depth[node] = 0;
s->opt_len--; if (stree) s->static_len -= stree[node].Len;
/* node is 0 or 1 so it does not have extra bits */
}
desc->max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems; /* next internal node of the tree */
do {
pqremove(s, tree, n); /* n = node of least frequency */
m = s->heap[SMALLEST]; /* m = node of next least frequency */
s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
s->heap[--(s->heap_max)] = m;
/* Create a new node father of n and m */
tree[node].Freq = tree[n].Freq + tree[m].Freq;
s->depth[node] = (uch) (MAX(s->depth[n], s->depth[m]) + 1);
tree[n].Dad = tree[m].Dad = (ush)node;
#ifdef DUMP_BL_TREE
if (tree == s->bl_tree) {
fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
}
#endif
/* and insert the new node in the heap */
s->heap[SMALLEST] = node++;
pqdownheap(s, tree, SMALLEST);
} while (s->heap_len >= 2);
s->heap[--(s->heap_max)] = s->heap[SMALLEST];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, (tree_desc *)desc);
/* The field len is now set, we can generate the bit codes */
gen_codes ((ct_data *)tree, max_code, s->bl_count);
}
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
local void scan_tree (s, tree, max_code)
deflate_state *s;
ct_data *tree; /* the tree to be scanned */
int max_code; /* and its largest code of non zero frequency */
{
int n; /* iterates over all tree elements */
int prevlen = -1; /* last emitted length */
int curlen; /* length of current code */
int nextlen = tree[0].Len; /* length of next code */
int count = 0; /* repeat count of the current code */
int max_count = 7; /* max repeat count */
int min_count = 4; /* min repeat count */
if (nextlen == 0) max_count = 138, min_count = 3;
tree[max_code+1].Len = (ush)0xffff; /* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen; nextlen = tree[n+1].Len;
if (++count < max_count && curlen == nextlen) {
continue;
} else if (count < min_count) {
s->bl_tree[curlen].Freq += count;
} else if (curlen != 0) {
if (curlen != prevlen) s->bl_tree[curlen].Freq++;
s->bl_tree[REP_3_6].Freq++;
} else if (count <= 10) {
s->bl_tree[REPZ_3_10].Freq++;
} else {
s->bl_tree[REPZ_11_138].Freq++;
}
count = 0; prevlen = curlen;
if (nextlen == 0) {
max_count = 138, min_count = 3;
} else if (curlen == nextlen) {
max_count = 6, min_count = 3;
} else {
max_count = 7, min_count = 4;
}
}
}
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
local void send_tree (s, tree, max_code)
deflate_state *s;
ct_data *tree; /* the tree to be scanned */
int max_code; /* and its largest code of non zero frequency */
{
int n; /* iterates over all tree elements */
int prevlen = -1; /* last emitted length */
int curlen; /* length of current code */
int nextlen = tree[0].Len; /* length of next code */
int count = 0; /* repeat count of the current code */
int max_count = 7; /* max repeat count */
int min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen == 0) max_count = 138, min_count = 3;
for (n = 0; n <= max_code; n++) {
curlen = nextlen; nextlen = tree[n+1].Len;
if (++count < max_count && curlen == nextlen) {
continue;
} else if (count < min_count) {
do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
} else if (curlen != 0) {
if (curlen != prevlen) {
send_code(s, curlen, s->bl_tree); count--;
}
Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
} else {
send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
}
count = 0; prevlen = curlen;
if (nextlen == 0) {
max_count = 138, min_count = 3;
} else if (curlen == nextlen) {
max_count = 6, min_count = 3;
} else {
max_count = 7, min_count = 4;
}
}
}
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
local int build_bl_tree(s)
deflate_state *s;
{
int max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, (tree_desc *)(&(s->bl_desc)));
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
}
/* Update opt_len to include the bit length tree and counts */
s->opt_len += 3*(max_blindex+1) + 5+5+4;
Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
s->opt_len, s->static_len));
return max_blindex;
}
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
local void send_all_trees(s, lcodes, dcodes, blcodes)
deflate_state *s;
int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
int rank; /* index in bl_order */
Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
"too many codes");
Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
send_bits(s, dcodes-1, 5);
send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
}
Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}
/* ===========================================================================
* Send a stored block
*/
void _tr_stored_block(s, buf, stored_len, eof)
deflate_state *s;
charf *buf; /* input block */
ulg stored_len; /* length of input block */
int eof; /* true if this is the last block for a file */
{
send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
#ifdef DEBUG
s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
s->compressed_len += (stored_len + 4) << 3;
#endif
copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
}
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
* The current inflate code requires 9 bits of lookahead. If the
* last two codes for the previous block (real code plus EOB) were coded
* on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
* the last real code. In this case we send two empty static blocks instead
* of one. (There are no problems if the previous block is stored or fixed.)
* To simplify the code, we assume the worst case of last real code encoded
* on one bit only.
*/
void _tr_align(s)
deflate_state *s;
{
send_bits(s, STATIC_TREES<<1, 3);
send_code(s, END_BLOCK, static_ltree);
#ifdef DEBUG
s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
#endif
bi_flush(s);
/* Of the 10 bits for the empty block, we have already sent
* (10 - bi_valid) bits. The lookahead for the last real code (before
* the EOB of the previous block) was thus at least one plus the length
* of the EOB plus what we have just sent of the empty static block.
*/
if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
send_bits(s, STATIC_TREES<<1, 3);
send_code(s, END_BLOCK, static_ltree);
#ifdef DEBUG
s->compressed_len += 10L;
#endif
bi_flush(s);
}
s->last_eob_len = 7;
}
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
void _tr_flush_block(s, buf, stored_len, eof)
deflate_state *s;
charf *buf; /* input block, or NULL if too old */
ulg stored_len; /* length of input block */
int eof; /* true if this is the last block for a file */
{
ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
int max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s->level > 0) {
/* Check if the file is ascii or binary */
if (s->data_type == Z_UNKNOWN) set_data_type(s);
/* Construct the literal and distance trees */
build_tree(s, (tree_desc *)(&(s->l_desc)));
Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
s->static_len));
build_tree(s, (tree_desc *)(&(s->d_desc)));
Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute first the block length in bytes*/
opt_lenb = (s->opt_len+3+7)>>3;
static_lenb = (s->static_len+3+7)>>3;
Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
s->last_lit));
if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
} else {
Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
}
#ifdef FORCE_STORED
if (buf != (char*)0) { /* force stored block */
#else
if (stored_len+4 <= opt_lenb && buf != (char*)0) {
/* 4: two words for the lengths */
#endif
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block(s, buf, stored_len, eof);
#ifdef FORCE_STATIC
} else if (static_lenb >= 0) { /* force static trees */
#else
} else if (static_lenb == opt_lenb) {
#endif
send_bits(s, (STATIC_TREES<<1)+eof, 3);
compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
#ifdef DEBUG
s->compressed_len += 3 + s->static_len;
#endif
} else {
send_bits(s, (DYN_TREES<<1)+eof, 3);
send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
max_blindex+1);
compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
#ifdef DEBUG
s->compressed_len += 3 + s->opt_len;
#endif
}
Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (eof) {
bi_windup(s);
#ifdef DEBUG
s->compressed_len += 7; /* align on byte boundary */
#endif
}
Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
s->compressed_len-7*eof));
}
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
int _tr_tally (s, dist, lc)
deflate_state *s;
unsigned dist; /* distance of matched string */
unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
s->d_buf[s->last_lit] = (ush)dist;
s->l_buf[s->last_lit++] = (uch)lc;
if (dist == 0) {
/* lc is the unmatched char */
s->dyn_ltree[lc].Freq++;
} else {
s->matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
Assert((ush)dist < (ush)MAX_DIST(s) &&
(ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
(ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
s->dyn_dtree[d_code(dist)].Freq++;
}
#ifdef TRUNCATE_BLOCK
/* Try to guess if it is profitable to stop the current block here */
if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
/* Compute an upper bound for the compressed length */
ulg out_length = (ulg)s->last_lit*8L;
ulg in_length = (ulg)((long)s->strstart - s->block_start);
int dcode;
for (dcode = 0; dcode < D_CODES; dcode++) {
out_length += (ulg)s->dyn_dtree[dcode].Freq *
(5L+extra_dbits[dcode]);
}
out_length >>= 3;
Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
s->last_lit, in_length, out_length,
100L - out_length*100L/in_length));
if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
}
#endif
return (s->last_lit == s->lit_bufsize-1);
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
local void compress_block(s, ltree, dtree)
deflate_state *s;
ct_data *ltree; /* literal tree */
ct_data *dtree; /* distance tree */
{
unsigned dist; /* distance of matched string */
int lc; /* match length or unmatched char (if dist == 0) */
unsigned lx = 0; /* running index in l_buf */
unsigned code; /* the code to send */
int extra; /* number of extra bits to send */
if (s->last_lit != 0) do {
dist = s->d_buf[lx];
lc = s->l_buf[lx++];
if (dist == 0) {
send_code(s, lc, ltree); /* send a literal byte */
Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code+LITERALS+1, ltree); /* send the length code */
extra = extra_lbits[code];
if (extra != 0) {
lc -= base_length[code];
send_bits(s, lc, extra); /* send the extra length bits */
}
dist--; /* dist is now the match distance - 1 */
code = d_code(dist);
Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree); /* send the distance code */
extra = extra_dbits[code];
if (extra != 0) {
dist -= base_dist[code];
send_bits(s, dist, extra); /* send the extra distance bits */
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
Assert(s->pending < s->lit_bufsize + 2*lx, "pendingBuf overflow");
} while (lx < s->last_lit);
send_code(s, END_BLOCK, ltree);
s->last_eob_len = ltree[END_BLOCK].Len;
}
/* ===========================================================================
* Set the data type to ASCII or BINARY, using a crude approximation:
* binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
* IN assertion: the fields freq of dyn_ltree are set and the total of all
* frequencies does not exceed 64K (to fit in an int on 16 bit machines).
*/
local void set_data_type(s)
deflate_state *s;
{
int n = 0;
unsigned ascii_freq = 0;
unsigned bin_freq = 0;
while (n < 7) bin_freq += s->dyn_ltree[n++].Freq;
while (n < 128) ascii_freq += s->dyn_ltree[n++].Freq;
while (n < LITERALS) bin_freq += s->dyn_ltree[n++].Freq;
s->data_type = (Byte)(bin_freq > (ascii_freq >> 2) ? Z_BINARY : Z_ASCII);
}
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
local unsigned bi_reverse(code, len)
unsigned code; /* the value to invert */
int len; /* its bit length */
{
register unsigned res = 0;
do {
res |= code & 1;
code >>= 1, res <<= 1;
} while (--len > 0);
return res >> 1;
}
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
local void bi_flush(s)
deflate_state *s;
{
if (s->bi_valid == 16) {
put_short(s, s->bi_buf);
s->bi_buf = 0;
s->bi_valid = 0;
} else if (s->bi_valid >= 8) {
put_byte(s, (Byte)s->bi_buf);
s->bi_buf >>= 8;
s->bi_valid -= 8;
}
}
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
local void bi_windup(s)
deflate_state *s;
{
if (s->bi_valid > 8) {
put_short(s, s->bi_buf);
} else if (s->bi_valid > 0) {
put_byte(s, (Byte)s->bi_buf);
}
s->bi_buf = 0;
s->bi_valid = 0;
#ifdef DEBUG
s->bits_sent = (s->bits_sent+7) & ~7;
#endif
}
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
local void copy_block(s, buf, len, header)
deflate_state *s;
charf *buf; /* the input data */
unsigned len; /* its length */
int header; /* true if block header must be written */
{
bi_windup(s); /* align on byte boundary */
s->last_eob_len = 8; /* enough lookahead for inflate */
if (header) {
put_short(s, (ush)len);
put_short(s, (ush)~len);
#ifdef DEBUG
s->bits_sent += 2*16;
#endif
}
#ifdef DEBUG
s->bits_sent += (ulg)len<<3;
#endif
while (len--) {
put_byte(s, *buf++);
}
}
| {
"pile_set_name": "Github"
} |
package org.ananas.cli;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CommandLineTable {
private static final String HORIZONTAL_SEP = "-";
private String verticalSep;
private String joinSep;
private String[] headers;
private List<String[]> rows = new ArrayList<>();
private boolean rightAlign;
public CommandLineTable() {
setShowVerticalLines(false);
}
public void setRightAlign(boolean rightAlign) {
this.rightAlign = rightAlign;
}
public void setShowVerticalLines(boolean showVerticalLines) {
verticalSep = showVerticalLines ? "|" : "";
joinSep = showVerticalLines ? "+" : " ";
}
public void setHeaders(String... headers) {
this.headers = headers;
}
public void addRow(String... cells) {
rows.add(cells);
}
public void print() {
int[] maxWidths =
headers != null ? Arrays.stream(headers).mapToInt(String::length).toArray() : null;
for (String[] cells : rows) {
if (maxWidths == null) {
maxWidths = new int[cells.length];
}
if (cells.length != maxWidths.length) {
throw new IllegalArgumentException("Number of row-cells and headers should be consistent");
}
for (int i = 0; i < cells.length; i++) {
maxWidths[i] = Math.max(maxWidths[i], cells[i].length());
}
}
if (headers != null) {
printLine(maxWidths);
printRow(headers, maxWidths);
printLine(maxWidths);
}
for (String[] cells : rows) {
printRow(cells, maxWidths);
}
if (headers != null) {
printLine(maxWidths);
}
}
private void printLine(int[] columnWidths) {
for (int i = 0; i < columnWidths.length; i++) {
String line =
String.join(
"", Collections.nCopies(columnWidths[i] + verticalSep.length() + 1, HORIZONTAL_SEP));
System.out.print(joinSep + line + (i == columnWidths.length - 1 ? joinSep : ""));
}
System.out.println();
}
private void printRow(String[] cells, int[] maxWidths) {
for (int i = 0; i < cells.length; i++) {
String s = cells[i];
String verStrTemp = i == cells.length - 1 ? verticalSep : "";
if (rightAlign) {
System.out.printf("%s %" + maxWidths[i] + "s %s", verticalSep, s, verStrTemp);
} else {
System.out.printf("%s %-" + maxWidths[i] + "s %s", verticalSep, s, verStrTemp);
}
}
System.out.println();
}
public static void main(String[] args) {
// test code
CommandLineTable st = new CommandLineTable();
// st.setRightAlign(true);//if true then cell text is right aligned
st.setShowVerticalLines(true); // if false (default) then no vertical lines are shown
st.setHeaders(
"one", "two",
"three"); // optional - if not used then there will be no header and horizontal lines
st.addRow("super", "broccoli", "flexible");
st.addRow("assumption", "announcement", "reflection");
st.addRow("logic", "pleasant", "wild");
st.print();
}
}
| {
"pile_set_name": "Github"
} |
(* check that differently nested lambdas are equal. *)
let f = λ (T : Type) (U : Type) (x : T) (y : U), x
let g = λ (T : Type) (U : Type), let _ = Type in (λ (x : T) (y : U), x)
do refl f : f == g
| {
"pile_set_name": "Github"
} |
/**
* Copyright 2020, SumUp Ltd.
* 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.
*/
import { Transform, JSCodeshift, Collection } from 'jscodeshift';
import { renameJSXAttribute, findLocalNames } from './utils';
function transformFactory(
j: JSCodeshift,
root: Collection,
componentName: string,
): void {
const components = findLocalNames(j, root, componentName);
if (!components) {
return;
}
components.forEach((component) => {
renameJSXAttribute(j, root, component, 'onToggle', 'onChange');
});
}
const transform: Transform = (file, api) => {
const j = api.jscodeshift;
const root = j(file.source);
transformFactory(j, root, 'RadioButton');
transformFactory(j, root, 'Switch');
transformFactory(j, root, 'Toggle');
return root.toSource();
};
export default transform;
| {
"pile_set_name": "Github"
} |
/* ----------------------------------------------------------------------------
* SAM Software Package License
* ----------------------------------------------------------------------------
* Copyright (c) 2013, Atmel Corporation
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the disclaimer below.
*
* Atmel's name may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
* ----------------------------------------------------------------------------
*/
/**
* \file
*
* Implementation of Watchdog Timer (WDT) controller.
*
*/
/** \addtogroup wdt_module Working with WDT
* The WDT driver provides the interface to configure and use the WDT
* peripheral.
*
* The WDT can be used to prevent system lock-up if the software becomes
* trapped in a deadlock. It can generate a general reset or a processor
* reset only. It is clocked by slow clock divided by 128.
*
* The WDT is running at reset with 16 seconds watchdog period (slow clock at 32.768 kHz)
* and external reset generation enabled. The user must either disable it or
* reprogram it to meet the application requires.
*
* To use the WDT, the user could follow these few steps:
* <ul>
* <li>Enable watchdog with given mode using \ref WDT_Enable().
* <li>Restart the watchdog using \ref WDT_Restart() within the watchdog period.
* </ul>
*
* For more accurate information, please look at the WDT section of the
* Datasheet.
*
* \note
* The Watchdog Mode Register (WDT_MR) can be written only once.\n
*
* Related files :\n
* \ref wdt.c\n
* \ref wdt.h.\n
*/
/*@{*/
/*@}*/
/*---------------------------------------------------------------------------
* Headers
*---------------------------------------------------------------------------*/
#include "chip.h"
#include <stdint.h>
/*----------------------------------------------------------------------------
* Exported functions
*----------------------------------------------------------------------------*/
/**
* \brief Enable watchdog with given mode.
*
* \note The Watchdog Mode Register (WDT_MR) can be written only once.
* Only a processor reset resets it.
*
* \param dwMode WDT mode to be set
*/
extern void WDT_Enable( Wdt* pWDT, uint32_t dwMode )
{
pWDT->WDT_MR = dwMode ;
}
/**
* \brief Disable watchdog.
*
* \note The Watchdog Mode Register (WDT_MR) can be written only once.
* Only a processor reset resets it.
*/
extern void WDT_Disable( Wdt* pWDT )
{
pWDT->WDT_MR = WDT_MR_WDDIS;
}
/**
* \brief Watchdog restart.
*/
extern void WDT_Restart( Wdt* pWDT )
{
pWDT->WDT_CR = 0xA5000001;
}
/**
* \brief Watchdog get status.
*/
extern uint32_t WDT_GetStatus( Wdt* pWDT )
{
return (pWDT->WDT_SR & 0x3) ;
}
/**
* \brief Watchdog get status.
*/
extern uint32_t WDT_GetCounterValue( Wdt* pWDT )
{
return (pWDT->WDT_MR & WDT_MR_WDV_Msk) ;
}
/**
* \brief Watchdog get period.
*
* \param dwMs desired watchdog period in millisecond.
*/
extern uint32_t WDT_GetPeriod( uint32_t dwMs )
{
if ( (dwMs < 4) || (dwMs > 16000) )
{
return 0 ;
}
return ((dwMs << 8) / 1000) ;
}
| {
"pile_set_name": "Github"
} |
arr6 = [ 1, 2.0 ] # INVALID
| {
"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/bind_fwd.hpp" header
// -- DO NOT modify by hand!
namespace boost { namespace mpl {
template<
typename F
>
struct bind0;
template<
typename F, typename T1
>
struct bind1;
template<
typename F, typename T1, typename T2
>
struct bind2;
template<
typename F, typename T1, typename T2, typename T3
>
struct bind3;
template<
typename F, typename T1, typename T2, typename T3, typename T4
>
struct bind4;
template<
typename F, typename T1, typename T2, typename T3, typename T4
, typename T5
>
struct bind5;
}}
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2009--2010 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.frontend.xmlrpc.serializer.test;
import com.redhat.rhn.domain.channel.ChannelArch;
import com.redhat.rhn.frontend.xmlrpc.serializer.ChannelArchSerializer;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import junit.framework.TestCase;
import redstone.xmlrpc.XmlRpcException;
import redstone.xmlrpc.XmlRpcSerializer;
public class ChannelArchSerializerTest extends TestCase {
public void testSerialize() throws XmlRpcException, IOException {
ChannelArchSerializer cas = new ChannelArchSerializer();
ChannelArch ca = new ChannelArch();
ca.setName("name");
ca.setLabel("label");
Writer output = new StringWriter();
cas.serialize(ca, output, new XmlRpcSerializer());
String actual = output.toString();
assertTrue(actual.contains("<name>name</name>"));
assertTrue(actual.contains("<name>label</name>"));
assertTrue(actual.contains("<string>name</string>"));
assertTrue(actual.contains("<string>label</string>"));
}
}
| {
"pile_set_name": "Github"
} |
function [chains, e2chain, chainsize] = chainEdgelets(pbVal, enext, thetaStart, ...
thetaEnd, pbThresh, thetaThresh)
% chains = chainEdgelets(
% pbVal, enext, thetaStart, thetaEnd, pbThresh, thetaThresh)
%
% Chains edglets with pbVal > pbThresh, such that the angle between
% consecutive fragments is always lower than thetaThresh.
%
% pbVal(1:ne) - weight for each edge
% enext{1:ne}(1:nadj) - adjacent edges
% thetaStart(1:ne) - orientation at start of edgelet (deg)
% thetaEnd(1:ne) - orientation at end of edglet (deg)
% pbThresh - minimum edge weight
% thetaThresh - maximum discontinuity (deg)
%
% chains{nc}(:) - edge indices in each chain
% e2chain(1:ne) - maps edge index to chain index
% chainsize(1:nc) - length of each chain (in edgelets)
ne = numel(pbVal);
enext2 = cell(size(enext));
eprev = cell(size(enext));
ra = cell(size(enext));
for k = 1:numel(enext)
enext{k} = enext{k}(:)';
end
thetaStart = thetaStart(:)';
thetaEnd = thetaEnd(:)';
nadj = 0;
for k = 1:numel(enext)
% relative angle (absolute angle between two edgelets
ra{k} = mod(abs(thetaEnd(k)-thetaStart(enext{k})), 180+1E-3);
% remove adjacency if relative angle is greater than thetaThresh
ind = (ra{k} <= thetaThresh);
ra{k} = ra{k}(ind);
enext2{k} = enext{k}(ind);
% create list of previous edgelets
for k2 = enext2{k}
eprev{k2}(end+1) = k;
end
nadj = nadj + numel(enext2{k});
end
%disp(num2str(nadj/ne))
enext = enext2;
used = (pbVal < pbThresh);
nused = sum(used);
allind = (1:ne);
nc = 0;
chains = cell(sum(~used), 1);
chainsize = zeros(sum(~used), 1);
e2chain = zeros(ne, 1);
for start = 1:ne
if ~used(start) && all(used(eprev{start}))
nc = nc + 1;
k = start;
chains{nc} = k;
used(k) = true;
nused = nused+1;
while 1
next = enext{k}(~used(enext{k}));
if isempty(next)
break;
elseif numel(next)>1
[tmpval, nextid] = min(ra{k}(~used(enext{k})));
next = next(nextid);
end
k = next;
chains{nc}(end+1) = k;
used(k) =true;
nused = nused+1;
end
chainsize(nc) = numel(chains{nc});
e2chain(chains{nc}) = nc;
end
end
chainsize = chainsize(1:nc);
chains = chains(1:nc);
| {
"pile_set_name": "Github"
} |
JASC-PAL
0100
16
197 213 213
255 255 255
222 230 238
189 205 230
156 180 222
148 115 131
230 106 189
57 74 123
41 49 90
115 189 246
98 172 238
255 164 90
255 131 90
255 98 90
222 82 82
131 189 98
| {
"pile_set_name": "Github"
} |
---
UUID: "85757b38-6e21-11e8-b42d-28d2442e1329"
Name: "CheckConnectivity"
Title: "Test connectivity between two interfaces"
Abstract: "This workflow aims to test the connectivity between two interfaces. It returns the status of the connection, true or false."
Description: >
# How to use:
1. Select the Source and Destination Nodes to check the Connectivity between them
2. Hit the 'Execute' button to run the workflow
3. Result will be shown as status true or false along with flows between those interfaces
# How It Works:
1. It will start capture on all Nodes from Source to Destination and injects 5 ICMP-Pkts from Source to Destination
2. After 1 sec it will check for flows having the same capture-id created by this workflow
3. If flows are there and the BA-Packtes in flow-metric > 0, then return 'Connectivity = ture' else 'Connectivity = false', along with this it also returns the flows
4. For more information about Skydive workflows please follow - 'skydive.network/blog/introduction-to-workflows.html'
Parameters:
- Name: source
Description: Source node
Type: node
- Name: destination
Description: Destination node
Type: node
Source: |
function CheckConnectivity(from, to) {
var result = {}
try {
var capture = new Capture();
capture.GremlinQuery = "G.V().Has('TID', '" + from + "').ShortestPathTo(Metadata('TID', '" + to + "'))";
var packetInjection = new PacketInjection();
packetInjection.Src = "G.V().Has('TID', '" + from + "')"
packetInjection.Dst = "G.V().Has('TID', '" + to + "')"
packetInjection.Type = "icmp4"
packetInjection.ICMPID = Math.floor(Math.random() * 1000);
packetInjection.Count = 5
capture = client.captures.create(capture)
sleep(1000)
client.packetInjections.create(packetInjection)
sleep(1000)
var flows = client.G.Flows().Has('CaptureID', capture.UUID).Dedup().result()
result["Connectivity"] = flows.length > 0 && flows[0].Metric.ABPackets > 0 && flows[0].Metric.BAPackets > 0
result["Flows"] = flows
} catch (e) {
console.log(e)
result["Error"] = JSON.stringify(e)
}
if (capture && capture.UUID) client.captures.delete(capture.UUID)
return result
}
| {
"pile_set_name": "Github"
} |
package com.sequenceiq.cloudbreak.dto.credential.azure;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel("RoleBasedV1Response")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class AzureRoleBasedAttributes implements Serializable {
@ApiModelProperty(hidden = true)
private final String deploymentAddress;
@ApiModelProperty
private final String spDisplayName;
@ApiModelProperty
private final Boolean codeGrantFlow;
@ApiModelProperty
private final String appObjectId;
private AzureRoleBasedAttributes(Builder builder) {
deploymentAddress = builder.deploymentAddress;
spDisplayName = builder.spDisplayName;
codeGrantFlow = builder.codeGrantFlow;
appObjectId = builder.appObjectId;
}
public String getDeploymentAddress() {
return deploymentAddress;
}
public String getSpDisplayName() {
return spDisplayName;
}
public Boolean getCodeGrantFlow() {
return codeGrantFlow;
}
public String getAppObjectId() {
return appObjectId;
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private String deploymentAddress;
private String spDisplayName;
private Boolean codeGrantFlow;
private String appObjectId;
public Builder deploymentAddress(String deploymentAddress) {
this.deploymentAddress = deploymentAddress;
return this;
}
public Builder spDisplayName(String spDisplayName) {
this.spDisplayName = spDisplayName;
return this;
}
public Builder codeGrantFlow(Boolean codeGrantFlow) {
this.codeGrantFlow = codeGrantFlow;
return this;
}
public Builder appObjectId(String appObjectId) {
this.appObjectId = appObjectId;
return this;
}
public AzureRoleBasedAttributes build() {
return new AzureRoleBasedAttributes(this);
}
}
}
| {
"pile_set_name": "Github"
} |
/**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.
*/
package com.afollestad.materialdialogs.color.view
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.Color.BLACK
import android.graphics.Color.WHITE
import android.graphics.drawable.ColorDrawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.core.view.ViewCompat
import com.afollestad.materialdialogs.color.R
import com.afollestad.materialdialogs.color.R.drawable
import com.afollestad.materialdialogs.color.R.layout
import com.afollestad.materialdialogs.color.utils.hexValue
import com.afollestad.materialdialogs.color.utils.toColor
import com.afollestad.materialdialogs.utils.MDUtil.isColorDark
internal typealias HexColorChanged = (Int) -> Boolean
/** @author Aidan Follestad (afollestad) */
internal class PreviewFrameView(
context: Context,
attrs: AttributeSet? = null
) : FrameLayout(context, attrs) {
companion object {
const val HEX_VALUE_ALPHA_THRESHOLD = 50
}
private lateinit var argbView: View
private lateinit var hexPrefixView: TextView
private lateinit var hexValueView: ObservableEditText
var supportCustomAlpha: Boolean = true
var onHexChanged: HexColorChanged = { true }
var color: Int? = null
private set
init {
setBackgroundResource(drawable.transparent_rect_repeat)
LayoutInflater.from(context)
.inflate(layout.md_color_chooser_preview_frame, this)
}
override fun onFinishInflate() {
super.onFinishInflate()
argbView = findViewById(R.id.argbView)
hexPrefixView = findViewById(R.id.hexPrefixView)
hexValueView = findViewById(R.id.hexValueView)
hexValueView.observe {
if (it.length < 4) {
return@observe
}
val newColor = it.toColor() ?: return@observe
if (onHexChanged(newColor)) {
setColor(newColor)
}
}
}
fun setColor(@ColorInt color: Int) {
if (this.color == color) {
// Not changed
return
}
this.color = color
argbView.background = ColorDrawable(color)
hexValueView.updateText(color.hexValue(supportCustomAlpha))
hexValueView.post { hexValueView.setSelection(hexValueView.textLength) }
val tintColor = tintColor(color)
hexPrefixView.setTextColor(tintColor)
hexValueView.setTextColor(tintColor)
ViewCompat.setBackgroundTintList(hexValueView, ColorStateList.valueOf(tintColor))
}
private fun tintColor(color: Int) =
if (color.isColorDark() && Color.alpha(color) >= HEX_VALUE_ALPHA_THRESHOLD) {
WHITE
} else {
BLACK
}
}
| {
"pile_set_name": "Github"
} |
version: 1
n_points: 4
{
1122.630 755.046
1122.630 1894.555
2262.138 1894.555
2262.138 755.046
}
| {
"pile_set_name": "Github"
} |
[condition][Reservation]客户想升舱=r : Reservation(classUpgrade == true)
[condition][Customer]客户是 {value} 会员=Customer(loyaltyLevel == "{value}")
[consequence][][r : Reservation]收取 {value} 的升舱费用=r.setClassUpgradeFees(new BigDecimal("{value}"));
| {
"pile_set_name": "Github"
} |
import pytest
from panel.widgets.indicators import Dial, Gauge, Number
def test_number_thresholds(document, comm):
number = Number(value=0, colors=[(0.33, 'green'), (0.66, 'yellow'), (1, 'red')])
model = number.get_root(document, comm)
assert 'green' in model.text
number.value = 0.5
assert 'yellow' in model.text
number.value = 0.7
assert 'red' in model.text
def test_dial_thresholds(document, comm):
dial = Dial(value=0, colors=[(0.33, 'green'), (0.66, 'yellow'), (1, 'red')])
model = dial.get_root(document, comm)
cds = model.select(name='annulus_source')
assert ['green', 'whitesmoke'] == cds.data['color']
dial.value = 50
assert ['yellow', 'whitesmoke'] == cds.data['color']
dial.value = 72
assert ['red', 'whitesmoke'] == cds.data['color']
def test_dial_thresholds_with_bounds(document, comm):
dial = Dial(value=25, colors=[(0.33, 'green'), (0.66, 'yellow'), (1, 'red')],
bounds=(25, 75))
model = dial.get_root(document, comm)
cds = model.select(name='annulus_source')
assert ['green', 'whitesmoke'] == cds.data['color']
dial.value = 50
assert ['yellow', 'whitesmoke'] == cds.data['color']
dial.value = 75
assert ['red', 'whitesmoke'] == cds.data['color']
def test_dial_bounds():
dial = Dial(bounds=(0, 20))
with pytest.raises(ValueError):
dial.value = 100
def test_gauge_bounds():
dial = Gauge(bounds=(0, 20))
with pytest.raises(ValueError):
dial.value = 100
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2005-2018 Team Kodi
* This file is part of Kodi - https://kodi.tv
*
* SPDX-License-Identifier: GPL-2.0-or-later
* See LICENSES/README.md for more information.
*/
#pragma once
///////////////////////////////////////////////////////////////////////
// Tween.h
// A couple of tweening classes implemented in C++.
// ref: http://www.robertpenner.com/easing/
//
// Author: d4rk <[email protected]>
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// Current list of classes:
//
// LinearTweener
// QuadTweener
// CubicTweener
// SineTweener
// CircleTweener
// BackTweener
// BounceTweener
// ElasticTweener
//
///////////////////////////////////////////////////////////////////////
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846f
#endif
enum TweenerType
{
EASE_IN,
EASE_OUT,
EASE_INOUT
};
class Tweener
{
public:
explicit Tweener(TweenerType tweenerType = EASE_OUT) { m_tweenerType = tweenerType; }
virtual ~Tweener() = default;
void SetEasing(TweenerType type) { m_tweenerType = type; }
virtual float Tween(float time, float start, float change, float duration)=0;
virtual bool HasResumePoint() const { return m_tweenerType == EASE_INOUT; }
protected:
TweenerType m_tweenerType;
};
class LinearTweener : public Tweener
{
public:
float Tween(float time, float start, float change, float duration) override
{
return change * time / duration + start;
}
bool HasResumePoint() const override { return false; }
};
class QuadTweener : public Tweener
{
public:
explicit QuadTweener(float a = 1.0f) { _a=a; }
float Tween(float time, float start, float change, float duration) override
{
switch (m_tweenerType)
{
case EASE_IN:
time /= duration;
return change * time * (_a * time + 1 - _a) + start;
break;
case EASE_OUT:
time /= duration;
return -change * time * (_a * time - 1 - _a) + start;
break;
case EASE_INOUT:
time /= duration/2;
if (time < 1)
return (change) * time * (_a * time + 1 - _a) + start;
time--;
return (-change) * time * (_a * time - 1 - _a) + start;
break;
}
return change * time * time + start;
}
private:
float _a;
};
class CubicTweener : public Tweener
{
public:
float Tween(float time, float start, float change, float duration) override
{
switch (m_tweenerType)
{
case EASE_IN:
time /= duration;
return change * time * time * time + start;
break;
case EASE_OUT:
time /= duration;
time--;
return change * (time * time * time + 1) + start;
break;
case EASE_INOUT:
time /= duration/2;
if (time < 1)
return (change/2) * time * time * time + start;
time-=2;
return (change/2) * (time * time * time + 2) + start;
break;
}
return change * time * time + start;
}
};
class CircleTweener : public Tweener
{
public:
float Tween(float time, float start, float change, float duration) override
{
switch (m_tweenerType)
{
case EASE_IN:
time /= duration;
return (-change) * (sqrt(1 - time * time) - 1) + start;
break;
case EASE_OUT:
time /= duration;
time--;
return change * sqrt(1 - time * time) + start;
break;
case EASE_INOUT:
time /= duration/2;
if (time < 1)
return (-change/2) * (sqrt(1 - time * time) - 1) + start;
time-=2;
return change/2 * (sqrt(1 - time * time) + 1) + start;
break;
}
return change * sqrt(1 - time * time) + start;
}
};
class BackTweener : public Tweener
{
public:
explicit BackTweener(float s=1.70158) { _s=s; }
float Tween(float time, float start, float change, float duration) override
{
float s = _s;
switch (m_tweenerType)
{
case EASE_IN:
time /= duration;
return change * time * time * ((s + 1) * time - s) + start;
break;
case EASE_OUT:
time /= duration;
time--;
return change * (time * time * ((s + 1) * time + s) + 1) + start;
break;
case EASE_INOUT:
time /= duration/2;
s*=(1.525f);
if ((time ) < 1)
{
return (change/2) * (time * time * ((s + 1) * time - s)) + start;
}
time-=2;
return (change/2) * (time * time * ((s + 1) * time + s) + 2) + start;
break;
}
return change * ((time-1) * time * ((s + 1) * time + s) + 1) + start;
}
private:
float _s;
};
class SineTweener : public Tweener
{
public:
float Tween(float time, float start, float change, float duration) override
{
time /= duration;
switch (m_tweenerType)
{
case EASE_IN:
return change * (1 - cos(time * M_PI / 2.0f)) + start;
break;
case EASE_OUT:
return change * sin(time * M_PI / 2.0f) + start;
break;
case EASE_INOUT:
return change/2 * (1 - cos(M_PI * time)) + start;
break;
}
return (change/2) * (1 - cos(M_PI * time)) + start;
}
};
class BounceTweener : public Tweener
{
public:
float Tween(float time, float start, float change, float duration) override
{
switch (m_tweenerType)
{
case EASE_IN:
return (change - easeOut(duration - time, 0, change, duration)) + start;
break;
case EASE_OUT:
return easeOut(time, start, change, duration);
break;
case EASE_INOUT:
if (time < duration/2)
return (change - easeOut (duration - (time * 2), 0, change, duration) + start) * .5f + start;
else
return (easeOut (time * 2 - duration, 0, change, duration) * .5f + change * .5f) + start;
break;
}
return easeOut(time, start, change, duration);
}
protected:
static float easeOut(float time, float start, float change, float duration)
{
time /= duration;
if (time < (1/2.75)) {
return change * (7.5625f * time * time) + start;
} else if (time < (2/2.75)) {
time -= (1.5f/2.75f);
return change * (7.5625f * time * time + .75f) + start;
} else if (time < (2.5/2.75)) {
time -= (2.25f/2.75f);
return change * (7.5625f * time * time + .9375f) + start;
} else {
time -= (2.625f/2.75f);
return change * (7.5625f * time * time + .984375f) + start;
}
}
};
class ElasticTweener : public Tweener
{
public:
ElasticTweener(float a=0.0, float p=0.0) { _a=a; _p=p; }
float Tween(float time, float start, float change, float duration) override
{
switch (m_tweenerType)
{
case EASE_IN:
return easeIn(time, start, change, duration);
break;
case EASE_OUT:
return easeOut(time, start, change, duration);
break;
case EASE_INOUT:
return easeInOut(time, start, change, duration);
break;
}
return easeOut(time, start, change, duration);
}
protected:
float _a;
float _p;
float easeIn(float time, float start, float change, float duration) const
{
float s=0;
float a=_a;
float p=_p;
if (time==0)
return start;
time /= duration;
if (time==1)
return start + change;
if (!p)
p=duration*.3f;
if (!a || a < fabs(change))
{
a = change;
s = p / 4.0f;
}
else
{
s = p / (2 * M_PI) * asin (change / a);
}
time--;
return -(a * pow(2.0f, 10*time) * sin((time * duration - s) * (2 * M_PI) / p )) + start;
}
float easeOut(float time, float start, float change, float duration) const
{
float s=0;
float a=_a;
float p=_p;
if (time==0)
return start;
time /= duration;
if (time==1)
return start + change;
if (!p)
p=duration*.3f;
if (!a || a < fabs(change))
{
a = change;
s = p / 4.0f;
}
else
{
s = p / (2 * M_PI) * asin (change / a);
}
return (a * pow(2.0f, -10*time) * sin((time * duration - s) * (2 * M_PI) / p )) + change + start;
}
float easeInOut(float time, float start, float change, float duration) const
{
float s=0;
float a=_a;
float p=_p;
if (time==0)
return start;
time /= duration/2;
if (time==2)
return start + change;
if (!p)
p=duration*.3f*1.5f;
if (!a || a < fabs(change))
{
a = change;
s = p / 4.0f;
}
else
{
s = p / (2 * M_PI) * asin (change / a);
}
if (time < 1)
{
time--;
return -.5f * (a * pow(2.0f, 10 * (time)) * sin((time * duration - s) * (2 * M_PI) / p )) + start;
}
time--;
return a * pow(2.0f, -10 * (time)) * sin((time * duration-s) * (2 * M_PI) / p ) * .5f + change + start;
}
};
| {
"pile_set_name": "Github"
} |
// @flow
import Point from '@mapbox/point-geometry';
import clipLine from './clip_line';
import PathInterpolator from './path_interpolator';
import * as intersectionTests from '../util/intersection_tests';
import Grid from './grid_index';
import {mat4} from 'gl-matrix';
import ONE_EM from '../symbol/one_em';
import assert from 'assert';
import * as projection from '../symbol/projection';
import type Transform from '../geo/transform';
import type {SingleCollisionBox} from '../data/bucket/symbol_bucket';
import type {
GlyphOffsetArray,
SymbolLineVertexArray
} from '../data/array_types';
// When a symbol crosses the edge that causes it to be included in
// collision detection, it will cause changes in the symbols around
// it. This constant specifies how many pixels to pad the edge of
// the viewport for collision detection so that the bulk of the changes
// occur offscreen. Making this constant greater increases label
// stability, but it's expensive.
const viewportPadding = 100;
/**
* A collision index used to prevent symbols from overlapping. It keep tracks of
* where previous symbols have been placed and is used to check if a new
* symbol overlaps with any previously added symbols.
*
* There are two steps to insertion: first placeCollisionBox/Circles checks if
* there's room for a symbol, then insertCollisionBox/Circles actually puts the
* symbol in the index. The two step process allows paired symbols to be inserted
* together even if they overlap.
*
* @private
*/
class CollisionIndex {
grid: Grid;
ignoredGrid: Grid;
transform: Transform;
pitchfactor: number;
screenRightBoundary: number;
screenBottomBoundary: number;
gridRightBoundary: number;
gridBottomBoundary: number;
constructor(
transform: Transform,
grid: Grid = new Grid(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25),
ignoredGrid: Grid = new Grid(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25)
) {
this.transform = transform;
this.grid = grid;
this.ignoredGrid = ignoredGrid;
this.pitchfactor = Math.cos(transform._pitch) * transform.cameraToCenterDistance;
this.screenRightBoundary = transform.width + viewportPadding;
this.screenBottomBoundary = transform.height + viewportPadding;
this.gridRightBoundary = transform.width + 2 * viewportPadding;
this.gridBottomBoundary = transform.height + 2 * viewportPadding;
}
placeCollisionBox(collisionBox: SingleCollisionBox, allowOverlap: boolean, textPixelRatio: number, posMatrix: mat4, collisionGroupPredicate?: any): { box: Array<number>, offscreen: boolean } {
const projectedPoint = this.projectAndGetPerspectiveRatio(posMatrix, collisionBox.anchorPointX, collisionBox.anchorPointY);
const tileToViewport = textPixelRatio * projectedPoint.perspectiveRatio;
const tlX = collisionBox.x1 * tileToViewport + projectedPoint.point.x;
const tlY = collisionBox.y1 * tileToViewport + projectedPoint.point.y;
const brX = collisionBox.x2 * tileToViewport + projectedPoint.point.x;
const brY = collisionBox.y2 * tileToViewport + projectedPoint.point.y;
if (!this.isInsideGrid(tlX, tlY, brX, brY) ||
(!allowOverlap && this.grid.hitTest(tlX, tlY, brX, brY, collisionGroupPredicate))) {
return {
box: [],
offscreen: false
};
}
return {
box: [tlX, tlY, brX, brY],
offscreen: this.isOffscreen(tlX, tlY, brX, brY)
};
}
placeCollisionCircles(allowOverlap: boolean,
symbol: any,
lineVertexArray: SymbolLineVertexArray,
glyphOffsetArray: GlyphOffsetArray,
fontSize: number,
posMatrix: mat4,
labelPlaneMatrix: mat4,
labelToScreenMatrix?: mat4,
showCollisionCircles: boolean,
pitchWithMap: boolean,
collisionGroupPredicate?: any,
circlePixelDiameter: number,
textPixelPadding: number): { circles: Array<number>, offscreen: boolean, collisionDetected: boolean } {
const placedCollisionCircles = [];
const tileUnitAnchorPoint = new Point(symbol.anchorX, symbol.anchorY);
const screenAnchorPoint = projection.project(tileUnitAnchorPoint, posMatrix);
const perspectiveRatio = projection.getPerspectiveRatio(this.transform.cameraToCenterDistance, screenAnchorPoint.signedDistanceFromCamera);
const labelPlaneFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio;
const labelPlaneFontScale = labelPlaneFontSize / ONE_EM;
const labelPlaneAnchorPoint = projection.project(tileUnitAnchorPoint, labelPlaneMatrix).point;
const projectionCache = {};
const lineOffsetX = symbol.lineOffsetX * labelPlaneFontScale;
const lineOffsetY = symbol.lineOffsetY * labelPlaneFontScale;
const firstAndLastGlyph = projection.placeFirstAndLastGlyph(
labelPlaneFontScale,
glyphOffsetArray,
lineOffsetX,
lineOffsetY,
/*flip*/ false,
labelPlaneAnchorPoint,
tileUnitAnchorPoint,
symbol,
lineVertexArray,
labelPlaneMatrix,
projectionCache);
let collisionDetected = false;
let inGrid = false;
let entirelyOffscreen = true;
if (firstAndLastGlyph) {
const radius = circlePixelDiameter * 0.5 * perspectiveRatio + textPixelPadding;
const screenPlaneMin = new Point(-viewportPadding, -viewportPadding);
const screenPlaneMax = new Point(this.screenRightBoundary, this.screenBottomBoundary);
const interpolator = new PathInterpolator();
// Construct a projected path from projected line vertices. Anchor points are ignored and removed
const first = firstAndLastGlyph.first;
const last = firstAndLastGlyph.last;
let projectedPath = [];
for (let i = first.path.length - 1; i >= 1; i--) {
projectedPath.push(first.path[i]);
}
for (let i = 1; i < last.path.length; i++) {
projectedPath.push(last.path[i]);
}
assert(projectedPath.length >= 2);
// Tolerate a slightly longer distance than one diameter between two adjacent circles
const circleDist = radius * 2.5;
// The path might need to be converted into screen space if a pitched map is used as the label space
if (labelToScreenMatrix) {
const screenSpacePath = projectedPath.map(p => projection.project(p, labelToScreenMatrix));
// Do not try to place collision circles if even of the points is behind the camera.
// This is a plausible scenario with big camera pitch angles
if (screenSpacePath.some(point => point.signedDistanceFromCamera <= 0)) {
projectedPath = [];
} else {
projectedPath = screenSpacePath.map(p => p.point);
}
}
let segments = [];
if (projectedPath.length > 0) {
// Quickly check if the path is fully inside or outside of the padded collision region.
// For overlapping paths we'll only create collision circles for the visible segments
const minPoint = projectedPath[0].clone();
const maxPoint = projectedPath[0].clone();
for (let i = 1; i < projectedPath.length; i++) {
minPoint.x = Math.min(minPoint.x, projectedPath[i].x);
minPoint.y = Math.min(minPoint.y, projectedPath[i].y);
maxPoint.x = Math.max(maxPoint.x, projectedPath[i].x);
maxPoint.y = Math.max(maxPoint.y, projectedPath[i].y);
}
if (minPoint.x >= screenPlaneMin.x && maxPoint.x <= screenPlaneMax.x &&
minPoint.y >= screenPlaneMin.y && maxPoint.y <= screenPlaneMax.y) {
// Quad fully visible
segments = [projectedPath];
} else if (maxPoint.x < screenPlaneMin.x || minPoint.x > screenPlaneMax.x ||
maxPoint.y < screenPlaneMin.y || minPoint.y > screenPlaneMax.y) {
// Not visible
segments = [];
} else {
segments = clipLine([projectedPath], screenPlaneMin.x, screenPlaneMin.y, screenPlaneMax.x, screenPlaneMax.y);
}
}
for (const seg of segments) {
// interpolate positions for collision circles. Add a small padding to both ends of the segment
assert(seg.length > 0);
interpolator.reset(seg, radius * 0.25);
let numCircles = 0;
if (interpolator.length <= 0.5 * radius) {
numCircles = 1;
} else {
numCircles = Math.ceil(interpolator.paddedLength / circleDist) + 1;
}
for (let i = 0; i < numCircles; i++) {
const t = i / Math.max(numCircles - 1, 1);
const circlePosition = interpolator.lerp(t);
// add viewport padding to the position and perform initial collision check
const centerX = circlePosition.x + viewportPadding;
const centerY = circlePosition.y + viewportPadding;
placedCollisionCircles.push(centerX, centerY, radius, 0);
const x1 = centerX - radius;
const y1 = centerY - radius;
const x2 = centerX + radius;
const y2 = centerY + radius;
entirelyOffscreen = entirelyOffscreen && this.isOffscreen(x1, y1, x2, y2);
inGrid = inGrid || this.isInsideGrid(x1, y1, x2, y2);
if (!allowOverlap) {
if (this.grid.hitTestCircle(centerX, centerY, radius, collisionGroupPredicate)) {
// Don't early exit if we're showing the debug circles because we still want to calculate
// which circles are in use
collisionDetected = true;
if (!showCollisionCircles) {
return {
circles: [],
offscreen: false,
collisionDetected
};
}
}
}
}
}
}
return {
circles: ((!showCollisionCircles && collisionDetected) || !inGrid) ? [] : placedCollisionCircles,
offscreen: entirelyOffscreen,
collisionDetected
};
}
/**
* Because the geometries in the CollisionIndex are an approximation of the shape of
* symbols on the map, we use the CollisionIndex to look up the symbol part of
* `queryRenderedFeatures`.
*
* @private
*/
queryRenderedSymbols(viewportQueryGeometry: Array<Point>) {
if (viewportQueryGeometry.length === 0 || (this.grid.keysLength() === 0 && this.ignoredGrid.keysLength() === 0)) {
return {};
}
const query = [];
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (const point of viewportQueryGeometry) {
const gridPoint = new Point(point.x + viewportPadding, point.y + viewportPadding);
minX = Math.min(minX, gridPoint.x);
minY = Math.min(minY, gridPoint.y);
maxX = Math.max(maxX, gridPoint.x);
maxY = Math.max(maxY, gridPoint.y);
query.push(gridPoint);
}
const features = this.grid.query(minX, minY, maxX, maxY)
.concat(this.ignoredGrid.query(minX, minY, maxX, maxY));
const seenFeatures = {};
const result = {};
for (const feature of features) {
const featureKey = feature.key;
// Skip already seen features.
if (seenFeatures[featureKey.bucketInstanceId] === undefined) {
seenFeatures[featureKey.bucketInstanceId] = {};
}
if (seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex]) {
continue;
}
// Check if query intersects with the feature box
// "Collision Circles" for line labels are treated as boxes here
// Since there's no actual collision taking place, the circle vs. square
// distinction doesn't matter as much, and box geometry is easier
// to work with.
const bbox = [
new Point(feature.x1, feature.y1),
new Point(feature.x2, feature.y1),
new Point(feature.x2, feature.y2),
new Point(feature.x1, feature.y2)
];
if (!intersectionTests.polygonIntersectsPolygon(query, bbox)) {
continue;
}
seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex] = true;
if (result[featureKey.bucketInstanceId] === undefined) {
result[featureKey.bucketInstanceId] = [];
}
result[featureKey.bucketInstanceId].push(featureKey.featureIndex);
}
return result;
}
insertCollisionBox(collisionBox: Array<number>, ignorePlacement: boolean, bucketInstanceId: number, featureIndex: number, collisionGroupID: number) {
const grid = ignorePlacement ? this.ignoredGrid : this.grid;
const key = {bucketInstanceId, featureIndex, collisionGroupID};
grid.insert(key, collisionBox[0], collisionBox[1], collisionBox[2], collisionBox[3]);
}
insertCollisionCircles(collisionCircles: Array<number>, ignorePlacement: boolean, bucketInstanceId: number, featureIndex: number, collisionGroupID: number) {
const grid = ignorePlacement ? this.ignoredGrid : this.grid;
const key = {bucketInstanceId, featureIndex, collisionGroupID};
for (let k = 0; k < collisionCircles.length; k += 4) {
grid.insertCircle(key, collisionCircles[k], collisionCircles[k + 1], collisionCircles[k + 2]);
}
}
projectAndGetPerspectiveRatio(posMatrix: mat4, x: number, y: number) {
const p = [x, y, 0, 1];
projection.xyTransformMat4(p, p, posMatrix);
const a = new Point(
(((p[0] / p[3] + 1) / 2) * this.transform.width) + viewportPadding,
(((-p[1] / p[3] + 1) / 2) * this.transform.height) + viewportPadding
);
return {
point: a,
// See perspective ratio comment in symbol_sdf.vertex
// We're doing collision detection in viewport space so we need
// to scale down boxes in the distance
perspectiveRatio: 0.5 + 0.5 * (this.transform.cameraToCenterDistance / p[3])
};
}
isOffscreen(x1: number, y1: number, x2: number, y2: number) {
return x2 < viewportPadding || x1 >= this.screenRightBoundary || y2 < viewportPadding || y1 > this.screenBottomBoundary;
}
isInsideGrid(x1: number, y1: number, x2: number, y2: number) {
return x2 >= 0 && x1 < this.gridRightBoundary && y2 >= 0 && y1 < this.gridBottomBoundary;
}
/*
* Returns a matrix for transforming collision shapes to viewport coordinate space.
* Use this function to render e.g. collision circles on the screen.
* example transformation: clipPos = glCoordMatrix * viewportMatrix * circle_pos
*/
getViewportMatrix(): mat4 {
const m = mat4.identity([]);
mat4.translate(m, m, [-viewportPadding, -viewportPadding, 0.0]);
return m;
}
}
export default CollisionIndex;
| {
"pile_set_name": "Github"
} |
<!doctype html>
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js"></script>
<script src="../morris.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/prettify/r224/prettify.min.js"></script>
<script src="lib/example.js"></script>
<link rel="stylesheet" href="lib/example.css">
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/prettify/r224/prettify.min.css">
<link rel="stylesheet" href="../morris.css">
</head>
<body>
<h1>Formatting Dates YYYY</h1>
<div id="graph"></div>
<pre id="code" class="prettyprint linenums">
/* data stolen from http://howmanyleft.co.uk/vehicle/jaguar_'e'_type */
var year_data = [
{"period": "2012", "licensed": 3407, "sorned": 660},
{"period": "2011", "licensed": 3351, "sorned": 629},
{"period": "2010", "licensed": 3269, "sorned": 618},
{"period": "2009", "licensed": 3246, "sorned": 661},
{"period": "2008", "licensed": 3257, "sorned": 667},
{"period": "2007", "licensed": 3248, "sorned": 627},
{"period": "2006", "licensed": 3171, "sorned": 660},
{"period": "2005", "licensed": 3171, "sorned": 676},
{"period": "2004", "licensed": 3201, "sorned": 656},
{"period": "2003", "licensed": 3215, "sorned": 622}
];
Morris.Line({
element: 'graph',
data: year_data,
xkey: 'period',
ykeys: ['licensed', 'sorned'],
labels: ['Licensed', 'SORN']
});
</pre>
</body>
| {
"pile_set_name": "Github"
} |
/* Copyright (c) 2010-2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* 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.
*
*/
#include <linux/unistd.h>
#include <media/msm/vidc_type.h>
#include "vidc.h"
#if DEBUG
#define DBG(x...) printk(KERN_DEBUG x)
#else
#define DBG(x...)
#endif
#define VIDC_720P_VERSION_STRING "VIDC_V1.0"
u8 *vidc_base_addr;
#ifdef VIDC_REGISTER_LOG_INTO_BUFFER
char vidclog[VIDC_REGLOG_BUFSIZE];
unsigned int vidclog_index;
#endif
void vidc_720p_set_device_virtual_base(u8 *core_virtual_base_addr)
{
vidc_base_addr = core_virtual_base_addr;
}
void vidc_720p_init(char **ppsz_version, u32 i_firmware_size,
u32 *pi_firmware_address,
enum vidc_720p_endian dma_endian,
u32 interrupt_off,
enum vidc_720p_interrupt_level_selection
interrupt_sel, u32 interrupt_mask)
{
if (ppsz_version)
*ppsz_version = VIDC_720P_VERSION_STRING;
if (interrupt_sel == VIDC_720P_INTERRUPT_LEVEL_SEL)
VIDC_IO_OUT(REG_491082, 0);
else
VIDC_IO_OUT(REG_491082, 1);
if (interrupt_off)
VIDC_IO_OUT(REG_609676, 1);
else
VIDC_IO_OUT(REG_609676, 0);
VIDC_IO_OUT(REG_614776, 1);
VIDC_IO_OUT(REG_418173, 0);
VIDC_IO_OUT(REG_418173, interrupt_mask);
VIDC_IO_OUT(REG_736316, dma_endian);
VIDC_IO_OUT(REG_215724, 0);
VIDC_IO_OUT(REG_361582, 1);
VIDC_IO_OUT(REG_591577, i_firmware_size);
VIDC_IO_OUT(REG_203921, pi_firmware_address);
VIDC_IO_OUT(REG_531515_ADDR, 0);
VIDC_IO_OUT(REG_614413, 1);
}
u32 vidc_720p_do_sw_reset(void)
{
u32 fw_start = 0;
VIDC_BUSY_WAIT(5);
VIDC_IO_OUT(REG_224135, 0);
VIDC_BUSY_WAIT(5);
VIDC_IO_OUT(REG_193553, 0);
VIDC_BUSY_WAIT(5);
VIDC_IO_OUT(REG_141269, 1);
VIDC_BUSY_WAIT(15);
VIDC_IO_OUT(REG_141269, 0);
VIDC_BUSY_WAIT(5);
VIDC_IO_IN(REG_193553, &fw_start);
if (!fw_start) {
DBG("\n VIDC-SW-RESET-FAILS!");
return false;
}
return true;
}
u32 vidc_720p_reset_is_success()
{
u32 stagecounter = 0;
VIDC_IO_IN(REG_352831, &stagecounter);
stagecounter &= 0xff;
if (stagecounter != 0xe5) {
DBG("\n VIDC-CPU_RESET-FAILS!");
VIDC_IO_OUT(REG_224135, 0);
msleep(10);
return false;
}
return true;
}
void vidc_720p_start_cpu(enum vidc_720p_endian dma_endian,
u32 *icontext_bufferstart,
u32 *debug_core_dump_addr,
u32 debug_buffer_size)
{
u32 dbg_info_input0_reg = 0x1;
VIDC_IO_OUT(REG_361582, 0);
VIDC_IO_OUT(REG_958768, icontext_bufferstart);
VIDC_IO_OUT(REG_736316, dma_endian);
if (debug_buffer_size) {
dbg_info_input0_reg = (debug_buffer_size << 0x10)
| (0x2 << 1) | 0x1;
VIDC_IO_OUT(REG_166247, debug_core_dump_addr);
}
VIDC_IO_OUT(REG_699747, dbg_info_input0_reg);
VIDC_IO_OUT(REG_224135, 1);
}
u32 vidc_720p_cpu_start()
{
u32 fw_status = 0x0;
VIDC_IO_IN(REG_381535, &fw_status);
if (fw_status != 0x02)
return false;
return true;
}
void vidc_720p_stop_fw(void)
{
VIDC_IO_OUT(REG_193553, 0);
VIDC_IO_OUT(REG_224135, 0);
}
void vidc_720p_get_interrupt_status(u32 *interrupt_status,
u32 *cmd_err_status, u32 *disp_pic_err_status, u32 *op_failed)
{
u32 err_status;
VIDC_IO_IN(REG_512143, interrupt_status);
VIDC_IO_IN(REG_300310, &err_status);
*cmd_err_status = err_status & 0xffff;
*disp_pic_err_status = (err_status & 0xffff0000) >> 16;
VIDC_IO_INF(REG_724381, OPERATION_FAILED, \
op_failed);
}
void vidc_720p_interrupt_done_clear(void)
{
VIDC_IO_OUT(REG_614776, 1);
VIDC_IO_OUT(REG_97293, 4);
}
void vidc_720p_submit_command(u32 ch_id, u32 cmd_id)
{
u32 fw_status;
VIDC_IO_OUT(REG_97293, ch_id);
VIDC_IO_OUT(REG_62325, cmd_id);
VIDC_DEBUG_REGISTER_LOG;
VIDC_IO_IN(REG_381535, &fw_status);
VIDC_IO_OUT(REG_926519, fw_status);
}
u32 vidc_720p_engine_reset(u32 ch_id,
enum vidc_720p_endian dma_endian,
enum vidc_720p_interrupt_level_selection interrupt_sel,
u32 interrupt_mask
)
{
u32 op_done = 0;
u32 counter = 0;
VIDC_LOGERR_STRING("ENG-RESET!!");
/* issue the engine reset command */
vidc_720p_submit_command(ch_id, VIDC_720P_CMD_MFC_ENGINE_RESET);
do {
VIDC_BUSY_WAIT(20);
VIDC_IO_IN(REG_982553, &op_done);
counter++;
} while (!op_done && counter < 10);
if (!op_done) {
/* Reset fails */
return false ;
}
/* write invalid channel id */
VIDC_IO_OUT(REG_97293, 4);
/* Set INT_PULSE_SEL */
if (interrupt_sel == VIDC_720P_INTERRUPT_LEVEL_SEL)
VIDC_IO_OUT(REG_491082, 0);
else
VIDC_IO_OUT(REG_491082, 1);
if (!interrupt_mask) {
/* Disable interrupt */
VIDC_IO_OUT(REG_609676, 1);
} else {
/* Enable interrupt */
VIDC_IO_OUT(REG_609676, 0);
}
/* Clear any pending interrupt */
VIDC_IO_OUT(REG_614776, 1);
/* Set INT_ENABLE_REG */
VIDC_IO_OUT(REG_418173, interrupt_mask);
/*Sets the DMA endianness */
VIDC_IO_OUT(REG_736316, dma_endian);
/*Restore ARM endianness */
VIDC_IO_OUT(REG_215724, 0);
/* retun engine reset success */
return true ;
}
void vidc_720p_set_channel(u32 i_ch_id,
enum vidc_720p_enc_dec_selection
enc_dec_sel, enum vidc_720p_codec codec,
u32 *pi_fw, u32 i_firmware_size)
{
u32 std_sel = 0;
VIDC_IO_OUT(REG_661565, 0);
if (enc_dec_sel)
std_sel = VIDC_REG_713080_ENC_ON_BMSK;
std_sel |= (u32) codec;
VIDC_IO_OUT(REG_713080, std_sel);
switch (codec) {
default:
case VIDC_720P_DIVX:
case VIDC_720P_XVID:
case VIDC_720P_MPEG4:
{
if (enc_dec_sel == VIDC_720P_ENCODER)
VIDC_IO_OUT(REG_765787, pi_fw);
else
VIDC_IO_OUT(REG_225040, pi_fw);
break;
}
case VIDC_720P_H264:
{
if (enc_dec_sel == VIDC_720P_ENCODER)
VIDC_IO_OUT(REG_942456, pi_fw);
else
VIDC_IO_OUT(REG_942170_ADDR_3, pi_fw);
break;
}
case VIDC_720P_H263:
{
if (enc_dec_sel == VIDC_720P_ENCODER)
VIDC_IO_OUT(REG_765787, pi_fw);
else
VIDC_IO_OUT(REG_942170_ADDR_6, pi_fw);
break;
}
case VIDC_720P_VC1:
{
VIDC_IO_OUT(REG_880188, pi_fw);
break;
}
case VIDC_720P_MPEG2:
{
VIDC_IO_OUT(REG_40293, pi_fw);
break;
}
}
VIDC_IO_OUT(REG_591577, i_firmware_size);
vidc_720p_submit_command(i_ch_id, VIDC_720P_CMD_CHSET);
}
void vidc_720p_encode_set_profile(u32 i_profile, u32 i_level)
{
u32 profile_level = i_profile|(i_level << 0x8);
VIDC_IO_OUT(REG_839021, profile_level);
}
void vidc_720p_set_frame_size(u32 i_size_x, u32 i_size_y)
{
VIDC_IO_OUT(REG_999267, i_size_x);
VIDC_IO_OUT(REG_345712, i_size_y);
}
void vidc_720p_encode_set_fps(u32 i_rc_frame_rate)
{
VIDC_IO_OUT(REG_625444, i_rc_frame_rate);
}
void vidc_720p_encode_set_short_header(u32 i_short_header)
{
VIDC_IO_OUT(REG_314290, i_short_header);
}
void vidc_720p_encode_set_vop_time(u32 vop_time_resolution,
u32 vop_time_increment)
{
u32 enable_vop, vop_timing_reg;
if (!vop_time_resolution)
VIDC_IO_OUT(REG_64895, 0x0);
else {
enable_vop = 0x1;
vop_timing_reg = (enable_vop << 0x1f) |
(vop_time_resolution << 0x10) | vop_time_increment;
VIDC_IO_OUT(REG_64895, vop_timing_reg);
}
}
void vidc_720p_encode_set_hec_period(u32 hec_period)
{
VIDC_IO_OUT(REG_407718, hec_period);
}
void vidc_720p_encode_set_qp_params(u32 i_max_qp, u32 i_min_qp)
{
u32 qp = i_min_qp | (i_max_qp << 0x8);
VIDC_IO_OUT(REG_734318, qp);
}
void vidc_720p_encode_set_rc_config(u32 enable_frame_level_rc,
u32 enable_mb_level_rc_flag,
u32 i_frame_qp, u32 pframe_qp)
{
u32 rc_config = i_frame_qp;
if (enable_frame_level_rc)
rc_config |= (0x1 << 0x9);
if (enable_mb_level_rc_flag)
rc_config |= (0x1 << 0x8);
VIDC_IO_OUT(REG_58211, rc_config);
VIDC_IO_OUT(REG_548359, pframe_qp);
}
void vidc_720p_encode_set_bit_rate(u32 i_target_bitrate)
{
VIDC_IO_OUT(REG_174150, i_target_bitrate);
}
void vidc_720p_encoder_set_param_change(u32 enc_param_change)
{
VIDC_IO_OUT(REG_804959, enc_param_change);
}
void vidc_720p_encode_set_control_param(u32 param_val)
{
VIDC_IO_OUT(REG_128234, param_val);
}
void vidc_720p_encode_set_frame_level_rc_params(u32 i_reaction_coeff)
{
VIDC_IO_OUT(REG_677784, i_reaction_coeff);
}
void vidc_720p_encode_set_mb_level_rc_params(u32 dark_region_as_flag,
u32 smooth_region_as_flag,
u32 static_region_as_flag,
u32 activity_region_flag)
{
u32 mb_level_rc = 0x0;
if (activity_region_flag)
mb_level_rc |= 0x1;
if (static_region_as_flag)
mb_level_rc |= (0x1 << 0x1);
if (smooth_region_as_flag)
mb_level_rc |= (0x1 << 0x2);
if (dark_region_as_flag)
mb_level_rc |= (0x1 << 0x3);
/* Write MB level rate control */
VIDC_IO_OUT(REG_995041, mb_level_rc);
}
void vidc_720p_encode_set_entropy_control(enum vidc_720p_entropy_sel
entropy_sel,
enum vidc_720p_cabac_model
cabac_model_number)
{
u32 num;
u32 entropy_params = (u32)entropy_sel;
/* Set Model Number */
if (entropy_sel == VIDC_720P_ENTROPY_SEL_CABAC) {
num = (u32)cabac_model_number;
entropy_params |= (num << 0x2);
}
/* Set Entropy parameters */
VIDC_IO_OUT(REG_504878, entropy_params);
}
void vidc_720p_encode_set_db_filter_control(enum vidc_720p_DBConfig
db_config,
u32 i_slice_alpha_offset,
u32 i_slice_beta_offset)
{
u32 deblock_params;
deblock_params = (u32)db_config;
deblock_params |=
((i_slice_beta_offset << 0x2) | (i_slice_alpha_offset << 0x7));
/* Write deblocking control settings */
VIDC_IO_OUT(REG_458130, deblock_params);
}
void vidc_720p_encode_set_intra_refresh_mb_number(u32 i_cir_mb_number)
{
VIDC_IO_OUT(REG_857491, i_cir_mb_number);
}
void vidc_720p_encode_set_multi_slice_info(enum
vidc_720p_MSlice_selection
m_slice_sel,
u32 multi_slice_size)
{
switch (m_slice_sel) {
case VIDC_720P_MSLICE_BY_MB_COUNT:
{
VIDC_IO_OUT(REG_588301, 0x1);
VIDC_IO_OUT(REG_1517, m_slice_sel);
VIDC_IO_OUT(REG_105335, multi_slice_size);
break;
}
case VIDC_720P_MSLICE_BY_BYTE_COUNT:
{
VIDC_IO_OUT(REG_588301, 0x1);
VIDC_IO_OUT(REG_1517, m_slice_sel);
VIDC_IO_OUT(REG_561679, multi_slice_size);
break;
}
case VIDC_720P_MSLICE_BY_GOB:
{
VIDC_IO_OUT(REG_588301, 0x1);
break;
}
default:
case VIDC_720P_MSLICE_OFF:
{
VIDC_IO_OUT(REG_588301, 0x0);
break;
}
}
}
void vidc_720p_encode_set_dpb_buffer(u32 *pi_enc_dpb_addr, u32 alloc_len)
{
VIDC_IO_OUT(REG_341928_ADDR, pi_enc_dpb_addr);
VIDC_IO_OUT(REG_319934, alloc_len);
}
void vidc_720p_encode_set_i_period(u32 i_i_period)
{
VIDC_IO_OUT(REG_950374, i_i_period);
}
void vidc_720p_encode_init_codec(u32 i_ch_id,
enum vidc_720p_memory_access_method
memory_access_model)
{
VIDC_IO_OUT(REG_841539, memory_access_model);
vidc_720p_submit_command(i_ch_id, VIDC_720P_CMD_INITCODEC);
}
void vidc_720p_encode_unalign_bitstream(u32 upper_unalign_word,
u32 lower_unalign_word)
{
VIDC_IO_OUT(REG_792026, upper_unalign_word);
VIDC_IO_OUT(REG_844152, lower_unalign_word);
}
void vidc_720p_encode_set_seq_header_buffer(u32 ext_buffer_start,
u32 ext_buffer_end,
u32 start_byte_num)
{
VIDC_IO_OUT(REG_275113_ADDR, ext_buffer_start);
VIDC_IO_OUT(REG_87912, ext_buffer_start);
VIDC_IO_OUT(REG_988007_ADDR, ext_buffer_end);
VIDC_IO_OUT(REG_66693, start_byte_num);
}
void vidc_720p_encode_frame(u32 ch_id,
u32 ext_buffer_start,
u32 ext_buffer_end,
u32 start_byte_number, u32 y_addr,
u32 c_addr)
{
VIDC_IO_OUT(REG_275113_ADDR, ext_buffer_start);
VIDC_IO_OUT(REG_988007_ADDR, ext_buffer_end);
VIDC_IO_OUT(REG_87912, ext_buffer_start);
VIDC_IO_OUT(REG_66693, start_byte_number);
VIDC_IO_OUT(REG_99105, y_addr);
VIDC_IO_OUT(REG_777113_ADDR, c_addr);
vidc_720p_submit_command(ch_id, VIDC_720P_CMD_FRAMERUN);
}
void vidc_720p_encode_get_header(u32 *pi_enc_header_size)
{
VIDC_IO_IN(REG_114286, pi_enc_header_size);
}
void vidc_720p_enc_frame_info(struct vidc_720p_enc_frame_info
*enc_frame_info)
{
VIDC_IO_IN(REG_782249, &enc_frame_info->enc_size);
VIDC_IO_IN(REG_441270, &enc_frame_info->frame);
enc_frame_info->frame &= 0x03;
VIDC_IO_IN(REG_613254,
&enc_frame_info->metadata_exists);
}
void vidc_720p_decode_bitstream_header(u32 ch_id,
u32 dec_unit_size,
u32 start_byte_num,
u32 ext_buffer_start,
u32 ext_buffer_end,
enum
vidc_720p_memory_access_method
memory_access_model,
u32 decode_order)
{
VIDC_IO_OUT(REG_965480, decode_order);
VIDC_IO_OUT(REG_639999, 0x8080);
VIDC_IO_OUT(REG_275113_ADDR, ext_buffer_start);
VIDC_IO_OUT(REG_988007_ADDR, ext_buffer_end);
VIDC_IO_OUT(REG_87912, ext_buffer_end);
VIDC_IO_OUT(REG_761892, dec_unit_size);
VIDC_IO_OUT(REG_66693, start_byte_num);
VIDC_IO_OUT(REG_841539, memory_access_model);
vidc_720p_submit_command(ch_id, VIDC_720P_CMD_INITCODEC);
}
void vidc_720p_decode_get_seq_hdr_info(struct vidc_720p_seq_hdr_info
*seq_hdr_info)
{
u32 display_status;
VIDC_IO_IN(REG_999267, &seq_hdr_info->img_size_x);
VIDC_IO_IN(REG_345712, &seq_hdr_info->img_size_y);
VIDC_IO_IN(REG_257463, &seq_hdr_info->min_num_dpb);
VIDC_IO_IN(REG_854281, &seq_hdr_info->min_dpb_size);
VIDC_IO_IN(REG_580603, &seq_hdr_info->dec_frm_size);
VIDC_IO_INF(REG_606447, DISP_PIC_PROFILE,
&seq_hdr_info->profile);
VIDC_IO_INF(REG_606447, DIS_PIC_LEVEL,
&seq_hdr_info->level);
VIDC_IO_INF(REG_612715, DISPLAY_STATUS,
&display_status);
seq_hdr_info->progressive =
((display_status & 0x4) >> 2);
/* bit 3 is for crop existence */
seq_hdr_info->crop_exists = ((display_status & 0x8) >> 3);
if (seq_hdr_info->crop_exists) {
/* read the cropping information */
VIDC_IO_INF(REG_881638, CROP_RIGHT_OFFSET, \
&seq_hdr_info->crop_right_offset);
VIDC_IO_INF(REG_881638, CROP_LEFT_OFFSET, \
&seq_hdr_info->crop_left_offset);
VIDC_IO_INF(REG_161486, CROP_BOTTOM_OFFSET, \
&seq_hdr_info->crop_bottom_offset);
VIDC_IO_INF(REG_161486, CROP_TOP_OFFSET, \
&seq_hdr_info->crop_top_offset);
}
/* Read the MPEG4 data partitioning indication */
VIDC_IO_INF(REG_441270, DATA_PARTITIONED, \
&seq_hdr_info->data_partitioned);
}
void vidc_720p_decode_set_dpb_release_buffer_mask(u32
i_dpb_release_buffer_mask)
{
VIDC_IO_OUT(REG_603032, i_dpb_release_buffer_mask);
}
void vidc_720p_decode_set_dpb_buffers(u32 i_buf_index, u32 *pi_dpb_buffer)
{
VIDC_IO_OUTI(REG_615716, i_buf_index, pi_dpb_buffer);
}
void vidc_720p_decode_set_comv_buffer(u32 *pi_dpb_comv_buffer,
u32 alloc_len)
{
VIDC_IO_OUT(REG_456376_ADDR, pi_dpb_comv_buffer);
VIDC_IO_OUT(REG_490443, alloc_len);
}
void vidc_720p_decode_set_dpb_details(u32 num_dpb, u32 alloc_len,
u32 *ref_buffer)
{
VIDC_IO_OUT(REG_518133, ref_buffer);
VIDC_IO_OUT(REG_267567, 0);
VIDC_IO_OUT(REG_883500, num_dpb);
VIDC_IO_OUT(REG_319934, alloc_len);
}
void vidc_720p_decode_set_mpeg4Post_filter(u32 enable_post_filter)
{
if (enable_post_filter)
VIDC_IO_OUT(REG_443811, 0x1);
else
VIDC_IO_OUT(REG_443811, 0x0);
}
void vidc_720p_decode_set_error_control(u32 enable_error_control)
{
if (enable_error_control)
VIDC_IO_OUT(REG_846346, 0);
else
VIDC_IO_OUT(REG_846346, 1);
}
void vidc_720p_set_deblock_line_buffer(u32 *pi_deblock_line_buffer_start,
u32 alloc_len)
{
VIDC_IO_OUT(REG_979942, pi_deblock_line_buffer_start);
VIDC_IO_OUT(REG_101184, alloc_len);
}
void vidc_720p_decode_set_mpeg4_data_partitionbuffer(u32 *vsp_buf_start)
{
VIDC_IO_OUT(REG_958768, vsp_buf_start);
}
void vidc_720p_decode_setH264VSPBuffer(u32 *pi_vsp_temp_buffer_start)
{
VIDC_IO_OUT(REG_958768, pi_vsp_temp_buffer_start);
}
void vidc_720p_decode_frame(u32 ch_id, u32 ext_buffer_start,
u32 ext_buffer_end, u32 dec_unit_size,
u32 start_byte_num, u32 input_frame_tag)
{
VIDC_IO_OUT(REG_275113_ADDR, ext_buffer_start);
VIDC_IO_OUT(REG_988007_ADDR, ext_buffer_end);
VIDC_IO_OUT(REG_87912, ext_buffer_end);
VIDC_IO_OUT(REG_66693, start_byte_num);
VIDC_IO_OUT(REG_94750, input_frame_tag);
VIDC_IO_OUT(REG_761892, dec_unit_size);
vidc_720p_submit_command(ch_id, VIDC_720P_CMD_FRAMERUN);
}
void vidc_720p_issue_eos(u32 i_ch_id)
{
VIDC_IO_OUT(REG_896825, 0x1);
VIDC_IO_OUT(REG_761892, 0);
vidc_720p_submit_command(i_ch_id, VIDC_720P_CMD_FRAMERUN);
}
void vidc_720p_eos_info(u32 *disp_status, u32 *resl_change)
{
VIDC_IO_INF(REG_612715, DISPLAY_STATUS, disp_status);
(*disp_status) = (*disp_status) & 0x3;
VIDC_IO_INF(REG_724381, RESOLUTION_CHANGE, resl_change);
}
void vidc_720p_decode_display_info(struct vidc_720p_dec_disp_info
*disp_info)
{
u32 display_status = 0;
VIDC_IO_INF(REG_612715, DISPLAY_STATUS, &display_status);
disp_info->disp_status =
(enum vidc_720p_display_status)((display_status & 0x3));
disp_info->disp_is_interlace = ((display_status & 0x4) >> 2);
disp_info->crop_exists = ((display_status & 0x8) >> 3);
disp_info->resl_change = ((display_status & 0x30) >> 4);
VIDC_IO_INF(REG_724381, RESOLUTION_CHANGE,
&disp_info->reconfig_flush_done);
VIDC_IO_IN(REG_999267, &disp_info->img_size_x);
VIDC_IO_IN(REG_345712, &disp_info->img_size_y);
VIDC_IO_IN(REG_151345, &disp_info->y_addr);
VIDC_IO_IN(REG_293983, &disp_info->c_addr);
VIDC_IO_IN(REG_370409, &disp_info->tag_top);
VIDC_IO_IN(REG_438677, &disp_info->tag_bottom);
VIDC_IO_IN(REG_679165, &disp_info->pic_time_top);
VIDC_IO_IN(REG_374150, &disp_info->pic_time_bottom);
if (disp_info->crop_exists) {
VIDC_IO_INF(REG_881638, CROP_RIGHT_OFFSET,
&disp_info->crop_right_offset);
VIDC_IO_INF(REG_881638, CROP_LEFT_OFFSET,
&disp_info->crop_left_offset);
VIDC_IO_INF(REG_161486, CROP_BOTTOM_OFFSET,
&disp_info->crop_bottom_offset);
VIDC_IO_INF(REG_161486, CROP_TOP_OFFSET,
&disp_info->crop_top_offset);
}
VIDC_IO_IN(REG_613254, &disp_info->metadata_exists);
VIDC_IO_IN(REG_580603,
&disp_info->input_bytes_consumed);
VIDC_IO_IN(REG_757835, &disp_info->input_frame_num);
VIDC_IO_INF(REG_441270, FRAME_TYPE,
&disp_info->input_frame);
disp_info->input_is_interlace =
((disp_info->input_frame & 0x4) >> 2);
if (disp_info->input_frame & 0x10)
disp_info->input_frame = VIDC_720P_IDRFRAME;
else
disp_info->input_frame &= 0x3;
}
void vidc_720p_decode_skip_frm_details(u32 *free_luma_dpb)
{
u32 disp_frm;
VIDC_IO_IN(REG_697961, &disp_frm);
if (disp_frm == VIDC_720P_NOTCODED)
VIDC_IO_IN(REG_347105, free_luma_dpb);
}
void vidc_720p_metadata_enable(u32 flag, u32 *input_buffer)
{
VIDC_IO_OUT(REG_854681, flag);
VIDC_IO_OUT(REG_988552, input_buffer);
}
void vidc_720p_decode_dynamic_req_reset(void)
{
VIDC_IO_OUT(REG_76706, 0x0);
VIDC_IO_OUT(REG_147682, 0x0);
VIDC_IO_OUT(REG_896825, 0x0);
}
void vidc_720p_decode_dynamic_req_set(u32 property)
{
if (property == VIDC_720P_FLUSH_REQ)
VIDC_IO_OUT(REG_76706, 0x1);
else if (property == VIDC_720P_EXTRADATA)
VIDC_IO_OUT(REG_147682, 0x1);
}
void vidc_720p_decode_setpassthrough_start(u32 pass_startaddr)
{
VIDC_IO_OUT(REG_486169, pass_startaddr);
}
| {
"pile_set_name": "Github"
} |
/** @file
* Linux seamless guest additions simulator in host.
*/
/*
* Copyright (C) 2007 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#include <stdlib.h> /* exit() */
#include <iprt/initterm.h>
#include <iprt/semaphore.h>
#include <iprt/stream.h>
#include <VBox/VBoxGuestLib.h>
#include "../seamless.h"
static RTSEMEVENT eventSem;
int VbglR3SeamlessSendRects(uint32_t cRects, PRTRECT pRects)
{
RTPrintf("Received rectangle update (%u rectangles):\n", cRects);
for (unsigned i = 0; i < cRects; ++i)
{
RTPrintf(" xLeft: %d yTop: %d xRight: %d yBottom: %d\n",
pRects[i].xLeft, pRects[i].yTop, pRects[i].xRight,
pRects[i].yBottom);
}
return true;
}
int VbglR3SeamlessSetCap(bool bState)
{
RTPrintf("%s\n", bState ? "Seamless capability set"
: "Seamless capability unset");
return true;
}
int VbglR3CtlFilterMask(uint32_t u32OrMask, uint32_t u32NotMask)
{
RTPrintf("IRQ filter mask changed. Or mask: 0x%x. Not mask: 0x%x\n",
u32OrMask, u32NotMask);
return true;
}
int VbglR3SeamlessWaitEvent(VMMDevSeamlessMode *pMode)
{
static bool active = false;
int rc = VINF_SUCCESS;
if (!active)
{
active = true;
*pMode = VMMDev_Seamless_Visible_Region;
}
else
{
rc = RTSemEventWait(eventSem, RT_INDEFINITE_WAIT);
if (RT_SUCCESS(rc))
{
rc = VERR_INTERRUPTED;
}
}
return true;
}
int VbglR3InterruptEventWaits(void)
{
return RTSemEventSignal(eventSem);
}
/**
* Xlib error handler for certain errors that we can't avoid.
*/
int vboxClientXLibErrorHandler(Display *pDisplay, XErrorEvent *pError)
{
char errorText[1024];
if (pError->error_code == BadWindow)
{
/* This can be triggered if a guest application destroys a window before we notice. */
RTPrintf("ignoring BadAtom error and returning\n");
return 0;
}
XGetErrorText(pDisplay, pError->error_code, errorText, sizeof(errorText));
RTPrintf("An X Window protocol error occurred: %s\n"
" Request code: %d\n"
" Minor code: %d\n"
" Serial number of the failed request: %d\n\n"
"exiting.\n",
errorText, (int)pError->request_code, (int)pError->minor_code,
(int)pError->serial);
exit(1);
}
int main( int argc, char **argv)
{
int rc = VINF_SUCCESS;
char ach[2];
RTR3InitExe(argc, &argv, 0);
RTPrintf("VirtualBox guest additions X11 seamless mode testcase\n");
if (0 == XInitThreads())
{
RTPrintf("Failed to initialise X11 threading, exiting.\n");
exit(1);
}
/* Set an X11 error handler, so that we don't die when we get unavoidable errors. */
XSetErrorHandler(vboxClientXLibErrorHandler);
RTPrintf("\nPress <Enter> to exit...\n");
RTSemEventCreate(&eventSem);
/** Our instance of the seamless class. */
VBoxGuestSeamless seamless;
LogRel(("Starting seamless Guest Additions...\n"));
rc = seamless.init();
if (rc != VINF_SUCCESS)
{
RTPrintf("Failed to initialise seamless Additions, rc = %d\n", rc);
}
RTStrmGetLine(g_pStdIn, ach, sizeof(ach));
seamless.uninit();
return rc;
}
| {
"pile_set_name": "Github"
} |
/* SPDX-License-Identifier: BSD-3-Clause
* Copyright(c) 2019 Intel Corporation
*/
#ifndef _OPAE_INTEL_MAX10_H_
#define _OPAE_INTEL_MAX10_H_
#include "opae_osdep.h"
#include "opae_spi.h"
struct max10_compatible_id {
char compatible[128];
};
#define MAX10_PAC "intel,max10"
#define MAX10_PAC_N3000 "intel,max10-pac-n3000"
#define MAX10_PAC_END "intel,end"
/* max10 capability flags */
#define MAX10_FLAGS_NO_I2C2 BIT(0)
#define MAX10_FLAGS_NO_BMCIMG_FLASH BIT(1)
#define MAX10_FLAGS_DEVICE_TABLE BIT(2)
#define MAX10_FLAGS_SPI BIT(3)
#define MAX10_FLGAS_NIOS_SPI BIT(4)
#define MAX10_FLAGS_PKVL BIT(5)
#define MAX10_FLAGS_SECURE BIT(6)
#define MAX10_FLAGS_MAC_CACHE BIT(7)
/** List of opae sensors */
TAILQ_HEAD(opae_sensor_list, opae_sensor_info);
struct intel_max10_device {
unsigned int flags; /*max10 hardware capability*/
struct altera_spi_device *spi_master;
struct spi_transaction_dev *spi_tran_dev;
struct max10_compatible_id *id; /*max10 compatible*/
char *fdt_root;
unsigned int base; /* max10 base address */
u16 bus;
struct opae_sensor_list opae_sensor_list;
};
/* retimer speed */
enum retimer_speed {
MXD_1GB = 1,
MXD_2_5GB = 2,
MXD_5GB = 5,
MXD_10GB = 10,
MXD_25GB = 25,
MXD_40GB = 40,
MXD_100GB = 100,
MXD_SPEED_UNKNOWN,
};
/* retimer info */
struct opae_retimer_info {
unsigned int nums_retimer;
unsigned int ports_per_retimer;
unsigned int nums_fvl;
unsigned int ports_per_fvl;
enum retimer_speed support_speed;
};
/* retimer status*/
struct opae_retimer_status {
enum retimer_speed speed;
/*
* retimer line link status bitmap:
* bit 0: Retimer0 Port0 link status
* bit 1: Retimer0 Port1 link status
* bit 2: Retimer0 Port2 link status
* bit 3: Retimer0 Port3 link status
*
* bit 4: Retimer1 Port0 link status
* bit 5: Retimer1 Port1 link status
* bit 6: Retimer1 Port2 link status
* bit 7: Retimer1 Port3 link status
*/
unsigned int line_link_bitmap;
};
#define FLASH_BASE 0x10000000
#define FLASH_OPTION_BITS 0x10000
/* System Registers */
#define MAX10_BASE_ADDR 0x300400
#define MAX10_SEC_BASE_ADDR 0x300800
/* Register offset of system registers */
#define NIOS2_FW_VERSION 0x0
#define MAX10_MACADDR1 0x10
#define MAX10_MAC_BYTE4 GENMASK(7, 0)
#define MAX10_MAC_BYTE3 GENMASK(15, 8)
#define MAX10_MAC_BYTE2 GENMASK(23, 16)
#define MAX10_MAC_BYTE1 GENMASK(31, 24)
#define MAX10_MACADDR2 0x14
#define MAX10_MAC_BYTE6 GENMASK(7, 0)
#define MAX10_MAC_BYTE5 GENMASK(15, 8)
#define MAX10_MAC_COUNT GENMASK(23, 16)
#define RSU_REG 0x2c
#define FPGA_RECONF_PAGE GENMASK(2, 0)
#define FPGA_RP_LOAD BIT(3)
#define NIOS2_PRERESET BIT(4)
#define NIOS2_HANG BIT(5)
#define RSU_ENABLE BIT(6)
#define NIOS2_RESET BIT(7)
#define NIOS2_I2C2_POLL_STOP BIT(13)
#define PKVL_EEPROM_LOAD BIT(31)
#define FPGA_RECONF_REG 0x30
#define MAX10_TEST_REG 0x3c
#define COUNTDOWN_START BIT(18)
#define MAX10_BUILD_VER 0x68
#define MAX10_VERSION_MAJOR GENMASK(23, 16)
#define PCB_INFO GENMASK(31, 24)
#define FPGA_PAGE_INFO 0x6c
#define DT_AVAIL_REG 0x90
#define DT_AVAIL BIT(0)
#define DT_BASE_ADDR_REG 0x94
#define MAX10_DOORBELL 0x400
#define RSU_REQUEST BIT(0)
#define SEC_PROGRESS GENMASK(7, 4)
#define HOST_STATUS GENMASK(11, 8)
#define SEC_STATUS GENMASK(23, 16)
/* PKVL related registers, in system register region */
#define PKVL_POLLING_CTRL 0x80
#define POLLING_MODE GENMASK(15, 0)
#define PKVL_A_PRELOAD BIT(16)
#define PKVL_A_PRELOAD_TIMEOUT BIT(17)
#define PKVL_A_DATA_TOO_BIG BIT(18)
#define PKVL_A_HDR_CHECKSUM BIT(20)
#define PKVL_B_PRELOAD BIT(24)
#define PKVL_B_PRELOAD_TIMEOUT BIT(25)
#define PKVL_B_DATA_TOO_BIG BIT(26)
#define PKVL_B_HDR_CHECKSUM BIT(28)
#define PKVL_EEPROM_UPG_STATUS GENMASK(31, 16)
#define PKVL_LINK_STATUS 0x164
#define PKVL_A_VERSION 0x254
#define PKVL_B_VERSION 0x258
#define SERDES_VERSION GENMASK(15, 0)
#define SBUS_VERSION GENMASK(31, 16)
#define DFT_MAX_SIZE 0x7e0000
int max10_reg_read(struct intel_max10_device *dev,
unsigned int reg, unsigned int *val);
int max10_reg_write(struct intel_max10_device *dev,
unsigned int reg, unsigned int val);
int max10_sys_read(struct intel_max10_device *dev,
unsigned int offset, unsigned int *val);
int max10_sys_write(struct intel_max10_device *dev,
unsigned int offset, unsigned int val);
struct intel_max10_device *
intel_max10_device_probe(struct altera_spi_device *spi,
int chipselect);
int intel_max10_device_remove(struct intel_max10_device *dev);
#define SENSOR_REG_VALUE 0x0
#define SENSOR_REG_HIGH_WARN 0x1
#define SENSOR_REG_HIGH_FATAL 0x2
#define SENSOR_REG_LOW_WARN 0x3
#define SENSOR_REG_LOW_FATAL 0x4
#define SENSOR_REG_HYSTERESIS 0x5
#define SENSOR_REG_MAX 0x6
static const char * const sensor_reg_name[] = {
"value",
"high_warn",
"high_fatal",
"low_warn",
"low_fatal",
"hysteresis",
};
struct sensor_reg {
unsigned int regoff;
size_t size;
};
struct raw_sensor_info {
const char *name;
const char *type;
unsigned int id;
unsigned int multiplier;
struct sensor_reg regs[SENSOR_REG_MAX];
};
#define OPAE_SENSOR_VALID 0x1
#define OPAE_SENSOR_HIGH_WARN_VALID 0x2
#define OPAE_SENSOR_HIGH_FATAL_VALID 0x4
#define OPAE_SENSOR_LOW_WARN_VALID 0x8
#define OPAE_SENSOR_LOW_FATAL_VALID 0x10
#define OPAE_SENSOR_HYSTERESIS_VALID 0x20
struct opae_sensor_info {
TAILQ_ENTRY(opae_sensor_info) node;
const char *name;
const char *type;
unsigned int id;
unsigned int high_fatal;
unsigned int high_warn;
unsigned int low_fatal;
unsigned int low_warn;
unsigned int hysteresis;
unsigned int multiplier;
unsigned int flags;
unsigned int value;
unsigned int value_reg;
};
#endif
| {
"pile_set_name": "Github"
} |
{
"name": "node-uuid",
"repo": "broofa/node-uuid",
"description": "Rigorous implementation of RFC4122 (v1 and v4) UUIDs.",
"version": "1.4.0",
"author": "Robert Kieffer <[email protected]>",
"contributors": [
{"name": "Christoph Tavan <[email protected]>", "github": "https://github.com/ctavan"}
],
"keywords": ["uuid", "guid", "rfc4122"],
"dependencies": {},
"development": {},
"main": "uuid.js",
"scripts": [
"uuid.js"
],
"license": "MIT"
} | {
"pile_set_name": "Github"
} |
package me.kafeitu.activiti.chapter10.listeners;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
/**
* @author henryyan
*/
public class HandleErrorInfoForPaymentListener implements ExecutionListener {
private static final long serialVersionUID = 1L;
@Override
public void notify(DelegateExecution execution) throws Exception {
String currentActivityId = execution.getCurrentActivityId();
if ("exclusivegateway-treasurerAudit".equals(currentActivityId)) {
execution.setVariable("message", "财务审批未通过");
} else if ("exclusivegateway-generalManagerAudit".equals(currentActivityId)) {
execution.setVariable("message", "总经理审批未通过");
}
}
}
| {
"pile_set_name": "Github"
} |
/*
HyPhy - Hypothesis Testing Using Phylogenies.
Copyright (C) 1997-now
Core Developers:
Sergei L Kosakovsky Pond ([email protected])
Art FY Poon ([email protected])
Steven Weaver ([email protected])
Module Developers:
Lance Hepler ([email protected])
Martin Smith ([email protected])
Significant contributions from:
Spencer V Muse ([email protected])
Simon DW Frost ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, 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.
*/
#include "avllistx_iterator.h"
#define AVL_LISTX_ITERATOR_ENDINDEX (-1L)
AVLListXIterator::AVLListXIterator (_AVLListX const * the_list):
current_location (AVL_LISTX_ITERATOR_ENDINDEX),
traversal_lookup (AVL_LISTX_ITERATOR_ENDINDEX),
traversal_history () {
this->the_list = the_list;
}
AVLListXIterator::AVLListXIterator (AVLListXIterator const& copy_from) :
traversal_history(copy_from.traversal_history) {
this->the_list = copy_from.the_list;
this->current_location = copy_from.current_location;
this->traversal_lookup = copy_from.traversal_lookup;
}
AVLListXIterator& AVLListXIterator::begin (void) {
this->current_location = the_list->Traverser (traversal_history, traversal_lookup, the_list->GetRoot());
return *this;
}
AVLListXIterator& AVLListXIterator::end (void) {
this->current_location = AVL_LISTX_ITERATOR_ENDINDEX;
return *this;
}
AVLListXIterator& AVLListXIterator::operator++ (void) {
this->current_location = the_list->Traverser (traversal_history, traversal_lookup);
return *this;
}
AVLListXIterator& AVLListXIterator::operator = (const AVLListXIterator& assign_from) {
if (this != &assign_from) {
this->the_list = assign_from.the_list;
this->current_location = assign_from.current_location;
this->traversal_lookup = assign_from.traversal_lookup;
this->traversal_history = assign_from.traversal_history;
}
return *this;
}
AVLListXIteratorKeyValue const AVLListXIterator::operator* (void) {
if (this->current_location >= 0) {
return AVLListXIteratorKeyValue (this->current_location, the_list->GetXtra(this->current_location));
}
return AVLListXIteratorKeyValue (AVL_LISTX_ITERATOR_ENDINDEX,0);
}
bool AVLListXIterator::operator == (AVLListXIterator const & compare) {
return this->the_list == compare.the_list && this->current_location == compare.current_location;
}
bool AVLListXIterator::operator != (AVLListXIterator const & compare) {
return this->the_list != compare.the_list || this->current_location != compare.current_location;
}
| {
"pile_set_name": "Github"
} |
function [ForCount, IfCount] = adigatorPrintTempFiles(Ffid,Tfid,FlowInfo,...
DerNumber,ForCount,FunStrChecks)
% adigatorPrintTempFiles(Ffid,FlowInfo)
% This function is used to make blocks of temporary functions, which
% contain lines of user code interspersed with statements which call
% adigatorVarAnalyzer in order to read and print out the derivative function
% properly.
% This routine is called from adigator.m and calls no routines which are not
% sub-routines of adigatorPrintTempFiles.m itself.
%
% Copyright 2011-214 Matthew J. Weinstein and Anil V. Rao
% Distributed under the GNU General Public License version 3.0
% ----------------------------------------------------------------------- %
% MAIN %
% ----------------------------------------------------------------------- %
IfCount = 0;
indent = [];
MainFlag = ~ForCount;
ForIfFlag = [0 0 0];
StartLocation = FlowInfo.StartLocation;
if ~isempty(FlowInfo.Children)
% Print the first block of code.
EndLocation = FlowInfo.Children(1).StartLocation;
PrintTemp(Ffid,StartLocation,EndLocation,Tfid,indent,FunStrChecks,DerNumber);
% Print the children blocks of code.
[StartLocation,ForCount,IfCount,~] = FlowPrint(Ffid,FlowInfo.Children,...
Tfid,indent,ForCount,IfCount,DerNumber,MainFlag,FunStrChecks,ForIfFlag);
end
EndLocation = FlowInfo.EndLocation;
% Print the last block of code.
PrintTemp(Ffid,StartLocation,EndLocation,Tfid,indent,FunStrChecks,DerNumber);
return
end
function [EndLocation,ForCount,IfCount,ForIfFlag] = FlowPrint(Ffid,FlowInfo,Tfid,...
indent,ForCount,IfCount,DerNumber,MainFlag,FunStrChecks,ForIfFlag)
global ADIGATOR
% Function Recursively calls itself to get through the FlowInfo structure
% and print out all of the temporary files.
FlowSize = length(FlowInfo);
LastBro = 0;
for FlowCount = 1:FlowSize
if strcmp(FlowInfo(FlowCount).Type,'if')
% ------------------------------------------------------------------- %
% IF STATEMENTS - START %
% ------------------------------------------------------------------- %
IfCount = IfCount+1;
ForIfFlag(2) = ForIfFlag(2)+1;
BroCount = 1;
CurIfCount = IfCount;
if FlowCount ~= 1
% Need to get the section between previous Flow Control Statment and
% this one.
StartLocation = EndLocation; % Starting at the End of the last section
EndLocation = FlowInfo(FlowCount).StartLocation;
PrintTemp(Ffid,StartLocation,EndLocation,Tfid,indent,FunStrChecks,DerNumber);
end
fprintf(Tfid,[indent,'%% ADiGator IF Statement #%1.0d: START\n'],IfCount);
% --------------- Print Out the Conditional Variables --------------- %
CondVarStr = getIfForStatement(Ffid,FlowInfo(FlowCount).StartLocation);
CadaVarStr = 'cadaconditional1';
if DerNumber == 1
fprintf(Tfid,[indent,CadaVarStr,' = ',CondVarStr,';\n']);
CondVarStr = FindDoinkers(CondVarStr);
fprintf(Tfid,[indent,CadaVarStr,' = adigatorVarAnalyzer(''',CadaVarStr,...
' = ',CondVarStr,''',',CadaVarStr,',''',CadaVarStr,''',0);\n']);
end
CondVarStrs = cell(1,FlowSize-FlowCount);
CondVarStrs{1} = [CadaVarStr,','];
% Get Any ElseIf variables
for FlowCount2 = FlowCount+1:FlowSize
if strcmp(FlowInfo(FlowCount2).Type,'elseif')
BroCount = BroCount+1;
if DerNumber == 1
CondVarStr = getIfForStatement(Ffid,FlowInfo(FlowCount2).StartLocation);
CadaVarStr = sprintf('cadaconditional%1.0d',BroCount);
fprintf(Tfid,[indent,CadaVarStr,' = ',CondVarStr,';\n']);
CondVarStr = FindDoinkers(CondVarStr);
fprintf(Tfid,[indent,CadaVarStr,' = adigatorVarAnalyzer(''',CadaVarStr,...
' = ',CondVarStr,''',',CadaVarStr,',''',CadaVarStr,''',0);\n']);
end
CondVarStrs{BroCount} = [CadaVarStr,','];
elseif strcmp(FlowInfo(FlowCount2).Type,'else')
BroCount = BroCount+1;
CondVarStrs{BroCount} = '[],';
else
break
end
end
LastBro = BroCount;
% ---------------- Print Out the IF Initialize Statement ------------ %
CondVarStrs = CondVarStrs(1:BroCount);
CondVarStrs = cell2mat(CondVarStrs);
if ADIGATOR.OPTIONS.UNROLL && (ForIfFlag(2) == 1 || ForIfFlag(3))
fprintf(Tfid,[indent,'for adigatorIfPrint%1.0f = adigatorIfLooper(%1.0f)\n'],...
IfCount,IfCount);
fprintf(Tfid,[indent,'adigatorIfLooperi(adigatorIfPrint%1.0f,%1.0f);\n'],IfCount,IfCount);
end
fprintf(Tfid,[indent,'adigatorIfInitialize(%1.0f,',...
CondVarStrs(1:end-1),');\n'],IfCount);
if ADIGATOR.OPTIONS.UNROLL
fprintf(Tfid,[indent,'[adigatorIfEvalStr, adigatorIfEvalVar] = ',...
'adigatorIfIterStart(%1.0f,1);%%#ok<NASGU>\n'],IfCount);
fprintf(Tfid,[indent,'if ~isempty(adigatorIfEvalStr);',...
' cellfun(@eval,adigatorIfEvalStr); end\n']);
else
fprintf(Tfid,[indent,'adigatorIfIterStart(%1.0f,1);\n'],IfCount);
end
BroCount = 1;
elseif strcmp(FlowInfo(FlowCount).Type,'elseif') || strcmp(FlowInfo(FlowCount).Type,'else')
% ------------------------------------------------------------------- %
% ELSEIF/ELSE STATEMENTS - START %
% ------------------------------------------------------------------- %
BroCount = BroCount+1;
% ------------------ Print Out the ELSEIF Statement ----------------- %
fprintf(Tfid,[indent,'[adigatorIfEvalStr, adigatorIfEvalVar] = ',...
'adigatorIfIterStart(%1.0f,%1.0f);%%#ok<NASGU>\n'],CurIfCount,BroCount);
fprintf(Tfid,[indent,'if ~isempty(adigatorIfEvalStr);',...
' cellfun(@eval,adigatorIfEvalStr); end\n']);
elseif strcmp(FlowInfo(FlowCount).Type,'for')
% ------------------------------------------------------------------- %
% FOR STATEMENTS - START %
% ------------------------------------------------------------------- %
ForCount = ForCount+1;
ForIfFlag(1) = ForIfFlag(1)+1;
if ForIfFlag(2); ForIfFlag(3) = ForIfFlag(3)+1; end
CurForCount = ForCount;
if FlowCount ~= 1
% Need to get the section between previous Flow Control Statment and
% this one.
StartLocation = EndLocation; % Starting at the End of the last section
EndLocation = FlowInfo(FlowCount).StartLocation;
PrintTemp(Ffid,StartLocation,EndLocation,Tfid,indent,FunStrChecks,DerNumber);
end
fprintf(Tfid,[indent,'%% ADiGator FOR Statement #%1.0d: START\n'],ForCount);
% -------------------- Get the Loop Variable ------------------------ %
LoopStr = getIfForStatement(Ffid,FlowInfo(FlowCount).StartLocation);
% See if we need to print it out or not
EqLoc = strfind(LoopStr,'=');
if ~isempty(EqLoc)
LoopStrLHS = strtrim(LoopStr(1:EqLoc(1)-1));
LoopStrRHS = strtrim(LoopStr(EqLoc(1)+1:end));
LoopVar = sprintf('cadaforvar%1.0d',ForCount);
LoopCount = sprintf('cadaforcount%1.0d',ForCount);
if DerNumber == 1
LoopVarStr = [LoopVar,' = ',LoopStrRHS,';'];
fprintf(Tfid,[indent,LoopVarStr,'\n']);
fprintf(Tfid,[indent,LoopVar,' = adigatorVarAnalyzer(''',FindDoinkers(LoopVarStr),''',',...
LoopVar,',''',LoopVar,''',0);\n']);
else
LoopVar = LoopStrRHS;
LoopCount = LoopStrLHS;
end
else
errlink = GenErrorLink(Ffid,FlowInfo(FlowCount).StartLocation(1));
error(['???Unable to parse ',LoopStr,': No Equal Sign at: ',errlink])
end
% --------------- Print the FOR Initialize Statement ---------------- %
if ForIfFlag(1) == 1 && ~ADIGATOR.OPTIONS.UNROLL
% Main function on an outer loop
fprintf(Tfid,[indent,'[adigatorForVariable%1.0d, adigatorForEvalStr, adigatorForEvalVar]',...
' = adigatorForInitialize(%1.0d,',LoopVar,');%%#ok<NASGU>\n'],ForCount,ForCount);
fprintf(Tfid,[indent,'if ~isempty(adigatorForEvalStr)\n']);
fprintf(Tfid,[indent,' cellfun(@eval,adigatorForEvalStr);\n']);
fprintf(Tfid,[indent,'end\n']);
else
fprintf(Tfid,[indent,'adigatorForVariable%1.0d = adigatorForInitialize(%1.0d,',...
LoopVar,');\n'],ForCount,ForCount);
end
fprintf(Tfid,[indent,'for adigatorForVariable%1.0di = adigatorForVariable%1.0d\n'],...
ForCount,ForCount);
fprintf(Tfid,[indent,LoopCount,' = adigatorForIterStart(%1.0d,',...
'adigatorForVariable%1.0di);\n'],ForCount,ForCount);
if DerNumber == 1
fprintf(Tfid,[indent,LoopStrLHS,' = ',LoopVar,'(:,',LoopCount,');\n']);
fprintf(Tfid,[indent,LoopStrLHS,' = adigatorVarAnalyzer(''',LoopStrLHS,...
' = ',LoopVar,'(:,',LoopCount,');'',',LoopStrLHS,',''',LoopStrLHS,''',0);\n']);
end
end
% --------------------------------------------------------------------- %
% CALCULATIONS WITHIN THE FLOW CONTROL %
% --------------------------------------------------------------------- %
indent = [indent,' ']; %#ok<AGROW>
StartLocation = FlowInfo(FlowCount).StartLocation;
if ~isempty(FlowInfo(FlowCount).Children)
% Print out the block leading to first child.
EndLocation = FlowInfo(FlowCount).Children(1).StartLocation;
PrintTemp(Ffid,StartLocation,EndLocation,Tfid,indent,FunStrChecks,DerNumber);
% Print the children blocks of code.
[StartLocation,ForCount,IfCount,ForIfFlag] = ...
FlowPrint(Ffid,FlowInfo(FlowCount).Children,Tfid,indent,...
ForCount,IfCount,DerNumber,MainFlag,FunStrChecks,ForIfFlag);
end
EndLocation = FlowInfo(FlowCount).EndLocation;
% Print the last block of code for this section.
PrintTemp(Ffid,StartLocation,EndLocation,Tfid,indent,FunStrChecks,DerNumber)
% --------------------------------------------------------------------- %
% END OF THE FLOW CONTROL BLOCK %
% --------------------------------------------------------------------- %
indent(1:4) = [];
if strcmp(FlowInfo(FlowCount).Type,'for')
fprintf(Tfid,[indent,'[adigatorForEvalStr, adigatorForEvalVar]',...
'= adigatorForIterEnd(%1.0d,adigatorForVariable%1.0di);\n'],CurForCount,CurForCount);
fprintf(Tfid,[indent,'if ~isempty(adigatorForEvalStr)\n']);
fprintf(Tfid,[indent,' cellfun(@eval,adigatorForEvalStr);\n']);
fprintf(Tfid,[indent,'end\n']);
fprintf(Tfid,[indent,'end\n']);
fprintf(Tfid,[indent,'%% ADiGator FOR Statement #%1.0d: END\n'],CurForCount);
ForIfFlag(1) = ForIfFlag(1)-1;
if ForIfFlag(2); ForIfFlag(3) = ForIfFlag(3) - 1; end
elseif BroCount == LastBro
fprintf(Tfid,[indent,'[adigatorIfEvalStr, adigatorIfEvalVar] = ',...
'adigatorIfIterEnd(%1.0f,%1.0f);%%#ok<NASGU>\n'],CurIfCount,BroCount);
fprintf(Tfid,[indent,'if ~isempty(adigatorIfEvalStr);',...
' cellfun(@eval,adigatorIfEvalStr); end\n']);
if ADIGATOR.OPTIONS.UNROLL && (ForIfFlag(2) == 1 || ForIfFlag(3))
fprintf(Tfid,[indent,'end\n']);
end
fprintf(Tfid,[indent,'%% ADiGator IF Statement #%1.0d: END\n'],CurIfCount);
ForIfFlag(2) = ForIfFlag(2)-1;
else
fprintf(Tfid,[indent,'adigatorIfIterEnd(%1.0f,%1.0f);\n'],CurIfCount,BroCount);
end
end
return
end
function PrintTemp(Ffid,StartLocation,EndLocation,Tfid,indent,FunStrChecks,DerNumber)
% Read from file Ffid, print to temporary function.
% Temporary function is named by the EndLocation(3).
global ADIGATOR
VAstr = 'adigatorVarAnalyzer';
fseek(Ffid,StartLocation(4),-1);
% ----------------First Line If There are Multiple Evaluations------------%
FunStrFULL = fgets(Ffid);
MajorLineCount = StartLocation(1);
MinorLineStart = StartLocation(2)+1;
while MajorLineCount <= EndLocation(1) && ~isnumeric(FunStrFULL)
FunStrFull = strtrim(FunStrFULL);
if ~isempty(FunStrFull)
if length(FunStrFull) > 3 && ~strcmp(FunStrFull(1),'%')
multlines1 = strcmp(FunStrFull(end-2:end),'...');
osquarelocs = strfind(FunStrFull,'[');
csquarelocs = strfind(FunStrFull,']');
multlines2 = length(osquarelocs) > length(csquarelocs);
while multlines1 || multlines2
% Single command spanning multiple lines - look for a comment at
% end of this line
commentloc = strfind(FunStrFull,'%');
if ~isempty(commentloc)
% Just trash the comment - no good way of keeping it
FunStrFull = strtrim(FunStrFull(1:commentloc(1)-1));
end
if multlines1 && length(FunStrFull) > 6 && strcmp(FunStrFull(1:7),'global ')
% ... at end of line with global
FunStrFull = [FunStrFull(1:end-3),' '];
elseif multlines1
% ... at end of line
FunStrFull = FunStrFull(1:end-3);
elseif strcmp(FunStrFull(end),',')
% Building a Matrix and have ',' at end for some reason
FunStrFull = [FunStrFull(1:end-1),';'];
elseif ~strcmp(FunStrFull(end),';')
% Building a Matrix and dont have the vertcat operator
FunStrFull = [FunStrFull,';']; %#ok<AGROW>
end
FunStrFull = strtrim([FunStrFull,fgets(Ffid)]);
MajorLineCount = MajorLineCount + 1;
multlines1 = strcmp(FunStrFull(end-2:end),'...');
osquarelocs = strfind(FunStrFull,'[');
csquarelocs = strfind(FunStrFull,']');
multlines2 = length(osquarelocs) > length(csquarelocs);
end
end
[FunStr,NUMFunStr] = adigatorSeperateFunLines(FunStrFull);
if MajorLineCount == EndLocation(1)
NUMFunStr = EndLocation(2)-1;
end
% -----------------Work on Function Lines--------------------------
for adigatorFScount = MinorLineStart:NUMFunStr
FunStri = FunStr{adigatorFScount};
StrLength = length(FunStri);
FunStri = strtrim(FindComments(FunStri));
SlashLocs = strfind(FunStri,'\');
if ~isempty(SlashLocs)
FunStri = strtrim(FindSlashes(FunStri,SlashLocs));
end
EqualLoc = regexp(FunStri,'[^=><~]=[^=]')+1;
if strcmp(FunStri(1),'%')
% COMMENT
FunStri = FindDoinkers(FunStri);
fprintf(Tfid,[indent,VAstr,'(''',FunStri,''');\n']);
elseif ~isempty(EqualLoc)
% Some sort of Assignment/Calculation
FunStri = CheckFunctionCall(FunStri,FunStrChecks,Tfid,indent,DerNumber,MajorLineCount);
if isempty(FunStri)
continue
end
% --- Check For Structure Subsref on RHS ---
svrcount = 0; svrtype = 1;
FunStrRHS = strtrim(FunStri(EqualLoc+1:end));
[strucloc1,strucloc2] = regexpi(FunStrRHS,'\([^\)\(]*[a-z][^\)\(]*\)\.[a-z]',...
'start','end','once');
strucloc2 = strucloc2-1;
[cellyloc1,cellyloc2] = regexpi(FunStrRHS,'\{[^\}\{]*[a-z][^\}\{]*\}',...
'start','end','once');
if isempty(strucloc1) || (~isempty(cellyloc1) && strucloc1 > cellyloc1)
strucloc1 = cellyloc1; strucloc2 = cellyloc2; svrtype = 0;
end
while ~isempty(strucloc1)
fprintf(Tfid,[indent,'%% ',FunStrRHS,'\n']);
svrcount = svrcount+1;
if svrtype
%svendloc = regexp(FunStrRHS,'\([^\)]*[a-z].*\)\.\w+','end','once');
svendloc = regexp(FunStrRHS(strucloc2+1:end),'\W','once','start')+strucloc2-1;
svstartloc = regexp(FunStrRHS(1:strucloc1-2),'[\w\(\)\{\}\.]+$','start','once');
StrucRef.i = FunStrRHS(strucloc1+1:strucloc2-2);
else
svendloc = strucloc2;
svstartloc = regexp(FunStrRHS(1:strucloc1-1),'[\w\(\)\{\}\.]+$','start','once');
StrucRef.i = FunStrRHS(strucloc1+1:strucloc2-1);
end
ADIGATOR.SVACOUNT = ADIGATOR.SVACOUNT+1;
if DerNumber == 1
StrucRef.new = sprintf('adigatorStrucRef%1.0f',ADIGATOR.SVACOUNT);
else
StrucRef.new = strtrim(FunStri(1:EqualLoc-1));
end
StrucRef.old = FunStrRHS(svstartloc:svendloc);
openloc = strfind(StrucRef.old,'(');
closeloc = strfind(StrucRef.old,')');
if length(openloc) > length(closeloc)
svstartloc = openloc(length(openloc)-length(closeloc))+svstartloc;
StrucRef.old = FunStrRHS(svstartloc:svendloc);
end
StrucRef.s = FunStrRHS(svstartloc:strucloc1-1);
%FunStrRHS = [StrucRef.new,FunStrRHS(svendloc+1:end)];
strucloc1 = strfind(FunStrRHS,StrucRef.old);
FunStrRHS = [FunStrRHS(1:strucloc1-1) StrucRef.new,...
FunStrRHS(strucloc1+length(StrucRef.old):end)];
StrucRef.old = FindDoinkers(StrucRef.old);
fprintf(Tfid,[indent,'[',StrucRef.new,',',StrucRef.s,'] = adigatorCellStrucRef(%1.0f,',...
StrucRef.s,',''',StrucRef.new,' = ',StrucRef.old,';'',',StrucRef.i,');\n'],...
ADIGATOR.SVACOUNT);
svrtype = 1; % 1 for structure, 0 for cell
[strucloc1,strucloc2] = regexpi(FunStrRHS,'\([^\)\(]*[a-z][^\)\(]*\)\.[a-z]',...
'start','end','once');
strucloc2 = strucloc2-1;
[cellyloc1,cellyloc2] = regexpi(FunStrRHS,'\{[^\}]*[a-z][^\}]*\}',...
'start','end','once');
if isempty(strucloc1) || (~isempty(cellyloc1) && strucloc1 > cellyloc1)
strucloc1 = cellyloc1; strucloc2 = cellyloc2; svrtype = 0;
end
end
if svrcount
ADIGATOR.OPTIONS.PREALLOCATE = 1;
if DerNumber == 1
FunStri = [FunStri(1:EqualLoc),FunStrRHS];
else
continue
end
end
% ---Work on LHS of equal Sign---
VarStr = strtrim(FunStri(1:EqualLoc-1));
if strcmp(VarStr(1),'[')
% Multiple Assignments
VarStrings = SeperateOutputStrings(strtrim(VarStr(2:end-1)),0);
NumOutVars = length(VarStrings);
else
% Single Assignment
VarStrings = cell(1); VarStrings{1} = VarStr;
NumOutVars = 1;
end
SubsFlags = zeros(NumOutVars,1);
svacount = ADIGATOR.SVACOUNT;
for Vcount = 1:NumOutVars
VarStr = VarStrings{Vcount};
% Check for Structure Assignments
svatype = 1; % 1 for structure, 0 for cell
[strucloc1,strucloc2] = regexpi(VarStr,'\([^\)\(]*[a-z][^\)\(]*\)\.[a-z]',...
'start','end','once');
strucloc2 = strucloc2-1;
[cellyloc1,cellyloc2] = regexpi(VarStr,'\{[^\}\{]*[a-z][^\}\{]*\}',...
'start','end','once');
if isempty(strucloc1) || (~isempty(cellyloc1) && strucloc1 > cellyloc1)
strucloc1 = cellyloc1; strucloc2 = cellyloc2; svatype = 0;
end
while ~isempty(strucloc1)
ADIGATOR.OPTIONS.PREALLOCATE = 1;
% s(i).a = something; - have to replace this with
% adigatorstrucasgn = something;
% s = adigatorCellStrucAsgn(s,i,adigatorstrucasgn,'s(i).a','struct');
fprintf(Tfid,[indent,'%% ',VarStr,'\n']);
svacount = svacount+1;
if svatype
%svendloc = regexp(VarStr,'\([^\)]*[a-z][^\)]*\)\.\w*','end','once');
svendloc = regexp(VarStr(strucloc2+1:end),'\W','once','start')+strucloc2-1;
if isempty(svendloc)
svendloc = length(VarStr);
end
StrucAsgn(svacount).i = VarStr(strucloc1+1:strucloc2-2);
else
svendloc = strucloc2;
StrucAsgn(svacount).i = VarStr(strucloc1+1:strucloc2-1);
end
if DerNumber == 1
StrucAsgn(svacount).new = sprintf('adigatorStrucAsgn%1.0f',svacount);
else
StrucAsgn(svacount).new = strtrim(FunStri(EqualLoc+1:end-1));
end
StrucAsgn(svacount).old = VarStr(1:svendloc);
StrucAsgn(svacount).s = VarStr(1:strucloc1-1);
StrucAsgn(svacount).type = svatype;
VarStr = [StrucAsgn(svacount).new,VarStr(svendloc+1:end)];
VarStrings{Vcount} = VarStr;
strucloc1 = strfind(FunStri,StrucAsgn(svacount).old);
FunStri = [FunStri(1:strucloc1-1) StrucAsgn(svacount).new,...
FunStri(strucloc1+length(StrucAsgn(svacount).old):end)];
svatype = 1; % 1 for structure, 0 for cell
[strucloc1,strucloc2] = regexpi(VarStr,'\([^\)\(]*[a-z][^\)\(]*\)\.[a-z]',...
'start','end','once');
strucloc2 = strucloc2-1;
[cellyloc1,cellyloc2] = regexpi(VarStr,'\{[^\}]*[a-z][^\}]*\}',...
'start','end','once');
if isempty(strucloc1) || (~isempty(cellyloc1) && strucloc1 > cellyloc1)
strucloc1 = cellyloc1; strucloc2 = cellyloc2; svatype = 0;
end
end
% Check For SubsAsgn on all of the VarStrings
if strcmp(VarStr(end),')')
SubsFlags(Vcount) = 1;
SubsLocs = strfind(VarStr,'(');
StrucLoc = strfind(VarStr,').');
if ~isempty(StrucLoc)
SubsLocs = SubsLocs(SubsLocs > StrucLoc(end));
end
VarStrings{Vcount} = VarStr(1:SubsLocs(1)-1);
end
end
if DerNumber == 1 || svacount == ADIGATOR.SVACOUNT
% Print Out the Actual Calculation
fprintf(Tfid,[indent,FunStri,'\n']);
% Get the Strings for the variables that we are going to feed into
% the Variable Analyzer
if NumOutVars == 1
LHSout = VarStrings{1};
RHSout = sprintf([VarStrings{1},',''',VarStrings{1},...
''',%1.0f'],SubsFlags(1));
else
LHSout = cell(1,NumOutVars); RHSout = cell(1,NumOutVars);
LHSout{1} = ['[',VarStrings{1},','];
RHSout{1} = sprintf([VarStrings{1},',''',VarStrings{1},...
''',%1.0f,'],SubsFlags(1));
for Vcount = 2:NumOutVars-1
LHSout{Vcount} = [VarStrings{Vcount},','];
RHSout{Vcount} = sprintf([VarStrings{Vcount},',''',VarStrings{Vcount},...
''',%1.0f,'],SubsFlags(Vcount));
end
LHSout{NumOutVars} = [VarStrings{NumOutVars},']'];
RHSout{NumOutVars} = sprintf([VarStrings{NumOutVars},',''',VarStrings{NumOutVars},...
''',%1.0f'],SubsFlags(NumOutVars));
LHSout = cell2mat(LHSout); RHSout = cell2mat(RHSout);
end
% Print Out the call to the Variable Analyzer
FunStri = FindDoinkers(FunStri);
fprintf(Tfid,[indent,LHSout,' = ',VAstr,'(''',FunStri,''',',RHSout,');\n']);
end
for svacounti = svacount:-1:ADIGATOR.SVACOUNT+1
% Was a Structure Assignment
fprintf(Tfid,[indent,'try adigatorDummyStruc = ',StrucAsgn(svacounti).s,...
'; catch adigatorDummyErr; ']);
if StrucAsgn(svacounti).type
fprintf(Tfid,'adigatorDummyStruc = struct([]); end\n');
else
fprintf(Tfid,'adigatorDummyStruc = {}; end\n');
end
fprintf(Tfid,[indent,StrucAsgn(svacounti).s,' = adigatorCellStrucAsgn(%1.0f,',...
'adigatorDummyStruc,',StrucAsgn(svacounti).new,...
',''',FindDoinkers(StrucAsgn(svacounti).old),' = ',StrucAsgn(svacounti).new,';'',',...
StrucAsgn(svacounti).i,');\n'],...
svacounti);
end
ADIGATOR.SVACOUNT = svacount;
elseif StrLength > 7 && strcmp(FunStri(1:8),'keyboard')
% KEYBOARD
ADIGATOR.OPTIONS.KEYBOARD = 1;
fprintf(Tfid,'keyboard\n');
fprintf(Tfid,[indent,VAstr,'(''keyboard'');\n']);
elseif StrLength > 4 && strcmp(FunStri(1:5),'break')
% BREAK
IfCount = evalin('caller','IfCount');
BroCount = evalin('caller','BroCount');
fprintf(Tfid,[indent,'adigatorBreakCont(''break'',%1.0d,%1.0d);\n'],...
IfCount,BroCount);
elseif StrLength > 7 && strcmp(FunStri(1:8),'continue')
% CONTINUE
IfCount = evalin('caller','IfCount');
BroCount = evalin('caller','BroCount');
fprintf(Tfid,[indent,'adigatorBreakCont(''continue'',%1.0d,%1.0d);\n'],...
IfCount,BroCount);
elseif StrLength > 6 && strcmp(FunStri(1:6),'error(')
% ERROR MESSAGE
IfCount = evalin('caller','IfCount');
BroCount = evalin('caller','BroCount');
FunStri = FindDoinkers(FunStri);
fprintf(Tfid,[indent,'adigatorError(%1.0d,%1.0d,''',FunStri,''');\n'],...
IfCount,BroCount);
elseif StrLength > 5 && strcmp(FunStri(1:6),'return')
% RETURN
fprintf(Tfid,[indent,VAstr,'(''return'');\n']);
elseif StrLength > 6 && strcmp(FunStri(1:7),'global ')
% GLOBAL ASSIGNMENT
VarString = strtrim(FunStri(8:end));
if strcmp(VarString(end),';'); VarString = VarString(1:end-1); end
VarLocs = strfind(VarString,' ');
if ~isempty(VarLocs)
% Check for multiple spaces.
for Lcount = 2:length(VarLocs)
if VarLocs(Lcount) == VarLocs(Lcount-1)+1
VarLocs(Lcount-1) = 0;
end
end
VarLocs = nonzeros(VarLocs);
InVarStrs = cell(1,length(VarLocs)+1);
OutVarStrs = cell(1,length(VarLocs)+1);
InVarStrs{1} = ['''',strtrim(VarString(1:VarLocs(1)-1)),''','];
OutVarStrs{1} = [strtrim(VarString(1:VarLocs(1)-1)),','];
for Lcount = 2:length(VarLocs)
InVarStrs{Lcount} = ['''',strtrim(VarString(...
VarLocs(Lcount-1)+1:VarLocs(Lcount)-1)),''','];
OutVarStrs{Lcount} = [strtrim(VarString(...
VarLocs(Lcount-1)+1:VarLocs(Lcount)-1)),','];
end
InVarStrs{end} = ['''',strtrim(VarString(VarLocs(end)+1:end)),''''];
OutVarStrs{end} = strtrim(VarString(VarLocs(end)+1:end));
InVarStrs = cell2mat(InVarStrs);
OutVarStrs = ['[',cell2mat(OutVarStrs),']'];
else
InVarStrs = ['''',VarString,''''];
OutVarStrs = VarString;
end
fprintf(Tfid,[indent,OutVarStrs,' = ',VAstr,'(''global'',',InVarStrs,');\n']);
elseif StrLength > 4 && strcmp(FunStri(1:5),'load(')
% CHECK FOR LOAD - DONT ALLOW IT.
errlink = GenErrorLink(Ffid,MajorLineCount);
error(['In order to load in variables, must assign them to a'...
' variable name. At ',FunStri,' ',errlink]);
else
% Dont know what this statement is.
errlink = GenErrorLink(Ffid,MajorLineCount);
error(['Cannot process statement: ',FunStrFull,' at ',errlink])
end
end
end
MinorLineStart = 1;
FunStrFULL = fgets(Ffid);
MajorLineCount = MajorLineCount+1;
end
return
end
function FunStri = CheckFunctionCall(FunStri,FunStrChecks,Tfid,indent,DerNumber,MajorLineCount)
[Start,End] = regexp(FunStri,FunStrChecks,'start','end');
FunLoc = ~cellfun(@isempty,Start);
if FunLoc(1)
errlink = GenErrorLink(Ffid,MajorLineCount);
error(['User program cannot call main user function from within its methods at:' errlink])
elseif sum(FunLoc) > 1
errlink = GenErrorLink(Ffid,MajorLineCount);
error(['Currently can only handle one call to a user defined function per line at line: ',FunStri,' at: ',errlink])
elseif any(FunLoc)
FunLocNum = 1:length(FunStrChecks);
FunLoc = FunLocNum(FunLoc);
Start = strfind(FunStri,FunStrChecks{FunLoc}(3:end));
End = End{FunLoc};
if length(Start) > 1
errlink = GenErrorLink(Ffid,MajorLineCount);
error(['Currently can only handle one call to a user defined function per line at line: ',FunStri,' at: ',errlink])
end
fprintf(Tfid,[indent,'%% Call to User Function ',...
FunStrChecks{FunLoc}(3:end-1),' --- (FunID %1.0d)\n'],FunLoc);
% -------------------- Work on Inputs to Function --------------------- %
InputStart = End+1;
OpenLocs = strfind(FunStri(InputStart:end),'(')+InputStart;
CloseLocs = strfind(FunStri(InputStart:end),')')+InputStart;
NumOpen = length(OpenLocs);
if ~isempty(OpenLocs)
InputEnd = CloseLocs(find(CloseLocs(1:NumOpen) < OpenLocs,1,'first'))-2;
if isempty(InputEnd)
InputEnd = CloseLocs(NumOpen+1)-2;
end
else
InputEnd = CloseLocs(1)-2;
end
InputStr = FunStri(InputStart:InputEnd);
InputStrs = SeperateOutputStrings(InputStr(~isspace(InputStr)),1);
NumInputs = length(InputStrs);
InVarStrs = cell(1,NumInputs);
for Icount = 1:NumInputs
VarStr = sprintf('cadainput%1.0d',Icount);
InVarStrs{Icount} = [VarStr,';'];
if DerNumber == 1
AsgnStr = [VarStr,' = ',InputStrs{Icount},';'];
fprintf(Tfid,[indent,AsgnStr,'\n']);
AsgnStr = FindDoinkers(AsgnStr);
fprintf(Tfid,[indent,VarStr,' = adigatorVarAnalyzer(''',AsgnStr,''',',...
VarStr,',''',VarStr,''',0);\n']);
end
end
InVarStrs = cell2mat(InVarStrs);
fprintf(Tfid,[indent,'adigatorInputs = {',InVarStrs(1:end-1),'};\n']);
End = InputEnd+1;
% -------------------- Print Call to Function ------------------------- %
fprintf(Tfid,[indent,'[adigatorFunInfo, adigatorOutputs] = ',...
'adigatortempfunc%1.0d(adigatorFunInfo,adigatorInputs);\n'],FunLoc);
% ----------------------- Work On Outputs ----------------------------- %
if ~isempty(regexp(FunStri(1:Start-1),'=\s*\>','once')) && strcmp(FunStri(1),'[') &&...
(length(FunStri) == End+1 || ~isempty(regexp(FunStri(End+1:end),'<\\s*;','once')))
% --------------------- Multiple Outputs ---------------------------- %
EqLoc = strfind(FunStri,'=');
OutputStart = 2;
OutputEnd = strfind(FunStri(1:EqLoc-1),']')-1;
OutputStrs = SeperateOutputStrings(FunStri(OutputStart:OutputEnd),0);
NumOutput = length(OutputStrs);
for Ocount = 1:NumOutput
OutVarStr = sprintf('cadaoutput%1.0d',Ocount);
fprintf(Tfid,[indent,OutVarStr,' = adigatorOutputs{%1.0d};\n'],Ocount);
if DerNumber == 1 && ~strcmp(OutputStrs{Ocount},'~')
AsgnStr = [OutputStrs{Ocount},' = ',OutVarStr,';'];
fprintf(Tfid,[indent,AsgnStr,'\n']);
SubLoc = strfind(OutputStrs{Ocount},'(');
if ~isempty(SubLoc)
SubsStr = '1';
VarStr = OutputStrs{Ocount}(1:SubLoc(1)-1);
else
SubsStr = '0';
VarStr = OutputStrs{Ocount};
end
fprintf(Tfid,[indent,VarStr,' = adigatorVarAnalyzer(''',AsgnStr,''',',...
VarStr,',''',VarStr,''',',SubsStr,');\n']);
end
end
FunStri = [];
else
% ----------------------- Single Output ----------------------------- %
OutVarStr = 'cadaoutput1';
fprintf(Tfid,[indent,OutVarStr,' = adigatorOutputs{1};\n']);
if DerNumber == 1
FunStri = [FunStri(1:Start-1),OutVarStr,FunStri(End+1:end)];
else
FunStri = [];
end
end
end
end
function FunStri = FindDoinkers(FunStri)
DoinkLocs = strfind(FunStri,'''');
if ~isempty(DoinkLocs)
for Dcount = 1:length(DoinkLocs)
Dloc = DoinkLocs(Dcount)+Dcount;
FunStri = [FunStri(1:Dloc-1),'''',FunStri(Dloc:end)];
end
end
return
end
function FunStri = FindSlashes(FunStri,SlashLocs)
if ~isempty(SlashLocs)
for Dcount = 1:length(SlashLocs)
Dloc = SlashLocs(Dcount)+Dcount;
FunStri = [FunStri(1:Dloc-1),'\',FunStri(Dloc:end)];
end
end
return
end
function FunStri = FindComments(FunStri)
DoinkLocs = strfind(FunStri,'%');
if ~isempty(DoinkLocs)
for Dcount = 1:length(DoinkLocs)
Dloc = DoinkLocs(Dcount)+Dcount;
FunStri = [FunStri(1:Dloc-1),'%',FunStri(Dloc:end)];
end
end
return
end
function VarStrings = SeperateOutputStrings(VarStr,IOflag)
% Just seperates output variable strings
SpaceLocs = ones(1,length(VarStr));
SpaceLocs(~isspace(VarStr)) = 0;
CommaLocs = strfind(VarStr,',');
SpaceLocs(CommaLocs) = -1;
CharLocs = 1:length(VarStr);
% Have a vector of locations where a zero or comma is.
ParenLoc1 = strfind(VarStr,'(');
if ~isempty(ParenLoc1)
% Remove any entries of my zero/comma vector that are in
% between parenthesis
ParenLoc2 = strfind(VarStr,')');
for Pcount = 1:length(ParenLoc1)
SpaceLocs(CharLocs > ParenLoc1(Pcount) & CharLocs<ParenLoc2(Pcount)) = 0;
end
end
CurlyLoc1 = strfind(VarStr,'{');
if ~isempty(CurlyLoc1)
% Remove any entries of my zero/comma vector that are in
% between curlies
CurlyLoc2 = strfind(VarStr,'}');
for Ccount = 1:length(CurlyLoc1)
SpaceLocs(CharLocs > CurlyLoc1(Ccount) & CharLocs<CurlyLoc2(Ccount)) = 0;
end
end
if IOflag
SquareLoc1 = strfind(VarStr,'[');
if ~isempty(SquareLoc1)
% Remove any entries of my zero/comma vector that are in
% between square brackets
SquareLoc2 = strfind(VarStr,']');
for Ccount = 1:length(SquareLoc1)
SpaceLocs(SpaceLocs > SquareLoc1(Ccount) & SpaceLocs<SquareLoc2(Ccount)) = 0;
end
end
end
for Scount = 1:length(SpaceLocs)-1
if SpaceLocs(Scount) && SpaceLocs(Scount+1)
if SpaceLocs(Scount) < 1
SpaceLocs(Scount+1) = 0;
for S2count = Scount+2:length(SpaceLocs)-1
if SpaceLocs(S2count) > 1
SpaceLocs(S2count) = 1;
else
break
end
end
else
SpaceLocs(Scount) = 0;
end
end
end
SpaceLocs(end) = 0;
SpaceLocs1 = 1:length(VarStr);
SpaceLocs = SpaceLocs1(logical(SpaceLocs));
NumOutVars = length(SpaceLocs)+1;
VarLocs = [0,SpaceLocs,length(VarStr)+1];
VarStrings = cell(NumOutVars,1);
for Vcount = 1:NumOutVars
VarStrings{Vcount} = strtrim(VarStr(VarLocs(Vcount)+1:VarLocs(Vcount+1)-1));
end
end
function Statement = getIfForStatement(Ffid,Location)
fseek(Ffid,Location(4),-1);
StrFull = strtrim(fgets(Ffid));
while strcmp(StrFull(end-2:end),'...')
StrFull = [StrFull(1:end-3),strtrim(fgets(Ffid))];
end
[MultStrs, ~] = adigatorSeperateFunLines(StrFull);
Statement = MultStrs{Location(2)};
sLength = length(Statement);
%Statement = FindDoinkers(Statement);
if sLength > 2 && strcmp(Statement(1:2),'if')
Statement = strtrim(Statement(3:end));
elseif sLength > 6 && strcmp(Statement(1:6),'elseif')
Statement = strtrim(Statement(7:end));
elseif sLength > 3 && strcmp(Statement(1:3),'for')
Statement = strtrim(Statement(4:end));
else
errlink = GenErrorLink(Ffid,Location(1));
error(['??? Unsure of what this statement is:',Statement,' at: ',errlink])
end
Statement = regexprep(Statement,'&&','&');
Statement = regexprep(Statement,'\|\|','|');
if strcmp(Statement(end),';')
Statement = strtrim(Statement(1:end-1));
end
if strcmp(Statement(end),',')
Statement = strtrim(Statement(1:end-1));
end
end
function errlink = GenErrorLink(Ffid,MajorLineCount)
filename = fopen(Ffid);
filenameloc = strfind(filename,filesep);
filenameDisp = filename(filenameloc(end)+1:end);
errlink = sprintf(['User''s Function: <a href="matlab: opentoline(',filename,',%1.0d)">',filenameDisp,' line %1.0d</a>'],MajorLineCount,MajorLineCount);
end | {
"pile_set_name": "Github"
} |
# 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.
$appPoolName = 'Carbon-Get-IisWebsite'
$siteName = 'Carbon-Get-IisWebsite'
function Start-TestFixture
{
& (Join-Path -Path $PSScriptRoot '..\Initialize-CarbonTest.ps1' -Resolve)
}
function Start-Test
{
Install-IisAppPool -Name $appPoolName
$bindings = @( 'http/*:8401:', 'https/*:8401:', 'http/1.2.3.4:80:', "http/5.6.7.8:80:$siteName" )
Install-IisWebsite -Name $siteName -Bindings $bindings -Path $TestDir -AppPoolName $appPoolName
}
function Stop-Test
{
Remove-IisWebsite -Name $siteName
}
function Test-ShouldReturnNullForNonExistentWebsite
{
$website = Get-IisWebsite -SiteName 'ISureHopeIDoNotExist'
Assert-Null $website
}
function Test-ShouldGetWebsiteDetails
{
$website = Get-IisWebsite -SiteName $siteName
Assert-NotNull $website
Assert-Equal $siteName $website.Name 'site name not set'
Assert-True ($website.ID -gt 0) 'site ID not set'
Assert-Equal 4 $website.Bindings.Count 'site bindings not set'
Assert-Equal 'http' $website.Bindings[0].Protocol
Assert-Equal '0.0.0.0' $website.Bindings[0].Endpoint.Address
Assert-Equal 8401 $website.Bindings[0].Endpoint.Port
Assert-Empty $website.Bindings[0].Host
Assert-Equal 'https' $website.Bindings[1].Protocol
Assert-Equal '0.0.0.0' $website.Bindings[1].Endpoint.Address
Assert-Equal 8401 $website.Bindings[1].Endpoint.Port
Assert-Empty $website.Bindings[1].Host
Assert-Equal 'http' $website.Bindings[2].Protocol
Assert-Equal '1.2.3.4' $website.Bindings[2].Endpoint.Address
Assert-Equal 80 $website.Bindings[2].Endpoint.Port
Assert-Empty $website.Bindings[2].Host
Assert-Equal 'http' $website.Bindings[3].Protocol
Assert-Equal '5.6.7.8' $website.Bindings[3].Endpoint.Address
Assert-Equal 80 $website.Bindings[3].Endpoint.Port
Assert-Equal $siteName $website.Bindings[3].Host "bindings[3] host name"
$physicalPath = $website.Applications |
Where-Object { $_.Path -eq '/' } |
Select-Object -ExpandProperty VirtualDirectories |
Where-Object { $_.Path -eq '/' } |
Select-Object -ExpandProperty PhysicalPath
Assert-Equal $physicalPath $website.PhysicalPath
Assert-ServerManagerMember -Website $website
}
function Test-ShouldGetAllWebsites
{
$foundAtLeastOne = $false
$foundTestWebsite = $false
Get-IisWebsite | ForEach-Object {
$foundAtLeastOne = $true
Assert-ServerManagerMember -Website $_
if( $_.Name -eq $siteName )
{
$foundTestWebsite = $true
}
}
Assert-True $foundAtLeastOne
Assert-True $foundTestWebsite
}
function Assert-ServerManagerMember
{
param(
$Website
)
Assert-NotNull ($Website.ServerManager) 'no server manager property'
Assert-NotNull ($Website | Get-Member | Where-Object { $_.Name -eq 'CommitChanges' -and $_.MemberType -eq 'ScriptMethod' }) 'no CommitChanges method'
}
| {
"pile_set_name": "Github"
} |
#[cfg(feature = "wasm")]
mod wasm_bindings;
#[cfg(feature = "wasm")]
pub use crate::wasm_bindings::*;
#[cfg(not(feature = "wasm"))]
mod bindings;
#[cfg(not(feature = "wasm"))]
pub use crate::bindings::*;
impl ImVec2 {
#[inline]
pub fn new(x: f32, y: f32) -> ImVec2 {
ImVec2 { x, y }
}
#[inline]
pub fn zero() -> ImVec2 {
ImVec2 { x: 0.0, y: 0.0 }
}
}
impl From<[f32; 2]> for ImVec2 {
#[inline]
fn from(array: [f32; 2]) -> ImVec2 {
ImVec2::new(array[0], array[1])
}
}
impl From<(f32, f32)> for ImVec2 {
#[inline]
fn from((x, y): (f32, f32)) -> ImVec2 {
ImVec2::new(x, y)
}
}
impl Into<[f32; 2]> for ImVec2 {
#[inline]
fn into(self) -> [f32; 2] {
[self.x, self.y]
}
}
impl Into<(f32, f32)> for ImVec2 {
#[inline]
fn into(self) -> (f32, f32) {
(self.x, self.y)
}
}
impl ImVec4 {
#[inline]
pub fn new(x: f32, y: f32, z: f32, w: f32) -> ImVec4 {
ImVec4 { x, y, z, w }
}
#[inline]
pub fn zero() -> ImVec4 {
ImVec4 {
x: 0.0,
y: 0.0,
z: 0.0,
w: 0.0,
}
}
}
impl From<[f32; 4]> for ImVec4 {
#[inline]
fn from(array: [f32; 4]) -> ImVec4 {
ImVec4::new(array[0], array[1], array[2], array[3])
}
}
impl From<(f32, f32, f32, f32)> for ImVec4 {
#[inline]
fn from((x, y, z, w): (f32, f32, f32, f32)) -> ImVec4 {
ImVec4::new(x, y, z, w)
}
}
impl Into<[f32; 4]> for ImVec4 {
#[inline]
fn into(self) -> [f32; 4] {
[self.x, self.y, self.z, self.w]
}
}
impl Into<(f32, f32, f32, f32)> for ImVec4 {
#[inline]
fn into(self) -> (f32, f32, f32, f32) {
(self.x, self.y, self.z, self.w)
}
}
#[test]
fn test_imvec2_memory_layout() {
use std::mem;
assert_eq!(mem::size_of::<ImVec2>(), mem::size_of::<[f32; 2]>());
assert_eq!(mem::align_of::<ImVec2>(), mem::align_of::<[f32; 2]>());
let test = ImVec2::new(1.0, 2.0);
let ref_a: &ImVec2 = &test;
let ref_b: &[f32; 2] = unsafe { mem::transmute(&test) };
assert_eq!(&ref_a.x as *const _, &ref_b[0] as *const _);
assert_eq!(&ref_a.y as *const _, &ref_b[1] as *const _);
}
#[test]
fn test_imvec4_memory_layout() {
use std::mem;
assert_eq!(mem::size_of::<ImVec4>(), mem::size_of::<[f32; 4]>());
assert_eq!(mem::align_of::<ImVec4>(), mem::align_of::<[f32; 4]>());
let test = ImVec4::new(1.0, 2.0, 3.0, 4.0);
let ref_a: &ImVec4 = &test;
let ref_b: &[f32; 4] = unsafe { mem::transmute(&test) };
assert_eq!(&ref_a.x as *const _, &ref_b[0] as *const _);
assert_eq!(&ref_a.y as *const _, &ref_b[1] as *const _);
assert_eq!(&ref_a.z as *const _, &ref_b[2] as *const _);
assert_eq!(&ref_a.w as *const _, &ref_b[3] as *const _);
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2008-2020 Bird Dog Games, Inc.
*
* This file is part of Ardor3D.
*
* Ardor3D is free software: you can redistribute it and/or modify it
* under the terms of its license which may be found in the accompanying
* LICENSE file or at <https://git.io/fjRmv>.
*/
package com.ardor3d.extension.interact.filter;
import com.ardor3d.extension.interact.InteractManager;
import com.ardor3d.extension.interact.data.SpatialState;
import com.ardor3d.extension.interact.widget.AbstractInteractWidget;
import com.ardor3d.math.type.ReadOnlyVector3;
public class AllowScaleFilter extends UpdateFilterAdapter {
protected boolean _xAxis, _yAxis, _zAxis;
public AllowScaleFilter(final boolean xAxis, final boolean yAxis, final boolean zAxis) {
_xAxis = xAxis;
_yAxis = yAxis;
_zAxis = zAxis;
}
@Override
public void applyFilter(final InteractManager manager, final AbstractInteractWidget widget) {
final ReadOnlyVector3 oldScale = manager.getSpatialTarget().getScale();
final SpatialState state = manager.getSpatialState();
final ReadOnlyVector3 scale = state.getTransform().getScale();
state.getTransform().setScale( //
_xAxis ? scale.getX() : oldScale.getX(), //
_yAxis ? scale.getY() : oldScale.getY(), //
_zAxis ? scale.getZ() : oldScale.getZ());
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2013 Luke Klinker
*
* 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.
*/
package com.klinker.android.twitter_l.adapters.emoji;
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.klinker.android.twitter_l.views.widgets.EmojiKeyboard;
import com.klinker.android.twitter_l.utils.EmojiUtils;
public class TransEmojiAdapter extends BaseEmojiAdapter {
public TransEmojiAdapter(Context context, EmojiKeyboard keyboard) {
super(context, keyboard);
if (res == null) {
init(context);
}
}
@Override
public int getCount() {
return EmojiUtils.ios ? mEmojiTextsIos.length : mEmojiTexts.length;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
int scale = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, context.getResources().getDisplayMetrics());
imageView.setPadding(scale, (int) (scale * 1.2), scale, (int) (scale * 1.2));
imageView.setAdjustViewBounds(true);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageDrawable(res.getDrawable(sIconIds[position]));
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
keyboard.insertEmoji(EmojiUtils.ios ? mEmojiTextsIos[position] : mEmojiTexts[position], sIconIds[position]);
}
});
return imageView;
}
public static final String[] mEmojiTexts = {
// transportation
"\uD83C\uDFE0", "\uD83C\uDFe1", "\uD83C\uDFE2", "\uD83C\uDFE3", "\uD83C\uDFE4",
"\uD83C\uDFE5", "\uD83C\uDFe6", "\uD83C\uDFE7", "\uD83C\uDFE8", "\uD83C\uDFE9",
"\uD83C\uDFEa", "\uD83C\uDFeb", "\u26ea", "\u26f2", "\uD83C\uDFEc",
"\uD83C\uDFEf", "\uD83C\uDFf0", "\uD83C\uDFEd", "\uD83D\uDDFB", "\uD83D\uDDFc",
"\uD83D\uDC88", "\uD83D\uDD27", "\uD83D\uDD28", "\uD83D\uDD29", "\uD83D\uDEBF",
"\uD83D\uDEc1", "\uD83D\uDEc0", "\uD83D\uDEbd", "\uD83D\uDEBe", "\uD83C\uDFbd",
"\uD83C\uDFa3", "\uD83C\uDFb1", "\uD83C\uDFb3", "\u26be", "\u26f3",
"\uD83C\uDFbe", "\u26bd", "\uD83C\uDFbf", "\uD83C\uDFc0", "\uD83C\uDFc1",
"\uD83C\uDFc2", "\uD83C\uDFc3", "\uD83C\uDFc4", "\uD83C\uDFc6", "\uD83C\uDFc7",
"\uD83D\uDC0E", "\uD83C\uDFc8", "\uD83C\uDFc9", "\uD83C\uDFca", "\uD83D\uDE82",
"\uD83D\uDE83", "\uD83D\uDE84", "\uD83D\uDE85", "\uD83D\uDE86", "\uD83D\uDE87",
"\u24c2", "\uD83D\uDE88", "\uD83D\uDE8a", "\uD83D\uDE8b", "\uD83D\uDE8c",
"\uD83D\uDE8d", "\uD83D\uDE8e", "\uD83D\uDE8f", "\uD83D\uDE90", "\uD83D\uDE91",
"\uD83D\uDE92", "\uD83D\uDE93", "\uD83D\uDE94", "\uD83D\uDE95", "\uD83D\uDE96",
"\uD83D\uDE97", "\uD83D\uDE98", "\uD83D\uDE99", "\uD83D\uDE9a", "\uD83D\uDE9b",
"\uD83D\uDE9c", "\uD83D\uDE9d", "\uD83D\uDE9e", "\uD83D\uDE9f", "\uD83D\uDEa0",
"\uD83D\uDEa1", "\uD83D\uDEa2", "\uD83D\uDEa3", "\uD83D\uDE81", "\u2708",
"\uD83D\uDEc2", "\uD83D\uDEc3", "\uD83D\uDEc4", "\uD83D\uDEc5", "\u26f5",
"\uD83D\uDEb2", "\uD83D\uDEb3", "\uD83D\uDEb4", "\uD83D\uDEb5", "\uD83D\uDEb7",
"\uD83D\uDEb8", "\uD83D\uDE89", "\uD83D\uDE80", "\uD83D\uDEa4", "\uD83D\uDEb6",
"\u26fd", "\uD83C\uDD7F", "\uD83D\uDEa5", "\uD83D\uDEa6", "\uD83D\uDEa7",
"\uD83D\uDEa8", "\u2668", "\uD83D\uDC8C", "\uD83D\uDC8d", "\uD83D\uDC8e",
"\uD83D\uDC90", "\uD83D\uDC92", "\uD83C\uDDEF\uD83C\uDDF5", "\uD83C\uDDFA\uD83C\uDDF8", "\uD83C\uDDEB\uD83C\uDDF7",
"\uD83C\uDDE9\uD83C\uDDEA", "\uD83C\uDDEE\uD83C\uDDF9", "\uD83C\uDDEC\uD83C\uDDE7", "\uD83C\uDDEA\uD83C\uDDF8", "\uD83C\uDDF7\uD83C\uDDFA",
"\uD83C\uDDE8\uD83C\uDDF3", "\uD83C\uDDF0\uD83C\uDDF7"
};
public static final String[] mEmojiTextsIos = {
// transportation
"\uD83C\uDFE0", "\uD83C\uDFe1", "\uD83C\uDFE2", "\uD83C\uDFE3", "\uD83C\uDFE4",
"\uD83C\uDFE5", "\uD83C\uDFe6", "\uD83C\uDFE7", "\uD83C\uDFE8", "\uD83C\uDFE9",
"\uD83C\uDFEa", "\uD83C\uDFeb", "\u26ea", "\u26f2", "\uD83C\uDFEc",
"\uD83C\uDFEf", "\uD83C\uDFf0", "\uD83C\uDFEd", "\uD83D\uDDFB", "\uD83D\uDDFc",
"\uD83D\uDC88", "\uD83D\uDD27", "\uD83D\uDD28", "\uD83D\uDD29", "\uD83D\uDEBF",
"\uD83D\uDEc1", "\uD83D\uDEc0", "\uD83D\uDEbd", "\uD83D\uDEBe", "\uD83C\uDFbd",
"\uD83C\uDFa3", "\uD83C\uDFb1", "\uD83C\uDFb3", "\u26be", "\u26f3",
"\uD83C\uDFbe", "\u26bd", "\uD83C\uDFbf", "\uD83C\uDFc0", "\uD83C\uDFc1",
"\uD83C\uDFc2", "\uD83C\uDFc3", "\uD83C\uDFc4", "\uD83C\uDFc6", "\uD83C\uDFc7",
"\uD83D\uDC0E", "\uD83C\uDFc8", "\uD83C\uDFc9", "\uD83C\uDFca", "\uD83D\uDE82",
"\uD83D\uDE84", "\uD83D\uDE85", "\uD83D\uDE86", "\uD83D\uDE87",
"\u24c2", "\uD83D\uDE88", "\uD83D\uDE8a", "\uD83D\uDE8b", "\uD83D\uDE8c",
"\uD83D\uDE8d", "\uD83D\uDE8e", "\uD83D\uDE8f", "\uD83D\uDE90", "\uD83D\uDE91",
"\uD83D\uDE92", "\uD83D\uDE93", "\uD83D\uDE94", "\uD83D\uDE95", "\uD83D\uDE96",
"\uD83D\uDE97", "\uD83D\uDE98", "\uD83D\uDE99", "\uD83D\uDE9a", "\uD83D\uDE9b",
"\uD83D\uDE9c", "\uD83D\uDE9d", "\uD83D\uDE9f", "\uD83D\uDEa0",
"\uD83D\uDEa1", "\uD83D\uDEa2", "\uD83D\uDEa3", "\uD83D\uDE81", "\u2708",
"\uD83D\uDEc2", "\uD83D\uDEc3", "\uD83D\uDEc4", "\uD83D\uDEc5", "\u26f5",
"\uD83D\uDEb2", "\uD83D\uDEb3", "\uD83D\uDEb4", "\uD83D\uDEb5", "\uD83D\uDEb7",
"\uD83D\uDEb8", "\uD83D\uDE89", "\uD83D\uDE80", "\uD83D\uDEa4", "\uD83D\uDEb6",
"\u26fd", "\uD83C\uDD7F", "\uD83D\uDEa5", "\uD83D\uDEa6", "\uD83D\uDEa7",
"\uD83D\uDEa8", "\u2668", "\uD83D\uDC8C", "\uD83D\uDC8d", "\uD83D\uDC8e",
"\uD83D\uDC90", "\uD83D\uDC92", "\uD83C\uDDEF\uD83C\uDDF5", "\uD83C\uDDFA\uD83C\uDDF8", "\uD83C\uDDEB\uD83C\uDDF7",
"\uD83C\uDDE9\uD83C\uDDEA", "\uD83C\uDDEE\uD83C\uDDF9", "\uD83C\uDDEC\uD83C\uDDE7", "\uD83C\uDDEA\uD83C\uDDF8", "\uD83C\uDDF7\uD83C\uDDFA",
"\uD83C\uDDE8\uD83C\uDDF3", "\uD83C\uDDF0\uD83C\uDDF7"
};
private static String pack = "com.klinker.android.emoji_keyboard_trial";
private static Resources res;
private static int[] sIconIds;
public static void init(Context context) {
try {
res = context.getPackageManager().getResourcesForApplication(pack);
} catch (Exception e) {
try {
pack = "com.klinker.android.emoji_keyboard_trial_ios";
res = context.getPackageManager().getResourcesForApplication(pack);
} catch (Exception f) {
Log.v("emoji_utils", "no emoji keyboard found");
return;
}
}
if (!EmojiUtils.ios) {
sIconIds = new int[]{
res.getIdentifier("emoji_u1f3e0", "drawable", pack),
res.getIdentifier("emoji_u1f3e1", "drawable", pack),
res.getIdentifier("emoji_u1f3e2", "drawable", pack),
res.getIdentifier("emoji_u1f3e3", "drawable", pack),
res.getIdentifier("emoji_u1f3e4", "drawable", pack),
res.getIdentifier("emoji_u1f3e5", "drawable", pack),
res.getIdentifier("emoji_u1f3e6", "drawable", pack),
res.getIdentifier("emoji_u1f3e7", "drawable", pack),
res.getIdentifier("emoji_u1f3e8", "drawable", pack),
res.getIdentifier("emoji_u1f3e9", "drawable", pack),
res.getIdentifier("emoji_u1f3ea", "drawable", pack),
res.getIdentifier("emoji_u1f3eb", "drawable", pack),
res.getIdentifier("emoji_u26ea", "drawable", pack),
res.getIdentifier("emoji_u26f2", "drawable", pack),
res.getIdentifier("emoji_u1f3ec", "drawable", pack),
res.getIdentifier("emoji_u1f3ef", "drawable", pack),
res.getIdentifier("emoji_u1f3f0", "drawable", pack),
res.getIdentifier("emoji_u1f3ed", "drawable", pack),
res.getIdentifier("emoji_u1f5fb", "drawable", pack),
res.getIdentifier("emoji_u1f5fc", "drawable", pack),
res.getIdentifier("emoji_u1f488", "drawable", pack),
res.getIdentifier("emoji_u1f527", "drawable", pack),
res.getIdentifier("emoji_u1f528", "drawable", pack),
res.getIdentifier("emoji_u1f529", "drawable", pack),
res.getIdentifier("emoji_u1f6bf", "drawable", pack),
res.getIdentifier("emoji_u1f6c1", "drawable", pack),
res.getIdentifier("emoji_u1f6c0", "drawable", pack),
res.getIdentifier("emoji_u1f6bd", "drawable", pack),
res.getIdentifier("emoji_u1f6be", "drawable", pack),
res.getIdentifier("emoji_u1f3bd", "drawable", pack),
res.getIdentifier("emoji_u1f3a3", "drawable", pack),
res.getIdentifier("emoji_u1f3b1", "drawable", pack),
res.getIdentifier("emoji_u1f3b3", "drawable", pack),
res.getIdentifier("emoji_u26be", "drawable", pack),
res.getIdentifier("emoji_u26f3", "drawable", pack),
res.getIdentifier("emoji_u1f3be", "drawable", pack),
res.getIdentifier("emoji_u26bd", "drawable", pack),
res.getIdentifier("emoji_u1f3bf", "drawable", pack),
res.getIdentifier("emoji_u1f3c0", "drawable", pack),
res.getIdentifier("emoji_u1f3c1", "drawable", pack),
res.getIdentifier("emoji_u1f3c2", "drawable", pack),
res.getIdentifier("emoji_u1f3c3", "drawable", pack),
res.getIdentifier("emoji_u1f3c4", "drawable", pack),
res.getIdentifier("emoji_u1f3c6", "drawable", pack),
res.getIdentifier("emoji_u1f3c7", "drawable", pack),
res.getIdentifier("emoji_u1f40e", "drawable", pack),
res.getIdentifier("emoji_u1f3c8", "drawable", pack),
res.getIdentifier("emoji_u1f3c9", "drawable", pack),
res.getIdentifier("emoji_u1f3ca", "drawable", pack),
res.getIdentifier("emoji_u1f682", "drawable", pack),
res.getIdentifier("emoji_u1f683", "drawable", pack),
res.getIdentifier("emoji_u1f684", "drawable", pack),
res.getIdentifier("emoji_u1f685", "drawable", pack),
res.getIdentifier("emoji_u1f686", "drawable", pack),
res.getIdentifier("emoji_u1f687", "drawable", pack),
res.getIdentifier("emoji_u24c2", "drawable", pack),
res.getIdentifier("emoji_u1f688", "drawable", pack),
res.getIdentifier("emoji_u1f68a", "drawable", pack),
res.getIdentifier("emoji_u1f68b", "drawable", pack),
res.getIdentifier("emoji_u1f68c", "drawable", pack),
res.getIdentifier("emoji_u1f68d", "drawable", pack),
res.getIdentifier("emoji_u1f68e", "drawable", pack),
res.getIdentifier("emoji_u1f68f", "drawable", pack),
res.getIdentifier("emoji_u1f690", "drawable", pack),
res.getIdentifier("emoji_u1f691", "drawable", pack),
res.getIdentifier("emoji_u1f692", "drawable", pack),
res.getIdentifier("emoji_u1f693", "drawable", pack),
res.getIdentifier("emoji_u1f694", "drawable", pack),
res.getIdentifier("emoji_u1f695", "drawable", pack),
res.getIdentifier("emoji_u1f696", "drawable", pack),
res.getIdentifier("emoji_u1f697", "drawable", pack),
res.getIdentifier("emoji_u1f698", "drawable", pack),
res.getIdentifier("emoji_u1f699", "drawable", pack),
res.getIdentifier("emoji_u1f69a", "drawable", pack),
res.getIdentifier("emoji_u1f69b", "drawable", pack),
res.getIdentifier("emoji_u1f69c", "drawable", pack),
res.getIdentifier("emoji_u1f69d", "drawable", pack),
res.getIdentifier("emoji_u1f69e", "drawable", pack),
res.getIdentifier("emoji_u1f69f", "drawable", pack),
res.getIdentifier("emoji_u1f6a0", "drawable", pack),
res.getIdentifier("emoji_u1f6a1", "drawable", pack),
res.getIdentifier("emoji_u1f6a2", "drawable", pack),
res.getIdentifier("emoji_u1f6a3", "drawable", pack),
res.getIdentifier("emoji_u1f681", "drawable", pack),
res.getIdentifier("emoji_u2708", "drawable", pack),
res.getIdentifier("emoji_u1f6c2", "drawable", pack),
res.getIdentifier("emoji_u1f6c3", "drawable", pack),
res.getIdentifier("emoji_u1f6c4", "drawable", pack),
res.getIdentifier("emoji_u1f6c5", "drawable", pack),
res.getIdentifier("emoji_u26f5", "drawable", pack),
res.getIdentifier("emoji_u1f6b2", "drawable", pack),
res.getIdentifier("emoji_u1f6b3", "drawable", pack),
res.getIdentifier("emoji_u1f6b4", "drawable", pack),
res.getIdentifier("emoji_u1f6b5", "drawable", pack),
res.getIdentifier("emoji_u1f6b7", "drawable", pack),
res.getIdentifier("emoji_u1f6b8", "drawable", pack),
res.getIdentifier("emoji_u1f689", "drawable", pack),
res.getIdentifier("emoji_u1f680", "drawable", pack),
res.getIdentifier("emoji_u1f6a4", "drawable", pack),
res.getIdentifier("emoji_u1f6b6", "drawable", pack),
res.getIdentifier("emoji_u26fd", "drawable", pack),
res.getIdentifier("emoji_u1f17f", "drawable", pack),
res.getIdentifier("emoji_u1f6a5", "drawable", pack),
res.getIdentifier("emoji_u1f6a6", "drawable", pack),
res.getIdentifier("emoji_u1f6a7", "drawable", pack),
res.getIdentifier("emoji_u1f6a8", "drawable", pack),
res.getIdentifier("emoji_u2668", "drawable", pack),
res.getIdentifier("emoji_u1f48c", "drawable", pack),
res.getIdentifier("emoji_u1f48d", "drawable", pack),
res.getIdentifier("emoji_u1f48e", "drawable", pack),
res.getIdentifier("emoji_u1f490", "drawable", pack),
res.getIdentifier("emoji_u1f492", "drawable", pack),
res.getIdentifier("emoji_ufe4e5", "drawable", pack),
res.getIdentifier("emoji_ufe4e6", "drawable", pack),
res.getIdentifier("emoji_ufe4e7", "drawable", pack),
res.getIdentifier("emoji_ufe4e8", "drawable", pack),
res.getIdentifier("emoji_ufe4e9", "drawable", pack),
res.getIdentifier("emoji_ufe4ea", "drawable", pack),
res.getIdentifier("emoji_ufe4eb", "drawable", pack),
res.getIdentifier("emoji_ufe4ec", "drawable", pack),
res.getIdentifier("emoji_ufe4ed", "drawable", pack),
res.getIdentifier("emoji_ufe4ee", "drawable", pack)
};
} else {
sIconIds = new int[]{
res.getIdentifier("emoji_u1f3e0", "drawable", pack),
res.getIdentifier("emoji_u1f3e1", "drawable", pack),
res.getIdentifier("emoji_u1f3e2", "drawable", pack),
res.getIdentifier("emoji_u1f3e3", "drawable", pack),
res.getIdentifier("emoji_u1f3e4", "drawable", pack),
res.getIdentifier("emoji_u1f3e5", "drawable", pack),
res.getIdentifier("emoji_u1f3e6", "drawable", pack),
res.getIdentifier("emoji_u1f3e7", "drawable", pack),
res.getIdentifier("emoji_u1f3e8", "drawable", pack),
res.getIdentifier("emoji_u1f3e9", "drawable", pack),
res.getIdentifier("emoji_u1f3ea", "drawable", pack),
res.getIdentifier("emoji_u1f3eb", "drawable", pack),
res.getIdentifier("emoji_u26ea", "drawable", pack),
res.getIdentifier("emoji_u26f2", "drawable", pack),
res.getIdentifier("emoji_u1f3ec", "drawable", pack),
res.getIdentifier("emoji_u1f3ef", "drawable", pack),
res.getIdentifier("emoji_u1f3f0", "drawable", pack),
res.getIdentifier("emoji_u1f3ed", "drawable", pack),
res.getIdentifier("emoji_u1f5fb", "drawable", pack),
res.getIdentifier("emoji_u1f5fc", "drawable", pack),
res.getIdentifier("emoji_u1f488", "drawable", pack),
res.getIdentifier("emoji_u1f527", "drawable", pack),
res.getIdentifier("emoji_u1f528", "drawable", pack),
res.getIdentifier("emoji_u1f529", "drawable", pack),
res.getIdentifier("emoji_u1f6bf", "drawable", pack),
res.getIdentifier("emoji_u1f6c1", "drawable", pack),
res.getIdentifier("emoji_u1f6c0", "drawable", pack),
res.getIdentifier("emoji_u1f6bd", "drawable", pack),
res.getIdentifier("emoji_u1f6be", "drawable", pack),
res.getIdentifier("emoji_u1f3bd", "drawable", pack),
res.getIdentifier("emoji_u1f3a3", "drawable", pack),
res.getIdentifier("emoji_u1f3b1", "drawable", pack),
res.getIdentifier("emoji_u1f3b3", "drawable", pack),
res.getIdentifier("emoji_u26be", "drawable", pack),
res.getIdentifier("emoji_u26f3", "drawable", pack),
res.getIdentifier("emoji_u1f3be", "drawable", pack),
res.getIdentifier("emoji_u26bd", "drawable", pack),
res.getIdentifier("emoji_u1f3bf", "drawable", pack),
res.getIdentifier("emoji_u1f3c0", "drawable", pack),
res.getIdentifier("emoji_u1f3c1", "drawable", pack),
res.getIdentifier("emoji_u1f3c2", "drawable", pack),
res.getIdentifier("emoji_u1f3c3", "drawable", pack),
res.getIdentifier("emoji_u1f3c4", "drawable", pack),
res.getIdentifier("emoji_u1f3c6", "drawable", pack),
res.getIdentifier("emoji_u1f3c7", "drawable", pack),
res.getIdentifier("emoji_u1f40e", "drawable", pack),
res.getIdentifier("emoji_u1f3c8", "drawable", pack),
res.getIdentifier("emoji_u1f3c9", "drawable", pack),
res.getIdentifier("emoji_u1f3ca", "drawable", pack),
res.getIdentifier("emoji_u1f682", "drawable", pack),
res.getIdentifier("emoji_u1f684", "drawable", pack),
res.getIdentifier("emoji_u1f685", "drawable", pack),
res.getIdentifier("emoji_u1f686", "drawable", pack),
res.getIdentifier("emoji_u1f687", "drawable", pack),
res.getIdentifier("emoji_u24c2", "drawable", pack),
res.getIdentifier("emoji_u1f688", "drawable", pack),
res.getIdentifier("emoji_u1f68a", "drawable", pack),
res.getIdentifier("emoji_u1f68b", "drawable", pack),
res.getIdentifier("emoji_u1f68c", "drawable", pack),
res.getIdentifier("emoji_u1f68d", "drawable", pack),
res.getIdentifier("emoji_u1f68e", "drawable", pack),
res.getIdentifier("emoji_u1f68f", "drawable", pack),
res.getIdentifier("emoji_u1f690", "drawable", pack),
res.getIdentifier("emoji_u1f691", "drawable", pack),
res.getIdentifier("emoji_u1f692", "drawable", pack),
res.getIdentifier("emoji_u1f693", "drawable", pack),
res.getIdentifier("emoji_u1f694", "drawable", pack),
res.getIdentifier("emoji_u1f695", "drawable", pack),
res.getIdentifier("emoji_u1f696", "drawable", pack),
res.getIdentifier("emoji_u1f697", "drawable", pack),
res.getIdentifier("emoji_u1f698", "drawable", pack),
res.getIdentifier("emoji_u1f699", "drawable", pack),
res.getIdentifier("emoji_u1f69a", "drawable", pack),
res.getIdentifier("emoji_u1f69b", "drawable", pack),
res.getIdentifier("emoji_u1f69c", "drawable", pack),
res.getIdentifier("emoji_u1f69d", "drawable", pack),
res.getIdentifier("emoji_u1f69f", "drawable", pack),
res.getIdentifier("emoji_u1f6a0", "drawable", pack),
res.getIdentifier("emoji_u1f6a1", "drawable", pack),
res.getIdentifier("emoji_u1f6a2", "drawable", pack),
res.getIdentifier("emoji_u1f6a3", "drawable", pack),
res.getIdentifier("emoji_u1f681", "drawable", pack),
res.getIdentifier("emoji_u2708", "drawable", pack),
res.getIdentifier("emoji_u1f6c2", "drawable", pack),
res.getIdentifier("emoji_u1f6c3", "drawable", pack),
res.getIdentifier("emoji_u1f6c4", "drawable", pack),
res.getIdentifier("emoji_u1f6c5", "drawable", pack),
res.getIdentifier("emoji_u26f5", "drawable", pack),
res.getIdentifier("emoji_u1f6b2", "drawable", pack),
res.getIdentifier("emoji_u1f6b3", "drawable", pack),
res.getIdentifier("emoji_u1f6b4", "drawable", pack),
res.getIdentifier("emoji_u1f6b5", "drawable", pack),
res.getIdentifier("emoji_u1f6b7", "drawable", pack),
res.getIdentifier("emoji_u1f6b8", "drawable", pack),
res.getIdentifier("emoji_u1f689", "drawable", pack),
res.getIdentifier("emoji_u1f680", "drawable", pack),
res.getIdentifier("emoji_u1f6a4", "drawable", pack),
res.getIdentifier("emoji_u1f6b6", "drawable", pack),
res.getIdentifier("emoji_u26fd", "drawable", pack),
res.getIdentifier("emoji_u1f17f", "drawable", pack),
res.getIdentifier("emoji_u1f6a5", "drawable", pack),
res.getIdentifier("emoji_u1f6a6", "drawable", pack),
res.getIdentifier("emoji_u1f6a7", "drawable", pack),
res.getIdentifier("emoji_u1f6a8", "drawable", pack),
res.getIdentifier("emoji_u2668", "drawable", pack),
res.getIdentifier("emoji_u1f48c", "drawable", pack),
res.getIdentifier("emoji_u1f48d", "drawable", pack),
res.getIdentifier("emoji_u1f48e", "drawable", pack),
res.getIdentifier("emoji_u1f490", "drawable", pack),
res.getIdentifier("emoji_u1f492", "drawable", pack),
res.getIdentifier("emoji_ufe4e5", "drawable", pack),
res.getIdentifier("emoji_ufe4e6", "drawable", pack),
res.getIdentifier("emoji_ufe4e7", "drawable", pack),
res.getIdentifier("emoji_ufe4e8", "drawable", pack),
res.getIdentifier("emoji_ufe4e9", "drawable", pack),
res.getIdentifier("emoji_ufe4ea", "drawable", pack),
res.getIdentifier("emoji_ufe4eb", "drawable", pack),
res.getIdentifier("emoji_ufe4ec", "drawable", pack),
res.getIdentifier("emoji_ufe4ed", "drawable", pack),
res.getIdentifier("emoji_ufe4ee", "drawable", pack)
};
}
}
} | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug-static|Win32">
<Configuration>Debug-static</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug-static|x64">
<Configuration>Debug-static</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release-static|Win32">
<Configuration>Release-static</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release-static|x64">
<Configuration>Release-static</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\..\..\src\arena.c" />
<ClCompile Include="..\..\..\..\src\background_thread.c" />
<ClCompile Include="..\..\..\..\src\base.c" />
<ClCompile Include="..\..\..\..\src\bin.c" />
<ClCompile Include="..\..\..\..\src\bitmap.c" />
<ClCompile Include="..\..\..\..\src\ckh.c" />
<ClCompile Include="..\..\..\..\src\ctl.c" />
<ClCompile Include="..\..\..\..\src\div.c" />
<ClCompile Include="..\..\..\..\src\extent.c" />
<ClCompile Include="..\..\..\..\src\extent_dss.c" />
<ClCompile Include="..\..\..\..\src\extent_mmap.c" />
<ClCompile Include="..\..\..\..\src\hash.c" />
<ClCompile Include="..\..\..\..\src\hook.c" />
<ClCompile Include="..\..\..\..\src\jemalloc.c" />
<ClCompile Include="..\..\..\..\src\large.c" />
<ClCompile Include="..\..\..\..\src\log.c" />
<ClCompile Include="..\..\..\..\src\malloc_io.c" />
<ClCompile Include="..\..\..\..\src\mutex.c" />
<ClCompile Include="..\..\..\..\src\mutex_pool.c" />
<ClCompile Include="..\..\..\..\src\nstime.c" />
<ClCompile Include="..\..\..\..\src\pages.c" />
<ClCompile Include="..\..\..\..\src\prng.c" />
<ClCompile Include="..\..\..\..\src\prof.c" />
<ClCompile Include="..\..\..\..\src\rtree.c" />
<ClCompile Include="..\..\..\..\src\sc.c" />
<ClCompile Include="..\..\..\..\src\stats.c" />
<ClCompile Include="..\..\..\..\src\sz.c" />
<ClCompile Include="..\..\..\..\src\tcache.c" />
<ClCompile Include="..\..\..\..\src\ticker.c" />
<ClCompile Include="..\..\..\..\src\tsd.c" />
<ClCompile Include="..\..\..\..\src\witness.c" />
<ClCompile Include="..\..\..\..\src\safety_check.c" />
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{8D6BB292-9E1C-413D-9F98-4864BDC1514A}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>jemalloc</RootNamespace>
<WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<TargetName>$(ProjectName)d</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|Win32'">
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformToolset)-$(Configuration)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|Win32'">
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformToolset)-$(Configuration)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<TargetName>$(ProjectName)d</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|x64'">
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<TargetName>$(ProjectName)-vc$(PlatformToolsetVersion)-$(Configuration)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|x64'">
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<TargetName>$(ProjectName)-vc$(PlatformToolsetVersion)-$(Configuration)</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>JEMALLOC_NO_PRIVATE_NAMESPACE;_REENTRANT;_WINDLL;DLLEXPORT;JEMALLOC_DEBUG;_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<DisableSpecificWarnings>4090;4146;4267;4334</DisableSpecificWarnings>
<ProgramDataBaseFileName>$(OutputPath)$(TargetName).pdb</ProgramDataBaseFileName>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>JEMALLOC_NO_PRIVATE_NAMESPACE;JEMALLOC_DEBUG;_REENTRANT;JEMALLOC_EXPORT=;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<DisableSpecificWarnings>4090;4146;4267;4334</DisableSpecificWarnings>
<ProgramDataBaseFileName>$(OutputPath)$(TargetName).pdb</ProgramDataBaseFileName>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>JEMALLOC_NO_PRIVATE_NAMESPACE;_REENTRANT;_WINDLL;DLLEXPORT;JEMALLOC_DEBUG;_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<DisableSpecificWarnings>4090;4146;4267;4334</DisableSpecificWarnings>
<ProgramDataBaseFileName>$(OutputPath)$(TargetName).pdb</ProgramDataBaseFileName>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>JEMALLOC_NO_PRIVATE_NAMESPACE;JEMALLOC_DEBUG;_REENTRANT;JEMALLOC_EXPORT=;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<DisableSpecificWarnings>4090;4146;4267;4334</DisableSpecificWarnings>
<DebugInformationFormat>OldStyle</DebugInformationFormat>
<MinimalRebuild>false</MinimalRebuild>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>JEMALLOC_NO_PRIVATE_NAMESPACE;_REENTRANT;_WINDLL;DLLEXPORT;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<DisableSpecificWarnings>4090;4146;4267;4334</DisableSpecificWarnings>
<ProgramDataBaseFileName>$(OutputPath)$(TargetName).pdb</ProgramDataBaseFileName>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>JEMALLOC_NO_PRIVATE_NAMESPACE;_REENTRANT;JEMALLOC_EXPORT=;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<DisableSpecificWarnings>4090;4146;4267;4334</DisableSpecificWarnings>
<ProgramDataBaseFileName>$(OutputPath)$(TargetName).pdb</ProgramDataBaseFileName>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<AdditionalIncludeDirectories>..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>JEMALLOC_NO_PRIVATE_NAMESPACE;_REENTRANT;_WINDLL;DLLEXPORT;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<DisableSpecificWarnings>4090;4146;4267;4334</DisableSpecificWarnings>
<ProgramDataBaseFileName>$(OutputPath)$(TargetName).pdb</ProgramDataBaseFileName>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>JEMALLOC_NO_PRIVATE_NAMESPACE;_REENTRANT;JEMALLOC_EXPORT=;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<DisableSpecificWarnings>4090;4146;4267;4334</DisableSpecificWarnings>
<DebugInformationFormat>OldStyle</DebugInformationFormat>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
| {
"pile_set_name": "Github"
} |
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var prefix = 'fab';
var iconName = 'odnoklassniki-square';
var width = 448;
var height = 512;
var ligatures = [];
var unicode = 'f264';
var svgPathData = 'M184.2 177.1c0-22.1 17.9-40 39.8-40s39.8 17.9 39.8 40c0 22-17.9 39.8-39.8 39.8s-39.8-17.9-39.8-39.8zM448 80v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V80c0-26.5 21.5-48 48-48h352c26.5 0 48 21.5 48 48zm-305.1 97.1c0 44.6 36.4 80.9 81.1 80.9s81.1-36.2 81.1-80.9c0-44.8-36.4-81.1-81.1-81.1s-81.1 36.2-81.1 81.1zm174.5 90.7c-4.6-9.1-17.3-16.8-34.1-3.6 0 0-22.7 18-59.3 18s-59.3-18-59.3-18c-16.8-13.2-29.5-5.5-34.1 3.6-7.9 16.1 1.1 23.7 21.4 37 17.3 11.1 41.2 15.2 56.6 16.8l-12.9 12.9c-18.2 18-35.5 35.5-47.7 47.7-17.6 17.6 10.7 45.8 28.4 28.6l47.7-47.9c18.2 18.2 35.7 35.7 47.7 47.9 17.6 17.2 46-10.7 28.6-28.6l-47.7-47.7-13-12.9c15.5-1.6 39.1-5.9 56.2-16.8 20.4-13.3 29.3-21 21.5-37z';
exports.definition = {
prefix: prefix,
iconName: iconName,
icon: [
width,
height,
ligatures,
unicode,
svgPathData
]};
exports.faOdnoklassnikiSquare = exports.definition;
exports.prefix = prefix;
exports.iconName = iconName;
exports.width = width;
exports.height = height;
exports.ligatures = ligatures;
exports.unicode = unicode;
exports.svgPathData = svgPathData; | {
"pile_set_name": "Github"
} |
<?php
namespace classes\chaining_test;
class Class1
{
public static $x;
public static $y;
};
Class1::$x->a->b->c[0][1][2]->x["A"]->y["B"]->z["C"] = "Hujer";
Class1::$y->a->b->c[0][1][2]->x["A"]->y["B"]->z["C"] =& Class1::$x->a->b->c;
echo Class1::$y->a->b->c[0][1][2]->x["A"]->y["B"]->z["C"][0][1][2]->x["A"]->y["B"]->z["C"];
| {
"pile_set_name": "Github"
} |
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Communicator client code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# This library 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 library 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 this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from . import constants
# KOI8-R language model
# Character Mapping Table:
KOI8R_CharToOrderMap = (
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40
155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50
253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60
67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70
191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206, # 80
207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222, # 90
223,224,225, 68,226,227,228,229,230,231,232,233,234,235,236,237, # a0
238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253, # b0
27, 3, 21, 28, 13, 2, 39, 19, 26, 4, 23, 11, 8, 12, 5, 1, # c0
15, 16, 9, 7, 6, 14, 24, 10, 17, 18, 20, 25, 30, 29, 22, 54, # d0
59, 37, 44, 58, 41, 48, 53, 46, 55, 42, 60, 36, 49, 38, 31, 34, # e0
35, 43, 45, 32, 40, 52, 56, 33, 61, 62, 51, 57, 47, 63, 50, 70, # f0
)
win1251_CharToOrderMap = (
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40
155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50
253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60
67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70
191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,
207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,
223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,
239,240,241,242,243,244,245,246, 68,247,248,249,250,251,252,253,
37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35,
45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43,
3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15,
9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27, 16,
)
latin5_CharToOrderMap = (
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40
155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50
253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60
67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70
191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,
207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,
223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,
37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35,
45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43,
3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15,
9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27, 16,
239, 68,240,241,242,243,244,245,246,247,248,249,250,251,252,255,
)
macCyrillic_CharToOrderMap = (
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40
155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50
253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60
67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70
37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35,
45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43,
191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,
207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,
223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,
239,240,241,242,243,244,245,246,247,248,249,250,251,252, 68, 16,
3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15,
9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27,255,
)
IBM855_CharToOrderMap = (
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40
155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50
253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60
67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70
191,192,193,194, 68,195,196,197,198,199,200,201,202,203,204,205,
206,207,208,209,210,211,212,213,214,215,216,217, 27, 59, 54, 70,
3, 37, 21, 44, 28, 58, 13, 41, 2, 48, 39, 53, 19, 46,218,219,
220,221,222,223,224, 26, 55, 4, 42,225,226,227,228, 23, 60,229,
230,231,232,233,234,235, 11, 36,236,237,238,239,240,241,242,243,
8, 49, 12, 38, 5, 31, 1, 34, 15,244,245,246,247, 35, 16,248,
43, 9, 45, 7, 32, 6, 40, 14, 52, 24, 56, 10, 33, 17, 61,249,
250, 18, 62, 20, 51, 25, 57, 30, 47, 29, 63, 22, 50,251,252,255,
)
IBM866_CharToOrderMap = (
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40
155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50
253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60
67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70
37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35,
45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43,
3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15,
191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,
207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,
223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,
9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27, 16,
239, 68,240,241,242,243,244,245,246,247,248,249,250,251,252,255,
)
# Model Table:
# total sequences: 100%
# first 512 sequences: 97.6601%
# first 1024 sequences: 2.3389%
# rest sequences: 0.1237%
# negative sequences: 0.0009%
RussianLangModel = (
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,1,3,3,3,3,1,3,3,3,2,3,2,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,2,2,2,2,2,0,0,2,
3,3,3,2,3,3,3,3,3,3,3,3,3,3,2,3,3,0,0,3,3,3,3,3,3,3,3,3,2,3,2,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,2,2,3,3,3,3,3,3,3,3,3,2,3,3,0,0,3,3,3,3,3,3,3,3,2,3,3,1,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,2,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,0,0,3,3,3,3,3,3,3,3,3,3,3,2,1,
0,0,0,0,0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,0,0,3,3,3,3,3,3,3,3,3,3,3,2,1,
0,0,0,0,0,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,2,2,2,3,1,3,3,1,3,3,3,3,2,2,3,0,2,2,2,3,3,2,1,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,2,3,3,3,3,3,2,2,3,2,3,3,3,2,1,2,2,0,1,2,2,2,2,2,2,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,3,0,2,2,3,3,2,1,2,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,2,3,3,1,2,3,2,2,3,2,3,3,3,3,2,2,3,0,3,2,2,3,1,1,1,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,2,2,3,3,3,3,3,2,3,3,3,3,2,2,2,0,3,3,3,2,2,2,2,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,3,3,2,3,2,3,3,3,3,3,3,2,3,2,2,0,1,3,2,1,2,2,1,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,3,3,3,2,1,1,3,0,1,1,1,1,2,1,1,0,2,2,2,1,2,0,1,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,2,3,3,2,2,2,2,1,3,2,3,2,3,2,1,2,2,0,1,1,2,1,2,1,2,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,3,3,3,3,3,3,2,2,3,2,3,3,3,2,2,2,2,0,2,2,2,2,3,1,1,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
3,2,3,2,2,3,3,3,3,3,3,3,3,3,1,3,2,0,0,3,3,3,3,2,3,3,3,3,2,3,2,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,3,3,3,3,3,2,2,3,3,0,2,1,0,3,2,3,2,3,0,0,1,2,0,0,1,0,1,2,1,1,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,0,3,0,2,3,3,3,3,2,3,3,3,3,1,2,2,0,0,2,3,2,2,2,3,2,3,2,2,3,0,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,2,3,0,2,3,2,3,0,1,2,3,3,2,0,2,3,0,0,2,3,2,2,0,1,3,1,3,2,2,1,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,1,3,0,2,3,3,3,3,3,3,3,3,2,1,3,2,0,0,2,2,3,3,3,2,3,3,0,2,2,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,2,2,3,3,2,2,2,3,3,0,0,1,1,1,1,1,2,0,0,1,1,1,1,0,1,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,2,2,3,3,3,3,3,3,3,0,3,2,3,3,2,3,2,0,2,1,0,1,1,0,1,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,3,2,3,3,3,2,2,2,2,3,1,3,2,3,1,1,2,1,0,2,2,2,2,1,3,1,0,
0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
2,2,3,3,3,3,3,1,2,2,1,3,1,0,3,0,0,3,0,0,0,1,1,0,1,2,1,0,0,0,0,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,2,2,1,1,3,3,3,2,2,1,2,2,3,1,1,2,0,0,2,2,1,3,0,0,2,1,1,2,1,1,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,2,3,3,3,3,1,2,2,2,1,2,1,3,3,1,1,2,1,2,1,2,2,0,2,0,0,1,1,0,1,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,3,3,3,3,3,2,1,3,2,2,3,2,0,3,2,0,3,0,1,0,1,1,0,0,1,1,1,1,0,1,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,2,3,3,3,2,2,2,3,3,1,2,1,2,1,0,1,0,1,1,0,1,0,0,2,1,1,1,0,1,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,
3,1,1,2,1,2,3,3,2,2,1,2,2,3,0,2,1,0,0,2,2,3,2,1,2,2,2,2,2,3,1,0,
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3,3,3,3,3,1,1,0,1,1,2,2,1,1,3,0,0,1,3,1,1,1,0,0,0,1,0,1,1,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,1,3,3,3,2,0,0,0,2,1,0,1,0,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,0,1,0,0,2,3,2,2,2,1,2,2,2,1,2,1,0,0,1,1,1,0,2,0,1,1,1,0,0,1,1,
1,0,0,0,0,0,1,2,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,
2,3,3,3,3,0,0,0,0,1,0,0,0,0,3,0,1,2,1,0,0,0,0,0,0,0,1,1,0,0,1,1,
1,0,1,0,1,2,0,0,1,1,2,1,0,1,1,1,1,0,1,1,1,1,0,1,0,0,1,0,0,1,1,0,
2,2,3,2,2,2,3,1,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,0,1,0,1,1,1,0,2,1,
1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1,0,1,1,0,
3,3,3,2,2,2,2,3,2,2,1,1,2,2,2,2,1,1,3,1,2,1,2,0,0,1,1,0,1,0,2,1,
1,1,1,1,1,2,1,0,1,1,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,1,0,
2,0,0,1,0,3,2,2,2,2,1,2,1,2,1,2,0,0,0,2,1,2,2,1,1,2,2,0,1,1,0,2,
1,1,1,1,1,0,1,1,1,2,1,1,1,2,1,0,1,2,1,1,1,1,0,1,1,1,0,0,1,0,0,1,
1,3,2,2,2,1,1,1,2,3,0,0,0,0,2,0,2,2,1,0,0,0,0,0,0,1,0,0,0,0,1,1,
1,0,1,1,0,1,0,1,1,0,1,1,0,2,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,
2,3,2,3,2,1,2,2,2,2,1,0,0,0,2,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,2,1,
1,1,2,1,0,2,0,0,1,0,1,0,0,1,0,0,1,1,0,1,1,0,0,0,0,0,1,0,0,0,0,0,
3,0,0,1,0,2,2,2,3,2,2,2,2,2,2,2,0,0,0,2,1,2,1,1,1,2,2,0,0,0,1,2,
1,1,1,1,1,0,1,2,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0,0,1,
2,3,2,3,3,2,0,1,1,1,0,0,1,0,2,0,1,1,3,1,0,0,0,0,0,0,0,1,0,0,2,1,
1,1,1,1,1,1,1,0,1,0,1,1,1,1,0,1,1,1,0,0,1,1,0,1,0,0,0,0,0,0,1,0,
2,3,3,3,3,1,2,2,2,2,0,1,1,0,2,1,1,1,2,1,0,1,1,0,0,1,0,1,0,0,2,0,
0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2,3,3,3,2,0,0,1,1,2,2,1,0,0,2,0,1,1,3,0,0,1,0,0,0,0,0,1,0,1,2,1,
1,1,2,0,1,1,1,0,1,0,1,1,0,1,0,1,1,1,1,0,1,0,0,0,0,0,0,1,0,1,1,0,
1,3,2,3,2,1,0,0,2,2,2,0,1,0,2,0,1,1,1,0,1,0,0,0,3,0,1,1,0,0,2,1,
1,1,1,0,1,1,0,0,0,0,1,1,0,1,0,0,2,1,1,0,1,0,0,0,1,0,1,0,0,1,1,0,
3,1,2,1,1,2,2,2,2,2,2,1,2,2,1,1,0,0,0,2,2,2,0,0,0,1,2,1,0,1,0,1,
2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,2,1,1,1,0,1,0,1,1,0,1,1,1,0,0,1,
3,0,0,0,0,2,0,1,1,1,1,1,1,1,0,1,0,0,0,1,1,1,0,1,0,1,1,0,0,1,0,1,
1,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,1,0,0,0,0,1,0,0,0,1,0,0,0,1,
1,3,3,2,2,0,0,0,2,2,0,0,0,1,2,0,1,1,2,0,0,0,0,0,0,0,0,1,0,0,2,1,
0,1,1,0,0,1,1,0,0,0,1,1,0,1,1,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,1,0,
2,3,2,3,2,0,0,0,0,1,1,0,0,0,2,0,2,0,2,0,0,0,0,0,1,0,0,1,0,0,1,1,
1,1,2,0,1,2,1,0,1,1,2,1,1,1,1,1,2,1,1,0,1,0,0,1,1,1,1,1,0,1,1,0,
1,3,2,2,2,1,0,0,2,2,1,0,1,2,2,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,
0,0,1,1,0,1,1,0,0,1,1,0,1,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
1,0,0,1,0,2,3,1,2,2,2,2,2,2,1,1,0,0,0,1,0,1,0,2,1,1,1,0,0,0,0,1,
1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,
2,0,2,0,0,1,0,3,2,1,2,1,2,2,0,1,0,0,0,2,1,0,0,2,1,1,1,1,0,2,0,2,
2,1,1,1,1,1,1,1,1,1,1,1,1,2,1,0,1,1,1,1,0,0,0,1,1,1,1,0,1,0,0,1,
1,2,2,2,2,1,0,0,1,0,0,0,0,0,2,0,1,1,1,1,0,0,0,0,1,0,1,2,0,0,2,0,
1,0,1,1,1,2,1,0,1,0,1,1,0,0,1,0,1,1,1,0,1,0,0,0,1,0,0,1,0,1,1,0,
2,1,2,2,2,0,3,0,1,1,0,0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
0,0,0,1,1,1,0,0,1,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,
1,2,2,3,2,2,0,0,1,1,2,0,1,2,1,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1,
0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,1,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,
2,2,1,1,2,1,2,2,2,2,2,1,2,2,0,1,0,0,0,1,2,2,2,1,2,1,1,1,1,1,2,1,
1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,0,1,1,1,0,0,0,0,1,1,1,0,1,1,0,0,1,
1,2,2,2,2,0,1,0,2,2,0,0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,
0,0,1,0,0,1,0,0,0,0,1,0,1,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,2,2,2,2,0,0,0,2,2,2,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,
0,1,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,2,2,2,2,0,0,0,0,1,0,0,1,1,2,0,0,0,0,1,0,1,0,0,1,0,0,2,0,0,0,1,
0,0,1,0,0,1,0,0,0,1,1,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,
1,2,2,2,1,1,2,0,2,1,1,1,1,0,2,2,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,1,
0,0,1,0,1,1,0,0,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
1,0,2,1,2,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,
0,0,1,0,1,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,
1,0,0,0,0,2,0,1,2,1,0,1,1,1,0,1,0,0,0,1,0,1,0,0,1,0,1,0,0,0,0,1,
0,0,0,0,0,1,0,0,1,1,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,
2,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,
2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,1,1,0,1,0,1,0,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,0,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,1,0,1,1,0,1,0,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,0,
0,1,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,
)
Koi8rModel = {
'charToOrderMap': KOI8R_CharToOrderMap,
'precedenceMatrix': RussianLangModel,
'mTypicalPositiveRatio': 0.976601,
'keepEnglishLetter': False,
'charsetName': "KOI8-R"
}
Win1251CyrillicModel = {
'charToOrderMap': win1251_CharToOrderMap,
'precedenceMatrix': RussianLangModel,
'mTypicalPositiveRatio': 0.976601,
'keepEnglishLetter': False,
'charsetName': "windows-1251"
}
Latin5CyrillicModel = {
'charToOrderMap': latin5_CharToOrderMap,
'precedenceMatrix': RussianLangModel,
'mTypicalPositiveRatio': 0.976601,
'keepEnglishLetter': False,
'charsetName': "ISO-8859-5"
}
MacCyrillicModel = {
'charToOrderMap': macCyrillic_CharToOrderMap,
'precedenceMatrix': RussianLangModel,
'mTypicalPositiveRatio': 0.976601,
'keepEnglishLetter': False,
'charsetName': "MacCyrillic"
};
Ibm866Model = {
'charToOrderMap': IBM866_CharToOrderMap,
'precedenceMatrix': RussianLangModel,
'mTypicalPositiveRatio': 0.976601,
'keepEnglishLetter': False,
'charsetName': "IBM866"
}
Ibm855Model = {
'charToOrderMap': IBM855_CharToOrderMap,
'precedenceMatrix': RussianLangModel,
'mTypicalPositiveRatio': 0.976601,
'keepEnglishLetter': False,
'charsetName': "IBM855"
}
# flake8: noqa
| {
"pile_set_name": "Github"
} |
:10FC000001C0F2C0112484B790E890936100109273
:10FC10006100882369F0982F9A70923049F081FF33
:10FC200002C097EF94BF282E80E001D10C94000011
:10FC300085E08093810082E08093300188E18093A9
:10FC4000310188E08093340186E0809332018EE0B8
:10FC5000EED0279A84E028E13EEF91E030938500D2
:10FC60002093840096BBB09BFECF1F9AA89540912D
:10FC7000300147FD02C0815089F7CDD0813479F43D
:10FC8000CAD0C82FDAD0C23829F480E0BDD080E1D4
:10FC9000BBD0F3CF83E0C138C9F788E0F7CF823417
:10FCA00019F484E1D2D0F3CF853411F485E0FACF92
:10FCB000853581F4B0D0E82EAED0F82E87FF07C08E
:10FCC0008BB781608BBFEE0CFF1CB7D0E0CF8BB73A
:10FCD0008E7FF8CF863579F49ED08D3451F49BD049
:10FCE000CBB799D0C170880F8C2B8BBF81E0ADD082
:10FCF000CCCF83E0FCCF843609F046C08CD0C82F2F
:10FD0000D0E0DC2FCC2787D0C82B85D0D82E5E0141
:10FD10008EEFB81A00E012E04801EFEF8E1A9E0A4B
:10FD20007AD0F801808384018A149B04A9F785D0D6
:10FD3000F5E410E000E0DF1609F150E040E063E098
:10FD4000C70152D08701C12C92E0D92EF601419112
:10FD500051916F0161E0C80147D00E5F1F4F22979C
:10FD6000A9F750E040E065E0C7013ED090CF608148
:10FD7000C8018E0D9F1D78D00F5F1F4FF801FE5FE9
:10FD8000C017D107A1F783CF843701F544D0C82F1E
:10FD9000D0E0DC2FCC273FD0C82B3DD0D82E4DD083
:10FDA0008701F5E4DF120BC0CE0DDF1DC80154D072
:10FDB0002BD00F5F1F4FC017D107C1F768CFF801D5
:10FDC00087918F0121D02197D1F761CF853731F409
:10FDD00034D08EE119D086E917D05FCF813509F094
:10FDE00074CF88E024D071CFFC010A0167BFE89589
:10FDF000112407B600FCFDCF667029F0452B19F4DD
:10FE000081E187BFE89508959091300195FFFCCF7F
:10FE10008093360108958091300187FFFCCF809157
:10FE2000300184FD01C0A895809136010895E0E677
:10FE3000F0E098E1908380830895EDDF803219F03F
:10FE400088E0F5DFFFCF84E1DFCFCF93C82FE3DF7A
:10FE5000C150E9F7CF91F1CFF999FECF92BD81BDA5
:10FE6000F89A992780B50895262FF999FECF1FBAE1
:10FE700092BD81BD20BD0FB6F894FA9AF99A0FBED3
:04FE8000019608954A
:02FFFE000008F9
:040000030000FC00FD
:00000001FF
| {
"pile_set_name": "Github"
} |
using FluentMigrator.Builders.Create.Table;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Discounts;
using Nop.Data.Extensions;
namespace Nop.Data.Mapping.Builders.Discounts
{
/// <summary>
/// Represents a discount manufacturer mapping entity builder
/// </summary>
public partial class DiscountManufacturerMappingBuilder : NopEntityBuilder<DiscountManufacturerMapping>
{
#region Methods
/// <summary>
/// Apply entity configuration
/// </summary>
/// <param name="table">Create table expression builder</param>
public override void MapEntity(CreateTableExpressionBuilder table)
{
table
.WithColumn(NameCompatibilityManager.GetColumnName(typeof(DiscountManufacturerMapping), nameof(DiscountManufacturerMapping.DiscountId)))
.AsInt32().PrimaryKey().ForeignKey<Discount>()
.WithColumn(NameCompatibilityManager.GetColumnName(typeof(DiscountManufacturerMapping), nameof(DiscountManufacturerMapping.EntityId)))
.AsInt32().PrimaryKey().ForeignKey<Manufacturer>();
}
#endregion
}
} | {
"pile_set_name": "Github"
} |
chip_shape: [4.0, 4.0]
description: QFN-20-EP-MAX for MAX17503
ep_mask_shape: [0.85, 0.85, 0.28, 0.28]
ep_paste_shape: [0.85, 0.85, 0.28, 0.28]
ep_shape: [2.85, 2.85]
ep_vias: [0.35, 0.5, 0.65]
model:
offset: [0, 0, 0]
path: ${KISYS3DMOD}/Housings_DFN_QFN.3dshapes/QFN-20-1EP_4x4mm_Pitch0.5mm.wrl
rotate: [0, 0, 0]
scale: [1, 1, 1]
name: QFN-20-EP-MAX
pad_shape: [0.6, 0.3]
pin_pitch: 0.5
pin_shape: [-0.55, 0.25]
pins: 20
row_pitch: 3.85
rows: 4
| {
"pile_set_name": "Github"
} |
range-set ::= range ( logical-or range ) *
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
range ::= hyphen | simple ( ' ' simple ) * | ''
hyphen ::= partial ' - ' partial
simple ::= primitive | partial | tilde | caret
primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
xr ::= 'x' | 'X' | '*' | nr
nr ::= '0' | [1-9] ( [0-9] ) *
tilde ::= '~' partial
caret ::= '^' partial
qualifier ::= ( '-' pre )? ( '+' build )?
pre ::= parts
build ::= parts
parts ::= part ( '.' part ) *
part ::= nr | [-0-9A-Za-z]+
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\DICOM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class VelocityEncodingMaximumValue extends AbstractTag
{
protected $Id = '0018,9217';
protected $Name = 'VelocityEncodingMaximumValue';
protected $FullName = 'DICOM::Main';
protected $GroupName = 'DICOM';
protected $g0 = 'DICOM';
protected $g1 = 'DICOM';
protected $g2 = 'Image';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Velocity Encoding Maximum Value';
}
| {
"pile_set_name": "Github"
} |
// { dg-options "-std=gnu++17" }
// { dg-skip-if "" { *-*-* } { "-D_GLIBCXX_PROFILE" } }
// Copyright (C) 2015-2019 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option)
// any later version.
// This library 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 library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include <utility>
#include <map>
#include <testsuite_hooks.h>
struct Val
{
bool moved_from_ctor = false;
bool moved_from_assign = false;
int val;
Val(int val = 0) : val(val) {}
Val(const Val& other) : val(other.val)
{
}
Val(Val&& other) : val(other.val)
{
other.moved_from_ctor = true;
}
Val& operator=(Val&& other)
{
val = other.val;
other.moved_from_assign = true;
return *this;
}
Val& operator=(const Val& other)
{
val = other.val;
return *this;
}
};
bool operator<(const Val& a, const Val& b)
{
return a.val < b.val;
}
void test01()
{
typedef std::map<int, Val> Map;
Map m;
auto res1 = m.insert_or_assign(0, Val(5));
VERIFY(res1.second);
VERIFY(res1.first != m.end());
VERIFY(m[0].val == 5);
Val v1{6};
VERIFY(m.size() == 1);
auto res2 = m.insert_or_assign(0, std::move(v1));
VERIFY(!res2.second);
VERIFY(res2.first == res1.first);
VERIFY(m[0].val == 6);
VERIFY(!v1.moved_from_ctor);
VERIFY(v1.moved_from_assign);
VERIFY(m.size() == 1);
v1.moved_from_assign = false;
auto res3 = m.insert_or_assign(1, std::move(v1));
VERIFY(res3.first != res1.first && res3.first != m.end());
VERIFY(res3.second);
VERIFY(m[0].val == 6);
VERIFY(m[1].val == 6);
VERIFY(v1.moved_from_ctor);
VERIFY(!v1.moved_from_assign);
VERIFY(m.size() == 2);
}
void test02()
{
typedef std::map<int, Val> Map;
Map m;
auto res1 = m.insert_or_assign(m.begin(), 0, Val(5));
VERIFY(res1 != m.end());
VERIFY(m[0].val == 5);
Val v1{6};
VERIFY(m.size() == 1);
auto res2 = m.insert_or_assign(m.begin(), 0, std::move(v1));
VERIFY(res2 == res1);
VERIFY(m[0].val == 6);
VERIFY(!v1.moved_from_ctor);
VERIFY(v1.moved_from_assign);
VERIFY(m.size() == 1);
v1.moved_from_assign = false;
auto res3 = m.insert_or_assign(m.begin(), 1, std::move(v1));
VERIFY(res3 != res1 && res3 != m.end());
VERIFY(m[0].val == 6);
VERIFY(m[1].val == 6);
VERIFY(v1.moved_from_ctor);
VERIFY(!v1.moved_from_assign);
VERIFY(m.size() == 2);
}
void test03()
{
typedef std::map<Val, Val> Map;
Map m;
auto res1 = m.insert_or_assign(0, Val(5));
VERIFY(res1.second);
VERIFY(res1.first != m.end());
VERIFY(m[0].val == 5);
Val k1{0};
Val v1{6};
VERIFY(m.size() == 1);
auto res2 = m.insert_or_assign(std::move(k1), std::move(v1));
VERIFY(!res2.second);
VERIFY(res2.first == res1.first);
VERIFY(m[0].val == 6);
VERIFY(!k1.moved_from_ctor);
VERIFY(!k1.moved_from_assign);
VERIFY(!v1.moved_from_ctor);
VERIFY(v1.moved_from_assign);
VERIFY(m.size() == 1);
Val k2{1};
v1.moved_from_assign = false;
auto res3 = m.insert_or_assign(std::move(k2), std::move(v1));
VERIFY(res3.first != res1.first && res3.first != m.end());
VERIFY(res3.second);
VERIFY(m[0].val == 6);
VERIFY(m[1].val == 6);
VERIFY(k2.moved_from_ctor);
VERIFY(!k2.moved_from_assign);
VERIFY(v1.moved_from_ctor);
VERIFY(!v1.moved_from_assign);
VERIFY(m.size() == 2);
}
void test04()
{
typedef std::map<Val, Val> Map;
Map m;
auto res1 = m.insert_or_assign(m.begin(), 0, Val(5));
VERIFY(res1 != m.end());
VERIFY(m[0].val == 5);
Val k1{0};
Val v1{6};
VERIFY(m.size() == 1);
auto res2 = m.insert_or_assign(m.begin(), std::move(k1), std::move(v1));
VERIFY(res2 == res1);
VERIFY(m[0].val == 6);
VERIFY(!k1.moved_from_ctor);
VERIFY(!k1.moved_from_assign);
VERIFY(!v1.moved_from_ctor);
VERIFY(v1.moved_from_assign);
VERIFY(m.size() == 1);
Val k2{1};
v1.moved_from_assign = false;
auto res3 = m.insert_or_assign(m.begin(), std::move(k2), std::move(v1));
VERIFY(res3 != res1 && res3 != m.end());
VERIFY(m[0].val == 6);
VERIFY(m[1].val == 6);
VERIFY(k2.moved_from_ctor);
VERIFY(!k2.moved_from_assign);
VERIFY(v1.moved_from_ctor);
VERIFY(!v1.moved_from_assign);
VERIFY(m.size() == 2);
}
void test05()
{
typedef std::map<int, Val> Map;
Map m;
auto res1 = m.insert_or_assign(0, Val(5));
VERIFY(res1.second);
VERIFY(res1.first != m.end());
VERIFY(m[0].val == 5);
Val v1{6};
VERIFY(m.size() == 1);
auto res2 = m.insert_or_assign(0, v1);
VERIFY(!res2.second);
VERIFY(res2.first == res1.first);
VERIFY(m[0].val == 6);
VERIFY(!v1.moved_from_ctor);
VERIFY(!v1.moved_from_assign);
VERIFY(m.size() == 1);
auto res3 = m.insert_or_assign(1, v1);
VERIFY(res3.first != res1.first && res3.first != m.end());
VERIFY(res3.second);
VERIFY(m[0].val == 6);
VERIFY(m[1].val == 6);
VERIFY(!v1.moved_from_ctor);
VERIFY(!v1.moved_from_assign);
VERIFY(m.size() == 2);
}
void test06()
{
typedef std::map<int, Val> Map;
Map m;
auto res1 = m.insert_or_assign(m.begin(), 0, Val(5));
VERIFY(res1 != m.end());
VERIFY(m[0].val == 5);
Val v1{6};
VERIFY(m.size() == 1);
auto res2 = m.insert_or_assign(m.begin(), 0, v1);
VERIFY(res2 == res1);
VERIFY(m[0].val == 6);
VERIFY(!v1.moved_from_ctor);
VERIFY(!v1.moved_from_assign);
VERIFY(m.size() == 1);
auto res3 = m.insert_or_assign(m.begin(), 1, v1);
VERIFY(res3 != res1 && res3 != m.end());
VERIFY(m[0].val == 6);
VERIFY(m[1].val == 6);
VERIFY(!v1.moved_from_ctor);
VERIFY(!v1.moved_from_assign);
VERIFY(m.size() == 2);
}
void test07()
{
typedef std::map<Val, Val> Map;
Map m;
auto res1 = m.insert_or_assign(0, Val(5));
VERIFY(res1.second);
VERIFY(res1.first != m.end());
VERIFY(m[0].val == 5);
Val k1{0};
Val v1{6};
VERIFY(m.size() == 1);
auto res2 = m.insert_or_assign(k1, v1);
VERIFY(!res2.second);
VERIFY(res2.first == res1.first);
VERIFY(m[0].val == 6);
VERIFY(!k1.moved_from_ctor);
VERIFY(!k1.moved_from_assign);
VERIFY(!v1.moved_from_ctor);
VERIFY(!v1.moved_from_assign);
VERIFY(m.size() == 1);
Val k2{1};
auto res3 = m.insert_or_assign(k2, v1);
VERIFY(res3.first != res1.first && res3.first != m.end());
VERIFY(res3.second);
VERIFY(m[0].val == 6);
VERIFY(m[1].val == 6);
VERIFY(!k2.moved_from_ctor);
VERIFY(!k2.moved_from_assign);
VERIFY(!v1.moved_from_ctor);
VERIFY(!v1.moved_from_assign);
VERIFY(m.size() == 2);
}
void test08()
{
typedef std::map<Val, Val> Map;
Map m;
auto res1 = m.insert_or_assign(m.begin(), 0, Val(5));
VERIFY(res1 != m.end());
VERIFY(m[0].val == 5);
Val k1{0};
Val v1{6};
VERIFY(m.size() == 1);
auto res2 = m.insert_or_assign(m.begin(), k1, v1);
VERIFY(res2 == res1);
VERIFY(m[0].val == 6);
VERIFY(!k1.moved_from_ctor);
VERIFY(!k1.moved_from_assign);
VERIFY(!v1.moved_from_ctor);
VERIFY(!v1.moved_from_assign);
VERIFY(m.size() == 1);
Val k2{1};
auto res3 = m.insert_or_assign(m.begin(), k2, v1);
VERIFY(res3 != res1 && res3 != m.end());
VERIFY(m[0].val == 6);
VERIFY(m[1].val == 6);
VERIFY(!k2.moved_from_ctor);
VERIFY(!k2.moved_from_assign);
VERIFY(!v1.moved_from_ctor);
VERIFY(!v1.moved_from_assign);
VERIFY(m.size() == 2);
}
int main()
{
test01();
test02();
test03();
test04();
test05();
test06();
test07();
test08();
return 0;
}
| {
"pile_set_name": "Github"
} |
<device>
<name>drm_renderD129</name>
<path>/sys/devices/pci0000:00/0000:00:02.0/drm/renderD129</path>
<devnode type='dev'>/dev/dri/renderD129</devnode>
<devnode type='link'>/dev/dri/by-path/pci-0000:00:02.0-render</devnode>
<parent>pci_0000_00_02_0</parent>
<capability type='drm'>
<type>render</type>
</capability>
</device>
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.