问:
How a broadcast receiver can function normally even on app crash
Problem scenario:  I have an android application with a statically registered broadcast receiver having intent filter registered for AIRPLANE_MODE is working fine. When I turn on the airplane mode, a toast is displayed.
        When I force stop my application, the broadcast receiver doesn't work which is an expected result. But now when my app crashes, still the broadcast receiver is displaying toast. So, my question is why my broadcast receiver is working even on app crash whereas it is destroyed when I force stop the application. It will be really helpful if someone could provide a clear understanding of App Force Stop scenario.</p>

答:
In your app, you have 4 points for starting your app: BroadcastReceiver, Activity, Service, ContentProvider.

So if you register your BroadcastReceiver in AndroidManifest, even if u make a force stop app, you will actually getting callbacks in BroadcastReceiver, because it's a point of starting app. You actually can disable BroadcastReceiver programatically by following code:

```<code>ComponentName component = new ComponentName(context, YourReceiver.class);

//Disable BroadcastReceiver
context.getPackageManager().setComponentEnabledSetting(component,  PackageManager.COMPONENT_ENABLED_STATE_DISABLED , PackageManager.DONT_KILL_APP);

//Enable BroadcastReceiver
context.getPackageManager().setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_ENABLED , PackageManager.DONT_KILL_APP);
</code>```

Body:
In your app, you have 4 points for starting your app: BroadcastReceiver, Activity, Service, ContentProvider.

So if you register your BroadcastReceiver in AndroidManifest, even if u make a force stop app, you will actually getting callbacks in BroadcastReceiver, because it's a point of starting app. You actually can disable BroadcastReceiver programatically by following code:

ComponentName component = new ComponentName(context, YourReceiver.class);

//Disable BroadcastReceiver
context.getPackageManager().setComponentEnabledSetting(component,  PackageManager.COMPONENT_ENABLED_STATE_DISABLED , PackageManager.DONT_KILL_APP);

//Enable BroadcastReceiver
context.getPackageManager().setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_ENABLED , PackageManager.DONT_KILL_APP);


来源: stackexchange

问:
Converting {integer} to f32 in Rust
I want to convert a value from {integer} to f32:

```<code>struct Vector3 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

for x in -5..5 {
    for y in -5..5 {
        for z in -5..5 {
            let foo: Vector3 = Vector3 { x: x, y: y, z: z };
            // do stuff with foo
        }
    }
}
</code>```

The compiler chokes on this with a type mismatch error (expecting f32 but getting {integer}). Unfortunately I can not simply change Vector3. I'm feeding a C-API with this.

Is there any easy and concise way I can convert x, y and z from {integer} to f32?

I guess there is no builtin conversion from i32 or {integer} to f32 because it could be lossy in certain situations. However, in my case the range I'm using is so small that this wouldn't be an issue. So I would like to tell the compiler to convert the value anyways.

Interestingly, the following works:

```<code>for x in -5..5 {
    let tmp: i32 = x;
    let foo: f32 = tmp as f32;
}
</code>```

I'm using a lot more that just one foo and one x so this turns hideous really fast.

Also, this works:

```<code>for x in -5i32..5i32 {
    let foo: f32 = x as f32;
    // do stuff with foo here
}
</code>```

But with my usecase this turns into:

```<code>for x in -5i32..5i32 {
    for y in -5i32..5i32 {
        for z in -5i32..5i32 {
            let foo: Vector3 = Vector3 {
                x: x as f32,
                y: y as f32,
                z: z as f32,
            };
            // do stuff with foo
        }
    }
}
</code>```

Which I think is pretty unreadable and an unreasonable amount of cruft for a simple conversion.

What am I missing here?

答:
As many problems in Computer Science, it can be solved by applying another layer of indirection.

For example, defining a constructor for Vec3:

```<code>impl Vec3 {
    fn new(x: i16, y: i16, z: i16) -> Vec3 {
        Vec3 { x: x as f32, y: y as f32, z: z as f32 }
    }
}

fn main() {
    for x in -5..5 {
        for y in -5..5 {
            for z in -5..5 {
                let foo = Vector3::new(x, y, z);
                println!("{:?}", foo);
            }
        }
    }
}
</code>```

You can use a plethora of other methods (generics, builders, etc...); but a good old constructor is just the simplest.

ContentLicense: CC BY-SA 3.0

Title: Converting {integer} to f32 in Rust

Body:
I want to convert a value from {integer} to f32:

struct Vector3 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

for x in -5..5 {
    for y in -5..5 {
        for z in -5..5 {
            let foo: Vector3 = Vector3 { x: x, y: y, z: z };
            // do stuff with foo
        }
    }
}

The compiler chokes on this with a type mismatch error (expecting f32 but getting {integer}). Unfortunately I can not simply change Vector3. I'm feeding a C-API with this.

Is there any easy and concise way I can convert x, y and z from {integer} to f32?

I guess there is no builtin conversion from i32 or {integer} to f32 because it could be lossy in certain situations. However, in my case the range I'm using is so small that this wouldn't be an issue. So I would like to tell the compiler to convert the value anyways.

Interestingly, the following works:

for x in -5..5 {
    let tmp: i32 = x;
    let foo: f32 = tmp as f32;
}

I'm using a lot more that just one foo and one x so this turns hideous really fast.

Also, this works:

for x in -5i32..5i32 {
    let foo: f32 = x as f32;
    // do stuff with foo here
}

But with my usecase this turns into:

for x in -5i32..5i32 {
    for y in -5i32..5i32 {
        for z in -5i32..5i32 {
            let foo: Vector3 = Vector3 {
                x: x as f32,
                y: y as f32,
                z: z as f32,
            };
            // do stuff with foo
        }
    }
}

Which I think is pretty unreadable and an unreasonable amount of cruft for a simple conversion.

What am I missing here?

Body:
As many problems in Computer Science, it can be solved by applying another layer of indirection.

For example, defining a constructor for Vec3:

impl Vec3 {
    fn new(x: i16, y: i16, z: i16) -> Vec3 {
        Vec3 { x: x as f32, y: y as f32, z: z as f32 }
    }
}

fn main() {
    for x in -5..5 {
        for y in -5..5 {
            for z in -5..5 {
                let foo = Vector3::new(x, y, z);
                println!("{:?}", foo);
            }
        }
    }
}

You can use a plethora of other methods (generics, builders, etc...); but a good old constructor is just the simplest.


问:
Unable to send mail via php mail()
I am unable to send an email via php's mail function.

This is the error I receive.
Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in D:\inetpub\vhosts\southernbatteries.com\httpdocs\includes\utils.php on line 6
Array ( [0] => [1] => Could not send mail, please try later... )

What exactly does this mean ? Does it mean there is not mail server installed on my webserver ? Is it possible to use a different mail server. E.g Gmails mail server to send the mail ?

答:
you should avoid using php's mail()-function as ist connects and disconnects to the mailserver for every mail sent.

instead of that, try to use something like phpMailer wich allows easy configuration and sending a lot of mails without performance-problems.

ContentLicense: CC BY-SA 2.5

Title: Unable to send mail via php mail()


问:
Debug external project from winform application
I have two separated projects
XLSWriterUI (WinFormApp)
XLSWriter (consoleapp)

The XLSWriteUI starts without any problems. In the XLSWriteUI applications, there Is a button called "Parse". When you hit this button, the XLSWriter application executable Is called like this:

Main.cs In XLSWriterUI

```<code> private void Parse_Click(object sender, EventArgs e)
        {
            // Enable waitcursor
            // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            Tabs_SetWaitCursor(Parse);

            try
            {
                Debug.Text = String.Empty;
                Debug.Refresh();

                // Create process
                // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                // Set startup parameters
                proc.StartInfo.FileName = @"XLSWriter.exe";
                proc.StartInfo.Arguments = Tabs_GetParameters();
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.OutputDataReceived += new DataReceivedEventHandler(StdOutReceiver);

                // Start process
                // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                proc.Start();
                proc.BeginOutputReadLine();
                proc.WaitForExit();
            }
            catch (Exception Ex)
            {
                // Whatever
                Debug.AppendText(Ex.Message);
            }
            // Cancel waitcursor
            // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            Tabs_CancelWaitCursor(Parse);
        }
</code>```

As you can see, the executable of the XLSWriter Is called when you hit the Parse-button. I don't want this. I want to be able to debug the XLSWriter application project when you hit the button so I can step in and out in code in Visual studio.

So basically, I want to do this:
Start both the applications via visual studio so they are running,
Set a breakpoint in XLSWriter,
When I click on the button in XLSWriterUI, the breakpoint In XLSWriter should be triggerd.

How can I do this?

答:
VS 2010:
Open solution for XLSWriter
ctrl+alt+p
attach to process.

You need to set a period of sleep time at the beginning in order to make room for attaching the running process.

Body:
I have two separated projects
XLSWriterUI (WinFormApp)
XLSWriter (consoleapp)

The XLSWriteUI starts without any problems. In the XLSWriteUI applications, there Is a button called "Parse". When you hit this button, the XLSWriter application executable Is called like this:

Main.cs In XLSWriterUI

 private void Parse_Click(object sender, EventArgs e)
        {
            // Enable waitcursor
            // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            Tabs_SetWaitCursor(Parse);

            try
            {
                Debug.Text = String.Empty;
                Debug.Refresh();

                // Create process
                // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                // Set startup parameters
                proc.StartInfo.FileName = @"XLSWriter.exe";
                proc.StartInfo.Arguments = Tabs_GetParameters();
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.OutputDataReceived += new DataReceivedEventHandler(StdOutReceiver);

                // Start process
                // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                proc.Start();
                proc.BeginOutputReadLine();
                proc.WaitForExit();
            }
            catch (Exception Ex)
            {
                // Whatever
                Debug.AppendText(Ex.Message);
            }
            // Cancel waitcursor
            // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            Tabs_CancelWaitCursor(Parse);
        }

As you can see, the executable of the XLSWriter Is called when you hit the Parse-button. I don't want this. I want to be able to debug the XLSWriter application project when you hit the button so I can step in and out in code in Visual studio.

So basically, I want to do this:
Start both the applications via visual studio so they are running,
Set a breakpoint in XLSWriter,
When I click on the button in XLSWriterUI, the breakpoint In XLSWriter should be triggerd.

