问:
Django : 'unicode' object has no attribute 'get'
I had a problem with my Django program. I'm a beginner in Django, I was looking for an answer with different posts with the same error than mine but no success ...

```<code>Here's my traceback :

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/pod

Django Version: 1.11.2
Python Version: 2.7.13
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'labinit',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\admin\Desktop\django_learneo3\Learneo\labinit\views.py" in groupe_pod
  121.      if form.is_valid():

File "C:\Python27\lib\site-packages\django\forms\forms.py" in is_valid
  183.         return self.is_bound and not self.errors

File "C:\Python27\lib\site-packages\django\forms\forms.py" in errors
  175.             self.full_clean()

File "C:\Python27\lib\site-packages\django\forms\forms.py" in full_clean
  384.         self._clean_fields()

File "C:\Python27\lib\site-packages\django\forms\forms.py" in _clean_fields
  396.                 value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))

File "C:\Python27\lib\site-packages\django\forms\widgets.py" in

 value_from_datadict
  639.         getter = data.get

Exception Type: AttributeError at /pod
Exception Value: 'unicode' object has no attribute 'get'
</code>```

This issue appears since I have changed my init fonction, for the form that I use in my view :

Forms:

```<code>class Groupe_Form(forms.ModelForm) :
    def __init__(self, nom_groupe, *args, **kwargs):
        super(Groupe_Form,self).__init__(*args, **kwargs)
        self.fields['pod'].widget = forms.Select()
        pod1 = Groupe.objects.filter(nom_groupe = nom_groupe).values_list('pod', flat = True)
        pods = list(pod1)
        self.fields['pod'].queryset = Pod.objects.filter(id__in=pods)
    class Meta:
        model = Groupe
        fields = ['pod']
</code>```

Views :

```<code>def groupe_pod(request):

    global new_groupe
    grp = new_groupe
    form = forms.Groupe_Form(request.POST, grp)
    if request.method == 'POST':
        if form.is_valid():
            print "form was valid"
            data_groupe_pod = request.POST.get('grp_pod')
            print "data_groupe :", data_groupe_pod

            global new_cours
            print new_cours

            if new_cours == "ICND1":
                return redirect('http://127.0.0.1:8000/icnd_1')
            elif new_cours == "ICND2":
                return redirect('http://127.0.0.1:8000/icnd_2')
    else :
        form = forms.Groupe_Form(new_groupe)
    return render(request, 'pod.html', locals())
</code>```

I've tried many things, I really don't know where is the problem in my Django code.

答:
Your __init__ signature has as its first parameter nom_groupe. In form = forms.Groupe_Form(request.POST, grp) you pass request.POST as the first parameter. You have to switch the parameters:

```<code>form = forms.Groupe_Form(grp, request.POST)
</code>```

Body:
I had a problem with my Django program. I'm a beginner in Django, I was looking for an answer with different posts with the same error than mine but no success ...

Here's my traceback :

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/pod

Django Version: 1.11.2
Python Version: 2.7.13
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'labinit',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\admin\Desktop\django_learneo3\Learneo\labinit\views.py" in groupe_pod
  121.      if form.is_valid():

File "C:\Python27\lib\site-packages\django\forms\forms.py" in is_valid
  183.         return self.is_bound and not self.errors

File "C:\Python27\lib\site-packages\django\forms\forms.py" in errors
  175.             self.full_clean()

File "C:\Python27\lib\site-packages\django\forms\forms.py" in full_clean
  384.         self._clean_fields()

File "C:\Python27\lib\site-packages\django\forms\forms.py" in _clean_fields
  396.                 value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))

File "C:\Python27\lib\site-packages\django\forms\widgets.py" in

 value_from_datadict
  639.         getter = data.get

Exception Type: AttributeError at /pod
Exception Value: 'unicode' object has no attribute 'get'

This issue appears since I have changed my init fonction, for the form that I use in my view :

Forms:

class Groupe_Form(forms.ModelForm) :
    def __init__(self, nom_groupe, *args, **kwargs):
        super(Groupe_Form,self).__init__(*args, **kwargs)
        self.fields['pod'].widget = forms.Select()
        pod1 = Groupe.objects.filter(nom_groupe = nom_groupe).values_list('pod', flat = True)
        pods = list(pod1)
        self.fields['pod'].queryset = Pod.objects.filter(id__in=pods)
    class Meta:
        model = Groupe
        fields = ['pod']

Views :

def groupe_pod(request):

    global new_groupe
    grp = new_groupe
    form = forms.Groupe_Form(request.POST, grp)
    if request.method == 'POST':
        if form.is_valid():
            print "form was valid"
            data_groupe_pod = request.POST.get('grp_pod')
            print "data_groupe :", data_groupe_pod

            global new_cours
            print new_cours

            if new_cours == "ICND1":
                return redirect('http://127.0.0.1:8000/icnd_1')
            elif new_cours == "ICND2":
                return redirect('http://127.0.0.1:8000/icnd_2')
    else :
        form = forms.Groupe_Form(new_groupe)
    return render(request, 'pod.html', locals())

I've tried many things, I really don't know where is the problem in my Django code.

Body:
Your __init__ signature has as its first parameter nom_groupe. In form = forms.Groupe_Form(request.POST, grp) you pass request.POST as the first parameter. You have to switch the parameters:

form = forms.Groupe_Form(grp, request.POST)


来源: stackexchange

问:
android studio webview Fragment "Uncaught TypeError: $(...).dialog is not a function"
need help,
my code working fine on

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

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

    final WebView myWebView1 = (WebView) findViewById(R.id.webView1);
    WebSettings webSettings1 = myWebView1.getSettings();
    webSettings1.setJavaScriptEnabled(true);
    myWebView1.setWebViewClient(new WebViewClient());
    myWebView1.setWebChromeClient(new WebChromeClient());
    myWebView1.loadUrl("https://example.com");
}}
</code>```

But generate error when i use in Fragment

```<code>public class ReportSales01Activity extends Fragment{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_report_sales_01, container, false);

        final WebView myWebView1 = (WebView) view.findViewById(R.id.webView1);
        WebSettings webSettings1 = myWebView1.getSettings();
        webSettings1.setJavaScriptEnabled(true);
        myWebView1.setWebViewClient(new WebViewClient());
        myWebView1.setWebChromeClient(new WebChromeClient());
        myWebView1.loadUrl("https://example.com");
        return view;}}
</code>```

the error message

I/chromium: [INFO:CONSOLE(313)] "Uncaught TypeError: $(...).dialog is not a function", source: http://example.com (313)

Can some help me solving this issue.

答:
Uncaught TypeError: $(...).dialog is not a function

Enable .setDomStorageEnabled(true); .setDatabaseEnabled(true)

```<code>public class ReportSales01Activity extends Fragment
{

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
         {
            View view = inflater.inflate(R.layout.fragment_report_sales_01, container, false);

                final WebView myWebView1 = (WebView) view.findViewById(R.id.webView1);
                WebSettings webSettings1 = myWebView1.getSettings();
                webSettings1.setJavaScriptEnabled(true);
                webSettings1.setDomStorageEnabled(true);// Add this
                webSettings1.setDatabaseEnabled(true);// Add this
                myWebView1.setWebViewClient(new WebViewClient());
                myWebView1.setWebChromeClient(new WebChromeClient());
                myWebView1.loadUrl("https://example.com");
                return view;
         }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
need help,
my code working fine on

public class MainActivity extends AppCompatActivity {

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

    final WebView myWebView1 = (WebView) findViewById(R.id.webView1);
    WebSettings webSettings1 = myWebView1.getSettings();
    webSettings1.setJavaScriptEnabled(true);
    myWebView1.setWebViewClient(new WebViewClient());
    myWebView1.setWebChromeClient(new WebChromeClient());
    myWebView1.loadUrl("https://example.com");
}}

But generate error when i use in Fragment

public class ReportSales01Activity extends Fragment{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_report_sales_01, container, false);

        final WebView myWebView1 = (WebView) view.findViewById(R.id.webView1);
        WebSettings webSettings1 = myWebView1.getSettings();
        webSettings1.setJavaScriptEnabled(true);
        myWebView1.setWebViewClient(new WebViewClient());
        myWebView1.setWebChromeClient(new WebChromeClient());
        myWebView1.loadUrl("https://example.com");
        return view;}}

the error message

I/chromium: [INFO:CONSOLE(313)] "Uncaught TypeError: $(...).dialog is not a function", source: http://example.com (313)

Can some help me solving this issue.

Body:
Uncaught TypeError: $(...).dialog is not a function

Enable .setDomStorageEnabled(true); .setDatabaseEnabled(true)

public class ReportSales01Activity extends Fragment
{

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
         {
            View view = inflater.inflate(R.layout.fragment_report_sales_01, container, false);

                final WebView myWebView1 = (WebView) view.findViewById(R.id.webView1);
                WebSettings webSettings1 = myWebView1.getSettings();
                webSettings1.setJavaScriptEnabled(true);
                webSettings1.setDomStorageEnabled(true);// Add this
                webSettings1.setDatabaseEnabled(true);// Add this
                myWebView1.setWebViewClient(new WebViewClient());
                myWebView1.setWebChromeClient(new WebChromeClient());
                myWebView1.loadUrl("https://example.com");
                return view;
         }
    }


问:
How do you store a list of directories into an array in Bash (and then print them out)?
I want to write a shell script to show a list of directories entered by a user and then for a user to select one of the directories with an index number based on how many directories there are

I'm thinking this is some kind of array operation, but im not sure how to do this in shell script

example:

```<code>> whichdir
There are 3 dirs in the current path
1 dir1
2 dir2
3 dir3
which dir do you want?
> 3
you selected dir3!
</code>```

答:
Update: my answer is wrong

Leaving it here to address a common misunderstanding, below the line is erroneous.

To put the directories in an array you can do...

```<code>array=( $( ls -1p | grep / | sed 's/^\(.*\)/"\1"/') )
</code>```

This will capture the dir names, including those with spaces.

Extracting from comments:

literal quotes don't have any effect on string-splitting, so array=( echo '"hello world" "goodbye world"' ) is an array with four elements, not two

@Charles Duffy

Charles also supplied the following link Bash FAQ #50 which is an extended discussion on this issue.

I should also draw attention to the link posted by @Dennis Williamson - why I shouldn't have used ls

ContentLicense: CC BY-SA 2.5

Body:
I want to write a shell script to show a list of directories entered by a user and then for a user to select one of the directories with an index number based on how many directories there are

I'm thinking this is some kind of array operation, but im not sure how to do this in shell script

example:

> whichdir
There are 3 dirs in the current path
1 dir1
2 dir2
3 dir3
which dir do you want?
> 3
you selected dir3!

Body:
Update: my answer is wrong

Leaving it here to address a common misunderstanding, below the line is erroneous.

To put the directories in an array you can do...

array=( $( ls -1p | grep / | sed 's/^\(.*\)/"\1"/') )

This will capture the dir names, including those with spaces.

Extracting from comments:

literal quotes don't have any effect on string-splitting, so array=( echo '"hello world" "goodbye world"' ) is an array with four elements, not two

@Charles Duffy

Charles also supplied the following link Bash FAQ #50 which is an extended discussion on this issue.

I should also draw attention to the link posted by @Dennis Williamson - why I shouldn't have used ls

ContentLicense: CC BY-SA 4.0


问:
Sorting Characters Of A C++ String
If i have a string is there a built in function to sort the characters or would I have to write my own?

for example:

```<code>string word = "dabc";
</code>```

I would want to change it so that:

```<code>string sortedWord = "abcd";
</code>```

Maybe using char is a better option? How would I do this in C++?

答:
You can use sort() function. sort() exists in algorithm header file

```<code>        #include<bits/stdc++.h>
        using namespace std;

        int main()
        {
            ios::sync_with_stdio(false);
            string str = "sharlock";

            sort(str.begin(), str.end());
            cout<<str<<endl;

            return 0;
        }
</code>```

Output:

achklors

Title: Sorting Characters Of A C++ String

Body:
If i have a string is there a built in function to sort the characters or would I have to write my own?

for example:

string word = "dabc";

I would want to change it so that:

string sortedWord = "abcd";

Maybe using char is a better option? How would I do this in C++?

Body:
You can use sort() function. sort() exists in algorithm header file

        #include<bits/stdc++.h>
        using namespace std;

        int main()
        {
            ios::sync_with_stdio(false);
            string str = "sharlock";

            sort(str.begin(), str.end());
            cout<<str<<endl;

            return 0;
        }

Output:

achklors


问:
Button color change when untouched

<!DOCTYPE html>

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

Dummy form

<form name="myForm">
<input name="myInput" ng-model="myInput" required />

<input  type="button" ng-click="deleteRow($event,name)" value="Remove" class="btn" >

<input type="button"  ng-click="deleteRow($event,name)" value="Remove" class="btn btn-primary" >
</form>

```

When the inputs are touched I'm trying the change the remove button color.I tried with if else,it was not working.So, used ng-show where I'm getting two buttons and the one button with changed color is working only when I click outside the form.Can anyone help?

答:
Do it with ng-click

```<code><input name="myInput" ng-model="myInput" ng-click="ChangeColor()"required />

<input  type="button" ng-click="deleteRow($event,name)" value="Remove" ng-class="{'btn-warning': started, 'btn-danger': !started}" >
</code>```

Inside your controller

```<code>$scope.started = false;
$scope.ChangeColor=function(){
$scope.started = true;
}
</code>```

Title: Button color change when untouched

Body:
<!DOCTYPE html>

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

Dummy form

<form name="myForm">
<input name="myInput" ng-model="myInput" required />

<input  type="button" ng-click="deleteRow($event,name)" value="Remove" class="btn" >

<input type="button"  ng-click="deleteRow($event,name)" value="Remove" class="btn btn-primary" >
</form>

When the inputs are touched I'm trying the change the remove button color.I tried with if else,it was not working.So, used ng-show where I'm getting two buttons and the one button with changed color is working only when I click outside the form.Can anyone help?

Body:
Do it with ng-click

<input name="myInput" ng-model="myInput" ng-click="ChangeColor()"required />

<input  type="button" ng-click="deleteRow($event,name)" value="Remove" ng-class="{'btn-warning': started, 'btn-danger': !started}" >

Inside your controller

$scope.started = false;
$scope.ChangeColor=function(){
$scope.started = true;
}


问:
Why call stack info is absent for my EventLogTraceListener instance?
C# 6.0, .NET Framework 4.6.1, Debug mode.

I set the TraceOptions.Callstack value for my EventLogTraceListener instance, but I don't see the call stack in the Windows Event Viewer.

This is my simple code:

```<code>public static string GetMsgHeaders() {

    string currentMethodName = MethodBase
        .GetCurrentMethod().Name;

    Console.Out.WriteLine("The {0} method was called!",
        currentMethodName);

    if (!EventLog.SourceExists("sharp_sandbox")) {
        EventLog.CreateEventSource("sharp_sandbox",
            "Application");
    }

    EventLogTraceListener listener = new
        EventLogTraceListener("sharp_sandbox");

    listener.TraceOutputOptions = TraceOptions.DateTime
        | TraceOptions.Callstack;

    Trace.Listeners.Add(listener);
    Trace.Write("Trace.Write");
    Trace.WriteLine("Trace.WriteLine");
    Trace.TraceWarning("Trace.TraceWarning");
    Trace.TraceError("Trace.TraceError");
    Trace.TraceInformation("Trace.TraceInformation");

    listener.Close();

    return "ABCDEF";
}
</code>```

But I get info without call stack, for example:

```<code><Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
    <System>
        <Provider Name="sharp_sandbox" />
        <EventID Qualifiers="0">0</EventID>
        <Level>4</Level>
        <Task>0</Task>
        <Keywords>0x80000000000000</Keywords>
        <TimeCreated SystemTime="2016-08-17T09:48:40.367843800Z" />
        <EventRecordID>13778</EventRecordID>
        <Channel>Application</Channel>
        <Computer>Win10x64-VS.spb.gpsm.ru</Computer>
        <Security />
    </System>
    <EventData>
        <Data>Trace.TraceInformation</Data>
    </EventData>
</Event>
</code>```

Why call stack info is absent?

答:
Unfortunately the Trace Options are not used by the EventLogTraceListener. It Claims that it would spit out too much data!

https://msdn.microsoft.com/en-us/library/a10k7w6c(v=vs.110).aspx

Stated in the Remarks section.

Body:
C# 6.0, .NET Framework 4.6.1, Debug mode.

I set the TraceOptions.Callstack value for my EventLogTraceListener instance, but I don't see the call stack in the Windows Event Viewer.

This is my simple code:

public static string GetMsgHeaders() {

    string currentMethodName = MethodBase
        .GetCurrentMethod().Name;

    Console.Out.WriteLine("The {0} method was called!",
        currentMethodName);

    if (!EventLog.SourceExists("sharp_sandbox")) {
        EventLog.CreateEventSource("sharp_sandbox",
            "Application");
    }

    EventLogTraceListener listener = new
        EventLogTraceListener("sharp_sandbox");

    listener.TraceOutputOptions = TraceOptions.DateTime
        | TraceOptions.Callstack;

    Trace.Listeners.Add(listener);
    Trace.Write("Trace.Write");
    Trace.WriteLine("Trace.WriteLine");
    Trace.TraceWarning("Trace.TraceWarning");
    Trace.TraceError("Trace.TraceError");
    Trace.TraceInformation("Trace.TraceInformation");

    listener.Close();

    return "ABCDEF";
}

But I get info without call stack, for example:

<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
    <System>
        <Provider Name="sharp_sandbox" />
        <EventID Qualifiers="0">0</EventID>
        <Level>4</Level>
        <Task>0</Task>
        <Keywords>0x80000000000000</Keywords>
        <TimeCreated SystemTime="2016-08-17T09:48:40.367843800Z" />
        <EventRecordID>13778</EventRecordID>
        <Channel>Application</Channel>
        <Computer>Win10x64-VS.spb.gpsm.ru</Computer>
        <Security />
    </System>
    <EventData>
        <Data>Trace.TraceInformation</Data>
    </EventData>
</Event>

Why call stack info is absent?


问:
How come this relative positioned div is displayed differently in IE?
I have a relative positioned div inside another div. The inside-div is positioned with percentage (left: 0%; top:13%).

My problem is that in all IE versions the div is displayed some pixels further down than where it is displayed in Chrome, or FF...

Anybody recognize this?

```<code>   <div class="nav_container" id="nav_container">
   <div id="nav_container2" style="position: relative; left: 0%; top: 13%;"></div>
   </div>
</code>```

Also, I am just about to browser adjust my website so some article about most common problems with IE is appreciated.

Thanks

UPDATE:

Here is the style for the primary div.

```<code>.nav_container {
    background-image: url(../Graphics/menu_lvl1.gif);
    height: 101px;
    width: 720px;
}
</code>```

答:
@Camran

Here you go bro I hope this helps you out. http://www.positioniseverything.net/articles/cc-plus.html Everything is fully detailed and easy to follow along. Trust me I was having that same issue and what kills me is everyone I talked to who claimed they were professionals kept stating that it's an impossibility to have perfect positioning, yet here's somebody who came up with a solution.

Body:
I have a relative positioned div inside another div. The inside-div is positioned with percentage (left: 0%; top:13%).

My problem is that in all IE versions the div is displayed some pixels further down than where it is displayed in Chrome, or FF...

Anybody recognize this?

Also, I am just about to browser adjust my website so some article about most common problems with IE is appreciated.

Thanks

UPDATE:

Here is the style for the primary div.

.nav_container {
    background-image: url(../Graphics/menu_lvl1.gif);
    height: 101px;
    width: 720px;
}


问:
stellar.js not working with dynamically loaded elements via AJAX
I'm using the fantastic Stellar.js (http://markdalgleish.com/projects/stellar.js/) for parallax on a recent project, but I've run into a challenge:

Stellar isn't noticing when I change content via AJAX (in this case loading in new div's from an html file and using jQuery's replaceWith method).  So, my new elements have no parallax, even though they have stellar data attributes.

I've tried calling the .stellar function on my window again after the AJAX is complete, but it doesn't do anything.

How can I get Stellar to correctly apply parallax to the new AJAX'd in elements?

答:
I know that the topic is old but I want to share the solution that I found, hoping that it will be useful for people who are still searching.
First create the function:

```<code>function init () {
$(window).data('plugin_stellar').refresh();
}

