问:
Facebook webhook making multiple calls for the same message?
I made and echo bot on AWS with Python and serverless.

I keep getting the same request again and again.
I read the faq where it says u have to deliver a status code 200 else it will keep retrying the webhook.

I'm not sure How I do this.

I have noticed that the sequence number is always the same for the calls so I assume the reply I sent was not acknowledged.
my code is here

```<code>import os
import json
import requests
import random
from datetime import datetime
######################
# helper functions
######################
##recursively look/return for an item in dict given key
def find_item(obj, key):
    item = None
    if key in obj: return obj[key]
    for k, v in obj.items():
        if isinstance(v,dict):
            item = find_item(v, key)
            if item is not None:
                return item

##recursivley check for items in a dict given key
def keys_exist(obj, keys):
    for key in keys:
        if find_item(obj, key) is None:
            return(False)
    return(True)

##send txt via messenger to id
def send_message(send_id, msg_txt):
    print("Send message called")
    print (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    params  = {"statusCode": 200,"access_token": os.environment['accesstoken']}
    headers = {"statusCode": "200","Content-Type": "application/json"}
    data = json.dumps({"statusCode": "200","recipient": {"id": send_id},
                       "message": {"text": msg_txt}})

    r = requests.post("https://graph.facebook.com/v2.9/me/messages", params=params, headers=headers, data=data)
    print (r.text)

    if r.status_code != 200:
        print(r.status_code)
        print(r.text)

#-----------------------------------------------------------

def hello(event, context):
    #debug
    event=json.loads(json.dumps(event))
    print("event:" )
    print(event)
    # print("context")
    # print(context)

    #handle webhook challenge
    try:

        if keys_exist(event, ["queryStringParameters","hub.verify_token","hub.challenge"]):
            print("subscribe to webhook invoked")
            v_token   = str(find_item(event, 'hub.verify_token'))
            challenge = find_item(event, 'hub.challenge')
            if ("strongtoken" == v_token):
                response = {
                    "statusCode": 200,
                    "body": str(challenge)
                }
                print(challenge)
                return response

        #handle messaging events
        if keys_exist(event, ['body']):
            event_entry=json.loads(event['body'])
            if ((len(event_entry['entry'])>0) & (keys_exist(event_entry['entry'][0],['messaging'])) ):
                messaging_event = event_entry['entry'][0]['messaging'][0]
                if (keys_exist(messaging_event,['message'])):
                    msg_txt   = messaging_event['message']['text']
                    sender_id = messaging_event['sender']['id']
                    print(sender_id)
                    first_word = msg_txt.split(" ")[0]
                    send_message(sender_id, msg_txt)
                else:
                    print("Did not send message")
                    pass
            else:
                print("Did not send message")
                pass

        else:
            pass
    except:
        pass
</code>```

I have given the status code 200 in soo many places and I'm not sure y I still keep getting the same problem.

答:
If you are getting multiple messages your server did not return 200 status code to webhook request from Facebook server. This means an error occurred on your part otherwise 200 should be returned. It looks to me that problems are in following lines:

```<code>params  = {"statusCode": 200,"access_token": os.environment['accesstoken']}
headers = {"statusCode": "200","Content-Type": "application/json"}
data = json.dumps({"statusCode": "200","recipient": {"id": send_id},
                   "message": {"text": msg_txt}})
</code>```

Firstly you are passing statusCode in a data body of message and according to this documentation message response should not contain it.

Another problem could be sending status code inside params. I would remove status code completely from send_message method. I doubt its needed there. You are basically trying to return status 200 on wrong end. You are trying to return it on output instead of input (from Facebooks point of view).

So its quite possible you are correctly getting message from Facebook but you are still returning wrong status code because you are calling send_message method from inside messaging event and send_message method should return status "400 bad request" because you are sending faulty request. Thus your server also returns wrong response code.

Just make sure your code works correctly and 200 should be returned.

EDIT:
So i would try with following code:

```<code>params  = {"access_token": os.environment['accesstoken']}
headers = {"Content-Type": "application/json"}
data = json.dumps({"recipient": {"id": send_id},
                   "message": {"text": msg_txt}})
</code>```

Body:
I made and echo bot on AWS with Python and serverless.

I keep getting the same request again and again.
I read the faq where it says u have to deliver a status code 200 else it will keep retrying the webhook.

I'm not sure How I do this.

I have noticed that the sequence number is always the same for the calls so I assume the reply I sent was not acknowledged.
my code is here

import os
import json
import requests
import random
from datetime import datetime
######################
# helper functions
######################
##recursively look/return for an item in dict given key
def find_item(obj, key):
    item = None
    if key in obj: return obj[key]
    for k, v in obj.items():
        if isinstance(v,dict):
            item = find_item(v, key)
            if item is not None:
                return item

##recursivley check for items in a dict given key
def keys_exist(obj, keys):
    for key in keys:
        if find_item(obj, key) is None:
            return(False)
    return(True)

##send txt via messenger to id
def send_message(send_id, msg_txt):
    print("Send message called")
    print (datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    params  = {"statusCode": 200,"access_token": os.environment['accesstoken']}
    headers = {"statusCode": "200","Content-Type": "application/json"}
    data = json.dumps({"statusCode": "200","recipient": {"id": send_id},
                       "message": {"text": msg_txt}})

    r = requests.post("https://graph.facebook.com/v2.9/me/messages", params=params, headers=headers, data=data)
    print (r.text)

    if r.status_code != 200:
        print(r.status_code)
        print(r.text)

#-----------------------------------------------------------

def hello(event, context):
    #debug
    event=json.loads(json.dumps(event))
    print("event:" )
    print(event)
    # print("context")
    # print(context)

    #handle webhook challenge
    try:

        if keys_exist(event, ["queryStringParameters","hub.verify_token","hub.challenge"]):
            print("subscribe to webhook invoked")
            v_token   = str(find_item(event, 'hub.verify_token'))
            challenge = find_item(event, 'hub.challenge')
            if ("strongtoken" == v_token):
                response = {
                    "statusCode": 200,
                    "body": str(challenge)
                }
                print(challenge)
                return response

        #handle messaging events
        if keys_exist(event, ['body']):
            event_entry=json.loads(event['body'])
            if ((len(event_entry['entry'])>0) & (keys_exist(event_entry['entry'][0],['messaging'])) ):
                messaging_event = event_entry['entry'][0]['messaging'][0]
                if (keys_exist(messaging_event,['message'])):
                    msg_txt   = messaging_event['message']['text']
                    sender_id = messaging_event['sender']['id']
                    print(sender_id)
                    first_word = msg_txt.split(" ")[0]
                    send_message(sender_id, msg_txt)
                else:
                    print("Did not send message")
                    pass
            else:
                print("Did not send message")
                pass

        else:
            pass
    except:
        pass

I have given the status code 200 in soo many places and I'm not sure y I still keep getting the same problem.

Body:
If you are getting multiple messages your server did not return 200 status code to webhook request from Facebook server. This means an error occurred on your part otherwise 200 should be returned. It looks to me that problems are in following lines:

params  = {"statusCode": 200,"access_token": os.environment['accesstoken']}
headers = {"statusCode": "200","Content-Type": "application/json"}
data = json.dumps({"statusCode": "200","recipient": {"id": send_id},
                   "message": {"text": msg_txt}})

Firstly you are passing statusCode in a data body of message and according to this documentation message response should not contain it.

Another problem could be sending status code inside params. I would remove status code completely from send_message method. I doubt its needed there. You are basically trying to return status 200 on wrong end. You are trying to return it on output instead of input (from Facebooks point of view).

So its quite possible you are correctly getting message from Facebook but you are still returning wrong status code because you are calling send_message method from inside messaging event and send_message method should return status "400 bad request" because you are sending faulty request. Thus your server also returns wrong response code.

Just make sure your code works correctly and 200 should be returned.

EDIT:
So i would try with following code:

params  = {"access_token": os.environment['accesstoken']}
headers = {"Content-Type": "application/json"}
data = json.dumps({"recipient": {"id": send_id},
                   "message": {"text": msg_txt}})


来源: stackexchange

问:
How to obtain a pathname or dentry or struct file from a given inode?
I need to know how to obtain a pathname or dentry or struct file from a given inode.

I was using file_open to obtain struct file from a pathname but but always gave kernel panic. I need a way to compare an inode from my list of inodes with a inode from a pathname or compare all inodes in the disk to find corresponding pathnames, and then compare with my list of inodes.

答:
This sample code will work well in Linux kernel version 2.6.xx

```<code>struct dentry *sample_dentry = NULL;
struct inode *tmp_inode = &inode_need_to_get;
struct list_head *tmp_list = NULL;
list_for_each(tmp_list, &(tmp_inode->i_dentry))
{
    sample_dentry = list_entry(tmp_list, struct dentry, d_alias);
    printk(KERN_EMERG, "name of file is %s\n", sample_dentry->d_iname);
}
</code>```

Each inode object will have one or more dentries object in case this file have a hard link.

ContentLicense: CC BY-SA 3.0

Body:
This sample code will work well in Linux kernel version 2.6.xx

struct dentry *sample_dentry = NULL;
struct inode *tmp_inode = &inode_need_to_get;
struct list_head *tmp_list = NULL;
list_for_each(tmp_list, &(tmp_inode->i_dentry))
{
    sample_dentry = list_entry(tmp_list, struct dentry, d_alias);
    printk(KERN_EMERG, "name of file is %s\n", sample_dentry->d_iname);
}

Each inode object will have one or more dentries object in case this file have a hard link.


问:
Getting "is not a thenable" message while using "eventually" in protractor chai
When I tried to verify the condition as below.

```<code> var val1 = "ONE";
 var val2 = "TWO";
 expect(val1==val2).to.eventually.equal(false)
</code>```

I'm getting false is not a thenable message, If I removed eventually condition as below then it working fine.

```<code> var val1 = "ONE";
 var val2 = "TWO";
 expect(val1==val2).to.equal(false)
</code>```

Can anyone help me to understand the difference. Also If the condition fails, It displays the error message and not executing the hooks.js.

答:
In simple words:

eventually - is a method from chai-as-promised.
If you use eventually protractor expects that you are asserting result of a promise to value (in this case false).
val1 and val2 are bools. Comparison of val1 and val2 is also a bool.

Bool is not a promise.

You've got two possibilities:
1. Don't use eventually (just a chai).
2. Return a promise from comparison of those values.

Body:
When I tried to verify the condition as below.

 var val1 = "ONE";
 var val2 = "TWO";
 expect(val1==val2).to.eventually.equal(false)

I'm getting false is not a thenable message, If I removed eventually condition as below then it working fine.

 var val1 = "ONE";
 var val2 = "TWO";
 expect(val1==val2).to.equal(false)

Can anyone help me to understand the difference. Also If the condition fails, It displays the error message and not executing the hooks.js.


问:
hide-unhide with radio button
Im trying to unhide div id=Q3 with my first 2 radio inputs (id= Q1 & id = Q2)

if   (Q1 = Ja and Q2 = Ja) show Q3.

Can somebody please help me!

See my html code below (sorry for the bad coding im a totally noob!).

HTML

```<code><body>

<header>
    <h2>Helpdesk</h2>
    <div>Wat is u probleem?</div>
</header>

<form>

<h4>Kunt computer normaal aanzetten?<span class = "req" id= "req_Q1">*</span></h4>
<input type="radio" name="A1" id="A1" value ="Ja" /> : Ja<br />
<input type="radio" name="A1" id="A2" value ="Nee" /> : Nee<br />

<p class= "instruct" id="instruct_Q1">
<small>Controleer eerst de kabels!</small>
</p>

<h4 id= "Q2">Geeft de monitor normaal beeld?<span class = "req" id= "req_Q2">*</span> </h4>
<input type="radio" name="A2" id="A3" /> : Ja<br />
<input type="radio" name="A2" id="A4"/> : Nee<br />

<p class= "instruct" id="instruct_Q2">
<small>Controleer eerst de kabels!</small>
</p>
</div>

<div id= "Q3" style="display: none;">
<label for ="Q3.1" ><h4>Start windows normaal op?</h4></label>
<select name="Q3.1">
    <option value="A3.1" >Ja, geen probleem</option>
    <option value="A3.2" >Ja, maar met foutmelding</option>
    <option value="A3.3" >Nee, zwart scherm</option>
    <option value="A3.4" >Nee, blauw scherm</option>
</select>
</div>

<div style="display: none;">
<h4>Kunt u inloggen?</h4>
<input type="radio" name="Q4" />Ja, geen probleem<br />
<input type="radio" name="Q4" /> Nee, ik krijg een foutmelding<br />
</div>

<div style="display: none;">
<h4>Ik krijg de volgende foutmelding <span class = "req" id= "req_Q5">*</span></h4>
<input type="radio" name="Q5" />Kan u niet aanmelden bij het domein. Controleer of uw gebruikersnaam en/of toegangscode correct zijn.<br />
<input type="radio" name="Q5" />Kan u niet aanmelden omdat het domein niet beschikbaar is. <br />
<input type="radio" name="Q5" />Uw account is geblokkeerd. Neem contact op met de beheerder. <br />
</div>
</code>```

Javascript

```<code>  $("input[name=A1]").click(function()
  {
  if(this.id =="A1"){
    $("#Q3").show('slow');
  }
  else {
  $("#Q3").hide('slow');
  }
  });
</code>```

答:
Look at this fiddle, and let me know, if it is the desired result :-) https://jsfiddle.net/7LL98L24/

