问:
How to use formatPercentage and renderDataTable together
I'd like to use formatPercentage,rowname=FALSE in renderDataTable. See below code Method 1 contains formatPercentage and Method 2 contains rowname=FALSE. I'd like to merge them together but keeps getting errors (renderDataTable ignores ... arguments when expr yields a datatable object; see ?renderDataTable). How do I do this?

Method 1 contains formatPercentage but can't pass renderDataTable options:

```<code># Method 1 format Percentage
output$funddetails <- DT::renderDataTable(
      DT::datatable({
      heatmap_raw[heatmap_raw$Keeper%in%
                    input$selectkeeper&month(heatmap_raw$period)%in%
                    input$selectmonth,c("apid","Fund Name","Status","Comments","Last Update by Keeper","Most Recent Portfolio")]
      })%>%formatPercentage(1, 2)
)
</code>```

Method 2 only contains options for renderDataTable but I can't use formatPercentage:

```<code>#Method 2
data_fund <- reactive({
    heatmap_raw[heatmap_raw$Keeper%in%
        input$selectkeeper&month(heatmap_raw$period)%in%
        input$selectmonth,c("apid","Fund Name","Status","Comments","Last Update by Keeper","Most Recent Portfolio")]
})

output$funddetails <- DT::renderDataTable(
  data_fund(),
  rowname=FALSE,
  options = list(
    pageLength=10,
    #autoWidth = TRUE,
    lengthMenu = list(c(25, 50, -1), c('25', '50', 'All')),
    searchHighlight = TRUE,
    scrollX=TRUE
  )
)
</code>```

答:
I think your problem with method 1 is due to the position of the curly brackets of the datatable command. You don't need them actually. Here is an example that should work for you:</p>

```<code>library(shiny)

shinyApp(

  ui = fluidPage(
    DT::dataTableOutput('tbl')
  ),

  server = function(input, output) {
    output$tbl = DT::renderDataTable(
      datatable(iris,
                rowname=FALSE,
                options = list(
                  pageLength=10,
                  #autoWidth = TRUE,
                  lengthMenu = list(c(25, 50, -1), c('25', '50', 'All')),
                  searchHighlight = TRUE,
                  scrollX=TRUE)
      ) %>% formatPercentage(1, 2)
    )
  }
)
</code>```

Body:
I'd like to use formatPercentage,rowname=FALSE in renderDataTable. See below code Method 1 contains formatPercentage and Method 2 contains rowname=FALSE. I'd like to merge them together but keeps getting errors (renderDataTable ignores ... arguments when expr yields a datatable object; see ?renderDataTable). How do I do this?

Method 1 contains formatPercentage but can't pass renderDataTable options:

# Method 1 format Percentage
output$funddetails <- DT::renderDataTable(
      DT::datatable({
      heatmap_raw[heatmap_raw$Keeper%in%
                    input$selectkeeper&month(heatmap_raw$period)%in%
                    input$selectmonth,c("apid","Fund Name","Status","Comments","Last Update by Keeper","Most Recent Portfolio")]
      })%>%formatPercentage(1, 2)
)

Method 2 only contains options for renderDataTable but I can't use formatPercentage:

#Method 2
data_fund <- reactive({
    heatmap_raw[heatmap_raw$Keeper%in%
        input$selectkeeper&month(heatmap_raw$period)%in%
        input$selectmonth,c("apid","Fund Name","Status","Comments","Last Update by Keeper","Most Recent Portfolio")]
})

output$funddetails <- DT::renderDataTable(
  data_fund(),
  rowname=FALSE,
  options = list(
    pageLength=10,
    #autoWidth = TRUE,
    lengthMenu = list(c(25, 50, -1), c('25', '50', 'All')),
    searchHighlight = TRUE,
    scrollX=TRUE
  )
)

Body:
I think your problem with method 1 is due to the position of the curly brackets of the datatable command. You don't need them actually. Here is an example that should work for you:

library(shiny)

shinyApp(

  ui = fluidPage(
    DT::dataTableOutput('tbl')
  ),

  server = function(input, output) {
    output$tbl = DT::renderDataTable(
      datatable(iris,
                rowname=FALSE,
                options = list(
                  pageLength=10,
                  #autoWidth = TRUE,
                  lengthMenu = list(c(25, 50, -1), c('25', '50', 'All')),
                  searchHighlight = TRUE,
                  scrollX=TRUE)
      ) %>% formatPercentage(1, 2)
    )
  }
)


来源: stackexchange

问:
How to select a picker view item in an iOS UI test in Xcode?
I have a picker view with few items: "Red", "Green", "Yellow", "Black". In my UI test I need to select a specific item "Green" from it. I am using the  XCTest UI testing APIs that were intruduced with Xcode 7.

What I managed to do so far is to swipe the whole picker view up in the unit test. It is not ideal because it always changes the picker view to the bottom item (when swiping up).

```<code>let app = XCUIApplication()
app.launch()
app.pickers.elementAtIndex(0).swipeUp()
XCTAssert(app.staticTexts["Selected: Black"].exists)
</code>```

Another but very similar way of changing the picker view is to call pressForDuration ... thenDragToElement, which is not what I want.

```<code>app.pickers.elementAtIndex(0).pressForDuration(0.1, thenDragToElement: someElement)
</code>```

When I use the UI test record function it does not record the picker view scrolling events. It does record when I tap on picker view items:

```<code>app.pickerWheels["Green"].tap()
</code>```

but that does not actually work when the test is run (probably because it needs to scroll the picker view first before tapping).

Here is the demo app with the test.

https://github.com/exchangegroup/PickerViewTestDemo

Update

It is now possible to select a picker view since Xcode 7.0 beta 6 .

```<code>app.pickerWheels["Green"].adjustToPickerWheelValue("Yellow")
</code>```

答:
Swift 4 version of @Joao_dche's answer

```<code>app.pickerWheels.element(boundBy: 0).adjust(toPickerWheelValue: "March")
app.pickerWheels.element(boundBy: 1).adjust(toPickerWheelValue: "13")
app.pickerWheels.element(boundBy: 2).adjust(toPickerWheelValue: "1990")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a picker view with few items: "Red", "Green", "Yellow", "Black". In my UI test I need to select a specific item "Green" from it. I am using the  XCTest UI testing APIs that were intruduced with Xcode 7.

What I managed to do so far is to swipe the whole picker view up in the unit test. It is not ideal because it always changes the picker view to the bottom item (when swiping up).

let app = XCUIApplication()
app.launch()
app.pickers.elementAtIndex(0).swipeUp()
XCTAssert(app.staticTexts["Selected: Black"].exists)

Another but very similar way of changing the picker view is to call pressForDuration ... thenDragToElement, which is not what I want.

app.pickers.elementAtIndex(0).pressForDuration(0.1, thenDragToElement: someElement)

When I use the UI test record function it does not record the picker view scrolling events. It does record when I tap on picker view items:

app.pickerWheels["Green"].tap()

but that does not actually work when the test is run (probably because it needs to scroll the picker view first before tapping).

Here is the demo app with the test.

https://github.com/exchangegroup/PickerViewTestDemo

Update

It is now possible to select a picker view since Xcode 7.0 beta 6 .

app.pickerWheels["Green"].adjustToPickerWheelValue("Yellow")

Body:
Swift 4 version of @Joao_dche's answer

app.pickerWheels.element(boundBy: 0).adjust(toPickerWheelValue: "March")
app.pickerWheels.element(boundBy: 1).adjust(toPickerWheelValue: "13")
app.pickerWheels.element(boundBy: 2).adjust(toPickerWheelValue: "1990")

ContentLicense: CC BY-SA 4.0


问:
How to change visibility of a input field in Aurelia?
I have following form in Aurelia. In the top of the form, there's a drop down menu to select user type. There are only two options. I need to show and hide some input fields when user change the type.

I.E : When user select type as 'Producer', I need to hide username. When user select 'Writer' , I need to show username and also hide email address. Like this. Need to do this using JavaScript controller.

https://gist.github.com/chanakaDe/75934983cb4a02a7a8914959e38bf0f3

This is the HTML code as a github gist. Please give me a solution for this.

答:
You can use show.bind (if you just want to show and hide the element), or if.bind (if you want to add and remove it form the DOM). For instance:

```<code><div class="form-group" id="div_username" if.bind="user_type === 'writer'">
  <label for="userame">Username:</label>
  <input type="text" class="form-control" id="userame" value.bind="userame" placeholder="Userame">
</div>
</code>```

Runnable example https://gist.run/?id=33db6b8f919eb95d63b8bfbc2e912fe5 - Change the User Type to 'writer' and you'll see the Username input.

Body:
You can use show.bind (if you just want to show and hide the element), or if.bind (if you want to add and remove it form the DOM). For instance:

<div class="form-group" id="div_username" if.bind="user_type === 'writer'">
  <label for="userame">Username:</label>
  <input type="text" class="form-control" id="userame" value.bind="userame" placeholder="Userame">
</div>

Runnable example https://gist.run/?id=33db6b8f919eb95d63b8bfbc2e912fe5 - Change the User Type to 'writer' and you'll see the Username input.


问:
c# Windows Service Console.Writeln
I wrote, installed, and successfully started a Windows Service in c# that does nothing :)  Initially I just want echo stuff to the console, db queries the service makes etc.  I used the OnStart in my service, but from a cmd prompt when I do a     net start "My Service"  where do these messages show up?

I'm open to better ways.  I'm new to this and feeling my way through it step by step by echoing back to the console my progress.  Should I echo to the event log instead? How do I do that?(I know, I know, google it)

```<code> protected override void OnStart(string[] args)
    {
        base.OnStart(args);
        Console.WriteLine("Sham-Wow!");
    }
