问:
Datatable not searchable

Issue

I am currently using DataTables to display data to the user and I would quite like to be able to filter the data that is being displayed. So I have added textboxes to the top of the table columns.

I have followed the documentation but the code doesn't seem to be working. When typing something into the textboxes the table will flash and then just display all the results again. I have tried moving the function from the $(document).ready into my populate method with no luck. I then moved it into its own method with no success either; I tried calling the method after my data has been added.

Code

HTML with the text boxes:

```<code><table id="tblGrid" class="display" cellspacing="0" width="100%">
    <thead id="tblHead">
        <tr>
            <th><input type="text" class="form-control" placeholder="Search name" name="name" id="name" /></th>
            <th><input type="text" class="form-control" placeholder="Search surname" name="surname" id="surname" /></th>
            <th><input type="text" class="form-control" placeholder="Search ID number" name="idnum" id="idnum" /></th>
            <th><input type="text" class="form-control" placeholder="Search email" name="email" id="email" /></th>
            <th><input type="text" class="form-control" placeholder="Search status" name="status" id="status" /></th>
            <th><input type="text" class="form-control" placeholder="Search xxx" name="xxx" id="xxx" /></th>
            <th><input type="text" class="form-control" placeholder="Search relation" name="relation" id="relation" /></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
        </tr>
        <tr style="text-align:left;">
            <th>Name</th>
            <th>Surname</th>
            <th>ID Number</th>
            <th>Email</th>
            <th>Status</th>
            <th>XXX</th>
            <th>Relation</th>
            <th>EDIT</th>
            <th>MANAGE</th>
            <th>SMS</th>
            <th>EMAIL</th>
        </tr>
    </thead>
    <tbody id="tBody"></tbody>
    <tfoot id="tblFoot">
        <tr style="text-align:left;">
            <th>Name</th>
            <th>Surname</th>
            <th>ID Number</th>
            <th>Email</th>
            <th>Status</th>
            <th>XXX</th>
            <th>Relation</th>
            <th>EDIT</th>
            <th>MANAGE</th>
            <th>SMS</th>
            <th>EMAIL</th>
        </tr>
    </tfoot>
</table>
</code>```

Javascript for loading data and trying to filter:

```<code>function getPage() {
        let tBody = $("#tBody");
        tBody.empty();
        let Broker = $("#ddlBroker").val();

        $('#tblGrid').dataTable({
            "processing": true,
            "serverSide": true,
            "paging": true,
            "info": true,
            "stateSave": true,
            "lengthMenu": [[10, 20, 50, 100], [10, 20, 50, 100]],
            "ajax": {
                "url": "@($"{Request.Url?.Scheme}://{Request.Url.Authority}{Url.Content("~")}")/Member/AjaxGetJsonData",
                "type": "GET",
                "data": { "BRK": Broker }
            },
            "columns": [
                { "data": "Name" },
                { "data": "Surname" },
                { "data": "IDNum" },
                { "data": "Email" },
                { "data": "Status" },
                { "data": "XXXXXX" },
                { "data": "Relation" },
                { "data": "btnEDIT", sortable: false},
                { "data": "btnMANAGE", sortable: false },
                { "data": "btnSMS", sortable: false },
                { "data": "btnEMAIL", sortable: false }
            ],
            "order": [[5, "asc"]]
        });

        addFilter();
}
function addFilter() {
    // DataTable
    var table = $('#tblGrid').DataTable();

    // Apply the search
    table.columns().every( function () {
        var that = this;

        $( 'input' ).on( 'keyup change', function () {
            if (that.search() !== this.value) {
                console.log(this.value);
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );
}
</code>```

答:
you need to add this right after initializing DataTables
    "searching": true,</p>

Title: Datatable not searchable

Body:
Issue

I am currently using DataTables to display data to the user and I would quite like to be able to filter the data that is being displayed. So I have added textboxes to the top of the table columns.

I have followed the documentation but the code doesn't seem to be working. When typing something into the textboxes the table will flash and then just display all the results again. I have tried moving the function from the $(document).ready into my populate method with no luck. I then moved it into its own method with no success either; I tried calling the method after my data has been added.

Code

HTML with the text boxes:

            <input type="text" class="form-control" placeholder="Search name" name="name" id="name" />
            <input type="text" class="form-control" placeholder="Search surname" name="surname" id="surname" />
            <input type="text" class="form-control" placeholder="Search ID number" name="idnum" id="idnum" />
            <input type="text" class="form-control" placeholder="Search email" name="email" id="email" />
            <input type="text" class="form-control" placeholder="Search status" name="status" id="status" />
            <input type="text" class="form-control" placeholder="Search xxx" name="xxx" id="xxx" />
            <input type="text" class="form-control" placeholder="Search relation" name="relation" id="relation" />

            Name
            Surname
            ID Number
            Email
            Status
            XXX
            Relation
            EDIT
            MANAGE
            SMS
            EMAIL

            Name
            Surname
            ID Number
            Email
            Status
            XXX
            Relation
            EDIT
            MANAGE
            SMS
            EMAIL

Javascript for loading data and trying to filter:

function getPage() {
        let tBody = $("#tBody");
        tBody.empty();
        let Broker = $("#ddlBroker").val();

        $('#tblGrid').dataTable({
            "processing": true,
            "serverSide": true,
            "paging": true,
            "info": true,
            "stateSave": true,
            "lengthMenu": [[10, 20, 50, 100], [10, 20, 50, 100]],
            "ajax": {
                "url": "@($"{Request.Url?.Scheme}://{Request.Url.Authority}{Url.Content("~")}")/Member/AjaxGetJsonData",
                "type": "GET",
                "data": { "BRK": Broker }
            },
            "columns": [
                { "data": "Name" },
                { "data": "Surname" },
                { "data": "IDNum" },
                { "data": "Email" },
                { "data": "Status" },
                { "data": "XXXXXX" },
                { "data": "Relation" },
                { "data": "btnEDIT", sortable: false},
                { "data": "btnMANAGE", sortable: false },
                { "data": "btnSMS", sortable: false },
                { "data": "btnEMAIL", sortable: false }
            ],
            "order": [[5, "asc"]]
        });

        addFilter();
}
function addFilter() {
    // DataTable
    var table = $('#tblGrid').DataTable();

    // Apply the search
    table.columns().every( function () {
        var that = this;

        $( 'input' ).on( 'keyup change', function () {
            if (that.search() !== this.value) {
                console.log(this.value);
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );
}


来源: stackexchange

问:
Force UITableView to scroll to top?
How would you go about forcing a UITableViewCell to scroll to the top if the tableview contains less than 10 or so cells? I support editing of Managed Object Contexts within my tableView cells while the tableview is in editing mode. Needless to say, if a cell is at the bottom of the tableview, it gets blocked by the keyboard when a user goes to edit the title or location of an event. I tried a solution like:

```<code>-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    if(_selectedIndex == indexPath.row){
        _selectedIndex = -1;
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                         withRowAnimation:UITableViewRowAnimationFade];
        return;
    }

    if(_selectedIndex >= 0){
        NSIndexPath *previous = [NSIndexPath indexPathForRow:_selectedIndex inSection:0];
        _selectedIndex = indexPath.row;
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:previous]
                         withRowAnimation:UITableViewRowAnimationFade];
    }

    _selectedIndex = indexPath.row;
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                     withRowAnimation:UITableViewRowAnimationFade];

    [tableView setContentOffset:CGPointMake(0, [tableView rowHeight]*indexPath.row) animated:YES];
}
</code>```

But this does not keep the tableview at the contentOffset. it will snap to the top and then snap back

答:
It will be helpful to scroll to top your tableView

```<code>tableView.setContentOffset(CGPoint(x: 0, y: -tableView.contentInset.top), animated: true).
</code>```

ContentLicense: CC BY-SA 3.0

Title: Force UITableView to scroll to top?

Body:
How would you go about forcing a UITableViewCell to scroll to the top if the tableview contains less than 10 or so cells? I support editing of Managed Object Contexts within my tableView cells while the tableview is in editing mode. Needless to say, if a cell is at the bottom of the tableview, it gets blocked by the keyboard when a user goes to edit the title or location of an event. I tried a solution like:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    if(_selectedIndex == indexPath.row){
        _selectedIndex = -1;
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                         withRowAnimation:UITableViewRowAnimationFade];
        return;
    }

    if(_selectedIndex >= 0){
        NSIndexPath *previous = [NSIndexPath indexPathForRow:_selectedIndex inSection:0];
        _selectedIndex = indexPath.row;
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:previous]
                         withRowAnimation:UITableViewRowAnimationFade];
    }

    _selectedIndex = indexPath.row;
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                     withRowAnimation:UITableViewRowAnimationFade];

    [tableView setContentOffset:CGPointMake(0, [tableView rowHeight]*indexPath.row) animated:YES];
}

But this does not keep the tableview at the contentOffset. it will snap to the top and then snap back

