问:
Issue trying to find a control inside a MasterPage
I am trying to change the DATA attribute in an html
 tag using C# in the code-behind file for an asp.page.

This is my HTML Code

```<code><div class="tile page-content" id="fullTextArticle"
                    data-ID=""
                    data-permission="" runat="server">
</div>
</code>```

This is my c# in the code-behind file

```<code>private void DisplayFullTextArticle()
        {

            string contentID = "";

            if (Context.Request.QueryString["contentID"] != null)//check for a value in the query string
            {
                contentID = Context.Request.QueryString["contentID"];

                try
                {

                    //define connection string
                    string connString = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

                    using (SqlConnection conn = new SqlConnection(connString))//create connection object
                    {

                        SqlCommand cmd = new SqlCommand("spDisplayFullTextArticle", conn);

                        cmd.CommandType = CommandType.StoredProcedure;

                        conn.Open();

                        cmd.Parameters.Add("@ID", SqlDbType.Int).Value = Convert.ToInt32(contentID);

                        SqlDataReader myReader = cmd.ExecuteReader();

                        HtmlControl divDataID = FindControl(id: "fullTextArticle") as HtmlControl;

                        while (myReader.Read())
                        {
                            divDataID.Attributes["class"]= myReader["ID"].ToString();

                        }

                        myReader.Close();

                        //}//end using statement for SqlCommmand Object

                    }//end using statement for SQLConnection

                }//end try block

                catch (Exception ex)
                {

                } //end catch block

            }//end if statement

}
</code>```

Some context: My method gets a value from the query string and passes the value to a stored procedure which runs a SELECT query to pull full text content from a SQL database. I used break points to do some debugging and I can see the query string does pass the value to the procedure and it runs the query successfully. The trouble is that my HtmlControl variable, divDataID, ends up being null. So the ID value is not being set, so the
 attribute is not being set in the browser.

Does anyone know what I'm doing wrong? How do I set the data-ID attribute from the code-behind file?

答:
When you use Master pages finding controls is trickier. You should do something like this:

```<code>var divDataID = Master.FindControl("ContentPlaceHolder").FindControl(id: "fullTextArticle") as HtmlControl;
</code>```

Where "ContentPlaceHolder" is the ContentPlaceHolder ID in the master page.

Body:
I am trying to change the DATA attribute in an html
 tag using C# in the code-behind file for an asp.page.

This is my HTML Code

This is my c# in the code-behind file

private void DisplayFullTextArticle()
        {

            string contentID = "";

            if (Context.Request.QueryString["contentID"] != null)//check for a value in the query string
            {
                contentID = Context.Request.QueryString["contentID"];

                try
                {

                    //define connection string
                    string connString = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

                    using (SqlConnection conn = new SqlConnection(connString))//create connection object
                    {

                        SqlCommand cmd = new SqlCommand("spDisplayFullTextArticle", conn);

                        cmd.CommandType = CommandType.StoredProcedure;

                        conn.Open();

                        cmd.Parameters.Add("@ID", SqlDbType.Int).Value = Convert.ToInt32(contentID);

                        SqlDataReader myReader = cmd.ExecuteReader();

                        HtmlControl divDataID = FindControl(id: "fullTextArticle") as HtmlControl;

                        while (myReader.Read())
                        {
                            divDataID.Attributes["class"]= myReader["ID"].ToString();

                        }

                        myReader.Close();

                        //}//end using statement for SqlCommmand Object

                    }//end using statement for SQLConnection

                }//end try block

                catch (Exception ex)
                {

                } //end catch block

            }//end if statement

}

Some context: My method gets a value from the query string and passes the value to a stored procedure which runs a SELECT query to pull full text content from a SQL database. I used break points to do some debugging and I can see the query string does pass the value to the procedure and it runs the query successfully. The trouble is that my HtmlControl variable, divDataID, ends up being null. So the ID value is not being set, so the
 attribute is not being set in the browser.

Does anyone know what I'm doing wrong? How do I set the data-ID attribute from the code-behind file?

Body:
When you use Master pages finding controls is trickier. You should do something like this:

var divDataID = Master.FindControl("ContentPlaceHolder").FindControl(id: "fullTextArticle") as HtmlControl;

Where "ContentPlaceHolder" is the ContentPlaceHolder ID in the master page.


来源: stackexchange

问:
iteritems: match k value lower/upper and white space
I am using a dictionary in Python 2.7.

Below is the code:

```<code>d = {}
with open('input') as f:
    for line in f:
        if ":" not in line:
            continue
        key, value = line.strip().split(":", 1)
        d[key] = value

for k, v in d.iteritems():
    if k == 'items':
</code>```

In input file they mention some times "items" like below:

```<code>items:
Items:
ITEMS:
     Items  :
</code>```

I want to match all of above in my code that is Now I am using

```<code>k == "items":
</code>```

This does not work if "items" in upper case or has whitespaces.

Please help to fix my script.

答:
Redefine k to lowercase and remove whitespace with</p>

```<code>k = k.lower().strip()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using a dictionary in Python 2.7.

Below is the code:

d = {}
with open('input') as f:
    for line in f:
        if ":" not in line:
            continue
        key, value = line.strip().split(":", 1)
        d[key] = value

for k, v in d.iteritems():
    if k == 'items':

In input file they mention some times "items" like below:

items:
Items:
ITEMS:
     Items  :

I want to match all of above in my code that is Now I am using

k == "items":

This does not work if "items" in upper case or has whitespaces.

Please help to fix my script.

Body:
Redefine k to lowercase and remove whitespace with

k = k.lower().strip()


问:
Why REST API method name important? Because I can use any of those method to perform CRUD operation
In REST full API has some method name like (GET, PUT, POST etc.) for some specific operation (CRUD)
But I can perform any operation using any of the methods

Example for DB operations:

I can create or insert a new document or delete or update using GET
 method.

I can post or update or delete using POST method.

I can delete or update or delete using PUT method.

the same way I can use any of this method to perform DB (CRUD) operation

So, Why need this method to specify when we call any rest full API?

答:
It's a convention based on HTTP standard. REST is built on top of convention over configuration paradigm. That is, a set of conventions avoid a lot of boilerplate and configuration.

For example, HTTP 1.1 standard says:

GET: The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process

POST: The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line [...].

...and so on.


问:
SQL: how to alter column size
What SQL statement will resize a column in an Access MDB database?</p>

答:
Example for MySQL on how to change size of a column named baz in table bar in database foo to 20 characters.

```<code>ALTER TABLE `foo`.`bar` MODIFY COLUMN `baz` VARCHAR(20)
</code>```

Check the SQL manual for the exact syntax for your database.

MySQL ALTER manual

Edit: This is for MS ACCESS 2007:

```<code>ALTER TABLE Employees ALTER COLUMN Salary CHAR(20);
</code>```

Got this example from Microsoft

ContentLicense: CC BY-SA 2.5

Title: SQL: how to alter column size

Body:
Example for MySQL on how to change size of a column named baz in table bar in database foo to 20 characters.

ALTER TABLE `foo`.`bar` MODIFY COLUMN `baz` VARCHAR(20)

Check the SQL manual for the exact syntax for your database.

MySQL ALTER manual

Edit: This is for MS ACCESS 2007:

ALTER TABLE Employees ALTER COLUMN Salary CHAR(20);

Got this example from Microsoft


问:
How to display images in Word generated from HTML?
I'm currently creating a Word document by generating HTML and changing the header information to display as a .doc file.  It's a poor man's method, but it works just fine (until now).

I was just asked to include an image in the file.  My best idea was to base64 embed the image.  This works fine in a browser, however Word just gives me a box with an X in it.

Suggestions on how I can embed an image into this file and have it display in Microsoft Word?

答: I just achieved this by printing the DOCX to PDF then using Acrobat to Save As to HTML.  Images showed up small, but there.</p>


问:
TensorFlow Spark-pyspark rdd transformation return RuntimeError: maximum recursion depth exceeded
I'm tryng to use pyspark to execute TensorFlow in a collection of images but I'm getting this error when I applied a transformation in an RDD.
The error is inside the function run_inference_on_image
I've got the error using "local" and "spark://master.spark.tfm:7077"

This is the trace of the error:

```<code>/usr/bin/python2.7 /home/utad/PycharmProjects/TensorFlowMirFlickr/ClasificacionImagenes.py
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
17/06/04 00:47:16 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
('Model already downloaded:', '/home/utad/TFM/model/inception-2015-12-05.tgz', posix.stat_result(st_mode=33204, st_ino=709599, st_dev=2049, st_nlink=1, st_uid=1000, st_gid=1000, st_size=88931400, st_atime=1496482158, st_mtime=1496482158, st_ctime=1496482158))
('rddImagenes: ', [['http://host.images.tfm:8000/mirflickr/im1.jpg'], ['http://host.images.tfm:8000/mirflickr/im10.jpg'], ['http://host.images.tfm:8000/mirflickr/im100.jpg']])
17/06/04 00:47:24 ERROR executor.Executor: Exception in task 0.0 in stage 1.0 (TID 1)
org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/opt/spark/python/lib/pyspark.zip/pyspark/worker.py", line 163, in main
    func, profiler, deserializer, serializer = read_command(pickleSer, infile)
  File "/opt/spark/python/lib/pyspark.zip/pyspark/worker.py", line 54, in read_command
    command = serializer._read_with_length(file)
  File "/opt/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 169, in _read_with_length
    return self.loads(obj)
  File "/opt/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 454, in loads
    return pickle.loads(obj)
  File "/home/utad/.local/lib/python2.7/site-packages/six.py", line 118, in __getattr__
    _module = self._resolve()
  File "/home/utad/.local/lib/python2.7/site-packages/six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "/home/utad/.local/lib/python2.7/site-packages/six.py", line 118, in __getattr__
    _module = self._resolve()
  File "/home/utad/.local/lib/python2.7/site-packages/six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "/home/utad/.local/lib/python2.7/site-packages/six.py", line 118, in __getattr__
    _module = self._resolve()
...
...
...
  File "/home/utad/.local/lib/python2.7/site-packages/six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "/home/utad/.local/lib/python2.7/site-packages/six.py", line 118, in __getattr__
    _module = self._resolve()
  File "/home/utad/.local/lib/python2.7/site-packages/six.py", line 115, in _resolve
    return _import_module(self.mod)