</code>```

答: Try System.Diagnostics.Trace.WriteLine and you will see your messages in Output window of Visual Studio or with dbgview utility.</p>

ContentLicense: CC BY-SA 2.5

Title: c# Windows Service Console.Writeln

Body:
I wrote, installed, and successfully started a Windows Service in c# that does nothing :)  Initially I just want echo stuff to the console, db queries the service makes etc.  I used the OnStart in my service, but from a cmd prompt when I do a     net start "My Service"  where do these messages show up?

I'm open to better ways.  I'm new to this and feeling my way through it step by step by echoing back to the console my progress.  Should I echo to the event log instead? How do I do that?(I know, I know, google it)

 protected override void OnStart(string[] args)
    {
        base.OnStart(args);
        Console.WriteLine("Sham-Wow!");
    }


问:
DataTables - search/filter box on each column (AJAX)
There's a  lot of questions about separating filter on each columns. But none of them I have found about the same question, but of course with a touch of AJAX.

I'm using datatables for almost a month. While searching for a cool stuff I can add to my datatable, I found a site that has this datatable with filter on each columns. I want to have that but I can't figure it out how.

I've read some documentation in Datatables, but it seems to be difficult for me to understand it. So can someone help me to fix my problem?

By the way here's my AJAX code:

```<code>var initAjaxDatatables = function () {

var grid = new Datatable();

grid.init({
    src: $("#applicationTracker"),
    loadingMessage: 'Loading...',
    dataTable: {
        "bStateSave": true,

        "lengthMenu": [
            [10, 20, 50, 100, 150, -1],
            [10, 20, 50, 100, 150, "All"]
        ],
        "pageLength": 10,
        "ajax": {
            "url": root_path + "/public/ajax/report/application/LoadAllDataAsync/",
        },
        "order": [
            [1, "asc"]
        ],

        buttons: [
            { extend: 'print', className: 'btn default' },
            { extend: 'copy', className: 'btn default' },
            { extend: 'pdf', className: 'btn default' },
            { extend: 'excel', className: 'btn default' },
            { extend: 'csv', className: 'btn default' },
            {
                text: 'Reload',
                className: 'btn default',
                action: function ( e, dt, node, config ) {
                    dt.ajax.reload();
                }
            }
        ],

    }
});

// handle datatable custom tools
$('#datatable_ajax_tools > li > a.tool-action').on('click', function() {
    var action = $(this).attr('data-action');
    grid.getDataTable().button(action).trigger();
});
</code>```

答:
I have implemented the filter for each column in footer, try this:

```<code>$(document).ready(function() {
    var data = [];
    data.push(
        [1,"Sasha","Brenna","0800 1111"],
        [2,"Sage","Mia","(01012) 405872"],
        [3,"Chelsea","Allistair","076 0578 0265"],
        [4,"Uta","Savannah","070 1247 5884"],
        [5,"Remedios","Berk","0995 181 0007"],
        [6,"Ruby","Wayne","0800 1111"],
        [7,"Faith","Fredericka","(01709) 099879"],
        [8,"Myra","Harrison","070 4241 9576"],
        [9,"Drake","Miriam","0800 733635"],
        [10,"Reed","Shannon","076 8597 5067"]
    );

    var count = 0;
    $('#data_table').DataTable( {
        data:           data,

        initComplete: function (){
            this.api().columns().every( function () {
                /*if(count == 2)
                {*/
                    var column = this;
                    var select = $('<select><option value=""></option></select>')
                        .appendTo( $(column.footer()).empty() )
                        .on( 'change', function () {
                            var val = $.fn.dataTable.util.escapeRegex(
                                $(this).val()
                            );

                            column
                                .search( val ? '^'+val+'$' : '', true, false )
                                .draw();
                        });

                    column.data().unique().sort().each( function ( d, j ) {
                        select.append( '<option value="'+d+'">'+d+'</option>' )
                    });
                /*}*/
                count++;
            });
        }
    });
});
</code>```

Github Demo

Working JSFiddle

Body:
There's a  lot of questions about separating filter on each columns. But none of them I have found about the same question, but of course with a touch of AJAX.

I'm using datatables for almost a month. While searching for a cool stuff I can add to my datatable, I found a site that has this datatable with filter on each columns. I want to have that but I can't figure it out how.

I've read some documentation in Datatables, but it seems to be difficult for me to understand it. So can someone help me to fix my problem?

By the way here's my AJAX code:

var initAjaxDatatables = function () {

var grid = new Datatable();

grid.init({
    src: $("#applicationTracker"),
    loadingMessage: 'Loading...',
    dataTable: {
        "bStateSave": true,

        "lengthMenu": [
            [10, 20, 50, 100, 150, -1],
            [10, 20, 50, 100, 150, "All"]
        ],
        "pageLength": 10,
        "ajax": {
            "url": root_path + "/public/ajax/report/application/LoadAllDataAsync/",
        },
        "order": [
            [1, "asc"]
        ],

        buttons: [
            { extend: 'print', className: 'btn default' },
            { extend: 'copy', className: 'btn default' },
            { extend: 'pdf', className: 'btn default' },
            { extend: 'excel', className: 'btn default' },
            { extend: 'csv', className: 'btn default' },
            {
                text: 'Reload',
                className: 'btn default',
                action: function ( e, dt, node, config ) {
                    dt.ajax.reload();
                }
            }
        ],

    }
});

// handle datatable custom tools
$('#datatable_ajax_tools > li > a.tool-action').on('click', function() {
    var action = $(this).attr('data-action');
    grid.getDataTable().button(action).trigger();
});

Body:
I have implemented the filter for each column in footer, try this:

$(document).ready(function() {
    var data = [];
    data.push(
        [1,"Sasha","Brenna","0800 1111"],
        [2,"Sage","Mia","(01012) 405872"],
        [3,"Chelsea","Allistair","076 0578 0265"],
        [4,"Uta","Savannah","070 1247 5884"],
        [5,"Remedios","Berk","0995 181 0007"],
        [6,"Ruby","Wayne","0800 1111"],
        [7,"Faith","Fredericka","(01709) 099879"],
        [8,"Myra","Harrison","070 4241 9576"],
        [9,"Drake","Miriam","0800 733635"],
        [10,"Reed","Shannon","076 8597 5067"]
    );

    var count = 0;
    $('#data_table').DataTable( {
        data:           data,

        initComplete: function (){
            this.api().columns().every( function () {
                /*if(count == 2)
                {*/
                    var column = this;
                    var select = $('<select><option value=""></option></select>')
                        .appendTo( $(column.footer()).empty() )
                        .on( 'change', function () {
                            var val = $.fn.dataTable.util.escapeRegex(
                                $(this).val()
                            );

                            column
                                .search( val ? '^'+val+'$' : '', true, false )
                                .draw();
                        });

                    column.data().unique().sort().each( function ( d, j ) {
                        select.append( '<option value="'+d+'">'+d+'</option>' )
                    });
                /*}*/
                count++;
            });
        }
    });
});

Github Demo

Working JSFiddle


问:
Getting error android.view.InflateException: Binary XML file line #10: Error inflating class fragment
I am testing zxing barcode scanner from github https://github.com/dm77/barcodescanner .

I have fragment A, Fragment ScanFragment and fragment ProductDetail. Fragment ScanFragment has SimpleScannerFragment which contains code for barcode scanner. I am using replace fragment transaction and putting fragment in backstack.

I go from fragments in following direction.

Fragment A -> ScanFragment -> Fragment Product detail -> ScanFragment

Then, I press back to get back in same way,
ScanFragment -> Fragment Product detail -> ScanFragment(Error here)

```<code>Exception in MessageQueue callback: handleReceiveCallback
android.view.InflateException: Binary XML file line #10: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:719)

at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at np.com.ddm1.myandroidtoolshelper.BarcodeTest.BarcodeScanner.ScanFragment.onCreateView(ScanFragment.java:56)
</code>```

Fragment A consist only button to pass to ScanFragment.
Fragment Product detail has button which opens ScanFragment to get barcode Scanner.

I need help on following things.
1. I have used replace fragment transaction here. But I am not sure if I should use add or replace fragment here. In which scenario we should use add or replace?
2. Should I make second fragment "ScanFragment2" to avoid this error? or I can use same ScanFragment repeatedly.

ScanFragment :

```<code>public class ScanFragment extends Fragment {
private static final String TAG = "ScanFragment";

View view;
TextView textViewToolbarTitle;
ImageView imageViewBack;
LinearLayout linearLayout_Skip;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    PrintLog.showTag(TAG,"== onCreate ==");
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    PrintLog.showTag(TAG,"== onViewCreated ==");
}

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    PrintLog.showTag(TAG,"--- onCreateView ---");
    view = inflater.inflate(R.layout.bc_fragment_scan,container,false);
    ButterKnife.setDebug(true);
    ButterKnife.bind(this,view);
    initializeUI();
    onClick();
    return view;
}

private void initializeUI(){
    textViewToolbarTitle = (TextView) view.findViewById(R.id.textViewToolbarTitle);
    imageViewBack = (ImageView) view.findViewById(R.id.imageViewBack);

    textViewToolbarTitle.setText("Scan Fragment");
    imageViewBack.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            getActivity().onBackPressed();
        }
    });
    linearLayout_Skip = (LinearLayout) view.findViewById(R.id.linearLayout_skip);
}

private void onClick(){
    linearLayout_Skip.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            releaseCamera();
            ProductDetailFormFragment productDetailFormFragment  = new ProductDetailFormFragment();
            getActivity().getSupportFragmentManager().beginTransaction()
                    .replace(R.id.mainFragment, productDetailFormFragment).addToBackStack("scan_fragment").commit();
        }
    });
}

private void releaseCamera(){
    SimpleScannerFragment simpleScannerFragment = (SimpleScannerFragment) getChildFragmentManager()
            .findFragmentById(R.id.scanner_fragment);
    simpleScannerFragment.releaseCamera();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    PrintLog.show("CALLED ON ACTIVITY RESULT");
}
}
</code>```

SimpleScannerFragment :

```<code>public class SimpleScannerFragment extends
Fragment implements ZXingScannerView.ResultHandler {
private static final String TAG = "SimpleScannerFragment";
private ZXingScannerView mScannerView;
ScanListener scanListener;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mScannerView = new ZXingScannerView(getActivity());
    PrintLog.showTag(TAG,"===  onCreateView() ==");
    return mScannerView;
}

@Override
public void onResume() {
    super.onResume();
    PrintLog.showTag(TAG,"== onResume() ==");
    mScannerView.setResultHandler(this);
    mScannerView.startCamera();
}

@Override
public void handleResult(Result rawResult) {
    PrintLog.showTag(TAG,"== handleResult() ==");
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            mScannerView.resumeCameraPreview(SimpleScannerFragment.this);
        }
    }, 2000);

    //--- case for calling from different fragments
    if(getArguments() != null){
        if(getArguments().getString("parent_fragment").equals("product_details")){
            getActivity().getSupportFragmentManager().popBackStack();
            scanListener.onScanComplete(rawResult.getText());
        }
    }else{
        ProductDetailFormFragment productDetailFormFragment  = new ProductDetailFormFragment();
        Bundle bundle = new Bundle();
        bundle.putString("serial_number",rawResult.getText());
        productDetailFormFragment.setArguments(bundle);
        getActivity().getSupportFragmentManager().beginTransaction()
                .add(R.id.mainFragment, productDetailFormFragment).addToBackStack("scan_fragment").commit();
    }
}

public void releaseCamera(){
    PrintLog.showTag(TAG,"== releaseCamera() ==");
    mScannerView.stopCamera();
}

public interface ScanListener{
    public void onScanComplete(String serialNumber);
}

@Override
public void onPause() {
    super.onPause();
    PrintLog.showTag(TAG,"== onPause() ==");
    mScannerView.stopCamera();
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    PrintLog.showTag(TAG,"== onDestroyView() ==");
}
}
</code>```

ScanFragment layout :

```<code><FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:clickable="true"
>

<fragment android:name="np.com.ddm1.myandroidtoolshelper.BarcodeTest.BarcodeScanner.SimpleScannerFragment"
    android:id="@+id/scanner_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</FrameLayout>
