问:
Grab text from a child element jquery
I have a navigation list as well as a separate headline and paragraph of text. Each list item has its own headline and text. When you hover over a nav item I want the main headline and text to switch.

jsFiddle

Currently my code displays ALL text. I only want to display the H1 & P text found within the class name .spot_titles: https://jsfiddle.net/d28zh777/

To illustrate what i'm trying to achieve:

When you hover over Acne or Oiliness or whatever the headline and text above should change to whatever item you are hovering over. This is the active state and what I'm trying to achieve:

jQuery

```<code>// Get the original content
var main_url = $(".index__hero-image").css('background-image');
var main_title = $(".index__hero-image h1").text();
var main_text = $(".index__hero-image p").text();

$(".index__spot").hover(function () {
  var image_url = $(this).css('background-image');
  // These vars below are wrong I think.
  var spottitle = $(this).text();
  var spottext = $(this).text();

  $(".index__hero-image").css('background-image', image_url);
  $(".index__hero-image h1").text(spottitle);
  $(".index__hero-image p").text(spottext);
},
function() {
  // Display original content when nothing hovered
  $(".index__hero-image").css('background-image', main_url);
  $(".index__hero-image h1").text(main_title);
  $(".index__hero-image p").text(main_text);
});
</code>```

HTML

```<code><div class=" index__text-block">
  <h1>Original headline</h1>
  <p>Original text block goes here</p>
</div>

<div class="solutions-bar">
<a href="acne.html" class="index__spot" style="background-image: url('http://placekitten.com/700/700');">
<!-- Ignore next 3 lines / Create the icon in the link list -->
<img src="icon.png">
<h6 class="content-1">Acne</h6>
<h6 class="content-2">Shop Now</h6>

<!-- Use this text to replace that in index__text-block -->
<div class="spot_titles">
  <h1>Acne headline</h1>
  <p>
    Some text relating to acne
  </p>
</div>
</code>```

答:
As you need to target the child element text, so use .find() with valid selector

```<code>// These vars below are wrong I think.
var spottitle = $(this).find('.spot_titles h1').text();
var spottext = $(this).find('.spot_titles p').text();
</code>```

Fiddle

Title: Grab text from a child element jquery

Body:
I have a navigation list as well as a separate headline and paragraph of text. Each list item has its own headline and text. When you hover over a nav item I want the main headline and text to switch.

jsFiddle

Currently my code displays ALL text. I only want to display the H1 & P text found within the class name .spot_titles: https://jsfiddle.net/d28zh777/

To illustrate what i'm trying to achieve:

When you hover over Acne or Oiliness or whatever the headline and text above should change to whatever item you are hovering over. This is the active state and what I'm trying to achieve:

jQuery

// Get the original content
var main_url = $(".index__hero-image").css('background-image');
var main_title = $(".index__hero-image h1").text();
var main_text = $(".index__hero-image p").text();

$(".index__spot").hover(function () {
  var image_url = $(this).css('background-image');
  // These vars below are wrong I think.
  var spottitle = $(this).text();
  var spottext = $(this).text();

  $(".index__hero-image").css('background-image', image_url);
  $(".index__hero-image h1").text(spottitle);
  $(".index__hero-image p").text(spottext);
},
function() {
  // Display original content when nothing hovered
  $(".index__hero-image").css('background-image', main_url);
  $(".index__hero-image h1").text(main_title);
  $(".index__hero-image p").text(main_text);
});

HTML

Original headline

Original text block goes here

Acne

Shop Now

Acne headline

    Some text relating to acne

Body:
As you need to target the child element text, so use .find() with valid selector

// These vars below are wrong I think.
var spottitle = $(this).find('.spot_titles h1').text();
var spottext = $(this).find('.spot_titles p').text();

Fiddle


来源: stackexchange

问:
Can't import dependency installed with Cocoapods
I've installed FBSDK with Cocoapods but can't import it in my AppDelegate.swift file for some reason. The FBSDK kit appears in my Xcode project so I feel like it should be working.

I'm not an iOS developer by any means, I'm just trying to write a simple native plugin for Flutter SDK. Anyone an idea?

--Here is what the pod file looks like--

```<code># Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

if ENV['FLUTTER_FRAMEWORK_DIR'] == nil
  abort('Please set FLUTTER_FRAMEWORK_DIR to the directory containing Flutter.framework')
end

target 'Runner' do
  use_frameworks!

  # Pods for Runner
pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
pod 'FBSDKShareKit'

  # Flutter Pods
  pod 'Flutter', :path => ENV['FLUTTER_FRAMEWORK_DIR']

  if File.exists? '../.flutter-plugins'
    flutter_root = File.expand_path('..')
    File.foreach('../.flutter-plugins') { |line|
      plugin = line.split(pattern='=')
      if plugin.length == 2
        name = plugin[0].strip()
        path = plugin[1].strip()
        resolved_path = File.expand_path("#{path}/ios", flutter_root)
        pod name, :path => resolved_path
      else
        puts "Invalid plugin specification: #{line}"
      end
    }
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end
</code>```

---EDIT---

I''m getting the following error atm: FBSDKCoreKit.framework: No such file or directory.When I open the Frameworks folder in xCode, all file names are in red:

But that exact folder in Finder is empty. So I guess that's why the error is showing. The question is how to fix this...

This is what my embedded binaries and linked frameworks and libraries look like in the project:

答:
The above solutions for Header Search Path should work.
If you are too lazy to go there.
Copy podfile content, remove all pods, pod install, then revert your podfile, pod install again.... Should work ;-)</p>

ContentLicense: CC BY-SA 3.0

Body:
I've installed FBSDK with Cocoapods but can't import it in my AppDelegate.swift file for some reason. The FBSDK kit appears in my Xcode project so I feel like it should be working.

I'm not an iOS developer by any means, I'm just trying to write a simple native plugin for Flutter SDK. Anyone an idea?

--Here is what the pod file looks like--

# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

if ENV['FLUTTER_FRAMEWORK_DIR'] == nil
  abort('Please set FLUTTER_FRAMEWORK_DIR to the directory containing Flutter.framework')
end

target 'Runner' do
  use_frameworks!

  # Pods for Runner
pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
pod 'FBSDKShareKit'

  # Flutter Pods
  pod 'Flutter', :path => ENV['FLUTTER_FRAMEWORK_DIR']

  if File.exists? '../.flutter-plugins'
    flutter_root = File.expand_path('..')
    File.foreach('../.flutter-plugins') { |line|
      plugin = line.split(pattern='=')
      if plugin.length == 2
        name = plugin[0].strip()
        path = plugin[1].strip()
        resolved_path = File.expand_path("#{path}/ios", flutter_root)
        pod name, :path => resolved_path
      else
        puts "Invalid plugin specification: #{line}"
      end
    }
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end

---EDIT---

I''m getting the following error atm: FBSDKCoreKit.framework: No such file or directory.When I open the Frameworks folder in xCode, all file names are in red:

But that exact folder in Finder is empty. So I guess that's why the error is showing. The question is how to fix this...

This is what my embedded binaries and linked frameworks and libraries look like in the project:


问:
UPDATE MySQL Query taking a long time to execute - ways to optimize
I have a doubt with the following query.

```<code>update src_woz_waardeklasse_2011 a use index(waardeklasse_main,woz_val)
inner join waardeklasse_average b use index (waardeklasse)
on b.waardeklasse_new = a.waardeklasse
set a.woz_value = b.average
where b.waardeklasse_new = a.waardeklasse;
</code>```

I am trying to update a new column 'woz_val' in the 'src_woz_waardeklasse_2011' table using the 'average' values from the 'waardeklasse_average' table. I am joining using the 'waaderklasse' numbers in both the tables. But the 'src_woz_waardeklasse_2011' table is nearly 7 million records and the 'waardeklasee_average' table is 46 records. So the query is taking a really long time. 25 minutes and counting.

Is there a way to optimize it? I am sure it's taking a long time as I am trying to compare values between a large table and a small table. I have included the table structure of both the tables below.

```<code>src_woz_waardeklasse_2011
+----------------------+---------------------------+------+-----+---------+-
---------------+
| Field                | Type                      | Null | Key | Default |
Extra          |
+----------------------+---------------------------+------+-----+---------+-
---------------+
| id                   | int(11) unsigned          | NO   | PRI | NULL    |
auto_increment |
| postcode             | varchar(150)              | YES  | MUL | NULL    |
|
| huisnummeraanduiding | varchar(150)              | YES  |     | NULL    |
|
| huisletter           | varchar(150)              | YES  |     | NULL    |
|
 soort_woonobject     | varchar(150)              | YES  |     | NULL    |
|
| bouwjaar             | varchar(150)              | YES  |     | NULL    |
|
| bouwjaarsklasse      | varchar(150)              | YES  |     | NULL    |
|
| inhoud               | varchar(150)              | YES  |     | NULL    |
|
| reg_oppervlak        | varchar(150)              | YES  |     | NULL    |
|
| woz_value            | int(15) unsigned zerofill | YES  | UNI | NULL    |
|
| reg_oppervlak_bn     | varchar(150)              | YES  |     | NULL    |
|
| waardeklasse         | int(10)                   | NO   | PRI | NULL    |
|
| waardepeildatum      | varchar(150)              | YES  |     | NULL    |
|
| zipandnumber         | varchar(150)              | YES  |     | NULL    |
|
+----------------------+---------------------------+------+-----+---------+-
---------------+

waardeklasse_average
+-------------------------+---------+------+-----+---------+-------+
| Field                   | Type    | Null | Key | Default | Extra |
+-------------------------+---------+------+-----+---------+-------+
| waardeklasse_average_id | int(11) | NO   |     | NULL    |       |
| waardeklasse_new        | int(10) | NO   | PRI | NULL    |       |
| lower                   | int(11) | NO   |     | NULL    |       |
| higher                  | int(11) | NO   |     | NULL    |       |
| average                 | int(11) | NO   | PRI | NULL    |       |
+-------------------------+---------+------+-----+---------+-------+
</code>```

答:
```<code>update src_woz_waardeklasse_2011 a use index(waardeklasse_main,woz_val)
Left join waardeklasse_average b
on b.waardeklasse_new = a.waardeklasse
set a.woz_value = b.average
where b.waardeklasse_new = a.waardeklasse;
</code>```

Use the above query - in this you can use the left join and where condition to speed up the query.

Also don't use the index for the second table which has 46 record this will affect the performance - if the table has less records then index will create more burden in this case full table scan without index is lot better. Also if you have a cluster index in the first table(7 million) remove them and run the query, because for each and every update you perform default table structure And page alignment will be updated in the clustered index. Hope this helps..!

Body:
I have a doubt with the following query.

update src_woz_waardeklasse_2011 a use index(waardeklasse_main,woz_val)
inner join waardeklasse_average b use index (waardeklasse)
on b.waardeklasse_new = a.waardeklasse
set a.woz_value = b.average
where b.waardeklasse_new = a.waardeklasse;

I am trying to update a new column 'woz_val' in the 'src_woz_waardeklasse_2011' table using the 'average' values from the 'waardeklasse_average' table. I am joining using the 'waaderklasse' numbers in both the tables. But the 'src_woz_waardeklasse_2011' table is nearly 7 million records and the 'waardeklasee_average' table is 46 records. So the query is taking a really long time. 25 minutes and counting.

Is there a way to optimize it? I am sure it's taking a long time as I am trying to compare values between a large table and a small table. I have included the table structure of both the tables below.

