问:
Preprocessing function of inception v3 in Keras
This is preprocessing function of inception v3 in Keras. It is totally different from other models preprocessing.

```<code>def preprocess_input(x):
    x /= 255.
    x -= 0.5
    x *= 2.
    return x
</code>```

1. Why there is no mean subtraction?

2. Why there is no RGB to BGR?

3. Mapping between [-1,1] is normal for this model?

and this is preprocessing function of VGG and ResNet in Keras:

```<code>def preprocess_input(x, data_format=None):
    if data_format is None:
        data_format = K.image_data_format()
    assert data_format in {'channels_last', 'channels_first'}

    if data_format == 'channels_first':
        # 'RGB'->'BGR'
        x = x[:, ::-1, :, :]
        # Zero-center by mean pixel

        x[:, 0, :, :] -= 103.939
        x[:, 1, :, :] -= 116.779
        x[:, 2, :, :] -= 123.68
    else:
        # 'RGB'->'BGR'
        x = x[:, :, :, ::-1]
        # Zero-center by mean pixel
        x[:, :, :, 0] -= 103.939
        x[:, :, :, 1] -= 116.779
        x[:, :, :, 2] -= 123.68
    return x
</code>```

Also Caffe models use mean subtraction and RGB to BGR.

答:
The Inception model has been trained using the preprocess function that you quoted. Therefore your images have to run through that function rather than the one for VGG/ResNet. Subtracting the mean is not required. See also this thread: https://github.com/fchollet/keras/issues/5416.

The original GoogleNet Paper refers to RGB images rather than BGR. VGG on the other hand was trained using Caffe, and Caffe uses OpenCV to load images which uses BGR by default.

Yes. See also this thread and Marcins answer: Should I substract imagenet pretrained inception_v3 model mean value at inception_v3.py keras?

Body:
This is preprocessing function of inception v3 in Keras. It is totally different from other models preprocessing.

def preprocess_input(x):
    x /= 255.
    x -= 0.5
    x *= 2.
    return x

1. Why there is no mean subtraction?

2. Why there is no RGB to BGR?

3. Mapping between [-1,1] is normal for this model?

and this is preprocessing function of VGG and ResNet in Keras:

def preprocess_input(x, data_format=None):
    if data_format is None:
        data_format = K.image_data_format()
    assert data_format in {'channels_last', 'channels_first'}

    if data_format == 'channels_first':
        # 'RGB'->'BGR'
        x = x[:, ::-1, :, :]
        # Zero-center by mean pixel

        x[:, 0, :, :] -= 103.939
        x[:, 1, :, :] -= 116.779
        x[:, 2, :, :] -= 123.68
    else:
        # 'RGB'->'BGR'
        x = x[:, :, :, ::-1]
        # Zero-center by mean pixel
        x[:, :, :, 0] -= 103.939
        x[:, :, :, 1] -= 116.779
        x[:, :, :, 2] -= 123.68
    return x

Also Caffe models use mean subtraction and RGB to BGR.


来源: stackexchange

问:
Unable to download tzdbgen jar
I want to download this file tzdbgen-1.0.1.jar. But I get this message:

```<code>You do not have access to this repository.
Return to the previous page or go back to your dashboard.
</code>```

when I try to download it from https://github.com/akashche/tzdbgen . How can I download the jar?

答:
Reached out to the repo owner at github and now the jar is made available at :
https://github.com/akashche/tzdbgen/releases .</p>

ContentLicense: CC BY-SA 3.0

Title: Unable to download tzdbgen jar

Body:
I want to download this file tzdbgen-1.0.1.jar. But I get this message:

You do not have access to this repository.
Return to the previous page or go back to your dashboard.

when I try to download it from https://github.com/akashche/tzdbgen . How can I download the jar?


问:
How to link jenkins pipeline job to label on docker slaves containers
I'm looking for a way to run Jenkins jobs/build inside Jenkins slaves, dynamically (on-demand) started by docker. The scenario is the following:

I have one physical slave (node name: jenkins-slave-01 and label: mySlave) which I can easily trigger jobs to it by using this code on my jenkins pipeline script:

```<code>node ('jenkins-slave-01') {
stage ('Checkout and compile') {
   //code ommited
}
...
//other stages ommited }
</code>```

Using docker plugin, I have docker images configured as docker templates with labels 'docker-slave-01, docker-slave-02, etc'. What I want is to use this images as docker slave for some pipeline jobs, but in this kind of job, the option to link this job to this label (Restrict where this project can be run and the Label expression field) is not showed.

In the job configuration, the option "Docker Container" is not enough to trigger the docker container once it triggers the physical slave.

How can I handle this in a pipeline job? Is it possible to do this?

答:
A Jenkins Pipeline job always starts on a flyweight Jenkins Master executor (just after it starts you can briefly see it pop up in the Build Executor Status overview). In your Pipeline script you define which part is executed on which agent (slave) using the node('[AGENT_NAME]') step.

Note that [AGENT_NAME] may also be a label, so if you would set up your docker agents to have the label docker-agent you can make sure your Pipeline runs on the just spawned docker agent by adding the node('docker-agent') step.

Body:
I'm looking for a way to run Jenkins jobs/build inside Jenkins slaves, dynamically (on-demand) started by docker. The scenario is the following:

I have one physical slave (node name: jenkins-slave-01 and label: mySlave) which I can easily trigger jobs to it by using this code on my jenkins pipeline script:

node ('jenkins-slave-01') {
stage ('Checkout and compile') {
   //code ommited
}
...
//other stages ommited }

Using docker plugin, I have docker images configured as docker templates with labels 'docker-slave-01, docker-slave-02, etc'. What I want is to use this images as docker slave for some pipeline jobs, but in this kind of job, the option to link this job to this label (Restrict where this project can be run and the Label expression field) is not showed.

In the job configuration, the option "Docker Container" is not enough to trigger the docker container once it triggers the physical slave.

How can I handle this in a pipeline job? Is it possible to do this?


问:
Opening a mvc application from classic asp.net application
I am having a fully developed MVC Application having login functionality using custom membership.
My client is having a classic asp.net application, must be having its own login functionality(Don't have exact details of login may be simple database user allowed to login or windows authentication)

Client application will have a button, clicking on which should redirect to my mvc app/somecontroller/someaction

I have tried normal coding as below, but app does not redirect.

```<code>protected void btnConfig_Click(object sender, EventArgs e)
        {
            string mywebUrl = System.Configuration.ConfigurationManager.AppSettings["mywebUrl"];
            //It is like localhost:9108

            /* I have tried setting cookie same way as it is set in my mvc app */

            //string cookiedata = "admin";
            //string userData = string.Empty;
            //var expiretime = DateTime.Now.Add(FormsAuthentication.Timeout);
            //FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, cookiedata, DateTime.Now, expiretime, false, userData);
            //string encTicket = FormsAuthentication.Encrypt(authTicket);
            //HttpCookie formAuthCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
            //Response.Cookies.Add(formAuthCookie);

            Response.Redirect(mywebUrl + "/Home/Index", true);
        }
</code>```

答:
This button click code is in asp.net application from where I want to open MVC Application.
I was making a very silly mistake.</p>

```<code>    protected void btnConfig_Click(object sender, EventArgs e)
    {
        Response.Redirect("http://localhost:5555" + "/Home/Index");
        // I was missing http:// in my url
    }
</code>```

Body:
I am having a fully developed MVC Application having login functionality using custom membership.
My client is having a classic asp.net application, must be having its own login functionality(Don't have exact details of login may be simple database user allowed to login or windows authentication)

Client application will have a button, clicking on which should redirect to my mvc app/somecontroller/someaction

I have tried normal coding as below, but app does not redirect.

protected void btnConfig_Click(object sender, EventArgs e)
        {
            string mywebUrl = System.Configuration.ConfigurationManager.AppSettings["mywebUrl"];
            //It is like localhost:9108

            /* I have tried setting cookie same way as it is set in my mvc app */

            //string cookiedata = "admin";
            //string userData = string.Empty;
            //var expiretime = DateTime.Now.Add(FormsAuthentication.Timeout);
            //FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, cookiedata, DateTime.Now, expiretime, false, userData);
            //string encTicket = FormsAuthentication.Encrypt(authTicket);
            //HttpCookie formAuthCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
            //Response.Cookies.Add(formAuthCookie);

            Response.Redirect(mywebUrl + "/Home/Index", true);
        }

Body:
This button click code is in asp.net application from where I want to open MVC Application.
I was making a very silly mistake.

    protected void btnConfig_Click(object sender, EventArgs e)
    {
        Response.Redirect("http://localhost:5555" + "/Home/Index");
        // I was missing http:// in my url
    }


问:
How to get text with some specific tags' text together in a tag by scrapy in python?
I am new to scrapy. I want to crawl some data from the web. I got the html document like below.

```<code><div class="user-info">
    <p class="user-img">
        something in p tag
    </p>
    <em>text</em> data I want
    <a href="#">
        something in a tag
    </a>
</div>
</code>```

I want to get the text data I want only. But the text is in the tag . So if I use div[contains(@class, "user-info")]/text(), I can get data I want only. If I use div[contains(@class, "user-info")]/node() I get all the tags inside div.user-info, and also div[contains(@class, "user-info")]/node()/text(). So the question is, how can I get the text and the data I want together to be text data I want?

答: I replace the  and  with "", and then use div[contains(@class, "user-info")]/text()

Body:
I am new to scrapy. I want to crawl some data from the web. I got the html document like below.

        something in p tag

    text data I want

        something in a tag

I want to get the text data I want only. But the text is in the tag . So if I use div[contains(@class, "user-info")]/text(), I can get data I want only. If I use div[contains(@class, "user-info")]/node() I get all the tags inside div.user-info, and also div[contains(@class, "user-info")]/node()/text(). So the question is, how can I get the text and the data I want together to be text data I want?

Body: I replace the <em> and </em> with "", and then use div[contains(@class, "user-info")]/text()


问:
Why doesn't typescript check an option argument?
Why doesn't typescript show any type errors for the following example?

```<code>function fancyMethod({ option1 = true }: { option1?: boolean } = {}) {
    console.log(option1);
}

fancyMethod("abc");
fancyMethod(false);
fancyMethod(42);
</code>```

Try it yourself using this Playground Link

答:
You can force TypeScript to accept only objects by merging your type with object type:

```<code>function fancyMethod({ option1 = true }: { option1?: boolean } & object = {}) {
    console.log(option1);
}

fancyMethod("abc");
fancyMethod(false);
fancyMethod(42);
fancyMethod({}); // no error
</code>```

Body:
Why doesn't typescript show any type errors for the following example?

function fancyMethod({ option1 = true }: { option1?: boolean } = {}) {
    console.log(option1);
}

fancyMethod("abc");
fancyMethod(false);
fancyMethod(42);

Try it yourself using this Playground Link

Body:
You can force TypeScript to accept only objects by merging your type with object type:

function fancyMethod({ option1 = true }: { option1?: boolean } & object = {}) {
    console.log(option1);
}

fancyMethod("abc");
fancyMethod(false);
fancyMethod(42);
fancyMethod({}); // no error


问:
What is the best way to match elements by index for update in a Scatter plot?
Using d3.v3.min.js and the example D3 Zoomable Plot as reference I built a scatter plot. The most relevant bits are:

```<code>var svg = d3.select("#scatter1")
    .append("svg")
    .attr("width", outerWidth)
    .attr("height", outerHeight)
    .attr("viewBox", "0 0 " + (width + margin.left + margin.right) + " " + (height + margin.top + margin.bottom))
    .attr("preserveAspectRatio", "xMidYMid meet")
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")

var objects = svg.append("svg")
    .classed("objects", true)
    .attr("width", width)
    .attr("height", height);

objects.selectAll(".dot")
    .data(values)
    .enter().append("circle")
    .classed("dot", true)
    .attr("r", function (d) {
        return 6 * Math.sqrt(2.0 / Math.PI);
    })
    .attr("transform", transform)
    .style("fill", colorVal);
</code>```

and some needed css:

```<code>.dot {
  fill-opacity: .5;
}

.dotHidden {
  fill-opacity: .1;
}
</code>```

My data values are defined as:

```<code>var values = [[x0, y0], [x1, y1], ....];
</code>```

with a custom property idx per element i.e.

```<code>values[i].idx === i
</code>```

Now I'd like to highlight only a subset of the dot elements, namely only those that are in an indexes list e.g. selectedIdx = [4, 8, 10, 38, 90]. How can I do that in the fastest possible way? is there an d3 js idiomatic way to do it? I have attempted to do this below and it does the job to "hide" all the dots but I actually want to hide only the ones not in the selectedIdx.

```<code>d3.select("#scatter1 svg")
  .selectAll("circle")
  .attr("class", "dotHidden");
</code>```

UPDATE: This is a follow up of the question How to get the index of the data element in a histogram on mouseover?

答:
Once you have the selected data (not the indexes) you can use data binding capabilities of d3.js, in particular selection.exit():

```<code>d3.select("#scatter1 svg")
  .selectAll("circle")
  // make sure to reset all circles to normal
  .classed("dotHidden", false);
  .data(selectedValues)
  // narrow selection to values that are not in selectedValues
  .exit()
  .classed("dotHidden", true);
</code>```

Body:
Using d3.v3.min.js and the example D3 Zoomable Plot as reference I built a scatter plot. The most relevant bits are:

var svg = d3.select("#scatter1")
    .append("svg")
    .attr("width", outerWidth)
    .attr("height", outerHeight)
    .attr("viewBox", "0 0 " + (width + margin.left + margin.right) + " " + (height + margin.top + margin.bottom))
    .attr("preserveAspectRatio", "xMidYMid meet")
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")

var objects = svg.append("svg")
    .classed("objects", true)
    .attr("width", width)
    .attr("height", height);

objects.selectAll(".dot")
    .data(values)
    .enter().append("circle")
    .classed("dot", true)
    .attr("r", function (d) {
        return 6 * Math.sqrt(2.0 / Math.PI);
    })
    .attr("transform", transform)
    .style("fill", colorVal);

and some needed css:

.dot {
  fill-opacity: .5;
}

.dotHidden {
  fill-opacity: .1;
}

My data values are defined as:

var values = [[x0, y0], [x1, y1], ....];

with a custom property idx per element i.e.

values[i].idx === i

Now I'd like to highlight only a subset of the dot elements, namely only those that are in an indexes list e.g. selectedIdx = [4, 8, 10, 38, 90]. How can I do that in the fastest possible way? is there an d3 js idiomatic way to do it? I have attempted to do this below and it does the job to "hide" all the dots but I actually want to hide only the ones not in the selectedIdx.

d3.select("#scatter1 svg")
  .selectAll("circle")
  .attr("class", "dotHidden");

UPDATE: This is a follow up of the question How to get the index of the data element in a histogram on mouseover?

Body:
Once you have the selected data (not the indexes) you can use data binding capabilities of d3.js, in particular selection.exit():

d3.select("#scatter1 svg")
  .selectAll("circle")
  // make sure to reset all circles to normal
  .classed("dotHidden", false);
  .data(selectedValues)
  // narrow selection to values that are not in selectedValues
  .exit()
  .classed("dotHidden", true);


问:
Can't save file with .json extension
when I am trying to save my file as .txt or .xml the file created on my device but when I am trying to save it as .json the file never created.
This is how I call my method </p>

```<code>  String test = "test";
  String fileName = "kyriakos.txt";
  saveDataToFile(AnswerQ1, fileName);

public void saveDataToFile(String answer, String fileName) {

   Log.d("Checks", "Trying to save data");

   try {
        // Set up the file directory
        String filePath = Environment.getExternalStorageDirectory().toString() + "/Data Folder";
        File fileDirectory = new File(filePath);
        fileDirectory.mkdirs();
        Log.d("Checks", "Directory created");

       // Set up the file itself
        File textFile = new File(fileDirectory, fileName);
        textFile.createNewFile();
        Log.d("Checks", "File created");

       // Write to the file
        FileOutputStream fileOutputStream = new FileOutputStream(textFile,true);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
        outputStreamWriter.append("  " +"\"fcov\":" +"  "+ "\""+answer+"\","  +  "\n" );
        outputStreamWriter.close();
        fileOutputStream.close();

       Toast.makeText(getApplicationContext(), "Done writing to SD card", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
    }}
</code>```

答: You can store your json in ShredPreference as a string</p>

Title: Can't save file with .json extension

Body:
when I am trying to save my file as .txt or .xml the file created on my device but when I am trying to save it as .json the file never created.
This is how I call my method

  String test = "test";
  String fileName = "kyriakos.txt";
  saveDataToFile(AnswerQ1, fileName);

public void saveDataToFile(String answer, String fileName) {

   Log.d("Checks", "Trying to save data");

   try {
        // Set up the file directory
        String filePath = Environment.getExternalStorageDirectory().toString() + "/Data Folder";
        File fileDirectory = new File(filePath);
        fileDirectory.mkdirs();
        Log.d("Checks", "Directory created");

       // Set up the file itself
        File textFile = new File(fileDirectory, fileName);
        textFile.createNewFile();
        Log.d("Checks", "File created");

       // Write to the file
        FileOutputStream fileOutputStream = new FileOutputStream(textFile,true);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
        outputStreamWriter.append("  " +"\"fcov\":" +"  "+ "\""+answer+"\","  +  "\n" );
        outputStreamWriter.close();
        fileOutputStream.close();

       Toast.makeText(getApplicationContext(), "Done writing to SD card", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
    }}


问:
Kivy. Strange view on android
On Android(only) device all widgets are situated on left-bottom corner and have small sizes.I tried use size_hint and pos_hint and FloatLayout, but there is no results.What's wrong?

This is .kv file

```<code>#:kivy 1.0.0
#:import win kivy.core.window

Widget:

    Label:
        id:TopLabel
        text:'Eye verification app'
        width: self.texture_size[0] + dp(40)
        height: '48dp'
        pos: 40,40
        bold:True
        color:1,0,0,1

    Button:
        id:registrateButton
        on_release:

            app.take_picture('registrate')
        text: 'Registrate'
        width: self.texture_size[0] + dp(40)
        height: '48dp'
        pos: 40,160
</code>```

答:
This is how your app looks like on my PC:

And this is how it looks on my Android device:

I'm guessing that's still too small for you, here's a way to make the buttons bigger:

```<code>from kivy.base import runTouchApp
from kivy.lang import Builder

runTouchApp(Builder.load_string('''
#:kivy 1.0.0
#:import win kivy.core.window

FloatLayout:

    Label:
        id:TopLabel
        text:'Eye verification app'

        size_hint: 0.8, 0.2 # to react to the screen's size
        pos_hint: {"top": 0.4, "center_x": 0.5} # to place where we want it on the screen

        bold:True
        color:1,0,0,1

    Button:
        id:registrateButton
        on_release:
            app.take_picture('registrate')

        size_hint: 0.8, 0.2 # the same as previous
        pos_hint: {"top": 0.7, "center_x": 0.5} # top is a little lower

        text: 'Registrate'
'''))
</code>```

Here's how it looks now:

On Android:

Title: Kivy. Strange view on android

Body:
On Android(only) device all widgets are situated on left-bottom corner and have small sizes.I tried use size_hint and pos_hint and FloatLayout, but there is no results.What's wrong?

This is .kv file

#:kivy 1.0.0
#:import win kivy.core.window

Widget:

    Label:
        id:TopLabel
        text:'Eye verification app'
        width: self.texture_size[0] + dp(40)
        height: '48dp'
        pos: 40,40
        bold:True
        color:1,0,0,1

    Button:
        id:registrateButton
        on_release:

            app.take_picture('registrate')
        text: 'Registrate'
        width: self.texture_size[0] + dp(40)
        height: '48dp'
        pos: 40,160

Body:
This is how your app looks like on my PC:

And this is how it looks on my Android device:

I'm guessing that's still too small for you, here's a way to make the buttons bigger:

from kivy.base import runTouchApp
from kivy.lang import Builder

runTouchApp(Builder.load_string('''
#:kivy 1.0.0
#:import win kivy.core.window

FloatLayout:

    Label:
        id:TopLabel
        text:'Eye verification app'

        size_hint: 0.8, 0.2 # to react to the screen's size
        pos_hint: {"top": 0.4, "center_x": 0.5} # to place where we want it on the screen

        bold:True
        color:1,0,0,1

    Button:
        id:registrateButton
        on_release:
            app.take_picture('registrate')

        size_hint: 0.8, 0.2 # the same as previous
        pos_hint: {"top": 0.7, "center_x": 0.5} # top is a little lower

        text: 'Registrate'
'''))

Here's how it looks now:

On Android:


问:
iOS - UITableViewCell, UIAlertController
Good day to all. Faced a problem. I need to make a table with a button and by clicking on the button I get a alert with the number of the cell. The table cells themselves are not active. That's how I realized it. When I scroll the table in the beginning everything is fine, when you press the button, a alert is displayed with the correct line number, but  after 4 elements an error appears.

This error appears in the line where I'm working with the 4 tag.
Fatal error: unexpectedly found nil while unwrapping an Optional value

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as UITableViewCell

    if (tableView.tag == 1) {
        let numLabel: UILabel = tableView.viewWithTag(3) as! UILabel
        numLabel.text = String(indexPath.row)
    } else if (tableView.tag == 2) {

        //Error appears here
        let numButton: UIButton = tableView.viewWithTag(4) as! UIButton
        numButton.setTitle(String(indexPath.row), for: .normal)

        numButton.tag = indexPath.row
    }

    return cell
}

@IBAction func showAlertForRow(row: UIButton) {
    let alert = UIAlertController(title:"Test work",message:"Cell at row \(row.tag) was tapped!",preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil))
    self.present(alert, animated: true, completion: nil)
}
</code>```

答:
What you are designing for implementing this procedure is not correct. What you can do

Make a custom cell

Add a button in custom cell

Add action in that button in CellForRowAtIndexPath

Handle action from ViewController where you added tableView.

I made a whole project for you.Just to let you know. if you want to add customCell in tableView you need to register it like this in viewDidLoad.
i have done is in ViewController.swift file. check out my project.

```<code>let nib = UINib.init(nibName:String(describing: sampleTableViewCell.self) , bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "chatCell")
</code>```

Then check cellForRowAtIndexPath function:

```<code>public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "chatCell", for: indexPath) as! sampleTableViewCell

    cell.clickMeBtn.tag = indexPath.row
    cell.clickMeBtn.addTarget(self, action: #selector(onButtonPressed(sender :)), for: .touchUpInside)
    return cell

}
</code>```

Button press function:

```<code>func onButtonPressed(sender:UIButton) {
    let alert = UIAlertController.init(title:"Cell index is"+String(sender.tag), message: nil, preferredStyle: UIAlertControllerStyle.alert)
    let okAction = UIAlertAction.init(title: "ok", style: UIAlertActionStyle.default) { (UIAlertAction) in

    }

    alert.addAction(okAction)
    self.present(alert, animated: true, completion: nil)

}
</code>```

Check only three files:

Github link

ViewController.swift

sampleTableViewCell.swift

sampleTableViewCell.xib**

Here is the output:

Body:
Good day to all. Faced a problem. I need to make a table with a button and by clicking on the button I get a alert with the number of the cell. The table cells themselves are not active. That's how I realized it. When I scroll the table in the beginning everything is fine, when you press the button, a alert is displayed with the correct line number, but  after 4 elements an error appears.

This error appears in the line where I'm working with the 4 tag.
Fatal error: unexpectedly found nil while unwrapping an Optional value

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as UITableViewCell

    if (tableView.tag == 1) {
        let numLabel: UILabel = tableView.viewWithTag(3) as! UILabel
        numLabel.text = String(indexPath.row)
    } else if (tableView.tag == 2) {

        //Error appears here
        let numButton: UIButton = tableView.viewWithTag(4) as! UIButton
        numButton.setTitle(String(indexPath.row), for: .normal)

        numButton.tag = indexPath.row
    }

    return cell
}

@IBAction func showAlertForRow(row: UIButton) {
    let alert = UIAlertController(title:"Test work",message:"Cell at row \(row.tag) was tapped!",preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil))
    self.present(alert, animated: true, completion: nil)
}

Body:
What you are designing for implementing this procedure is not correct. What you can do

Make a custom cell

Add a button in custom cell

Add action in that button in CellForRowAtIndexPath

Handle action from ViewController where you added tableView.

I made a whole project for you.Just to let you know. if you want to add customCell in tableView you need to register it like this in viewDidLoad.
i have done is in ViewController.swift file. check out my project.

let nib = UINib.init(nibName:String(describing: sampleTableViewCell.self) , bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "chatCell")

Then check cellForRowAtIndexPath function:

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "chatCell", for: indexPath) as! sampleTableViewCell

    cell.clickMeBtn.tag = indexPath.row
    cell.clickMeBtn.addTarget(self, action: #selector(onButtonPressed(sender :)), for: .touchUpInside)
    return cell

}

Button press function:

func onButtonPressed(sender:UIButton) {
    let alert = UIAlertController.init(title:"Cell index is"+String(sender.tag), message: nil, preferredStyle: UIAlertControllerStyle.alert)
    let okAction = UIAlertAction.init(title: "ok", style: UIAlertActionStyle.default) { (UIAlertAction) in

    }

    alert.addAction(okAction)
    self.present(alert, animated: true, completion: nil)

}

Check only three files:

Github link

ViewController.swift

sampleTableViewCell.swift

sampleTableViewCell.xib**

Here is the output:


问:
Raspberry pi lirc irw connect: connection refused
since days i try getting irw to work after having installed lirc.

I am using raspian, always freshly updated / upgraded. For lirc i am using the latest version of 2nd of june which is 0.10.0 from lirc.org

Until now i did:

install lirc

connecting a receiver TSOP

testing with mode2 -d /dev/lirc0 and seeing the raw data space/pulse coming in to the assigned GPIO

But following problem persists:

Calling ''irw''( without parameters ) only tells me:

connect: No such file or directory

Calling ''irw /dev/lirc0'' tells me the error message:

connect: Connection refused

Now i am at the end of googleing around and hope for a helpful answer out of the community.

Thanks in advance!

best regards
Franz

答:
You don't bring much information about what lirc or OS version you are using. There are vast differences between the "old" 0.9.0 lirc still present in the debian universe, and the modern currently at 0.9.4d.

That said, the short story is that  irw reads data from a socket created by lircd. To get irw working you need to start lircd in a way which depends on your OS and lirc version. lircd reads raw data from /dev/lirc0, decodes it and makes it available on (typically) /var/run/lirc/lircd. This is where irw expects decoded data.

I'd suggest you read http://lirc.org/html/configuration-guide.html which explains the configuration. Note that this is for a modern setup, though.

EDIT: typos


问:
How to search a string for different types of numbers
I have multiple strings that each contain a year and some text. An example of one string is: "The year is 2004". But, another string may look like this "this was made in 2003.5". How would I check many strings like this and extract the correct number?

答:
For your types of numbers also works:

```<code>def find_number(my_string):
    for element in my_string.split():
        try:
            return int(element)
        except ValueError:
            try:
                return float(element)
            except ValueError:
                pass
my_string = "The year is 2004"
number = find_number(my_string)
</code>```

This will give you the right output for both examples.

Body:
For your types of numbers also works:

def find_number(my_string):
    for element in my_string.split():
        try:
            return int(element)
        except ValueError:
            try:
                return float(element)
            except ValueError:
                pass
my_string = "The year is 2004"
number = find_number(my_string)

This will give you the right output for both examples.


问:
Google Maps: How to add shadow to custom marker?
I'm using the new functionality of Animation (bouncing) found in Google Maps JavaScript API v3.

http://code.google.com/apis/maps/documentation/javascript/overlays.html#MarkerAnimations

In the examples in the linked code above, the default map marker icons have a dropshadow show on the map during the bounce.

I'm using a custom map marker icon that is a PNG.

Question: How do I create a dropshadow for my custom map marker icon that will also be shown when doing the Animation (bounce) effect?

UPDATE

Here is an example using the default map marker icon.

```<code>http://code.google.com/apis/maps/documentation/javascript/examples/marker-animations-iteration.html
</code>```

How do I do this using a custom map marker icon that also has a drop shadow.

答:
Got it to work.

http://jsfiddle.net/brWhw/

ContentLicense: CC BY-SA 2.5

Body:
I'm using the new functionality of Animation (bouncing) found in Google Maps JavaScript API v3.

http://code.google.com/apis/maps/documentation/javascript/overlays.html#MarkerAnimations

In the examples in the linked code above, the default map marker icons have a dropshadow show on the map during the bounce.

I'm using a custom map marker icon that is a PNG.

Question: How do I create a dropshadow for my custom map marker icon that will also be shown when doing the Animation (bounce) effect?

UPDATE

Here is an example using the default map marker icon.

http://code.google.com/apis/maps/documentation/javascript/examples/marker-animations-iteration.html

How do I do this using a custom map marker icon that also has a drop shadow.


问:
Android camera2 api
I need to take a picture from camera where it goes to another activity where we have image view to show the picture taken through camera.My questions is how to pass image data through intents using camera2api?

In which method in camera2api i need to pass data for another activity?

答:
You don't need Intent to pass image data from one Activity of your app to another. Actually, you cannot use Intent to pass a picture: there are restrictions on the size of the data bundled with Intent. So, you can use Intent extras to pass the path to an image, or some parameters extracted from the image. The Camera app uses intent extra("data") to return a thumbnail (very small) image.

Using the standard MediaStore.ACTION_IMAGE_CAPTURE Intent for latest devices which feature hardware.camera2 API is not different from the older devices that used the deprecated hardware.Camera.

You can employ some private Intent-based mechanism to communicate between activities of your app. In this case the consumer will probably pass necessary parameters to capture activity with startActivityForResult() and get the results in onActivityResult(). There are no methods in hardware.camera2 that can (or could be expected to) help you with these tasks.

Title: Android camera2 api


问:
add CCS style which depends on php IF statement inside mysqli_fetch_array
I want to add CCS style which depends on php IF statement. I have found something: changing the style inside "if" statement, but somehow it doesn`t work, maybe because of WHILE statement in my code.

```<code><?php
$possible_lang_list = mysqli_query($con,
'SELECT * FROM page WHERE title = "lang" ORDER BY name1 ASC');

while ($row = mysqli_fetch_array($possible_lang_list)) {
  echo '
      <div class="language" id="' . $row['name2'] . '">
      <p>' . $row['name1'] . '</p>
      </div>
  ';
}
?>
</code>```

I want to display only div class="language" where $row['name2'] == $x, with possibility to display whole class "language" with JavaScript.  Could anyone help?

I have tried:

```<code> while ($row = mysqli_fetch_array($possible_lang_list)) {
  if ($row['name2'] == $x) {
  ?>
  <div style="display:block;">
  <?php } else {
  ?>
  <div style="display:none;">
  <?php
  echo '
      <div class="" id="' . $row['name2'] . '">
        <p>' . $row['name1'] . '</p>

      </div>
  </div>';
  }
}
</code>```

答:
Assign a style element with a true/false ternary, like below. Then just output it!

```<code><?php

while ($row = mysqli_fetch_array($possible_lang_list)) {
  $class = ($row['name2'] == $x) ? 'language' : null;
  echo '
      <div class="'.$class.'" id="' . $row['name2'] . '">
      <p>' . $row['name1'] . '</p>
      </div>
  ';
}
</code>```

And then:

Body:
I want to add CCS style which depends on php IF statement. I have found something: changing the style inside "if" statement, but somehow it doesn`t work, maybe because of WHILE statement in my code.

<?php
$possible_lang_list = mysqli_query($con,
'SELECT * FROM page WHERE title = "lang" ORDER BY name1 ASC');

while ($row = mysqli_fetch_array($possible_lang_list)) {
  echo '

' . $row['name1'] . '

  ';
}
?>

I want to display only div class="language" where $row['name2'] == $x, with possibility to display whole class "language" with JavaScript.  Could anyone help?

I have tried:

 while ($row = mysqli_fetch_array($possible_lang_list)) {
  if ($row['name2'] == $x) {
  ?>

  <?php } else {
  ?>

  <?php
  echo '

' . $row['name1'] . '

';
  }
}

Body:
Assign a style element with a true/false ternary, like below. Then just output it!

<?php

while ($row = mysqli_fetch_array($possible_lang_list)) {
  $class = ($row['name2'] == $x) ? 'language' : null;
  echo '
      <div class="'.$class.'" id="' . $row['name2'] . '">
      <p>' . $row['name1'] . '</p>
      </div>
  ';
}

And then:


问:
Display custom values on x axis using Highcharts
I have written following code to display chart. I haven't mentioned x Axis and y axis labels. Those are auto generated.

I want to display 'low' on starting of scale and 'high' at end of scale on x axis instead of full scale.

```<code>    $('#container').highcharts({
    yAxis: {
        title: {
            text: 'Temperature'
        },
        id: 'my_y',
        lineWidth: 2,
        lineColor: '#F33',
        min:0,
        max:100
    },

    series: [{
        name: 'Temperature',
        data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6],
        color: '#F33'
    }]
});
</code>```

答:
like this?

Its a bit "hacky" i'm sure there is a better way of doing it but it works.

```<code>xAxis: {
     tickAmount: 2,
        labels: {
            formatter: function () {
              if (typeof(this.axis.ticks[this.value]) != "undefined"){
                if(this.axis.ticks[this.value].isFirst) {
                    return 'low'
                }
                else if (this.axis.ticks[this.value].isLast){
                    return 'high'
                }
              }
            }
     }
        }