jQuery(document).ready(function () {
// Initialise the plugin when the DOM is ready to be acted upon
init();
});
</code>```

Second insert this line in your Ajax call:

```<code>// Reinitialise plugins:
    init();
</code>```

Body:
I know that the topic is old but I want to share the solution that I found, hoping that it will be useful for people who are still searching.
First create the function:

function init () {
$(window).data('plugin_stellar').refresh();
}

jQuery(document).ready(function () {
// Initialise the plugin when the DOM is ready to be acted upon
init();
});

Second insert this line in your Ajax call:

// Reinitialise plugins:
    init();


问:
Adding Items to DataGridView from a ListBox to a Single Column
I need to populate a DataGridView with items from a List.

I need the first row of the GridView populated with the items from the String List and i need to do some processing on the items in the GridView one by one and add the result to the second row(String).

Currently im Binding the DataGridView like this

```<code> dataGridView1.DataSource = mylist.ConvertAll(x => new { Value = x });
 dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
</code>```

I need to predefine the column name add strings in the first row,process these strings one by one and update the second column..what is the best way to do this?

答:
here is your solution,

```<code>        dgvDataViewer.ColumnCount = 1;
        dgvDataViewer.Columns[0].Name = "Language";

        string[] row = new string[] { "C#" };
        dgvDataViewer.Rows.Add(row);
        row = new string[] { "C++" };
        dgvDataViewer.Rows.Add(row);
        row = new string[] { "C" };
        dgvDataViewer.Rows.Add(row);

        DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
        cmb.HeaderText = "HeaderText";
        cmb.Name = "Name";
        cmb.FlatStyle = FlatStyle.System;
        dgvDataViewer.Columns.Add(cmb);

        DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell)dgvDataViewer.Rows[0].Cells[1];
        dgvcbc.Items.Add("Apple");
        dgvcbc.Items.Add("Google");
        dgvcbc.Items.Add("Apache");
        dgvcbc.Items.Add("Microsoft");
</code>```

Hope this will help you for your solution.

Body:
I need to populate a DataGridView with items from a List.

I need the first row of the GridView populated with the items from the String List and i need to do some processing on the items in the GridView one by one and add the result to the second row(String).

Currently im Binding the DataGridView like this

 dataGridView1.DataSource = mylist.ConvertAll(x => new { Value = x });
 dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

I need to predefine the column name add strings in the first row,process these strings one by one and update the second column..what is the best way to do this?

Body:
here is your solution,

        dgvDataViewer.ColumnCount = 1;
        dgvDataViewer.Columns[0].Name = "Language";

        string[] row = new string[] { "C#" };
        dgvDataViewer.Rows.Add(row);
        row = new string[] { "C++" };
        dgvDataViewer.Rows.Add(row);
        row = new string[] { "C" };
        dgvDataViewer.Rows.Add(row);

        DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
        cmb.HeaderText = "HeaderText";
        cmb.Name = "Name";
        cmb.FlatStyle = FlatStyle.System;
        dgvDataViewer.Columns.Add(cmb);

        DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell)dgvDataViewer.Rows[0].Cells[1];
        dgvcbc.Items.Add("Apple");
        dgvcbc.Items.Add("Google");
        dgvcbc.Items.Add("Apache");
        dgvcbc.Items.Add("Microsoft");

Hope this will help you for your solution.


问:
Looking for some Java good practice advice regarding distributed applications and message passing
Some background information. This is a distributed application with multiples nodes. A 'communication' thread sends and receives all messages sent between these nodes. This cannot be changed.

A 'doStuff' thread asks the 'communication' thread to send a message to a node. It then needs to wait for a response from the other node. The 'communication' thread will receive this response message. It then needs to deliver this message to the correct 'doStuff' thread.

I am unsure what sort of information needs to be stored at the node or within the message to ensure that the correct thread always receives the response message.

Looking for some advice upon how to achieve this. Thanks for reading :)

答:
It doesn't seem very difficult

Use either a thread id, or other opaque token invented by the doStuff thread which is stored by the Communication thread (mapped to the calling thread id) and returned with the response The communication thread looks it up in the Map to identify the corresponding thread.

Or am I missing something?


问:
What is dependency injection?
There have been several questions already posted with specific questions about dependency injection, such as when to use it and what frameworks are there for it. However,

What is dependency injection and when/why should or shouldn't it be used?

答:
Let's try simple example with Car and Engine classes, any car need an engine to go anywhere, at least for now. So below how code will look without dependency injection.

public class Car
{
    public Car()
    {
        GasEngine engine = new GasEngine();
        engine.Start();
    }
}

public class GasEngine
{
    public void Start()
    {
        Console.WriteLine("I use gas as my fuel!");
    }
}
```

<p>And to instantiate the Car class we will use next code:</p>

<pre class="lang-csh prettyprint-override"><code>Car car = new Car();
</code>```

The issue with this code that we tightly coupled to GasEngine and if we decide to change it to ElectricityEngine then we will need to rewrite Car class. And the bigger the application the more issues and headache we will have to add and use new type of engine.

In other words with this approach is that our high level Car class is dependent on the lower level GasEngine class which violate Dependency Inversion Principle(DIP) from SOLID. DIP suggests that we should depend on abstractions, not concrete classes. So to satisfy this we introduce IEngine interface and rewrite code like below:

    public interface IEngine
    {
        void Start();
    }

    public class GasEngine : IEngine
    {
        public void Start()
        {
            Console.WriteLine("I use gas as my fuel!");
        }
    }

    public class ElectricityEngine : IEngine
    {
        public void Start()
        {
            Console.WriteLine("I am electrocar");
        }
    }

    public class Car
    {
        private readonly IEngine _engine;
        public Car(IEngine engine)
        {
            _engine = engine;
        }

        public void Run()
        {
            _engine.Start();
        }
    }
```

<p>Now our Car class is dependent on only the IEngine interface, not a specific implementation of engine.
Now, the only trick is how do we create an instance of the Car and give it an actual concrete Engine class like GasEngine or ElectricityEngine. That's where <strong>Dependency Injection</strong> comes in. </p>

<pre class="lang-csh prettyprint-override"><code>   Car gasCar = new Car(new GasEngine());
   gasCar.Run();
   Car electroCar = new Car(new ElectricityEngine());
   electroCar.Run();