src_woz_waardeklasse_2011
+----------------------+---------------------------+------+-----+---------+-
---------------+
| Field                | Type                      | Null | Key | Default |
Extra          |
+----------------------+---------------------------+------+-----+---------+-
---------------+
| id                   | int(11) unsigned          | NO   | PRI | NULL    |
auto_increment |
| postcode             | varchar(150)              | YES  | MUL | NULL    |
|
| huisnummeraanduiding | varchar(150)              | YES  |     | NULL    |
|
| huisletter           | varchar(150)              | YES  |     | NULL    |
|
 soort_woonobject     | varchar(150)              | YES  |     | NULL    |
|
| bouwjaar             | varchar(150)              | YES  |     | NULL    |
|
| bouwjaarsklasse      | varchar(150)              | YES  |     | NULL    |
|
| inhoud               | varchar(150)              | YES  |     | NULL    |
|
| reg_oppervlak        | varchar(150)              | YES  |     | NULL    |
|
| woz_value            | int(15) unsigned zerofill | YES  | UNI | NULL    |
|
| reg_oppervlak_bn     | varchar(150)              | YES  |     | NULL    |
|
| waardeklasse         | int(10)                   | NO   | PRI | NULL    |
|
| waardepeildatum      | varchar(150)              | YES  |     | NULL    |
|
| zipandnumber         | varchar(150)              | YES  |     | NULL    |
|
+----------------------+---------------------------+------+-----+---------+-
---------------+

waardeklasse_average
+-------------------------+---------+------+-----+---------+-------+
| Field                   | Type    | Null | Key | Default | Extra |
+-------------------------+---------+------+-----+---------+-------+
| waardeklasse_average_id | int(11) | NO   |     | NULL    |       |
| waardeklasse_new        | int(10) | NO   | PRI | NULL    |       |
| lower                   | int(11) | NO   |     | NULL    |       |
| higher                  | int(11) | NO   |     | NULL    |       |
| average                 | int(11) | NO   | PRI | NULL    |       |
+-------------------------+---------+------+-----+---------+-------+

Body:
update src_woz_waardeklasse_2011 a use index(waardeklasse_main,woz_val)
Left join waardeklasse_average b
on b.waardeklasse_new = a.waardeklasse
set a.woz_value = b.average
where b.waardeklasse_new = a.waardeklasse;

Use the above query - in this you can use the left join and where condition to speed up the query.

Also don't use the index for the second table which has 46 record this will affect the performance - if the table has less records then index will create more burden in this case full table scan without index is lot better. Also if you have a cluster index in the first table(7 million) remove them and run the query, because for each and every update you perform default table structure And page alignment will be updated in the clustered index. Hope this helps..!


答:
Change this lines:

```<code>var spottitle = $(this).text();
var spottext = $(this).text();
</code>```

to this:

```<code>var spottitle = $(this).find('.spot_titles h1').text();
var spottext = $(this).find('.spot_titles p').text();
</code>```

This will get the h1 inside of .spot_titles and the p inside .spot_titles.

You can read more about find() on jQuery API Documentation.

Title: Grab text from a child element jquery

Body:
Change this lines:

var spottitle = $(this).text();
var spottext = $(this).text();

to this:

var spottitle = $(this).find('.spot_titles h1').text();
var spottext = $(this).find('.spot_titles p').text();

This will get the h1 inside of .spot_titles and the p inside .spot_titles.

You can read more about find() on jQuery API Documentation.


问:
how can I use FirstOrDefault()?
I have this code and I want to set a value to Viewdate when the expression returns no data:

```<code>ViewData["Fix"] = db.PreStatusViws.Where(c => c.LkpNameFix == "1").FirstOrDefault().NumCoefficientFix;
</code>```

can I set zero or a "Text" for that? I no, what can I do?!
note: FirstOrDefault(null) cause an error.

答:
If I understand your question correctly, the following code should solve your problem:</p>

```<code>var p = db.PreStatusViws.Where(c => c.LkpNameFix == "1").FirstOrDefault();
if(p != null)
    ViewData["Fix"] = p.NumCoefficientFix;
else
    ViewData["Fix"] = 0;
</code>```

ContentLicense: CC BY-SA 2.5

Title: how can I use FirstOrDefault()?

Body:
I have this code and I want to set a value to Viewdate when the expression returns no data:

ViewData["Fix"] = db.PreStatusViws.Where(c => c.LkpNameFix == "1").FirstOrDefault().NumCoefficientFix;

can I set zero or a "Text" for that? I no, what can I do?!
note: FirstOrDefault(null) cause an error.

Body:
If I understand your question correctly, the following code should solve your problem:

var p = db.PreStatusViws.Where(c => c.LkpNameFix == "1").FirstOrDefault();
if(p != null)
    ViewData["Fix"] = p.NumCoefficientFix;
else
    ViewData["Fix"] = 0;


问:
Unable to respond with basic_card on Actions on Google
I'm building an app using Api.ai with where I need to respond to an Intent named Login by a basic card. I'm trying this without webhook fulfillment.
By Api.ai try section my query returns this:

{
  "id": "bb09aa94-a2d0-48d5-8c7f-62fc688d17b1",
  "timestamp": "2017-07-06T13:19:30.776Z",
  "lang": "en",
  "result": {
"source": "agent",
"resolvedQuery": "login",
"action": "Login",
"actionIncomplete": false,
"parameters": {},
"contexts": [],
"metadata": {
  "intentId": "39842aa0-53c4-4d47-b3b7-61ba0fc6d80c",
  "webhookUsed": "false",
  "webhookForSlotFillingUsed": "false",
  "intentName": "account.login"
},
"fulfillment": {
  "speech": "You should visit http://www.curlpad.com for login.",
  "messages": [
    {
      "type": "basic_card",
      "platform": "google",
      "title": "Login to Curlpad",
      "subtitle": "",
      "formattedText": "Visit this link to login to your account",
      "image": {
        "url": "http://www.curlpad.com/favicons/apple-icon.png"
      },
      "buttons": [
        {
          "title": "Curlpad",
          "openUrlAction": {
            "url": "http://www.curlpad.com"
          }
        }
      ]
    },
    {
      "type": 1,
      "platform": "telegram",
      "title": "Curlpad | Login",
      "subtitle": "Click on login button to continue",
      "imageUrl": "http://www.curlpad.com/favicons/apple-icon.png",
      "buttons": [
        {
          "text": "Login",
          "postback": "http://www.curlpad.com/"
        }
      ]
    },
    {
      "type": 0,
      "speech": "Open this url http://www.curlpad.com"
    }
  ]
},
"score": 1
  },
  "status": {
"code": 200,
"errorType": "success"
  },
  "sessionId": "7ba9cd11-239c-4467-8c3f-2d79d867ba18"
}```

The telegram card works fine on my telegram bot, but gives an error on Actions on Google.
Here is the response on Actions Simulator:

Other query works fine on that simulator.
Can anyone help to make this work?
I've one more intent to search user which works using webhook fulfillment, there also I'm getting the same problem while returning basic_card.

Screenshots of intent response with the try on api.ai:

答:
If you are not using a webhook, you need to do the following 3 steps as cycled
in the screenshot below to enable the basic card response. If you don't see the ACTION ON GOOGLE tab, click on the + sign to add it.

If you are using webhook, below is the sample code that works for me. You can also follow the google documentation below.
google basic card documentation

'use strict';

const express = require('express')();
const router = require('express').Router();
const bodyParser = require('body-parser');
const ApiAiApp = require('actions-on-google').ApiAiApp;

express.use(bodyParser.json({type: 'application/json'}));

router.post('/card', (req, res) => {
 const app = new ApiAiApp({request: req, response: res});
 const WELCOME_INTENT = 'input.welcome';

 const actionMap = new Map();
 actionMap.set(WELCOME_INTENT, welcomeIntent);
 app.handleRequest(actionMap);

});

function welcomeIntent(app){
 app.ask(app.buildRichResponse()
 // Create a basic card and add it to the rich response
 .addSimpleResponse('Math and prime numbers it is!')
  .addBasicCard(app.buildBasicCard(`42 is an even composite number. It
   is composed of three distinct prime numbers multiplied together. It
   has a total of eight divisors. 42 is an abundant number, because the
   sum of its proper divisors 54 is greater than itself. To count from
   1 to 42 would take you about twenty-one…`)
   .setTitle('Math & prime numbers')
   .addButton('Read more')
   .setImage('https://example.google.com/42.png', 'Image alternate text')
  )
 );
}

express.use('/example', router);

express.listen('8081', function () {
  console.log('Example app is running')
})```

Body:
I'm building an app using Api.ai with where I need to respond to an Intent named Login by a basic card. I'm trying this without webhook fulfillment.
By Api.ai try section my query returns this:

{
  "id": "bb09aa94-a2d0-48d5-8c7f-62fc688d17b1",
  "timestamp": "2017-07-06T13:19:30.776Z",
  "lang": "en",
  "result": {
"source": "agent",
"resolvedQuery": "login",
"action": "Login",
"actionIncomplete": false,
"parameters": {},
"contexts": [],
"metadata": {
  "intentId": "39842aa0-53c4-4d47-b3b7-61ba0fc6d80c",
  "webhookUsed": "false",
  "webhookForSlotFillingUsed": "false",
  "intentName": "account.login"
},
"fulfillment": {
  "speech": "You should visit http://www.curlpad.com for login.",
  "messages": [
    {
      "type": "basic_card",
      "platform": "google",
      "title": "Login to Curlpad",
      "subtitle": "",
      "formattedText": "Visit this link to login to your account",
      "image": {
        "url": "http://www.curlpad.com/favicons/apple-icon.png"
      },
      "buttons": [
        {
          "title": "Curlpad",
          "openUrlAction": {
            "url": "http://www.curlpad.com"
          }
        }
      ]
    },
    {
      "type": 1,
      "platform": "telegram",
      "title": "Curlpad | Login",
      "subtitle": "Click on login button to continue",
      "imageUrl": "http://www.curlpad.com/favicons/apple-icon.png",
      "buttons": [
        {
          "text": "Login",
          "postback": "http://www.curlpad.com/"
        }
      ]
    },
    {
      "type": 0,
      "speech": "Open this url http://www.curlpad.com"
    }
  ]
},
"score": 1
  },
  "status": {
"code": 200,
"errorType": "success"
  },
  "sessionId": "7ba9cd11-239c-4467-8c3f-2d79d867ba18"
}

The telegram card works fine on my telegram bot, but gives an error on Actions on Google.
Here is the response on Actions Simulator:

Other query works fine on that simulator.
Can anyone help to make this work?
I've one more intent to search user which works using webhook fulfillment, there also I'm getting the same problem while returning basic_card.

Screenshots of intent response with the try on api.ai:


问:
Java: Sort Arraylist of objects on property
I have a Array list of object for class "Emp"[String eno, skill;   ArrayList<Jobs> Empjobs;].

EmpJobs in itself is an arraylist for class "Jobs"[String jobId, skill;int priority, TTC;].

Now in code I created few object of Emps, say Emp1, Emp2 and they have 2 jobs assigned to each as objects of Jobs class.

job11,job12 assigned to Emp1

job21, job22 assigned to Emp2

I need to sort Arraylist of Emp based on total of their jobs TTC(Time to Completeion). I tried using comparor method but no succeess. Any help will be much appreciated.below are snippets of code.

Also to add,

Emp array values are like : 'EmpId#Skill'

Job Array values are like :  'skill#priority#TTC#JobId'

I am not able to work out Collections.sort(emp2,new MyComparator());

