问:
Xamarin IOS file picker : unable to get selected file from icloud drive
I've installed filepicker control from Nuget and added tried adding reference from MonoTouch10 folder and later from github to my xamarin.ios project.

```<code>FileData file = await CrossFilePicker.Current.PickFile();

if (file != null) { }
</code>```

this is the code i added to my browse button, after selecting a file from iCloud drive, control never comes to "if condition".

and again when i click on browse button for second time, app crashes saying "only one operation can be active at a time".

答:
To answer my own question, i customized in plugin, like

Used DocumentPicker_DidPickDocumentAtUrls event instead of DocumentPicker_DidPickDocument.

while returning selected file used

```<code> new FileData(e.FilePath, e.FileName, () =>
        {
            var url = new Foundation.NSUrl(e.FilePath);
            return new FileStream(url.Path, FileMode.Open, FileAccess.Read);
        })
</code>```

This solved my issue. Thanks.

Body:
I've installed filepicker control from Nuget and added tried adding reference from MonoTouch10 folder and later from github to my xamarin.ios project.

FileData file = await CrossFilePicker.Current.PickFile();

if (file != null) { }

this is the code i added to my browse button, after selecting a file from iCloud drive, control never comes to "if condition".

and again when i click on browse button for second time, app crashes saying "only one operation can be active at a time".

Body:
To answer my own question, i customized in plugin, like

Used DocumentPicker_DidPickDocumentAtUrls event instead of DocumentPicker_DidPickDocument.

while returning selected file used

 new FileData(e.FilePath, e.FileName, () =>
        {
            var url = new Foundation.NSUrl(e.FilePath);
            return new FileStream(url.Path, FileMode.Open, FileAccess.Read);
        })

This solved my issue. Thanks.


来源: stackexchange

问:
How to schedule jenkins job to run with seconds unit?
Jenkins job trigger cron expression format is ? ? ? ? ?.
It cannot possible set the seconds unit.

But I want schedule seconds unit, like run at everyday 15:20:10.
Because there is a job with cron(0 12 * * *) and every minute job, and these two job must not to run simultaneously.

How can I do that?

Thanks for help.

答:
you can have several options to do that :

use lock plugin to wait until your first job run will finish and only than trigger it.

use the Quiet period option in the Job configuration , add 10 seconds so the job will sleep 10 seconds after it trigger.

ContentLicense: CC BY-SA 3.0


问:
When we try to separate style files app doesn't render it shows spinner with background all time
image of CMD
Before doing it styles were on the same files. We cut all styles and pasted it on the separate file. Here is how it looks like.

```<code>import React, {Component} from "react";
import {Dimensions} from "react-native";
const win = Dimensions.get('window');

const styles={
  content: {

  justifyContent:'center'
},

  img: {
    flex: 1,
    alignSelf: "stretch",
    width: win.width,
         height: win.height,

  },

  item:{
borderBottomColor: "#0dc49c"
  },

  icon:{
color: "#a4916c",
 marginLeft: 10,
  marginRight: 5
  },

  input:{
    color: "#a4916c"
  },

  list:{
     borderBottomWidth: 0,
     borderTopWidth: 0,
     borderBottomColor: "#a4916c",
  },

  contacticon: {
    justifyContent: "center",
    alignSelf: "center",
    fontSize: 60,
    fontWeight: "bold",
    color: "#0dc49c",
    marginBottom: 2,
  },
  contacttext: {
    justifyContent: "center",
    alignSelf: "center",
    fontSize: 25,
    color: "#0dc49c",
    marginBottom: 180,
  },

}

module.exports = styles;
</code>```

When it was on the same files as components it was worked perfectly while because of duplicate styles we decided to separate them. What is wrong? How can it be fixed?

答:
try using styles like this

```<code>import { StyleSheet } from "react-native";

 const styles = StyleSheet.create({
 content: {
   justifyContent:'center'
 },
});

module.exports = styles;
</code>```

and import styles like this

```<code>import styles from "../styles/file
</code>```

Body:
image of CMD
Before doing it styles were on the same files. We cut all styles and pasted it on the separate file. Here is how it looks like.

import React, {Component} from "react";
import {Dimensions} from "react-native";
const win = Dimensions.get('window');

const styles={
  content: {

  justifyContent:'center'
},

  img: {
    flex: 1,
    alignSelf: "stretch",
    width: win.width,
         height: win.height,

  },

  item:{
borderBottomColor: "#0dc49c"
  },

  icon:{
color: "#a4916c",
 marginLeft: 10,
  marginRight: 5
  },

  input:{
    color: "#a4916c"
  },

  list:{
     borderBottomWidth: 0,
     borderTopWidth: 0,
     borderBottomColor: "#a4916c",
  },

  contacticon: {
    justifyContent: "center",
    alignSelf: "center",
    fontSize: 60,
    fontWeight: "bold",
    color: "#0dc49c",
    marginBottom: 2,
  },
  contacttext: {
    justifyContent: "center",
    alignSelf: "center",
    fontSize: 25,
    color: "#0dc49c",
    marginBottom: 180,
  },

}

module.exports = styles;

When it was on the same files as components it was worked perfectly while because of duplicate styles we decided to separate them. What is wrong? How can it be fixed?

Body:
try using styles like this

import { StyleSheet } from "react-native";

 const styles = StyleSheet.create({
 content: {
   justifyContent:'center'
 },
});

module.exports = styles;

and import styles like this

import styles from "../styles/file


问:
how to fix a bottom relative layout when soft keyboard comes?
When i write something on the edit text in my app ,the soft keyboard comes in along with a bottom relative layout..I want to fix the bottom relative layout position fixed.Any help will be greatly appreciated..</p>

答:
In Relative layout paste the following code</p>

```<code>  <LinearLayout
        android:id="@+id/ll_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_marginTop="@dimen/_16dp">

        <Button
            android:id="@+id/btn_continue"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:text="@string/conti"
            android:padding="@dimen/_8dp"
            android:textColor="@color/white"
            android:textSize="@dimen/_16sp" />
    </LinearLayout>
</code>```

Body:
In Relative layout paste the following code

  <LinearLayout
        android:id="@+id/ll_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_marginTop="@dimen/_16dp">

        <Button
            android:id="@+id/btn_continue"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:text="@string/conti"
            android:padding="@dimen/_8dp"
            android:textColor="@color/white"
            android:textSize="@dimen/_16sp" />
    </LinearLayout>


问:
Creating a single thread for multiple objects
I have a thread which I am creating whenever an object is created of the class , the thread I am creating in the constructor itself. So, depending on how many objects are created , the number of threads will be equal to number of objects created. But I want to create only a single thread , no matter how many objects are created..

Any help would be appreciated.

I can't put the code here as it is too big.
A simple suggestion will be helpful for me.

答: You can use singleton design pattern to restrict an object to have one (or specific number of) instance(s). Moreover, look at this for a thread safe implementation if you create object from multiple threads.</p>


问:
Tile not getting center in Collapsed toolbar
I tried setting collapsingToolbarLayout.setCollapsedTitleGravity(Gravity.CENTER);

```<code>collapsingToolbarLayout.setExpandedTitleGravity(Gravity.CENTER);
</code>```

and almost all available links on INTERNET but i am not able to put the title in center of toolbar.

plz help !

答:
make your Toolbar like this

```<code>       <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:contentInsetEnd="0dp"
            app:contentInsetLeft="0dp"
            app:contentInsetRight="0dp"
            app:contentInsetStart="0dp"
            app:contentInsetStartWithNavigation="0dp"
            app:layout_collapseMode="pin"
            app:popupTheme="@style/AppTheme.PopupOverlay">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:orientation="vertical"
                android:text="Center">

                <TextView
                    android:layout_marginLeft="-25dp"
                    android:id="@+id/toolbar_title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center" />
            </LinearLayout>

        </android.support.v7.widget.Toolbar>
</code>```

in your activity file change like this

```<code>toolbar=(Toolbar)findViewById(R.id.tool_bar);
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
mTitle.setText("PREM");
setSupportActionBar(toolbar);
</code>```

Body:
I tried setting collapsingToolbarLayout.setCollapsedTitleGravity(Gravity.CENTER);

collapsingToolbarLayout.setExpandedTitleGravity(Gravity.CENTER);

and almost all available links on INTERNET but i am not able to put the title in center of toolbar.

plz help !

Body:
make your Toolbar like this

       <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:contentInsetEnd="0dp"
            app:contentInsetLeft="0dp"
            app:contentInsetRight="0dp"
            app:contentInsetStart="0dp"
            app:contentInsetStartWithNavigation="0dp"
            app:layout_collapseMode="pin"
            app:popupTheme="@style/AppTheme.PopupOverlay">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:orientation="vertical"
                android:text="Center">

                <TextView
                    android:layout_marginLeft="-25dp"
                    android:id="@+id/toolbar_title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center" />
            </LinearLayout>

        </android.support.v7.widget.Toolbar>

in your activity file change like this

toolbar=(Toolbar)findViewById(R.id.tool_bar);
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
mTitle.setText("PREM");
setSupportActionBar(toolbar);


问:
Why PriorityQueue requires API 24 in Android
PriorityQueue was added in Java 1.5

new PriorityQueue()is enabled in Android, but

```<code>  new PriorityQueue(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            return 0;
        }
    });
</code>```

requires API 24. Why?

答:
Because PriorityQueue(Comparator) constructor was added to the SDK in API level 24. In JDK, that constructor was added in Java 8.

For compatibility with earlier API levels, you can use PriorityQueue(int,Comparator) that has been there since API level 1.

Body:
PriorityQueue was added in Java 1.5

new PriorityQueue()is enabled in Android, but

  new PriorityQueue(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            return 0;
        }
    });

requires API 24. Why?


问:
Django class based DeleteView check constraints
In a django application, there are two model with 1-M relationship, e.g. Parent and Child. I need to delete the Parent model object using DeleteView class. Before deleting the object, I need to check if it has any child objects and if there was, it returns an error message instead of deleting the object.
Currently my DeleteView, like the default is:

```<code>class ParentDeleteView(DeleteView):
    model = Parent
    def get_success_url(self):
        return reverse_lazy('parent-list')
</code>```

Which methods should I implement to check constraints?

答:
In that case you need to override the delete method.

```<code>from django.http import HttpResponseRedirect

class ParentDeleteView(DeleteView):
    model = Parent

    def delete(self, request, *args, **kwargs):
        self.object = self.get_object()
        # check if object has child if yes return error
        # otherwise
        success_url = self.get_success_url()
        self.object.delete()
        return HttpResponseRedirect(success_url)

    def get_success_url(self):
        return reverse_lazy('parent-list')
</code>```