</code>```

答:
Remove

```<code>android:layout_weight="1"
</code>```

from the xml file in the <FrameLayout> tag

Body:
I am testing zxing barcode scanner from github https://github.com/dm77/barcodescanner .

I have fragment A, Fragment ScanFragment and fragment ProductDetail. Fragment ScanFragment has SimpleScannerFragment which contains code for barcode scanner. I am using replace fragment transaction and putting fragment in backstack.

I go from fragments in following direction.

Fragment A -> ScanFragment -> Fragment Product detail -> ScanFragment

Then, I press back to get back in same way,
ScanFragment -> Fragment Product detail -> ScanFragment(Error here)

Exception in MessageQueue callback: handleReceiveCallback
android.view.InflateException: Binary XML file line #10: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:719)

at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at np.com.ddm1.myandroidtoolshelper.BarcodeTest.BarcodeScanner.ScanFragment.onCreateView(ScanFragment.java:56)

Fragment A consist only button to pass to ScanFragment.
Fragment Product detail has button which opens ScanFragment to get barcode Scanner.

I need help on following things.
1. I have used replace fragment transaction here. But I am not sure if I should use add or replace fragment here. In which scenario we should use add or replace?
2. Should I make second fragment "ScanFragment2" to avoid this error? or I can use same ScanFragment repeatedly.

ScanFragment :

public class ScanFragment extends Fragment {
private static final String TAG = "ScanFragment";

View view;
TextView textViewToolbarTitle;
ImageView imageViewBack;
LinearLayout linearLayout_Skip;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    PrintLog.showTag(TAG,"== onCreate ==");
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    PrintLog.showTag(TAG,"== onViewCreated ==");
}

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    PrintLog.showTag(TAG,"--- onCreateView ---");
    view = inflater.inflate(R.layout.bc_fragment_scan,container,false);
    ButterKnife.setDebug(true);
    ButterKnife.bind(this,view);
    initializeUI();
    onClick();
    return view;
}

private void initializeUI(){
    textViewToolbarTitle = (TextView) view.findViewById(R.id.textViewToolbarTitle);
    imageViewBack = (ImageView) view.findViewById(R.id.imageViewBack);

    textViewToolbarTitle.setText("Scan Fragment");
    imageViewBack.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            getActivity().onBackPressed();
        }
    });
    linearLayout_Skip = (LinearLayout) view.findViewById(R.id.linearLayout_skip);
}

private void onClick(){
    linearLayout_Skip.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            releaseCamera();
            ProductDetailFormFragment productDetailFormFragment  = new ProductDetailFormFragment();
            getActivity().getSupportFragmentManager().beginTransaction()
                    .replace(R.id.mainFragment, productDetailFormFragment).addToBackStack("scan_fragment").commit();
        }
    });
}

private void releaseCamera(){
    SimpleScannerFragment simpleScannerFragment = (SimpleScannerFragment) getChildFragmentManager()
            .findFragmentById(R.id.scanner_fragment);
    simpleScannerFragment.releaseCamera();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    PrintLog.show("CALLED ON ACTIVITY RESULT");
}
}

SimpleScannerFragment :

public class SimpleScannerFragment extends
Fragment implements ZXingScannerView.ResultHandler {
private static final String TAG = "SimpleScannerFragment";
private ZXingScannerView mScannerView;
ScanListener scanListener;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mScannerView = new ZXingScannerView(getActivity());
    PrintLog.showTag(TAG,"===  onCreateView() ==");
    return mScannerView;
}

@Override
public void onResume() {
    super.onResume();
    PrintLog.showTag(TAG,"== onResume() ==");
    mScannerView.setResultHandler(this);
    mScannerView.startCamera();
}

@Override
public void handleResult(Result rawResult) {
    PrintLog.showTag(TAG,"== handleResult() ==");
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            mScannerView.resumeCameraPreview(SimpleScannerFragment.this);
        }
    }, 2000);

    //--- case for calling from different fragments
    if(getArguments() != null){
        if(getArguments().getString("parent_fragment").equals("product_details")){
            getActivity().getSupportFragmentManager().popBackStack();
            scanListener.onScanComplete(rawResult.getText());
        }
    }else{
        ProductDetailFormFragment productDetailFormFragment  = new ProductDetailFormFragment();
        Bundle bundle = new Bundle();
        bundle.putString("serial_number",rawResult.getText());
        productDetailFormFragment.setArguments(bundle);
        getActivity().getSupportFragmentManager().beginTransaction()
                .add(R.id.mainFragment, productDetailFormFragment).addToBackStack("scan_fragment").commit();
    }
}

public void releaseCamera(){
    PrintLog.showTag(TAG,"== releaseCamera() ==");
    mScannerView.stopCamera();
}

public interface ScanListener{
    public void onScanComplete(String serialNumber);
}

@Override
public void onPause() {
    super.onPause();
    PrintLog.showTag(TAG,"== onPause() ==");
    mScannerView.stopCamera();
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    PrintLog.showTag(TAG,"== onDestroyView() ==");
}
}

ScanFragment layout :

<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:clickable="true"
>

<fragment android:name="np.com.ddm1.myandroidtoolshelper.BarcodeTest.BarcodeScanner.SimpleScannerFragment"
    android:id="@+id/scanner_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</FrameLayout>

Body:
Remove

android:layout_weight="1"

from the xml file in the <FrameLayout> tag


问:
What is the difference between Tomcat, JBoss and Glassfish?
I am starting to look into Enterprise Java and the book I am following mentions that it will use JBoss. Netbeans ships with Glassfish. I have used Tomcat in the past.

What are the differences between these three programs?

答: Apache tomcat is just an only serverlet container it does not support for Enterprise Java application(JEE). JBoss and Glassfish are supporting for JEE application but Glassfish much heavy than JBOSS server  : Reference Slide      </p>


问:
Pipe, ngModel and ngModelChange
I have a two-way data binding with a custom pipe.

My input text field code:

<input type="text" [ngModel]="post.price | myCurrencyPipe" (ngModelChange)="post.price = $event" name="price" id ="price" (change)="itemPriceUpdate(post)"/>
```

<p>and custom pipe code :</p>

<pre class="lang-ts prettyprint-override"><code>@Pipe({ name: 'myCurrencyPipe'})
export class MyCurrencyPipe implements PipeTransform{