</code>```

Body:
I have written following code to display chart. I haven't mentioned x Axis and y axis labels. Those are auto generated.

I want to display 'low' on starting of scale and 'high' at end of scale on x axis instead of full scale.

    $('#container').highcharts({
    yAxis: {
        title: {
            text: 'Temperature'
        },
        id: 'my_y',
        lineWidth: 2,
        lineColor: '#F33',
        min:0,
        max:100
    },

    series: [{
        name: 'Temperature',
        data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6],
        color: '#F33'
    }]
});

Body:
like this?

Its a bit "hacky" i'm sure there is a better way of doing it but it works.

xAxis: {
     tickAmount: 2,
        labels: {
            formatter: function () {
              if (typeof(this.axis.ticks[this.value]) != "undefined"){
                if(this.axis.ticks[this.value].isFirst) {
                    return 'low'
                }
                else if (this.axis.ticks[this.value].isLast){
                    return 'high'
                }
              }
            }
     }
        }


问:
Embed a svg shape in d3tip tooltip
I'm working with the popular tip library d3-tip.js, an example of it can be found here. Typically, the tip contains text that is defined dynamically like this:

```<code>var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    html = "";
    html += "<strong>Frequency:</strong> <span style='color:red'>" + d.frequency + "</span>";
    return html;
  })