Body:
In a django application, there are two model with 1-M relationship, e.g. Parent and Child. I need to delete the Parent model object using DeleteView class. Before deleting the object, I need to check if it has any child objects and if there was, it returns an error message instead of deleting the object.
Currently my DeleteView, like the default is:

class ParentDeleteView(DeleteView):
    model = Parent
    def get_success_url(self):
        return reverse_lazy('parent-list')

Which methods should I implement to check constraints?

Body:
In that case you need to override the delete method.

from django.http import HttpResponseRedirect

class ParentDeleteView(DeleteView):
    model = Parent

    def delete(self, request, *args, **kwargs):
        self.object = self.get_object()
        # check if object has child if yes return error
        # otherwise
        success_url = self.get_success_url()
        self.object.delete()
        return HttpResponseRedirect(success_url)

    def get_success_url(self):
        return reverse_lazy('parent-list')


问:
How to get a number at the end of a string followed by this character `:` using regex
I need to get a number (integer) at the end of a string followed by this character :.

Basically:

qwe-tyu-iop[-zxc:10  //result  should be 10

::qwe-ty:u-iop[-zxc:10  //result  should be 10

::qwe-ty:u-iop[-zxc:10.10  //result  should be undefined

::qwe-ty:u-iop[-zxc:abc  //result  should be undefined

::qwe-ty:u-iop[-zxc:afdf10  //result  should be undefined

Body: "qwe-tyu-iop[-zxc:10".match(/:?\d+$/);  // [":10"]


答:
That is because PriorityQueue in Java 1.5 does not have  PriorityQueue (Comparator<? super E> comparator) constructor at all. It was implemented only in Android SDK, and only in API 24.

You can use Java's PriorityQueue (int initialCapacity, Comparator<? super E> comparator) constructor from Android API 1

Title: Why PriorityQueue requires API 24 in Android


问:
How to Trim the first two characters of a column in csv using groovy
```<code><taskdef  name="groovy" classname="org.codehaus.groovy.ant.Groovy"/>
     <groovy>
    newFile("C://RxBen//exports//Control_Exception__c_Exportupdated.csv").withWriter {
    new File("C://RxBen//exports//Control_Exception__c_Export.csv").splitEachLine(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*\$)") { ID, Don_t_Work__c,Forwarding_fax_number__c, No_Go__c  ->
     it.println "${ID},${Forwarding_fax_number__c}AAA,${s}"
     }
    }
    </groovy>
</code>```

答:
You can use a substring on the String in the column with the argument of 2, this will take all the characters from third character to the end of the string in the target String.

Example:

```<code>def s = "AATestString"
def newString = s.substring(2)
assert newString == "TestString"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can use a substring on the String in the column with the argument of 2, this will take all the characters from third character to the end of the string in the target String.

Example:

def s = "AATestString"
def newString = s.substring(2)
assert newString == "TestString"


问:
The 'XamarinShellPackage' package did not load correctly
I have encountered the following error:

The 'XamarinShellPackage' package did not load correctly.

It happens when i start Visual Studio 2015 Community Update 3 Or Visual studio 15 Preview 4.
I even reinstalled windows 10 and it doesn't help.

As asked, pasting VS info:

```<code>Microsoft Visual Studio Enterprise 15 Preview 4
Version 15.0.25618.0 PREVIEW
Microsoft .NET Framework
Version 4.6.01586

Installed Version: Enterprise
Visual Basic 15 Preview 4   00369-50000-00000-AA551
Visual C# 15 Preview 4   00369-50000-00000-AA551
ASP.NET and Web Tools 2016   15.0.20802.0
Common Azure Tools   1.8
JavaScript Language Service   2.0
JavaScript Project System   2.0
JavaScript UWP Project System   2.0
NuGet Package Manager   3.5.0
Parallel Debugger   1.0
SQL Server Data Tools   15.1.60805.0
TypeScript   2.0.1.0
Visual Studio Tools for Apache Cordova   Update 10
Visual Studio Tools for Universal Windows Apps   15.0.25618.00
Xamarin   4.1.1.8 (60e5c00)
Xamarin.Android   6.1.1.1 (7db2aac)
Xamarin.iOS   9.8.1.4 (3cf8aae)
</code>```

答: Another quick thing people can try that worked for me was deleting the .vs folder from the root of the solution folder. Make sure VS is closed when you do it.

Body:
I have encountered the following error:

The 'XamarinShellPackage' package did not load correctly.

It happens when i start Visual Studio 2015 Community Update 3 Or Visual studio 15 Preview 4.
I even reinstalled windows 10 and it doesn't help.

As asked, pasting VS info:

Microsoft Visual Studio Enterprise 15 Preview 4
Version 15.0.25618.0 PREVIEW
Microsoft .NET Framework
Version 4.6.01586

Installed Version: Enterprise
Visual Basic 15 Preview 4   00369-50000-00000-AA551
Visual C# 15 Preview 4   00369-50000-00000-AA551
ASP.NET and Web Tools 2016   15.0.20802.0
Common Azure Tools   1.8
JavaScript Language Service   2.0
JavaScript Project System   2.0
JavaScript UWP Project System   2.0
NuGet Package Manager   3.5.0
Parallel Debugger   1.0
SQL Server Data Tools   15.1.60805.0
TypeScript   2.0.1.0
Visual Studio Tools for Apache Cordova   Update 10
Visual Studio Tools for Universal Windows Apps   15.0.25618.00
Xamarin   4.1.1.8 (60e5c00)
Xamarin.Android   6.1.1.1 (7db2aac)
Xamarin.iOS   9.8.1.4 (3cf8aae)


问:
Java: static abstract (again) - best practice how to work around
I theoretically understand the point why there is no abstract static in Java, as explained for instance in Why can't static methods be abstract in Java .

But how do I solve such a problem then?

My application uses files of a few types, which I want to assign static properties like a description of that file type (like "data file", the other being "config file", etc.).
Obviously, I would put that into a static String so that the description is accessible without instancing a file (useful for the GUI f.i.).
On the other hand, obviously all file types should have some common methods like getStatus(), which obviously I want to inherit from a common superclass MyFileType.

getDescription() would of course be abstract in the superclass.

Tried using a combination of a superclass and an interface, but similar problem: A static implementation of an abstract method is not allowed.

How would a Java guru solve this?
Is it really such a bad implementation that I want to create?

Many thanks,
Philipp

答:
I don't know how a java guru would solve it, but I'd probably create a resource bundle with all the descriptions in a properties file like this:

```<code>com.bigcompany.smallapp.files.DataFile=Data file
com.bigcompany.smallapp.files.ConfigFile=Config file
</code>```

Handling the bundle can conveniently be placed in the superclass or elsewhere.

Another option is to use reflection to access the static fields in each subclass, but then you need to make sure that all the subclasses have a static field with the same name.

There could be other options too, even refactoring the code so that the subtypes aren't represented by a separate class each, but in general there's no watertight solution.

Body:
I don't know how a java guru would solve it, but I'd probably create a resource bundle with all the descriptions in a properties file like this:

com.bigcompany.smallapp.files.DataFile=Data file
com.bigcompany.smallapp.files.ConfigFile=Config file

Handling the bundle can conveniently be placed in the superclass or elsewhere.

Another option is to use reflection to access the static fields in each subclass, but then you need to make sure that all the subclasses have a static field with the same name.

There could be other options too, even refactoring the code so that the subtypes aren't represented by a separate class each, but in general there's no watertight solution.

ContentLicense: CC BY-SA 2.5


问:
The KafkaConsumer does not read from the offset 0
I want to test a Kafka example. I am using Kafka 0.10.0.1
The producer:

```<code>object ProducerApp extends App {

val topic = "topicTest"
val  props = new Properties()
props.put("bootstrap.servers", "localhost:9092")
props.put(ConsumerConfig.GROUP_ID_CONFIG, "consumer")
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")
val producer = new KafkaProducer[String, String](props)
for(i <- 0 to 20)
{
val record = new ProducerRecord(topic, "key "+i," value "+i)
producer.send(record)
Thread.sleep(100)
}
}
</code>```

The consumer (the topic "topicTest" is created with 1 partition):

```<code>object ConsumerApp extends App {
val topic = "topicTest"
val properties = new Properties
properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092")
properties.put(ConsumerConfig.GROUP_ID_CONFIG, "consumer")
properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest")
properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
properties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
val consumer = new KafkaConsumer[String, String](properties)
consumer.subscribe(scala.List(topic).asJava)
while (true) {
consumer.seekToBeginning(consumer.assignment())
val records:ConsumerRecords[String,String] = consumer.poll(20000)
println("records size "+records.count())
records.asScala.foreach(rec => println("offset "+rec.offset()))
}
}
</code>```

the problem is that the consumer does not read from the offset 0 at the first iteration but at the other oiterations it does. I want to know the reason and how can I make the consumer reads from the offset 0 at all the iterations.
The expected result is:

```<code>records size 6
offset 0
offset 1
offset 2
offset 3
offset 4
offset 5
records size 6
offset 0
offset 1
offset 2
offset 3
offset 4
offset 5
...
</code>```

but the obtained result is:

```<code>records size 4
offset 2
offset 3
offset 4
offset 5
records size 6
offset 0
offset 1
offset 2
offset 3
offset 4
offset 5
...
</code>```

答:
I am unable to figure out what is exact mistake, I have written same code as yours. but for me it is working fine. if you want you can use below snippet.

```<code>import java.util
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.KafkaConsumer
import org.apache.kafka.common.TopicPartition
import org.apache.kafka.common.serialization.LongDeserializer;
import scala.collection.JavaConverters._
import java.util.Properties

object ConsumerExample extends App {

  val TOPIC = "test-stack"

  val props = new Properties()

  props.put("bootstrap.servers", "localhost:9092")

  props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
  props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
  props.put("group.id", "testinf")
  props.put("auto.offset.reset", "earliest")
  props.put("auto.offset.reset.config", "false")

  var listener = new ConsumerRebalanceListener() {
    override def onPartitionsAssigned(partitions: util.Collection[TopicPartition]): Unit = {
      println("Assignment : " + partitions)

    }
    override def onPartitionsRevoked(partitions: util.Collection[TopicPartition]): Unit = {
      // do nothing
    }

  }

  val consumer = new KafkaConsumer[String, String](props)

  consumer.subscribe(util.Collections.singletonList(TOPIC), listener)

  while (true) {

    consumer.seekToBeginning(consumer.assignment())
    val records = consumer.poll(20000)
    // for (record <- records.asScala) {
    //   println(record)
    // }
    println("records size "+records.count())
    records.asScala.foreach(rec => println("offset "+rec.offset()))
  }

}
</code>```

Try it out and let me know. if you have any issues.

Body:
I want to test a Kafka example. I am using Kafka 0.10.0.1
The producer:

object ProducerApp extends App {

val topic = "topicTest"
val  props = new Properties()
props.put("bootstrap.servers", "localhost:9092")
props.put(ConsumerConfig.GROUP_ID_CONFIG, "consumer")
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")
val producer = new KafkaProducer[String, String](props)
for(i <- 0 to 20)
{
val record = new ProducerRecord(topic, "key "+i," value "+i)
producer.send(record)
Thread.sleep(100)
}
}

The consumer (the topic "topicTest" is created with 1 partition):

object ConsumerApp extends App {
val topic = "topicTest"
val properties = new Properties
properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092")
properties.put(ConsumerConfig.GROUP_ID_CONFIG, "consumer")
properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false")
properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest")
properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
properties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
val consumer = new KafkaConsumer[String, String](properties)
consumer.subscribe(scala.List(topic).asJava)
while (true) {
consumer.seekToBeginning(consumer.assignment())
val records:ConsumerRecords[String,String] = consumer.poll(20000)
println("records size "+records.count())
records.asScala.foreach(rec => println("offset "+rec.offset()))
}
}

the problem is that the consumer does not read from the offset 0 at the first iteration but at the other oiterations it does. I want to know the reason and how can I make the consumer reads from the offset 0 at all the iterations.
The expected result is:

records size 6
offset 0
offset 1
offset 2
offset 3
offset 4
offset 5
records size 6
offset 0
offset 1
offset 2
offset 3
offset 4
offset 5
...

but the obtained result is:

records size 4
offset 2
offset 3
offset 4
offset 5
records size 6
offset 0
offset 1
offset 2
offset 3
offset 4
offset 5
...

Body:
I am unable to figure out what is exact mistake, I have written same code as yours. but for me it is working fine. if you want you can use below snippet.

import java.util
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.KafkaConsumer
import org.apache.kafka.common.TopicPartition
import org.apache.kafka.common.serialization.LongDeserializer;
import scala.collection.JavaConverters._
import java.util.Properties

object ConsumerExample extends App {

  val TOPIC = "test-stack"

  val props = new Properties()

  props.put("bootstrap.servers", "localhost:9092")

  props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
  props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
  props.put("group.id", "testinf")
  props.put("auto.offset.reset", "earliest")
  props.put("auto.offset.reset.config", "false")

  var listener = new ConsumerRebalanceListener() {
    override def onPartitionsAssigned(partitions: util.Collection[TopicPartition]): Unit = {
      println("Assignment : " + partitions)

    }
    override def onPartitionsRevoked(partitions: util.Collection[TopicPartition]): Unit = {
      // do nothing
    }

  }

  val consumer = new KafkaConsumer[String, String](props)

  consumer.subscribe(util.Collections.singletonList(TOPIC), listener)

  while (true) {

    consumer.seekToBeginning(consumer.assignment())
    val records = consumer.poll(20000)
    // for (record <- records.asScala) {
    //   println(record)
    // }
    println("records size "+records.count())
    records.asScala.foreach(rec => println("offset "+rec.offset()))
  }

}

Try it out and let me know. if you have any issues.


问:
How to redirect to another component without using a button
I'm using a library to render a Gantt Chart. This Chart provides an js event to handle a button click. I need to route or render another react component in that event. So... how can i render o route to my component in that event? I'm using react router and meteor.</p>

```<code>render() {
gantt.config.buttons_left=["dhx_save_btn","dhx_cancel_btn","dhx_delete_btn"];
gantt.config.buttons_right = ["go_task_btn"];
gantt.locale.labels["go_task_btn"] = 'VER';
gantt.attachEvent("onLightboxButton", function(button_id, node, e){
      if(button_id == "go_task_btn"){
          var idTask = gantt.getState().lightbox;

         //HERE I WAN TO REDIRECT OR RENDER ANOTHER
         // REACT COMPONENTE

      }
  });

return (
  <div>
    <Toolbar
        zoom={this.state.currentZoom}
        onZoomChange={this.handleZoomChange}
    />
    <div className="gantt-container">
      <Gantt
        tasks={data}
        zoom={this.state.currentZoom}
        onTaskUpdated={this.logTaskUpdate}
        onLinkUpdated={this.logLinkUpdate}
      />
    </div>
     {/*<MessageArea messages={this.state.messages}/> */}
  </div>
);  }}export default App;
</code>```

答: You can do this by making a function outside render, put all your code their and call this function in the return.</p>

Body:
I'm using a library to render a Gantt Chart. This Chart provides an js event to handle a button click. I need to route or render another react component in that event. So... how can i render o route to my component in that event? I'm using react router and meteor.

render() {
gantt.config.buttons_left=["dhx_save_btn","dhx_cancel_btn","dhx_delete_btn"];
gantt.config.buttons_right = ["go_task_btn"];
gantt.locale.labels["go_task_btn"] = 'VER';
gantt.attachEvent("onLightboxButton", function(button_id, node, e){
      if(button_id == "go_task_btn"){
          var idTask = gantt.getState().lightbox;

         //HERE I WAN TO REDIRECT OR RENDER ANOTHER
         // REACT COMPONENTE

      }
  });

return (

    <Toolbar
        zoom={this.state.currentZoom}
        onZoomChange={this.handleZoomChange}
    />

      <Gantt
        tasks={data}
        zoom={this.state.currentZoom}
        onTaskUpdated={this.logTaskUpdate}
        onLinkUpdated={this.logLinkUpdate}
      />

     {/*<MessageArea messages={this.state.messages}/> */}

);  }}export default App;


问:
Serialize a FaultException of Generic Type
We currently have a mechanism of calling our web services in a test page.  However, I am trying to look at the better practices of WCF services and using the FaultException.

So there are cases when the FaultException is thrown by our service, I want to serialize the fault as xml and display on the page.

I've looked at the XmlSerializer and DataContractSerializer so far.

So consider the code:

```<code>public SomeResponse DoSomething()
{
    throw new FaultException<AuthenticationFault>(
                new AuthenticationFault(),
                new FaultReason("BooHoo"),
                new FaultCode("1234"));
}
</code>```

And the futile attempts at serializing:

DataContractSerializer

```<code>public static string Serialize(object obj)
{
    using (MemoryStream memoryStream = new MemoryStream())
    using (StreamReader reader = new StreamReader(memoryStream))
    {
        DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
        serializer.WriteObject(memoryStream, obj);
        memoryStream.Position = 0;
        return reader.ReadToEnd();
    }
}
</code>```

XmlSerializer

```<code>public string Serialize<TObject>(TObject obj)
{
    if (obj == null)
    {
        return string.Empty;
    }

    XmlSerializer serializer = new XmlSerializer(obj.GetType());
    XmlWriterSettings settings = new XmlWriterSettings()
    {
        Encoding = new UnicodeEncoding(false, false), string
        Indent = true,
        OmitXmlDeclaration = true
    };

    using (StringWriter textWriter = new StringWriter())
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
        {
            serializer.Serialize(xmlWriter, obj);
        }
        return textWriter.ToString();
    }
}
</code>```

Test Call and Catch

```<code>public override string Invoke(string request)
{
    try
    {
        var service = new AcmeService();
        return Serialize(service.DoSomething());
    }
    catch (FaultException ex)
    {
        return Serialize(ex);
    }
}
</code>```

AuthenticationFault

```<code>[DataContract]
public class AuthenticationFault
{
}
</code>```

Exceptions

The following exceptions are raised in the scenarios above.  However, I do appreciate there is no parameterless constructor for the generic FaultException.  The runtime must be able to serialize back over the wire.

DataContractSerializer

```<code>System.Runtime.Serialization.SerializationException occurred
  HResult=0x8013150C
  Message=Type 'BuyerAcmeApp.Services.Faults.AuthenticationFault' with data contract name 'AuthenticationFault:http://schemas.acme.com/p4/services/2017/11' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>
</code>```

XmlSerializer

```<code>System.InvalidOperationException occurred
  HResult=0x80131509
  Message=There was an error reflecting type 'System.ServiceModel.FaultException'.
  Source=App_Code.etbsvkgf
  StackTrace:
   at AcmeApp.WebServices.Tests.WebServiceMethodItem`2.Serialize[TObject](TObject obj) in T:\acmejpa\AcmeAppTemplate\dev\solution\AcmeApp.Template\src\AcmeApp\App_Code\WebServices\Tests\WebServiceMethodItemBase.cs:line 70
   at AcmeApp.WebServices.Tests.WebServiceMethodItemWithError`2.Invoke(String request) in T:\acmejpa\AcmeAppTemplate\dev\solution\AcmeApp.Template\src\AcmeApp\App_Code\WebServices\Tests\WebServiceMethodItemBase.cs:line 104
   at AcmeApp.Diagnostics.WebServiceTestPage.CallMethodButton_OnClick(Object sender, EventArgs e) in T:\acmejpa\AcmeAppTemplate\dev\solution\AcmeApp.Template\src\AcmeApp\Diagnostics\WebServiceTestPage.aspx.cs:line 44

Inner Exception 1:
NotSupportedException: Cannot serialize member System.Exception.Data of type System.Collections.IDictionary, because it implements IDictionary.
</code>```

答:
When serialising, the known types need to be supplied to the DataContractSerializer.

```<code>public static string Serialize(object obj)
{
    var settings = new XmlWriterSettings { Indent = true };

    using (MemoryStream memoryStream = new MemoryStream())
    using (StreamReader reader = new StreamReader(memoryStream))
    {
        DataContractSerializer serializer = new DataContractSerializer(
        obj.GetType(), new Type[]
        {
            typeof(AuthenticationFault)
        });

        serializer.WriteObject(memoryStream , obj);
        memoryStream.Position = 0;
        return reader.ReadToEnd();
    }
}
</code>```

Body:
We currently have a mechanism of calling our web services in a test page.  However, I am trying to look at the better practices of WCF services and using the FaultException.

So there are cases when the FaultException is thrown by our service, I want to serialize the fault as xml and display on the page.

I've looked at the XmlSerializer and DataContractSerializer so far.

So consider the code:

public SomeResponse DoSomething()
{
    throw new FaultException<AuthenticationFault>(
                new AuthenticationFault(),
                new FaultReason("BooHoo"),
                new FaultCode("1234"));
}

And the futile attempts at serializing:

DataContractSerializer

public static string Serialize(object obj)
{
    using (MemoryStream memoryStream = new MemoryStream())
    using (StreamReader reader = new StreamReader(memoryStream))
    {
        DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
        serializer.WriteObject(memoryStream, obj);
        memoryStream.Position = 0;
        return reader.ReadToEnd();
    }
}

XmlSerializer

public string Serialize<TObject>(TObject obj)
{
    if (obj == null)
    {
        return string.Empty;
    }

    XmlSerializer serializer = new XmlSerializer(obj.GetType());
    XmlWriterSettings settings = new XmlWriterSettings()
    {
        Encoding = new UnicodeEncoding(false, false), string
        Indent = true,
        OmitXmlDeclaration = true
    };

    using (StringWriter textWriter = new StringWriter())
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
        {
            serializer.Serialize(xmlWriter, obj);
        }
        return textWriter.ToString();
    }
}

Test Call and Catch

public override string Invoke(string request)
{
    try
    {
        var service = new AcmeService();
        return Serialize(service.DoSomething());
    }
    catch (FaultException ex)
    {
        return Serialize(ex);
    }
}

AuthenticationFault

[DataContract]
public class AuthenticationFault
{
}

Exceptions

The following exceptions are raised in the scenarios above.  However, I do appreciate there is no parameterless constructor for the generic FaultException.  The runtime must be able to serialize back over the wire.

DataContractSerializer

System.Runtime.Serialization.SerializationException occurred
  HResult=0x8013150C
  Message=Type 'BuyerAcmeApp.Services.Faults.AuthenticationFault' with data contract name 'AuthenticationFault:http://schemas.acme.com/p4/services/2017/11' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>

XmlSerializer

System.InvalidOperationException occurred
  HResult=0x80131509
  Message=There was an error reflecting type 'System.ServiceModel.FaultException'.
  Source=App_Code.etbsvkgf
  StackTrace:
   at AcmeApp.WebServices.Tests.WebServiceMethodItem`2.Serialize[TObject](TObject obj) in T:\acmejpa\AcmeAppTemplate\dev\solution\AcmeApp.Template\src\AcmeApp\App_Code\WebServices\Tests\WebServiceMethodItemBase.cs:line 70
   at AcmeApp.WebServices.Tests.WebServiceMethodItemWithError`2.Invoke(String request) in T:\acmejpa\AcmeAppTemplate\dev\solution\AcmeApp.Template\src\AcmeApp\App_Code\WebServices\Tests\WebServiceMethodItemBase.cs:line 104
   at AcmeApp.Diagnostics.WebServiceTestPage.CallMethodButton_OnClick(Object sender, EventArgs e) in T:\acmejpa\AcmeAppTemplate\dev\solution\AcmeApp.Template\src\AcmeApp\Diagnostics\WebServiceTestPage.aspx.cs:line 44

Inner Exception 1:
NotSupportedException: Cannot serialize member System.Exception.Data of type System.Collections.IDictionary, because it implements IDictionary.

Body:
When serialising, the known types need to be supplied to the DataContractSerializer.

public static string Serialize(object obj)
{
    var settings = new XmlWriterSettings { Indent = true };

    using (MemoryStream memoryStream = new MemoryStream())
    using (StreamReader reader = new StreamReader(memoryStream))
    {
        DataContractSerializer serializer = new DataContractSerializer(
        obj.GetType(), new Type[]
        {
            typeof(AuthenticationFault)
        });

        serializer.WriteObject(memoryStream , obj);
        memoryStream.Position = 0;
        return reader.ReadToEnd();
    }
}


问:
Overlay one activity partially on another
I am creating android apps by self learning. I have tried searching for this everywhere but have not found it.

My exact question is how do I create the layout shown below. I want the Activity2 to slide up and down with up and down swipes respectively.

答: You can use BottomSheet to perform this. </p>


问:
What is the lifecycle for Android's StrictMode?
I'm trying to minimize the number of places in my code where I need to setup StrictMode. But I'm not sure if I'm right or not about the following.

The documentation for Android's StrictMode says you can use it for Applications, Activities and other components. I've read that it is not desirable to extend the Application class, and I'd prefer not to extend Application just to enable StrictMode. But I don't think I have to.

There are two policies you can use: ThreadPolicy (for a thread) and VmPolicy (for all threads). So it would seem that if I setup StrictMode on a thread once, it doesn't matter from where I do that, and violations will be reported thereafter on that thread regardless of other calls or not on StrictMode. I just need to call it from somewhere before violations could occur that I want to detect. And it needs to be setup for any new threads that get created in my application that I also want to check.

What I think I want to avoid is calling the build() methods more than I need to. Putting StrictMode at the beginning of onCreate() in all my activities means that build() is going to get called more than once on that thread. If I have one Launcher activity in my application, setting up StrictMode in that activity's onCreate() should be sufficient for the rest of the application. Is that true?

Secondly, if my main activity gets restarted even though the application did not die, is it technically necessary to call StrictMode again? Or is my thread still setup to report violations? I was thinking there might be some value in doing a wrapper-type of class around StrictMode like so:

```<code>public class MyStrictModeSettings {
    static private List<Long> setThreads = new ArrayList<Long>();

    // Prevent instantiation of this class
    private MyStrictModeSettings() {}

    static public synchronized void init() {
        try {
            Long tid = Thread.currentThread().getId();
            if(!setThreads.contains(tid)) {
                setThreads.add(tid);
                Class sMode = Class.forName("android.os.StrictMode");
                Method enableDefaults = sMode.getMethod("enableDefaults");
                enableDefaults.invoke(null);
            }
        }
        catch(Exception e) {
            // StrictMode not supported on this device, punt
            Log.v("StrictMode", "... not supported. Skipping...");
        }
    }
}
</code>```

That way, in my main activity's onCreate(), I can simply call MyStrictModeSettings.init() and be done with it. And it should work on Android versions prior to 2.3 too. But it may not be worth it. Brad, are you there? Thanks.

Edit: Since VmPolicy is for all threads, technically I only need to set that up once per application, right? So enableDefaults() is wasting effort to redo the VmPolicy when it gets called a second, third, etc time? Again, maybe it's more trouble than it's worth to try to avoid the extra calls.

答:
Yes, VmPolicy is for the whole process so doing it once is fine.  More times is cheap, though, so don't wory about it.

And yes, you only need to do it in your main/launcher activity's onCreate() --- that's the same "main" thread as all your other components.

Body:
I'm trying to minimize the number of places in my code where I need to setup StrictMode. But I'm not sure if I'm right or not about the following.

The documentation for Android's StrictMode says you can use it for Applications, Activities and other components. I've read that it is not desirable to extend the Application class, and I'd prefer not to extend Application just to enable StrictMode. But I don't think I have to.

There are two policies you can use: ThreadPolicy (for a thread) and VmPolicy (for all threads). So it would seem that if I setup StrictMode on a thread once, it doesn't matter from where I do that, and violations will be reported thereafter on that thread regardless of other calls or not on StrictMode. I just need to call it from somewhere before violations could occur that I want to detect. And it needs to be setup for any new threads that get created in my application that I also want to check.

What I think I want to avoid is calling the build() methods more than I need to. Putting StrictMode at the beginning of onCreate() in all my activities means that build() is going to get called more than once on that thread. If I have one Launcher activity in my application, setting up StrictMode in that activity's onCreate() should be sufficient for the rest of the application. Is that true?

Secondly, if my main activity gets restarted even though the application did not die, is it technically necessary to call StrictMode again? Or is my thread still setup to report violations? I was thinking there might be some value in doing a wrapper-type of class around StrictMode like so:

public class MyStrictModeSettings {
    static private List<Long> setThreads = new ArrayList<Long>();

    // Prevent instantiation of this class
    private MyStrictModeSettings() {}

    static public synchronized void init() {
        try {
            Long tid = Thread.currentThread().getId();
            if(!setThreads.contains(tid)) {
                setThreads.add(tid);
                Class sMode = Class.forName("android.os.StrictMode");
                Method enableDefaults = sMode.getMethod("enableDefaults");
                enableDefaults.invoke(null);
            }
        }
        catch(Exception e) {
            // StrictMode not supported on this device, punt
            Log.v("StrictMode", "... not supported. Skipping...");
        }
    }
}

That way, in my main activity's onCreate(), I can simply call MyStrictModeSettings.init() and be done with it. And it should work on Android versions prior to 2.3 too. But it may not be worth it. Brad, are you there? Thanks.

Edit: Since VmPolicy is for all threads, technically I only need to set that up once per application, right? So enableDefaults() is wasting effort to redo the VmPolicy when it gets called a second, third, etc time? Again, maybe it's more trouble than it's worth to try to avoid the extra calls.


问:
could not get input field value in jquery
I am creating an input field using foreach loop like this

```<code><?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
</code>```

$data is Array

```<code>(
    [0] => Array
        (
            [asset_id] => abc-02
            [asset_name] => Freezer
        )

    [1] => Array
        (
            [asset_id] => xyz-01
            [asset_name] => Refrigerator
        )

    [2] => Array
        (
            [asset_id] => 300001
            [asset_name] => Generator
        )
)
</code>```

and in javascript, I am trying to get the value using this code but it always alerts first value of the input.

```<code><script type="text/javascript">
 $(document).ready(function () {
           var typename = $('#typename').val();
           alert(typename);
});
</script>
</code>```

i have to disable this input field when value is 'Generator'

答:
You should never use same id for several elements.

Update you code for debug, and you'll see that you have an array:

```<code><script type="text/javascript">
 $(document).ready(function () {
           var typename = $('[name="model[]"]')
              .toArray().map(e => e.value);
           alert(JSON.stringify(typename));
});
</script>
</code>```

You should update your php, to set different id for each element drawn in a cycle, i.e:

```<code><?php $i=1;foreach($nomatter as $a) {?>
<input id="typename_<?=$i++?>">
<?php } ?>
</code>```

So you'll be able to address eash input separately:

```<code>       var typename = $('#typename_1').val();
</code>```

Body:
I am creating an input field using foreach loop like this

<?php foreach($data as $key=>$val) { ?>

<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">

<?php } ?>

$data is Array

(
    [0] => Array
        (
            [asset_id] => abc-02
            [asset_name] => Freezer
        )

    [1] => Array
        (
            [asset_id] => xyz-01
            [asset_name] => Refrigerator
        )

    [2] => Array
        (
            [asset_id] => 300001
            [asset_name] => Generator
        )
)

and in javascript, I am trying to get the value using this code but it always alerts first value of the input.

i have to disable this input field when value is 'Generator'

Body:
You should never use same id for several elements.

Update you code for debug, and you'll see that you have an array:

<script type="text/javascript">
 $(document).ready(function () {
           var typename = $('[name="model[]"]')
              .toArray().map(e => e.value);
           alert(JSON.stringify(typename));
});
</script>

You should update your php, to set different id for each element drawn in a cycle, i.e:

<?php $i=1;foreach($nomatter as $a) {?>
<input id="typename_<?=$i++?>">
<?php } ?>

So you'll be able to address eash input separately:

       var typename = $('#typename_1').val();


问:
PHP : how to convert object to array using loop
(
    [0] => stdClass Object
        (
            [name] => Ford
            [models] => Array
                (
                    [0] => Fiesta
                    [1] => Focus
                    [2] => Mustang
                )

```<code>    )

[1] => stdClass Object
    (
        [name] => BMW
        [models] => Array
            (
                [0] => 320
                [1] => X3
                [2] => X5
            )

    )

[2] => stdClass Object
    (
        [name] => Fiat
        [models] => Array
            (
                [0] => 500
                [1] => Panda
            )

    )
</code>```

)

答:
The easiest way is to JSON-encode your object and then decode it back to an array:

```<code>$array = json_decode(json_encode($object), True);
</code>```

Or if you prefer, you can traverse the object manually, too:

```<code>foreach ($object as $value) {
    $array[] = $value->name;
}
</code>```

Try it!

Body:
(
    [0] => stdClass Object
        (
            [name] => Ford
            [models] => Array
                (
                    [0] => Fiesta
                    [1] => Focus
                    [2] => Mustang
                )

    )

[1] => stdClass Object
    (
        [name] => BMW
        [models] => Array
            (
                [0] => 320
                [1] => X3
                [2] => X5
            )

    )

[2] => stdClass Object
    (
        [name] => Fiat
        [models] => Array
            (
                [0] => 500
                [1] => Panda
            )

    )

)

Body:
The easiest way is to JSON-encode your object and then decode it back to an array:

$array = json_decode(json_encode($object), True);

Or if you prefer, you can traverse the object manually, too:

foreach ($object as $value) {
    $array[] = $value->name;
}

Try it!


问:
What does "~[]" do?
I saw the following line of code here .

```<code>puts("sigprocmask(SIG_UNBLOCK, ~[], []) = 0");
</code>```

I don't understand, what does empty array script([]) do?

Also, What is the purpose of ~[] in C?

答:
It does nothing.

```<code>puts("sigprocmask(SIG_UNBLOCK, ~[], []) = 0");
     ^                                     ^
</code>```

It's a string literal. This line is probably used to generate a program in another language, which at least isn't C.

Title: What does "~[]" do?

Body:
I saw the following line of code here .

puts("sigprocmask(SIG_UNBLOCK, ~[], []) = 0");

I don't understand, what does empty array script([]) do?

Also, What is the purpose of ~[] in C?

Body:
It does nothing.

puts("sigprocmask(SIG_UNBLOCK, ~[], []) = 0");
     ^                                     ^

It's a string literal. This line is probably used to generate a program in another language, which at least isn't C.


问:
Check for username while typing in field?
I am fluent with HTML, and mostly PHP.

I can do the scanning part with PHP.. I'm just not sure how to call a function in PHP with JavaScript, because I don't know JavaScript.

My PHP code will connect to my MySQL database and see if the text currently in the textbox (Not clicked enter yet, still typing) is in the database..

Do you know how to do this, or at least know a link that tells you how to do it?

答:
I see everybody likes jQuery so much, wow!
I'd tell you just need some very basic Ajax script to call your PHP script and receive the response.
Here's the simple Javascript function (actually two):

```<code>function getXMLObject() {
  var xmlHttp = false;
  try {
    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// For Old Microsoft Browsers
  }
  catch (e) {
    try {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");// For Microsoft IE 6.0+
    }
    catch (e2) {
      xmlHttp = false;// No Browser accepts the XMLHTTP Object then false
    }
  }
  if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
    xmlHttp = new XMLHttpRequest();//For Mozilla, Opera Browsers
  }
  return xmlHttp;// Mandatory Statement returning the ajax object created
}

var xmlhttp = new getXMLObject();//xmlhttp holds the ajax object

//use this method for asynchronous communication
function doRequest(scriptAddressWithParams, callback) {
  if (xmlhttp) {
    xmlhttp.open("POST", scriptAddressWithParams, true);
    xmlhttp.onreadystatechange = function () {
      if (xmlhttp.readyState == 4) {
        if (xmlhttp.status == 200) {
          callback(xmlhttp.responseText);
        }
        else {
          alert("Error retrieving information (status = " + xmlhttp.status + ")\n" + response);
        }
      }
    };
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send(null);
  }
}
</code>```

and here's an example of usage:

```<code><input type="text" onchange="doRequest('myphpscript.php?checkvalue='+this.value, function (returnedText) { alert(returnedText);});"/>
</code>```

Body:
I see everybody likes jQuery so much, wow!
I'd tell you just need some very basic Ajax script to call your PHP script and receive the response.
Here's the simple Javascript function (actually two):

function getXMLObject() {
  var xmlHttp = false;
  try {
    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// For Old Microsoft Browsers
  }
  catch (e) {
    try {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");// For Microsoft IE 6.0+
    }
    catch (e2) {
      xmlHttp = false;// No Browser accepts the XMLHTTP Object then false
    }
  }
  if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
    xmlHttp = new XMLHttpRequest();//For Mozilla, Opera Browsers
  }
  return xmlHttp;// Mandatory Statement returning the ajax object created
}

var xmlhttp = new getXMLObject();//xmlhttp holds the ajax object

//use this method for asynchronous communication
function doRequest(scriptAddressWithParams, callback) {
  if (xmlhttp) {
    xmlhttp.open("POST", scriptAddressWithParams, true);
    xmlhttp.onreadystatechange = function () {
      if (xmlhttp.readyState == 4) {
        if (xmlhttp.status == 200) {
          callback(xmlhttp.responseText);
        }
        else {
          alert("Error retrieving information (status = " + xmlhttp.status + ")\n" + response);
        }
      }
    };
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send(null);
  }
}

and here's an example of usage:

<input type="text" onchange="doRequest('myphpscript.php?checkvalue='+this.value, function (returnedText) { alert(returnedText);});"/>


答:
try this ,
this will call alert function for each input with form-control class

```<code> $(document).ready(function () {
          $(".form-control").each(function(){

           alert($(this).val());
     })
});
</code>```

Title: could not get input field value in jquery

Body:
try this ,
this will call alert function for each input with form-control class

 $(document).ready(function () {
          $(".form-control").each(function(){

           alert($(this).val());
     })
});


问:
Permission denied when installing Tensorflow
I am trying to install TensorFlow by Anaconda(My Python is 3.5.2 edition).

When I run:

```<code>(tensorflow)C:> pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-1.0.1-cp35-cp35m-win_amd64.whl
</code>```

According to the guide in Tensorflow.org, the following tips emerge:

```<code>Exception:
Traceback (most recent call last):
File "C:\Users\Anaconda3\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
File "C:\Users\Anaconda3\lib\site-packages\pip\commands\install.py", line 317, in run
prefix=options.prefix_path,
File "C:Anaconda3\lib\site-packages\pip\req\req_set.py", line 742, in install
**kwargs
File "C:\Users\Anaconda3\lib\site-packages\pip\req\req_install.py", line 831, in install
self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
File "C:\Users\Anaconda3\lib\site-packages\pip\req\req_install.py", line 1032, in move_wheel_files
isolated=self.isolated,
File "C:\Users\Anaconda3\lib\site-packages\pip\wheel.py", line 346, in move_wheel_files
clobber(source, lib_dir, True)
File "C:\Users\Anaconda3\lib\site-packages\pip\wheel.py", line 324, in clobber
shutil.copyfile(srcfile, destfile)
File "C:\Users\Anaconda3\lib\shutil.py", line 115, in copyfile
with open(dst, 'wb') as fdst:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Anaconda3\\Lib\\site-packages\\numpy\\core\\multiarray.cp35-win_amd64.pyd'
</code>```

I don't know what causes this error. Can someone help me with that?

答:
I had permission denied problem on windows but this worked for me:

right click on cmd or git console > run as administrator

pip install tensorflow

Body:
I am trying to install TensorFlow by Anaconda(My Python is 3.5.2 edition).

When I run:

(tensorflow)C:> pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-1.0.1-cp35-cp35m-win_amd64.whl

According to the guide in Tensorflow.org, the following tips emerge:

Exception:
Traceback (most recent call last):
File "C:\Users\Anaconda3\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
File "C:\Users\Anaconda3\lib\site-packages\pip\commands\install.py", line 317, in run
prefix=options.prefix_path,
File "C:Anaconda3\lib\site-packages\pip\req\req_set.py", line 742, in install
**kwargs
File "C:\Users\Anaconda3\lib\site-packages\pip\req\req_install.py", line 831, in install
self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
File "C:\Users\Anaconda3\lib\site-packages\pip\req\req_install.py", line 1032, in move_wheel_files
isolated=self.isolated,
File "C:\Users\Anaconda3\lib\site-packages\pip\wheel.py", line 346, in move_wheel_files
clobber(source, lib_dir, True)
File "C:\Users\Anaconda3\lib\site-packages\pip\wheel.py", line 324, in clobber
shutil.copyfile(srcfile, destfile)
File "C:\Users\Anaconda3\lib\shutil.py", line 115, in copyfile
with open(dst, 'wb') as fdst:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Anaconda3\\Lib\\site-packages\\numpy\\core\\multiarray.cp35-win_amd64.pyd'

I don't know what causes this error. Can someone help me with that?


问:
What is the difference between expo and react native app developing?
I am going to develop react native app using Expo but I don't have idea which one is best? Please suggest me any idea?

Actually I am using Expo. Which is best Expo or normal Android or Xcode development?

答:
When you write code in Expo (abbr. XDE), you write React Native code. Expo has two main pieces:

1) XDE: a developer tool for creating projects, viewing logs, opening on your device, publishing, etc.

2) The Expo client: an app on your phone that lets you open your projects while you're working on them, without needing to go through XCode or Android Studio, and also lets other people view them too!

But ...

With most apps in React Native, you end up needing to utilise several
  third party native libraries, which Expo doesn’t current support
  outside of their built in APIs. There are a lot of things that can be
  done in JS only, but I’ve always ended up running into a need for
  native libraries with every React Native project I’ve worked on
  (several production apps). That being said, Expo does support
  “detaching” your app from Expo, which will allow you to carry on with
  a standard free standing React Native app.

Expo has some advantages over using normal Xcode/Studio like expo client, but it also has its cons when it comes to large scale applications . You can choose based on your needs.

If you’re just getting started and you need to get off the ground quickly, I’d definitely recommend Expo

Note: This answer is a blend from multiple developers


答:
Use class instead of duplicate id like this.

```<code><?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control clsValue" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
</code>```

And in jquery loop your class and get value using this instant..

```<code>$(document).ready(function () {
        $( ".clsValue" ).each(function( index ) {
          var typename = $(this).val();
           alert(typename);
    });
});
</code>```

Body:
Use class instead of duplicate id like this.

<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control clsValue" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>

And in jquery loop your class and get value using this instant..

$(document).ready(function () {
        $( ".clsValue" ).each(function( index ) {
          var typename = $(this).val();
           alert(typename);
    });
});


问:
Trigger external events through Yammer
I was wondering if it was possible to trigger external events by scanning comments on posts. Yammer doesn't seem to provide a callback for messages posted through the Yammer API. What is the best way this can be achieved?

Thank you!

答: You are correct, there isn't a callback-based API using something like web hooks. Developers typically achieve this by utilizing the Yammer Data Export API, but you need to manage state and scan through a list of messages which may be more than just the last message. Make note of all the available parameters, because you can just get the messages model.</p>

Title: Trigger external events through Yammer


问:
How do I pass data from login to another page
I am new to react-native and redux. I have successfully created a login function which calls a post-request api. The credentials insert by a user are matric no and password. I have another post-method api need to be called to display a list of data in another page after the user successfully logged on. However I dunno how to pass the matric no  to another page since there is no event that ought to trigger the user to enter their matric no i order to call the post-method api. Can somebody help me how to solve this?</p>

答:
Use Redux Store or AsyncStorage to store important login information like token or your matrix no.

Retrieve on next page in componentWillMount() and send to Ajax to validate and get data.

ref : https://facebook.github.io/react-native/docs/asyncstorage.html


问:
Objective-C Helper Methods
I'm good with Swift but new to objective-C. When user taps button on alert view, that button needs to be disabled for next 24 hours.Code shown below is a helper method that stores key:userId, value:timestamp in NSUserDefaults-which I've never really used. I have some concerns.

My helper method is in a class that only has class methods, so even though I'd like for my helper method to be private, it can't since its called inside class method. Puzzled about how to conceal this from other objects.

Better procedure for logic? The nested if statements look ugly and would probably be hard to read if it wasn't fresh in my mind.

Is it best practice to just copy alertAction input or use inout, since I'm just enabling or disabling button based off logic.

better name for method? Its purpose is to enable/disable alert controller based off logic, and to store in NSUserDefaults. configXXX seems very generic.

Thanks in advance.

```<code>    + (UIAlertAction *)configureAlertAction:(UIAlertAction *)alertAction
                                    forUser:(id<BaseUser>)user {
        /// Check User defaults to see if current user has reported this user already.
        /// if not: store userID and timestamp 24 hours out in defaults and enable alert action.
        /// If so, disable action.

        NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
        UIAlertAction *modifiedAlertAction = alertAction;

        double currentDate = [[NSDate date] timeIntervalSince1970];
        double previousDate = [standardDefaults doubleForKey:user.userId];

        if (previousDate) {
            if (previousDate > currentDate) {
                // remove from userdefaults..
                [standardDefaults removeObjectForKey:user.userId];
                // enable alert
                [modifiedAlertAction setEnabled:YES];
            } else if (previousDate > currentDate) {
                [modifiedAlertAction setEnabled:NO];
            }
        } else {
            // store in NSuserdefaults
            [modifiedAlertAction setEnabled:YES];
            double expirationDate = currentDate + 86400;
            [standardDefaults setDouble:expirationDate forKey:user.userId];
        }

        return modifiedAlertAction;
    }
</code>```

答:
For your questions

There isn't really a "private method" in Objective-C. You can learn more here Best way to define private methods for a class in Objective-C

If you don't like nested if statements, it's my suggestion

```<code>+ (UIAlertAction *)configureAlertAction:(UIAlertAction *)alertAction
                                forUser:(id<BaseUser>)user {
  /// Check User defaults to see if current user has reported this user already.
  /// if not: store userID and timestamp 24 hours out in defaults and enable alert action.
  /// If so, disable action.

  NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];

  double currentDate = [[NSDate date] timeIntervalSince1970];
  double previousDate = [standardDefaults doubleForKey:user.userId];

  if (!previousDate) {
    // store in NSuserdefaults
    [alertAction setEnabled:YES];
    double expirationDate = currentDate + 86400;
    [standardDefaults setDouble:expirationDate forKey:user.userId];

    return alertAction;
  }

  BOOL shouldEnableAlert = previousDate > currentDate;
  if (shouldEnableAlert) {
    // remove from userdefaults..
    [standardDefaults removeObjectForKey:user.userId];
  }
  [alertAction setEnabled:shouldEnableAlert];

  return alertAction;
}
</code>```

I don't think you have to copy alert since I'm just enabling or disabling button based off logic. You don't need another alert.

In my opinion, the method name is ok.

Title: Objective-C Helper Methods

Body:
I'm good with Swift but new to objective-C. When user taps button on alert view, that button needs to be disabled for next 24 hours.Code shown below is a helper method that stores key:userId, value:timestamp in NSUserDefaults-which I've never really used. I have some concerns.

My helper method is in a class that only has class methods, so even though I'd like for my helper method to be private, it can't since its called inside class method. Puzzled about how to conceal this from other objects.

Better procedure for logic? The nested if statements look ugly and would probably be hard to read if it wasn't fresh in my mind.

Is it best practice to just copy alertAction input or use inout, since I'm just enabling or disabling button based off logic.

better name for method? Its purpose is to enable/disable alert controller based off logic, and to store in NSUserDefaults. configXXX seems very generic.

Thanks in advance.

    + (UIAlertAction *)configureAlertAction:(UIAlertAction *)alertAction
                                    forUser:(id<BaseUser>)user {
        /// Check User defaults to see if current user has reported this user already.
        /// if not: store userID and timestamp 24 hours out in defaults and enable alert action.
        /// If so, disable action.

        NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
        UIAlertAction *modifiedAlertAction = alertAction;

        double currentDate = [[NSDate date] timeIntervalSince1970];
        double previousDate = [standardDefaults doubleForKey:user.userId];

        if (previousDate) {
            if (previousDate > currentDate) {
                // remove from userdefaults..
                [standardDefaults removeObjectForKey:user.userId];
                // enable alert
                [modifiedAlertAction setEnabled:YES];
            } else if (previousDate > currentDate) {
                [modifiedAlertAction setEnabled:NO];
            }
        } else {
            // store in NSuserdefaults
            [modifiedAlertAction setEnabled:YES];
            double expirationDate = currentDate + 86400;
            [standardDefaults setDouble:expirationDate forKey:user.userId];
        }

        return modifiedAlertAction;
    }

Body:
For your questions

There isn't really a "private method" in Objective-C. You can learn more here Best way to define private methods for a class in Objective-C

If you don't like nested if statements, it's my suggestion

+ (UIAlertAction *)configureAlertAction:(UIAlertAction *)alertAction
                                forUser:(id<BaseUser>)user {
  /// Check User defaults to see if current user has reported this user already.
  /// if not: store userID and timestamp 24 hours out in defaults and enable alert action.
  /// If so, disable action.

  NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];

  double currentDate = [[NSDate date] timeIntervalSince1970];
  double previousDate = [standardDefaults doubleForKey:user.userId];

  if (!previousDate) {
    // store in NSuserdefaults
    [alertAction setEnabled:YES];
    double expirationDate = currentDate + 86400;
    [standardDefaults setDouble:expirationDate forKey:user.userId];

    return alertAction;
  }

  BOOL shouldEnableAlert = previousDate > currentDate;
  if (shouldEnableAlert) {
    // remove from userdefaults..
    [standardDefaults removeObjectForKey:user.userId];
  }
  [alertAction setEnabled:shouldEnableAlert];

  return alertAction;
}

I don't think you have to copy alert since I'm just enabling or disabling button based off logic. You don't need another alert.

In my opinion, the method name is ok.


问:
How does one get a code-behind file to recognize type of a user control?
I have a custom control in my mater page that represents a menu, let's call it CustomMenu. The control code files are located in a non special directory.

I want to give each page that uses that master page the ability to access the control and, using a public property, tell the control whether or not it should render itself.

I have a public property on the control to do that, and I know I can get the control by referencing Page.Master.FindControl('IdOfControlIwant');

The problem I'm having is that I can't seem to get the control Type recognized by the compiler, so when I do find the menu control, I can't actually work with it. The only way I can get the code behind to recognize the type is to register it in the ascx file, and then add at least one control to the page, which is undesirable.

Thoughts?

答:
Make a property of your MasterPage class:

```<code>bool IsCustomMenuVisible {set{ CustomMenu.Visible = value;}}
</code>```

And use it wherever you like.

Body:
Make a property of your MasterPage class:

bool IsCustomMenuVisible {set{ CustomMenu.Visible = value;}}

And use it wherever you like.


问:
ORA-00936 when select statement
```<code>SELECT * FROM A,B
WHERE
A.COMP_CODE = B.COMP_CODE (+)
AND
A.DATE = TO_CHAR(ADD_MONTHS(TO_DATE(B.DATE,'yyyymm'),-1),'YYYYMM') (+)
</code>```

When I execute this statement I get error: ORA-00936.
When I remove the (+) at the end this statement then it works, but I want keep (+) in this statement.

答:
When using the old (+) syntax for outer joins, the (+) should directly follow the column your're outer-joining on, not the entire expression:

```<code>SELECT *
FROM   A, B
WHERE  A.COMP_CODE = B.COMP_CODE (+)
       AND
       A.DATE = TO_CHAR(ADD_MONTHS(TO_DATE(B.DATE (+), 'yyyymm'), 'YYYYMM')
       -- Here -----------------------------------^
</code>```

But honestly, this syntax has been considered deprecated for several years no. You'd probably be better off using the modern explicit outer join syntax:

```<code>SELECT *
FROM   A
LEFT OUTER JOIN B ON -- Here!
    A.COMP_CODE = B.COMP_CODE
    AND
    A.DATE = TO_CHAR(ADD_MONTHS(TO_DATE(B.DATE, 'yyyymm'), 'YYYYMM')
</code>```

Title: ORA-00936 when select statement

Body:
SELECT * FROM A,B
WHERE
A.COMP_CODE = B.COMP_CODE (+)
AND
A.DATE = TO_CHAR(ADD_MONTHS(TO_DATE(B.DATE,'yyyymm'),-1),'YYYYMM') (+)

When I execute this statement I get error: ORA-00936.
When I remove the (+) at the end this statement then it works, but I want keep (+) in this statement.

Body:
When using the old (+) syntax for outer joins, the (+) should directly follow the column your're outer-joining on, not the entire expression:

SELECT *
FROM   A, B
WHERE  A.COMP_CODE = B.COMP_CODE (+)
       AND
       A.DATE = TO_CHAR(ADD_MONTHS(TO_DATE(B.DATE (+), 'yyyymm'), 'YYYYMM')
       -- Here -----------------------------------^

But honestly, this syntax has been considered deprecated for several years no. You'd probably be better off using the modern explicit outer join syntax:

SELECT *
FROM   A
LEFT OUTER JOIN B ON -- Here!
    A.COMP_CODE = B.COMP_CODE
    AND
    A.DATE = TO_CHAR(ADD_MONTHS(TO_DATE(B.DATE, 'yyyymm'), 'YYYYMM')


问:
MySQL UWP "Could not load file or assembly"
I have a MySQL 5.7.20-log server running on Windows Server 2012.

I have created two simple applications:

1. C# Windows Forms application (.NET) using 6.10.4 Connector (NuGet package)

```<code>    private void Form1_Load(object sender, EventArgs e)
    {
        TestMySqlConnection();
    }

    private void TestMySqlConnection()
    {
        string dbConnectionString =
        " Data source = 192.168.0.12;" +
        " Database = rcp;" +
        " User Id = rcp;" +
        " Password = *******;" +
        " SslMode = None;";

        using (MySqlConnection dbConnection = new MySqlConnection(dbConnectionString))
        {
            dbConnection.Open();
        }
    }
</code>```

This application runs without problems.

2. Universal Windows Platform application (UWP /.NetCore) using 6.10.4 Connector (NuGet package)

```<code>    private void Page_Loaded(object sender, RoutedEventArgs e)
    {
        TestMySqlConnection();
    }

    private void TestMySqlConnection()
    {
        string dbConnectionString =
        " Data source = 192.168.0.12;" +
        " Database = rcp;" +
        " User Id = rcp;" +
        " Password = *******;" +
        " SslMode = None;";

        using (MySqlConnection dbConnection = new MySqlConnection(dbConnectionString))
        {
            dbConnection.Open();
        }
    }
</code>```

This application does not work and throws an Exception.

Exception:

Exception has been thrown by the target of an invocation.

InnerException:

FileNotFoundException: Could not load file or assembly 'System.Diagnostics.Process, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

Any help would be appreciated.

答:
Connecting to MySql database directly in UWP is a new feature which is introduced from .NET Standard 2.0.

For the previous Universal Windows Platform, it only supports .NET Standard 1.4.

So, that's the issue you're facing. I also can reproduce it on my side if I set my project's target version is 16299, but min version is the previous version (15063,14393 etc).

To solve this issue, you would need to make the project's target version and min version are 16299.

Body:
I have a MySQL 5.7.20-log server running on Windows Server 2012.

I have created two simple applications:

1. C# Windows Forms application (.NET) using 6.10.4 Connector (NuGet package)

    private void Form1_Load(object sender, EventArgs e)
    {
        TestMySqlConnection();
    }

    private void TestMySqlConnection()
    {
        string dbConnectionString =
        " Data source = 192.168.0.12;" +
        " Database = rcp;" +
        " User Id = rcp;" +
        " Password = *******;" +
        " SslMode = None;";

        using (MySqlConnection dbConnection = new MySqlConnection(dbConnectionString))
        {
            dbConnection.Open();
        }
    }

This application runs without problems.

2. Universal Windows Platform application (UWP /.NetCore) using 6.10.4 Connector (NuGet package)

    private void Page_Loaded(object sender, RoutedEventArgs e)
    {
        TestMySqlConnection();
    }

    private void TestMySqlConnection()
    {
        string dbConnectionString =
        " Data source = 192.168.0.12;" +
        " Database = rcp;" +
        " User Id = rcp;" +
        " Password = *******;" +
        " SslMode = None;";

        using (MySqlConnection dbConnection = new MySqlConnection(dbConnectionString))
        {
            dbConnection.Open();
        }
    }

This application does not work and throws an Exception.

Exception:

Exception has been thrown by the target of an invocation.

InnerException:

FileNotFoundException: Could not load file or assembly 'System.Diagnostics.Process, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

Any help would be appreciated.


答:
Set  class="typename" instead of  id="typename":

```<code>   <?php foreach($data as $key=>$val) { ?>
    <td class="table-td-1">
    <input readonly class="form-control" name="model[]" class="typename" type="text" value="<?php echo $val['asset']; ?>">
    </td>
    <?php } ?>
</code>```

You can get values like this:

```<code><script type="text/javascript">
 $(document).ready(function () {
           var typename1 = $('.typename')[0].val();
           var typename2 = $('.typename')[1].val();
           alert(typename1);
});
</script>
</code>```

Body:
Set  class="typename" instead of  id="typename":

   <?php foreach($data as $key=>$val) { ?>
    <td class="table-td-1">
    <input readonly class="form-control" name="model[]" class="typename" type="text" value="<?php echo $val['asset']; ?>">
    </td>
    <?php } ?>

You can get values like this:

<script type="text/javascript">
 $(document).ready(function () {
           var typename1 = $('.typename')[0].val();
           var typename2 = $('.typename')[1].val();
           alert(typename1);
});
</script>


问:
Why PriorityQueue requires API 24 in Android
PriorityQueue was added in Java 1.5

new PriorityQueue()is enabled in Android, but

```<code>  new PriorityQueue(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            return 0;
        }
    });