How can I do this?


问:
Bind images in razor view to <img src> that are in loop
Right now the only thing i want to know is how to bind the Image to the "img src" in razor view.I have searched the other questions but did not find the answer for images in loop.The current way written down does not work."~/Images/" is the folder where the uploaded images are.   </p>

```<code>@model List<propertyMgmt.Models.Property>
    <div id="propertyList">
          <label>Select properties to be Featured:</label><br />
          <table class="table">
            <tr>
              <th>
                @Html.Label("Property Description")
              </th>
              <th>
                @Html.Label("Property Cost")
              </th>
              <th>
                @Html.Label("Property Image")
              </th>
              <th>
                @Html.Label("Featured??")
              </th>
            </tr>
            @for (int i=0;i<Model.Count;i++)
            {
            <tr>
              <td>
                @Html.DisplayFor(m => m[i].PropertyDescription)
              </td>
              <td>
                @Html.DisplayFor(m => m[i].PropertyCost)
              </td>
              <td>
                <img src="~/Images/@(m=>m[i].PropertyImage)" />
              </td>
              <td>
                @Html.CheckBoxFor(m => m[i].IsFeatured, new {
                @onclick = "propertyCheckBoxSelect(this)" })
              </td>
            </tr>
            }
          </table>
        </div>
</code>```

答:
You can use like this.</p>

```<code><img src="~/Images/@(Model[i].PropertyImage)" />
</code>```

Body:
Right now the only thing i want to know is how to bind the Image to the "img src" in razor view.I have searched the other questions but did not find the answer for images in loop.The current way written down does not work."~/Images/" is the folder where the uploaded images are.

@model List<propertyMgmt.Models.Property>

          Select properties to be Featured:

                @Html.Label("Property Description")

                @Html.Label("Property Cost")

                @Html.Label("Property Image")

                @Html.Label("Featured??")

            @for (int i=0;i<Model.Count;i++)
            {

                @Html.DisplayFor(m => m[i].PropertyDescription)

                @Html.DisplayFor(m => m[i].PropertyCost)

                m[i].PropertyImage)" />

                @Html.CheckBoxFor(m => m[i].IsFeatured, new {
                @onclick = "propertyCheckBoxSelect(this)" })

            }

Body:
You can use like this.

<img src="~/Images/@(Model[i].PropertyImage)" />


问:
SQL - Optimize the execution time
I am trying to fetch data from stackexchange database. My query is:

```<code>select distinct top 50 U.Id, U.DisplayName, U.Reputation,
       Tags = stuff( (SELECT ','+p2.Tags
                       FROM posts p2 join votes V on p2.id = V.PostId
                       where V.VoteTypeId=5 and V.UserId = U.id
                       order by p2.CreationDate DESC
                       FOR XML PATH, TYPE).value('.[1]','nvarchar(max)')
                    ,1,1,'')
from Users U
order by U.Reputation DESC;
</code>```

However, when I run the query on data.stackexchange.com, it shows an error saying:Execution Timeout Expired. Is there any way that I can modify the query to optimize the execution time so that I can run this query successfully?

答:
You need exclude subqueries with individual XML. This will require building common XML with structure <user ...><tag1><tag2>...</user><user>... (using EXPLICIT MODE). And parse it to rows for individual user's.

```<code>with U as(
    select top 50 id, Reputation, DisplayName
      from users order by Reputation DESC
),
V as(
 select U.*,p2.Tags, p2.CreationDate
  from U, posts p2, votes V
 where p2.id = V.PostId and V.VoteTypeId=5 and V.UserId = U.id
),
Q(XML) as(
    select tag,parent,id [user!1!id],Reputation [user!1!Reputation],Name [user!1!Name], T [T!2!!element]
      from (
        select 1 tag, NULL parent, U.id, U.Reputation, U.DisplayName Name, NULL t, NULL dt
          from U
         union all
        select 2, 1, V.id, NULL, NULL, ','+Tags, CreationDate
          from V
     ) X
     order by id, tag, dt desc
       for xml explicit, type
)
select node.value('(@id)[1]','int'),
       node.value('(@Reputation)[1]','int'),
       node.value('(@Name)[1]','nvarchar(max)'),
       stuff(node.value('.[1]','nvarchar(max)'),1,1,'')
  from Q
 cross apply XML.nodes('/user') as Y(node)
 order by 2 desc
</code>```

Title: SQL - Optimize the execution time

Body:
I am trying to fetch data from stackexchange database. My query is:

select distinct top 50 U.Id, U.DisplayName, U.Reputation,
       Tags = stuff( (SELECT ','+p2.Tags
                       FROM posts p2 join votes V on p2.id = V.PostId
                       where V.VoteTypeId=5 and V.UserId = U.id
                       order by p2.CreationDate DESC
                       FOR XML PATH, TYPE).value('.[1]','nvarchar(max)')
                    ,1,1,'')
from Users U
order by U.Reputation DESC;

However, when I run the query on data.stackexchange.com, it shows an error saying:Execution Timeout Expired. Is there any way that I can modify the query to optimize the execution time so that I can run this query successfully?

Body:
You need exclude subqueries with individual XML. This will require building common XML with structure <user ...><tag1><tag2>...</user><user>... (using EXPLICIT MODE). And parse it to rows for individual user's.

with U as(
    select top 50 id, Reputation, DisplayName
      from users order by Reputation DESC
),
V as(
 select U.*,p2.Tags, p2.CreationDate
  from U, posts p2, votes V
 where p2.id = V.PostId and V.VoteTypeId=5 and V.UserId = U.id
),
Q(XML) as(
    select tag,parent,id [user!1!id],Reputation [user!1!Reputation],Name [user!1!Name], T [T!2!!element]
      from (
        select 1 tag, NULL parent, U.id, U.Reputation, U.DisplayName Name, NULL t, NULL dt
          from U
         union all
        select 2, 1, V.id, NULL, NULL, ','+Tags, CreationDate
          from V
     ) X
     order by id, tag, dt desc
       for xml explicit, type
)
select node.value('(@id)[1]','int'),
       node.value('(@Reputation)[1]','int'),
       node.value('(@Name)[1]','nvarchar(max)'),
       stuff(node.value('.[1]','nvarchar(max)'),1,1,'')
  from Q
 cross apply XML.nodes('/user') as Y(node)
 order by 2 desc


问:
Webpage is not loading correctly on In-App browser Android
I am working on a project which requires opening another Web app in app browser. For that, I used WebView inside Activity and simply loads the Web App URL into it. But it is not rendering the page as it renders in Chrome browser.
I have searched for that and updated some WebView setting in Activity but still no luck.
Following are the settings:
webView.getSettings().setJavaScriptEnabled(true);

```<code>    // Other webview options
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.setScrollbarFadingEnabled(false);
    webView.getSettings().setPluginState(WebSettings.PluginState.ON);
    webView.getSettings().setAllowFileAccess(true);
  webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setAppCacheEnabled(true);
</code>```

Do I need to add more settings apart from that? Any leads will be appreciable.

答:
Try using viewport properties.

You can enable wide viewport mode with setUseWideViewPort().

You can define properties of the viewport for your web page, such as the width and initial zoom level, using the <meta name="viewport" ...> tag in your document .

Check this tutorial for additional insights.

Body:
I am working on a project which requires opening another Web app in app browser. For that, I used WebView inside Activity and simply loads the Web App URL into it. But it is not rendering the page as it renders in Chrome browser.
I have searched for that and updated some WebView setting in Activity but still no luck.
Following are the settings:
webView.getSettings().setJavaScriptEnabled(true);

    // Other webview options
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.setScrollbarFadingEnabled(false);
    webView.getSettings().setPluginState(WebSettings.PluginState.ON);
    webView.getSettings().setAllowFileAccess(true);
  webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setAppCacheEnabled(true);

Do I need to add more settings apart from that? Any leads will be appreciable.

Body:
Try using viewport properties.

You can enable wide viewport mode with setUseWideViewPort().

You can define properties of the viewport for your web page, such as the width and initial zoom level, using the <meta name="viewport" ...> tag in your document <head>.

Check this tutorial for additional insights.


问:
Generate random string/characters in JavaScript
I want a 5 character string composed of characters picked randomly from the set [a-zA-Z0-9].

What's the best way to do this with JavaScript?

答:
How about something like this: Date.now().toString(36)
Not very random, but short and quite unique every time you call it.


问:
Android Paging Library when to request more items when doing an endless scrolling
How to know when to request the server for more items using the new android Paging Library of Architecture Components? For example, if I want to implement an endless scrolling where the data is loaded from server how do I know when I have to request more items. </p>

答:
I use next class for implementing this feature:

```<code>package com.mlsdev.enjoymusic.data.repository;

import android.arch.paging.DataSource;
import android.arch.paging.TiledDataSource;
import android.arch.persistence.room.InvalidationTracker;
import android.support.annotation.NonNull;
import android.support.annotation.WorkerThread;
import android.util.Log;

import com.mlsdev.enjoymusic.data.local.DeezerDatabase;
import com.mlsdev.enjoymusic.data.local.Table;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by stafievsky on 09.10.17.
 */

public abstract class PagedNetworkBoundResource<ResultType, RequestType> extends TiledDataSource<ResultType> {

    private final InvalidationTracker.Observer mObserver;
    private DeezerDatabase db;

    public PagedNetworkBoundResource(DeezerDatabase db) {
        this.db = db;
        mObserver = new InvalidationTracker.Observer(Table.States.PLAY_STATE) {

            public void onInvalidated(@NonNull Set<String> tables) {
                invalidate();
            }
        };
        this.db.getInvalidationTracker().addWeakObserver(mObserver);
    }

    @Override
    public boolean isInvalid() {
        db.getInvalidationTracker().refreshVersionsSync();
        return super.isInvalid();
    }

    @Override
    public int countItems() {
        return DataSource.COUNT_UNDEFINED;
    }

    @Override
    public List<ResultType> loadRange(int startPosition, int count) {
        if (startPosition == 0 && count == 20) {
            clearDB();
        }
        fetchFromNetwork(startPosition, count);
        return loadFromDb(startPosition, count);
    }

    public abstract void clearDB();

    @WorkerThread
    private void fetchFromNetwork(int startPosition, int count) {
        if (createCall(startPosition, count) != null)
            try {
                Response<RequestType> response = createCall(startPosition, count).execute();
                if (response.isSuccessful() && response.code() == 200) {
                    saveCallResult(response.body());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

    @WorkerThread
    protected abstract void saveCallResult(@NonNull RequestType item);

    @WorkerThread
    protected abstract List<ResultType> loadFromDb(int startPosition, int count);

    @WorkerThread
    protected abstract Call<RequestType> createCall(int startPosition, int count);
}
</code>```