</code>```

Here we basically inject(pass) our dependency(Engine instance) to Car constructor. So now our classes have loose coupling between objects and their dependencies, and we can easily add new types of engines without changing the Car class.

The main benefit of the Dependency Injection that classes are more loosely coupled, because they do not have hard-coded dependencies. This follows the Dependency Inversion Principle, which was mentioned above. Instead of referencing specific implementations, classes request abstractions (usually interfaces) which are provided to them when the class is constructed.

So in the end Dependency injection is just a technique for
  achieving loose coupling between objects and their dependencies.
  Rather than directly instantiating dependencies that class needs in
  order to perform its actions, dependencies are provided to the class
  (most often) via constructor injection.

Also when we have many dependencies it is very good practice to use Inversion of Control(IoC) containers which we can tell which interfaces should be mapped to which concrete implementations for all our dependencies and we can have it resolve those dependencies for us when it constructs our object. For example, we could specify in the mapping for the IoC container that the IEngine dependency should be mapped to the GasEngine class and when we ask the IoC container for an instance of our Car class, it will automatically construct our Car class with a GasEngine dependency passed in.

UPDATE: Watched course about EF Core from Julie Lerman recently and also liked her short definition about DI.

Dependency injection is a pattern to allow your application to inject
  objects on the fly to classes that need them, without forcing those
  classes to be responsible for those objects. It allows your code to be
  more loosely coupled, and Entity Framework Core plugs in to this same
  system of services.

OwnerDisplayName: AR

Title: What is dependency injection?

LastEditorDisplayName: AR

Body:
Let's try simple example with Car and Engine classes, any car need an engine to go anywhere, at least for now. So below how code will look without dependency injection.

public class Car
{
    public Car()
    {
        GasEngine engine = new GasEngine();
        engine.Start();
    }
}

public class GasEngine
{
    public void Start()
    {
        Console.WriteLine("I use gas as my fuel!");
    }
}

And to instantiate the Car class we will use next code:

Car car = new Car();

The issue with this code that we tightly coupled to GasEngine and if we decide to change it to ElectricityEngine then we will need to rewrite Car class. And the bigger the application the more issues and headache we will have to add and use new type of engine.

In other words with this approach is that our high level Car class is dependent on the lower level GasEngine class which violate Dependency Inversion Principle(DIP) from SOLID. DIP suggests that we should depend on abstractions, not concrete classes. So to satisfy this we introduce IEngine interface and rewrite code like below:

    public interface IEngine
    {
        void Start();
    }

    public class GasEngine : IEngine
    {
        public void Start()
        {
            Console.WriteLine("I use gas as my fuel!");
        }
    }

    public class ElectricityEngine : IEngine
    {
        public void Start()
        {
            Console.WriteLine("I am electrocar");
        }
    }

    public class Car
    {
        private readonly IEngine _engine;
        public Car(IEngine engine)
        {
            _engine = engine;
        }

        public void Run()
        {
            _engine.Start();
        }
    }

Now our Car class is dependent on only the IEngine interface, not a specific implementation of engine.
Now, the only trick is how do we create an instance of the Car and give it an actual concrete Engine class like GasEngine or ElectricityEngine. That's where Dependency Injection comes in.

   Car gasCar = new Car(new GasEngine());
   gasCar.Run();
   Car electroCar = new Car(new ElectricityEngine());
   electroCar.Run();

Here we basically inject(pass) our dependency(Engine instance) to Car constructor. So now our classes have loose coupling between objects and their dependencies, and we can easily add new types of engines without changing the Car class.

The main benefit of the Dependency Injection that classes are more loosely coupled, because they do not have hard-coded dependencies. This follows the Dependency Inversion Principle, which was mentioned above. Instead of referencing specific implementations, classes request abstractions (usually interfaces) which are provided to them when the class is constructed.

So in the end Dependency injection is just a technique for
  achieving loose coupling between objects and their dependencies.
  Rather than directly instantiating dependencies that class needs in
  order to perform its actions, dependencies are provided to the class
  (most often) via constructor injection.

Also when we have many dependencies it is very good practice to use Inversion of Control(IoC) containers which we can tell which interfaces should be mapped to which concrete implementations for all our dependencies and we can have it resolve those dependencies for us when it constructs our object. For example, we could specify in the mapping for the IoC container that the IEngine dependency should be mapped to the GasEngine class and when we ask the IoC container for an instance of our Car class, it will automatically construct our Car class with a GasEngine dependency passed in.

UPDATE: Watched course about EF Core from Julie Lerman recently and also liked her short definition about DI.

Dependency injection is a pattern to allow your application to inject
  objects on the fly to classes that need them, without forcing those
  classes to be responsible for those objects. It allows your code to be
  more loosely coupled, and Entity Framework Core plugs in to this same
  system of services.


问:
Setting password field to 'required' in Sails Mongo blocks beforeCreate
My API uses SailsJs and MongoDb. For user creation, I am using the beforeCreate lifecycle callback to run bcrypt to hash my password field.

I encounter this wierd error, wherein if I set my encrPassword field to

```<code>{required : true}
</code>```

my code stops working and emits the following error :

```<code> {
  "error": "E_VALIDATION",
  "status": 400,
  "summary": "1 attribute is invalid",
  "model": "User",
  "invalidAttributes": {
    "encrPassword": [
      {
        "rule": "string",
        "message": "Value should be a string (instead of null, which is an object)"
      },
      {
        "rule": "required",
        "message": "\"required\" validation rule failed for input: null\nSpecifically, it threw an error.  Details:\n undefined"
      }
    ]
  }
</code>```

here is my code sample :

```<code>attributes: {
    fullname : {type : 'string'},
    username : {type : 'string', unique:true, required:true},
    encrPassword : {type : 'string'}, // ==> this works
    // encrPassword : {type : 'string', required:true}, ==> this doesn't
},

insert : function(req, cb){
    console.log('Insert ', req);
    if(typeof req.fullName == 'string' && typeof req.username == 'string'){
        User.findOne({username : req.username}).exec(function(err, res){
            if(!res){
                User.create(req).exec(function(err, resp){
                    console.log('create', null, resp);
                    if(err)
                      cb(err);
                    else cb(null, resp);
                });
            }
            else cb({message: 'already eists'})
        });
    }
    else cb({message: 'Bad Request'});
},

beforeCreate : function(req, next){
    console.log('In bcrypt');
    bcrypt.genSalt(10, function(err, salt){
        if(err) return next(err);
        bcrypt.hash(req.password, salt, function(err, hash){
            if(err) return next(err);
            req.encrPassword = hash;
            delete req.password;
            console.log('Leaving BCrypt');
            next();
        });
    });
}
</code>```

ps. I rigorously checked for typos; any typos or syntax errors in the above sample are the result of editing to hide any code i wouldnt want to share

答:
Validation is done before calling beforeCreate.

There is no encrPassword at that moment, hence the error.

Body:
My API uses SailsJs and MongoDb. For user creation, I am using the beforeCreate lifecycle callback to run bcrypt to hash my password field.

I encounter this wierd error, wherein if I set my encrPassword field to

{required : true}

my code stops working and emits the following error :

 {
  "error": "E_VALIDATION",
  "status": 400,
  "summary": "1 attribute is invalid",
  "model": "User",
  "invalidAttributes": {
    "encrPassword": [
      {
        "rule": "string",
        "message": "Value should be a string (instead of null, which is an object)"
      },
      {
        "rule": "required",
        "message": "\"required\" validation rule failed for input: null\nSpecifically, it threw an error.  Details:\n undefined"
      }
    ]
  }

here is my code sample :

attributes: {
    fullname : {type : 'string'},
    username : {type : 'string', unique:true, required:true},
    encrPassword : {type : 'string'}, // ==> this works
    // encrPassword : {type : 'string', required:true}, ==> this doesn't
},

insert : function(req, cb){
    console.log('Insert ', req);
    if(typeof req.fullName == 'string' && typeof req.username == 'string'){
        User.findOne({username : req.username}).exec(function(err, res){
            if(!res){
                User.create(req).exec(function(err, resp){
                    console.log('create', null, resp);
                    if(err)
                      cb(err);
                    else cb(null, resp);
                });
            }
            else cb({message: 'already eists'})
        });
    }
    else cb({message: 'Bad Request'});
},

beforeCreate : function(req, next){
    console.log('In bcrypt');
    bcrypt.genSalt(10, function(err, salt){
        if(err) return next(err);
        bcrypt.hash(req.password, salt, function(err, hash){
            if(err) return next(err);
            req.encrPassword = hash;
            delete req.password;
            console.log('Leaving BCrypt');
            next();
        });
    });
}

ps. I rigorously checked for typos; any typos or syntax errors in the above sample are the result of editing to hide any code i wouldnt want to share


问:
SQL join with selecting previous matching value with group by
I have 2 tables that I want to join on a key that matches with the first previous record.

I have a query that does this. However I also want to include a column in the results from each of the table. This forces me to include those 2 columns in the Group By attribute which is returning duplicate results.

The query I am using is similar to this (courtesy: stackoverflow):

```<code>SELECT t1.frame as frame1,
    t1.string as string1,
    max(t2.frame) as frame2,
    t2.string as string2
    FROM t1
    JOIN t2
    ON t2.frame < t1.frame and
    t1.key=t2.key
    GROUP BY t1.frame, t2.frame, t1.string, t2.string
    ORDER BY t2.frame
</code>```

The (problem) output I see is:

```<code>frame1, string1, frame2, string2
51      text1     6       text2
107253  text3     6       text2
</code>```

How can I include string2 in my results such that I don't want to group by it but only include its value for corresponding frame2?

I tried setting this up on sqlfiddle.com to make it easy to try. I populated with some dummy data but here along with this problem, I also see another problem which is it is also returning results where frame2=2. This is not expected, since it should always match frame=6. I suppose this may be side effect of grouping by string2?

Link to sqlfiddle example

Here I expect the output should only be 1 record which is:

```<code>frame1,string1,frame2,string2
51      text1    6     text2
</code>```

I am doing this on Spark SQL but this should be a generic SQL question.
Thanks.

Edit:
My data consists of incoming packets and I want to match a packet to the most recent one that came before it which has the matching ID. For e.g.

```<code>Table t2:
    frame#1:Key=a,Text=abc
    frame#2:Key=a,Text=def
    frame#3:Key=b,Text=efg
    frame#5:Key=c,Text=xyz

Table t1:
    frame#4:Key=a,Text=pqr
    frame#6:Key=c,Text=mno
</code>```

So here, for frame#4 from t1, I want to match it with frame from t2 that has come before it and has the same key. So it should match with frame#2 (not frame#3 coz key is different and not frame#1 coz frame#2 is more recent). Similarly, frame#6 should match with frame#5.

Hope it is clear now.

答:
http://sqlfiddle.com/#!17/47c11/2</p>

```<code>select distinct on (t.frame1, t.key1, t.string1)
    t.*
from
    (select
        t1.frame frame1, t1.key key1, t1.string string1, t2.frame frame2, t2.key key2, t2.string string2
    from
         t1
    join
         t2
    on
         t1.key=t2.key
         and t1.frame > t2.frame
    order by
         t2.frame desc) t
</code>```

Body:
I have 2 tables that I want to join on a key that matches with the first previous record.

I have a query that does this. However I also want to include a column in the results from each of the table. This forces me to include those 2 columns in the Group By attribute which is returning duplicate results.

The query I am using is similar to this (courtesy: stackoverflow):

SELECT t1.frame as frame1,
    t1.string as string1,
    max(t2.frame) as frame2,
    t2.string as string2
    FROM t1
    JOIN t2
    ON t2.frame < t1.frame and
    t1.key=t2.key
    GROUP BY t1.frame, t2.frame, t1.string, t2.string
    ORDER BY t2.frame

The (problem) output I see is:

frame1, string1, frame2, string2
51      text1     6       text2
107253  text3     6       text2

How can I include string2 in my results such that I don't want to group by it but only include its value for corresponding frame2?

I tried setting this up on sqlfiddle.com to make it easy to try. I populated with some dummy data but here along with this problem, I also see another problem which is it is also returning results where frame2=2. This is not expected, since it should always match frame=6. I suppose this may be side effect of grouping by string2?

Link to sqlfiddle example

Here I expect the output should only be 1 record which is:

frame1,string1,frame2,string2
51      text1    6     text2

I am doing this on Spark SQL but this should be a generic SQL question.
Thanks.

Edit:
My data consists of incoming packets and I want to match a packet to the most recent one that came before it which has the matching ID. For e.g.

Table t2:
    frame#1:Key=a,Text=abc
    frame#2:Key=a,Text=def
    frame#3:Key=b,Text=efg
    frame#5:Key=c,Text=xyz

Table t1:
    frame#4:Key=a,Text=pqr
    frame#6:Key=c,Text=mno

So here, for frame#4 from t1, I want to match it with frame from t2 that has come before it and has the same key. So it should match with frame#2 (not frame#3 coz key is different and not frame#1 coz frame#2 is more recent). Similarly, frame#6 should match with frame#5.

Hope it is clear now.

Body:
http://sqlfiddle.com/#!17/47c11/2

select distinct on (t.frame1, t.key1, t.string1)
    t.*
from
    (select
        t1.frame frame1, t1.key key1, t1.string string1, t2.frame frame2, t2.key key2, t2.string string2
    from
         t1
    join
         t2
    on
         t1.key=t2.key
         and t1.frame > t2.frame
    order by
         t2.frame desc) t


问:
MVC: Date in Chrome-browser
The problem:
I want to show a date in german-format with globalize. With the solution mentioned in MVc 5 - validation german date with unobtrusiv js - a simple approach it works in IE and Firefox - no Problem.

But Google-Chrome uses the input-type "date" and shows an datepicker. The Validation ever failed.

答:
After reading a lot of answers here at stackoverflow I came to this solution:

In the model I introduce a new, not mapped property:

```<code>...
    [NotMapped]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime GeburtsdatumChromeEdit
    {
        get { return this.Geburtsdatum; }
        set { this.Geburtsdatum = value; }
    }
...
</code>```

This is necessary to add the dataannotiation DisplayFormat with the format Chrome wants. It pipes the value to the original property.

In the view I doubled the Input for the date and encapsulated the two groups by div's with special classes:

```<code><div class="date4Normal">
        @*Tut nicht in Chrome, da dieser dann einen Input vom Type "Date" verwendet und dieser verlangt dann ein Normdatum yyyy-mm-dd*@
        @Html.EditorFor(model => model.Geburtsdatum)
        @Html.ValidationMessageFor(m => m.Geburtsdatum, String.Empty, new {@class = "text-danger"})
    </div>
    <div class="date4Chrome">
        @Html.EditorFor(model => model.GeburtsdatumChromeEdit)
        @Html.ValidationMessageFor(m => m.GeburtsdatumChromeEdit, String.Empty, new { @class = "text-danger" })
        @*@Html.TextBoxFor(model => model.Geburtsdatum, "{0:dd.MM.yyyy}")
        @Html.ValidationMessageFor(m => m.Geburtsdatum, String.Empty, new { @class = "text-danger" })*@
    </div>
</code>```

With a function I found on stackoverflow (How can I tell if a browser supports <input type='date'>) I can detect if the actual browser uses date-input:

```<code> function checkDateInput() {
        var input = document.createElement('input');
        input.setAttribute('type', 'date');

        var notADateValue = 'not-a-date';
        input.setAttribute('value', notADateValue);

        return (input.value !== notADateValue);
    }
</code>```

With the next function I remove the input-blocks I do not need:

```<code> function switchForChrome() {
        var isChrome = checkDateInput();
        if (isChrome) {
            $('.date4Normal').remove();
        } else {
            $('.date4Chrome').remove();
        }
    };
</code>```

In the $(document).ready function I call the switchForChrome();.

At this point it seems to work, but the validation of the date allways failed.

So I add some code to work around (ASP.NET MVC 4 avoid generation of data-val-date for datetime):

```<code>if (checkDateInput()) {
    $.validator.addMethod('date',
        function (value, element) {
            return true;
     });
}
</code>```

And finally it works.
For display I use the original property (Geburtsdatum) so I get the language-specific format and for edit either the original property (IE, Firefox) or the new property GeburtsdatumChromeEdit (Chrome, Opera).

Title: MVC: Date in Chrome-browser

Body:
After reading a lot of answers here at stackoverflow I came to this solution:

In the model I introduce a new, not mapped property:

...
    [NotMapped]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime GeburtsdatumChromeEdit
    {
        get { return this.Geburtsdatum; }
        set { this.Geburtsdatum = value; }
    }
...

This is necessary to add the dataannotiation DisplayFormat with the format Chrome wants. It pipes the value to the original property.

In the view I doubled the Input for the date and encapsulated the two groups by div's with special classes:

<div class="date4Normal">
        @*Tut nicht in Chrome, da dieser dann einen Input vom Type "Date" verwendet und dieser verlangt dann ein Normdatum yyyy-mm-dd*@
        @Html.EditorFor(model => model.Geburtsdatum)
        @Html.ValidationMessageFor(m => m.Geburtsdatum, String.Empty, new {@class = "text-danger"})
    </div>
    <div class="date4Chrome">
        @Html.EditorFor(model => model.GeburtsdatumChromeEdit)
        @Html.ValidationMessageFor(m => m.GeburtsdatumChromeEdit, String.Empty, new { @class = "text-danger" })
        @*@Html.TextBoxFor(model => model.Geburtsdatum, "{0:dd.MM.yyyy}")
        @Html.ValidationMessageFor(m => m.Geburtsdatum, String.Empty, new { @class = "text-danger" })*@
    </div>

With a function I found on stackoverflow (How can I tell if a browser supports <input type='date'>) I can detect if the actual browser uses date-input:

 function checkDateInput() {
        var input = document.createElement('input');
        input.setAttribute('type', 'date');

        var notADateValue = 'not-a-date';
        input.setAttribute('value', notADateValue);

        return (input.value !== notADateValue);
    }

With the next function I remove the input-blocks I do not need:

 function switchForChrome() {
        var isChrome = checkDateInput();
        if (isChrome) {
            $('.date4Normal').remove();
        } else {
            $('.date4Chrome').remove();
        }
    };

In the $(document).ready function I call the switchForChrome();.

At this point it seems to work, but the validation of the date allways failed.

So I add some code to work around (ASP.NET MVC 4 avoid generation of data-val-date for datetime):

if (checkDateInput()) {
    $.validator.addMethod('date',
        function (value, element) {
            return true;
     });
}

And finally it works.
For display I use the original property (Geburtsdatum) so I get the language-specific format and for edit either the original property (IE, Firefox) or the new property GeburtsdatumChromeEdit (Chrome, Opera).


问:
Lazy evaluation and problems with const correctness
I have made an openGL camera class that uses lazy evaluation to provide the final projection or model-view-projection matrices through getter functions.  The user provides the various camera parameters throughout the life of the instance (FOV, position, etc. ), but rather than have the projection matrix and/or MVP matrix recalculated every time a parameter is changed, a 'changed' flag is set (i.e. the old cached matrix is now invalid).  Whenever the user then requests the updated final matrix, it is recalculated, the result cached, and a const reference returned.

Everything sounds fine until I call my:

```<code>const QMatrix4x4& oE_GLCamera::getModelViewProjection() const;
</code>```

function from a const oE_GLCamera instance...  I use const references everywhere in my app to extract camera data from CAD viewports without changing the camera, but my getter function performs lazy evaluation on member variables if they are invalid - therefore breaking const-correctness.

Is there a language feature or design paradigm I'm unaware of to help with this?  Or is lazy evaluation fundamentally incompatible with const-correctness?  I am aware of const_cast<>, I have never used it myself but have a read few things about it which boil down to: If you have you use it, you have already gone wrong somewhere.  Or will it be my saviour?

Any advice will be greatfully received,
Cam

答:
Is there a language feature or design paradigm I'm unaware of to help with this?

Perhaps, mutable ?

A member of a class that is marked as mutable is always non-const even if it is accessed via a reference or pointer to the owning class which is a const reference or a pointer to const.

Body:
I have made an openGL camera class that uses lazy evaluation to provide the final projection or model-view-projection matrices through getter functions.  The user provides the various camera parameters throughout the life of the instance (FOV, position, etc. ), but rather than have the projection matrix and/or MVP matrix recalculated every time a parameter is changed, a 'changed' flag is set (i.e. the old cached matrix is now invalid).  Whenever the user then requests the updated final matrix, it is recalculated, the result cached, and a const reference returned.

Everything sounds fine until I call my:

const QMatrix4x4& oE_GLCamera::getModelViewProjection() const;

function from a const oE_GLCamera instance...  I use const references everywhere in my app to extract camera data from CAD viewports without changing the camera, but my getter function performs lazy evaluation on member variables if they are invalid - therefore breaking const-correctness.

Is there a language feature or design paradigm I'm unaware of to help with this?  Or is lazy evaluation fundamentally incompatible with const-correctness?  I am aware of const_cast<>, I have never used it myself but have a read few things about it which boil down to: If you have you use it, you have already gone wrong somewhere.  Or will it be my saviour?

Any advice will be greatfully received,
Cam


问:
get the hostname(Base URL) using javascript
I get too many ways to get the hostname like code below:

```<code>window.location.host // you'll get sub.domain.com:8080 or sub.domain.com:80
window.location.hostname // you'll get sub.domain.com
window.location.protocol // you'll get http:
window.location.port // you'll get 8080 or 80
window.location.pathname // you'll get /virtualPath
</code>```

In my case I want something different. For example:

My QA site name is example.com/testsite/index.html

My PROD site name is example.com/index.html

The problem here using the above methods to get the hostname it is returning me only the hostname like this: example.com

However for QA I need to return example.com/testsite

For PROD i need to return example.com

Is it possible with the single code? Thanks in advance.

答:
Use window.location.hostname;

Example:

Page URL is  http://localhost:2239/Default2.aspx?id=5&name=SatinderSingh

```<code>var getCurrentURL =window.location.href; //http://localhost:2239/Default2.aspx?id=5&name=SatinderSingh
var getHostname=window.location.hostname; //localhost
var getPathName=window.location.pathname  // Default2.aspx
var getPortNo=window.location.port        // 2239
var getQueryString=window.location.search //?id=5&name=SatinderSingh
</code>```

```<code>   var getHostname = window.location.hostname; //localhost
   var getPathName = window.location.pathname  // Default2.aspx
   var split_PathName = String(getPathName.split("/"));
   var FinalURL = getHostname + "/" + split_PathName[1]
</code>```

Body:
I get too many ways to get the hostname like code below:

window.location.host // you'll get sub.domain.com:8080 or sub.domain.com:80
window.location.hostname // you'll get sub.domain.com
window.location.protocol // you'll get http:
window.location.port // you'll get 8080 or 80
window.location.pathname // you'll get /virtualPath

In my case I want something different. For example:

My QA site name is example.com/testsite/index.html

My PROD site name is example.com/index.html

The problem here using the above methods to get the hostname it is returning me only the hostname like this: example.com

However for QA I need to return example.com/testsite

For PROD i need to return example.com

Is it possible with the single code? Thanks in advance.

Body:
Use window.location.hostname;

Example:

Page URL is  http://localhost:2239/Default2.aspx?id=5&name=SatinderSingh

var getCurrentURL =window.location.href; //http://localhost:2239/Default2.aspx?id=5&name=SatinderSingh
var getHostname=window.location.hostname; //localhost
var getPathName=window.location.pathname  // Default2.aspx
var getPortNo=window.location.port        // 2239
var getQueryString=window.location.search //?id=5&name=SatinderSingh

   var getHostname = window.location.hostname; //localhost
   var getPathName = window.location.pathname  // Default2.aspx
   var split_PathName = String(getPathName.split("/"));
   var FinalURL = getHostname + "/" + split_PathName[1]


问:
node-red parsing a json string to msg.payload
Noob question

I am using the snmp function to collect data via oid lists.
I have extracted the data and used the json function to parse the data into a json string seen below.

msg.payload : string[81]
  "[{"oid":"1.3.6.1.4.1.38783.3.3.1.1.1.0","type":2,"value":53800,"tstr":"Integer"}]"

I am trying to write a function to strip out "value":53800 from this string and output it in msg.payload.

I have tried below but it returns

"TypeError: Cannot assign to read only property '_msgid' of "value":53700,"tstr":"Integer"}]"

```<code>var msg = msg.payload;
var value = msg.substr(49,62);

return value;
</code>```

答:
Don't try and split the string up like that, it's too prone to errors if the value lengths ever change.

Instead run the message through the JSON node before the function node.

This will parse the string and generate a proper JSON object.

You can then access value field as such:

```<code>var value = msg.payload[0].value;
msg.payload = value;
return msg;
</code>```

The Cannot assign to read only property error is because you returned a string from the function. You need to return a message JSON object not a string. My example sets the msg.payload to the required value.

Body:
Noob question

I am using the snmp function to collect data via oid lists.
I have extracted the data and used the json function to parse the data into a json string seen below.

msg.payload : string[81]
  "[{"oid":"1.3.6.1.4.1.38783.3.3.1.1.1.0","type":2,"value":53800,"tstr":"Integer"}]"

I am trying to write a function to strip out "value":53800 from this string and output it in msg.payload.

I have tried below but it returns

"TypeError: Cannot assign to read only property '_msgid' of "value":53700,"tstr":"Integer"}]"

var msg = msg.payload;
var value = msg.substr(49,62);

return value;

Body:
Don't try and split the string up like that, it's too prone to errors if the value lengths ever change.

Instead run the message through the JSON node before the function node.

This will parse the string and generate a proper JSON object.

You can then access value field as such:

var value = msg.payload[0].value;
msg.payload = value;
return msg;

The Cannot assign to read only property error is because you returned a string from the function. You need to return a message JSON object not a string. My example sets the msg.payload to the required value.


问:
Elastic Beanstalk: ERROR: The EB CLI cannot find a platform for key "docker 17.03.1-ce"
I've recently been getting this error when trying to run an eb deploy command using the Elastic Beanstalk CLI. I cannot see any documentation around this issue.

Any pointers in the right direction would be very much appreciated.

答: My ~/.elasticbeanstalk/config.yml and project .elasticbeanstalk/config.yml had different content. I needed to edit the entry for the project to change the default_platform entry to match my currently installed docker version.</p>


问:
oracle between query not taking end date time
Oracle between query ignoring end date time.

Below is my table.

```<code>Id   Upload Date
1   05-JUL-17 12.02.11.309000000 PM
2   05-JUL-17 12.03.34.123000000 PM
3   05-JUL-17 12.04.15.334000000 PM
</code>```

My requirement is to fetch the files between the given date time.

```<code> select * from fileupload where uploaddate between to_DATE('05-07-17 12:02:11', 'DD-MM-YY HH24:MI:SS') and to_DATE('05-07-17 12:04:15', 'DD-MM-YY HH24:MI:SS')

select * from fileupload where uploaddate between to_timestamp('05-07-17 12:02:11', 'DD-MM-YY HH24:MI:SS') and to_timestamp('05-07-17 12:04:15', 'DD-MM-YY HH24:MI:SS')
</code>```

Both queries not returns the end date time it returns only two row.

```<code>Id   Upload Date
1   05-JUL-17 12.02.11.309000000 PM
2   05-JUL-17 12.03.34.123000000 PM
</code>```

But the expected result is

```<code> Id   Upload Date
    1   05-JUL-17 12.02.11.309000000 PM
    2   05-JUL-17 12.03.34.123000000 PM
    3   05-JUL-17 12.04.15.334000000 PM
</code>```

why the end date time is not fetching when using between.

Any help will be greatly appreciated!!!!

答:
The value to_DATE('05-07-17 12:04:15', 'DD-MM-YY HH24:MI:SS') is equivalent to 05-JUL-17 12.04.15.000000000 PM that comes before  05-JUL-17 12.04.15.334000000 PM

So the third result is not extracted because is not in the range for 334 ms.

To extract all the records you need to update the query not considering the milliseconds as follow:

```<code> select * from fileupload
 where  cast(uploaddate as date)
        between to_DATE('05-07-17 12:02:11', 'DD-MM-YY HH24:MI:SS')
        and to_DATE('05-07-17 12:04:15', 'DD-MM-YY HH24:MI:SS')
</code>```

Body:
Oracle between query ignoring end date time.

Below is my table.

Id   Upload Date
1   05-JUL-17 12.02.11.309000000 PM
2   05-JUL-17 12.03.34.123000000 PM
3   05-JUL-17 12.04.15.334000000 PM

My requirement is to fetch the files between the given date time.

 select * from fileupload where uploaddate between to_DATE('05-07-17 12:02:11', 'DD-MM-YY HH24:MI:SS') and to_DATE('05-07-17 12:04:15', 'DD-MM-YY HH24:MI:SS')

select * from fileupload where uploaddate between to_timestamp('05-07-17 12:02:11', 'DD-MM-YY HH24:MI:SS') and to_timestamp('05-07-17 12:04:15', 'DD-MM-YY HH24:MI:SS')

Both queries not returns the end date time it returns only two row.

Id   Upload Date
1   05-JUL-17 12.02.11.309000000 PM
2   05-JUL-17 12.03.34.123000000 PM

But the expected result is

 Id   Upload Date
    1   05-JUL-17 12.02.11.309000000 PM
    2   05-JUL-17 12.03.34.123000000 PM
    3   05-JUL-17 12.04.15.334000000 PM

why the end date time is not fetching when using between.

Any help will be greatly appreciated!!!!

Body:
The value to_DATE('05-07-17 12:04:15', 'DD-MM-YY HH24:MI:SS') is equivalent to 05-JUL-17 12.04.15.000000000 PM that comes before  05-JUL-17 12.04.15.334000000 PM

So the third result is not extracted because is not in the range for 334 ms.

To extract all the records you need to update the query not considering the milliseconds as follow:

 select * from fileupload
 where  cast(uploaddate as date)
        between to_DATE('05-07-17 12:02:11', 'DD-MM-YY HH24:MI:SS')
        and to_DATE('05-07-17 12:04:15', 'DD-MM-YY HH24:MI:SS')


问:
Find Gene name in Column A and put the given ID in column B
I have an excel Sheet with 2 columns, in this form

```<code>ADRBK2  NA
ADRBK2  NA
A1CF    ID1
A2M     ID2
ADRBK2  NA
</code>```

Now what I want to achieve is that i look up the gene ADRBK2 in Column A and where ever i find this gene in Column A in my file, I want to put ID3 at the column B next to it. How can i Achieve this ?

答: Sort your data alphabetically, put ID3 in cell next to first ADRBK2, drag by left bottom corner of the ADRBK2 cell to the end of empty cells(simple copy).</p>

Body:
I have an excel Sheet with 2 columns, in this form

ADRBK2  NA
ADRBK2  NA
A1CF    ID1
A2M     ID2
ADRBK2  NA

Now what I want to achieve is that i look up the gene ADRBK2 in Column A and where ever i find this gene in Column A in my file, I want to put ID3 at the column B next to it. How can i Achieve this ?


问:
Upload recorded audio file in Objective-C using PHP
I am trying to record an audio file in my app, then I want to upload to a web server,
the code i have written is working for recording and playback and even for uploading to the web server using PHP, the only issues that I am facing that the uploaded file is always blank, ZERO file size

Can you please have a look at my code and let me know what am i doing incorrectly to cause this issue

Everything below is working perfectly, the only piece that I struggling with the when the file uploaded it appears in the destination folder of the server, but of ZERO file size, I am also attaching my php at the end of the post.

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

    // Disable Stop/Play button when application launches
    [btnStop setEnabled:NO];
    [btnPlay setEnabled:NO];

    // Set the audio file
    NSArray *pathComponents = [NSArray arrayWithObjects: [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], @"MyAudioMemo.m4a", nil];
    //NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
    outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];

    // Setup audio session
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];

    // Define the recorder setting
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];

    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
    [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
    [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];

    // Initiate and prepare the recorder
    recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:nil];
    recorder.delegate = self;
    recorder.meteringEnabled = YES;
    [recorder prepareToRecord];

}

- (IBAction)record:(id)sender {
    // Stop the audio player before recording
    if (player.playing) {
        [player stop];
    }

    if (!recorder.recording) {
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setActive:YES error:nil];

        // Start recording
        [recorder record];
        [btnRecord setTitle:@"Pause" forState:UIControlStateNormal];

    } else {

        // Pause recording
        [recorder pause];
        [btnRecord setTitle:@"Record" forState:UIControlStateNormal];
    }

    [btnStop setEnabled:YES];
    [btnPlay setEnabled:NO];
}

- (IBAction)stop:(id)sender {
    [recorder stop];

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setActive:NO error:nil];
}

- (IBAction)play:(id)sender {
    if (!recorder.recording){
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:recorder.url error:nil];
        [player setDelegate:self];
        [player play];
    }
}

- (IBAction)upload:(id)sender {
    NSData *file1Data = [[NSData alloc] initWithContentsOfFile:[recorder.url absoluteString]];
    NSString *urlString = @"http://mydomain.com/phpcodes/uploadFile.php";

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];

    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"AudioFile3.m4a\"\r\n"]] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:file1Data]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [request setHTTPBody:body];

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

    NSLog(@"Return String= %@",returnString);
}

- (void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully (BOOL)flag{
    [btnRecord setTitle:@"Record" forState:UIControlStateNormal];
    [btnStop setEnabled:NO];
    [btnPlay setEnabled:YES];
}

- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Done"
                                                    message: @"Finish playing the recording!"
                                                   delegate: nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
}
</code>```

PHP Code

```<code>    <?php
        $folder = "audio/";

        if (is_uploaded_file($_FILES['userfile']['tmp_name']))  {
        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $folder.$_FILES['userfile']['name'])) {
            Echo "File uploaded";
        } else {
            Echo "File not moved to destination folder. Check permissions";
        };
        } else {
            Echo "File is not uploaded.";
        };
    ?>
</code>```

答:
You can use this alternate solution:</p>

```<code>NSData *mediaContent = [[NSFileManager defaultManager] contentsAtPath:_mediaURL.absoluteString];
</code>```

Body:
I am trying to record an audio file in my app, then I want to upload to a web server,
the code i have written is working for recording and playback and even for uploading to the web server using PHP, the only issues that I am facing that the uploaded file is always blank, ZERO file size

Can you please have a look at my code and let me know what am i doing incorrectly to cause this issue

Everything below is working perfectly, the only piece that I struggling with the when the file uploaded it appears in the destination folder of the server, but of ZERO file size, I am also attaching my php at the end of the post.

- (void)viewDidLoad {
    [super viewDidLoad];

    // Disable Stop/Play button when application launches
    [btnStop setEnabled:NO];
    [btnPlay setEnabled:NO];

    // Set the audio file
    NSArray *pathComponents = [NSArray arrayWithObjects: [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], @"MyAudioMemo.m4a", nil];
    //NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
    outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];

    // Setup audio session
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];

    // Define the recorder setting
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];

    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
    [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
    [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];

    // Initiate and prepare the recorder
    recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:nil];
    recorder.delegate = self;
    recorder.meteringEnabled = YES;
    [recorder prepareToRecord];

}