```<code>$("#helpdesk :input").change(function() {
  if($("#A1").is(':checked') && $("#A3").is(':checked')) {
    $("#Q3").fadeIn(500);
  } else {
    $("#Q3").fadeOut(500);
  }
});
</code>```

Please notice, that I added an ID to your form Element to use the .change Method of jQuery

Title: hide-unhide with radio button

Body:
Im trying to unhide div id=Q3 with my first 2 radio inputs (id= Q1 & id = Q2)

if   (Q1 = Ja and Q2 = Ja) show Q3.

Can somebody please help me!

See my html code below (sorry for the bad coding im a totally noob!).

HTML

Helpdesk

Wat is u probleem?

<form>

Kunt computer normaal aanzetten?*

<input type="radio" name="A1" id="A1" value ="Ja" /> : Ja

<input type="radio" name="A1" id="A2" value ="Nee" /> : Nee

Controleer eerst de kabels!

Geeft de monitor normaal beeld?*

<input type="radio" name="A2" id="A3" /> : Ja

<input type="radio" name="A2" id="A4"/> : Nee

Controleer eerst de kabels!

Start windows normaal op?

<select name="Q3.1">
    <option value="A3.1" >Ja, geen probleem</option>
    <option value="A3.2" >Ja, maar met foutmelding</option>
    <option value="A3.3" >Nee, zwart scherm</option>
    <option value="A3.4" >Nee, blauw scherm</option>
</select>

Kunt u inloggen?

<input type="radio" name="Q4" />Ja, geen probleem

<input type="radio" name="Q4" /> Nee, ik krijg een foutmelding

Ik krijg de volgende foutmelding *

<input type="radio" name="Q5" />Kan u niet aanmelden bij het domein. Controleer of uw gebruikersnaam en/of toegangscode correct zijn.

<input type="radio" name="Q5" />Kan u niet aanmelden omdat het domein niet beschikbaar is.

<input type="radio" name="Q5" />Uw account is geblokkeerd. Neem contact op met de beheerder.

Javascript

  $("input[name=A1]").click(function()
  {
  if(this.id =="A1"){
    $("#Q3").show('slow');
  }
  else {
  $("#Q3").hide('slow');
  }
  });

Body:
Look at this fiddle, and let me know, if it is the desired result :-) https://jsfiddle.net/7LL98L24/

$("#helpdesk :input").change(function() {
  if($("#A1").is(':checked') && $("#A3").is(':checked')) {
    $("#Q3").fadeIn(500);
  } else {
    $("#Q3").fadeOut(500);
  }
});

Please notice, that I added an ID to your form Element to use the .change Method of jQuery


问:
Not able to check the condition on submit button swift
Short description :

I am getting one value called UserValue. This will come from one response.And i have one Confirm button press method. In that each time i need to check whether the user entered amount is greater then UserValue amount.

but some time the value will be UserValue  will be nill.That time it should not check whethere entered amount in text filed is greater than UserValue

Now here my code :

```<code> @IBAction func confirmButnClicked(_ sender: Any) {
 print(UserValue)
 let Mvalue = Double((UserValue.formattedAmount()))
                    let stringValue = Int(Mvalue!)

 if doubleValue < stringValue {
      DialogUtils.showMessageWithOk(controller: self, message:  "Maximum Value is : \(UserValue)")

  }
}
</code>```

Its working fine when i got some value in UserValue but when i get nill value here its crashing...How can i handle this:

```<code>let stringValue = Int(Mvalue!)   // crash here
</code>```

Thanks in advance !!

答:
Instead of force casting MValue to Int you will get error when MValue is nil or anyother type content except integer

```<code> let stringValue = Int(Mvalue!)
</code>```

use like below

```<code>if let stringValue = Int(Mvalue) {
  //Now it prints your perfect unwrapping value
  if doubleValue < stringValue {
      DialogUtils.showMessageWithOk(controller: self, message:  "Maximum Value   is : \(UserValue)")
  }
}
</code>```

Body:
Short description :

I am getting one value called UserValue. This will come from one response.And i have one Confirm button press method. In that each time i need to check whether the user entered amount is greater then UserValue amount.

but some time the value will be UserValue  will be nill.That time it should not check whethere entered amount in text filed is greater than UserValue

Now here my code :

 @IBAction func confirmButnClicked(_ sender: Any) {
 print(UserValue)
 let Mvalue = Double((UserValue.formattedAmount()))
                    let stringValue = Int(Mvalue!)

 if doubleValue < stringValue {
      DialogUtils.showMessageWithOk(controller: self, message:  "Maximum Value is : \(UserValue)")

  }
}

Its working fine when i got some value in UserValue but when i get nill value here its crashing...How can i handle this:

let stringValue = Int(Mvalue!)   // crash here

Thanks in advance !!

Body:
Instead of force casting MValue to Int you will get error when MValue is nil or anyother type content except integer

 let stringValue = Int(Mvalue!)

use like below

if let stringValue = Int(Mvalue) {
  //Now it prints your perfect unwrapping value
  if doubleValue < stringValue {
      DialogUtils.showMessageWithOk(controller: self, message:  "Maximum Value   is : \(UserValue)")
  }
}


问:
How to show html table always on top
I am creating table

#myUL li a {
  background-color: #f6f6f6;
  padding: 5px;
  width: 100%;
  text-decoration: none;
  font-size: 14px;
  color: black;
  display: block;
}

#myUL li a.header {
  background-color: #e2e2e2;
  cursor: default;
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="myInput" list="myUL" onclick="openingList()" onkeyup="openingList()" style="width:90%; ">
<ul id="myUL" hidden=true>
  <li>

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

On click of input tag is myUL is opening. Now I implemented this on the top of some box. Now the problem is when I am clicking, myUL is not displaying fully because it is getting hide because of box. How Can show this always on top.

Note :

Applying z-index is also not working.

Typing in input is also not working.

Can anybody help me to fix this.

答:
You should use z-index,however, it works with (position:absolute, position:relative, or position:fixed)
 So You have to add Position attribute to your #myUL li a style

Title: How to show html table always on top

Body:
I am creating table

#myUL li a {
  background-color: #f6f6f6;
  padding: 5px;
  width: 100%;
  text-decoration: none;
  font-size: 14px;
  color: black;
  display: block;
}

#myUL li a.header {
  background-color: #e2e2e2;
  cursor: default;
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}

<input type="text" id="myInput" list="myUL" onclick="openingList()" onkeyup="openingList()" style="width:90%; ">

On click of input tag is myUL is opening. Now I implemented this on the top of some box. Now the problem is when I am clicking, myUL is not displaying fully because it is getting hide because of box. How Can show this always on top.

Note :

Applying z-index is also not working.

Typing in input is also not working.

Can anybody help me to fix this.


问:
ASP.NET MVC - Order By Date
I am trying to sort table (columns: ID, Name, SermonDate, SermonTitle, BibleReading, VideoLink, BulletinLink) by date (SermonDate) so the data with the newest date comes on top and display it in my MVC application.

After some researching, I've tried putting the below with reference to this and this but nothing worked for me - probably because I misunderstood and put wrong code though.

```<code>public async Task<IActionResult> Index()
{
     return View(await _context.Sermon.OrderBy(sermon =>
     DateTime.Now).Take(5).ToListAsync());
}
</code>```

My current controller (SermonsController.cs):

```<code>public SermonsController(BKPCContext context)
    {
        _context = context;
    }

    public async Task<IActionResult> Index()
    {
        return View(await _context.Sermon.OrderBy(sermon => DateTime.Now).Take(5).ToListAsync());
    }

    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var sermon = await _context.Sermon
            .SingleOrDefaultAsync(m => m.ID == id);
        if (sermon == null)
        {
            return NotFound();
        }

        return View(sermon);
    }

    public IActionResult Create()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("ID,Name,SermonDate,SermonTitle,BibleReading,VideoLink,BulletinLink")] Sermon sermon)
    {
        if (ModelState.IsValid)
        {
            _context.Add(sermon);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        return View(sermon);
    }
</code>```

And the html table in /Sermons/Index.cshtml as below:

```<code><table class="table">
<thead>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.SermonDate)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.SermonTitle)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.BibleReading)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.VideoLink)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.BulletinLink)
        </th>
        <th>

        </th>
    </tr>
</thead>
<tbody>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.SermonDate)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.SermonTitle)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.BibleReading)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.VideoLink)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.BulletinLink)
        </td>
        <td id="aspButton">
            <a role="button" id="btn-primary" class="btn btn-primary" asp-action="Edit" asp-route-id="@item.ID">Edit</a>
            <a role="button" id="btn-danger" class="btn btn-danger" asp-action="Delete" asp-route-id="@item.ID">Delete</a>
        </td>
    </tr>
    }
</tbody>
</code>```