And this implementation of this class:

```<code>public LiveData<PagedList<ChartAlbumDao.Album>> getAlbums() {

    return new LivePagedListProvider<Integer, ChartAlbumDao.Album>() {
        @Override
        protected DataSource<Integer, ChartAlbumDao.Album> createDataSource() {
            return new PagedNetworkBoundResource<ChartAlbumDao.Album, ModelList<ChartAlbumEntity>>(db) {

                @Override
                public void clearDB() {

                }

                @Override
                protected void saveCallResult(@NonNull ModelList<ChartAlbumEntity> item) {
                    if (item != null) {
                        chartAlbumDao.saveAlbums(item.getItems());
                    }
                }

                @NonNull
                @Override
                protected List<ChartAlbumDao.Album> loadFromDb(int startPosition, int count) {
                    return chartAlbumDao.loadAlbums(count, startPosition);
                }

                @NonNull
                @Override
                protected Call<ModelList<ChartAlbumEntity>> createCall(int startPosition, int count) {
                    return deezerService.getChartAlbums(startPosition, count);
                }
            };
        }

    }.create(0, new PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setPageSize(20)
            .setInitialLoadSizeHint(20)
            .build());
}
</code>```

Body:
I use next class for implementing this feature:

package com.mlsdev.enjoymusic.data.repository;

import android.arch.paging.DataSource;
import android.arch.paging.TiledDataSource;
import android.arch.persistence.room.InvalidationTracker;
import android.support.annotation.NonNull;
import android.support.annotation.WorkerThread;
import android.util.Log;

import com.mlsdev.enjoymusic.data.local.DeezerDatabase;
import com.mlsdev.enjoymusic.data.local.Table;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by stafievsky on 09.10.17.
 */

public abstract class PagedNetworkBoundResource<ResultType, RequestType> extends TiledDataSource<ResultType> {

    private final InvalidationTracker.Observer mObserver;
    private DeezerDatabase db;

    public PagedNetworkBoundResource(DeezerDatabase db) {
        this.db = db;
        mObserver = new InvalidationTracker.Observer(Table.States.PLAY_STATE) {

            public void onInvalidated(@NonNull Set<String> tables) {
                invalidate();
            }
        };
        this.db.getInvalidationTracker().addWeakObserver(mObserver);
    }

    @Override
    public boolean isInvalid() {
        db.getInvalidationTracker().refreshVersionsSync();
        return super.isInvalid();
    }

    @Override
    public int countItems() {
        return DataSource.COUNT_UNDEFINED;
    }

    @Override
    public List<ResultType> loadRange(int startPosition, int count) {
        if (startPosition == 0 && count == 20) {
            clearDB();
        }
        fetchFromNetwork(startPosition, count);
        return loadFromDb(startPosition, count);
    }

    public abstract void clearDB();