- (IBAction)record:(id)sender {
    // Stop the audio player before recording
    if (player.playing) {
        [player stop];
    }

    if (!recorder.recording) {
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setActive:YES error:nil];

        // Start recording
        [recorder record];
        [btnRecord setTitle:@"Pause" forState:UIControlStateNormal];

    } else {

        // Pause recording
        [recorder pause];
        [btnRecord setTitle:@"Record" forState:UIControlStateNormal];
    }

    [btnStop setEnabled:YES];
    [btnPlay setEnabled:NO];
}

- (IBAction)stop:(id)sender {
    [recorder stop];

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setActive:NO error:nil];
}

- (IBAction)play:(id)sender {
    if (!recorder.recording){
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:recorder.url error:nil];
        [player setDelegate:self];
        [player play];
    }
}

- (IBAction)upload:(id)sender {
    NSData *file1Data = [[NSData alloc] initWithContentsOfFile:[recorder.url absoluteString]];
    NSString *urlString = @"http://mydomain.com/phpcodes/uploadFile.php";

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];

    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"AudioFile3.m4a\"\r\n"]] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:file1Data]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [request setHTTPBody:body];

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

    NSLog(@"Return String= %@",returnString);
}

- (void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully (BOOL)flag{
    [btnRecord setTitle:@"Record" forState:UIControlStateNormal];
    [btnStop setEnabled:NO];
    [btnPlay setEnabled:YES];
}

- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Done"
                                                    message: @"Finish playing the recording!"
                                                   delegate: nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
}

