问:
MS SQL Server - Bulk insert from local file - How to indicate path on Mac OS?
I have just created an empty SQL table called "claims" with its attributes using Aqua Data Studio. SQL standard is based on Microsoft SQL Server Express via Docker (a VM for Mac OS). Now I am trying to fill it in via Bulk insert statement from a local csv file called "claims.csv", like this:

```<code>BULK INSERT Claims
FROM 'Users/Antonio/wd/hhp/data/Claims.csv'
WITH
(
MAXERRORS = 0,
FIRSTROW = 2,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
</code>```

But I get the following error:

[Error] Script lines: 1-9 --------------------------
   Id 4860, Level 16, State 1, Line 1
      Cannot bulk load. The file "Users/Antonio/wd/hhp/data/Claims.csv" does not exist or you don't have file access rights.
   Msg: 4860, Level: 16, State: 1, Procedure: , Line: 1

What am I doing wrong? am I specifying the path to file incorrectly? Many thx.

答:
It looks like you have your path set incorrectly. Try:</p>

```<code>BULK INSERT Claims
FROM 'C:/Users/Antonio/wd/hhp/data/Claims.csv'
WITH
(
MAXERRORS = 0,
FIRSTROW = 2,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
</code>```

Body:
I have just created an empty SQL table called "claims" with its attributes using Aqua Data Studio. SQL standard is based on Microsoft SQL Server Express via Docker (a VM for Mac OS). Now I am trying to fill it in via Bulk insert statement from a local csv file called "claims.csv", like this:

BULK INSERT Claims
FROM 'Users/Antonio/wd/hhp/data/Claims.csv'
WITH
(
MAXERRORS = 0,
FIRSTROW = 2,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)

But I get the following error:

[Error] Script lines: 1-9 --------------------------
   Id 4860, Level 16, State 1, Line 1
      Cannot bulk load. The file "Users/Antonio/wd/hhp/data/Claims.csv" does not exist or you don't have file access rights.
   Msg: 4860, Level: 16, State: 1, Procedure: , Line: 1

What am I doing wrong? am I specifying the path to file incorrectly? Many thx.

Body:
It looks like you have your path set incorrectly. Try:

BULK INSERT Claims
FROM 'C:/Users/Antonio/wd/hhp/data/Claims.csv'
WITH
(
MAXERRORS = 0,
FIRSTROW = 2,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)


来源: stackexchange

问:
boundingRectWithSize for NSAttributedString returning wrong size
I am trying to get the rect for an attributed string, but the boundingRectWithSize call is not respecting the size I pass in and is returning a rect with a single line height as opposed to a large height (it is a long string). I have experimented by passing in a very large value for the height and also 0 as in the code below, but the rect returned is always the same.

```<code>CGRect paragraphRect = [attributedText boundingRectWithSize:CGSizeMake(300,0.0)
  options:NSStringDrawingUsesDeviceMetrics
  context:nil];
</code>```

Is this broken, or do I need to do something else to have it returned a rect for wrapped text?

答:
Swift four version

```<code>let string = "A great test string."
let font = UIFont.systemFont(ofSize: 14)
let attributes: [NSAttributedStringKey: Any] = [.font: font]
let attributedString = NSAttributedString(string: string, attributes: attributes)
let largestSize = CGSize(width: bounds.width, height: .greatestFiniteMagnitude)

//Option one (best option)
let framesetter = CTFramesetterCreateWithAttributedString(attributedString)
let textSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRange(), nil, largestSize, nil)

//Option two
let textSize = (string as NSString).boundingRect(with: largestSize, options: [.usesLineFragmentOrigin , .usesFontLeading], attributes: attributes, context: nil).size

//Option three
let textSize = attributedString.boundingRect(with: largestSize, options: [.usesLineFragmentOrigin , .usesFontLeading], context: nil).size
</code>```

Measuring the text with the CTFramesetter works best as it provides integer sizes and handles emoji's and other unicode characters well.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to get the rect for an attributed string, but the boundingRectWithSize call is not respecting the size I pass in and is returning a rect with a single line height as opposed to a large height (it is a long string). I have experimented by passing in a very large value for the height and also 0 as in the code below, but the rect returned is always the same.

CGRect paragraphRect = [attributedText boundingRectWithSize:CGSizeMake(300,0.0)
  options:NSStringDrawingUsesDeviceMetrics
  context:nil];

Is this broken, or do I need to do something else to have it returned a rect for wrapped text?

Body:
Swift four version

let string = "A great test string."
let font = UIFont.systemFont(ofSize: 14)
let attributes: [NSAttributedStringKey: Any] = [.font: font]
let attributedString = NSAttributedString(string: string, attributes: attributes)
let largestSize = CGSize(width: bounds.width, height: .greatestFiniteMagnitude)

//Option one (best option)
let framesetter = CTFramesetterCreateWithAttributedString(attributedString)
let textSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRange(), nil, largestSize, nil)

//Option two
let textSize = (string as NSString).boundingRect(with: largestSize, options: [.usesLineFragmentOrigin , .usesFontLeading], attributes: attributes, context: nil).size

//Option three
let textSize = attributedString.boundingRect(with: largestSize, options: [.usesLineFragmentOrigin , .usesFontLeading], context: nil).size

Measuring the text with the CTFramesetter works best as it provides integer sizes and handles emoji's and other unicode characters well.

ContentLicense: CC BY-SA 4.0


问:
PHP big array performance?
I have a question regarding array's performance with huge amount of elements. I have this big array that currently has about 100 elements and I will keep adding to it in the future so it will get larger and larger with time. My question is, will there be a huge performance impact when this array gets to 500+ elements or more?</p>

```<code>  $pages=array(
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>',
  '<div class="article"><img src="image url here"></div>');
  }
</code>```

答:
500+ will not do HUGE impact on performance. If your server has good RAM you do not need to be worry even though it reaches like, 10,000 - 50,000+.

But your concern has a valid point regarding scale-ability. Try to index your array with a known key and always try to use isset[<knonwn_key>] other than going for is_array operation (as Joey stated).

Even after doing this if you face performance issues, it will be the time to go to memcache. (Going from normal array to memcache will be easy if you have a known key array)

Hope this would help you! Thanks.

Title: PHP big array performance?

Body:
I have a question regarding array's performance with huge amount of elements. I have this big array that currently has about 100 elements and I will keep adding to it in the future so it will get larger and larger with time. My question is, will there be a huge performance impact when this array gets to 500+ elements or more?

  $pages=array(
  '

',
  '

',
  '

',
  '

',
  '

',
  '

',
  '

',
  '

');
  }


问:
Batch - Count string appearance between two patterns
This question is pretty similar to this question.

I've been stuck trying to count how many a string appears between brackets. Consider the follow text file(although it looks like a .bat script)

```<code>(
echo a
echo b
echo c
)
echo z
</code>```

In the file above, we can see 4 echo, but I only want to count the ones inside the brackets(the result should be 3)

```<code>for /f "delims=][  tokens=2" %%H in ('FART.exe -c -i -p %File% ^( a') do set /a count+=1
</code>```

This code works, but only counts 1, because I couldn't figure out how to count multiple appearances. Please help me, any help will be appreciated.

Edit - 5/7/17

You can assume

There would be only 1 echo on each line.

Parentheses are not nested

echo would not appear on the same line as parentheses

Bonus if you can make your script count the echo on the same line of parentheses

答:
You can try this regex:

```<code>echo(?=((?!\().)*\))
</code>```

The number of match of the word 'echo' inside bracket will be your count

Regex101 Demo

As, windows batch won't support lookaheads thus you may use python script for the same purpose instead of using batch if you have to apply regex. Apart, you may try non regex solution in batch

This block will do: (run here )

```<code>regex = r"echo(?=((?!\().)*\))"
matches = re.finditer(regex, test_str, re.DOTALL)
count=0

for match in matches:
        count +=1
print(count)
</code>```

where test_str is the content of the file

Body:
This question is pretty similar to this question.

I've been stuck trying to count how many a string appears between brackets. Consider the follow text file(although it looks like a .bat script)

(
echo a
echo b
echo c
)
echo z

In the file above, we can see 4 echo, but I only want to count the ones inside the brackets(the result should be 3)

for /f "delims=][  tokens=2" %%H in ('FART.exe -c -i -p %File% ^( a') do set /a count+=1

This code works, but only counts 1, because I couldn't figure out how to count multiple appearances. Please help me, any help will be appreciated.

Edit - 5/7/17

You can assume

There would be only 1 echo on each line.

Parentheses are not nested

echo would not appear on the same line as parentheses

Bonus if you can make your script count the echo on the same line of parentheses

Body:
You can try this regex:

echo(?=((?!\().)*\))

The number of match of the word 'echo' inside bracket will be your count

Regex101 Demo

As, windows batch won't support lookaheads thus you may use python script for the same purpose instead of using batch if you have to apply regex. Apart, you may try non regex solution in batch

This block will do: (run here )

regex = r"echo(?=((?!\().)*\))"
matches = re.finditer(regex, test_str, re.DOTALL)
count=0

for match in matches:
        count +=1
print(count)

where test_str is the content of the file


问:
"Comments are not Supported in JSON because developers used to pass instructions to the parser". Can anyone explain what this means?
I was searching for the reason behind removing Comments in JSON although many parsers have the capability of reading comments. The reason sited by Douglas Crawford, is because of the practice of passing instructions to the parsers via comments. Can anyone explain what that means?</p>

答: this brings trouble, data is data, consistency should not brought uncertainty, says you could read environment variable or control layout / rules or so? i guess</p>


问:
how to display image description written by user in django template
I am a newbie in Django.I want to create simple upload app in which description of image ,price and email-id will be entered by the user.And want to display the description text and email along with the image.But the text is not appearing along with the image.
See the final image after uploading

Below is my code :

Models.py