Any help would really be appreciated.

答:
```<code>public class Sermon{
     public int ID {get;set;}
     public DateTime DateAdded {get; set}
}

mySermonList.OrderByDescending(x => x.DateAdded);
</code>```

Title: ASP.NET MVC - Order By Date

Body:
I am trying to sort table (columns: ID, Name, SermonDate, SermonTitle, BibleReading, VideoLink, BulletinLink) by date (SermonDate) so the data with the newest date comes on top and display it in my MVC application.

After some researching, I've tried putting the below with reference to this and this but nothing worked for me - probably because I misunderstood and put wrong code though.

public async Task<IActionResult> Index()
{
     return View(await _context.Sermon.OrderBy(sermon =>
     DateTime.Now).Take(5).ToListAsync());
}

My current controller (SermonsController.cs):

public SermonsController(BKPCContext context)
    {
        _context = context;
    }

    public async Task<IActionResult> Index()
    {
        return View(await _context.Sermon.OrderBy(sermon => DateTime.Now).Take(5).ToListAsync());
    }

    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var sermon = await _context.Sermon
            .SingleOrDefaultAsync(m => m.ID == id);
        if (sermon == null)
        {
            return NotFound();
        }

        return View(sermon);
    }

    public IActionResult Create()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("ID,Name,SermonDate,SermonTitle,BibleReading,VideoLink,BulletinLink")] Sermon sermon)
    {
        if (ModelState.IsValid)
        {
            _context.Add(sermon);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        return View(sermon);
    }

And the html table in /Sermons/Index.cshtml as below:

            @Html.DisplayNameFor(model => model.Name)

            @Html.DisplayNameFor(model => model.SermonDate)

            @Html.DisplayNameFor(model => model.SermonTitle)

            @Html.DisplayNameFor(model => model.BibleReading)

            @Html.DisplayNameFor(model => model.VideoLink)

            @Html.DisplayNameFor(model => model.BulletinLink)

@foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.Name)

            @Html.DisplayFor(modelItem => item.SermonDate)

            @Html.DisplayFor(modelItem => item.SermonTitle)

            @Html.DisplayFor(modelItem => item.BibleReading)

            @Html.DisplayFor(modelItem => item.VideoLink)

            @Html.DisplayFor(modelItem => item.BulletinLink)

            Edit
            Delete

    }

Any help would really be appreciated.


问:
Outside scope this key word in JavaScript?
I am not sure why I'm getting undefined with the code below. I tried to declare a variable under the say method var _this = this and then console.log out _this.name but it did not work.</p>

```<code>let dog = {
  name: 'doggo',
  sayName() {
    console.log(this.name)
  }
}
let sayName = dog.sayName
sayName()
</code>```

答:
```<code>window.name="test";
sayName();//test
</code>```

Executes the function in window context so this is window. You may want to keep the dog context either through passing it:

```<code>sayName.call(dog);//doggo
</code>```

Or through keeping a bound function:

```<code>let sayName = dog.sayName.bind(dog);
sayName();//doggo
</code>```

Body:
I am not sure why I'm getting undefined with the code below. I tried to declare a variable under the say method var _this = this and then console.log out _this.name but it did not work.

let dog = {
  name: 'doggo',
  sayName() {
    console.log(this.name)
  }
}
let sayName = dog.sayName
sayName()

Body:
window.name="test";
sayName();//test

Executes the function in window context so this is window. You may want to keep the dog context either through passing it:

sayName.call(dog);//doggo

Or through keeping a bound function:

let sayName = dog.sayName.bind(dog);
sayName();//doggo


问:
general error: 2031 when uniting two queries (laravel datatables)
Those are the queries that form the collection to be pushed to the laravel datatables builder:

```<code>foreach (Session::get('trienios') as $trienio) {
    $oeTrienios = $oeTrienios->where('data_trienio', $trienio->trienio)->whereHas('curso', function ($query) use ($trienio) {
        $query->where('curso', $trienio->curso);
    });
}

$union = Trienio::with('curso')->whereHas('curso', function ($query) use ($coordinatedCourse) {
    $query->where('curso', $coordinatedCourse);
})->union($oeTrienios);

$trienios = \DB::table(\DB::raw("({$union->toSql()}) as x"))->select(['data_trienio']);
</code>```

There is a tutorial on the official laravel-datatables site that "explains" how to work with united queries, however it is pretty vague and can't realistically explain anything, and besides, when I tried to add a code they had on the tutorial:

```<code>$trienios = \DB::table(\DB::raw("({$union->toSql()}) as x"))
</code>```

It gives me the following error:

```<code>SQLSTATE[HY000]: General error: 2031 (SQL: select count(*) as aggregate from (select `data_trienio` from ((select * from `trienios` where exists (select * from `cursos` where `trienios`.`curso_id` = `cursos`.`id` and `curso` = ?)) union (select * from `trienios` where `data_trienio` = ? and exists (select * from `cursos` where `trienios`.`curso_id` = `cursos`.`id` and `curso` = ?) and `data_trienio` = ? and exists (select * from `cursos` where `trienios`.`curso_id` = `cursos`.`id` and `curso` = ?))) as x) count_row_table)
</code>```

If I, however, attach the parameter ->get() to the ->union($oeTrienios), it will work just fine, however, the collection will come unorderable on the datatable.

How do I solve this issue? Any help would be very welcome.

P.S - Link to the demo: https://datatables.yajrabox.com/fluent/union

答:
The subquery $union->toSql() has only sql code without parameters and you need call bindings. See here and code will be:

```<code>$trienios = \DB::table(\DB::raw("({$union->toSql()}) as x"))
    ->select(['data_trienio'])
    ->mergeBindings($union);
</code>```

Body:
Those are the queries that form the collection to be pushed to the laravel datatables builder:

foreach (Session::get('trienios') as $trienio) {
    $oeTrienios = $oeTrienios->where('data_trienio', $trienio->trienio)->whereHas('curso', function ($query) use ($trienio) {
        $query->where('curso', $trienio->curso);
    });
}

$union = Trienio::with('curso')->whereHas('curso', function ($query) use ($coordinatedCourse) {
    $query->where('curso', $coordinatedCourse);
})->union($oeTrienios);

$trienios = \DB::table(\DB::raw("({$union->toSql()}) as x"))->select(['data_trienio']);

There is a tutorial on the official laravel-datatables site that "explains" how to work with united queries, however it is pretty vague and can't realistically explain anything, and besides, when I tried to add a code they had on the tutorial:

$trienios = \DB::table(\DB::raw("({$union->toSql()}) as x"))

It gives me the following error:

SQLSTATE[HY000]: General error: 2031 (SQL: select count(*) as aggregate from (select `data_trienio` from ((select * from `trienios` where exists (select * from `cursos` where `trienios`.`curso_id` = `cursos`.`id` and `curso` = ?)) union (select * from `trienios` where `data_trienio` = ? and exists (select * from `cursos` where `trienios`.`curso_id` = `cursos`.`id` and `curso` = ?) and `data_trienio` = ? and exists (select * from `cursos` where `trienios`.`curso_id` = `cursos`.`id` and `curso` = ?))) as x) count_row_table)

If I, however, attach the parameter ->get() to the ->union($oeTrienios), it will work just fine, however, the collection will come unorderable on the datatable.

How do I solve this issue? Any help would be very welcome.

P.S - Link to the demo: https://datatables.yajrabox.com/fluent/union

Body:
The subquery $union->toSql() has only sql code without parameters and you need call bindings. See here and code will be:

$trienios = \DB::table(\DB::raw("({$union->toSql()}) as x"))
    ->select(['data_trienio'])
    ->mergeBindings($union);


问:
How to identify whether my container is running on AWS ECS or not?
If I am running my docker based container in AWS ECS (EC2 Container Service), is there a way I can identify from inside the application whether my container is running on AWS ECS or not? This is required, because my docker container can run on any platform, but when it is running on AWS ECS, I need to perform some extra operations.</p>

答:
After a lot of trial and error, I found the following most helpful:

Invoke  http://169.254.169.254/latest/meta-data/

If you get 200 OK, then you can assume you are running inside AWS EC2/ECS.

But if you don't get 200 OK, then you are not running in AWS EC2/ECS.


问:
how to instantiate a dsp slice in virtex 6?
i am working on a vhdl code (virtex 6). where i need to do number of multiply and accumulate operation. how do i use dsp slices for this(an in the instantiation and inference). Are there any examples which can help me? </p>

答:
Look here in ISE:

Edit > Language Templates > VHDL > Device Primitive Instantiation > Virtex 6 > Arithmetic Functions

A detailed user guide for the DSP slice is available from the Xilinx Website. It explains the function of every port on the entity.

If you want a better answer, you need to give far more detail in your question.


问:
ExpressJS change route without refresh
Hey I have a website run with Express.js and Handlebars that has a navbar and sidebar that stays the same for all the pages. When I route it only changes the page container which is {{{body}}}.

Is there a way I can just load the content of the routes without the page actually refreshing and reloading the nav and sidebar?

I'm currently using this for routing.

```<code>router.get('/', checkAuthentication, function(req, res){
  res.render('index');
});
</code>```

Any help would be nice as I'm quite new with node.

I want only the container to load not the whole url/page

答:
Thank you all for considering/looking at the post, i have come to the conclusion to be using PJAX to do this.

The tutorial i read, for anyone wondering is : Pjax Tutorial

Title: ExpressJS change route without refresh

Body:
Hey I have a website run with Express.js and Handlebars that has a navbar and sidebar that stays the same for all the pages. When I route it only changes the page container which is {{{body}}}.

Is there a way I can just load the content of the routes without the page actually refreshing and reloading the nav and sidebar?

I'm currently using this for routing.

router.get('/', checkAuthentication, function(req, res){
  res.render('index');
});

Any help would be nice as I'm quite new with node.

I want only the container to load not the whole url/page


问:
sqlite3.OperationalError python
so what i'am basically trying to do is getting data from a from developed with pyqt and insert it into a database, the problem is with my ID column,this is the code i'am using to insert the data to the database :

```<code>connection.execute("INSERT INTO UTILISATEURS VALUES (?,?,?,?,?,?) ",(fullname,email,cin,address,phonenumber,ribnumber))
</code>```

i always get this error :

```<code>sqlite3.OperationalError: table UTILISATEURS has 7 columns but 6 values were supplied
</code>```

when i enter a query to insert into the table directly from sqlite cli i get the results desired without needing to insert the ID it automatically autoincrements

here is the output of the .schema command :

```<code>sqlite> .schema
CREATE TABLE ADMINSS(USERNAME TEXT NOT NULL,PASSWORD TEXT);
CREATE TABLE UTILISATEURS(ID INTEGER PRIMARY KEY,FULLNAME TEXT NOT NULL,EMAIL INT NOT NULL,CIN INTEGER,ADDRESS CHAR(50),PHONE INTEGER,RIB INTEGER);
</code>```

答:
You need to pass a list of columns:

```<code>connection.execute("INSERT INTO UTILISATEURS (FULLNAME, EMAIL, CIN, ADDRESS, PHONE, RIB) VALUES (?,?,?,?,?,?) ", (fullname, email, cin, address, phonenumber, ribnumber))
</code>```

The only way to skip the list is to pass all 7 columns.

Title: sqlite3.OperationalError python

Body:
so what i'am basically trying to do is getting data from a from developed with pyqt and insert it into a database, the problem is with my ID column,this is the code i'am using to insert the data to the database :

connection.execute("INSERT INTO UTILISATEURS VALUES (?,?,?,?,?,?) ",(fullname,email,cin,address,phonenumber,ribnumber))

i always get this error :

sqlite3.OperationalError: table UTILISATEURS has 7 columns but 6 values were supplied

when i enter a query to insert into the table directly from sqlite cli i get the results desired without needing to insert the ID it automatically autoincrements

here is the output of the .schema command :

sqlite> .schema
CREATE TABLE ADMINSS(USERNAME TEXT NOT NULL,PASSWORD TEXT);
CREATE TABLE UTILISATEURS(ID INTEGER PRIMARY KEY,FULLNAME TEXT NOT NULL,EMAIL INT NOT NULL,CIN INTEGER,ADDRESS CHAR(50),PHONE INTEGER,RIB INTEGER);

Body:
You need to pass a list of columns:

connection.execute("INSERT INTO UTILISATEURS (FULLNAME, EMAIL, CIN, ADDRESS, PHONE, RIB) VALUES (?,?,?,?,?,?) ", (fullname, email, cin, address, phonenumber, ribnumber))

The only way to skip the list is to pass all 7 columns.


问:
Formatting a Duration in Java 8 / jsr310
I am transitioning a project from Joda-Time to java8's native time libraries, and I have run into a snag.

I have been unable to find a formatter for Duration. I would like to have a custom String format of, for instance, HHH+MM, where a Duration of 75 hours and 15 minutes would format as "75+15".

This was easy to do with Joda-Time by converting to period, and using a PeriodFormatter, but I have been unable to find this type of class in Java8. Am I missing something?

答:
you can use the DurationFormatUtils from commons-lang3-time (for minutes you have to use "mm" as the format is the same as in SimpleDateFormat):

DurationFormatUtils.formatDuration(interval.toMillis(), "HHH+mm")

Sadly I found no way to exclude empty parts, like in my case days or hours could be 0, so I still had to roll my own.

Update: I have opened an issue for this on Apache commons.lang.time.DurationFormatUtils JIRA.

ContentLicense: CC BY-SA 4.0


问:
Using php code in symfony YAML as string value
I want to create some YAML key with value - the code in php. But this code shouldn't be executed - I want to use it as the value itself. How can I do this?

Example:

```<code>somekey: <?php echo 1; ?>
</code>```

This line shouldn't be recognized as somekey: 1 after parsing - I want to receive value for somekey key as <?php echo 1; ?>.

Update:

I want to use this to store some code in database (with fixtures.yml) and then load it and use as php-based template.

答:
i've been using fixtures for migrations purpose and also needed to use php to generate the proper yaml file. My work around this problem was doing something like:

```<code><?php $handle=fopen(sfConfig::get('sf_data_dir')."/fixtures/csv/file.csv","r")?>
<?php fgetcsv($handle,0, ";"); ?>
<?php $i=100; ?>
<?php while (($data = fgetcsv($handle,0, ";")) !== false):?>
<?php
$code=trim($data[0]);
$user=trim($data[1]);
$criteria = new Criteria();
$criteria->add(ObjectPeer::CODE, $code);
$unit= objectPeer::doSelectOne($criteria, $error);
if (is_null($unit) || empty($unit))
  continue;
?>
  auto_generated_label_<?php echo 'value'.$i; $i++?>:

    attribute_1: <?php echo $user ?>

    attribute_2: <?php echo $unit->getId() ?>

<?php endwhile ?>
</code>```

So in symfony 1.2 this is working nicely, and remember, always leave a blank like between each yaml entity like in the example, and respect indentation when dealing with php embebbed on a yaml file, because those blank lines will not be there when the yaml parse reads it, so if you not put them, you could end up with somethink like:

auto_generated_label_1: attribute_1: asdasdasd attribute_2: 1233123

Best of luck!

ContentLicense: CC BY-SA 2.5

Body:
I want to create some YAML key with value - the code in php. But this code shouldn't be executed - I want to use it as the value itself. How can I do this?

Example:

somekey: <?php echo 1; ?>

This line shouldn't be recognized as somekey: 1 after parsing - I want to receive value for somekey key as <?php echo 1; ?>.

Update:

I want to use this to store some code in database (with fixtures.yml) and then load it and use as php-based template.

Body:
i've been using fixtures for migrations purpose and also needed to use php to generate the proper yaml file. My work around this problem was doing something like:

<?php $handle=fopen(sfConfig::get('sf_data_dir')."/fixtures/csv/file.csv","r")?>
<?php fgetcsv($handle,0, ";"); ?>
<?php $i=100; ?>
<?php while (($data = fgetcsv($handle,0, ";")) !== false):?>
<?php
$code=trim($data[0]);
$user=trim($data[1]);
$criteria = new Criteria();
$criteria->add(ObjectPeer::CODE, $code);
$unit= objectPeer::doSelectOne($criteria, $error);
if (is_null($unit) || empty($unit))
  continue;
?>
  auto_generated_label_<?php echo 'value'.$i; $i++?>:

    attribute_1: <?php echo $user ?>

    attribute_2: <?php echo $unit->getId() ?>

<?php endwhile ?>

So in symfony 1.2 this is working nicely, and remember, always leave a blank like between each yaml entity like in the example, and respect indentation when dealing with php embebbed on a yaml file, because those blank lines will not be there when the yaml parse reads it, so if you not put them, you could end up with somethink like:

auto_generated_label_1: attribute_1: asdasdasd attribute_2: 1233123

Best of luck!


问:
ES6 imports using module names without path
I would like to be able to import my modules using just name without path.

For example, say I want to use:

```<code>import ViewportChecker from 'viewport-checker';
</code>```

instead of

```<code>import ViewportChecker from '../ViewportChecker';
</code>```

But I want to keep the file where it is and not create a new npm module of it. Would it be possible to define it as module for exmaple in package.json?

答:
You can put a default file with naming convention of index.js which contains all the exports.

like:

```<code>-App
--home
---index.js // <--it will hold all the exports from otherClass.js and anotherClass.js
---otherClass.js
---anotherClass.js
</code>```

Now you have to import just folder name and it will automatically search for index.js file to get the particular exported item.

It might look like this:

```<code>import Home from './home';
</code>```

Body:
I would like to be able to import my modules using just name without path.

For example, say I want to use:

import ViewportChecker from 'viewport-checker';

instead of

import ViewportChecker from '../ViewportChecker';

But I want to keep the file where it is and not create a new npm module of it. Would it be possible to define it as module for exmaple in package.json?

Body:
You can put a default file with naming convention of index.js which contains all the exports.

like:

-App
--home
---index.js // <--it will hold all the exports from otherClass.js and anotherClass.js
---otherClass.js
---anotherClass.js

Now you have to import just folder name and it will automatically search for index.js file to get the particular exported item.

It might look like this:

import Home from './home';


问:
How to set search path for dllimport in mono?
I'm developing an Unity app which needs to dynamically load native libraries from outside where the app is installed, for some reason I cannot set the absolute path to DllImport before compiling (such as read the library path in a .txt at runtime and load it), and I don't want to use platform specific API such as LoadLibrary() on Windows or dlopen on Linux because it's inconvenient. And I have been struggled for several days.

I know that the search path can be adjusted by SetDllDirectory() on Windows from this post, and it works well when testing on .NET Framework applications.
However, it does not work in Unity which is based on mono 2.0, it just throws DllNotFoundException at runtime, but it works fine when I use absolute path in DllImport or copy the dll into my Unity project (I'm sure that the code is same)

The next way I tried is environment variable, and it does not work on both .NET and Mono, this post explained that CLR never refreshes the environment during process execution.

The third way I tried is to load the native library with platform specific API such as LoadLibrary() on Windows and dlopen() on Linux first, and then Dllimport may find that the library with same name has already been loaded, then it will use the load library to find function pointers, just as this post did. And I get the same result. The top answer of that question says we can write a wrapper class which uses platform specific API to explicitly load library and get functions pointers, instead of an approach focusing Dllimport, but it is not what I want.

If my guess is right, according to mono's document, DllImportAttribute calls LoadLibrary or dlopen internally at runtime to load a library into memory space. So it follows the search rules of specific OS platform, for example windows:

The directory from which the application loaded.

The current directory

The system directory. Use the GetSystemDirectory() function to get the path of this directory.

The 16-bit system directory.

The Windows directory. Use the GetWindowsDirectory() function to get
the path of this directory.

The directories that are listed in the PATH environment variable.

and Linux:

A colon-separated list of directories in the user’s LD_LIBRARY_PATH
environment variable. This is a frequently-used way to allow native
shared libraries to be found by a CLI program.

The list of libraries cached in /etc/ld.so.cache. /etc/ld.so.cache
is created by editing /etc/ld.so.conf and running ldconfig(8).
Editing /etc/ld.so.conf is the preferred way to search additional
directories, as opposed to using LD_LIBRARY_PATH, as this is more
secure (it’s more difficult to get a trojan library into
/etc/ld.so.cache than it is to insert it into LD_LIBRARY_PATH).

/lib, followed by /usr/lib.

By the way, I also tried to set LD_LIBRARY_PATH at runtime, but it does not work because LD_LIBRARY_PATH will be parsed only once when a process started, which is similar to PATH environment variable on Windows.

So my question is:

Why does the same code performs differently on .NET Framework and Mono? Does Mono just ignore the effect of SetDllDirectory() on Windows? What does DllImportAttribute actually do in Mono?

Is there any way to adjust search path for Unity/Mono apps at runtime, just using DllImport rather than platform specific APIs such as LoadLibrary() and dlopen()?

答:
Unfortunately the answer is that this behaviour is different between Mono on Linux, and .Net on windows, so you are just going to have to deal with that.

The best option, if you know where each DLL is located (e.g. you can put this into a config file), is to load each one explicitly yourself using LoadLibrary or dlopen. This must be done prior to the first call to a DllImport function. DllImport then need not specify a path.

This way you know exactly which DLL you are getting, and can load them in whatever order is correct, if this is an issue.

If for some reason you really don't want to do that, I suggest you create a function like MySetDllDirectory which on Windows calls SetDllDirectory and on Linux sets LD_LIBRARY_PATH. In this way the changes can be isolated to a single module.


问:
JavaScript function is not defined in external .js file in IE only
I use an external JavaScript file (.js) in a classic ASP program. I added a new function 'isFutureDate(dt)' to this file.  The new function works fine when using Chrome browser to access the web page. When using IE 11, it showed the error of "isFutureDate() is undefined". Other functions in external .js are working.

I run into this type of problems several times recently.  The existing functions in external .js file are working, but the newly added ones didn't work.  I had to move those functions back to the ASP program, then they worked fine.  My web server is IIS 7.5. I am not sure whether this issue is related to type of web server I am using.

I read several posts about problems with JavaScript function in external .js file.  But, I have not found one that describe the same problem as mine.

答: I had a similar problem after company upgraded IE - answer: ensure the correct DOCTYPE is at the top of the page</p>


问:
egrep search for whitespace
I'm trying to use egrep with a regex pattern to match whitespace.

I've used RegEx with Perl and C# before and they both support the pattern \s to search for whitespace. egrep (or at least the version I'm using) does not seem to support this pattern.