PHP Code

    <?php
        $folder = "audio/";

        if (is_uploaded_file($_FILES['userfile']['tmp_name']))  {
        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $folder.$_FILES['userfile']['name'])) {
            Echo "File uploaded";
        } else {
            Echo "File not moved to destination folder. Check permissions";
        };
        } else {
            Echo "File is not uploaded.";
        };
    ?>

Body:
You can use this alternate solution:

NSData *mediaContent = [[NSFileManager defaultManager] contentsAtPath:_mediaURL.absoluteString];


问:
Load image to markers on maps
I have implemented a simple google map where i display a list of markers depending on a list that i have for that.

To display them i iterate over the list and create each marker, like this:

```<code>for (final PhotosForPlants p : photos) {
            if (p.getLat() != null && p.getLon() != null && p.getLat() != 0.0 && p.getLon() != 0.0) // check for 0.0
            {
                if (p.getId() == currentPlantId) {
                    plantLocation = new LatLng(p.getLat(), p.getLon());
                    yellowPos = plantLocation;
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(plantLocation, 35f));
                    Marker m = mMap.addMarker(new MarkerOptions().position(plantLocation)
                            .icon(BitmapDescriptorFactory
                                    .defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));

                    m.setTag(p);
                    markers.add(m);
                } else {
                    plantLocation = new LatLng(p.getLat(), p.getLon());
                    positions.add(plantLocation);
                    positionSave = index;
                    Marker m = mMap.addMarker(new MarkerOptions().position(plantLocation)
                            .icon(BitmapDescriptorFactory
                                    .defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));

                    m.setTag(p);
                    markers.add(m);
                }

            }
            index++;
        }
    }
</code>```