```<code>class EmpJobsAssign{
    class Emp
    {
    String eno, skill;
    ArrayList<Jobs> Empjobs;
    public Emp(){
        }
    @Override
    public String toString() {
        return ("eno:"+this.eno+
                " skill: "+ this.skill+
                " Job: "+  this.Empjobs);
        }
    }

public class MyComparator implements Comparator<Emp> {
@Override
public int compare(Emp e1, Emp e2) {
    if (e1.Empjobs.TTC > e2.Empjobs.TTC)
     {
         return 1;
     }
    else if (e1.Empjobs.TTC > e2.Empjobs.TTC)
    {
        return -1;
    }
    return 0;
}
}

class Jobs
    {
    String jobId, skill;
    int priority, TTC;
    public Jobs(){
     }
     @Override
    public String toString() {
        return ("jobId:"+this.jobId+
                " skill: "+ this.skill +
                " priority: "+ this.priority +
                " TTC: "+ this.TTC);
        }
     }

public static void main(String []args){

        String[] arrayEmp = {"w4#j","w1#c","w2#c","W3#j"};
        String[] arrayJob = {"c#3#25#obj1","j#2#20#obj2","j#1#45#obj3","c#4#45#obj4","c#1#15#obj5"};
        EmpJobsAssign HW =new EmpJobsAssign();
        EmpJobsAssign.Emp emp=HW.new Emp();
        EmpJobsAssign.Jobs job=HW.new Jobs();
        Emp[] emps= HW.SortEmp(arrayEmp,0);
        Jobs[] empjobs=HW.SortJob(arrayJob,1,2);
        int jobindex=0;
        while(jobindex < empjobs.length)
        {
         job=empjobs[jobindex];
            ArrayList<Emp> emp2=new ArrayList<Emp>();
             String AssignedFlag="";
            for(int empindex=0;empindex<emps.length;empindex++)
            {
                AssignedFlag="F";
                emp=emps[empindex];
               if(emp.Empjobs == null) {emp.Empjobs=new ArrayList<Jobs>();}
                if(emp.skill.equals(job.skill) && emp.Empjobs.isEmpty()){
                    emp.Empjobs.add(job);
                    System.out.println("empjobs : " +emp);
                    AssignedFlag="T";
                    System.out.println("Emp2  "+ emp2.size());
                    break;
                }
            }
            System.out.println(" AssignedFlag "+AssignedFlag);
            if(AssignedFlag.equals("F")) {
                Collections.sort(emp2,new MyComparator());
                 System.out.println("Inside If  "+ emp2.get(0));
                Iterator itr=emp2.iterator();
                while(itr.hasNext()){
                    System.out.println("test "+ itr.next());
                }
            }
            jobindex++;
        }
        System.out.println("check");
        System.out.println(Arrays.toString(emps));
        System.out.println(Arrays.toString(empjobs));
 }

private Emp[] SortEmp(String[] a, int index1)
    {
        Emp[] SortEmp=new Emp[a.length];
        for(int i=0;i<a.length;i++){
            for(int j=i+1;j<a.length;j++){
                if(Integer.parseInt(a[i].substring(1,2))>Integer.parseInt(a[j].substring(1,2))){
                    String temp=a[i];
                    a[i]=a[j];
                    a[j]=temp;
                }
                }
                Emp tempEmp = new Emp();
                tempEmp.eno=a[i].split("#")[0];
                tempEmp.skill=a[i].split("#")[1];
            SortEmp[i]=tempEmp;
        }
        return SortEmp;
    }

    private Jobs[] SortJob(String[] a, int index1, int index2)
    {
        Jobs[] SortJobs=new Jobs[a.length];
        for(int i=0;i<a.length;i++){
            for(int j=i+1;j<a.length;j++){
                if(Integer.parseInt(a[i].split("#")[index1])>Integer.parseInt(a[j].split("#")[index1])){
                    String temp=a[i];
                    a[i]=a[j];
                    a[j]=temp;
                }
                 if(Integer.parseInt(a[i].split("#")[index1])==Integer.parseInt(a[j].split("#")[index1])){
                    if(Integer.parseInt(a[i].split("#")[index2]) > Integer.parseInt(a[j].split("#")[index2])){
                    String temp=a[i];
                    a[i]=a[j];
                    a[j]=temp;
                    }
                }
                }
                Jobs tempJobs=new Jobs();
                tempJobs.jobId=a[i].split("#")[3];
                tempJobs.skill=a[i].split("#")[0];
                tempJobs.priority=Integer.parseInt(a[i].split("#")[1]);
                tempJobs.TTC=Integer.parseInt(a[i].split("#")[2]);
            SortJobs[i]=tempJobs;
        }
        return SortJobs;
    }
  }
</code>```

答:
The comparator is incorrectly implemented, both if statements have the same predicate.

```<code>@Override
public int compare(Emp e1, Emp e2) {
    if (e1.Empjobs.TTC > e2.Empjobs.TTC)      // predicate 1
     {
         return 1;
     }
    else if (e1.Empjobs.TTC > e2.Empjobs.TTC) // predicate 2, same as predicate 1
    {
        return -1;
    }
    return 0;
}
</code>```

Change the second predicate to e1.Empjobs.TTC < e2.Empjobs.TTC.

Body:
I have a Array list of object for class "Emp"[String eno, skill;   ArrayList<Jobs> Empjobs;].

EmpJobs in itself is an arraylist for class "Jobs"[String jobId, skill;int priority, TTC;].

Now in code I created few object of Emps, say Emp1, Emp2 and they have 2 jobs assigned to each as objects of Jobs class.

job11,job12 assigned to Emp1

job21, job22 assigned to Emp2

I need to sort Arraylist of Emp based on total of their jobs TTC(Time to Completeion). I tried using comparor method but no succeess. Any help will be much appreciated.below are snippets of code.

Also to add,

Emp array values are like : 'EmpId#Skill'

Job Array values are like :  'skill#priority#TTC#JobId'

I am not able to work out Collections.sort(emp2,new MyComparator());

class EmpJobsAssign{
    class Emp
    {
    String eno, skill;
    ArrayList<Jobs> Empjobs;
    public Emp(){
        }
    @Override
    public String toString() {
        return ("eno:"+this.eno+
                " skill: "+ this.skill+
                " Job: "+  this.Empjobs);
        }
    }

public class MyComparator implements Comparator<Emp> {
@Override
public int compare(Emp e1, Emp e2) {
    if (e1.Empjobs.TTC > e2.Empjobs.TTC)
     {
         return 1;
     }
    else if (e1.Empjobs.TTC > e2.Empjobs.TTC)
    {
        return -1;
    }
    return 0;
}
}

class Jobs
    {
    String jobId, skill;
    int priority, TTC;
    public Jobs(){
     }
     @Override
    public String toString() {
        return ("jobId:"+this.jobId+
                " skill: "+ this.skill +
                " priority: "+ this.priority +
                " TTC: "+ this.TTC);
        }
     }

public static void main(String []args){

        String[] arrayEmp = {"w4#j","w1#c","w2#c","W3#j"};
        String[] arrayJob = {"c#3#25#obj1","j#2#20#obj2","j#1#45#obj3","c#4#45#obj4","c#1#15#obj5"};
        EmpJobsAssign HW =new EmpJobsAssign();
        EmpJobsAssign.Emp emp=HW.new Emp();
        EmpJobsAssign.Jobs job=HW.new Jobs();
        Emp[] emps= HW.SortEmp(arrayEmp,0);
        Jobs[] empjobs=HW.SortJob(arrayJob,1,2);
        int jobindex=0;
        while(jobindex < empjobs.length)
        {
         job=empjobs[jobindex];
            ArrayList<Emp> emp2=new ArrayList<Emp>();
             String AssignedFlag="";
            for(int empindex=0;empindex<emps.length;empindex++)
            {
                AssignedFlag="F";
                emp=emps[empindex];
               if(emp.Empjobs == null) {emp.Empjobs=new ArrayList<Jobs>();}
                if(emp.skill.equals(job.skill) && emp.Empjobs.isEmpty()){
                    emp.Empjobs.add(job);
                    System.out.println("empjobs : " +emp);
                    AssignedFlag="T";
                    System.out.println("Emp2  "+ emp2.size());
                    break;
                }
            }
            System.out.println(" AssignedFlag "+AssignedFlag);
            if(AssignedFlag.equals("F")) {
                Collections.sort(emp2,new MyComparator());
                 System.out.println("Inside If  "+ emp2.get(0));
                Iterator itr=emp2.iterator();
                while(itr.hasNext()){
                    System.out.println("test "+ itr.next());
                }
            }
            jobindex++;
        }
        System.out.println("check");
        System.out.println(Arrays.toString(emps));
        System.out.println(Arrays.toString(empjobs));
 }

private Emp[] SortEmp(String[] a, int index1)
    {
        Emp[] SortEmp=new Emp[a.length];
        for(int i=0;i<a.length;i++){
            for(int j=i+1;jInteger.parseInt(a[j].substring(1,2))){
                    String temp=a[i];
                    a[i]=a[j];
                    a[j]=temp;
                }
                }
                Emp tempEmp = new Emp();
                tempEmp.eno=a[i].split("#")[0];
                tempEmp.skill=a[i].split("#")[1];
            SortEmp[i]=tempEmp;
        }
        return SortEmp;
    }

    private Jobs[] SortJob(String[] a, int index1, int index2)
    {
        Jobs[] SortJobs=new Jobs[a.length];
        for(int i=0;i<a.length;i++){
            for(int j=i+1;jInteger.parseInt(a[j].split("#")[index1])){
                    String temp=a[i];
                    a[i]=a[j];
                    a[j]=temp;
                }
                 if(Integer.parseInt(a[i].split("#")[index1])==Integer.parseInt(a[j].split("#")[index1])){
                    if(Integer.parseInt(a[i].split("#")[index2]) > Integer.parseInt(a[j].split("#")[index2])){
                    String temp=a[i];
                    a[i]=a[j];
                    a[j]=temp;
                    }
                }
                }
                Jobs tempJobs=new Jobs();
                tempJobs.jobId=a[i].split("#")[3];
                tempJobs.skill=a[i].split("#")[0];
                tempJobs.priority=Integer.parseInt(a[i].split("#")[1]);
                tempJobs.TTC=Integer.parseInt(a[i].split("#")[2]);
            SortJobs[i]=tempJobs;
        }
        return SortJobs;
    }
  }

Body:
The comparator is incorrectly implemented, both if statements have the same predicate.

@Override
public int compare(Emp e1, Emp e2) {
    if (e1.Empjobs.TTC > e2.Empjobs.TTC)      // predicate 1
     {
         return 1;
     }
    else if (e1.Empjobs.TTC > e2.Empjobs.TTC) // predicate 2, same as predicate 1
    {
        return -1;
    }
    return 0;
}

Change the second predicate to e1.Empjobs.TTC < e2.Empjobs.TTC.


问:
How to properly use an expression in a scale function in ggplot2?
I am plotting some results with ggplot2. The data are organized in data frame structured like this:

```<code>   category  comparison    value
1  A         deltaXT/FT    6807
2  B         deltaXT/FT    11894
3  C         deltaXT/FT    1215
4  D         deltaXT/FT    42862
5  E         deltaXT/FT    34313
...
</code>```

There are 4 comparisons in total, each subdivided into the categories A-E, in the same data frame (the plot looks like this). My aim is to substitute "deltaXT/FT" with "ΔXT/FT", using the greek symbol for Delta.