    @WorkerThread
    private void fetchFromNetwork(int startPosition, int count) {
        if (createCall(startPosition, count) != null)
            try {
                Response<RequestType> response = createCall(startPosition, count).execute();
                if (response.isSuccessful() && response.code() == 200) {
                    saveCallResult(response.body());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

    @WorkerThread
    protected abstract void saveCallResult(@NonNull RequestType item);

    @WorkerThread
    protected abstract List<ResultType> loadFromDb(int startPosition, int count);

    @WorkerThread
    protected abstract Call<RequestType> createCall(int startPosition, int count);
}

And this implementation of this class:

public LiveData<PagedList<ChartAlbumDao.Album>> getAlbums() {

    return new LivePagedListProvider<Integer, ChartAlbumDao.Album>() {
        @Override
        protected DataSource<Integer, ChartAlbumDao.Album> createDataSource() {
            return new PagedNetworkBoundResource<ChartAlbumDao.Album, ModelList<ChartAlbumEntity>>(db) {

                @Override
                public void clearDB() {

                }

                @Override
                protected void saveCallResult(@NonNull ModelList<ChartAlbumEntity> item) {
                    if (item != null) {
                        chartAlbumDao.saveAlbums(item.getItems());
                    }
                }

                @NonNull
                @Override
                protected List<ChartAlbumDao.Album> loadFromDb(int startPosition, int count) {
                    return chartAlbumDao.loadAlbums(count, startPosition);
                }

                @NonNull
                @Override
                protected Call<ModelList<ChartAlbumEntity>> createCall(int startPosition, int count) {
                    return deezerService.getChartAlbums(startPosition, count);
                }
            };
        }

    }.create(0, new PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setPageSize(20)
            .setInitialLoadSizeHint(20)
            .build());
}


问:
Upload Multiple images to mysql database
I relatively new to PHP. I need to upload multiple images to the database with one button tap. this is the code. I understand that I have to add a foreach loop to go through each image individually(insert the images individually) but I can't seem to find the right place to insert the for each loop. Any answers would be very much appreciated.

```<code><?php

    error_reporting( ~E_NOTICE ); // avoid notice

    require_once 'dbconfig.php';

    if(isset($_POST['btnsave']))
    {
        $carname = $_POST['car_name'];// car name
        $carmodel = $_POST['car_model'];// car model
        $caramount = $_POST['car_amount'];// car amount

        $imgFile = $_FILES['car_image']['name'];
        $tmp_dir = $_FILES['car_image']['tmp_name'];
        $imgSize = $_FILES['car_image']['size'];

        if(empty($carname)){
            $errMSG = "Please Enter Name of the Car.";
        }
        else if(empty($carmodel)){
            $errMSG = "Please Enter Model Number of the car.";
        }
        else if(empty($caramount)){
            $errMSG = "Please Enter the cost of the car.";
        }
        else if(empty($imgFile)){
            $errMSG = "Please Select Image File.";
        }
        else
        {

            $upload_dir = 'user_images/'; // upload directory

            $imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension

            // valid image extensions
            $valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions

            // rename uploading image
            $carpic = rand(1000,1000000).".".$imgExt;

            // allow valid image file formats
            if(in_array($imgExt, $valid_extensions)){
                // Check file size '5MB'
                if($imgSize < 5000000)                {
                    move_uploaded_file($tmp_dir,$upload_dir.$carpic);
                }
                else{
                    $errMSG = "Sorry, your file is too large.";
                }
            }
            else{
                $errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            }
        }

        // if no error occured, continue ....
        if(!isset($errMSG))
        {
            $stmt = $DB_con->prepare('INSERT INTO tbl_cars(carName,carModel,carAmount,carPic) VALUES(:cname, :cmodel, :camount, :cpic)');
            $stmt->bindParam(':cname',$carname);
            $stmt->bindParam(':cmodel',$carmodel);
            $stmt->bindParam(':camount',$caramount);
            $stmt->bindParam(':cpic',$carpic);
            if($stmt->execute())
            {
                $successMSG = "new record succesfully inserted ...";
                header("refresh:5;car_display.php"); // redirects image view page after 5 seconds.
            }
            else
            {
                $errMSG = "error while inserting....";
            }
        }
    }
?>
</code>```

I know I need to add a simple for each loop, execution is failing me.
Somebody Save Me

This is the HTML bit that uploads

```<code> <tr>
        <td><label class="control-label">Car Img.</label></td>
        <td><input class="input-group" type="file" name="car_image" multiple="multiple" accept="image/*" /></td>
</code>```

答:
You need to specify in html that is it will be an array of files
and then call the foreach in your php, basically the post will be an array.

My example is not using PDO or adapted to your example but it is working in uploading multiple files.

PHP:

```<code><?php
if(isset($_FILES['files'])){
    $errors= array();
    foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
        $file_name = $key.$_FILES['files']['name'][$key];
        $file_size =$_FILES['files']['size'][$key];
        $file_tmp =$_FILES['files']['tmp_name'][$key];
        $file_type=$_FILES['files']['type'][$key];
        if($file_size > 2097152){
            $errors[]='File size must be less than 2 MB';
        }
        $query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
        $desired_dir="user_data";
        if(empty($errors)==true){
            if(is_dir($desired_dir)==false){
                mkdir("$desired_dir", 0700);        // Create directory if it does not exist
            }
            if(is_dir("$desired_dir/".$file_name)==false){
                move_uploaded_file($file_tmp,"user_data/".$file_name);
            }else{                                  //rename the file if another one exist
                $new_dir="user_data/".$file_name.time();
                 rename($file_tmp,$new_dir) ;
            }
            mysql_query($query);
        }else{
                print_r($errors);
        }
    }
    if(empty($error)){
        echo "Success";
    }
}
?>
</code>```

HTML

```<code><form action="yourphpfile.php" method="POST" enctype="multipart/form-data">
    <input type="file" name="files[]" multiple="" />
    <input type="submit"/>
</form>
</code>```

Body:
I relatively new to PHP. I need to upload multiple images to the database with one button tap. this is the code. I understand that I have to add a foreach loop to go through each image individually(insert the images individually) but I can't seem to find the right place to insert the for each loop. Any answers would be very much appreciated.

<?php

    error_reporting( ~E_NOTICE ); // avoid notice

    require_once 'dbconfig.php';

    if(isset($_POST['btnsave']))
    {
        $carname = $_POST['car_name'];// car name
        $carmodel = $_POST['car_model'];// car model
        $caramount = $_POST['car_amount'];// car amount

        $imgFile = $_FILES['car_image']['name'];
        $tmp_dir = $_FILES['car_image']['tmp_name'];
        $imgSize = $_FILES['car_image']['size'];

        if(empty($carname)){
            $errMSG = "Please Enter Name of the Car.";
        }
        else if(empty($carmodel)){
            $errMSG = "Please Enter Model Number of the car.";
        }
        else if(empty($caramount)){
            $errMSG = "Please Enter the cost of the car.";
        }
        else if(empty($imgFile)){
            $errMSG = "Please Select Image File.";
        }
        else
        {

            $upload_dir = 'user_images/'; // upload directory

            $imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension

            // valid image extensions
            $valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions

            // rename uploading image
            $carpic = rand(1000,1000000).".".$imgExt;

            // allow valid image file formats
            if(in_array($imgExt, $valid_extensions)){
                // Check file size '5MB'
                if($imgSize < 5000000)                {
                    move_uploaded_file($tmp_dir,$upload_dir.$carpic);
                }
                else{
                    $errMSG = "Sorry, your file is too large.";
                }
            }
            else{
                $errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            }
        }

        // if no error occured, continue ....
        if(!isset($errMSG))
        {
            $stmt = $DB_con->prepare('INSERT INTO tbl_cars(carName,carModel,carAmount,carPic) VALUES(:cname, :cmodel, :camount, :cpic)');
            $stmt->bindParam(':cname',$carname);
            $stmt->bindParam(':cmodel',$carmodel);
            $stmt->bindParam(':camount',$caramount);
            $stmt->bindParam(':cpic',$carpic);
            if($stmt->execute())
            {
                $successMSG = "new record succesfully inserted ...";
                header("refresh:5;car_display.php"); // redirects image view page after 5 seconds.
            }
            else
            {
                $errMSG = "error while inserting....";
            }
        }
    }
?>

I know I need to add a simple for each loop, execution is failing me.
Somebody Save Me

This is the HTML bit that uploads

        Car Img.
        <input class="input-group" type="file" name="car_image" multiple="multiple" accept="image/*" />

Body:
You need to specify in html that is it will be an array of files
and then call the foreach in your php, basically the post will be an array.

My example is not using PDO or adapted to your example but it is working in uploading multiple files.

PHP:

<?php
if(isset($_FILES['files'])){
    $errors= array();
    foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
        $file_name = $key.$_FILES['files']['name'][$key];
        $file_size =$_FILES['files']['size'][$key];
        $file_tmp =$_FILES['files']['tmp_name'][$key];
        $file_type=$_FILES['files']['type'][$key];
        if($file_size > 2097152){
            $errors[]='File size must be less than 2 MB';
        }
        $query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
        $desired_dir="user_data";
        if(empty($errors)==true){
            if(is_dir($desired_dir)==false){
                mkdir("$desired_dir", 0700);        // Create directory if it does not exist
            }
            if(is_dir("$desired_dir/".$file_name)==false){
                move_uploaded_file($file_tmp,"user_data/".$file_name);
            }else{                                  //rename the file if another one exist
                $new_dir="user_data/".$file_name.time();
                 rename($file_tmp,$new_dir) ;
            }
            mysql_query($query);
        }else{
                print_r($errors);
        }
    }
    if(empty($error)){
        echo "Success";
    }
}
?>

HTML

<form action="yourphpfile.php" method="POST" enctype="multipart/form-data">
    <input type="file" name="files[]" multiple="" />
    <input type="submit"/>
</form>


问:
Checking a column with two attributes
I have list of names that have either one checking account and/or one saving account linked to their direct deposit. 22 means checking and 32 means savings.

If they have just a checking account (22) or just a savings account (32) in the column then I want to have a '100%' in the column next to it. However, if a person has a checking and a savings account, I want to leave it blank. (We have to manually look in another software for the information)

Example

Employee #   Account      Allocated %
 100          22

 100          32

 101          22              100
 102          32              100

How would I go about this?

答:
A real simple way to do this is like this:

```<code>SELECT *, CASE WHEN
    (SELECT COUNT(*) FROM Accounts WHERE EmpNo = A.EmpNo) = 1
     THEN 100 ELSE NULL END AS Allocation FROM Accounts A
</code>```

This does not check for 22 or 32 status. It's simply seeing if they have more then one type of account. This is probably the most straightforward way, assuming your logic is they have more than one account, then it needs to be 100.

Here is a sample fiddle.

Title: Checking a column with two attributes

Body:
A real simple way to do this is like this:

SELECT *, CASE WHEN
    (SELECT COUNT(*) FROM Accounts WHERE EmpNo = A.EmpNo) = 1
     THEN 100 ELSE NULL END AS Allocation FROM Accounts A

This does not check for 22 or 32 status. It's simply seeing if they have more then one type of account. This is probably the most straightforward way, assuming your logic is they have more than one account, then it needs to be 100.

Here is a sample fiddle.


问:
Is manually managing memory with .unpersist() a good idea?
I've read a lot of questions and answers here about unpersist() on dataframes. I so far haven't found an answer to this question:

In Spark, once I am done with a dataframe, is it a good idea to call .unpersist() to manually force that dataframe to be unpersisted from memory, as opposed to waiting for GC (which is an expensive task)? In my case I am loading many dataframes so that I can perform joins and other transformations.

So, for example, if I wish to load and join 3 dataframes A, B and C:
I load dataframe A and B, join these two to create X, and then .unpersist() B because I don't need it any more (but I will need A), and could use the memory to load C (which is big). So then I load C, and join C to X, .unpersist() on C so I have more memory for the operations I will now perform on X and A.

I understand that GC will unpersist for me eventually, but I also understand than GC is an expensive task that should be avoided if possible. To re-phrase my question: Is this an appropriate method of manually managing memory, to optimise my spark jobs?

My understanding (please correct if wrong):

I understand that .unpersist() is a very cheap operation.

I understand that GC calls .unpersist() on my dataframes eventually anyway.

I understand that spark monitors cache and drops based on Last Recently Used policy. But in some cases I do not want the 'Last Used' DF to be dropped, so instead I can call.unpersist() on the datafames I know I will not need in future, so that I don't drop the DFs I will need and have to reload them later.

To re-phrase my question again if unclear: is this an appropriate use of .unpersist(), or should I just let Spark and GC do their job?

Thanks in advance :)

答:
There seem to be some misconception. While using unpersist is a valid approach to get better control over the storage, it doesn't avoid garbage collection. In fact all the on heap objects associated with cached data will be left garbage collector.

So while operation itself is relatively cheap, chain of events it triggers might not be cheap. Luckily explicit persist is not worse than waiting for automatic cleaner or GC triggered cleaner, so if you want to clean specific objects, go ahead and do it.

To limit GC on unpersist it might be worth to take a look at the OFF_HEAP StorageLevel.


问:
IndexOutOfBound error with string manipulation
this is the code for a pig-latin translator in JAVA, it works with one word but never with a sentence. It seems that the code at line 30 is messing everything up, and I'm not sure how it is doing that or how I can fix it. IndexOutOfBoundError on line 8 and line 30. I'm not sure how to fix this, help.</p>

```<code>    public class Practice
    {
        public static void main(String[] args)
        {
            String a = "hello Stranger";

        System.out.println(translate(a)); //8
    }

    private static String translate(String a)
    {
        String XD = a;
        boolean repeat = true;
        int first = 1;
        int second = 0;

        do
        {
            second = XD.indexOf(" ");

            if (second == -1)
            {
                repeat = false;
                XD = vowelFinder(a);
                break;
            }
            else
            {
              XD = XD + vowelFinder(a.substring(first, second)); //30
            }

            first = second +1;
        }while(repeat == true);

        return XD;
    }

    private static boolean isVowel (char c)
    {
        if (c == 'a'|| c== 'e'|| c== 'i' || c == 'o' || c== 'u')
        {
            return true;
        }

        return false;
    }

    private static String vowelFinder(String s)
    {
        String nope = s;

        for(int i = 0; i <= s.length(); i++)
        {
            if(isVowel(s.charAt(i)) == true)
            {
                nope = nope.substring(i) + "-"+nope.substring(0, i);`
                return nope;
            }
        }

        return nope;
    }

}
</code>```

答:
Try this;</p>

```<code>import java.util.Scanner;

public class PigLatin {
    public static void main(String[] args) {
        Scanner input = new Scanner( System.in );
        String yourSentence="";
        do {
            String[] words;
            System.out.print("Enter your words here: ");
            yourSentence = input.nextLine();
            words = yourSentence.split(" ");
            for (String word : words) {
                if (word.startsWith("a") || word.startsWith("e") || word.startsWith("i") || word.startsWith("o") || word.startsWith("u"))
                    System.out.print(word + "way ");
                else if (word.startsWith("sh") || word.startsWith("ch") || word.startsWith("th"))
                    System.out.print(word.substring(2)+word.substring(0,2)+"ay ");
                else
                    System.out.print(word.substring(1)+word.substring(0,1)+"ay ");
        }
        System.out.println();
        } while(!yourSentence.equals("quit"));
    }
}
</code>```

Body:
this is the code for a pig-latin translator in JAVA, it works with one word but never with a sentence. It seems that the code at line 30 is messing everything up, and I'm not sure how it is doing that or how I can fix it. IndexOutOfBoundError on line 8 and line 30. I'm not sure how to fix this, help.

    public class Practice
    {
        public static void main(String[] args)
        {
            String a = "hello Stranger";

        System.out.println(translate(a)); //8
    }

    private static String translate(String a)
    {
        String XD = a;
        boolean repeat = true;
        int first = 1;
        int second = 0;

        do
        {
            second = XD.indexOf(" ");

            if (second == -1)
            {
                repeat = false;
                XD = vowelFinder(a);
                break;
            }
            else
            {
              XD = XD + vowelFinder(a.substring(first, second)); //30
            }

            first = second +1;
        }while(repeat == true);

        return XD;
    }

    private static boolean isVowel (char c)
    {
        if (c == 'a'|| c== 'e'|| c== 'i' || c == 'o' || c== 'u')
        {
            return true;
        }

        return false;
    }

    private static String vowelFinder(String s)
    {
        String nope = s;

        for(int i = 0; i <= s.length(); i++)
        {
            if(isVowel(s.charAt(i)) == true)
            {
                nope = nope.substring(i) + "-"+nope.substring(0, i);`
                return nope;
            }
        }

        return nope;
    }

}

Body:
Try this;

import java.util.Scanner;

public class PigLatin {
    public static void main(String[] args) {
        Scanner input = new Scanner( System.in );
        String yourSentence="";
        do {
            String[] words;
            System.out.print("Enter your words here: ");
            yourSentence = input.nextLine();
            words = yourSentence.split(" ");
            for (String word : words) {
                if (word.startsWith("a") || word.startsWith("e") || word.startsWith("i") || word.startsWith("o") || word.startsWith("u"))
                    System.out.print(word + "way ");
                else if (word.startsWith("sh") || word.startsWith("ch") || word.startsWith("th"))
                    System.out.print(word.substring(2)+word.substring(0,2)+"ay ");
                else
                    System.out.print(word.substring(1)+word.substring(0,1)+"ay ");
        }
        System.out.println();
        } while(!yourSentence.equals("quit"));
    }
}