instead of having a simple marker image, i need to have something like a square image loaded from my server, i try to use picasso for it but i don't know if i get any problem doing it this way to get the bitmap:

```<code> public void loadBitmap(String url) {

        if (loadtarget == null) loadtarget = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                // do something with the Bitmap
                handleLoadedBitmap(bitmap);
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {

            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {

            }

        };

        Picasso.with(this).load(url).into(loadtarget);
    }

    public Bitmap handleLoadedBitmap(Bitmap b) {
        return b;
    }
</code>```

my main problem is that i don't know how i can retrive each image loaded for the specific marker, and how to set it ip with my maps :S.

Any help?

答:
try this</p>

```<code>Marker source = mMap.addMarker(
               new MarkerOptions()
    .position(
        new LatLng(
            Double.parseDouble(info.getLatitude()),
            Double.parseDouble(info.getLongitude())))
    .title(info.getBankName())
    .snippet(info.getBankAddress())
    .icon(BitmapDescriptorFactory.fromResource(getBitmap(url))));

 public static Bitmap getBitmap(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        // Log exception
        return null;
    }
}
</code>```

Title: Load image to markers on maps

Body:
I have implemented a simple google map where i display a list of markers depending on a list that i have for that.

To display them i iterate over the list and create each marker, like this:

for (final PhotosForPlants p : photos) {
            if (p.getLat() != null && p.getLon() != null && p.getLat() != 0.0 && p.getLon() != 0.0) // check for 0.0
            {
                if (p.getId() == currentPlantId) {
                    plantLocation = new LatLng(p.getLat(), p.getLon());
                    yellowPos = plantLocation;
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(plantLocation, 35f));
                    Marker m = mMap.addMarker(new MarkerOptions().position(plantLocation)
                            .icon(BitmapDescriptorFactory
                                    .defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));

                    m.setTag(p);
                    markers.add(m);
                } else {
                    plantLocation = new LatLng(p.getLat(), p.getLon());
                    positions.add(plantLocation);
                    positionSave = index;
                    Marker m = mMap.addMarker(new MarkerOptions().position(plantLocation)
                            .icon(BitmapDescriptorFactory
                                    .defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));

                    m.setTag(p);
                    markers.add(m);
                }

            }
            index++;
        }
    }

instead of having a simple marker image, i need to have something like a square image loaded from my server, i try to use picasso for it but i don't know if i get any problem doing it this way to get the bitmap:

 public void loadBitmap(String url) {

        if (loadtarget == null) loadtarget = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                // do something with the Bitmap
                handleLoadedBitmap(bitmap);
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {

            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {

            }

        };

        Picasso.with(this).load(url).into(loadtarget);
    }

    public Bitmap handleLoadedBitmap(Bitmap b) {
        return b;
    }

my main problem is that i don't know how i can retrive each image loaded for the specific marker, and how to set it ip with my maps :S.

Any help?

Body:
try this

Marker source = mMap.addMarker(
               new MarkerOptions()
    .position(
        new LatLng(
            Double.parseDouble(info.getLatitude()),
            Double.parseDouble(info.getLongitude())))
    .title(info.getBankName())
    .snippet(info.getBankAddress())
    .icon(BitmapDescriptorFactory.fromResource(getBitmap(url))));

 public static Bitmap getBitmap(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        // Log exception
        return null;
    }
}


问:
Responsive fullscreen youtube video with no black bars?
I have a fullscreen youtube video embedded on my website.

It looks good when the size of the browser is proportional to the video’s width and height. However, when I resize the browser to a different proportion, I get black bars around the video.

What I want is to have the video fill the whole window at all times, but without any stretching. I want the “excess” to hide when the browser size is not proportional to the video.

What I am trying to achieve is something you can see in the background of these two websites: http://ginlane.com/ and http://www.variousways.com/.

Is it possible to do this with a youtube video?

答:
You can also use this below:-</p>

```<code><iframe class="" style="background:url(ImageName.jpg) center; background-size: 100% 140%; " allowfullscreen="" width="300" height="200"></iframe>
</code>```

Body:
You can also use this below:-

<iframe class="" style="background:url(ImageName.jpg) center; background-size: 100% 140%; " allowfullscreen="" width="300" height="200"></iframe>


问:
MutationObserver and querySelectorAll
I am currently learning Javascript and one of my chapters is "Mutation Observer". I am trying to create a simple function which detects if a new div was added to the page and display it in the console. However, I am getting this message and I struggle to find a solution how to fix this error. I will be very grateful if someone can explain to me what I am doing wrong. Thank you in advance!

Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.

So far this is the code I wrote:

document.getElementById("Button").onclick = function(){
  var Add = document.createElement('div');
    Add.setAttribute("class", "Alpha");
    Add.appendChild(document.createTextNode("Test"));
    document.getElementById('Frame').appendChild(Add);
};