RuntimeError: maximum recursion depth exceeded

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:193)
    at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:234)
    at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:152)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:63)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:322)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)
</code>```

Launched with spark-submit gives me this Driver stacktrace

```<code>Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1435)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1423)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1422)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1422)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:802)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1650)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1605)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1594)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:628)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1925)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1938)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1951)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1965)
    at org.apache.spark.rdd.RDD$$anonfun$collect$1.apply(RDD.scala:936)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:362)
    at org.apache.spark.rdd.RDD.collect(RDD.scala:935)
    at org.apache.spark.api.python.PythonRDD$.collectAndServe(PythonRDD.scala:453)
    at org.apache.spark.api.python.PythonRDD.collectAndServe(PythonRDD.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:280)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:214)
    at java.lang.Thread.run(Thread.java:748)
</code>```

And my code:

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Módulos a usar
from pyspark import SparkContext
import os.path
from six.moves import urllib
import tarfile
import tensorflow as tf
import re
import numpy as np

# **************************************************************************************
# Configuración proceso
# Modelo lo bajamos de la red y lo guardamos en directorio local
MODEL_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'
model_dir = '/home/utad/TFM/model'

# Simulamos que las imagenes las obtenermos de un servicio web
IMAGES_INDEX_URL = 'http://host.images.tfm:8000/mirflickr/'

# Otros datos
numero_imagenes_proceso = 3  # Número total de imágenes a procesar
lote_size = 1  # Número de imágenes por lote
max_etiquetas = 5  # Número máximo de etiquetas por imagen

# Fin Configuración proceso
# **************************************************************************************

# Obtenemos modelo
def get_tensorflow_model():
    # Download and extract model tar file
    filename = MODEL_URL.split('/')[-1]
    filepath = os.path.join(model_dir, filename)
    if not os.path.exists(filepath):
        filepath2, _ = urllib.request.urlretrieve(MODEL_URL, filepath)
        print("filepath2", filepath2)
        statinfo = os.stat(filepath)
        print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.')
        tarfile.open(filepath, 'r:gz').extractall(model_dir)
    else:
        print('Model already downloaded:', filepath, os.stat(filepath))

# Obtenida de classify_image.py del github de TensorFlow
class NodeLookup(object):
    """Converts integer node IDs to human readable labels."""

    def __init__(self, label_lookup_path=None, uid_lookup_path=None):
        if not label_lookup_path:
            label_lookup_path = os.path.join(
                model_dir, 'imagenet_2012_challenge_label_map_proto.pbtxt')
        if not uid_lookup_path:
            uid_lookup_path = os.path.join(
                model_dir, 'imagenet_synset_to_human_label_map.txt')
            self.node_lookup = self.load(label_lookup_path, uid_lookup_path)

    def load(self, label_lookup_path, uid_lookup_path):
        """Loads a human readable English name for each softmax node.

        Args:
            label_lookup_path: string UID to integer node ID.
            uid_lookup_path: string UID to human-readable string.

        Returns:
            dict from integer node ID to human-readable string.
        """
        if not tf.gfile.Exists(uid_lookup_path):
            tf.logging.fatal('File does not exist %s', uid_lookup_path)
        if not tf.gfile.Exists(label_lookup_path):
            tf.logging.fatal('File does not exist %s', label_lookup_path)

        # Loads mapping from string UID to human-readable string
        proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()
        uid_to_human = {}
        p = re.compile(r'[n\d]*[ \S,]*')
        for line in proto_as_ascii_lines:
            parsed_items = p.findall(line)
            uid = parsed_items[0]
            human_string = parsed_items[2]
            uid_to_human[uid] = human_string

        # Loads mapping from string UID to integer node ID.
        node_id_to_uid = {}
        proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()
        for line in proto_as_ascii:
            if line.startswith('  target_class:'):
                target_class = int(line.split(': ')[1])
            if line.startswith('  target_class_string:'):
                target_class_string = line.split(': ')[1]
                node_id_to_uid[target_class] = target_class_string[1:-2]

        # Loads the final mapping of integer node ID to human-readable string
        node_id_to_name = {}
        for key, val in node_id_to_uid.items():
            if val not in uid_to_human:
                tf.logging.fatal('Failed to locate: %s', val)
            name = uid_to_human[val]
            node_id_to_name[key] = name

        return node_id_to_name

    def id_to_string(self, node_id):
        if node_id not in self.node_lookup:
            return ''
        return self.node_lookup[node_id]

def run_inference_on_image(sess, image, lookup):
    """Hacemos inferencia sobre la imagen.

    Args:
        sess: TensorFlow Session
        image: Imagen a leer
        lookup: node lookup obtenido previamente

    Returns:
      (image ID, image URL, scores),
      where scores is a list of (human-readable node names, score) pairs
    """
    image_data = urllib.request.urlopen(image).read()
    print("Image: ", image_data)
    # Some useful tensors:
    # 'softmax:0': A tensor containing the normalized prediction across
    #   1000 labels.
    # 'pool_3:0': A tensor containing the next-to-last layer containing 2048
    #   float description of the image.
    # 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG
    #   encoding of the image.
    # Runs the softmax tensor by feeding the image_data as input to the graph.
    softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
    try:
        predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data})
        print("predictions: ", predictions)
    except:
        # Handle problems with malformed JPEG files
        return image, None
    predictions = np.squeeze(predictions)
    top_k = predictions.argsort()[-max_etiquetas:][::-1]
    print("top_k predictions: ", top_k)
    scores = []
    for node_id in top_k:
        if node_id not in lookup:
            human_string = ''
        else:
            human_string = lookup[node_id]
        score = predictions[node_id]
        scores.append((human_string, score))
    print ("tupla: ", image, scores)
    return image, scores

def apply_inference_on_batch(lote, lookup_bc):
    """Apply inference to a batch of images.

    We do not explicitly tell TensorFlow to use a GPU.
    It is able to choose between CPU and GPU based on its guess of which will be faster.
    """
    with tf.Graph().as_default() as g:
        print("Apply")
        graph_def = tf.GraphDef()
        print("Graph_def: ", graph_def)

        graph_def.ParseFromString(model_data_bc.value)
        print("Graph_def1: ", graph_def)
        _ = tf.import_graph_def(graph_def, name='')
        print("TF: ", tf)
        with tf.Session() as sess:
            print("Sesion: ", sess)
            print("Lote: ", lote)
            print("Node_lookup: ", lookup_bc)
            labeled = [run_inference_on_image(sess, image, lookup_bc.value) for image in
                       lote]
            return [tup for tup in labeled if tup[1] is not None]

# Función auxiliar para obtener el nombre de una imagen.
def obtener_nombre_imagen(x):
    return IMAGES_INDEX_URL + x.split('<')[1].split('>')[1]

# Iniciamos SparkContext
# sc = SparkContext('spark://master.spark.tfm:7077', 'TensorFlow')
sc = SparkContext('local')
get_tensorflow_model()

# Cargamos el modelo y lo distribuimos
model_path = os.path.join(model_dir, 'classify_image_graph_def.pb')
with tf.gfile.FastGFile(model_path, 'rb') as f:
    model_data = f.read()
model_data_bc = sc.broadcast(model_data)

# Distribuimos node lookup para ser utilizado en los workers
node_lookup = NodeLookup().node_lookup
node_lookup_bc = sc.broadcast(node_lookup)

# Obtenemos una lista de las imágenes a procesar y las agrupamos en lotes
imagenes = urllib.request.urlopen(IMAGES_INDEX_URL).read().split('<li>')[2:numero_imagenes_proceso+2]
lote_imagenes = [imagenes[i:i + lote_size] for i in range(0, len(imagenes), lote_size)]

# Paralelizamos los lotes de imagenes y procesamos
rddImagenes = sc.parallelize(lote_imagenes).map(lambda x: map(obtener_nombre_imagen, x))
print("rddImagenes: ", rddImagenes.collect())
imagenes_etiquetadas = rddImagenes.flatMap(lambda x: apply_inference_on_batch(x, node_lookup_bc))
# imagenes_etiquetadas = rddImagenes.flatMap(lambda x: x[0].split("/"))

l = imagenes_etiquetadas.collect()
</code>```

Please, any advice about what is going on?

Edit: I've just discovered that the problem is when calling to "image_data = urllib.request.urlopen(image).read()"

答:
I figured out, or at least I've found a workaround.

I've changed:

```<code>from six.moves import urllib
</code>```

for:

```<code>import urllib
</code>```

I don't know why urllib from six is not working, but this solves my problem.

Body:
I'm tryng to use pyspark to execute TensorFlow in a collection of images but I'm getting this error when I applied a transformation in an RDD.
The error is inside the function run_inference_on_image
I've got the error using "local" and "spark://master.spark.tfm:7077"

This is the trace of the error:

/usr/bin/python2.7 /home/utad/PycharmProjects/TensorFlowMirFlickr/ClasificacionImagenes.py
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
17/06/04 00:47:16 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
('Model already downloaded:', '/home/utad/TFM/model/inception-2015-12-05.tgz', posix.stat_result(st_mode=33204, st_ino=709599, st_dev=2049, st_nlink=1, st_uid=1000, st_gid=1000, st_size=88931400, st_atime=1496482158, st_mtime=1496482158, st_ctime=1496482158))
('rddImagenes: ', [['http://host.images.tfm:8000/mirflickr/im1.jpg'], ['http://host.images.tfm:8000/mirflickr/im10.jpg'], ['http://host.images.tfm:8000/mirflickr/im100.jpg']])
17/06/04 00:47:24 ERROR executor.Executor: Exception in task 0.0 in stage 1.0 (TID 1)
org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/opt/spark/python/lib/pyspark.zip/pyspark/worker.py", line 163, in main
    func, profiler, deserializer, serializer = read_command(pickleSer, infile)
  File "/opt/spark/python/lib/pyspark.zip/pyspark/worker.py", line 54, in read_command
    command = serializer._read_with_length(file)
  File "/opt/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 169, in _read_with_length
    return self.loads(obj)
  File "/opt/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 454, in loads
    return pickle.loads(obj)
  File "/home/utad/.local/lib/python2.7/site-packages/six.py", line 118, in __getattr__
    _module = self._resolve()
  File "/home/utad/.local/lib/python2.7/site-packages/six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "/home/utad/.local/lib/python2.7/site-packages/six.py", line 118, in __getattr__
    _module = self._resolve()
  File "/home/utad/.local/lib/python2.7/site-packages/six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "/home/utad/.local/lib/python2.7/site-packages/six.py", line 118, in __getattr__
    _module = self._resolve()