      transform(val:any) {
        var value = parseInt(data);
        var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
        return num;

      }
</code>```

When I go to edit my input field value it displays NaN on keypress.

答:
This is because you have character $ at the front of val which added by your custom pipe. remove it before calling parseInt(data) will solve your problem.

```<code>transform(val:any) {
  val = val.toString().replace(/[^0-9.]/g, '');
  if (val === '') return '';
  var value = parseInt(val);
  var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
  return num;
}
</code>```

plinker demo.

Title: Pipe, ngModel and ngModelChange

Body:
I have a two-way data binding with a custom pipe.

My input text field code:

<input type="text" [ngModel]="post.price | myCurrencyPipe" (ngModelChange)="post.price = $event" name="price" id ="price" (change)="itemPriceUpdate(post)"/>

and custom pipe code :

@Pipe({ name: 'myCurrencyPipe'})
export class MyCurrencyPipe implements PipeTransform{

      transform(val:any) {
        var value = parseInt(data);
        var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
        return num;

      }

When I go to edit my input field value it displays NaN on keypress.

Body:
This is because you have character $ at the front of val which added by your custom pipe. remove it before calling parseInt(data) will solve your problem.

transform(val:any) {
  val = val.toString().replace(/[^0-9.]/g, '');
  if (val === '') return '';
  var value = parseInt(val);
  var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
  return num;
}

plinker demo.


问:
Javascript: trivial lib for writing game-style skill tree graphs
I want to do something like this skill tree. What I dislike about that beautiful graph is that background is a standard Photoshop layout, and to change that skill tree I need to rewrite a layout.

Question: Can you suggest me a javascript lib which will satisfy 2 requirements:

Can build a beautiful graph

Is pretty easy to customize (i.e. replace connection arrows style, etc.)

答: You might be looking for this: https://github.com/352Media/skilltree, it's made with Knockout.js.</p>


问:
In bash, after `bind` a command to a key, without echo the command which is executing
First you may refer to this great post here: Bash bind for better understanding what I am trying to achieve.

I want to achieve that when I hit the enter then update the shell prompt dynamically, now I already had is:

```<code>__update_shell_prompt () {
  # according what I had done in the terminal regenerate the new shell prompt
  # new_shell_prompt
  export PS1=$new_shell_prompt
}

bind '"\C-M":"\n__update_shell_prompt\n"'
</code>```

It works as expected, just after each command I executed it would echo the text __update_shell_prompt also, like:

I also tried to use the bind with the -x option like this:

bind -x '"\C-M":"\n__update_shell_prompt\n"''

Then it doesn't respect the \n, so it totally doesn't work, if I remove the \n, it still doesn't work, and bring another serious problem in, the command I tried to execute just remain in the screen and never would get executed, like so: all commands just get stuck there...

So:

How can I make that don't echo the command text...

If this is not the right way to achieve this(dynamically update shell prompt upon enter hitting), then how should I do this?

答:
First thanks @Charles Duffy, I followed his suggestion and used the tput.

The solution is simple, use tput cup to move the cursor up, then use tput el to delete that line, as below:

```<code># Get the current cursor coordinate.
IFS=';' read -sdR -p $'\E[6n' ROW COL; local current_row=`echo "${ROW#*[}"`

# Move the cursor up then delete that line
tput cup $((current_row-2)) 0 && tput el
</code>```

Tips:

To prevent the potential commands history pollution, you can put export HISTCONTROL=ignorespace into your ~/.bash_profile or ~/.bashrc;

Then invoke the command with prefixed space.

The problem I used this scenario to solve can be referred here: docker-machine PR #4127.

Body:
First you may refer to this great post here: Bash bind for better understanding what I am trying to achieve.

I want to achieve that when I hit the enter then update the shell prompt dynamically, now I already had is:

__update_shell_prompt () {
  # according what I had done in the terminal regenerate the new shell prompt
  # new_shell_prompt
  export PS1=$new_shell_prompt
}

bind '"\C-M":"\n__update_shell_prompt\n"'

It works as expected, just after each command I executed it would echo the text __update_shell_prompt also, like:

I also tried to use the bind with the -x option like this:

bind -x '"\C-M":"\n__update_shell_prompt\n"''

Then it doesn't respect the \n, so it totally doesn't work, if I remove the \n, it still doesn't work, and bring another serious problem in, the command I tried to execute just remain in the screen and never would get executed, like so: all commands just get stuck there...

So:

How can I make that don't echo the command text...

If this is not the right way to achieve this(dynamically update shell prompt upon enter hitting), then how should I do this?

Body:
First thanks @Charles Duffy, I followed his suggestion and used the tput.

The solution is simple, use tput cup to move the cursor up, then use tput el to delete that line, as below:

# Get the current cursor coordinate.
IFS=';' read -sdR -p $'\E[6n' ROW COL; local current_row=`echo "${ROW#*[}"`

# Move the cursor up then delete that line
tput cup $((current_row-2)) 0 && tput el

Tips:

To prevent the potential commands history pollution, you can put export HISTCONTROL=ignorespace into your ~/.bash_profile or ~/.bashrc;

Then invoke the command with prefixed space.

The problem I used this scenario to solve can be referred here: docker-machine PR #4127.


问:
Linux driver module "kobj_to_dev" not working
I am trying to develop my first linux driver, but I got a blocking issue using the API kobj_to_dev in order to get a "struct device*" reference from a "struct kobject*" passed as parameter to a "show" event of a r/o attribute.

I would better explain the scenario describing only some of the instructions I have written to fall into the above problem:

static struct kobj_attribute myOption_attr = __ATTR_RO(myOption)

static struct attribute *my_attrs[] = { &myOption_attr.attr, NULL }

static struct attribute_group my_attr_group = { .attrs = my_attrs }

struct device* myDev = device_create( ... SOME PARAMETERS ... )

struct kobject* myKObj = kobject_create_and_add("mySettings", &myDev->kobj)

sysfs_create_group(myKObj, &my_attr_group)

static ssize_t pinNumber_show(
struct kobject        *kobj,
struct kobj_attribute *attr,
char                  *buf
)
{
struct device *kobjDev = kobj_to_dev(kobj);

pr_info(
  "Expected: %p - Passed: %p %d:%d.\n",
  myDev,
  kobjDev,
  MAJOR(kobjDev->devt)
  MINOR(kobjDev->devt)
);
}

After installing the driver module I successfully get the virtual file /sys/class/myDev/mySettings/myOption .

When I run then command "cat /sys/class/myDev/mySettings/myOption" inside the /var/log/kern.log I get to different pointers value for myDev and kobjDev, and the major and minor number are 0.

Could anybody point me to what I missed?

Thank you so much!

答:
I found the solution on my own, I had to change

```<code>kobj_to_dev(kobj)
</code>```

to

```<code>kobj_to_dev(kobj->parent)
</code>```

Thank you anyway! :)

Body:
I found the solution on my own, I had to change

kobj_to_dev(kobj)

to

kobj_to_dev(kobj->parent)

Thank you anyway! :)


问:
GROUP BY & ORDER BY - Ordering by a specific field
I need to write a query which returns a list of unique 'classes' ordered by the most popular item in that class. Here's an example query:

```<code>SELECT items.title, items.popularity
FROM items, classes
WHERE class_id = classes.id
GROUP BY class_id
ORDER BY MAX(items.popularity) DESC
</code>```

This query returns the correct class but the item it returns is the first that appears in the table rather than the most popular.

Similarly I have tried:

```<code>SELECT MAX(items.title), items.popularity
FROM items, classes
WHERE class_id = classes.id
GROUP BY class_id
ORDER BY MAX(items.popularity) DESC
</code>```

And all variations - this just returns the most recent added and not the most popular.

I've read lots and lots of other answers.

I'm sure there's a simple answer, please help!

答:
I haven't try it but I think it should work...</p>

```<code>SELECT MAX(items.title), items.popularity
FROM items, classes
WHERE class_id = classes.id
GROUP BY class_id
ORDER BY items.popularity DESC
</code>```

Body:
I need to write a query which returns a list of unique 'classes' ordered by the most popular item in that class. Here's an example query:

SELECT items.title, items.popularity
FROM items, classes
WHERE class_id = classes.id
GROUP BY class_id
ORDER BY MAX(items.popularity) DESC

This query returns the correct class but the item it returns is the first that appears in the table rather than the most popular.

Similarly I have tried:

SELECT MAX(items.title), items.popularity
FROM items, classes
WHERE class_id = classes.id
GROUP BY class_id
ORDER BY MAX(items.popularity) DESC

And all variations - this just returns the most recent added and not the most popular.

I've read lots and lots of other answers.

I'm sure there's a simple answer, please help!

Body:
I haven't try it but I think it should work...

SELECT MAX(items.title), items.popularity
FROM items, classes
WHERE class_id = classes.id
GROUP BY class_id
ORDER BY items.popularity DESC


问:
Jface Table row validation
Background:
I have a Jface table on which I have set Editing support with text cell editor for each column. There are around 20 columns.

Problem:
I want to highlight invalid row field text with dark red color and whole row with light red color.

What I tried as of now:
1. I have highlighted invalid field(single cell of row) using label providers getBackgroundColor() and getForgroundColor().
2. I tried CellEditors setValidator() method to add a validator, but I don't want to clear invalid text from a cell, I just want to highlight it.
3. I have one approach to use a flag for each cell to check the validity of that cell if any of the flags is true will highlight all cells of that row(can be achieved using label providers). But, I think this approach will impact performance for my table.
4. I am not sure performance impact of table updatatestrategy of Jface. So I am not using it.

Reason of highlighting the whole row of the table is: Table have 20+ columns and user don't want to scroll the table to find out problem location.

Please suggest if you know any better solutions.

答:
Using label providers to for the colors is the  way to do this.

The label provider is only asked for the color when the row is created or refreshed - by calling one of the viewer refresh or update methods, so this should not impact performance.

Title: Jface Table row validation


问:
ICal.net Calendar Comparison
I've been using a nuget package called ICal.net to load ics files to check for events that have recently been added.

I've noticed while using the IEnumerable Except method for this that some events are missed even though you can see that more events have been added.

I came across the Uid property in the Event, checked it out and noticed that its unique - https://github.com/rianjs/ical.net/blob/5176d27ac243eb98a01157f2ed7ff3e2852b98eb/v2/ical.NET/Interfaces/Components/IUniqueComponent.cs#L14

I wrote a IEqualityComparer<IEvent> for this using the Uid but now all events are being seen as new events.

Was just wondering if anyone had any suggestions on how I can take 2 calendars, compare the events and get the differences? Currently there is 2000+ events and increasing so trying to keep it performant.

答:
I would recommend doing a Where In query with LINQ.

assuming you have two collections (registered and possibly new):

```<code>List<string> registeredIds = GetRegisteredComponentsUIds();

List<ComponentImplemenation> newEvents = GetNewEvents();

List<ComponentImplemenation> result = newEvents.Where(m => registeredIds.Contains(m.Uid))
                                               .ToList();
</code>```

Title: ICal.net Calendar Comparison

Body:
I would recommend doing a Where In query with LINQ.

assuming you have two collections (registered and possibly new):

List<string> registeredIds = GetRegisteredComponentsUIds();

List<ComponentImplemenation> newEvents = GetNewEvents();

List<ComponentImplemenation> result = newEvents.Where(m => registeredIds.Contains(m.Uid))
                                               .ToList();


问:
custom height for swipe delete button swift
I have custom table cell. Each cell have different height. I want to give swipe delete button with cell height.

I have used view in cell. View height is cell height - 16. Top-bottom margin 8.

So please help me to do this.

答:
Use this code in your Custom Cell Swift class</p>

```<code>override func layoutSubviews() {
    let fltHeight:CGFloat = 46
    var subviews: [Any] = self.subviews
    let subview: UIView? = subviews[0] as? UIView
    if NSClassFromString("UITableViewCellDeleteConfirmationView") != nil {
        if (subview?.isKind(of: NSClassFromString("UITableViewCellDeleteConfirmationView")!))! {
            let deleteButtonView: UIView? = (subview?.subviews[0])
            var buttonFrame: CGRect? = deleteButtonView?.frame
            buttonFrame?.origin.x = (deleteButtonView?.frame.origin.x)!
            buttonFrame?.origin.y = (deleteButtonView?.frame.origin.y)!
            buttonFrame?.size.width = (deleteButtonView?.frame.size.width)!
            buttonFrame?.size.height = fltHeight
            deleteButtonView?.frame = buttonFrame!

            // Placing at the center of the cell.
            subview?.frame = CGRect(x: CGFloat((subview?.frame.origin.x)!),
                                    y: CGFloat((subview?.frame.origin.y)! + ((subview?.frame.size.height)!-fltHeight)/2),
                                    width: CGFloat((subview?.frame.size.width)!),
                                    height: CGFloat(fltHeight))
            deleteButtonView?.clipsToBounds = true
            subview?.clipsToBounds = true
        }
    }
}
</code>```

Body:
Use this code in your Custom Cell Swift class

override func layoutSubviews() {
    let fltHeight:CGFloat = 46
    var subviews: [Any] = self.subviews
    let subview: UIView? = subviews[0] as? UIView
    if NSClassFromString("UITableViewCellDeleteConfirmationView") != nil {
        if (subview?.isKind(of: NSClassFromString("UITableViewCellDeleteConfirmationView")!))! {
            let deleteButtonView: UIView? = (subview?.subviews[0])
            var buttonFrame: CGRect? = deleteButtonView?.frame
            buttonFrame?.origin.x = (deleteButtonView?.frame.origin.x)!
            buttonFrame?.origin.y = (deleteButtonView?.frame.origin.y)!
            buttonFrame?.size.width = (deleteButtonView?.frame.size.width)!
            buttonFrame?.size.height = fltHeight
            deleteButtonView?.frame = buttonFrame!

            // Placing at the center of the cell.
            subview?.frame = CGRect(x: CGFloat((subview?.frame.origin.x)!),
                                    y: CGFloat((subview?.frame.origin.y)! + ((subview?.frame.size.height)!-fltHeight)/2),
                                    width: CGFloat((subview?.frame.size.width)!),
                                    height: CGFloat(fltHeight))
            deleteButtonView?.clipsToBounds = true
            subview?.clipsToBounds = true
        }
    }
}


答:
this should do what you want:

```<code>import csv

def int_or_float(strg):
    val = float(strg)
    return int(val) if val.is_integer() else val

with open('test.csv') as in_file:
    it = zip(*csv.reader(in_file))
    dct = {el[0]: [int_or_float(val) for val in el[1:]] for el in it}
</code>```

zip(*it) will just transpose the data you have and rearrange it in the way you want; the dictionary comprehension then builds your new dictionary.

dct now contains the dictionary you want.

Title: convert csv to dictionary

Body:
I have the following csv file(total 20000 lines)

ozone,paricullate_matter,carbon_monoxide,sulfure_dioxide,nitrogen_dioxide,longitude,latitude,timestamp,avg_measured_time,avg_speed,median_measured_time,timestamp:1,vehicle_count,lat1,long1,lat2,long2,distance_between_2_points,duration_of_measurement,ndt_in_kmh
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,0,0,0,1407575099.99998,0,56.1089513576227,10.1823955595246,56.1048021343541,10.1988040846558,1124,65,62
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,0,0,0,1407575099.99998,0,56.10986429895,10.1627288048935,56.1089513576227,10.1823955595246,1254,71,64
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,0,0,0,1407575099.99998,0,56.1425188527673,10.1868802625656,56.1417522836526,10.1927236478157,521,62,30
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,18,84,18,1407575099.99998,1,56.1395320665735,10.1772034087371,56.1384485157567,10.1791506011887,422,50,30

I want to convert this into a dictionary like

{'ozone': [99,99,99,99], 'paricullate_matter': [99,99,99,99],'carbon_monoxide': [98,98,98,98],etc....}

What i have tried

import csv

reader = csv.DictReader(open('resulttable.csv'))

output = open("finalprojdata.py","w")

result = {}
for row in reader:
    for column, value in row.iteritems():
        result.setdefault(column, []).append(float(value))
output.write(str(result))

The output am getting is consisting of only few dictionaries. Like from

{'vehicle_count': [0,0,0,1], 'lat1': etc}

The whole csv file is not getting converted to dictionary.

Body:
this should do what you want:

import csv

def int_or_float(strg):
    val = float(strg)
    return int(val) if val.is_integer() else val

with open('test.csv') as in_file:
    it = zip(*csv.reader(in_file))
    dct = {el[0]: [int_or_float(val) for val in el[1:]] for el in it}

zip(*it) will just transpose the data you have and rearrange it in the way you want; the dictionary comprehension then builds your new dictionary.

dct now contains the dictionary you want.


问:
How do I convert an integer to the corresponding words in objective-c?
Is there a way in Objective-C on iOS to spell out an integer number as text?

For example, if I have

```<code>NSInteger someNumber = 11242043;
</code>```

I would like to know some function so that would return a string similar to "eleven million two hundred forty two thousand forty three."

答:
You can use the below function to convert an integer to words using swift native number style.</p>

```<code>func toWords<N>(number: N) -> String? {
    let formatter = NumberFormatter()
    formatter.numberStyle = .spellOut

    switch number {
    case is Int, is UInt, is Float, is Double:
        return formatter.string(from: number as! NSNumber)
    case is String:
        if let number = Double(number as! String) {
            return formatter.string(from: NSNumber(floatLiteral: number))
        }
    default:
        break
    }
    return nil
}

print(toWords(number: 12312))

print(toWords(number: "12312"))
</code>```

Body:
Is there a way in Objective-C on iOS to spell out an integer number as text?

For example, if I have

NSInteger someNumber = 11242043;

I would like to know some function so that would return a string similar to "eleven million two hundred forty two thousand forty three."

Body:
You can use the below function to convert an integer to words using swift native number style.

func toWords<N>(number: N) -> String? {
    let formatter = NumberFormatter()
    formatter.numberStyle = .spellOut

    switch number {
    case is Int, is UInt, is Float, is Double:
        return formatter.string(from: number as! NSNumber)
    case is String:
        if let number = Double(number as! String) {
            return formatter.string(from: NSNumber(floatLiteral: number))
        }
    default:
        break
    }
    return nil
}

print(toWords(number: 12312))

print(toWords(number: "12312"))


问:
Static allocation of opaque data types
Very often malloc() is absolutely not allowed when programming for embedded systems. Most of the time I'm pretty able to deal with this, but one thing irritates me: it keeps me from using so called 'opaque types' to enable data hiding. Normally I'd do something like this:

```<code>// In file module.h
typedef struct handle_t handle_t;

handle_t *create_handle();
void operation_on_handle(handle_t *handle, int an_argument);
void another_operation_on_handle(handle_t *handle, char etcetera);
void close_handle(handle_t *handle);

// In file module.c
struct handle_t {
    int foo;
    void *something;
    int another_implementation_detail;
};

handle_t *create_handle() {
    handle_t *handle = malloc(sizeof(struct handle_t));
    // other initialization
    return handle;
}
</code>```

There you go: create_handle() performs a malloc() to create an 'instance'. A construction often used to prevent having to malloc() is to change the prototype of create_handle() like this:

```<code>void create_handle(handle_t *handle);
</code>```

And then the caller could create the handle this way:

```<code>// In file caller.c
void i_am_the_caller() {
    handle_t a_handle;    // Allocate a handle on the stack instead of malloc()
    create_handle(&a_handle);
    // ... a_handle is ready to go!
}
</code>```

But unfortunately this code is obviously invalid, the size of handle_t isn't known!

I never really found a solution to solve this in a proper way. I'd very like to know if anyone has a proper way of doing this, or maybe a complete different approach to enable data hiding in C (not using static globals in the module.c of course, one must be able to create multiple instances).

答:
One way would be to add something like

```<code>#define MODULE_HANDLE_SIZE (4711)
</code>```

to the public module.h header. Since that creates a worrying requirement of keeping this in sync with the actual size, the line is of course best auto-generated by the build process.

The other option is of course to actually expose the structure, but document it as being opaque and forbidding access through any other means than through the defined API. This can be made more clear by doing something like:

```<code>#include "module_private.h"

typedef struct
{
  handle_private_t private;
} handle_t;
</code>```

Here, the actual declaration of the module's handle has been moved into a separate header, to make it less obviously visible. A type declared in that header is then simply wrapped in the desired typedef name, making sure to indicate that it is private.

Functions inside the module that take handle_t * can safely access private as a handle_private_t value, since it's the first member of the public struct.

Title: Static allocation of opaque data types

Body:
Very often malloc() is absolutely not allowed when programming for embedded systems. Most of the time I'm pretty able to deal with this, but one thing irritates me: it keeps me from using so called 'opaque types' to enable data hiding. Normally I'd do something like this:

// In file module.h
typedef struct handle_t handle_t;

handle_t *create_handle();
void operation_on_handle(handle_t *handle, int an_argument);
void another_operation_on_handle(handle_t *handle, char etcetera);
void close_handle(handle_t *handle);

// In file module.c
struct handle_t {
    int foo;
    void *something;
    int another_implementation_detail;
};

handle_t *create_handle() {
    handle_t *handle = malloc(sizeof(struct handle_t));
    // other initialization
    return handle;
}

There you go: create_handle() performs a malloc() to create an 'instance'. A construction often used to prevent having to malloc() is to change the prototype of create_handle() like this:

void create_handle(handle_t *handle);

And then the caller could create the handle this way:

// In file caller.c
void i_am_the_caller() {
    handle_t a_handle;    // Allocate a handle on the stack instead of malloc()
    create_handle(&a_handle);
    // ... a_handle is ready to go!
}

But unfortunately this code is obviously invalid, the size of handle_t isn't known!

I never really found a solution to solve this in a proper way. I'd very like to know if anyone has a proper way of doing this, or maybe a complete different approach to enable data hiding in C (not using static globals in the module.c of course, one must be able to create multiple instances).

Body:
One way would be to add something like

#define MODULE_HANDLE_SIZE (4711)

to the public module.h header. Since that creates a worrying requirement of keeping this in sync with the actual size, the line is of course best auto-generated by the build process.

The other option is of course to actually expose the structure, but document it as being opaque and forbidding access through any other means than through the defined API. This can be made more clear by doing something like:

#include "module_private.h"

typedef struct
{
  handle_private_t private;
} handle_t;

Here, the actual declaration of the module's handle has been moved into a separate header, to make it less obviously visible. A type declared in that header is then simply wrapped in the desired typedef name, making sure to indicate that it is private.

Functions inside the module that take handle_t * can safely access private as a handle_private_t value, since it's the first member of the public struct.


问:
How can I set custom length for integer field by using Blueprint class in Laravel

I am trying to set custom length for integer type field from user
  input.
  By using Blueprint class I can set custom length for varchar field
  like $table->string('varchar_field',50);. But I didn't find any way
  to set custom length for integer field, It takes default length always.

Ex :

```<code>Varchar :
$table->string('varchar_field',50);

Integer :
$table->integer('interger_field');
</code>```

答:
You can't do that, but you can choose one of available integer types:

```<code>// BIGINT equivalent, integers from -9223372036854775808 to 9223372036854775807
$table->bigInteger('interger_field');

// INTEGER equivalent, integers from -2147483648 to 2147483647
$table->integer('interger_field');

// MEDIUMINT equivalent, integers from -8388608 to 8388607
$table->mediumInteger('interger_field');

// SMALLINT equivalent, integers from -32768 to 32767
$table->smallInteger('interger_field');

// TINYINT equivalent, integers from -128 to 127
$table->tinyInteger('interger_field');
</code>```

You will find the description of all integer types here.

Body:
I am trying to set custom length for integer type field from user
  input.
  By using Blueprint class I can set custom length for varchar field
  like $table->string('varchar_field',50);. But I didn't find any way
  to set custom length for integer field, It takes default length always.

Ex :

Varchar :
$table->string('varchar_field',50);

Integer :
$table->integer('interger_field');

Body:
You can't do that, but you can choose one of available integer types:

// BIGINT equivalent, integers from -9223372036854775808 to 9223372036854775807
$table->bigInteger('interger_field');

// INTEGER equivalent, integers from -2147483648 to 2147483647
$table->integer('interger_field');

// MEDIUMINT equivalent, integers from -8388608 to 8388607
$table->mediumInteger('interger_field');

// SMALLINT equivalent, integers from -32768 to 32767
$table->smallInteger('interger_field');

// TINYINT equivalent, integers from -128 to 127
$table->tinyInteger('interger_field');

You will find the description of all integer types here.


问:
OjAlgo How to map / update all the values in PrimitiveDenseStore?
Say I have an 2x2 matrix as PrimitiveDenseStore

```<code>pstore = [ 1 2
           3 4 ]
</code>```

Is there anyway to map all these values based on given anonymous function like

```<code>pstore.map(x -> x * x)
</code>```

So the result is

```<code>pstore = [ 1 4
           9 16 ]
</code>```

答:
There are at least 3 alternatives for you to "investigate":

```<code>pstore.loopAll(...);
pstore.modifyAll(...);
pstore.operateOnAll(...);
</code>```

and/or you could have a look at the answers to these questions:

OjAlgo : Is there a way to add/subtract a double from all elements of a PrimitiveDenseStore in ojAlgo?

Elementwise multiplication two matrices or PrimitiveDenseStores in ojAlgo

Body:
Say I have an 2x2 matrix as PrimitiveDenseStore

pstore = [ 1 2
           3 4 ]

Is there anyway to map all these values based on given anonymous function like

pstore.map(x -> x * x)

So the result is

pstore = [ 1 4
           9 16 ]

Body:
There are at least 3 alternatives for you to "investigate":

pstore.loopAll(...);
pstore.modifyAll(...);
pstore.operateOnAll(...);

and/or you could have a look at the answers to these questions:

OjAlgo : Is there a way to add/subtract a double from all elements of a PrimitiveDenseStore in ojAlgo?

Elementwise multiplication two matrices or PrimitiveDenseStores in ojAlgo


问:
Printing last name + first name - but it shows error (Java)
So I have made a code for user to enter their first and last name; then exhanging the two position.

for example. Bulota Babi becomes Babi, Bulota

this is my code

```<code>public class trial {
    public static void main(String [] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();

        String fname = input.substring(0, input.indexOf(0));
        String lname = input.substring(1, input.indexOf(input.length()));

        System.out.println(lname +","+ fname);
    }

}
</code>```

im not sure whats wrong with it, this is the error message

```<code>Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1967)
    at trial.main(trial.java:11)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