</code>```

However, lets say I have a legend like this:

```<code>  var legend = g.append("g")
      .attr("font-family", "sans-serif")
      .attr("font-size", 10)
      .attr("text-anchor", "end")
    .selectAll("g")
    .data(keys.slice().reverse())
    .enter().append("g")
      .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

  legend.append("rect")
      .attr("x", width - 19)
      .attr("width", 19)
      .attr("height", 19)
      .attr("fill", z);

  legend.append("text")
      .attr("x", width - 24)
      .attr("y", 9.5)
      .attr("dy", "0.32em")
      .text(function(d) { return d; });
</code>```

I would like to somehow append a small svg rect inside the d3 toolip. This way when you hover over a graph with different classes (i.e. grouped bar chart) the tooltip will have a svg rect of matching color in addition to the html text. Ideally by using an existing legend variable, as seen above.

If it's not possible, then just explain why and I can accept that as an answer as well.

For clarity, here is a rough idea of what I'm going for visually:

答:
It's easy to create an SVG inside a d3.tip tooltip. Actually, you just have to use the same logic of any other D3 created SVG: select the container and append the SVG to it.

In the following demo, in your var tip, I'll create an empty div with a given ID. In this case, the div has an ID named mySVGtooltip:

```<code>var tool_tip = d3.tip()
    .attr("class", "d3-tip")
    .offset([20, 40])
    .html("<div id='mySVGtooltip'></div>");
</code>```

After that, it's just a matter of, inside the mouseover event, selecting that div by ID and appending the SVG to it:

```<code>var legendSVG = d3.select("#mySVGtooltip")
    .append("svg")
    .attr("width", 160)
    .attr("height", 50);
</code>```

Here is the demo, hover over the circles:

var svg = d3.select("body")
  .append("svg")
  .attr("width", 300)
  .attr("height", 300);

var tool_tip = d3.tip()
  .attr("class", "d3-tip")
  .offset([20, 40])
  .html("

");

svg.call(tool_tip);

var data = [20, 10, 30, 15, 35];

var circles = svg.selectAll(null)
  .data(data)
  .enter()
  .append("circle");

circles.attr("cy", 50)
  .attr("cx", function(d, i) {
    return 30 + 55 * i
  })
  .attr("r", function(d) {
    return d
  })
  .attr("fill", "lightgreen")
  .attr("stroke", "dimgray")
  .on('mouseover', function(d) {
    tool_tip.show();
    var legendSVG = d3.select("#mySVGtooltip")
      .append("svg")
      .attr("width", 160)
      .attr("height", 50);

    var legend = legendSVG.append("g")
      .attr("font-family", "sans-serif")
      .attr("font-size", 10);

      legend.append("text")
      .attr("x", 80)
      .attr("text-anchor", "middle")
      .attr("y", 16)
      .attr("font-size", 14)
      .text("Age Group:");

    legend.append("rect")
     .attr("y", 25)
      .attr("x", 10)
      .attr("width", 19)
      .attr("height", 19)
      .attr("fill", "goldenrod");

    legend.append("text")
      .attr("x", 35)
      .attr("y", 40)
      .text(function() {
        return d + " years and over";
      });
  })
  .on('mouseout', tool_tip.hide);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.d3-tip {
  line-height: 1;
  background: gainsboro;
  border: 1px solid black;
  font-size: 12px;
}

p {
  font-family: Helvetica;
}</code>```

```

Notice that, in this very simple demo, I'm using the datum (d) passed to the anonymous function by the mouseover event. I'm seeing in your question that you have your own data. Thus, change the code in my demo accordingly.

Title: Embed a svg shape in d3tip tooltip

Body:
I'm working with the popular tip library d3-tip.js, an example of it can be found here. Typically, the tip contains text that is defined dynamically like this:

var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    html = "";
    html += "Frequency: " + d.frequency + "";
    return html;
  })

However, lets say I have a legend like this:

  var legend = g.append("g")
      .attr("font-family", "sans-serif")
      .attr("font-size", 10)
      .attr("text-anchor", "end")
    .selectAll("g")
    .data(keys.slice().reverse())
    .enter().append("g")
      .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

  legend.append("rect")
      .attr("x", width - 19)
      .attr("width", 19)
      .attr("height", 19)
      .attr("fill", z);

  legend.append("text")
      .attr("x", width - 24)
      .attr("y", 9.5)
      .attr("dy", "0.32em")
      .text(function(d) { return d; });

I would like to somehow append a small svg rect inside the d3 toolip. This way when you hover over a graph with different classes (i.e. grouped bar chart) the tooltip will have a svg rect of matching color in addition to the html text. Ideally by using an existing legend variable, as seen above.

If it's not possible, then just explain why and I can accept that as an answer as well.

For clarity, here is a rough idea of what I'm going for visually:

Body:
It's easy to create an SVG inside a d3.tip tooltip. Actually, you just have to use the same logic of any other D3 created SVG: select the container and append the SVG to it.

In the following demo, in your var tip, I'll create an empty div with a given ID. In this case, the div has an ID named mySVGtooltip:

var tool_tip = d3.tip()
    .attr("class", "d3-tip")
    .offset([20, 40])
    .html("<div id='mySVGtooltip'></div>");

After that, it's just a matter of, inside the mouseover event, selecting that div by ID and appending the SVG to it:

var legendSVG = d3.select("#mySVGtooltip")
    .append("svg")
    .attr("width", 160)
    .attr("height", 50);

Here is the demo, hover over the circles:

var svg = d3.select("body")
  .append("svg")
  .attr("width", 300)
  .attr("height", 300);

var tool_tip = d3.tip()
  .attr("class", "d3-tip")
  .offset([20, 40])
  .html("<div id='mySVGtooltip'></div>");

svg.call(tool_tip);

var data = [20, 10, 30, 15, 35];

var circles = svg.selectAll(null)
  .data(data)
  .enter()
  .append("circle");

circles.attr("cy", 50)
  .attr("cx", function(d, i) {
    return 30 + 55 * i
  })
  .attr("r", function(d) {
    return d
  })
  .attr("fill", "lightgreen")
  .attr("stroke", "dimgray")
  .on('mouseover', function(d) {
    tool_tip.show();
    var legendSVG = d3.select("#mySVGtooltip")
      .append("svg")
      .attr("width", 160)
      .attr("height", 50);

    var legend = legendSVG.append("g")
      .attr("font-family", "sans-serif")
      .attr("font-size", 10);

      legend.append("text")
      .attr("x", 80)
      .attr("text-anchor", "middle")
      .attr("y", 16)
      .attr("font-size", 14)
      .text("Age Group:");

    legend.append("rect")
     .attr("y", 25)
      .attr("x", 10)
      .attr("width", 19)
      .attr("height", 19)
      .attr("fill", "goldenrod");

    legend.append("text")
      .attr("x", 35)
      .attr("y", 40)
      .text(function() {
        return d + " years and over";
      });
  })
  .on('mouseout', tool_tip.hide);

.d3-tip {
  line-height: 1;
  background: gainsboro;
  border: 1px solid black;
  font-size: 12px;
}

p {
  font-family: Helvetica;
}

<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.7.1/d3-tip.min.js"></script>

Notice that, in this very simple demo, I'm using the datum (d) passed to the anonymous function by the mouseover event. I'm seeing in your question that you have your own data. Thus, change the code in my demo accordingly.


问:
Persistent issues with installation of OpenAI gym
I am running Ubuntu 16.04 and am having trouble doing a full installation of "gym".  What I did:

Installed Anaconda 4.2.0 (the version that comes with Python 3.5)

Installed dependencies with sudo apt-get install -y python-numpy python-dev cmake zlib1g-dev libjpeg-dev xvfb libav-tools xorg-dev python-opengl libboost-all-dev libsdl2-dev swig

Cloned gym repository with "git clone https://github.com/openai/gym.git"

Installed gym with cd gym and then pip install -e '.[all]'

I get no errors throughout this process.  Then I open the Spyder ide and run:

```<code>import gym