...
...
...
  File "/home/utad/.local/lib/python2.7/site-packages/six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "/home/utad/.local/lib/python2.7/site-packages/six.py", line 118, in __getattr__
    _module = self._resolve()
  File "/home/utad/.local/lib/python2.7/site-packages/six.py", line 115, in _resolve
    return _import_module(self.mod)
RuntimeError: maximum recursion depth exceeded

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:193)
    at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:234)
    at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:152)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:63)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:322)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)

Launched with spark-submit gives me this Driver stacktrace

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1435)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1423)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1422)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1422)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:802)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1650)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1605)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1594)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:628)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1925)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1938)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1951)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1965)
    at org.apache.spark.rdd.RDD$$anonfun$collect$1.apply(RDD.scala:936)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:362)
    at org.apache.spark.rdd.RDD.collect(RDD.scala:935)
    at org.apache.spark.api.python.PythonRDD$.collectAndServe(PythonRDD.scala:453)
    at org.apache.spark.api.python.PythonRDD.collectAndServe(PythonRDD.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:280)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:214)
    at java.lang.Thread.run(Thread.java:748)

And my code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Módulos a usar
from pyspark import SparkContext
import os.path
from six.moves import urllib
import tarfile
import tensorflow as tf
import re
import numpy as np

# **************************************************************************************
# Configuración proceso
# Modelo lo bajamos de la red y lo guardamos en directorio local
MODEL_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'
model_dir = '/home/utad/TFM/model'

# Simulamos que las imagenes las obtenermos de un servicio web
IMAGES_INDEX_URL = 'http://host.images.tfm:8000/mirflickr/'

# Otros datos
numero_imagenes_proceso = 3  # Número total de imágenes a procesar
lote_size = 1  # Número de imágenes por lote
max_etiquetas = 5  # Número máximo de etiquetas por imagen

# Fin Configuración proceso
# **************************************************************************************

# Obtenemos modelo
def get_tensorflow_model():
    # Download and extract model tar file
    filename = MODEL_URL.split('/')[-1]
    filepath = os.path.join(model_dir, filename)
    if not os.path.exists(filepath):
        filepath2, _ = urllib.request.urlretrieve(MODEL_URL, filepath)
        print("filepath2", filepath2)
        statinfo = os.stat(filepath)
        print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.')
        tarfile.open(filepath, 'r:gz').extractall(model_dir)
    else:
        print('Model already downloaded:', filepath, os.stat(filepath))

# Obtenida de classify_image.py del github de TensorFlow
class NodeLookup(object):
    """Converts integer node IDs to human readable labels."""

    def __init__(self, label_lookup_path=None, uid_lookup_path=None):
        if not label_lookup_path:
            label_lookup_path = os.path.join(
                model_dir, 'imagenet_2012_challenge_label_map_proto.pbtxt')
        if not uid_lookup_path:
            uid_lookup_path = os.path.join(
                model_dir, 'imagenet_synset_to_human_label_map.txt')
            self.node_lookup = self.load(label_lookup_path, uid_lookup_path)

    def load(self, label_lookup_path, uid_lookup_path):
        """Loads a human readable English name for each softmax node.

        Args:
            label_lookup_path: string UID to integer node ID.
            uid_lookup_path: string UID to human-readable string.

        Returns:
            dict from integer node ID to human-readable string.
        """
        if not tf.gfile.Exists(uid_lookup_path):
            tf.logging.fatal('File does not exist %s', uid_lookup_path)
        if not tf.gfile.Exists(label_lookup_path):
            tf.logging.fatal('File does not exist %s', label_lookup_path)

        # Loads mapping from string UID to human-readable string
        proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()
        uid_to_human = {}
        p = re.compile(r'[n\d]*[ \S,]*')
        for line in proto_as_ascii_lines:
            parsed_items = p.findall(line)
            uid = parsed_items[0]
            human_string = parsed_items[2]
            uid_to_human[uid] = human_string

        # Loads mapping from string UID to integer node ID.
        node_id_to_uid = {}
        proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()
        for line in proto_as_ascii:
            if line.startswith('  target_class:'):
                target_class = int(line.split(': ')[1])
            if line.startswith('  target_class_string:'):
                target_class_string = line.split(': ')[1]
                node_id_to_uid[target_class] = target_class_string[1:-2]

        # Loads the final mapping of integer node ID to human-readable string
        node_id_to_name = {}
        for key, val in node_id_to_uid.items():
            if val not in uid_to_human:
                tf.logging.fatal('Failed to locate: %s', val)
            name = uid_to_human[val]
            node_id_to_name[key] = name

        return node_id_to_name

    def id_to_string(self, node_id):
        if node_id not in self.node_lookup:
            return ''
        return self.node_lookup[node_id]

def run_inference_on_image(sess, image, lookup):
    """Hacemos inferencia sobre la imagen.

    Args:
        sess: TensorFlow Session
        image: Imagen a leer
        lookup: node lookup obtenido previamente

    Returns:
      (image ID, image URL, scores),
      where scores is a list of (human-readable node names, score) pairs
    """
    image_data = urllib.request.urlopen(image).read()
    print("Image: ", image_data)
    # Some useful tensors:
    # 'softmax:0': A tensor containing the normalized prediction across
    #   1000 labels.
    # 'pool_3:0': A tensor containing the next-to-last layer containing 2048
    #   float description of the image.
    # 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG
    #   encoding of the image.
    # Runs the softmax tensor by feeding the image_data as input to the graph.
    softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
    try:
        predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data})
        print("predictions: ", predictions)
    except:
        # Handle problems with malformed JPEG files
        return image, None
    predictions = np.squeeze(predictions)
    top_k = predictions.argsort()[-max_etiquetas:][::-1]
    print("top_k predictions: ", top_k)
    scores = []
    for node_id in top_k:
        if node_id not in lookup:
            human_string = ''
        else:
            human_string = lookup[node_id]
        score = predictions[node_id]
        scores.append((human_string, score))
    print ("tupla: ", image, scores)
    return image, scores

def apply_inference_on_batch(lote, lookup_bc):
    """Apply inference to a batch of images.

    We do not explicitly tell TensorFlow to use a GPU.
    It is able to choose between CPU and GPU based on its guess of which will be faster.
    """
    with tf.Graph().as_default() as g:
        print("Apply")
        graph_def = tf.GraphDef()
        print("Graph_def: ", graph_def)

        graph_def.ParseFromString(model_data_bc.value)
        print("Graph_def1: ", graph_def)
        _ = tf.import_graph_def(graph_def, name='')
        print("TF: ", tf)
        with tf.Session() as sess:
            print("Sesion: ", sess)
            print("Lote: ", lote)
            print("Node_lookup: ", lookup_bc)
            labeled = [run_inference_on_image(sess, image, lookup_bc.value) for image in
                       lote]
            return [tup for tup in labeled if tup[1] is not None]

# Función auxiliar para obtener el nombre de una imagen.
def obtener_nombre_imagen(x):
    return IMAGES_INDEX_URL + x.split('<')[1].split('>')[1]

# Iniciamos SparkContext
# sc = SparkContext('spark://master.spark.tfm:7077', 'TensorFlow')
sc = SparkContext('local')
get_tensorflow_model()

# Cargamos el modelo y lo distribuimos
model_path = os.path.join(model_dir, 'classify_image_graph_def.pb')
with tf.gfile.FastGFile(model_path, 'rb') as f:
    model_data = f.read()
model_data_bc = sc.broadcast(model_data)

# Distribuimos node lookup para ser utilizado en los workers
node_lookup = NodeLookup().node_lookup
node_lookup_bc = sc.broadcast(node_lookup)