问:
trying to make query with registers with comma separated
I have a table with these structure:

```<code>Field A     FieldB                  FieldC
material    clay,rush
material    air
metal       iron
metal       gold,silver,aluminium
</code>```

What I need to do is fill in the C field. For this I have to make a query like:

```<code>select xxxxx from yyyyy where jjjjj in (material, clay, rush)
select xxxxx from yyyyy where jjjjj in (material, air)
select xxxxx from yyyyy where jjjjj in (metal, iron)
select xxxxx from yyyyy where jjjjj in (metal, gold, silver, aluminum)
</code>```

yyyy is another table.

Is possible to make these with pl/sql Oracle? I've been trying but I'm not capable, it seems a bit confusing. Thanks and regards,

答:
This will work fo you </p>

```<code>DECLARE
l_query VARCHAR(500);
BEGIN
    FOR i in (SELECT FiledA, FiledB, FiledA||','||FiledB  AS  FiledC FROM test)
    LOOP
        l_query :=  'SELECT xxxxx FROM yyyyy WHERE jjjjj IN ';
        l_query := l_query||'('||i.FiledC||')';
        UPDATE  test
           SET FiledC = l_query
        WHERE FiledA = i.FiledA
          AND FiledB = i.FiledB;
        l_query := NULL;
    END LOOP;
    COMMIT;
END;
/
</code>```

Body:
I have a table with these structure:

Field A     FieldB                  FieldC
material    clay,rush
material    air
metal       iron
metal       gold,silver,aluminium

What I need to do is fill in the C field. For this I have to make a query like:

select xxxxx from yyyyy where jjjjj in (material, clay, rush)
select xxxxx from yyyyy where jjjjj in (material, air)
select xxxxx from yyyyy where jjjjj in (metal, iron)
select xxxxx from yyyyy where jjjjj in (metal, gold, silver, aluminum)

yyyy is another table.

Is possible to make these with pl/sql Oracle? I've been trying but I'm not capable, it seems a bit confusing. Thanks and regards,

Body:
This will work fo you

DECLARE
l_query VARCHAR(500);
BEGIN
    FOR i in (SELECT FiledA, FiledB, FiledA||','||FiledB  AS  FiledC FROM test)
    LOOP
        l_query :=  'SELECT xxxxx FROM yyyyy WHERE jjjjj IN ';
        l_query := l_query||'('||i.FiledC||')';
        UPDATE  test
           SET FiledC = l_query
        WHERE FiledA = i.FiledA
          AND FiledB = i.FiledB;
        l_query := NULL;
    END LOOP;
    COMMIT;
END;
/


问:
Automatic Scrolling to current date in timelineWeek view using fullcalendar
I am using Rails 4 and fullCalendar and want to achieve the following functionality:

Use timelineWeek view to automatically scroll my "now" indicator to the current datetime. I have all my Resources on my Y-axis. I'm having a problem in achieving this functionality with timelineWeek view. Can anyone help?

I have tried the following code for it, but no progress:

```<code>var firstHour = new Date().getUTCHours() - 5;
$('#calendar').fullCalendar({
  firstHour: firstHour;
});
</code>```

And also used this:

```<code>setTimeout(function(){ // Timeout
    $(".fc-today").attr("id","scrollTo"); // Set an ID for the current day..
    $("html, body").animate({
        scrollTop: $("#scrollTo").offset().top // Scroll to this ID
    }, 2000);
}, 500);
</code>```

and this:

```<code>$('#calendar').fullCalendar('today');
</code>```

The above code works perfectly for agendaWeek view. The only problem is for timelineWeek view.

答:
I've figured out a way to do this, maybe it is possible to do some other way.

I decided to put scrolling in viewRender function, since it is called on both initial load and changing dates.

Now firstly I check if current time is in my view and we have slot width set.
Then calculate how many slots until the current slot and calculate left scroll. Modify it by your needs: e.g. I wanted to have it to show yesterday on load at far left.

```<code>if (moment().isBetween(view.start, view.end) && view.timeGrid.slotWidth !== undefined) {
    var scrollSlots = moment.duration(moment() - view.start) / moment.duration(view.viewSpec.overrides.slotDuration);
    var slotWidth = view.timeGrid.slotWidth;
    var scroll = {left: scrollSlots * slotWidth - $('.fc-time-area').width() / 4};
    view.addScroll(scroll);
}
</code>```

End result: on load (cropped out resources). This is month view with 200 slotWidth.

Body:
I am using Rails 4 and fullCalendar and want to achieve the following functionality:

Use timelineWeek view to automatically scroll my "now" indicator to the current datetime. I have all my Resources on my Y-axis. I'm having a problem in achieving this functionality with timelineWeek view. Can anyone help?

I have tried the following code for it, but no progress:

var firstHour = new Date().getUTCHours() - 5;
$('#calendar').fullCalendar({
  firstHour: firstHour;
});

And also used this:

setTimeout(function(){ // Timeout
    $(".fc-today").attr("id","scrollTo"); // Set an ID for the current day..
    $("html, body").animate({
        scrollTop: $("#scrollTo").offset().top // Scroll to this ID
    }, 2000);
}, 500);

and this:

$('#calendar').fullCalendar('today');

The above code works perfectly for agendaWeek view. The only problem is for timelineWeek view.

Body:
I've figured out a way to do this, maybe it is possible to do some other way.

I decided to put scrolling in viewRender function, since it is called on both initial load and changing dates.

Now firstly I check if current time is in my view and we have slot width set.
Then calculate how many slots until the current slot and calculate left scroll. Modify it by your needs: e.g. I wanted to have it to show yesterday on load at far left.

if (moment().isBetween(view.start, view.end) && view.timeGrid.slotWidth !== undefined) {
    var scrollSlots = moment.duration(moment() - view.start) / moment.duration(view.viewSpec.overrides.slotDuration);
    var slotWidth = view.timeGrid.slotWidth;
    var scroll = {left: scrollSlots * slotWidth - $('.fc-time-area').width() / 4};
    view.addScroll(scroll);
}

End result: on load (cropped out resources). This is month view with 200 slotWidth.


问:
Vertically aligned content in segment (Semantic UI)
Is there a way to center vertically a content inside a segment class div? I've got the following markup:

```<code><div class="stretched row">
  <div class="two wide column">
    <div class="ui basic segment">
      <select>
        <!-- OPTION VALUES IN HERE -->
      </select>
    </div>
  </div>
  <div class="column">
    <div class="ui basic segment>
     <!-- DIV CONTENT -->
    </div>
  </div>
  <div class="column">
    <div class="ui basic segment">
      <!-- DIV CONTENT -->
    </div>
  </div>
</code>```

Now, thanks to the stretched row class, all 3 columns have the same height, and so do the segment divs inside them, looking like this:

I'd like that the content inside the 3 segments was vertically centered inside of them. Instead, they always appear at the top. I've tried adding class="ui middle aligned basic segment" but it doesn't work. Adding class="middle aligned column" to the parent columns center the segment inside of them but they don't take up all the vertical space of the column and, as they have border and colored background, it looks odd (each segment has its own height).

I'd like to avoid adding padding to the segments, because I don't know the heights of them and its content varies from 1 line (a select) to several lines of text (from 2 to 7 lines, depending on what the user selects).

Thanks!

答: As @VXp suggested, applying {display: flex; align-items: center} to the segment class worked perfectly.

Body:
Is there a way to center vertically a content inside a segment class div? I've got the following markup:

      <select>

      </select>

Now, thanks to the stretched row class, all 3 columns have the same height, and so do the segment divs inside them, looking like this:

I'd like that the content inside the 3 segments was vertically centered inside of them. Instead, they always appear at the top. I've tried adding class="ui middle aligned basic segment" but it doesn't work. Adding class="middle aligned column" to the parent columns center the segment inside of them but they don't take up all the vertical space of the column and, as they have border and colored background, it looks odd (each segment has its own height).

I'd like to avoid adding padding to the segments, because I don't know the heights of them and its content varies from 1 line (a select) to several lines of text (from 2 to 7 lines, depending on what the user selects).

Thanks!


问:
New version of entity framework designer
I've seen in this article
http://blogs.msdn.com/b/efdesign/archive/2010/10/11/entity-designer-improvements-preview.aspx
that a new version of entity framework designer is planned.

Does anyone know when this one would be released ?

Thank's by advance.

答: It will be shipped only with the next version of VS, because of new recently added features of the the product are either not reflected in VS shipping plan or in VS2010 SP1, because it will require some FW support just like new cx0++ features drafts.</p>


问:
Check whether an array contains some data
I have 2 variables,  users and friend inside a component

Variable users is an array. Each iteration contains id, name and email

Variable friend have same structure in addition to pivot.

In my components file (.vue file), I need to check whether users contains friend without using loops so that I can use it inside the v-if condition.

Note: email and id are unique values.

How can I check it? Single line code will be very helpful.

Eg:

users have 2 iterations

id: 1

name: First

email: first@example.com

id: 2

name: Second

email: second@example.com

friend is like this

id: 2

name: Second

email: second@example.com

pivot: {...}

答:
Try using v-if:

```<code><div v-if=":user.friend"></div>
</code>```

Body:
Try using v-if:

<div v-if=":user.friend"></div>


问:
How do I maintain the formatting of text in a cell in an Excel spreadsheet when importing into R markdown?
I have an .xlsx file in which some of the cells have boldface numbers and some have italicized numbers. I am using read_xlsx to read the .xlsx file into R and then using kable to present it with this code:

```<code>knitr::kable(spreadsheet, format="latex", booktabs = T) %>%
kable_styling(latex_options = c("striped"))
</code>```

I cannot get the boldface and italics numbers from the .xlsx to stay boldface and italicized when they appear in the .pdf generated from the .Rmd file. How do I do this?

答:
In answer to your question, you cannot maintain the formattting, but you can replicate it.