</code>```

答:
The input.indexOf(0) command is looking for the index of the char which has the ASCII value 0. As it is not found, it returns the value -1.

The indexOf is made to look for the place of a character in a String. You can't use it by giving it a number, unless it is the character ASCII value

Body:
So I have made a code for user to enter their first and last name; then exhanging the two position.

for example. Bulota Babi becomes Babi, Bulota

this is my code

public class trial {
    public static void main(String [] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();

        String fname = input.substring(0, input.indexOf(0));
        String lname = input.substring(1, input.indexOf(input.length()));

        System.out.println(lname +","+ fname);
    }

}

im not sure whats wrong with it, this is the error message

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1967)
    at trial.main(trial.java:11)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)


问:
Login "onSuccess" navigating to another page. React
So i want to be able to go to the main page after the user successfully logs in. I am still new to React. How can this be done. I am using v4 of react as well. When i hit the login button it seems to trigger the action but not complete it.

Here is the action that handles the login:

```<code>const mainPage = (response, dispatch) => {
if(POST_DATA_SUCCESS) {
  this.props.history.push('/main');
}
dispatch({
    type: POST_DATA_SUCCESS,
    response,
});
};

export function loginUser(username1, password1) {
const promise = fetch('http://localhost:8080/users/login', {
method: 'POST',
headers: {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
  'Authorization': 'Basic ' + btoa(username1 + ":" + password1),
},
body: JSON.stringify({
  username: username1,
  password: password1,
})
});
return {
    onRequest: POST_DATA_TRIGGERED,
    onSuccess: mainPage,
    onFailure: POST_DATA_FAILURE,
    promise,
};
}
</code>```

Here is the backend that handles the login request:

```<code>router.get('/login',
passport.authenticate('basic', {session: false}),
(req, res) => res.json({user: req.user.apiRepr()})
);