env = gym.make("CartPole-v0")
</code>```

And it works fine.  However, when I run

```<code>import gym

env = gym.make("LunarLander-v2")
</code>```

I get the error:

```<code>/path/anaconda3/lib/python3.5/site-packages/Box2D/_Box2D.cpython-35m-x86_64-linux-gnu.so: undefined symbol: _ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9_M_appendEPKcm
</code>```

I also get errors when I try to access other box2d and atari environments.

It is also worth noting that I tried doing all of this on another virtual machine on which I installed the Python 2.7 version of Anaconda, and I got the same message...so this does not seem to have anything to do with the version of python I am using.

答:
If you installed conda environment, use conda in your channel.

```<code>$ conda install -c https://conda.anaconda.org/kne pybox2d
</code>```

Box2d will be added under python3.5/site-packages, and try code again.

```<code>import gym

env = gym.make("LunarLander-v2")
</code>```

Good luck.

Body:
I am running Ubuntu 16.04 and am having trouble doing a full installation of "gym".  What I did:

Installed Anaconda 4.2.0 (the version that comes with Python 3.5)

Installed dependencies with sudo apt-get install -y python-numpy python-dev cmake zlib1g-dev libjpeg-dev xvfb libav-tools xorg-dev python-opengl libboost-all-dev libsdl2-dev swig

Cloned gym repository with "git clone https://github.com/openai/gym.git"

Installed gym with cd gym and then pip install -e '.[all]'

I get no errors throughout this process.  Then I open the Spyder ide and run:

import gym

env = gym.make("CartPole-v0")

And it works fine.  However, when I run

import gym

env = gym.make("LunarLander-v2")

I get the error:

/path/anaconda3/lib/python3.5/site-packages/Box2D/_Box2D.cpython-35m-x86_64-linux-gnu.so: undefined symbol: _ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9_M_appendEPKcm

I also get errors when I try to access other box2d and atari environments.

It is also worth noting that I tried doing all of this on another virtual machine on which I installed the Python 2.7 version of Anaconda, and I got the same message...so this does not seem to have anything to do with the version of python I am using.

Body:
If you installed conda environment, use conda in your channel.

$ conda install -c https://conda.anaconda.org/kne pybox2d

Box2d will be added under python3.5/site-packages, and try code again.

import gym

env = gym.make("LunarLander-v2")

Good luck.


问:
What's the best way to assign a method body at construction time when using Moose?
I'm using Moose (specifically MooseX::Declare) to create an iterator object, Iter which has a next method that advances state and returns 0 or 1 as required for use in a while statement. The problem I'm running into is that depending on the existence of one of the construction parameters, next needs to perform two very different sets of operations. The way I see it I have five options:

if ... then in next method

subclass

hash dispatch

symbol table manipulation

put methods in different modules and load required one at construction time

Number 1 is just amateur.

Number 2 is, I suppose, the proper OOP way of doing things.  I have no objections to doing it that way but seems a little bit overkill simply to override a single method.

I've often used Number 3 in the past when working procedurally or pseudo-functionally and it's what I'm doing now.

Number 4 is, as we all know, fraught with peril and I know nothing about Moose Guts to want to start messing around when unnecessary.

The last item, number 5 seems to me to be the most sensible (and Perlish) but like Number 2, is a little too much work.  I'm really wondering if there's a fifth way I haven't considered such as hooking into the metaclass or perhaps a MooseX module that is reasonably mature.

答:
Pass your 'next' subref into the constructor and save it in an attribute:

```<code>has next => (
    isa => 'CodeRef',
    required => 1,
    traits => ['Code'],
    handles => { next => 'execute_method' },
);
</code>```

With the 'execute_method' handler provided by the native attribute 'Code' trait, you can call the 'next' method as a normal method and it will find the subref body in the attribute.

If you want to pre-define the subref body/ies and decide at construction time which version to use, you could set the value of 'next' in a builder sub according to other conditions of the object:

```<code>has next => (
    # ...
    lazy => 1,
    default => sub {
         my $self = shift;
         return sub { ... } if $self->some_condition;
         # etc etc...
    },
);
</code>```

Body:
Pass your 'next' subref into the constructor and save it in an attribute:

has next => (
    isa => 'CodeRef',
    required => 1,
    traits => ['Code'],
    handles => { next => 'execute_method' },
);

With the 'execute_method' handler provided by the native attribute 'Code' trait, you can call the 'next' method as a normal method and it will find the subref body in the attribute.

If you want to pre-define the subref body/ies and decide at construction time which version to use, you could set the value of 'next' in a builder sub according to other conditions of the object:

has next => (
    # ...
    lazy => 1,
    default => sub {
         my $self = shift;
         return sub { ... } if $self->some_condition;
         # etc etc...
    },
);


问:
How to pass URLs as parameters in a GET request within python flask (restplus)?
I am creating a REST API using python flask. The API is ready and works on port number 8000 of my localhost. Now I intend to give this REST API a user friendly interface for which I decided to go with python - restplus. I thought of calling this service (running on 8000) internally from swagger application running on 5000

I was able to create the basic structure of the API (Swagger). The code for which looks like this:

```<code>import flask
from flask import Flask, request
from flask_restplus import Resource, Api

app = Flask(__name__)
api = Api(app)

@api.route('/HybridComparator/<string:url2>/<string:url1>')
class HybridComparator(Resource):
    def get(self, url1, url2):
        print(url1)
        print(url2)
        return url1 + ' ' + url2

if __name__ == '__main__':
    app.run(debug=True)
</code>```

The application as a whole runs seamlessly (with random strings as parameters) on port 5000. But when the URLs I pass are actual links, the application returns a response of  404 - Not found. Further to my investigation I realized the culprit being '/' embedded within the links I try to provide. Is there a way to handle URLs in particular?

Should I encode them before sending a request. (This will make my parameters look ugly). Is there something I am missing?

答:
it seems that :

```<code>@api.route('/HybridComparator/<path:url2>/<path:url1>')
</code>```

should fix it ,it fixes the 404 but i am getting only "http:/" part of the param

Body:
I am creating a REST API using python flask. The API is ready and works on port number 8000 of my localhost. Now I intend to give this REST API a user friendly interface for which I decided to go with python - restplus. I thought of calling this service (running on 8000) internally from swagger application running on 5000

I was able to create the basic structure of the API (Swagger). The code for which looks like this:

import flask
from flask import Flask, request
from flask_restplus import Resource, Api

app = Flask(__name__)
api = Api(app)

@api.route('/HybridComparator/<string:url2>/<string:url1>')
class HybridComparator(Resource):
    def get(self, url1, url2):
        print(url1)
        print(url2)
        return url1 + ' ' + url2

if __name__ == '__main__':
    app.run(debug=True)

The application as a whole runs seamlessly (with random strings as parameters) on port 5000. But when the URLs I pass are actual links, the application returns a response of  404 - Not found. Further to my investigation I realized the culprit being '/' embedded within the links I try to provide. Is there a way to handle URLs in particular?

Should I encode them before sending a request. (This will make my parameters look ugly). Is there something I am missing?

Body:
it seems that :

@api.route('/HybridComparator/<path:url2>/<path:url1>')

should fix it ,it fixes the 404 but i am getting only "http:/" part of the param


问:
Oracle, replace string for REGEXP_REPLACE based on the matched expression
I want to repair some data, which was uploaded using incorrect encoding.
Consider the following example:

```<code>RUE DE SAN MARTI¦O N¦ 123
</code>```

I want to replace the ¦ with say #, but only in cases when it's preceeded by a number or the character N

My desired output is:

```<code>RUE DE SAN MARTI¦O N# 123
</code>```

I tried the following replace:

```<code>SELECT REGEXP_REPLACE('RUE DE SAN MARTI¦O N¦ 123','[\d]\¦|[N]\¦','#')
  FROM dual;