```<code>  # -*- coding: utf-8 -*-
from django.db import models

class Document(models.Model):

    docfile = models.FileField(upload_to='documents/%Y/%m/%d')

    description = models.CharField(max_length=255, blank=True)

    price = models.IntegerField(default=0)

    emailId = models.CharField(max_length=255, blank=True)

**forms.py**

    from django import forms

class DocumentForm(forms.Form):

    docfile = forms.FileField(
        label='Select a file',
    )
    description = forms.CharField(max_length=255)

    price = forms.IntegerField()

    emailId = forms.CharField(max_length=255)

**views.py**

from django.template import RequestContext

from django.http import HttpResponseRedirect

from django.core.urlresolvers import reverse

from django.shortcuts import render

from django.shortcuts import render_to_response

from myapp.models import Document

from myapp.forms import DocumentForm

def list(request):

    if request.method == 'POST':

        form = DocumentForm(request.POST, request.FILES)

        if form.is_valid():

            newdoc = Document(docfile = request.FILES['docfile'])

            newdoc.save()

            return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm() # A empty, unbound form

    documents = Document.objects.all()

    return render(request,'myapp/list.html',{'documents': documents, 'form': form} )

def index(request):

    return render_to_response('myapp/index1.html')

**list.html**

{% load staticfiles %}

{% load static %}

<html>

  <head>

    <meta charset="utf-8">

    <title>Recent Uploads</title>

  </head>
  <body>

    <form action="{% url "list" %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Upload</button>
</form>

    <div id="wrapper">
      <section>
        {% if documents %}
        <ul id="gallery">
          {% for document in documents %}
          <li>
             <a href="{{ document.docfile.url }}">
              <img src="{{ document.docfile.url }}" alt=""></a>
              <p>
                <font color="black">
                  <p>Description : {{ document.description }}</p>
                  <p>Price :{{ document.price }}</p>
                  <p>Contact/Email-ID : {{ document.emailId }}</p>
            </font>
            </a>
          </li>
          {% endfor %}
        </ul>
        {% else %}
            <p>No documents.</p>
        {% endif %}
      </section>
    </div>
  </body>
</html>
</code>```

答:
Your form does not save data to the database. You need to inherit from forms.ModelForm rather than forms.Form. For the latter, you may require to write your own custom save method. ModelForms does that for you implicitly.

forms.py,

```<code>class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = "__all__"
</code>```

views.py,

```<code>def list(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            doc = form.save(commit=False)
            doc.docfile = request.FILES['docfile']
            doc.save()
            return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm()
    documents = Document.objects.all()
    return render(request,'myapp/list.html',{'documents': documents, 'form': form} )
</code>```

Body:
I am a newbie in Django.I want to create simple upload app in which description of image ,price and email-id will be entered by the user.And want to display the description text and email along with the image.But the text is not appearing along with the image.
See the final image after uploading

Below is my code :

Models.py

  # -*- coding: utf-8 -*-
from django.db import models

class Document(models.Model):

    docfile = models.FileField(upload_to='documents/%Y/%m/%d')

    description = models.CharField(max_length=255, blank=True)

    price = models.IntegerField(default=0)

    emailId = models.CharField(max_length=255, blank=True)

**forms.py**

    from django import forms

class DocumentForm(forms.Form):

    docfile = forms.FileField(
        label='Select a file',
    )
    description = forms.CharField(max_length=255)

    price = forms.IntegerField()

    emailId = forms.CharField(max_length=255)

**views.py**

from django.template import RequestContext

from django.http import HttpResponseRedirect

from django.core.urlresolvers import reverse

from django.shortcuts import render

from django.shortcuts import render_to_response

from myapp.models import Document

from myapp.forms import DocumentForm

def list(request):

    if request.method == 'POST':

        form = DocumentForm(request.POST, request.FILES)

        if form.is_valid():

            newdoc = Document(docfile = request.FILES['docfile'])

            newdoc.save()

            return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm() # A empty, unbound form

    documents = Document.objects.all()

    return render(request,'myapp/list.html',{'documents': documents, 'form': form} )

def index(request):

    return render_to_response('myapp/index1.html')

**list.html**

{% load staticfiles %}

{% load static %}

    <meta charset="utf-8">

    <title>Recent Uploads</title>

    <form action="{% url "list" %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Upload</button>
</form>

        {% if documents %}

          {% for document in documents %}

Description : {{ document.description }}

Price :{{ document.price }}

Contact/Email-ID : {{ document.emailId }}

          {% endfor %}

        {% else %}

No documents.

        {% endif %}

Body:
Your form does not save data to the database. You need to inherit from forms.ModelForm rather than forms.Form. For the latter, you may require to write your own custom save method. ModelForms does that for you implicitly.

forms.py,

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = "__all__"

views.py,