When the read_xlsx() function is run, it extracts the data from the cells but does not retain any of the formatting. As a result, any bold font will not be automatically transferred to R.

The easiest way of achieving what you want would be to add the bold text after you have loaded the data into R. The kableExtra is perfect for doing such things. Here is an example, using the column_spec and row_spec functions to change the format of the cells:

```<code>```{r}
library(kableExtra)

knitr::kable(iris[1:5,], format = "latex", booktab = TRUE) %>%
  column_spec(1, bold = T) %>%
  row_spec(0, bold = T, color = "red")

```
</code>```

You can customise a number of properties (run ?row_specto load the helper):

Font size

Alignment

Text Angle

Text Colour

Background Colour

If you need more fine tuning of cell formatting to specific cells, you can investigate the cell_spec function.

View the full guidance for customising LaTeX tables here: https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf

Body:
I have an .xlsx file in which some of the cells have boldface numbers and some have italicized numbers. I am using read_xlsx to read the .xlsx file into R and then using kable to present it with this code:

knitr::kable(spreadsheet, format="latex", booktabs = T) %>%
kable_styling(latex_options = c("striped"))

I cannot get the boldface and italics numbers from the .xlsx to stay boldface and italicized when they appear in the .pdf generated from the .Rmd file. How do I do this?

Body:
In answer to your question, you cannot maintain the formattting, but you can replicate it.

When the read_xlsx() function is run, it extracts the data from the cells but does not retain any of the formatting. As a result, any bold font will not be automatically transferred to R.

The easiest way of achieving what you want would be to add the bold text after you have loaded the data into R. The kableExtra is perfect for doing such things. Here is an example, using the column_spec and row_spec functions to change the format of the cells:

```{r}
library(kableExtra)

knitr::kable(iris[1:5,], format = "latex", booktab = TRUE) %>%
  column_spec(1, bold = T) %>%
  row_spec(0, bold = T, color = "red")

```

You can customise a number of properties (run ?row_specto load the helper):

Font size

Alignment

Text Angle

Text Colour

Background Colour

If you need more fine tuning of cell formatting to specific cells, you can investigate the cell_spec function.

View the full guidance for customising LaTeX tables here: https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf


问:
Escape of Escape character not accepted (Java and MySQL)
I have a statement for MySQL 5.5.58-0+deb8u1 that looks like this:

```<code>UPDATE `general` SET `CUSTOMER_NUMBER` = 'null', `MAINTENANCE_CONTRACT_NR` = '5678', `CONTACT1_NAME` =  + 'ss\' where `general`.`uuid` = '06f8417b-c865-11e7-9a86-000c2924bf92'
</code>```

I try to escape the \ (after ss) with

```<code>string statementEsc = statement.replace('\\', '\\\\');
</code>```

this results in:

```<code>UPDATE `general` SET `CUSTOMER_NUMBER` = 'null', `MAINTENANCE_CONTRACT_NR` = '5678', `CONTACT1_NAME` =  + 'ss\\' where `general`.`uuid` = '06f8417b-c865-11e7-9a86-000c2924bf92'
</code>```

When trying the query manually, MySQL accepts this query, but the program gives an error

MySQL JDBC Driver Registered
Problem occured at executeUpdate operation : com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ss\', `...at line 1
SQL UPDATE operation has been failed: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ss\', ... = '' at line 1.

I don't understand why.

答: Though using PreparedStatement is best answer, try going through this class StringEscapeUtils. It have methods for Escapes and unescapes Strings for Java, Java Script, HTML, XML, and SQL.</p>

Body:
I have a statement for MySQL 5.5.58-0+deb8u1 that looks like this:

UPDATE `general` SET `CUSTOMER_NUMBER` = 'null', `MAINTENANCE_CONTRACT_NR` = '5678', `CONTACT1_NAME` =  + 'ss\' where `general`.`uuid` = '06f8417b-c865-11e7-9a86-000c2924bf92'

I try to escape the \ (after ss) with

string statementEsc = statement.replace('\\', '\\\\');

this results in:

UPDATE `general` SET `CUSTOMER_NUMBER` = 'null', `MAINTENANCE_CONTRACT_NR` = '5678', `CONTACT1_NAME` =  + 'ss\\' where `general`.`uuid` = '06f8417b-c865-11e7-9a86-000c2924bf92'

When trying the query manually, MySQL accepts this query, but the program gives an error

MySQL JDBC Driver Registered
Problem occured at executeUpdate operation : com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ss\', `...at line 1
SQL UPDATE operation has been failed: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ss\', ... = '' at line 1.

I don't understand why.


问:
req.body is empty in POST express nodejs
Below is my code for HTML form to post data on server side.

HTML Code:

```<code><form action="/Device_Data" method="post">
    <select name="deviceSelect" id="deviceSelect" class="selectdevice" type = "text" style="margin-top:1.5%">
        <option value="" selected="selected">Choose Device</option>
        <option value="Device1">Device 1</option>
        <option value="Device2">Device 2</option>
        <option value="Device3">Device 3</option>
        <option value="Device4">Device 4</option>
        <option value="Device5">Device 5</option>
        <option value="Device6">Device 6</option>
        <option value="Device7">Device 7</option>
        <option value="Device8">Device 8</option>
    </select>
    <button id="Import" value="Import" class="button1" type="button" formenctype="text/plain">Import</button>
</form>
</code>```

Server code:

```<code>var express = require('express');
//require the body-parser nodejs module
var bodyParser = require('body-parser');
var path = require('path');
var qs = require('querystring');
var app = express();
// var server = http.createServer(app);

//support parsing of application/json type post data
app.use(bodyParser.json());

//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: false }));

app.post("/Device_Data", function (req, res) {

  // result.entries contains entities matching the query
 //res.setHeader('Content-Type', 'application/json');
  console.log(req.body);
  res.send(200, req.body);
});
</code>```

Output:

```<code>{}
Thu, 16 Nov 2017 14:05:13 GMT express deprecated res.send(status, body): Use res.status(status).send(body) instead at server.js:122:7
</code>```

Can anyone help me?
Thanks in advance.

I just want to print the req.body data.

答:
Just like the error says, using the syntax res.send(status, body): is deprecated.

Change your following code:

```<code>res.send(200, req.body);
</code>```

To:

```<code>res.status(200).send(req.body);
</code>```

For more information see:
http://expressjs.com/en/api.html

Body:
Below is my code for HTML form to post data on server side.

HTML Code:

<form action="/Device_Data" method="post">
    <select name="deviceSelect" id="deviceSelect" class="selectdevice" type = "text" style="margin-top:1.5%">
        <option value="" selected="selected">Choose Device</option>
        <option value="Device1">Device 1</option>
        <option value="Device2">Device 2</option>
        <option value="Device3">Device 3</option>
        <option value="Device4">Device 4</option>
        <option value="Device5">Device 5</option>
        <option value="Device6">Device 6</option>
        <option value="Device7">Device 7</option>
        <option value="Device8">Device 8</option>
    </select>
    <button id="Import" value="Import" class="button1" type="button" formenctype="text/plain">Import</button>
</form>

Server code:

var express = require('express');
//require the body-parser nodejs module
var bodyParser = require('body-parser');
var path = require('path');
var qs = require('querystring');
var app = express();
// var server = http.createServer(app);

//support parsing of application/json type post data
app.use(bodyParser.json());

//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: false }));

app.post("/Device_Data", function (req, res) {

  // result.entries contains entities matching the query
 //res.setHeader('Content-Type', 'application/json');
  console.log(req.body);
  res.send(200, req.body);
});

Output:

{}
Thu, 16 Nov 2017 14:05:13 GMT express deprecated res.send(status, body): Use res.status(status).send(body) instead at server.js:122:7

Can anyone help me?
Thanks in advance.

I just want to print the req.body data.

Body:
Just like the error says, using the syntax res.send(status, body): is deprecated.

Change your following code:

res.send(200, req.body);

To:

res.status(200).send(req.body);

For more information see:
http://expressjs.com/en/api.html


问:
How to get audio feild of wordpress toolset types plugin
I am using Toolset Types for custom fields

I am trying to get audio field of product

using

```<code>types_render_field( "slig-name", array("output" => "html") )
</code>```

and

```<code>types_render_field( "slig-name", array() )
</code>```

getting audio player & text of audio file URL

I need only audio player

Thanks in advance for help

答:
This should give you the audio file URL:

```<code>$attachment_id = types_render_field('slug-name', array('raw'=>'true'));
$fileurl = wp_get_attachment_url($attachment_id);
</code>```

Which you could then pass to an audio player or standard embed shortcode.

Source

Body:
I am using Toolset Types for custom fields

I am trying to get audio field of product

using

types_render_field( "slig-name", array("output" => "html") )

and

types_render_field( "slig-name", array() )

getting audio player & text of audio file URL

I need only audio player

Thanks in advance for help

Body:
This should give you the audio file URL:

$attachment_id = types_render_field('slug-name', array('raw'=>'true'));
$fileurl = wp_get_attachment_url($attachment_id);

Which you could then pass to an audio player or standard embed shortcode.

Source


问:
Pointers sent to function
I have following code in main():

```<code>msgs, err := ch.Consume(
        q.Name, // queue
        //..
    )

    cache := ttlru.New(100, ttlru.WithTTL(5 * time.Minute)) //Cache type

    //log.Println(reflect.TypeOf(msgs)) 'chan amqp.Delivery'

    go func() {
       //here I use `cache` and `msgs` as closures. And it works fine.
    }
</code>```

I decided to create separate function for instead of anonymous.