var Divs = document.querySelectorAll("div");
var Observer = new MutationObserver(function(mutations){
  mutations.forEach(function(mutation){
    for(var i = 0; i <= mutation.addedNodes.length; i++){
      if(!(mutation.addedNodes[i] == null)){
        console.log(mutation.addedNodes[i].innerHTML);
      }
    }
  });
});
Observer.observe(Divs, {childList: true, subtree:true});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.Alpha{
  color:red;
}</code>```

<button id="Button">Generate a new div</button>

```

答:
The issue is explained in the error message. The observe function expects a Node but you're assigning the return value of querySelectorAll lookup which actually returns a NodeList (so one or many Nodes). Even if it finds nothing, it'll return an empty NodeList and still be invalid.

In your instance, you appear to be pushing items into a DIV with an id of Frame so we'll attach our MutationObserver onto that and watch for any changes to its children. Finally, we'll push any changed nodes into an array and console log the contents so you can see what it's capturing,

```<code>var target = document.getElementById('Frame');
var insertedNodes = [];
var Observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        for(var i = 0; i < mutation.addedNodes.length; i++) {
            insertedNodes.push(mutation.addedNodes[i]);
        }
    });
});

Observer.observe(target, {
    childList: true,
    subtree:true
});

console.log(insertedNodes);
</code>```

Title: MutationObserver and querySelectorAll

Body:
I am currently learning Javascript and one of my chapters is "Mutation Observer". I am trying to create a simple function which detects if a new div was added to the page and display it in the console. However, I am getting this message and I struggle to find a solution how to fix this error. I will be very grateful if someone can explain to me what I am doing wrong. Thank you in advance!

Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.

So far this is the code I wrote:

document.getElementById("Button").onclick = function(){
  var Add = document.createElement('div');
    Add.setAttribute("class", "Alpha");
    Add.appendChild(document.createTextNode("Test"));
    document.getElementById('Frame').appendChild(Add);
};

var Divs = document.querySelectorAll("div");
var Observer = new MutationObserver(function(mutations){
  mutations.forEach(function(mutation){
    for(var i = 0; i <= mutation.addedNodes.length; i++){
      if(!(mutation.addedNodes[i] == null)){
        console.log(mutation.addedNodes[i].innerHTML);
      }
    }
  });
});
Observer.observe(Divs, {childList: true, subtree:true});

.Alpha{
  color:red;
}

<button id="Button">Generate a new div</button>

Body:
The issue is explained in the error message. The observe function expects a Node but you're assigning the return value of querySelectorAll lookup which actually returns a NodeList (so one or many Nodes). Even if it finds nothing, it'll return an empty NodeList and still be invalid.

In your instance, you appear to be pushing items into a DIV with an id of Frame so we'll attach our MutationObserver onto that and watch for any changes to its children. Finally, we'll push any changed nodes into an array and console log the contents so you can see what it's capturing,

var target = document.getElementById('Frame');
var insertedNodes = [];
var Observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        for(var i = 0; i < mutation.addedNodes.length; i++) {
            insertedNodes.push(mutation.addedNodes[i]);
        }
    });
});

Observer.observe(target, {
    childList: true,
    subtree:true
});

console.log(insertedNodes);


问:
Disabling JACK in android compilation
Does anybody know how to completely disable jack while compiling AOSP (Master)?

I've always had problems with jack, so I've just always turned it off by adding ANDROID_COMPILE_WITH_JACK := false in BoardConfig.mk (when compiling CyanogenMod).
I'm now compiling aosp and it just seems to ignore this command.

Note: I'm not really trying to solve any jack related issues I have, I'm trying to turn it off.

答:
You can disable the JACK without to change any code.

```<code>make ANDROID_COMPILE_WITH_JACK:=false
</code>```

Just do it when making the entire Android Project.

The magic is in build/make/combo/javac.mk:

```<code>ifndef ANDROID_COMPILE_WITH_JACK
# Defines if compilation with jack is enabled by default.
ANDROID_COMPILE_WITH_JACK := true
endif
</code>```

And build/make/core/config.mk:

```<code>ifeq ($(ANDROID_COMPILE_WITH_JACK),true)
DEFAULT_JACK_ENABLED:=full
else
DEFAULT_JACK_ENABLED:=
endif
</code>```

And build/make/core/clear_vars.mk:

```<code>LOCAL_JACK_ENABLED:=DEFAULT_JACK_ENABLED
</code>```

It also indicates why your modification in a local module is in vain.

Title: Disabling JACK in android compilation

Body:
You can disable the JACK without to change any code.

make ANDROID_COMPILE_WITH_JACK:=false

Just do it when making the entire Android Project.

The magic is in build/make/combo/javac.mk:

ifndef ANDROID_COMPILE_WITH_JACK
# Defines if compilation with jack is enabled by default.
ANDROID_COMPILE_WITH_JACK := true
endif

And build/make/core/config.mk:

ifeq ($(ANDROID_COMPILE_WITH_JACK),true)
DEFAULT_JACK_ENABLED:=full
else
DEFAULT_JACK_ENABLED:=
endif

And build/make/core/clear_vars.mk:

LOCAL_JACK_ENABLED:=DEFAULT_JACK_ENABLED

It also indicates why your modification in a local module is in vain.


问:
How do you store a list of directories into an array in Bash (and then print them out)?
I want to write a shell script to show a list of directories entered by a user and then for a user to select one of the directories with an index number based on how many directories there are

I'm thinking this is some kind of array operation, but im not sure how to do this in shell script

example:

```<code>> whichdir
There are 3 dirs in the current path
1 dir1
2 dir2
3 dir3
which dir do you want?
> 3
you selected dir3!
</code>```

答:
Array syntax

Assuming you have the directories stored in an array:

```<code>dirs=(dir1 dir2 dir3)
</code>```

You can get the length of the array thusly:

```<code>echo "There are ${#dirs[@]} dirs in the current path"
</code>```

You can loop through it like so:

```<code>let i=1

for dir in "${dirs[@]}"; do
    echo "$((i++)) $dir"
done
</code>```

And assuming you've gotten the user's answer, you can index it as follows. Remember that arrays are 0-based so the 3rd entry is index 2.

```<code>answer=2

echo "you selected ${dirs[$answer]}!"
</code>```

Find

How do you get the file names into an array, anyways? It's a bit tricky. If you have find that might be the best way:

```<code>readarray -t dirs < <(find . -maxdepth 1 -type d -printf '%P\n')
</code>```

The -maxdepth 1 stops find from looking through subdirectories, -type d tells it to find directories and skip files, and -printf '%P\n' tells it to print the directory names without the leading ./ it normally likes to print.

Body:
I want to write a shell script to show a list of directories entered by a user and then for a user to select one of the directories with an index number based on how many directories there are

I'm thinking this is some kind of array operation, but im not sure how to do this in shell script

example:

> whichdir
There are 3 dirs in the current path
1 dir1
2 dir2
3 dir3
which dir do you want?
> 3
you selected dir3!

Body:
Array syntax

Assuming you have the directories stored in an array:

dirs=(dir1 dir2 dir3)

You can get the length of the array thusly:

echo "There are ${#dirs[@]} dirs in the current path"

You can loop through it like so:

let i=1

for dir in "${dirs[@]}"; do
    echo "$((i++)) $dir"
done

And assuming you've gotten the user's answer, you can index it as follows. Remember that arrays are 0-based so the 3rd entry is index 2.

answer=2

echo "you selected ${dirs[$answer]}!"

Find

How do you get the file names into an array, anyways? It's a bit tricky. If you have find that might be the best way:

readarray -t dirs < <(find . -maxdepth 1 -type d -printf '%P\n')

The -maxdepth 1 stops find from looking through subdirectories, -type d tells it to find directories and skip files, and -printf '%P\n' tells it to print the directory names without the leading ./ it normally likes to print.


问:
Sorting a string using STL
I am trying to sort the characters of a string using C++ STL and came up with this code.

```<code>#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

int main()
{
    using namespace std;
    vector<string>::iterator it;
    string arr[] = {"jajajaj"};
    vector<string> v(arr, arr+2);
    sort(v.begin(), v.end());
    for (it=v.begin(); it<v.end(); it++) {
      cout << *it;
   }
    return 0;
}
</code>```

But unfortunately its not sorting properly when the array contains single element. How to do it using STL.
Please help.

答:
You can use sort() function. sort() exists in algorithm header file

```<code>        #include<bits/stdc++.h>
        using namespace std;

        int main()
        {
            ios::sync_with_stdio(false);
            string str = "sharlock";

            sort(str.begin(), str.end());
            cout<<str<<endl;

            return 0;
        }
</code>```

Output:

```<code>achklors
</code>```

Title: Sorting a string using STL

Body:
I am trying to sort the characters of a string using C++ STL and came up with this code.

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

int main()
{
    using namespace std;
    vector<string>::iterator it;
    string arr[] = {"jajajaj"};
    vector<string> v(arr, arr+2);
    sort(v.begin(), v.end());
    for (it=v.begin(); it<v.end(); it++) {
      cout << *it;
   }
    return 0;
}

But unfortunately its not sorting properly when the array contains single element. How to do it using STL.
Please help.

Body:
You can use sort() function. sort() exists in algorithm header file

        #include<bits/stdc++.h>
        using namespace std;

        int main()
        {
            ios::sync_with_stdio(false);
            string str = "sharlock";

            sort(str.begin(), str.end());
            cout<<str<<endl;

            return 0;
        }

Output:

achklors


问:
Laravel Blades - Assign JS variable to PHP variable
Is it possible to assign javascript variable to php variable?

Defined:
{{ $var }} and @{{ jsVar }}

I'd like to something like this (this example not working): {{ $var = jsVar }}.

This is needed to pass the parameter to e.g. generate named routes. I can't do something like that route('user', ['id' => jsVar])

答:
No, it is not possible. PHP is a server side language and executed before you even see the HTML output. JS is client side and runs after the server side code has been executed.

You will need to rethink your architecture and call a API endpoint via AJAX from JS so you can talk to the server side of your application