# Obtenemos una lista de las imágenes a procesar y las agrupamos en lotes
imagenes = urllib.request.urlopen(IMAGES_INDEX_URL).read().split('
')[2:numero_imagenes_proceso+2]
lote_imagenes = [imagenes[i:i + lote_size] for i in range(0, len(imagenes), lote_size)]

# Paralelizamos los lotes de imagenes y procesamos
rddImagenes = sc.parallelize(lote_imagenes).map(lambda x: map(obtener_nombre_imagen, x))
print("rddImagenes: ", rddImagenes.collect())
imagenes_etiquetadas = rddImagenes.flatMap(lambda x: apply_inference_on_batch(x, node_lookup_bc))
# imagenes_etiquetadas = rddImagenes.flatMap(lambda x: x[0].split("/"))

l = imagenes_etiquetadas.collect()

Please, any advice about what is going on?

Edit: I've just discovered that the problem is when calling to "image_data = urllib.request.urlopen(image).read()"

Body:
I figured out, or at least I've found a workaround.

I've changed:

from six.moves import urllib

for:

import urllib

I don't know why urllib from six is not working, but this solves my problem.


问:
Is it possible to retrieve the user token in an app, after migrating an app from swift to react native?
We have an existing app written in Swift where the logged in user has their oAuth token stored in the app.

The app is now being redeveloped in React Native. If we release the app as a new version of the app in the App Store, when a user upgrades and installs the new version, can we get hold of the user token even though the app is completely differently architected?

答: Application will be "the same" until you update app id regardless of technology. So you can access all data saved by native application. Where are you keeping this token?</p>


问:
Sorting MySQL results in PHP...?
I have a page on my site that lists a bunch of products, each with a user rating. I use one query to pull some data points for each product ("details query"), and a second query that returns the average user rating for each product ("ratings query").

I want to append the user rating for each product onto the "details query" result set, then sort by rating in descending order. I've read a bunch of entries on Stack Overflow, php.net etc. and I think I need to use usort() with a custom function, but every time I pass my MySQL result to usort() I get a php error saying the object I'm passing to usort() isn't an array. For example, I've tried:

```<code>$data = mysql_fetch_array($details_query);
usort($data,"compare");
</code>```

Doing the above will throw an error saying $data isn't an array. What am I doing wrong?

Also, if anyone has any other suggestions on how to get this done I'd really appreciate. I'm having a really tough time with this for some reason...

Thanks!

答:
mysql_fetch_array retrieves a single row from the database result set into an indexed and associative array.

It does not give you an array containing every row in the result set. You still need to loop to get all the rows:

```<code>while ($row = mysql_fetch_array($details_query)) {
    $data[] = $row;
}
</code>```

Now you can define and use your comparison function to sort by each entry of $data's rating property, or whatever you need to do.

Title: Sorting MySQL results in PHP...?

Body:
I have a page on my site that lists a bunch of products, each with a user rating. I use one query to pull some data points for each product ("details query"), and a second query that returns the average user rating for each product ("ratings query").

I want to append the user rating for each product onto the "details query" result set, then sort by rating in descending order. I've read a bunch of entries on Stack Overflow, php.net etc. and I think I need to use usort() with a custom function, but every time I pass my MySQL result to usort() I get a php error saying the object I'm passing to usort() isn't an array. For example, I've tried:

$data = mysql_fetch_array($details_query);
usort($data,"compare");

Doing the above will throw an error saying $data isn't an array. What am I doing wrong?

Also, if anyone has any other suggestions on how to get this done I'd really appreciate. I'm having a really tough time with this for some reason...

Thanks!

Body:
mysql_fetch_array retrieves a single row from the database result set into an indexed and associative array.

It does not give you an array containing every row in the result set. You still need to loop to get all the rows:

while ($row = mysql_fetch_array($details_query)) {
    $data[] = $row;
}

Now you can define and use your comparison function to sort by each entry of $data's rating property, or whatever you need to do.


问:
How to add multiple numbers using a method in java?
I have a PHP function for adding multiple numbers,

```<code>function add(...$numbers) {
  $sum = 0;
  $ad = array();
  foreach ($numbers as $n) {
      $sum += $n;
      $ad[] = $n;
  }
  $ret = "Sum of ".implode(" , ", $ad)." is ".$sum;
  return $ret;
}
</code>```

what I want is how to convert this PHP function into java method,
THANK YOU VERY MUCH to those who will answer my question.

答:
you can pass value to be sum as an array or var args.</p>

```<code>public int add(int... nums) {
        int sum = 0;
        for (int num : nums) {
            sum = sum + num;
        }
        return sum;
    }
</code>```

Body:
I have a PHP function for adding multiple numbers,

function add(...$numbers) {
  $sum = 0;
  $ad = array();
  foreach ($numbers as $n) {
      $sum += $n;
      $ad[] = $n;
  }
  $ret = "Sum of ".implode(" , ", $ad)." is ".$sum;
  return $ret;
}

what I want is how to convert this PHP function into java method,
THANK YOU VERY MUCH to those who will answer my question.

Body:
you can pass value to be sum as an array or var args.

public int add(int... nums) {
        int sum = 0;
        for (int num : nums) {
            sum = sum + num;
        }
        return sum;
    }


答:
I suppose your problem is with variable number of arguments. Java does support it, see this example:

```<code>package com.javapapers.corejava;

public class VarArgSample {

  static int sum(int i, int... marks) {
    int total = 0;
    for (int mark : marks) {
      total = total + mark;
    }
    return total;
  }

  public static void main(String[] args) {

    //invoking with variable arguments
    System.out.println(sum(1, 2, 3));

    //same invocation using an array
    int arr[] = {2,3};
    System.out.println(sum(1, arr));
  }
}
</code>```

This examples comes from: http://javapapers.com/core-java/java-variable-arguments/

Title: How to add multiple numbers using a method in java?

Body:
I suppose your problem is with variable number of arguments. Java does support it, see this example:

package com.javapapers.corejava;

public class VarArgSample {

  static int sum(int i, int... marks) {
    int total = 0;
    for (int mark : marks) {
      total = total + mark;
    }
    return total;
  }

  public static void main(String[] args) {

    //invoking with variable arguments
    System.out.println(sum(1, 2, 3));

    //same invocation using an array
    int arr[] = {2,3};
    System.out.println(sum(1, arr));
  }
}

This examples comes from: http://javapapers.com/core-java/java-variable-arguments/


问:
Comparing values of cells in a column with ComboBox value input by user
I am not able to compare the values of a cells in a column with combobox value input.

I have 2 workbooks tests(contains ComboBox2) and test1(contains a column whose cells are compared with ComboBox2.value)

I have a for loop to achieve this.

```<code>For i = 1 To LastRow

    If wkbSource.Worksheets(sheet_no).Cells(i, 1) = ComboBox2.Value Then
         'do something
    End If
Next i
</code>```

I have debugged the code and I understood that if statement doesn't execute even after a match.

How can I fix it ?

EDIT  :

Also I would like to know how you can add two cell values because directly adding it is showing incorrect output.
For example

wkbSource.Worksheets(sheet_no).Cells(i, 1) + wkbSource.Worksheets(sheet_no).Cells(i, 3)

答:
This was due (once again) to the Variant Comparison Curse. See in particular the "UPDATE 4" of that question.

```<code>If wkbSource.Worksheets(sheet_no).Cells(i, 1) = ComboBox2.Value Then
</code>```

This compares two Variants. But, when the cell contains a number, and is not explictly formatted as Text, not preceded by ' when entered. Excel will consider it as a number and so it's .Value will be a number Variant. On the other hand, Combobox2.Value retuned a text Variant, so the comparison failed!

When comparing two Variant variables, these operations will fail:

```<code>  2 = "2"    ' False
  3 > "2"    ' False
</code>```

Therefore, the solution in your particular situation is to force comparing texts, using the .Text properties of the control and the cell. Here's how you would - for example - sum up cells that match your query:

```<code>For i = 1 To LastRow
  If Trim(wkbSource.Worksheets(sheet_no).Cells(i, 1).Text) =  Trim(ComboBox2.Text) Then
     'do something
      if IsNumeric(wkbSource.Worksheets(sheet_no).Cells(i, 1).Value2) Then _
        mySum = mySum + wkbSource.Worksheets(sheet_no).Cells(i, 1).Value2
  End If
Next i
</code>```

Body:
I am not able to compare the values of a cells in a column with combobox value input.

I have 2 workbooks tests(contains ComboBox2) and test1(contains a column whose cells are compared with ComboBox2.value)

I have a for loop to achieve this.

For i = 1 To LastRow

    If wkbSource.Worksheets(sheet_no).Cells(i, 1) = ComboBox2.Value Then
         'do something
    End If
Next i

I have debugged the code and I understood that if statement doesn't execute even after a match.

How can I fix it ?

EDIT  :

Also I would like to know how you can add two cell values because directly adding it is showing incorrect output.
For example

wkbSource.Worksheets(sheet_no).Cells(i, 1) + wkbSource.Worksheets(sheet_no).Cells(i, 3)

Body:
This was due (once again) to the Variant Comparison Curse. See in particular the "UPDATE 4" of that question.

If wkbSource.Worksheets(sheet_no).Cells(i, 1) = ComboBox2.Value Then

This compares two Variants. But, when the cell contains a number, and is not explictly formatted as Text, not preceded by ' when entered. Excel will consider it as a number and so it's .Value will be a number Variant. On the other hand, Combobox2.Value retuned a text Variant, so the comparison failed!

When comparing two Variant variables, these operations will fail:

  2 = "2"    ' False
  3 > "2"    ' False

Therefore, the solution in your particular situation is to force comparing texts, using the .Text properties of the control and the cell. Here's how you would - for example - sum up cells that match your query:

For i = 1 To LastRow
  If Trim(wkbSource.Worksheets(sheet_no).Cells(i, 1).Text) =  Trim(ComboBox2.Text) Then
     'do something
      if IsNumeric(wkbSource.Worksheets(sheet_no).Cells(i, 1).Value2) Then _
        mySum = mySum + wkbSource.Worksheets(sheet_no).Cells(i, 1).Value2
  End If
Next i


问:
Android studio Dangerous permission
I'm trying to change my system/phone brightness through my application. For this I need to ask for permission ("dangerous permission"). I'm not quiet sure if I've done the correct way but this doesn't seem work as it always returns permission denied.

```<code>public void switches() {
            if (systemBrightness) {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.WRITE_SETTINGS},
                        1);
                Toast.makeText(this, "Changed to system brightness: changing the “system brightness” is permanent", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Changed to screen brightness: ", Toast.LENGTH_SHORT).show();
            }
        }

public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {

                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }
</code>```

//Mani fest

```<code><uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />

  public void changeScreenBrightness(float brightness) {
        mBrightness = brightness;
        if (systemBrightness) {
            if (!Settings.System.canWrite(this)) {
                Intent i = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                startActivity(i);
            } else {
                Settings.System.putInt(mContentResolver, Settings.System.SCREEN_BRIGHTNESS, (int) (mBrightness * 255)* preset);
            }
        } else {
            WindowManager.LayoutParams mLayoutParams = mWindow.getAttributes();
            mLayoutParams.screenBrightness = mBrightness * preset;
            mWindow.setAttributes(mLayoutParams);
        }
    }
</code>```

答:
Asking for dangerous permission is handled differently than vulnerable permissions. You need to use Settings.System.canWrite(Context) method to check if you can do that. And if not send appropriate Intent to the system by calling startActivityForResult:

```<code>public boolean checkWriteSettingsPermission() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return true;
    }
    if (!Settings.System.canWrite(getContext())) {
        Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
            Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, REQUEST_CODE);
        return false;
    } else {
        return true;
    }
}
</code>```

Everything written in the documentation

Title: Android studio Dangerous permission

Body:
I'm trying to change my system/phone brightness through my application. For this I need to ask for permission ("dangerous permission"). I'm not quiet sure if I've done the correct way but this doesn't seem work as it always returns permission denied.

public void switches() {
            if (systemBrightness) {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.WRITE_SETTINGS},
                        1);
                Toast.makeText(this, "Changed to system brightness: changing the “system brightness” is permanent", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Changed to screen brightness: ", Toast.LENGTH_SHORT).show();
            }
        }