router.post('/login', function (req, res, next) {
passport.authenticate('basic', function (err, user, info) {
    if (err) {
        return console.log(err);
    }
    if (!user) {
        return res.status(401).json({
            message: 'Username/Password Incorrect'
        });
    }
    req.logIn(user, function (err) {
        if (err) {
            return console.log(err);
        }
        return res.status(200).json({
            user: user.username
        });
    });
})(req, res, next);
});
</code>```

And the login component with the form:

```<code>import React from 'react';
import {BrowserRouter as Router, Route, Link} from 'react-router-dom';
import { loginUser } from '../actions';
import { connect } from 'react-redux';

export class Login extends React.Component {
 constructor(props) {
  super(props);
  this.state = {
  //username: '',
  //password: '',
 }
}

render() {
 return(
 <form>
   <h3>Login to start your Journey</h3>
   <input placeholder="username" ref={input => {this.username = input}}>
   </input>
  <input placeholder="password" type="password"ref={input => {this.password
  = input}}></input>
  <button onClick={this.login.bind(this)}>Login</button>
 </form>
  )
}

login() {
 const userName = this.username.value;
 const passWord = this.password.value;
 console.log(userName);
 console.log(passWord);
 this.props.loginUser(userName, passWord);
 }
}

export default connect(null, { loginUser })(Login);
</code>```

答:
You can utilize redux-little-router to dispatch push actions like so:

```<code>export function navigateAbout(string) {
  return (dispatch) => {
    dispatch(someOtherAction(string)); <--- other action you want to do
    dispatch(push('/about')) <--- your navigation action
  }
}
</code>```

Body:
So i want to be able to go to the main page after the user successfully logs in. I am still new to React. How can this be done. I am using v4 of react as well. When i hit the login button it seems to trigger the action but not complete it.

Here is the action that handles the login:

const mainPage = (response, dispatch) => {
if(POST_DATA_SUCCESS) {
  this.props.history.push('/main');
}
dispatch({
    type: POST_DATA_SUCCESS,
    response,
});
};

export function loginUser(username1, password1) {
const promise = fetch('http://localhost:8080/users/login', {
method: 'POST',
headers: {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
  'Authorization': 'Basic ' + btoa(username1 + ":" + password1),
},
body: JSON.stringify({
  username: username1,
  password: password1,
})
});
return {
    onRequest: POST_DATA_TRIGGERED,
    onSuccess: mainPage,
    onFailure: POST_DATA_FAILURE,
    promise,
};
}

Here is the backend that handles the login request:

router.get('/login',
passport.authenticate('basic', {session: false}),
(req, res) => res.json({user: req.user.apiRepr()})
);

router.post('/login', function (req, res, next) {
passport.authenticate('basic', function (err, user, info) {
    if (err) {
        return console.log(err);
    }
    if (!user) {
        return res.status(401).json({
            message: 'Username/Password Incorrect'
        });
    }
    req.logIn(user, function (err) {
        if (err) {
            return console.log(err);
        }
        return res.status(200).json({
            user: user.username
        });
    });
})(req, res, next);
});

And the login component with the form:

import React from 'react';
import {BrowserRouter as Router, Route, Link} from 'react-router-dom';
import { loginUser } from '../actions';
import { connect } from 'react-redux';

export class Login extends React.Component {
 constructor(props) {
  super(props);
  this.state = {
  //username: '',
  //password: '',
 }
}

render() {
 return(
 <form>

Login to start your Journey

   <input placeholder="username" ref={input => {this.username = input}}>
   </input>
  <input placeholder="password" type="password"ref={input => {this.password
  = input}}></input>
  <button onClick={this.login.bind(this)}>Login</button>
 </form>
  )
}

login() {
 const userName = this.username.value;
 const passWord = this.password.value;
 console.log(userName);
 console.log(passWord);
 this.props.loginUser(userName, passWord);
 }
}

export default connect(null, { loginUser })(Login);

Body:
You can utilize redux-little-router to dispatch push actions like so:

export function navigateAbout(string) {
  return (dispatch) => {
    dispatch(someOtherAction(string)); <--- other action you want to do
    dispatch(push('/about')) <--- your navigation action
  }
}


问:
AIML - getting unknown values from set values
I'm using recursion in AIML using the <srai> tag, like the following code:

```<code><category><pattern>I LIKE *</pattern>
 <think><set name="name"><star/></set>
 <set name="it">
 <set name="topic"><star/>
 </set>
 </set>
 </think>
 <template><srai>I DIG</srai></template>
 </category>

 <category><pattern>I DIG</pattern>
 <template>
 <random>
 <li>If you dig <get name="name"/>, plant something in it</li>
 <li>I dig <get name="name"/> too.</li>
 <li>If you dig <get name="name"/> deep enough, rabbits will live in it.</li>
 </random>
 </template>
 </category>
</code>```

A few days ago, this code was working, but now it works as values have not been set.
I'm getting:

If you dig unknown, plant something in it.

I dig unknown too.

If you dig unknown deep enough, rabbits will live in it.

what am I doing wrong?

答:
This because these variables are session scoped. That means, if you assign value to a variable, it is globally accessible. So as you have same variable name for Bird and User, it will behave in the same way you've mentioned.
What you can do is keep two variables:

```<code><category>
      <pattern>I LIKE *</pattern>
      <template>
          <think>
             <set name="name"><star/></set>
             <set name="it">
                 <set name="topic"><star/></set>
             </set>
          </think>
          <srai>I DIG</srai>
     </template>
  </category>
</code>```

And keep another variable for username e.g.

```<code>  <category>
      <pattern>My name is *</pattern>
      <template>Ok <think><set name="userName"><star/></set> </think></template>
  </category>

  <category>
      <pattern>What is my name?</pattern>
      <template>My name is <get name="userName"/></template>
  </category>