</code>```

requires API 24. Why?

答:
PriorityQueue(Comparator) constructor was implemented in API level 24.

 Android Developers reference:

Body:
PriorityQueue was added in Java 1.5

new PriorityQueue()is enabled in Android, but

  new PriorityQueue(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            return 0;
        }
    });

requires API 24. Why?


问:
MongoEngine fields, typing and PyCharm
PyCharm gives a type warning when working with a MongoEngine field's value. For example, when working with StringField as with str:

```<code>class ExampleDocument(Document):
    s = StringField()

doc = ExampleDocument(s='mongoengine-test')
print(doc.s.endswith('test'))
</code>```

I get a warning Unresolved attribute reference 'endswith' for class StringField unless I use typing.cast (i.e. typing.cast(str, doc.s).endswith('test'). The code executes as intended, but is there any way to get rid of these warnings and also to get the necessary autocompletes for MongoEngine field types?

答:
It is probably not the best of all thinkable solutions, but you can add your own type hints directly to the field declarations. Either using 2.7 syntax with comments (also works in 3.x):

```<code>class ExampleDocument(Document):
    s = StringField()  # type: str
</code>```

Or with 3.x:

```<code>class ExampleDocument(Document):
    s: str = StringField()
</code>```

Using type defintions in doc strings should also work:

```<code>class ExampleDocument(Document):
    s = StringField()
    """:type: str"""
