text
stringlengths 2
100k
| meta
dict |
---|---|
=pod
=head1 NAME
d2i_DSAPublicKey, i2d_DSAPublicKey, d2i_DSAPrivateKey, i2d_DSAPrivateKey,
d2i_DSA_PUBKEY, i2d_DSA_PUBKEY, d2i_DSAparams, i2d_DSAparams, d2i_DSA_SIG, i2d_DSA_SIG - DSA key encoding
and parsing functions.
=head1 SYNOPSIS
#include <openssl/dsa.h>
#include <openssl/x509.h>
DSA * d2i_DSAPublicKey(DSA **a, const unsigned char **pp, long length);
int i2d_DSAPublicKey(const DSA *a, unsigned char **pp);
DSA * d2i_DSA_PUBKEY(DSA **a, const unsigned char **pp, long length);
int i2d_DSA_PUBKEY(const DSA *a, unsigned char **pp);
DSA * d2i_DSAPrivateKey(DSA **a, const unsigned char **pp, long length);
int i2d_DSAPrivateKey(const DSA *a, unsigned char **pp);
DSA * d2i_DSAparams(DSA **a, const unsigned char **pp, long length);
int i2d_DSAparams(const DSA *a, unsigned char **pp);
DSA * d2i_DSA_SIG(DSA_SIG **a, const unsigned char **pp, long length);
int i2d_DSA_SIG(const DSA_SIG *a, unsigned char **pp);
=head1 DESCRIPTION
d2i_DSAPublicKey() and i2d_DSAPublicKey() decode and encode the DSA public key
components structure.
d2i_DSA_PUBKEY() and i2d_DSA_PUBKEY() decode and encode an DSA public key using
a SubjectPublicKeyInfo (certificate public key) structure.
d2i_DSAPrivateKey(), i2d_DSAPrivateKey() decode and encode the DSA private key
components.
d2i_DSAparams(), i2d_DSAparams() decode and encode the DSA parameters using
a B<Dss-Parms> structure as defined in RFC2459.
d2i_DSA_SIG(), i2d_DSA_SIG() decode and encode a DSA signature using a
B<Dss-Sig-Value> structure as defined in RFC2459.
The usage of all of these functions is similar to the d2i_X509() and
i2d_X509() described in the L<d2i_X509(3)|d2i_X509(3)> manual page.
=head1 NOTES
The B<DSA> structure passed to the private key encoding functions should have
all the private key components present.
The data encoded by the private key functions is unencrypted and therefore
offers no private key security.
The B<DSA_PUBKEY> functions should be used in preference to the B<DSAPublicKey>
functions when encoding public keys because they use a standard format.
The B<DSAPublicKey> functions use an non standard format the actual data encoded
depends on the value of the B<write_params> field of the B<a> key parameter.
If B<write_params> is zero then only the B<pub_key> field is encoded as an
B<INTEGER>. If B<write_params> is 1 then a B<SEQUENCE> consisting of the
B<p>, B<q>, B<g> and B<pub_key> respectively fields are encoded.
The B<DSAPrivateKey> functions also use a non standard structure consiting
consisting of a SEQUENCE containing the B<p>, B<q>, B<g> and B<pub_key> and
B<priv_key> fields respectively.
=head1 SEE ALSO
L<d2i_X509(3)|d2i_X509(3)>
=head1 HISTORY
TBA
=cut
|
{
"pile_set_name": "Github"
}
|
"""Print 'Hello World' every two seconds, using a callback."""
import asyncio
def print_and_repeat(loop):
print('Hello World')
loop.call_later(2, print_and_repeat, loop)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
print_and_repeat(loop)
try:
loop.run_forever()
finally:
loop.close()
|
{
"pile_set_name": "Github"
}
|
// (C) Copyright John Maddock 2005.
// Use, modification and distribution are subject to 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)
//
// The aim of this header is just to include <memory> but to do
// so in a way that does not result in recursive inclusion of
// the Boost TR1 components if boost/tr1/tr1/memory is in the
// include search path. We have to do this to avoid circular
// dependencies:
//
#ifndef BOOST_CONFIG_MEMORY
# define BOOST_CONFIG_MEMORY
# ifndef BOOST_TR1_NO_RECURSION
# define BOOST_TR1_NO_RECURSION
# define BOOST_CONFIG_NO_MEMORY_RECURSION
# endif
# include <memory>
# ifdef BOOST_CONFIG_NO_MEMORY_RECURSION
# undef BOOST_TR1_NO_RECURSION
# undef BOOST_CONFIG_NO_MEMORY_RECURSION
# endif
#endif
|
{
"pile_set_name": "Github"
}
|
package com.spotify.heroic.grammar;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doReturn;
@RunWith(MockitoJUnitRunner.class)
public class DefaultScopeTest {
@Mock
Context ctx;
private DefaultScope scope;
@Before
public void setup() {
scope = new DefaultScope(42L);
}
@Test
public void lookupTest() {
assertEquals(new IntegerExpression(ctx, 42L), scope.lookup(ctx, Expression.NOW));
}
@Test(expected = ParseException.class)
public void lookupMissingTest() {
doReturn(new ParseException("", null, 0, 0, 0, 0)).when(ctx).scopeLookupError("missing");
scope.lookup(ctx, "missing");
}
}
|
{
"pile_set_name": "Github"
}
|
/**
* Tencent is pleased to support the open source community by making APT available.
* Copyright (C) 2014 THL A29 Limited, a Tencent company. 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.
*/
package com.tencent.wstt.apt.data;
/**
* Jiffies值统计模型
* @ClassName: JiffiesStatisticsDataInfo
* @Description: TODO
* @date 2013-5-23 上午9:34:28
*
*/
public class JiffiesStatisticsDataInfo extends AbstractStatisticsDataInfo{
public static final int INITVALUE_INDEX = 0;
public static final int CURVALUE_INDEX = 1;
public static final int DVALUE_INDEX = 2;
public static final int VALUE_NUMBER = 3;
public JiffiesStatisticsDataInfo()
{
valueNumber = VALUE_NUMBER;
contents = new long[VALUE_NUMBER];
}
}
|
{
"pile_set_name": "Github"
}
|
package aws
import (
"fmt"
"log"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
)
func resourceAwsVpcMigrateState(
v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) {
switch v {
case 0:
log.Println("[INFO] Found AWS VPC State v0; migrating to v1")
return migrateVpcStateV0toV1(is)
default:
return is, fmt.Errorf("Unexpected schema version: %d", v)
}
}
func migrateVpcStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceState, error) {
if is.Empty() || is.Attributes == nil {
log.Println("[DEBUG] Empty VPC State; nothing to migrate.")
return is, nil
}
log.Printf("[DEBUG] Attributes before migration: %#v", is.Attributes)
is.Attributes["assign_generated_ipv6_cidr_block"] = "false"
log.Printf("[DEBUG] Attributes after migration: %#v", is.Attributes)
return is, nil
}
|
{
"pile_set_name": "Github"
}
|
#
# Settings for Microsoft Windows Vista and Server 2008
#
# The Vista theme can only be defined on Windows Vista and above. The theme
# is created in C due to the need to assign a theme-enabled function for
# detecting when themeing is disabled. On systems that cannot support the
# Vista theme, there will be no such theme created and we must not
# evaluate this script.
if {"vista" ni [ttk::style theme names]} {
return
}
namespace eval ttk::theme::vista {
ttk::style theme settings vista {
ttk::style configure . \
-background SystemButtonFace \
-foreground SystemWindowText \
-selectforeground SystemHighlightText \
-selectbackground SystemHighlight \
-insertcolor SystemWindowText \
-font TkDefaultFont \
;
ttk::style map "." \
-foreground [list disabled SystemGrayText] \
;
ttk::style configure TButton -anchor center -padding {1 1} -width -11
ttk::style configure TRadiobutton -padding 2
ttk::style configure TCheckbutton -padding 2
ttk::style configure TMenubutton -padding {8 4}
ttk::style element create Menubutton.dropdown vsapi \
TOOLBAR 4 {{selected active} 6 {selected !active} 5
disabled 4 pressed 3 active 2 {} 1} \
-syssize {SM_CXVSCROLL SM_CYVSCROLL}
ttk::style configure TNotebook -tabmargins {2 2 2 0}
ttk::style map TNotebook.Tab \
-expand [list selected {2 2 2 2}]
# Treeview:
ttk::style configure Heading -font TkHeadingFont
ttk::style configure Treeview -background SystemWindow
ttk::style map Treeview \
-background [list disabled SystemButtonFace \
{!disabled !selected} SystemWindow \
selected SystemHighlight] \
-foreground [list disabled SystemGrayText \
{!disabled !selected} SystemWindowText \
selected SystemHighlightText]
# Label and Toolbutton
ttk::style configure TLabelframe.Label -foreground SystemButtonText
ttk::style configure Toolbutton -padding {4 4}
# Combobox
ttk::style configure TCombobox -padding 2
ttk::style element create Combobox.border vsapi \
COMBOBOX 4 {disabled 4 focus 3 active 2 hover 2 {} 1}
ttk::style element create Combobox.background vsapi \
EDIT 3 {disabled 3 readonly 5 focus 4 hover 2 {} 1}
ttk::style element create Combobox.rightdownarrow vsapi \
COMBOBOX 6 {disabled 4 pressed 3 active 2 {} 1} \
-syssize {SM_CXVSCROLL SM_CYVSCROLL}
ttk::style layout TCombobox {
Combobox.border -sticky nswe -border 0 -children {
Combobox.rightdownarrow -side right -sticky ns
Combobox.padding -expand 1 -sticky nswe -children {
Combobox.background -sticky nswe -children {
Combobox.focus -expand 1 -sticky nswe -children {
Combobox.textarea -sticky nswe
}
}
}
}
}
# Vista.Combobox droplist frame
ttk::style element create ComboboxPopdownFrame.background vsapi\
LISTBOX 3 {disabled 4 active 3 focus 2 {} 1}
ttk::style layout ComboboxPopdownFrame {
ComboboxPopdownFrame.background -sticky news -border 1 -children {
ComboboxPopdownFrame.padding -sticky news
}
}
ttk::style map TCombobox \
-selectbackground [list !focus SystemWindow] \
-selectforeground [list !focus SystemWindowText] \
-foreground [list \
disabled SystemGrayText \
{readonly focus} SystemHighlightText \
] \
-focusfill [list {readonly focus} SystemHighlight] \
;
# Entry
ttk::style configure TEntry -padding {1 1 1 1} ;# Needs lookup
ttk::style element create Entry.field vsapi \
EDIT 6 {disabled 4 focus 3 hover 2 {} 1} -padding {2 2 2 2}
ttk::style element create Entry.background vsapi \
EDIT 3 {disabled 3 readonly 3 focus 4 hover 2 {} 1}
ttk::style layout TEntry {
Entry.field -sticky news -border 0 -children {
Entry.background -sticky news -children {
Entry.padding -sticky news -children {
Entry.textarea -sticky news
}
}
}
}
ttk::style map TEntry \
-selectbackground [list !focus SystemWindow] \
-selectforeground [list !focus SystemWindowText] \
;
# Spinbox
ttk::style configure TSpinbox -padding 0
ttk::style element create Spinbox.field vsapi \
EDIT 9 {disabled 4 focus 3 hover 2 {} 1} -padding {1 1 1 2}
ttk::style element create Spinbox.background vsapi \
EDIT 3 {disabled 3 readonly 3 focus 4 hover 2 {} 1}
ttk::style element create Spinbox.innerbg vsapi \
EDIT 3 {disabled 3 readonly 3 focus 4 hover 2 {} 1}\
-padding {2 0 15 2}
ttk::style element create Spinbox.uparrow vsapi \
SPIN 1 {disabled 4 pressed 3 active 2 {} 1} \
-padding 1 -halfheight 1 \
-syssize { SM_CXVSCROLL SM_CYVSCROLL }
ttk::style element create Spinbox.downarrow vsapi \
SPIN 2 {disabled 4 pressed 3 active 2 {} 1} \
-padding 1 -halfheight 1 \
-syssize { SM_CXVSCROLL SM_CYVSCROLL }
ttk::style layout TSpinbox {
Spinbox.field -sticky nswe -children {
Spinbox.background -sticky news -children {
Spinbox.padding -sticky news -children {
Spinbox.innerbg -sticky news -children {
Spinbox.textarea -expand 1
}
}
Spinbox.uparrow -side top -sticky ens
Spinbox.downarrow -side bottom -sticky ens
}
}
}
ttk::style map TSpinbox \
-selectbackground [list !focus SystemWindow] \
-selectforeground [list !focus SystemWindowText] \
;
# SCROLLBAR elements (Vista includes a state for 'hover')
ttk::style element create Vertical.Scrollbar.uparrow vsapi \
SCROLLBAR 1 {disabled 4 pressed 3 active 2 hover 17 {} 1} \
-syssize {SM_CXVSCROLL SM_CYVSCROLL}
ttk::style element create Vertical.Scrollbar.downarrow vsapi \
SCROLLBAR 1 {disabled 8 pressed 7 active 6 hover 18 {} 5} \
-syssize {SM_CXVSCROLL SM_CYVSCROLL}
ttk::style element create Vertical.Scrollbar.trough vsapi \
SCROLLBAR 7 {disabled 4 pressed 3 active 2 hover 5 {} 1}
ttk::style element create Vertical.Scrollbar.thumb vsapi \
SCROLLBAR 3 {disabled 4 pressed 3 active 2 hover 5 {} 1} \
-syssize {SM_CXVSCROLL SM_CYVSCROLL}
ttk::style element create Vertical.Scrollbar.grip vsapi \
SCROLLBAR 9 {disabled 4 pressed 3 active 2 hover 5 {} 1} \
-syssize {SM_CXVSCROLL SM_CYVSCROLL}
ttk::style element create Horizontal.Scrollbar.leftarrow vsapi \
SCROLLBAR 1 {disabled 12 pressed 11 active 10 hover 19 {} 9} \
-syssize {SM_CXHSCROLL SM_CYHSCROLL}
ttk::style element create Horizontal.Scrollbar.rightarrow vsapi \
SCROLLBAR 1 {disabled 16 pressed 15 active 14 hover 20 {} 13} \
-syssize {SM_CXHSCROLL SM_CYHSCROLL}
ttk::style element create Horizontal.Scrollbar.trough vsapi \
SCROLLBAR 5 {disabled 4 pressed 3 active 2 hover 5 {} 1}
ttk::style element create Horizontal.Scrollbar.thumb vsapi \
SCROLLBAR 2 {disabled 4 pressed 3 active 2 hover 5 {} 1} \
-syssize {SM_CXHSCROLL SM_CYHSCROLL}
ttk::style element create Horizontal.Scrollbar.grip vsapi \
SCROLLBAR 8 {disabled 4 pressed 3 active 2 hover 5 {} 1}
# Progressbar
ttk::style element create Horizontal.Progressbar.pbar vsapi \
PROGRESS 3 {{} 1} -padding 8
ttk::style layout Horizontal.TProgressbar {
Horizontal.Progressbar.trough -sticky nswe -children {
Horizontal.Progressbar.pbar -side left -sticky ns
}
}
ttk::style element create Vertical.Progressbar.pbar vsapi \
PROGRESS 3 {{} 1} -padding 8
ttk::style layout Vertical.TProgressbar {
Vertical.Progressbar.trough -sticky nswe -children {
Vertical.Progressbar.pbar -side bottom -sticky we
}
}
# Scale
ttk::style element create Horizontal.Scale.slider vsapi \
TRACKBAR 3 {disabled 5 focus 4 pressed 3 active 2 {} 1} \
-width 6 -height 12
ttk::style layout Horizontal.TScale {
Scale.focus -expand 1 -sticky nswe -children {
Horizontal.Scale.trough -expand 1 -sticky nswe -children {
Horizontal.Scale.track -sticky we
Horizontal.Scale.slider -side left -sticky {}
}
}
}
ttk::style element create Vertical.Scale.slider vsapi \
TRACKBAR 6 {disabled 5 focus 4 pressed 3 active 2 {} 1} \
-width 12 -height 6
ttk::style layout Vertical.TScale {
Scale.focus -expand 1 -sticky nswe -children {
Vertical.Scale.trough -expand 1 -sticky nswe -children {
Vertical.Scale.track -sticky ns
Vertical.Scale.slider -side top -sticky {}
}
}
}
# Treeview
ttk::style configure Item -padding {4 0 0 0}
package provide ttk::theme::vista 1.0
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2015 the original author or authors.
* @https://github.com/scouter-project/scouter
*
* 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 scouter.client.xlog.dialog;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import scouter.client.model.TextProxy;
import scouter.client.model.XLogData;
import scouter.client.popup.SQLFormatDialog;
import scouter.client.util.UIUtil;
import scouter.lang.step.HashedMessageStep;
import scouter.lang.step.SqlStep;
import scouter.lang.step.SqlStep3;
import scouter.lang.step.Step;
import scouter.lang.step.StepEnum;
import scouter.lang.step.StepSingle;
import scouter.util.FormatUtil;
import scouter.util.Hexa32;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
public class XlogSummarySQLDialog extends Dialog {
private Table sqlTable;
private Table bindTable;
private Step[] steps;
private XLogData xperf;
private HashMap<Integer, SQLSumData> sqlMap = new HashMap<Integer, SQLSumData>();
public XlogSummarySQLDialog(Shell shell, Step[] steps, XLogData xperf) {
super(shell);
this.xperf = xperf;
this.steps = steps;
}
protected Control createDialogArea(Composite parent) {
Composite container = (Composite) super.createDialogArea(parent);
FillLayout layout = new FillLayout();
container.setLayout(layout);
SashForm sashVertForm = new SashForm(container, SWT.VERTICAL);
sashVertForm.SASH_WIDTH = 3;
initSQLTable(sashVertForm);
initBindTable(sashVertForm);
sashVertForm.setWeights(new int [] {55, 45});
processSqlData();
displaySQLSumData();
return container;
}
private void initSQLTable(Composite parent){
sqlTable = new Table(parent, SWT.BORDER | SWT.FULL_SELECTION);
TableColumn tableColumn = new TableColumn(sqlTable, SWT.RIGHT);
tableColumn.setText("Execs");
tableColumn.setWidth(80);
tableColumn = new TableColumn(sqlTable, SWT.RIGHT);
tableColumn.setText("Binds");
tableColumn.setWidth(80);
tableColumn = new TableColumn(sqlTable, SWT.RIGHT);
tableColumn.setText("Exec Time");
tableColumn.setWidth(80);
tableColumn = new TableColumn(sqlTable, SWT.RIGHT);
tableColumn.setText("Fetch Time");
tableColumn.setWidth(80);
tableColumn = new TableColumn(sqlTable, SWT.RIGHT);
tableColumn.setText("Total Rows");
tableColumn.setWidth(80);
tableColumn = new TableColumn(sqlTable, SWT.LEFT);
tableColumn.setText("SQL Text");
tableColumn.setWidth(600);
sqlTable.setHeaderVisible(true);
sqlTable.setVisible(true);
sqlTable.addSelectionListener(new SelectionListener(){
public void widgetDefaultSelected(SelectionEvent event) {
}
@SuppressWarnings("unchecked")
public void widgetSelected(SelectionEvent event) {
bindTable.clearAll();
bindTable.setItemCount(0);
TableItem item = (TableItem)event.item;
if(item == null)
return;
Integer hash = (Integer)item.getData();
ArrayList<BindSumData> list = getLBindSumDataList(hash.intValue());
Collections.sort(list, new BindSumDataComp());
String sqlText = sqlMap.get(hash).sqlText;
if (sqlText != null) {
sqlText = sqlText.replaceAll("(\r\n|\r|\n|\n\r)", " ");
}
TableItem bindItem;
for(BindSumData value : list){
bindItem = new TableItem(bindTable, SWT.BORDER);
bindItem.setText(value.toTableInfo());
bindItem.setData(sqlText);
}
}
});
}
private void initBindTable(Composite parent){
bindTable = new Table(parent, SWT.BORDER | SWT.FULL_SELECTION);
TableColumn tableColumn = new TableColumn(bindTable, SWT.RIGHT);
tableColumn.setText("Execs");
tableColumn.setWidth(80);
tableColumn = new TableColumn(bindTable, SWT.RIGHT);
tableColumn.setText("Exec Time");
tableColumn.setWidth(80);
tableColumn = new TableColumn(bindTable, SWT.RIGHT);
tableColumn.setText("Fetch Time");
tableColumn.setWidth(80);
tableColumn = new TableColumn(bindTable, SWT.RIGHT);
tableColumn.setText("Total Rows");
tableColumn.setWidth(80);
tableColumn = new TableColumn(bindTable, SWT.LEFT);
tableColumn.setText("Bind Variables");
tableColumn.setWidth(600);
bindTable.setHeaderVisible(true);
bindTable.setVisible(true);
bindTable.setToolTipText("Please double click on in order to view the complete SQL statement");
bindTable.addMouseListener(new MouseListener(){
public void mouseDoubleClick(MouseEvent event) {
TableItem [] items = bindTable.getSelection();
if(items.length == 0){
return;
}
TableItem item = items[0];
String sqlText = (String)item.getData();
String binds = item.getText(4);
new SQLFormatDialog().show(sqlText, null, binds);
}
@Override
public void mouseDown(MouseEvent event) {
}
@Override
public void mouseUp(MouseEvent event) {
}
});
}
protected void displaySQLSumData(){
sqlTable.clearAll();
sqlTable.setItemCount(0);
ArrayList<SQLSumData> list = getLSQLSumDataList();
Collections.sort(list, new SQLSumDataComp());
TableItem item;
for(SQLSumData value : list){
item = new TableItem(sqlTable, SWT.BORDER);
item.setText(value.toTableInfo());
item.setData(new Integer(value.hash));
}
}
protected void processSqlData(){
StepSingle stepSingle;
SqlStep sql;
HashedMessageStep message;
SQLSumData sqlSumData = null;
BindSumData bindSumData = null;
String bindParam;
for (int i = 0; i < steps.length; i++) {
stepSingle = (StepSingle)steps[i];
switch(stepSingle.getStepType()){
case StepEnum.SQL:
case StepEnum.SQL2:
case StepEnum.SQL3:
sql = (SqlStep)stepSingle;
sqlSumData = sqlMap.get(sql.hash);
if(sqlSumData == null){
sqlSumData = new SQLSumData();
sqlSumData.hash = sql.hash;
sqlSumData.sqlText = TextProxy.sql.getText(sql.hash);
if (sqlSumData.sqlText != null) {
sqlSumData.sqlText = sqlSumData.sqlText.replaceAll("(\r\n|\r|\n|\n\r)", " ");
}
sqlMap.put(sql.hash, sqlSumData);
}
sqlSumData.execs++;
sqlSumData.execTime += sql.elapsed;
bindSumData = sqlSumData.bindMap.get(sql.param);
if(bindSumData == null){
sqlSumData.binds++;
bindSumData = new BindSumData();
if(sql.param == null){
bindParam = "[No Value]";
}else{
bindParam = sql.param;
}
bindSumData.bindText = bindParam;
sqlSumData.bindMap.put(bindParam, bindSumData);
}
bindSumData.execs++;
bindSumData.execTime += sql.elapsed;
if(StepEnum.SQL3 == stepSingle.getStepType()){
int updatedCount = ((SqlStep3)stepSingle).updated;
if (updatedCount > SqlStep3.EXECUTE_RESULT_SET) {
sqlSumData.totalRows += updatedCount;
bindSumData.totalRows += updatedCount;
}
}
break;
case StepEnum.HASHED_MESSAGE:
message = (HashedMessageStep)stepSingle;
if(!"RESULT-SET-FETCH".equals(TextProxy.hashMessage.getText(message.hash))){
continue;
}
if(sqlSumData != null){
sqlSumData.fetchTime += message.time;
sqlSumData.totalRows += message.value;
}
if(bindSumData != null){
bindSumData.fetchTime += message.time;
bindSumData.totalRows += message.value;
}
break;
}
}
}
private ArrayList<SQLSumData> getLSQLSumDataList(){
ArrayList<SQLSumData> list = new ArrayList<SQLSumData>();
Iterator<SQLSumData> itor = sqlMap.values().iterator();
while(itor.hasNext()){
list.add(itor.next());
}
return list;
}
private ArrayList<BindSumData> getLBindSumDataList(int hash){
ArrayList<BindSumData> list = new ArrayList<BindSumData>();
SQLSumData sqlSumData = sqlMap.get(hash);
if(sqlSumData == null){
return null;
}
HashMap<String, BindSumData> bindMap = sqlSumData.bindMap;
Iterator<BindSumData> itor = bindMap.values().iterator();
while(itor.hasNext()){
list.add(itor.next());
}
return list;
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(new StringBuilder(100).append("SQL Statistics Summary-").append(TextProxy.service.getText(xperf.p.service)).append('(').append(Hexa32.toString32(xperf.p.txid)).append(")-").append(FormatUtil.print(xperf.p.elapsed, "#,##0")).append("ms").toString());
}
@Override
protected boolean isResizable() {
return true;
}
@Override
protected Control createButtonBar(Composite parent){
return null;
}
@Override
protected void initializeBounds(){
int[] size = UIUtil.getScreenSize();
this.getShell().setBounds((size[0]/2)-400, (size[1]/2)-200, 800, 400);
}
private class SQLSumData {
public int execs = 0;
public int binds = 0;
public int execTime = 0;
public int fetchTime = 0;
public int totalRows = 0;
public String sqlText = null;
public int hash = 0;
public HashMap<String, BindSumData> bindMap = new HashMap<String, BindSumData>();
public String[] toTableInfo(){
String [] values = new String[6];
values[0] = FormatUtil.print(execs, "#,##0");
values[1] = FormatUtil.print(binds, "#,##0");
values[2] = FormatUtil.print(execTime, "#,##0");
values[3] = FormatUtil.print(fetchTime, "#,##0");
values[4] = FormatUtil.print(totalRows, "#,##0");
values[5] = sqlText;
return values;
}
}
private class BindSumData {
public int execs = 0;
public int execTime = 0;
public int fetchTime = 0;
public int totalRows = 0;
public String bindText = null;
public String[] toTableInfo(){
String [] values = new String[6];
values[0] = FormatUtil.print(execs, "#,##0");
values[1] = FormatUtil.print(execTime, "#,##0");
values[2] = FormatUtil.print(fetchTime, "#,##0");
values[3] = FormatUtil.print(totalRows, "#,##0");
values[4] = bindText;
return values;
}
}
private class SQLSumDataComp implements Comparator<SQLSumData>{
public int compare(SQLSumData o1, SQLSumData o2) {
if(o1.execTime > o2.execTime)
return -1;
else if(o1.execTime < o2.execTime)
return 1;
return 0;
}
}
private class BindSumDataComp implements Comparator<BindSumData>{
public int compare(BindSumData o1, BindSumData o2) {
if(o1.execTime > o2.execTime)
return -1;
else if(o1.execTime < o2.execTime)
return 1;
return 0;
}
}
}
|
{
"pile_set_name": "Github"
}
|
/*====================================================================*
- Copyright (C) 2001 Leptonica. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials
- provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY 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 ANY
- 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.
*====================================================================*/
/*
* kernel_reg.c
*/
#include <string.h>
#ifndef _WIN32
#include <unistd.h>
#else
#include <windows.h> /* for Sleep() */
#endif /* _WIN32 */
#include "allheaders.h"
static const char *kdatastr = " 20.3 50 80 50 20 "
" 51.4 100 140 100 50 "
" 92.5 160 200 160 90 "
" 53.7 100 140 100 50 "
" 24.9 50 80 50 20 ";
int main(int argc,
char **argv)
{
char *str;
l_int32 i, j, same, ok;
l_float32 sum, avediff, rmsdiff;
L_KERNEL *kel1, *kel2, *kel3, *kel4, *kelx, *kely;
BOX *box;
PIX *pix, *pixs, *pixb, *pixg, *pixd, *pixp, *pixt;
PIX *pixt1, *pixt2, *pixt3;
PIXA *pixa;
SARRAY *sa;
L_REGPARAMS *rp;
if (regTestSetup(argc, argv, &rp))
return 1;
pixa = pixaCreate(0);
/* Test creating from a string */
kel1 = kernelCreateFromString(5, 5, 2, 2, kdatastr);
pixd = kernelDisplayInPix(kel1, 41, 2);
pixWrite("/tmp/lept/regout/pixkern.png", pixd, IFF_PNG);
regTestCheckFile(rp, "/tmp/lept/regout/pixkern.png"); /* 0 */
pixSaveTiled(pixd, pixa, 1.0, 1, 20, 8);
pixDestroy(&pixd);
kernelDestroy(&kel1);
/* Test read/write for kernel. Note that both get
* compared to the same golden file, which is
* overwritten with a copy of /tmp/lept/regout/kern2.kel */
kel1 = kernelCreateFromString(5, 5, 2, 2, kdatastr);
kernelWrite("/tmp/lept/regout/kern1.kel", kel1);
regTestCheckFile(rp, "/tmp/lept/regout/kern1.kel"); /* 1 */
kel2 = kernelRead("/tmp/lept/regout/kern1.kel");
kernelWrite("/tmp/lept/regout/kern2.kel", kel2);
regTestCheckFile(rp, "/tmp/lept/regout/kern2.kel"); /* 2 */
regTestCompareFiles(rp, 1, 2); /* 3 */
kernelDestroy(&kel1);
kernelDestroy(&kel2);
/* Test creating from a file */
sa = sarrayCreate(0);
sarrayAddString(sa, (char *)"# small 3x3 kernel", L_COPY);
sarrayAddString(sa, (char *)"3 5", L_COPY);
sarrayAddString(sa, (char *)"1 2", L_COPY);
sarrayAddString(sa, (char *)"20.5 50 80 50 20", L_COPY);
sarrayAddString(sa, (char *)"82. 120 180 120 80", L_COPY);
sarrayAddString(sa, (char *)"22.1 50 80 50 20", L_COPY);
str = sarrayToString(sa, 1);
l_binaryWrite("/tmp/lept/regout/kernfile.kel", "w", str, strlen(str));
kel2 = kernelCreateFromFile("/tmp/lept/regout/kernfile.kel");
pixd = kernelDisplayInPix(kel2, 41, 2);
pixSaveTiled(pixd, pixa, 1.0, 1, 20, 0);
pixWrite("/tmp/lept/regout/ker1.png", pixd, IFF_PNG);
regTestCheckFile(rp, "/tmp/lept/regout/ker1.png"); /* 4 */
pixDestroy(&pixd);
sarrayDestroy(&sa);
lept_free(str);
kernelDestroy(&kel2);
/* Test creating from a pix */
pixt = pixCreate(5, 3, 8);
pixSetPixel(pixt, 0, 0, 20);
pixSetPixel(pixt, 1, 0, 50);
pixSetPixel(pixt, 2, 0, 80);
pixSetPixel(pixt, 3, 0, 50);
pixSetPixel(pixt, 4, 0, 20);
pixSetPixel(pixt, 0, 1, 80);
pixSetPixel(pixt, 1, 1, 120);
pixSetPixel(pixt, 2, 1, 180);
pixSetPixel(pixt, 3, 1, 120);
pixSetPixel(pixt, 4, 1, 80);
pixSetPixel(pixt, 0, 0, 20);
pixSetPixel(pixt, 1, 2, 50);
pixSetPixel(pixt, 2, 2, 80);
pixSetPixel(pixt, 3, 2, 50);
pixSetPixel(pixt, 4, 2, 20);
kel3 = kernelCreateFromPix(pixt, 1, 2);
pixd = kernelDisplayInPix(kel3, 41, 2);
pixSaveTiled(pixd, pixa, 1.0, 0, 20, 0);
pixWrite("/tmp/lept/regout/ker2.png", pixd, IFF_PNG);
regTestCheckFile(rp, "/tmp/lept/regout/ker2.png"); /* 5 */
pixDestroy(&pixd);
pixDestroy(&pixt);
kernelDestroy(&kel3);
/* Test convolution with kel1 */
pixs = pixRead("test24.jpg");
pixg = pixScaleRGBToGrayFast(pixs, 3, COLOR_GREEN);
pixSaveTiled(pixg, pixa, 1.0, 1, 20, 0);
kel1 = kernelCreateFromString(5, 5, 2, 2, kdatastr);
pixd = pixConvolve(pixg, kel1, 8, 1);
pixSaveTiled(pixd, pixa, 1.0, 0, 20, 0);
pixWrite("/tmp/lept/regout/ker3.png", pixd, IFF_PNG);
regTestCheckFile(rp, "/tmp/lept/regout/ker3.png"); /* 6 */
pixDestroy(&pixs);
pixDestroy(&pixg);
pixDestroy(&pixd);
kernelDestroy(&kel1);
/* Test convolution with flat rectangular kel; also test
* block convolution with tiling. */
pixs = pixRead("test24.jpg");
pixg = pixScaleRGBToGrayFast(pixs, 3, COLOR_GREEN);
kel2 = makeFlatKernel(11, 11, 5, 5);
pixd = pixConvolve(pixg, kel2, 8, 1);
pixSaveTiled(pixd, pixa, 1.0, 1, 20, 0);
pixWrite("/tmp/lept/regout/ker4.png", pixd, IFF_PNG);
regTestCheckFile(rp, "/tmp/lept/regout/ker4.png"); /* 7 */
pixt = pixBlockconv(pixg, 5, 5);
pixSaveTiled(pixt, pixa, 1.0, 0, 20, 0);
pixWrite("/tmp/lept/regout/ker5.png", pixt, IFF_PNG);
regTestCheckFile(rp, "/tmp/lept/regout/ker5.png"); /* 8 */
if (rp->display)
pixCompareGray(pixd, pixt, L_COMPARE_ABS_DIFF, GPLOT_PNG, NULL,
NULL, NULL, NULL);
pixt2 = pixBlockconvTiled(pixg, 5, 5, 3, 6);
pixSaveTiled(pixt2, pixa, 1.0, 0, 20, 0);
pixWrite("/tmp/lept/regout/ker5a.png", pixt2, IFF_PNG);
regTestCheckFile(rp, "/tmp/lept/regout/ker5a.png"); /* 9 */
pixDestroy(&pixt2);
ok = TRUE;
for (i = 1; i <= 7; i++) {
for (j = 1; j <= 7; j++) {
if (i == 1 && j == 1) continue;
pixt2 = pixBlockconvTiled(pixg, 5, 5, j, i);
pixEqual(pixt2, pixd, &same);
if (!same) {
fprintf(stderr," Error for nx = %d, ny = %d\n", j, i);
ok = FALSE;
}
pixDestroy(&pixt2);
}
}
if (ok)
fprintf(stderr, "OK: Tiled results identical to pixConvolve()\n");
else
fprintf(stderr, "ERROR: Tiled results not identical to pixConvolve()\n");
pixDestroy(&pixs);
pixDestroy(&pixg);
pixDestroy(&pixd);
pixDestroy(&pixt);
kernelDestroy(&kel2);
/* Do another flat rectangular test; this time with white at edge.
* About 1% of the pixels near the image edge differ by 1 between
* the pixConvolve() and pixBlockconv(). For what it's worth,
* pixConvolve() gives the more accurate result; namely, 255 for
* pixels at the edge. */
pix = pixRead("pageseg1.tif");
box = boxCreate(100, 100, 2260, 3160);
pixb = pixClipRectangle(pix, box, NULL);
pixs = pixScaleToGray4(pixb);
kel3 = makeFlatKernel(7, 7, 3, 3);
startTimer();
pixt = pixConvolve(pixs, kel3, 8, 1);
fprintf(stderr, "Generic convolution time: %5.3f sec\n", stopTimer());
pixSaveTiled(pixt, pixa, 1.0, 1, 20, 0);
pixWrite("/tmp/lept/regout/conv1.png", pixt, IFF_PNG);
regTestCheckFile(rp, "/tmp/lept/regout/conv1.png"); /* 10 */
startTimer();
pixt2 = pixBlockconv(pixs, 3, 3);
fprintf(stderr, "Flat block convolution time: %5.3f sec\n", stopTimer());
pixSaveTiled(pixt2, pixa, 1.0, 0, 20, 0);
pixWrite("/tmp/lept/regout/conv2.png", pixt2, IFF_PNG); /* ditto */
regTestCheckFile(rp, "/tmp/lept/regout/conv2.png"); /* 11 */
pixCompareGray(pixt, pixt2, L_COMPARE_ABS_DIFF, GPLOT_PNG, NULL,
&avediff, &rmsdiff, NULL);
#if 0
#ifndef _WIN32
sleep(1); /* give gnuplot time to write out the file */
#else
Sleep(1000);
#endif /* _WIN32 */
#endif
pixp = pixRead("/tmp/lept/comp/compare_gray0.png");
pixSaveTiled(pixp, pixa, 1.0, 0, 20, 0);
pixWrite("/tmp/lept/regout/conv3.png", pixp, IFF_PNG);
regTestCheckFile(rp, "/tmp/lept/regout/conv3.png"); /* 12 */
fprintf(stderr, "Ave diff = %6.4f, RMS diff = %6.4f\n", avediff, rmsdiff);
if (avediff <= 0.01)
fprintf(stderr, "OK: avediff = %6.4f <= 0.01\n", avediff);
else
fprintf(stderr, "Bad?: avediff = %6.4f > 0.01\n", avediff);
pixDestroy(&pixt);
pixDestroy(&pixt2);
pixDestroy(&pixs);
pixDestroy(&pixp);
pixDestroy(&pix);
pixDestroy(&pixb);
boxDestroy(&box);
kernelDestroy(&kel3);
/* Do yet another set of flat rectangular tests, this time
* on an RGB image */
pixs = pixRead("test24.jpg");
kel4 = makeFlatKernel(7, 7, 3, 3);
startTimer();
pixt1 = pixConvolveRGB(pixs, kel4);
fprintf(stderr, "Time 7x7 non-separable: %7.3f sec\n", stopTimer());
pixWrite("/tmp/lept/regout/conv4.jpg", pixt1, IFF_JFIF_JPEG);
regTestCheckFile(rp, "/tmp/lept/regout/conv4.jpg"); /* 13 */
kelx = makeFlatKernel(1, 7, 0, 3);
kely = makeFlatKernel(7, 1, 3, 0);
startTimer();
pixt2 = pixConvolveRGBSep(pixs, kelx, kely);
fprintf(stderr, "Time 7x1,1x7 separable: %7.3f sec\n", stopTimer());
pixWrite("/tmp/lept/regout/conv5.jpg", pixt2, IFF_JFIF_JPEG);
regTestCheckFile(rp, "/tmp/lept/regout/conv5.jpg"); /* 14 */
startTimer();
pixt3 = pixBlockconv(pixs, 3, 3);
fprintf(stderr, "Time 7x7 blockconv: %7.3f sec\n", stopTimer());
pixWrite("/tmp/lept/regout/conv6.jpg", pixt3, IFF_JFIF_JPEG);
regTestCheckFile(rp, "/tmp/lept/regout/conv6.jpg"); /* 15 */
regTestComparePix(rp, pixt1, pixt2); /* 16 */
regTestCompareSimilarPix(rp, pixt2, pixt3, 15, 0.0005, 0); /* 17 */
pixDestroy(&pixs);
pixDestroy(&pixt1);
pixDestroy(&pixt2);
pixDestroy(&pixt3);
kernelDestroy(&kel4);
kernelDestroy(&kelx);
kernelDestroy(&kely);
/* Test generation and convolution with gaussian kernel */
pixs = pixRead("test8.jpg");
pixSaveTiled(pixs, pixa, 1.0, 1, 20, 0);
kel1 = makeGaussianKernel(5, 5, 3.0, 5.0);
kernelGetSum(kel1, &sum);
fprintf(stderr, "Sum for gaussian kernel = %f\n", sum);
kernelWrite("/tmp/lept/regout/gauss.kel", kel1);
pixt = pixConvolve(pixs, kel1, 8, 1);
pixt2 = pixConvolve(pixs, kel1, 16, 0);
pixSaveTiled(pixt, pixa, 1.0, 0, 20, 0);
pixSaveTiled(pixt2, pixa, 1.0, 0, 20, 0);
pixWrite("/tmp/lept/regout/ker6.png", pixt, IFF_PNG);
regTestCheckFile(rp, "/tmp/lept/regout/ker6.png"); /* 18 */
pixDestroy(&pixt);
pixDestroy(&pixt2);
pixt = kernelDisplayInPix(kel1, 25, 2);
pixSaveTiled(pixt, pixa, 1.0, 0, 20, 0);
pixDestroy(&pixt);
kernelDestroy(&kel1);
pixDestroy(&pixs);
/* Test generation and convolution with separable gaussian kernel */
pixs = pixRead("test8.jpg");
pixSaveTiled(pixs, pixa, 1.0, 1, 20, 0);
makeGaussianKernelSep(5, 5, 3.0, 5.0, &kelx, &kely);
kernelGetSum(kelx, &sum);
fprintf(stderr, "Sum for x gaussian kernel = %f\n", sum);
kernelGetSum(kely, &sum);
fprintf(stderr, "Sum for y gaussian kernel = %f\n", sum);
kernelWrite("/tmp/lept/regout/gauss.kelx", kelx);
kernelWrite("/tmp/lept/regout/gauss.kely", kely);
pixt = pixConvolveSep(pixs, kelx, kely, 8, 1);
pixt2 = pixConvolveSep(pixs, kelx, kely, 16, 0);
pixSaveTiled(pixt, pixa, 1.0, 0, 20, 0);
pixSaveTiled(pixt2, pixa, 1.0, 0, 20, 0);
pixWrite("/tmp/lept/regout/ker7.png", pixt, IFF_PNG);
regTestCheckFile(rp, "/tmp/lept/regout/ker7.png"); /* 19 */
pixDestroy(&pixt);
pixDestroy(&pixt2);
pixt = kernelDisplayInPix(kelx, 25, 2);
pixSaveTiled(pixt, pixa, 1.0, 0, 20, 0);
pixDestroy(&pixt);
pixt = kernelDisplayInPix(kely, 25, 2);
pixSaveTiled(pixt, pixa, 1.0, 0, 20, 0);
pixDestroy(&pixt);
kernelDestroy(&kelx);
kernelDestroy(&kely);
pixDestroy(&pixs);
/* Test generation and convolution with diff of gaussians kernel */
/* pixt = pixRead("marge.jpg");
pixs = pixConvertRGBToLuminance(pixt);
pixDestroy(&pixt); */
pixs = pixRead("test8.jpg");
pixSaveTiled(pixs, pixa, 1.0, 1, 20, 0);
kel1 = makeDoGKernel(7, 7, 1.5, 2.7);
kernelGetSum(kel1, &sum);
fprintf(stderr, "Sum for DoG kernel = %f\n", sum);
kernelWrite("/tmp/lept/regout/dog.kel", kel1);
pixt = pixConvolve(pixs, kel1, 8, 0);
/* pixInvert(pixt, pixt); */
pixSaveTiled(pixt, pixa, 1.0, 0, 20, 0);
pixWrite("/tmp/lept/regout/ker8.png", pixt, IFF_PNG);
regTestCheckFile(rp, "/tmp/lept/regout/ker8.png"); /* 20 */
pixDestroy(&pixt);
pixt = kernelDisplayInPix(kel1, 20, 2);
pixSaveTiled(pixt, pixa, 1.0, 0, 20, 0);
pixDestroy(&pixt);
kernelDestroy(&kel1);
pixDestroy(&pixs);
pixd = pixaDisplay(pixa, 0, 0);
pixDisplayWithTitle(pixd, 100, 100, NULL, rp->display);
pixWrite("/tmp/lept/regout/kernel.jpg", pixd, IFF_JFIF_JPEG);
pixDestroy(&pixd);
pixaDestroy(&pixa);
return regTestCleanup(rp);
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2013-2020 Software Radio Systems Limited
*
* This file is part of srsLTE.
*
* srsLTE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* srsLTE 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 Affero General Public License for more details.
*
* A copy of the GNU Affero General Public License can be found in
* the LICENSE file in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/.
*
*/
#ifndef SRSLTE_ENB_RRC_INTERFACE_TYPES_H
#define SRSLTE_ENB_RRC_INTERFACE_TYPES_H
#include <vector>
namespace srsenb {
// SCell configuration
struct scell_cfg_t {
uint32_t cell_id;
bool cross_carrier_sched = false;
uint32_t sched_cell_id;
bool ul_allowed;
};
// Cell to measure for Handover
struct meas_cell_cfg_t {
uint32_t earfcn;
uint16_t pci;
uint32_t eci;
float q_offset;
};
// neigh measurement Cell info
struct rrc_meas_cfg_t {
std::vector<meas_cell_cfg_t> meas_cells;
std::vector<asn1::rrc::report_cfg_eutra_s> meas_reports;
asn1::rrc::quant_cfg_eutra_s quant_cfg;
// TODO: Add blacklist cells
// TODO: Add multiple meas configs
};
// Cell/Sector configuration
struct cell_cfg_t {
uint32_t rf_port;
uint32_t cell_id;
uint16_t tac;
uint32_t pci;
uint16_t root_seq_idx;
uint32_t dl_earfcn;
double dl_freq_hz;
uint32_t ul_earfcn;
double ul_freq_hz;
uint32_t initial_dl_cqi;
std::vector<scell_cfg_t> scell_list;
rrc_meas_cfg_t meas_cfg;
};
typedef std::vector<cell_cfg_t> cell_list_t;
} // namespace srsenb
#endif // SRSLTE_ENB_RRC_INTERFACE_TYPES_H
|
{
"pile_set_name": "Github"
}
|
using UnityEngine;
using UnityEditor;
using System;
namespace Cinemachine.Editor
{
public static class CinemachineMenu
{
public const string kCinemachineRootMenu = "Assets/Create/Cinemachine/";
[MenuItem(kCinemachineRootMenu + "Blender/Settings")]
private static void CreateBlenderSettingAsset()
{
ScriptableObjectUtility.Create<CinemachineBlenderSettings>();
}
[MenuItem(kCinemachineRootMenu + "Noise/Settings")]
private static void CreateNoiseSettingAsset()
{
ScriptableObjectUtility.Create<NoiseSettings>();
}
[MenuItem("Cinemachine/Create Virtual Camera", false, 1)]
public static CinemachineVirtualCamera CreateVirtualCamera()
{
return InternalCreateVirtualCamera(
"CM vcam", true, typeof(CinemachineComposer), typeof(CinemachineTransposer));
}
[MenuItem("Cinemachine/Create FreeLook Camera", false, 1)]
private static void CreateFreeLookCamera()
{
CreateCameraBrainIfAbsent();
GameObject go = new GameObject(
GenerateUniqueObjectName(typeof(CinemachineFreeLook), "CM FreeLook"));
Undo.RegisterCreatedObjectUndo(go, "create FreeLook");
Undo.AddComponent<CinemachineFreeLook>(go);
Selection.activeGameObject = go;
}
[MenuItem("Cinemachine/Create State-Driven Camera", false, 1)]
private static void CreateStateDivenCamera()
{
CreateCameraBrainIfAbsent();
GameObject go = new GameObject(
GenerateUniqueObjectName(typeof(CinemachineStateDrivenCamera), "CM StateDrivenCamera"));
Undo.RegisterCreatedObjectUndo(go, "create state driven camera");
Undo.AddComponent<CinemachineStateDrivenCamera>(go);
Selection.activeGameObject = go;
// Give it a child
Undo.SetTransformParent(CreateDefaultVirtualCamera().transform, go.transform, "create state driven camera");
}
[MenuItem("Cinemachine/Create ClearShot Camera", false, 1)]
private static void CreateClearShotVirtualCamera()
{
CreateCameraBrainIfAbsent();
GameObject go = new GameObject(
GenerateUniqueObjectName(typeof(CinemachineClearShot), "CM ClearShot"));
Undo.RegisterCreatedObjectUndo(go, "create ClearShot camera");
Undo.AddComponent<CinemachineClearShot>(go);
Selection.activeGameObject = go;
// Give it a child
var child = CreateDefaultVirtualCamera();
Undo.SetTransformParent(child.transform, go.transform, "create ClearShot camera");
var collider = Undo.AddComponent<CinemachineCollider>(child.gameObject);
collider.m_AvoidObstacles = false;
Undo.RecordObject(collider, "create ClearShot camera");
}
[MenuItem("Cinemachine/Create Dolly Camera with Track", false, 1)]
private static void CreateDollyCameraWithPath()
{
CinemachineVirtualCamera vcam = InternalCreateVirtualCamera(
"CM vcam", true, typeof(CinemachineComposer), typeof(CinemachineTrackedDolly));
GameObject go = new GameObject(
GenerateUniqueObjectName(typeof(CinemachineSmoothPath), "DollyTrack"));
Undo.RegisterCreatedObjectUndo(go, "create track");
CinemachineSmoothPath path = Undo.AddComponent<CinemachineSmoothPath>(go);
var dolly = vcam.GetCinemachineComponent<CinemachineTrackedDolly>();
Undo.RecordObject(dolly, "create track");
dolly.m_Path = path;
}
[MenuItem("Cinemachine/Create Target Group Camera", false, 1)]
private static void CreateTargetGroupCamera()
{
CinemachineVirtualCamera vcam = InternalCreateVirtualCamera(
"CM vcam", true, typeof(CinemachineGroupComposer), typeof(CinemachineTransposer));
GameObject go = new GameObject(
GenerateUniqueObjectName(typeof(CinemachineTargetGroup), "TargetGroup"),
typeof(CinemachineTargetGroup));
Undo.RegisterCreatedObjectUndo(go, "create target group");
vcam.LookAt = go.transform;
vcam.Follow = go.transform;
}
[MenuItem("Cinemachine/Create Mixing Camera", false, 1)]
private static void CreateMixingCamera()
{
CreateCameraBrainIfAbsent();
GameObject go = new GameObject(
GenerateUniqueObjectName(typeof(CinemachineMixingCamera), "CM MixingCamera"));
Undo.RegisterCreatedObjectUndo(go, "create MixingCamera camera");
Undo.AddComponent<CinemachineMixingCamera>(go);
Selection.activeGameObject = go;
// Give it a couple of children
Undo.SetTransformParent(CreateDefaultVirtualCamera().transform, go.transform, "create MixedCamera child");
Undo.SetTransformParent(CreateDefaultVirtualCamera().transform, go.transform, "create MixingCamera child");
}
[MenuItem("Cinemachine/Create 2D Camera", false, 1)]
private static void Create2DCamera()
{
InternalCreateVirtualCamera("CM vcam", true, typeof(CinemachineFramingTransposer));
}
[MenuItem("Cinemachine/Create Dolly Track with Cart", false, 1)]
private static void CreateDollyTrackWithCart()
{
GameObject go = new GameObject(
GenerateUniqueObjectName(typeof(CinemachineSmoothPath), "DollyTrack"));
Undo.RegisterCreatedObjectUndo(go, "create track");
CinemachineSmoothPath path = Undo.AddComponent<CinemachineSmoothPath>(go);
Selection.activeGameObject = go;
go = new GameObject(GenerateUniqueObjectName(typeof(CinemachineDollyCart), "DollyCart"));
Undo.RegisterCreatedObjectUndo(go, "create cart");
CinemachineDollyCart cart = Undo.AddComponent<CinemachineDollyCart>(go);
Undo.RecordObject(cart, "create track");
cart.m_Path = path;
}
/// <summary>
/// Create a default Virtual Camera, with standard components
/// </summary>
public static CinemachineVirtualCamera CreateDefaultVirtualCamera()
{
return InternalCreateVirtualCamera(
"CM vcam", false, typeof(CinemachineComposer), typeof(CinemachineTransposer));
}
/// <summary>
/// Create a Virtual Camera, with components
/// </summary>
static CinemachineVirtualCamera InternalCreateVirtualCamera(
string name, bool selectIt, params Type[] components)
{
// Create a new virtual camera
CreateCameraBrainIfAbsent();
GameObject go = new GameObject(
GenerateUniqueObjectName(typeof(CinemachineVirtualCamera), name));
Undo.RegisterCreatedObjectUndo(go, "create " + name);
CinemachineVirtualCamera vcam = Undo.AddComponent<CinemachineVirtualCamera>(go);
GameObject componentOwner = vcam.GetComponentOwner().gameObject;
foreach (Type t in components)
Undo.AddComponent(componentOwner, t);
vcam.InvalidateComponentPipeline();
if (selectIt)
Selection.activeObject = go;
return vcam;
}
/// <summary>
/// If there is no CinemachineBrain in the scene, try to create one on the main camera
/// </summary>
public static void CreateCameraBrainIfAbsent()
{
CinemachineBrain[] brains = UnityEngine.Object.FindObjectsOfType(
typeof(CinemachineBrain)) as CinemachineBrain[];
if (brains == null || brains.Length == 0)
{
Camera cam = Camera.main;
if (cam == null)
{
Camera[] cams = UnityEngine.Object.FindObjectsOfType(
typeof(Camera)) as Camera[];
if (cams != null && cams.Length > 0)
cam = cams[0];
}
if (cam != null)
{
Undo.AddComponent<CinemachineBrain>(cam.gameObject);
}
}
}
/// <summary>
/// Generate a unique name with the given prefix by adding a suffix to it
/// </summary>
public static string GenerateUniqueObjectName(Type type, string prefix)
{
int count = 0;
UnityEngine.Object[] all = Resources.FindObjectsOfTypeAll(type);
foreach (UnityEngine.Object o in all)
{
if (o != null && o.name.StartsWith(prefix))
{
string suffix = o.name.Substring(prefix.Length);
int i;
if (Int32.TryParse(suffix, out i) && i > count)
count = i;
}
}
return prefix + (count + 1);
}
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2012, 2020 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.enterprise.connectors.jms.deployment.annotation.handlers;
import com.sun.enterprise.deployment.JMSDestinationDefinitionDescriptor;
import com.sun.enterprise.deployment.annotation.context.ResourceContainerContext;
import com.sun.enterprise.deployment.annotation.handlers.AbstractResourceHandler;
import com.sun.enterprise.util.LocalStringManagerImpl;
import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.Set;
import jakarta.jms.JMSDestinationDefinition;
import jakarta.jms.JMSDestinationDefinitions;
import org.glassfish.apf.AnnotationHandlerFor;
import org.glassfish.apf.AnnotationInfo;
import org.glassfish.apf.AnnotationProcessorException;
import org.glassfish.apf.HandlerProcessingResult;
import org.jvnet.hk2.annotations.Service;
@Service
@AnnotationHandlerFor(JMSDestinationDefinitions.class)
public class JMSDestinationDefinitionsHandler extends AbstractResourceHandler {
protected final static LocalStringManagerImpl localStrings =
new LocalStringManagerImpl(JMSDestinationDefinitionsHandler.class);
public JMSDestinationDefinitionsHandler() {
}
@Override
protected HandlerProcessingResult processAnnotation(AnnotationInfo ainfo, ResourceContainerContext[] rcContexts)
throws AnnotationProcessorException {
JMSDestinationDefinitions defns = (JMSDestinationDefinitions) ainfo.getAnnotation();
JMSDestinationDefinition values[] = defns.value();
Set<String> duplicates = new HashSet<String>();
if (values != null && values.length > 0) {
for (JMSDestinationDefinition defn : values) {
String defnName = JMSDestinationDefinitionDescriptor.getJavaName(defn.name());
if (duplicates.contains(defnName)) {
String localString = localStrings.getLocalString(
"enterprise.deployment.annotation.handlers.jmsdestinationdefinitionsduplicates",
"@JMSDestinationDefinition cannot have multiple definitions with same name : ''{0}''",
defnName);
throw new IllegalStateException(localString);
} else {
duplicates.add(defnName);
}
JMSDestinationDefinitionHandler handler = new JMSDestinationDefinitionHandler();
handler.processAnnotation(defn, ainfo, rcContexts);
}
duplicates.clear();
}
return getDefaultProcessedResult();
}
public Class<? extends Annotation>[] getTypeDependencies() {
return getEjbAndWebAnnotationTypes();
}
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" ?>
<annotation>
<folder>widerface</folder>
<filename>45--Balloonist_45_Balloonist_Balloonist_45_282.jpg</filename>
<source>
<database>wider face Database</database>
<annotation>PASCAL VOC2007</annotation>
<image>flickr</image>
<flickrid>-1</flickrid>
</source>
<owner>
<flickrid>yanyu</flickrid>
<name>yanyu</name>
</owner>
<size>
<width>1024</width>
<height>800</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>322</xmin>
<ymin>254</ymin>
<xmax>392</xmax>
<ymax>352</ymax>
</bndbox>
<lm>
<x1>346.571</x1>
<y1>288.848</y1>
<x2>378.219</x2>
<y2>299.397</y2>
<x3>361.464</x3>
<y3>309.326</y3>
<x4>340.366</x4>
<y4>321.737</y4>
<x5>369.531</x5>
<y5>331.665</y5>
<visible>0</visible>
<blur>0.72</blur>
</lm>
<has_lm>1</has_lm>
</object>
</annotation>
|
{
"pile_set_name": "Github"
}
|
module.exports = [
573576346, // Sagira's Shell
1558857470, // Star Map Shell
1558857466, // Electronica Shell
1558857471, // Cosmos Shell
1558857468, // Fast Lane Shell
1558857469, // Fire Victorious Shell
3681086675,
3681086674,
3681086673,
3681086672,
1271045323,
1271045322,
1271045319,
1271045318,
1271045317,
1271045316,
1271045315,
1271045314,
1271045313,
1271045312,
89965919,
89965918,
89965911,
89965910,
89965909,
89965908,
89965907,
89965906,
89965905,
89965904
];
|
{
"pile_set_name": "Github"
}
|
var assocIndexOf = require('./_assocIndexOf');
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
module.exports = listCacheSet;
|
{
"pile_set_name": "Github"
}
|
// CompareView.h : header file of the CCompareView class
//
// Copyright (c) 2015 by Andrew W. Phillips
//
// This file is distributed under the MIT license, which basically says
// you can do what you want with it and I take no responsibility for bugs.
// See http://www.opensource.org/licenses/mit-license.php for full details.
//
#ifndef COMPAREVIEW_INCLUDED
#define COMPAREVIEW_INCLUDED 1
#include "ScrView.h"
#include <vector>
// Forward declarations
class CHexEditDoc;
class CChildFrame;
// When comparing files we use this to displayed the compared with file.
// It depends on the corresponding CHexEditView for a lot of its display
// formating but there is independent control over:
// - file displayed and hence OnDraw and OnInitialUpdate
// - current position (unless using auto-sync)
// - selection (so the user can select parts of this file)
// - searches
class CCompareView : public CScrView
{
friend CHexEditView;
protected: // create from serialization only
CCompareView();
DECLARE_DYNCREATE(CCompareView)
public:
CHexEditView * phev_;
// Attributes
public:
CHexEditDoc * GetDocument() { return (CHexEditDoc*)phev_->m_pDocument; }
FILE_ADDRESS GetPos() const { return pos2addr(GetCaret()); }
BOOL ReadOnly() const { return TRUE; }
BOOL CharMode() const { return phev_->display_.edit_char; }
BOOL EbcdicMode() const { return phev_->display_.char_set == CHARSET_EBCDIC; }
BOOL OemMode() const { return phev_->display_.char_set == CHARSET_OEM; }
BOOL AnsiMode() const { return phev_->display_.char_set == CHARSET_ANSI; }
BOOL DecAddresses() const { return !phev_->display_.hex_addr; } // Now that user can show both addresses at once this is probably the best return value
// Operations
//virtual void SetSel(CPointAp, CPointAp, bool base1 = false);
bool CopyToClipboard();
virtual BOOL MovePos(UINT nChar, UINT nRepCnt, BOOL, BOOL, BOOL);
void MoveToAddress(FILE_ADDRESS astart, FILE_ADDRESS aend = -1, int row = 0);
public:
// Overrides
//virtual void DisplayCaret(int char_width = -1);
virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra,
AFX_CMDHANDLERINFO* pHandlerInfo)
{
// If compare view can't handle it try "owner" hex view
if (CScrView::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo))
return TRUE;
else if (phev_ != NULL)
return phev_->OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);
else
return FALSE;
}
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual void OnInitialUpdate();
// virtual void OnPrepareDC(CDC* pDC, CPrintInfo* pInfo = NULL);
protected:
//virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
//virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
//virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
//virtual void OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint);
//virtual void OnPrint(CDC* pDC, CPrintInfo* pInfo);
//virtual void OnEndPrintPreview(CDC* pDC, CPrintInfo* pInfo, POINT point, CPreviewView* pView);
//virtual void OnActivateView(BOOL bActivate, CView* pActivateView, CView* pDeactiveView);
//virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
// Implementation
public:
//virtual void DoInvalidate();
protected:
virtual void ValidateCaret(CPointAp &pos, BOOL inside=TRUE);
//virtual void InvalidateRange(CPointAp start, CPointAp end, bool f = false);
//virtual void DoInvalidateRect(LPCRECT lpRect);
//virtual void DoInvalidateRgn(CRgn* pRgn);
virtual void DoScrollWindow(int xx, int yy);
//virtual void DoUpdateWindow();
//virtual void DoHScroll(int total, int page, int pos);
//virtual void DoVScroll(int total, int page, int pos);
//void DoUpdate();
virtual void AfterScroll(CPointAp newpos)
{
if (phev_ != NULL && phev_->display_.auto_scroll_comp)
phev_->SetScroll(newpos);
}
protected:
//afx_msg void OnDestroy();
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg void OnContextMenu(CWnd* pWnd, CPoint point);
afx_msg void OnSetFocus(CWnd* pNewWnd);
afx_msg void OnKillFocus(CWnd* pNewWnd);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg LRESULT OnMouseHover(WPARAM wp, LPARAM lp);
afx_msg LRESULT OnMouseLeave(WPARAM wp, LPARAM lp);
afx_msg void OnUpdateDisable(CCmdUI* pCmdUI) { pCmdUI->Enable(FALSE); }
afx_msg void OnCompFirst();
afx_msg void OnUpdateCompFirst(CCmdUI* pCmdUI);
afx_msg void OnCompPrev();
afx_msg void OnUpdateCompPrev(CCmdUI* pCmdUI);
afx_msg void OnCompNext();
afx_msg void OnUpdateCompNext(CCmdUI* pCmdUI);
afx_msg void OnCompLast();
afx_msg void OnUpdateCompLast(CCmdUI* pCmdUI);
afx_msg void OnEditCopy();
afx_msg void OnUpdateEditCopy(CCmdUI* pCmdUI);
afx_msg void OnSelectAll();
DECLARE_MESSAGE_MAP()
private:
void calc_addr_width(FILE_ADDRESS); // Also used by recalc_display
//void draw_bg(CDC* pDC, const CRectAp &doc_rect, bool neg_x, bool neg_y,
// int char_height, int char_width, int char_width_w,
// COLORREF, FILE_ADDRESS start_addr, FILE_ADDRESS end_addr,
// int draw_height = -1);
void draw_bg(CDC* pDC, const CRectAp &doc_rect, bool neg_x, bool neg_y,
int line_height, int char_width, int char_width_w,
COLORREF clr, FILE_ADDRESS start_addr, FILE_ADDRESS end_addr,
bool merge = true, int draw_height = -1);
void draw_deletions(CDC* pDC, const vector<FILE_ADDRESS> & addr, const vector<FILE_ADDRESS> & len,
FILE_ADDRESS first_virt, FILE_ADDRESS last_virt,
const CRectAp &doc_rect, bool neg_x, bool neg_y,
int line_height, int char_width, int char_width_w,
COLORREF colour);
void draw_backgrounds(CDC* pDC,
const vector<FILE_ADDRESS> & addr, const vector<FILE_ADDRESS> & len,
FILE_ADDRESS first_virt, FILE_ADDRESS last_virt,
const CRectAp &doc_rect, bool neg_x, bool neg_y,
int line_height, int char_width, int char_width_w,
COLORREF colour, bool merge = true, int draw_height = -1);
CPointAp addr2pos(FILE_ADDRESS address, int row = 0) const; // Convert byte address in doc to display position
int hex_pos(int column, int width=0) const // get X coord of hex display column
{
if (width == 0) width = phev_->text_width_;
return (addr_width_ + column*3 + column/phev_->group_by_)*width;
}
int char_pos(int column, int widthd=0, int widthw=0) const // get X coord of ASCII/EBCDIC display column
{
if (widthd == 0) widthd = phev_->text_width_;
if (widthw == 0) widthw = phev_->text_width_w_;
if (phev_->display_.vert_display)
return addr_width_*widthd +
(column + column/phev_->group_by_)*widthw;
else if (phev_->display_.hex_area)
return (addr_width_ + phev_->rowsize_*3)*widthd +
((phev_->rowsize_-1)/phev_->group_by_)*widthd +
column*widthw;
else
return addr_width_*widthd +
column*widthw;
}
int pos_hex(int, int inside = FALSE) const; // Closest hex display col given X
int pos_char(int, int inside = FALSE) const; // Closest char area col given X
FILE_ADDRESS pos2addr(CPointAp pos, BOOL inside = TRUE) const; // Convert a display position to closest address
int pos2row(CPointAp pos); // Find vert_display row (0, 1, or 2) of display position
BOOL GetSelAddr(FILE_ADDRESS &start_addr, FILE_ADDRESS &end_addr)
{
ASSERT(phev_->line_height_ > 0);
CPointAp start, end;
BOOL retval = GetSel(start, end);
start_addr = pos2addr(start);
end_addr = pos2addr(end);
return retval;
}
// Functions for selection tip (sel_tip_)
// void show_selection_tip();
void invalidate_addr_range(FILE_ADDRESS, FILE_ADDRESS); // Invalidate hex/aerial display for address range
void invalidate_hex_addr_range(FILE_ADDRESS start_addr, FILE_ADDRESS end_addr); // Invalidate hex view only
void recalc_display();
int addr_width_; // How much room in display does address area take?
int hex_width_, dec_width_, num_width_; // Components of addr_width_
void begin_change(); // Store current state etc
void end_change(); // Fix display etc
BOOL previous_caret_displayed_;
FILE_ADDRESS previous_start_addr_, previous_end_addr_; // selection
BOOL previous_end_base_;
int previous_row_; // row (0-2) if vert_display
};
#endif // COMPAREVIEW_INCLUDED
/////////////////////////////////////////////////////////////////////////////
|
{
"pile_set_name": "Github"
}
|
[aws_csm]
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
|
{
"pile_set_name": "Github"
}
|
package migrations
import (
"database/sql"
"github.com/pressly/goose"
)
func init() {
goose.AddMigration(Up20200411164603, Down20200411164603)
}
func Up20200411164603(tx *sql.Tx) error {
_, err := tx.Exec(`
alter table playlist
add created_at datetime;
alter table playlist
add updated_at datetime;
update playlist
set created_at = datetime('now'), updated_at = datetime('now');
`)
return err
}
func Down20200411164603(tx *sql.Tx) error {
return nil
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* JDK-8137240: Negative lookahead in RegEx breaks backreference
*
* @test
* @run
*/
Assert.assertEquals('aa'.replace(/(a)(?!b)\1/gm, 'c'), 'c');
var result = 'aa'.match(/(a)(?!b)\1/);
Assert.assertTrue(result.length === 2);
Assert.assertTrue(result[0] === 'aa');
Assert.assertTrue(result[1] === 'a');
result = 'aa'.match(/(a)(?!(b))\2(a)/);
Assert.assertTrue(result.length === 4);
Assert.assertTrue(result[0] === 'aa');
Assert.assertTrue(result[1] === 'a');
Assert.assertTrue(result[2] === undefined);
Assert.assertTrue(result[3] === 'a');
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2005-2020 Radiance Kirill Grouchnikov. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of the copyright holder 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.
*/
package org.pushingpixels.substance.internal.utils.filters;
import org.pushingpixels.neon.api.filter.NeonAbstractFilter;
import java.awt.*;
import java.awt.image.BufferedImage;
/**
* @author Kirill Grouchnikov
*/
public class ColorFilter extends NeonAbstractFilter {
private int color;
public ColorFilter(Color color) {
this.color = color.getRGB();
}
@Override
public BufferedImage filter(BufferedImage src, BufferedImage dst) {
if (dst == null) {
dst = createCompatibleDestImage(src, null);
}
int width = src.getWidth();
int height = src.getHeight();
int[] pixels = new int[width * height];
getPixels(src, 0, 0, width, height, pixels);
int colorAlpha = (this.color >>> 24) & 0xFF;
int colorRed = (this.color >>> 16) & 0xFF;
int colorGreen = (this.color >>> 8) & 0xFF;
int colorBlue = this.color & 0xFF;
for (int i = 0; i < pixels.length; i++) {
// Multiply source alpha by the alpha in our target color
int alpha = ((pixels[i] >>> 24) & 0xFF) * colorAlpha / 256;
// and use R/G/B from our target color
pixels[i] = alpha << 24 | colorRed << 16 | colorGreen << 8 | colorBlue;
}
setPixels(dst, 0, 0, width, height, pixels);
return dst;
}
}
|
{
"pile_set_name": "Github"
}
|
################################################################################
#
# tmon
#
################################################################################
LINUX_TOOLS += tmon
TMON_DEPENDENCIES = host-pkgconf ncurses
TMON_MAKE_OPTS = $(LINUX_MAKE_FLAGS) \
CC=$(TARGET_CC) \
PKG_CONFIG_PATH=$(STAGING_DIR)/usr/lib/pkgconfig
ifeq ($(BR2_TOOLCHAIN_HAS_SSP),)
define TMON_DISABLE_STACK_PROTECTOR
$(SED) 's%-fstack-protector%%' $(LINUX_DIR)/tools/thermal/tmon/Makefile
endef
endif
define TMON_BUILD_CMDS
$(Q)if ! grep install $(LINUX_DIR)/tools/thermal/tmon/Makefile >/dev/null 2>&1 ; then \
echo "Your kernel version is too old and does not have the tmon tool." ; \
echo "At least kernel 3.13 must be used." ; \
exit 1 ; \
fi
$(TMON_DISABLE_STACK_PROTECTOR)
$(TARGET_MAKE_ENV) $(MAKE) -C $(LINUX_DIR)/tools \
$(TMON_MAKE_OPTS) \
tmon
endef
define TMON_INSTALL_TARGET_CMDS
$(TARGET_MAKE_ENV) $(MAKE) -C $(LINUX_DIR)/tools \
$(TMON_MAKE_OPTS) \
INSTALL_ROOT=$(TARGET_DIR) \
tmon_install
endef
|
{
"pile_set_name": "Github"
}
|
Internal structures and implementation
======================================
In this (last) section on object orientation in PHP we'll have a look at some of the internal structures that were
previously only mentioned in passing. In particular we'll see more thoroughly the default object structure and the object
store.
Object properties
-----------------
The probably by far most complicated part of PHP's object orientation system is the handling of object properties. In
the following we'll take a look at some of its parts in more detail.
Property storage
~~~~~~~~~~~~~~~~
In PHP object properties can be declared, but don't have to. How can one efficiently handle such a situation? To find
out let's recall the standard ``zend_object`` structure::
typedef struct _zend_object {
zend_class_entry *ce;
HashTable *properties;
zval **properties_table;
HashTable *guards;
} zend_object;
This structure contains two fields for storing properties: The ``properties`` hash table and the ``properties_table``
array of ``zval`` pointers. Two separate fields are used to best handle both declared and dynamic properties: For the
latter, i.e. properties that have not been declared in the class, there is no way around using the ``properties``
hash table (which uses a simple property name => value mapping).
For declared properties on the other hand storing them in a hashtable would be overly wasteful: PHP's hash tables
have a very high per-element overhead (of nearly one hundred bytes), but the only thing that really needs to be stored
is a ``zval`` pointer for the value. For this reason PHP employs a small trick: The properties are stored in a normal
C array and accessed using their offset. The offset for each property name is stored in a (global) hashtable in the
class entry. Thus the property lookup happens with one additional level of indirection, i.e. rather than directly
fetching the property value, first the property offset is fetched and that offset is then used to fetch the actual
value.
Property information (including the storage offset) is stored in ``class_entry->properties_info``. This hash table
is a map of property names to ``zend_property_info`` structs::
typedef struct _zend_property_info {
zend_uint flags;
const char *name;
int name_length;
ulong h; /* hash of name */
int offset; /* storage offset */
const char *doc_comment;
int doc_comment_len;
zend_class_entry *ce; /* CE of declaring class */
} zend_property_info;
One remaining question is what happens when both types of properties exist. In this case both structures will be used
simultaneously: All properties will be written into the ``properties`` hashtable, but ``properties_table`` will still
contain pointers to them. Note though that if both are used the properties table holds ``zval**`` values rather than
``zval*`` values.
Sometimes PHP needs the properties as a hashtable even if they are all declared, e.g. when the ``get_properties``
handler is used. In this case PHP also switches to using ``properties`` (or rather the hybrid approach described above).
This is done using the ``rebuild_object_properties`` function::
ZEND_API HashTable *zend_std_get_properties(zval *object TSRMLS_DC)
{
zend_object *zobj;
zobj = Z_OBJ_P(object);
if (!zobj->properties) {
rebuild_object_properties(zobj);
}
return zobj->properties;
}
Property name mangling
~~~~~~~~~~~~~~~~~~~~~~
Consider the following code snippet:
.. code-block:: php
class A {
private $prop = 'A';
}
class B extends A {
private $prop = 'B';
}
class C extends B {
protected $prop = 'C';
}
var_dump(new C);
// Output:
object(C)#1 (3) {
["prop":protected]=>
string(1) "C"
["prop":"B":private]=>
string(1) "B"
["prop":"A":private]=>
string(1) "A"
}
In the above example you can see the "same" property ``$prop`` being defined three times: Once as a private property of
``A``, once as a private property of ``B`` and once as a protected property of ``C``. Even though these three properties
have the same name they are still distinct properties and require separate storage.
In order to support this situation PHP "mangles" the property name by including the type of the property and the
defining class:
.. code-block:: none
class Foo { private $prop; } => "\0Foo\0prop"
class Bar { private $prop; } => "\0Bar\0prop"
class Rab { protected $prop; } => "\0*\0prop"
class Oof { public $prop; } => "prop"
As you can see public properties have "normal" names, protected ones get a ``\0*\0`` prefix (where ``\0`` are NUL bytes)
and private ones start with ``\0ClassName\0``.
Most of the time PHP does a good job hiding the mangled names from userland. You only get to see them in some rare
cases, e.g. if you cast an object to array or look at serialization output. Internally you usually don't need to care
about mangled names either, e.g. when using the ``zend_declare_property`` APIs the mangling is automatically done for
you.
The only places where you have to look out for mangled names is if you access the ``property_info->name`` field or if
you try to directly access the ``zobj->properties`` hash. In this cases you can use the
``zend_(un)mangle_property_name`` APIs::
// Unmangling
const char *class_name, *property_name;
int property_name_len;
if (zend_unmangle_property_name_ex(
mangled_property_name, mangled_property_name_len,
&class_name, &property_name, &property_name_len
) == SUCCESS) {
// ...
}
// Mangling
char *mangled_property_name;
int mangled_property_name_len;
zend_mangle_property_name(
&mangled_property_name, &mangled_property_name_len,
class_name, class_name_len, property_name, property_name_len,
should_do_persistent_alloc ? 1 : 0
);
Property recursion guards
~~~~~~~~~~~~~~~~~~~~~~~~~
The last member in ``zend_object`` is the ``HashTable *guards`` field. To find out what it is used for, consider what
happens in the following code using magic ``__set`` properties:
.. code-block:: php
class Foo {
public function __set($name, $value) {
$this->$name = $value;
}
}
$foo = new Foo;
$foo->bar = 'baz';
var_dump($foo->bar);
The ``$foo->bar = 'baz'`` assignment in the script will call ``$foo->__set('bar', 'baz')`` as the ``$bar`` property is
not defined. The ``$this->$name = $value`` line in the method body in this case would become ``$foo->bar = 'baz'``.
Once again ``$bar`` is an undefined property. So, does that mean that the ``__set`` method will be (recursively) called
again?
That's not what happens. Rather PHP sees that it is already within ``__set`` and does *not* do a recursive call. Instead
it actually creates the new ``$bar`` property. In order to implement this behavior PHP uses recursion guards which
remember whether PHP is already in ``__set`` etc for a certain property. These guards are stored in the ``guards`` hash
table, which maps property names to ``zend_guard`` structures::
typedef struct _zend_guard {
zend_bool in_get;
zend_bool in_set;
zend_bool in_unset;
zend_bool in_isset;
zend_bool dummy; /* sizeof(zend_guard) must not be equal to sizeof(void*) */
} zend_guard;
Object store
------------
We already made a lot of use of the object store, so let's have a closer look at it now::
typedef struct _zend_objects_store {
zend_object_store_bucket *object_buckets;
zend_uint top;
zend_uint size;
int free_list_head;
} zend_objects_store;
The object store is basically a dynamically resized array of ``object_buckets``. ``size`` specifies the size of the
allocation, whereas ``top`` is the next object handle to be used. Handles are counted starting from 1, to ensure that
all handles are "truthy". Thus if ``top == 1`` the next object will get ``handle = 1``, but will be put at position
``object_buckets[0]``.
The ``free_list_head`` is the head of a linked list of unused buckets. Whenever an object is destroyed it leaves behind
an unused bucket, which is then put in this list. If a new object is created and such a bucket exists (i.e.
``free_list_head`` is not ``-1``), then this bucket is used instead of the ``top`` one.
To see how this linked list is maintained have a look at the ``zend_object_store_bucket`` structure::
typedef struct _zend_object_store_bucket {
zend_bool destructor_called;
zend_bool valid;
zend_uchar apply_count;
union _store_bucket {
struct _store_object {
void *object;
zend_objects_store_dtor_t dtor;
zend_objects_free_object_storage_t free_storage;
zend_objects_store_clone_t clone;
const zend_object_handlers *handlers;
zend_uint refcount;
gc_root_buffer *buffered;
} obj;
struct {
int next;
} free_list;
} bucket;
} zend_object_store_bucket;
If the bucket is in use (i.e. stores an object), then the ``valid`` member will be 1. In this case the
``struct _store_object`` part of the union will be used. If the bucket is not used, then ``valid`` will be 0 and PHP
will make use of ``free_list.next``.
This reclaiming of unused object handles can be shown with a small script:
.. code-block:: php
var_dump($a = new stdClass); // object(stdClass)#1 (0) {}
var_dump($b = new stdClass); // object(stdClass)#2 (0) {}
var_dump($c = new stdClass); // object(stdClass)#3 (0) {}
unset($b); // free handle 2
unset($a); // free handle 1
var_dump($e = new stdClass); // object(stdClass)#1 (0) {}
var_dump($f = new stdClass); // object(stdClass)#2 (0) {}
As you can see the handles of ``$b`` and ``$a`` are reused in reverse order of destruction.
Apart from ``valid`` the bucket structure also contains a ``destructor_called`` flag. This flag is needed for PHP's
two-phase object destruction process: As already outlined previously PHP has distinct dtor (can run userland code, isn't
always run) and free (must not run userland code, is always executed) phases. After the dtor handler has been called,
the ``destructor_called`` flag is set to 1, so that the dtor is not run again when the object is freed.
The ``apply_count`` member serves the same role as the ``nApplyCount`` member of ``HashTable``: It protects against
infinite recursion. It is used via the macros ``Z_OBJ_UNPROTECT_RECURSION(zval_ptr)`` (leave recursion) and
``Z_OBJ_PROTECT_RECURSION(zval_ptr)`` (enter recursion). The latter will throw an error if the nesting level for an
object is 3 or larger. Currently this protection mechanism is only used in the object comparison handler.
The ``handlers`` member in the ``_store_object`` struct is also required for destruction. The reason for this is that
the ``dtor`` handler only gets passed the stored object and its handle::
typedef void (*zend_objects_store_dtor_t)(void *object, zend_object_handle handle TSRMLS_DC);
But in order to call ``__destruct`` PHP needs a zval. Thus it creates a temporary zval using the passed object handle
and the object handlers stored in ``bucket.obj.handlers``. The issue is that this member can only be set if the object
is destructed through ``zval_ptr_dtor`` or some other method where the zval (and as such the object handlers) is known.
If on the other hand the object is destroyed during shutdown (using ``zend_objects_store_call_destructors``) the zval
is *not* known. In this case ``bucket.obj.handlers`` will be ``NULL`` and PHP falls back to the default object handlers.
Thus it can sometimes happen that overloaded object behavior is not available in ``__destruct``. An example:
.. code-block:: php
class DLL extends SplDoublyLinkedList {
public function __destruct() {
var_dump($this);
}
}
$dll = new DLL;
$dll->push(1);
$dll->push(2);
$dll->push(3);
var_dump($dll);
set_error_handler(function() use ($dll) {});
This code snippet adds a ``__destruct`` method to ``SplDoublyLinkedList`` and then forces the destructor to be called
during shutdown by binding it to the error handler (the error handler is one of the last things that is freed during
shutdown.) This will produce the following output:
.. code-block:: none
object(DLL)#1 (2) {
["flags":"SplDoublyLinkedList":private]=>
int(0)
["dllist":"SplDoublyLinkedList":private]=>
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
}
object(DLL)#1 (0) {
}
For the ``var_dump`` outside the destructor ``get_debug_info`` is invoked and you get meaningful debugging output.
Inside the destructor PHP uses the default object handlers and as such you don't get anything apart from the class
name. The same also applies to other handlers, e.g. things like cloning, comparison, etc will not work properly.
This concludes the chapter on object orientation. You should now have a good understanding of how the object orientation
system in PHP works and how extensions can make use of it.
|
{
"pile_set_name": "Github"
}
|
// Code generated by MockGen. DO NOT EDIT.
// Source: ./event_handlers.go
// Package mock_controller is a generated GoMock package.
package mock_controller
import (
context "context"
reflect "reflect"
gomock "github.com/golang/mock/gomock"
v1alpha2 "github.com/solo-io/service-mesh-hub/pkg/api/certificates.smh.solo.io/v1alpha2"
controller "github.com/solo-io/service-mesh-hub/pkg/api/certificates.smh.solo.io/v1alpha2/controller"
predicate "sigs.k8s.io/controller-runtime/pkg/predicate"
)
// MockIssuedCertificateEventHandler is a mock of IssuedCertificateEventHandler interface
type MockIssuedCertificateEventHandler struct {
ctrl *gomock.Controller
recorder *MockIssuedCertificateEventHandlerMockRecorder
}
// MockIssuedCertificateEventHandlerMockRecorder is the mock recorder for MockIssuedCertificateEventHandler
type MockIssuedCertificateEventHandlerMockRecorder struct {
mock *MockIssuedCertificateEventHandler
}
// NewMockIssuedCertificateEventHandler creates a new mock instance
func NewMockIssuedCertificateEventHandler(ctrl *gomock.Controller) *MockIssuedCertificateEventHandler {
mock := &MockIssuedCertificateEventHandler{ctrl: ctrl}
mock.recorder = &MockIssuedCertificateEventHandlerMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockIssuedCertificateEventHandler) EXPECT() *MockIssuedCertificateEventHandlerMockRecorder {
return m.recorder
}
// CreateIssuedCertificate mocks base method
func (m *MockIssuedCertificateEventHandler) CreateIssuedCertificate(obj *v1alpha2.IssuedCertificate) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CreateIssuedCertificate", obj)
ret0, _ := ret[0].(error)
return ret0
}
// CreateIssuedCertificate indicates an expected call of CreateIssuedCertificate
func (mr *MockIssuedCertificateEventHandlerMockRecorder) CreateIssuedCertificate(obj interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateIssuedCertificate", reflect.TypeOf((*MockIssuedCertificateEventHandler)(nil).CreateIssuedCertificate), obj)
}
// UpdateIssuedCertificate mocks base method
func (m *MockIssuedCertificateEventHandler) UpdateIssuedCertificate(old, new *v1alpha2.IssuedCertificate) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "UpdateIssuedCertificate", old, new)
ret0, _ := ret[0].(error)
return ret0
}
// UpdateIssuedCertificate indicates an expected call of UpdateIssuedCertificate
func (mr *MockIssuedCertificateEventHandlerMockRecorder) UpdateIssuedCertificate(old, new interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateIssuedCertificate", reflect.TypeOf((*MockIssuedCertificateEventHandler)(nil).UpdateIssuedCertificate), old, new)
}
// DeleteIssuedCertificate mocks base method
func (m *MockIssuedCertificateEventHandler) DeleteIssuedCertificate(obj *v1alpha2.IssuedCertificate) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DeleteIssuedCertificate", obj)
ret0, _ := ret[0].(error)
return ret0
}
// DeleteIssuedCertificate indicates an expected call of DeleteIssuedCertificate
func (mr *MockIssuedCertificateEventHandlerMockRecorder) DeleteIssuedCertificate(obj interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteIssuedCertificate", reflect.TypeOf((*MockIssuedCertificateEventHandler)(nil).DeleteIssuedCertificate), obj)
}
// GenericIssuedCertificate mocks base method
func (m *MockIssuedCertificateEventHandler) GenericIssuedCertificate(obj *v1alpha2.IssuedCertificate) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GenericIssuedCertificate", obj)
ret0, _ := ret[0].(error)
return ret0
}
// GenericIssuedCertificate indicates an expected call of GenericIssuedCertificate
func (mr *MockIssuedCertificateEventHandlerMockRecorder) GenericIssuedCertificate(obj interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GenericIssuedCertificate", reflect.TypeOf((*MockIssuedCertificateEventHandler)(nil).GenericIssuedCertificate), obj)
}
// MockIssuedCertificateEventWatcher is a mock of IssuedCertificateEventWatcher interface
type MockIssuedCertificateEventWatcher struct {
ctrl *gomock.Controller
recorder *MockIssuedCertificateEventWatcherMockRecorder
}
// MockIssuedCertificateEventWatcherMockRecorder is the mock recorder for MockIssuedCertificateEventWatcher
type MockIssuedCertificateEventWatcherMockRecorder struct {
mock *MockIssuedCertificateEventWatcher
}
// NewMockIssuedCertificateEventWatcher creates a new mock instance
func NewMockIssuedCertificateEventWatcher(ctrl *gomock.Controller) *MockIssuedCertificateEventWatcher {
mock := &MockIssuedCertificateEventWatcher{ctrl: ctrl}
mock.recorder = &MockIssuedCertificateEventWatcherMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockIssuedCertificateEventWatcher) EXPECT() *MockIssuedCertificateEventWatcherMockRecorder {
return m.recorder
}
// AddEventHandler mocks base method
func (m *MockIssuedCertificateEventWatcher) AddEventHandler(ctx context.Context, h controller.IssuedCertificateEventHandler, predicates ...predicate.Predicate) error {
m.ctrl.T.Helper()
varargs := []interface{}{ctx, h}
for _, a := range predicates {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "AddEventHandler", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// AddEventHandler indicates an expected call of AddEventHandler
func (mr *MockIssuedCertificateEventWatcherMockRecorder) AddEventHandler(ctx, h interface{}, predicates ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{ctx, h}, predicates...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddEventHandler", reflect.TypeOf((*MockIssuedCertificateEventWatcher)(nil).AddEventHandler), varargs...)
}
// MockCertificateRequestEventHandler is a mock of CertificateRequestEventHandler interface
type MockCertificateRequestEventHandler struct {
ctrl *gomock.Controller
recorder *MockCertificateRequestEventHandlerMockRecorder
}
// MockCertificateRequestEventHandlerMockRecorder is the mock recorder for MockCertificateRequestEventHandler
type MockCertificateRequestEventHandlerMockRecorder struct {
mock *MockCertificateRequestEventHandler
}
// NewMockCertificateRequestEventHandler creates a new mock instance
func NewMockCertificateRequestEventHandler(ctrl *gomock.Controller) *MockCertificateRequestEventHandler {
mock := &MockCertificateRequestEventHandler{ctrl: ctrl}
mock.recorder = &MockCertificateRequestEventHandlerMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockCertificateRequestEventHandler) EXPECT() *MockCertificateRequestEventHandlerMockRecorder {
return m.recorder
}
// CreateCertificateRequest mocks base method
func (m *MockCertificateRequestEventHandler) CreateCertificateRequest(obj *v1alpha2.CertificateRequest) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "CreateCertificateRequest", obj)
ret0, _ := ret[0].(error)
return ret0
}
// CreateCertificateRequest indicates an expected call of CreateCertificateRequest
func (mr *MockCertificateRequestEventHandlerMockRecorder) CreateCertificateRequest(obj interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateCertificateRequest", reflect.TypeOf((*MockCertificateRequestEventHandler)(nil).CreateCertificateRequest), obj)
}
// UpdateCertificateRequest mocks base method
func (m *MockCertificateRequestEventHandler) UpdateCertificateRequest(old, new *v1alpha2.CertificateRequest) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "UpdateCertificateRequest", old, new)
ret0, _ := ret[0].(error)
return ret0
}
// UpdateCertificateRequest indicates an expected call of UpdateCertificateRequest
func (mr *MockCertificateRequestEventHandlerMockRecorder) UpdateCertificateRequest(old, new interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateCertificateRequest", reflect.TypeOf((*MockCertificateRequestEventHandler)(nil).UpdateCertificateRequest), old, new)
}
// DeleteCertificateRequest mocks base method
func (m *MockCertificateRequestEventHandler) DeleteCertificateRequest(obj *v1alpha2.CertificateRequest) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DeleteCertificateRequest", obj)
ret0, _ := ret[0].(error)
return ret0
}
// DeleteCertificateRequest indicates an expected call of DeleteCertificateRequest
func (mr *MockCertificateRequestEventHandlerMockRecorder) DeleteCertificateRequest(obj interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCertificateRequest", reflect.TypeOf((*MockCertificateRequestEventHandler)(nil).DeleteCertificateRequest), obj)
}
// GenericCertificateRequest mocks base method
func (m *MockCertificateRequestEventHandler) GenericCertificateRequest(obj *v1alpha2.CertificateRequest) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GenericCertificateRequest", obj)
ret0, _ := ret[0].(error)
return ret0
}
// GenericCertificateRequest indicates an expected call of GenericCertificateRequest
func (mr *MockCertificateRequestEventHandlerMockRecorder) GenericCertificateRequest(obj interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GenericCertificateRequest", reflect.TypeOf((*MockCertificateRequestEventHandler)(nil).GenericCertificateRequest), obj)
}
// MockCertificateRequestEventWatcher is a mock of CertificateRequestEventWatcher interface
type MockCertificateRequestEventWatcher struct {
ctrl *gomock.Controller
recorder *MockCertificateRequestEventWatcherMockRecorder
}
// MockCertificateRequestEventWatcherMockRecorder is the mock recorder for MockCertificateRequestEventWatcher
type MockCertificateRequestEventWatcherMockRecorder struct {
mock *MockCertificateRequestEventWatcher
}
// NewMockCertificateRequestEventWatcher creates a new mock instance
func NewMockCertificateRequestEventWatcher(ctrl *gomock.Controller) *MockCertificateRequestEventWatcher {
mock := &MockCertificateRequestEventWatcher{ctrl: ctrl}
mock.recorder = &MockCertificateRequestEventWatcherMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockCertificateRequestEventWatcher) EXPECT() *MockCertificateRequestEventWatcherMockRecorder {
return m.recorder
}
// AddEventHandler mocks base method
func (m *MockCertificateRequestEventWatcher) AddEventHandler(ctx context.Context, h controller.CertificateRequestEventHandler, predicates ...predicate.Predicate) error {
m.ctrl.T.Helper()
varargs := []interface{}{ctx, h}
for _, a := range predicates {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "AddEventHandler", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// AddEventHandler indicates an expected call of AddEventHandler
func (mr *MockCertificateRequestEventWatcherMockRecorder) AddEventHandler(ctx, h interface{}, predicates ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{ctx, h}, predicates...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddEventHandler", reflect.TypeOf((*MockCertificateRequestEventWatcher)(nil).AddEventHandler), varargs...)
}
|
{
"pile_set_name": "Github"
}
|
grpc_host_port: &grpc_host_port
grpc_host: "127.0.0.1"
grpc_port: "50100"
channel_check:
check_period: 10
stop_flag_file: "channel_check.stop"
alignment:
check_period: 1
loops_check:
check_period: 1
time_flag_file: "collect.time"
|
{
"pile_set_name": "Github"
}
|
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include <cstring>
#include <memory>
#include <numeric>
#include <utility>
#include "base/profiler/stack_buffer.h"
#include "base/profiler/stack_copier_suspend.h"
#include "base/profiler/suspendable_thread_delegate.h"
#include "base/stl_util.h"
#include "build/build_config.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
namespace {
using ::testing::ElementsAre;
// A thread delegate for use in tests that provides the expected behavior when
// operating on the supplied fake stack.
class TestSuspendableThreadDelegate : public SuspendableThreadDelegate {
public:
class TestScopedSuspendThread
: public SuspendableThreadDelegate::ScopedSuspendThread {
public:
TestScopedSuspendThread() = default;
TestScopedSuspendThread(const TestScopedSuspendThread&) = delete;
TestScopedSuspendThread& operator=(const TestScopedSuspendThread&) = delete;
bool WasSuccessful() const override { return true; }
};
TestSuspendableThreadDelegate(const std::vector<uintptr_t>& fake_stack,
// The register context will be initialized to
// *|thread_context| if non-null.
RegisterContext* thread_context = nullptr)
: fake_stack_(fake_stack), thread_context_(thread_context) {}
TestSuspendableThreadDelegate(const TestSuspendableThreadDelegate&) = delete;
TestSuspendableThreadDelegate& operator=(
const TestSuspendableThreadDelegate&) = delete;
std::unique_ptr<ScopedSuspendThread> CreateScopedSuspendThread() override {
return std::make_unique<TestScopedSuspendThread>();
}
bool GetThreadContext(RegisterContext* thread_context) override {
if (thread_context_)
*thread_context = *thread_context_;
// Set the stack pointer to be consistent with the provided fake stack.
RegisterContextStackPointer(thread_context) =
reinterpret_cast<uintptr_t>(&fake_stack_[0]);
RegisterContextInstructionPointer(thread_context) =
reinterpret_cast<uintptr_t>(fake_stack_[0]);
return true;
}
PlatformThreadId GetThreadId() const override { return PlatformThreadId(); }
uintptr_t GetStackBaseAddress() const override {
return reinterpret_cast<uintptr_t>(&fake_stack_[0] + fake_stack_.size());
}
bool CanCopyStack(uintptr_t stack_pointer) override { return true; }
std::vector<uintptr_t*> GetRegistersToRewrite(
RegisterContext* thread_context) override {
return {&RegisterContextFramePointer(thread_context)};
}
private:
// Must be a reference to retain the underlying allocation from the vector
// passed to the constructor.
const std::vector<uintptr_t>& fake_stack_;
RegisterContext* thread_context_;
};
class TestStackCopierDelegate : public StackCopier::Delegate {
public:
void OnStackCopy() override {
on_stack_copy_was_invoked_ = true;
}
bool on_stack_copy_was_invoked() const { return on_stack_copy_was_invoked_; }
private:
bool on_stack_copy_was_invoked_ = false;
};
} // namespace
TEST(StackCopierSuspendTest, CopyStack) {
const std::vector<uintptr_t> stack = {0, 1, 2, 3, 4};
StackCopierSuspend stack_copier_suspend(
std::make_unique<TestSuspendableThreadDelegate>(stack));
std::unique_ptr<StackBuffer> stack_buffer =
std::make_unique<StackBuffer>(stack.size() * sizeof(uintptr_t));
uintptr_t stack_top = 0;
TimeTicks timestamp;
RegisterContext register_context{};
TestStackCopierDelegate stack_copier_delegate;
stack_copier_suspend.CopyStack(stack_buffer.get(), &stack_top, ×tamp,
®ister_context, &stack_copier_delegate);
uintptr_t* stack_copy_bottom =
reinterpret_cast<uintptr_t*>(stack_buffer.get()->buffer());
std::vector<uintptr_t> stack_copy(stack_copy_bottom,
stack_copy_bottom + stack.size());
EXPECT_EQ(stack, stack_copy);
}
TEST(StackCopierSuspendTest, CopyStackBufferTooSmall) {
std::vector<uintptr_t> stack = {0, 1, 2, 3, 4};
StackCopierSuspend stack_copier_suspend(
std::make_unique<TestSuspendableThreadDelegate>(stack));
std::unique_ptr<StackBuffer> stack_buffer =
std::make_unique<StackBuffer>((stack.size() - 1) * sizeof(uintptr_t));
// Make the buffer different than the input stack.
stack_buffer->buffer()[0] = 100;
uintptr_t stack_top = 0;
TimeTicks timestamp;
RegisterContext register_context{};
TestStackCopierDelegate stack_copier_delegate;
stack_copier_suspend.CopyStack(stack_buffer.get(), &stack_top, ×tamp,
®ister_context, &stack_copier_delegate);
uintptr_t* stack_copy_bottom =
reinterpret_cast<uintptr_t*>(stack_buffer.get()->buffer());
std::vector<uintptr_t> stack_copy(stack_copy_bottom,
stack_copy_bottom + stack.size());
// Use the buffer not being overwritten as a proxy for the unwind being
// aborted.
EXPECT_NE(stack, stack_copy);
}
TEST(StackCopierSuspendTest, CopyStackAndRewritePointers) {
// Allocate space for the stack, then make its elements point to themselves.
std::vector<uintptr_t> stack(2);
stack[0] = reinterpret_cast<uintptr_t>(&stack[0]);
stack[1] = reinterpret_cast<uintptr_t>(&stack[1]);
StackCopierSuspend stack_copier_suspend(
std::make_unique<TestSuspendableThreadDelegate>(stack));
std::unique_ptr<StackBuffer> stack_buffer =
std::make_unique<StackBuffer>(stack.size() * sizeof(uintptr_t));
uintptr_t stack_top = 0;
TimeTicks timestamp;
RegisterContext register_context{};
TestStackCopierDelegate stack_copier_delegate;
stack_copier_suspend.CopyStack(stack_buffer.get(), &stack_top, ×tamp,
®ister_context, &stack_copier_delegate);
uintptr_t* stack_copy_bottom =
reinterpret_cast<uintptr_t*>(stack_buffer.get()->buffer());
std::vector<uintptr_t> stack_copy(stack_copy_bottom,
stack_copy_bottom + stack.size());
EXPECT_THAT(stack_copy,
ElementsAre(reinterpret_cast<uintptr_t>(stack_copy_bottom),
reinterpret_cast<uintptr_t>(stack_copy_bottom) +
sizeof(uintptr_t)));
}
TEST(StackCopierSuspendTest, CopyStackTimeStamp) {
const std::vector<uintptr_t> stack = {0};
StackCopierSuspend stack_copier_suspend(
std::make_unique<TestSuspendableThreadDelegate>(stack));
std::unique_ptr<StackBuffer> stack_buffer =
std::make_unique<StackBuffer>(stack.size() * sizeof(uintptr_t));
uintptr_t stack_top = 0;
TimeTicks timestamp;
RegisterContext register_context{};
TestStackCopierDelegate stack_copier_delegate;
TimeTicks before = TimeTicks::Now();
stack_copier_suspend.CopyStack(stack_buffer.get(), &stack_top, ×tamp,
®ister_context, &stack_copier_delegate);
TimeTicks after = TimeTicks::Now();
EXPECT_GE(timestamp, before);
EXPECT_LE(timestamp, after);
}
TEST(StackCopierSuspendTest, CopyStackDelegateInvoked) {
const std::vector<uintptr_t> stack = {0};
StackCopierSuspend stack_copier_suspend(
std::make_unique<TestSuspendableThreadDelegate>(stack));
std::unique_ptr<StackBuffer> stack_buffer =
std::make_unique<StackBuffer>(stack.size() * sizeof(uintptr_t));
uintptr_t stack_top = 0;
TimeTicks timestamp;
RegisterContext register_context{};
TestStackCopierDelegate stack_copier_delegate;
stack_copier_suspend.CopyStack(stack_buffer.get(), &stack_top, ×tamp,
®ister_context, &stack_copier_delegate);
EXPECT_TRUE(stack_copier_delegate.on_stack_copy_was_invoked());
}
TEST(StackCopierSuspendTest, RewriteRegisters) {
std::vector<uintptr_t> stack = {0, 1, 2};
RegisterContext register_context{};
TestStackCopierDelegate stack_copier_delegate;
RegisterContextFramePointer(®ister_context) =
reinterpret_cast<uintptr_t>(&stack[1]);
StackCopierSuspend stack_copier_suspend(
std::make_unique<TestSuspendableThreadDelegate>(stack,
®ister_context));
std::unique_ptr<StackBuffer> stack_buffer =
std::make_unique<StackBuffer>(stack.size() * sizeof(uintptr_t));
uintptr_t stack_top = 0;
TimeTicks timestamp;
stack_copier_suspend.CopyStack(stack_buffer.get(), &stack_top, ×tamp,
®ister_context, &stack_copier_delegate);
uintptr_t stack_copy_bottom =
reinterpret_cast<uintptr_t>(stack_buffer.get()->buffer());
EXPECT_EQ(stack_copy_bottom + sizeof(uintptr_t),
RegisterContextFramePointer(®ister_context));
}
} // namespace base
|
{
"pile_set_name": "Github"
}
|
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
|
{
"pile_set_name": "Github"
}
|
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in 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.
*
* The Original Code is Copyright (C) 2006 Blender Foundation.
* All rights reserved.
*/
/** \file
* \ingroup render
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "MEM_guardedalloc.h"
#include "BLI_utildefines.h"
#include "BLI_ghash.h"
#include "BLI_listbase.h"
#include "BLI_hash_md5.h"
#include "BLI_path_util.h"
#include "BLI_rect.h"
#include "BLI_string.h"
#include "BLI_threads.h"
#include "BKE_appdir.h"
#include "BKE_camera.h"
#include "BKE_global.h"
#include "BKE_image.h"
#include "BKE_report.h"
#include "BKE_scene.h"
#include "IMB_imbuf.h"
#include "IMB_imbuf_types.h"
#include "IMB_colormanagement.h"
#include "intern/openexr/openexr_multi.h"
#include "RE_engine.h"
#include "render_result.h"
#include "render_types.h"
/********************************** Free *************************************/
static void render_result_views_free(RenderResult *res)
{
while (res->views.first) {
RenderView *rv = res->views.first;
BLI_remlink(&res->views, rv);
if (rv->rect32) {
MEM_freeN(rv->rect32);
}
if (rv->rectz) {
MEM_freeN(rv->rectz);
}
if (rv->rectf) {
MEM_freeN(rv->rectf);
}
MEM_freeN(rv);
}
res->have_combined = false;
}
void render_result_free(RenderResult *res)
{
if (res == NULL) {
return;
}
while (res->layers.first) {
RenderLayer *rl = res->layers.first;
while (rl->passes.first) {
RenderPass *rpass = rl->passes.first;
if (rpass->rect) {
MEM_freeN(rpass->rect);
}
BLI_remlink(&rl->passes, rpass);
MEM_freeN(rpass);
}
BLI_remlink(&res->layers, rl);
MEM_freeN(rl);
}
render_result_views_free(res);
if (res->rect32) {
MEM_freeN(res->rect32);
}
if (res->rectz) {
MEM_freeN(res->rectz);
}
if (res->rectf) {
MEM_freeN(res->rectf);
}
if (res->text) {
MEM_freeN(res->text);
}
if (res->error) {
MEM_freeN(res->error);
}
BKE_stamp_data_free(res->stamp_data);
MEM_freeN(res);
}
/* version that's compatible with fullsample buffers */
void render_result_free_list(ListBase *lb, RenderResult *rr)
{
RenderResult *rrnext;
for (; rr; rr = rrnext) {
rrnext = rr->next;
if (lb && lb->first) {
BLI_remlink(lb, rr);
}
render_result_free(rr);
}
}
/********************************* multiview *************************************/
/* create a new views Listbase in rr without duplicating the memory pointers */
void render_result_views_shallowcopy(RenderResult *dst, RenderResult *src)
{
RenderView *rview;
if (dst == NULL || src == NULL) {
return;
}
for (rview = src->views.first; rview; rview = rview->next) {
RenderView *rv;
rv = MEM_mallocN(sizeof(RenderView), "new render view");
BLI_addtail(&dst->views, rv);
BLI_strncpy(rv->name, rview->name, sizeof(rv->name));
rv->rectf = rview->rectf;
rv->rectz = rview->rectz;
rv->rect32 = rview->rect32;
}
}
/* free the views created temporarily */
void render_result_views_shallowdelete(RenderResult *rr)
{
if (rr == NULL) {
return;
}
while (rr->views.first) {
RenderView *rv = rr->views.first;
BLI_remlink(&rr->views, rv);
MEM_freeN(rv);
}
}
static char *set_pass_name(char *outname, const char *name, int channel, const char *chan_id)
{
BLI_strncpy(outname, name, EXR_PASS_MAXNAME);
if (channel >= 0) {
char token[3] = {'.', chan_id[channel], '\0'};
strncat(outname, token, EXR_PASS_MAXNAME);
}
return outname;
}
static void set_pass_full_name(
char *fullname, const char *name, int channel, const char *view, const char *chan_id)
{
BLI_strncpy(fullname, name, EXR_PASS_MAXNAME);
if (view && view[0]) {
strncat(fullname, ".", EXR_PASS_MAXNAME);
strncat(fullname, view, EXR_PASS_MAXNAME);
}
if (channel >= 0) {
char token[3] = {'.', chan_id[channel], '\0'};
strncat(fullname, token, EXR_PASS_MAXNAME);
}
}
/********************************** New **************************************/
static RenderPass *render_layer_add_pass(RenderResult *rr,
RenderLayer *rl,
int channels,
const char *name,
const char *viewname,
const char *chan_id)
{
const int view_id = BLI_findstringindex(&rr->views, viewname, offsetof(RenderView, name));
RenderPass *rpass = MEM_callocN(sizeof(RenderPass), name);
size_t rectsize = ((size_t)rr->rectx) * rr->recty * channels;
rpass->channels = channels;
rpass->rectx = rl->rectx;
rpass->recty = rl->recty;
rpass->view_id = view_id;
BLI_strncpy(rpass->name, name, sizeof(rpass->name));
BLI_strncpy(rpass->chan_id, chan_id, sizeof(rpass->chan_id));
BLI_strncpy(rpass->view, viewname, sizeof(rpass->view));
set_pass_full_name(rpass->fullname, rpass->name, -1, rpass->view, rpass->chan_id);
if (rl->exrhandle) {
int a;
for (a = 0; a < channels; a++) {
char passname[EXR_PASS_MAXNAME];
IMB_exr_add_channel(rl->exrhandle,
rl->name,
set_pass_name(passname, rpass->name, a, rpass->chan_id),
viewname,
0,
0,
NULL,
false);
}
}
/* Always allocate combined for display, in case of save buffers
* other passes are not allocated and only saved to the EXR file. */
if (rl->exrhandle == NULL || STREQ(rpass->name, RE_PASSNAME_COMBINED)) {
float *rect;
int x;
rpass->rect = MEM_mapallocN(sizeof(float) * rectsize, name);
if (rpass->rect == NULL) {
MEM_freeN(rpass);
return NULL;
}
if (STREQ(rpass->name, RE_PASSNAME_VECTOR)) {
/* initialize to max speed */
rect = rpass->rect;
for (x = rectsize - 1; x >= 0; x--) {
rect[x] = PASS_VECTOR_MAX;
}
}
else if (STREQ(rpass->name, RE_PASSNAME_Z)) {
rect = rpass->rect;
for (x = rectsize - 1; x >= 0; x--) {
rect[x] = 10e10;
}
}
}
BLI_addtail(&rl->passes, rpass);
return rpass;
}
/* wrapper called from render_opengl */
RenderPass *gp_add_pass(
RenderResult *rr, RenderLayer *rl, int channels, const char *name, const char *viewname)
{
return render_layer_add_pass(rr, rl, channels, name, viewname, "RGBA");
}
/* called by main render as well for parts */
/* will read info from Render *re to define layers */
/* called in threads */
/* re->winx,winy is coordinate space of entire image, partrct the part within */
RenderResult *render_result_new(Render *re,
rcti *partrct,
int crop,
int savebuffers,
const char *layername,
const char *viewname)
{
RenderResult *rr;
RenderLayer *rl;
RenderView *rv;
int rectx, recty;
rectx = BLI_rcti_size_x(partrct);
recty = BLI_rcti_size_y(partrct);
if (rectx <= 0 || recty <= 0) {
return NULL;
}
rr = MEM_callocN(sizeof(RenderResult), "new render result");
rr->rectx = rectx;
rr->recty = recty;
rr->renrect.xmin = 0;
rr->renrect.xmax = rectx - 2 * crop;
/* crop is one or two extra pixels rendered for filtering, is used for merging and display too */
rr->crop = crop;
/* tilerect is relative coordinates within render disprect. do not subtract crop yet */
rr->tilerect.xmin = partrct->xmin - re->disprect.xmin;
rr->tilerect.xmax = partrct->xmax - re->disprect.xmin;
rr->tilerect.ymin = partrct->ymin - re->disprect.ymin;
rr->tilerect.ymax = partrct->ymax - re->disprect.ymin;
if (savebuffers) {
rr->do_exr_tile = true;
}
render_result_views_new(rr, &re->r);
/* check renderdata for amount of layers */
FOREACH_VIEW_LAYER_TO_RENDER_BEGIN (re, view_layer) {
if (layername && layername[0]) {
if (!STREQ(view_layer->name, layername)) {
continue;
}
}
rl = MEM_callocN(sizeof(RenderLayer), "new render layer");
BLI_addtail(&rr->layers, rl);
BLI_strncpy(rl->name, view_layer->name, sizeof(rl->name));
rl->layflag = view_layer->layflag;
/* for debugging: view_layer->passflag | SCE_PASS_RAYHITS; */
rl->passflag = view_layer->passflag;
rl->rectx = rectx;
rl->recty = recty;
if (rr->do_exr_tile) {
rl->exrhandle = IMB_exr_get_handle();
}
for (rv = rr->views.first; rv; rv = rv->next) {
const char *view = rv->name;
if (viewname && viewname[0]) {
if (!STREQ(view, viewname)) {
continue;
}
}
if (rr->do_exr_tile) {
IMB_exr_add_view(rl->exrhandle, view);
}
#define RENDER_LAYER_ADD_PASS_SAFE(rr, rl, channels, name, viewname, chan_id) \
do { \
if (render_layer_add_pass(rr, rl, channels, name, viewname, chan_id) == NULL) { \
render_result_free(rr); \
return NULL; \
} \
} while (false)
/* a renderlayer should always have a Combined pass*/
render_layer_add_pass(rr, rl, 4, "Combined", view, "RGBA");
if (view_layer->passflag & SCE_PASS_Z) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 1, RE_PASSNAME_Z, view, "Z");
}
if (view_layer->passflag & SCE_PASS_VECTOR) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 4, RE_PASSNAME_VECTOR, view, "XYZW");
}
if (view_layer->passflag & SCE_PASS_NORMAL) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_NORMAL, view, "XYZ");
}
if (view_layer->passflag & SCE_PASS_UV) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_UV, view, "UVA");
}
if (view_layer->passflag & SCE_PASS_EMIT) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_EMIT, view, "RGB");
}
if (view_layer->passflag & SCE_PASS_AO) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_AO, view, "RGB");
}
if (view_layer->passflag & SCE_PASS_ENVIRONMENT) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_ENVIRONMENT, view, "RGB");
}
if (view_layer->passflag & SCE_PASS_SHADOW) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_SHADOW, view, "RGB");
}
if (view_layer->passflag & SCE_PASS_INDEXOB) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 1, RE_PASSNAME_INDEXOB, view, "X");
}
if (view_layer->passflag & SCE_PASS_INDEXMA) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 1, RE_PASSNAME_INDEXMA, view, "X");
}
if (view_layer->passflag & SCE_PASS_MIST) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 1, RE_PASSNAME_MIST, view, "Z");
}
if (rl->passflag & SCE_PASS_RAYHITS) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 4, RE_PASSNAME_RAYHITS, view, "RGB");
}
if (view_layer->passflag & SCE_PASS_DIFFUSE_DIRECT) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_DIFFUSE_DIRECT, view, "RGB");
}
if (view_layer->passflag & SCE_PASS_DIFFUSE_INDIRECT) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_DIFFUSE_INDIRECT, view, "RGB");
}
if (view_layer->passflag & SCE_PASS_DIFFUSE_COLOR) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_DIFFUSE_COLOR, view, "RGB");
}
if (view_layer->passflag & SCE_PASS_GLOSSY_DIRECT) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_GLOSSY_DIRECT, view, "RGB");
}
if (view_layer->passflag & SCE_PASS_GLOSSY_INDIRECT) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_GLOSSY_INDIRECT, view, "RGB");
}
if (view_layer->passflag & SCE_PASS_GLOSSY_COLOR) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_GLOSSY_COLOR, view, "RGB");
}
if (view_layer->passflag & SCE_PASS_TRANSM_DIRECT) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_TRANSM_DIRECT, view, "RGB");
}
if (view_layer->passflag & SCE_PASS_TRANSM_INDIRECT) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_TRANSM_INDIRECT, view, "RGB");
}
if (view_layer->passflag & SCE_PASS_TRANSM_COLOR) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_TRANSM_COLOR, view, "RGB");
}
if (view_layer->passflag & SCE_PASS_SUBSURFACE_DIRECT) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_SUBSURFACE_DIRECT, view, "RGB");
}
if (view_layer->passflag & SCE_PASS_SUBSURFACE_INDIRECT) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_SUBSURFACE_INDIRECT, view, "RGB");
}
if (view_layer->passflag & SCE_PASS_SUBSURFACE_COLOR) {
RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_SUBSURFACE_COLOR, view, "RGB");
}
#undef RENDER_LAYER_ADD_PASS_SAFE
}
}
FOREACH_VIEW_LAYER_TO_RENDER_END;
/* previewrender doesn't do layers, so we make a default one */
if (BLI_listbase_is_empty(&rr->layers) && !(layername && layername[0])) {
rl = MEM_callocN(sizeof(RenderLayer), "new render layer");
BLI_addtail(&rr->layers, rl);
rl->rectx = rectx;
rl->recty = recty;
/* duplicate code... */
if (rr->do_exr_tile) {
rl->exrhandle = IMB_exr_get_handle();
}
for (rv = rr->views.first; rv; rv = rv->next) {
const char *view = rv->name;
if (viewname && viewname[0]) {
if (strcmp(view, viewname) != 0) {
continue;
}
}
if (rr->do_exr_tile) {
IMB_exr_add_view(rl->exrhandle, view);
}
/* a renderlayer should always have a Combined pass */
render_layer_add_pass(rr, rl, 4, RE_PASSNAME_COMBINED, view, "RGBA");
}
/* note, this has to be in sync with scene.c */
rl->layflag = 0x7FFF; /* solid ztra halo strand */
rl->passflag = SCE_PASS_COMBINED;
re->active_view_layer = 0;
}
/* border render; calculate offset for use in compositor. compo is centralized coords */
/* XXX obsolete? I now use it for drawing border render offset (ton) */
rr->xof = re->disprect.xmin + BLI_rcti_cent_x(&re->disprect) - (re->winx / 2);
rr->yof = re->disprect.ymin + BLI_rcti_cent_y(&re->disprect) - (re->winy / 2);
return rr;
}
void render_result_clone_passes(Render *re, RenderResult *rr, const char *viewname)
{
RenderLayer *rl;
RenderPass *main_rp;
for (rl = rr->layers.first; rl; rl = rl->next) {
RenderLayer *main_rl = BLI_findstring(
&re->result->layers, rl->name, offsetof(RenderLayer, name));
if (!main_rl) {
continue;
}
for (main_rp = main_rl->passes.first; main_rp; main_rp = main_rp->next) {
if (viewname && viewname[0] && !STREQ(main_rp->view, viewname)) {
continue;
}
/* Compare fullname to make sure that the view also is equal. */
RenderPass *rp = BLI_findstring(
&rl->passes, main_rp->fullname, offsetof(RenderPass, fullname));
if (!rp) {
render_layer_add_pass(
rr, rl, main_rp->channels, main_rp->name, main_rp->view, main_rp->chan_id);
}
}
}
}
void render_result_add_pass(RenderResult *rr,
const char *name,
int channels,
const char *chan_id,
const char *layername,
const char *viewname)
{
RenderLayer *rl;
RenderPass *rp;
RenderView *rv;
for (rl = rr->layers.first; rl; rl = rl->next) {
if (layername && layername[0] && !STREQ(rl->name, layername)) {
continue;
}
for (rv = rr->views.first; rv; rv = rv->next) {
const char *view = rv->name;
if (viewname && viewname[0] && !STREQ(view, viewname)) {
continue;
}
/* Ensure that the pass doesn't exist yet. */
for (rp = rl->passes.first; rp; rp = rp->next) {
if (!STREQ(rp->name, name)) {
continue;
}
if (!STREQ(rp->view, view)) {
continue;
}
break;
}
if (!rp) {
render_layer_add_pass(rr, rl, channels, name, view, chan_id);
}
}
}
}
static int passtype_from_name(const char *name)
{
const char delim[] = {'.', '\0'};
const char *sep, *suf;
int len = BLI_str_partition(name, delim, &sep, &suf);
#define CHECK_PASS(NAME) \
if (STREQLEN(name, RE_PASSNAME_##NAME, len)) \
return SCE_PASS_##NAME
CHECK_PASS(COMBINED);
CHECK_PASS(Z);
CHECK_PASS(VECTOR);
CHECK_PASS(NORMAL);
CHECK_PASS(UV);
CHECK_PASS(EMIT);
CHECK_PASS(SHADOW);
CHECK_PASS(AO);
CHECK_PASS(ENVIRONMENT);
CHECK_PASS(INDEXOB);
CHECK_PASS(INDEXMA);
CHECK_PASS(MIST);
CHECK_PASS(RAYHITS);
CHECK_PASS(DIFFUSE_DIRECT);
CHECK_PASS(DIFFUSE_INDIRECT);
CHECK_PASS(DIFFUSE_COLOR);
CHECK_PASS(GLOSSY_DIRECT);
CHECK_PASS(GLOSSY_INDIRECT);
CHECK_PASS(GLOSSY_COLOR);
CHECK_PASS(TRANSM_DIRECT);
CHECK_PASS(TRANSM_INDIRECT);
CHECK_PASS(TRANSM_COLOR);
CHECK_PASS(SUBSURFACE_DIRECT);
CHECK_PASS(SUBSURFACE_INDIRECT);
CHECK_PASS(SUBSURFACE_COLOR);
#undef CHECK_PASS
return 0;
}
/* callbacks for render_result_new_from_exr */
static void *ml_addlayer_cb(void *base, const char *str)
{
RenderResult *rr = base;
RenderLayer *rl;
rl = MEM_callocN(sizeof(RenderLayer), "new render layer");
BLI_addtail(&rr->layers, rl);
BLI_strncpy(rl->name, str, EXR_LAY_MAXNAME);
return rl;
}
static void ml_addpass_cb(void *base,
void *lay,
const char *name,
float *rect,
int totchan,
const char *chan_id,
const char *view)
{
RenderResult *rr = base;
RenderLayer *rl = lay;
RenderPass *rpass = MEM_callocN(sizeof(RenderPass), "loaded pass");
BLI_addtail(&rl->passes, rpass);
rpass->channels = totchan;
rl->passflag |= passtype_from_name(name);
/* channel id chars */
BLI_strncpy(rpass->chan_id, chan_id, sizeof(rpass->chan_id));
rpass->rect = rect;
BLI_strncpy(rpass->name, name, EXR_PASS_MAXNAME);
BLI_strncpy(rpass->view, view, sizeof(rpass->view));
set_pass_full_name(rpass->fullname, name, -1, view, rpass->chan_id);
if (view[0] != '\0') {
rpass->view_id = BLI_findstringindex(&rr->views, view, offsetof(RenderView, name));
}
else {
rpass->view_id = 0;
}
}
static void *ml_addview_cb(void *base, const char *str)
{
RenderResult *rr = base;
RenderView *rv;
rv = MEM_callocN(sizeof(RenderView), "new render view");
BLI_strncpy(rv->name, str, EXR_VIEW_MAXNAME);
/* For stereo drawing we need to ensure:
* STEREO_LEFT_NAME == STEREO_LEFT_ID and
* STEREO_RIGHT_NAME == STEREO_RIGHT_ID */
if (STREQ(str, STEREO_LEFT_NAME)) {
BLI_addhead(&rr->views, rv);
}
else if (STREQ(str, STEREO_RIGHT_NAME)) {
RenderView *left_rv = BLI_findstring(&rr->views, STEREO_LEFT_NAME, offsetof(RenderView, name));
if (left_rv == NULL) {
BLI_addhead(&rr->views, rv);
}
else {
BLI_insertlinkafter(&rr->views, left_rv, rv);
}
}
else {
BLI_addtail(&rr->views, rv);
}
return rv;
}
static int order_render_passes(const void *a, const void *b)
{
// 1 if a is after b
RenderPass *rpa = (RenderPass *)a;
RenderPass *rpb = (RenderPass *)b;
unsigned int passtype_a = passtype_from_name(rpa->name);
unsigned int passtype_b = passtype_from_name(rpb->name);
/* Render passes with default type always go first. */
if (passtype_b && !passtype_a) {
return 1;
}
if (passtype_a && !passtype_b) {
return 0;
}
if (passtype_a && passtype_b) {
if (passtype_a > passtype_b) {
return 1;
}
else if (passtype_a < passtype_b) {
return 0;
}
}
else {
int cmp = strncmp(rpa->name, rpb->name, EXR_PASS_MAXNAME);
if (cmp > 0) {
return 1;
}
if (cmp < 0) {
return 0;
}
}
/* they have the same type */
/* left first */
if (STREQ(rpa->view, STEREO_LEFT_NAME)) {
return 0;
}
else if (STREQ(rpb->view, STEREO_LEFT_NAME)) {
return 1;
}
/* right second */
if (STREQ(rpa->view, STEREO_RIGHT_NAME)) {
return 0;
}
else if (STREQ(rpb->view, STEREO_RIGHT_NAME)) {
return 1;
}
/* remaining in ascending id order */
return (rpa->view_id < rpb->view_id);
}
/* From imbuf, if a handle was returned and
* it's not a singlelayer multiview we convert this to render result. */
RenderResult *render_result_new_from_exr(
void *exrhandle, const char *colorspace, bool predivide, int rectx, int recty)
{
RenderResult *rr = MEM_callocN(sizeof(RenderResult), __func__);
RenderLayer *rl;
RenderPass *rpass;
const char *to_colorspace = IMB_colormanagement_role_colorspace_name_get(
COLOR_ROLE_SCENE_LINEAR);
rr->rectx = rectx;
rr->recty = recty;
IMB_exr_multilayer_convert(exrhandle, rr, ml_addview_cb, ml_addlayer_cb, ml_addpass_cb);
for (rl = rr->layers.first; rl; rl = rl->next) {
rl->rectx = rectx;
rl->recty = recty;
BLI_listbase_sort(&rl->passes, order_render_passes);
for (rpass = rl->passes.first; rpass; rpass = rpass->next) {
rpass->rectx = rectx;
rpass->recty = recty;
if (rpass->channels >= 3) {
IMB_colormanagement_transform(rpass->rect,
rpass->rectx,
rpass->recty,
rpass->channels,
colorspace,
to_colorspace,
predivide);
}
}
}
return rr;
}
void render_result_view_new(RenderResult *rr, const char *viewname)
{
RenderView *rv = MEM_callocN(sizeof(RenderView), "new render view");
BLI_addtail(&rr->views, rv);
BLI_strncpy(rv->name, viewname, sizeof(rv->name));
}
void render_result_views_new(RenderResult *rr, RenderData *rd)
{
SceneRenderView *srv;
/* clear previously existing views - for sequencer */
render_result_views_free(rr);
/* check renderdata for amount of views */
if ((rd->scemode & R_MULTIVIEW)) {
for (srv = rd->views.first; srv; srv = srv->next) {
if (BKE_scene_multiview_is_render_view_active(rd, srv) == false) {
continue;
}
render_result_view_new(rr, srv->name);
}
}
/* we always need at least one view */
if (BLI_listbase_count_at_most(&rr->views, 1) == 0) {
render_result_view_new(rr, "");
}
}
bool render_result_has_views(RenderResult *rr)
{
RenderView *rv = rr->views.first;
return (rv && (rv->next || rv->name[0]));
}
/*********************************** Merge ***********************************/
static void do_merge_tile(
RenderResult *rr, RenderResult *rrpart, float *target, float *tile, int pixsize)
{
int y, tilex, tiley;
size_t ofs, copylen;
copylen = tilex = rrpart->rectx;
tiley = rrpart->recty;
if (rrpart->crop) { /* filters add pixel extra */
tile += pixsize * (rrpart->crop + ((size_t)rrpart->crop) * tilex);
copylen = tilex - 2 * rrpart->crop;
tiley -= 2 * rrpart->crop;
ofs = (((size_t)rrpart->tilerect.ymin) + rrpart->crop) * rr->rectx +
(rrpart->tilerect.xmin + rrpart->crop);
target += pixsize * ofs;
}
else {
ofs = (((size_t)rrpart->tilerect.ymin) * rr->rectx + rrpart->tilerect.xmin);
target += pixsize * ofs;
}
copylen *= sizeof(float) * pixsize;
tilex *= pixsize;
ofs = pixsize * rr->rectx;
for (y = 0; y < tiley; y++) {
memcpy(target, tile, copylen);
target += ofs;
tile += tilex;
}
}
/* used when rendering to a full buffer, or when reading the exr part-layer-pass file */
/* no test happens here if it fits... we also assume layers are in sync */
/* is used within threads */
void render_result_merge(RenderResult *rr, RenderResult *rrpart)
{
RenderLayer *rl, *rlp;
RenderPass *rpass, *rpassp;
for (rl = rr->layers.first; rl; rl = rl->next) {
rlp = RE_GetRenderLayer(rrpart, rl->name);
if (rlp) {
/* Passes are allocated in sync. */
for (rpass = rl->passes.first, rpassp = rlp->passes.first; rpass && rpassp;
rpass = rpass->next) {
/* For save buffers, skip any passes that are only saved to disk. */
if (rpass->rect == NULL || rpassp->rect == NULL) {
continue;
}
/* Renderresult have all passes, renderpart only the active view's passes. */
if (strcmp(rpassp->fullname, rpass->fullname) != 0) {
continue;
}
do_merge_tile(rr, rrpart, rpass->rect, rpassp->rect, rpass->channels);
/* manually get next render pass */
rpassp = rpassp->next;
}
}
}
}
/* Called from the UI and render pipeline, to save multilayer and multiview
* images, optionally isolating a specific, view, layer or RGBA/Z pass. */
bool RE_WriteRenderResult(ReportList *reports,
RenderResult *rr,
const char *filename,
ImageFormatData *imf,
const char *view,
int layer)
{
void *exrhandle = IMB_exr_get_handle();
const bool half_float = (imf && imf->depth == R_IMF_CHAN_DEPTH_16);
const bool multi_layer = !(imf && imf->imtype == R_IMF_IMTYPE_OPENEXR);
const bool write_z = !multi_layer && (imf && (imf->flag & R_IMF_FLAG_ZBUF));
/* Write first layer if not multilayer and no layer was specified. */
if (!multi_layer && layer == -1) {
layer = 0;
}
/* First add views since IMB_exr_add_channel checks number of views. */
if (render_result_has_views(rr)) {
for (RenderView *rview = rr->views.first; rview; rview = rview->next) {
if (!view || STREQ(view, rview->name)) {
IMB_exr_add_view(exrhandle, rview->name);
}
}
}
/* Compositing result. */
if (rr->have_combined) {
for (RenderView *rview = rr->views.first; rview; rview = rview->next) {
if (!rview->rectf) {
continue;
}
const char *viewname = rview->name;
if (view) {
if (!STREQ(view, viewname)) {
continue;
}
else {
viewname = "";
}
}
/* Skip compositing if only a single other layer is requested. */
if (!multi_layer && layer != 0) {
continue;
}
for (int a = 0; a < 4; a++) {
char passname[EXR_PASS_MAXNAME];
char layname[EXR_PASS_MAXNAME];
const char *chan_id = "RGBA";
if (multi_layer) {
set_pass_name(passname, "Combined", a, chan_id);
BLI_strncpy(layname, "Composite", sizeof(layname));
}
else {
passname[0] = chan_id[a];
passname[1] = '\0';
layname[0] = '\0';
}
IMB_exr_add_channel(exrhandle,
layname,
passname,
viewname,
4,
4 * rr->rectx,
rview->rectf + a,
half_float);
}
if (write_z && rview->rectz) {
const char *layname = (multi_layer) ? "Composite" : "";
IMB_exr_add_channel(exrhandle, layname, "Z", viewname, 1, rr->rectx, rview->rectz, false);
}
}
}
/* Other render layers. */
int nr = (rr->have_combined) ? 1 : 0;
for (RenderLayer *rl = rr->layers.first; rl; rl = rl->next, nr++) {
/* Skip other render layers if requested. */
if (!multi_layer && nr != layer) {
continue;
}
for (RenderPass *rp = rl->passes.first; rp; rp = rp->next) {
/* Skip non-RGBA and Z passes if not using multi layer. */
if (!multi_layer && !(STREQ(rp->name, RE_PASSNAME_COMBINED) || STREQ(rp->name, "") ||
(STREQ(rp->name, RE_PASSNAME_Z) && write_z))) {
continue;
}
/* Skip pass if it does not match the requested view(s). */
const char *viewname = rp->view;
if (view) {
if (!STREQ(view, viewname)) {
continue;
}
else {
viewname = "";
}
}
/* We only store RGBA passes as half float, for
* others precision loss can be problematic. */
bool pass_half_float = half_float &&
(STREQ(rp->chan_id, "RGB") || STREQ(rp->chan_id, "RGBA") ||
STREQ(rp->chan_id, "R") || STREQ(rp->chan_id, "G") ||
STREQ(rp->chan_id, "B") || STREQ(rp->chan_id, "A"));
for (int a = 0; a < rp->channels; a++) {
/* Save Combined as RGBA if single layer save. */
char passname[EXR_PASS_MAXNAME];
char layname[EXR_PASS_MAXNAME];
if (multi_layer) {
set_pass_name(passname, rp->name, a, rp->chan_id);
BLI_strncpy(layname, rl->name, sizeof(layname));
}
else {
passname[0] = rp->chan_id[a];
passname[1] = '\0';
layname[0] = '\0';
}
IMB_exr_add_channel(exrhandle,
layname,
passname,
viewname,
rp->channels,
rp->channels * rr->rectx,
rp->rect + a,
pass_half_float);
}
}
}
errno = 0;
BLI_make_existing_file(filename);
int compress = (imf ? imf->exr_codec : 0);
bool success = IMB_exr_begin_write(
exrhandle, filename, rr->rectx, rr->recty, compress, rr->stamp_data);
if (success) {
IMB_exr_write_channels(exrhandle);
}
else {
/* TODO, get the error from openexr's exception */
BKE_reportf(
reports, RPT_ERROR, "Error writing render result, %s (see console)", strerror(errno));
}
IMB_exr_close(exrhandle);
return success;
}
/**************************** Single Layer Rendering *************************/
void render_result_single_layer_begin(Render *re)
{
/* all layers except the active one get temporally pushed away */
/* officially pushed result should be NULL... error can happen with do_seq */
RE_FreeRenderResult(re->pushedresult);
re->pushedresult = re->result;
re->result = NULL;
}
/* if scemode is R_SINGLE_LAYER, at end of rendering, merge the both render results */
void render_result_single_layer_end(Render *re)
{
ViewLayer *view_layer;
RenderLayer *rlpush;
RenderLayer *rl;
int nr;
if (re->result == NULL) {
printf("pop render result error; no current result!\n");
return;
}
if (!re->pushedresult) {
return;
}
if (re->pushedresult->rectx == re->result->rectx &&
re->pushedresult->recty == re->result->recty) {
/* find which layer in re->pushedresult should be replaced */
rl = re->result->layers.first;
/* render result should be empty after this */
BLI_remlink(&re->result->layers, rl);
/* reconstruct render result layers */
for (nr = 0, view_layer = re->view_layers.first; view_layer;
view_layer = view_layer->next, nr++) {
if (nr == re->active_view_layer) {
BLI_addtail(&re->result->layers, rl);
}
else {
rlpush = RE_GetRenderLayer(re->pushedresult, view_layer->name);
if (rlpush) {
BLI_remlink(&re->pushedresult->layers, rlpush);
BLI_addtail(&re->result->layers, rlpush);
}
}
}
}
RE_FreeRenderResult(re->pushedresult);
re->pushedresult = NULL;
}
/************************* EXR Tile File Rendering ***************************/
static void save_render_result_tile(RenderResult *rr, RenderResult *rrpart, const char *viewname)
{
RenderLayer *rlp, *rl;
RenderPass *rpassp;
int offs, partx, party;
BLI_thread_lock(LOCK_IMAGE);
for (rlp = rrpart->layers.first; rlp; rlp = rlp->next) {
rl = RE_GetRenderLayer(rr, rlp->name);
/* should never happen but prevents crash if it does */
BLI_assert(rl);
if (UNLIKELY(rl == NULL)) {
continue;
}
if (rrpart->crop) { /* filters add pixel extra */
offs = (rrpart->crop + rrpart->crop * rrpart->rectx);
}
else {
offs = 0;
}
/* passes are allocated in sync */
for (rpassp = rlp->passes.first; rpassp; rpassp = rpassp->next) {
const int xstride = rpassp->channels;
int a;
char fullname[EXR_PASS_MAXNAME];
for (a = 0; a < xstride; a++) {
set_pass_full_name(fullname, rpassp->name, a, viewname, rpassp->chan_id);
IMB_exr_set_channel(rl->exrhandle,
rlp->name,
fullname,
xstride,
xstride * rrpart->rectx,
rpassp->rect + a + xstride * offs);
}
}
}
party = rrpart->tilerect.ymin + rrpart->crop;
partx = rrpart->tilerect.xmin + rrpart->crop;
for (rlp = rrpart->layers.first; rlp; rlp = rlp->next) {
rl = RE_GetRenderLayer(rr, rlp->name);
/* should never happen but prevents crash if it does */
BLI_assert(rl);
if (UNLIKELY(rl == NULL)) {
continue;
}
IMB_exrtile_write_channels(rl->exrhandle, partx, party, 0, viewname, false);
}
BLI_thread_unlock(LOCK_IMAGE);
}
void render_result_save_empty_result_tiles(Render *re)
{
RenderResult *rr;
RenderLayer *rl;
for (rr = re->result; rr; rr = rr->next) {
for (rl = rr->layers.first; rl; rl = rl->next) {
GHashIterator pa_iter;
GHASH_ITER (pa_iter, re->parts) {
RenderPart *pa = BLI_ghashIterator_getValue(&pa_iter);
if (pa->status != PART_STATUS_MERGED) {
int party = pa->disprect.ymin - re->disprect.ymin;
int partx = pa->disprect.xmin - re->disprect.xmin;
IMB_exrtile_write_channels(rl->exrhandle, partx, party, 0, re->viewname, true);
}
}
}
}
}
/* Compute list of passes needed by render engine. */
static void templates_register_pass_cb(void *userdata,
Scene *UNUSED(scene),
ViewLayer *UNUSED(view_layer),
const char *name,
int channels,
const char *chan_id,
int UNUSED(type))
{
ListBase *templates = userdata;
RenderPass *pass = MEM_callocN(sizeof(RenderPass), "RenderPassTemplate");
pass->channels = channels;
BLI_strncpy(pass->name, name, sizeof(pass->name));
BLI_strncpy(pass->chan_id, chan_id, sizeof(pass->chan_id));
BLI_addtail(templates, pass);
}
static void render_result_get_pass_templates(RenderEngine *engine,
Render *re,
RenderLayer *rl,
ListBase *templates)
{
BLI_listbase_clear(templates);
if (engine && engine->type->update_render_passes) {
ViewLayer *view_layer = BLI_findstring(&re->view_layers, rl->name, offsetof(ViewLayer, name));
if (view_layer) {
RE_engine_update_render_passes(
engine, re->scene, view_layer, templates_register_pass_cb, templates);
}
}
}
/* begin write of exr tile file */
void render_result_exr_file_begin(Render *re, RenderEngine *engine)
{
char str[FILE_MAX];
for (RenderResult *rr = re->result; rr; rr = rr->next) {
for (RenderLayer *rl = rr->layers.first; rl; rl = rl->next) {
/* Get passes needed by engine. Normally we would wait for the
* engine to create them, but for EXR file we need to know in
* advance. */
ListBase templates;
render_result_get_pass_templates(engine, re, rl, &templates);
/* Create render passes requested by engine. Only this part is
* mutex locked to avoid deadlock with Python GIL. */
BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
for (RenderPass *pass = templates.first; pass; pass = pass->next) {
render_result_add_pass(
re->result, pass->name, pass->channels, pass->chan_id, rl->name, NULL);
}
BLI_rw_mutex_unlock(&re->resultmutex);
BLI_freelistN(&templates);
/* Open EXR file for writing. */
render_result_exr_file_path(re->scene, rl->name, rr->sample_nr, str);
printf("write exr tmp file, %dx%d, %s\n", rr->rectx, rr->recty, str);
IMB_exrtile_begin_write(rl->exrhandle, str, 0, rr->rectx, rr->recty, re->partx, re->party);
}
}
}
/* end write of exr tile file, read back first sample */
void render_result_exr_file_end(Render *re, RenderEngine *engine)
{
/* Close EXR files. */
for (RenderResult *rr = re->result; rr; rr = rr->next) {
for (RenderLayer *rl = rr->layers.first; rl; rl = rl->next) {
IMB_exr_close(rl->exrhandle);
rl->exrhandle = NULL;
}
rr->do_exr_tile = false;
}
/* Create new render result in memory instead of on disk. */
BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
render_result_free_list(&re->fullresult, re->result);
re->result = render_result_new(re, &re->disprect, 0, RR_USE_MEM, RR_ALL_LAYERS, RR_ALL_VIEWS);
BLI_rw_mutex_unlock(&re->resultmutex);
for (RenderLayer *rl = re->result->layers.first; rl; rl = rl->next) {
/* Get passes needed by engine. */
ListBase templates;
render_result_get_pass_templates(engine, re, rl, &templates);
/* Create render passes requested by engine. Only this part is
* mutex locked to avoid deadlock with Python GIL. */
BLI_rw_mutex_lock(&re->resultmutex, THREAD_LOCK_WRITE);
for (RenderPass *pass = templates.first; pass; pass = pass->next) {
render_result_add_pass(
re->result, pass->name, pass->channels, pass->chan_id, rl->name, NULL);
}
BLI_freelistN(&templates);
/* Render passes contents from file. */
char str[FILE_MAXFILE + MAX_ID_NAME + MAX_ID_NAME + 100] = "";
render_result_exr_file_path(re->scene, rl->name, 0, str);
printf("read exr tmp file: %s\n", str);
if (!render_result_exr_file_read_path(re->result, rl, str)) {
printf("cannot read: %s\n", str);
}
BLI_rw_mutex_unlock(&re->resultmutex);
}
}
/* save part into exr file */
void render_result_exr_file_merge(RenderResult *rr, RenderResult *rrpart, const char *viewname)
{
for (; rr && rrpart; rr = rr->next, rrpart = rrpart->next) {
save_render_result_tile(rr, rrpart, viewname);
}
}
/* path to temporary exr file */
void render_result_exr_file_path(Scene *scene, const char *layname, int sample, char *filepath)
{
char name[FILE_MAXFILE + MAX_ID_NAME + MAX_ID_NAME + 100];
const char *fi = BLI_path_basename(BKE_main_blendfile_path_from_global());
if (sample == 0) {
BLI_snprintf(name, sizeof(name), "%s_%s_%s.exr", fi, scene->id.name + 2, layname);
}
else {
BLI_snprintf(name, sizeof(name), "%s_%s_%s%d.exr", fi, scene->id.name + 2, layname, sample);
}
/* Make name safe for paths, see T43275. */
BLI_filename_make_safe(name);
BLI_make_file_string("/", filepath, BKE_tempdir_session(), name);
}
/* called for reading temp files, and for external engines */
int render_result_exr_file_read_path(RenderResult *rr,
RenderLayer *rl_single,
const char *filepath)
{
RenderLayer *rl;
RenderPass *rpass;
void *exrhandle = IMB_exr_get_handle();
int rectx, recty;
if (IMB_exr_begin_read(exrhandle, filepath, &rectx, &recty) == 0) {
printf("failed being read %s\n", filepath);
IMB_exr_close(exrhandle);
return 0;
}
if (rr == NULL || rectx != rr->rectx || recty != rr->recty) {
if (rr) {
printf("error in reading render result: dimensions don't match\n");
}
else {
printf("error in reading render result: NULL result pointer\n");
}
IMB_exr_close(exrhandle);
return 0;
}
for (rl = rr->layers.first; rl; rl = rl->next) {
if (rl_single && rl_single != rl) {
continue;
}
/* passes are allocated in sync */
for (rpass = rl->passes.first; rpass; rpass = rpass->next) {
const int xstride = rpass->channels;
int a;
char fullname[EXR_PASS_MAXNAME];
for (a = 0; a < xstride; a++) {
set_pass_full_name(fullname, rpass->name, a, rpass->view, rpass->chan_id);
IMB_exr_set_channel(
exrhandle, rl->name, fullname, xstride, xstride * rectx, rpass->rect + a);
}
set_pass_full_name(rpass->fullname, rpass->name, -1, rpass->view, rpass->chan_id);
}
}
IMB_exr_read_channels(exrhandle);
IMB_exr_close(exrhandle);
return 1;
}
static void render_result_exr_file_cache_path(Scene *sce, const char *root, char *r_path)
{
char filename_full[FILE_MAX + MAX_ID_NAME + 100], filename[FILE_MAXFILE], dirname[FILE_MAXDIR];
char path_digest[16] = {0};
char path_hexdigest[33];
/* If root is relative, use either current .blend file dir, or temp one if not saved. */
const char *blendfile_path = BKE_main_blendfile_path_from_global();
if (blendfile_path[0] != '\0') {
BLI_split_dirfile(blendfile_path, dirname, filename, sizeof(dirname), sizeof(filename));
BLI_path_extension_replace(filename, sizeof(filename), ""); /* strip '.blend' */
BLI_hash_md5_buffer(blendfile_path, strlen(blendfile_path), path_digest);
}
else {
BLI_strncpy(dirname, BKE_tempdir_base(), sizeof(dirname));
BLI_strncpy(filename, "UNSAVED", sizeof(filename));
}
BLI_hash_md5_to_hexdigest(path_digest, path_hexdigest);
/* Default to *non-volatile* tmp dir. */
if (*root == '\0') {
root = BKE_tempdir_base();
}
BLI_snprintf(filename_full,
sizeof(filename_full),
"cached_RR_%s_%s_%s.exr",
filename,
sce->id.name + 2,
path_hexdigest);
BLI_make_file_string(dirname, r_path, root, filename_full);
}
void render_result_exr_file_cache_write(Render *re)
{
RenderResult *rr = re->result;
char str[FILE_MAXFILE + FILE_MAXFILE + MAX_ID_NAME + 100];
char *root = U.render_cachedir;
render_result_exr_file_cache_path(re->scene, root, str);
printf("Caching exr file, %dx%d, %s\n", rr->rectx, rr->recty, str);
RE_WriteRenderResult(NULL, rr, str, NULL, NULL, -1);
}
/* For cache, makes exact copy of render result */
bool render_result_exr_file_cache_read(Render *re)
{
char str[FILE_MAXFILE + MAX_ID_NAME + MAX_ID_NAME + 100] = "";
char *root = U.render_cachedir;
RE_FreeRenderResult(re->result);
re->result = render_result_new(re, &re->disprect, 0, RR_USE_MEM, RR_ALL_LAYERS, RR_ALL_VIEWS);
/* First try cache. */
render_result_exr_file_cache_path(re->scene, root, str);
printf("read exr cache file: %s\n", str);
if (!render_result_exr_file_read_path(re->result, NULL, str)) {
printf("cannot read: %s\n", str);
return false;
}
return true;
}
/*************************** Combined Pixel Rect *****************************/
ImBuf *render_result_rect_to_ibuf(RenderResult *rr, RenderData *rd, const int view_id)
{
ImBuf *ibuf = IMB_allocImBuf(rr->rectx, rr->recty, rd->im_format.planes, 0);
RenderView *rv = RE_RenderViewGetById(rr, view_id);
/* if not exists, BKE_imbuf_write makes one */
ibuf->rect = (unsigned int *)rv->rect32;
ibuf->rect_float = rv->rectf;
ibuf->zbuf_float = rv->rectz;
/* float factor for random dither, imbuf takes care of it */
ibuf->dither = rd->dither_intensity;
/* prepare to gamma correct to sRGB color space
* note that sequence editor can generate 8bpc render buffers
*/
if (ibuf->rect) {
if (BKE_imtype_valid_depths(rd->im_format.imtype) &
(R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16 | R_IMF_CHAN_DEPTH_24 | R_IMF_CHAN_DEPTH_32)) {
if (rd->im_format.depth == R_IMF_CHAN_DEPTH_8) {
/* Higher depth bits are supported but not needed for current file output. */
ibuf->rect_float = NULL;
}
else {
IMB_float_from_rect(ibuf);
}
}
else {
/* ensure no float buffer remained from previous frame */
ibuf->rect_float = NULL;
}
}
/* color -> grayscale */
/* editing directly would alter the render view */
if (rd->im_format.planes == R_IMF_PLANES_BW) {
ImBuf *ibuf_bw = IMB_dupImBuf(ibuf);
IMB_color_to_bw(ibuf_bw);
IMB_freeImBuf(ibuf);
ibuf = ibuf_bw;
}
return ibuf;
}
void RE_render_result_rect_from_ibuf(RenderResult *rr,
RenderData *UNUSED(rd),
ImBuf *ibuf,
const int view_id)
{
RenderView *rv = RE_RenderViewGetById(rr, view_id);
if (ibuf->rect_float) {
rr->have_combined = true;
if (!rv->rectf) {
rv->rectf = MEM_mallocN(4 * sizeof(float) * rr->rectx * rr->recty, "render_seq rectf");
}
memcpy(rv->rectf, ibuf->rect_float, 4 * sizeof(float) * rr->rectx * rr->recty);
/* TSK! Since sequence render doesn't free the *rr render result, the old rect32
* can hang around when sequence render has rendered a 32 bits one before */
MEM_SAFE_FREE(rv->rect32);
}
else if (ibuf->rect) {
rr->have_combined = true;
if (!rv->rect32) {
rv->rect32 = MEM_mallocN(sizeof(int) * rr->rectx * rr->recty, "render_seq rect");
}
memcpy(rv->rect32, ibuf->rect, 4 * rr->rectx * rr->recty);
/* Same things as above, old rectf can hang around from previous render. */
MEM_SAFE_FREE(rv->rectf);
}
}
void render_result_rect_fill_zero(RenderResult *rr, const int view_id)
{
RenderView *rv = RE_RenderViewGetById(rr, view_id);
if (rv->rectf) {
memset(rv->rectf, 0, 4 * sizeof(float) * rr->rectx * rr->recty);
}
else if (rv->rect32) {
memset(rv->rect32, 0, 4 * rr->rectx * rr->recty);
}
else {
rv->rect32 = MEM_callocN(sizeof(int) * rr->rectx * rr->recty, "render_seq rect");
}
}
void render_result_rect_get_pixels(RenderResult *rr,
unsigned int *rect,
int rectx,
int recty,
const ColorManagedViewSettings *view_settings,
const ColorManagedDisplaySettings *display_settings,
const int view_id)
{
RenderView *rv = RE_RenderViewGetById(rr, view_id);
if (rv->rect32) {
memcpy(rect, rv->rect32, sizeof(int) * rr->rectx * rr->recty);
}
else if (rv->rectf) {
IMB_display_buffer_transform_apply((unsigned char *)rect,
rv->rectf,
rr->rectx,
rr->recty,
4,
view_settings,
display_settings,
true);
}
else {
/* else fill with black */
memset(rect, 0, sizeof(int) * rectx * recty);
}
}
/*************************** multiview functions *****************************/
bool RE_HasCombinedLayer(RenderResult *res)
{
RenderView *rv;
if (res == NULL) {
return false;
}
rv = res->views.first;
if (rv == NULL) {
return false;
}
return (rv->rect32 || rv->rectf);
}
bool RE_HasFloatPixels(RenderResult *res)
{
RenderView *rview;
for (rview = res->views.first; rview; rview = rview->next) {
if (rview->rect32 && !rview->rectf) {
return false;
}
}
return true;
}
bool RE_RenderResult_is_stereo(RenderResult *res)
{
if (!BLI_findstring(&res->views, STEREO_LEFT_NAME, offsetof(RenderView, name))) {
return false;
}
if (!BLI_findstring(&res->views, STEREO_RIGHT_NAME, offsetof(RenderView, name))) {
return false;
}
return true;
}
RenderView *RE_RenderViewGetById(RenderResult *res, const int view_id)
{
RenderView *rv = BLI_findlink(&res->views, view_id);
BLI_assert(res->views.first);
return rv ? rv : res->views.first;
}
RenderView *RE_RenderViewGetByName(RenderResult *res, const char *viewname)
{
RenderView *rv = BLI_findstring(&res->views, viewname, offsetof(RenderView, name));
BLI_assert(res->views.first);
return rv ? rv : res->views.first;
}
static RenderPass *duplicate_render_pass(RenderPass *rpass)
{
RenderPass *new_rpass = MEM_mallocN(sizeof(RenderPass), "new render pass");
*new_rpass = *rpass;
new_rpass->next = new_rpass->prev = NULL;
if (new_rpass->rect != NULL) {
new_rpass->rect = MEM_dupallocN(new_rpass->rect);
}
return new_rpass;
}
static RenderLayer *duplicate_render_layer(RenderLayer *rl)
{
RenderLayer *new_rl = MEM_mallocN(sizeof(RenderLayer), "new render layer");
*new_rl = *rl;
new_rl->next = new_rl->prev = NULL;
new_rl->passes.first = new_rl->passes.last = NULL;
new_rl->exrhandle = NULL;
for (RenderPass *rpass = rl->passes.first; rpass != NULL; rpass = rpass->next) {
RenderPass *new_rpass = duplicate_render_pass(rpass);
BLI_addtail(&new_rl->passes, new_rpass);
}
return new_rl;
}
static RenderView *duplicate_render_view(RenderView *rview)
{
RenderView *new_rview = MEM_mallocN(sizeof(RenderView), "new render view");
*new_rview = *rview;
if (new_rview->rectf != NULL) {
new_rview->rectf = MEM_dupallocN(new_rview->rectf);
}
if (new_rview->rectz != NULL) {
new_rview->rectz = MEM_dupallocN(new_rview->rectz);
}
if (new_rview->rect32 != NULL) {
new_rview->rect32 = MEM_dupallocN(new_rview->rect32);
}
return new_rview;
}
RenderResult *RE_DuplicateRenderResult(RenderResult *rr)
{
RenderResult *new_rr = MEM_mallocN(sizeof(RenderResult), "new duplicated render result");
*new_rr = *rr;
new_rr->next = new_rr->prev = NULL;
new_rr->layers.first = new_rr->layers.last = NULL;
new_rr->views.first = new_rr->views.last = NULL;
for (RenderLayer *rl = rr->layers.first; rl != NULL; rl = rl->next) {
RenderLayer *new_rl = duplicate_render_layer(rl);
BLI_addtail(&new_rr->layers, new_rl);
}
for (RenderView *rview = rr->views.first; rview != NULL; rview = rview->next) {
RenderView *new_rview = duplicate_render_view(rview);
BLI_addtail(&new_rr->views, new_rview);
}
if (new_rr->rect32 != NULL) {
new_rr->rect32 = MEM_dupallocN(new_rr->rect32);
}
if (new_rr->rectf != NULL) {
new_rr->rectf = MEM_dupallocN(new_rr->rectf);
}
if (new_rr->rectz != NULL) {
new_rr->rectz = MEM_dupallocN(new_rr->rectz);
}
new_rr->stamp_data = BKE_stamp_data_copy(new_rr->stamp_data);
return new_rr;
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef WEBRTC_SYSTEM_WRAPPERS_SOURCE_TRACE_IMPL_H_
#define WEBRTC_SYSTEM_WRAPPERS_SOURCE_TRACE_IMPL_H_
#include <memory>
#include "webrtc/base/criticalsection.h"
#include "webrtc/system_wrappers/include/event_wrapper.h"
#include "webrtc/system_wrappers/include/file_wrapper.h"
#include "webrtc/system_wrappers/include/static_instance.h"
#include "webrtc/base/platform_thread.h"
#include "webrtc/system_wrappers/include/trace.h"
namespace webrtc {
#define WEBRTC_TRACE_MAX_MESSAGE_SIZE 1024
// Total buffer size is WEBRTC_TRACE_NUM_ARRAY (number of buffer partitions) *
// WEBRTC_TRACE_MAX_QUEUE (number of lines per buffer partition) *
// WEBRTC_TRACE_MAX_MESSAGE_SIZE (number of 1 byte charachters per line) =
// 1 or 4 Mbyte.
#define WEBRTC_TRACE_MAX_FILE_SIZE 100*1000
// Number of rows that may be written to file. On average 110 bytes per row (max
// 256 bytes per row). So on average 110*100*1000 = 11 Mbyte, max 256*100*1000 =
// 25.6 Mbyte
class TraceImpl : public Trace {
public:
virtual ~TraceImpl();
static TraceImpl* CreateInstance();
static TraceImpl* GetTrace(const TraceLevel level = kTraceAll);
int32_t SetTraceFileImpl(const char* file_name, const bool add_file_counter);
int32_t SetTraceCallbackImpl(TraceCallback* callback);
void AddImpl(const TraceLevel level, const TraceModule module,
const int32_t id, const char* msg);
bool TraceCheck(const TraceLevel level) const;
protected:
TraceImpl();
static TraceImpl* StaticInstance(CountOperation count_operation,
const TraceLevel level = kTraceAll);
int32_t AddThreadId(char* trace_message) const;
// OS specific implementations.
virtual int32_t AddTime(char* trace_message,
const TraceLevel level) const = 0;
virtual int32_t AddDateTimeInfo(char* trace_message) const = 0;
private:
friend class Trace;
int32_t AddLevel(char* sz_message, const TraceLevel level) const;
int32_t AddModuleAndId(char* trace_message, const TraceModule module,
const int32_t id) const;
int32_t AddMessage(char* trace_message,
const char msg[WEBRTC_TRACE_MAX_MESSAGE_SIZE],
const uint16_t written_so_far) const;
void AddMessageToList(
const char trace_message[WEBRTC_TRACE_MAX_MESSAGE_SIZE],
const uint16_t length,
const TraceLevel level);
bool UpdateFileName(
char file_name_with_counter_utf8[FileWrapper::kMaxFileNameSize],
const uint32_t new_count) const EXCLUSIVE_LOCKS_REQUIRED(crit_);
bool CreateFileName(
const char file_name_utf8[FileWrapper::kMaxFileNameSize],
char file_name_with_counter_utf8[FileWrapper::kMaxFileNameSize],
const uint32_t new_count) const;
void WriteToFile(const char* msg, uint16_t length)
EXCLUSIVE_LOCKS_REQUIRED(crit_);
TraceCallback* callback_ GUARDED_BY(crit_);
uint32_t row_count_text_ GUARDED_BY(crit_);
uint32_t file_count_text_ GUARDED_BY(crit_);
const std::unique_ptr<FileWrapper> trace_file_ GUARDED_BY(crit_);
std::string trace_file_path_ GUARDED_BY(crit_);
rtc::CriticalSection crit_;
};
} // namespace webrtc
#endif // WEBRTC_SYSTEM_WRAPPERS_SOURCE_TRACE_IMPL_H_
|
{
"pile_set_name": "Github"
}
|
// Copyright 2012-2016 Oliver Eilhard. All rights reserved.
// Use of this source code is governed by a MIT-license.
// See http://olivere.mit-license.org/license.txt for details.
// This file is (c) 2014 Cenk Altı and governed by the MIT license.
// See https://github.com/cenkalti/backoff for original source.
package backoff
import "time"
// An Operation is executing by Retry() or RetryNotify().
// The operation will be retried using a backoff policy if it returns an error.
type Operation func() error
// Notify is a notify-on-error function. It receives an operation error and
// backoff delay if the operation failed (with an error).
//
// NOTE that if the backoff policy stated to stop retrying,
// the notify function isn't called.
type Notify func(error, time.Duration)
// Retry the function f until it does not return error or BackOff stops.
// f is guaranteed to be run at least once.
// It is the caller's responsibility to reset b after Retry returns.
//
// Retry sleeps the goroutine for the duration returned by BackOff after a
// failed operation returns.
func Retry(o Operation, b Backoff) error { return RetryNotify(o, b, nil) }
// RetryNotify calls notify function with the error and wait duration
// for each failed attempt before sleep.
func RetryNotify(operation Operation, b Backoff, notify Notify) error {
var err error
var next time.Duration
b.Reset()
for {
if err = operation(); err == nil {
return nil
}
if next = b.Next(); next == Stop {
return err
}
if notify != nil {
notify(err, next)
}
time.Sleep(next)
}
}
|
{
"pile_set_name": "Github"
}
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.WAFRegional.DeletePermissionPolicy
-- Copyright : (c) 2013-2018 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Permanently deletes an IAM policy from the specified RuleGroup.
--
--
-- The user making the request must be the owner of the RuleGroup.
--
module Network.AWS.WAFRegional.DeletePermissionPolicy
(
-- * Creating a Request
deletePermissionPolicy
, DeletePermissionPolicy
-- * Request Lenses
, dppResourceARN
-- * Destructuring the Response
, deletePermissionPolicyResponse
, DeletePermissionPolicyResponse
-- * Response Lenses
, dpprsResponseStatus
) where
import Network.AWS.Lens
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
import Network.AWS.WAFRegional.Types
import Network.AWS.WAFRegional.Types.Product
-- | /See:/ 'deletePermissionPolicy' smart constructor.
newtype DeletePermissionPolicy = DeletePermissionPolicy'
{ _dppResourceARN :: Text
} deriving (Eq, Read, Show, Data, Typeable, Generic)
-- | Creates a value of 'DeletePermissionPolicy' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dppResourceARN' - The Amazon Resource Name (ARN) of the RuleGroup from which you want to delete the policy. The user making the request must be the owner of the RuleGroup.
deletePermissionPolicy
:: Text -- ^ 'dppResourceARN'
-> DeletePermissionPolicy
deletePermissionPolicy pResourceARN_ =
DeletePermissionPolicy' {_dppResourceARN = pResourceARN_}
-- | The Amazon Resource Name (ARN) of the RuleGroup from which you want to delete the policy. The user making the request must be the owner of the RuleGroup.
dppResourceARN :: Lens' DeletePermissionPolicy Text
dppResourceARN = lens _dppResourceARN (\ s a -> s{_dppResourceARN = a})
instance AWSRequest DeletePermissionPolicy where
type Rs DeletePermissionPolicy =
DeletePermissionPolicyResponse
request = postJSON wAFRegional
response
= receiveEmpty
(\ s h x ->
DeletePermissionPolicyResponse' <$>
(pure (fromEnum s)))
instance Hashable DeletePermissionPolicy where
instance NFData DeletePermissionPolicy where
instance ToHeaders DeletePermissionPolicy where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("AWSWAF_Regional_20161128.DeletePermissionPolicy" ::
ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON DeletePermissionPolicy where
toJSON DeletePermissionPolicy'{..}
= object
(catMaybes [Just ("ResourceArn" .= _dppResourceARN)])
instance ToPath DeletePermissionPolicy where
toPath = const "/"
instance ToQuery DeletePermissionPolicy where
toQuery = const mempty
-- | /See:/ 'deletePermissionPolicyResponse' smart constructor.
newtype DeletePermissionPolicyResponse = DeletePermissionPolicyResponse'
{ _dpprsResponseStatus :: Int
} deriving (Eq, Read, Show, Data, Typeable, Generic)
-- | Creates a value of 'DeletePermissionPolicyResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dpprsResponseStatus' - -- | The response status code.
deletePermissionPolicyResponse
:: Int -- ^ 'dpprsResponseStatus'
-> DeletePermissionPolicyResponse
deletePermissionPolicyResponse pResponseStatus_ =
DeletePermissionPolicyResponse' {_dpprsResponseStatus = pResponseStatus_}
-- | -- | The response status code.
dpprsResponseStatus :: Lens' DeletePermissionPolicyResponse Int
dpprsResponseStatus = lens _dpprsResponseStatus (\ s a -> s{_dpprsResponseStatus = a})
instance NFData DeletePermissionPolicyResponse where
|
{
"pile_set_name": "Github"
}
|
//
// NamedEvent_Android.h
//
// $Id: //poco/1.4/Foundation/include/Poco/NamedEvent_Android.h#1 $
//
// Library: Foundation
// Package: Processes
// Module: NamedEvent
//
// Definition of the NamedEventImpl class for Android.
//
// Copyright (c) 2004-2011, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Foundation_NamedEvent_Android_INCLUDED
#define Foundation_NamedEvent_Android_INCLUDED
#include "Poco/Foundation.h"
namespace Poco {
class Foundation_API NamedEventImpl
{
protected:
NamedEventImpl(const std::string& name);
~NamedEventImpl();
void setImpl();
void waitImpl();
};
} // namespace Poco
#endif // Foundation_NamedEvent_Android_INCLUDED
|
{
"pile_set_name": "Github"
}
|
@project: virtualcar
@author: Halis Duraki <[email protected]>
@homepage: https://duraki.gitlab.io
### Version 1.0.0-m.patch of 05 May 2017
+ #added: new logo!
+ #fixed: code structure
+ #fixed: sframe / socket nb offset
.devist
|
{
"pile_set_name": "Github"
}
|
#
# Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle in the LICENSE file that accompanied this code.
#
# This code 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
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
# (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
# (C) Copyright IBM Corp. 1996 - 1999 - All Rights Reserved
#
# The original version of this source code and documentation
# is copyrighted and owned by Taligent, Inc., a wholly-owned
# subsidiary of IBM. These materials are provided under terms
# of a License Agreement between Taligent and Sun. This technology
# is protected by multiple US and International patents.
#
# This notice and attribution to Taligent may not be removed.
# Taligent is a registered trademark of Taligent, Inc.
firstDayOfWeek=2
minimalDaysInFirstWeek=4
|
{
"pile_set_name": "Github"
}
|
# PUPPI LOG README
Documentation and examples related to the puppi action log
## SYNOPSIS (cli)
puppi log [topic] [-i]
## EXAMPLES (cli)
Tails (tail -10f) all the known logs.
puppi log
Tails only the logs related to the given topic
puppi log apache
Choose interactively which logs to show
puppi log
Grep the output with the string defined
puppi log -g <string>
## EXAMPLES (puppet)
The basic define related to a log is:
puppi::log
it creates a file in /etc/puppi/logs/ with one or more logs paths.
A simple, operating system aware, example might be:
puppi::log { 'auth':
description => 'Users and authentication' ,
log => $::operatingsystem ? {
redhat => '/var/log/secure',
darwin => '/var/log/secure.log',
ubuntu => ['/var/log/user.log','/var/log/auth.log'],
}
}
but also something that uses variables Puppet already knows
puppi::log { "tomcat-${instance_name}":
log => "${tomcat::params::storedir}/${instance_name}/logs/catalina.out"
}
EXAMPLES (with example42 puppet modules)
If you use the old Example42 modules set you get automatically many service related logs out of the box to be used with Puppi One.
NextGen modules are supposed to provide puppi log intergration on Puppi Two (TO DO)
|
{
"pile_set_name": "Github"
}
|
/* TA-LIB Copyright (c) 1999-2008, Mario Fortier
* 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 name of author 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
* REGENTS 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.
*/
/* List of contributors:
*
* Initial Name/description
* -------------------------------------------------------------------
* MF Mario Fortier
*
*
* Change history:
*
* MMDDYY BY Description
* -------------------------------------------------------------------
* 112400 MF Template creation.
* 052603 MF Adapt code to compile with .NET Managed C++
*
*/
/**** START GENCODE SECTION 1 - DO NOT DELETE THIS LINE ****/
/* All code within this section is automatically
* generated by gen_code. Any modification will be lost
* next time gen_code is run.
*/
/* Generated */
/* Generated */ #if defined( _MANAGED )
/* Generated */ #include "TA-Lib-Core.h"
/* Generated */ #define TA_INTERNAL_ERROR(Id) (RetCode::InternalError)
/* Generated */ namespace TicTacTec { namespace TA { namespace Library {
/* Generated */ #elif defined( _JAVA )
/* Generated */ #include "ta_defs.h"
/* Generated */ #include "ta_java_defs.h"
/* Generated */ #define TA_INTERNAL_ERROR(Id) (RetCode.InternalError)
/* Generated */ #else
/* Generated */ #include <string.h>
/* Generated */ #include <math.h>
/* Generated */ #include "ta_func.h"
/* Generated */ #endif
/* Generated */
/* Generated */ #ifndef TA_UTILITY_H
/* Generated */ #include "ta_utility.h"
/* Generated */ #endif
/* Generated */
/* Generated */ #ifndef TA_MEMORY_H
/* Generated */ #include "ta_memory.h"
/* Generated */ #endif
/* Generated */
/* Generated */ #define TA_PREFIX(x) TA_##x
/* Generated */ #define INPUT_TYPE double
/* Generated */
/* Generated */ #if defined( _MANAGED )
/* Generated */ int Core::StochLookback( int optInFastK_Period, /* From 1 to 100000 */
/* Generated */ int optInSlowK_Period, /* From 1 to 100000 */
/* Generated */ MAType optInSlowK_MAType,
/* Generated */ int optInSlowD_Period, /* From 1 to 100000 */
/* Generated */ MAType optInSlowD_MAType ) /* Generated */
/* Generated */ #elif defined( _JAVA )
/* Generated */ public int stochLookback( int optInFastK_Period, /* From 1 to 100000 */
/* Generated */ int optInSlowK_Period, /* From 1 to 100000 */
/* Generated */ MAType optInSlowK_MAType,
/* Generated */ int optInSlowD_Period, /* From 1 to 100000 */
/* Generated */ MAType optInSlowD_MAType ) /* Generated */
/* Generated */ #else
/* Generated */ int TA_STOCH_Lookback( int optInFastK_Period, /* From 1 to 100000 */
/* Generated */ int optInSlowK_Period, /* From 1 to 100000 */
/* Generated */ TA_MAType optInSlowK_MAType,
/* Generated */ int optInSlowD_Period, /* From 1 to 100000 */
/* Generated */ TA_MAType optInSlowD_MAType ) /* Generated */
/* Generated */ #endif
/**** END GENCODE SECTION 1 - DO NOT DELETE THIS LINE ****/
{
/* insert local variable here */
int retValue;
/**** START GENCODE SECTION 2 - DO NOT DELETE THIS LINE ****/
/* Generated */ #ifndef TA_FUNC_NO_RANGE_CHECK
/* Generated */ /* min/max are checked for optInFastK_Period. */
/* Generated */ if( (int)optInFastK_Period == TA_INTEGER_DEFAULT )
/* Generated */ optInFastK_Period = 5;
/* Generated */ else if( ((int)optInFastK_Period < 1) || ((int)optInFastK_Period > 100000) )
/* Generated */ return -1;
/* Generated */
/* Generated */ /* min/max are checked for optInSlowK_Period. */
/* Generated */ if( (int)optInSlowK_Period == TA_INTEGER_DEFAULT )
/* Generated */ optInSlowK_Period = 3;
/* Generated */ else if( ((int)optInSlowK_Period < 1) || ((int)optInSlowK_Period > 100000) )
/* Generated */ return -1;
/* Generated */
/* Generated */ #if !defined(_MANAGED) && !defined(_JAVA)
/* Generated */ if( (int)optInSlowK_MAType == TA_INTEGER_DEFAULT )
/* Generated */ optInSlowK_MAType = (TA_MAType)0;
/* Generated */ else if( ((int)optInSlowK_MAType < 0) || ((int)optInSlowK_MAType > 8) )
/* Generated */ return -1;
/* Generated */
/* Generated */ #endif /* !defined(_MANAGED) && !defined(_JAVA)*/
/* Generated */ /* min/max are checked for optInSlowD_Period. */
/* Generated */ if( (int)optInSlowD_Period == TA_INTEGER_DEFAULT )
/* Generated */ optInSlowD_Period = 3;
/* Generated */ else if( ((int)optInSlowD_Period < 1) || ((int)optInSlowD_Period > 100000) )
/* Generated */ return -1;
/* Generated */
/* Generated */ #if !defined(_MANAGED) && !defined(_JAVA)
/* Generated */ if( (int)optInSlowD_MAType == TA_INTEGER_DEFAULT )
/* Generated */ optInSlowD_MAType = (TA_MAType)0;
/* Generated */ else if( ((int)optInSlowD_MAType < 0) || ((int)optInSlowD_MAType > 8) )
/* Generated */ return -1;
/* Generated */
/* Generated */ #endif /* !defined(_MANAGED) && !defined(_JAVA)*/
/* Generated */ #endif /* TA_FUNC_NO_RANGE_CHECK */
/**** END GENCODE SECTION 2 - DO NOT DELETE THIS LINE ****/
/* insert lookback code here. */
/* Account for the initial data needed for Fast-K. */
retValue = (optInFastK_Period - 1);
/* Add the smoothing being done for %K slow */
retValue += LOOKBACK_CALL(MA)( optInSlowK_Period, optInSlowK_MAType );
/* Add the smoothing being done for %D slow. */
retValue += LOOKBACK_CALL(MA)( optInSlowD_Period, optInSlowD_MAType );
return retValue;
}
/**** START GENCODE SECTION 3 - DO NOT DELETE THIS LINE ****/
/*
* TA_STOCH - Stochastic
*
* Input = High, Low, Close
* Output = double, double
*
* Optional Parameters
* -------------------
* optInFastK_Period:(From 1 to 100000)
* Time period for building the Fast-K line
*
* optInSlowK_Period:(From 1 to 100000)
* Smoothing for making the Slow-K line. Usually set to 3
*
* optInSlowK_MAType:
* Type of Moving Average for Slow-K
*
* optInSlowD_Period:(From 1 to 100000)
* Smoothing for making the Slow-D line
*
* optInSlowD_MAType:
* Type of Moving Average for Slow-D
*
*
*/
/* Generated */
/* Generated */ #if defined( _MANAGED ) && defined( USE_SUBARRAY )
/* Generated */ enum class Core::RetCode Core::Stoch( int startIdx,
/* Generated */ int endIdx,
/* Generated */ SubArray<double>^ inHigh,
/* Generated */ SubArray<double>^ inLow,
/* Generated */ SubArray<double>^ inClose,
/* Generated */ int optInFastK_Period, /* From 1 to 100000 */
/* Generated */ int optInSlowK_Period, /* From 1 to 100000 */
/* Generated */ MAType optInSlowK_MAType,
/* Generated */ int optInSlowD_Period, /* From 1 to 100000 */
/* Generated */ MAType optInSlowD_MAType,
/* Generated */ [Out]int% outBegIdx,
/* Generated */ [Out]int% outNBElement,
/* Generated */ SubArray<double>^ outSlowK,
/* Generated */ SubArray<double>^ outSlowD )
/* Generated */ #elif defined( _MANAGED )
/* Generated */ enum class Core::RetCode Core::Stoch( int startIdx,
/* Generated */ int endIdx,
/* Generated */ cli::array<double>^ inHigh,
/* Generated */ cli::array<double>^ inLow,
/* Generated */ cli::array<double>^ inClose,
/* Generated */ int optInFastK_Period, /* From 1 to 100000 */
/* Generated */ int optInSlowK_Period, /* From 1 to 100000 */
/* Generated */ MAType optInSlowK_MAType,
/* Generated */ int optInSlowD_Period, /* From 1 to 100000 */
/* Generated */ MAType optInSlowD_MAType,
/* Generated */ [Out]int% outBegIdx,
/* Generated */ [Out]int% outNBElement,
/* Generated */ cli::array<double>^ outSlowK,
/* Generated */ cli::array<double>^ outSlowD )
/* Generated */ #elif defined( _JAVA )
/* Generated */ public RetCode stoch( int startIdx,
/* Generated */ int endIdx,
/* Generated */ double inHigh[],
/* Generated */ double inLow[],
/* Generated */ double inClose[],
/* Generated */ int optInFastK_Period, /* From 1 to 100000 */
/* Generated */ int optInSlowK_Period, /* From 1 to 100000 */
/* Generated */ MAType optInSlowK_MAType,
/* Generated */ int optInSlowD_Period, /* From 1 to 100000 */
/* Generated */ MAType optInSlowD_MAType,
/* Generated */ MInteger outBegIdx,
/* Generated */ MInteger outNBElement,
/* Generated */ double outSlowK[],
/* Generated */ double outSlowD[] )
/* Generated */ #else
/* Generated */ TA_RetCode TA_STOCH( int startIdx,
/* Generated */ int endIdx,
/* Generated */ const double inHigh[],
/* Generated */ const double inLow[],
/* Generated */ const double inClose[],
/* Generated */ int optInFastK_Period, /* From 1 to 100000 */
/* Generated */ int optInSlowK_Period, /* From 1 to 100000 */
/* Generated */ TA_MAType optInSlowK_MAType,
/* Generated */ int optInSlowD_Period, /* From 1 to 100000 */
/* Generated */ TA_MAType optInSlowD_MAType,
/* Generated */ int *outBegIdx,
/* Generated */ int *outNBElement,
/* Generated */ double outSlowK[],
/* Generated */ double outSlowD[] )
/* Generated */ #endif
/**** END GENCODE SECTION 3 - DO NOT DELETE THIS LINE ****/
{
/* Insert local variables here. */
ENUM_DECLARATION(RetCode) retCode;
double lowest, highest, tmp, diff;
ARRAY_REF( tempBuffer );
int outIdx, lowestIdx, highestIdx;
int lookbackTotal, lookbackK, lookbackKSlow, lookbackDSlow;
int trailingIdx, today, i;
#if !defined( _MANAGED ) && !defined(USE_SINGLE_PRECISION_INPUT) &&!defined(_JAVA)
int bufferIsAllocated;
#endif
/**** START GENCODE SECTION 4 - DO NOT DELETE THIS LINE ****/
/* Generated */
/* Generated */ #ifndef TA_FUNC_NO_RANGE_CHECK
/* Generated */
/* Generated */ /* Validate the requested output range. */
/* Generated */ if( startIdx < 0 )
/* Generated */ return ENUM_VALUE(RetCode,TA_OUT_OF_RANGE_START_INDEX,OutOfRangeStartIndex);
/* Generated */ if( (endIdx < 0) || (endIdx < startIdx))
/* Generated */ return ENUM_VALUE(RetCode,TA_OUT_OF_RANGE_END_INDEX,OutOfRangeEndIndex);
/* Generated */
/* Generated */ #if !defined(_JAVA)
/* Generated */ /* Verify required price component. */
/* Generated */ if(!inHigh||!inLow||!inClose)
/* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */
/* Generated */ #endif /* !defined(_JAVA)*/
/* Generated */ /* min/max are checked for optInFastK_Period. */
/* Generated */ if( (int)optInFastK_Period == TA_INTEGER_DEFAULT )
/* Generated */ optInFastK_Period = 5;
/* Generated */ else if( ((int)optInFastK_Period < 1) || ((int)optInFastK_Period > 100000) )
/* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */
/* Generated */ /* min/max are checked for optInSlowK_Period. */
/* Generated */ if( (int)optInSlowK_Period == TA_INTEGER_DEFAULT )
/* Generated */ optInSlowK_Period = 3;
/* Generated */ else if( ((int)optInSlowK_Period < 1) || ((int)optInSlowK_Period > 100000) )
/* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */
/* Generated */ #if !defined(_MANAGED) && !defined(_JAVA)
/* Generated */ if( (int)optInSlowK_MAType == TA_INTEGER_DEFAULT )
/* Generated */ optInSlowK_MAType = (TA_MAType)0;
/* Generated */ else if( ((int)optInSlowK_MAType < 0) || ((int)optInSlowK_MAType > 8) )
/* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */
/* Generated */ #endif /* !defined(_MANAGED) && !defined(_JAVA)*/
/* Generated */ /* min/max are checked for optInSlowD_Period. */
/* Generated */ if( (int)optInSlowD_Period == TA_INTEGER_DEFAULT )
/* Generated */ optInSlowD_Period = 3;
/* Generated */ else if( ((int)optInSlowD_Period < 1) || ((int)optInSlowD_Period > 100000) )
/* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */
/* Generated */ #if !defined(_MANAGED) && !defined(_JAVA)
/* Generated */ if( (int)optInSlowD_MAType == TA_INTEGER_DEFAULT )
/* Generated */ optInSlowD_MAType = (TA_MAType)0;
/* Generated */ else if( ((int)optInSlowD_MAType < 0) || ((int)optInSlowD_MAType > 8) )
/* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */
/* Generated */ #endif /* !defined(_MANAGED) && !defined(_JAVA)*/
/* Generated */ #if !defined(_JAVA)
/* Generated */ if( !outSlowK )
/* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */
/* Generated */ if( !outSlowD )
/* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */
/* Generated */ #endif /* !defined(_JAVA) */
/* Generated */ #endif /* TA_FUNC_NO_RANGE_CHECK */
/* Generated */
/**** END GENCODE SECTION 4 - DO NOT DELETE THIS LINE ****/
/* Insert TA function code here. */
/* With stochastic, there is a total of 4 different lines that
* are defined: FASTK, FASTD, SLOWK and SLOWD.
*
* The D is the signal line usually drawn over its
* corresponding K function.
*
* (Today's Close - LowestLow)
* FASTK(Kperiod) = --------------------------- * 100
* (HighestHigh - LowestLow)
*
* FASTD(FastDperiod, MA type) = MA Smoothed FASTK over FastDperiod
*
* SLOWK(SlowKperiod, MA type) = MA Smoothed FASTK over SlowKperiod
*
* SLOWD(SlowDperiod, MA Type) = MA Smoothed SLOWK over SlowDperiod
*
* The HighestHigh and LowestLow are the extreme values among the
* last 'Kperiod'.
*
* SLOWK and FASTD are equivalent when using the same period.
*
* The following shows how these four lines are made available in TA-LIB:
*
* TA_STOCH : Returns the SLOWK and SLOWD
* TA_STOCHF : Returns the FASTK and FASTD
*
* The TA_STOCH function correspond to the more widely implemented version
* found in many software/charting package. The TA_STOCHF is more rarely
* used because its higher volatility cause often whipsaws.
*/
/* Identify the lookback needed. */
lookbackK = optInFastK_Period-1;
lookbackKSlow = LOOKBACK_CALL(MA)( optInSlowK_Period, optInSlowK_MAType );
lookbackDSlow = LOOKBACK_CALL(MA)( optInSlowD_Period, optInSlowD_MAType );
lookbackTotal = lookbackK + lookbackDSlow + lookbackKSlow;
/* Move up the start index if there is not
* enough initial data.
*/
if( startIdx < lookbackTotal )
startIdx = lookbackTotal;
/* Make sure there is still something to evaluate. */
if( startIdx > endIdx )
{
/* Succeed... but no data in the output. */
VALUE_HANDLE_DEREF_TO_ZERO(outBegIdx);
VALUE_HANDLE_DEREF_TO_ZERO(outNBElement);
return ENUM_VALUE(RetCode,TA_SUCCESS,Success);
}
/* Do the K calculation:
*
* Kt = 100 x ((Ct-Lt)/(Ht-Lt))
*
* Kt is today stochastic
* Ct is today closing price.
* Lt is the lowest price of the last K Period (including today)
* Ht is the highest price of the last K Period (including today)
*/
/* Proceed with the calculation for the requested range.
* Note that this algorithm allows the input and
* output to be the same buffer.
*/
outIdx = 0;
/* Calculate just enough K for ending up with the caller
* requested range. (The range of k must consider all
* the lookback involve with the smoothing).
*/
trailingIdx = startIdx-lookbackTotal;
today = trailingIdx+lookbackK;
lowestIdx = highestIdx = -1;
diff = highest = lowest = 0.0;
/* Allocate a temporary buffer large enough to
* store the K.
*
* If the output is the same as the input, great
* we just save ourself one memory allocation.
*/
#if !defined( _MANAGED ) && !defined(USE_SINGLE_PRECISION_INPUT) && !defined( _JAVA )
bufferIsAllocated = 0;
#endif
#if defined(USE_SINGLE_PRECISION_INPUT) || defined( USE_SUBARRAY )
/* Always alloc, since output is of different type and
* its allocated size is not guarantee to be as large as
* the input.
*/
ARRAY_ALLOC( tempBuffer, endIdx-today+1 );
#else
if( (outSlowK == inHigh) ||
(outSlowK == inLow) ||
(outSlowK == inClose) )
{
tempBuffer = outSlowK;
}
else if( (outSlowD == inHigh) ||
(outSlowD == inLow) ||
(outSlowD == inClose) )
{
tempBuffer = outSlowD;
}
else
{
#if !defined( _MANAGED ) && !defined(_JAVA)
bufferIsAllocated = 1;
#endif
ARRAY_ALLOC( tempBuffer, endIdx-today+1 );
}
#endif
/* Do the K calculation */
while( today <= endIdx )
{
/* Set the lowest low */
tmp = inLow[today];
if( lowestIdx < trailingIdx )
{
lowestIdx = trailingIdx;
lowest = inLow[lowestIdx];
i = lowestIdx;
while( ++i<=today )
{
tmp = inLow[i];
if( tmp < lowest )
{
lowestIdx = i;
lowest = tmp;
}
}
diff = (highest - lowest)/100.0;
}
else if( tmp <= lowest )
{
lowestIdx = today;
lowest = tmp;
diff = (highest - lowest)/100.0;
}
/* Set the highest high */
tmp = inHigh[today];
if( highestIdx < trailingIdx )
{
highestIdx = trailingIdx;
highest = inHigh[highestIdx];
i = highestIdx;
while( ++i<=today )
{
tmp = inHigh[i];
if( tmp > highest )
{
highestIdx = i;
highest = tmp;
}
}
diff = (highest - lowest)/100.0;
}
else if( tmp >= highest )
{
highestIdx = today;
highest = tmp;
diff = (highest - lowest)/100.0;
}
/* Calculate stochastic. */
if( diff != 0.0 )
tempBuffer[outIdx++] = (inClose[today]-lowest)/diff;
else
tempBuffer[outIdx++] = 0.0;
trailingIdx++;
today++;
}
/* Un-smoothed K calculation completed. This K calculation is not returned
* to the caller. It is always smoothed and then return.
* Some documentation will refer to the smoothed version as being
* "K-Slow", but often this end up to be shorten to "K".
*/
retCode = FUNCTION_CALL_DOUBLE(MA)( 0, outIdx-1,
tempBuffer, optInSlowK_Period,
optInSlowK_MAType,
outBegIdx, outNBElement, tempBuffer );
if( (retCode != ENUM_VALUE(RetCode,TA_SUCCESS,Success) ) || ((int)VALUE_HANDLE_DEREF(outNBElement) == 0) )
{
#if defined(USE_SINGLE_PRECISION_INPUT)
ARRAY_FREE( tempBuffer );
#else
ARRAY_FREE_COND( bufferIsAllocated, tempBuffer );
#endif
/* Something wrong happen? No further data? */
VALUE_HANDLE_DEREF_TO_ZERO(outBegIdx);
VALUE_HANDLE_DEREF_TO_ZERO(outNBElement);
return retCode;
}
/* Calculate the %D which is simply a moving average of
* the already smoothed %K.
*/
retCode = FUNCTION_CALL_DOUBLE(MA)( 0, (int)VALUE_HANDLE_DEREF(outNBElement)-1,
tempBuffer, optInSlowD_Period,
optInSlowD_MAType,
outBegIdx, outNBElement, outSlowD );
/* Copy tempBuffer into the caller buffer.
* (Calculation could not be done directly in the
* caller buffer because more input data then the
* requested range was needed for doing %D).
*/
ARRAY_MEMMOVE( outSlowK, 0, tempBuffer,lookbackDSlow,(int)VALUE_HANDLE_DEREF(outNBElement));
/* Don't need K anymore, free it if it was allocated here. */
#if defined(USE_SINGLE_PRECISION_INPUT)
ARRAY_FREE( tempBuffer );
#else
ARRAY_FREE_COND( bufferIsAllocated, tempBuffer );
#endif
if( retCode != ENUM_VALUE(RetCode,TA_SUCCESS,Success) )
{
/* Something wrong happen while processing %D? */
VALUE_HANDLE_DEREF_TO_ZERO(outBegIdx);
VALUE_HANDLE_DEREF_TO_ZERO(outNBElement);
return retCode;
}
/* Note: Keep the outBegIdx relative to the
* caller input before returning.
*/
VALUE_HANDLE_DEREF(outBegIdx) = startIdx;
return ENUM_VALUE(RetCode,TA_SUCCESS,Success);
}
/**** START GENCODE SECTION 5 - DO NOT DELETE THIS LINE ****/
/* Generated */
/* Generated */ #define USE_SINGLE_PRECISION_INPUT
/* Generated */ #undef TA_LIB_PRO
/* Generated */ #if !defined( _MANAGED ) && !defined( _JAVA )
/* Generated */ #undef TA_PREFIX
/* Generated */ #define TA_PREFIX(x) TA_S_##x
/* Generated */ #endif
/* Generated */ #undef INPUT_TYPE
/* Generated */ #define INPUT_TYPE float
/* Generated */ #if defined( _MANAGED ) && defined( USE_SUBARRAY )
/* Generated */ enum class Core::RetCode Core::Stoch( int startIdx,
/* Generated */ int endIdx,
/* Generated */ SubArray<float>^ inHigh,
/* Generated */ SubArray<float>^ inLow,
/* Generated */ SubArray<float>^ inClose,
/* Generated */ int optInFastK_Period, /* From 1 to 100000 */
/* Generated */ int optInSlowK_Period, /* From 1 to 100000 */
/* Generated */ MAType optInSlowK_MAType,
/* Generated */ int optInSlowD_Period, /* From 1 to 100000 */
/* Generated */ MAType optInSlowD_MAType,
/* Generated */ [Out]int% outBegIdx,
/* Generated */ [Out]int% outNBElement,
/* Generated */ SubArray<double>^ outSlowK,
/* Generated */ SubArray<double>^ outSlowD )
/* Generated */ #elif defined( _MANAGED )
/* Generated */ enum class Core::RetCode Core::Stoch( int startIdx,
/* Generated */ int endIdx,
/* Generated */ cli::array<float>^ inHigh,
/* Generated */ cli::array<float>^ inLow,
/* Generated */ cli::array<float>^ inClose,
/* Generated */ int optInFastK_Period, /* From 1 to 100000 */
/* Generated */ int optInSlowK_Period, /* From 1 to 100000 */
/* Generated */ MAType optInSlowK_MAType,
/* Generated */ int optInSlowD_Period, /* From 1 to 100000 */
/* Generated */ MAType optInSlowD_MAType,
/* Generated */ [Out]int% outBegIdx,
/* Generated */ [Out]int% outNBElement,
/* Generated */ cli::array<double>^ outSlowK,
/* Generated */ cli::array<double>^ outSlowD )
/* Generated */ #elif defined( _JAVA )
/* Generated */ public RetCode stoch( int startIdx,
/* Generated */ int endIdx,
/* Generated */ float inHigh[],
/* Generated */ float inLow[],
/* Generated */ float inClose[],
/* Generated */ int optInFastK_Period, /* From 1 to 100000 */
/* Generated */ int optInSlowK_Period, /* From 1 to 100000 */
/* Generated */ MAType optInSlowK_MAType,
/* Generated */ int optInSlowD_Period, /* From 1 to 100000 */
/* Generated */ MAType optInSlowD_MAType,
/* Generated */ MInteger outBegIdx,
/* Generated */ MInteger outNBElement,
/* Generated */ double outSlowK[],
/* Generated */ double outSlowD[] )
/* Generated */ #else
/* Generated */ TA_RetCode TA_S_STOCH( int startIdx,
/* Generated */ int endIdx,
/* Generated */ const float inHigh[],
/* Generated */ const float inLow[],
/* Generated */ const float inClose[],
/* Generated */ int optInFastK_Period, /* From 1 to 100000 */
/* Generated */ int optInSlowK_Period, /* From 1 to 100000 */
/* Generated */ TA_MAType optInSlowK_MAType,
/* Generated */ int optInSlowD_Period, /* From 1 to 100000 */
/* Generated */ TA_MAType optInSlowD_MAType,
/* Generated */ int *outBegIdx,
/* Generated */ int *outNBElement,
/* Generated */ double outSlowK[],
/* Generated */ double outSlowD[] )
/* Generated */ #endif
/* Generated */ {
/* Generated */ ENUM_DECLARATION(RetCode) retCode;
/* Generated */ double lowest, highest, tmp, diff;
/* Generated */ ARRAY_REF( tempBuffer );
/* Generated */ int outIdx, lowestIdx, highestIdx;
/* Generated */ int lookbackTotal, lookbackK, lookbackKSlow, lookbackDSlow;
/* Generated */ int trailingIdx, today, i;
/* Generated */ #if !defined( _MANAGED ) && !defined(USE_SINGLE_PRECISION_INPUT) &&!defined(_JAVA)
/* Generated */ int bufferIsAllocated;
/* Generated */ #endif
/* Generated */ #ifndef TA_FUNC_NO_RANGE_CHECK
/* Generated */ if( startIdx < 0 )
/* Generated */ return ENUM_VALUE(RetCode,TA_OUT_OF_RANGE_START_INDEX,OutOfRangeStartIndex);
/* Generated */ if( (endIdx < 0) || (endIdx < startIdx))
/* Generated */ return ENUM_VALUE(RetCode,TA_OUT_OF_RANGE_END_INDEX,OutOfRangeEndIndex);
/* Generated */ #if !defined(_JAVA)
/* Generated */ if(!inHigh||!inLow||!inClose)
/* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */ #endif
/* Generated */ if( (int)optInFastK_Period == TA_INTEGER_DEFAULT )
/* Generated */ optInFastK_Period = 5;
/* Generated */ else if( ((int)optInFastK_Period < 1) || ((int)optInFastK_Period > 100000) )
/* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */ if( (int)optInSlowK_Period == TA_INTEGER_DEFAULT )
/* Generated */ optInSlowK_Period = 3;
/* Generated */ else if( ((int)optInSlowK_Period < 1) || ((int)optInSlowK_Period > 100000) )
/* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */ #if !defined(_MANAGED) && !defined(_JAVA)
/* Generated */ if( (int)optInSlowK_MAType == TA_INTEGER_DEFAULT )
/* Generated */ optInSlowK_MAType = (TA_MAType)0;
/* Generated */ else if( ((int)optInSlowK_MAType < 0) || ((int)optInSlowK_MAType > 8) )
/* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */ #endif
/* Generated */ if( (int)optInSlowD_Period == TA_INTEGER_DEFAULT )
/* Generated */ optInSlowD_Period = 3;
/* Generated */ else if( ((int)optInSlowD_Period < 1) || ((int)optInSlowD_Period > 100000) )
/* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */ #if !defined(_MANAGED) && !defined(_JAVA)
/* Generated */ if( (int)optInSlowD_MAType == TA_INTEGER_DEFAULT )
/* Generated */ optInSlowD_MAType = (TA_MAType)0;
/* Generated */ else if( ((int)optInSlowD_MAType < 0) || ((int)optInSlowD_MAType > 8) )
/* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */ #endif
/* Generated */ #if !defined(_JAVA)
/* Generated */ if( !outSlowK )
/* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */ if( !outSlowD )
/* Generated */ return ENUM_VALUE(RetCode,TA_BAD_PARAM,BadParam);
/* Generated */ #endif
/* Generated */ #endif
/* Generated */ lookbackK = optInFastK_Period-1;
/* Generated */ lookbackKSlow = LOOKBACK_CALL(MA)( optInSlowK_Period, optInSlowK_MAType );
/* Generated */ lookbackDSlow = LOOKBACK_CALL(MA)( optInSlowD_Period, optInSlowD_MAType );
/* Generated */ lookbackTotal = lookbackK + lookbackDSlow + lookbackKSlow;
/* Generated */ if( startIdx < lookbackTotal )
/* Generated */ startIdx = lookbackTotal;
/* Generated */ if( startIdx > endIdx )
/* Generated */ {
/* Generated */ VALUE_HANDLE_DEREF_TO_ZERO(outBegIdx);
/* Generated */ VALUE_HANDLE_DEREF_TO_ZERO(outNBElement);
/* Generated */ return ENUM_VALUE(RetCode,TA_SUCCESS,Success);
/* Generated */ }
/* Generated */ outIdx = 0;
/* Generated */ trailingIdx = startIdx-lookbackTotal;
/* Generated */ today = trailingIdx+lookbackK;
/* Generated */ lowestIdx = highestIdx = -1;
/* Generated */ diff = highest = lowest = 0.0;
/* Generated */ #if !defined( _MANAGED ) && !defined(USE_SINGLE_PRECISION_INPUT) && !defined( _JAVA )
/* Generated */ bufferIsAllocated = 0;
/* Generated */ #endif
/* Generated */ #if defined(USE_SINGLE_PRECISION_INPUT) || defined( USE_SUBARRAY )
/* Generated */ ARRAY_ALLOC( tempBuffer, endIdx-today+1 );
/* Generated */ #else
/* Generated */ if( (outSlowK == inHigh) ||
/* Generated */ (outSlowK == inLow) ||
/* Generated */ (outSlowK == inClose) )
/* Generated */ {
/* Generated */ tempBuffer = outSlowK;
/* Generated */ }
/* Generated */ else if( (outSlowD == inHigh) ||
/* Generated */ (outSlowD == inLow) ||
/* Generated */ (outSlowD == inClose) )
/* Generated */ {
/* Generated */ tempBuffer = outSlowD;
/* Generated */ }
/* Generated */ else
/* Generated */ {
/* Generated */ #if !defined( _MANAGED ) && !defined(_JAVA)
/* Generated */ bufferIsAllocated = 1;
/* Generated */ #endif
/* Generated */ ARRAY_ALLOC( tempBuffer, endIdx-today+1 );
/* Generated */ }
/* Generated */ #endif
/* Generated */ while( today <= endIdx )
/* Generated */ {
/* Generated */ tmp = inLow[today];
/* Generated */ if( lowestIdx < trailingIdx )
/* Generated */ {
/* Generated */ lowestIdx = trailingIdx;
/* Generated */ lowest = inLow[lowestIdx];
/* Generated */ i = lowestIdx;
/* Generated */ while( ++i<=today )
/* Generated */ {
/* Generated */ tmp = inLow[i];
/* Generated */ if( tmp < lowest )
/* Generated */ {
/* Generated */ lowestIdx = i;
/* Generated */ lowest = tmp;
/* Generated */ }
/* Generated */ }
/* Generated */ diff = (highest - lowest)/100.0;
/* Generated */ }
/* Generated */ else if( tmp <= lowest )
/* Generated */ {
/* Generated */ lowestIdx = today;
/* Generated */ lowest = tmp;
/* Generated */ diff = (highest - lowest)/100.0;
/* Generated */ }
/* Generated */ tmp = inHigh[today];
/* Generated */ if( highestIdx < trailingIdx )
/* Generated */ {
/* Generated */ highestIdx = trailingIdx;
/* Generated */ highest = inHigh[highestIdx];
/* Generated */ i = highestIdx;
/* Generated */ while( ++i<=today )
/* Generated */ {
/* Generated */ tmp = inHigh[i];
/* Generated */ if( tmp > highest )
/* Generated */ {
/* Generated */ highestIdx = i;
/* Generated */ highest = tmp;
/* Generated */ }
/* Generated */ }
/* Generated */ diff = (highest - lowest)/100.0;
/* Generated */ }
/* Generated */ else if( tmp >= highest )
/* Generated */ {
/* Generated */ highestIdx = today;
/* Generated */ highest = tmp;
/* Generated */ diff = (highest - lowest)/100.0;
/* Generated */ }
/* Generated */ if( diff != 0.0 )
/* Generated */ tempBuffer[outIdx++] = (inClose[today]-lowest)/diff;
/* Generated */ else
/* Generated */ tempBuffer[outIdx++] = 0.0;
/* Generated */ trailingIdx++;
/* Generated */ today++;
/* Generated */ }
/* Generated */ retCode = FUNCTION_CALL_DOUBLE(MA)( 0, outIdx-1,
/* Generated */ tempBuffer, optInSlowK_Period,
/* Generated */ optInSlowK_MAType,
/* Generated */ outBegIdx, outNBElement, tempBuffer );
/* Generated */ if( (retCode != ENUM_VALUE(RetCode,TA_SUCCESS,Success) ) || ((int)VALUE_HANDLE_DEREF(outNBElement) == 0) )
/* Generated */ {
/* Generated */ #if defined(USE_SINGLE_PRECISION_INPUT)
/* Generated */ ARRAY_FREE( tempBuffer );
/* Generated */ #else
/* Generated */ ARRAY_FREE_COND( bufferIsAllocated, tempBuffer );
/* Generated */ #endif
/* Generated */ VALUE_HANDLE_DEREF_TO_ZERO(outBegIdx);
/* Generated */ VALUE_HANDLE_DEREF_TO_ZERO(outNBElement);
/* Generated */ return retCode;
/* Generated */ }
/* Generated */ retCode = FUNCTION_CALL_DOUBLE(MA)( 0, (int)VALUE_HANDLE_DEREF(outNBElement)-1,
/* Generated */ tempBuffer, optInSlowD_Period,
/* Generated */ optInSlowD_MAType,
/* Generated */ outBegIdx, outNBElement, outSlowD );
/* Generated */ ARRAY_MEMMOVE( outSlowK, 0, tempBuffer,lookbackDSlow,(int)VALUE_HANDLE_DEREF(outNBElement));
/* Generated */ #if defined(USE_SINGLE_PRECISION_INPUT)
/* Generated */ ARRAY_FREE( tempBuffer );
/* Generated */ #else
/* Generated */ ARRAY_FREE_COND( bufferIsAllocated, tempBuffer );
/* Generated */ #endif
/* Generated */ if( retCode != ENUM_VALUE(RetCode,TA_SUCCESS,Success) )
/* Generated */ {
/* Generated */ VALUE_HANDLE_DEREF_TO_ZERO(outBegIdx);
/* Generated */ VALUE_HANDLE_DEREF_TO_ZERO(outNBElement);
/* Generated */ return retCode;
/* Generated */ }
/* Generated */ VALUE_HANDLE_DEREF(outBegIdx) = startIdx;
/* Generated */ return ENUM_VALUE(RetCode,TA_SUCCESS,Success);
/* Generated */ }
/* Generated */
/* Generated */ #if defined( _MANAGED )
/* Generated */ }}} // Close namespace TicTacTec.TA.Lib
/* Generated */ #endif
/**** END GENCODE SECTION 5 - DO NOT DELETE THIS LINE ****/
|
{
"pile_set_name": "Github"
}
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2016 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <Eigen/LU>
#include <Eigen/Cholesky>
#include <Eigen/QR>
// This file test inplace decomposition through Ref<>, as supported by Cholesky, LU, and QR decompositions.
template<typename DecType,typename MatrixType> void inplace(bool square = false, bool SPD = false)
{
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> RhsType;
typedef Matrix<Scalar, MatrixType::ColsAtCompileTime, 1> ResType;
Index rows = MatrixType::RowsAtCompileTime==Dynamic ? internal::random<Index>(2,EIGEN_TEST_MAX_SIZE/2) : Index(MatrixType::RowsAtCompileTime);
Index cols = MatrixType::ColsAtCompileTime==Dynamic ? (square?rows:internal::random<Index>(2,rows)) : Index(MatrixType::ColsAtCompileTime);
MatrixType A = MatrixType::Random(rows,cols);
RhsType b = RhsType::Random(rows);
ResType x(cols);
if(SPD)
{
assert(square);
A.topRows(cols) = A.topRows(cols).adjoint() * A.topRows(cols);
A.diagonal().array() += 1e-3;
}
MatrixType A0 = A;
MatrixType A1 = A;
DecType dec(A);
// Check that the content of A has been modified
VERIFY_IS_NOT_APPROX( A, A0 );
// Check that the decomposition is correct:
if(rows==cols)
{
VERIFY_IS_APPROX( A0 * (x = dec.solve(b)), b );
}
else
{
VERIFY_IS_APPROX( A0.transpose() * A0 * (x = dec.solve(b)), A0.transpose() * b );
}
// Check that modifying A breaks the current dec:
A.setRandom();
if(rows==cols)
{
VERIFY_IS_NOT_APPROX( A0 * (x = dec.solve(b)), b );
}
else
{
VERIFY_IS_NOT_APPROX( A0.transpose() * A0 * (x = dec.solve(b)), A0.transpose() * b );
}
// Check that calling compute(A1) does not modify A1:
A = A0;
dec.compute(A1);
VERIFY_IS_EQUAL(A0,A1);
VERIFY_IS_NOT_APPROX( A, A0 );
if(rows==cols)
{
VERIFY_IS_APPROX( A0 * (x = dec.solve(b)), b );
}
else
{
VERIFY_IS_APPROX( A0.transpose() * A0 * (x = dec.solve(b)), A0.transpose() * b );
}
}
void test_inplace_decomposition()
{
EIGEN_UNUSED typedef Matrix<double,4,3> Matrix43d;
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1(( inplace<LLT<Ref<MatrixXd> >, MatrixXd>(true,true) ));
CALL_SUBTEST_1(( inplace<LLT<Ref<Matrix4d> >, Matrix4d>(true,true) ));
CALL_SUBTEST_2(( inplace<LDLT<Ref<MatrixXd> >, MatrixXd>(true,true) ));
CALL_SUBTEST_2(( inplace<LDLT<Ref<Matrix4d> >, Matrix4d>(true,true) ));
CALL_SUBTEST_3(( inplace<PartialPivLU<Ref<MatrixXd> >, MatrixXd>(true,false) ));
CALL_SUBTEST_3(( inplace<PartialPivLU<Ref<Matrix4d> >, Matrix4d>(true,false) ));
CALL_SUBTEST_4(( inplace<FullPivLU<Ref<MatrixXd> >, MatrixXd>(true,false) ));
CALL_SUBTEST_4(( inplace<FullPivLU<Ref<Matrix4d> >, Matrix4d>(true,false) ));
CALL_SUBTEST_5(( inplace<HouseholderQR<Ref<MatrixXd> >, MatrixXd>(false,false) ));
CALL_SUBTEST_5(( inplace<HouseholderQR<Ref<Matrix43d> >, Matrix43d>(false,false) ));
CALL_SUBTEST_6(( inplace<ColPivHouseholderQR<Ref<MatrixXd> >, MatrixXd>(false,false) ));
CALL_SUBTEST_6(( inplace<ColPivHouseholderQR<Ref<Matrix43d> >, Matrix43d>(false,false) ));
CALL_SUBTEST_7(( inplace<FullPivHouseholderQR<Ref<MatrixXd> >, MatrixXd>(false,false) ));
CALL_SUBTEST_7(( inplace<FullPivHouseholderQR<Ref<Matrix43d> >, Matrix43d>(false,false) ));
CALL_SUBTEST_8(( inplace<CompleteOrthogonalDecomposition<Ref<MatrixXd> >, MatrixXd>(false,false) ));
CALL_SUBTEST_8(( inplace<CompleteOrthogonalDecomposition<Ref<Matrix43d> >, Matrix43d>(false,false) ));
}
}
|
{
"pile_set_name": "Github"
}
|
'use strict';
var loader = require('./js-yaml/loader');
var dumper = require('./js-yaml/dumper');
function deprecated(name) {
return function () {
throw new Error('Function ' + name + ' is deprecated and cannot be used.');
};
}
module.exports.Type = require('./js-yaml/type');
module.exports.Schema = require('./js-yaml/schema');
module.exports.MINIMAL_SCHEMA = require('./js-yaml/schema/minimal');
module.exports.SAFE_SCHEMA = require('./js-yaml/schema/safe');
module.exports.DEFAULT_SCHEMA = require('./js-yaml/schema/default');
module.exports.load = loader.load;
module.exports.loadAll = loader.loadAll;
module.exports.safeLoad = loader.safeLoad;
module.exports.safeLoadAll = loader.safeLoadAll;
module.exports.dump = dumper.dump;
module.exports.safeDump = dumper.safeDump;
module.exports.YAMLException = require('./js-yaml/exception');
module.exports.scan = deprecated('scan');
module.exports.parse = deprecated('parse');
module.exports.compose = deprecated('compose');
module.exports.addConstructor = deprecated('addConstructor');
require('./js-yaml/require');
|
{
"pile_set_name": "Github"
}
|
/*
* rcar_du_kms.c -- R-Car Display Unit Mode Setting
*
* Copyright (C) 2013-2015 Renesas Electronics Corporation
*
* Contact: Laurent Pinchart ([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 of the License, or
* (at your option) any later version.
*/
#include <drm/drmP.h>
#include <drm/drm_atomic.h>
#include <drm/drm_atomic_helper.h>
#include <drm/drm_crtc.h>
#include <drm/drm_crtc_helper.h>
#include <drm/drm_fb_cma_helper.h>
#include <drm/drm_gem_cma_helper.h>
#include <linux/of_graph.h>
#include <linux/wait.h>
#include "rcar_du_crtc.h"
#include "rcar_du_drv.h"
#include "rcar_du_encoder.h"
#include "rcar_du_kms.h"
#include "rcar_du_lvdsenc.h"
#include "rcar_du_regs.h"
#include "rcar_du_vsp.h"
/* -----------------------------------------------------------------------------
* Format helpers
*/
static const struct rcar_du_format_info rcar_du_format_infos[] = {
{
.fourcc = DRM_FORMAT_RGB565,
.bpp = 16,
.planes = 1,
.pnmr = PnMR_SPIM_TP | PnMR_DDDF_16BPP,
.edf = PnDDCR4_EDF_NONE,
}, {
.fourcc = DRM_FORMAT_ARGB1555,
.bpp = 16,
.planes = 1,
.pnmr = PnMR_SPIM_ALP | PnMR_DDDF_ARGB,
.edf = PnDDCR4_EDF_NONE,
}, {
.fourcc = DRM_FORMAT_XRGB1555,
.bpp = 16,
.planes = 1,
.pnmr = PnMR_SPIM_ALP | PnMR_DDDF_ARGB,
.edf = PnDDCR4_EDF_NONE,
}, {
.fourcc = DRM_FORMAT_XRGB8888,
.bpp = 32,
.planes = 1,
.pnmr = PnMR_SPIM_TP | PnMR_DDDF_16BPP,
.edf = PnDDCR4_EDF_RGB888,
}, {
.fourcc = DRM_FORMAT_ARGB8888,
.bpp = 32,
.planes = 1,
.pnmr = PnMR_SPIM_ALP | PnMR_DDDF_16BPP,
.edf = PnDDCR4_EDF_ARGB8888,
}, {
.fourcc = DRM_FORMAT_UYVY,
.bpp = 16,
.planes = 1,
.pnmr = PnMR_SPIM_TP_OFF | PnMR_DDDF_YC,
.edf = PnDDCR4_EDF_NONE,
}, {
.fourcc = DRM_FORMAT_YUYV,
.bpp = 16,
.planes = 1,
.pnmr = PnMR_SPIM_TP_OFF | PnMR_DDDF_YC,
.edf = PnDDCR4_EDF_NONE,
}, {
.fourcc = DRM_FORMAT_NV12,
.bpp = 12,
.planes = 2,
.pnmr = PnMR_SPIM_TP_OFF | PnMR_DDDF_YC,
.edf = PnDDCR4_EDF_NONE,
}, {
.fourcc = DRM_FORMAT_NV21,
.bpp = 12,
.planes = 2,
.pnmr = PnMR_SPIM_TP_OFF | PnMR_DDDF_YC,
.edf = PnDDCR4_EDF_NONE,
}, {
.fourcc = DRM_FORMAT_NV16,
.bpp = 16,
.planes = 2,
.pnmr = PnMR_SPIM_TP_OFF | PnMR_DDDF_YC,
.edf = PnDDCR4_EDF_NONE,
},
/* The following formats are not supported on Gen2 and thus have no
* associated .pnmr or .edf settings.
*/
{
.fourcc = DRM_FORMAT_NV61,
.bpp = 16,
.planes = 2,
}, {
.fourcc = DRM_FORMAT_YUV420,
.bpp = 12,
.planes = 3,
}, {
.fourcc = DRM_FORMAT_YVU420,
.bpp = 12,
.planes = 3,
}, {
.fourcc = DRM_FORMAT_YUV422,
.bpp = 16,
.planes = 3,
}, {
.fourcc = DRM_FORMAT_YVU422,
.bpp = 16,
.planes = 3,
}, {
.fourcc = DRM_FORMAT_YUV444,
.bpp = 24,
.planes = 3,
}, {
.fourcc = DRM_FORMAT_YVU444,
.bpp = 24,
.planes = 3,
},
};
const struct rcar_du_format_info *rcar_du_format_info(u32 fourcc)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE(rcar_du_format_infos); ++i) {
if (rcar_du_format_infos[i].fourcc == fourcc)
return &rcar_du_format_infos[i];
}
return NULL;
}
/* -----------------------------------------------------------------------------
* Frame buffer
*/
int rcar_du_dumb_create(struct drm_file *file, struct drm_device *dev,
struct drm_mode_create_dumb *args)
{
struct rcar_du_device *rcdu = dev->dev_private;
unsigned int min_pitch = DIV_ROUND_UP(args->width * args->bpp, 8);
unsigned int align;
/* The R8A7779 DU requires a 16 pixels pitch alignment as documented,
* but the R8A7790 DU seems to require a 128 bytes pitch alignment.
*/
if (rcar_du_needs(rcdu, RCAR_DU_QUIRK_ALIGN_128B))
align = 128;
else
align = 16 * args->bpp / 8;
args->pitch = roundup(min_pitch, align);
return drm_gem_cma_dumb_create_internal(file, dev, args);
}
static struct drm_framebuffer *
rcar_du_fb_create(struct drm_device *dev, struct drm_file *file_priv,
const struct drm_mode_fb_cmd2 *mode_cmd)
{
struct rcar_du_device *rcdu = dev->dev_private;
const struct rcar_du_format_info *format;
unsigned int max_pitch;
unsigned int align;
unsigned int bpp;
unsigned int i;
format = rcar_du_format_info(mode_cmd->pixel_format);
if (format == NULL) {
dev_dbg(dev->dev, "unsupported pixel format %08x\n",
mode_cmd->pixel_format);
return ERR_PTR(-EINVAL);
}
/*
* The pitch and alignment constraints are expressed in pixels on the
* hardware side and in bytes in the DRM API.
*/
bpp = format->planes == 1 ? format->bpp / 8 : 1;
max_pitch = 4096 * bpp;
if (rcar_du_needs(rcdu, RCAR_DU_QUIRK_ALIGN_128B))
align = 128;
else
align = 16 * bpp;
if (mode_cmd->pitches[0] & (align - 1) ||
mode_cmd->pitches[0] >= max_pitch) {
dev_dbg(dev->dev, "invalid pitch value %u\n",
mode_cmd->pitches[0]);
return ERR_PTR(-EINVAL);
}
for (i = 1; i < format->planes; ++i) {
if (mode_cmd->pitches[i] != mode_cmd->pitches[0]) {
dev_dbg(dev->dev,
"luma and chroma pitches do not match\n");
return ERR_PTR(-EINVAL);
}
}
return drm_fb_cma_create(dev, file_priv, mode_cmd);
}
static void rcar_du_output_poll_changed(struct drm_device *dev)
{
struct rcar_du_device *rcdu = dev->dev_private;
drm_fbdev_cma_hotplug_event(rcdu->fbdev);
}
/* -----------------------------------------------------------------------------
* Atomic Check and Update
*/
static int rcar_du_atomic_check(struct drm_device *dev,
struct drm_atomic_state *state)
{
struct rcar_du_device *rcdu = dev->dev_private;
int ret;
ret = drm_atomic_helper_check_modeset(dev, state);
if (ret)
return ret;
ret = drm_atomic_normalize_zpos(dev, state);
if (ret)
return ret;
ret = drm_atomic_helper_check_planes(dev, state);
if (ret)
return ret;
if (rcar_du_has(rcdu, RCAR_DU_FEATURE_VSP1_SOURCE))
return 0;
return rcar_du_atomic_check_planes(dev, state);
}
struct rcar_du_commit {
struct work_struct work;
struct drm_device *dev;
struct drm_atomic_state *state;
u32 crtcs;
};
static void rcar_du_atomic_complete(struct rcar_du_commit *commit)
{
struct drm_device *dev = commit->dev;
struct rcar_du_device *rcdu = dev->dev_private;
struct drm_atomic_state *old_state = commit->state;
/* Apply the atomic update. */
drm_atomic_helper_commit_modeset_disables(dev, old_state);
drm_atomic_helper_commit_modeset_enables(dev, old_state);
drm_atomic_helper_commit_planes(dev, old_state,
DRM_PLANE_COMMIT_ACTIVE_ONLY);
drm_atomic_helper_wait_for_vblanks(dev, old_state);
drm_atomic_helper_cleanup_planes(dev, old_state);
drm_atomic_state_put(old_state);
/* Complete the commit, wake up any waiter. */
spin_lock(&rcdu->commit.wait.lock);
rcdu->commit.pending &= ~commit->crtcs;
wake_up_all_locked(&rcdu->commit.wait);
spin_unlock(&rcdu->commit.wait.lock);
kfree(commit);
}
static void rcar_du_atomic_work(struct work_struct *work)
{
struct rcar_du_commit *commit =
container_of(work, struct rcar_du_commit, work);
rcar_du_atomic_complete(commit);
}
static int rcar_du_atomic_commit(struct drm_device *dev,
struct drm_atomic_state *state,
bool nonblock)
{
struct rcar_du_device *rcdu = dev->dev_private;
struct rcar_du_commit *commit;
struct drm_crtc *crtc;
struct drm_crtc_state *crtc_state;
unsigned int i;
int ret;
ret = drm_atomic_helper_prepare_planes(dev, state);
if (ret)
return ret;
/* Allocate the commit object. */
commit = kzalloc(sizeof(*commit), GFP_KERNEL);
if (commit == NULL) {
ret = -ENOMEM;
goto error;
}
INIT_WORK(&commit->work, rcar_du_atomic_work);
commit->dev = dev;
commit->state = state;
/* Wait until all affected CRTCs have completed previous commits and
* mark them as pending.
*/
for_each_crtc_in_state(state, crtc, crtc_state, i)
commit->crtcs |= drm_crtc_mask(crtc);
spin_lock(&rcdu->commit.wait.lock);
ret = wait_event_interruptible_locked(rcdu->commit.wait,
!(rcdu->commit.pending & commit->crtcs));
if (ret == 0)
rcdu->commit.pending |= commit->crtcs;
spin_unlock(&rcdu->commit.wait.lock);
if (ret) {
kfree(commit);
goto error;
}
/* Swap the state, this is the point of no return. */
drm_atomic_helper_swap_state(state, true);
drm_atomic_state_get(state);
if (nonblock)
schedule_work(&commit->work);
else
rcar_du_atomic_complete(commit);
return 0;
error:
drm_atomic_helper_cleanup_planes(dev, state);
return ret;
}
/* -----------------------------------------------------------------------------
* Initialization
*/
static const struct drm_mode_config_funcs rcar_du_mode_config_funcs = {
.fb_create = rcar_du_fb_create,
.output_poll_changed = rcar_du_output_poll_changed,
.atomic_check = rcar_du_atomic_check,
.atomic_commit = rcar_du_atomic_commit,
};
static int rcar_du_encoders_init_one(struct rcar_du_device *rcdu,
enum rcar_du_output output,
struct of_endpoint *ep)
{
static const struct {
const char *compatible;
enum rcar_du_encoder_type type;
} encoders[] = {
{ "adi,adv7123", RCAR_DU_ENCODER_VGA },
{ "adi,adv7511w", RCAR_DU_ENCODER_HDMI },
{ "thine,thc63lvdm83d", RCAR_DU_ENCODER_LVDS },
};
enum rcar_du_encoder_type enc_type = RCAR_DU_ENCODER_NONE;
struct device_node *connector = NULL;
struct device_node *encoder = NULL;
struct device_node *ep_node = NULL;
struct device_node *entity_ep_node;
struct device_node *entity;
int ret;
/*
* Locate the connected entity and infer its type from the number of
* endpoints.
*/
entity = of_graph_get_remote_port_parent(ep->local_node);
if (!entity) {
dev_dbg(rcdu->dev, "unconnected endpoint %s, skipping\n",
ep->local_node->full_name);
return -ENODEV;
}
entity_ep_node = of_parse_phandle(ep->local_node, "remote-endpoint", 0);
for_each_endpoint_of_node(entity, ep_node) {
if (ep_node == entity_ep_node)
continue;
/*
* We've found one endpoint other than the input, this must
* be an encoder. Locate the connector.
*/
encoder = entity;
connector = of_graph_get_remote_port_parent(ep_node);
of_node_put(ep_node);
if (!connector) {
dev_warn(rcdu->dev,
"no connector for encoder %s, skipping\n",
encoder->full_name);
of_node_put(entity_ep_node);
of_node_put(encoder);
return -ENODEV;
}
break;
}
of_node_put(entity_ep_node);
if (encoder) {
/*
* If an encoder has been found, get its type based on its
* compatible string.
*/
unsigned int i;
for (i = 0; i < ARRAY_SIZE(encoders); ++i) {
if (of_device_is_compatible(encoder,
encoders[i].compatible)) {
enc_type = encoders[i].type;
break;
}
}
if (i == ARRAY_SIZE(encoders)) {
dev_warn(rcdu->dev,
"unknown encoder type for %s, skipping\n",
encoder->full_name);
of_node_put(encoder);
of_node_put(connector);
return -EINVAL;
}
} else {
/*
* If no encoder has been found the entity must be the
* connector.
*/
connector = entity;
}
ret = rcar_du_encoder_init(rcdu, enc_type, output, encoder, connector);
if (ret && ret != -EPROBE_DEFER)
dev_warn(rcdu->dev,
"failed to initialize encoder %s on output %u (%d), skipping\n",
of_node_full_name(encoder), output, ret);
of_node_put(encoder);
of_node_put(connector);
return ret;
}
static int rcar_du_encoders_init(struct rcar_du_device *rcdu)
{
struct device_node *np = rcdu->dev->of_node;
struct device_node *ep_node;
unsigned int num_encoders = 0;
/*
* Iterate over the endpoints and create one encoder for each output
* pipeline.
*/
for_each_endpoint_of_node(np, ep_node) {
enum rcar_du_output output;
struct of_endpoint ep;
unsigned int i;
int ret;
ret = of_graph_parse_endpoint(ep_node, &ep);
if (ret < 0) {
of_node_put(ep_node);
return ret;
}
/* Find the output route corresponding to the port number. */
for (i = 0; i < RCAR_DU_OUTPUT_MAX; ++i) {
if (rcdu->info->routes[i].possible_crtcs &&
rcdu->info->routes[i].port == ep.port) {
output = i;
break;
}
}
if (i == RCAR_DU_OUTPUT_MAX) {
dev_warn(rcdu->dev,
"port %u references unexisting output, skipping\n",
ep.port);
continue;
}
/* Process the output pipeline. */
ret = rcar_du_encoders_init_one(rcdu, output, &ep);
if (ret < 0) {
if (ret == -EPROBE_DEFER) {
of_node_put(ep_node);
return ret;
}
continue;
}
num_encoders++;
}
return num_encoders;
}
static int rcar_du_properties_init(struct rcar_du_device *rcdu)
{
rcdu->props.alpha =
drm_property_create_range(rcdu->ddev, 0, "alpha", 0, 255);
if (rcdu->props.alpha == NULL)
return -ENOMEM;
/* The color key is expressed as an RGB888 triplet stored in a 32-bit
* integer in XRGB8888 format. Bit 24 is used as a flag to disable (0)
* or enable source color keying (1).
*/
rcdu->props.colorkey =
drm_property_create_range(rcdu->ddev, 0, "colorkey",
0, 0x01ffffff);
if (rcdu->props.colorkey == NULL)
return -ENOMEM;
return 0;
}
int rcar_du_modeset_init(struct rcar_du_device *rcdu)
{
static const unsigned int mmio_offsets[] = {
DU0_REG_OFFSET, DU2_REG_OFFSET
};
struct drm_device *dev = rcdu->ddev;
struct drm_encoder *encoder;
struct drm_fbdev_cma *fbdev;
unsigned int num_encoders;
unsigned int num_groups;
unsigned int i;
int ret;
drm_mode_config_init(dev);
dev->mode_config.min_width = 0;
dev->mode_config.min_height = 0;
dev->mode_config.max_width = 4095;
dev->mode_config.max_height = 2047;
dev->mode_config.funcs = &rcar_du_mode_config_funcs;
rcdu->num_crtcs = rcdu->info->num_crtcs;
ret = rcar_du_properties_init(rcdu);
if (ret < 0)
return ret;
/* Initialize vertical blanking interrupts handling. Start with vblank
* disabled for all CRTCs.
*/
ret = drm_vblank_init(dev, (1 << rcdu->info->num_crtcs) - 1);
if (ret < 0)
return ret;
/* Initialize the groups. */
num_groups = DIV_ROUND_UP(rcdu->num_crtcs, 2);
for (i = 0; i < num_groups; ++i) {
struct rcar_du_group *rgrp = &rcdu->groups[i];
mutex_init(&rgrp->lock);
rgrp->dev = rcdu;
rgrp->mmio_offset = mmio_offsets[i];
rgrp->index = i;
rgrp->num_crtcs = min(rcdu->num_crtcs - 2 * i, 2U);
/* If we have more than one CRTCs in this group pre-associate
* the low-order planes with CRTC 0 and the high-order planes
* with CRTC 1 to minimize flicker occurring when the
* association is changed.
*/
rgrp->dptsr_planes = rgrp->num_crtcs > 1
? (rcdu->info->gen >= 3 ? 0x04 : 0xf0)
: 0;
if (!rcar_du_has(rcdu, RCAR_DU_FEATURE_VSP1_SOURCE)) {
ret = rcar_du_planes_init(rgrp);
if (ret < 0)
return ret;
}
}
/* Initialize the compositors. */
if (rcar_du_has(rcdu, RCAR_DU_FEATURE_VSP1_SOURCE)) {
for (i = 0; i < rcdu->num_crtcs; ++i) {
struct rcar_du_vsp *vsp = &rcdu->vsps[i];
vsp->index = i;
vsp->dev = rcdu;
rcdu->crtcs[i].vsp = vsp;
ret = rcar_du_vsp_init(vsp);
if (ret < 0)
return ret;
}
}
/* Create the CRTCs. */
for (i = 0; i < rcdu->num_crtcs; ++i) {
struct rcar_du_group *rgrp = &rcdu->groups[i / 2];
ret = rcar_du_crtc_create(rgrp, i);
if (ret < 0)
return ret;
}
/* Initialize the encoders. */
ret = rcar_du_lvdsenc_init(rcdu);
if (ret < 0)
return ret;
ret = rcar_du_encoders_init(rcdu);
if (ret < 0)
return ret;
if (ret == 0) {
dev_err(rcdu->dev, "error: no encoder could be initialized\n");
return -EINVAL;
}
num_encoders = ret;
/* Set the possible CRTCs and possible clones. There's always at least
* one way for all encoders to clone each other, set all bits in the
* possible clones field.
*/
list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
struct rcar_du_encoder *renc = to_rcar_encoder(encoder);
const struct rcar_du_output_routing *route =
&rcdu->info->routes[renc->output];
encoder->possible_crtcs = route->possible_crtcs;
encoder->possible_clones = (1 << num_encoders) - 1;
}
drm_mode_config_reset(dev);
drm_kms_helper_poll_init(dev);
if (dev->mode_config.num_connector) {
fbdev = drm_fbdev_cma_init(dev, 32,
dev->mode_config.num_connector);
if (IS_ERR(fbdev))
return PTR_ERR(fbdev);
rcdu->fbdev = fbdev;
} else {
dev_info(rcdu->dev,
"no connector found, disabling fbdev emulation\n");
}
return 0;
}
|
{
"pile_set_name": "Github"
}
|
/*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
object nuTilda;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 2 -1 0 0 0 0];
internalField uniform 0;
boundaryField
{
axis
{
type empty;
}
inlet
{
type fixedValue;
value uniform 0;
}
walls
{
type fixedValue;
value uniform 0;
}
atmosphere
{
type inletOutlet;
inletValue uniform 0;
value uniform 0;
}
front
{
type wedge;
}
back
{
type wedge;
}
}
// ************************************************************************* //
|
{
"pile_set_name": "Github"
}
|
{
"index": 9,
"lineNumber": 1,
"column": 10,
"message": "Error: Line 1: Unexpected token ."
}
|
{
"pile_set_name": "Github"
}
|
"""
Example to show how to draw basic shapes using OpenCV (2)
"""
# Import required packages:
import cv2
import numpy as np
import matplotlib.pyplot as plt
def show_with_matplotlib(img, title):
"""Shows an image using matplotlib capabilities"""
# Convert BGR image to RGB:
img_RGB = img[:, :, ::-1]
# Show the image using matplotlib:
plt.imshow(img_RGB)
plt.title(title)
plt.show()
# Dictionary containing some colors:
colors = {'blue': (255, 0, 0), 'green': (0, 255, 0), 'red': (0, 0, 255), 'yellow': (0, 255, 255),
'magenta': (255, 0, 255), 'cyan': (255, 255, 0), 'white': (255, 255, 255), 'black': (0, 0, 0),
'gray': (125, 125, 125), 'rand': np.random.randint(0, high=256, size=(3,)).tolist(),
'dark_gray': (50, 50, 50), 'light_gray': (220, 220, 220)}
# We create the canvas to draw: 300 x 300 pixels, 3 channels, uint8 (8-bit unsigned integers)
# We set background to black using np.zeros():
image = np.zeros((300, 300, 3), dtype="uint8")
# If you want another background color you can do the following:
image[:] = colors['light_gray']
# 1. We are going to see how cv2.clipLine() works
# Draw a rectangle and a line:
cv2.line(image, (0, 0), (300, 300), colors['green'], 3)
cv2.rectangle(image, (0, 0), (100, 100), colors['blue'], 3)
# We call the function cv2.clipLine():
ret, p1, p2 = cv2.clipLine((0, 0, 100, 100), (0, 0), (300, 300))
# cv2.clipLine() returns False if the line is outside the rectangle
# And returns True otherwise
if ret:
cv2.line(image, p1, p2, colors['yellow'], 3)
# Show image:
show_with_matplotlib(image, 'cv2.clipLine()')
# Clean the canvas to draw again:
image[:] = colors['light_gray']
# 2. We are going to see how cv2.arrowedLine() works:
cv2.arrowedLine(image, (50, 50), (200, 50), colors['red'], 3, 8, 0, 0.1)
cv2.arrowedLine(image, (50, 120), (200, 120), colors['green'], 3, cv2.LINE_AA, 0, 0.3)
cv2.arrowedLine(image, (50, 200), (200, 200), colors['blue'], 3, 8, 0, 0.3)
# Show image:
show_with_matplotlib(image, 'cv2.arrowedLine()')
# Clean the canvas to draw again:
image[:] = colors['light_gray']
# 3. We are going to see how cv2.ellipse() works:
cv2.ellipse(image, (80, 80), (60, 40), 0, 0, 360, colors['red'], -1)
cv2.ellipse(image, (80, 200), (80, 40), 0, 0, 360, colors['green'], 3)
cv2.ellipse(image, (80, 200), (10, 40), 0, 0, 360, colors['blue'], 3)
cv2.ellipse(image, (200, 200), (10, 40), 0, 0, 180, colors['yellow'], 3)
cv2.ellipse(image, (200, 100), (10, 40), 0, 0, 270, colors['cyan'], 3)
cv2.ellipse(image, (250, 250), (30, 30), 0, 0, 360, colors['magenta'], 3)
cv2.ellipse(image, (250, 100), (20, 40), 45, 0, 360, colors['gray'], 3)
# Show image:
show_with_matplotlib(image, 'cv2.ellipse()')
# Clean the canvas to draw again:
image[:] = colors['light_gray']
# 4. We are going to draw several polylines
# These points define a triangle:
pts = np.array([[250, 5], [220, 80], [280, 80]], np.int32)
# Reshape to shape (number_vertex, 1, 2)
pts = pts.reshape((-1, 1, 2))
# Print the shapes: this line is not necessary, only for visualization:
print("shape of pts '{}'".format(pts.shape))
# Draw this polygon with True option:
cv2.polylines(image, [pts], True, colors['green'], 3)
# These points define a triangle:
pts = np.array([[250, 105], [220, 180], [280, 180]], np.int32)
# Reshape to shape (number_vertex, 1, 2)
pts = pts.reshape((-1, 1, 2))
# Print the shapes:
print("shape of pts '{}'".format(pts.shape))
# Draw this polygon with False option:
cv2.polylines(image, [pts], False, colors['green'], 3)
# These points define a pentagon:
pts = np.array([[20, 90], [60, 60], [100, 90], [80, 130], [40, 130]], np.int32)
# Reshape to shape (number_vertex, 1, 2)
pts = pts.reshape((-1, 1, 2))
# Print the shapes:
print("shape of pts '{}'".format(pts.shape))
# Draw this polygon with True option:
cv2.polylines(image, [pts], True, colors['blue'], 3)
# These points define a pentagon:
pts = np.array([[20, 180], [60, 150], [100, 180], [80, 220], [40, 220]], np.int32)
# Reshape to shape (number_vertex, 1, 2)
pts = pts.reshape((-1, 1, 2))
# Print the shapes:
print("shape of pts '{}'".format(pts.shape))
# Draw this polygon with False option:
cv2.polylines(image, [pts], False, colors['blue'], 3)
# These points define a rectangle:
pts = np.array([[150, 100], [200, 100], [200, 150], [150, 150]], np.int32)
# Reshape to shape (number_vertex, 1, 2)
pts = pts.reshape((-1, 1, 2))
# Print the shapes:
print("shape of pts '{}'".format(pts.shape))
# Draw this polygon with False option:
cv2.polylines(image, [pts], True, colors['yellow'], 3)
# These points define a rectangle:
pts = np.array([[150, 200], [200, 200], [200, 250], [150, 250]], np.int32)
# Reshape to shape (number_vertex, 1, 2)
pts = pts.reshape((-1, 1, 2))
# Print the shapes:
print("shape of pts '{}'".format(pts.shape))
# Draw this polygon with False option:
cv2.polylines(image, [pts], False, colors['yellow'], 3)
# Show image:
show_with_matplotlib(image, 'cv2.polylines()')
|
{
"pile_set_name": "Github"
}
|
/*
Copyright (c) 2017 TOSHIBA Digital Solutions Corporation
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.toshiba.mwcloud.gs;
import java.io.Closeable;
/**
* <div lang="ja">
* クエリ実行より求めたロウの集合を管理します。
*
* <p>ロウ単位・ロウフィールド単位での操作機能を持ち、対象とするロウを
* 指し示すための、{@link java.sql.ResultSet}と同様のカーソル状態を保持します。
* 初期状態のカーソルは、ロウ集合の先頭より手前に位置しています。</p>
* </div><div lang="en">
* Manages a set of Rows obtained by executing a query.
*
* <p>It has a function of per-Row and per-Row-field manipulation and holds a cursor state similar to
* {@link java.sql.ResultSet} to specify a target Row. The cursor is initially located just before the head of
* a Row set.</p>
* </div>
*/
public interface RowSet<R> extends Closeable {
/**
* <div lang="ja">
* 現在のカーソル位置を基準として、ロウ集合内に後続のロウが存在するかどうかを
* 取得します。
*
* @throws GSException 現バージョンでは送出されない
* </div><div lang="en">
* Returns TRUE if a Row set has at least one Row ahead of the current cursor position.
*
* @throws GSException It will not be thrown in the current version.
* </div>
*/
public boolean hasNext() throws GSException;
/**
* <div lang="ja">
* ロウ集合内の後続のロウにカーソル移動し、移動後の位置にあるロウオブジェクトを
* 取得します。
*
* <p>{@link FetchOption#PARTIAL_EXECUTION}が有効に設定されていた場合、
* クエリ実行処理の続きを行う場合があります。</p>
*
* @throws GSException 対象位置のロウが存在しない場合
* @throws GSException 接続障害によりロウオブジェクトの生成に失敗した場合
* @throws GSException この処理または関連するトランザクションのタイムアウト、
* 対応するコンテナの削除もしくはスキーマ変更、接続障害が発生した場合
* @throws GSException このオブジェクトまたは対応する{@link Container}の
* クローズ後に呼び出された場合
* </div><div lang="en">
* Moves the cursor to the next Row in a Row set and returns the Row object at the moved position.
*
* <p>When {@link FetchOption#PARTIAL_EXECUTION} has been set
* to be effective, the continuation of the query execution may
* be executed in this method.</p>
*
* @throws GSException if there is no Row at the cursor position.
* @throws GSException if a connection failure caused an error in creation of a Row object
* @throws GSException when there is a timeout of transaction for this processing or of related processing, the target container has been deleted, its schema has been changed or there is a connection failure.
* @throws GSException if called after this object or the relevant {@link Container} is closed.
* </div>
*/
public R next() throws GSException;
/**
* <div lang="ja">
* 現在のカーソル位置のロウを削除します。
*
* <p>ロックを有効にして取得した{@link RowSet}に対してのみ使用できます。
* また、{@link Container#remove(Object)}と同様、
* コンテナの種別ならびに設定によっては、さらに制限が設けられています。</p>
*
* @throws GSException 対象位置のロウが存在しない場合
* @throws GSException ロックを有効にせずに取得した{@link RowSet}に対して
* 呼び出された場合
* @throws GSException 特定コンテナ固有の制限に反する操作を行った場合
* @throws GSException この処理または関連するトランザクションのタイムアウト、
* 対応するコンテナの削除もしくはスキーマ変更、接続障害が発生した場合
* @throws GSException このオブジェクトまたは対応する{@link Container}の
* クローズ後に呼び出された場合
* </div><div lang="en">
* Deletes the Row at the current cursor position.
*
* <p>It can be used only for {@link RowSet} obtained with locking enabled. Like {@link Container#remove(Object)},
* further limitations are placed depending on the type and settings of a Container.
*
* @throws GSException if there is no Row at the cursor position.
* @throws GSException If called on {@link RowSet} obtained without locking enabled.
* @throws GSException if its operation is contrary to the restrictions specific to a particular Container.
* @throws GSException if a timeout occurs during this operation or its related transaction, the relevant Container
* is deleted, its schema is changed or a connection failure occurs.
* @throws GSException if called after this object or the relevant {@link Container} is closed.
* </div>
*/
void remove() throws GSException;
/**
* <div lang="ja">
* 現在のカーソル位置のロウについて、指定のロウオブジェクトを使用してロウキー
* 以外の値を更新します。
*
* <p>{@code null}は指定できません。指定のロウオブジェクトに含まれるロウキーは
* 無視されます。</p>
*
* <p>ロックを有効にして取得した{@link RowSet}に対してのみ使用できます。
* また、{@link Container#put(Object, Object)}と同様、
* コンテナの種別ならびに設定によっては、さらに制限が設けられています。</p>
*
* @throws GSException 対象位置のロウが存在しない場合
* @throws GSException ロックを有効にせずに取得した{@link RowSet}に対して
* 呼び出された場合
* @throws GSException 特定コンテナ固有の制限に反する操作を行った場合
* @throws GSException この処理または関連するトランザクションのタイムアウト、
* 対応するンテナの削除もしくはスキーマ変更、接続障害が発生した場合
* @throws GSException このオブジェクトまたは対応する{@link Container}の
* クローズ後に呼び出された場合
* @throws ClassCastException 指定のロウオブジェクトがマッピング処理で使用される
* ロウオブジェクトの型と対応しない場合
* @throws NullPointerException 引数に{@code null}が指定された場合。
* また、ロウフィールドに対応するロウオブジェクト内のオブジェクトが1つ以上存在しない場合
* </div><div lang="en">
* Updates the values except a Row key of the Row at the cursor position, using the specified Row object.
*
* <p>{@code null} cannot be specified. The Row key contained in the specified Row object is ignored.</p>
*
* <p>It can be used only for{@link RowSet} obtained with locking enabled.
* Like {@link Container#put(Object, Object)}, further limitations are placed depending on the type and settings of
* a Container.
*
* @throws GSException if there is no Row at the cursor position.
* @throws GSException If called on {@link RowSet} obtained without locking enabled.
* @throws GSException if its operation is contrary to the restrictions specific to a particular Container.
* @throws GSException if a timeout occurs during this operation or its related transaction, the relevant Container
* is deleted, its schema is changed or a connection failure occurs.
* @throws GSException if called after this object or the relevant {@link Container} is closed.
* @throws ClassCastException if the specified Row object does not match the value types of the Row object used in
* mapping operation.
* @throws NullPointerException If a {@code null} parameter is specified;
* or if no object exists in the Row object which corresponds to the Row field.
* </div>
*/
public void update(R rowObj) throws GSException;
/**
* <div lang="ja">
* サイズ、すなわちロウ集合作成時点におけるロウの数を取得します。
*
* <p>{@link FetchOption#PARTIAL_EXECUTION}が有効に設定されていた場合、
* クエリ実行処理の進行状況によらず、結果を求めることはできません。</p>
*
* @throws IllegalStateException オプション設定の影響によりロウの数を取得
* できない場合
*
* </div><div lang="en">
* Returns the size, namely the number of Rows at the time of creating a Row set.
*
* <p>If {@link FetchOption#PARTIAL_EXECUTION} has been set to
* be effective, the result cannot be obtained despite
* the status of the query processing progress.</p>
*
* @throws IllegalStateException if the number of rows cannot be obtained by the option setting.
* </div>
*/
public int size();
/**
* <div lang="ja">
* 関連するリソースを適宜解放します。
*
* @throws GSException 現バージョンでは送出されない
*
* @see Closeable#close()
* </div><div lang="en">
* Releases related resources as necessary.
*
* @throws GSException It will not be thrown in the current version.
*
* @see Closeable#close()
* </div>
*/
public void close() throws GSException;
}
|
{
"pile_set_name": "Github"
}
|
// @file bnorm_cpu.cpp
// @brief Batch normalization implementation (CPU)
// @author Sebastien Ehrhardt
// @author Andrea Vedaldi
/*
Copyright (C) 2015 Sebastien Ehrhardt and Andrea Vedaldi.
All rights reserved.
This file is part of the VLFeat library and is made available under
the terms of the BSD license (see the COPYING file).
*/
#include "bnorm.hpp"
#include "../data.hpp"
#include <math.h>
#include <memory.h>
#include <cstdlib>
#include <algorithm>
#include <limits>
#include <cassert>
/* ---------------------------------------------------------------- */
/* compute_moments, compute_ders, compute_ders_and_moments */
/* ---------------------------------------------------------------- */
// Compute moments (means and sigmas) from the batch data
// WH is the product of the data width and height
// moments is a 2 x depth array with means and sigmas
template<typename T> inline void
compute_moments(T * moments,
T const * data,
int WH,
int depth,
int num,
T epsilon)
{
int mass = WH * num ;
for(int channel = 0; channel < depth; ++channel) {
for(int element = 0; element < num; ++element) {
for(int wh = 0; wh < WH; ++wh){
T x = data[wh + channel*WH + element*(depth*WH)] ;
moments[channel] += x ; // mean
moments[channel + depth] += x * x; // sigma
}
}
}
for(int i = 0; i < depth; ++i) {
moments[i] /= mass;
moments[i + depth] = sqrt(moments[i + depth]/mass
- moments[i]*moments[i] + epsilon);
}
}
// this version assumes that moments is precomputed
template<typename T> inline void
compute_ders(T * derMultipliers,
T * derBiases,
T const * moments,
T const * data,
T const * derOutput,
int WH, int depth, int num,
T epsilon)
{
memset(derMultipliers, 0, sizeof(T) * depth) ;
memset(derBiases, 0, sizeof(T) * depth) ;
for(int channel = 0; channel < depth; ++channel){
for(int element = 0; element < num; ++element ){
for(int wh = 0; wh < WH; ++wh){
int offset = wh + channel*WH + element * (WH*depth) ;
derMultipliers[channel] += derOutput[offset] * data[offset];
derBiases[channel] += derOutput[offset];
}
}
}
T mass = WH*num;
for(int i = 0; i < depth; ++i) {
T mean = moments[i] ;
T sigma = moments[i + depth] ;
derMultipliers[i] = (derMultipliers[i] - mean*derBiases[i]) / sigma;
}
}
template<typename T> inline void
compute_ders_and_moments(T * derMultipliers,
T * derBiases,
T * moments,
T const * data,
T const * derOutput,
int WH, int depth, int num,
T epsilon)
{
memset(derMultipliers, 0, sizeof(T) * depth) ;
memset(derBiases, 0, sizeof(T) * depth) ;
for(int channel = 0; channel < depth; ++channel){
for(int element = 0; element < num; ++element ){
for(int wh = 0; wh < WH; ++wh){
int offset = wh + channel*WH + element * (WH*depth) ;
moments[channel] += data[offset] ;
moments[channel + depth] += data[offset] * data[offset];
derMultipliers[channel] += derOutput[offset] * data[offset];
derBiases[channel] += derOutput[offset];
}
}
}
T mass = WH*num;
for(int i = 0; i < depth; ++i) {
T mean = moments[i] /= mass ;
T sigma = sqrt(moments[i + depth]/mass - mean*mean + epsilon);
moments[i] = mean ;
moments[i + depth] = sigma ;
derMultipliers[i] = (derMultipliers[i] - mean*derBiases[i]) / sigma;
}
}
/* ---------------------------------------------------------------- */
/* batch_normalize_backward */
/* ---------------------------------------------------------------- */
template<typename T> inline void
batch_normalize_backward(T * derData,
T const * moments,
T const * data,
T const * multipliers,
T const * derMultipliers,
T const * derBiases,
T const * derOutput,
int WH,
int depth,
int num)
{
T mass = WH*num;
for(int channel = 0; channel < depth; ++channel ) {
T mean = moments[channel] ;
T sigma = moments[channel + depth] ;
T muz = derBiases[channel]/mass;
T G1 = multipliers[channel]/sigma ;
T G2 = G1 * derMultipliers[channel]/(mass*sigma);
for(int element = 0; element < num; ++element){
for(int wh = 0; wh < WH; ++wh){
int offset = wh + channel*WH + element * (WH*depth) ;
derData[offset] = G1 * (derOutput[offset] - muz) - G2 * (data[offset]-mean) ;
}
}
}
}
/* ---------------------------------------------------------------- */
/* bnorm functions */
/* ---------------------------------------------------------------- */
namespace vl { namespace impl {
template<typename T>
struct bnorm<vl::CPU,T>
{
/* ------------------------------------------------------------ */
/* forward */
/* ------------------------------------------------------------ */
static vl::Error
forward_given_moments(Context& context,
T* output,
T const* moments,
T const* data,
T const* multipliers,
T const* biases,
int height, int width, int depth, int num)
{
int WH = height * width ;
for(int channel = 0; channel < depth; ++channel) {
T mean = moments[channel] ;
T sigma = moments[channel + depth] ;
T bias = biases[channel];
T coefficient = multipliers[channel] / sigma ;
for(int element = 0; element < num; ++element) {
for(int wh = 0; wh < WH; ++wh){
int offset = wh + channel*WH + element * (depth*WH) ;
output[offset] = coefficient * (data[offset] - mean) + bias ;
}
}
}
return vlSuccess;
}
static vl::Error
forward(Context& context,
T* output,
T* moments,
T const* data,
T const* multipliers,
T const* biases,
int height, int width, int depth, int size,
T epsilon)
{
vl::Error error = vlSuccess ;
bool ownMoments = false ;
if (moments == NULL) {
moments = (T*)calloc(sizeof(T),2*depth);
if (!moments) {
error = vlErrorOutOfMemory ;
goto done ;
}
ownMoments = true ;
} else {
memset(moments, 0, sizeof(T) * 2*depth) ;
}
compute_moments<T>(moments,
data, width*height, depth, size,
epsilon) ;
error = bnorm<vl::CPU,T>::forward_given_moments
(context,
output,
moments, data,
multipliers, biases,
height, width, depth, size) ;
// Delete intermediate variable
done:
if (ownMoments) { free(moments) ; }
return error ;
}
/*------------------------------------------------------------- */
/* backward */
/* ------------------------------------------------------------ */
static vl::Error
backward_given_moments(Context& context,
T* derData,
T* derMultipliers,
T* derBiases,
T const* moments,
T const* data,
T const* multipliers,
T const* biases,
T const* derOutput,
int height, int width, int depth, int size,
T epsilon)
{
vl::Error error = vlSuccess ;
T * muz;
int WH = width * height;
// Allocate muz
muz = (T*)calloc(sizeof(T),depth);
if (!muz) {
error = vlErrorOutOfMemory ;
goto done ;
}
// Compute derMultipliers, derBiases, muz, and moments
compute_ders<T>(derMultipliers, derBiases,
moments, data, derOutput,
WH, depth, size,
epsilon);
// Compute derData
batch_normalize_backward<T>(derData,
moments, data, muz,
multipliers, derMultipliers, derOutput,
WH, depth, size);
done:;
if (muz) { free(muz) ; }
return error ;
}
static vl::Error
backward(Context& context,
T* derData,
T* derMultipliers,
T* derBiases,
T* moments,
T const* data,
T const* multipliers,
T const* biases,
T const* derOutput,
int height, int width, int depth, int size,
float epsilon)
{
vl::Error error = vlSuccess ;
T* muz = NULL ;
bool ownMoments = false ;
int WH = width * height;
// Allocate or reuse moments
if (moments == NULL) {
moments = (T*)calloc(sizeof(T),2*depth);
if (!moments) {
error = vlErrorOutOfMemory ;
goto done ;
}
ownMoments = true ;
} else {
memset(moments, 0, sizeof(T) * 2*depth) ;
}
// Compute derMultipliers, derBiases, and moments
compute_ders_and_moments<T>(derMultipliers, derBiases, moments,
data, derOutput,
WH, depth, size,
epsilon);
// Compute derData
batch_normalize_backward<T>(derData,
moments, data,
multipliers,
derMultipliers, derBiases, derOutput,
WH, depth, size);
// Delete intermediate variable
done:;
if (ownMoments) { free(moments) ; }
return error ;
}
} ;
} } // namespace vl::impl
template struct vl::impl::bnorm<vl::CPU, float> ;
|
{
"pile_set_name": "Github"
}
|
fileFormatVersion: 2
guid: 197606a9fb7b52147ae7f99ff5696833
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
|
{
"pile_set_name": "Github"
}
|
<HTML>
<HEAD>
<meta charset="UTF-8">
<title>GACardNetwork.MASTERCARD - tock</title>
<link rel="stylesheet" href="../../../style.css">
</HEAD>
<BODY>
<a href="../../index.html">tock</a> / <a href="../index.html">ai.tock.bot.connector.ga.model.response</a> / <a href="index.html">GACardNetwork</a> / <a href="./-m-a-s-t-e-r-c-a-r-d.html">MASTERCARD</a><br/>
<br/>
<h1>MASTERCARD</h1>
<a name="ai.tock.bot.connector.ga.model.response.GACardNetwork.MASTERCARD"></a>
<code><span class="identifier">MASTERCARD</span></code> <a href="https://github.com/theopenconversationkit/tock/blob/master/bot/connector-ga/src/main/kotlin/model/response/GACardNetwork.kt#L27">(source)</a>
</BODY>
</HTML>
|
{
"pile_set_name": "Github"
}
|
"use strict";var exports=module.exports={};require('../../modules/es6.object.create.js');
var $Object = require('../../modules/_core.js').Object;
module.exports = function create(P, D){
return $Object.create(P, D);
};
|
{
"pile_set_name": "Github"
}
|
using Git.Framework.Controller;
using Git.Framework.DataTypes;
using Git.Framework.DataTypes.ExtensionMethods;
using Git.Storage.Common;
using Git.Storage.Common.Enum;
using Git.Storage.Entity.Move;
using Git.WMS.Sdk;
using Git.WMS.Sdk.ApiName;
using Git.WMS.Web.Lib;
using Git.WMS.Web.Lib.Filter;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Git.WMS.Web.Areas.Order.Controllers
{
public class MoveAjaxController : AjaxPage
{
/// <summary>
/// 新增或编辑移库单
/// </summary>
/// <returns></returns>
[LoginAjaxFilter]
public ActionResult Add()
{
MoveOrderEntity entity = WebUtil.GetFormObject<MoveOrderEntity>("Entity");
List<MoveOrderDetailEntity> listDetail = Session[SessionKey.SESSION_MOVE_DETAIL] as List<MoveOrderDetailEntity>;
string CompanyID = this.CompanyID;
if (listDetail.IsNullOrEmpty())
{
DataResult<string> dataResult = new DataResult<string>() { Code = (int)EResponseCode.Exception, Message = "请选择要移库的产品" };
return Content(JsonHelper.SerializeObject(dataResult));
}
string ApiName = MoveApiName.MoveApiName_Add;
if (!entity.SnNum.IsEmpty())
{
ApiName = MoveApiName.MoveApiName_Edit;
}
entity.CreateUser = this.LoginUser.UserNum;
entity.CreateTime = DateTime.Now;
entity.IsDelete = (int)EIsDelete.NotDelete;
entity.Status = (int)EAudite.Wait;
entity.CompanyID = CompanyID;
entity.StorageNum = this.DefaultStorageNum;
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("CompanyID", CompanyID);
dic.Add("Entity", JsonConvert.SerializeObject(entity));
dic.Add("List", JsonConvert.SerializeObject(listDetail));
ITopClient client = new TopClientDefault();
string result = client.Execute(ApiName, dic);
return Content(result);
}
/// <summary>
/// 加载移库单详细
/// </summary>
/// <returns></returns>
[LoginAjaxFilter(true,false)]
public ActionResult LoadDetail()
{
List<MoveOrderDetailEntity> listDetail = Session[SessionKey.SESSION_MOVE_DETAIL] as List<MoveOrderDetailEntity>;
listDetail = listDetail.IsNull() ? new List<MoveOrderDetailEntity>() : listDetail;
int PageIndex = WebUtil.GetFormValue<int>("PageIndex", 1);
int PageSize = WebUtil.GetFormValue<int>("PageSize", 5);
PageInfo pageInfo = new PageInfo() { PageIndex = PageIndex, PageSize = PageSize };
List<MoveOrderDetailEntity> listResult = listDetail.Skip((pageInfo.PageIndex - 1) * pageInfo.PageSize).Take(pageInfo.PageSize).ToList();
pageInfo.RowCount = listDetail.Count;
DataListResult<MoveOrderDetailEntity> dataResult = new DataListResult<MoveOrderDetailEntity>()
{
Code = (int)EResponseCode.Success,
Message = "响应成功",
Result = listResult,
PageInfo = pageInfo
};
return Content(JsonHelper.SerializeObject(dataResult));
}
/// <summary>
/// 新增产品
/// </summary>
/// <returns></returns>
[LoginAjaxFilter(true,false)]
public ActionResult AddProduct()
{
List<MoveOrderDetailEntity> listDetail = Session[SessionKey.SESSION_MOVE_DETAIL] as List<MoveOrderDetailEntity>;
listDetail = listDetail.IsNull() ? new List<MoveOrderDetailEntity>() : listDetail;
List<MoveOrderDetailEntity> list = WebUtil.GetFormObject<List<MoveOrderDetailEntity>>("List");
if (!list.IsNullOrEmpty())
{
list.ForEach(a =>
{
a.SnNum = ConvertHelper.NewGuid();
a.Amount = a.InPrice * a.Num;
a.CompanyID = this.CompanyID;
listDetail.Add(a);
});
}
Session[SessionKey.SESSION_MOVE_DETAIL] = listDetail;
DataResult dataResult = new DataResult()
{
Code = (int)EResponseCode.Success,
Message = "响应成功"
};
return Content(JsonHelper.SerializeObject(dataResult));
}
/// <summary>
/// 删除产品
/// </summary>
/// <returns></returns>
[LoginAjaxFilter(true,false)]
public ActionResult DelProduct()
{
List<MoveOrderDetailEntity> listDetail = Session[SessionKey.SESSION_MOVE_DETAIL] as List<MoveOrderDetailEntity>;
listDetail = listDetail.IsNull() ? new List<MoveOrderDetailEntity>() : listDetail;
string SnNum = WebUtil.GetFormValue<string>("SnNum");
if (!SnNum.IsEmpty())
{
listDetail.Remove(a => a.SnNum == SnNum);
}
Session[SessionKey.SESSION_MOVE_DETAIL] = listDetail;
DataResult dataResult = new DataResult()
{
Code = (int)EResponseCode.Success,
Message = "响应成功"
};
return Content(JsonHelper.SerializeObject(dataResult));
}
}
}
|
{
"pile_set_name": "Github"
}
|
/* HTML Elements */
html, body { margin: 0; padding: 0; }
body { font: 90% "Verdana", "Arial", "Helvetica", sans-serif; }
img { border: none; padding: 0; margin: 0;}
table { font: 1em "Verdana", "Arial", "Helvetica", sans-serif; }
h1 { font-size: 1.8em; font-weight: bold; }
h2 { font-size: 1.5em; font-weight: bold; }
h3 { font-size: 1.2em; font-weight: bold; }
h4 { font-size: 1em; font-weight: bold; }
ul.across { width: 100%; display: block; list-style: none; }
ul.across li { float: left; display: block; width: 9em }
/* Masthead and Main Menu */
#header { margin: 0; padding: 0; width: 100%; }
#header img { border: none; padding: 0; margin: 0;}
#header #logo { margin: 0; padding: 0; position: absolute; top: 15px; left: 15px}
#header #nav { min-width: 670px; margin: 25px 0 10px 200px; padding: 15px 0 15px 5px;
border-top: 1px solid black; border-bottom: 1px solid black; border-left: 1px solid black;
white-space: nowrap; }
/* Hide from IE-mac \*/
* html #nav { height: 1%; }
/* End of IE-mac hack */
#nav a{ text-decoration: none; color: #000; font: small "Times New Roman", Roman, serif;
text-transform: uppercase; margin: 0 5px; padding: 5px 10px; border: 1px solid black; }
#nav a.active { background: #999; }
#nav a:hover { background: #CCC; }
#nav a.disabled, a:hover.disabled { color: #CCC; background: white; border: 1px solid #CCC; }
/* Submenu */
#subnav { position: absolute; top: 100px; left: 76%; background-color: #ffd;
width: 24%; margin: 1em 0 0; padding: .25em ; border: solid #ccc;
border-width: .1em 0 .1em .1em; }
#subnav ul { margin: 0; padding: 0; list-style: none; }
#subnav li{ margin: 0; padding: 2px 0 2px; }
#subnav a { font: 1em "Times New Roman", Roman, serif; margin: 0; padding: 0 0 0 26px;
text-transform: uppercase; text-decoration: none; color: #000; white-space: nowrap;
background: url(img/bulletOff.gif) no-repeat 10px 50%; display: block}
#subnav ul ul a { padding: 0 0 0 46px; background-position: 30px 50%; }
#subnav ul ul ul a { padding: 0 0 0 66px; background-position: 50px 50%; }
#subnav ul ul ul ul a { padding: 0 0 0 86px; background-position: 70px 50%; }
#subnav ul ul ul ul ul a { padding: 0 0 0 106px; background-position: 90px 50%; }
#subnav li#current a{ background-image: url(img/bulletOn.gif) }
#subnav li a:hover { background-image: url(img/bulletOn.gif) }
/* Main Content */
#content { margin: 3em 25% 10px 0; padding: 0 5% 1em 5%; }
#content.wide { margin: 3em 5% 0 5%; padding: 0 5% 1em 5%; }
#content p { padding: 0; margin: 0 0 1em 0; max-width: 660px; }
#content ul { max-width: 660px; }
#content ol { max-width: 660px; }
#content blockquote { max-width: 580px }
#content div.screenshot { text-align: center; margin: 1em 0; }
#content div.screenshot-right { text-align: center; float: right; margin: 0 0 0 1em; }
#content img { padding: 0; margin: 0; border: 0 }
/* Page Footer */
#footer { text-align: center; font-size: .8em; color: #444; clear: both;
border-top: 2px solid #999; margin: 0 30% 10px 5%; padding: 5px 0 0 0;
page-break-after: always }
#sig { text-align: right; font-size: .8em; width: 95%; display: none }
table.nunit { margin: 1em 5%; padding: 0; width: auto; border-collapse: collapse; }
table.nunit td, table.nunit th { border: 1px solid black; padding: 6px; text-align: left }
table.nunit th { background: #ccf; font-weight: bold; }
table.articles { margin: 20px 0 0 5%; padding: 0 10px 0 0; }
table.downloads { margin: 1em 5%; padding: 0; width: 24em; border-collapse: collapse; }
table.downloads td, table.downloads th { border: 1px solid black; padding: 2px; text-align: left }
table.downloads th { background: #ccf; font-weight: bold; }
table.platforms { margin: 1em 0; padding: 0; width: 24em; border-collapse: collapse; }
table.platforms td, table.platforms th { border: 1px solid black; padding: 5px; text-align: center }
table.platforms th { background: #ccf; font-weight: bold; }
table.constraints { margin: 1em 0; padding: 0; width: auto; border-collapse: collapse; }
table.constraints td, table.constraints th { border: 1px solid black; padding: 6px; text-align: left }
table.constraints th { background: #ccf; font-weight: bold; text-align: center }
table.roadmap { margin: 1em 0; padding: 0; width: auto; border-collapse: collapse; }
table.roadmap td, table.roadmap th { border: 1px solid black; padding: 10px; text-align: left }
table.roadmap th { background: #eef; font-weight: bold; }
table.extensions { margin: 1em 2%; border-collapse: collapse; width: 96%; }
table.extensions td, table.extensions th { border: solid black 1px; padding: 6px }
table.extensions th { background: #bbf; font-weight: bold; text-align: center }
table.extensions td.label { font-weight: bold; text-align: left; width: 10em }
table.quote { margin-left: 30px; margin-right: 30px; background: #FFFFFF; border: 3px black solid;
font: 1.1em/1.5em "Times New Roman", Roman, serif; font-variant: small-caps;
letter-spacing: .1em; padding: 0 }
table.quote td { padding: 0 }
table.quote td.sig { border-left: solid black 1px; padding-left: 15px }
#news { position: absolute; top: 100px; left: 76%; border-left: 1px solid black;
width: 14%; margin: 1em 0 0; padding: 0 5%; font-size: .8em; background-color: #fff }
#news h4 { font: 1.2em "Times New Roman", Roman, serif; font-variant: small-caps; text-align: center; margin: 0 0 1em; }
div.code { width: 36em; margin: 0 0; padding: 0 0; position: relative; }
div.langFilter { position: absolute; top: 100px; left: 5%; }
div.code div.langFilter { position: absolute; top: -15px; left: 0;}
div.dropdown { position: absolute; top: 0; left: 14px; padding: 0 10px; width: 20px;
text-align: left; border: 1px solid #888; background-color: #ffd; }
div.lang div.dropdown { position: absolute; left: 14px; top: 0; padding: 0 10px; width: 20px;
text-align: left; border: 1px solid #888; background-color: #ffd; }
div.notice {
margin-left: 2em;
margin-right: 2em;
text-align: center;
font-style: italic;
font-weight: bold;
}
pre.prettyprint {
padding: 10px;
max-width: 660px;
}
/*
#content.wide p { width: expression( document.documentElement.clientWidth > 700 ? "660px" : "auto" ); }
#content.wide blockquote { width: expression( document.documentElement.clientWidth > 700 ? "580px" : "auto" ); }
pre, .programText { font-family: "Courier New", Courier, Monospace; color: #000; font-size: 1em }
// The following was needed for IE in quirks mode - probably still needed for IE 5
div.code div.langFilter { position: absolute; top: -14px; left: -1em; }
// Special handling for absence of max-width in IE
*/
|
{
"pile_set_name": "Github"
}
|
// <copyright>
// Copyright by the Spark Development Network
//
// Licensed under the Rock Community License (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.rockrms.com/license
//
// 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.
// </copyright>
//
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Quartz;
using Rock.Attribute;
using Rock.Data;
using Rock.Model;
using Rock.Web.Cache;
namespace Rock.Jobs
{
/// <summary>
/// Automate Steps From Dataviews
/// </summary>
[DisplayName( "Steps Automation" )]
[Description( "Creates steps for people within a dataview." )]
[IntegerField(
"Duplicate Prevention Day Range",
description: "This setting will keep additional step records from being added if a step was already added within the number of days provided.",
required: false,
defaultValue: 7,
order: 1,
key: AttributeKey.DuplicatePreventionDayRange )]
[DisallowConcurrentExecution]
public class StepsAutomation : IJob
{
#region Keys
/// <summary>
/// Attribute Keys
/// </summary>
private static class AttributeKey
{
/// <summary>
/// The duplicate prevention day range
/// </summary>
public const string DuplicatePreventionDayRange = "DuplicatePreventionDayRange";
}
#endregion Keys
#region Constructors
/// <summary>
/// Empty constructor for job initialization
/// <para>
/// Jobs require a public empty constructor so that the
/// scheduler can instantiate the class whenever it needs.
/// </para>
/// </summary>
public StepsAutomation()
{
}
#endregion Constructors
/// <summary>
/// Executes the specified context.
/// </summary>
/// <param name="context">The context.</param>
public void Execute( IJobExecutionContext context )
{
// Use concurrent safe data structures to track the count and errors
var errors = new ConcurrentBag<string>();
var results = new ConcurrentBag<int>();
// Get the step type view query
var stepTypeViews = GetStepTypeViews();
// Get the day threshold for adding new steps
var minDaysBetweenSteps = GetDuplicatePreventionDayRange( context );
// Loop through each step type and create steps based on what is in the dataview
Parallel.ForEach( stepTypeViews, stepTypeView =>
{
var stepsAdded = ProcessStepType( stepTypeView, minDaysBetweenSteps, out var errorsFromThisStepType );
if ( errorsFromThisStepType != null && errorsFromThisStepType.Any() )
{
errorsFromThisStepType.ForEach( errors.Add );
}
results.Add( stepsAdded );
} );
// Set the results for the job log
var total = results.Sum();
context.Result = $"{total} steps added";
if ( errors.Any() )
{
ThrowErrors( context, errors );
}
}
/// <summary>
/// Processes the step type. Add steps for everyone in the dataview
/// </summary>
/// <param name="stepTypeView">The step type view.</param>
/// <param name="errorMessages">The error message.</param>
/// <param name="minDaysBetweenSteps"></param>
/// <returns></returns>
private int ProcessStepType( StepTypeView stepTypeView, int minDaysBetweenSteps, out List<string> errorMessages )
{
errorMessages = new List<string>();
var rockContext = new RockContext();
// Steps are created with a status of "complete", so if we need to know the status id
var stepStatusId = stepTypeView.CompletedStepStatusIds.FirstOrDefault();
if ( stepStatusId == default )
{
errorMessages.Add( $"The Step Type with id {stepTypeView.StepTypeId} does not have a valid Complete Status to use" );
return 0;
}
// Get the dataview configured for the step type
var dataViewService = new DataViewService( rockContext );
var dataview = dataViewService.Get( stepTypeView.AutoCompleteDataViewId );
if ( dataview == null )
{
errorMessages.Add( $"The dataview {stepTypeView.AutoCompleteDataViewId} for step type {stepTypeView.StepTypeId} did not resolve" );
return 0;
}
// We can use the dataview to get the person alias id query
var dataViewGetQueryArgs = new DataViewGetQueryArgs
{
DbContext = rockContext
};
IQueryable<IEntity> dataviewQuery;
try
{
dataviewQuery = dataview.GetQuery( dataViewGetQueryArgs );
}
catch ( Exception ex )
{
errorMessages.Add( ex.Message );
ExceptionLogService.LogException( ex );
return 0;
}
if ( dataviewQuery == null )
{
errorMessages.Add( $"Generating a query for dataview {stepTypeView.AutoCompleteDataViewId} for step type {stepTypeView.StepTypeId} was not successful" );
return 0;
}
// This query contains person ids in the dataview
var personIdQuery = dataviewQuery.AsNoTracking().Select( e => e.Id );
// Get the query for person aliases that cannot get a new step
var peopleThatCannotGetStepQuery = GetPeopleThatCannotGetStepQuery( rockContext, stepTypeView, minDaysBetweenSteps );
// Subtract the people that cannot get a new step
personIdQuery = personIdQuery.Except( peopleThatCannotGetStepQuery );
// If there are prerequisites, then subtract the people that cannot be the step because of unmet prerequisites
if ( stepTypeView.PrerequisiteStepTypeIds.Any() )
{
var peopleThatHaveMetPrerequisitesQuery = GetPeopleThatHaveMetPrerequisitesQuery( rockContext, stepTypeView );
personIdQuery = personIdQuery.Intersect( peopleThatHaveMetPrerequisitesQuery );
}
// Convert to person aliases ids
var personAliasService = new PersonAliasService( rockContext );
var personAliasIds = personAliasService.Queryable().AsNoTracking()
.Where( pa => personIdQuery.Contains( pa.PersonId ) )
.Select( pa => pa.Id )
.Distinct()
.ToList();
// Add steps for each of the remaining aliases that have met all the conditions
var stepService = new StepService( rockContext );
var now = RockDateTime.Now;
var count = 0;
foreach ( var personAliasId in personAliasIds )
{
var step = new Step
{
StepTypeId = stepTypeView.StepTypeId,
CompletedDateTime = now,
StartDateTime = now,
StepStatusId = stepStatusId,
PersonAliasId = personAliasId
};
stepService.AddWithoutValidation( step );
count++;
if ( count % 100 == 0 )
{
rockContext.SaveChanges();
}
}
rockContext.SaveChanges();
return count;
}
#region Data Helpers
/// <summary>
/// Gets the step type view query. All active step types that have a person based
/// dataview configured
/// </summary>
/// <returns></returns>
private List<StepTypeView> GetStepTypeViews()
{
var personEntityTypeId = EntityTypeCache.Get<Person>().Id;
var rockContext = new RockContext();
var stepTypeService = new StepTypeService( rockContext );
var views = stepTypeService.Queryable().AsNoTracking()
.Where( st =>
st.StepProgram.IsActive &&
st.IsActive &&
st.AutoCompleteDataViewId.HasValue &&
st.AutoCompleteDataView.EntityTypeId == personEntityTypeId )
.Select( st => new StepTypeView
{
StepTypeId = st.Id,
StepProgramId = st.StepProgramId,
AllowMultiple = st.AllowMultiple,
AutoCompleteDataViewId = st.AutoCompleteDataViewId.Value,
PrerequisiteStepTypeIds = st.StepTypePrerequisites.Select( stp => stp.PrerequisiteStepTypeId ),
// Get a list of the step statuses, but only take 1 so that it doesn't cause a second database call
CompletedStepStatusIds = st.StepProgram.StepStatuses
.OrderBy( ss => ss.Order )
.Where( ss =>
ss.IsCompleteStatus &&
ss.IsActive )
.Select( ss => ss.Id )
.Take( 1 )
} )
.ToList();
return views;
}
/// <summary>
/// These are people that cannot have new step because they already
/// have one and are within the minimum date range.
/// </summary>
/// <param name="stepTypeView">The step type view.</param>
/// <param name="rockContext"></param>
/// <param name="minDaysBetweenSteps"></param>
/// <returns></returns>
private IQueryable<int> GetPeopleThatCannotGetStepQuery( RockContext rockContext, StepTypeView stepTypeView, int minDaysBetweenSteps )
{
var stepService = new StepService( rockContext );
var minStepDate = DateTime.MinValue;
// We are querying for people that will ultimately be excluded from getting a new
// step created from this job.
// If duplicates are not allowed, then we want to find anyone with a step ever
// If duplicates are allowed and a day range is set, then it is within that timeframe.
if ( stepTypeView.AllowMultiple && minDaysBetweenSteps >= 1 )
{
minStepDate = RockDateTime.Now.AddDays( 0 - minDaysBetweenSteps );
}
var query = stepService.Queryable().AsNoTracking()
.Where( s =>
s.StepTypeId == stepTypeView.StepTypeId &&
( !s.CompletedDateTime.HasValue || s.CompletedDateTime.Value >= minStepDate ) )
.Select( s => s.PersonAlias.PersonId );
return query;
}
/// <summary>
/// Get a query for people that have met prerequisites
/// </summary>
/// <param name="rockContext"></param>
/// <param name="stepTypeView"></param>
/// <returns></returns>
private IQueryable<int> GetPeopleThatHaveMetPrerequisitesQuery( RockContext rockContext, StepTypeView stepTypeView )
{
var stepService = new StepService( rockContext );
// We are querying for people that have met all the prerequisites for this step type
// This method should not be called for stepTypes that do not have prerequisites
// because that would be a query for everyone in the database
var firstStepTypeId = stepTypeView.PrerequisiteStepTypeIds.First();
var prerequisiteCount = stepTypeView.PrerequisiteStepTypeIds.Count();
// Aliases that have completed the first prerequisite
var query = stepService.Queryable().AsNoTracking()
.Where( s =>
s.StepStatus.IsCompleteStatus &&
s.StepTypeId == firstStepTypeId )
.Select( s => s.PersonAlias.PersonId );
for ( var i = 1; i < prerequisiteCount; i++ )
{
var stepTypeId = stepTypeView.PrerequisiteStepTypeIds.ElementAt( i );
// Aliases that have completed this subsequent prerequisite
var subquery = stepService.Queryable().AsNoTracking()
.Where( s =>
s.StepStatus.IsCompleteStatus &&
s.StepTypeId == stepTypeId )
.Select( s => s.PersonAlias.PersonId );
// Find the intersection (people in the main query who have also met this prerequisite)
query = query.Intersect( subquery );
}
return query;
}
#endregion Data Helpers
#region Job State Helpers
/// <summary>
/// Gets the duplicate prevention day range.
/// </summary>
/// <param name="jobExecutionContext">The job execution context.</param>
/// <returns></returns>
private int GetDuplicatePreventionDayRange( IJobExecutionContext jobExecutionContext )
{
var days = jobExecutionContext.JobDetail.JobDataMap.GetString( AttributeKey.DuplicatePreventionDayRange ).AsInteger();
return days;
}
/// <summary>
/// Throws the errors.
/// </summary>
/// <param name="jobExecutionContext">The job execution context.</param>
/// <param name="errors">The errors.</param>
private void ThrowErrors( IJobExecutionContext jobExecutionContext, IEnumerable<string> errors )
{
var sb = new StringBuilder();
if ( !jobExecutionContext.Result.ToStringSafe().IsNullOrWhiteSpace() )
{
sb.AppendLine();
}
sb.AppendLine( string.Format( "{0} Errors: ", errors.Count() ) );
foreach ( var error in errors )
{
sb.AppendLine( error );
}
var errorMessage = sb.ToString();
jobExecutionContext.Result += errorMessage;
var exception = new Exception( errorMessage );
var httpContext = HttpContext.Current;
ExceptionLogService.LogException( exception, httpContext );
throw exception;
}
#endregion Job State Helpers
#region SQL Views
/// <summary>
/// Selected properties from a <see cref="StepType"/> related query
/// </summary>
private class StepTypeView
{
/// <summary>
/// Gets or sets the step type identifier.
/// </summary>
/// <value>
/// The step type identifier.
/// </value>
public int StepTypeId { get; set; }
/// <summary>
/// Gets or sets the step program identifier.
/// </summary>
/// <value>
/// The step program identifier.
/// </value>
public int StepProgramId { get; set; }
/// <summary>
/// Gets or sets the completed step status ids.
/// </summary>
/// <value>
/// The completed step status ids.
/// </value>
public IEnumerable<int> CompletedStepStatusIds { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [allow multiple].
/// </summary>
/// <value>
/// <c>true</c> if [allow multiple]; otherwise, <c>false</c>.
/// </value>
public bool AllowMultiple { get; set; }
/// <summary>
/// Gets or sets a value indicating the dataview id.
/// </summary>
/// <value>
/// The dataview ID
/// </value>
public int AutoCompleteDataViewId { get; set; }
/// <summary>
/// Prerequisite StepTypeIds
/// </summary>
public IEnumerable<int> PrerequisiteStepTypeIds { get; set; }
}
#endregion SQL Views
}
}
|
{
"pile_set_name": "Github"
}
|
# -*- coding: utf-8 -*-
# Copyright 2011 David Malcolm <[email protected]>
# Copyright 2011 Red Hat, Inc.
#
# This 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/>.
from libcpychecker import main
main(verify_refcounting=True,
dump_traces=True,
show_traces=False)
|
{
"pile_set_name": "Github"
}
|
# react-native 实现cnodejs客户端
首页和详情页UI参考 https://github.com/shinygang/Vue-cnodejs
API由 https://cnodejs.org/api 提供
在官方提供的API之外,增加搜索入口和个人资料入口。
# 如何运行
<pre><code> npm install 或者 yarn </code></pre>
<pre><code> react-native start </code></pre>
<pre><code> react-native run-android 或者 react-native run-ios</code></pre>
如果还没有安装 react-native 那么先 npm i react-native-cli -g
如果遇到无法启动问题,先尝试将 node 版本切换到8.1.0(推荐使用nvm安装)
如果npm安装有提示问题,那么尝试使用 yarn 安装
# 主要功能
token登录、退出;
查看、发布、编辑主题;
点赞评论、回复主题、收藏主题;
搜索、添加好友、实时聊天;
查看资料、查看收藏的主题、回复的主题;
# 更新
17-9-25:
集成聊天,实现搜索好友,处理申请,实时聊天;
17-9-26:
<pre>修复安卓搜索框显示不全问题
修复安卓tabbar的icon不能显示问题
新增对评论进行回复
优化FlatList显示逻辑
修复搜索记录不能及时更新问题
修复android首页发布话题按钮不显示问题
修复点赞、收藏图标点击后不显示问题 </pre>
# 说明
这个项目之间断断续续花了差不多12天时间,之前有一点react基础,因此做react-native上手就稍微快了。
基本就是一边看文档一边做,不懂的Google,所以这个项目可能有些地方写的不好,有时间想到了改进下项目,但是期间学习到了很多知识。
比较复杂的功能还需要时间学习。
这只是一个练手的项目,希望大家多多交流
# 部分演示
<img src="https://github.com/linwh1115/react-native-cnodejs/blob/master/src/screenshot/chat.gif" width="50%" height="50%">
<img src="https://github.com/linwh1115/react-native-cnodejs/blob/master/src/screenshot/home.gif" width="50%" height="50%">
<img src="https://github.com/linwh1115/react-native-cnodejs/blob/master/src/screenshot/search.gif" width="50%" height="50%">
# 部分截图
<img src="https://github.com/linwh1115/react-native-cnodejs/blob/master/src/screenshot/511504842345_.pic_hd.jpg" width="50%" height="50%">
<img src="https://github.com/linwh1115/react-native-cnodejs/blob/master/src/screenshot/521504842419_.pic_hd.jpg" width="50%" height="50%">
<img src="https://github.com/linwh1115/react-native-cnodejs/blob/master/src/screenshot/531504842468_.pic.jpg" width="50%" height="50%">
<img src="https://github.com/linwh1115/react-native-cnodejs/blob/master/src/screenshot/541504842490_.pic.jpg" width="50%" height="50%">
<img src="https://github.com/linwh1115/react-native-cnodejs/blob/master/src/screenshot/551504842567_.pic.jpg" width="50%" height="50%">
<img src="https://github.com/linwh1115/react-native-cnodejs/blob/master/src/screenshot/561504842591_.pic_hd.jpg" width="50%" height="50%">
<img src="https://github.com/linwh1115/react-native-cnodejs/blob/master/src/screenshot/571504842628_.pic.jpg" width="50%" height="50%">
<img src="https://github.com/linwh1115/react-native-cnodejs/blob/master/src/screenshot/571504842628_.pic.jpg" width="50%" height="50%">
<img src="https://github.com/linwh1115/react-native-cnodejs/blob/master/src/screenshot/581504842670_.pic.jpg" width="50%" height="50%">
<img src="https://github.com/linwh1115/react-native-cnodejs/blob/master/src/screenshot/591504844116_.pic.jpg" width="50%" height="50%">
<img src="https://github.com/linwh1115/react-native-cnodejs/blob/master/src/screenshot/621504844256_.pic.jpg" width="50%" height="50%">
<img src="https://github.com/linwh1115/react-native-cnodejs/blob/master/src/screenshot/WX20170925-171924%402x.png" width="50%" height="50%">
<img src="https://github.com/linwh1115/react-native-cnodejs/blob/master/src/screenshot/WX20170925-171942%402x.png" width="50%" height="50%">
<img src="https://github.com/linwh1115/react-native-cnodejs/blob/master/src/screenshot/WX20170925-171950%402x.png" width="50%" height="50%">
<img src="https://github.com/linwh1115/react-native-cnodejs/blob/master/src/screenshot/WX20170925-173126%402x.png" width="50%" height="50%">
# 等待修复问题
- [ ] 上拉加载更多数据的时候,在android由于加载数据时间比较久,导致不能点击item,只有等待loading结束后才能正常点击(猜测是FlatList的问题,待观察)。
- [ ] android端,点击主页上的tab,反应慢的问题(Android貌似都会比ios慢半拍 = = )。
- [ ] 文章图片显示问题,可能需要换个解析html的框架。
- [x] android如果图片设置 position:'absolute',不能显示问题,比如新建文章按钮。
- [x] android如果图片是点击后才显示的,不显示问题,比如点赞和收藏按钮。
# 待完善的功能
- [ ] 实现扫码登录
- [ ] 首页UI调整区分 首页和招聘板块
- [x] 详情页面内容显示优化
- [x] 添加回复评论
- [ ] 话题发布优化
|
{
"pile_set_name": "Github"
}
|
---
title: Example post
date: '2011-09-01'
author: Jeff Leek
comments: true
slug: "examplepost"
---
Write your text here in Markdown. Be aware that our blog runs with [Jekyll](https://jekyllrb.com/)
* Do codeblocks like this https://help.github.com/articles/creating-and-highlighting-code-blocks/
* Put all images in the public/ directory or point to them on a website where they are permanent
|
{
"pile_set_name": "Github"
}
|
// Copyright 2015 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 htmlindex
import (
"golang.org/x/text/encoding"
"golang.org/x/text/encoding/charmap"
"golang.org/x/text/encoding/internal/identifier"
"golang.org/x/text/encoding/japanese"
"golang.org/x/text/encoding/korean"
"golang.org/x/text/encoding/simplifiedchinese"
"golang.org/x/text/encoding/traditionalchinese"
"golang.org/x/text/encoding/unicode"
)
// mibMap maps a MIB identifier to an htmlEncoding index.
var mibMap = map[identifier.MIB]htmlEncoding{
identifier.UTF8: utf8,
identifier.UTF16BE: utf16be,
identifier.UTF16LE: utf16le,
identifier.IBM866: ibm866,
identifier.ISOLatin2: iso8859_2,
identifier.ISOLatin3: iso8859_3,
identifier.ISOLatin4: iso8859_4,
identifier.ISOLatinCyrillic: iso8859_5,
identifier.ISOLatinArabic: iso8859_6,
identifier.ISOLatinGreek: iso8859_7,
identifier.ISOLatinHebrew: iso8859_8,
identifier.ISO88598I: iso8859_8I,
identifier.ISOLatin6: iso8859_10,
identifier.ISO885913: iso8859_13,
identifier.ISO885914: iso8859_14,
identifier.ISO885915: iso8859_15,
identifier.ISO885916: iso8859_16,
identifier.KOI8R: koi8r,
identifier.KOI8U: koi8u,
identifier.Macintosh: macintosh,
identifier.MacintoshCyrillic: macintoshCyrillic,
identifier.Windows874: windows874,
identifier.Windows1250: windows1250,
identifier.Windows1251: windows1251,
identifier.Windows1252: windows1252,
identifier.Windows1253: windows1253,
identifier.Windows1254: windows1254,
identifier.Windows1255: windows1255,
identifier.Windows1256: windows1256,
identifier.Windows1257: windows1257,
identifier.Windows1258: windows1258,
identifier.XUserDefined: xUserDefined,
identifier.GBK: gbk,
identifier.GB18030: gb18030,
identifier.Big5: big5,
identifier.EUCPkdFmtJapanese: eucjp,
identifier.ISO2022JP: iso2022jp,
identifier.ShiftJIS: shiftJIS,
identifier.EUCKR: euckr,
identifier.Replacement: replacement,
}
// encodings maps the internal htmlEncoding to an Encoding.
// TODO: consider using a reusable index in encoding/internal.
var encodings = [numEncodings]encoding.Encoding{
utf8: unicode.UTF8,
ibm866: charmap.CodePage866,
iso8859_2: charmap.ISO8859_2,
iso8859_3: charmap.ISO8859_3,
iso8859_4: charmap.ISO8859_4,
iso8859_5: charmap.ISO8859_5,
iso8859_6: charmap.ISO8859_6,
iso8859_7: charmap.ISO8859_7,
iso8859_8: charmap.ISO8859_8,
iso8859_8I: charmap.ISO8859_8I,
iso8859_10: charmap.ISO8859_10,
iso8859_13: charmap.ISO8859_13,
iso8859_14: charmap.ISO8859_14,
iso8859_15: charmap.ISO8859_15,
iso8859_16: charmap.ISO8859_16,
koi8r: charmap.KOI8R,
koi8u: charmap.KOI8U,
macintosh: charmap.Macintosh,
windows874: charmap.Windows874,
windows1250: charmap.Windows1250,
windows1251: charmap.Windows1251,
windows1252: charmap.Windows1252,
windows1253: charmap.Windows1253,
windows1254: charmap.Windows1254,
windows1255: charmap.Windows1255,
windows1256: charmap.Windows1256,
windows1257: charmap.Windows1257,
windows1258: charmap.Windows1258,
macintoshCyrillic: charmap.MacintoshCyrillic,
gbk: simplifiedchinese.GBK,
gb18030: simplifiedchinese.GB18030,
big5: traditionalchinese.Big5,
eucjp: japanese.EUCJP,
iso2022jp: japanese.ISO2022JP,
shiftJIS: japanese.ShiftJIS,
euckr: korean.EUCKR,
replacement: encoding.Replacement,
utf16be: unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM),
utf16le: unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM),
xUserDefined: charmap.XUserDefined,
}
|
{
"pile_set_name": "Github"
}
|
{
tile_pattern: [
{
image: "tiles/wooden-interior.png",
tiles: "1j",
reverse: false,
pattern: " .* , .* ,.*,
, wvd ,(wvd),
.* , .* ,.*",
},
{
image: "tiles/wooden-interior.png",
tiles: "1m",
reverse: false,
pattern: " .* , .* ,.* ,
(wvd) , wvd , ,
.* , .* ,.*",
},
{
image: "tiles/wooden-interior.png",
tiles: "1k|1l",
reverse: false,
pattern: " .* , .* , .* ,
.* , wvd , .* ,
.* , .* , .*",
},
],
multi_tile_pattern: [
{
chance: 30,
pattern: " .* , .* , .* , .*
(wvd) , wvd->tile1 , wvd->tile2 , (wvd)
.* , .* , .* , .* ",
tile1: {
image: "tiles/wooden-interior.png",
tiles: "0k",
},
tile2: {
image: "tiles/wooden-interior.png",
tiles: "0l",
},
},
],
}
|
{
"pile_set_name": "Github"
}
|
{"type":"Buffer","data":[0,0,0,1,0,31,116,101,115,116,45,116,111,112,105,99,45,57,102,57,98,48,55,52,48,53,55,97,99,100,52,51,51,53,57,52,54,0,0,0,1,0,0,0,0,255,255,255,255,255,255,255,255,0,0,0,0]}
|
{
"pile_set_name": "Github"
}
|
<!-- start profiling callstack -->
<table class="yiiLog" width="100%" cellpadding="2" style="border-spacing:1px;font:11px Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;color:#666666;">
<tr>
<th style="background:black;color:white;" colspan="2">
Profiling Callstack Report
</th>
</tr>
<tr style="background-color: #ccc;">
<th>Procedure</th>
<th>Time (s)</th>
</tr>
<?php
foreach($data as $index=>$entry)
{
$color=($index%2)?'#F5F5F5':'#FFFFFF';
list($proc,$time,$level)=$entry;
$proc=CHtml::encode($proc);
$time=sprintf('%0.5f',$time);
$spaces=str_repeat(' ',$level*8);
echo <<<EOD
<tr style="background:{$color}">
<td>{$spaces}{$proc}</td>
<td align="center">{$time}</td>
</tr>
EOD;
}
?>
</table>
<!-- end of profiling callstack -->
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2013 Elements of Programming Interviews. All rights reserved.
#include <algorithm>
#include <cassert>
#include <iostream>
#include <iterator>
#include <random>
#include <vector>
using std::cout;
using std::default_random_engine;
using std::endl;
using std::ostream_iterator;
using std::random_device;
using std::uniform_int_distribution;
using std::vector;
void PrintMatrix(const vector<vector<int>>& A) {
for (size_t i = 0; i < A.size(); ++i) {
copy(A[i].begin(), A[i].end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
}
void CheckAnswer(const vector<vector<int>>& A) {
int k = 1;
for (int j = A.size() - 1; j >= 0; --j) {
for (size_t i = 0; i < A.size(); ++i) {
assert(k++ == A[i][j]);
}
}
}
void RotateMatrixHelper(int x_s, int x_e, int y_s, int y_e,
vector<vector<int>>* A);
void CopyMatrix(int A_x_s, int A_x_e, int A_y_s, int A_y_e,
const vector<vector<int>>& S, int S_x, int S_y,
vector<vector<int>>* A);
// @include
void RotateMatrix(vector<vector<int>>* A) {
RotateMatrixHelper(0, A->size(), 0, A->size(), A);
}
void RotateMatrixHelper(int x_s, int x_e, int y_s, int y_e,
vector<vector<int>>* A) {
if (x_e > x_s + 1) {
int mid_x = x_s + ((x_e - x_s) / 2), mid_y = y_s + ((y_e - y_s) / 2);
// Move submatrices.
vector<vector<int>> C(mid_x - x_s, vector<int>(mid_y - y_s));
CopyMatrix(0, C.size(), 0, C.size(), *A, x_s, y_s, &C);
CopyMatrix(x_s, mid_x, y_s, mid_y, *A, mid_x, y_s, A);
CopyMatrix(mid_x, x_e, y_s, mid_y, *A, mid_x, mid_y, A);
CopyMatrix(mid_x, x_e, mid_y, y_e, *A, x_s, mid_y, A);
CopyMatrix(x_s, mid_x, mid_y, y_e, C, 0, 0, A);
// Recursively rotate submatrices.
RotateMatrixHelper(x_s, mid_x, y_s, mid_y, A);
RotateMatrixHelper(x_s, mid_x, mid_y, y_e, A);
RotateMatrixHelper(mid_x, x_e, mid_y, y_e, A);
RotateMatrixHelper(mid_x, x_e, y_s, mid_y, A);
}
}
void CopyMatrix(int A_x_s, int A_x_e, int A_y_s, int A_y_e,
const vector<vector<int>>& S, int S_x, int S_y,
vector<vector<int>>* A) {
for (int i = 0; i < A_x_e - A_x_s; ++i) {
copy(S[S_x + i].cbegin() + S_y, S[S_x + i].cbegin() + S_y + A_y_e - A_y_s,
(*A)[A_x_s + i].begin() + A_y_s);
}
}
// @exclude
int main(int argc, char* argv[]) {
int n;
if (argc == 2) {
n = atoi(argv[1]);
vector<vector<int>> A(1 << n, vector<int>(1 << n));
int k = 1;
for (size_t i = 0; i < A.size(); ++i) {
for (size_t j = 0; j < A[i].size(); ++j) {
A[i][j] = k++;
}
}
RotateMatrix(&A);
CheckAnswer(A);
} else {
default_random_engine gen((random_device())());
uniform_int_distribution<int> dis(1, 10);
for (int times = 0; times < 100; ++times) {
n = dis(gen);
vector<vector<int>> A(1 << n, vector<int>(1 << n));
int k = 1;
for (size_t i = 0; i < A.size(); ++i) {
for (size_t j = 0; j < A[i].size(); ++j) {
A[i][j] = k++;
}
}
// PrintMatrix(A);
RotateMatrix(&A);
CheckAnswer(A);
// PrintMatrix(A);
}
}
return 0;
}
|
{
"pile_set_name": "Github"
}
|
//===--- CodeGenTBAA.h - TBAA information for LLVM CodeGen ------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the code that manages TBAA information and defines the TBAA policy
// for the optimizer to use.
//
//===----------------------------------------------------------------------===//
#ifndef CLANG_CODEGEN_CODEGENTBAA_H
#define CLANG_CODEGEN_CODEGENTBAA_H
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/MDBuilder.h"
namespace llvm {
class LLVMContext;
class MDNode;
}
namespace clang {
class ASTContext;
class LangOptions;
class MangleContext;
class QualType;
class Type;
namespace CodeGen {
class CGRecordLayout;
/// CodeGenTBAA - This class organizes the cross-module state that is used
/// while lowering AST types to LLVM types.
class CodeGenTBAA {
ASTContext &Context;
llvm::LLVMContext& VMContext;
const LangOptions &Features;
MangleContext &MContext;
// MDHelper - Helper for creating metadata.
llvm::MDBuilder MDHelper;
/// MetadataCache - This maps clang::Types to llvm::MDNodes describing them.
llvm::DenseMap<const Type *, llvm::MDNode *> MetadataCache;
llvm::MDNode *Root;
llvm::MDNode *Char;
/// getRoot - This is the mdnode for the root of the metadata type graph
/// for this translation unit.
llvm::MDNode *getRoot();
/// getChar - This is the mdnode for "char", which is special, and any types
/// considered to be equivalent to it.
llvm::MDNode *getChar();
public:
CodeGenTBAA(ASTContext &Ctx, llvm::LLVMContext &VMContext,
const LangOptions &Features,
MangleContext &MContext);
~CodeGenTBAA();
/// getTBAAInfo - Get the TBAA MDNode to be used for a dereference
/// of the given type.
llvm::MDNode *getTBAAInfo(QualType QTy);
/// getTBAAInfoForVTablePtr - Get the TBAA MDNode to be used for a
/// dereference of a vtable pointer.
llvm::MDNode *getTBAAInfoForVTablePtr();
};
} // end namespace CodeGen
} // end namespace clang
#endif
|
{
"pile_set_name": "Github"
}
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <AppKit/NSView.h>
@protocol SiriUITalkGestureTargetDelegate;
__attribute__((visibility("hidden")))
@interface SiriUITalkGestureTarget : NSView
{
id <SiriUITalkGestureTargetDelegate> _delegate;
}
- (void).cxx_destruct;
- (BOOL)accessibilityPerformPress;
- (id)accessibilityLabel;
- (id)accessibilityIdentifier;
- (id)accessibilityRole;
- (BOOL)isAccessibilityElement;
- (BOOL)acceptsFirstMouse:(id)arg1;
- (id)initWithDelegate:(id)arg1;
@end
|
{
"pile_set_name": "Github"
}
|
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "AssetTypeActions_StringTable.h"
#include "StringTableEditorModule.h"
#define LOCTEXT_NAMESPACE "AssetTypeActions"
void FAssetTypeActions_StringTable::OpenAssetEditor(const TArray<UObject*>& InObjects, TSharedPtr<IToolkitHost> EditWithinLevelEditor)
{
FStringTableEditorModule& StringTableEditorModule = FModuleManager::LoadModuleChecked<FStringTableEditorModule>("StringTableEditor");
for (UObject* ObjToEdit : InObjects)
{
if (UStringTable* StringTable = Cast<UStringTable>(ObjToEdit))
{
StringTableEditorModule.CreateStringTableEditor(EToolkitMode::Standalone, EditWithinLevelEditor, StringTable);
}
}
}
#undef LOCTEXT_NAMESPACE
|
{
"pile_set_name": "Github"
}
|
Your Own Certificate Authority
==============================
A certificate authority (CA) is an entity that signs digital certificates.
Many websites need to let their customers know that the connection is secure, so they pay an internationally trusted CA (eg, VeriSign, DigiCert) to sign a certificate for their domain.
In some cases it may make more sense to act as your own CA, rather than paying a CA like DigiCert.
Common cases include securing an intranet website, or for issuing certificates to clients to allow them to authenticate to a server.
Main use cases for having your own CA:
- Trusted encrypted communication with your peers (man-in-the-middle attack prevention)
- Secure your internal REST micro-services and internal API's
- Client-certificate based login for web services, web applications and OpenVPN connections
- Secure access to your private cloud services with your own HTTPS scheme
- Secure your Internet of Things (IoT) network with your certificates
|
{
"pile_set_name": "Github"
}
|
-module(mutex_sup).
-export([start_link/0, init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init(_) ->
{ok, {{one_for_one, 5, 3600}, []}}.
% MutexChildSpec = {mutex,
% {mutex, start_link, [printer]},
% transient,
% 5000,
% [mutex]},
|
{
"pile_set_name": "Github"
}
|
#pragma once
/*
* Copyright(c) 2018 Jeremiah van Oosten
*
* 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.
*/
/**
* @file TextureUsage.h
* @date October 24, 2018
* @author Jeremiah van Oosten
*
* @brief The TextureUsage enumeration describes how a texture is used.
* Albedo (diffuse) textures should be loaded and stored using sRGB formats
* so that the texture sampler will automatically linearize the color when
* sampled.
* Height maps and normals must must not be linearized during load and thus
* must ignore any sRGB settings that they may contain in the metadata of the
* image file.
*/
enum class TextureUsage
{
Albedo,
Diffuse = Albedo, // Treat Diffuse and Albedo textures the same.
Heightmap,
Depth = Heightmap, // Treat height and depth textures the same.
Normalmap,
RenderTarget, // Texture is used as a render target.
};
|
{
"pile_set_name": "Github"
}
|
true
Byte
true
Short
true
Char
true
Int
true
Long
true
Float
true
Double
true
Boolean
true
Unit
true
Any
true
AnyVal
true
Object
true
Object
true
Null
true
Nothing
|
{
"pile_set_name": "Github"
}
|
// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.rankingexpression.importer.operations;
import ai.vespa.rankingexpression.importer.DimensionRenamer;
import ai.vespa.rankingexpression.importer.OrderedTensorType;
import com.yahoo.searchlib.rankingexpression.Reference;
import com.yahoo.searchlib.rankingexpression.evaluation.DoubleValue;
import com.yahoo.searchlib.rankingexpression.rule.ArithmeticNode;
import com.yahoo.searchlib.rankingexpression.rule.ArithmeticOperator;
import com.yahoo.searchlib.rankingexpression.rule.ConstantNode;
import com.yahoo.searchlib.rankingexpression.rule.EmbracedNode;
import com.yahoo.searchlib.rankingexpression.rule.ExpressionNode;
import com.yahoo.searchlib.rankingexpression.rule.ReferenceNode;
import com.yahoo.searchlib.rankingexpression.rule.TensorFunctionNode;
import com.yahoo.tensor.TensorType;
import com.yahoo.tensor.functions.Generate;
import com.yahoo.tensor.functions.Slice;
import com.yahoo.tensor.functions.TensorFunction;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static com.yahoo.searchlib.rankingexpression.rule.TensorFunctionNode.wrapScalar;
/*
* Onnx gather is the same as Numpy take.
*/
public class Gather extends IntermediateOperation {
private final AttributeMap attributeMap;
private int axis;
public Gather(String modelName, String nodeName, List<IntermediateOperation> inputs, AttributeMap attributeMap) {
super(modelName, nodeName, inputs);
this.attributeMap = attributeMap;
}
@Override
protected OrderedTensorType lazyGetType() {
if ( ! allInputTypesPresent(2)) return null;
OrderedTensorType dataType = inputs.get(0).type().get();
OrderedTensorType indicesType = inputs.get(1).type().get();
axis = (int) attributeMap.get("axis").orElse(DoubleValue.zero).asDouble();
if (axis < 0)
axis = dataType.rank() + axis;
OrderedTensorType.Builder typeBuilder = new OrderedTensorType.Builder(resultValueType());
for (int i = 0; i < axis; ++i) {
addDimension(i, dataType.dimensions().get(i).size().orElse(-1L), typeBuilder);
}
for (int i = 0; i < indicesType.rank(); ++i) {
addDimension(i + axis, indicesType.dimensions().get(i).size().orElse(-1L), typeBuilder);
}
for (int i = axis + 1; i < dataType.rank(); ++i) {
addDimension(i + indicesType.rank(), dataType.dimensions().get(i).size().orElse(-1L), typeBuilder);
}
inputs.get(0).exportAsRankingFunction = true;
inputs.get(1).exportAsRankingFunction = true;
return typeBuilder.build();
}
private void addDimension(int dimensionIndex, long size, OrderedTensorType.Builder typeBuilder) {
String name = String.format("%s_%d", vespaName(), dimensionIndex);
typeBuilder.add(TensorType.Dimension.indexed(name, size));
}
@Override
protected TensorFunction lazyGetFunction() {
if ( ! allInputFunctionsPresent(2)) return null;
IntermediateOperation data = inputs.get(0);
IntermediateOperation indices = inputs.get(1);
OrderedTensorType dataType = data.type().get();
OrderedTensorType indicesType = indices.type().get();
String dataFunctionName = data.rankingExpressionFunctionName();
String indicesFunctionName = indices.rankingExpressionFunctionName();
List<Slice.DimensionValue<Reference>> dataSliceDimensions = new ArrayList<>();
for (int i = 0; i < axis; ++i) {
addSliceDimension(dataSliceDimensions, dataType.dimensions().get(i).name(), i);
}
if (indicesType.rank() == 0 && indices.isConstant()) {
double constantValue = indices.getConstantValue().get().asDouble();
ExpressionNode indexExpression = new ConstantNode(new DoubleValue(constantValue));
if (constantValue < 0) {
ExpressionNode axisSize = new ConstantNode(new DoubleValue(dataType.dimensions().get(axis).size().get()));
indexExpression = new EmbracedNode(new ArithmeticNode(indexExpression, ArithmeticOperator.PLUS, axisSize));
}
addSliceDimension(dataSliceDimensions, dataType.dimensions().get(axis).name(), indexExpression);
} else {
List<Slice.DimensionValue<Reference>> indicesSliceDimensions = new ArrayList<>();
for (int i = 0; i < indicesType.rank(); ++i) {
addSliceDimension(indicesSliceDimensions, indicesType.dimensions().get(i).name(), axis + i);
}
ExpressionNode sliceExpression = createSliceExpression(indicesSliceDimensions, indicesFunctionName);
ExpressionNode indexExpression = createIndexExpression(dataType, sliceExpression);
addSliceDimension(dataSliceDimensions, dataType.dimensions().get(axis).name(), indexExpression);
}
for (int i = axis + 1; i < dataType.rank(); ++i) {
addSliceDimension(dataSliceDimensions, dataType.dimensions().get(i).name(), i + indicesType.rank() - 1);
}
ExpressionNode sliceExpression = createSliceExpression(dataSliceDimensions, dataFunctionName);
return Generate.bound(type.type(), wrapScalar(sliceExpression));
}
private ExpressionNode createSliceExpression(List<Slice.DimensionValue<Reference>> dimensionValues, String referenceName) {
TensorFunction<Reference> inputIndices = new TensorFunctionNode.ExpressionTensorFunction(new ReferenceNode(referenceName));
if (dimensionValues.isEmpty()) {
return new TensorFunctionNode(inputIndices);
}
Slice<Reference> sliceIndices = new Slice<>(inputIndices, dimensionValues);
return new TensorFunctionNode(sliceIndices);
}
/** to support negative indexing */
private ExpressionNode createIndexExpression(OrderedTensorType dataType, ExpressionNode slice) {
ExpressionNode axisSize = new ConstantNode(new DoubleValue(dataType.dimensions().get(axis).size().get()));
ExpressionNode plus = new EmbracedNode(new ArithmeticNode(slice, ArithmeticOperator.PLUS, axisSize));
ExpressionNode mod = new ArithmeticNode(plus, ArithmeticOperator.MODULO, axisSize);
return mod;
}
private void addSliceDimension(List<Slice.DimensionValue<Reference>> dimensionValues, String dimensionName, ExpressionNode expr) {
dimensionValues.add(new Slice.DimensionValue<>(Optional.of(dimensionName), wrapScalar(new EmbracedNode(expr))));
}
private void addSliceDimension(List<Slice.DimensionValue<Reference>> dimensionValues, String dimensionName, int dimensionIndex) {
String outputDimensionName = type.dimensions().get(dimensionIndex).name();
addSliceDimension(dimensionValues, dimensionName, new ReferenceNode(outputDimensionName));
}
@Override
public void addDimensionNameConstraints(DimensionRenamer renamer) {
if ( ! allInputTypesPresent(2)) return;
for (int i = 0; i < type.dimensions().size(); i++) {
renamer.addDimension(type.dimensions().get(i).name());
for (int j = i + 1; j < type.dimensions().size(); j++) {
renamer.addConstraint(type.dimensions().get(i).name(), type.dimensions().get(j).name(),
DimensionRenamer.Constraint.lessThan(), this);
}
}
OrderedTensorType dataType = inputs.get(0).type().get();
OrderedTensorType indicesType = inputs.get(1).type().get();
for (int i = 0; i < axis; ++i) {
renamer.addConstraint(type.dimensions().get(i).name(),
dataType.dimensions().get(i).name(),
DimensionRenamer.Constraint.equal(), this);
}
for (int i = 0; i < indicesType.rank(); ++i) {
renamer.addConstraint(type.dimensions().get(i + axis).name(),
indicesType.dimensions().get(i).name(),
DimensionRenamer.Constraint.equal(), this);
}
for (int i = axis + 1; i < dataType.rank(); ++i) {
renamer.addConstraint(type.dimensions().get(i + indicesType.rank() - 1).name(),
dataType.dimensions().get(i).name(),
DimensionRenamer.Constraint.equal(), this);
}
}
@Override
public Gather withInputs(List<IntermediateOperation> inputs) {
return new Gather(modelName(), name(), inputs, attributeMap);
}
@Override
public String operationName() { return "Gather"; }
}
|
{
"pile_set_name": "Github"
}
|
CREATE DATABASE IF NOT EXISTS ${DB};
USE ${DB};
DROP TABLE IF EXISTS kafka_temp_table_q40;
SET spark.testing=${TESTING_ENABLE};
SET spark.sql.streaming.query.timeout.ms=${TESTING_TIMEOUT_MS};
SET streaming.query.name=job40;
SET spark.sql.streaming.checkpointLocation.job40=${CHECKPOINT_ROOT}/job40;
CREATE TABLE kafka_temp_table_q40
USING kafka
OPTIONS (
kafka.bootstrap.servers = "${BOOTSTRAP_SERVERS}",
subscribe = 'temp_topic_q40',
output.mode = 'append',
kafka.schema.registry.url = "${SCHEMA_REGISTRY_URL}",
kafka.schema.record.name = 'TempResult',
kafka.schema.record.namespace = 'org.apache.spark.emr.baseline.testing',
kafka.auto.register.schemas = 'true');
INSERT INTO kafka_temp_table_q40
SELECT
w_state,
i_item_id
FROM
kafka_catalog_sales
LEFT OUTER JOIN kafka_catalog_returns ON
(cs_order_number = cr_order_number
AND cs_item_sk = cr_item_sk
AND cs_data_time >= cr_data_time
AND cs_data_time <= cr_data_time + interval 30 seconds)
, warehouse, item, date_dim
WHERE
i_current_price BETWEEN 0.99 AND 1.49
AND i_item_sk = cs_item_sk
AND cs_warehouse_sk = w_warehouse_sk
AND cs_sold_date_sk = d_date_sk
AND d_date BETWEEN (cast('2000-03-11' AS DATE) - INTERVAL 30 days)
AND (cast('2000-03-11' AS DATE) + INTERVAL 30 days)
AND delay(cr_data_time) < '30 seconds' and delay(cs_data_time) < '60 seconds'
|
{
"pile_set_name": "Github"
}
|
cheats = 2
cheat0_desc = "Team 1 Has A High Score"
cheat0_code = "00CC-FAFF"
cheat0_enable = false
cheat1_desc = "Team 2 Never Scores"
cheat1_code = "00CD-7200"
cheat1_enable = false
|
{
"pile_set_name": "Github"
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.sqoop.testutil.adapter;
import org.apache.sqoop.SqoopOptions;
import org.apache.sqoop.manager.ConnManager;
import org.apache.sqoop.manager.sqlserver.MSSQLTestUtils;
import java.sql.SQLException;
public class SqlServerDatabaseAdapter implements DatabaseAdapter {
@Override
public String getConnectionString() {
return MSSQLTestUtils.CONNECT_STRING;
}
@Override
public SqoopOptions injectConnectionParameters(SqoopOptions options) {
options.setConnectString(MSSQLTestUtils.CONNECT_STRING);
options.setUsername(MSSQLTestUtils.DATABASE_USER);
options.setPassword(MSSQLTestUtils.DATABASE_PASSWORD);
return options;
}
@Override
public void dropTableIfExists(String tableName, ConnManager manager) throws SQLException {
String dropTableStatement = "DROP TABLE IF EXISTS " + manager.escapeTableName(tableName);
manager.execAndPrint(dropTableStatement);
}
@Override
public String toString() {
return getClass().getSimpleName();
}
}
|
{
"pile_set_name": "Github"
}
|
package org.nd4j.linalg.shape.reshape;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.nd4j.linalg.BaseNd4jTest;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.factory.Nd4jBackend;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assume.assumeNotNull;
/**
* @author Adam Gibson
*/
@Slf4j
@RunWith(Parameterized.class)
public class ReshapeTests extends BaseNd4jTest {
public ReshapeTests(Nd4jBackend backend) {
super(backend);
}
@Test
public void testThreeTwoTwoTwo() {
INDArray threeTwoTwo = Nd4j.linspace(1, 12, 12).reshape(3, 2, 2);
INDArray sliceZero = Nd4j.create(new double[][] {{1, 7}, {4, 10}});
INDArray sliceOne = Nd4j.create(new double[][] {{2, 8}, {5, 11}});
INDArray sliceTwo = Nd4j.create(new double[][] {{3, 9}, {6, 12}});
INDArray[] assertions = new INDArray[] {sliceZero, sliceOne, sliceTwo};
for (int i = 0; i < threeTwoTwo.slices(); i++) {
INDArray sliceI = threeTwoTwo.slice(i);
assertEquals(assertions[i], sliceI);
}
INDArray linspaced = Nd4j.linspace(1, 4, 4).reshape(2, 2);
INDArray[] assertionsTwo = new INDArray[] {Nd4j.create(new double[] {1, 3}), Nd4j.create(new double[] {2, 4})};
for (int i = 0; i < assertionsTwo.length; i++)
assertEquals(linspaced.slice(i), assertionsTwo[i]);
}
@Test
public void testColumnVectorReshape() {
double delta = 1e-1;
INDArray arr = Nd4j.create(1, 3);
INDArray reshaped = arr.reshape('f', 3, 1);
assertArrayEquals(new int[] {3, 1}, reshaped.shape());
assertEquals(0.0, reshaped.getDouble(1), delta);
assertEquals(0.0, reshaped.getDouble(2), delta);
log.info("Reshaped: {}", reshaped.shapeInfoDataBuffer().asInt());
assumeNotNull(reshaped.toString());
}
@Override
public char ordering() {
return 'f';
}
}
|
{
"pile_set_name": "Github"
}
|
Documentation for tex-antiqua.
|
{
"pile_set_name": "Github"
}
|
<%--
Created by IntelliJ IDEA.
User: Elric
Date: 2017/7/7
Time: 14:48
To change this template use File | Settings | File Templates.
--%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ECharts</title>
<!-- 引入 echarts.js -->
<script type="text/javascript" src="${pageContext.request.contextPath}/js/echarts.common.min.js"></script>
<!-- 引入jquery.js -->
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.2.1.min.js"></script>
</head>
<body>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
var myChart = echarts.init(document.getElementById('main'));
// 显示标题,图例和空的坐标轴
myChart.setOption({
title: {
text: '异步数据加载示例'
},
tooltip: {},
legend: {
data: ['销量']
},
xAxis: {
data: []
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: []
}]
});
myChart.showLoading(); //数据加载完之前先显示一段简单的loading动画
var names = []; //类别数组(实际用来盛放X轴坐标值)
var nums = []; //销量数组(实际用来盛放Y坐标值)
$.ajax({
type: "post",
async: true, //异步请求(同步请求将会锁住浏览器,用户其他操作必须等待请求完成才可以执行)
url: "echartServlet", //请求发送到TestServlet处
data: {},
dataType: "json", //返回数据形式为json
success: function (result) {
//请求成功时执行该函数内容,result即为服务器返回的json对象
if (result) {
for (var i = 0; i < result.length; i++) {
names.push(result[i].name); //挨个取出类别并填入类别数组
}
for (var i = 0; i < result.length; i++) {
nums.push(result[i].num); //挨个取出销量并填入销量数组
}
myChart.hideLoading(); //隐藏加载动画
myChart.setOption({ //加载数据图表
xAxis: {
data: names
},
series: [{
// 根据名字对应到相应的系列
name: '销量',
data: nums
}]
});
}
},
error: function (errorMsg) {
//请求失败时执行该函数
alert("图表请求数据失败!");
myChart.hideLoading();
}
})
</script>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
[Unit]
Description=PulseAudio Sound System
After=syslog.target
[Service]
UMask=077
ExecStart=/usr/bin/pulseaudio --system --daemonize=no
Restart=always
[Install]
WantedBy=multi-user.target
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.jdt.launching.localJavaApplication">
<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_PATHS">
<listEntry value="/enderio-conduits"/>
</listAttribute>
<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_TYPES">
<listEntry value="4"/>
</listAttribute>
<listAttribute key="org.eclipse.debug.ui.favoriteGroups">
<listEntry value="org.eclipse.debug.ui.launchGroup.debug"/>
<listEntry value="org.eclipse.debug.ui.launchGroup.run"/>
</listAttribute>
<booleanAttribute key="org.eclipse.jdt.launching.ATTR_USE_START_ON_FIRST_THREAD" value="true"/>
<listAttribute key="org.eclipse.jdt.launching.CLASSPATH">
<listEntry value="<?xml version="1.0" encoding="UTF-8" standalone="no"?> <runtimeClasspathEntry containerPath="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8" javaProject="enderio-conduits" path="1" type="4"/> "/>
<listEntry value="<?xml version="1.0" encoding="UTF-8" standalone="no"?> <runtimeClasspathEntry id="org.eclipse.jdt.launching.classpathentry.defaultClasspath"> <memento exportedEntriesOnly="false" project="enderio-conduits"/> </runtimeClasspathEntry> "/>
<listEntry value="<?xml version="1.0" encoding="UTF-8" standalone="no"?> <runtimeClasspathEntry path="3" projectName="enderio-zoo" type="1"/> "/>
<listEntry value="<?xml version="1.0" encoding="UTF-8" standalone="no"?> <runtimeClasspathEntry path="3" projectName="enderio-machines" type="1"/> "/>
<listEntry value="<?xml version="1.0" encoding="UTF-8" standalone="no"?> <runtimeClasspathEntry path="3" projectName="enderio-base" type="1"/> "/>
<listEntry value="<?xml version="1.0" encoding="UTF-8" standalone="no"?> <runtimeClasspathEntry path="3" projectName="EnderCore" type="1"/> "/>
<listEntry value="<?xml version="1.0" encoding="UTF-8" standalone="no"?> <runtimeClasspathEntry path="3" projectName="enderio-conduits" type="1"/> "/>
</listAttribute>
<booleanAttribute key="org.eclipse.jdt.launching.DEFAULT_CLASSPATH" value="false"/>
<stringAttribute key="org.eclipse.jdt.launching.MAIN_TYPE" value="GradleStart"/>
<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="enderio-conduits"/>
<stringAttribute key="org.eclipse.jdt.launching.VM_ARGUMENTS" value="-Dfml.coreMods.load=com.enderio.core.common.transform.EnderCorePlugin -DINDEV=1 -Dforge.verboseMissingModelLoggingCount=1000"/>
<stringAttribute key="org.eclipse.jdt.launching.WORKING_DIRECTORY" value="${workspace_loc:EnderIO/run}"/>
</launchConfiguration>
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- qdom.cpp -->
<head>
<title>Qt 4.6: List of All Members for QDomText</title>
<link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><a href="http://qt.nokia.com/"><img src="images/qt-logo.png" align="left" border="0" /></a></td>
<td width="1"> </td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a> · <a href="classes.html"><font color="#004faf">All Classes</font></a> · <a href="functions.html"><font color="#004faf">All Functions</font></a> · <a href="overviews.html"><font color="#004faf">Overviews</font></a></td></tr></table><h1 class="title">List of All Members for QDomText</h1>
<p>This is the complete list of members for <a href="qdomtext.html">QDomText</a>, including inherited members.</p>
<p><table class="propsummary" width="100%" border="0" cellpadding="0" cellspacing="0">
<tr><td width="45%" valign="top"><ul>
<li><div class="fn">enum <b><a href="qdomnode.html#EncodingPolicy-enum">EncodingPolicy</a></b></div></li>
<li><div class="fn">enum <b><a href="qdomnode.html#NodeType-enum">NodeType</a></b></div></li>
<li><div class="fn"><b><a href="qdomtext.html#QDomText">QDomText</a></b> ()</div></li>
<li><div class="fn"><b><a href="qdomtext.html#QDomText-2">QDomText</a></b> ( const QDomText & )</div></li>
<li><div class="fn"><b><a href="qdomnode.html#appendChild">appendChild</a></b> ( const QDomNode & ) : QDomNode</div></li>
<li><div class="fn"><b><a href="qdomcharacterdata.html#appendData">appendData</a></b> ( const QString & )</div></li>
<li><div class="fn"><b><a href="qdomnode.html#attributes">attributes</a></b> () const : QDomNamedNodeMap</div></li>
<li><div class="fn"><b><a href="qdomnode.html#childNodes">childNodes</a></b> () const : QDomNodeList</div></li>
<li><div class="fn"><b><a href="qdomnode.html#clear">clear</a></b> ()</div></li>
<li><div class="fn"><b><a href="qdomnode.html#cloneNode">cloneNode</a></b> ( bool ) const : QDomNode</div></li>
<li><div class="fn"><b><a href="qdomnode.html#columnNumber">columnNumber</a></b> () const : int</div></li>
<li><div class="fn"><b><a href="qdomcharacterdata.html#data">data</a></b> () const : QString</div></li>
<li><div class="fn"><b><a href="qdomcharacterdata.html#deleteData">deleteData</a></b> ( unsigned long, unsigned long )</div></li>
<li><div class="fn"><b><a href="qdomnode.html#firstChild">firstChild</a></b> () const : QDomNode</div></li>
<li><div class="fn"><b><a href="qdomnode.html#firstChildElement">firstChildElement</a></b> ( const QString & ) const : QDomElement</div></li>
<li><div class="fn"><b><a href="qdomnode.html#hasAttributes">hasAttributes</a></b> () const : bool</div></li>
<li><div class="fn"><b><a href="qdomnode.html#hasChildNodes">hasChildNodes</a></b> () const : bool</div></li>
<li><div class="fn"><b><a href="qdomnode.html#impl-var">impl</a></b> : QDomNodePrivate *</div></li>
<li><div class="fn"><b><a href="qdomnode.html#insertAfter">insertAfter</a></b> ( const QDomNode &, const QDomNode & ) : QDomNode</div></li>
<li><div class="fn"><b><a href="qdomnode.html#insertBefore">insertBefore</a></b> ( const QDomNode &, const QDomNode & ) : QDomNode</div></li>
<li><div class="fn"><b><a href="qdomcharacterdata.html#insertData">insertData</a></b> ( unsigned long, const QString & )</div></li>
<li><div class="fn"><b><a href="qdomnode.html#isAttr">isAttr</a></b> () const : bool</div></li>
<li><div class="fn"><b><a href="qdomnode.html#isCDATASection">isCDATASection</a></b> () const : bool</div></li>
<li><div class="fn"><b><a href="qdomnode.html#isCharacterData">isCharacterData</a></b> () const : bool</div></li>
<li><div class="fn"><b><a href="qdomnode.html#isComment">isComment</a></b> () const : bool</div></li>
<li><div class="fn"><b><a href="qdomnode.html#isDocument">isDocument</a></b> () const : bool</div></li>
<li><div class="fn"><b><a href="qdomnode.html#isDocumentFragment">isDocumentFragment</a></b> () const : bool</div></li>
<li><div class="fn"><b><a href="qdomnode.html#isDocumentType">isDocumentType</a></b> () const : bool</div></li>
<li><div class="fn"><b><a href="qdomnode.html#isElement">isElement</a></b> () const : bool</div></li>
<li><div class="fn"><b><a href="qdomnode.html#isEntity">isEntity</a></b> () const : bool</div></li>
<li><div class="fn"><b><a href="qdomnode.html#isEntityReference">isEntityReference</a></b> () const : bool</div></li>
<li><div class="fn"><b><a href="qdomnode.html#isNotation">isNotation</a></b> () const : bool</div></li>
<li><div class="fn"><b><a href="qdomnode.html#isNull">isNull</a></b> () const : bool</div></li>
<li><div class="fn"><b><a href="qdomnode.html#isProcessingInstruction">isProcessingInstruction</a></b> () const : bool</div></li>
<li><div class="fn"><b><a href="qdomnode.html#isSupported">isSupported</a></b> ( const QString &, const QString & ) const : bool</div></li>
<li><div class="fn"><b><a href="qdomnode.html#isText">isText</a></b> () const : bool</div></li>
<li><div class="fn"><b><a href="qdomnode.html#lastChild">lastChild</a></b> () const : QDomNode</div></li>
<li><div class="fn"><b><a href="qdomnode.html#lastChildElement">lastChildElement</a></b> ( const QString & ) const : QDomElement</div></li>
<li><div class="fn"><b><a href="qdomcharacterdata.html#length">length</a></b> () const : uint</div></li>
<li><div class="fn"><b><a href="qdomnode.html#lineNumber">lineNumber</a></b> () const : int</div></li>
</ul></td><td valign="top"><ul>
<li><div class="fn"><b><a href="qdomnode.html#localName">localName</a></b> () const : QString</div></li>
<li><div class="fn"><b><a href="qdomnode.html#namedItem">namedItem</a></b> ( const QString & ) const : QDomNode</div></li>
<li><div class="fn"><b><a href="qdomnode.html#namespaceURIx">namespaceURI</a></b> () const : QString</div></li>
<li><div class="fn"><b><a href="qdomnode.html#nextSibling">nextSibling</a></b> () const : QDomNode</div></li>
<li><div class="fn"><b><a href="qdomnode.html#nextSiblingElement">nextSiblingElement</a></b> ( const QString & ) const : QDomElement</div></li>
<li><div class="fn"><b><a href="qdomnode.html#nodeName">nodeName</a></b> () const : QString</div></li>
<li><div class="fn"><b><a href="qdomtext.html#nodeType">nodeType</a></b> () const : QDomNode::NodeType</div></li>
<li><div class="fn"><b><a href="qdomnode.html#nodeValue">nodeValue</a></b> () const : QString</div></li>
<li><div class="fn"><b><a href="qdomnode.html#normalize">normalize</a></b> ()</div></li>
<li><div class="fn"><b><a href="qdomnode.html#ownerDocument">ownerDocument</a></b> () const : QDomDocument</div></li>
<li><div class="fn"><b><a href="qdomnode.html#parentNode">parentNode</a></b> () const : QDomNode</div></li>
<li><div class="fn"><b><a href="qdomnode.html#prefix">prefix</a></b> () const : QString</div></li>
<li><div class="fn"><b><a href="qdomnode.html#previousSibling">previousSibling</a></b> () const : QDomNode</div></li>
<li><div class="fn"><b><a href="qdomnode.html#previousSiblingElement">previousSiblingElement</a></b> ( const QString & ) const : QDomElement</div></li>
<li><div class="fn"><b><a href="qdomnode.html#removeChild">removeChild</a></b> ( const QDomNode & ) : QDomNode</div></li>
<li><div class="fn"><b><a href="qdomnode.html#replaceChild">replaceChild</a></b> ( const QDomNode &, const QDomNode & ) : QDomNode</div></li>
<li><div class="fn"><b><a href="qdomcharacterdata.html#replaceData">replaceData</a></b> ( unsigned long, unsigned long, const QString & )</div></li>
<li><div class="fn"><b><a href="qdomnode.html#save">save</a></b> ( QTextStream &, int ) const</div></li>
<li><div class="fn"><b><a href="qdomnode.html#save-2">save</a></b> ( QTextStream &, int, EncodingPolicy ) const</div></li>
<li><div class="fn"><b><a href="qdomcharacterdata.html#setData">setData</a></b> ( const QString & )</div></li>
<li><div class="fn"><b><a href="qdomnode.html#setNodeValue">setNodeValue</a></b> ( const QString & )</div></li>
<li><div class="fn"><b><a href="qdomnode.html#setPrefix">setPrefix</a></b> ( const QString & )</div></li>
<li><div class="fn"><b><a href="qdomtext.html#splitText">splitText</a></b> ( int ) : QDomText</div></li>
<li><div class="fn"><b><a href="qdomcharacterdata.html#substringData">substringData</a></b> ( unsigned long, unsigned long ) : QString</div></li>
<li><div class="fn"><b><a href="qdomnode.html#toAttr">toAttr</a></b> () const : QDomAttr</div></li>
<li><div class="fn"><b><a href="qdomnode.html#toCDATASection">toCDATASection</a></b> () const : QDomCDATASection</div></li>
<li><div class="fn"><b><a href="qdomnode.html#toCharacterData">toCharacterData</a></b> () const : QDomCharacterData</div></li>
<li><div class="fn"><b><a href="qdomnode.html#toComment">toComment</a></b> () const : QDomComment</div></li>
<li><div class="fn"><b><a href="qdomnode.html#toDocument">toDocument</a></b> () const : QDomDocument</div></li>
<li><div class="fn"><b><a href="qdomnode.html#toDocumentFragment">toDocumentFragment</a></b> () const : QDomDocumentFragment</div></li>
<li><div class="fn"><b><a href="qdomnode.html#toDocumentType">toDocumentType</a></b> () const : QDomDocumentType</div></li>
<li><div class="fn"><b><a href="qdomnode.html#toElement">toElement</a></b> () const : QDomElement</div></li>
<li><div class="fn"><b><a href="qdomnode.html#toEntity">toEntity</a></b> () const : QDomEntity</div></li>
<li><div class="fn"><b><a href="qdomnode.html#toEntityReference">toEntityReference</a></b> () const : QDomEntityReference</div></li>
<li><div class="fn"><b><a href="qdomnode.html#toNotation">toNotation</a></b> () const : QDomNotation</div></li>
<li><div class="fn"><b><a href="qdomnode.html#toProcessingInstruction">toProcessingInstruction</a></b> () const : QDomProcessingInstruction</div></li>
<li><div class="fn"><b><a href="qdomnode.html#toText">toText</a></b> () const : QDomText</div></li>
<li><div class="fn"><b><a href="qdomnode.html#operator-not-eq">operator!=</a></b> ( const QDomNode & ) const : bool</div></li>
<li><div class="fn"><b><a href="qdomtext.html#operator-eq">operator=</a></b> ( const QDomText & ) : QDomText &</div></li>
<li><div class="fn"><b><a href="qdomnode.html#operator-eq-eq">operator==</a></b> ( const QDomNode & ) const : bool</div></li>
</ul>
</td></tr>
</table></p>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="40%" align="left">Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies)</td>
<td width="20%" align="center"><a href="trademarks.html">Trademarks</a></td>
<td width="40%" align="right"><div align="right">Qt 4.6.0</div></td>
</tr></table></div></address></body>
</html>
|
{
"pile_set_name": "Github"
}
|
//
// Blackfriday Markdown Processor
// Available at http://github.com/russross/blackfriday
//
// Copyright © 2011 Russ Ross <[email protected]>.
// Distributed under the Simplified BSD License.
// See README.md for details.
//
//
// Unit tests for full document parsing and rendering
//
package blackfriday
import (
"testing"
)
func runMarkdown(input string) string {
return string(MarkdownCommon([]byte(input)))
}
func doTests(t *testing.T, tests []string) {
// catch and report panics
var candidate string
defer func() {
if err := recover(); err != nil {
t.Errorf("\npanic while processing [%#v]: %s\n", candidate, err)
}
}()
for i := 0; i+1 < len(tests); i += 2 {
input := tests[i]
candidate = input
expected := tests[i+1]
actual := runMarkdown(candidate)
if actual != expected {
t.Errorf("\nInput [%#v]\nExpected[%#v]\nActual [%#v]",
candidate, expected, actual)
}
// now test every substring to stress test bounds checking
if !testing.Short() {
for start := 0; start < len(input); start++ {
for end := start + 1; end <= len(input); end++ {
candidate = input[start:end]
_ = runMarkdown(candidate)
}
}
}
}
}
func TestDocument(t *testing.T) {
var tests = []string{
// Empty document.
"",
"",
" ",
"",
// This shouldn't panic.
// https://github.com/russross/blackfriday/issues/172
"[]:<",
"<p>[]:<</p>\n",
// This shouldn't panic.
// https://github.com/russross/blackfriday/issues/173
" [",
"<p>[</p>\n",
}
doTests(t, tests)
}
|
{
"pile_set_name": "Github"
}
|
@mixin theme-border-color($theme) {
.card{
border-color: map-get($theme, card);
}
.recentlygames li, .viewall, .navview #statis li, .navview #graph li, .blog-social, .time-stats, .pcategories > .col-sm-9, .tag, .btnbox, .form-group .bar, .questionstatus .tab-content > ul > li, nav .card,.question-section,.report-question-section,.social-icons,.close-div,.no-card,.social-icons-gameOver,.social-icons-blog,.close-div{
border-color: map-get($theme, default);
}
.viewall:after{
border-color: map-get($theme, viewall-after);
}
#currentgame li .innerli,.btn-share, .questions li{
border-color: map-get($theme, currentgame-list);
}
.gameplay li, .questionstatus .tabbing li, .questionstatus .tabbing li.active,.viewbublic, .tag, .avatarimg, #file-name, .expertise{
border-color: map-get($theme, primary);
}
input[type="text"], input[type="email"], .submitpage textarea, .enterquestion .formfield > input, #currentgame li .innerli .yourimg, .gameOver .yourimg, .invitationlist img, .categorybox img,.withfriends label .labelimg img, .saccount .formfield select, .subscrib-cont input[type="email"],.custom-file-upload{
border-color: map-get($theme, input);
}
.viewall:hover,.btn-share:hover,#currentgame li .innerli:hover{
border-color: map-get($theme, hover);
}
.tabbing li.active{
border-color: map-get($theme, active);
}
.h1block{
border-color: map-get($theme, header-block);
}
.h1block:after{
border-color: map-get($theme, header-block-after);
}
.optionbox .radiobtn label, .withfriends,.friendsslider .owl-prev,.friendsslider .owl-next, .formfield select,textarea{
border-color: map-get($theme, form-options);
}
.question-list li input:checked ~ label:before, .optionbox .radiobtn label:after, .formfield input[type="checkbox"]:checked:after,.enterquestion .formfield input[type="radio"]:checked:after, .gameplay li:after{
border-color: map-get($theme, form-options-label);
}
.skyblue h3:before{
border-color: map-get($theme, skyblue-before);
}
.red h3:before{
border-color: map-get($theme, red-before);
}
.green h3:before{
border-color: map-get($theme, green-before);
}
.yellow h3:before{
border-color: map-get($theme, yellow-before);
}
.orrange h3:before{
border-color: map-get($theme, orange-before);
}
.bluegrey h3:before{
border-color: map-get($theme, bluegrey-before);
}
.optionbox input:checked + label, .formfield input[type="checkbox"]:before,.enterquestion .formfield input[type="radio"]:before, .gameplay li:hover, .gameplay li.right{
border-color: map-get($theme, form-checkbox);
}
.formfield input[type="checkbox"]:disabled:before {
border-color: map-get($theme, form-checkbox-disabled);
}
.secondbg{
border-color: map-get($theme, secondary);
&:before {
border-color: map-get($theme, secondary) transparent transparent transparent;
}
&:after {
border-color: map-get($theme, secondary-after) transparent transparent transparent;
}
}
.logininner .formfield input[type="checkbox"]:before, .gameplay li.wrong, .reasons{
border-color: map-get($theme, login);
}
.timer .dots{
border-color: map-get($theme, timer);
}
.optionbox input:checked + label:before, .gameplay li.right:before{
border-top-color: map-get($theme, form-checkbox-checked);
border-right-color: map-get($theme, form-checkbox-checked);
}
.gameplay li.wrong:before{
border-top-color: map-get($theme, gameplay-wrong);
border-right-color: map-get($theme, gameplay-wrong);
}
.submitpage textarea, .enterquestion .formfield > input{
box-shadow: map-get($theme, input-box-shadow);
}
@media screen and ( min-width:1000px) {
.categorybox{
border-color: map-get($theme, categorybox-lg);
}
.withfriends .owl-prev:hover,.withfriends .owl-next:hover, .viewbublic:hover{
border-color: map-get($theme, hover-lg);
}
}
.div-border
{
border-bottom-color: map-get($theme,card);
}
.csv-error-msg
{
border-top-color: map-get($theme, red-before);
}
.downloadFile,.custom-file-upload,.rejection-div,.add-tag-btn{
border-color: map-get($theme, download-btn);
}
.mat-list .mat-list-item
{
border-top-color: map-get($theme, primary);
}
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">{
"Info": [
{
"IsSuccess": "True",
"InAddress": "高雄市鹽埕區五福四路163號一樓",
"InSRS": "EPSG:4326",
"InFuzzyType": "[單雙號機制]+[最近門牌號機制]",
"InFuzzyBuffer": "0",
"InIsOnlyFullMatch": "False",
"InIsLockCounty": "True",
"InIsLockTown": "False",
"InIsLockVillage": "False",
"InIsLockRoadSection": "False",
"InIsLockLane": "False",
"InIsLockAlley": "False",
"InIsLockArea": "False",
"InIsSameNumber_SubNumber": "True",
"InCanIgnoreVillage": "True",
"InCanIgnoreNeighborhood": "True",
"InReturnMaxCount": "0",
"OutTotal": "1",
"OutMatchType": "完全比對",
"OutMatchCode": "[高雄市]\tFULL:1",
"OutTraceInfo": "[高雄市]\t { 完全比對 } 找到符合的門牌地址"
}
],
"AddressList": [
{
"FULL_ADDR": "高雄市鹽埕區江南里2鄰五福四路163號",
"COUNTY": "高雄市",
"TOWN": "鹽埕區",
"VILLAGE": "江南里",
"NEIGHBORHOOD": "2鄰",
"ROAD": "五福四路",
"SECTION": "",
"LANE": "",
"ALLEY": "",
"SUB_ALLEY": "",
"TONG": "",
"NUMBER": "163號",
"X": 120.283367,
"Y": 22.623469
}
]
}</string>
|
{
"pile_set_name": "Github"
}
|
// This is mul/mbl/mbl_read_double.cxx
//:
// \file
// \brief Asks question and waits for an answer
// \author tim
// hand crafted into vxl by gvw
//
// - Function Name: mbl_read_double
// - Synopsis: double mbl_read_double(char* q_str, double default_d)
// - Inputs: q_str: A question
// default_d: Default answer
// min_d: Min allowed value (optional)
// max_d: Max allowed value (optional)
// - Outputs: -
// - Returns: The answer or a default
// - Description: Asks question and waits for an answer.
// If the answer is a double, returns it.
// If the answer is an empty std::string (return)
// then returns default.
// Otherwise waits for another input.
// - References: -
// - Example:
// \code
// double new_scale = mbl_read_double("Scale?",1.00);
// double new_scale = mbl_read_double("Scale?",1.00,min_scale,max_scale);
// \endcode
#include <iostream>
#include <cstdio>
#include "mbl_read_double.h"
#ifdef _MSC_VER
# include "vcl_msvc_warnings.h"
#endif
constexpr int MAX_LEN = 40;
// If min_d != 0 or max_d != 0 then prints range but doesn't check that reply is in range
double RD_ReadDouble1(const char *q_str, double default_d,
double min_d, double max_d)
{
char reply[MAX_LEN];
while (true)
{
if (min_d==0 && max_d==0)
std::cout<<q_str<<" ("<<default_d<<") :";
else
std::cout<<q_str<<" ["<<min_d<<".."<<max_d<<"] ("<<default_d<<") :";
std::cout.flush();
if (std::fgets(reply,MAX_LEN,stdin)!=nullptr)
{
double r = default_d;
if (reply[0]=='\n' || std::sscanf(reply,"%lf",&r)>0)
return r;
}
}
}
double mbl_read_double(const char *q_str, double default_d)
{
return RD_ReadDouble1(q_str,default_d,0,0);
}
double mbl_read_double( const char *q_str, double default_d,
double min_d, double max_d)
{
while (true)
{
double R = RD_ReadDouble1(q_str,default_d,min_d,max_d);
if (R<min_d)
std::cout<<R<<": must be at least "<<min_d<<"\n";
else if (R>max_d)
std::cout<<R<<": must be no more than "<<max_d<<"\n";
else
return R; // acceptable
}
}
|
{
"pile_set_name": "Github"
}
|
{
"Version": {
"Target": "Jazz² Resurrection"
},
"Animations": {
"CoinGold": {
"Path": "Pickup/coin_gold.png",
"FrameRate": 5,
"Shader": "SmoothAnimNormal"
},
"CoinSilver": {
"Path": "Pickup/coin_silver.png",
"FrameRate": 5,
"Shader": "SmoothAnimNormal"
}
}
}
|
{
"pile_set_name": "Github"
}
|
<?php
if (! function_exists('posted_on')) {
/**
* Prints HTML with meta information for the current post-date/time.
*/
function posted_on()
{
$time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>';
if (get_the_time('U') !== get_the_modified_time('U')) {
$time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time><time class="updated" datetime="%3$s">%4$s</time>';
}
$time_string = sprintf(
$time_string,
esc_attr(get_the_date(DATE_W3C)),
esc_html(get_the_date()),
esc_attr(get_the_modified_date(DATE_W3C)),
esc_html(get_the_modified_date())
);
/* translators: %s: post date. */
$posted_on = sprintf(
esc_html_x('Posted on %s', 'post date', THEME_TD),
'<a href="'.esc_url(get_permalink()).'" rel="bookmark">'.$time_string.'</a>'
);
return '<span class="posted-on">'.$posted_on.'</span>';
}
}
if (! function_exists('posted_by')) {
/**
* Prints HTML with meta information for the current author.
*/
function posted_by()
{
/* translators: %s: post author. */
$byline = sprintf(
esc_html_x('by %s', 'post author', THEME_TD),
'<span class="author vcard"><a class="url fn n" href="'.esc_url(get_author_posts_url(get_the_author_meta('ID'))).'">'.esc_html(get_the_author()).'</a></span>'
);
return '<span class="byline">'.$byline.'</span>';
}
}
if (! function_exists('post_thumbnail')) {
/**
* Displays an optional post thumbnail.
*
* Wraps the post thumbnail in an anchor element on index views, or a div
* element when on single views.
*/
function post_thumbnail()
{
if (post_password_required() || is_attachment() || ! has_post_thumbnail()) {
return;
}
if (is_singular()) {
return sprintf(
'<div class="post-thumbnail">%s</div>',
get_the_post_thumbnail()
);
} else {
return sprintf(
'<a class="post-thumbnail" href="%s" aria-hidden="true" tabindex="-1">%s</a>',
get_permalink(),
get_the_post_thumbnail(null, 'post-thumbnail', [
'alt' => the_title_attribute(['echo' => false])
])
);
}
}
}
if (! function_exists('entry_footer')) {
/**
* Prints HTML with meta information for the categories, tags and comments.
*/
function entry_footer()
{
// Hide category and tag text for pages.
if ('post' === get_post_type()) {
/* translators: used between list items, there is a space after the comma */
$categories_list = get_the_category_list(esc_html__(', ', THEME_TD));
if ($categories_list) {
/* translators: 1: list of categories. */
printf(
'<span class="cat-links">'.esc_html__('Posted in %1$s', THEME_TD).'</span>',
$categories_list
);
}
/* translators: used between list items, there is a space after the comma */
$tags_list = get_the_tag_list('', esc_html_x(', ', 'list item separator', THEME_TD));
if ($tags_list) {
/* translators: 1: list of tags. */
printf(
'<span class="tags-links">'.esc_html__('Tagged %1$s', THEME_TD).'</span>',
$tags_list
);
}
}
if (! is_single() && ! post_password_required() && (comments_open() || get_comments_number())) {
echo '<span class="comments-link">';
comments_popup_link(
sprintf(
wp_kses(
/* translators: %s: post title */
__('Leave a Comment<span class="screen-reader-text"> on %s</span>', THEME_TD),
[
'span' => [
'class' => []
]
]
),
get_the_title()
)
);
echo '</span>';
}
edit_post_link(
sprintf(
wp_kses(
/* translators: %s: Name of current post. Only visible to screen readers */
__('Edit <span class="screen-reader-text">%s</span>', THEME_TD),
[
'span' => [
'class' => []
]
]
),
get_the_title()
),
'<span class="edit-link">',
'</span>'
);
}
}
if (! function_exists('comments_title')) {
/**
* Return the comments title.
*
* @param int $count The number of comments.
*
* @return string
*/
function comments_title($count)
{
if (1 === $count) {
return sprintf(
esc_html__('One thought on “%1$s”', THEME_TD),
'<span>'.get_the_title().'</span>'
);
}
return sprintf(
esc_html(_nx('%1$s thought on “%2$s”', '%1$s thoughts on “%2$s”', $count, 'comments title', THEME_TD)),
number_format_i18n($count),
'<span>'.get_the_title().'</span>'
);
}
}
if (! function_exists('archive_content_message')) {
/**
* Return an archive content message.
*
* @return string
*/
function archive_content_message()
{
return sprintf(
'<p>'.esc_html__('Try looking in the monthly archives. %1$s', THEME_TD).'</p>',
convert_smilies(':)')
);
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2017, Mellanox Technologies. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* 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.
*
* 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 <linux/mlx5/driver.h>
#include <linux/etherdevice.h>
#include <linux/idr.h>
#include "mlx5_core.h"
#include "lib/mlx5.h"
void mlx5_init_reserved_gids(struct mlx5_core_dev *dev)
{
unsigned int tblsz = MLX5_CAP_ROCE(dev, roce_address_table_size);
ida_init(&dev->roce.reserved_gids.ida);
dev->roce.reserved_gids.start = tblsz;
dev->roce.reserved_gids.count = 0;
}
void mlx5_cleanup_reserved_gids(struct mlx5_core_dev *dev)
{
WARN_ON(!ida_is_empty(&dev->roce.reserved_gids.ida));
dev->roce.reserved_gids.start = 0;
dev->roce.reserved_gids.count = 0;
ida_destroy(&dev->roce.reserved_gids.ida);
}
int mlx5_core_reserve_gids(struct mlx5_core_dev *dev, unsigned int count)
{
if (test_bit(MLX5_INTERFACE_STATE_UP, &dev->intf_state)) {
mlx5_core_err(dev, "Cannot reserve GIDs when interfaces are up\n");
return -EPERM;
}
if (dev->roce.reserved_gids.start < count) {
mlx5_core_warn(dev, "GID table exhausted attempting to reserve %d more GIDs\n",
count);
return -ENOMEM;
}
if (dev->roce.reserved_gids.count + count > MLX5_MAX_RESERVED_GIDS) {
mlx5_core_warn(dev, "Unable to reserve %d more GIDs\n", count);
return -ENOMEM;
}
dev->roce.reserved_gids.start -= count;
dev->roce.reserved_gids.count += count;
mlx5_core_dbg(dev, "Reserved %u GIDs starting at %u\n",
dev->roce.reserved_gids.count,
dev->roce.reserved_gids.start);
return 0;
}
void mlx5_core_unreserve_gids(struct mlx5_core_dev *dev, unsigned int count)
{
WARN(test_bit(MLX5_INTERFACE_STATE_UP, &dev->intf_state), "Unreserving GIDs when interfaces are up");
WARN(count > dev->roce.reserved_gids.count, "Unreserving %u GIDs when only %u reserved",
count, dev->roce.reserved_gids.count);
dev->roce.reserved_gids.start += count;
dev->roce.reserved_gids.count -= count;
mlx5_core_dbg(dev, "%u GIDs starting at %u left reserved\n",
dev->roce.reserved_gids.count,
dev->roce.reserved_gids.start);
}
int mlx5_core_reserved_gid_alloc(struct mlx5_core_dev *dev, int *gid_index)
{
int end = dev->roce.reserved_gids.start +
dev->roce.reserved_gids.count;
int index = 0;
index = ida_simple_get(&dev->roce.reserved_gids.ida,
dev->roce.reserved_gids.start, end,
GFP_KERNEL);
if (index < 0)
return index;
mlx5_core_dbg(dev, "Allocating reserved GID %u\n", index);
*gid_index = index;
return 0;
}
void mlx5_core_reserved_gid_free(struct mlx5_core_dev *dev, int gid_index)
{
mlx5_core_dbg(dev, "Freeing reserved GID %u\n", gid_index);
ida_simple_remove(&dev->roce.reserved_gids.ida, gid_index);
}
unsigned int mlx5_core_reserved_gids_count(struct mlx5_core_dev *dev)
{
return dev->roce.reserved_gids.count;
}
EXPORT_SYMBOL_GPL(mlx5_core_reserved_gids_count);
int mlx5_core_roce_gid_set(struct mlx5_core_dev *dev, unsigned int index,
u8 roce_version, u8 roce_l3_type, const u8 *gid,
const u8 *mac, bool vlan, u16 vlan_id, u8 port_num)
{
#define MLX5_SET_RA(p, f, v) MLX5_SET(roce_addr_layout, p, f, v)
u32 in[MLX5_ST_SZ_DW(set_roce_address_in)] = {0};
u32 out[MLX5_ST_SZ_DW(set_roce_address_out)] = {0};
void *in_addr = MLX5_ADDR_OF(set_roce_address_in, in, roce_address);
char *addr_l3_addr = MLX5_ADDR_OF(roce_addr_layout, in_addr,
source_l3_address);
void *addr_mac = MLX5_ADDR_OF(roce_addr_layout, in_addr,
source_mac_47_32);
int gidsz = MLX5_FLD_SZ_BYTES(roce_addr_layout, source_l3_address);
if (MLX5_CAP_GEN(dev, port_type) != MLX5_CAP_PORT_TYPE_ETH)
return -EINVAL;
if (gid) {
if (vlan) {
MLX5_SET_RA(in_addr, vlan_valid, 1);
MLX5_SET_RA(in_addr, vlan_id, vlan_id);
}
ether_addr_copy(addr_mac, mac);
MLX5_SET_RA(in_addr, roce_version, roce_version);
MLX5_SET_RA(in_addr, roce_l3_type, roce_l3_type);
memcpy(addr_l3_addr, gid, gidsz);
}
if (MLX5_CAP_GEN(dev, num_vhca_ports) > 0)
MLX5_SET(set_roce_address_in, in, vhca_port_num, port_num);
MLX5_SET(set_roce_address_in, in, roce_address_index, index);
MLX5_SET(set_roce_address_in, in, opcode, MLX5_CMD_OP_SET_ROCE_ADDRESS);
return mlx5_cmd_exec(dev, in, sizeof(in), out, sizeof(out));
}
EXPORT_SYMBOL(mlx5_core_roce_gid_set);
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) 2013-2015 RoboVM AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable 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.bugvm.apple.uikit;
/*<imports>*/
import java.io.*;
import java.nio.*;
import java.util.*;
import com.bugvm.objc.*;
import com.bugvm.objc.annotation.*;
import com.bugvm.objc.block.*;
import com.bugvm.rt.*;
import com.bugvm.rt.annotation.*;
import com.bugvm.rt.bro.*;
import com.bugvm.rt.bro.annotation.*;
import com.bugvm.rt.bro.ptr.*;
import com.bugvm.apple.foundation.*;
import com.bugvm.apple.coreanimation.*;
import com.bugvm.apple.coregraphics.*;
import com.bugvm.apple.coredata.*;
import com.bugvm.apple.coreimage.*;
import com.bugvm.apple.coretext.*;
import com.bugvm.apple.corelocation.*;
/*</imports>*/
/*<javadoc>*/
/*</javadoc>*/
/*<annotations>*//*</annotations>*/
/*<visibility>*/public/*</visibility>*/ class /*<name>*/UIAdaptivePresentationControllerDelegateAdapter/*</name>*/
extends /*<extends>*/NSObject/*</extends>*/
/*<implements>*/implements UIAdaptivePresentationControllerDelegate/*</implements>*/ {
/*<ptr>*/
/*</ptr>*/
/*<bind>*/
/*</bind>*/
/*<constants>*//*</constants>*/
/*<constructors>*//*</constructors>*/
/*<properties>*/
/*</properties>*/
/*<members>*//*</members>*/
/*<methods>*/
@NotImplemented("adaptivePresentationStyleForPresentationController:")
public UIModalPresentationStyle getAdaptivePresentationStyle(UIPresentationController controller) { return null; }
/**
* @since Available in iOS 8.3 and later.
*/
@NotImplemented("adaptivePresentationStyleForPresentationController:traitCollection:")
public UIModalPresentationStyle getAdaptivePresentationStyle(UIPresentationController controller, UITraitCollection traitCollection) { return null; }
@NotImplemented("presentationController:viewControllerForAdaptivePresentationStyle:")
public UIViewController getViewController(UIPresentationController controller, UIModalPresentationStyle style) { return null; }
/**
* @since Available in iOS 8.3 and later.
*/
@NotImplemented("presentationController:willPresentWithAdaptiveStyle:transitionCoordinator:")
public void willPresent(UIPresentationController presentationController, UIModalPresentationStyle style, UIViewControllerTransitionCoordinator transitionCoordinator) {}
/*</methods>*/
}
|
{
"pile_set_name": "Github"
}
|
# Source Map
[](https://travis-ci.org/mozilla/source-map)
[](https://www.npmjs.com/package/source-map)
This is a library to generate and consume the source map format
[described here][format].
[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
## Use with Node
$ npm install source-map
## Use on the Web
<script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script>
--------------------------------------------------------------------------------
<!-- `npm run toc` to regenerate the Table of Contents -->
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
## Table of Contents
- [Examples](#examples)
- [Consuming a source map](#consuming-a-source-map)
- [Generating a source map](#generating-a-source-map)
- [With SourceNode (high level API)](#with-sourcenode-high-level-api)
- [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api)
- [API](#api)
- [SourceMapConsumer](#sourcemapconsumer)
- [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap)
- [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans)
- [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition)
- [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition)
- [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition)
- [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources)
- [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing)
- [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order)
- [SourceMapGenerator](#sourcemapgenerator)
- [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap)
- [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer)
- [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping)
- [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent)
- [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath)
- [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring)
- [SourceNode](#sourcenode)
- [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name)
- [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath)
- [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk)
- [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk)
- [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent)
- [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn)
- [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn)
- [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep)
- [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement)
- [SourceNode.prototype.toString()](#sourcenodeprototypetostring)
- [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Examples
### Consuming a source map
```js
var rawSourceMap = {
version: 3,
file: 'min.js',
names: ['bar', 'baz', 'n'],
sources: ['one.js', 'two.js'],
sourceRoot: 'http://example.com/www/js/',
mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
};
var smc = new SourceMapConsumer(rawSourceMap);
console.log(smc.sources);
// [ 'http://example.com/www/js/one.js',
// 'http://example.com/www/js/two.js' ]
console.log(smc.originalPositionFor({
line: 2,
column: 28
}));
// { source: 'http://example.com/www/js/two.js',
// line: 2,
// column: 10,
// name: 'n' }
console.log(smc.generatedPositionFor({
source: 'http://example.com/www/js/two.js',
line: 2,
column: 10
}));
// { line: 2, column: 28 }
smc.eachMapping(function (m) {
// ...
});
```
### Generating a source map
In depth guide:
[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/)
#### With SourceNode (high level API)
```js
function compile(ast) {
switch (ast.type) {
case 'BinaryExpression':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
[compile(ast.left), " + ", compile(ast.right)]
);
case 'Literal':
return new SourceNode(
ast.location.line,
ast.location.column,
ast.location.source,
String(ast.value)
);
// ...
default:
throw new Error("Bad AST");
}
}
var ast = parse("40 + 2", "add.js");
console.log(compile(ast).toStringWithSourceMap({
file: 'add.js'
}));
// { code: '40 + 2',
// map: [object SourceMapGenerator] }
```
#### With SourceMapGenerator (low level API)
```js
var map = new SourceMapGenerator({
file: "source-mapped.js"
});
map.addMapping({
generated: {
line: 10,
column: 35
},
source: "foo.js",
original: {
line: 33,
column: 2
},
name: "christopher"
});
console.log(map.toString());
// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}'
```
## API
Get a reference to the module:
```js
// Node.js
var sourceMap = require('source-map');
// Browser builds
var sourceMap = window.sourceMap;
// Inside Firefox
const sourceMap = require("devtools/toolkit/sourcemap/source-map.js");
```
### SourceMapConsumer
A SourceMapConsumer instance represents a parsed source map which we can query
for information about the original file positions by giving it a file position
in the generated source.
#### new SourceMapConsumer(rawSourceMap)
The only parameter is the raw source map (either as a string which can be
`JSON.parse`'d, or an object). According to the spec, source maps have the
following attributes:
* `version`: Which version of the source map spec this map is following.
* `sources`: An array of URLs to the original source files.
* `names`: An array of identifiers which can be referenced by individual
mappings.
* `sourceRoot`: Optional. The URL root from which all sources are relative.
* `sourcesContent`: Optional. An array of contents of the original source files.
* `mappings`: A string of base64 VLQs which contain the actual mappings.
* `file`: Optional. The generated filename this source map is associated with.
```js
var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData);
```
#### SourceMapConsumer.prototype.computeColumnSpans()
Compute the last column for each generated mapping. The last column is
inclusive.
```js
// Before:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1 },
// { line: 2,
// column: 10 },
// { line: 2,
// column: 20 } ]
consumer.computeColumnSpans();
// After:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1,
// lastColumn: 9 },
// { line: 2,
// column: 10,
// lastColumn: 19 },
// { line: 2,
// column: 20,
// lastColumn: Infinity } ]
```
#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)
Returns the original source, line, and column information for the generated
source's line and column positions provided. The only argument is an object with
the following properties:
* `line`: The line number in the generated source. Line numbers in
this library are 1-based (note that the underlying source map
specification uses 0-based line numbers -- this library handles the
translation).
* `column`: The column number in the generated source. Column numbers
in this library are 0-based.
* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or
`SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest
element that is smaller than or greater than the one we are searching for,
respectively, if the exact element cannot be found. Defaults to
`SourceMapConsumer.GREATEST_LOWER_BOUND`.
and an object is returned with the following properties:
* `source`: The original source file, or null if this information is not
available.
* `line`: The line number in the original source, or null if this information is
not available. The line number is 1-based.
* `column`: The column number in the original source, or null if this
information is not available. The column number is 0-based.
* `name`: The original identifier, or null if this information is not available.
```js
consumer.originalPositionFor({ line: 2, column: 10 })
// { source: 'foo.coffee',
// line: 2,
// column: 2,
// name: null }
consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 })
// { source: null,
// line: null,
// column: null,
// name: null }
```
#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)
Returns the generated line and column information for the original source,
line, and column positions provided. The only argument is an object with
the following properties:
* `source`: The filename of the original source.
* `line`: The line number in the original source. The line number is
1-based.
* `column`: The column number in the original source. The column
number is 0-based.
and an object is returned with the following properties:
* `line`: The line number in the generated source, or null. The line
number is 1-based.
* `column`: The column number in the generated source, or null. The
column number is 0-based.
```js
consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 })
// { line: 1,
// column: 56 }
```
#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)
Returns all generated line and column information for the original source, line,
and column provided. If no column is provided, returns all mappings
corresponding to a either the line we are searching for or the next closest line
that has any mappings. Otherwise, returns all mappings corresponding to the
given line and either the column we are searching for or the next closest column
that has any offsets.
The only argument is an object with the following properties:
* `source`: The filename of the original source.
* `line`: The line number in the original source. The line number is
1-based.
* `column`: Optional. The column number in the original source. The
column number is 0-based.
and an array of objects is returned, each with the following properties:
* `line`: The line number in the generated source, or null. The line
number is 1-based.
* `column`: The column number in the generated source, or null. The
column number is 0-based.
```js
consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" })
// [ { line: 2,
// column: 1 },
// { line: 2,
// column: 10 },
// { line: 2,
// column: 20 } ]
```
#### SourceMapConsumer.prototype.hasContentsOfAllSources()
Return true if we have the embedded source content for every source listed in
the source map, false otherwise.
In other words, if this method returns `true`, then
`consumer.sourceContentFor(s)` will succeed for every source `s` in
`consumer.sources`.
```js
// ...
if (consumer.hasContentsOfAllSources()) {
consumerReadyCallback(consumer);
} else {
fetchSources(consumer, consumerReadyCallback);
}
// ...
```
#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])
Returns the original source content for the source provided. The only
argument is the URL of the original source file.
If the source content for the given source is not found, then an error is
thrown. Optionally, pass `true` as the second param to have `null` returned
instead.
```js
consumer.sources
// [ "my-cool-lib.clj" ]
consumer.sourceContentFor("my-cool-lib.clj")
// "..."
consumer.sourceContentFor("this is not in the source map");
// Error: "this is not in the source map" is not in the source map
consumer.sourceContentFor("this is not in the source map", true);
// null
```
#### SourceMapConsumer.prototype.eachMapping(callback, context, order)
Iterate over each mapping between an original source/line/column and a
generated line/column in this source map.
* `callback`: The function that is called with each mapping. Mappings have the
form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,
name }`
* `context`: Optional. If specified, this object will be the value of `this`
every time that `callback` is called.
* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or
`SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over
the mappings sorted by the generated file's line/column order or the
original's source/line/column order, respectively. Defaults to
`SourceMapConsumer.GENERATED_ORDER`.
```js
consumer.eachMapping(function (m) { console.log(m); })
// ...
// { source: 'illmatic.js',
// generatedLine: 1,
// generatedColumn: 0,
// originalLine: 1,
// originalColumn: 0,
// name: null }
// { source: 'illmatic.js',
// generatedLine: 2,
// generatedColumn: 0,
// originalLine: 2,
// originalColumn: 0,
// name: null }
// ...
```
### SourceMapGenerator
An instance of the SourceMapGenerator represents a source map which is being
built incrementally.
#### new SourceMapGenerator([startOfSourceMap])
You may pass an object with the following properties:
* `file`: The filename of the generated source that this source map is
associated with.
* `sourceRoot`: A root for all relative URLs in this source map.
* `skipValidation`: Optional. When `true`, disables validation of mappings as
they are added. This can improve performance but should be used with
discretion, as a last resort. Even then, one should avoid using this flag when
running tests, if possible.
```js
var generator = new sourceMap.SourceMapGenerator({
file: "my-generated-javascript-file.js",
sourceRoot: "http://example.com/app/js/"
});
```
#### SourceMapGenerator.fromSourceMap(sourceMapConsumer)
Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance.
* `sourceMapConsumer` The SourceMap.
```js
var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer);
```
#### SourceMapGenerator.prototype.addMapping(mapping)
Add a single mapping from original source line and column to the generated
source's line and column for this source map being created. The mapping object
should have the following properties:
* `generated`: An object with the generated line and column positions.
* `original`: An object with the original line and column positions.
* `source`: The original source file (relative to the sourceRoot).
* `name`: An optional original token name for this mapping.
```js
generator.addMapping({
source: "module-one.scm",
original: { line: 128, column: 0 },
generated: { line: 3, column: 456 }
})
```
#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)
Set the source content for an original source file.
* `sourceFile` the URL of the original source file.
* `sourceContent` the content of the source file.
```js
generator.setSourceContent("module-one.scm",
fs.readFileSync("path/to/module-one.scm"))
```
#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])
Applies a SourceMap for a source file to the SourceMap.
Each mapping to the supplied source file is rewritten using the
supplied SourceMap. Note: The resolution for the resulting mappings
is the minimum of this map and the supplied map.
* `sourceMapConsumer`: The SourceMap to be applied.
* `sourceFile`: Optional. The filename of the source file.
If omitted, sourceMapConsumer.file will be used, if it exists.
Otherwise an error will be thrown.
* `sourceMapPath`: Optional. The dirname of the path to the SourceMap
to be applied. If relative, it is relative to the SourceMap.
This parameter is needed when the two SourceMaps aren't in the same
directory, and the SourceMap to be applied contains relative source
paths. If so, those relative source paths need to be rewritten
relative to the SourceMap.
If omitted, it is assumed that both SourceMaps are in the same directory,
thus not needing any rewriting. (Supplying `'.'` has the same effect.)
#### SourceMapGenerator.prototype.toString()
Renders the source map being generated to a string.
```js
generator.toString()
// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}'
```
### SourceNode
SourceNodes provide a way to abstract over interpolating and/or concatenating
snippets of generated JavaScript source code, while maintaining the line and
column information associated between those snippets and the original source
code. This is useful as the final intermediate representation a compiler might
use before outputting the generated JS and source map.
#### new SourceNode([line, column, source[, chunk[, name]]])
* `line`: The original line number associated with this source node, or null if
it isn't associated with an original line. The line number is 1-based.
* `column`: The original column number associated with this source node, or null
if it isn't associated with an original column. The column number
is 0-based.
* `source`: The original source's filename; null if no filename is provided.
* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
below.
* `name`: Optional. The original identifier.
```js
var node = new SourceNode(1, 2, "a.cpp", [
new SourceNode(3, 4, "b.cpp", "extern int status;\n"),
new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"),
new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"),
]);
```
#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])
Creates a SourceNode from generated code and a SourceMapConsumer.
* `code`: The generated code
* `sourceMapConsumer` The SourceMap for the generated code
* `relativePath` The optional path that relative sources in `sourceMapConsumer`
should be relative to.
```js
var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8"));
var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"),
consumer);
```
#### SourceNode.prototype.add(chunk)
Add a chunk of generated JS to this source node.
* `chunk`: A string snippet of generated JS code, another instance of
`SourceNode`, or an array where each member is one of those things.
```js
node.add(" + ");
node.add(otherNode);
node.add([leftHandOperandNode, " + ", rightHandOperandNode]);
```
#### SourceNode.prototype.prepend(chunk)
Prepend a chunk of generated JS to this source node.
* `chunk`: A string snippet of generated JS code, another instance of
`SourceNode`, or an array where each member is one of those things.
```js
node.prepend("/** Build Id: f783haef86324gf **/\n\n");
```
#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)
Set the source content for a source file. This will be added to the
`SourceMap` in the `sourcesContent` field.
* `sourceFile`: The filename of the source file
* `sourceContent`: The content of the source file
```js
node.setSourceContent("module-one.scm",
fs.readFileSync("path/to/module-one.scm"))
```
#### SourceNode.prototype.walk(fn)
Walk over the tree of JS snippets in this node and its children. The walking
function is called once for each snippet of JS and is passed that snippet and
the its original associated source's line/column location.
* `fn`: The traversal function.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.walk(function (code, loc) { console.log("WALK:", code, loc); })
// WALK: uno { source: 'b.js', line: 3, column: 4, name: null }
// WALK: dos { source: 'a.js', line: 1, column: 2, name: null }
// WALK: tres { source: 'a.js', line: 1, column: 2, name: null }
// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null }
```
#### SourceNode.prototype.walkSourceContents(fn)
Walk over the tree of SourceNodes. The walking function is called for each
source file content and is passed the filename and source content.
* `fn`: The traversal function.
```js
var a = new SourceNode(1, 2, "a.js", "generated from a");
a.setSourceContent("a.js", "original a");
var b = new SourceNode(1, 2, "b.js", "generated from b");
b.setSourceContent("b.js", "original b");
var c = new SourceNode(1, 2, "c.js", "generated from c");
c.setSourceContent("c.js", "original c");
var node = new SourceNode(null, null, null, [a, b, c]);
node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); })
// WALK: a.js : original a
// WALK: b.js : original b
// WALK: c.js : original c
```
#### SourceNode.prototype.join(sep)
Like `Array.prototype.join` except for SourceNodes. Inserts the separator
between each of this source node's children.
* `sep`: The separator.
```js
var lhs = new SourceNode(1, 2, "a.rs", "my_copy");
var operand = new SourceNode(3, 4, "a.rs", "=");
var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()");
var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]);
var joinedNode = node.join(" ");
```
#### SourceNode.prototype.replaceRight(pattern, replacement)
Call `String.prototype.replace` on the very right-most source snippet. Useful
for trimming white space from the end of a source node, etc.
* `pattern`: The pattern to replace.
* `replacement`: The thing to replace the pattern with.
```js
// Trim trailing white space.
node.replaceRight(/\s*$/, "");
```
#### SourceNode.prototype.toString()
Return the string representation of this source node. Walks over the tree and
concatenates all the various snippets together to one string.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.toString()
// 'unodostresquatro'
```
#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])
Returns the string representation of this tree of source nodes, plus a
SourceMapGenerator which contains all the mappings between the generated and
original sources.
The arguments are the same as those to `new SourceMapGenerator`.
```js
var node = new SourceNode(1, 2, "a.js", [
new SourceNode(3, 4, "b.js", "uno"),
"dos",
[
"tres",
new SourceNode(5, 6, "c.js", "quatro")
]
]);
node.toStringWithSourceMap({ file: "my-output-file.js" })
// { code: 'unodostresquatro',
// map: [object SourceMapGenerator] }
```
|
{
"pile_set_name": "Github"
}
|
# Electron Release Timelines
* The `-beta.1` and `stable` dates are our solid release dates.
* We strive for weekly beta releases, however we often release more betas than scheduled.
* All dates are our goals but there may be reasons for adjusting the stable deadline, such as security bugs.
* Take a look at the [5.0.0 Timeline blog post](https://electronjs.org/blog/electron-5-0-timeline) for info about publicizing our release dates.
* Since Electron 6.0, we've been targetting every other Chromium version and releasing our stable on the same day as Chrome stable. You can reference Chromium's release schedule [here](https://chromiumdash.appspot.com/schedule). See [Electron's new release cadence blog post](https://www.electronjs.org/blog/12-week-cadence) for more details on our release schedule.
| Version | -beta.1 | Stable | Chrome | Node |
| ------- | ---------- | ---------- | ------ | ------ |
| 2.0.0 | 2018-02-21 | 2018-05-01 | M61 | v8.9 |
| 3.0.0 | 2018-06-21 | 2018-09-18 | M66 | v10.2 |
| 4.0.0 | 2018-10-11 | 2018-12-20 | M69 | v10.11 |
| 5.0.0 | 2019-01-22 | 2019-04-24 | M73 | v12.0 |
| 6.0.0 | 2019-05-01 | 2019-07-30 | M76 | v12.4 |
| 7.0.0 | 2019-08-01 | 2019-10-22 | M78 | v12.8 |
| 8.0.0 | 2019-10-24 | 2020-02-04 | M80 | v12.13 |
| 9.0.0 | 2020-02-06 | 2020-05-19 | M83 | v12.14 |
| 10.0.0 | 2020-05-21 | 2020-08-25 | M85 | v12.16 |
| 11.0.0 | 2020-08-27 | 2020-11-17 | M87 | v12.x |
| 12.0.0 | TBD | TBD | TBD | TBD |
|
{
"pile_set_name": "Github"
}
|
package constants
// TBS Config List
var (
DuplicatedAssertionLimitLength = 5
ASSERTION_LIST = []string{
"assert",
"should",
"check", // ArchUnit,
"maynotbe", // ArchUnit,
"is", // RestAssured,
"spec", // RestAssured,
"verify", // Mockito,
}
)
var TechStopWords = []string{
"get",
"create",
"update",
"delete",
"save",
"post",
"add",
"remove",
"insert",
"select",
"exist",
"find",
"new",
"parse",
"set",
"get",
"first",
"last",
"type",
"key",
"value",
"equal",
"greater",
"greater",
"all",
"by",
"id",
"is",
"of",
"not",
"with",
"main",
"status",
"count",
"equals",
"start",
"config",
"sort",
"handle",
"handler",
"internal",
"cache",
"request",
"process",
"parameter",
"method",
"class",
"default",
"object",
"annotation",
"read",
"write",
"bean",
"message",
"factory",
"error",
"errors",
"exception",
"null",
"string",
"init",
"data",
"hash",
"convert",
"size",
"build",
"return",
}
|
{
"pile_set_name": "Github"
}
|
/* Configure library by modifying this file */
#ifndef SNES_NTSC_CONFIG_H
#define SNES_NTSC_CONFIG_H
/* Format of source pixels */
/* #define SNES_NTSC_IN_FORMAT SNES_NTSC_RGB16 */
#define SNES_NTSC_IN_FORMAT SNES_NTSC_BGR15
/* The following affect the built-in blitter only; a custom blitter can
handle things however it wants. */
/* Bits per pixel of output. Can be 15, 16, 32, or 24 (same as 32). */
#define SNES_NTSC_OUT_DEPTH 32
/* Type of input pixel values */
#define SNES_NTSC_IN_T unsigned short
/* Each raw pixel input value is passed through this. You might want to mask
the pixel index if you use the high bits as flags, etc. */
#define SNES_NTSC_ADJ_IN( in ) in
/* For each pixel, this is the basic operation:
output_color = SNES_NTSC_ADJ_IN( SNES_NTSC_IN_T ) */
#endif
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Microsoft.Research.ClousotRegression;
using System.Diagnostics.Contracts;
public static class Test
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 42, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 54, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"assert unproven", PrimaryILOffset = 84, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 99, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 114, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 129, MethodILOffset = 0)]
public static void M(ref int x, ref int y)
{
Contract.Requires(x < 50);
if (x > 25)
{
y = x - 24;
Contract.Assert(y >= 0);
Contract.Assert(y < 50);
}
else
{
y = x + 25;
Contract.Assert(y >= 0, "not true if x < -25");
Contract.Assert(y <= 50);
}
Contract.Assert(y >= 0);
Contract.Assert(y <= 50);
}
}
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/waf/WAF_EXPORTS.h>
#include <aws/waf/WAFRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace WAF
{
namespace Model
{
/**
*/
class AWS_WAF_API GetIPSetRequest : public WAFRequest
{
public:
GetIPSetRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "GetIPSet"; }
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
/**
* <p>The <code>IPSetId</code> of the <a>IPSet</a> that you want to get.
* <code>IPSetId</code> is returned by <a>CreateIPSet</a> and by
* <a>ListIPSets</a>.</p>
*/
inline const Aws::String& GetIPSetId() const{ return m_iPSetId; }
/**
* <p>The <code>IPSetId</code> of the <a>IPSet</a> that you want to get.
* <code>IPSetId</code> is returned by <a>CreateIPSet</a> and by
* <a>ListIPSets</a>.</p>
*/
inline bool IPSetIdHasBeenSet() const { return m_iPSetIdHasBeenSet; }
/**
* <p>The <code>IPSetId</code> of the <a>IPSet</a> that you want to get.
* <code>IPSetId</code> is returned by <a>CreateIPSet</a> and by
* <a>ListIPSets</a>.</p>
*/
inline void SetIPSetId(const Aws::String& value) { m_iPSetIdHasBeenSet = true; m_iPSetId = value; }
/**
* <p>The <code>IPSetId</code> of the <a>IPSet</a> that you want to get.
* <code>IPSetId</code> is returned by <a>CreateIPSet</a> and by
* <a>ListIPSets</a>.</p>
*/
inline void SetIPSetId(Aws::String&& value) { m_iPSetIdHasBeenSet = true; m_iPSetId = std::move(value); }
/**
* <p>The <code>IPSetId</code> of the <a>IPSet</a> that you want to get.
* <code>IPSetId</code> is returned by <a>CreateIPSet</a> and by
* <a>ListIPSets</a>.</p>
*/
inline void SetIPSetId(const char* value) { m_iPSetIdHasBeenSet = true; m_iPSetId.assign(value); }
/**
* <p>The <code>IPSetId</code> of the <a>IPSet</a> that you want to get.
* <code>IPSetId</code> is returned by <a>CreateIPSet</a> and by
* <a>ListIPSets</a>.</p>
*/
inline GetIPSetRequest& WithIPSetId(const Aws::String& value) { SetIPSetId(value); return *this;}
/**
* <p>The <code>IPSetId</code> of the <a>IPSet</a> that you want to get.
* <code>IPSetId</code> is returned by <a>CreateIPSet</a> and by
* <a>ListIPSets</a>.</p>
*/
inline GetIPSetRequest& WithIPSetId(Aws::String&& value) { SetIPSetId(std::move(value)); return *this;}
/**
* <p>The <code>IPSetId</code> of the <a>IPSet</a> that you want to get.
* <code>IPSetId</code> is returned by <a>CreateIPSet</a> and by
* <a>ListIPSets</a>.</p>
*/
inline GetIPSetRequest& WithIPSetId(const char* value) { SetIPSetId(value); return *this;}
private:
Aws::String m_iPSetId;
bool m_iPSetIdHasBeenSet;
};
} // namespace Model
} // namespace WAF
} // namespace Aws
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<style xmlns="http://purl.org/net/xbiblio/csl" version="1.0" default-locale="en-US">
<info>
<title>Journal of Marketing Research</title>
<title-short>JMR</title-short>
<id>http://www.zotero.org/styles/journal-of-marketing-research</id>
<link href="http://www.zotero.org/styles/journal-of-marketing-research" rel="self"/>
<link href="http://www.zotero.org/styles/american-marketing-association" rel="independent-parent"/>
<link href="https://www.ama.org/publications/JournalOfMarketingResearch/Pages/JMR_Accepted_Ms.aspx#references" rel="documentation"/>
<category citation-format="author-date"/>
<category field="social_science"/>
<category field="communications"/>
<issn>0022-2437</issn>
<eissn>1547-7193</eissn>
<summary>Style for theJournal of Marketing Research, published by the American Marketing Association</summary>
<updated>2014-10-18T00:10:38+00:00</updated>
<rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights>
</info>
</style>
|
{
"pile_set_name": "Github"
}
|
package dev.olog.presentation.tutorial
import android.app.Activity
import android.content.Context
import android.view.View
import androidx.core.content.ContextCompat
import com.getkeepsafe.taptargetview.TapTarget
import com.getkeepsafe.taptargetview.TapTargetSequence
import com.getkeepsafe.taptargetview.TapTargetView
import dev.olog.presentation.R
import dev.olog.shared.android.extensions.colorAccent
import dev.olog.shared.android.extensions.colorBackground
object TutorialTapTarget {
fun sortBy(text: View, arrow: View){
val context = text.context
val textTarget = TapTarget.forView(text, context.getString(R.string.tutorial_sort_by_text))
.transparentTarget(true)
.tint(context)
val arrowTarget = TapTarget.forView(arrow, context.getString(R.string.tutorial_sort_by_arrow))
.icon(ContextCompat.getDrawable(context, R.drawable.vd_arrow_down))
.tint(context)
TapTargetSequence(text.context as Activity)
.targets(textTarget, arrowTarget)
.start()
}
fun floatingWindow(view: View){
val context = view.context
val target = TapTarget.forView(view, context.getString(R.string.tutorial_floating_window))
.icon(ContextCompat.getDrawable(context, R.drawable.vd_search_text))
.tint(context)
TapTargetView.showFor(view.context as Activity, target)
}
fun lyrics(view: View){
val context = view.context
val target = TapTarget.forView(view, context.getString(R.string.tutorial_lyrics))
.tint(context)
.icon(ContextCompat.getDrawable(context, R.drawable.vd_offline_lyrics))
TapTargetView.showFor(view.context as Activity, target)
}
fun addLyrics(search: View, edit: View, sync: View){
val context = search.context
val searchTarget = TapTarget.forView(search, context.getString(R.string.tutorial_search_lyrics))
.tint(context)
.icon(ContextCompat.getDrawable(context, R.drawable.vd_search))
val editTarget = TapTarget.forView(edit, context.getString(R.string.tutorial_add_lyrics))
.tint(context)
.icon(ContextCompat.getDrawable(context, R.drawable.vd_edit))
val syncLyrics = TapTarget.forView(sync, context.getString(R.string.tutorial_adjust_sync))
.tint(context)
.icon(ContextCompat.getDrawable(context, R.drawable.vd_sync))
TapTargetSequence(search.context as Activity)
.targets(editTarget, searchTarget, syncLyrics)
.start()
}
private fun TapTarget.tint(context: Context): TapTarget {
val accentColor = context.colorAccent()
val backgroundColor = context.colorBackground()
return this.tintTarget(true)
.outerCircleColorInt(accentColor)
.targetCircleColorInt(backgroundColor)
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* SQL Schema AWS tests
* Copyright (C) 2015-2020, Wazuh Inc.
* April 1, 2019.
* This program is a free software, you can redistribute it
* and/or modify it under the terms of GPLv2.
*/
CREATE TABLE 'cloudtrail' (
bucket_path 'text' NOT NULL,
aws_account_id 'text' NOT NULL,
aws_region 'text' NOT NULL,
log_key 'text' NOT NULL,
processed_date 'text' NOT NULL,
created_date 'integer' NOT NULL,
PRIMARY KEY (bucket_path, aws_account_id, aws_region, log_key));
INSERT INTO 'cloudtrail' (
bucket_path,
aws_account_id,
aws_region,
log_key,
processed_date,
created_date) VALUES (
'test-bucket/',
'123456789',
'us-east-1',
'AWSLogs/123456789/CloudTrail/us-east-1/2019/04/01/123456789_CloudTrail-us-east-1_20190401T0030Z_aaaa.json.gz',
DATETIME('now'),
'');
INSERT INTO 'cloudtrail' (
bucket_path,
aws_account_id,
aws_region,
log_key,
processed_date,
created_date) VALUES (
'test-bucket/',
'123456789',
'us-east-1',
'AWSLogs/123456789/CloudTrail/us-east-1/2019/04/01/123456789_CloudTrail-us-east-1_20190401T0000Z_aaab.json.gz',
DATETIME('now'),
'');
INSERT INTO 'cloudtrail' (
bucket_path,
aws_account_id,
aws_region,
log_key,
processed_date,
created_date) VALUES (
'test-bucket/',
'123456789',
'us-east-1',
'AWSLogs/123456789/CloudTrail/us-east-1/2019/04/01/123456789_CloudTrail-us-east-1_20190401T0000Z_aaaa.json.gz',
DATETIME('now'),
'');
INSERT INTO 'cloudtrail' (
bucket_path,
aws_account_id,
aws_region,
log_key,
processed_date,
created_date) VALUES (
'test-bucket/',
'123456789',
'us-east-1',
'AWSLogs/123456789/CloudTrail/us-east-1/2019/04/01/123456789_CloudTrail-us-east-1_20190401T0005Z_aaaa.json.gz',
DATETIME('now'),
'');
INSERT INTO 'cloudtrail' (
bucket_path,
aws_account_id,
aws_region,
log_key,
processed_date,
created_date) VALUES (
'test-bucket/',
'123456789',
'us-east-1',
'AWSLogs/123456789/CloudTrail/us-east-1/2019/04/01/123456789_CloudTrail-us-east-1_20190401T0020Z_aaaa.json.gz',
DATETIME('now'),
'');
INSERT INTO 'cloudtrail' (
bucket_path,
aws_account_id,
aws_region,
log_key,
processed_date,
created_date) VALUES (
'test-bucket/',
'123456789',
'us-east-1',
'AWSLogs/123456789/CloudTrail/us-east-1/2019/04/01/123456789_CloudTrail-us-east-1_20190401T0010Z_aaaa.json.gz',
DATETIME('now'),
'');
INSERT INTO 'cloudtrail' (
bucket_path,
aws_account_id,
aws_region,
log_key,
processed_date,
created_date) VALUES (
'test-bucket/',
'123456789',
'us-east-1',
'AWSLogs/123456789/CloudTrail/us-east-1/2019/04/01/123456789_CloudTrail-us-east-1_20190401T0025Z_aaaa.json.gz',
DATETIME('now'),
'');
INSERT INTO 'cloudtrail' (
bucket_path,
aws_account_id,
aws_region,
log_key,
processed_date,
created_date) VALUES (
'test-bucket/',
'123456789',
'us-east-1',
'AWSLogs/123456789/CloudTrail/us-east-1/2019/04/01/123456789_CloudTrail-us-east-1_20190401T00015Z_aaaa.json.gz',
DATETIME('now'),
'');
|
{
"pile_set_name": "Github"
}
|
div {
color: blue;
}
@function myFn($var-1,$var-2,$var-3,$var-4,$var-5,$var-6) {
@return $var-1*$var-2/$var-3-($var-4+$var-5)%$var-6;
}
|
{
"pile_set_name": "Github"
}
|
#include "COMPLETE.h"
BRAINFUCK(STDIN)
|
{
"pile_set_name": "Github"
}
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <string>
// basic_string<charT,traits,Allocator>&
// assign(basic_string<charT,traits>&& str);
#include <string>
#include <utility>
#include <cassert>
#include "test_macros.h"
#include "min_allocator.h"
template <class S>
void
test(S s, S str, S expected)
{
s.assign(std::move(str));
LIBCPP_ASSERT(s.__invariants());
assert(s == expected);
}
int main()
{
{
typedef std::string S;
test(S(), S(), S());
test(S(), S("12345"), S("12345"));
test(S(), S("1234567890"), S("1234567890"));
test(S(), S("12345678901234567890"), S("12345678901234567890"));
test(S("12345"), S(), S());
test(S("12345"), S("12345"), S("12345"));
test(S("12345"), S("1234567890"), S("1234567890"));
test(S("12345"), S("12345678901234567890"), S("12345678901234567890"));
test(S("1234567890"), S(), S());
test(S("1234567890"), S("12345"), S("12345"));
test(S("1234567890"), S("1234567890"), S("1234567890"));
test(S("1234567890"), S("12345678901234567890"), S("12345678901234567890"));
test(S("12345678901234567890"), S(), S());
test(S("12345678901234567890"), S("12345"), S("12345"));
test(S("12345678901234567890"), S("1234567890"), S("1234567890"));
test(S("12345678901234567890"), S("12345678901234567890"),
S("12345678901234567890"));
}
#if TEST_STD_VER >= 11
{
typedef std::basic_string<char, std::char_traits<char>, min_allocator<char>> S;
test(S(), S(), S());
test(S(), S("12345"), S("12345"));
test(S(), S("1234567890"), S("1234567890"));
test(S(), S("12345678901234567890"), S("12345678901234567890"));
test(S("12345"), S(), S());
test(S("12345"), S("12345"), S("12345"));
test(S("12345"), S("1234567890"), S("1234567890"));
test(S("12345"), S("12345678901234567890"), S("12345678901234567890"));
test(S("1234567890"), S(), S());
test(S("1234567890"), S("12345"), S("12345"));
test(S("1234567890"), S("1234567890"), S("1234567890"));
test(S("1234567890"), S("12345678901234567890"), S("12345678901234567890"));
test(S("12345678901234567890"), S(), S());
test(S("12345678901234567890"), S("12345"), S("12345"));
test(S("12345678901234567890"), S("1234567890"), S("1234567890"));
test(S("12345678901234567890"), S("12345678901234567890"),
S("12345678901234567890"));
}
#endif
}
|
{
"pile_set_name": "Github"
}
|
julia 0.4
|
{
"pile_set_name": "Github"
}
|
module VERIFICATION
imports TEST
endmodule
module TEST-4-SPEC
imports VERIFICATION
rule
<k> add(f(X), f(3)) => end </k>
<a> 2 |-> 3 M => ?_ </a>
endmodule
|
{
"pile_set_name": "Github"
}
|
{
"sorts": [
"数据展示",
"数据录入",
"操作反馈",
"导航组件",
"布局组件",
"基础组件",
"业务组件"
],
"packages": [{
"name": "Cell",
"version": "1.0.0",
"sort": "4",
"chnName": "列表项",
"type": "component",
"showDemo": true,
"desc": "列表项,可组合成列表",
"author": "Frans、玉磊"
},
{
"name": "Dialog",
"version": "1.0.0",
"sort": "2",
"chnName": "对话框",
"type": "method",
"showDemo": true,
"desc": "模态弹窗,支持按钮交互,支持图片弹窗。",
"star": 5,
"author": "Frans、肖晓"
},
{
"name": "Icon",
"version": "1.0.0",
"sort": "5",
"chnName": "图标",
"type": "component",
"showDemo": true,
"desc": "网页小图标。",
"author": "Frans"
},
{
"version": "1.0.0",
"name": "Toast",
"sort": "2",
"chnName": "吐司",
"desc": "轻提示。",
"type": "method",
"showDemo": true,
"star": 4,
"author": "Frans、张宇"
},
{
"version": "1.0.0",
"name": "ActionSheet",
"sort": "2",
"chnName": "动作面板",
"desc": "从底部弹出的动作菜单面板。",
"type": "component",
"showDemo": true,
"star": 5,
"author": "iris"
},
{
"version": "1.0.0",
"name": "Tab",
"sort": "3",
"chnName": "选项卡",
"desc": "常用于平级区域大块内容的的收纳和展现。",
"type": "component",
"showDemo": true,
"star": 3,
"author": "甄玉磊"
},
{
"version": "1.0.0",
"name": "TabPanel",
"sort": "3",
"chnName": "选项卡",
"desc": "标签栏 选项卡组件",
"type": "component",
"showDemo": false,
"author": "甄玉磊"
},
{
"version": "1.0.0",
"name": "TabBar",
"sort": "3",
"chnName": "标签栏",
"desc": "用于不同模块以之间的切换",
"type": "component",
"showDemo": true,
"star": 3,
"author": "甄玉磊"
},
{
"version": "1.0.0",
"name": "Calendar",
"sort": "1",
"chnName": "日历",
"desc": "日历",
"type": "component",
"showDemo": true,
"star": 5,
"author": "iris"
},
{
"version": "1.0.0",
"name": "DatePicker",
"sort": "1",
"chnName": "日期选择",
"desc": "日期选择",
"type": "component",
"showDemo": true,
"star": 5,
"author": "iris"
},
{
"version": "1.0.0",
"name": "NavBar",
"sort": "3",
"chnName": "导航栏",
"desc": "移动端头部导航栏",
"type": "component",
"showDemo": true,
"author": "lishaoqi"
},
{
"version": "1.0.0",
"name": "NoticeBar",
"sort": "3",
"chnName": "公告栏",
"desc": "移动端公告栏",
"type": "component",
"showDemo": true,
"author": "wangyue"
},
{
"name": "Switch",
"version": "1.0.0",
"sort": "1",
"chnName": "开关",
"type": "component",
"showDemo": true,
"desc": "滑动开关,通过点击使按钮左右滑动,同时触发对应的开关状态",
"author": "Frans"
},
{
"version": "1.0.0",
"name": "Slider",
"sort": "1",
"chnName": "滑块",
"desc": "滑动输入器,用于在数值区间/自定义区间内进行选择。",
"type": "component",
"showDemo": true,
"star": 4,
"author": "Frans"
},
{
"version": "1.0.0",
"name": "Range",
"sort": "1",
"chnName": "区间选择器",
"desc": "区间选择器组件",
"type": "component",
"showDemo": true,
"star": 4,
"author": "famanoder"
},
{
"version": "1.0.0",
"name": "Picker",
"sort": "1",
"chnName": "拾取器",
"desc": "提供多个选项集合供用户选择其中一项。",
"type": "component",
"showDemo": true,
"star": 5,
"author": "iris"
},
{
"version": "1.0.0",
"name": "Progress",
"sort": "2",
"chnName": "进度条",
"desc": "展示操作或任务的当前进度,比如上传文件。",
"type": "component",
"showDemo": true,
"author": "张毓飞"
},
{
"version": "1.0.0",
"name": "Price",
"sort": "0",
"chnName": "商品价格",
"desc": "商品价格组件,支持小数点前后应用不同样式、千位分隔、人民币符号等功能",
"type": "component",
"showDemo": true,
"author": "liaoyanli5"
},
{
"version": "1.0.0",
"name": "Flex",
"sort": "4",
"chnName": "Flex布局",
"desc": "Flex布局速简便地创建布局",
"type": "component",
"showDemo": true,
"author": "秦伟伟,苏子刚"
},
{
"version": "1.0.0",
"name": "Col",
"sort": "4",
"chnName": "Flex布局",
"desc": "Flex布局速简便地创建布局",
"type": "component",
"showDemo": false,
"author": "秦伟伟,苏子刚"
},
{
"version": "1.0.0",
"name": "Row",
"sort": "4",
"chnName": "Flex布局",
"desc": "Flex布局速简便地创建布局",
"type": "component",
"showDemo": false,
"author": "秦伟伟,苏子刚"
},
{
"version": "1.0.0",
"name": "Steps",
"sort": "0",
"chnName": "步骤条",
"desc": "拆分展示某项流程的步骤,引导用户按流程完成任务或向用户展示当前状态。",
"type": "component",
"showDemo": true,
"author": "宋其斌"
},
{
"version": "1.0.0",
"name": "Button",
"sort": "5",
"chnName": "按钮",
"desc": "各式各样的按钮",
"type": "component",
"showDemo": true,
"author": "杨磊"
},
{
"version": "1.0.0",
"name": "Badge",
"sort": "0",
"chnName": "徽标",
"desc": "出现在图标或文字右上角的红色圆点、数字或者文字,表示有新内容或者待处理的信息",
"type": "component",
"showDemo": true,
"author": "杨磊"
},
{
"version": "1.0.0",
"name": "Rate",
"sort": "1",
"chnName": "评分",
"desc": "用于快速的评级操作,或对评价进行展示。",
"type": "component",
"showDemo": true,
"star": 4,
"author": "永无止晋"
},
{
"version": "1.0.1",
"name": "Swiper",
"chnName": "滑动切换",
"sort": "0",
"desc": "常用于一组图片或卡片轮播,当内容空间不足时,可以用走马灯的形式进行收纳,进行轮播展现。",
"type": "component",
"showDemo": true,
"star": 5,
"author": "wangnan31"
},
{
"version": "1.0.0",
"name": "Menu",
"sort": "3",
"chnName": "菜单",
"desc": "菜单",
"type": "component",
"showDemo": true,
"author": "苏子刚"
},
{
"version": "1.0.0",
"name": "Stepper",
"chnName": "步进器",
"desc": "通过点击按钮控制数字加减",
"type": "component",
"sort": "1",
"showDemo": true,
"star": 3,
"author": "famanoder"
},
{
"version": "1.0.0",
"name": "ButtonGroup",
"chnName": "按钮组",
"desc": "用于页面底部的按钮组",
"type": "component",
"sort": "5",
"showDemo": true,
"author": "杨磊"
},
{
"version": "1.0.0",
"name": "SearchBar",
"chnName": "搜索栏",
"desc": "搜索栏",
"type": "component",
"sort": "1",
"showDemo": true,
"author": "lemon"
},
{
"version": "1.0.0",
"name": "ImagePicker",
"sort": "1",
"chnName": "图片选择器",
"desc": "图片选择器",
"type": "component",
"showDemo": true,
"author": "苏子刚"
},
{
"name": "Radio",
"version": "1.0.0",
"sort": "1",
"chnName": "单选按钮",
"type": "component",
"showDemo": true,
"desc": "单选按钮,可组合成单选按钮组",
"author": "Frans"
},
{
"name": "RadioGroup",
"version": "1.0.0",
"sort": "1",
"chnName": "单选按钮组",
"type": "component",
"showDemo": false,
"desc": "单选按钮组",
"author": "Frans"
},
{
"version": "1.0.0",
"name": "CheckBox",
"sort": "1",
"chnName": "复选按钮",
"desc": "复选多个选项",
"type": "component",
"showDemo": true,
"author": "Vicky.Ye"
},
{
"version": "1.0.0",
"name": "CheckBoxGroup",
"sort": "1",
"chnName": "复选按钮组",
"desc": "成组出现的复选按钮组件",
"type": "component",
"showDemo": true,
"author": "Vicky.Ye"
},
{
"version": "1.0.0",
"name": "ShortPassword",
"chnName": "短密码",
"des": "短密码",
"type": "component",
"sort": "1",
"showDemo": true,
"author": "wangnan31"
},
{
"version": "1.0.0",
"name": "Skeleton",
"chnName": "骨架屏",
"des": "在页面上待加载区域填充灰色的占位图,本质上是界面加载过程中的过渡效果",
"type": "component",
"sort": "0",
"showDemo": true,
"author": "wangnan31"
},
{
"version": "1.0.0",
"name": "Scroller",
"chnName": "滚动",
"desc": "滚动组件",
"type": "component",
"sort": "0",
"star": 5,
"showDemo": true,
"author": "iris"
},
{
"version": "1.0.0",
"name": "BackTop",
"chnName": "回到顶部",
"desc": "用于页面内容高度过长,快捷回到顶部使用。",
"type": "component",
"sort": "2",
"showDemo": true,
"author": "永无止晋、richard1015"
},
{
"version": "1.0.0",
"name": "CountDown",
"chnName": "倒计时",
"desc": "倒计时组件",
"type": "component",
"sort": "0",
"showDemo": true,
"author": "famanoder"
},
{
"version": "1.0.0",
"name": "InfiniteLoading",
"chnName": "无限加载",
"desc": "无限加载",
"type": "component",
"sort": "0",
"star": 4,
"showDemo": true,
"author": "iris"
},
{
"version": "1.0.0",
"name": "Uploader",
"chnName": "上传",
"desc": "文件上传组件",
"type": "component",
"sort": "5",
"showDemo": true,
"author": "林如风"
},
{
"version": "1.0.0",
"name": "TextInput",
"chnName": "文本框",
"desc": "单行文本框",
"type": "component",
"sort": "1",
"showDemo": true,
"author": "Frans"
},
{
"version": "1.0.0",
"name": "Avatar",
"chnName": "头像",
"desc": "用来表示用户或事物,支持图片或字符展示。",
"type": "component",
"sort": "5",
"showDemo": true,
"author": "zhenyulei"
},
{
"version": "1.0.0",
"name": "Lazyload",
"chnName": "图片懒加载",
"desc": "图片懒加载",
"type": "component",
"sort": "0",
"showDemo": true,
"author": "richard1015"
},
{
"version": "1.0.0",
"name": "TextBox",
"chnName": "文本域",
"desc": "文本域",
"type": "component",
"sort": "1",
"showDemo": true,
"author": "guoxiaoxiao"
},
{
"version": "1.0.0",
"name": "Elevator",
"chnName": "电梯楼层",
"desc": "类似于电梯楼层,组件可以跟着右侧索引而滑动",
"type": "component",
"sort": "3",
"showDemo": true,
"author": "zhenyulei"
},
{
"version": "1.0.0",
"name": "Popup",
"chnName": "弹出层",
"desc": "弹出层",
"type": "component",
"sort": "5",
"showDemo": true,
"author": "杨凯旋"
},
{
"version": "1.0.0",
"name": "LeftSlip",
"chnName": "左滑删除",
"desc": "手势左滑删除元素",
"type": "component",
"sort": "2",
"showDemo": true,
"author": "vickyYE"
},
{
"version": "1.0.0",
"name": "TabSelect",
"chnName": "配送时间",
"desc": "两级配送时间",
"type": "component",
"sort": "6",
"showDemo": true,
"author": "dsj"
},
{
"version": "1.0.0",
"name": "LuckDraw",
"chnName": "转盘抽奖",
"desc": "可设置中奖奖品,转动时间,中奖标识等",
"type": "component",
"sort": "6",
"showDemo": true,
"author": "Ymm0008"
},
{
"version": "1.0.0",
"name": "Video",
"chnName": "视频",
"desc": "视频播放器",
"type": "component",
"sort": "0",
"showDemo": true,
"author": "VickyYe"
},
{
"version": "1.0.0",
"name": "Signature",
"chnName": "签名",
"desc": "签名",
"type": "component",
"sort": "6",
"showDemo": true,
"author": "irisSong"
},
{
"version": "1.0.0",
"name": "CircleProgress",
"chnName": "圆形进度条",
"desc": "显示当前任务的操作进度",
"type": "component",
"sort": "2",
"showDemo": true,
"author": "zyf"
},
{
"version": "1.0.0",
"name": "TimeLineItem",
"chnName": "时间轴节点",
"desc": "定义时间轴节点",
"type": "component",
"sort": "0",
"showDemo": false,
"author": "yangxiaolu"
},
{
"version": "1.0.0",
"name": "TimeLine",
"chnName": "时间轴节点",
"desc": "定义时间轴节点",
"type": "component",
"sort": "0",
"showDemo": true,
"author": "yangxiaolu"
},
{
"version": "1.0.0",
"name": "SideNavBar",
"chnName": "侧边栏导航",
"desc": "侧边栏导航",
"type": "component",
"sort": "3",
"showDemo": true,
"author": "szg2008"
},
{
"version": "1.0.0",
"name": "SubSideNavBar",
"chnName": "侧边栏导航",
"desc": "侧边栏导航",
"type": "component",
"sort": "3",
"showDemo": false,
"author": "szg2008"
},
{
"version": "1.0.0",
"name": "SideNavBarItem",
"chnName": "侧边栏导航",
"desc": "侧边栏导航",
"type": "component",
"sort": "3",
"showDemo": false,
"author": "szg2008"
},
{
"name": "Drag",
"chnName": "拖拽",
"desc": "实现可拖拽的任意元素",
"type": "component",
"sort": "5",
"showDemo": true,
"author": "张宇"
},
{
"version": "1.0.0",
"name": "Address",
"chnName": "地址选择",
"desc": "业务功能-地址选择",
"type": "component",
"sort": "6",
"showDemo": true,
"author": "yangxiaolu"
},
{
"version": "1.0.0",
"name": "Notify",
"type": "method",
"chnName": "展示消息提示",
"desc": "在页面顶部展示消息提示,支持函数调用和组件调用两种方式",
"sort": "2",
"showDemo": true,
"author": "wangyue217"
},
{
"name": "CountUp",
"type": "component",
"chnName": "数字滚动",
"desc": "用于数据展示",
"sort": "0",
"showDemo": true,
"author": "Ymm0008"
},
{
"name": "FixedNav",
"type": "component",
"chnName": "悬浮导航",
"desc": "拖拽导航",
"sort": "3",
"showDemo": true,
"author": "richard1015"
},
{
"version": "1.0.0",
"name": "Collapse",
"type": "component",
"chnName": "折叠面板",
"desc": "可以折叠/展开的内容区域",
"sort": "0",
"showDemo": true,
"author": "Ymm0008",
"showTest": true
},
{
"version": "1.0.0",
"name": "Luckycard",
"type": "component",
"chnName": "刮刮卡",
"desc": "挂挂卡抽奖",
"sort": "6",
"showDemo": true,
"author": "guoxiao"
},
{
"version": "1.0.0",
"name": "NumberKeyboard",
"type": "component",
"chnName": "数字键盘",
"desc": "数字虚拟键盘,自定义键盘",
"sort": "1",
"showDemo": true,
"author": "Ymm0008",
"showTest": true
}
]
}
|
{
"pile_set_name": "Github"
}
|
import { NgModule } from '@angular/core';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatListModule } from '@angular/material/list';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatToolbarModule } from '@angular/material/toolbar';
const modules = [
MatDividerModule,
MatIconModule,
MatListModule,
MatProgressBarModule,
MatSidenavModule,
MatToolbarModule
];
@NgModule({
exports: [...modules],
imports: [...modules]
})
export class MaterialModule {}
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// Dart test program importing with show/hide combinators.
library importCombinatorsNegativeTest;
import "import1_lib.dart" show hide, show hide ugly;
main() {
print(hide);
print(show);
print(ugly); // Resolution error, identifier 'ugly ' is hidden.
}
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.