public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {

                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

//Mani fest

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />

  public void changeScreenBrightness(float brightness) {
        mBrightness = brightness;
        if (systemBrightness) {
            if (!Settings.System.canWrite(this)) {
                Intent i = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                startActivity(i);
            } else {
                Settings.System.putInt(mContentResolver, Settings.System.SCREEN_BRIGHTNESS, (int) (mBrightness * 255)* preset);
            }
        } else {
            WindowManager.LayoutParams mLayoutParams = mWindow.getAttributes();
            mLayoutParams.screenBrightness = mBrightness * preset;
            mWindow.setAttributes(mLayoutParams);
        }
    }

Body:
Asking for dangerous permission is handled differently than vulnerable permissions. You need to use Settings.System.canWrite(Context) method to check if you can do that. And if not send appropriate Intent to the system by calling startActivityForResult:

public boolean checkWriteSettingsPermission() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return true;
    }
    if (!Settings.System.canWrite(getContext())) {
        Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
            Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, REQUEST_CODE);
        return false;
    } else {
        return true;
    }
}

Everything written in the documentation


问:
VSTO Add-in + Open XML
I would like to develop some add-in. This add-in should use open xml (not everything is doable using VSTO + Open XML is much faster), BUT is there any possibility to edit opened document? For example I have opened PowerPoint presentation (or Word doc/Excel spreadsheet)  and I would like to replace some text using Open XML, can I read it (from that what I read, reading is possible) and update without closing that file, using Open XML of course? If yes, how to do it?

There is some feeddata() method, memory streams, but I do not know how to use it. Could anyone show some example?

答:
```<code>        var fileFullName = Globals.ThisAddIn.Application.ActiveDocument.FullName;

        Globals.ThisAddIn.Application.ActiveDocument.Close(WdSaveOptions.wdSaveChanges, WdOriginalFormat.wdOriginalDocumentFormat, true);

        //edit document using OpenXml here

        Globals.ThisAddIn.Application.Documents.Open(fileFullName);
</code>```

This works for Word documents.

Title: VSTO Add-in + Open XML

Body:
        var fileFullName = Globals.ThisAddIn.Application.ActiveDocument.FullName;

        Globals.ThisAddIn.Application.ActiveDocument.Close(WdSaveOptions.wdSaveChanges, WdOriginalFormat.wdOriginalDocumentFormat, true);

        //edit document using OpenXml here

        Globals.ThisAddIn.Application.Documents.Open(fileFullName);

This works for Word documents.


问:
Registering singledispatch function in dynamically imported modules
I'm trying to register additional functions from dynamically imported modules to a singledispatch function.

main.py

```<code>from importlib import import_module
from functools import singledispatch

@singledispatch
def handle(a):
    return 'default'

def import_something():
    other_module = import_module('dynimp')
    handle_result = handle(1)
    assert handle_result == 'int', f'Error: {handle_result}'

if __name__ == '__main__':
    import_something()
</code>```

dynimp.py

```<code>from main import handle

@handle.register(int)
def handle_int(a):
    return 'int'
</code>```

The assertion in import_something fails, I get 'default', not 'int'.

I've investigated a bit further. The function object is somehow copied when imported in dynimp. If I set a breakpoint after other_module = import_module('dynimp'), other_module.handle != handle and while other_module.registry shows handle_int as registered, handle.registry does not.

A solution that works is to have a register function in dynimp.py, and pass it handle:

```<code>def do_register(handle_fn):
    handle_fn.register(int, handle_int)
</code>```

and then add other_module.do_register(handle) in the import_something function.

My question is: what happens when we import a decorated function, and why doesn't this work ?

答:
This happens because import main creates a new instance of your main file. An easy way to confirm this is the following code:

```<code>>>> sys.modules['main'] == sys.modules['__main__']
False
</code>```

One solution would be to change from main import handle to from __main__ import handle. (Note that this relies on the main.py file being the file that starts the program.) Another workaround would be to set sys.modules['main'] = sys.modules['__main__'] before you import dynimp.

Body:
I'm trying to register additional functions from dynamically imported modules to a singledispatch function.

main.py

from importlib import import_module
from functools import singledispatch

@singledispatch
def handle(a):
    return 'default'

def import_something():
    other_module = import_module('dynimp')
    handle_result = handle(1)
    assert handle_result == 'int', f'Error: {handle_result}'

if __name__ == '__main__':
    import_something()

dynimp.py

from main import handle

@handle.register(int)
def handle_int(a):
    return 'int'

The assertion in import_something fails, I get 'default', not 'int'.

I've investigated a bit further. The function object is somehow copied when imported in dynimp. If I set a breakpoint after other_module = import_module('dynimp'), other_module.handle != handle and while other_module.registry shows handle_int as registered, handle.registry does not.

A solution that works is to have a register function in dynimp.py, and pass it handle:

def do_register(handle_fn):
    handle_fn.register(int, handle_int)

and then add other_module.do_register(handle) in the import_something function.

My question is: what happens when we import a decorated function, and why doesn't this work ?

Body:
This happens because import main creates a new instance of your main file. An easy way to confirm this is the following code:

>>> sys.modules['main'] == sys.modules['__main__']
False

One solution would be to change from main import handle to from __main__ import handle. (Note that this relies on the main.py file being the file that starts the program.) Another workaround would be to set sys.modules['main'] = sys.modules['__main__'] before you import dynimp.


问:
parfor doesn't consider information about vectors which are used in it
This is a part of my code in Matlab. I tried to make it parallel but there is an error:

```<code> The variable gax in a parfor cannot be classified.
</code>```

I know why the error occurs. because I should tell Matlab that v is an incresing vector which doesn't contain repeated elements. Could anyone help me to use this information to parallelize the code?

```<code>v=[1,3,6,8];
ggx=5.*ones(15,14);
gax=ones(15,14);
for m=v
if m > 1
    parfor j=1:m-1
        gax(j,m-1) = ggx(j,m-1);
    end
end
if m<nn
    parfor jo=m+1:15
        gax(jo,m) = ggx(jo,m);
    end
end
end
</code>```

答:
Optimizing a code should be closely related to its purpose, especially when you use parfor. The code you wrote in the question can be written in a much more efficient way, and definitely, do not need to be parallelized.

However, I understand that you tried to simplify the problem, just to get the idea of how to slice your variables, so here is a fixed version the can run with parfor. But this is surely not the way to write this code:

```<code>v = [1,3,6,8];
ggx = 5.*ones(15,14);
gax = ones(15,14);
nn = 5;
for m = v
    if m > 1
        temp_end = m-1;
        temp = ggx(:,temp_end);
        parfor ja = 1:temp_end
            gax(ja,temp_end) = temp(ja);
        end
    end
    if m < nn
        temp = ggx(:,m);
        parfor jo = m+1:15
            gax(jo,m) = temp(jo);
        end
    end
end
</code>```

A vectorized implementation will look like this:

```<code>v = [1,3,6,8];
ggx = 5.*ones(15,14);
gax = ones(15,14);
nn = 5;

m1 = v>1; % first condition with logical indexing
temp = v(m1)-1; % get the values from v
r = ones(1,sum(temp)); % generate a vector of indicies
r(cumsum(temp)) = -temp+1; % place the reseting locations
r = cumsum(r); % calculate the indecies
r(cumsum(temp)) = temp; % place the ending points
c = repelem(temp,temp); % create an indecies vector for the columns
inds1 = sub2ind(size(gax),r,c); % convert the indecies to linear

mnn = v<nn; % second condition with logical indexing
temp = v(mnn)+1; % get the values from v
r_max = size(gax,1); % get the height of gax
r_count = r_max-temp+1; % calculate no. of rows per value in v
r = ones(1,sum(r_count)); % generate a vector of indicies
r([1 r_count(1:end-1)+1]) = temp; % set the t indicies
r(cumsum(r_count)+1) = -(r_count-temp)+1; % place the reseting locations
r = cumsum(r(1:end-1)); % calculate the indecies
c = repelem(temp-1,r_count); % create an indecies vector for the columns
inds2 = sub2ind(size(gax),r,c); % convert the indecies to linear

gax([inds1 inds2]) = ggx([inds1 inds2]); % assgin the relevant values
</code>```

This is indeed quite complicated, and not always necessary. A good thing to remember, though, is that nested for loop are much slower than a single loop, so in some cases (depend on the size of the output), this will may be the fastest solution:

```<code>for m = v
    if m > 1
        gax(1:m-1,m-1) = ggx(1:m-1,m-1);
    end
    if m<nn
        gax(m+1:15,m) = ggx(m+1:15,m);
    end
end
</code>```

Body:
This is a part of my code in Matlab. I tried to make it parallel but there is an error:

 The variable gax in a parfor cannot be classified.

I know why the error occurs. because I should tell Matlab that v is an incresing vector which doesn't contain repeated elements. Could anyone help me to use this information to parallelize the code?

v=[1,3,6,8];
ggx=5.*ones(15,14);
gax=ones(15,14);
for m=v
if m > 1
    parfor j=1:m-1
        gax(j,m-1) = ggx(j,m-1);
    end
end
if m<nn
    parfor jo=m+1:15
        gax(jo,m) = ggx(jo,m);
    end
end
end

Body:
Optimizing a code should be closely related to its purpose, especially when you use parfor. The code you wrote in the question can be written in a much more efficient way, and definitely, do not need to be parallelized.

However, I understand that you tried to simplify the problem, just to get the idea of how to slice your variables, so here is a fixed version the can run with parfor. But this is surely not the way to write this code:

v = [1,3,6,8];
ggx = 5.*ones(15,14);
gax = ones(15,14);
nn = 5;
for m = v
    if m > 1
        temp_end = m-1;
        temp = ggx(:,temp_end);
        parfor ja = 1:temp_end
            gax(ja,temp_end) = temp(ja);
        end
    end
    if m < nn
        temp = ggx(:,m);
        parfor jo = m+1:15
            gax(jo,m) = temp(jo);
        end
    end
end

A vectorized implementation will look like this:

v = [1,3,6,8];
ggx = 5.*ones(15,14);
gax = ones(15,14);
nn = 5;