In a few articles online I've come across a shorthand [[:space:]], but this does not seem to work. Any help is appreciated.

Using: SunOS 5.10

答:
Maybe you should protect the pattern with quotes (if bash, or anything equivalent for the shell you are using).

[ and ] may have special meaning for the shell.

Title: egrep search for whitespace

OwnerDisplayName: rjack


问:
How to organize my Buttons in Row layout and full width
I would like to have my two divs(Up and down buttons) organized in a layout row side by side and taking the full widh of the page.
right now, they are organized like this :

My HTML is this :

```<code> <div layout="row">
    <div class="btn btn-info btn-lg" width="50%;">
        <span class="glyphicon glyphicon-menu-up"></span> Up
    </div>
    <div class="btn btn-info btn-lg" width="50%;">
        <span class="glyphicon glyphicon-menu-down"></span> Down
    </div>
</div>
</code>```

答:
Something like this

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

       Up

       Down

```

Body:
I would like to have my two divs(Up and down buttons) organized in a layout row side by side and taking the full widh of the page.
right now, they are organized like this :

My HTML is this :

         Up

         Down

Body:
Something like this

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div layout="row">
  <div class="col-xs-6">
    <div class="btn btn-block btn-info btn-lg">
      <span class="glyphicon glyphicon-menu-up"></span> Up
    </div>
  </div>
  <div class="col-xs-6">
    <div class="btn btn-block btn-info btn-lg">
      <span class="glyphicon glyphicon-menu-down"></span> Down
    </div>
  </div>
</div>


问:
How to filter posts by category in Camaleon CMS?
I am trying to filter posts by category in my Rails project, I am using Camaleon CMS. My basic requirement is to display only specific posts.

For example, only those posts to be shown who belong to the category "Fruits"?

Here is the code I have used:

```<code>  <% current_site.the_posts(current_theme.get_field("recent_post_type")).latest.limit(current_theme.get_field("home_qty")).decorate.each do |post| %>
      <!-- PORTFOLIO ITEM -->
      <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 text-center discussion-bot-box">
        <h4><%= post.the_title %> <span>(299)</span></h4>
        <p><%= post.the_content.html_safe %></p>
      </div> <!-- /col -->
  <% end %>
</code>```

答:
Try finding the category first:

```<code>category = current_site.the_full_categories.find_by(name: 'Fruits')
</code>```

then decorate and get the associated posts:

```<code>category.decorate.the_posts
</code>```

Body:
I am trying to filter posts by category in my Rails project, I am using Camaleon CMS. My basic requirement is to display only specific posts.

For example, only those posts to be shown who belong to the category "Fruits"?

Here is the code I have used:

  <% current_site.the_posts(current_theme.get_field("recent_post_type")).latest.limit(current_theme.get_field("home_qty")).decorate.each do |post| %>

<%= post.the_title %> (299)

<%= post.the_content.html_safe %>

  <% end %>

Body:
Try finding the category first:

category = current_site.the_full_categories.find_by(name: 'Fruits')

then decorate and get the associated posts:

category.decorate.the_posts


问:
ec2metadata equivalent for Azure virtual machines
Is there something similar to ec2metadata in Azure virtual machines?

I need to extract data like the the public hostname or the instance id. In Amazon EC2 instances, I can do this:

```<code>$ ec2metadata --instance-id
i-3a1dcfa3
$ ec2metadata --public-hostname
ec2-54-91-124-63.compute-1.amazonaws.com
</code>```

答:
It seems this question was asked a long time ago, so maybe you already found the answer. If not, though, then have you tried Azure Instance Metadata? (https://learn.microsoft.com/en-us/azure/virtual-machines/virtual-machines-instancemetadataservice-overview) You can do an http request like this:

```<code>curl -H Metadata:true "http://169.254.169.254/metadata/instance?api-version=2017-04-02"
</code>```

The response looks like this:

```<code>{
  "compute": {
    "location": "westcentralus",
    "name": "IMDSSample",
    "offer": "UbuntuServer",
    "osType": "Linux",
    "platformFaultDomain": "0",
    "platformUpdateDomain": "0",
    "publisher": "Canonical",
    "sku": "16.04.0-LTS",
    "version": "16.04.201610200",
    "vmId": "5d33a910-a7a0-4443-9f01-6a807801b29b",
    "vmSize": "Standard_A1"
  },
  "network": {
    "interface": [
      {
        "ipv4": {
          "ipAddress": [
            {
              "privateIpAddress": "10.1.0.4",
              "publicIpAddress": "X.X.X.X"
            }
          ],
          "subnet": [
            {
              "address": "10.1.0.0",
              "prefix": "24"
            }
          ]
        },
        "ipv6": {
          "ipAddress": []
        },
        "macAddress": "000D3AF806EC"
      }
    ]
  }
}
</code>```

Hope this helps! :)

Body:
Is there something similar to ec2metadata in Azure virtual machines?

I need to extract data like the the public hostname or the instance id. In Amazon EC2 instances, I can do this:

$ ec2metadata --instance-id
i-3a1dcfa3
$ ec2metadata --public-hostname
ec2-54-91-124-63.compute-1.amazonaws.com

Body:
It seems this question was asked a long time ago, so maybe you already found the answer. If not, though, then have you tried Azure Instance Metadata? (https://learn.microsoft.com/en-us/azure/virtual-machines/virtual-machines-instancemetadataservice-overview) You can do an http request like this:

curl -H Metadata:true "http://169.254.169.254/metadata/instance?api-version=2017-04-02"

The response looks like this:

{
  "compute": {
    "location": "westcentralus",
    "name": "IMDSSample",
    "offer": "UbuntuServer",
    "osType": "Linux",
    "platformFaultDomain": "0",
    "platformUpdateDomain": "0",
    "publisher": "Canonical",
    "sku": "16.04.0-LTS",
    "version": "16.04.201610200",
    "vmId": "5d33a910-a7a0-4443-9f01-6a807801b29b",
    "vmSize": "Standard_A1"
  },
  "network": {
    "interface": [
      {
        "ipv4": {
          "ipAddress": [
            {
              "privateIpAddress": "10.1.0.4",
              "publicIpAddress": "X.X.X.X"
            }
          ],
          "subnet": [
            {
              "address": "10.1.0.0",
              "prefix": "24"
            }
          ]
        },
        "ipv6": {
          "ipAddress": []
        },
        "macAddress": "000D3AF806EC"
      }
    ]
  }
}

Hope this helps! :)


问:
Validation in .net MVC
I need to check whether all fields are filled while clicking insert button.
This is my view:

```<code><body>

    <form name="form1">
        <h2>MEDICATION</h2>
        <div class="med">
            ```
 Patient code       <input type="text" id="pat" name="ptcode" size="25" value="" />                                ICD10  <input style="width:85px;height:30px;" type="text" name="icd10" value="">    <button style="height:30px;width:59px;" name="search" onclick="openicd()";>search</button>

Medication         @Html.DropDownListFor(Model => Model.medication, Model.medication,"Select Medication", new { style = "width:200px; height :30px" })   <button style="height:30px;"onclick="openmedication()";>search</button>            Prescription Date  <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value="">

Strength           @Html.DropDownListFor(Model => Model.strength, Model.strength, "Select Strength", new { style = "width:200px; height :30px" })                    Start Date         <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value="">   End Date  <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value="">

Form               @Html.DropDownListFor(Model => Model.form, Model.form, "Select form", new { style = "width:200px; height :30px" })                    Renewal Date       <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value=""> Days Supply <input type="text" style="width:85px;height:30px;" name="supply" value="">

Route              @Html.DropDownListFor(Model => Model.route, Model.route, "Select route", new { style = "width:200px; height :30px" })                    Pharmacy           @Html.DropDownListFor(Model => Model.pharmacy, Model.pharmacy, "Select Pharmacy", new { style = "width:200px; height :30px" })

Dose               @Html.DropDownListFor(Model => Model.dosage, Model.dosage, "Select Dose", new { style = "width:200px; height :30px" })
```
        </div>
    </form>
    <hr />
    <div class="wrapper">
        <button class="button" style="height:30px;" id="a" >Insert</button>      <button class="button" style="height:30px;" id="b">Update</button>      <button class="button" style="height:30px;" id="c">Delete</button>

    </div></body>