</code>```

Body:
I'm using recursion in AIML using the <srai> tag, like the following code:

<category><pattern>I LIKE *</pattern>
 <think><set name="name"><star/></set>
 <set name="it">
 <set name="topic"><star/>
 </set>
 </set>
 </think>
 <template><srai>I DIG</srai></template>
 </category>

 <category><pattern>I DIG</pattern>
 <template>
 <random>

If you dig <get name="name"/>, plant something in it

I dig <get name="name"/> too.

If you dig <get name="name"/> deep enough, rabbits will live in it.

 </random>
 </template>
 </category>

A few days ago, this code was working, but now it works as values have not been set.
I'm getting:

If you dig unknown, plant something in it.

I dig unknown too.

If you dig unknown deep enough, rabbits will live in it.

what am I doing wrong?

Body:
This because these variables are session scoped. That means, if you assign value to a variable, it is globally accessible. So as you have same variable name for Bird and User, it will behave in the same way you've mentioned.
What you can do is keep two variables:

<category>
      <pattern>I LIKE *</pattern>
      <template>
          <think>
             <set name="name"><star/></set>
             <set name="it">
                 <set name="topic"><star/></set>
             </set>
          </think>
          <srai>I DIG</srai>
     </template>
  </category>

And keep another variable for username e.g.

  <category>
      <pattern>My name is *</pattern>
      <template>Ok <think><set name="userName"><star/></set> </think></template>
  </category>

  <category>
      <pattern>What is my name?</pattern>
      <template>My name is <get name="userName"/></template>
  </category>


问:
std::vector new runs out of memory
I am writing a program in C++ for a embedded platform STM32. I used to use normal arrays but for the first time I am using vectors in it. So far it runs well in the majority of the cases. However in a very few cases I got the error stated in the title eventhough it shouldn't. Would appreciate some help as I run out of ideas.

My situation

The vectors are like this

```<code>struct Boundary{
  vector<unsigned short> x; //The x coordinates
  vector<unsigned short> y; //The y coordinates
};
</code>```

Everytime I use these vectors I clear them with

```<code>boundary0.x.clear();
boundary0.y.clear();
</code>```

I add elements with the normal push_back

The strange part

Sometimes, the program finishes with the "Operator new out of memory" when adding elements to the vector.

"!Ah, you run out of memory!"- you would say, but that is the strange part. The vector so far has only 275 elements which being short gives 550 bytes.

But this very same program has handled the same vector with many more elements (500 or more) without problem.

Somehow, you previously leaked out memory!- can be said, and I suspect that. Perhaps I used this before and failed to clean it up (although I cleaned it as I stated) but this error appears even when I disconnect and connect the processor wiping out any previous used memory.

I am at lost why this could be happening. Any help or comment or advice greatly appreciated.

答:
What you need is to reduce vector capacity to its size after vector has been used and clear was performed.

C++11 solution:

Use shrink_to_fit() after clear() function to release memory allocated previously.

```<code>boundary0.x.clear();
boundary0.x.shrink_to_fit();
boundary0.y.clear();
boundary0.y.shrink_to_fit();
</code>```

It will reduce capacity of vector to be equal to its size which after clear() equals to zero.
Note, that shrink_to_fit introduced since C++11.

C++03 and earlier:

'Swap-to-fit' idiom can be used to have same as shrink_to_fit effect.

```<code>std::vector<T>(my_vector.begin(), my_vector.end()).swap(my_vector);
</code>```

will reduce my_vector capacity to its size.

This idiom is described here with detailed explanation how exactly it works: https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Shrink-to-fit

Title: std::vector new runs out of memory

Body:
I am writing a program in C++ for a embedded platform STM32. I used to use normal arrays but for the first time I am using vectors in it. So far it runs well in the majority of the cases. However in a very few cases I got the error stated in the title eventhough it shouldn't. Would appreciate some help as I run out of ideas.

My situation

The vectors are like this

struct Boundary{
  vector<unsigned short> x; //The x coordinates
  vector<unsigned short> y; //The y coordinates
};

Everytime I use these vectors I clear them with

boundary0.x.clear();
boundary0.y.clear();

I add elements with the normal push_back

The strange part

Sometimes, the program finishes with the "Operator new out of memory" when adding elements to the vector.

"!Ah, you run out of memory!"- you would say, but that is the strange part. The vector so far has only 275 elements which being short gives 550 bytes.

But this very same program has handled the same vector with many more elements (500 or more) without problem.

Somehow, you previously leaked out memory!- can be said, and I suspect that. Perhaps I used this before and failed to clean it up (although I cleaned it as I stated) but this error appears even when I disconnect and connect the processor wiping out any previous used memory.

I am at lost why this could be happening. Any help or comment or advice greatly appreciated.

Body:
What you need is to reduce vector capacity to its size after vector has been used and clear was performed.

C++11 solution:

Use shrink_to_fit() after clear() function to release memory allocated previously.

boundary0.x.clear();
boundary0.x.shrink_to_fit();
boundary0.y.clear();
boundary0.y.shrink_to_fit();

It will reduce capacity of vector to be equal to its size which after clear() equals to zero.
Note, that shrink_to_fit introduced since C++11.

C++03 and earlier:

'Swap-to-fit' idiom can be used to have same as shrink_to_fit effect.

std::vector<T>(my_vector.begin(), my_vector.end()).swap(my_vector);

will reduce my_vector capacity to its size.

This idiom is described here with detailed explanation how exactly it works: https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Shrink-to-fit


问:
Big ugly SQL query problem
I have two tables:
Status(status_id, desc1, desc2, desc3, desc4)
Status_Level(status_level_id, desc, levelD, levelS)

The connection is on the desc1..4 fileds in Status and desc in Status_Level.
I need to select status_id, levelD and levelS where levelD and levelS are highest levels of all four descs.

I tried this:

```<code>SELECT Status.status_id, MAX(levelS) AS ds_column, MAX(levelD) AS ss_column
FROM Status, Status_level WHERE
Status_level.desc=Status.desc1 OR
Status_level.desc=Status.desc2 OR
Status_level.desc=Status.desc3 OR
Status_level.desc=Status.desc4
GROUP BY Status.status_id
</code>```

My SQL is very rusty so any help would be greatly appreciated.
Thanks.

edit:
example:

```<code>Status:
-----------------------------------------------------------
| 1 | ABC_LEVEL_1 | DEF_LEVEL_5| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------
| 2 | ABC_LEVEL_1 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_1|
-----------------------------------------------------------
| 3 | ABC_LEVEL_4 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------

Status_Level:
---------------------------
| 1 | ABC_LEVEL_1 | 1 | 7 |
---------------------------
| 1 | DEF_LEVEL_5 | 5 | 6 |
---------------------------
| 1 | CBA_LEVEL_2 | 2 | 3 |
---------------------------
| 1 | ABC_LEVEL_4 | 4 | 5 |
---------------------------
| 1 | DEF_LEVEL_1 | 1 | 2 |

Desired output:

-------------
| 1 | 5 | 7 | <- 5 from DEF_LEVEL_5 and 7 from ABC_LEVEL_1
-------------
| 2 | 2 | 7 | <- 2 from CBA_LEVEL_2 and 7 from ABC_LEVEL_1
-------------
| 3 | 4 | 5 | <- 4 from ABC_LEVEL_4 and 5 from ABC_LEVEL_4
-------------
</code>```

答:
How about:</p>

```<code>SELECT t.status_id, Max(Status_Level.levelD) AS MaxOflevelD,
       Max(Status_Level.levelS) AS MaxOflevelS
FROM Status_Level INNER JOIN (SELECT s.status_id, s.desc1 As [Desc]
FROM status s
UNION ALL
SELECT s.status_id, s.desc2 As [Desc]
FROM status s
UNION ALL
SELECT s.status_id, s.desc3 As [Desc]
FROM status s
UNION ALL
SELECT s.status_id, s.desc4 As [Desc]
FROM status s)  AS t ON Status_Level.desc = t.Desc
GROUP BY t.status_id;
</code>```

Title: Big ugly SQL query problem

Body:
I have two tables:
Status(status_id, desc1, desc2, desc3, desc4)
Status_Level(status_level_id, desc, levelD, levelS)

The connection is on the desc1..4 fileds in Status and desc in Status_Level.
I need to select status_id, levelD and levelS where levelD and levelS are highest levels of all four descs.

I tried this:

SELECT Status.status_id, MAX(levelS) AS ds_column, MAX(levelD) AS ss_column
FROM Status, Status_level WHERE
Status_level.desc=Status.desc1 OR
Status_level.desc=Status.desc2 OR
Status_level.desc=Status.desc3 OR
Status_level.desc=Status.desc4
GROUP BY Status.status_id

My SQL is very rusty so any help would be greatly appreciated.
Thanks.

edit:
example:

Status:
-----------------------------------------------------------
| 1 | ABC_LEVEL_1 | DEF_LEVEL_5| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------
| 2 | ABC_LEVEL_1 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_1|
-----------------------------------------------------------
| 3 | ABC_LEVEL_4 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------

Status_Level:
---------------------------
| 1 | ABC_LEVEL_1 | 1 | 7 |
---------------------------
| 1 | DEF_LEVEL_5 | 5 | 6 |
---------------------------
| 1 | CBA_LEVEL_2 | 2 | 3 |
---------------------------
| 1 | ABC_LEVEL_4 | 4 | 5 |
---------------------------
| 1 | DEF_LEVEL_1 | 1 | 2 |

Desired output:

-------------
| 1 | 5 | 7 | <- 5 from DEF_LEVEL_5 and 7 from ABC_LEVEL_1
-------------
| 2 | 2 | 7 | <- 2 from CBA_LEVEL_2 and 7 from ABC_LEVEL_1
-------------
| 3 | 4 | 5 | <- 4 from ABC_LEVEL_4 and 5 from ABC_LEVEL_4
-------------

Body:
How about:

SELECT t.status_id, Max(Status_Level.levelD) AS MaxOflevelD,
       Max(Status_Level.levelS) AS MaxOflevelS
FROM Status_Level INNER JOIN (SELECT s.status_id, s.desc1 As [Desc]
FROM status s
UNION ALL
SELECT s.status_id, s.desc2 As [Desc]
FROM status s
UNION ALL
SELECT s.status_id, s.desc3 As [Desc]
FROM status s
UNION ALL
SELECT s.status_id, s.desc4 As [Desc]
FROM status s)  AS t ON Status_Level.desc = t.Desc
GROUP BY t.status_id;


答:
If you know that the columns will be named 30 through 900 in multiples of 30, you can generate that explicitly like this:

```<code>c = [str(i) for i in range(30, 901, 30)]
</code>```

Then add it to the other columns:

```<code>c = c + ['Item', 'Price', 'Size', 'Time', 'Type', 'Unnamed: 0']
</code>```

Then you should be able to access it as df[c]

Title: Pandas - Resort Column Location

Body:
I have a pandas frame. When I print the columns (shown below), its turns out that my columns are out of order. Is there a way to sort only the first 30 columns so they are in order (30,60,90...900)?

[in]   df.columns

[out]  Index(['120', '150', '180', '210', '240', '270', '30', '300', '330', '360',
   '390', '420', '450', '480', '510', '540', '570', '60', '600', '630',
   '660', '690', '720', '750', '780', '810', '840', '870', '90', '900',
   'Item', 'Price', 'Size', 'Time', 'Type', 'Unnamed: 0'],
  dtype='object')

The fixed frame would be as follows:

[out]  Index(['30','60','90,'120', '150', '180', '210', '240', '270','300', '330', '360',
   '390', '420', '450', '480', '510', '540', '570','600', '630',
   '660', '690', '720', '750', '780', '810', '840', '870','900',
   'Item', 'Price', 'Size', 'Time', 'Type', 'Unnamed: 0'],
  dtype='object')

Body:
If you know that the columns will be named 30 through 900 in multiples of 30, you can generate that explicitly like this:

c = [str(i) for i in range(30, 901, 30)]

Then add it to the other columns:

c = c + ['Item', 'Price', 'Size', 'Time', 'Type', 'Unnamed: 0']

Then you should be able to access it as df[c]


问:
C# Passing multidimensional arrays between forms
i have a main form where i can set settings and show some stuff inlcuding a "MenuStrip" and a second form that opens upon clicking "Add" Button in Form 1.

In The 2. Form the user can add multiple strings to text boxes. After clicking "Done" in Form 2 all the Informationes will be saved in an multidimensional array [,].

The form 1 then retrieves these Informations with get/set.

The Problem: I am getting an Infinite Loop on the get methode =/ I think it is because i have not defined how many columns/rows the array has (which is impossible since the user can add more informations dynamcally). So maybe i have to pass the reference (and how do i manage that? i know how to pass things between forms when CREATING an instance of a new form but not when the old form is already open and i close the 2nd one) or is there any other way?

My Code:

```<code>    //in Form 1
    private void btn_Add_Click(object sender, EventArgs e)
    {
        using (form2 = new AddStuff())
        {
            form2.ShowDialog();
            string [,] copy = form2._NewMenuStrip.Clone() as string [,];
            for (int i = 0; i < copy.GetLength(0);i++ )
            {
                for (int j=0; j < copy.GetLength(1);j++)
                {
                    MessageBox.Show(copy[i, j]);
                }
            }
        }
     }

     //in Form 2
    public string [,] _NewMenuStrip
    {
        get { return _NewMenuStrip; } // Here i get the infinite Loop
        set { _NewMenuStrip = value;}
    }

    private void btn_Done_Click(object sender, EventArgs e)
    {
        WriteInformationToArray();
        this.Close();
    }
</code>```

Thanks in Advance!

Regards,
Christian

答:
You get that infinite loop, because the property is self referencing. You need to either access a variable or just leave the getter and setter definitions empty. .Net will take care of the variables then. Just define it like this:

```<code>public string [,] _NewMenuStrip { get; set; }
</code>```

OR

define a private variable holding your value:

```<code>private string [,] _newMenuStrip;