m1 = v>1; % first condition with logical indexing
temp = v(m1)-1; % get the values from v
r = ones(1,sum(temp)); % generate a vector of indicies
r(cumsum(temp)) = -temp+1; % place the reseting locations
r = cumsum(r); % calculate the indecies
r(cumsum(temp)) = temp; % place the ending points
c = repelem(temp,temp); % create an indecies vector for the columns
inds1 = sub2ind(size(gax),r,c); % convert the indecies to linear

mnn = v<nn; % second condition with logical indexing
temp = v(mnn)+1; % get the values from v
r_max = size(gax,1); % get the height of gax
r_count = r_max-temp+1; % calculate no. of rows per value in v
r = ones(1,sum(r_count)); % generate a vector of indicies
r([1 r_count(1:end-1)+1]) = temp; % set the t indicies
r(cumsum(r_count)+1) = -(r_count-temp)+1; % place the reseting locations
r = cumsum(r(1:end-1)); % calculate the indecies
c = repelem(temp-1,r_count); % create an indecies vector for the columns
inds2 = sub2ind(size(gax),r,c); % convert the indecies to linear

gax([inds1 inds2]) = ggx([inds1 inds2]); % assgin the relevant values

This is indeed quite complicated, and not always necessary. A good thing to remember, though, is that nested for loop are much slower than a single loop, so in some cases (depend on the size of the output), this will may be the fastest solution:

for m = v
    if m > 1
        gax(1:m-1,m-1) = ggx(1:m-1,m-1);
    end
    if m<nn
        gax(m+1:15,m) = ggx(m+1:15,m);
    end
end


问:
How to do one-liner if else statement?
Please see https://golangdocs.com/ternary-operator-in-golang as pointed by @accdias (see comments)

Can I write a simple if-else statement with variable assignment in go (golang) as I would do in php? For example:

```<code>$var = ( $a > $b )? $a: $b;
</code>```

Currently I have to use the following:

```<code>var c int
if a > b {
    c = a
} else {
    c = b
}
</code>```

Sorry I cannot remember the name if this control statement and I couldn't find the info in-site or through google search. :/

答:
As the others mentioned, Go does not support ternary one-liners. However, I wrote a utility function that could help you achieve what you want.

```<code>// IfThenElse evaluates a condition, if true returns the first parameter otherwise the second
func IfThenElse(condition bool, a interface{}, b interface{}) interface{} {
    if condition {
        return a
    }
    return b
}
</code>```

Here are some test cases to show how you can use it

```<code>func TestIfThenElse(t *testing.T) {
    assert.Equal(t, IfThenElse(1 == 1, "Yes", false), "Yes")
    assert.Equal(t, IfThenElse(1 != 1, nil, 1), 1)
    assert.Equal(t, IfThenElse(1 < 2, nil, "No"), nil)
}
</code>```

For fun, I wrote more useful utility functions such as:

```<code>IfThen(1 == 1, "Yes") // "Yes"
IfThen(1 != 1, "Woo") // nil
IfThen(1 < 2, "Less") // "Less"

IfThenElse(1 == 1, "Yes", false) // "Yes"
IfThenElse(1 != 1, nil, 1)       // 1
IfThenElse(1 < 2, nil, "No")     // nil

DefaultIfNil(nil, nil)  // nil
DefaultIfNil(nil, "")   // ""
DefaultIfNil("A", "B")  // "A"
DefaultIfNil(true, "B") // true
DefaultIfNil(1, false)  // 1

FirstNonNil(nil, nil)                // nil
FirstNonNil(nil, "")                 // ""
FirstNonNil("A", "B")                // "A"
FirstNonNil(true, "B")               // true
FirstNonNil(1, false)                // 1
FirstNonNil(nil, nil, nil, 10)       // 10
FirstNonNil(nil, nil, nil, nil, nil) // nil
FirstNonNil()                        // nil
</code>```

If you would like to use any of these, you can find them here https://github.com/shomali11/util

ContentLicense: CC BY-SA 4.0

Title: How to do one-liner if else statement?

Body:
Please see https://golangdocs.com/ternary-operator-in-golang as pointed by @accdias (see comments)

Can I write a simple if-else statement with variable assignment in go (golang) as I would do in php? For example:

$var = ( $a > $b )? $a: $b;

Currently I have to use the following:

var c int
if a > b {
    c = a
} else {
    c = b
}

Sorry I cannot remember the name if this control statement and I couldn't find the info in-site or through google search. :/

Body:
As the others mentioned, Go does not support ternary one-liners. However, I wrote a utility function that could help you achieve what you want.

// IfThenElse evaluates a condition, if true returns the first parameter otherwise the second
func IfThenElse(condition bool, a interface{}, b interface{}) interface{} {
    if condition {
        return a
    }
    return b
}

Here are some test cases to show how you can use it

func TestIfThenElse(t *testing.T) {
    assert.Equal(t, IfThenElse(1 == 1, "Yes", false), "Yes")
    assert.Equal(t, IfThenElse(1 != 1, nil, 1), 1)
    assert.Equal(t, IfThenElse(1 < 2, nil, "No"), nil)
}

For fun, I wrote more useful utility functions such as:

IfThen(1 == 1, "Yes") // "Yes"
IfThen(1 != 1, "Woo") // nil
IfThen(1 < 2, "Less") // "Less"

IfThenElse(1 == 1, "Yes", false) // "Yes"
IfThenElse(1 != 1, nil, 1)       // 1
IfThenElse(1 < 2, nil, "No")     // nil

DefaultIfNil(nil, nil)  // nil
DefaultIfNil(nil, "")   // ""
DefaultIfNil("A", "B")  // "A"
DefaultIfNil(true, "B") // true
DefaultIfNil(1, false)  // 1

FirstNonNil(nil, nil)                // nil
FirstNonNil(nil, "")                 // ""
FirstNonNil("A", "B")                // "A"
FirstNonNil(true, "B")               // true
FirstNonNil(1, false)                // 1
FirstNonNil(nil, nil, nil, 10)       // 10
FirstNonNil(nil, nil, nil, nil, nil) // nil
FirstNonNil()                        // nil

If you would like to use any of these, you can find them here https://github.com/shomali11/util


问:
Regex to get multiple capture groups from one generic regex
This is for JavaScript.

My Problem:

So I want a regex that can get multiple sub capture groups for a string. Right now my attempt only gets one, while I expect 3. Ideally, it should be varied in that it should be able to get 2 or 3 or more.

My attempt

let characters = {
  some: {
    test: {
      var: "hi"
    }
  }
}

let b = document.getElementById("body");
let h = b.innerHTML;
let regex = /(?:\$\{)([^.]*[.]?)*(?:\})/;
let match;
match = regex.exec(h);

console.log(match);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="body">
  ${some.test.var}
</div></code>```

What I want

let characters = {
      some: {
        test: {
          var: "hi"
        }
      }
    }

let b = document.getElementById("body");
let h = b.innerHTML;
let regex = /(?:\$\{)([^.]*)[.]([^.]*)[.]([^.]*)(?:\})/;
let match;
match = regex.exec(h);

console.log(match);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="body">
  ${some.test.var}
</div></code>```

答:
It seems you want to use a single capturing group to obtain multiple groups in the resulting array. It is not possible with JavaScript regex. See Repeating a Capturing Group vs. Capturing a Repeated Group. There will always be as many groups in the resulting array as there are capturing groups in the pattern (+1, the zeroth group containing the whole match). If you use (\w* )* it will match 0+ word chars and then a space and place it into Group 1 buffer, then, if it finds another streak of word chars and a space, the regex engine will match this text portion, replace the contents inside Group 1, and will go on searching, etc.

You need to match ${...} substrings first (there may be several options here, BTW, I suggest /\${(\w+(?:\.\w+)*)}/g to only match ${...} that have word chars and . inside, but it can also be /\${([^}]+)}/g) and then split with .:

const regex = /\${(\w+(?:\.\w+)*)}/g;
const str = `\${some.test.var} \${some.test.var.more.here}`;
let m;

while (m = regex.exec(str)) {
  console.log(m[1].split('.'));
}```

Note you have the whole match value in m[0].

Pattern details:

\${ - a ${ literal substring

(\w+(?:\.\w+)*) - Group 1 capturing:

\w+ - 1 or more word chars

(?:\.\w+)* - zero or more sequences of:

\. - a dot

\w+  - 1 or more word chars

} -  a literal }

If you want to simplify the pattern, use /\${([.\w]+)}/g or /\${([^}]+)}/g.

Body:
This is for JavaScript.

My Problem:

So I want a regex that can get multiple sub capture groups for a string. Right now my attempt only gets one, while I expect 3. Ideally, it should be varied in that it should be able to get 2 or 3 or more.

My attempt

let characters = {
  some: {
    test: {
      var: "hi"
    }
  }
}

let b = document.getElementById("body");
let h = b.innerHTML;
let regex = /(?:\$\{)([^.]*[.]?)*(?:\})/;
let match;
match = regex.exec(h);

console.log(match);

  ${some.test.var}

What I want

let characters = {
      some: {
        test: {
          var: "hi"
        }
      }
    }

let b = document.getElementById("body");
let h = b.innerHTML;
let regex = /(?:\$\{)([^.]*)[.]([^.]*)[.]([^.]*)(?:\})/;
let match;
match = regex.exec(h);

console.log(match);

  ${some.test.var}

Body:
It seems you want to use a single capturing group to obtain multiple groups in the resulting array. It is not possible with JavaScript regex. See Repeating a Capturing Group vs. Capturing a Repeated Group. There will always be as many groups in the resulting array as there are capturing groups in the pattern (+1, the zeroth group containing the whole match). If you use (\w* )* it will match 0+ word chars and then a space and place it into Group 1 buffer, then, if it finds another streak of word chars and a space, the regex engine will match this text portion, replace the contents inside Group 1, and will go on searching, etc.

You need to match ${...} substrings first (there may be several options here, BTW, I suggest /\${(\w+(?:\.\w+)*)}/g to only match ${...} that have word chars and . inside, but it can also be /\${([^}]+)}/g) and then split with .:

const regex = /\${(\w+(?:\.\w+)*)}/g;
const str = `\${some.test.var} \${some.test.var.more.here}`;
let m;

while (m = regex.exec(str)) {
  console.log(m[1].split('.'));
}

Note you have the whole match value in m[0].

Pattern details:

\${ - a ${ literal substring

(\w+(?:\.\w+)*) - Group 1 capturing:

\w+ - 1 or more word chars

(?:\.\w+)* - zero or more sequences of:

\. - a dot

\w+  - 1 or more word chars

} -  a literal }

If you want to simplify the pattern, use /\${([.\w]+)}/g or /\${([^}]+)}/g.


问:
Getting encoding error while writing data to csv file
```<code>from tweetpy import *
import re
import json
from pprint import pprint
import csv