Body:
It will be helpful to scroll to top your tableView

tableView.setContentOffset(CGPoint(x: 0, y: -tableView.contentInset.top), animated: true).

ContentLicense: CC BY-SA 4.0


问:
Simplify one row Grid Xamarin forms Xaml
Does anyone know a simpler way to define a one row Grid. I have the following:

```<code><Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="100"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Label Text="Tester:"/>
    <Entry Grid.Column="1" />
</Grid>
</code>```

Hard to explain but using xamStrap to layout some forms and due to the label and entry layout wrapping required we need to create Grid's currently for the label and entry pairing. Having a grid for every label and entry on the form is making some really ugly large xaml contentviews.

Is there any shorthand or better way to lay this out in xaml?

答:
You should be using BindableLayouts to simplify your XAML.

As for the elements, you can achieve with Grid or StackLayout.
I would prefer using the Grid, since you have more control over the size of the elements.

Body:
Does anyone know a simpler way to define a one row Grid. I have the following:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="100"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    <Entry Grid.Column="1" />
</Grid>

Hard to explain but using xamStrap to layout some forms and due to the label and entry layout wrapping required we need to create Grid's currently for the label and entry pairing. Having a grid for every label and entry on the form is making some really ugly large xaml contentviews.

Is there any shorthand or better way to lay this out in xaml?


问:
How to set array of records Using GenericRecordBuilder
I'm trying to turn a Scala object (i.e case class) into byte array.

In order to do so, I'm inserting the object content into a GenericRecordBuilder using its specific schema, and eventually using GenericDatumWriter i turn it into a byte array.

I have no problem to set primitive types, and array of primitive types into the GenericRecordBuilder.

But, I need help with Inserting array of records into the GenericRecordBuilder, and create a byte array from it.

What is the right way to insert array of records into the GenericRecordBuilder?

Here is part of what i'm trying to do:

This is the Schema:

```<code>{
    "type": "record",
    "name": "test1",
    "namespace": "ns",
    "fields": [
      {
        "name": "t_name",
        "type": "string",
        "default": "a"
      },
      {
        "name": "t_num",
        "type": "int",
        "default": 0
      },
      {"name" : "t_arr", "type":
        ["null",
         {"type": "array", "items": {
              "name": "t_arr_a",
              "type": "record",
              "fields": [
                {
                  "name": "t_arr_f1",
                  "type": "int",
                  "default": 0
                },
                {
                  "name": "t_arr_f2",
                  "type": "int",
                  "default": 0
                }
              ]
            }
            }
         ]
       }
    ]
}
</code>```

This is the Scala class that populate the GenericRecordBuilder and transform it into byte Array:

```<code>package utils

import java.io.ByteArrayOutputStream

import org.apache.avro.{Schema, generic}
import org.apache.avro.generic.{GenericData, GenericDatumWriter}
import org.apache.avro.io.EncoderFactory
import org.apache.avro.generic.GenericRecordBuilder

object CheckRecBuilder extends App {

  val avroSchema: Schema = new Schema.Parser().parse(this.getClass.getResourceAsStream("/data/myschema.avsc"))
  val recordBuilder = new GenericRecordBuilder(avroSchema)

  recordBuilder.set("t_name", "X")
  recordBuilder.set("t_num", 100)

  recordBuilder.set("t_arr", ???)

  val record = recordBuilder.build()

  val w = new GenericDatumWriter[GenericData.Record](avroSchema)
  val outputStream = new ByteArrayOutputStream()
  val e = EncoderFactory.get.binaryEncoder(outputStream, null)
  w.write(record, e)
  val barr =  outputStream.toByteArray

  println("End")

}
</code>```

答:
I manged to set the array of objects.

I wonder if there is a better or righter way for doing it.

Here is what I did:

Created a case class:

case class t_arr_a(t_arr_f1:Int, t_arr_f2:Int)

Created a method that transform case class into a GenericData.Record:

def caseClassToGenericDataRecord(cc:Product, schema:Schema): GenericData.Record = {
        val childRecord = new GenericData.Record(schema.getElementType)

        val values = cc.productIterator
        cc.getClass.getDeclaredFields.map(f =>  childRecord.put(f.getName, values.next ))
        childRecord
      }

Updated the class CheckRecBuilder above:

replaced:

```<code>recordBuilder.set("t_arr", ???)
</code>```

With:

```<code>  val childSchema = new GenericData.Record(avroSchema2).getSchema.getField("t_arr").schema().getTypes().get(1)
  val tArray = Array(t_arr_a(2,4), t_arr_a(25,14))
  val tArrayGRecords: util.List[GenericData.Record]
    = Some(yy.map(x => caseClassToGenericDataRecord(x,childSchema))).map(arr => java.util.Arrays.asList(arr: _*)).orNull

  recordBuilder.set("t_arr", tArrayGRecords)
</code>```

Body:
I'm trying to turn a Scala object (i.e case class) into byte array.

In order to do so, I'm inserting the object content into a GenericRecordBuilder using its specific schema, and eventually using GenericDatumWriter i turn it into a byte array.

I have no problem to set primitive types, and array of primitive types into the GenericRecordBuilder.

But, I need help with Inserting array of records into the GenericRecordBuilder, and create a byte array from it.

What is the right way to insert array of records into the GenericRecordBuilder?

Here is part of what i'm trying to do:

This is the Schema:

{
    "type": "record",
    "name": "test1",
    "namespace": "ns",
    "fields": [
      {
        "name": "t_name",
        "type": "string",
        "default": "a"
      },
      {
        "name": "t_num",
        "type": "int",
        "default": 0
      },
      {"name" : "t_arr", "type":
        ["null",
         {"type": "array", "items": {
              "name": "t_arr_a",
              "type": "record",
              "fields": [
                {
                  "name": "t_arr_f1",
                  "type": "int",
                  "default": 0
                },
                {
                  "name": "t_arr_f2",
                  "type": "int",
                  "default": 0
                }
              ]
            }
            }
         ]
       }
    ]
}

This is the Scala class that populate the GenericRecordBuilder and transform it into byte Array:

package utils

import java.io.ByteArrayOutputStream

import org.apache.avro.{Schema, generic}
import org.apache.avro.generic.{GenericData, GenericDatumWriter}
import org.apache.avro.io.EncoderFactory
import org.apache.avro.generic.GenericRecordBuilder

object CheckRecBuilder extends App {

  val avroSchema: Schema = new Schema.Parser().parse(this.getClass.getResourceAsStream("/data/myschema.avsc"))
  val recordBuilder = new GenericRecordBuilder(avroSchema)

  recordBuilder.set("t_name", "X")
  recordBuilder.set("t_num", 100)

  recordBuilder.set("t_arr", ???)

  val record = recordBuilder.build()

  val w = new GenericDatumWriter[GenericData.Record](avroSchema)
  val outputStream = new ByteArrayOutputStream()
  val e = EncoderFactory.get.binaryEncoder(outputStream, null)
  w.write(record, e)
  val barr =  outputStream.toByteArray

  println("End")

}

Body:
I manged to set the array of objects.

I wonder if there is a better or righter way for doing it.

Here is what I did:

Created a case class:

case class t_arr_a(t_arr_f1:Int, t_arr_f2:Int)

Created a method that transform case class into a GenericData.Record:

def caseClassToGenericDataRecord(cc:Product, schema:Schema): GenericData.Record = {
        val childRecord = new GenericData.Record(schema.getElementType)

        val values = cc.productIterator
        cc.getClass.getDeclaredFields.map(f =>  childRecord.put(f.getName, values.next ))
        childRecord
      }

Updated the class CheckRecBuilder above:

replaced:

recordBuilder.set("t_arr", ???)

With:

  val childSchema = new GenericData.Record(avroSchema2).getSchema.getField("t_arr").schema().getTypes().get(1)
  val tArray = Array(t_arr_a(2,4), t_arr_a(25,14))
  val tArrayGRecords: util.List[GenericData.Record]
    = Some(yy.map(x => caseClassToGenericDataRecord(x,childSchema))).map(arr => java.util.Arrays.asList(arr: _*)).orNull

  recordBuilder.set("t_arr", tArrayGRecords)


问:
Getting A new session could not be created
Can anyone help me out I am new to Android testing with Appium , I am trying to open app in AVD the app getting installed but then m getting Error "A new Session could not be created.(Original error: Command failed: )","killed":false,"code":1,"signal":null,"origValue":"Command failed: "},"sessionId":null}

Thanks for the help in advance

tried with just giving capabilities.setCapability("appActivity", ".MainActivity");