def list(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            doc = form.save(commit=False)
            doc.docfile = request.FILES['docfile']
            doc.save()
            return HttpResponseRedirect(reverse('list'))
    else:
        form = DocumentForm()
    documents = Document.objects.all()
    return render(request,'myapp/list.html',{'documents': documents, 'form': form} )


问:
Refreshing routes are 404ing when I deploy to the server
I am using react-router v4.  You can see my site shell here.
http://responder.azurewebsites.net/

Click on one of the tabs at the bottom, such as the 3rd tab which goes to here:
http://responder.azurewebsites.net/profile

If you try to refresh this page or click it directly it will 404.

However, on localhost this does not happen and things work well.

Cannot think of why this is working locally but refreshing on the server fails.

Direction would be great!

Here is my router

```<code> <div className="App">
        <Header />
        <Router>
          <div className="App-content">
            <Route path="/bank" component={BankPage} />
            <Route path="/active-chats" component={ActiveChatsPage} />
            <Route path="/profile" component={ProfilePage} />
            <NavBar />
          </div>
        </Router>
      </div>
</code>```

答:
You shoud to add route to this link. Ex: if you use Express and nodejs on sever side add this

```<code>express().get('*', function(req, res) {...})
</code>```

If you use Php laravel on server side add this line to route file (web.php)

```<code>Route::get('/{any?}', 'KeywordController@index');
</code>```

Body:
I am using react-router v4.  You can see my site shell here.
http://responder.azurewebsites.net/

Click on one of the tabs at the bottom, such as the 3rd tab which goes to here:
http://responder.azurewebsites.net/profile

If you try to refresh this page or click it directly it will 404.

However, on localhost this does not happen and things work well.

Cannot think of why this is working locally but refreshing on the server fails.

Direction would be great!

Here is my router

        <Router>

            <Route path="/bank" component={BankPage} />
            <Route path="/active-chats" component={ActiveChatsPage} />
            <Route path="/profile" component={ProfilePage} />
            <NavBar />

        </Router>

Body:
You shoud to add route to this link. Ex: if you use Express and nodejs on sever side add this

express().get('*', function(req, res) {...})

If you use Php laravel on server side add this line to route file (web.php)

Route::get('/{any?}', 'KeywordController@index');


问:
SharePoint: "Failed to extract the cab file in the solution"
I'm receiving a "Failed to extract the cab file in the solution" error when I try to deploy my wsp using stsadm -o addsolution -filename...

I've open the wsp as a cab and checked that there are no duplicate files in there as I understand that can sometimes cause this issue.

The issue only started when I tried to include a custom field type as part of my solution, to do this I added the following to the ddf

..\CustomFields\ShortMonth\ShortMonthControl.ascx ..\CONTROLTEMPLATES\ShortMonthControl.ascx

..\CustomFields\ShortMonth\fldtypes_shortmonth.xml ..\XML\fldtypes_shortmonth.xml

and

<TemplateFiles>

<TemplateFile Location="CONTROLTEMPLATES\ShortMonthControl.ascx"/>

<TemplateFile Location="XML\fldtypes_shortmonth.xml"/>

</TemplateFiles>

to the manifest.

I've tried taking it back to just references to the ascx in both but it doesn't see to help.

Any ideas?

答: The List Instance Name I had was "MyListInstance (List Instance)". I removed the brackets from the name and it deployed without issues.</p>

ContentLicense: CC BY-SA 2.5


问:
reference variable in ngFor not working
I want to convert following HTML code to Angular code using *ngFor

```<code><div>Children: <input type="radio" id="1" name="children" [value]="1" [(ngModel)]="this.children"/>1
      <input type="radio" id="2" name="children" [value]="2" [(ngModel)]="this.children"/>2
      <input type="radio" id="3" name="children" [value]="3" [(ngModel)]="this.children"/>3
      You have {{this.children}} children
      </div>
</code>```

Angular code

```<code><div>Children: <input *ngFor = "let option of selectOptions" type="radio" id=option name="children" [value]=option [(ngModel)]="this.children"/>{{option}}
        You have {{this.children}} children
      </div>
</code>```

selectOptions is defined in Component's class as follows:

```<code>selectOptions:Array<number>=[1,2,3]
</code>```

I can see error for {{option}} that Angular: Identifier 'option' is not defined. The component declaration, template variable declarations, and element references do not contain such a member

I also see error for id=option name="children" that tag start is not closed.

What am I doing wrong?

答:
It seems one issue is that option goes out of scope once input tag is closed. If I move *ngFor to div then I get the labels. But they are now displayed vertically, not horizontally. This code works but with vertical alignment
 <input type="radio" [id]="option" name="children" [value]=option [(ngModel)]="this.children">{{option}}

For horizontal alignment, this worked. Instead of repeating div, I repeated label. label wraps the input so option is in scope of input -
  <input type="radio" [id]="option" name="children" [value]=option [(ngModel)]="this.children"> {{option}}

Title: reference variable in ngFor not working

Body:
I want to convert following HTML code to Angular code using *ngFor

Children: <input type="radio" id="1" name="children" [value]="1" [(ngModel)]="this.children"/>1
      <input type="radio" id="2" name="children" [value]="2" [(ngModel)]="this.children"/>2
      <input type="radio" id="3" name="children" [value]="3" [(ngModel)]="this.children"/>3
      You have {{this.children}} children

Angular code

Children: <input *ngFor = "let option of selectOptions" type="radio" id=option name="children" [value]=option [(ngModel)]="this.children"/>{{option}}
        You have {{this.children}} children

selectOptions is defined in Component's class as follows:

selectOptions:Array<number>=[1,2,3]

I can see error for {{option}} that Angular: Identifier 'option' is not defined. The component declaration, template variable declarations, and element references do not contain such a member

I also see error for id=option name="children" that tag start is not closed.

What am I doing wrong?

Body:
It seems one issue is that option goes out of scope once input tag is closed. If I move *ngFor to div then I get the labels. But they are now displayed vertically, not horizontally. This code works but with vertical alignment <div *ngFor = "let option of selectOptions"> <input type="radio" [id]="option" name="children" [value]=option [(ngModel)]="this.children">{{option}} </div>

For horizontal alignment, this worked. Instead of repeating div, I repeated label. label wraps the input so option is in scope of input - <div > <label *ngFor = "let option of this.selectOptions; let ind=index"> <input type="radio" [id]="option" name="children" [value]=option [(ngModel)]="this.children"> {{option}} </label> </div>


问:
how to select Multiple activities in android?
How to select multipleActivities?
I have a listview it consists of multiple activity .if i select multiple list i want to startactivity of selected list   .

答:
Try this :

```<code>listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
    switch(position){
    case 0:
    //Open first activity
    startActivity(new Intent(context,Activity1.class));
    break;
    case 1:
    //Open second activity
    startActivity(new Intent(context,Activity2.class));
    break;
    //So on...!!

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

Hope this helps.

Body:
Try this :

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
    switch(position){
    case 0:
    //Open first activity
    startActivity(new Intent(context,Activity1.class));
    break;
    case 1:
    //Open second activity
    startActivity(new Intent(context,Activity2.class));
    break;
    //So on...!!

    }
}
});

Hope this helps.


问:
UPDATED: How can I Insert a Json object inside a Json Array to SQLite
Good day, How to fetch this Json Response and insert it in Android SQLite.
Hope you will guide me how to fetch this Json object inside a Json Array inside a Object

```<code>{
  "error": false,
  "sl_summ": [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}
</code>```

This my whole JSON response. the 1st Json Object(user) was successfully parse and inserted to database but the 2nd Json response(sl_summ) was unsuccessfully parse and was not inserted. and thats my problem.

```<code>{
  "error": false,
  "user": {
    "br_code": 12,
    "mem_id": 13,
    "username": "novalyn",
    "email": "gsac_tabaco@yahoo.com",
    "created_at": "2016-07-22 09:05:21"
  }
}
{
  "error": false,
  "sl_summ":
  [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}
</code>```

This is the Logcat message

```<code>D/RegisterActivity: Login Response: {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}
07-05 16:19:15.068 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/ViewRootImpl@dd06ab4[LoginActivity]: dispatchDetachedFromWindow
07-05 16:19:15.083 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/InputTransport: Input channel destroyed: fd=76
07-05 16:19:15.084 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/RegisterActivity: Checking JSON Object{"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
07-05 16:19:15.085 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/TEST: -error attribute             : false
07-05 16:19:15.094 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SessionManager: User login session modified!
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -user object     : {"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -br_code         : 12
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -mem_id          : 13
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -username        : novalyn
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -email           : gsac_tabaco@yahoo.com
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -created at      : 2016-07-22 09:05:21
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: New member was inserted into table members: 13
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: BR CODE: 12
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Member ID: 13
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Username: novalyn
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Email: gsac_tabaco@yahoo.com
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Created at: 2016-07-22 09:05:21
07-05 16:19:15.118 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/sl_summ: JSON String                  : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
07-05 16:19:15.118 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/sl_summ: -error attribute             : false
07-05 16:19:15.119 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/TEST: org.json.JSONException: No value for sl_summ
</code>```

I noticed that only the 1st response was returned

```<code>D/sl_summ: JSON String : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/sl_summ: -error attribute             : false
D/TEST: org.json.JSONException: No value for sl_summ
</code>```

答:
Here are the steps you can follow:</p>

```<code>JSONObject jsonObject = new JSONObject("Your JSON String here");

String error=jsonObject.getString("");

JSONArray s1_sum = jsonObject.getJSONArray("sl_summ");

int s1_sum_length = s1_sum.length();

for (int i = 0; i < s1_sum_length; i++) {
String individualString = statementtag.getJSONObject(i);
sl_desc = individualString.getString("sl_desc");
tr_date = individualString.getString("tr_date");
actual_balance = individualString.getString("actual_balance");
available_balance = individualString.getString("available_balance");

//YOU CAN WRITE INSERT QUERY HERE
}
</code>```

Body:
Good day, How to fetch this Json Response and insert it in Android SQLite.
Hope you will guide me how to fetch this Json object inside a Json Array inside a Object

{
  "error": false,
  "sl_summ": [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}

This my whole JSON response. the 1st Json Object(user) was successfully parse and inserted to database but the 2nd Json response(sl_summ) was unsuccessfully parse and was not inserted. and thats my problem.

{
  "error": false,
  "user": {
    "br_code": 12,
    "mem_id": 13,
    "username": "novalyn",
    "email": "gsac_tabaco@yahoo.com",
    "created_at": "2016-07-22 09:05:21"
  }
}
{
  "error": false,
  "sl_summ":
  [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}

This is the Logcat message

D/RegisterActivity: Login Response: {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}
07-05 16:19:15.068 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/ViewRootImpl@dd06ab4[LoginActivity]: dispatchDetachedFromWindow
07-05 16:19:15.083 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/InputTransport: Input channel destroyed: fd=76
07-05 16:19:15.084 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/RegisterActivity: Checking JSON Object{"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
07-05 16:19:15.085 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/TEST: -error attribute             : false
07-05 16:19:15.094 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SessionManager: User login session modified!
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -user object     : {"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -br_code         : 12
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -mem_id          : 13
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -username        : novalyn
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -email           : gsac_tabaco@yahoo.com
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -created at      : 2016-07-22 09:05:21
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: New member was inserted into table members: 13
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: BR CODE: 12
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Member ID: 13
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Username: novalyn
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Email: gsac_tabaco@yahoo.com
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Created at: 2016-07-22 09:05:21
07-05 16:19:15.118 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/sl_summ: JSON String                  : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
07-05 16:19:15.118 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/sl_summ: -error attribute             : false
07-05 16:19:15.119 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/TEST: org.json.JSONException: No value for sl_summ

I noticed that only the 1st response was returned

D/sl_summ: JSON String : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/sl_summ: -error attribute             : false
D/TEST: org.json.JSONException: No value for sl_summ

Body:
Here are the steps you can follow:

JSONObject jsonObject = new JSONObject("Your JSON String here");

String error=jsonObject.getString("");

JSONArray s1_sum = jsonObject.getJSONArray("sl_summ");

int s1_sum_length = s1_sum.length();

for (int i = 0; i < s1_sum_length; i++) {
String individualString = statementtag.getJSONObject(i);
sl_desc = individualString.getString("sl_desc");
tr_date = individualString.getString("tr_date");
actual_balance = individualString.getString("actual_balance");
available_balance = individualString.getString("available_balance");

//YOU CAN WRITE INSERT QUERY HERE
}


问:
exception occurence in mvc
****I am getting an exception of type 'System.IndexOutOfRangeException' in System.Data.dll but was not handled in user code**** </p>

```<code>    public List<ItemModel> med()
            {
                List<ItemModel> itemList = new List<ItemModel>();
                connection();
                SqlCommand cmd = new SqlCommand("procmedication_dropdown1", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@PstrOperationFlag", "S-drugname");
                con.Open();
                SqlDataAdapter sd = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                sd.Fill(dt);
                ItemModel item = new ItemModel();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    ItemModel io = new ItemModel();
                    while (sdr.Read())
                    {
                        io = new ItemModel();
                        io.medication = sdr["medications"].ToString();

                        itemList.Add(io);

                    }
                }
                con.Close();
                return itemList;
            }
        }
    }
</code>```

答:
Try this</p>

```<code>    public List<ItemModel> med()
    {
        List<ItemModel> itemList = new List<ItemModel>();
        ItemModel io;
        connection();
        SqlCommand cmd = new SqlCommand("procmedication_dropdown1", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@PstrOperationFlag", "S-drugname");
        con.Open();
        using (SqlDataReader sdr = cmd.ExecuteReader())
        {
            while (sdr.Read())
            {
                io = new ItemModel();
                io.medication = sdr["medications"].ToString();
                itemList.Add(io);
            }
        }
        con.Close();
        return itemList;
    }
</code>```

Title: exception occurence in mvc

Body:
****I am getting an exception of type 'System.IndexOutOfRangeException' in System.Data.dll but was not handled in user code****

    public List<ItemModel> med()
            {
                List<ItemModel> itemList = new List<ItemModel>();
                connection();
                SqlCommand cmd = new SqlCommand("procmedication_dropdown1", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@PstrOperationFlag", "S-drugname");
                con.Open();
                SqlDataAdapter sd = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                sd.Fill(dt);
                ItemModel item = new ItemModel();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    ItemModel io = new ItemModel();
                    while (sdr.Read())
                    {
                        io = new ItemModel();
                        io.medication = sdr["medications"].ToString();

                        itemList.Add(io);

                    }
                }
                con.Close();
                return itemList;
            }
        }
    }

Body:
Try this

    public List<ItemModel> med()
    {
        List<ItemModel> itemList = new List<ItemModel>();
        ItemModel io;
        connection();
        SqlCommand cmd = new SqlCommand("procmedication_dropdown1", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@PstrOperationFlag", "S-drugname");
        con.Open();
        using (SqlDataReader sdr = cmd.ExecuteReader())
        {
            while (sdr.Read())
            {
                io = new ItemModel();
                io.medication = sdr["medications"].ToString();
                itemList.Add(io);
            }
        }
        con.Close();
        return itemList;
    }


问:
Android EditText background text
Is there a way to set the background text of an EditText? for instance, I have a login screen with 2 EditText views, one for username and one for password. I want the text "Username" and "Password" be written inside the EditText, and once the user touches those the text disappears but once user deleted his own entry, text re-appears.

Is there a property for that or should I implement this on my own with events and stuff?

答: The hint property will take care of that for you.

Title: Android EditText background text


问:
ngStorage module not found only in gulp dist:serve?
I strike this error one again, last time I have fixed but do not know how this fixed but again it occurs.

I have ngstorage module installed and projecr run fine when it's in development ( gulp clean serve ) BUT when it goes to production ( gulp serve:dist) , it execute well but main page is blank and there is error in console

Uncaught Error: [$injector:modulerr] Failed to instantiate module app
  due to: Error: [$injector:modulerr] Failed to instantiate module
  ngStorage due to: Error: [$injector:nomod] Module 'ngStorage' is not
  available! You either misspelled the module name or forgot to load it.
  If registering a module ensure that you specify the dependencies as
  the second argument.
  http://errors.angularjs.org/1.5.8/$injector/nomod?p0=ngStorage

although I have checked that it's installed   can somebody can suggest what is the issue and how to fix this? here is my bower.json

```<code>{
  "name": "project",
  "version": "0.1.1",
  "dependencies": {
    "angular-animate": "1.5.8",
    "angular-touch": "~1.5.0",
    "angular-sanitize": "~1.5.0",
    "angular-messages": "~1.5.0",
    "angular-aria": "~1.5.0",
    "jquery": "~2.1.4",
    "angular-resource": "~1.5.0",
    "angular-ui-router": "~0.2.15",
    "bootstrap": "~3.3.6",
    "angular-bootstrap": "~1.1.2",
    "angular-toastr": "~2.0.0",
    "moment": "~2.13.0",
    "animate.css": "~3.4.0",
    "angular": "~1.5.0",
    "ng-table": "^1.0.0",
    "pace": "~1.0.2",
    "metisMenu": "~2.0.2",
    "fontawesome": "~4.5.0",
    "roboto-fontface": "^0.7.0",
    "angular-ui-validate": "^1.2.2",
    "ng-stomp": "^0.2.0",
    "angular-scrollable-table": "^1.1.1",
    "aws-sdk": "aws-sdk-js#^2.7.7",
    "ng-file-upload": "^12.2.13",
    "angular-recaptcha": "^4.0.3",
    "ng-csv": "^0.3.6",
    "ngstorage": "^0.3.11",
    "intl-tel-input": "5.1.7",
    "international-phone-number": "^0.0.16",
    "angular-chart.js": "^1.1.1"
  },
  "devDependencies": {
    "angular-mocks": "1.5.8"
  },
  "overrides": {
    "bootstrap": {
      "main": [
        "less/bootstrap.less",
        "dist/fonts/glyphicons-halflings-regular.eot",
        "dist/fonts/glyphicons-halflings-regular.svg",
        "dist/fonts/glyphicons-halflings-regular.ttf",
        "dist/fonts/glyphicons-halflings-regular.woff",
        "dist/fonts/glyphicons-halflings-regular.woff2"
      ]
    },
    "fontawesome": {
      "main": [
        "less/font-awesome.less",
        "fonts/fontawesome-webfont.eot",
        "fonts/fontawesome-webfont.svg",
        "fonts/fontawesome-webfont.ttf",
        "fonts/fontawesome-webfont.woff",
        "fonts/fontawesome-webfont.woff2"
      ]
    },
    "roboto-fontface": {
      "main": [
        "css/roboto/less/roboto-fontface.less"
      ]
    },
    "chart.js": {
               "main": [
                   "dist/Chart.bundle.min.js"
               ]
           }
   },
  "resolutions": {
    "jquery": "~2.1.4",
    "angular": "1.5.8"
  },
  "description": "Project Manager On-Premise",
  "main": "",
  "homepage": "index.html",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "test",
    "tests"
  ]
}
</code>```

I think there is issue related to stmop or I am using broswer-sync , that may be cause but cant be sure.

see the

答:
Issue was dues to one of library --which is included-- missing semicolon in it's main js file

cause:

I was using ng-stomp in my project and installed this library using bower install and when I run gulp dist:serve it minified all the files which are mentioned in the main bower.json file and it read bower_components/ng-stomp/package.json where main file location was   "main": "src/ng-stomp.js" and this file missing semicolon in the end so when next js library ( ngStorage) is minified, it does not recognize by it's parser and it throws error.

solution:

override the main file by writing below code in my bower.json overrides block ( add the ng-stomp.min.js which has semicolon in end)

```<code> "ng-stomp": {
            "main": [
                "dist/ng-stmop.min.js"
            ]
        }
</code>```

hope it helps someone

Body:
I strike this error one again, last time I have fixed but do not know how this fixed but again it occurs.

I have ngstorage module installed and projecr run fine when it's in development ( gulp clean serve ) BUT when it goes to production ( gulp serve:dist) , it execute well but main page is blank and there is error in console

Uncaught Error: [$injector:modulerr] Failed to instantiate module app
  due to: Error: [$injector:modulerr] Failed to instantiate module
  ngStorage due to: Error: [$injector:nomod] Module 'ngStorage' is not
  available! You either misspelled the module name or forgot to load it.
  If registering a module ensure that you specify the dependencies as
  the second argument.
  http://errors.angularjs.org/1.5.8/$injector/nomod?p0=ngStorage

although I have checked that it's installed   can somebody can suggest what is the issue and how to fix this? here is my bower.json

{
  "name": "project",
  "version": "0.1.1",
  "dependencies": {
    "angular-animate": "1.5.8",
    "angular-touch": "~1.5.0",
    "angular-sanitize": "~1.5.0",
    "angular-messages": "~1.5.0",
    "angular-aria": "~1.5.0",
    "jquery": "~2.1.4",
    "angular-resource": "~1.5.0",
    "angular-ui-router": "~0.2.15",
    "bootstrap": "~3.3.6",
    "angular-bootstrap": "~1.1.2",
    "angular-toastr": "~2.0.0",
    "moment": "~2.13.0",
    "animate.css": "~3.4.0",
    "angular": "~1.5.0",
    "ng-table": "^1.0.0",
    "pace": "~1.0.2",
    "metisMenu": "~2.0.2",
    "fontawesome": "~4.5.0",
    "roboto-fontface": "^0.7.0",
    "angular-ui-validate": "^1.2.2",
    "ng-stomp": "^0.2.0",
    "angular-scrollable-table": "^1.1.1",
    "aws-sdk": "aws-sdk-js#^2.7.7",
    "ng-file-upload": "^12.2.13",
    "angular-recaptcha": "^4.0.3",
    "ng-csv": "^0.3.6",
    "ngstorage": "^0.3.11",
    "intl-tel-input": "5.1.7",
    "international-phone-number": "^0.0.16",
    "angular-chart.js": "^1.1.1"
  },
  "devDependencies": {
    "angular-mocks": "1.5.8"
  },
  "overrides": {
    "bootstrap": {
      "main": [
        "less/bootstrap.less",
        "dist/fonts/glyphicons-halflings-regular.eot",
        "dist/fonts/glyphicons-halflings-regular.svg",
        "dist/fonts/glyphicons-halflings-regular.ttf",
        "dist/fonts/glyphicons-halflings-regular.woff",
        "dist/fonts/glyphicons-halflings-regular.woff2"
      ]
    },
    "fontawesome": {
      "main": [
        "less/font-awesome.less",
        "fonts/fontawesome-webfont.eot",
        "fonts/fontawesome-webfont.svg",
        "fonts/fontawesome-webfont.ttf",
        "fonts/fontawesome-webfont.woff",
        "fonts/fontawesome-webfont.woff2"
      ]
    },
    "roboto-fontface": {
      "main": [
        "css/roboto/less/roboto-fontface.less"
      ]
    },
    "chart.js": {
               "main": [
                   "dist/Chart.bundle.min.js"
               ]
           }
   },
  "resolutions": {
    "jquery": "~2.1.4",
    "angular": "1.5.8"
  },
  "description": "Project Manager On-Premise",
  "main": "",
  "homepage": "index.html",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "test",
    "tests"
  ]
}

I think there is issue related to stmop or I am using broswer-sync , that may be cause but cant be sure.

see the

Body:
Issue was dues to one of library --which is included-- missing semicolon in it's main js file

cause:

I was using ng-stomp in my project and installed this library using bower install and when I run gulp dist:serve it minified all the files which are mentioned in the main bower.json file and it read bower_components/ng-stomp/package.json where main file location was   "main": "src/ng-stomp.js" and this file missing semicolon in the end so when next js library ( ngStorage) is minified, it does not recognize by it's parser and it throws error.

solution:

override the main file by writing below code in my bower.json overrides block ( add the ng-stomp.min.js which has semicolon in end)

 "ng-stomp": {
            "main": [
                "dist/ng-stmop.min.js"
            ]
        }

hope it helps someone


问:
Cannot call value of non-function type "calendar"
I made a simple count down app and I get this wrong message: cannot call value of non-function type "calendar".

What I need to change?

```<code>    @IBOutlet weak var deteLabelOutlet: UILabel!
    let formatter = DateFormatter()
    let useCalendar = NSCalendar.current()
    let requesedComponent: NSCalendar.Unit = [
        NSCalendar.Unit.month,
        NSCalendar.Unit.day,
        NSCalendar.Unit.hour,
        NSCalendar.Unit.minute,
        NSCalendar.Unit.second
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(printTime), userInfo: nil, repeats: true)
        timer.fire()
    }

    func printTime() {
        formatter.dateFormat = "MM/dd/yy hh:mm:ss a"
        let startTime = Date()
        let endTime = formatter.date(from: String("12/25/16 12:00:00 a"))

        let timeDiffrenece = useCalendar.components(requesedComponent,fromDate: startTime, toDate: endTime!, options: [] )

        deteLabelOutlet.text = "\(timeDiffrenece.month)Month \(timeDiffrenece.day) days \(timeDiffrenece.minute) minutes \(timeDiffrenece.second) seconds"
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
</code>```

答:
In Swift 3 the current calendar is not a function. Remove the parentheses.

Anyway it's highly recommended to use the native struct Calendar as suggested in the other answer

```<code>let useCalendar = Calendar.current
</code>```

Edit:

You have to unwrap all date components when assigning the values to the label because in Swift 3 all date components are optional. However as all relevant components are specified you can forced unwrap the components safely.

```<code>deteLabelOutlet.text = "\(timeDiffrenece.month!)Month \(timeDiffrenece.day!) days \(timeDiffrenece.minute!) minutes \(timeDiffrenece.second!) seconds"
</code>```

Body:
I made a simple count down app and I get this wrong message: cannot call value of non-function type "calendar".

What I need to change?

    @IBOutlet weak var deteLabelOutlet: UILabel!
    let formatter = DateFormatter()
    let useCalendar = NSCalendar.current()
    let requesedComponent: NSCalendar.Unit = [
        NSCalendar.Unit.month,
        NSCalendar.Unit.day,
        NSCalendar.Unit.hour,
        NSCalendar.Unit.minute,
        NSCalendar.Unit.second
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(printTime), userInfo: nil, repeats: true)
        timer.fire()
    }

    func printTime() {
        formatter.dateFormat = "MM/dd/yy hh:mm:ss a"
        let startTime = Date()
        let endTime = formatter.date(from: String("12/25/16 12:00:00 a"))

        let timeDiffrenece = useCalendar.components(requesedComponent,fromDate: startTime, toDate: endTime!, options: [] )

        deteLabelOutlet.text = "\(timeDiffrenece.month)Month \(timeDiffrenece.day) days \(timeDiffrenece.minute) minutes \(timeDiffrenece.second) seconds"
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

Body:
In Swift 3 the current calendar is not a function. Remove the parentheses.

Anyway it's highly recommended to use the native struct Calendar as suggested in the other answer

let useCalendar = Calendar.current

Edit:

You have to unwrap all date components when assigning the values to the label because in Swift 3 all date components are optional. However as all relevant components are specified you can forced unwrap the components safely.

deteLabelOutlet.text = "\(timeDiffrenece.month!)Month \(timeDiffrenece.day!) days \(timeDiffrenece.minute!) minutes \(timeDiffrenece.second!) seconds"


问:
What is the state of the art in HTML content extraction?
There's a lot of scholarly work on HTML content extraction, e.g., Gupta & Kaiser (2005) Extracting Content from Accessible Web Pages, and some signs of interest here, e.g., one, two, and three, but I'm not really clear about how well the practice of the latter reflects the ideas of the former.  What is the best practice?

Pointers to good (in particular, open source) implementations and good scholarly surveys of implementations would be the kind of thing I'm looking for.

Postscript the first: To be precise, the kind of survey I'm after would be a paper (published, unpublished, whatever) that discusses both criteria from the scholarly literature, and a number of existing implementations, and analyses how unsuccessful the implementations are from the viewpoint of the criteria.  And, really, a post to a mailing list would work for me too.

Postscript the second To be clear, after Peter Rowell's answer, which I have accepted, we can see that this question leads to two subquestions: (i) the solved problem of cleaning up non-conformant HTML, for which Beautiful Soup is the most recommended solution, and (ii) the unsolved problem or separating cruft (mostly site-added boilerplate and promotional material) from meat (the contentthat the kind of people who think the page might be interesting in fact find relevant.  To address the state of the art, new answers need to address the cruft-from-meat peoblem explicitly.

答:
I have come across http://www.keyvan.net/2010/08/php-readability/

Last year I ported Arc90′s Readability
  to use in the Five Filters project.
  It’s been over a year now and
  Readability has improved a lot —
  thanks to Chris Dary and the rest of
  the team at Arc90.

As part of an update to the Full-Text
  RSS service I started porting a more
  recent version (1.6.2) to PHP and the
  code is now online.

For anyone not familiar, Readability
  was created for use as a browser addon
  (a bookmarklet). With one click it
  transforms web pages for easy reading
  and strips away clutter. Apple
  recently incorporated it into Safari
  Reader.

It’s also very handy for content
  extraction, which is why I wanted to
  port it to PHP in the first place.


问:
Exporting data scraped with Selenium to a csv file
I'm trying to fetch and export the data in the front page of https://icostats.com/ to a .csv file. This is my code so far:

```<code>import csv
from selenium import webdriver

def get_elements_by_xpath(driver, xpath):
    return [entry.text for entry in driver.find_elements_by_xpath(xpath)]

url = ("https://icostats.com")
driver = webdriver.Firefox(executable_path=r'C:\Users\alph1\Scrapers\geckodriver.exe')
driver.get(url)

search_entries = [
    ("NAME", "//div[@class='tdName-0-73']"),
    ("DATE", "//div[@class='tdDate-0-74']"),
    ("CUR PRICE", "//div[@class='tdPrice-0-72'][1]"),
    ("ICO PRICE", "//div[@class='tdPrice-0-72'][0]"),
    ("24H ROI", "//div[@class='tdPrimary-0-75']")]

with open('textfile.csv', 'wb') as f_output:
    csv_output = csv.writer(f_output)

    # Write header
    csv_output.writerow([name for name, xpath in search_entries])
    entries = []

    for name, xpath in search_entries:
        entries.append(get_elements_by_xpath(driver, xpath))

    csv_output.writerows(zip(*entries))

get_elements_by_xpath()
</code>```

And here is the exception I'm getting.

File "C:/Users/alph1/PycharmProjects/PyQtPS/ICO2CSV.py", line 28, in  csv_output.writerow([name for name, xpath in search_entries])
  TypeError: a bytes-like object is required, not 'str'

I have a feeling I shouldn't be calling the method like this in the end, but don't know how else I'd do it.

答:
I believe this is due to the fact that you have opened the file as a binary (open('textfile.csv', 'wb'). This means that all data from it will be read in binary, as bytes.

To remedy this, simply do open('textfile.csv', 'w') instead.

Body:
I'm trying to fetch and export the data in the front page of https://icostats.com/ to a .csv file. This is my code so far:

import csv
from selenium import webdriver

def get_elements_by_xpath(driver, xpath):
    return [entry.text for entry in driver.find_elements_by_xpath(xpath)]

url = ("https://icostats.com")
driver = webdriver.Firefox(executable_path=r'C:\Users\alph1\Scrapers\geckodriver.exe')
driver.get(url)

search_entries = [
    ("NAME", "//div[@class='tdName-0-73']"),
    ("DATE", "//div[@class='tdDate-0-74']"),
    ("CUR PRICE", "//div[@class='tdPrice-0-72'][1]"),
    ("ICO PRICE", "//div[@class='tdPrice-0-72'][0]"),
    ("24H ROI", "//div[@class='tdPrimary-0-75']")]

with open('textfile.csv', 'wb') as f_output:
    csv_output = csv.writer(f_output)

    # Write header
    csv_output.writerow([name for name, xpath in search_entries])
    entries = []

    for name, xpath in search_entries:
        entries.append(get_elements_by_xpath(driver, xpath))

    csv_output.writerows(zip(*entries))

get_elements_by_xpath()

And here is the exception I'm getting.

File "C:/Users/alph1/PycharmProjects/PyQtPS/ICO2CSV.py", line 28, in  csv_output.writerow([name for name, xpath in search_entries])
  TypeError: a bytes-like object is required, not 'str'

I have a feeling I shouldn't be calling the method like this in the end, but don't know how else I'd do it.


问:
Convert function with byte[] from C# to C++
There is original C# code for my function:
Them works like a charm, and i will convert them to C++

```<code>    public static byte[] EncryptBlock(byte[] filebuffer)
    {
        int a, i, j, k, tmp;
        int[] key, box;
        byte[] cipher;

        key = new int[KeyBoxLength];
        box = new int[KeyBoxLength];
        cipher = new byte[filebuffer.Length];

        for (i = 0; i < KeyBoxLength; i++)
        {
            key[i] = XorContentLock[i % XorContentLock.Length];
            box[i] = i;
        }
        for (j = i = 0; i < KeyBoxLength; i++)
        {
            j = (j + box[i] + key[i]) % 256;
            tmp = box[i];
            box[i] = box[j];
            box[j] = tmp;
        }
        for (a = j = i = 0; i < filebuffer.Length; i++)
        {
            a++;
            a %= KeyBoxLength;
            j += box[a];
            j %= KeyBoxLength;
            tmp = box[a];
            box[a] = box[j];
            box[j] = tmp;
            k = box[((box[a] + box[j]) % KeyBoxLength)];
            cipher[i] = (byte)(filebuffer[i] ^ k);
        }
        return cipher;
    }
</code>```

And that is how them looks on C++, but i dont have idea, why i've got those errors.

```<code>std::string Conversion::EncryptBlock(std::string& buffer)
{
    int32 a, i, j, k, tmp;
    int key[256];
    int box[256];
    BYTE* cipher = new BYTE[buffer.length];
    for (i = 0; i < KeyBoxLength; i++)
    {
        key[i] = XorFileLock[i % 16];
        box[i] = i;
    }
    for (j = i = 0; i < KeyBoxLength; i++)
    {
        j = (j + box[i] + key[i]) % 256;
        tmp = box[i];
        box[i] = box[j];
        box[j] = tmp;
    }
    for (a = j = i = 0; i < buffer.length; i++)
    {
        a++;
        a %= KeyBoxLength;
        j += box[a];
        j %= KeyBoxLength;
        tmp = box[a];
        box[a] = box[j];
        box[j] = tmp;
        k = box[((box[a] + box[j]) % KeyBoxLength)];
        cipher[i] = (byte)(buffer[i] ^ k);
    }
    std::string ret(reinterpret_cast< char const* >(cipher));
    delete[] cipher;

    return ret;
}
</code>```

And when i compile that, i've got this:

I already got some articles for how convert them, and assign dynamically a byte array. But in my case, seems it's does not work, and i cant understand how to convert those working C# code into C++. Did not got how to resolve C# byte[] into unsigned* int C++, with conversion of those array to std::string after.

Well, what i am doing wrong there? And explain please, why? And how it's should be?
Another example:

答:
std::string::length is a method, not a constant.  The error you're seeing is telling you you can't convert from "pointer to member function of std::string" to unsigned int.  You're missing a pair of parenthesis:

```<code>BYTE* cipher = new BYTE[buffer.length()];
                                  // ^^ Here
</code>```

Unrelated to your problem, you should use std::vector<BYTE> instead of managing your own raw arrays.  You can change the declaration of cipher to

```<code>std::vector<BYTE> cipher(buffer.length());
</code>```

and change the declaration of ret to

```<code>std::string ret(cipher.begin(), cipher.end());
</code>```

Then you don't have to remember to delete[] cipher.  There's no real reason to copy cipher to ret though, you could just declare cipher as std::string cipher(buffer.length(), '\0'); and return cipher; directly.

Body:
There is original C# code for my function:
Them works like a charm, and i will convert them to C++

    public static byte[] EncryptBlock(byte[] filebuffer)
    {
        int a, i, j, k, tmp;
        int[] key, box;
        byte[] cipher;

        key = new int[KeyBoxLength];
        box = new int[KeyBoxLength];
        cipher = new byte[filebuffer.Length];

        for (i = 0; i < KeyBoxLength; i++)
        {
            key[i] = XorContentLock[i % XorContentLock.Length];
            box[i] = i;
        }
        for (j = i = 0; i < KeyBoxLength; i++)
        {
            j = (j + box[i] + key[i]) % 256;
            tmp = box[i];
            box[i] = box[j];
            box[j] = tmp;
        }
        for (a = j = i = 0; i < filebuffer.Length; i++)
        {
            a++;
            a %= KeyBoxLength;
            j += box[a];
            j %= KeyBoxLength;
            tmp = box[a];
            box[a] = box[j];
            box[j] = tmp;
            k = box[((box[a] + box[j]) % KeyBoxLength)];
            cipher[i] = (byte)(filebuffer[i] ^ k);
        }
        return cipher;
    }

And that is how them looks on C++, but i dont have idea, why i've got those errors.

std::string Conversion::EncryptBlock(std::string& buffer)
{
    int32 a, i, j, k, tmp;
    int key[256];
    int box[256];
    BYTE* cipher = new BYTE[buffer.length];
    for (i = 0; i < KeyBoxLength; i++)
    {
        key[i] = XorFileLock[i % 16];
        box[i] = i;
    }
    for (j = i = 0; i < KeyBoxLength; i++)
    {
        j = (j + box[i] + key[i]) % 256;
        tmp = box[i];
        box[i] = box[j];
        box[j] = tmp;
    }
    for (a = j = i = 0; i < buffer.length; i++)
    {
        a++;
        a %= KeyBoxLength;
        j += box[a];
        j %= KeyBoxLength;
        tmp = box[a];
        box[a] = box[j];
        box[j] = tmp;
        k = box[((box[a] + box[j]) % KeyBoxLength)];
        cipher[i] = (byte)(buffer[i] ^ k);
    }
    std::string ret(reinterpret_cast< char const* >(cipher));
    delete[] cipher;

    return ret;
}

And when i compile that, i've got this:

I already got some articles for how convert them, and assign dynamically a byte array. But in my case, seems it's does not work, and i cant understand how to convert those working C# code into C++. Did not got how to resolve C# byte[] into unsigned* int C++, with conversion of those array to std::string after.

Well, what i am doing wrong there? And explain please, why? And how it's should be?
Another example:

Body:
std::string::length is a method, not a constant.  The error you're seeing is telling you you can't convert from "pointer to member function of std::string" to unsigned int.  You're missing a pair of parenthesis:

BYTE* cipher = new BYTE[buffer.length()];
                                  // ^^ Here

Unrelated to your problem, you should use std::vector<BYTE> instead of managing your own raw arrays.  You can change the declaration of cipher to

std::vector<BYTE> cipher(buffer.length());

and change the declaration of ret to

std::string ret(cipher.begin(), cipher.end());

Then you don't have to remember to delete[] cipher.  There's no real reason to copy cipher to ret though, you could just declare cipher as std::string cipher(buffer.length(), '\0'); and return cipher; directly.


问:
Firebase functions ENOTFOUND on all http requests
I'm trying to set up a function that uses Express and makes HTTP requests, but I always get an ENOTFOUND error, no matter the request I make.

I already tried making the requests using 4 different libraries (https, request, request-promise, requestify), but all give the same error.

I followed this examples to set up the system: minimal-webhook + authorized-https-endpoint.

My basic test function, that also throws the error:

```<code>"use strict";
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);

const express = require("express");
const app = express();

const https = require("https");

app.get("*", (req, res) =>
{
    var testReq = https.request({
        host: "www.google.com",
        path: "/recaptcha/api/siteverify"
    },

    (res) => {
        console.log("Finished with response " + res);
    });

    testReq.on("error", (e) => {
        console.log("Crashed with error " + e);
    });

    testReq.end();
});

exports.test = functions.https.onRequest(app);
</code>```

Log of GET request to https://us-central1-project-abc.cloudfunctions.net/test/ using Postman, for example:

```<code>Crashed with error Error: getaddrinfo ENOTFOUND www.google.com www.google.com:443
</code>```

答:
Actually you just need to be on a paid plan to be able to make external requests.

The Blaze plan (pay as you go) can be good for you (I'm currently using that plan with zero charges).

https://firebase.google.com/pricing/

Body:
I'm trying to set up a function that uses Express and makes HTTP requests, but I always get an ENOTFOUND error, no matter the request I make.

I already tried making the requests using 4 different libraries (https, request, request-promise, requestify), but all give the same error.

I followed this examples to set up the system: minimal-webhook + authorized-https-endpoint.

My basic test function, that also throws the error:

"use strict";
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);

const express = require("express");
const app = express();

const https = require("https");

app.get("*", (req, res) =>
{
    var testReq = https.request({
        host: "www.google.com",
        path: "/recaptcha/api/siteverify"
    },

    (res) => {
        console.log("Finished with response " + res);
    });

    testReq.on("error", (e) => {
        console.log("Crashed with error " + e);
    });

    testReq.end();
});

exports.test = functions.https.onRequest(app);

Log of GET request to https://us-central1-project-abc.cloudfunctions.net/test/ using Postman, for example:

Crashed with error Error: getaddrinfo ENOTFOUND www.google.com www.google.com:443


问:
How to get MongoDB version from Ruby code using Mongoid or Mongo Ruby Driver?
I have a Rails app with MongoDB. I need to dynamically display current MongoDB version on the status webpage. It's important for my client to know whether it's 3.0, 3.2 or 3.4 version.

However, I can't find this value anywhere. I'm using pry to debug the connection details and I've already tried any relevant public method from Mongoid and Mongo class hierarchy without success.

The canonical way to do this with pure MongoDB is db.version(), but it seems there is no way to send this raw query with Mongoid.

答:
You should do the following call (Mongoid 5+):

```<code>Mongoid.default_client.command(buildInfo: 1).first[:version]
</code>```

Or, in earlier versions:

```<code>Mongoid.default_session.command(buildinfo: 1)["version"]
</code>```

(Answer updated according to @yeasayer comment)

Body:
You should do the following call (Mongoid 5+):

Mongoid.default_client.command(buildInfo: 1).first[:version]

Or, in earlier versions:

Mongoid.default_session.command(buildinfo: 1)["version"]

(Answer updated according to @yeasayer comment)


问:
Mysql Index is not being used correctly
I got a strange problem with a simple MySQL index.

I got the following table:

```<code>CREATE TABLE `import` (
  `import_id` int(11) NOT NULL AUTO_INCREMENT,
  `import_title` text,
  `import_url` text,
  `import_description` text,
  `import_completed` enum('y','n') NOT NULL DEFAULT 'n',
  `import_user` int(11) DEFAULT NULL,
  `import_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`import_id`),
  KEY `import_added` (`import_added`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
</code>```

In that table are a few thousand rows and I want to get the first 100 with the following Select Clause:

```<code>SELECT
  import_id,
  import_title,
  import_url,
  import_description,
  import_user,
  import_added
FROM import
WHERE import_completed = 'n'
ORDER by import_added ASC
LIMIT 0,100
</code>```

When I use DESCRIBE to take a closer look at the query, my local machine uses the "added" index and returns 100 rows within a few milliseconds like expected.

When I use the same database with the same structure and content on my "production" server and use DESCRIBE there, it shows that the index is used as well, but it returns all rows in that table and the query takes about 6 seconds.

What am I missing? Why is the index not working correctly?

答: Try to make an index on  (import_completed, import_added) The where part will use import_completed and for order by it will use import_added. (I hope this works on MyIsam - On Innodb this is the behavior)

Title: Mysql Index is not being used correctly

Body:
I got a strange problem with a simple MySQL index.

I got the following table:

CREATE TABLE `import` (
  `import_id` int(11) NOT NULL AUTO_INCREMENT,
  `import_title` text,
  `import_url` text,
  `import_description` text,
  `import_completed` enum('y','n') NOT NULL DEFAULT 'n',
  `import_user` int(11) DEFAULT NULL,
  `import_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`import_id`),
  KEY `import_added` (`import_added`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

In that table are a few thousand rows and I want to get the first 100 with the following Select Clause:

SELECT
  import_id,
  import_title,
  import_url,
  import_description,
  import_user,
  import_added
FROM import
WHERE import_completed = 'n'
ORDER by import_added ASC
LIMIT 0,100

When I use DESCRIBE to take a closer look at the query, my local machine uses the "added" index and returns 100 rows within a few milliseconds like expected.

When I use the same database with the same structure and content on my "production" server and use DESCRIBE there, it shows that the index is used as well, but it returns all rows in that table and the query takes about 6 seconds.

What am I missing? Why is the index not working correctly?


问:
Scope of Default function parameters in javascript
I'm playing with some EcmaScript 2015 features and I must say that specification is rather hard to understand.

I totally understand that this code should throw error of some kind:

```<code>(function(a = b, b = 1) { })();
</code>```

And I know that default value could use outer scope:

```<code>(function() {
  let c = 1;
  return (function(a = c) { return a === 1; })();
})();
</code>```

But I don't understand why these examples are not good:

```<code>(function() {
  let a = 1;
  (function(a = a) { })();
})();

(function() {
  let b = 1;
  (function(a = b, b = 2) { })();
})();
</code>```

My Chrome 59.0.3071.115 throws ReferenceError that variable is not defined.

It seems that Chrome is doing some optimization where only 1 scope is created where all parameters set as inaccessible, and they are added one by one after their assignment.

Some proof of this could be:

```<code>(function(a = () => b, b = 2) { return a() === 2; })();
</code>```

This looks like an missing opportunity for my taste and I'm wondering does specification force to use only 1 scope here or this is only v8 implementation details.

Could somebody please point me to place in specification which could clarify this?

答:
I don't understand why these examples are not good

Because the default initialisers are not evaluated in the parent scope, but rather inside the function scope. The parameters themselves are already in scope, so that you can do something like

```<code>(function(a = 2, b = a) { console.log(b); }());
</code>```

Could somebody please point me to place in specification which could clarify this?

The relevant section is §9.2.12 FunctionDeclarationInstantiation.

I must say that specification is rather hard to understand.

Yes it is, although it's written for engine implementors not for programmers. However, the explanatory note basically confirms your understanding of the optimisation

If the function’s formal parameters do not include any default value initializers then the body declarations are instantiated in the same Environment Record as the parameters. If default value parameter initializers exist, a second Environment Record is created for the body declarations.

Your examples basically desugar to

```<code>(function() {
  let a = arguments[0] !== undefined ? arguments[0] : b,
//                                                    ^ clearly a ReferenceError
      b = arguments[1] !== undefined ? arguments[1] : 1;
  {
  }
})();

(function() {
  let c = 1;
  return (function() {
    let a = arguments[0] !== undefined ? arguments[0] : c;
//                                                      ^ works as you'd think
    {
      return a === 1;
    }
  })();
})();

(function() {
  let a = 1;
  (function() {
    let a = arguments[0] !== undefined ? arguments[0] : a;
//                                                      ^ again clearly a ReferenceError
    {
    }
  })();
})();

(function() {
  let b = 1;
  (function() {
    let a = arguments[0] !== undefined ? arguments[0] : b,
//                                                      ^ still a ReferenceError
        b = arguments[1] !== undefined ? arguments[1] : 2;
    {
    }
  })();
})();

(function() {
  let a = arguments[0] !== undefined ? arguments[0] : () => b,
//                                                          ^ works indeed
      b = arguments[1] !== undefined ? arguments[1] : 2;
  {
    return a() === 2;
  }
})();
</code>```

Body:
I'm playing with some EcmaScript 2015 features and I must say that specification is rather hard to understand.

I totally understand that this code should throw error of some kind:

(function(a = b, b = 1) { })();

And I know that default value could use outer scope:

(function() {
  let c = 1;
  return (function(a = c) { return a === 1; })();
})();

But I don't understand why these examples are not good:

(function() {
  let a = 1;
  (function(a = a) { })();
})();

(function() {
  let b = 1;
  (function(a = b, b = 2) { })();
})();

My Chrome 59.0.3071.115 throws ReferenceError that variable is not defined.

It seems that Chrome is doing some optimization where only 1 scope is created where all parameters set as inaccessible, and they are added one by one after their assignment.

Some proof of this could be:

(function(a = () => b, b = 2) { return a() === 2; })();

This looks like an missing opportunity for my taste and I'm wondering does specification force to use only 1 scope here or this is only v8 implementation details.

Could somebody please point me to place in specification which could clarify this?

Body:
I don't understand why these examples are not good

Because the default initialisers are not evaluated in the parent scope, but rather inside the function scope. The parameters themselves are already in scope, so that you can do something like

(function(a = 2, b = a) { console.log(b); }());

Could somebody please point me to place in specification which could clarify this?

The relevant section is §9.2.12 FunctionDeclarationInstantiation.

I must say that specification is rather hard to understand.

Yes it is, although it's written for engine implementors not for programmers. However, the explanatory note basically confirms your understanding of the optimisation

If the function’s formal parameters do not include any default value initializers then the body declarations are instantiated in the same Environment Record as the parameters. If default value parameter initializers exist, a second Environment Record is created for the body declarations.

Your examples basically desugar to

(function() {
  let a = arguments[0] !== undefined ? arguments[0] : b,
//                                                    ^ clearly a ReferenceError
      b = arguments[1] !== undefined ? arguments[1] : 1;
  {
  }
})();

(function() {
  let c = 1;
  return (function() {
    let a = arguments[0] !== undefined ? arguments[0] : c;
//                                                      ^ works as you'd think
    {
      return a === 1;
    }
  })();
})();

(function() {
  let a = 1;
  (function() {
    let a = arguments[0] !== undefined ? arguments[0] : a;
//                                                      ^ again clearly a ReferenceError
    {
    }
  })();
})();

(function() {
  let b = 1;
  (function() {
    let a = arguments[0] !== undefined ? arguments[0] : b,
//                                                      ^ still a ReferenceError
        b = arguments[1] !== undefined ? arguments[1] : 2;
    {
    }
  })();
})();

(function() {
  let a = arguments[0] !== undefined ? arguments[0] : () => b,
//                                                          ^ works indeed
      b = arguments[1] !== undefined ? arguments[1] : 2;
  {
    return a() === 2;
  }
})();


问:
wildfly: How to use encrypted password for a xa-datasource?
I have a wildfly 8.2.0.Final running. I use two oracle datasources, one <datasource> and one <xa-datasource>. I want to have my DB passwords encrypted and managed to do that for the datasource using a security-domain but not for the xa-datasource.
I haven't found documentation or other postings with a solution for this problem.

Here is what I've done:

```<code>        <datasources>
            <datasource jta="false" jndi-name="java:/myproject/jdbc/datasources/jdbc" pool-name="my_JDBC_DS" enabled="true" use-ccm="false">
                <connection-url>jdbc:oracle:thin:@localhost:1521:DB</connection-url>
                <driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
                <driver>oracle</driver>
                <pool>
                    <min-pool-size>1</min-pool-size>
                    <max-pool-size>50</max-pool-size>
                </pool>
                <security>
                    <security-domain>databaseSecure</security-domain>
                </security>
                <validation>
                    <check-valid-connection-sql>select 1 from dual</check-valid-connection-sql>
                    <validate-on-match>true</validate-on-match>
                    <background-validation>false</background-validation>
                </validation>
            </datasource>
            <xa-datasource jndi-name="java:/myproject/jdbc/datasources/db_tx" pool-name="MYTXDS" enabled="true" use-ccm="false">
                <xa-datasource-property name="URL">
                    jdbc:oracle:thin:@localhost:1521:DB
                </xa-datasource-property>
                <xa-datasource-property name="User">
                    scott
                </xa-datasource-property>
                <xa-datasource-property name="Password">
                    tiger
                </xa-datasource-property>
                <driver>oracle</driver>
                <security>
                  <user-name>scott</user-name>
                    <password>tiger</password>
                </security>
                <xa-pool>
                    <min-pool-size>1</min-pool-size>
                    <max-pool-size>50</max-pool-size>
                    <wrap-xa-resource>false</wrap-xa-resource>
                </xa-pool>
                <validation>
                    <check-valid-connection-sql>select 1 from dual</check-valid-connection-sql>
                    <validate-on-match>true</validate-on-match>
                    <background-validation>false</background-validation>
                </validation>
                <statement>
                    <prepared-statement-cache-size>32</prepared-statement-cache-size>
                    <share-prepared-statements>true</share-prepared-statements>
                </statement>
            </xa-datasource>
            <drivers>
                <driver name="oracle" module="oracle">
                    <xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource</xa-datasource-class>
                </driver>
            </drivers>
        </datasources>
...
            <security-domain name="databaseSecure" cache-type="default">
                <authentication>
                    <login-module code="org.picketbox.datasource.security.SecureIdentityLoginModule" flag="required">
                        <module-option name="username" value="scott"/>
                        <module-option name="password" value="-170dd0fbd8c13748"/>
                    </login-module>
                </authentication>
            </security-domain>
</code>```

I've tried removing the xa-datasource-property entries for user and password and referring to the security-domain both nested in the security-tag and on the same level as the properties. Both attempts did not work, with the latter the wildfly exits early because of problems parsing the standalone.xml, with the latter the deployment fails.

To show the most promising attempt, this is how I tried to refer to the security-domain:

```<code><xa-datasource jndi-name="java:/myproject/jdbc/datasources/db_tx" pool-name="MYTXDS" enabled="true" use-ccm="false">
            <xa-datasource-property name="URL">
                jdbc:oracle:thin:@localhost:1521:DB
            </xa-datasource-property>
            <driver>oracle</driver>
            <security>
              <security-domain>databaseSecure</security-domain>
            </security>
            <xa-pool>
                <min-pool-size>1</min-pool-size>
                <max-pool-size>50</max-pool-size>
                <wrap-xa-resource>false</wrap-xa-resource>
            </xa-pool>
            <validation>
                <check-valid-connection-sql>select 1 from dual</check-valid-connection-sql>
                <validate-on-match>true</validate-on-match>
                <background-validation>false</background-validation>
            </validation>
            <statement>
                <prepared-statement-cache-size>32</prepared-statement-cache-size>
                <share-prepared-statements>true</share-prepared-statements>
            </statement>
        </xa-datasource>
</code>```

Doing that the wildfly runs into a javax.resource.ResourceException: No matching credentials in Subject!
I've debugged into the code and although I'm missing the code for the last few classes in the call stack I see that the Subject actually has the credentials as properties but still the AccessController.doPrivilegedcall fails, leading to the above mentioned exception.

You see I'm kind of lost, any suggestions?

答:
i disabled caching of security-domain by removing cache-type="default" from security-domain in standalone.xml and it works for me
This happens where multiple datasources are defined backed by the same security domain,
- Either make separte security-domain for each datasource or
- if a security domain is to be used with multiple datasources then no caching should be enabled for that domain, this means that each time the PasswordCredential is obtained from the security domain it will be a new instance and do do this remove cache-type="default" from security-domain in standalone.xml

References:
https://community.appian.com/support/w/kb/299/kb-1074-cannot-open-connection-caused-by-javax-resource-resourceexception-no-matching-credentials-in-subject-error-thrown-during-jboss-startup

https://bugzilla.redhat.com/show_bug.cgi?id=1103684

Body:
I have a wildfly 8.2.0.Final running. I use two oracle datasources, one <datasource> and one <xa-datasource>. I want to have my DB passwords encrypted and managed to do that for the datasource using a security-domain but not for the xa-datasource.
I haven't found documentation or other postings with a solution for this problem.

Here is what I've done:

        <datasources>
            <datasource jta="false" jndi-name="java:/myproject/jdbc/datasources/jdbc" pool-name="my_JDBC_DS" enabled="true" use-ccm="false">
                <connection-url>jdbc:oracle:thin:@localhost:1521:DB</connection-url>
                <driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
                <driver>oracle</driver>
                <pool>
                    <min-pool-size>1</min-pool-size>
                    <max-pool-size>50</max-pool-size>
                </pool>
                <security>
                    <security-domain>databaseSecure</security-domain>
                </security>
                <validation>
                    <check-valid-connection-sql>select 1 from dual</check-valid-connection-sql>
                    <validate-on-match>true</validate-on-match>
                    <background-validation>false</background-validation>
                </validation>
            </datasource>
            <xa-datasource jndi-name="java:/myproject/jdbc/datasources/db_tx" pool-name="MYTXDS" enabled="true" use-ccm="false">
                <xa-datasource-property name="URL">
                    jdbc:oracle:thin:@localhost:1521:DB
                </xa-datasource-property>
                <xa-datasource-property name="User">
                    scott
                </xa-datasource-property>
                <xa-datasource-property name="Password">
                    tiger
                </xa-datasource-property>
                <driver>oracle</driver>
                <security>
                  <user-name>scott</user-name>
                    <password>tiger</password>
                </security>
                <xa-pool>
                    <min-pool-size>1</min-pool-size>
                    <max-pool-size>50</max-pool-size>
                    <wrap-xa-resource>false</wrap-xa-resource>
                </xa-pool>
                <validation>
                    <check-valid-connection-sql>select 1 from dual</check-valid-connection-sql>
                    <validate-on-match>true</validate-on-match>
                    <background-validation>false</background-validation>
                </validation>
                <statement>
                    <prepared-statement-cache-size>32</prepared-statement-cache-size>
                    <share-prepared-statements>true</share-prepared-statements>
                </statement>
            </xa-datasource>
            <drivers>
                <driver name="oracle" module="oracle">
                    <xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource</xa-datasource-class>
                </driver>
            </drivers>
        </datasources>
...
            <security-domain name="databaseSecure" cache-type="default">
                <authentication>
                    <login-module code="org.picketbox.datasource.security.SecureIdentityLoginModule" flag="required">
                        <module-option name="username" value="scott"/>
                        <module-option name="password" value="-170dd0fbd8c13748"/>
                    </login-module>
                </authentication>
            </security-domain>

I've tried removing the xa-datasource-property entries for user and password and referring to the security-domain both nested in the security-tag and on the same level as the properties. Both attempts did not work, with the latter the wildfly exits early because of problems parsing the standalone.xml, with the latter the deployment fails.

To show the most promising attempt, this is how I tried to refer to the security-domain:

<xa-datasource jndi-name="java:/myproject/jdbc/datasources/db_tx" pool-name="MYTXDS" enabled="true" use-ccm="false">
            <xa-datasource-property name="URL">
                jdbc:oracle:thin:@localhost:1521:DB
            </xa-datasource-property>
            <driver>oracle</driver>
            <security>
              <security-domain>databaseSecure</security-domain>
            </security>
            <xa-pool>
                <min-pool-size>1</min-pool-size>
                <max-pool-size>50</max-pool-size>
                <wrap-xa-resource>false</wrap-xa-resource>
            </xa-pool>
            <validation>
                <check-valid-connection-sql>select 1 from dual</check-valid-connection-sql>
                <validate-on-match>true</validate-on-match>
                <background-validation>false</background-validation>
            </validation>
            <statement>
                <prepared-statement-cache-size>32</prepared-statement-cache-size>
                <share-prepared-statements>true</share-prepared-statements>
            </statement>
        </xa-datasource>

Doing that the wildfly runs into a javax.resource.ResourceException: No matching credentials in Subject!
I've debugged into the code and although I'm missing the code for the last few classes in the call stack I see that the Subject actually has the credentials as properties but still the AccessController.doPrivilegedcall fails, leading to the above mentioned exception.

You see I'm kind of lost, any suggestions?


问:
Java: Detect duplicates in ArrayList?
How could I go about detecting (returning true/false) whether an ArrayList contains more than one of the same element in Java?

Many thanks,
Terry

Edit
Forgot to mention that I am not looking to compare "Blocks" with each other but their integer values. Each "block" has an int and this is what makes them different.
I find the int of a particular Block by calling a method named "getNum" (e.g. table1[0][2].getNum();

答:
```<code>    ArrayList<String> withDuplicates = new ArrayList<>();
    withDuplicates.add("1");
    withDuplicates.add("2");
    withDuplicates.add("1");
    withDuplicates.add("3");
    HashSet<String> set = new HashSet<>(withDuplicates);
    ArrayList<String> withoutDupicates = new ArrayList<>(set);

    ArrayList<String> duplicates = new ArrayList<String>();

    Iterator<String> dupIter = withDuplicates.iterator();
    while(dupIter.hasNext())
    {
    String dupWord = dupIter.next();
    if(withDuplicates.contains(dupWord))
    {
        duplicates.add(dupWord);
    }else{
        withoutDupicates.add(dupWord);
    }
    }
  System.out.println(duplicates);
  System.out.println(withoutDupicates);
</code>```

OwnerDisplayName: Terry

LastEditorDisplayName: Terry

Title: Java: Detect duplicates in ArrayList?


问:
Phoenix 1.3 problems adding custom action "No function clause ... "
Few day ago, I started using Phoenix 1.3, and everything was fine until I started adding a new action in the controller.

Router.ex

```<code> resources "/users", UserController, only: [:show] do
    resources "/events", EventController do

      get "/:id", EventController, :join, as: :join
    end
  end
</code>```

Event_controller.ex

```<code>def join(conn, %{"event_id" => id}, current_user) do
#some stuff..
conn
  |> put_status(:ok)
  |> put_flash(:info, "You just joined Event")
  |> redirect(to: page_path(conn, :index, current_user))
end
</code>```

then in my show template: /event/show.html.eex

```<code><%= link "To list", to: user_event_path(@conn, :index, @event.user) %>
<%= if @current_user.id != @user.id do %>
  <h1> <%= @user.name %> Event ! </h1>
  <h3> <%= @event.title %></h3>
  <p><%= @event.description %></p>
  <p><%= @event.location %></p>
  <p><%= @event.price %></p>
  <%= link "Join", to: user_event_path(@conn, :join, @current_user.id,
  @event.id), class: "btn btn-default btn-xs" %>
</code>```

I tried to do something like that in other projects with Phoenix 1.2 and its work, but it wasn't exactly the same code.

Can someone help me to understand why it is not working...

Btw sorry for my English!

The Error saying :

```<code>No function clause for Eventoma.Web.Router.Helpers.user_event_path/4
and action :join. The following actions/clauses are supported:
user_event_path(conn_or_endpoint, :create, user_id, opts \\ [])
user_event_path(conn_or_endpoint, :delete, user_id, id, opts \\ [])
user_event_path(conn_or_endpoint, :edit, user_id, id, opts \\ [])
user_event_path(conn_or_endpoint, :index, user_id, opts \\ [])
user_event_path(conn_or_endpoint, :new, user_id, opts \\ [])
user_event_path(conn_or_endpoint, :show, user_id, id, opts \\ [])
user_event_path(conn_or_endpoint, :update, user_id, id, opts \\ [])
    (phoenix) lib/phoenix/router/helpers.ex:299: Phoenix.Router.Helpers.raise_route_error/5
</code>```

答:
So playing around I understand, was doing completly wrong stuff!
As Phoenix is one big plug that modify my conn, the answer is something like this:

router.ex:

```<code>post "/events/:id", EventController, :join
</code>```

wich then bring as to event_controller.ex :

```<code>def join(conn,  %{"id" => id}, current_user) do
     conn
     |> put_flash(:info, "You just joined Event")
     |> redirect(to: page_path(conn, :index))
end
</code>```

and will be called from template as /template/show.html.exx:

```<code><%= link "Join", to: user_event_path(@conn, :join,
                   @current_user, @event),
                   method: :join,
                   class: "btn btn-danger btn-xs" %>
</code>```

so i hope if some one get same errors and can't figured out what is going on.

Body:
Few day ago, I started using Phoenix 1.3, and everything was fine until I started adding a new action in the controller.

Router.ex

 resources "/users", UserController, only: [:show] do
    resources "/events", EventController do

      get "/:id", EventController, :join, as: :join
    end
  end

Event_controller.ex

def join(conn, %{"event_id" => id}, current_user) do
#some stuff..
conn
  |> put_status(:ok)
  |> put_flash(:info, "You just joined Event")
  |> redirect(to: page_path(conn, :index, current_user))
end

then in my show template: /event/show.html.eex

<%= link "To list", to: user_event_path(@conn, :index, @event.user) %>
<%= if @current_user.id != @user.id do %>

 <%= @user.name %> Event !

 <%= @event.title %>

<%= @event.description %>

<%= @event.location %>

<%= @event.price %>

  <%= link "Join", to: user_event_path(@conn, :join, @current_user.id,
  @event.id), class: "btn btn-default btn-xs" %>

I tried to do something like that in other projects with Phoenix 1.2 and its work, but it wasn't exactly the same code.

Can someone help me to understand why it is not working...

Btw sorry for my English!

The Error saying :

No function clause for Eventoma.Web.Router.Helpers.user_event_path/4
and action :join. The following actions/clauses are supported:
user_event_path(conn_or_endpoint, :create, user_id, opts \\ [])
user_event_path(conn_or_endpoint, :delete, user_id, id, opts \\ [])
user_event_path(conn_or_endpoint, :edit, user_id, id, opts \\ [])
user_event_path(conn_or_endpoint, :index, user_id, opts \\ [])
user_event_path(conn_or_endpoint, :new, user_id, opts \\ [])
user_event_path(conn_or_endpoint, :show, user_id, id, opts \\ [])
user_event_path(conn_or_endpoint, :update, user_id, id, opts \\ [])
    (phoenix) lib/phoenix/router/helpers.ex:299: Phoenix.Router.Helpers.raise_route_error/5

Body:
So playing around I understand, was doing completly wrong stuff!
As Phoenix is one big plug that modify my conn, the answer is something like this:

router.ex:

post "/events/:id", EventController, :join

wich then bring as to event_controller.ex :

def join(conn,  %{"id" => id}, current_user) do
     conn
     |> put_flash(:info, "You just joined Event")
     |> redirect(to: page_path(conn, :index))
end

and will be called from template as /template/show.html.exx:

<%= link "Join", to: user_event_path(@conn, :join,
                   @current_user, @event),
                   method: :join,
                   class: "btn btn-danger btn-xs" %>

so i hope if some one get same errors and can't figured out what is going on.


问:
This site can't be reached error
I have an asp.net MVC project developed in VS2015. Now I try to run it in VS2017 and get an error:

This site can't be reached.

What can I do with this trouble?

答:
Try this and it should work:

1-Go to your project folder and open .vs folder (keep your check hidden item-box checked as this folder may be hidden sometimes)

2- in .vs folder - open config

3- see that applicationhost config file there? Delete that thing.(Do not worry it will regenerate automatically once you recompile the project.)

link:
localhost refused to connect Error in visual studio

Title: This site can't be reached error