# Import the necessary methods from "twitter" library
from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream

# Variables that contains the user credentials to access Twitter API
ACCESS_TOKEN =  ''
ACCESS_SECRET = ''
CONSUMER_KEY = ''
CONSUMER_SECRET = ''

oauth = OAuth(ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY, CONSUMER_SECRET)

# Initiate the connection to Twitter Streaming API
twitter_stream = TwitterStream(auth=oauth)

# Get a sample of the public data following through Twitter
iterator = twitter_stream.statuses.filter(track="#kindle",language="en",replies="all")
 # Print each tweet in the stream to the screen

 # Here we set it to stop after getting 10000000 tweets.
 # You don't have to set it to stop, but can continue running
 # the Twitter API to collect data for days or even longer.

tweet_count = 10000000

file = "C:\\Users\\WELCOME\\Desktop\\twitterfeeds.csv"
with open(file,"w") as csvfile:
    fieldnames=['Username','Tweet','Timezone','Timestamp','Location']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for tweet in iterator:
        #pprint(tweet)
        username = str(tweet['user']['screen_name'])
        tweet_text = str(tweet['text'])
        user_timezone = str(tweet['user']['time_zone'])
        tweet_timestamp=str(tweet['created_at'])
        user_location = str(tweet['user']['location'])
        print tweet
        tweet_count -= 1
        writer.writerow({'Username':username,'Tweet':tweet_text,'Timezone':user_timezone,'Location':user_location,'Timestamp':tweet_timestamp})

        if tweet_count <= 0:
            break
</code>```

I am trying to write tweets to to csv file with columns 'username', 'Tweet', 'Timezone', 'Location', and 'Timestamp'.

But I am getting the following error:

tweet_text = str(tweet['text'])
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' in position 139: ordinal not in range(128).
```

I know it is encoding issue but I dont know the exact position of the variable to encode.

答:
If you really want to transform all your unicode data</p>

```<code>tweet['text'].encode("ascii", "replace")
or
tweet['text'].encode("ascii", "ignore") # if you want skip char
</code>```

Body:
from tweetpy import *
import re
import json
from pprint import pprint
import csv

# Import the necessary methods from "twitter" library
from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream

# Variables that contains the user credentials to access Twitter API
ACCESS_TOKEN =  ''
ACCESS_SECRET = ''
CONSUMER_KEY = ''
CONSUMER_SECRET = ''

oauth = OAuth(ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY, CONSUMER_SECRET)

# Initiate the connection to Twitter Streaming API
twitter_stream = TwitterStream(auth=oauth)

# Get a sample of the public data following through Twitter
iterator = twitter_stream.statuses.filter(track="#kindle",language="en",replies="all")
 # Print each tweet in the stream to the screen

 # Here we set it to stop after getting 10000000 tweets.
 # You don't have to set it to stop, but can continue running
 # the Twitter API to collect data for days or even longer.

tweet_count = 10000000

file = "C:\\Users\\WELCOME\\Desktop\\twitterfeeds.csv"
with open(file,"w") as csvfile:
    fieldnames=['Username','Tweet','Timezone','Timestamp','Location']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for tweet in iterator:
        #pprint(tweet)
        username = str(tweet['user']['screen_name'])
        tweet_text = str(tweet['text'])
        user_timezone = str(tweet['user']['time_zone'])
        tweet_timestamp=str(tweet['created_at'])
        user_location = str(tweet['user']['location'])
        print tweet
        tweet_count -= 1
        writer.writerow({'Username':username,'Tweet':tweet_text,'Timezone':user_timezone,'Location':user_location,'Timestamp':tweet_timestamp})

        if tweet_count <= 0:
            break

I am trying to write tweets to to csv file with columns 'username', 'Tweet', 'Timezone', 'Location', and 'Timestamp'.

But I am getting the following error:

tweet_text = str(tweet['text'])
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' in position 139: ordinal not in range(128).

I know it is encoding issue but I dont know the exact position of the variable to encode.

Body:
If you really want to transform all your unicode data

tweet['text'].encode("ascii", "replace")
or
tweet['text'].encode("ascii", "ignore") # if you want skip char


问:
Assigning name attributes to objects in WPF application
We create test automation for a WPF application based on the objects and the names of the objects. We don't have access to the WPF source code. Not all name attributes are filled, which makes test automation difficult.

Is there a way to assign name attributes to objects from the outside, without having access to the source code in any way? I know this is almost certain impossible to do, but I want to make sure I don't overlook a solution here, as it would make our test automation effort so much easier.

答:
I don't know any way to change the name attributes.
But maybe you can use some other means of identifying the objects.

We use for our UI Tests the TestStack.White Framework, which allows to get an object based on different criterias, like the ID, the name, by type, class name etc. Maybe this could help you circumvent your problem.

In order to figure out these attributes we use the UIAVerify Tool and Inspect.exe from Microsoft.


问:
Rails not indexing locations
So I tried to add this code to first the views and then the controller. It didn't work and gave me an error : undefined method save for 4:Fixnum.

Code:

```<code><% unless location.user.interests.blank? %>
  <% @merged_array = location.user.interests.split(',').uniq +
                       current_user.interests.split(',').uniq %>
  <% location.score = @merged_array.length - @merged_array.uniq.length %>
  <% location.score.save %>
<% else %>
  <% location.score = 0 %>
  <% location.score.save %>
<% end %>
</code>```

But then I removed it from both controller and views..... Now the index page isn't showing the locations at all I checked and the show page is working and records still exist

答: Sorry forgot that it only displays locations within a 50 mile radius and i was travelling...... Silly me :)</p>

Title: Rails not indexing locations

Body:
So I tried to add this code to first the views and then the controller. It didn't work and gave me an error : undefined method save for 4:Fixnum.

Code:

<% unless location.user.interests.blank? %>
  <% @merged_array = location.user.interests.split(',').uniq +
                       current_user.interests.split(',').uniq %>
  <% location.score = @merged_array.length - @merged_array.uniq.length %>
  <% location.score.save %>
<% else %>
  <% location.score = 0 %>
  <% location.score.save %>
<% end %>

But then I removed it from both controller and views..... Now the index page isn't showing the locations at all I checked and the show page is working and records still exist


问:
Files vs Database for Lua on iPhone
I have an iPhone app I'm writing which uses Lua. My question is in regards to the Lua routines. Should I keep them in an SQLite database, or a file.

I am leaning towards database because of the following perceived benefits:

1. I open the database once only, whereas with a file I have to reopen each time I want that routine. This makes it faster?

2. Easier to transfer/save the routines as they are all in one file

3. Neater file structure.

Anyone faced the same situation before?

答:
I open the database once only, whereas with a file I have to reopen each time I want that routine. This makes it faster?

Why are you discarding the routine in the first place? Once you've loaded your script(s) into a Lua state, there's no need to hit the file system again, unless a script calls dofile/loadfile/etc., right?

Easier to transfer/save the routines as they are all in one file

But to read/write the scripts within that file you need to execute SQL statements, right? Seems like it would be a pain in the butt, rather than make anything easier.

Neater file structure.

If you're going to use dofile/loadfile/require in your scripts, you'll need to hook them to look in the database instead.

Is this question prompted by a performance problem you're having, or is it a hypothetical? I'm a big fan of keeping it simple, so I wouldn't do anything like this unless you need to and it produces a measurable performance gain (I don't imagine it would).

Title: Files vs Database for Lua on iPhone


问:
populate imageview with item selected from spinner
I want to be able to populate the imageview when an item is selected from the spinner! i have tried to implement onitemselectedlistener but could not get the code to work correctly so looking for help!