public string [,] _NewMenuStrip
{
    get { return _newMenuStrip; } //<--- Set the private one !
    set { _newMenuStrip = value; } //<--- return the private one !
}
</code>```

which is the exact same thing like above ( the complier will create a private field for you) !

Body:
i have a main form where i can set settings and show some stuff inlcuding a "MenuStrip" and a second form that opens upon clicking "Add" Button in Form 1.

In The 2. Form the user can add multiple strings to text boxes. After clicking "Done" in Form 2 all the Informationes will be saved in an multidimensional array [,].

The form 1 then retrieves these Informations with get/set.

The Problem: I am getting an Infinite Loop on the get methode =/ I think it is because i have not defined how many columns/rows the array has (which is impossible since the user can add more informations dynamcally). So maybe i have to pass the reference (and how do i manage that? i know how to pass things between forms when CREATING an instance of a new form but not when the old form is already open and i close the 2nd one) or is there any other way?

My Code:

    //in Form 1
    private void btn_Add_Click(object sender, EventArgs e)
    {
        using (form2 = new AddStuff())
        {
            form2.ShowDialog();
            string [,] copy = form2._NewMenuStrip.Clone() as string [,];
            for (int i = 0; i < copy.GetLength(0);i++ )
            {
                for (int j=0; j < copy.GetLength(1);j++)
                {
                    MessageBox.Show(copy[i, j]);
                }
            }
        }
     }

     //in Form 2
    public string [,] _NewMenuStrip
    {
        get { return _NewMenuStrip; } // Here i get the infinite Loop
        set { _NewMenuStrip = value;}
    }

    private void btn_Done_Click(object sender, EventArgs e)
    {
        WriteInformationToArray();
        this.Close();
    }

Thanks in Advance!

Regards,
Christian

Body:
You get that infinite loop, because the property is self referencing. You need to either access a variable or just leave the getter and setter definitions empty. .Net will take care of the variables then. Just define it like this:

public string [,] _NewMenuStrip { get; set; }

OR

define a private variable holding your value:

private string [,] _newMenuStrip;

public string [,] _NewMenuStrip
{
    get { return _newMenuStrip; } //<--- Set the private one !
    set { _newMenuStrip = value; } //<--- return the private one !
}

which is the exact same thing like above ( the complier will create a private field for you) !


问:
get nlargest values from multi index data frame
I have a data frame that looks like following image:

Here uid and id are indexes. This data frame was converted from a single index dataframe, so there are duplicate values for some columns. For each uid, all values for avg_diff are same, but different uid will have different values for this field. I want to get the largest 10 avg_diff values, with different uids.

Note: This is a huge data frame, so I am looking for the most optimized way.

答:
If I understood you right, you just need to drop duplicates of "uid" and then sort by avr_diff</p>

```<code>unique_uid = data.reset_index().drop_duplicates("uid").set_index("uid")
print(unique_uid["avr_diff"].sort_values(ascending=False)[:10])
</code>```

Body:
If I understood you right, you just need to drop duplicates of "uid" and then sort by avr_diff

unique_uid = data.reset_index().drop_duplicates("uid").set_index("uid")
print(unique_uid["avr_diff"].sort_values(ascending=False)[:10])


问:
c# Windows Service Console.Writeln
I wrote, installed, and successfully started a Windows Service in c# that does nothing :)  Initially I just want echo stuff to the console, db queries the service makes etc.  I used the OnStart in my service, but from a cmd prompt when I do a     net start "My Service"  where do these messages show up?

I'm open to better ways.  I'm new to this and feeling my way through it step by step by echoing back to the console my progress.  Should I echo to the event log instead? How do I do that?(I know, I know, google it)

```<code> protected override void OnStart(string[] args)
    {
        base.OnStart(args);
        Console.WriteLine("Sham-Wow!");
    }
</code>```

答:
You cannot write the console from a Windows Service.

I recommend you using any logging utility, such as log4net.

The second alternative is writing to the Event Log (System.Diagnostics.EventLog)

Title: c# Windows Service Console.Writeln

Body:
I wrote, installed, and successfully started a Windows Service in c# that does nothing :)  Initially I just want echo stuff to the console, db queries the service makes etc.  I used the OnStart in my service, but from a cmd prompt when I do a     net start "My Service"  where do these messages show up?

I'm open to better ways.  I'm new to this and feeling my way through it step by step by echoing back to the console my progress.  Should I echo to the event log instead? How do I do that?(I know, I know, google it)

 protected override void OnStart(string[] args)
    {
        base.OnStart(args);
        Console.WriteLine("Sham-Wow!");
    }


问:
JDBC Connection close conecpt
I have created connection's object and stored in the hashMap. While executing query on the connection object I retrieve the object from the hashMap. In finally block I close the connection.
However, when we come for the second time I again retrieve the connection's object from the hashMap. This time while executing the query I get closed connection exception.
If I remove conn.close() from finally, it works.
what is the reason behind this? Moreover, when i print the connection's object I get the object.</p>

答:
If you are re-using the same Connection object for multiple queries, you shouldn't close the connection after each time you use it, since closing it means the second query will fail.

Therefore, you should either create a new open Connection for each query, or keep the cached Connection open (i.e. don't close it in the finally block).

Title: JDBC Connection close conecpt


问:
How to use dataset to groupby
I have a request to use rdd to do so：

```<code>val test = Seq(("New York", "Jack"),
    ("Los Angeles", "Tom"),
    ("Chicago", "David"),
    ("Houston", "John"),
    ("Detroit", "Michael"),
    ("Chicago", "Andrew"),
    ("Detroit", "Peter"),
    ("Detroit", "George")
  )
sc.parallelize(test).groupByKey().mapValues(_.toList).foreach(println)
</code>```

The result is that：

(New York,List(Jack))

(Detroit,List(Michael, Peter, George))

(Los Angeles,List(Tom))

(Houston,List(John))

(Chicago,List(David, Andrew))

How to do it use dataset with spark2.0?

I have a way to use a custom function, but the feeling is so complicated, there is no simple point method？

答:
First i would turn your RDD into a DataSet:

```<code>val spark: org.apache.spark.sql.SparkSession = ???
import spark.implicits._

val testDs = test.toDS()
</code>```

Here you get your col names :) Use it wise !

```<code>testDs.schema.fields.foreach(x => println(x))
</code>```

In the end you only need to use a groupBy:

```<code>testDs.groupBy("City?", "Name?")
</code>```

RDD-s are not really the 2.0 version way I think.
If you have any question please just ask.

Title: How to use dataset to groupby

Body:
I have a request to use rdd to do so：

val test = Seq(("New York", "Jack"),
    ("Los Angeles", "Tom"),
    ("Chicago", "David"),
    ("Houston", "John"),
    ("Detroit", "Michael"),
    ("Chicago", "Andrew"),
    ("Detroit", "Peter"),
    ("Detroit", "George")
  )
sc.parallelize(test).groupByKey().mapValues(_.toList).foreach(println)

The result is that：

(New York,List(Jack))

(Detroit,List(Michael, Peter, George))

(Los Angeles,List(Tom))

(Houston,List(John))

(Chicago,List(David, Andrew))

How to do it use dataset with spark2.0?

I have a way to use a custom function, but the feeling is so complicated, there is no simple point method？

Body:
First i would turn your RDD into a DataSet:

val spark: org.apache.spark.sql.SparkSession = ???
import spark.implicits._

val testDs = test.toDS()

Here you get your col names :) Use it wise !

testDs.schema.fields.foreach(x => println(x))

In the end you only need to use a groupBy:

testDs.groupBy("City?", "Name?")

RDD-s are not really the 2.0 version way I think.
If you have any question please just ask.


问:
Why would SQL be very slow when doing updates?
Suddenly doing updates into a few tables have gotten 10 times slower than they used to be.  What are some good recommendations to determine root cause and optimization?  Could it be that indexing certain columns are causing updates to be slow?  Any other recommendations?

I guess more important than guesses would be help on the process of identifying the root cause or metrics around performance.

Is there anything in Fluent NHibernate that you can use to help identify the root cause of performance issues?

答:
Also check if you're inserting data into a clustered index in an out-of-order way.

A clustered index stored the data in order of the field, which means if it's a uniqueidentifer, you'll be re-arranging the data on each insert.

Clustered indexes work better with sequential data.


问:
Counting Words in vector
Currently I have enrolled in a R course and one of the practice exercises is building a R program to count words in a string. We cannot use the function table but must return an output of the most popular word in a string using conventional means.
i.e. The fox jumped over the cone and the...
So the program would have to return "the" as it is the most popular phrase.

So far I have the following:

```<code>string_read<- function(phrase) {

  phrase <- strsplit(phrase, " ")[[1]]
  for (i in 1:length(phrase)){
    phrase.freq <- ....
#if Word already exists then increase counter by 1

      }
</code>```

I've hit a road block however as I'm not sure how to increase the counter for specific words. Can anyone give me a pointer in the right direction? My psuedo code would be something like: "For every word that is looped through, increase wordIndex by 1. If word has already occured before, increase wordIndex counter."

答:
We can do this with str_extract

```<code>library(stringr)
string_read<- function(str1) {
  temp <- tolower(unlist(str_extract_all(str1, "\\w+")))
  which.max(sapply(temp, function(x) sum(x == temp)))
}

phrase <- "The fox jumped over the cone and the"
string_read(phrase)
#the
#  1
phrase2 <- "The fox jumped over the cone and the fox, fox, fox, fox, fox"
string_read(phrase)
#fox
# 2
</code>```

Title: Counting Words in vector

Body:
Currently I have enrolled in a R course and one of the practice exercises is building a R program to count words in a string. We cannot use the function table but must return an output of the most popular word in a string using conventional means.
i.e. The fox jumped over the cone and the...
So the program would have to return "the" as it is the most popular phrase.

So far I have the following:

string_read<- function(phrase) {

  phrase <- strsplit(phrase, " ")[[1]]
  for (i in 1:length(phrase)){
    phrase.freq <- ....
#if Word already exists then increase counter by 1

      }

I've hit a road block however as I'm not sure how to increase the counter for specific words. Can anyone give me a pointer in the right direction? My psuedo code would be something like: "For every word that is looped through, increase wordIndex by 1. If word has already occured before, increase wordIndex counter."

Body:
We can do this with str_extract

library(stringr)
string_read<- function(str1) {
  temp <- tolower(unlist(str_extract_all(str1, "\\w+")))
  which.max(sapply(temp, function(x) sum(x == temp)))
}

phrase <- "The fox jumped over the cone and the"
string_read(phrase)
#the
#  1
phrase2 <- "The fox jumped over the cone and the fox, fox, fox, fox, fox"
string_read(phrase)
#fox
# 2


问:
Implementation 3D tiles into cesium itself
I am trying to implement 3D tiles into the project based on cesium. I am using cesium as npm in one angular project. I am quite confused, how to implement 3D Tiles. Do you have any idea? </p>

答: cesium has a 3d-tiles branch – I believe for now you have to use a custom build (instead of the npm version).