</code>```

which correctly detects the chacter to match, but from what I know replacement string is used as literal. However I want to preserve the N before ¦.
Has anyone had any luck solving similar issue?

答:
You may use

```<code>([0-9N])¦
</code>```

and replace with \1#.

See  the regex demo

Details:

([0-9N]) - a capturing group matching a digit or N (can be referred to with the \1 backreference from the replacement pattern)

¦ - a literal symbol is matched.

See an Oracle online demo:

```<code>SELECT REGEXP_REPLACE('RUE DE SAN MARTI¦O N¦ 123','([0-9N])¦','\1#') AS Result FROM dual
</code>```

Body:
I want to repair some data, which was uploaded using incorrect encoding.
Consider the following example:

RUE DE SAN MARTI¦O N¦ 123

I want to replace the ¦ with say #, but only in cases when it's preceeded by a number or the character N

My desired output is:

RUE DE SAN MARTI¦O N# 123

I tried the following replace:

SELECT REGEXP_REPLACE('RUE DE SAN MARTI¦O N¦ 123','[\d]\¦|[N]\¦','#')
  FROM dual;

which correctly detects the chacter to match, but from what I know replacement string is used as literal. However I want to preserve the N before ¦.
Has anyone had any luck solving similar issue?

Body:
You may use

([0-9N])¦

and replace with \1#.

See  the regex demo

Details:

([0-9N]) - a capturing group matching a digit or N (can be referred to with the \1 backreference from the replacement pattern)

¦ - a literal symbol is matched.

See an Oracle online demo:

SELECT REGEXP_REPLACE('RUE DE SAN MARTI¦O N¦ 123','([0-9N])¦','\1#') AS Result FROM dual


问:
Star before and after variables in c# documentation
The following code, what are the '*' doing?</p>

```<code>for (Char* ptr1 = (Char*)bstr1.ToPointer(), ptr2 = (Char*)bstr2.ToPointer();
                    *ptr1 != 0 && *ptr2 != 0;
</code>```

答:
They are unsafe pointers. Look for C# pointers, unsafe C# and similar. Like https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/unsafe and https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/unsafe-code-pointers/pointer-types

That code, if it is

```<code>for (Char* ptr1 = (Char*)bstr1.ToPointer(), ptr2 = (Char*)bstr2.ToPointer();
                *ptr1 != 0 && *ptr2 != 0;
                ptr1 = IntPtr.Add(ptr1, 1), ptr2 = IntPtr.Add(ptr2, 1))
</code>```

(note that the part of the code that increments the ptr1 and ptr2 could be a little different. Sadly there is no ++ operator for IntPtr)

cycles the characters cointained in the bstr1 and bstr2 until one of them is '\0'. Given the name, bstr1 and bstr2 are probably BSTR (Windows unicode strings used in COM programming)

You have that *ptr1 is the char contained in the memory location "pointed" by ptr1.

Body:
The following code, what are the '*' doing?

for (Char* ptr1 = (Char*)bstr1.ToPointer(), ptr2 = (Char*)bstr2.ToPointer();
                    *ptr1 != 0 && *ptr2 != 0;

Body:
They are unsafe pointers. Look for C# pointers, unsafe C# and similar. Like https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/unsafe and https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/unsafe-code-pointers/pointer-types

That code, if it is

for (Char* ptr1 = (Char*)bstr1.ToPointer(), ptr2 = (Char*)bstr2.ToPointer();
                *ptr1 != 0 && *ptr2 != 0;
                ptr1 = IntPtr.Add(ptr1, 1), ptr2 = IntPtr.Add(ptr2, 1))

(note that the part of the code that increments the ptr1 and ptr2 could be a little different. Sadly there is no ++ operator for IntPtr)

cycles the characters cointained in the bstr1 and bstr2 until one of them is '\0'. Given the name, bstr1 and bstr2 are probably BSTR (Windows unicode strings used in COM programming)

You have that *ptr1 is the char contained in the memory location "pointed" by ptr1.


答:
now it is working:</p>

```<code>while ($row = mysqli_fetch_array($possible_lang_list)) {
  if ($row['name2'] == $x) {
  ?>
  <div style="display:block;">
  <?php } else {
  ?>
  <div style="display:none;">
  <?php   }
  echo '
      <div class="" id="' . $row['name2'] . '">
        <p>' . $row['name1'] . '</p>

      </div>
  </div>';

}
</code>```

Title: add CCS style which depends on php IF statement inside mysqli_fetch_array

Body:
now it is working:

while ($row = mysqli_fetch_array($possible_lang_list)) {
  if ($row['name2'] == $x) {
  ?>
  <div style="display:block;">
  <?php } else {
  ?>
  <div style="display:none;">
  <?php   }
  echo '
      <div class="" id="' . $row['name2'] . '">
        <p>' . $row['name1'] . '</p>

      </div>
  </div>';

}


问:
Linq to join tables on XElement.Name = XAttribute("n")
This is driving me bat-guano crazy!
Client data file:

```<code><rows>
    <row>
        <CustomerID>ABC123</CustomerID>
        <PrdcrCd>10</PrdcrCd>
        <StrAdr>123 Main St., NW</StrAdr>
        <City>Anytown</City>
        etc.
    </row>
<rows>
</code>```

Map file for transforming client data into acceptable input:

```<code><SourceEntries>
    <map>
        <Field n='CustomerID' m='201' />
        <Field n='StrAdr' m='315' />
        <Field n='City' m='316' />
        <Field n='PrdrCd' m='442' />
        etc.
    </map>
</SourceEntries>
</code>```

Finally, the template for acceptable input:

```<code><template>
    <Field n='ClientId' id='201' />
    <Field n='Street Address' id='315' />
    <Field n='City' id='316' />
    <Field n='ProducerCode' id='442' />
    etc.
</template>
</code>```

So, from the client file XElement name, match the Source Entries attribute value 'n', and get the Source Entires map reference m. Then, use m to match a template element attribute i, retrieve the template name attribute 'n' and create a new XElement tree using that name.

Since I'm a noob at Linq, and not particularly adept at XML, I thought I'd start out slowly. Like this:

```<code>var results = from t1 in clientXm.Elements("row").Descendants()
      join t2 in sourceEntries.Elements("Field") on t1.Name equals t2.Attributes("n") into xRef
      select new
          {
              (string)xRef.Attributes("n"),
              (string)xRef.Attributes("m")
          };
</code>```

First error, in the join clause at "on t1.Name.LocalName equals" is that Argument type 'string' is not assignable to parameter type 'TKey'. Then, in the select clause, for the two items I'm interested in, I get "Anonymous type projection initializer should be simple name or member access expression." Oh, and of course, the XML file structures are specification requirements, so I can't change any of them.

At this point, I'm so freaking confused I don't know whether the world is upside-down, or I'm standing on my head. Can I please buy a clue... or at least a vowel? Any and all help greatly appreciated.

EDIT

Using LinqPad, I tried this statement:

```<code>XElement _clientXml = XElement.Load(@"client.xml");
XElement _sourceEntries = XElement.Load(@"Client_Map.xml");

foreach (XElement clientData in _clientXml.Descendants("row").Descendants()){
    IEnumerable<XElement> mapRefs =
        from mapData in _sourceEntries.Descendants("Field")
        where clientData.Name.LocalName == (string) mapData.Attribute("n")
        select mapData;
    foreach (XElement item in mapRefs){
        Console.WriteLine(item.Attribute("m"));
    }
}
</code>```

In LinqPad, this produced a list of "m" values -- just what I'm trying to get at this baby step. BUT the exact same code in VS gives me nothing. When I debug, mapRefs is an empty set when I get to the second foreach.

Does this make any sense at all?

Thanks
Randy

答:
Some of your inputs aren't aligned quite right. Here's a good starting place:

```<code>var rowText =
@"<rows>
    <row>
        <CustomerID>ABC123</CustomerID>
        <PrdrCd>10</PrdrCd>
        <StrAdr>123 Main St., NW</StrAdr>
        <City>Anytown</City>
        etc.
    </row>
</rows>";
var sourceEntriesText =
@"<SourceEntries>
    <map>
        <Field n='CustomerID' m='201' />
        <Field n='StrAdr' m='315' />
        <Field n='City' m='316' />
        <Field n='PrdrCd' m='442' />
        etc.
    </map>
</SourceEntries>";
var templateText =
@"<template>
    <Field n='ClientId' id='201' />
    <Field n='Street Address' id='315' />
    <Field n='City' id='316' />
    <Field n='ProducerCode' id='442' />
    etc.
</template>";
var clientXm = XDocument.Parse(rowText);
var sourceEntries = XDocument.Parse(sourceEntriesText);
var results = from r in clientXm.Descendants("row")
            from t1 in r.Elements()
            let xRef = sourceEntries.Descendants("Field").FirstOrDefault(
                        t2 => t1.Name == t2.Attribute("n").Value)
            select new
                {
                    t1,
                    xRef
                };
</code>```

A little more work yields something probably closer to what you're looking for:

```<code>var results = from r in clientXm.Descendants("row")
            from t1 in r.Elements()
            join t2 in sourceEntries.Descendants("Field")
            on t1.Name equals t2.Attribute("n").Value
            join t3 in template.Descendants("Field")
            on t2.Attribute("m").Value equals t3.Attribute("id").Value
            select new
                {
                    Name = t3.Attribute("n").Value,
                    Value = t1.Value,
                };
</code>```

Body:
This is driving me bat-guano crazy!
Client data file:

<rows>
    <row>
        <CustomerID>ABC123</CustomerID>
        <PrdcrCd>10</PrdcrCd>
        <StrAdr>123 Main St., NW</StrAdr>
        <City>Anytown</City>
        etc.
    </row>
<rows>

Map file for transforming client data into acceptable input:

<SourceEntries>
    <map>
        <Field n='CustomerID' m='201' />
        <Field n='StrAdr' m='315' />
        <Field n='City' m='316' />
        <Field n='PrdrCd' m='442' />
        etc.
    </map>
</SourceEntries>

Finally, the template for acceptable input:

<template>
    <Field n='ClientId' id='201' />
    <Field n='Street Address' id='315' />
    <Field n='City' id='316' />
    <Field n='ProducerCode' id='442' />
    etc.
</template>

So, from the client file XElement name, match the Source Entries attribute value 'n', and get the Source Entires map reference m. Then, use m to match a template element attribute i, retrieve the template name attribute 'n' and create a new XElement tree using that name.

Since I'm a noob at Linq, and not particularly adept at XML, I thought I'd start out slowly. Like this:

var results = from t1 in clientXm.Elements("row").Descendants()
      join t2 in sourceEntries.Elements("Field") on t1.Name equals t2.Attributes("n") into xRef
      select new
          {
              (string)xRef.Attributes("n"),
              (string)xRef.Attributes("m")
          };

First error, in the join clause at "on t1.Name.LocalName equals" is that Argument type 'string' is not assignable to parameter type 'TKey'. Then, in the select clause, for the two items I'm interested in, I get "Anonymous type projection initializer should be simple name or member access expression." Oh, and of course, the XML file structures are specification requirements, so I can't change any of them.

At this point, I'm so freaking confused I don't know whether the world is upside-down, or I'm standing on my head. Can I please buy a clue... or at least a vowel? Any and all help greatly appreciated.

EDIT

Using LinqPad, I tried this statement:

XElement _clientXml = XElement.Load(@"client.xml");
XElement _sourceEntries = XElement.Load(@"Client_Map.xml");

foreach (XElement clientData in _clientXml.Descendants("row").Descendants()){
    IEnumerable<XElement> mapRefs =
        from mapData in _sourceEntries.Descendants("Field")
        where clientData.Name.LocalName == (string) mapData.Attribute("n")
        select mapData;
    foreach (XElement item in mapRefs){
        Console.WriteLine(item.Attribute("m"));
    }
}

In LinqPad, this produced a list of "m" values -- just what I'm trying to get at this baby step. BUT the exact same code in VS gives me nothing. When I debug, mapRefs is an empty set when I get to the second foreach.

Does this make any sense at all?

Thanks
Randy

Body:
Some of your inputs aren't aligned quite right. Here's a good starting place:

var rowText =
@"<rows>
    <row>
        <CustomerID>ABC123</CustomerID>
        <PrdrCd>10</PrdrCd>
        <StrAdr>123 Main St., NW</StrAdr>
        <City>Anytown</City>
        etc.
    </row>
</rows>";
var sourceEntriesText =
@"<SourceEntries>
    <map>
        <Field n='CustomerID' m='201' />
        <Field n='StrAdr' m='315' />
        <Field n='City' m='316' />
        <Field n='PrdrCd' m='442' />
        etc.
    </map>
</SourceEntries>";
var templateText =
@"<template>
    <Field n='ClientId' id='201' />
    <Field n='Street Address' id='315' />
    <Field n='City' id='316' />
    <Field n='ProducerCode' id='442' />
    etc.
</template>";
var clientXm = XDocument.Parse(rowText);
var sourceEntries = XDocument.Parse(sourceEntriesText);
var results = from r in clientXm.Descendants("row")
            from t1 in r.Elements()
            let xRef = sourceEntries.Descendants("Field").FirstOrDefault(
                        t2 => t1.Name == t2.Attribute("n").Value)
            select new
                {
                    t1,
                    xRef
                };

A little more work yields something probably closer to what you're looking for:

var results = from r in clientXm.Descendants("row")
            from t1 in r.Elements()
            join t2 in sourceEntries.Descendants("Field")
            on t1.Name equals t2.Attribute("n").Value
            join t3 in template.Descendants("Field")
            on t2.Attribute("m").Value equals t3.Attribute("id").Value
            select new
                {
                    Name = t3.Attribute("n").Value,
                    Value = t1.Value,
                };


问:
How to select most repeated field in a column in pandas?
I am a beginner in coding and would highly appreciate your help. I have a file of 4gb and i am trying to select the the most repeated field in column B (that is not similar to column A) and the corresponding column C

For example,

```<code> Column A       Column B    Column C    id
 Sam             Sam          12        001
 Alex            David        10        001
 David           David        15        002
 Sarah           Alice        23        001
 Alice           Sam          18        002
 Sam             Alice        20        002
 Anna            Sam          26        003
</code>```

I would like to exclude if names in column A and column B are same and then find the most repeated names in column B. And also I would like to find the corresponding id of the most repeated fields in column B.

When i tried using the following command, i get memory error.

```<code>(df.loc[~(df['Column B'].isin(df['Column A']) & df['Column B'].isin(df['Column C'])), 'Column B'])
</code>```

答:
You're going to have trouble with a 4Gb dataframe using pandas. I recommend you have a look at dask instead which replicates parts of the pandas api but does out of core computation, i.e. does not load everything into memory at once. It should be a drop in replacement for most operations.

https://dask.pydata.org

If I understand your requirements correctly this should work

```<code>import pandas as pd
from dask import dataframe as dd

df = pd.DataFrame([['Sam', 'Alex', 'David', 'Sarah', 'Alice', 'Sam', 'Anna'],
                   ['Sam', 'David', 'David', 'Alice', 'Sam', 'Alice', 'Sam'],
                   [12, 10, 15, 23, 18, 20, 26]],
                  index=['Column A', 'Column B', 'Column C']).T
# have a look at dd.read_csv to avoid creating a pandas dataframe
# first, there's no need for that actually
dask_df = dd.from_pandas(df)
</code>```

The dask dataframe now looks the same as the pandas df

```<code>In [39]: dask_df.head()
Out[39]:
  Column A Column B Column C
0      Sam      Sam       12
1     Alex    David       10
2    David    David       15
3    Sarah    Alice       23
4    Alice      Sam       18
</code>```

then compute the frequencies of elements in the second column

```<code>freq = (dask_df[dask_df['Column A'] != dask_df['Column B']]
        .groupby('Column B') # group by the values in the first column
        .value_counts() # the length of the group is the number of elements in it, i.e. the frequency
       )

freq.compute() # dask requires to call .compute()
Out[42]:
Alice    2
David    1
Sam      2
dtype: int64
</code>```

Now that we know the frequencies you can just pick out the rows you want from the dask dataframe

```<code>In [44]: dask_df[dask_df['Column B'] == 'Alice'][['Column B', 'Column C']].compute()
Out[44]:
  Column B Column C
3    Alice       23
5    Alice       20
</code>```

If you just want to top k=5 frequencies use freq.nlargest(n=5).compute()

Body:
I am a beginner in coding and would highly appreciate your help. I have a file of 4gb and i am trying to select the the most repeated field in column B (that is not similar to column A) and the corresponding column C

For example,

 Column A       Column B    Column C    id
 Sam             Sam          12        001
 Alex            David        10        001
 David           David        15        002
 Sarah           Alice        23        001
 Alice           Sam          18        002
 Sam             Alice        20        002
 Anna            Sam          26        003

I would like to exclude if names in column A and column B are same and then find the most repeated names in column B. And also I would like to find the corresponding id of the most repeated fields in column B.

When i tried using the following command, i get memory error.

(df.loc[~(df['Column B'].isin(df['Column A']) & df['Column B'].isin(df['Column C'])), 'Column B'])

Body:
You're going to have trouble with a 4Gb dataframe using pandas. I recommend you have a look at dask instead which replicates parts of the pandas api but does out of core computation, i.e. does not load everything into memory at once. It should be a drop in replacement for most operations.

https://dask.pydata.org

If I understand your requirements correctly this should work

import pandas as pd
from dask import dataframe as dd

df = pd.DataFrame([['Sam', 'Alex', 'David', 'Sarah', 'Alice', 'Sam', 'Anna'],
                   ['Sam', 'David', 'David', 'Alice', 'Sam', 'Alice', 'Sam'],
                   [12, 10, 15, 23, 18, 20, 26]],
                  index=['Column A', 'Column B', 'Column C']).T
# have a look at dd.read_csv to avoid creating a pandas dataframe
# first, there's no need for that actually
dask_df = dd.from_pandas(df)

The dask dataframe now looks the same as the pandas df

In [39]: dask_df.head()
Out[39]:
  Column A Column B Column C
0      Sam      Sam       12
1     Alex    David       10
2    David    David       15
3    Sarah    Alice       23
4    Alice      Sam       18

then compute the frequencies of elements in the second column

freq = (dask_df[dask_df['Column A'] != dask_df['Column B']]
        .groupby('Column B') # group by the values in the first column
        .value_counts() # the length of the group is the number of elements in it, i.e. the frequency
       )

freq.compute() # dask requires to call .compute()
Out[42]:
Alice    2
David    1
Sam      2
dtype: int64

Now that we know the frequencies you can just pick out the rows you want from the dask dataframe

In [44]: dask_df[dask_df['Column B'] == 'Alice'][['Column B', 'Column C']].compute()
Out[44]:
  Column B Column C
3    Alice       23
5    Alice       20

If you just want to top k=5 frequencies use freq.nlargest(n=5).compute()


问:
Opencart 2.2.0 for each category/subcategory display ONLY third level categories in category module
This may be a duplicate, but which ever answer I found, didn't solve my problem.  I have category structure like this: Category->Subcategory->Sub sub category. In my category module, I managed to show the whole structure (Category->Subcategory->Subsub category). But what I need is only Subsub categories to show for each Category or subcategory. My  category.php module file looks like this:

```<code><?php
class ControllerModuleCategory extends Controller {
    public function index() {
        $this->load->language('module/category');

        $data['heading_title'] = $this->language->get('heading_title');

        if (isset($this->request->get['path'])) {
            $parts = explode('_', (string)$this->request->get['path']);
        } else {
            $parts = array();
        }

        if (isset($parts[0])) {
            $data['category_id'] = $parts[0];
        } else {
            $data['category_id'] = 0;
        }

        if (isset($parts[1])) {
            $data['child_id'] = $parts[1];
        } else {
            $data['child_id'] = 0;
        }

        $this->load->model('catalog/category');

        $this->load->model('catalog/product');

        $data['categories'] = array();

        $categories = $this->model_catalog_category->getCategories(0);

        foreach ($categories as $category) {
            $children_data = array();

            if ($category['category_id'] == $data['category_id']) {
                $children = $this->model_catalog_category->getCategories($category['category_id']);

                foreach($children as $child) {
                    $children_data_2 = array();

                    $children_2 = $this->model_catalog_category->getCategories($child['category_id']);

                    foreach ($children_2 as $child_2) {
    $filter_data = array(
        'filter_category_id'  => $child_2['category_id'],
        'filter_sub_category' => true
    );

    $children_data_2[] = array(
        'category_id' => $child_2['category_id'],
        'name'        => $child_2['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
        'href'        => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'] . '_' . $child_2['category_id'])
    );
}

                    $filter_data = array('filter_category_id' => $child['category_id'], 'filter_sub_category' => true);

                    $children_data[] = array(
                        'category_id' => $child['category_id'],
                        'name' => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
                        'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id']),
                            'children'    => $children_data_2 // insert this line

                    );
                }
            }

            $filter_data = array(
                'filter_category_id'  => $category['category_id'],
                'filter_sub_category' => true
            );

            $data['categories'][] = array(
                'category_id' => $category['category_id'],
                'name'        => $category['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
                'children'    => $children_data,
                'href'        => $this->url->link('product/category', 'path=' . $category['category_id'])
            );
        }

        return $this->load->view('module/category', $data);
    }
}
</code>```

My category.tpl module file looks like this:

```<code><h3><?php echo "Potkategorije" ?></h3>
<div class="list-group">
<ul>
    <?php foreach ($categories as $category) { ?>
    <?php if ($category['category_id'] == $category_id) { ?>
    <li class="cat-active">
        <a href="<?php echo $category['href']; ?>" class="active"><?php echo $category['name']; ?></a>
    <?php } else { ?>
    <li>
        <a href="<?php echo $category['href']; ?>"><?php echo $category['name']; ?></a>
        <?php } ?>
        <?php if ($category['children']) { ?>
        <b class="cc"></b>
        <ul class="col-subcat">
            <?php foreach ($category['children'] as $child) { ?>
            <li>
                <?php if ($child['category_id'] == $child_id) { ?>
                <a href="<?php echo $child['href']; ?>" class="active"><?php echo $child['name']; ?></a>
                <?php } else { ?>
                <a href="<?php echo $child['href']; ?>"><?php echo $child['name']; ?></a>
                <?php } ?>
                <?php if ($child['children']) { ?>
                <b class="cc"></b>
                <ul class="col-subcat">
                    <?php foreach ($child['children'] as $child_2) { ?>
                    <li>
                        <?php if ($child_2['category_id'] == $child_id) { ?>
                        <a href="<?php echo $child_2['href']; ?>" class="active"><?php echo $child_2['name']; ?></a>
                        <?php } else { ?>
                        <a href="<?php echo $child_2['href']; ?>"><?php echo $child_2['name']; ?></a>
                        <?php } ?>
                    </li>
                    <?php } ?>
                </ul>
                <?php } ?>
            </li>
            <?php } ?>
        </ul>
        <?php } ?>
    </li>
    <?php } ?>
</ul>
</div>
</code>```

How to modify files to make this work? I appreciate your time, thanx.

答:
I think you have a problem in variable comparison :

```<code><?php foreach ($child['children'] as $child_2) { ?>
<li>
<?php if ($child_2['category_id'] == $child_id) { ?>
</code>```

To

```<code> <?php if ($child_2['category_id'] == $child_2_id) { ?>
</code>```

Body:
This may be a duplicate, but which ever answer I found, didn't solve my problem.  I have category structure like this: Category->Subcategory->Sub sub category. In my category module, I managed to show the whole structure (Category->Subcategory->Subsub category). But what I need is only Subsub categories to show for each Category or subcategory. My  category.php module file looks like this:

<?php
class ControllerModuleCategory extends Controller {
    public function index() {
        $this->load->language('module/category');

        $data['heading_title'] = $this->language->get('heading_title');

        if (isset($this->request->get['path'])) {
            $parts = explode('_', (string)$this->request->get['path']);
        } else {
            $parts = array();
        }

        if (isset($parts[0])) {
            $data['category_id'] = $parts[0];
        } else {
            $data['category_id'] = 0;
        }

        if (isset($parts[1])) {
            $data['child_id'] = $parts[1];
        } else {
            $data['child_id'] = 0;
        }

        $this->load->model('catalog/category');

        $this->load->model('catalog/product');

        $data['categories'] = array();

        $categories = $this->model_catalog_category->getCategories(0);

        foreach ($categories as $category) {
            $children_data = array();

            if ($category['category_id'] == $data['category_id']) {
                $children = $this->model_catalog_category->getCategories($category['category_id']);

                foreach($children as $child) {
                    $children_data_2 = array();

                    $children_2 = $this->model_catalog_category->getCategories($child['category_id']);

                    foreach ($children_2 as $child_2) {
    $filter_data = array(
        'filter_category_id'  => $child_2['category_id'],
        'filter_sub_category' => true
    );

    $children_data_2[] = array(
        'category_id' => $child_2['category_id'],
        'name'        => $child_2['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
        'href'        => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'] . '_' . $child_2['category_id'])
    );
}

                    $filter_data = array('filter_category_id' => $child['category_id'], 'filter_sub_category' => true);

                    $children_data[] = array(
                        'category_id' => $child['category_id'],
                        'name' => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
                        'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id']),
                            'children'    => $children_data_2 // insert this line

                    );
                }
            }

            $filter_data = array(
                'filter_category_id'  => $category['category_id'],
                'filter_sub_category' => true
            );

            $data['categories'][] = array(
                'category_id' => $category['category_id'],
                'name'        => $category['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
                'children'    => $children_data,
                'href'        => $this->url->link('product/category', 'path=' . $category['category_id'])
            );
        }

        return $this->load->view('module/category', $data);
    }
}

My category.tpl module file looks like this:

<?php echo "Potkategorije" ?>

    <?php foreach ($categories as $category) { ?>
    <?php if ($category['category_id'] == $category_id) { ?>

        <a href="<?php echo $category['href']; ?>" class="active"><?php echo $category['name']; ?>
    <?php } else { ?>

        <a href="<?php echo $category['href']; ?>"><?php echo $category['name']; ?>
        <?php } ?>
        <?php if ($category['children']) { ?>

            <?php foreach ($category['children'] as $child) { ?>

                <?php if ($child['category_id'] == $child_id) { ?>
                <a href="<?php echo $child['href']; ?>" class="active"><?php echo $child['name']; ?>
                <?php } else { ?>
                <a href="<?php echo $child['href']; ?>"><?php echo $child['name']; ?>
                <?php } ?>
                <?php if ($child['children']) { ?>

                    <?php foreach ($child['children'] as $child_2) { ?>

                        <?php if ($child_2['category_id'] == $child_id) { ?>
                        <a href="<?php echo $child_2['href']; ?>" class="active"><?php echo $child_2['name']; ?>
                        <?php } else { ?>
                        <a href="<?php echo $child_2['href']; ?>"><?php echo $child_2['name']; ?>
                        <?php } ?>

                    <?php } ?>

                <?php } ?>

            <?php } ?>

        <?php } ?>

    <?php } ?>

How to modify files to make this work? I appreciate your time, thanx.

Body:
I think you have a problem in variable comparison :

<?php foreach ($child['children'] as $child_2) { ?>
<li>
<?php if ($child_2['category_id'] == $child_id) { ?>

To

 <?php if ($child_2['category_id'] == $child_2_id) { ?>


问:
Merge Scala Seq
I have following Seq as input:

```<code>Seq(Seq(1,2),Seq(2,3),Seq(3,4),Seq(7,8),Seq(8,9))
</code>```

I would like to create another Seq from this like below:

```<code>Seq(Seq(1,4),Seq(7,9))
</code>```

I thought to use sliding operation (take 2) and merge as set to remove duplicates but I am not sure how to achieve it using Seq as it is immutable. Can someone help me?

答:
I am not sure if I understand that correctly, but try below code:

```<code>val input = Seq(Seq(1, 2), Seq(2, 3), Seq(3, 4), Seq(7, 8), Seq(8, 9))

input.flatten.groupBy(x => x).mapValues(_.size).filter{
  case (key, value) => value == 1
}.keySet.toList.sorted.grouped(2).toList
</code>```

Output for such is:

```<code>input: Seq[Seq[Int]] = List(List(1, 2), List(2, 3), List(3, 4), List(7, 8), List(8, 9))

res0: List[List[Int]] = List(List(1, 4), List(7, 9))
</code>```

Title: Merge Scala Seq

Body:
I have following Seq as input:

Seq(Seq(1,2),Seq(2,3),Seq(3,4),Seq(7,8),Seq(8,9))

I would like to create another Seq from this like below:

Seq(Seq(1,4),Seq(7,9))

I thought to use sliding operation (take 2) and merge as set to remove duplicates but I am not sure how to achieve it using Seq as it is immutable. Can someone help me?

Body:
I am not sure if I understand that correctly, but try below code:

val input = Seq(Seq(1, 2), Seq(2, 3), Seq(3, 4), Seq(7, 8), Seq(8, 9))

input.flatten.groupBy(x => x).mapValues(_.size).filter{
  case (key, value) => value == 1
}.keySet.toList.sorted.grouped(2).toList

Output for such is:

input: Seq[Seq[Int]] = List(List(1, 2), List(2, 3), List(3, 4), List(7, 8), List(8, 9))

res0: List[List[Int]] = List(List(1, 4), List(7, 9))


问:
How to get value from JSON Array
May I know how to get respond value from JSON in below code format? Currently I'm using this way, but it won't work for me

What I use to get JSON value:

```<code>NSError * err2 = nil;
NSArray* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                options:0
                                                  error:&err2];

NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
</code>```

The JSON value that I wanted to get:

```<code> [
          {
            "Status": 1,
            "NearuCode": "17060521957",
            "ParcelBox": "Thursday"
          },
          {
            "Status": 1,
            "NearuCode": "17060521957",
            "ParcelBox": "Thursday"
          }
        ]
</code>```

答:
Your JSON response is Array not Dictionary also in your response both the object in array are having the same data.

```<code>NSMutableArray *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *dic in jsonObject) {
     NSLog(@"%@", dic[@"Status"])
     NSLog(@"%@", dic[@"NearuCode"])
     NSLog(@"%@", dic[@"ParcelBox"])
}
</code>```

Title: How to get value from JSON Array

Body:
May I know how to get respond value from JSON in below code format? Currently I'm using this way, but it won't work for me

What I use to get JSON value:

NSError * err2 = nil;
NSArray* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                options:0
                                                  error:&err2];

NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];

The JSON value that I wanted to get:

 [
          {
            "Status": 1,
            "NearuCode": "17060521957",
            "ParcelBox": "Thursday"
          },
          {
            "Status": 1,
            "NearuCode": "17060521957",
            "ParcelBox": "Thursday"
          }
        ]

Body:
Your JSON response is Array not Dictionary also in your response both the object in array are having the same data.

NSMutableArray *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *dic in jsonObject) {
     NSLog(@"%@", dic[@"Status"])
     NSLog(@"%@", dic[@"NearuCode"])
     NSLog(@"%@", dic[@"ParcelBox"])
}


答:
Try this code :

```<code>while ($row = mysqli_fetch_array($possible_lang_list))
{
  if($row['name2'] == $x)
  {
     echo '<div class="language" id="' . $row['name2'] . '"><p>' . $row['name1'] . '</p>
  </div>';
  }
  else
  {
    echo '<div class="" id="' . $row['name2'] . '"><p>' . $row['name1'] . '</p>
  </div>';
  }
</code>```

}

Hope it will work

Body:
I want to add CCS style which depends on php IF statement. I have found something: changing the style inside "if" statement, but somehow it doesn`t work, maybe because of WHILE statement in my code.

<?php
$possible_lang_list = mysqli_query($con,
'SELECT * FROM page WHERE title = "lang" ORDER BY name1 ASC');

while ($row = mysqli_fetch_array($possible_lang_list)) {
  echo '

' . $row['name1'] . '

  ';
}
?>

I want to display only div class="language" where $row['name2'] == $x, with possibility to display whole class "language" with JavaScript.  Could anyone help?

I have tried:

 while ($row = mysqli_fetch_array($possible_lang_list)) {
  if ($row['name2'] == $x) {
  ?>

  <?php } else {
  ?>

  <?php
  echo '

' . $row['name1'] . '

';
  }
}

Body:
Try this code :

while ($row = mysqli_fetch_array($possible_lang_list))
{
  if($row['name2'] == $x)
  {
     echo '<div class="language" id="' . $row['name2'] . '"><p>' . $row['name1'] . '</p>
  </div>';
  }
  else
  {
    echo '<div class="" id="' . $row['name2'] . '"><p>' . $row['name1'] . '</p>
  </div>';
  }

}

Hope it will work


问:
How to create an iPhone app that interacts with my website?
What I want to do is to make an iPhone application for my website similar to the photofunia. The users will be able to select an effect from a list, and then upload their own photo. Then the result will be shown in the browser where the user can save the image and/or publish to website like facebook, etc.

What software can I use to do that? Phonegap, appcelerator, etc? Can some of these help?

Thanks.

答: Create a webservice for your website and try to use that in your iPhone Application</p>


问:
How use Window aggrgates on strongly typed Spark Datasets?
I'm slowely trying to adapt to the new (strongly typed) Dataset[U] from Spark 2.x, but struggling to maintain the type info when using Window functions.

```<code>case class Measurement(nb:Long,x:Double)
</code>```

ds being a Dataset[Measurement], I would like to do something like

```<code>ds.map{m => (m,sum($"x").over(Window.orderBy($"nb"))}
</code>```

But this will not work (as it gives my a Dataset[(Measurement,Column)]) instead of Dataset[(Measurement,Double)]

Using withColumn  gives me a Dataset[Row], so I'm loosing the type info:

```<code>ds.withColumn("cumsum",sum($"x").over(Window.orderBy($"nb")))
</code>```

So, is there a better way to use Window functions on strongly typed Datasets?

答:
You can use the as[U] method to convert a Dataframe (or Dataset[Row]) to a Dataset[U]

For you special case :

```<code>ds.withColumn("cumsum",sum($"x").over(Window.orderBy($"nb"))).as[(Measurement,Column)]
</code>```

Hope it helps

Body:
I'm slowely trying to adapt to the new (strongly typed) Dataset[U] from Spark 2.x, but struggling to maintain the type info when using Window functions.

case class Measurement(nb:Long,x:Double)

ds being a Dataset[Measurement], I would like to do something like

ds.map{m => (m,sum($"x").over(Window.orderBy($"nb"))}

But this will not work (as it gives my a Dataset[(Measurement,Column)]) instead of Dataset[(Measurement,Double)]

Using withColumn  gives me a Dataset[Row], so I'm loosing the type info:

ds.withColumn("cumsum",sum($"x").over(Window.orderBy($"nb")))

So, is there a better way to use Window functions on strongly typed Datasets?

Body:
You can use the as[U] method to convert a Dataframe (or Dataset[Row]) to a Dataset[U]

For you special case :

ds.withColumn("cumsum",sum($"x").over(Window.orderBy($"nb"))).as[(Measurement,Column)]

Hope it helps