I declared it as func hitCache(cache *ttlru.Cache, msgs *chan amqp.Delivery) {

I get compile exception:

```<code>./go_server.go:61: cannot use cache (type ttlru.Cache) as type *ttlru.Cache in argument to hitCache:
    *ttlru.Cache is pointer to interface, not interface
./go_server.go:61: cannot use msgs (type <-chan amqp.Delivery) as type *chan amqp.Delivery in argument to hitCache
</code>```

Question: How should I pass msg and cache into the new function?

答:
Well, if the receiving variable or a function parameter expects a value
of type *T — that is, "a pointer to T",
and you have a variable of type T, to get a pointer to it,
you have to get the address of that variable.
That's because "a pointer" is a value holding an address.

The address-taking operator in Go is &, so you need something like

```<code>hitCache(&cache, &msgs)
</code>```

But note that some types have so-called "reference semantics".
That is, values of them keep references to some "hidden" data structure.
That means when you copy such values, you're copying references which all reference the same data structure.

In Go, the built-in types maps, slices and channels have reference semantics,
and hence you almost never need to pass around pointers to the values of such types (well, sometimes it can be useful but not now).

Interfaces can be thought of to have reference semantics, too (let's not for now digress into discussing this) because each value of any interface type contains two pointers.

So, in your case it's better to merely not declare the formal parameters of your function as pointers — declare them as "plain" types and be done with it.

All in all, you should definitely complete some basic resource on Go which explains these basic matters in more detail and more extensively.

Title: Pointers sent to function

Body:
I have following code in main():

msgs, err := ch.Consume(
        q.Name, // queue
        //..
    )

    cache := ttlru.New(100, ttlru.WithTTL(5 * time.Minute)) //Cache type

    //log.Println(reflect.TypeOf(msgs)) 'chan amqp.Delivery'

    go func() {
       //here I use `cache` and `msgs` as closures. And it works fine.
    }

I decided to create separate function for instead of anonymous.

I declared it as func hitCache(cache *ttlru.Cache, msgs *chan amqp.Delivery) {

I get compile exception:

./go_server.go:61: cannot use cache (type ttlru.Cache) as type *ttlru.Cache in argument to hitCache:
    *ttlru.Cache is pointer to interface, not interface
./go_server.go:61: cannot use msgs (type <-chan amqp.Delivery) as type *chan amqp.Delivery in argument to hitCache

Question: How should I pass msg and cache into the new function?

Body:
Well, if the receiving variable or a function parameter expects a value
of type *T — that is, "a pointer to T",
and you have a variable of type T, to get a pointer to it,
you have to get the address of that variable.
That's because "a pointer" is a value holding an address.

The address-taking operator in Go is &, so you need something like

hitCache(&cache, &msgs)

But note that some types have so-called "reference semantics".
That is, values of them keep references to some "hidden" data structure.
That means when you copy such values, you're copying references which all reference the same data structure.

In Go, the built-in types maps, slices and channels have reference semantics,
and hence you almost never need to pass around pointers to the values of such types (well, sometimes it can be useful but not now).

Interfaces can be thought of to have reference semantics, too (let's not for now digress into discussing this) because each value of any interface type contains two pointers.

So, in your case it's better to merely not declare the formal parameters of your function as pointers — declare them as "plain" types and be done with it.

All in all, you should definitely complete some basic resource on Go which explains these basic matters in more detail and more extensively.


问:
Why "C:\Program Files" used as default. Is there any violations or degradation in performance if we change it?
Why does Microsoft recommend "C:\Program Files" for default installation destination? Are there any specific reason for that? And if I change the location is that going to effect the performance of the system and the application?</p>

答:
Don't forget that in Vista they've also added a little more security on the Program Files folder itself so that rogue programs can't mess up other programs in the same general directory area. If you're trying to follow the Microsoft conventions, they now ask that you put all "Common" application data in the C:\ProgramData folder, which gives the application and a little more control over it.

In addition, you can also use the CSIDLs to define your program data and program files folders so that they'll be properly referenced regardless if it is XP or Vista (where some folders have changed).

OwnerDisplayName: Maharajan

LastEditorDisplayName: bdukes

OwnerDisplayName: Dillie-O


问:
Is foreach guaranteed to iterate in the array order in php?
When an array is passed to foreach is the output order guaranteed to be the same as the input? I know in some languages that the output order is not guaranteed since each element is processed at the same time.

For example, I'm passing a sorted array to foreach to write to a file. I want to be sure that the array will be sorted in the output file.

答: Yes ...whatever order you will give to foreach it will iterate in same orders. And in your case array will be sorted in the output file.


问:
Set default value for dropdown list FormGroup
I have 2 response data from my API like as:
List all roles:

```<code>{
  "content": [{
      "id": 1,
      "roleName": "admin",
    },
    {
      "id": 2,
      "roleName": "user",

    },
    {
      "id": 3,
      "roleName": "other",

    }
  ],
  "last": true,
  "totalElements": 3,
  "totalPages": 1,
  "size": 20,
  "number": 0,
  "first": true,
  "sort": null,
  "numberOfElements": 3
}
</code>```

and user info:

```<code>{
  "id": 1,
  "userName": "admin"
  userRole[
    "id": 1,
    "roleName": "admin",
  ]
}
</code>```

in HTML, I want to show the list role:

```<code><div class="form-group">
  <label>Roles</label>
  <select formControlName="roles" class="form-control" id="roles">
    <option>{{user.userRole.roleName}}</option>
    <option *ngFor="let ls of roles">{{ls.roleName}}</option>
  </select>
</div>
</code>```

but, the UI shows : [admin],[admin],[user],[other]

I try to remove the duplicate role by using *ngIf:

```<code><div class="form-group">
  <label>Roles</label>
  <select formControlName="roles" class="form-control" id="roles">
    <option>{{user.userRole.roleName}}</option>
    <option *ngFor="let ls of roles">
      <div *ngIf="user.userRole.roleName!=ls.roleName">{{ls.roleName}}</div>
    </option>
  </select>
</div>
</code>```

but the UI shows:[admin],[blank],[user],[other]

Please advice me to show the list role correctly.

答:
I found the solution to user [attr.selected]:</p>

```<code> <select formControlName="roles" class="form-control" id="roles"  >
                        <option *ngFor="let rl of roles;"
                        [attr.value]='rl.id'
                        [attr.selected]="rl.id == desc ? true : null">
                           {{rl.roleName}}
                          </option>
                    </select>
</code>```

Body:
I have 2 response data from my API like as:
List all roles:

{
  "content": [{
      "id": 1,
      "roleName": "admin",
    },
    {
      "id": 2,
      "roleName": "user",

    },
    {
      "id": 3,
      "roleName": "other",

    }
  ],
  "last": true,
  "totalElements": 3,
  "totalPages": 1,
  "size": 20,
  "number": 0,
  "first": true,
  "sort": null,
  "numberOfElements": 3
}

and user info:

{
  "id": 1,
  "userName": "admin"
  userRole[
    "id": 1,
    "roleName": "admin",
  ]
}

in HTML, I want to show the list role:

  Roles
  <select formControlName="roles" class="form-control" id="roles">
    <option>{{user.userRole.roleName}}</option>
    <option *ngFor="let ls of roles">{{ls.roleName}}</option>
  </select>

but, the UI shows : [admin],[admin],[user],[other]

I try to remove the duplicate role by using *ngIf:

  Roles
  <select formControlName="roles" class="form-control" id="roles">
    <option>{{user.userRole.roleName}}</option>
    <option *ngFor="let ls of roles">

{{ls.roleName}}

    </option>
  </select>

but the UI shows:[admin],[blank],[user],[other]

Please advice me to show the list role correctly.

Body:
I found the solution to user [attr.selected]:

 <select formControlName="roles" class="form-control" id="roles"  >
                        <option *ngFor="let rl of roles;"
                        [attr.value]='rl.id'
                        [attr.selected]="rl.id == desc ? true : null">
                           {{rl.roleName}}
                          </option>
                    </select>


问:
data table search data correctly but when i remove search text from search box data didn't come again in tables
```<code>  <table id="example1" class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>Vendor Code</th>
                                <th>Vendor Name</th>
                                <th>Vendor Type</th>
                                <th>Credit Days</th>
                                <th  width="4px">Edit</th>
                                <th  width="4px">Delete</th>
                            </tr>
                        </thead>
                        <tbody id="VendorList"></tbody>

                    </table>
</code>```

here is my ajax call search box work properly but when i remove text from search box it table didnot fill again with data
  i dont know what happen in it
  need help !

```<code>    $.get("/Vendor/GetVendorList", null, DataBind);
    function DataBind(VendorList) {
        var setdata = $("#VendorList");
        for (var i = 0; i < VendorList.length; i++) {
            var Data = "<tr 'class='row" + VendorList[i].VendorID + "'>" +
                 "<td>" + VendorList[i].VendorCode + "</td>" +
                "<td>" + VendorList[i].VendorName + "</td>" +
                 "<td>" + VendorList[i].VendorType + "</td>" +
                  "<td>" + VendorList[i].CreditDays + "</td>" +
                 " <td>" + "<a href='/vendor/Addvendor/?VendorID=" + VendorList[i].VendorID + "'><span class='glyphicon glyphicon-pencil'></span></a>" + " </td>" +
                 " <td>" + "<a href='/vendor/deleterecord/?DeleteId=" + VendorList[i].VendorID + "' ><span class='glyphicon glyphicon-trash'></span></a>" + " </td>" +
            "</tr>";
            setdata.append(Data);
            $("#example1").DataTable();
        }
    }

</script>
</code>```

here is my controller

```<code> public JsonResult GetVendorList()
    {
        List<VendorViewModel> ven = ObjModel.Vendors.Select(x => new VendorViewModel
        {
            VendorID = x.VendorID,
            VendorName = x.VendorName,
            VendorType = x.VendorType,
            VendorCode = x.VendorCode,
            VendorEmail = x.VendorEmail,
            VendorPhoneNo = x.VendorPhoneNo,
            VendorMobileNo = x.VendorMobileNo,
            VendorAddress = x.VendorAddress,
            CreditDays = x.CreditDays,
            IsActive = x.IsActive,
            Website = x.Website,
            IsDelete = x.IsDelete,
            UserID = x.UserID,
            ComapnyId = x.ComapnyId
        }).ToList();
        return Json(ven, JsonRequestBehavior.AllowGet);
    }
</code>```

this is my JSON method where data comes from

答:
First clear all rows of table. you are appending every time.

```<code>$('#example1 tbody').empty();
</code>```

Also, you don't need to specify every time to table as DataTable in loop.

```<code>$.get("/Vendor/GetVendorList", null, DataBind);
    function DataBind(VendorList) {
        $('#example1 tbody').empty();
        var setdata = $("#VendorList");
        for (var i = 0; i < VendorList.length; i++) {
            var Data = "<tr 'class='row" + VendorList[i].VendorID + "'>" +
                 "<td>" + VendorList[i].VendorCode + "</td>" +
                "<td>" + VendorList[i].VendorName + "</td>" +
                 "<td>" + VendorList[i].VendorType + "</td>" +
                  "<td>" + VendorList[i].CreditDays + "</td>" +
                 " <td>" + "<a href='/vendor/Addvendor/?VendorID=" + VendorList[i].VendorID + "'><span class='glyphicon glyphicon-pencil'></span></a>" + " </td>" +
                 " <td>" + "<a href='/vendor/deleterecord/?DeleteId=" + VendorList[i].VendorID + "' ><span class='glyphicon glyphicon-trash'></span></a>" + " </td>" +
            "</tr>";
            setdata.append(Data);
        }
        $("#example1").DataTable();
    }
</code>```

Body:
                                Vendor Code
                                Vendor Name
                                Vendor Type
                                Credit Days
                                Edit
                                Delete

here is my ajax call search box work properly but when i remove text from search box it table didnot fill again with data
  i dont know what happen in it
  need help !

    $.get("/Vendor/GetVendorList", null, DataBind);
    function DataBind(VendorList) {
        var setdata = $("#VendorList");
        for (var i = 0; i < VendorList.length; i++) {
            var Data = "
" +
                 "" + VendorList[i].VendorCode + "	" +
                "" + VendorList[i].VendorName + "	" +
                 "" + VendorList[i].VendorType + "	" +
                  "" + VendorList[i].CreditDays + "	" +
                 " " + "" + " 	" +
                 " " + "" + " 	" +
            "
";
            setdata.append(Data);
            $("#example1").DataTable();
        }
    }

</script>

here is my controller

 public JsonResult GetVendorList()
    {
        List<VendorViewModel> ven = ObjModel.Vendors.Select(x => new VendorViewModel
        {
            VendorID = x.VendorID,
            VendorName = x.VendorName,
            VendorType = x.VendorType,
            VendorCode = x.VendorCode,
            VendorEmail = x.VendorEmail,
            VendorPhoneNo = x.VendorPhoneNo,
            VendorMobileNo = x.VendorMobileNo,
            VendorAddress = x.VendorAddress,
            CreditDays = x.CreditDays,
            IsActive = x.IsActive,
            Website = x.Website,
            IsDelete = x.IsDelete,
            UserID = x.UserID,
            ComapnyId = x.ComapnyId
        }).ToList();
        return Json(ven, JsonRequestBehavior.AllowGet);
    }

this is my JSON method where data comes from

Body:
First clear all rows of table. you are appending every time.

$('#example1 tbody').empty();

Also, you don't need to specify every time to table as DataTable in loop.

$.get("/Vendor/GetVendorList", null, DataBind);
    function DataBind(VendorList) {
        $('#example1 tbody').empty();
        var setdata = $("#VendorList");
        for (var i = 0; i < VendorList.length; i++) {
            var Data = "<tr 'class='row" + VendorList[i].VendorID + "'>" +
                 "<td>" + VendorList[i].VendorCode + "</td>" +
                "<td>" + VendorList[i].VendorName + "</td>" +
                 "<td>" + VendorList[i].VendorType + "</td>" +
                  "<td>" + VendorList[i].CreditDays + "</td>" +
                 " <td>" + "<a href='/vendor/Addvendor/?VendorID=" + VendorList[i].VendorID + "'><span class='glyphicon glyphicon-pencil'></span></a>" + " </td>" +
                 " <td>" + "<a href='/vendor/deleterecord/?DeleteId=" + VendorList[i].VendorID + "' ><span class='glyphicon glyphicon-trash'></span></a>" + " </td>" +
            "</tr>";
            setdata.append(Data);
        }
        $("#example1").DataTable();
    }


问:
Java Cannot be resolved or is not a field
Writing a for loop in a neural network i'm working on, and it's throwing an error for part of the loop condition itself.

The code is as follows:

```<code>// for each neuron sum the (inputs * corresponding weights) .Throw
// the total at our sigmoid function to get the output.

for (int j = 0; j < neuronLayers.get(i).numNeurons; ++j)
    {}
}
</code>```

neuronLayers itself is an ArrayList, defined as such:

```<code>// storage for each layer of neurons including the output layer

private ArrayList<Double> neuronLayers;
</code>```

and numNeurons is an integer value from another class, SNeuronLayer, defined as such:

```<code>// the number of neurons in this layer

int numNeurons;
</code>```

The error is with

```<code>neuronLayers.get(i).numNeurons;
</code>```

and it says "numNeurons cannot be resolved or is not a field".

Any help would be greatly appreciated, as i'm going to have to reference another ArrayList from the same second class in the for loop itself and i'd like to know how best to phrase it to ensure my code works.

答:
Hint: When you do neuronLayers.get(i), it returns double, so you can not access the SNeuronLayer. Instead, Try to make ArrayList of that class and include that double value as one of the attributes. So you can access both Double and SNeuronLayer.

Let's assume you have class named SNeuronLayer. Than keep following attributes in it.

```<code>class SNeuronLayer{
    int numNeurons;
    double your_double;
}
</code>```

now define array list as:

```<code>ArrayList<SNeuronLayer> list;
</code>```

So you can access double value by

```<code>list.get(i).your_double;
</code>```

and you can access Int value like:

```<code>list.get(i).numNeurons;
</code>```

Body:
Writing a for loop in a neural network i'm working on, and it's throwing an error for part of the loop condition itself.

The code is as follows:

// for each neuron sum the (inputs * corresponding weights) .Throw
// the total at our sigmoid function to get the output.

for (int j = 0; j < neuronLayers.get(i).numNeurons; ++j)
    {}
}

neuronLayers itself is an ArrayList, defined as such:

// storage for each layer of neurons including the output layer

private ArrayList<Double> neuronLayers;

and numNeurons is an integer value from another class, SNeuronLayer, defined as such:

// the number of neurons in this layer

int numNeurons;

The error is with

neuronLayers.get(i).numNeurons;

and it says "numNeurons cannot be resolved or is not a field".

Any help would be greatly appreciated, as i'm going to have to reference another ArrayList from the same second class in the for loop itself and i'd like to know how best to phrase it to ensure my code works.

Body:
Hint: When you do neuronLayers.get(i), it returns double, so you can not access the SNeuronLayer. Instead, Try to make ArrayList of that class and include that double value as one of the attributes. So you can access both Double and SNeuronLayer.

Let's assume you have class named SNeuronLayer. Than keep following attributes in it.

class SNeuronLayer{
    int numNeurons;
    double your_double;
}

now define array list as:

ArrayList<SNeuronLayer> list;

So you can access double value by

list.get(i).your_double;

and you can access Int value like:

list.get(i).numNeurons;


问:
Why does my code not end even when directly prompted to?
So I have the rest of the code correct, but it doesn't end and I'm unsure why. It shouldn't be infinite because it is prompted when either variable is over 5 to end yet it continues. Any answers?</p>

```<code>import random
Round = 0
Player_Score = 0
Computer_Score = 0
while Player_Score < 5 or Computer_Score < 5:
    Player_object = input("Would you like to choose R, P, or S?")
    Computer_object = random.sample("RPS", 1)[0]
    if Player_object == "R" or Player_object == "r":
        if Computer_object == "R":
             print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have tied with the Computer and neither of you have scored a point.")
        elif Computer_object == "P":
            Computer_Score += 1
            print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ". You have been beaten by the Computer and it has scored a point.")
        else:
            Player_Score += 1
            print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have beaten the Computer and you have scored a point.")

    if Player_object == "P" or Player_object == "p":
        if str(Computer_object) == "R":
            Player_Score += 1
            print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have beaten the Computer and you have scored a point.")
        elif str(Computer_object) == "P":
           print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ". You have tied with the Computer and neither of you have scored a point.")
        else:
            Computer_Score += 1
            print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have been beaten by the Computer and it has scored a point.")

    if Player_object == "S" or Player_object == "s":
        if str(Computer_object) == "R":
             print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have been beaten by the Computer and it has scored a point.")
        elif str(Computer_object) == "P":
            Computer_Score += 1
            print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ". You have beaten the Computer and you have scored a point.")
        else:
            Player_Score += 1
            print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have tied with the Computer and neither of you have scored a point.")
if Computer_Score == 5 and Player_Score != 5:
    print("The Computer has won!")
if Player_Score == 5 and Computer_Score != 5:
    print("You have won and beaten the computer")
</code>```

答:
Your loop ends when both are higher than 5, if you want it to stop when either are higher then 5 you need to have the following in your main for loop:</p>

```<code>while Player_Score < 5 and Computer_Score < 5
</code>```

Body:
So I have the rest of the code correct, but it doesn't end and I'm unsure why. It shouldn't be infinite because it is prompted when either variable is over 5 to end yet it continues. Any answers?

import random
Round = 0
Player_Score = 0
Computer_Score = 0
while Player_Score < 5 or Computer_Score < 5:
    Player_object = input("Would you like to choose R, P, or S?")
    Computer_object = random.sample("RPS", 1)[0]
    if Player_object == "R" or Player_object == "r":
        if Computer_object == "R":
             print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have tied with the Computer and neither of you have scored a point.")
        elif Computer_object == "P":
            Computer_Score += 1
            print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ". You have been beaten by the Computer and it has scored a point.")
        else:
            Player_Score += 1
            print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have beaten the Computer and you have scored a point.")

    if Player_object == "P" or Player_object == "p":
        if str(Computer_object) == "R":
            Player_Score += 1
            print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have beaten the Computer and you have scored a point.")
        elif str(Computer_object) == "P":
           print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ". You have tied with the Computer and neither of you have scored a point.")
        else:
            Computer_Score += 1
            print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have been beaten by the Computer and it has scored a point.")

    if Player_object == "S" or Player_object == "s":
        if str(Computer_object) == "R":
             print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have been beaten by the Computer and it has scored a point.")
        elif str(Computer_object) == "P":
            Computer_Score += 1
            print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ". You have beaten the Computer and you have scored a point.")
        else:
            Player_Score += 1
            print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have tied with the Computer and neither of you have scored a point.")
if Computer_Score == 5 and Player_Score != 5:
    print("The Computer has won!")
if Player_Score == 5 and Computer_Score != 5:
    print("You have won and beaten the computer")

Body:
Your loop ends when both are higher than 5, if you want it to stop when either are higher then 5 you need to have the following in your main for loop:

while Player_Score < 5 and Computer_Score < 5