```<code>'''

File classpathRoot = new File(System.getProperty("user.dir"));
        File appDir = new File(classpathRoot, "/Apps/src/");
        File app = new File(appDir, "ChatApp-release.apk");

        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
        capabilities.setCapability("deviceName", "emulator-5554");
        capabilities.setCapability("platformVersion", "7.1.1");
        capabilities.setCapability("platformName", "Android");
        capabilities.setCapability("app", app.getAbsolutePath());
        capabilities.setCapability("appPackage", "com.aaa.charla");
        capabilities.setCapability("appActivity", "com.aaa.xxx.MainActivity");

        driver = new AndroidDriver(new URL("https://127.0.0.1:4723/wd/hub"), capabilities);
        driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);
        Thread.sleep(10000);
        driver.quit();
</code>```

Following are the Debug log:

info: Console LogLevel: debug
  info: --> POST /wd/hub/session {"desiredCapabilities":{"app":"D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk","appPackage":"com.odysseyinc.charla","appActivity":"com.odyssey.chatapp.MainActivity","newCommandTimeout":"10000","platformName":"Android","version":"7.1.1","deviceName":"emulator-5554"}}
  info: Client User-Agent string: Apache-HttpClient/4.5.2 (Java/1.8.0_162)
  info: [debug] The following desired capabilities were provided, but not recognized by appium. They will be passed on to any other services running on this server. : version
  info: [debug] Using local app from desired caps: D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk
  info: [debug] Creating new appium session 0d25aeac-d055-449f-af84-b6d314d9b4a5
  info: Starting android appium
  info: [debug] Getting Java version
  info: Java version is: 1.8.0_162
  info: [debug] Checking whether adb is present
  info: [debug] Using adb from C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe
  info: [debug] Set chromedriver binary as: C:\Program Files (x86)\Appium\node_modules\appium\build\chromedriver\windows\chromedriver.exe
  info: [debug] Using fast reset? true
  info: [debug] Preparing device for session
  info: [debug] Checking whether app is actually present
  info: Retrieving device
  info: [debug] Trying to find a connected android device
  info: [debug] Getting connected devices...
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe devices
  info: [debug] 1 device(s) connected
  info: Found device emulator-5554
  info: [debug] Setting device id to emulator-5554
  info: [debug] Waiting for device to be ready and to respond to shell commands (timeout = 5)
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 wait-for-device
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "echo 'ready'"
  info: [debug] Starting logcat capture
  info: [debug] Getting device API level
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "getprop ro.build.version.sdk"
  info: [debug] Device is at API Level 25
  info: Device API level is: 25
  info: [debug] Extracting strings for language: default
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "getprop persist.sys.language"
  info: [debug] Current device persist.sys.language:
  info: [debug] java -jar "C:\Program Files (x86)\Appium\node_modules\appium\node_modules\appium-adb\jars\appium_apk_tools.jar" "stringsFromApk" "D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk" "C:\Users\UNMESH~1.GHA\AppData\Local\Temp\com.odysseyinc.charla"
  info: [debug] Reading strings from converted strings.json
  info: [debug] Setting language to default
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 push "C:\Users\UNMESH~1.GHA\AppData\Local\Temp\com.odysseyinc.charla\strings.json" /data/local/tmp
  info: [debug] Checking whether aapt is present
  info: [debug] Using aapt from C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\build-tools\28.0.3\aapt.exe
  info: [debug] Retrieving process from manifest.
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\build-tools\28.0.3\aapt.exe dump xmltree D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk AndroidManifest.xml
  info: [debug] Set app process to: com.odysseyinc.charla
  info: [debug] Not uninstalling app since server not started with --full-reset
  info: [debug] Checking app cert for D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk.
  info: [debug] executing cmd: java -jar "C:\Program Files (x86)\Appium\node_modules\appium\node_modules\appium-adb\jars\verify.jar" D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk
  info: [debug] App already signed.
  info: [debug] Zip-aligning D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk
  info: [debug] Checking whether zipalign is present
  info: [debug] Using zipalign from C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\build-tools\28.0.3\zipalign.exe
  info: [debug] Zip-aligning apk.
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\build-tools\28.0.3\zipalign.exe -f 4 D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk C:\Users\UNMESH~1.GHA\AppData\Local\Temp\119427-15556-1rmbgw9\appium.tmp
  info: [debug] MD5 for app is f3d7efc8b197792c3d0529a48dc92ff2
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "ls /data/local/tmp/f3d7efc8b197792c3d0529a48dc92ff2.apk"
  info: [debug] Getting install status for com.odysseyinc.charla
  info: [debug] Getting device API level
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "getprop ro.build.version.sdk"
  info: [debug] Device is at API Level 25
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "pm list packages -3 com.odysseyinc.charla"
  info: [debug] App is installed
  info: App is already installed, resetting app
  info: [debug] Running fast reset (stop and clear)
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "am force-stop com.odysseyinc.charla"
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "pm clear com.odysseyinc.charla"
  info: [debug] Forwarding system:4724 to device:4724
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 forward tcp:4724 tcp:4724
  info: [debug] Pushing appium bootstrap to device...
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 push "C:\Program Files (x86)\Appium\node_modules\appium\build\android_bootstrap\AppiumBootstrap.jar" /data/local/tmp/
  info: [debug] Pushing settings apk to device...
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 install "C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk"
  info: [debug] Stopping logcat capture
  info: [debug] Logcat terminated with code null, signal SIGTERM
  info: [debug] Sent shutdown command, waiting for UiAutomator to stop...
  warn: UiAutomator did not shut down fast enough, calling it gone
  error: Failed to start an Appium session, err was: Error: Command failed: adb: failed to install C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install io.appium.settings without first uninstalling.]

info: [debug] Cleaning up android objects
  info: [debug] Cleaning up appium session
  info: [debug] Error: Command failed: adb: failed to install C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install io.appium.settings without first uninstalling.]

```<code>at ChildProcess.exithandler (child_process.js:637:15)
at ChildProcess.EventEmitter.emit (events.js:98:17)
at maybeClose (child_process.js:743:16)
at Process.ChildProcess._handle.onexit (child_process.js:810:5)
</code>```

info: [debug] Responding to client with error: {"status":33,"value":{"message":"A new session could not be created. (Original error: Command failed: adb: failed to install C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install io.appium.settings without first uninstalling.]\r\n)","killed":false,"code":1,"signal":null,"origValue":"Command failed: adb: failed to install C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install io.appium.settings without first uninstalling.]\r\n"},"sessionId":null}
  info: <-- POST /wd/hub/session 500 32039.992 ms - 664