```<code>public class MainActivity extends AppCompatActivity {

Context context = this;
MediaPlayer mp;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayList<ItemData> list = new ArrayList<>();
    list.add(new ItemData("Blue", R.drawable.blue));
    list.add(new ItemData("Green", R.drawable.green));
    list.add(new ItemData("Orange", R.drawable.orange));
    list.add(new ItemData("Pink", R.drawable.pink));
    list.add(new ItemData("Yellow", R.drawable.yel));

    Spinner sp = (Spinner) findViewById(R.id.spinner);
    SpinnerAdapter adapter = new SpinnerAdapter(this,
            R.layout.spinner_layout, R.id.txt, list);
    sp.setAdapter(adapter);

    mp = MediaPlayer.create(context, R.raw.sound);

    ImageView myView = (ImageView) findViewById(R.id.mainimage);

    myView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            try {
                if (mp.isPlaying()) {
                    mp.stop();
                    mp.release();
                    mp = MediaPlayer.create(context, R.raw.sound);
                }
                mp.start();
            } catch (Exception e) {
                e.printStackTrace();
            }

            ImageView myView = (ImageView) findViewById(R.id.mainimage);
            Animation a = new RotateAnimation(0.0f, 360.0f,
                    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                    0.5f);
            a.setInterpolator(new LinearInterpolator());
            a.setRepeatCount(-1);
            a.setDuration(500);
            a.setFillAfter(true);
            a.setRepeatCount(7);
            myView.startAnimation(a);

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

}

```<code>public class ItemData {

String text;
Integer imageId;
public ItemData(String text, Integer imageId){
    this.text=text;
    this.imageId=imageId;
}

public String getText(){
    return text;
}

public Integer getImageId(){
    return imageId;
}
</code>```

}

答:
If you want to show the color when you clicked on an item..</p>

```<code>    sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            ItemData data = sp.getSelectedItem();
            int res = data.getImageId();  //change Integer type to int  if error exists
            myView.setImageDrawable(getResources().getDrawable(res));
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
</code>```

Body:
I want to be able to populate the imageview when an item is selected from the spinner! i have tried to implement onitemselectedlistener but could not get the code to work correctly so looking for help!

public class MainActivity extends AppCompatActivity {

Context context = this;
MediaPlayer mp;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayList<ItemData> list = new ArrayList<>();
    list.add(new ItemData("Blue", R.drawable.blue));
    list.add(new ItemData("Green", R.drawable.green));
    list.add(new ItemData("Orange", R.drawable.orange));
    list.add(new ItemData("Pink", R.drawable.pink));
    list.add(new ItemData("Yellow", R.drawable.yel));

    Spinner sp = (Spinner) findViewById(R.id.spinner);
    SpinnerAdapter adapter = new SpinnerAdapter(this,
            R.layout.spinner_layout, R.id.txt, list);
    sp.setAdapter(adapter);

    mp = MediaPlayer.create(context, R.raw.sound);

    ImageView myView = (ImageView) findViewById(R.id.mainimage);

    myView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            try {
                if (mp.isPlaying()) {
                    mp.stop();
                    mp.release();
                    mp = MediaPlayer.create(context, R.raw.sound);
                }
                mp.start();
            } catch (Exception e) {
                e.printStackTrace();
            }

            ImageView myView = (ImageView) findViewById(R.id.mainimage);
            Animation a = new RotateAnimation(0.0f, 360.0f,
                    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                    0.5f);
            a.setInterpolator(new LinearInterpolator());
            a.setRepeatCount(-1);
            a.setDuration(500);
            a.setFillAfter(true);
            a.setRepeatCount(7);
            myView.startAnimation(a);

        }
    });
}

}

public class ItemData {

String text;
Integer imageId;
public ItemData(String text, Integer imageId){
    this.text=text;
    this.imageId=imageId;
}

public String getText(){
    return text;
}

public Integer getImageId(){
    return imageId;
}

}

Body:
If you want to show the color when you clicked on an item..

    sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            ItemData data = sp.getSelectedItem();
            int res = data.getImageId();  //change Integer type to int  if error exists
            myView.setImageDrawable(getResources().getDrawable(res));
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });


问:
PHP Undefined $_POST index
this might be a stupid question, but I'm doing simple form for editing data in database in PHP, but I can't figure out, where is mistake, it only keeps telling me, that I have undefined index

```<code><table>
     <tr>

                 <td><input type="text" name="first"></td>
                 <td><input type="text" name="sur"></td>
     </tr>
     <tr>
                 <td><input type="submit" name="edit" value="Firstname":</td>
                 <td><input type="submit" name="edit" value="Surname"></td>
     </tr>
</code>```

```<code><?php

                  if($_POST['edit']=='Firstname')
                  {
                      $firstchange=$_POST['first'];

                  }
                  elseif($_POST['edit']=='Surname')
                  {
                      $surchange=$_POST['sur'];
                  }
</code>```

?>

Notice: Undefined index: edit in edit.php on line 177

Notice: Undefined index: edit in edit.php on line 183

This happens when I open the page. And I'm dissapointed I couldn't find what's wrong.

答:
You will get this error every time the page is visited unless it is via a <form method="post"> with an input of ?edit=x&first=x&sur=x.

$_POST is an array of all the inputs in a form submitted to that url via a post. It is empty if you visit the page normally (with a GET).

Title: PHP Undefined $_POST index

Body:
this might be a stupid question, but I'm doing simple form for editing data in database in PHP, but I can't figure out, where is mistake, it only keeps telling me, that I have undefined index

                 <input type="text" name="first">
                 <input type="text" name="sur">

                 <input type="submit" name="edit" value="Firstname":
                 <input type="submit" name="edit" value="Surname">

<?php

                  if($_POST['edit']=='Firstname')
                  {
                      $firstchange=$_POST['first'];

                  }
                  elseif($_POST['edit']=='Surname')
                  {
                      $surchange=$_POST['sur'];
                  }

?>

Notice: Undefined index: edit in edit.php on line 177

Notice: Undefined index: edit in edit.php on line 183

This happens when I open the page. And I'm dissapointed I couldn't find what's wrong.


问:
What causes Invalid address specified to RtlValidateHeap
When I run my program it throws error:

```<code>invalid address specified to RtlValidateHeap( 00530000, 00A39B18 )
</code>```

I think it's because of realloc but I can't understand why. And I must use malloc, realloc and free instead of new and delete.
My .h file:

```<code>#pragma once

class String
{
private:
    char* mas;
    int n;
public:
    String();
    void EmptyStr();
    void print();
    void operator = (char* str);
    void operator = (const String &a);
    String operator+ (char* str);
    String operator + (const String &a);
    void operator += (char*);
    void operator += (const String &a);
    char &operator [] (int i);
};
</code>```

My .cpp file:

```<code>#include"Strings.h"
#include<stdlib.h>
#include<iostream>

String::String()
{
    this->mas = NULL;
    this->n = 0;
}

void String::print()
{
    std::cout << this->mas << ' ' << this->n << std::endl;
}

void String::EmptyStr()
{
    this->mas = (char*)realloc(this->mas, sizeof(char));
    this->n = 0;
    this->mas[0] = '\0';
}

void String::operator =(char* str)
{
    this->n = strlen(str);
    this->mas = (char*)realloc(this->mas, (this->n + 1) * sizeof(char));
    this->mas = str;
}

void String::operator=(const String &a)
{
    this->mas = (char*)realloc(this->mas, (a.n + 1)* sizeof(char));
    this->n = a.n;
    *this = a.mas;
}

String String::operator+(char* str)
{
    String tmp;
    tmp.mas = (char*)malloc((this->n + strlen(str)+1) * sizeof(char));
    tmp.n = this->n + strlen(str);
    tmp.mas[0] = '\0';
    strcat(tmp.mas, this->mas);
    strcat(tmp.mas, str);
    return tmp;
}

String String::operator+(const String &a)
{
    String tmp;
    tmp.mas = (char*)malloc((this->n + a.n + 1) * sizeof(char));
    tmp.n = this->n + a.n;
    tmp = *this + a.mas;
    return tmp;
}

void String::operator+=(char* str)
{
    *this = *this + str;
}
</code>```

And my main .cpp file

```<code>#include"Strings.h"
#include <iostream>

int main()
{
    String a, b, c;
    a = "Hello";
    b = "ASD";
    b = a;
    b.print();

    system("PAUSE");
}
</code>```

I really can't understand what is wrong, so I hope you can help me.

答:
The problem is here:

```<code>this->mas = (char*)realloc(this->mas, (this->n + 1) * sizeof(char));
this->mas = str;
</code>```

The first line allocates memory, and makes mas point to that newly allocated memory. The second line makes mas point somewhere else completely. Here you should not just assign the pointer to point somewhere else, but copy the string using e.g. strcpy.

With the code you have now, when you do

```<code>b = "ASD";
</code>```

you make b.mas point to the first character in the string literal. Then when you do

```<code>b = a;
</code>```

you use the pointer to the string literal in the realloc call, which is wrong since you have not allocated that memory through malloc or realloc.

On another note, you should never assign right back to the pointer you passed to realloc. If realloc fails and returns a null pointer, you lose the original pointer and will have a memory leak.

Body:
When I run my program it throws error:

invalid address specified to RtlValidateHeap( 00530000, 00A39B18 )

I think it's because of realloc but I can't understand why. And I must use malloc, realloc and free instead of new and delete.
My .h file:

#pragma once

class String
{
private:
    char* mas;
    int n;
public:
    String();
    void EmptyStr();
    void print();
    void operator = (char* str);
    void operator = (const String &a);
    String operator+ (char* str);
    String operator + (const String &a);
    void operator += (char*);
    void operator += (const String &a);
    char &operator [] (int i);
};

My .cpp file:

#include"Strings.h"
#include<stdlib.h>
#include<iostream>

String::String()
{
    this->mas = NULL;
    this->n = 0;
}

void String::print()
{
    std::cout << this->mas << ' ' << this->n << std::endl;
}

void String::EmptyStr()
{
    this->mas = (char*)realloc(this->mas, sizeof(char));
    this->n = 0;
    this->mas[0] = '\0';
}

void String::operator =(char* str)
{
    this->n = strlen(str);
    this->mas = (char*)realloc(this->mas, (this->n + 1) * sizeof(char));
    this->mas = str;
}

void String::operator=(const String &a)
{
    this->mas = (char*)realloc(this->mas, (a.n + 1)* sizeof(char));
    this->n = a.n;
    *this = a.mas;
}

String String::operator+(char* str)
{
    String tmp;
    tmp.mas = (char*)malloc((this->n + strlen(str)+1) * sizeof(char));
    tmp.n = this->n + strlen(str);
    tmp.mas[0] = '\0';
    strcat(tmp.mas, this->mas);
    strcat(tmp.mas, str);
    return tmp;
}

String String::operator+(const String &a)
{
    String tmp;
    tmp.mas = (char*)malloc((this->n + a.n + 1) * sizeof(char));
    tmp.n = this->n + a.n;
    tmp = *this + a.mas;
    return tmp;
}

void String::operator+=(char* str)
{
    *this = *this + str;
}

And my main .cpp file

#include"Strings.h"
#include <iostream>

int main()
{
    String a, b, c;
    a = "Hello";
    b = "ASD";
    b = a;
    b.print();

    system("PAUSE");
}

I really can't understand what is wrong, so I hope you can help me.

Body:
The problem is here:

this->mas = (char*)realloc(this->mas, (this->n + 1) * sizeof(char));
this->mas = str;

The first line allocates memory, and makes mas point to that newly allocated memory. The second line makes mas point somewhere else completely. Here you should not just assign the pointer to point somewhere else, but copy the string using e.g. strcpy.

With the code you have now, when you do

b = "ASD";

you make b.mas point to the first character in the string literal. Then when you do

b = a;

you use the pointer to the string literal in the realloc call, which is wrong since you have not allocated that memory through malloc or realloc.

On another note, you should never assign right back to the pointer you passed to realloc. If realloc fails and returns a null pointer, you lose the original pointer and will have a memory leak.