In the plot I'm using the "comparison" column to define the colour of the bars, like this:

```<code>ggplot(data=vars, aes(x=category, y=value, fill=comparison)) +
...
scale_fill_manual(values=c("deltaXT/FT"="#6FA9BC"), ...)
</code>```

Basically, everything works just fine while I use "deltaXT/FT" in scale_fill_manual and in the original data frame. If I try to use expression(Delta * "XT/FT")="#6FA9BC", ...) I get this error:

```<code>Error: unexpected '=' in:
...
scale_fill_manual(values=c(expression(Delta * "XT/FT"))="
</code>```

The issue seems to be with scale_fill_manual(): the expression() couldn't be used as key in there. I read other threads here in StackOverflow where people got suggested to use bquote(expression()=value) but the error didn't change when using it.

Any suggestion on how to get past this problem and have a nice ΔXT/FT name in the legend?

EDIT: copy-pasting the Δ character into the Rscript where needed works, but I'm more interested in if the expression() can be used as a key in such situation in general.

答:
You can just change the label associated with each comparison, not the value that's mapping it.

```<code>... +
scale_color_manual(values = c("deltaXT/FT" = "#6FA9BC"),
                   labels = c("deltaXT/FT" = expression(Delta * "XT/FT")))
</code>```

Or, in a complete plot:

```<code>library(ggplot2)
ggplot(data=df, aes(x=category, y=value, color=comparison)) +
  geom_point(size = 5) +
  scale_color_manual(values=c("deltaXT/FT"="#6FA9BC"),
                     labels = expression(Delta * "XT/FT"))
</code>```

Data:

```<code>df <- read.table(text = ' category  comparison    value
1  A         deltaXT/FT    6807
                 2  B         deltaXT/FT    11894
                 3  C         deltaXT/FT    1215
                 4  D         deltaXT/FT    42862
                 5  E         deltaXT/FT    34313', header = TRUE)
</code>```

Body:
I am plotting some results with ggplot2. The data are organized in data frame structured like this:

   category  comparison    value
1  A         deltaXT/FT    6807
2  B         deltaXT/FT    11894
3  C         deltaXT/FT    1215
4  D         deltaXT/FT    42862
5  E         deltaXT/FT    34313
...

There are 4 comparisons in total, each subdivided into the categories A-E, in the same data frame (the plot looks like this). My aim is to substitute "deltaXT/FT" with "ΔXT/FT", using the greek symbol for Delta.

In the plot I'm using the "comparison" column to define the colour of the bars, like this:

ggplot(data=vars, aes(x=category, y=value, fill=comparison)) +
...
scale_fill_manual(values=c("deltaXT/FT"="#6FA9BC"), ...)

Basically, everything works just fine while I use "deltaXT/FT" in scale_fill_manual and in the original data frame. If I try to use expression(Delta * "XT/FT")="#6FA9BC", ...) I get this error:

Error: unexpected '=' in:
...
scale_fill_manual(values=c(expression(Delta * "XT/FT"))="

The issue seems to be with scale_fill_manual(): the expression() couldn't be used as key in there. I read other threads here in StackOverflow where people got suggested to use bquote(expression()=value) but the error didn't change when using it.

Any suggestion on how to get past this problem and have a nice ΔXT/FT name in the legend?

EDIT: copy-pasting the Δ character into the Rscript where needed works, but I'm more interested in if the expression() can be used as a key in such situation in general.

Body:
You can just change the label associated with each comparison, not the value that's mapping it.

... +
scale_color_manual(values = c("deltaXT/FT" = "#6FA9BC"),
                   labels = c("deltaXT/FT" = expression(Delta * "XT/FT")))

Or, in a complete plot:

library(ggplot2)
ggplot(data=df, aes(x=category, y=value, color=comparison)) +
  geom_point(size = 5) +
  scale_color_manual(values=c("deltaXT/FT"="#6FA9BC"),
                     labels = expression(Delta * "XT/FT"))

Data:

df <- read.table(text = ' category  comparison    value
1  A         deltaXT/FT    6807
                 2  B         deltaXT/FT    11894
                 3  C         deltaXT/FT    1215
                 4  D         deltaXT/FT    42862
                 5  E         deltaXT/FT    34313', header = TRUE)


问:
Detecting if this is an iframe load or direct
I am looking to only show a form if it is pulled on a page within an iframe. How do I do that? Is there a server side solution?</p>

答:
I can't think of purely serverside way, but you could use a bit of hybrid javascript/rails.

assuming that you have a dedicated iframe layout template e.g. 'layouts/iframe.erb'

you could put some javascript in the head to check if it is being loaded as an iframe, and if it is not, redirect to an action and maybe display a flash msg "can only load this page inside application"

The javascript/rails for the head

```<code>    <script type="text/javascript">

        function parentExists()
        {
         return (parent.location == window.location)? true : false;
        };

        function check_modal(){
        if (parentExists()) {
          window.location = '<%= url_for( :controller => "home", :action => 'iframe_action', :iframe_fail => 'true')%>'}
        }
        check_modal()
    </script>
</code>```

notice the param :iframe_fail which you could check for in a controller and do whatever you please if that param is present e.g. display flash msg or redirect

example controller

```<code>def iframe_action
  if params[:iframe_fail]
         flash[:notice] = 'can only load inside app'
      else
       #do something else
      end
end
</code>```

Not real pretty but might help you get the job done.

Body:
I can't think of purely serverside way, but you could use a bit of hybrid javascript/rails.

assuming that you have a dedicated iframe layout template e.g. 'layouts/iframe.erb'

you could put some javascript in the head to check if it is being loaded as an iframe, and if it is not, redirect to an action and maybe display a flash msg "can only load this page inside application"

The javascript/rails for the head

    <script type="text/javascript">

        function parentExists()
        {
         return (parent.location == window.location)? true : false;
        };

        function check_modal(){
        if (parentExists()) {
          window.location = '<%= url_for( :controller => "home", :action => 'iframe_action', :iframe_fail => 'true')%>'}
        }
        check_modal()
    </script>

notice the param :iframe_fail which you could check for in a controller and do whatever you please if that param is present e.g. display flash msg or redirect

example controller

def iframe_action
  if params[:iframe_fail]
         flash[:notice] = 'can only load inside app'
      else
       #do something else
      end
end

Not real pretty but might help you get the job done.


问:
Is a non-correlated exists(...) query in the where clause executed for each row or just once?
I have the following query:

```<code>SELECT *
FROM   t1, t2
WHERE  t1.some_id = t2.some_id
       and
       not exists(select true from some_table where some_column = true)
</code>```

Here, the not exists(select true from some_table where ...) does not refer to t1 or t2 from the main query.

Is this not exists(select true from some_table where ...) executed just once or for every tuple from the product between t1 and t2 for which t1.some_id = t2.some_id is true?

In other words, if it is executed just once, an empty table can be returned immediately if the result is false. Logically, we have written:

```<code>if (not exists(select true from some_table where some_column = true))
    SELECT *
    FROM   t1, t2
    WHERE  t1.some_id = t2.some_id
else
    empty table
</code>```

答:
You can even wrap the EXISTS() condition in a pure SQL function, and it will be executed only once:

```<code>-- \i tmp.sql

CREATE TABLE omg
        ( id integer NOT NULL PRIMARY KEY
        , must_pay integer NOT NULL
        );
INSERT INTO omg(id, must_pay) VALUES(1,0);

CREATE FUNCTION owe_money() RETURNS BOOLEAN AS
$func$

SELECT EXISTS(SELECT 1
        FROM omg o
        WHERE o.must_pay > 0
        );
$func$
-- language sql;
language sql STABLE;

EXPLAIN
SELECT owe_money();

INSERT INTO omg(id, must_pay) VALUES(2,100);

EXPLAIN
SELECT owe_money();

EXPLAIN
SELECT * FROM omg
WHERE owe_money();
</code>```

If you add the keyword STABLE to the function definition, the DBMS will know that the return value will not change (within the same transaction/statement). Without STABLE, the function will be invoked once for every row.

```<code>                                           QUERY PLAN
-------------------------------------------------------------------------------------------------
 Seq Scan on omg  (cost=0.00..566.40 rows=713 width=8) (actual time=0.303..0.331 rows=2 loops=1)
   Filter: owe_money()
 Total runtime: 0.384 ms
(3 rows)
</code>```

The result for the STABLE function is a one-time Filter:

```<code>                                             QUERY PLAN
-------------------------------------------------------------------------------------------------------
 Result  (cost=0.25..31.65 rows=2140 width=8) (actual time=0.304..0.316 rows=2 loops=1)
   One-Time Filter: owe_money()
   ->  Seq Scan on omg  (cost=0.25..31.65 rows=2140 width=8) (actual time=0.004..0.009 rows=2 loops=1)
 Total runtime: 0.379 ms
</code>```

(4 rows)

And the same condition as an uncorrelated subquery essentially yields the same plan as the STABLE function (now the subquery is executed once and its result ($0)is tested in the one-time Filter):

```<code>EXPLAIN ANALYZE
SELECT * FROM omg
WHERE EXISTS (
        SELECT 1
        FROM omg o
        WHERE o.must_pay > 0
        );

                                                QUERY PLAN
----------------------------------------------------------------------------------------------------------
 Result  (cost=0.05..31.45 rows=2140 width=8) (actual time=0.022..0.034 rows=2 loops=1)
   One-Time Filter: $0
   InitPlan 1 (returns $0)
     ->  Seq Scan on omg o  (cost=0.00..36.75 rows=713 width=0) (actual time=0.011..0.011 rows=1 loops=1)
           Filter: (must_pay > 0)
           Rows Removed by Filter: 1
   ->  Seq Scan on omg  (cost=0.00..31.40 rows=2140 width=8) (actual time=0.003..0.008 rows=2 loops=1)
 Total runtime: 0.081 ms
(8 rows)
</code>```

But aren't we still scanning through the table and essentially doing where false for each row if that function returned false or where true if that function returned true?

```<code>EXPLAIN ANALYZE
SELECT * FROM omg
WHERE EXISTS (
        SELECT 1
        FROM omg o
        WHERE o.id < 0
        );

                                                         QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------
 Result  (cost=1.66..3.66 rows=100 width=8) (actual time=0.011..0.011 rows=0 loops=1)
   One-Time Filter: $0
   InitPlan 1 (returns $0)
     ->  Index Only Scan using omg_pkey on omg o  (cost=0.14..1.66 rows=1 width=0) (actual time=0.006..0.006 rows=0 loops=1)
           Index Cond: (id < 0)
           Heap Fetches: 0
   ->  Seq Scan on omg  (cost=0.00..2.00 rows=100 width=8) (never executed)
 Total runtime: 0.063 ms
(8 rows)
</code>```

never executed says it all.

Body:
I have the following query:

SELECT *
FROM   t1, t2
WHERE  t1.some_id = t2.some_id
       and
       not exists(select true from some_table where some_column = true)

Here, the not exists(select true from some_table where ...) does not refer to t1 or t2 from the main query.

Is this not exists(select true from some_table where ...) executed just once or for every tuple from the product between t1 and t2 for which t1.some_id = t2.some_id is true?

In other words, if it is executed just once, an empty table can be returned immediately if the result is false. Logically, we have written:

if (not exists(select true from some_table where some_column = true))
    SELECT *
    FROM   t1, t2
    WHERE  t1.some_id = t2.some_id
else
    empty table

Body:
You can even wrap the EXISTS() condition in a pure SQL function, and it will be executed only once:

-- \i tmp.sql

CREATE TABLE omg
        ( id integer NOT NULL PRIMARY KEY
        , must_pay integer NOT NULL
        );
INSERT INTO omg(id, must_pay) VALUES(1,0);

CREATE FUNCTION owe_money() RETURNS BOOLEAN AS
$func$

SELECT EXISTS(SELECT 1
        FROM omg o
        WHERE o.must_pay > 0
        );
$func$
-- language sql;
language sql STABLE;

EXPLAIN
SELECT owe_money();

INSERT INTO omg(id, must_pay) VALUES(2,100);

EXPLAIN
SELECT owe_money();

EXPLAIN
SELECT * FROM omg
WHERE owe_money();

If you add the keyword STABLE to the function definition, the DBMS will know that the return value will not change (within the same transaction/statement). Without STABLE, the function will be invoked once for every row.

                                           QUERY PLAN
-------------------------------------------------------------------------------------------------
 Seq Scan on omg  (cost=0.00..566.40 rows=713 width=8) (actual time=0.303..0.331 rows=2 loops=1)
   Filter: owe_money()
 Total runtime: 0.384 ms
(3 rows)

The result for the STABLE function is a one-time Filter:

                                             QUERY PLAN
-------------------------------------------------------------------------------------------------------
 Result  (cost=0.25..31.65 rows=2140 width=8) (actual time=0.304..0.316 rows=2 loops=1)
   One-Time Filter: owe_money()
   ->  Seq Scan on omg  (cost=0.25..31.65 rows=2140 width=8) (actual time=0.004..0.009 rows=2 loops=1)
 Total runtime: 0.379 ms

(4 rows)

And the same condition as an uncorrelated subquery essentially yields the same plan as the STABLE function (now the subquery is executed once and its result ($0)is tested in the one-time Filter):

EXPLAIN ANALYZE
SELECT * FROM omg
WHERE EXISTS (
        SELECT 1
        FROM omg o
        WHERE o.must_pay > 0
        );

                                                QUERY PLAN
----------------------------------------------------------------------------------------------------------
 Result  (cost=0.05..31.45 rows=2140 width=8) (actual time=0.022..0.034 rows=2 loops=1)
   One-Time Filter: $0
   InitPlan 1 (returns $0)
     ->  Seq Scan on omg o  (cost=0.00..36.75 rows=713 width=0) (actual time=0.011..0.011 rows=1 loops=1)
           Filter: (must_pay > 0)
           Rows Removed by Filter: 1
   ->  Seq Scan on omg  (cost=0.00..31.40 rows=2140 width=8) (actual time=0.003..0.008 rows=2 loops=1)
 Total runtime: 0.081 ms
(8 rows)

But aren't we still scanning through the table and essentially doing where false for each row if that function returned false or where true if that function returned true?

EXPLAIN ANALYZE
SELECT * FROM omg
WHERE EXISTS (
        SELECT 1
        FROM omg o
        WHERE o.id < 0
        );

                                                         QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------
 Result  (cost=1.66..3.66 rows=100 width=8) (actual time=0.011..0.011 rows=0 loops=1)
   One-Time Filter: $0
   InitPlan 1 (returns $0)
     ->  Index Only Scan using omg_pkey on omg o  (cost=0.14..1.66 rows=1 width=0) (actual time=0.006..0.006 rows=0 loops=1)
           Index Cond: (id < 0)
           Heap Fetches: 0
   ->  Seq Scan on omg  (cost=0.00..2.00 rows=100 width=8) (never executed)
 Total runtime: 0.063 ms
(8 rows)

never executed says it all.


问:
url or content as a variable in the header of the page
I am designing a site where external links form various are being shown on my page. I am using

```<code>$url=$_GET['url'];
$website_data = file_get_contents($url);
echo $website_data;
</code>```

so essentially a user would click on a hyperlink which is something like www.test.com/display_page.php?url=http://www.xyz.com/article/2.jpg

My page, list_of_images.php, typically has a list of images with href for each image as above on the page and when any image is clicked it would go to display_page.php, which would show our banner on the top of this page, some text and then this image beneath that. This image could be from any website.

I am currently sending the url directly and grabbing it using GET. I understand that users/hackers can actually do some coding and send commands for the url variable and could break the server or do something harmful and so i would like to avoid this method or sending the url directly in the header. what is the alternate approach for this problem?

答:
I would make sure the url starts with http:// or https://:

```<code>if(preg_match("`^https?://`i", $_GET['url']))
// do stuff
</code>```

You may also want to make sure it isn't pointing anywhere internal:

```<code>if(preg_match('`^https?://(?!localhost|127\.|192\.|10\.0\.)`i', $_GET['url']))
// do stuff
</code>```

Rather than a big dirty regex, you could go for a more elegant host black-list approach, but you get my drift...

Body:
I am designing a site where external links form various are being shown on my page. I am using

$url=$_GET['url'];
$website_data = file_get_contents($url);
echo $website_data;

so essentially a user would click on a hyperlink which is something like www.test.com/display_page.php?url=http://www.xyz.com/article/2.jpg

My page, list_of_images.php, typically has a list of images with href for each image as above on the page and when any image is clicked it would go to display_page.php, which would show our banner on the top of this page, some text and then this image beneath that. This image could be from any website.

I am currently sending the url directly and grabbing it using GET. I understand that users/hackers can actually do some coding and send commands for the url variable and could break the server or do something harmful and so i would like to avoid this method or sending the url directly in the header. what is the alternate approach for this problem?

Body:
I would make sure the url starts with http:// or https://:

if(preg_match("`^https?://`i", $_GET['url']))
// do stuff

You may also want to make sure it isn't pointing anywhere internal:

if(preg_match('`^https?://(?!localhost|127\.|192\.|10\.0\.)`i', $_GET['url']))
// do stuff

Rather than a big dirty regex, you could go for a more elegant host black-list approach, but you get my drift...


问:
How to account for the observer's elevation when calculating sunrise/sunset?
How to account for observer elevation when calculating sunrise/sunset?

Calculating sunrise/set for any lat/longitude is no problem, but how to account for elevation instead of sea-level??? I've run out of combinations to try, and having spent over three days on this am putting my hand up for help

I'm using the excellent public domain C source by Paul Schlyter which seems to be the most common. It DOES let you set "altitude which the Sun should cross", eg -12 for nautical twilight or -35/60 etc, but I'm not sure how to modify that to account for observer elevation above sea level.

For example, Quito in Ecuador is one of the highest cities at 2850m above sea level.

Lat+Lon: -78.46784, -0.18065

Timezone: -5

Elev: 2850m

Using Casio's calculator (http://keisan.casio.com/exec/system/1224686065), one of the few I've found that does account for elevation, it returns the following (Date=Jan 1 2017):

Sunrise=6:14 Sunset=18:22 Elevation=0m      <- i can already get this

Sunrise=6:05 Sunset=18:30 Elevation=2850m   <- but how can i get this?

I'm able to get the first one (elev=0) by setting Altitude=-35/60 (-0.58333) UpperLimb=1.0
But how to get the second?

I'm using the following function:

```<code>int sunriset( int year, int month, int day, double lon, double lat,
                  double altit, int upper_limb, double *trise, double *tset )
/*************************************************************/
/* altit = the altitude which the Sun should cross           */
/*         Set to -35/60 degrees for rise/set, -6 degrees    */
/*         for civil, -12 degrees for nautical and -18       */
/*         degrees for astronomical twilight.                */
/* upper_limb: non-zero -> upper limb, zero -> center        */
/*         Set to non-zero (e.g. 1) when computing rise/set  */
/*         times, and to zero when computing start/end of    */
/*         twilight.                                         */
/**************************************************************/
</code>```

SUNRISE.C (i've made this READY-TO-RUN EXAMPLE): with hard-coded Quito lat/long/etc: https://pastebin.com/XSWR2Hby
Compile: gcc sunrise.c -o sunrise.exe

答:
Assuming a non-elevated surrounding, i.e. on a mountain, not on a large plateau, you could first calculate the circle that is formed by all points that touch the tangents to the surface of the Earth that go through the point of interest (Quito) and then find the earliest sunrise and the latest sunset on this circle. If the sun shines on any part of this circle, it will also shine at the point of interest.

On a plateau, I don't think you need to do anything (and if Quito is on a plateau this means that Casio is wrong) as the right thing to do would be to make the calculations for an Earth with a larger radius or diameter but there is no variable for this in Paul's code. Presumably, the effect of the size of the planet is too small to be relevant and the sun rays reaching Earth are assumed to be parallel (which they are not).

Body:
How to account for observer elevation when calculating sunrise/sunset?

Calculating sunrise/set for any lat/longitude is no problem, but how to account for elevation instead of sea-level??? I've run out of combinations to try, and having spent over three days on this am putting my hand up for help

I'm using the excellent public domain C source by Paul Schlyter which seems to be the most common. It DOES let you set "altitude which the Sun should cross", eg -12 for nautical twilight or -35/60 etc, but I'm not sure how to modify that to account for observer elevation above sea level.

For example, Quito in Ecuador is one of the highest cities at 2850m above sea level.

Lat+Lon: -78.46784, -0.18065

Timezone: -5

Elev: 2850m

Using Casio's calculator (http://keisan.casio.com/exec/system/1224686065), one of the few I've found that does account for elevation, it returns the following (Date=Jan 1 2017):

Sunrise=6:14 Sunset=18:22 Elevation=0m      <- i can already get this

Sunrise=6:05 Sunset=18:30 Elevation=2850m   <- but how can i get this?

I'm able to get the first one (elev=0) by setting Altitude=-35/60 (-0.58333) UpperLimb=1.0
But how to get the second?

I'm using the following function:

int sunriset( int year, int month, int day, double lon, double lat,
                  double altit, int upper_limb, double *trise, double *tset )
/*************************************************************/
/* altit = the altitude which the Sun should cross           */
/*         Set to -35/60 degrees for rise/set, -6 degrees    */
/*         for civil, -12 degrees for nautical and -18       */
/*         degrees for astronomical twilight.                */
/* upper_limb: non-zero -> upper limb, zero -> center        */
/*         Set to non-zero (e.g. 1) when computing rise/set  */
/*         times, and to zero when computing start/end of    */
/*         twilight.                                         */
/**************************************************************/

SUNRISE.C (i've made this READY-TO-RUN EXAMPLE): with hard-coded Quito lat/long/etc: https://pastebin.com/XSWR2Hby
Compile: gcc sunrise.c -o sunrise.exe


问:
LocalStorage TextBox's in JSON
Weave: https://codepen.io/anon/pen/BZVdaM?editors=0010

I'm using LocalStorage to remember the states of input[type=text] elements. I was able to push to a JSON fine

```<code>{"website": "value","behance": "value","dribbble": "value"}
</code>```

However, my problem now is I'm having difficulty populating the saved data on back in the inputs for page load.

On first run the string returned shouldn't have the quote outside of it; in addition, I noticed after 2nd run it wouldn't show any of the saved data.

Here's the result from Chrome Dev Tools (this is after the 2nd run adding text to another textbox)

Thus what am I doing wrong?

var arr = localStorage.getItem("socialValues") || {};
if ( localStorage.getItem("socialValues")) {
  var savedArrData = JSON.parse(arr);
  $.each(savedArrData, function(key, value) {
    $("[data-social=links] input#" + key).val(value);
  });
}
$("[data-social=links] input").on("change keyup", function() {
  var id = this.id;
  arr[id] = (this.value ? '"' + this.value + '"' : "");
  localStorage.removeItem("socialValues");
  localStorage.setItem("socialValues", JSON.stringify(arr));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="uk-nav uk-nav-default" data-social="links">
  <li>

      <span class="uk-margin-small-right" uk-icon="icon: world"></span>
      <input id="website" class="socialbox" type="text" placeholder="http://yoursite.com/" value="hello world">

  </li>
  <li>

      <span class="uk-margin-small-right" uk-icon="icon: behance"></span>
      <input id="behance" class="socialbox" type="text" placeholder="Your behance page">

  </li>
  <li>

      <span class="uk-margin-small-right" uk-icon="icon: dribbble"></span>
      <input id="dribbble" class="socialbox" type="text" placeholder="Your dribbble page">

  </li>
</ul></code>```

答:
You had multiple issues in your code

On first run the string returned shouldn't have the quote outside of it

This is because you're saving the strings with multiple quotes.

```<code>arr[id] = (this.value ? '"' + this.value + '"' : "");
</code>```

Should be:

```<code>savedArrData[id] = (this.value ? this.value : "");
</code>```

in addition, I noticed after 2nd run it wouldn't show any of the saved data.

This is because you load the initial arr incorrectly.

```<code>var arr = localStorage.getItem("socialValues") || {};
</code>```

If the local storage is empty you load an object into arr. localStorage.getItem() returns a string therefore on next loads arr holds a string. This causes:

```<code>arr[id] = (this.value ? '"' + this.value + '"' : "");
</code>```

To stop working on the next loads.

So what you need to do is to load string into arr, parse it into an object savedArrData and then work only on the object.

```<code>var obj = localStorage.getItem("socialValues") || "{}";
var savedArrData = JSON.parse(obj);

$.each(savedArrData, function (key, value) {
    $("[data-social=links] input#" + key).val(value);
});

$("[data-social=links] input").on("change keyup", function () {
    var id = this.id;
    savedArrData[id] = (this.value ? this.value : "");
    localStorage.removeItem("socialValues");
    localStorage.setItem("socialValues", JSON.stringify(savedArrData));
});
</code>```

Here is a working demo with all changes

BTW

arr should be actually named obj as its an object rather than an array.

Title: LocalStorage TextBox's in JSON

Body:
Weave: https://codepen.io/anon/pen/BZVdaM?editors=0010

I'm using LocalStorage to remember the states of input[type=text] elements. I was able to push to a JSON fine

{"website": "value","behance": "value","dribbble": "value"}

However, my problem now is I'm having difficulty populating the saved data on back in the inputs for page load.

On first run the string returned shouldn't have the quote outside of it; in addition, I noticed after 2nd run it wouldn't show any of the saved data.

Here's the result from Chrome Dev Tools (this is after the 2nd run adding text to another textbox)

Thus what am I doing wrong?

var arr = localStorage.getItem("socialValues") || {};
if ( localStorage.getItem("socialValues")) {
  var savedArrData = JSON.parse(arr);
  $.each(savedArrData, function(key, value) {
    $("[data-social=links] input#" + key).val(value);
  });
}
$("[data-social=links] input").on("change keyup", function() {
  var id = this.id;
  arr[id] = (this.value ? '"' + this.value + '"' : "");
  localStorage.removeItem("socialValues");
  localStorage.setItem("socialValues", JSON.stringify(arr));
});

      <input id="website" class="socialbox" type="text" placeholder="http://yoursite.com/" value="hello world">

      <input id="behance" class="socialbox" type="text" placeholder="Your behance page">

      <input id="dribbble" class="socialbox" type="text" placeholder="Your dribbble page">

Body:
You had multiple issues in your code

On first run the string returned shouldn't have the quote outside of it

This is because you're saving the strings with multiple quotes.

arr[id] = (this.value ? '"' + this.value + '"' : "");

Should be:

savedArrData[id] = (this.value ? this.value : "");

in addition, I noticed after 2nd run it wouldn't show any of the saved data.

This is because you load the initial arr incorrectly.

var arr = localStorage.getItem("socialValues") || {};

If the local storage is empty you load an object into arr. localStorage.getItem() returns a string therefore on next loads arr holds a string. This causes:

arr[id] = (this.value ? '"' + this.value + '"' : "");

To stop working on the next loads.

So what you need to do is to load string into arr, parse it into an object savedArrData and then work only on the object.

var obj = localStorage.getItem("socialValues") || "{}";
var savedArrData = JSON.parse(obj);

$.each(savedArrData, function (key, value) {
    $("[data-social=links] input#" + key).val(value);
});

$("[data-social=links] input").on("change keyup", function () {
    var id = this.id;
    savedArrData[id] = (this.value ? this.value : "");
    localStorage.removeItem("socialValues");
    localStorage.setItem("socialValues", JSON.stringify(savedArrData));
});

Here is a working demo with all changes

BTW

arr should be actually named obj as its an object rather than an array.


问:
Align columns output c++
I want read a file where there are the names of AC Milan's players and their date of birth. I want display this in two aligned columns. I tried to use setw() and left but the result isn't what I want. This is the code that I used for read and print:

```<code>void read(char filename[]){
    fstream mio_file;
    char c;
    bool start_name = true;
    bool start_date = true;

    mio_file.open(filename, ios_base::in | ios_base::binary);

    mio_file.read(&c, sizeof(char));
    while(!mio_file.eof()){

        if(c >= 'A' && c <= 'z' && start_name){
            cout << endl << "Name : ";
            start_name = false;
            start_date = true;
        }
        if(c >= '0' && c <= '9' && start_date){
            cout << setw(25) << left << "Date of birth : ";
            start_date = false;
            start_name = true;
        }

        cout << c;
        mio_file.read(&c, sizeof(char));
    }

    mio_file.close();
}
</code>```

This is output :

And this is output that I want :

答:
(N.B. I'm guessing at your input data, which you did not provide.)

You put setw in the wrong place.

It goes before the thing you're columnising, not afterwards. (This is because the manipulator needs to start counting characters in order to make it work.)

So, instead of (example):

```<code>cout << setw(25) << left << "Date of birth : ";
</code>```

try (example):

```<code>cout << endl << "Name : " << setw(25) << left;
</code>```

Now the stream is set up to treat the next insertion (i.e your. cout << c) as columnar, left-aligned with width 25.

Unfortunately, you're reading individual characters at a time, so your IO manipulator is never going to work on the full name; only individual characters.

So you're also going to have to do some buffering before you feed cout with full strings (example):

```<code>std::string token;
mio_file.read(&c, sizeof(char));
while(!mio_file.eof()){

    if (c >= 'A' && c <= 'z' && start_name) {
        cout << token;
        cout << endl << "Name : " << setw(25) << left;
        token = "";
        start_name = false;
        start_date = true;
    }
    if (c >= '0' && c <= '9' && start_date) {
        cout << token;
        cout << "Date of birth : ";
        token = "";
        start_date = false;
        start_name = true;
    }

    token += c;
    mio_file.read(&c, sizeof(char));
}

// Final write
cout << token;
</code>```

I'm sure there's a better way of implementing this loop, though.

Title: Align columns output c++

Body:
I want read a file where there are the names of AC Milan's players and their date of birth. I want display this in two aligned columns. I tried to use setw() and left but the result isn't what I want. This is the code that I used for read and print:

void read(char filename[]){
    fstream mio_file;
    char c;
    bool start_name = true;
    bool start_date = true;

    mio_file.open(filename, ios_base::in | ios_base::binary);

    mio_file.read(&c, sizeof(char));
    while(!mio_file.eof()){

        if(c >= 'A' && c <= 'z' && start_name){
            cout << endl << "Name : ";
            start_name = false;
            start_date = true;
        }
        if(c >= '0' && c <= '9' && start_date){
            cout << setw(25) << left << "Date of birth : ";
            start_date = false;
            start_name = true;
        }

        cout << c;
        mio_file.read(&c, sizeof(char));
    }

    mio_file.close();
}

This is output :

And this is output that I want :

Body:
(N.B. I'm guessing at your input data, which you did not provide.)

You put setw in the wrong place.

It goes before the thing you're columnising, not afterwards. (This is because the manipulator needs to start counting characters in order to make it work.)

So, instead of (example):

cout << setw(25) << left << "Date of birth : ";

try (example):

cout << endl << "Name : " << setw(25) << left;

Now the stream is set up to treat the next insertion (i.e your. cout << c) as columnar, left-aligned with width 25.

Unfortunately, you're reading individual characters at a time, so your IO manipulator is never going to work on the full name; only individual characters.

So you're also going to have to do some buffering before you feed cout with full strings (example):

std::string token;
mio_file.read(&c, sizeof(char));
while(!mio_file.eof()){

    if (c >= 'A' && c <= 'z' && start_name) {
        cout << token;
        cout << endl << "Name : " << setw(25) << left;
        token = "";
        start_name = false;
        start_date = true;
    }
    if (c >= '0' && c <= '9' && start_date) {
        cout << token;
        cout << "Date of birth : ";
        token = "";
        start_date = false;
        start_name = true;
    }

    token += c;
    mio_file.read(&c, sizeof(char));
}

// Final write
cout << token;

I'm sure there's a better way of implementing this loop, though.


问:
How to remove elements from queue in javascript?
I was trying to use the queue inside javascript. I was referring this link

I was able to add to queue, but while trying to remove from queue i was not successful completely.

```<code>var queue = [];
var input = $(".text").text();
for (var i = 0; i < input.length; i++) {
  queue.push("<span class='charToFade'>" + input.charAt(i) +"</span>");
}
$(".text").text("");
for (var j = 0; j < queue.length; j++) {
  $(".text").append(queue.shift());
}
</code>```

Input:

```<code><div class="text">Phone</div>
</code>```

Output:

```<code>Pho
</code>```

you can check the Jsfiddle

Can any one help me here

答:
While you loop the queue in each iteration the length will get reduced by 1. So It won't iterate completely.

```<code>var queue = [];
var input = $(".text").text();
for (var i = 0; i < input.length; i++) {
  queue.push("<span class='charToFade'>" + input.charAt(i) + "</span>");
}
$(".text").text("");
var l = queue.length;
for (var j = 0; j <l ; j++) {
    var e = queue.shift();
  $(".text").append(e);
}
</code>```

Body:
I was trying to use the queue inside javascript. I was referring this link

I was able to add to queue, but while trying to remove from queue i was not successful completely.

var queue = [];
var input = $(".text").text();
for (var i = 0; i < input.length; i++) {
  queue.push("" + input.charAt(i) +"");
}
$(".text").text("");
for (var j = 0; j < queue.length; j++) {
  $(".text").append(queue.shift());
}

Input:

Phone

Output:

Pho

you can check the Jsfiddle

Can any one help me here

Body:
While you loop the queue in each iteration the length will get reduced by 1. So It won't iterate completely.

var queue = [];
var input = $(".text").text();
for (var i = 0; i < input.length; i++) {
  queue.push("<span class='charToFade'>" + input.charAt(i) + "</span>");
}
$(".text").text("");
var l = queue.length;
for (var j = 0; j <l ; j++) {
    var e = queue.shift();
  $(".text").append(e);
}


问:
relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
So I ve been trying to recompile with -fPIC but it seems I am getting the same error, am I doing it right or am I missing something else?

```<code>all: pr1 pr2

pr1:
    g++ -std=c++11 -fPIC -c $(wildcard pr1.cpp)
    g++ -std=c++11 -o $(PROGRAM) pr1.o $(LIBRARY) $(LINKER_FLAGS)
    rm -f pr1.o
pr2:
    g++ -std=c++11 -fPIC -c $(wildcard pr2.cpp)
    g++ -std=c++11 -o $(PROGRAM1) pr2.o $(LIBRARY) $(LINKER_FLAGS)
    rm -f pr2.o
</code>```

The problem seems to occur at the second program (pr2), possibly when I am trying to reuse LIBRARY(.a file)?

答: apparently I was not removing the .a library that was produced . make clean first</p>

Body:
So I ve been trying to recompile with -fPIC but it seems I am getting the same error, am I doing it right or am I missing something else?

all: pr1 pr2

pr1:
    g++ -std=c++11 -fPIC -c $(wildcard pr1.cpp)
    g++ -std=c++11 -o $(PROGRAM) pr1.o $(LIBRARY) $(LINKER_FLAGS)
    rm -f pr1.o
pr2:
    g++ -std=c++11 -fPIC -c $(wildcard pr2.cpp)
    g++ -std=c++11 -o $(PROGRAM1) pr2.o $(LIBRARY) $(LINKER_FLAGS)
    rm -f pr2.o

The problem seems to occur at the second program (pr2), possibly when I am trying to reuse LIBRARY(.a file)?


问:
Append function of string builder not working in ssrs custom code
i have built a function in ssrs custom code but append function is not working and giving error "character is not valid"</p>

```<code>Public Function fnErrRecommendation (ByVal ErrRecommendation As String
) As String
Dim Result As New System.Text.StringBuilder()

Dim ErrRecom As String() = ErrRecommendation.Split("|")
                for  i as Integer = 0 to ErrRecom.Length-1
                    IF (NOT String.IsNullOrEmpty(ErrRecom(0))) THEN
                       Result=Result.Append(i + 1 + ".").Append(ErrRecom(i));
                        IF (i < ErrRecom.Length - 1) THEN

                           Result= Result.Append("<br><br>");
                        End If
                    End If

                Next

RETURN Result
End Function
</code>```

答:
Since the embedded code language is VB you have to remove the semicolon from your code.

Also your code has the following errors:

You must convert i+1 to string before appending it to the string builder

```<code>Result=Result.Append(Cstr(i + 1) + ".").Append(ErrRecom(i))
</code>```

Your function returns a string so you have to use ToString() method of string builder RETURN Result.ToString()

Body:
i have built a function in ssrs custom code but append function is not working and giving error "character is not valid"

Public Function fnErrRecommendation (ByVal ErrRecommendation As String
) As String
Dim Result As New System.Text.StringBuilder()

Dim ErrRecom As String() = ErrRecommendation.Split("|")
                for  i as Integer = 0 to ErrRecom.Length-1
                    IF (NOT String.IsNullOrEmpty(ErrRecom(0))) THEN
                       Result=Result.Append(i + 1 + ".").Append(ErrRecom(i));
                        IF (i < ErrRecom.Length - 1) THEN

                           Result= Result.Append("

");
                        End If
                    End If

                Next

RETURN Result
End Function

Body:
Since the embedded code language is VB you have to remove the semicolon from your code.

Also your code has the following errors:

You must convert i+1 to string before appending it to the string builder

Result=Result.Append(Cstr(i + 1) + ".").Append(ErrRecom(i))

Your function returns a string so you have to use ToString() method of string builder RETURN Result.ToString()


问:
Python threads all executing on a single core
I have a Python program that spawns many threads, runs 4 at a time, and each performs an expensive operation. Pseudocode:

```<code>for object in list:
    t = Thread(target=process, args=(object))
    # if fewer than 4 threads are currently running, t.start(). Otherwise, add t to queue
</code>```

But when the program is run, Activity Monitor in OS X shows that 1 of the 4 logical cores is at 100% and the others are at nearly 0. Obviously I can't force the OS to do anything but I've never had to pay attention to performance in multi-threaded code like this before so I was wondering if I'm just missing or misunderstanding something.

Thanks.

答:
Python has a Global Interpreter Lock, which can prevent threads of interpreted code from being processed concurrently.

http://en.wikipedia.org/wiki/Global_Interpreter_Lock

http://wiki.python.org/moin/GlobalInterpreterLock

For ways to get around this, try the multiprocessing module, as advised here:

Does running separate python processes avoid the GIL?

Body:
I have a Python program that spawns many threads, runs 4 at a time, and each performs an expensive operation. Pseudocode:

for object in list:
    t = Thread(target=process, args=(object))
    # if fewer than 4 threads are currently running, t.start(). Otherwise, add t to queue

But when the program is run, Activity Monitor in OS X shows that 1 of the 4 logical cores is at 100% and the others are at nearly 0. Obviously I can't force the OS to do anything but I've never had to pay attention to performance in multi-threaded code like this before so I was wondering if I'm just missing or misunderstanding something.

Thanks.


问:
How to get string of selection field?
i have following selection fields in my module i want to get string value of selection field. suppose user select 'o' i want to print O - Original please provide me any better solution.

```<code>type = fields.Selection([
                        ('o', 'O - Original'),
                        ('a', 'A - Amended')],
                         string="Is this an Original Invoice or Amended Invoice ?"
</code>```

i have this solution

```<code>def get_string_value_of_selection():
    if self.type == 'o':
        value = "O - Original",
    if self.type == 'a':
        value = "A - Amended"

    print "value = ",value
</code>```

output

if user select o

```<code>value = O - Original
</code>```

答:
it can be archive as follow. working in odoo 9, 10 not tried in 8

```<code>print dict(self._fields['type'].selection).get(self.type)
</code>```

if user select o

output
O - Original

Title: How to get string of selection field?

Body:
i have following selection fields in my module i want to get string value of selection field. suppose user select 'o' i want to print O - Original please provide me any better solution.

type = fields.Selection([
                        ('o', 'O - Original'),
                        ('a', 'A - Amended')],
                         string="Is this an Original Invoice or Amended Invoice ?"

i have this solution

def get_string_value_of_selection():
    if self.type == 'o':
        value = "O - Original",
    if self.type == 'a':
        value = "A - Amended"

    print "value = ",value

output

if user select o

value = O - Original

Body:
it can be archive as follow. working in odoo 9, 10 not tried in 8

print dict(self._fields['type'].selection).get(self.type)

if user select o

output
O - Original


问:
Why can't I directly assign an int to an int pointer like this: int *p = 6;?
error: invalid conversion from 'int' to 'int*'

int *q = 8;

Works fine.

*q = 6;

Why can't I directly assign an int to an int pointer like this: int *q = 6; and I can assign it safely in the next line?

答: In this case you are assigning value 8 to pointer *q and it wont work during initialization, Memory address is unique at that time not available to assign but you can set once memory block created after initialization for *q.</p>


问:
Why do `set shm+=s` and `cno <silent> <cr> <cr>` make Vim display a search command, when the pattern has no match in the current buffer?
If I start Vim with a minimum of initializations:

```<code>vim -Nu NONE /path/to/a/file
</code>```

Then execute the following 2 commands:

```<code>set shm+=s
cno <silent> <cr> <cr>
</code>```

And finally search for a pattern which has no match in the current buffer:

```<code>/pattern_with_no_match
</code>```

Vim displays the error:

```<code>E486: Pattern not found: pattern_with_no_match
</code>```

... which is expected. But Vim also displays a line showing the literal search command. Because of this, in total, Vim displays 2 lines + a prompt:

```<code>/pattern_with_no_match
E486: Pattern not found: pattern_with_no_match
Press ENTER or type command to continue
</code>```

Instead of just one line with no prompt:

```<code>E486: Pattern not found: pattern_with_no_match
</code>```

If I remove the s flag from the 'shortmess' option:

```<code>set shm-=s
</code>```

Or if I remove the <silent> argument in the mapping:

```<code>cno <cr> <cr>
</code>```

Vim displays only 1 line again:

```<code>E486: Pattern not found: pattern_with_no_match
</code>```

Adding the s flag to 'shortmess' suppresses the messages such as:

```<code>search hit BOTTOM, continuing at TOP
</code>```

And the <silent> argument passed to the :cnoremap command should prevent the mapping from being echoed on the command line.

None of these settings should make Vim more verbose.
So, why does the combination of the setting set shm+=s and the mapping cno <silent> <cr> <cr>, makes Vim display a search command, when the pattern has no match in the current buffer?

It may be a known issue, because I've just found a comment inside a plugin which seems related:

```<code>set shm+=s
cno <silent> <cr> <cr>
</code>```0

But I can't find the relevant section in the help which describes it.

There's this line in :h map-<silent>:

```<code>set shm+=s
cno <silent> <cr> <cr>
</code>```1

But it's about abbreviations not mappings. Maybe the 2 are linked though.

答:
Vim has some built-in logic to determine whether a user message has been shown and can be discarded. Only when there are more messages at once, the hit-enter prompt will occur. By silencing the <CR> in the command-line, you disrupt this logic; <silent> means no output (by the mapping), but the command-line is still open and contains the typed search. Normally, the search wrap message would then clear the command-line, but with your 'shm' setting, you're disabling that, too. Therefore, with the combination of both, you see this effect.

I'm deliberately fuzzy in my explanation because most of this is a side effect of the implementation, and not formally specified. cno <silent> <cr> <cr> doesn't make sense. If you have a real-world use case where this is causing problems, please post details about that. In general, hooking into keys that change modes (like <CR> and <Esc>) is a bad idea and should be avoided.

Body:
If I start Vim with a minimum of initializations:

vim -Nu NONE /path/to/a/file

Then execute the following 2 commands:

set shm+=s
cno <silent> <cr> <cr>

And finally search for a pattern which has no match in the current buffer:

/pattern_with_no_match

Vim displays the error:

E486: Pattern not found: pattern_with_no_match

... which is expected. But Vim also displays a line showing the literal search command. Because of this, in total, Vim displays 2 lines + a prompt:

/pattern_with_no_match
E486: Pattern not found: pattern_with_no_match
Press ENTER or type command to continue

Instead of just one line with no prompt:

E486: Pattern not found: pattern_with_no_match

If I remove the s flag from the 'shortmess' option:

set shm-=s

Or if I remove the <silent> argument in the mapping:

cno <cr> <cr>

Vim displays only 1 line again:

E486: Pattern not found: pattern_with_no_match

Adding the s flag to 'shortmess' suppresses the messages such as:

search hit BOTTOM, continuing at TOP

And the <silent> argument passed to the :cnoremap command should prevent the mapping from being echoed on the command line.

None of these settings should make Vim more verbose.
So, why does the combination of the setting set shm+=s and the mapping cno <silent> <cr> <cr>, makes Vim display a search command, when the pattern has no match in the current buffer?

It may be a known issue, because I've just found a comment inside a plugin which seems related:

" NOTE: This cannot use <silent> - it would break cmdline refresh in some
" cases (e.g. multiline commands, <C-R>= usage).

But I can't find the relevant section in the help which describes it.

There's this line in :h map-<silent>:

Using "<silent>" for an abbreviation is possible, but will cause redrawing of the command line to fail.

But it's about abbreviations not mappings. Maybe the 2 are linked though.


问:
WPF : How to create separate Resources for each item in a bound ItemsControl
I want to achieve the following:

My ViewModel exposes a property named 'Categories' which is a collection of CategoryViewModel objects

Each CategoryViewModel object exposes a property called 'Items' which is a collection of strings*.

On my View, I want a TabControl with a TabItem for each object in the 'Categories' collection.

The Content of each TabItem should be a xceed DataGrid control displaying the contents of the selected tab's Items collection.

```<code><TabControl ItemsSource="{Binding Categories}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding CategoryName}" />
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <xcdg:DataGridControl
                    ItemsSource="{Binding Items}"
                    AutoCreateColumns="True">
            </xcdg:DataGridControl>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>
</code>```

This works ok when I bind directly to the ItemsSource property of the DataGridControl. However, in order to utilize all of the functionality of the DataGridControl, I need to bind the ItemsSource property of the DataGridControl to a DataGridCollectionViewSource object that is bound to my Items collection. I do this when the grid ISN'T nested in another control by creating a DataGridCollectionViewSource object in the Resources section of the UserControl and binding to that.

```<code><UserControl>
    <UserControl.Resources>
        <xcdg:DataGridCollectionViewSource x:Key="GridData"
            Source="{Binding Items}" />
    </UserControl.Resources>
    <Grid>
        <xcdg:DataGridControl
                ItemsSource="{Binding Source={StaticResource GridData}}"
                AutoCreateColumns="True">
        </xcdg:DataGridControl>
    </Grid>
</UserControl>
</code>```

How do I need to structure the XAML so that when the TabControl is being bound, a DataGridCollectionViewSource object is created for each TabItem so that the DataGridControl that is generated within the content of the TabItem can be bound to it?

Clear as mud, right? :)

Thanks!

Notes:

*In the real solution the collection contains objects of a class that is more complex than a simple string, but a string was used to make the example more simple.

答:
You can use x:Shared="True" attribute on a resource. That means a new instance is created for every use of that resource.

Example:

```<code><UserControl.Resources>
    <xcdg:DataGridCollectionViewSource x:Key="GridData"
        x:Shared="False"
        Source="{Binding Items}" />
</UserControl.Resources>
</code>```

Body:
I want to achieve the following:

My ViewModel exposes a property named 'Categories' which is a collection of CategoryViewModel objects

Each CategoryViewModel object exposes a property called 'Items' which is a collection of strings*.

On my View, I want a TabControl with a TabItem for each object in the 'Categories' collection.

The Content of each TabItem should be a xceed DataGrid control displaying the contents of the selected tab's Items collection.

<TabControl ItemsSource="{Binding Categories}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding CategoryName}" />
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <xcdg:DataGridControl
                    ItemsSource="{Binding Items}"
                    AutoCreateColumns="True">
            </xcdg:DataGridControl>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

This works ok when I bind directly to the ItemsSource property of the DataGridControl. However, in order to utilize all of the functionality of the DataGridControl, I need to bind the ItemsSource property of the DataGridControl to a DataGridCollectionViewSource object that is bound to my Items collection. I do this when the grid ISN'T nested in another control by creating a DataGridCollectionViewSource object in the Resources section of the UserControl and binding to that.

<UserControl>
    <UserControl.Resources>
        <xcdg:DataGridCollectionViewSource x:Key="GridData"
            Source="{Binding Items}" />
    </UserControl.Resources>
    <Grid>
        <xcdg:DataGridControl
                ItemsSource="{Binding Source={StaticResource GridData}}"
                AutoCreateColumns="True">
        </xcdg:DataGridControl>
    </Grid>
</UserControl>

How do I need to structure the XAML so that when the TabControl is being bound, a DataGridCollectionViewSource object is created for each TabItem so that the DataGridControl that is generated within the content of the TabItem can be bound to it?

Clear as mud, right? :)

Thanks!

Notes:

*In the real solution the collection contains objects of a class that is more complex than a simple string, but a string was used to make the example more simple.

Body:
You can use x:Shared="True" attribute on a resource. That means a new instance is created for every use of that resource.

Example:

<UserControl.Resources>
    <xcdg:DataGridCollectionViewSource x:Key="GridData"
        x:Shared="False"
        Source="{Binding Items}" />
</UserControl.Resources>


问:
Even after setting TNS_ADMIN, Oracle uses the default tnsnames.ora
In our LINUX box, due to some security reasons we need to test out a Database connectivity using an alternative tnsnames.ora file, instead of making changes directly in the default file under /network/admin. For this reason, after setting $ORACLE_HOME, we are also setting TNS_ADMIN, which points to a dummy tnsnames which we need to use.
For example : export TNS_ADMIN=/psapps/admin/tnsnames.ora
However, even after setting this file, when tried to tnsping, Oracle still uses the default tnsnames.ora

Any suggestions in this matter ?

答:
TNS_ADMIN should point onto a directory, not onto a particular file.

There can be other files in this directory, for example sqlnet.ora.


问:
How could I make the SurfaceView and Button have a different orientation in a Activity
I hava a simple program about video recording .
I use the surfaceView to show the preview screen.
and I also want to put some buttons on the screen.

I put all the component mentioned above into a XML file which is "ipcam.xml"

I use MediaRecorder , SurfaceView , SurfaceHolder to complete this program
because the preview screen does not orientate correctly when I rotate my phone.
so I use "setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);"
but , the button in the program is always in LANDSCAPE direction .
it will not auto change direction when I rotate my phone , but the preview is ok!!

so is there anyway to solve this problem.

Thank you all very much in advance.

you can see this picture , I put my phone in vertical direction
the preview screen seems OK
 but the button is in horizontal direction , i don't want it.

https://newslab.csie.ntu.edu.tw/~poc7667/123.png

答: Did you specify android:configChanges="keyboardHidden|orientation" on your activity's configuration in the manifest.xml?


问:
How to set visibility GONE of views for always with shared preferences in Fragment
I have some views in fragment under TabLayout. I want these views to be hidden with 'view.setVisibility' for always (till clearing app data or uninstalling) after a clicking a button. Can somebody help me please. I don't think this question needs any  code to show you.</p>

答:
When the button is clicked set a boolean value as true in SharedPreference.

Then, in onCreate() function of the layout/fragment in which the views are inflated, check the value from SharedPreference and set the visibility accordingly.


问:
What are the primary differences between Haskell and F#?
I've searched on the Internet for comparisons between F# and Haskell but haven't found anything really definitive. What are the primary differences and why would I want to choose one over the other?</p>

答:
Well, for one I'd say a main advantage is that F# compiles against the .NET platform which makes it easy to deploy on windows. I've seen examples which explained using F# combined with ASP.NET to build web applications ;-)

On the other hand, Haskell has been around for waaaaay longer, so I think the group of people who are real experts on that language is a lot bigger.

For F# I've only seen one real implementation so far, which is the Singularity proof of concept OS. I've seen more real world implementations of Haskell.

OwnerDisplayName: kronoz

LastEditorDisplayName: jolson

OwnerDisplayName: Erik van Brakel


问:
Which is the more efficient regex?
I recently received some job applicant test results in which one person claimed the the solution they gave was more efficient (I won't say which since I don't want to influence the answers). Needless to say, I was sceptical, but I don't know enough about the inner workings of RE compilers to comment intelligently.

The question was: Give a regular expression to recognise numbers from 0 through 99 inclusive.

The answers were:

```<code>[0-9]{1,2}
[0-9]?[0-9]
[0-9]|([0-9][0-9])
</code>```

I'd be interested as to why any of these are faster (or better in any other way). Bonus points for providing evidence rather than conjecture, but I'll still take conjecture if you make it sound convincing enough :-)

答:
Just like C and ++i versus i=i+1, a good regex compiler should compile all three of these to exactly the same finite automaton. If it doesn't, I would consider that a bug.

(Exception: If parenthesized subexpression tagging is enabled, the third would obviously compile to include the extra tagging information.)

Title: Which is the more efficient regex?

Body:
I recently received some job applicant test results in which one person claimed the the solution they gave was more efficient (I won't say which since I don't want to influence the answers). Needless to say, I was sceptical, but I don't know enough about the inner workings of RE compilers to comment intelligently.

The question was: Give a regular expression to recognise numbers from 0 through 99 inclusive.

The answers were:

[0-9]{1,2}
[0-9]?[0-9]
[0-9]|([0-9][0-9])

I'd be interested as to why any of these are faster (or better in any other way). Bonus points for providing evidence rather than conjecture, but I'll still take conjecture if you make it sound convincing enough :-)


问:
Remote mysql Database access error using spark
Accessing Table from remote mysql database, which works fine locally from eclipse but throwing error while trying from spark-submit.

```<code>ERROR SparkContext: Error initializing SparkContext.java.lang.IllegalArgumentException: java.net.UnknownHostException: namenode
at org.apache.hadoop.security.SecurityUtil.buildTokenService(SecurityUtil.java:378)
</code>```

Spark-submit below:

```<code>spark-submit \
--jars /home/hduser/.ivy2/cache/com.typesafe/config/bundles/config-1.3.1.jar \
--class "retail.stack" --master local[2] \
--driver-memory 2g --executor-memory 2g --executor-cores 2 \
sample-spark-180417_2.11-1.0.jar \
/home/hduser/spark-training/workspace/demos/output/extra_in_src \
/home/hduser/spark-training/workspace/demos/output/extradest \
/home/hduser/spark-training/workspace/demos/output/bestMatch
</code>```

Code Below:

```<code>  val spark = SparkSession.builder().master("local").appName("Database")
  .getOrCreate()

val jdbcUsername = "root"
val jdbcPassword = "root"
val url = "jdbc:mysql://192.168.175.35:3306/sample?useSSL=false"

val connectionProperties = new java.util.Properties()
connectionProperties.put("user", jdbcUsername)
connectionProperties.put("password", jdbcPassword)

 val querySource = "(select * from source1) as src"
val queryDestination = "(select * from destination1) as dest"

val source = spark.read.jdbc(url, querySource, connectionProperties).rdd.map(_.mkString(","))
val destination = spark.read.jdbc(url, queryDestination, connectionProperties).rdd.map(_.mkString(","))
</code>```

Thank you

答: I resolved it by reconfiguring the Connection string. It worked fine.!</p>

Body:
Accessing Table from remote mysql database, which works fine locally from eclipse but throwing error while trying from spark-submit.

ERROR SparkContext: Error initializing SparkContext.java.lang.IllegalArgumentException: java.net.UnknownHostException: namenode
at org.apache.hadoop.security.SecurityUtil.buildTokenService(SecurityUtil.java:378)

Spark-submit below:

spark-submit \
--jars /home/hduser/.ivy2/cache/com.typesafe/config/bundles/config-1.3.1.jar \
--class "retail.stack" --master local[2] \
--driver-memory 2g --executor-memory 2g --executor-cores 2 \
sample-spark-180417_2.11-1.0.jar \
/home/hduser/spark-training/workspace/demos/output/extra_in_src \
/home/hduser/spark-training/workspace/demos/output/extradest \
/home/hduser/spark-training/workspace/demos/output/bestMatch

Code Below:

  val spark = SparkSession.builder().master("local").appName("Database")
  .getOrCreate()

val jdbcUsername = "root"
val jdbcPassword = "root"
val url = "jdbc:mysql://192.168.175.35:3306/sample?useSSL=false"

val connectionProperties = new java.util.Properties()
connectionProperties.put("user", jdbcUsername)
connectionProperties.put("password", jdbcPassword)

 val querySource = "(select * from source1) as src"
val queryDestination = "(select * from destination1) as dest"

val source = spark.read.jdbc(url, querySource, connectionProperties).rdd.map(_.mkString(","))
val destination = spark.read.jdbc(url, queryDestination, connectionProperties).rdd.map(_.mkString(","))

Thank you