`

答: I have upgraded the Appuim 1.4 to 1.9 and started working as Expected .</p>

Body:
Can anyone help me out I am new to Android testing with Appium , I am trying to open app in AVD the app getting installed but then m getting Error "A new Session could not be created.(Original error: Command failed: )","killed":false,"code":1,"signal":null,"origValue":"Command failed: "},"sessionId":null}

Thanks for the help in advance

tried with just giving capabilities.setCapability("appActivity", ".MainActivity");

'''

File classpathRoot = new File(System.getProperty("user.dir"));
        File appDir = new File(classpathRoot, "/Apps/src/");
        File app = new File(appDir, "ChatApp-release.apk");

        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
        capabilities.setCapability("deviceName", "emulator-5554");
        capabilities.setCapability("platformVersion", "7.1.1");
        capabilities.setCapability("platformName", "Android");
        capabilities.setCapability("app", app.getAbsolutePath());
        capabilities.setCapability("appPackage", "com.aaa.charla");
        capabilities.setCapability("appActivity", "com.aaa.xxx.MainActivity");

        driver = new AndroidDriver(new URL("https://127.0.0.1:4723/wd/hub"), capabilities);
        driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);
        Thread.sleep(10000);
        driver.quit();

Following are the Debug log:

info: Console LogLevel: debug
  info: --> POST /wd/hub/session {"desiredCapabilities":{"app":"D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk","appPackage":"com.odysseyinc.charla","appActivity":"com.odyssey.chatapp.MainActivity","newCommandTimeout":"10000","platformName":"Android","version":"7.1.1","deviceName":"emulator-5554"}}
  info: Client User-Agent string: Apache-HttpClient/4.5.2 (Java/1.8.0_162)
  info: [debug] The following desired capabilities were provided, but not recognized by appium. They will be passed on to any other services running on this server. : version
  info: [debug] Using local app from desired caps: D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk
  info: [debug] Creating new appium session 0d25aeac-d055-449f-af84-b6d314d9b4a5
  info: Starting android appium
  info: [debug] Getting Java version
  info: Java version is: 1.8.0_162
  info: [debug] Checking whether adb is present
  info: [debug] Using adb from C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe
  info: [debug] Set chromedriver binary as: C:\Program Files (x86)\Appium\node_modules\appium\build\chromedriver\windows\chromedriver.exe
  info: [debug] Using fast reset? true
  info: [debug] Preparing device for session
  info: [debug] Checking whether app is actually present
  info: Retrieving device
  info: [debug] Trying to find a connected android device
  info: [debug] Getting connected devices...
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe devices
  info: [debug] 1 device(s) connected
  info: Found device emulator-5554
  info: [debug] Setting device id to emulator-5554
  info: [debug] Waiting for device to be ready and to respond to shell commands (timeout = 5)
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 wait-for-device
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "echo 'ready'"
  info: [debug] Starting logcat capture
  info: [debug] Getting device API level
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "getprop ro.build.version.sdk"
  info: [debug] Device is at API Level 25
  info: Device API level is: 25
  info: [debug] Extracting strings for language: default
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "getprop persist.sys.language"
  info: [debug] Current device persist.sys.language:
  info: [debug] java -jar "C:\Program Files (x86)\Appium\node_modules\appium\node_modules\appium-adb\jars\appium_apk_tools.jar" "stringsFromApk" "D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk" "C:\Users\UNMESH~1.GHA\AppData\Local\Temp\com.odysseyinc.charla"
  info: [debug] Reading strings from converted strings.json
  info: [debug] Setting language to default
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 push "C:\Users\UNMESH~1.GHA\AppData\Local\Temp\com.odysseyinc.charla\strings.json" /data/local/tmp
  info: [debug] Checking whether aapt is present
  info: [debug] Using aapt from C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\build-tools\28.0.3\aapt.exe
  info: [debug] Retrieving process from manifest.
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\build-tools\28.0.3\aapt.exe dump xmltree D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk AndroidManifest.xml
  info: [debug] Set app process to: com.odysseyinc.charla
  info: [debug] Not uninstalling app since server not started with --full-reset
  info: [debug] Checking app cert for D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk.
  info: [debug] executing cmd: java -jar "C:\Program Files (x86)\Appium\node_modules\appium\node_modules\appium-adb\jars\verify.jar" D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk
  info: [debug] App already signed.
  info: [debug] Zip-aligning D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk
  info: [debug] Checking whether zipalign is present
  info: [debug] Using zipalign from C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\build-tools\28.0.3\zipalign.exe
  info: [debug] Zip-aligning apk.
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\build-tools\28.0.3\zipalign.exe -f 4 D:\AndroidNew\Yrreport\YrReport\RemoteSystemsTempFiles\Appium\apk\ChatApp-master-0.9.35.1195-release.apk C:\Users\UNMESH~1.GHA\AppData\Local\Temp\119427-15556-1rmbgw9\appium.tmp
  info: [debug] MD5 for app is f3d7efc8b197792c3d0529a48dc92ff2
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "ls /data/local/tmp/f3d7efc8b197792c3d0529a48dc92ff2.apk"
  info: [debug] Getting install status for com.odysseyinc.charla
  info: [debug] Getting device API level
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "getprop ro.build.version.sdk"
  info: [debug] Device is at API Level 25
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "pm list packages -3 com.odysseyinc.charla"
  info: [debug] App is installed
  info: App is already installed, resetting app
  info: [debug] Running fast reset (stop and clear)
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "am force-stop com.odysseyinc.charla"
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 shell "pm clear com.odysseyinc.charla"
  info: [debug] Forwarding system:4724 to device:4724
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 forward tcp:4724 tcp:4724
  info: [debug] Pushing appium bootstrap to device...
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 push "C:\Program Files (x86)\Appium\node_modules\appium\build\android_bootstrap\AppiumBootstrap.jar" /data/local/tmp/
  info: [debug] Pushing settings apk to device...
  info: [debug] executing cmd: C:\Users\unmesh.ghatbandhe\AppData\Local\Android\Sdk\platform-tools\adb.exe -s emulator-5554 install "C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk"
  info: [debug] Stopping logcat capture
  info: [debug] Logcat terminated with code null, signal SIGTERM
  info: [debug] Sent shutdown command, waiting for UiAutomator to stop...
  warn: UiAutomator did not shut down fast enough, calling it gone
  error: Failed to start an Appium session, err was: Error: Command failed: adb: failed to install C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install io.appium.settings without first uninstalling.]

info: [debug] Cleaning up android objects
  info: [debug] Cleaning up appium session
  info: [debug] Error: Command failed: adb: failed to install C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install io.appium.settings without first uninstalling.]

at ChildProcess.exithandler (child_process.js:637:15)
at ChildProcess.EventEmitter.emit (events.js:98:17)
at maybeClose (child_process.js:743:16)
at Process.ChildProcess._handle.onexit (child_process.js:810:5)

info: [debug] Responding to client with error: {"status":33,"value":{"message":"A new session could not be created. (Original error: Command failed: adb: failed to install C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install io.appium.settings without first uninstalling.]\r\n)","killed":false,"code":1,"signal":null,"origValue":"Command failed: adb: failed to install C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install io.appium.settings without first uninstalling.]\r\n"},"sessionId":null}
  info: <-- POST /wd/hub/session 500 32039.992 ms - 664

`


问:
Is there any way to count the no. of blank rows in csv file?
I have used fast-csv module and it only has the option to ignore the empty rows but I need to count the empty rows.</p>

```<code>    csv
    .fromPath(importFile.path, {
        headers: true,
        ignoreEmpty: true
    })
    .on("data", function(data) {
      console.log(data)
    })
</code>```

答:
From the code I am seeing you are already half way there. Just initialize a count variable at the top and in the callback of "data" event split the lines in array and check if the row is empty, based on your requirement.

```<code>function getEmptyRows(csv){

    return new Promise((resolve, reject) => {

    let emptyRows = 0;

        csv
        .fromPath(importFile.path, {
            headers: true,
            ignoreEmpty: true
        })
        .on("data", (data) => {
            const lines = data.trim().split(/\s*[\r\n]+\s*/g);

            lines.forEach((line) => {
                if(line.match(/([^\s,])/)){
                    count++;
                }
            });
        })
        .on('end', () => {
            return resolve(count);
        });
    });
}
</code>```

And you can use the function above in the following ways-

```<code>getEmptyRows(csv).then((count) => {
    // do your operation...
});

// or as an async/await

async () => {
    const count = await getEmptyRows(csv);
    // do your operation...
}
</code>```

Body:
I have used fast-csv module and it only has the option to ignore the empty rows but I need to count the empty rows.

    csv
    .fromPath(importFile.path, {
        headers: true,
        ignoreEmpty: true
    })
    .on("data", function(data) {
      console.log(data)
    })

Body:
From the code I am seeing you are already half way there. Just initialize a count variable at the top and in the callback of "data" event split the lines in array and check if the row is empty, based on your requirement.

function getEmptyRows(csv){

    return new Promise((resolve, reject) => {

    let emptyRows = 0;

        csv
        .fromPath(importFile.path, {
            headers: true,
            ignoreEmpty: true
        })
        .on("data", (data) => {
            const lines = data.trim().split(/\s*[\r\n]+\s*/g);

            lines.forEach((line) => {
                if(line.match(/([^\s,])/)){
                    count++;
                }
            });
        })
        .on('end', () => {
            return resolve(count);
        });
    });
}

And you can use the function above in the following ways-

getEmptyRows(csv).then((count) => {
    // do your operation...
});

// or as an async/await

async () => {
    const count = await getEmptyRows(csv);
    // do your operation...
}


问:
in laravel Upload image in two different folder at same time

This Code save image in only one "folder-one". I want to upload the
  image at the same time in two different folders, now it saving in folder-one

example

"folder-one"

and

"folder-two"

```<code><?php

namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Mail;
use Illuminate\Auth\Events\Registered;

class RegisterController extends Controller
{

use RegistersUsers;

protected $redirectTo = '/home';

public function __construct()
{
    $this->middleware('guest');
}

protected function validator(array $data)
{
    return Validator::make($data, [
       'photo_jpeg' => 'required|image|mimes:jpeg,png,jpg|max:2048',
    ]);
}

protected function create(array $data)
{
    $photo_jpeg= time() . '.' . $data['photo_jpeg']->getClientOriginalExtension();
    $data['photo_jpeg']->move(base_path() . 'public/folder-one', $photo_jpeg);

    return user::create([
        'photo_jpeg' => $photo_jpeg,
    ]);

}
</code>```

答:
You can't run move() twice for the same file because as it name says, it moves the file, so on the second run, the original file won't exist anymore.

You must copy the file:

```<code>$uploadPath = public_path('folder-one/');
$file = $data['photo_jpeg'];
$photo_jpeg= time() . '.' .$file->getClientOriginalExtension();
$file->move($uploadPath,$photo_jpeg);
\File::copy($uploadPath.$photo_jpeg,public_path('folder-two/').$photo_jpeg);
</code>```

Body:
This Code save image in only one "folder-one". I want to upload the
  image at the same time in two different folders, now it saving in folder-one

example

"folder-one"

and

"folder-two"

<?php

namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Mail;
use Illuminate\Auth\Events\Registered;