</code>```

Either one of those gives PyCharm (or Intelij with python plugins) the necessary clues about the type to use for these field.

Note that now you will get warnings, when you access something from original mongoengine field types, because you effectively replaced the type used for type checking. If you want PyCharm to recognise both the mongoengine and the Python type, you can use a Union type:

```<code>from typing import Union
class ExampleDocument(Document):
    s = StringField()  # type: Union[str, StringField]
</code>```

You find more details on using type hins in PyCharm in the PyCharm docs here.

Title: MongoEngine fields, typing and PyCharm

Body:
PyCharm gives a type warning when working with a MongoEngine field's value. For example, when working with StringField as with str:

class ExampleDocument(Document):
    s = StringField()

doc = ExampleDocument(s='mongoengine-test')
print(doc.s.endswith('test'))

I get a warning Unresolved attribute reference 'endswith' for class StringField unless I use typing.cast (i.e. typing.cast(str, doc.s).endswith('test'). The code executes as intended, but is there any way to get rid of these warnings and also to get the necessary autocompletes for MongoEngine field types?

Body:
It is probably not the best of all thinkable solutions, but you can add your own type hints directly to the field declarations. Either using 2.7 syntax with comments (also works in 3.x):

class ExampleDocument(Document):
    s = StringField()  # type: str

Or with 3.x:

class ExampleDocument(Document):
    s: str = StringField()

Using type defintions in doc strings should also work:

class ExampleDocument(Document):
    s = StringField()
    """:type: str"""

Either one of those gives PyCharm (or Intelij with python plugins) the necessary clues about the type to use for these field.

Note that now you will get warnings, when you access something from original mongoengine field types, because you effectively replaced the type used for type checking. If you want PyCharm to recognise both the mongoengine and the Python type, you can use a Union type:

from typing import Union
class ExampleDocument(Document):
    s = StringField()  # type: Union[str, StringField]

You find more details on using type hins in PyCharm in the PyCharm docs here.


问:
mysql select all table names except
Alright, I know you can do the following to get all column names.

```<code>SHOW COLUMNS FROM person;
</code>```

However, it does not allow where statements.

Is there any way to get the full list and just say not this one?

So I am basically looking for something like this:

```<code>select (show columns from person where Field <> 'id') from person
</code>```

答:
Or you can use proper a SQL query against information_schema

```<code>select * from information_schema.columns
where table_schema = 'test'    # your db name
and table_name = 'person '
and column_name != 'id'
</code>```

For MySQL 4, you can use LIKE directly instead of WHERE http://dev.mysql.com/doc/refman/4.1/en/show-columns.html

```<code>SHOW COLUMNS FROM 'Person' LIKE '%x%'
</code>```

However unfortunately, that does not support a NOT clause.

If I may suggest

If you need this information from
MySQL console/phpAdmin/equivalent,
just eyeball it..

If you need this
from a front-end program like php, do
it from that environment.

Title: mysql select all table names except

Body:
Alright, I know you can do the following to get all column names.

SHOW COLUMNS FROM person;

However, it does not allow where statements.

Is there any way to get the full list and just say not this one?

So I am basically looking for something like this:

select (show columns from person where Field <> 'id') from person

Body:
Or you can use proper a SQL query against information_schema

select * from information_schema.columns
where table_schema = 'test'    # your db name
and table_name = 'person '
and column_name != 'id'

For MySQL 4, you can use LIKE directly instead of WHERE http://dev.mysql.com/doc/refman/4.1/en/show-columns.html

SHOW COLUMNS FROM 'Person' LIKE '%x%'

However unfortunately, that does not support a NOT clause.

If I may suggest

If you need this information from
MySQL console/phpAdmin/equivalent,
just eyeball it..

If you need this
from a front-end program like php, do
it from that environment.


问:
Yii-2 how to update a record on basis of id
I want to update my table/model. The scenario is, I have a 'status' column, I want to SET this column to a value then update the model based on the id. I want to do something like update statement.

Update 'table' SET status = 'status value' where id = 'myid'

My action controller look like

```<code>$model = $this->findModel($id);
$ogp_id = $model->id;
$status = $model->status;
</code>```

I have searched for it but couldn't find a solution

Any help would be highly appreciated

答:
This Works for me

I added a function

```<code> protected function findModel($id)
{
    if (($model = Ogpheader::findOne($id)) !== null) {
        return $model;
    } else {
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
</code>```

Then access it inside the controller

```<code>$model = $this->findModel($id);
$ogp_id = $model->id;
</code>```

Then while saving my model I have done the following

```<code>if($m->save())
{
   $model->status = Ogpheader::$status_titles[1];
   $model->update();
   //my other code
}
</code>```

This has updated my table and set the column as required

Body:
I want to update my table/model. The scenario is, I have a 'status' column, I want to SET this column to a value then update the model based on the id. I want to do something like update statement.

Update 'table' SET status = 'status value' where id = 'myid'

My action controller look like

$model = $this->findModel($id);
$ogp_id = $model->id;
$status = $model->status;

I have searched for it but couldn't find a solution

Any help would be highly appreciated

Body:
This Works for me

I added a function

 protected function findModel($id)
{
    if (($model = Ogpheader::findOne($id)) !== null) {
        return $model;
    } else {
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

Then access it inside the controller

$model = $this->findModel($id);
$ogp_id = $model->id;

Then while saving my model I have done the following

if($m->save())
{
   $model->status = Ogpheader::$status_titles[1];
   $model->update();
   //my other code
}

This has updated my table and set the column as required


问:
Xamarin.Forms binding not updating after initial value
I'm binding the title of my Xamarin.Forms.ContentPage to a property BuggyTitle in my view model (VM). The VM derives from MvxViewModel. Here's the simplified version:

BuggyPage.xaml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<local:ContentPage Title="{Binding BuggyTitle}"
            xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            x:Class="MyProject.BuggyPage"
            xmlns:local="clr-namespace:Xamarin.Forms;assembly=MyProject">
<ContentPage.Content NavigationPage.HasNavigationBar="false">
        <Grid>
            <ScrollView>
                <!--and so on-->
</ContentPage.Content>
</local:ContentPage>
</code>```

BuggyViewModel.cs:

```<code>namespace MyProject
{
    [ImplementPropertyChanged]
    public class BuggyViewModel : MvxViewModel
    {
      private Random _random;

      public string BuggyTitle {get; set;}

      public BuggyViewModel()
      {
          _random = new Random();
      }

      public override void Start()
        {
            base.Start();
            BuggyTitle = "" + _random.Next(1000);
            RaisePropertyChanged("BuggyTitle"); // this seems to make no difference
        }
    }
}
</code>```

There's not much going on in the code behind other than a call to InitializeComponent() in the constructor.

The page is mapped to the VM generically in my project (not actually 'my' project, it's existing design), and it boils down to these (again, simplified) lines of code:

```<code>public static Page CreatePage(MvxViewModelRequest request)
{
    var viewModelName = request.ViewModelType.Name;
    var pageName = viewModelName.Replace ("ViewModel", "Page");
    var pageType = (typeof (MvxPagePresentationHelpers)).GetTypeInfo ().Assembly.CreatableTypes().FirstOrDefault(t => t.Name == pageName);
    var viewModelLoader = Mvx.Resolve<IMvxViewModelLoader>();
    var viewModel = viewModelLoader.LoadViewModel(request, null);
    var page = Activator.CreateInstance(pageType) as Page;
    page.BindingContext = viewModel;

   return page;
}
</code>```

The problem:

When BuggyPage loads, I initially get the correct value for the title. Whenever it is displayed after that, even though I can see in the debugger that BuggyTitle is getting updated correctly, the change does not appear in the page.

Question:

Why don't updates to BuggyTitle get reflected in the page?

Edit 1:

To further describe the weirdness, I added a Label to my ContentPage, with x:Name="BuggyLabel" and Text="{Binding BuggyLabelText}".
In my code-behind, I added this:

```<code>var binding_context = (BindingContext as BuggyViewModel);
if (binding_context != null)
{
    BuggyLabel.Text = binding_context.BuggyLabelText;
}
</code>```

I set a breakpoint at BuggyLabel.Text =. It gets hit every time the page loads, and BuggyLabel.Text already seems to have the correct value (i.e, whatever binding_context.BuggyLabelText is set to). However, the actual page displayed only ever shows what the text in this label is initially set to.

And yes, have clean/built about a million times.

Edit 2 (further weirdness):

I put this in the code-behind so that it runs during page load:

```<code>var binding_context = (BindingContext as BuggyViewModel);
if (binding_context != null)
{
    Device.BeginInvokeOnMainThread(() =>
    {
        binding_context.RefreshTitleCommand.Execute(null);
    });
}
</code>```

This again changes values in the debugger, but these changes don't get reflected in the displayed page.

I then added a button to the page and bound it to RefreshTitleCommand, and wham! the page updates its display.

Unfortunately I can't use this. Not only is it incredibly hackish, I can't have the user pressing buttons to have the page display what it's meant to on load.

I wonder if there's some caching going on with MvvmCross or Xamarin.

答:
 Answer

You need to add RaisePropertyChanged in BuggyTitle property declaration.

ViewModel

```<code>namespace MyProject
{
    [ImplementPropertyChanged]
    public class BuggyViewModel : MvxViewModel
    {
        private Random _random;

        string  _BuggyTitle { get; set; }

        public string BuggyTitle
        {
            get { return _BuggyTitle; }
            set { _BuggyTitle = value; RaisePropertyChanged(() => BuggyTitle); }
        }

        public BuggyViewModel()
        {
            _random = new Random();
        }

        public override void Start()
        {
            base.Start();
            BuggyTitle = "" + _random.Next(1000);
        }
    }
}
</code>```

-----New Update------

Code behind code

```<code>var binding_context = (BindingContext as BuggyViewModel);
if (binding_context != null)
{
    Device.BeginInvokeOnMainThread(() =>
    {
        BuggyLabel.Text = binding_context.BuggyLabelText;
    });
}
</code>```

Body:
I'm binding the title of my Xamarin.Forms.ContentPage to a property BuggyTitle in my view model (VM). The VM derives from MvxViewModel. Here's the simplified version:

BuggyPage.xaml:

<?xml version="1.0" encoding="UTF-8"?>
<local:ContentPage Title="{Binding BuggyTitle}"
            xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            x:Class="MyProject.BuggyPage"
            xmlns:local="clr-namespace:Xamarin.Forms;assembly=MyProject">
<ContentPage.Content NavigationPage.HasNavigationBar="false">
        <Grid>
            <ScrollView>

</ContentPage.Content>
</local:ContentPage>

BuggyViewModel.cs:

namespace MyProject
{
    [ImplementPropertyChanged]
    public class BuggyViewModel : MvxViewModel
    {
      private Random _random;

      public string BuggyTitle {get; set;}

      public BuggyViewModel()
      {
          _random = new Random();
      }

      public override void Start()
        {
            base.Start();
            BuggyTitle = "" + _random.Next(1000);
            RaisePropertyChanged("BuggyTitle"); // this seems to make no difference
        }
    }
}

There's not much going on in the code behind other than a call to InitializeComponent() in the constructor.

The page is mapped to the VM generically in my project (not actually 'my' project, it's existing design), and it boils down to these (again, simplified) lines of code:

public static Page CreatePage(MvxViewModelRequest request)
{
    var viewModelName = request.ViewModelType.Name;
    var pageName = viewModelName.Replace ("ViewModel", "Page");
    var pageType = (typeof (MvxPagePresentationHelpers)).GetTypeInfo ().Assembly.CreatableTypes().FirstOrDefault(t => t.Name == pageName);
    var viewModelLoader = Mvx.Resolve<IMvxViewModelLoader>();
    var viewModel = viewModelLoader.LoadViewModel(request, null);
    var page = Activator.CreateInstance(pageType) as Page;
    page.BindingContext = viewModel;

   return page;
}

The problem:

When BuggyPage loads, I initially get the correct value for the title. Whenever it is displayed after that, even though I can see in the debugger that BuggyTitle is getting updated correctly, the change does not appear in the page.

Question:

Why don't updates to BuggyTitle get reflected in the page?

Edit 1:

To further describe the weirdness, I added a Label to my ContentPage, with x:Name="BuggyLabel" and Text="{Binding BuggyLabelText}".
In my code-behind, I added this:

var binding_context = (BindingContext as BuggyViewModel);
if (binding_context != null)
{
    BuggyLabel.Text = binding_context.BuggyLabelText;
}

I set a breakpoint at BuggyLabel.Text =. It gets hit every time the page loads, and BuggyLabel.Text already seems to have the correct value (i.e, whatever binding_context.BuggyLabelText is set to). However, the actual page displayed only ever shows what the text in this label is initially set to.

And yes, have clean/built about a million times.

Edit 2 (further weirdness):

I put this in the code-behind so that it runs during page load:

var binding_context = (BindingContext as BuggyViewModel);
if (binding_context != null)
{
    Device.BeginInvokeOnMainThread(() =>
    {
        binding_context.RefreshTitleCommand.Execute(null);
    });
}

This again changes values in the debugger, but these changes don't get reflected in the displayed page.

I then added a button to the page and bound it to RefreshTitleCommand, and wham! the page updates its display.

Unfortunately I can't use this. Not only is it incredibly hackish, I can't have the user pressing buttons to have the page display what it's meant to on load.

I wonder if there's some caching going on with MvvmCross or Xamarin.

Body:
 Answer

You need to add RaisePropertyChanged in BuggyTitle property declaration.

ViewModel

namespace MyProject
{
    [ImplementPropertyChanged]
    public class BuggyViewModel : MvxViewModel
    {
        private Random _random;

        string  _BuggyTitle { get; set; }

        public string BuggyTitle
        {
            get { return _BuggyTitle; }
            set { _BuggyTitle = value; RaisePropertyChanged(() => BuggyTitle); }
        }

        public BuggyViewModel()
        {
            _random = new Random();
        }

        public override void Start()
        {
            base.Start();
            BuggyTitle = "" + _random.Next(1000);
        }
    }
}

-----New Update------

Code behind code

var binding_context = (BindingContext as BuggyViewModel);
if (binding_context != null)
{
    Device.BeginInvokeOnMainThread(() =>
    {
        BuggyLabel.Text = binding_context.BuggyLabelText;
    });
}