</html>
</code>```

答:
You can use your model for validation

```<code>public class Example {

    public int id { get; set; }

    [Required]
    public string name { get; set; }
}
</code>```

view more - Microsoft Docs

Title: Validation in .net MVC

Body:
I need to check whether all fields are filled while clicking insert button.
This is my view:

    <form name="form1">

MEDICATION

 Patient code       <input type="text" id="pat" name="ptcode" size="25" value="" />                                ICD10  <input style="width:85px;height:30px;" type="text" name="icd10" value="">    <button style="height:30px;width:59px;" name="search" onclick="openicd()";>search</button>

Medication         @Html.DropDownListFor(Model => Model.medication, Model.medication,"Select Medication", new { style = "width:200px; height :30px" })   <button style="height:30px;"onclick="openmedication()";>search</button>            Prescription Date  <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value="">

Strength           @Html.DropDownListFor(Model => Model.strength, Model.strength, "Select Strength", new { style = "width:200px; height :30px" })                    Start Date         <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value="">   End Date  <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value="">

Form               @Html.DropDownListFor(Model => Model.form, Model.form, "Select form", new { style = "width:200px; height :30px" })                    Renewal Date       <input type="date" class="sizetestdate" name="testdate" style="width:140px;height:30px;" value=""> Days Supply <input type="text" style="width:85px;height:30px;" name="supply" value="">

Route              @Html.DropDownListFor(Model => Model.route, Model.route, "Select route", new { style = "width:200px; height :30px" })                    Pharmacy           @Html.DropDownListFor(Model => Model.pharmacy, Model.pharmacy, "Select Pharmacy", new { style = "width:200px; height :30px" })

Dose               @Html.DropDownListFor(Model => Model.dosage, Model.dosage, "Select Dose", new { style = "width:200px; height :30px" })

    </form>

        <button class="button" style="height:30px;" id="a" >Insert</button>      <button class="button" style="height:30px;" id="b">Update</button>      <button class="button" style="height:30px;" id="c">Delete</button>

Body:
You can use your model for validation

public class Example {

    public int id { get; set; }

    [Required]
    public string name { get; set; }
}

view more - Microsoft Docs


问:
Application is active in server but page is not loading, shows err - Access denied
I was preparing production environment to deploy my ADF web application developed in jdeveloper 12.2.1. Installed and configured weblogic 12.2.1.1.0(latest version) and  database( Oracle DB 11g) in different servers. I tired to deploy a simple demo application which worked smoothly. But when i tired to deploy my application with MDS enabled which also having login credentials it's not get loading. Application and servers(3 managed servers added in a cluster) are active and its health is fine.
While I checked the log i can found the error message as below:

```<code>weblogic.kernel.Default (self-tuning)'> <OracleSystemUser> <BEA1-00A6CDC0DF4E2399D225> <c21c09b7-a391-47ae-b2eb-0d8dc5bec343-00000d61> <1477317511991> <[severity-value: 64] [rid: 0] [partition-id: 0] [partition-name: DOMAIN] > <BEA-010227> <EJB exception occurred during invocation from home or business: oracle.wsm.policymanager.bean.ejb.impl.UsageTracker_oi3aq7_Intf generated exception
: java.lang.SecurityException: WSM-02084 : Access denied. Permission "oracle.wsm.security.PolicyManagerPermission" is required to access the wsm policy manager "UsageTracker" method "recordUsage".>
</code>```

I am stuck with this issues. Tried by starting and stopping servers and deploy and undeploy application many times.

Any help would be appreciable.

Thanks in advance.

答:
You may want to check the suggestions on "SOA Suite 12.2.1 - OWSM WSM-02084 issue" from Michel Schildmeijer.

He suggests editing the policy.Accessor and adding oracle.wsm.security.PolicyManagerPermission for resource UsageTracker#recordUsage to the wsm-pm Application Stripe via "Fusion Middleware Control" under WebLogic Domain > Security > Application Policies.

https://community.oracle.com/blogs/mnemonic/2016/10/16/soa-suite-1221-owsm-wsm-02084-issue

Body:
I was preparing production environment to deploy my ADF web application developed in jdeveloper 12.2.1. Installed and configured weblogic 12.2.1.1.0(latest version) and  database( Oracle DB 11g) in different servers. I tired to deploy a simple demo application which worked smoothly. But when i tired to deploy my application with MDS enabled which also having login credentials it's not get loading. Application and servers(3 managed servers added in a cluster) are active and its health is fine.
While I checked the log i can found the error message as below:

weblogic.kernel.Default (self-tuning)'> <OracleSystemUser> <BEA1-00A6CDC0DF4E2399D225> <c21c09b7-a391-47ae-b2eb-0d8dc5bec343-00000d61> <1477317511991> <[severity-value: 64] [rid: 0] [partition-id: 0] [partition-name: DOMAIN] > <BEA-010227> <EJB exception occurred during invocation from home or business: oracle.wsm.policymanager.bean.ejb.impl.UsageTracker_oi3aq7_Intf generated exception
: java.lang.SecurityException: WSM-02084 : Access denied. Permission "oracle.wsm.security.PolicyManagerPermission" is required to access the wsm policy manager "UsageTracker" method "recordUsage".>

I am stuck with this issues. Tried by starting and stopping servers and deploy and undeploy application many times.

Any help would be appreciable.

Thanks in advance.


问:
Select from multiple tables with same condition, avoid ambiguity error
How can I do something like this but avoid the error column common_reference is ambiguous? I know it's ambiguous, I want to select from table_one all the results for common_reference there, and table_two the same.

SELECT * FROM table_one, table_two WHERE common_reference = 42

This is obviously not going to work, so how do I use subqueries to achieve what I need?

答:
MySQL will let you know via error if there is an unresolvable ambiguity in your SQL.

If you want to reference a specific field which also exists in another table (or the same table if you're doing a join on itself), use fully qualified fields

```<code>SELECT * FROM table_one, table_two WHERE table_one.common_reference = 42
</code>```

and/or table alias's

```<code>SELECT * FROM table_one T1a, table_one T1b WHERE T1a.common_reference = 42
</code>```

NB: Fair warning, as Mchl noted, these are Cartesian products and not typical joins.

Body:
MySQL will let you know via error if there is an unresolvable ambiguity in your SQL.

If you want to reference a specific field which also exists in another table (or the same table if you're doing a join on itself), use fully qualified fields

SELECT * FROM table_one, table_two WHERE table_one.common_reference = 42

and/or table alias's

SELECT * FROM table_one T1a, table_one T1b WHERE T1a.common_reference = 42

NB: Fair warning, as Mchl noted, these are Cartesian products and not typical joins.


问:
Render error in Android Studio 3.0 Layout Editor
I just started learning Kotlin for android development and started an empty project and added an activity. I have added the required gradle dependencies as said in Kotlin docs. By default the xml file of MainActivity contains only a TextView. But when I try to preview the xml in Layout Editor it shows a "Render Error"

```<code>Render problem