class RegisterController extends Controller
{

use RegistersUsers;

protected $redirectTo = '/home';

public function __construct()
{
    $this->middleware('guest');
}

protected function validator(array $data)
{
    return Validator::make($data, [
       'photo_jpeg' => 'required|image|mimes:jpeg,png,jpg|max:2048',
    ]);
}

protected function create(array $data)
{
    $photo_jpeg= time() . '.' . $data['photo_jpeg']->getClientOriginalExtension();
    $data['photo_jpeg']->move(base_path() . 'public/folder-one', $photo_jpeg);

    return user::create([
        'photo_jpeg' => $photo_jpeg,
    ]);

}

Body:
You can't run move() twice for the same file because as it name says, it moves the file, so on the second run, the original file won't exist anymore.

You must copy the file:

$uploadPath = public_path('folder-one/');
$file = $data['photo_jpeg'];
$photo_jpeg= time() . '.' .$file->getClientOriginalExtension();
$file->move($uploadPath,$photo_jpeg);
\File::copy($uploadPath.$photo_jpeg,public_path('folder-two/').$photo_jpeg);


问:
jquery stop event bubbling with live
I have this code

```<code> var input = $("form input[name='name'].dhxlist_txt_textarea");

 $(input).live('click', function () {

       ShowLookupGrid();
 });
</code>```

Then I've putted a second live binding before the first get executed

```<code>  $('#Id').live('click', function () {

       return false;
 });
</code>```

But the return false statement isn't stoping bubbling up the event to the second binding.

答: This is not event bubbling, you are attaching a handler twice to the same element (one through the id selector and other one through element selector).</p>

Title: jquery stop event bubbling with live

Body:
I have this code

 var input = $("form input[name='name'].dhxlist_txt_textarea");

 $(input).live('click', function () {

       ShowLookupGrid();
 });

Then I've putted a second live binding before the first get executed