Failed to load AppCompat ActionBar with unknown error.
</code>```

Also I'm getting this

```<code>The following classes could not be instantiated:
- android.support.v7.widget.AppCompatImageView (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.ActionBarContainer (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.Toolbar (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.AppCompatTextView (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.ActionBarContextView (Open Class, Show Exception, Clear Cache)
- android.support.v7.app.WindowDecorActionBar (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.ActionBarOverlayLayout (Open Class, Show Exception, Clear Cache)

Exception Details java.lang.ClassNotFoundException: android.support.v4.view.TintableBackgroundView
</code>```

I have tried rebuilding the project and refreshing layout manually. But nothing seems to work.

So what do I do? I'm using Android Studio 3.0 Canary 2 with Kotlin

EDITED:

I have made some progress. I have found that none of my AppCompat Themes are working.

答: I also have this problem, solved as follows: modify the appcompat-v7:26.0.0-beta2 on build.gradle (modle:app) to appcompat-v7:26.0.0-beta1.

Body:
I just started learning Kotlin for android development and started an empty project and added an activity. I have added the required gradle dependencies as said in Kotlin docs. By default the xml file of MainActivity contains only a TextView. But when I try to preview the xml in Layout Editor it shows a "Render Error"

Render problem

Failed to load AppCompat ActionBar with unknown error.

Also I'm getting this

The following classes could not be instantiated:
- android.support.v7.widget.AppCompatImageView (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.ActionBarContainer (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.Toolbar (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.AppCompatTextView (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.ActionBarContextView (Open Class, Show Exception, Clear Cache)
- android.support.v7.app.WindowDecorActionBar (Open Class, Show Exception, Clear Cache)
- android.support.v7.widget.ActionBarOverlayLayout (Open Class, Show Exception, Clear Cache)

Exception Details java.lang.ClassNotFoundException: android.support.v4.view.TintableBackgroundView

I have tried rebuilding the project and refreshing layout manually. But nothing seems to work.

So what do I do? I'm using Android Studio 3.0 Canary 2 with Kotlin

EDITED:

I have made some progress. I have found that none of my AppCompat Themes are working.


问:
ui-routing for angular using $stateparams and trying to send data
Okay, this is what I got so far https://embed.plnkr.co/QtM3ucPn6R1cPgdPjEzp/ .
I am trying to put information on the about me page, through $stateParams.
With a name and a nickname, In the state from about I gave the controller this  expect($stateParams).toBe({meId : 1}); and I gave the url this url : '/about/{meId}',. So on the page from about I want to give the state some information about me like my nickname and my name. So the id I gave for the information is 1. because the expect($stateParams).toBe({meId : 1}); is 1. I want to let the page get the meId 1. with the nickname and the name with it.

I tried a few different things like the data and params, but both didn't work like they should so what am I doing wrong right now.

答:
The problem statement here is quite ambiguous. From what I have understood, you need to show set of values from controller based on the $stateParams value.

See forked plunker

```<code>.state('about',{
    url : '/about/{meId}',
      templateUrl : 'about.html',
      controller: function($stateParams, $scope){
        if($stateParams.meId == 1) {
           $scope.meId = {
             id: $stateParams.meId,
             naam: 'audrey',
             nickname: 'audi'
           }
        }
      }
  });
</code>```

Moreover, expect($stateParams).toBe({meId : 1}); is a Jasmine unit testing framework syntax for unit tests and is irrelevant here.

Body:
The problem statement here is quite ambiguous. From what I have understood, you need to show set of values from controller based on the $stateParams value.

See forked plunker

.state('about',{
    url : '/about/{meId}',
      templateUrl : 'about.html',
      controller: function($stateParams, $scope){
        if($stateParams.meId == 1) {
           $scope.meId = {
             id: $stateParams.meId,
             naam: 'audrey',
             nickname: 'audi'
           }
        }
      }
  });

Moreover, expect($stateParams).toBe({meId : 1}); is a Jasmine unit testing framework syntax for unit tests and is irrelevant here.


问:
How can I get the total number of rows in a CSV file with PHP?
Using PHP, how can I get the total number of rows that are in a CSV file? I'm using this method but cannot get it to work properly.</p>
```<code>if (($fp = fopen("test.csv", "r")) !== FALSE) {
  while (($record = fgetcsv($fp)) !== FALSE) {
      $row++;
  }

  echo $row;
}
</code>```

答:
```<code>$filename=$_FILES['sel_file']['tmp_name'];
$file=fopen($filename,"r");
$RowCount=0;

while ((fgetcsv($file)) !== FALSE)
{
    $RowCount++;
}

echo $RowCount;
fclose($file);
</code>```

Body:
Using PHP, how can I get the total number of rows that are in a CSV file? I'm using this method but cannot get it to work properly.

if (($fp = fopen("test.csv", "r")) !== FALSE) {
  while (($record = fgetcsv($fp)) !== FALSE) {
      $row++;
  }

  echo $row;
}


问:
Getting AWS role credentials in Gradle
I have an S3 repository that I want to access in my build process. It contains some of my project's dependencies. My project is deployed to an EC2 instance with a designated role - Repo_dependent. The role has an Access_Repo policy attached to it:

```<code>{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "Stmt1484560548000",
        "Effect": "Allow",
        "Action": [
            "s3:GetObject",
            "s3:ListBucket",
            "s3:GetBucketLocation"
        ],
        "Resource": [
            "arn:aws:s3:::my_bucket",
            "arn:aws:s3:::my_bucket/*"
        ]
    }
  ]
}
</code>```

When I deploy the new server I get a The AWS Access Key Id you provided does not exist in our records. (Service: Amazon S3; Status Code: 403; Error Code: InvalidAccessKeyId; Request ID: 02169BFDCF7AFE10) exception.

My build script is this (abbreviated for simplicity)

```<code>buildscript {
  repositories {
    jcenter()
  }
  dependencies {
    classpath 'com.amazonaws:aws-java-sdk:1.11.83'
  }
}

import com.amazonaws.auth.*

repositories {
  jcenter()
  maven {
    url "s3://my_bucket.s3.amazonaws.com"
    credentials(AwsCredentials) {
        def providercreds = new InstanceProfileCredentialsProvider().getCredentials()
        accessKey providercreds.getAWSAccessKeyId()
        secretKey providercreds.getAWSSecretKey()
    }
  }
}
</code>```

My assumption is that I'm missing something in either how EC2 instances access their roles or something in how roles are defined. When trying to run the same script locally, with a user that has the Access_Repo policy attached to it and instead of using InstanceProfileCredentialsProvider use DefaultAWSCredentialsProviderChain, the build runs fine. However using DefaultAWSCredentialsProviderChain and deploying the instance again resulted in the same exception.

Any help would be very much appreciated.

Update:

Testing done using the AWS CLI and using the STSAssumeRoleSessionCredentialsProvider shows the the build script is using the right role with the DefaultAWSCredentialsProviderChain provider. Adding AmazonS3FullAccess policy to the role did not change the result

I'm using Jenkins to deploy the code so my next lead is that maybe something is wrong there

Update2:

I tried capturing the network traffic to see which credentials are sent to AWS and it seems like different credentials are sent by Gradle and by the AWS CLI so I'm back to my original assumption that Gradle doesn't pull the right role

答:
If any one encounters this issue. I fixed it after migrating from Gradle 3.0 to 3.3. This allowed me to use the following code:</p>

```<code>buildscript {
  repositories {
    jcenter()
  }
  dependencies {
  }
}

repositories {
  jcenter()
  maven {
    url "s3://my_bucket.s3.amazonaws.com"
    authentication {
        awsIm(AwsImAuthentication)
    }
  }
}

task wrapper(type: Wrapper) {
  gradleVersion = '3.3'
}

dependencies {
    compile 'com.amazonaws:aws-java-sdk-iam:1.11.78'
    compile 'com.amazonaws:aws-java-sdk-ec2:1.11.78'
}
</code>```

Title: Getting AWS role credentials in Gradle

Body:
I have an S3 repository that I want to access in my build process. It contains some of my project's dependencies. My project is deployed to an EC2 instance with a designated role - Repo_dependent. The role has an Access_Repo policy attached to it:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "Stmt1484560548000",
        "Effect": "Allow",
        "Action": [
            "s3:GetObject",
            "s3:ListBucket",
            "s3:GetBucketLocation"
        ],
        "Resource": [
            "arn:aws:s3:::my_bucket",
            "arn:aws:s3:::my_bucket/*"
        ]
    }
  ]
}

When I deploy the new server I get a The AWS Access Key Id you provided does not exist in our records. (Service: Amazon S3; Status Code: 403; Error Code: InvalidAccessKeyId; Request ID: 02169BFDCF7AFE10) exception.

My build script is this (abbreviated for simplicity)

buildscript {
  repositories {
    jcenter()
  }
  dependencies {
    classpath 'com.amazonaws:aws-java-sdk:1.11.83'
  }
}

import com.amazonaws.auth.*

repositories {
  jcenter()
  maven {
    url "s3://my_bucket.s3.amazonaws.com"
    credentials(AwsCredentials) {
        def providercreds = new InstanceProfileCredentialsProvider().getCredentials()
        accessKey providercreds.getAWSAccessKeyId()
        secretKey providercreds.getAWSSecretKey()
    }
  }
}

My assumption is that I'm missing something in either how EC2 instances access their roles or something in how roles are defined. When trying to run the same script locally, with a user that has the Access_Repo policy attached to it and instead of using InstanceProfileCredentialsProvider use DefaultAWSCredentialsProviderChain, the build runs fine. However using DefaultAWSCredentialsProviderChain and deploying the instance again resulted in the same exception.

Any help would be very much appreciated.

Update:

Testing done using the AWS CLI and using the STSAssumeRoleSessionCredentialsProvider shows the the build script is using the right role with the DefaultAWSCredentialsProviderChain provider. Adding AmazonS3FullAccess policy to the role did not change the result

I'm using Jenkins to deploy the code so my next lead is that maybe something is wrong there

Update2:

I tried capturing the network traffic to see which credentials are sent to AWS and it seems like different credentials are sent by Gradle and by the AWS CLI so I'm back to my original assumption that Gradle doesn't pull the right role

Body:
If any one encounters this issue. I fixed it after migrating from Gradle 3.0 to 3.3. This allowed me to use the following code:

buildscript {
  repositories {
    jcenter()
  }
  dependencies {
  }
}

repositories {
  jcenter()
  maven {
    url "s3://my_bucket.s3.amazonaws.com"
    authentication {
        awsIm(AwsImAuthentication)
    }
  }
}

task wrapper(type: Wrapper) {
  gradleVersion = '3.3'
}

dependencies {
    compile 'com.amazonaws:aws-java-sdk-iam:1.11.78'
    compile 'com.amazonaws:aws-java-sdk-ec2:1.11.78'
}


问:
can only login on Oracle with sys or system account
I just installed 12cR2 on centOS6.6.I logged in with sys account as follows:

```<code>sqlplus sys/syspasswd@dbcenter/pdbcenter as sysdba
</code>```

then,I created a user as follows:

```<code>SQL> CREATE USER test identified by test
SQL> GRANT CONNECT,RESOURCE,CREATE SESSION TO TEST
</code>```

sqlplus reported user create with no errors.but when I try to login with test account,I got error:

```<code>sqlplus test/test@dbcenter/pdbcenter

ORA-01017: invalid username/password; logon denied
</code>```

What could be the problem?
Thanks!!!

答: Check if user is listed in dba_users/all_users view. If not, then it might be that you have created the user in older oracle version and now trying to login with that in newer oracle12c. Confirm the port and ORACLE_HOME path listed in your TNS Entry is correct, as you mentioned while installing oracle.</p>

Body:
I just installed 12cR2 on centOS6.6.I logged in with sys account as follows:

sqlplus sys/syspasswd@dbcenter/pdbcenter as sysdba

then,I created a user as follows:

SQL> CREATE USER test identified by test
SQL> GRANT CONNECT,RESOURCE,CREATE SESSION TO TEST

sqlplus reported user create with no errors.but when I try to login with test account,I got error:

sqlplus test/test@dbcenter/pdbcenter

ORA-01017: invalid username/password; logon denied

What could be the problem?
Thanks!!!


问:
Is this a right way to check if Postgres Committed a Transaction id
In Postgresql, If the transaction id is "123456", table name is "table1" then am I right to execute the following query? :

```<code>Select count (*) from table1 where xmin=123456 OR xmax=123456
</code>```

if count returns value > 1, then can I assume that the transaction id is committed?

_

Note:

Transaction id is sent from a different java program to another java
program via RMI (OR) TCP Sockets (OR) File (OR) some other mechanism

Transaction id is gathered from an after update,insert,delete
trigger

Vacuum or any other maintenance procedures are not performed during these operations

Don't worry about txid wraparound issue either

When using oracle, the v$transaction came to the rescue... but in Postgres, I couldn't find anything similar...
Though some googling led me to believe there are ways to find it using the "pg_log" file or the "pg_locks" view but I couldn't figure out how

Only dirty way I could think of is the xmin and xmax... I couldn't even tell whether it's a dirty method for that matter

are there any Postgresql Sensei who can lead me in the right direction?

Updates:

For postgresql 9.5 and later, "laurenz albe"'s answer is perfect...
For those who use Postgresql 9.0 to 9.3, you should use,

```<code>SELECT count(xmin) as SIZE FROM table1 WHERE xmin = 123456 AND xmax = 0
</code>```

Also When a Delete operation happens and you get a transaction id, we need to check it the different way...

```<code>SELECT count(xmin) as SIZE FROM table1 WHERE xmin = 123456 OR xmax = 123456
</code>```

then check the result. if it returns zero, then the delete operation is committed... if result is non-zero then the transaction is rolled back and you need not worry about the uncommitted transaction

Note:
This is to check if the transaction id received from a trigger and sent to another external program(java) has been committed and not rolled back and the database session is different...

答:
If you see the xmin=123456 and your txid_current() <> 123456 yes - then transaction 123456 is committed.

There's no such column as transactionId in postgres.

Body:
In Postgresql, If the transaction id is "123456", table name is "table1" then am I right to execute the following query? :

Select count (*) from table1 where xmin=123456 OR xmax=123456

if count returns value > 1, then can I assume that the transaction id is committed?

_

Note:

Transaction id is sent from a different java program to another java
program via RMI (OR) TCP Sockets (OR) File (OR) some other mechanism

Transaction id is gathered from an after update,insert,delete
trigger

Vacuum or any other maintenance procedures are not performed during these operations

Don't worry about txid wraparound issue either

When using oracle, the v$transaction came to the rescue... but in Postgres, I couldn't find anything similar...
Though some googling led me to believe there are ways to find it using the "pg_log" file or the "pg_locks" view but I couldn't figure out how

Only dirty way I could think of is the xmin and xmax... I couldn't even tell whether it's a dirty method for that matter

are there any Postgresql Sensei who can lead me in the right direction?

Updates:

For postgresql 9.5 and later, "laurenz albe"'s answer is perfect...
For those who use Postgresql 9.0 to 9.3, you should use,

SELECT count(xmin) as SIZE FROM table1 WHERE xmin = 123456 AND xmax = 0

Also When a Delete operation happens and you get a transaction id, we need to check it the different way...

SELECT count(xmin) as SIZE FROM table1 WHERE xmin = 123456 OR xmax = 123456

then check the result. if it returns zero, then the delete operation is committed... if result is non-zero then the transaction is rolled back and you need not worry about the uncommitted transaction

Note:
This is to check if the transaction id received from a trigger and sent to another external program(java) has been committed and not rolled back and the database session is different...


问:
Autoload custom exceptions files with RoR
In my app/ directory I have a folder services. To autoload my files in the service folder, I added 'app/services' in my 'config/spring.rb'

```<code>%w(
  .ruby-version
  .rbenv-vars
  tmp/restart.txt
  tmp/caching-dev.txt
  app/services
).each { |path| Spring.watch(path) }
</code>```

It's work fine. But now, I want to create a sub dir for my custom exceptions (in app/services/errors/). But when I try to add a new line in my spring.rb :

```<code>%w(
      .ruby-version
      .rbenv-vars
      tmp/restart.txt
      tmp/caching-dev.txt
      app/services
      app/services/errors
    ).each { |path| Spring.watch(path) }
</code>```

It's not working, I got some :

```<code>NameError:
       uninitialized constant SixError
</code>```

Here my custom error file (app/services/errors/six_error.rb):

```<code>class SixError < RuntimeError
end

class NilTokenError < SixError
end

class SixRequestFailed < SixError
end

class NoAliasRequestPendingError < SixError
end

class AmountLessThanZeroError < SixError
end

class NilAliasError < SixError
end
</code>```

And this is how I called this :

```<code>SixError::SixRequestFailed
</code>```

答:
Rails is loading class in subdir with a namespace corresponding to the dirname.

If you have this structure :

-app

--services

---errors

----six_errors.rb

Rails expecting the file six_errors.rb to declare class upon the namespace Errors.

In your case you should declare all your errors class in a module named Errors.

```<code>module Errors
  class SixError < RuntimeError; end
end
</code>```

Body:
In my app/ directory I have a folder services. To autoload my files in the service folder, I added 'app/services' in my 'config/spring.rb'

%w(
  .ruby-version
  .rbenv-vars
  tmp/restart.txt
  tmp/caching-dev.txt
  app/services
).each { |path| Spring.watch(path) }

It's work fine. But now, I want to create a sub dir for my custom exceptions (in app/services/errors/). But when I try to add a new line in my spring.rb :

%w(
      .ruby-version
      .rbenv-vars
      tmp/restart.txt
      tmp/caching-dev.txt
      app/services
      app/services/errors
    ).each { |path| Spring.watch(path) }

It's not working, I got some :

NameError:
       uninitialized constant SixError

Here my custom error file (app/services/errors/six_error.rb):

class SixError < RuntimeError
end

class NilTokenError < SixError
end

class SixRequestFailed < SixError
end

class NoAliasRequestPendingError < SixError
end

class AmountLessThanZeroError < SixError
end

class NilAliasError < SixError
end

And this is how I called this :

SixError::SixRequestFailed

Body:
Rails is loading class in subdir with a namespace corresponding to the dirname.

If you have this structure :

-app

--services

---errors

----six_errors.rb

Rails expecting the file six_errors.rb to declare class upon the namespace Errors.

In your case you should declare all your errors class in a module named Errors.

module Errors
  class SixError < RuntimeError; end
end


问:
Vue 2 - change model in main instance from the component
I have the following component:

```<code>Vue.component('visible-filter', {
    template: `
        <span class="text-muted"
            @mouseenter="changeClassMouseenter($event)"
            @mouseout="changeClassMouseout($event)"
            @click="countryTest(filter)"
            @clicked="clicked = true"
            v-model="clicked"
        ><slot></slot></span>
    `,

    props: ['filter', 'clicked'],

    methods: {

        changeClassMouseenter(event) {
            console.log(this.clicked);
            event.target.classList.remove('text-muted')
        },

        changeClassMouseout(event) {
            event.target.classList.add('text-muted')
        },

        countryTest(filter) {
            Event.$emit('clicked');
            Event.$emit('country-filter', filter);
        }
    }

});
</code>```

The Event in the main instance:

```<code>Event.$on('clicked', () => {
    this.clicked = true;
})
</code>```

The data in the main instance:

```<code>data: {
    clicked: false
},
</code>```

The thing I want to do:

When I click on the element, I want to set the clicked property to true (for that element), and for the rest of the elements I want to set it to false; Also I want to check if the clicked is true/false when the mouseenter/mouseout event is fired.

How can I achive this?

答:
You should not change the parent from child.

To make communication between parent and child (and child->parent as well) you can/should set up the events.

Emit the event in child component. Nice examples here: https://v2.vuejs.org/v2/guide/components.html#Using-v-on-with-Custom-Events

Listen to event in your parent using <child-component @yourEventName='eventHandler(data)'>

Handle data in your parent, so add eventHandler(data) into your methods and do whatever you want with your data.

Body:
I have the following component:

Vue.component('visible-filter', {
    template: `
        <slot></slot>
    `,

    props: ['filter', 'clicked'],

    methods: {

        changeClassMouseenter(event) {
            console.log(this.clicked);
            event.target.classList.remove('text-muted')
        },

        changeClassMouseout(event) {
            event.target.classList.add('text-muted')
        },

        countryTest(filter) {
            Event.$emit('clicked');
            Event.$emit('country-filter', filter);
        }
    }

});

The Event in the main instance:

Event.$on('clicked', () => {
    this.clicked = true;
})

The data in the main instance:

data: {
    clicked: false
},

The thing I want to do:

When I click on the element, I want to set the clicked property to true (for that element), and for the rest of the elements I want to set it to false; Also I want to check if the clicked is true/false when the mouseenter/mouseout event is fired.

How can I achive this?


问:
Best way to add "current" class to nav in Rails 3
I have some static pages in a navigation menu. I want to add a class like "current" to the item which is currently displaying.

The way I am doing so is to add tons of helper methods (each for one item) to check the controller and action.

```<code>def current_root_class
  'class="current"' if controller_name == "homepage" && action_name == "index"
end

<ul>
  <li <%= current_root_class %>><%= link_to "Home", root_path %>
</code>```

Is there any better way to do so!? My current way is so stupid......

答:
Create a method in ApplicationHelper as below.

```<code>def active controllers, action_names = nil
  class_name = controllers.split(",").any? { |c| controller.controller_name == c.strip } ? "active" : ""
  if class_name.present? && action_names.present?
    return action_names.split(",").any? { |an| controller.action_name == an.strip } ? "active" : ""
  end
  class_name
end
</code>```

Now use it in view as below use cases.

1. For all action of any specific controller

```<code><li class="<%= active('controller_name')%>">
....
</li>
</code>```

2. For all action of many controllers (with comma seperated)

```<code><li class="<%= active('controller_name1,controller_name2')%>">
....
</li>
</code>```

3. For specific action of any specific controller

```<code><li class="<%= active('controller_name', 'action_name')%>">
....
</li>
</code>```

4. For specific action of many controllers (with comma seperated)

```<code><li class="<%= active('controller_name1,controller_name2', 'action_name')%>">
....
</li>
</code>```

5. For some specific actions of any specific controller

```<code><li class="<%= active('controller_name', 'index, show')%>">
....
</li>
</code>```

6. For some specific actions of many controllers (with comma seperated)

```<code><li class="<%= active('controller_name1,controller_name2', 'index, show')%>">
....
</li>
</code>```

Hope it helps

Body:
I have some static pages in a navigation menu. I want to add a class like "current" to the item which is currently displaying.

The way I am doing so is to add tons of helper methods (each for one item) to check the controller and action.

def current_root_class
  'class="current"' if controller_name == "homepage" && action_name == "index"
end

  <li <%= current_root_class %>><%= link_to "Home", root_path %>

Is there any better way to do so!? My current way is so stupid......

Body:
Create a method in ApplicationHelper as below.

def active controllers, action_names = nil
  class_name = controllers.split(",").any? { |c| controller.controller_name == c.strip } ? "active" : ""
  if class_name.present? && action_names.present?
    return action_names.split(",").any? { |an| controller.action_name == an.strip } ? "active" : ""
  end
  class_name
end

Now use it in view as below use cases.

1. For all action of any specific controller

<li class="<%= active('controller_name')%>">
....
</li>

2. For all action of many controllers (with comma seperated)

<li class="<%= active('controller_name1,controller_name2')%>">
....
</li>

3. For specific action of any specific controller

<li class="<%= active('controller_name', 'action_name')%>">
....
</li>

4. For specific action of many controllers (with comma seperated)

<li class="<%= active('controller_name1,controller_name2', 'action_name')%>">
....
</li>

5. For some specific actions of any specific controller

<li class="<%= active('controller_name', 'index, show')%>">
....
</li>

6. For some specific actions of many controllers (with comma seperated)

<li class="<%= active('controller_name1,controller_name2', 'index, show')%>">
....
</li>

Hope it helps


问:
Hide and show markers on MapBox
When I started this, I thought this is a rather trivial feature, but I keep struggling to achieve this:

On a MapBox map on Android, I want to hide all markers when I zoom out (at a certain zoom level), and show them again when I zoom in.

I couldn't find any option to hide (set visibility to false) the markers. So I remove them and add them again:

```<code>private void hideMarkers() {
    if (!markersHidden) {
        mapBoxMap.clear();
        markersHidden = true;
    }
}

private void showMarkers() {
    if (markersHidden) {
        markersHidden = false;
        for (Point point : markerMap.values()) {
            addMapMarker(point);
        }
    }
}

public void addMapMarker(Point point) {
    if (point == null) return;

    markerMap.put(point.id, point);
    if (markersHidden) return;

    MarkerOptions markerOptions = new MarkerOptions()
            .position(new LatLng(point.location.latitude, point.location.longitude))
            .setSnippet(point.id)
            .icon(IconUtils.drawableToIcon(getContext(), presenter.getMapIcon(point.provider).getMapIcon(point)))
            .title(point.name);

    mapBoxMap.addMarker(markerOptions);
}
</code>```

Where markerMap is a HashMap where I keep my Point references.
The methods do what they are supposed to do. markerMap keeps the references, and they are properly added to the map.
However, they are not shown.

Why are they not showing up on the map when they are added to it?

What can I do to show the markers again?

Is there any other way in which I can achieve hiding and showing the markers apart from removing and adding them?

The MapBox version I'm using is com.mapbox.mapboxsdk:mapbox-android-sdk:5.0.2@aar.

答:
I think it is possible to manage to hide and show the markers only if you use MarkerView. As a prof of concept here is a code showing how it works through the method setVisibility

```<code>markerView = map.addMarker(new MarkerViewOptions()
                    .anchor(.5f, .5f)
                    .icon(IconFactory.getInstance(getApplicationContext()).fromResource(R.drawable.mapbox_marker_icon_default))
                    .position(stuttgartLoc));

            CameraUpdate cameraNewPosition = CameraUpdateFactory
                    .newLatLngZoom(stuttgartLoc, 17);
            map.animateCamera(cameraNewPosition);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    markerView.setVisible(false);
                }
            }, 5000);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    markerView.setVisible(true);
                }
            }, 10000);