  $('#Id').live('click', function () {

       return false;
 });

But the return false statement isn't stoping bubbling up the event to the second binding.


问:
why does this if statement give my a ValueError?
I'm trying to iterate over a numpy 2d array and check where the values 1,2 and 3 occur in the array, but i receive a value error, because numpy states that it's ambiguous. What is the best way to fix this problem?

for x in range(row):
        for y in range(row):
            if grid[x,y] == 1:
                pygame.draw.rect(window, (0,255,0), (x * distance, y * distance, distance, distance))
            elif grid[x,y] == 2:
                pygame.draw.rect(window, (0,255,0), (x * distance, y * distance, distance, distance))
            elif  grid[x,y] == 3:
                pygame.draw.rect(window, (255,0,0), (x * distance, y * distance, distance, distance))
```

``` if grid[x,y] == 1:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
```

答:
As per your generateGrid function, shown in comments,

Replace grid[i.x, i.y] to grid[i.x][ i.y] in generateGrid function.

This has resolved your issue.

Body:
I'm trying to iterate over a numpy 2d array and check where the values 1,2 and 3 occur in the array, but i receive a value error, because numpy states that it's ambiguous. What is the best way to fix this problem?

for x in range(row):
        for y in range(row):
            if grid[x,y] == 1:
                pygame.draw.rect(window, (0,255,0), (x * distance, y * distance, distance, distance))
            elif grid[x,y] == 2:
                pygame.draw.rect(window, (0,255,0), (x * distance, y * distance, distance, distance))
            elif  grid[x,y] == 3:
                pygame.draw.rect(window, (255,0,0), (x * distance, y * distance, distance, distance))

 if grid[x,y] == 1:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


问:
How can I push a branch to remote after resolving rebase conflicts without using force push?
I have a Git branch with an open pull request in GitHub. But I can't merge it because GitHub complains that there are some conflicting files with latest master. Then I pull master and rebase master to my local branch and during rebase, I got conflicts. So I resolved the conflicts and when trying to push the branch to origin, my push was rejected and error says that the tip of my current branch is behind. However when I do force push it will get accepted. Anyway I can achieve this without using force push?</p>

答: Instead of rebasing you should merge, this will not rewrite the history and you will be able to push it without force push. If you don't want to merge then unfortunately there is no way I know to achieve this without force push.


问:
Getting null data on response body using retrofit2?
I am new to retrofit 2 and i am trying to get json array data but getting null, this is the url for getting the data.

But the funny thing is when i try to debug inside onResponse i am getting success message as well as response.body data. What is the problem here?

https://xenzet.com/GameCheat/viewgamesjson.php

this is json data

```<code>[
    {
        "gameid":"2",
        "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/counter strike 1.6.png",
        "Games_Name":"1"
    },
    {
        "gameid":"3",
        "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/gta.ico",
        "Games_Name":"vice city sucjlfsdrgefdsrhag"
    },
    {
        "gameid":"4",
        "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/pubg.png",
        "Games_Name":"pubg"
    },
    {
    "gameid":"5",
    "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/doom.png",
    "Games_Name":"Doom Enternal"
    },
    {
    "gameid":"6",
    "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/for.png",
    "Games_Name":"Fornite"
    },
    {
    "gameid":"9",
    "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/dota2.png",
    "Games_Name":"dota2"
    }
]
</code>```

this is the method which is trying to get data

```<code> public void fetch_information() {

        ApiInterface = ApiClient.getApiClient().create(Api.class);

        Call<List<Games>> call = ApiInterface.GetGames();

        call.enqueue(new Callback<List<Games>>() {
            @Override
            public void onResponse(Call<List<Games>> call, Response<List<Games>> response) {
                if(response.isSuccessful()) {

                    gameslist = response.body();
                    gamescounter = gameslist.size();
                    adapter = new GameRecyclerViewAdapter(GamesActivity.this, gameslist);
                    recyclerView.setAdapter(adapter);
                }
            }

            @Override
            public void onFailure(Call<List<Games>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

    }
</code>```

this is ApiClient

```<code>public class ApiClient {

    public static  String Base_URL ;

    public static Retrofit retrofit;

    public static Retrofit getApiClient()
    {
        if (retrofit == null)
        {
            Base_URL ="https://xenzet.com/GameCheat/";
            retrofit = new Retrofit.Builder().baseUrl(Base_URL)
                    .addConverterFactory(GsonConverterFactory.create()).build();

        }
        return retrofit;
    }
}
</code>```

and Api

```<code>public interface Api {

    @GET("viewgamesjson.php")
    Call<List<Games>> GetGames();
}
</code>```

and in OnCreate i am calling fetch information method.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_games);
    gameslist = new ArrayList<Games>();
    RecyclerView recyclerView = findViewById(R.id.recyclerview_gameslist);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
     fetch_information();

    Toast.makeText(getApplicationContext(),"" +gamescounter, Toast.LENGTH_SHORT).show();

    adapter = new GameRecyclerViewAdapter(this, gameslist);

   recyclerView.setAdapter(adapter);
    adapter.setClickListener((GameRecyclerViewAdapter.ItemClickListener) this);
}
</code>```

trying to fill data of game list in recycler view but fails as it null.

this is logcat

```<code>2019-05-27 14:03:43.261 1261-1261/com.example.quizgames E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.quizgames, PID: 1261
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
    at com.example.quizgames.GamesActivity$1.onResponse(GamesActivity.java:109)
    at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
    at android.os.Handler.handleCallback(Handler.java:836)
    at android.os.Handler.dispatchMessage(Handler.java:103)
    at android.os.Looper.loop(Looper.java:203)
    at android.app.ActivityThread.main(ActivityThread.java:6251)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
</code>```

This is class Games

```<code>public class Games {

    @SerializedName("gameid")
    @Expose
    private String gameid;
    @SerializedName("gameIcon")
    @Expose
    private String gameIcon;
    @SerializedName("Games_Name")
    @Expose
    private String gamesName;

    public String getGameid() {
        return gameid;
    }

    public void setGameid(String gameid) {
        this.gameid = gameid;
    }

    public String getGameIcon() {
        return gameIcon;
    }

    public void setGameIcon(String gameIcon) {
        this.gameIcon = gameIcon;
    }

    public String getGamesName() {
        return gamesName;
    }

    public void setGamesName(String gamesName) {
        this.gamesName = gamesName;
    }

//    public Games(String Gameid,String Gameicon,String GameName)
//    {
//      this.gameid = Gameid;
//      this.gameIcon = Gameicon;
//      this.gamesName = GameName;
//
//    }

}
</code>```

This is recycler view

```<code>class GameRecyclerViewAdapter extends RecyclerView.Adapter<GameRecyclerViewAdapter.ViewHolder> {

    private List<Games> mGames;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    // data is passed into the constructor
    GameRecyclerViewAdapter(Context context, List<Games> games) {
        this.mInflater = LayoutInflater.from(context);
        this.mGames = games;
    }

    // inflates the row layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.gameitem, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each row
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Games Game = mGames.get(position);
        String Gameid = Game.getGameid();
        String Gameicon = Game.getGameIcon();
        String Gamename = Game.getGamesName();
        holder.GameNameTxt.setText(Gamename);
        Glide.with(holder.GameIconImage.getContext()).load(Game.getGameIcon()).thumbnail(0.1f).
                placeholder(R.color.colorPrimary).diskCacheStrategy(DiskCacheStrategy.NONE).into(holder.GameIconImage);

    }

    // total number of rows
    @Override
    public int getItemCount() {

        return mGames == null ? 0 : mGames.size();

    }

    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView GameNameTxt;
        ImageView GameIconImage;
        ViewHolder(View itemView) {
            super(itemView);
            GameNameTxt = itemView.findViewById(R.id.gamename);
            GameIconImage = itemView.findViewById(R.id.imageView);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    // allows clicks events to be caught
    void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);

    }
}
</code>```

答:
I didn't check where you make mistake. But this code implementation returning me list having 10 data inside list.

```<code>public interface APIInterface {

    @GET()
    Call<List<ViewGame>> viewgamesjson(@Url String url);

}
</code>```

This is model class:

```<code>public class ViewGame {
    String gameid,gameIcon,Games_Name;

    public String getGameid() {
        return gameid;
    }

    public void setGameid(String gameid) {
        this.gameid = gameid;
    }

    public String getGameIcon() {
        return gameIcon;
    }

    public void setGameIcon(String gameIcon) {
        this.gameIcon = gameIcon;
    }

    public String getGames_Name() {
        return Games_Name;
    }

    public void setGames_Name(String games_Name) {
        Games_Name = games_Name;
    }
}
</code>```

This is APiClient Class:

```<code>public class APIClient {
    static Retrofit retrofit = null;

    public static String Base_URL = "https://xenzet.com/GameCheat/";

    public static APIInterface getInterface() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .addInterceptor(interceptor)
                .build();

        retrofit = new Retrofit.Builder()
                .baseUrl(Base_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

        return retrofit.create(APIInterface.class);
    }
}
</code>```

And this is API Call:

```<code> private void viewGame() {
        Call<List<ViewGame>> call = APIClient.getInterface().viewgamesjson("https://xenzet.com/GameCheat/viewgamesjson.php");

        call.enqueue(new Callback<List<ViewGame>>() {
            @Override
            public void onResponse(Call<List<ViewGame>> call, Response<List<ViewGame>> response) {
                try {
                    Global.dismissProgress();

                    if (response.isSuccessful() && response.body() != null) {
                        Global.dismissProgress();

                        Global.printLog("size===", response.body().size() + "");

                    } else {
                        Global.dismissProgress();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Global.dismissProgress();
                }
            }

            @Override
            public void onFailure(Call<List<ViewGame>> call, Throwable t) {
                Global.dismissProgress();
                try {
                    Global.showToast(SplashActivity.this, getString(R.string.something_wrong));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                call.cancel();
                t.printStackTrace();
            }
        });
    }
</code>```

Body:
I am new to retrofit 2 and i am trying to get json array data but getting null, this is the url for getting the data.

But the funny thing is when i try to debug inside onResponse i am getting success message as well as response.body data. What is the problem here?

https://xenzet.com/GameCheat/viewgamesjson.php

this is json data

[
    {
        "gameid":"2",
        "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/counter strike 1.6.png",
        "Games_Name":"1"
    },
    {
        "gameid":"3",
        "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/gta.ico",
        "Games_Name":"vice city sucjlfsdrgefdsrhag"
    },
    {
        "gameid":"4",
        "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/pubg.png",
        "Games_Name":"pubg"
    },
    {
    "gameid":"5",
    "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/doom.png",
    "Games_Name":"Doom Enternal"
    },
    {
    "gameid":"6",
    "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/for.png",
    "Games_Name":"Fornite"
    },
    {
    "gameid":"9",
    "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/dota2.png",
    "Games_Name":"dota2"
    }
]

this is the method which is trying to get data

 public void fetch_information() {

        ApiInterface = ApiClient.getApiClient().create(Api.class);

        Call<List<Games>> call = ApiInterface.GetGames();

        call.enqueue(new Callback<List<Games>>() {
            @Override
            public void onResponse(Call<List<Games>> call, Response<List<Games>> response) {
                if(response.isSuccessful()) {

                    gameslist = response.body();
                    gamescounter = gameslist.size();
                    adapter = new GameRecyclerViewAdapter(GamesActivity.this, gameslist);
                    recyclerView.setAdapter(adapter);
                }
            }

            @Override
            public void onFailure(Call<List<Games>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

    }

this is ApiClient

public class ApiClient {

    public static  String Base_URL ;

    public static Retrofit retrofit;

    public static Retrofit getApiClient()
    {
        if (retrofit == null)
        {
            Base_URL ="https://xenzet.com/GameCheat/";
            retrofit = new Retrofit.Builder().baseUrl(Base_URL)
                    .addConverterFactory(GsonConverterFactory.create()).build();

        }
        return retrofit;
    }
}

and Api

public interface Api {

    @GET("viewgamesjson.php")
    Call<List<Games>> GetGames();
}

and in OnCreate i am calling fetch information method.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_games);
    gameslist = new ArrayList<Games>();
    RecyclerView recyclerView = findViewById(R.id.recyclerview_gameslist);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
     fetch_information();

    Toast.makeText(getApplicationContext(),"" +gamescounter, Toast.LENGTH_SHORT).show();

    adapter = new GameRecyclerViewAdapter(this, gameslist);

   recyclerView.setAdapter(adapter);
    adapter.setClickListener((GameRecyclerViewAdapter.ItemClickListener) this);
}

trying to fill data of game list in recycler view but fails as it null.

this is logcat

2019-05-27 14:03:43.261 1261-1261/com.example.quizgames E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.quizgames, PID: 1261
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
    at com.example.quizgames.GamesActivity$1.onResponse(GamesActivity.java:109)
    at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
    at android.os.Handler.handleCallback(Handler.java:836)
    at android.os.Handler.dispatchMessage(Handler.java:103)
    at android.os.Looper.loop(Looper.java:203)
    at android.app.ActivityThread.main(ActivityThread.java:6251)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)

This is class Games

public class Games {

    @SerializedName("gameid")
    @Expose
    private String gameid;
    @SerializedName("gameIcon")
    @Expose
    private String gameIcon;
    @SerializedName("Games_Name")
    @Expose
    private String gamesName;

    public String getGameid() {
        return gameid;
    }

    public void setGameid(String gameid) {
        this.gameid = gameid;
    }

    public String getGameIcon() {
        return gameIcon;
    }

    public void setGameIcon(String gameIcon) {
        this.gameIcon = gameIcon;
    }

    public String getGamesName() {
        return gamesName;
    }

    public void setGamesName(String gamesName) {
        this.gamesName = gamesName;
    }

//    public Games(String Gameid,String Gameicon,String GameName)
//    {
//      this.gameid = Gameid;
//      this.gameIcon = Gameicon;
//      this.gamesName = GameName;
//
//    }

}

This is recycler view

class GameRecyclerViewAdapter extends RecyclerView.Adapter<GameRecyclerViewAdapter.ViewHolder> {

    private List<Games> mGames;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    // data is passed into the constructor
    GameRecyclerViewAdapter(Context context, List<Games> games) {
        this.mInflater = LayoutInflater.from(context);
        this.mGames = games;
    }

    // inflates the row layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.gameitem, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each row
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Games Game = mGames.get(position);
        String Gameid = Game.getGameid();
        String Gameicon = Game.getGameIcon();
        String Gamename = Game.getGamesName();
        holder.GameNameTxt.setText(Gamename);
        Glide.with(holder.GameIconImage.getContext()).load(Game.getGameIcon()).thumbnail(0.1f).
                placeholder(R.color.colorPrimary).diskCacheStrategy(DiskCacheStrategy.NONE).into(holder.GameIconImage);

    }

    // total number of rows
    @Override
    public int getItemCount() {

        return mGames == null ? 0 : mGames.size();

    }

    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView GameNameTxt;
        ImageView GameIconImage;
        ViewHolder(View itemView) {
            super(itemView);
            GameNameTxt = itemView.findViewById(R.id.gamename);
            GameIconImage = itemView.findViewById(R.id.imageView);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    // allows clicks events to be caught
    void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);

    }
}

Body:
I didn't check where you make mistake. But this code implementation returning me list having 10 data inside list.

public interface APIInterface {

    @GET()
    Call<List<ViewGame>> viewgamesjson(@Url String url);

}

This is model class:

public class ViewGame {
    String gameid,gameIcon,Games_Name;

    public String getGameid() {
        return gameid;
    }

    public void setGameid(String gameid) {
        this.gameid = gameid;
    }

    public String getGameIcon() {
        return gameIcon;
    }

    public void setGameIcon(String gameIcon) {
        this.gameIcon = gameIcon;
    }

    public String getGames_Name() {
        return Games_Name;
    }

    public void setGames_Name(String games_Name) {
        Games_Name = games_Name;
    }
}

This is APiClient Class:

public class APIClient {
    static Retrofit retrofit = null;

    public static String Base_URL = "https://xenzet.com/GameCheat/";

    public static APIInterface getInterface() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .addInterceptor(interceptor)
                .build();

        retrofit = new Retrofit.Builder()
                .baseUrl(Base_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

        return retrofit.create(APIInterface.class);
    }
}

And this is API Call:

 private void viewGame() {
        Call<List<ViewGame>> call = APIClient.getInterface().viewgamesjson("https://xenzet.com/GameCheat/viewgamesjson.php");

        call.enqueue(new Callback<List<ViewGame>>() {
            @Override
            public void onResponse(Call<List<ViewGame>> call, Response<List<ViewGame>> response) {
                try {
                    Global.dismissProgress();

                    if (response.isSuccessful() && response.body() != null) {
                        Global.dismissProgress();

                        Global.printLog("size===", response.body().size() + "");

                    } else {
                        Global.dismissProgress();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Global.dismissProgress();
                }
            }

            @Override
            public void onFailure(Call<List<ViewGame>> call, Throwable t) {
                Global.dismissProgress();
                try {
                    Global.showToast(SplashActivity.this, getString(R.string.something_wrong));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                call.cancel();
                t.printStackTrace();
            }
        });
    }


问:
Is it possible to use terraform to destroy ec2 instance without a state file
Is it possible to destroy an ec2 instance without the state file?
I want to destroy the instance by its tag name.

Thanks

Jake

答:
No. Terraform is not the tool that you can use to manage some random resources in your AWS cloud. The concept of Terraform is completely different, it does not work without the state file.

For your task you have to use aws cli.


问:
Get Tenant Id from RabbitMq Message for Db Connection
I have a microservice architecture with ASP.Net Core applications and RabbitMq as the event bus between the microservices.

I also want to support multi tenancy.

So I have following dependency injection service defined in the Startup.cs to open a connection to the Database on every request based on the user's tenant id.

```<code>services.AddScoped<IDocumentSession>(ds =>
            {
                var store = ds.GetRequiredService<IDocumentStore>();
                var httpContextAccessor = ds.GetRequiredService<IHttpContextAccessor>();
                var tenant = httpContextAccessor?.HttpContext?.User?.Claims.FirstOrDefault(c => c.Type == "tid")?.Value;
                return tenant != null ? store.OpenSession(tenant) : store.OpenSession();
            });
</code>```

The problem is when the service processes an event bus message (like UserUpdatedEvent).

In that case when it tries to open the Db connection, it obviously does not have the user information from the http context.

How do I send/access the tenant id of the respective user when injecting the scoped service and processing an event with RabbitMq?

Or rephrasing my question:
Is there any way to access the RabbitMQ message (and for example its headers) when the dependency injection code is executed?

答:
You can't

Or maybe, but not if your design depends on the HTTP context. As the .NET documentation on service lifetime states:

Scoped lifetime services are created once per client request
(connection).

So from the point of view of your (HTTP) service, the request is an entry point that used container magic to, by means of the global HTTP context, set up your database per request, before any of your business logic. This does not seem to be the best design choice, especially if you plan to use this same logic outside of an HTTP request.

In contrast, your message consumer service is long-running; In this lifetime cycle, if your connection setup requires information from each message (tenant id) you can't solely rely on dependency injection.

The "right" way would be not to rely on global state in the HTTP context to set up the database connection. Set up a database context that works for all your tenants instead.

Body:
I have a microservice architecture with ASP.Net Core applications and RabbitMq as the event bus between the microservices.

I also want to support multi tenancy.

So I have following dependency injection service defined in the Startup.cs to open a connection to the Database on every request based on the user's tenant id.

services.AddScoped<IDocumentSession>(ds =>
            {
                var store = ds.GetRequiredService<IDocumentStore>();
                var httpContextAccessor = ds.GetRequiredService<IHttpContextAccessor>();
                var tenant = httpContextAccessor?.HttpContext?.User?.Claims.FirstOrDefault(c => c.Type == "tid")?.Value;
                return tenant != null ? store.OpenSession(tenant) : store.OpenSession();
            });

The problem is when the service processes an event bus message (like UserUpdatedEvent).

In that case when it tries to open the Db connection, it obviously does not have the user information from the http context.

How do I send/access the tenant id of the respective user when injecting the scoped service and processing an event with RabbitMq?

Or rephrasing my question:
Is there any way to access the RabbitMQ message (and for example its headers) when the dependency injection code is executed?


问:
Camera calibration opencv python
I am following the OpenCV tutorial http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_calib3d/py_calibration/py_calibration.html

Instead of running it with a chess board, I got my 3D point coordinates from a LAS file. Here is my code:

```<code>import cv2
import numpy as np

obj_point = [(630931.35,4833642.85,157.67),(630948.03,4833662.76,73.94), (631156.3, 4833904.18, 43.89),(630873.71, 4833790, 44.85), (631381.3, 4834152.6, 79.41)]
img_point = [(1346.82,843.206),(1293.03,808.146),(1041.92, 585.168), (1150.21, 894.724), (756.993,345.904) ]

obj_point = np.array(obj_point,'float32')
img_point = np.array(img_point,'float32')

ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(obj_point, img_point, (1125, 1725),None,None)
</code>```

I got the following error message:

For non-planar calibration rigs the initial intrinsic matrix must be
  specified in function cvCalibrateCamera2

Thx in advance!

答:
Go through following code. It may resolve your problem. </p>

```<code>3dPts = 3dPts.astype('float32')
2dPts = 2dPts.astype('float32')

imgsize=(640, 480)
# This can be omitted and can be substituted with None below.
camera_matrix = cv2.initCameraMatrix2D([3dPts],[2dPts]), imgsize)

cv2.calibrateCamera([3dPts], [2dPts], imgsize, camera_matrix, None,
                    flags=cv2.CALIB_USE_INTRINSIC_GUESS)
</code>```

Title: Camera calibration opencv python

Body:
I am following the OpenCV tutorial http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_calib3d/py_calibration/py_calibration.html

Instead of running it with a chess board, I got my 3D point coordinates from a LAS file. Here is my code:

import cv2
import numpy as np

obj_point = [(630931.35,4833642.85,157.67),(630948.03,4833662.76,73.94), (631156.3, 4833904.18, 43.89),(630873.71, 4833790, 44.85), (631381.3, 4834152.6, 79.41)]
img_point = [(1346.82,843.206),(1293.03,808.146),(1041.92, 585.168), (1150.21, 894.724), (756.993,345.904) ]

obj_point = np.array(obj_point,'float32')
img_point = np.array(img_point,'float32')

ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(obj_point, img_point, (1125, 1725),None,None)

I got the following error message:

For non-planar calibration rigs the initial intrinsic matrix must be
  specified in function cvCalibrateCamera2

Thx in advance!

Body:
Go through following code. It may resolve your problem.

3dPts = 3dPts.astype('float32')
2dPts = 2dPts.astype('float32')

imgsize=(640, 480)
# This can be omitted and can be substituted with None below.
camera_matrix = cv2.initCameraMatrix2D([3dPts],[2dPts]), imgsize)

cv2.calibrateCamera([3dPts], [2dPts], imgsize, camera_matrix, None,
                    flags=cv2.CALIB_USE_INTRINSIC_GUESS)


问:
error with searching Facebook Graph API user search
i want to user Facebook graph api to search for user information
but i get an Error when i write
 GET graph.facebook.com/v3.3/search?q=java&type=user</p>

```<code>{
      "error": {
        "message": "Unsupported operation",
        "type": "OAuthException",
        "code": 100,
        "fbtrace_id": "GLFKEUeypcH"
      }
    }
</code>```

答:
https://developers.facebook.com/docs/graph-api/advanced#search lists the available search types - those are place, placetopic, and several ad_* searches for targeting purposes.

You can not search for users any more.

Body:
i want to user Facebook graph api to search for user information
but i get an Error when i write
 GET graph.facebook.com/v3.3/search?q=java&type=user

{
      "error": {
        "message": "Unsupported operation",
        "type": "OAuthException",
        "code": 100,
        "fbtrace_id": "GLFKEUeypcH"
      }
    }


问:
You can't specify target table 'A' for update in FROM clause
This is my request

```<code>> DELETE FROM A WHERE id in (    Select
> id From A    Left Join B on A.id=B.id
> Where B.id is null )
</code>```

When I execute this I have this error

You can't specify target table 'A' for
  update in FROM clause

答:
```<code>DELETE FROM A
WHERE NOT EXISTS (
    SELECT *
    FROM B
    WHERE content_id = B.content_id
)
</code>```

Body:
This is my request

> DELETE FROM A WHERE id in (    Select
> id From A    Left Join B on A.id=B.id
> Where B.id is null )

When I execute this I have this error

You can't specify target table 'A' for
  update in FROM clause


问:
Can I append an array to 'formdata' in javascript?
I'm using FormData to upload files. I also want to send an array of other data.

When I send just the image, it works fine. When I append some text to the formdata, it works fine. When I try to attach the 'tags' array below, everything else works fine but no array is sent.

Any known issues with FormData and appending arrays?

Instantiate formData:

formdata = new FormData();

The array I create. Console.log shows everything working fine.

```<code>        // Get the tags
        tags = new Array();
        $('.tag-form').each(function(i){
            article = $(this).find('input[name="article"]').val();
            gender = $(this).find('input[name="gender"]').val();
            brand = $(this).find('input[name="brand"]').val();
            this_tag = new Array();
            this_tag.article = article;
            this_tag.gender = gender;
            this_tag.brand = brand;
            tags.push(this_tag);
            console.log('This is tags array: ');
            console.log(tags);
        });
        formdata.append('tags', tags);
        console.log('This is formdata: ');
        console.log(formdata);
</code>```

How I send it:

```<code>        // Send to server
        $.ajax({
            url: "../../build/ajaxes/upload-photo.php",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function (response) {
                console.log(response);
                $.fancybox.close();
            }
        });
</code>```

答:
This works for me when I sent file + text + array:</p>

```<code>const uploadData = new FormData();
if (isArray(value)) {
  const k = `${key}[]`;
  uploadData.append(k, value);
} else {
  uploadData.append(key, value);
}

const headers = {
  'Content-Type': 'multipart/form-data',
};
</code>```

Body:
I'm using FormData to upload files. I also want to send an array of other data.

When I send just the image, it works fine. When I append some text to the formdata, it works fine. When I try to attach the 'tags' array below, everything else works fine but no array is sent.

Any known issues with FormData and appending arrays?

Instantiate formData:

formdata = new FormData();

The array I create. Console.log shows everything working fine.

        // Get the tags
        tags = new Array();
        $('.tag-form').each(function(i){
            article = $(this).find('input[name="article"]').val();
            gender = $(this).find('input[name="gender"]').val();
            brand = $(this).find('input[name="brand"]').val();
            this_tag = new Array();
            this_tag.article = article;
            this_tag.gender = gender;
            this_tag.brand = brand;
            tags.push(this_tag);
            console.log('This is tags array: ');
            console.log(tags);
        });
        formdata.append('tags', tags);
        console.log('This is formdata: ');
        console.log(formdata);

How I send it:

        // Send to server
        $.ajax({
            url: "../../build/ajaxes/upload-photo.php",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function (response) {
                console.log(response);
                $.fancybox.close();
            }
        });

Body:
This works for me when I sent file + text + array:

const uploadData = new FormData();
if (isArray(value)) {
  const k = `${key}[]`;
  uploadData.append(k, value);
} else {
  uploadData.append(key, value);
}

const headers = {
  'Content-Type': 'multipart/form-data',
};


问:
How to use SQL-View with PQGrid in combination of saving to db
PQGrid: How I can save changes from grid to DB when I have a View as data source

I have read all examples from the homepage/forum etc. Furthermore I tried to transfer from jqGrid / other Gridtools to PQGrid. No chance.

The code below shows the PopUp-Editing opportunity and when I change any value, e.g. Prio = Priority, the values in the grid are edited, but when I reload the data, I got the original value from database.

Likewise I have created a PHP-file (Vormerkungen_Grid_Speichern.php) for parameter 'editurl' by a template, but nothing happens. He don't call this special file.

<?php
    // FILENAME: Vormerkungen_Grid_Speichern.php
    // Datei dient nur zum Speichen von Veränderungen im Grid
    require ('./system_connector_mysql.php');

    $artikelnr = $_POST['ArtikelNr'];
    $aufgabe = $_POST['Aufgabe'];
    $prio = $_POST['Prio'];

    echo $_POST['ArtikelNr'];
    echo $_POST['Aufgabe'];
    echo $_POST['Prio'];

    switch ($_POST["oper"]) {
        case "add":
          // do mysql insert statement here
            break;

        case "edit":
                $query = "UPDATE tab_vormerkungen SET Aufgabe = '$aufgabe', Prio=$prio WHERE ArtikelNr=$artikelnr";
                mysql_query($query) OR ('Vormerkungen_Speichern.php - Zeile 13 |' . mysql_error());

                $datei = fopen('Vormerkungen_Speichern.txt', 'w');
                fwrite($datei, $query);
                fclose($datei);
            break;

            case "del":
          // do mysql delete statement here
            break;
    }

?>
```

```    // FILENAME: Vormerkungen.php
      function editRow() {
          var rowIndx = getRowIndx();
          if (rowIndx != null) {

              var row = $grid.pqGrid('getRowData', { rowIndx: rowIndx });
              var aufgabeAlt = row.Aufgabe;

              var $frm = $("form#crud-form");
              $frm.find("input[name='artikelnr']").val(row.ArtikelNr);
              $frm.find("input[name='aufgabe']").val(row.Aufgabe);
              $frm.find("input[name='prio']").val(row.Prio);
              $frm.find("input[name='VFG']").val(row.VFG);

              $("#popup-dialog-crud").dialog({ title: "Vormerkung " + row.ArtikelNr + " bearbeiten", buttons: {
                  Update: function () {
                      //update row.
                      row = [];
                      row.ArtikelNr = $frm.find("input[name='artikelnr']").val();
                      row.Aufgabe = $frm.find("input[name='aufgabe']").val();
                      row.Prio = $frm.find("input[name='prio']").val();

                      // Umsetzung im Grid
                      $grid.pqGrid('updateRow', { rowIndx: rowIndx, row: row, checkEditable: false });

                      $(this).dialog("close");
                  },
                  Cancel: function () {
                      $(this).dialog("close");
                  }
              }
              }).dialog("open");
          }
      }

```

答:
Thank you @Tony Tmov (Sarcasm). PQGrid has a better license for me, that is the reason why I have choose PQGrid.

I think my biggest problem is the data source. If I didn't have a view as a data source, I wouldn't have a problem with storing it in the database.

But I also have no other choice with the data source.

Body:
PQGrid: How I can save changes from grid to DB when I have a View as data source

I have read all examples from the homepage/forum etc. Furthermore I tried to transfer from jqGrid / other Gridtools to PQGrid. No chance.

The code below shows the PopUp-Editing opportunity and when I change any value, e.g. Prio = Priority, the values in the grid are edited, but when I reload the data, I got the original value from database.

Likewise I have created a PHP-file (Vormerkungen_Grid_Speichern.php) for parameter 'editurl' by a template, but nothing happens. He don't call this special file.

<?php
    // FILENAME: Vormerkungen_Grid_Speichern.php
    // Datei dient nur zum Speichen von Veränderungen im Grid
    require ('./system_connector_mysql.php');

    $artikelnr = $_POST['ArtikelNr'];
    $aufgabe = $_POST['Aufgabe'];
    $prio = $_POST['Prio'];

    echo $_POST['ArtikelNr'];
    echo $_POST['Aufgabe'];
    echo $_POST['Prio'];

    switch ($_POST["oper"]) {
        case "add":
          // do mysql insert statement here
            break;

        case "edit":
                $query = "UPDATE tab_vormerkungen SET Aufgabe = '$aufgabe', Prio=$prio WHERE ArtikelNr=$artikelnr";
                mysql_query($query) OR ('Vormerkungen_Speichern.php - Zeile 13 |' . mysql_error());

                $datei = fopen('Vormerkungen_Speichern.txt', 'w');
                fwrite($datei, $query);
                fclose($datei);
            break;

            case "del":
          // do mysql delete statement here
            break;
    }

?>

    // FILENAME: Vormerkungen.php
      function editRow() {
          var rowIndx = getRowIndx();
          if (rowIndx != null) {

              var row = $grid.pqGrid('getRowData', { rowIndx: rowIndx });
              var aufgabeAlt = row.Aufgabe;

              var $frm = $("form#crud-form");
              $frm.find("input[name='artikelnr']").val(row.ArtikelNr);
              $frm.find("input[name='aufgabe']").val(row.Aufgabe);
              $frm.find("input[name='prio']").val(row.Prio);
              $frm.find("input[name='VFG']").val(row.VFG);

              $("#popup-dialog-crud").dialog({ title: "Vormerkung " + row.ArtikelNr + " bearbeiten", buttons: {
                  Update: function () {
                      //update row.
                      row = [];
                      row.ArtikelNr = $frm.find("input[name='artikelnr']").val();
                      row.Aufgabe = $frm.find("input[name='aufgabe']").val();
                      row.Prio = $frm.find("input[name='prio']").val();

                      // Umsetzung im Grid
                      $grid.pqGrid('updateRow', { rowIndx: rowIndx, row: row, checkEditable: false });

                      $(this).dialog("close");
                  },
                  Cancel: function () {
                      $(this).dialog("close");
                  }
              }
              }).dialog("open");
          }
      }