</code>```

Title: Hide and show markers on MapBox

Body:
When I started this, I thought this is a rather trivial feature, but I keep struggling to achieve this:

On a MapBox map on Android, I want to hide all markers when I zoom out (at a certain zoom level), and show them again when I zoom in.

I couldn't find any option to hide (set visibility to false) the markers. So I remove them and add them again:

private void hideMarkers() {
    if (!markersHidden) {
        mapBoxMap.clear();
        markersHidden = true;
    }
}

private void showMarkers() {
    if (markersHidden) {
        markersHidden = false;
        for (Point point : markerMap.values()) {
            addMapMarker(point);
        }
    }
}

public void addMapMarker(Point point) {
    if (point == null) return;

    markerMap.put(point.id, point);
    if (markersHidden) return;

    MarkerOptions markerOptions = new MarkerOptions()
            .position(new LatLng(point.location.latitude, point.location.longitude))
            .setSnippet(point.id)
            .icon(IconUtils.drawableToIcon(getContext(), presenter.getMapIcon(point.provider).getMapIcon(point)))
            .title(point.name);

    mapBoxMap.addMarker(markerOptions);
}

Where markerMap is a HashMap where I keep my Point references.
The methods do what they are supposed to do. markerMap keeps the references, and they are properly added to the map.
However, they are not shown.

Why are they not showing up on the map when they are added to it?

What can I do to show the markers again?

Is there any other way in which I can achieve hiding and showing the markers apart from removing and adding them?

The MapBox version I'm using is com.mapbox.mapboxsdk:mapbox-android-sdk:5.0.2@aar.

Body:
I think it is possible to manage to hide and show the markers only if you use MarkerView. As a prof of concept here is a code showing how it works through the method setVisibility

markerView = map.addMarker(new MarkerViewOptions()
                    .anchor(.5f, .5f)
                    .icon(IconFactory.getInstance(getApplicationContext()).fromResource(R.drawable.mapbox_marker_icon_default))
                    .position(stuttgartLoc));

            CameraUpdate cameraNewPosition = CameraUpdateFactory
                    .newLatLngZoom(stuttgartLoc, 17);
            map.animateCamera(cameraNewPosition);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    markerView.setVisible(false);
                }
            }, 5000);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    markerView.setVisible(true);
                }
            }, 10000);