问:
Spring Boot - @Async is ignored
Using Spring Boot 1.5.2.RELEASE and the @Async annotation seems to be ignored.

Have setup the environment like this:

```<code>@SpringBootApplication
@EnableAsync
public class Application extends AsyncConfigurerSupport {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public Executor getAsyncExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(500);
        executor.setThreadNamePrefix("async-task-");

        executor.initialize();

        return executor;
    }

    ...
</code>```

... the async method itself:

```<code>@Service
public class MyService {

    @Async
    public Future<Long> asyncTask() throws Exception {

        Long test = 1023L;

        Thread.sleep(10000);

        return new AsyncResult<>(test);
    }
}
</code>```

... now I'm trying to use this:

```<code>@RestController
public MyController {

    @Autowired
    public MyService myService;

    @PostMapping("/test")
    public ResponseEntity<MyResponse> test() {
        return new ResponseEntity<>(
                       new MyResponse(myService
                           .asyncTask()
                           .get()),
                       HttpStatus.OK);
    }
}
</code>```

... and the controller method still hangs for 10sec instead of to be immediatelly returned.

The @Async method is called from the different object. It's neither private nor transactional one as it mentioned at the similar questions.

How to let the method to be invoked asynchronously?

答:
Your test() function is invoking get() on the Future instance. The documentation for this function states: "Waits if necessary for the computation to complete, and then retrieves its result."

So rather than invoking get(), you likely want to return some sort if ID that the caller can use to retrieve the result at a later time (or switch to a synchronous response).

Title: Spring Boot - @Async is ignored

Body:
Using Spring Boot 1.5.2.RELEASE and the @Async annotation seems to be ignored.

Have setup the environment like this:

@SpringBootApplication
@EnableAsync
public class Application extends AsyncConfigurerSupport {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public Executor getAsyncExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(500);
        executor.setThreadNamePrefix("async-task-");

        executor.initialize();

        return executor;
    }

    ...

... the async method itself:

@Service
public class MyService {

    @Async
    public Future<Long> asyncTask() throws Exception {

        Long test = 1023L;

        Thread.sleep(10000);

        return new AsyncResult<>(test);
    }
}

... now I'm trying to use this:

@RestController
public MyController {

    @Autowired
    public MyService myService;

    @PostMapping("/test")
    public ResponseEntity<MyResponse> test() {
        return new ResponseEntity<>(
                       new MyResponse(myService
                           .asyncTask()
                           .get()),
                       HttpStatus.OK);
    }
}

... and the controller method still hangs for 10sec instead of to be immediatelly returned.

The @Async method is called from the different object. It's neither private nor transactional one as it mentioned at the similar questions.

How to let the method to be invoked asynchronously?


来源: stackexchange

问:
Best way to store thousands of numbers in SQL?
I have about 250 products and they all come with 52 weeks of history + 52 weeks of forecasts. I need to store these numbers in SQL but can't figure out the best way of doing it. I've only used databases a couple of times before so my knowledge is pretty limited...

I thought about using plain text and read/write with separators. But it felt bad in so many ways and made the entire database kinda useless.

Then I thought of adding 52 columns to the table, but I read it was a bad idea.

So now I'm back to where I began and it's just a table with

```<code>[ID] [WEEK_NUMBERS] [HISTORY_NUMBERS] [FORECAST_NUMBERS]
</code>```

Is this the best way of doing it?

The ~25000-30000 rows are not a problem?

答:
You would use a table something like this:

```<code>create table ProductHistory (
    ProductHistoryId int identity primary key,
    ProductId int not null references Products(ProductId),
    Type varchar(255) not null,
    Week date not null,    -- storing this as a date is a guess
    Number decimal(38, 10), -- should probably be decimal, but the scale and precision might be overkill,
    constraint chk_ProductHistory_type (type in ('Forecast', 'Actual')
);
</code>```

This is an example.  It is unclear:

Should each row have a column for Forecast and Actual, or should they be on separate rows?

How should the week be stored?

What is the right type for Number?

But the idea is the same . . . at least one row per product/week combination.

ContentLicense: CC BY-SA 3.0

Body:
I have about 250 products and they all come with 52 weeks of history + 52 weeks of forecasts. I need to store these numbers in SQL but can't figure out the best way of doing it. I've only used databases a couple of times before so my knowledge is pretty limited...

I thought about using plain text and read/write with separators. But it felt bad in so many ways and made the entire database kinda useless.

Then I thought of adding 52 columns to the table, but I read it was a bad idea.

So now I'm back to where I began and it's just a table with

[ID] [WEEK_NUMBERS] [HISTORY_NUMBERS] [FORECAST_NUMBERS]

Is this the best way of doing it?

The ~25000-30000 rows are not a problem?

Body:
You would use a table something like this:

create table ProductHistory (
    ProductHistoryId int identity primary key,
    ProductId int not null references Products(ProductId),
    Type varchar(255) not null,
    Week date not null,    -- storing this as a date is a guess
    Number decimal(38, 10), -- should probably be decimal, but the scale and precision might be overkill,
    constraint chk_ProductHistory_type (type in ('Forecast', 'Actual')
);

This is an example.  It is unclear:

Should each row have a column for Forecast and Actual, or should they be on separate rows?

How should the week be stored?

What is the right type for Number?

But the idea is the same . . . at least one row per product/week combination.


问:
Scrollmagic TimelineMax not animating
I'm trying to figure out how to use TimelineMax with Scrollmagic.
The problem is easy to explain.

I have similar DOM elements, like particles that have to move slowly than scrolling speed.

This first implementation is WORKING (no Timeline)

```<code>var controller = new ScrollMagic.Controller();
var $particles = $("#particles li");
$particles.each(function() {
    var tween = TweenMax.to($(this), 1, { y: -100, ease: Linear.easeNone });
    var scene = new ScrollMagic.Scene({
        triggerElement: ".wrapper",
        duration: 1000
    });
    scene.setTween(tween);
    scene.addTo(controller);
});
</code>```

The second implementation is NOT WORKING (uses Timeline)

```<code>var controller = new ScrollMagic.Controller();
var $particles = $("#particles li");
var timeline = new TimelineMax();
$particles.each(function() {
    timeline.to($(this), 1, {  y: -200, ease: Linear.easeNone });
});
var scene = new ScrollMagic.Scene({
    triggerElement: ".wrapper",
    duration: 1000
});
scene.setTween(timeline)
scene.addTo(controller);
</code>```

I'd like to make timeline working but elements are not animating. They move but with null timing.

Thank you for help

--- CODEPENS ---

https://codepen.io/anon/pen/wJOveM (multiple scenes)

https://codepen.io/anon/pen/dvryog?editors=1111 (w/ timeline NOT WORKING)

答:
Can you try to use the TimelineMax .add() method instead of the .to() method in you second implementation? So your code should look like this:

```<code>var controller = new ScrollMagic.Controller();
var $particles = $("#particles li");
var timeline = new TimelineMax();
$particles.each(function() {
    timeline.add(TweenMax.to($(this), 1, {  y: -200, ease: Linear.easeNone }),0);
});
var scene = new ScrollMagic.Scene({
    triggerElement: ".wrapper",
    duration: 1000
});
scene.setTween(timeline)
scene.addTo(controller);
</code>```

Also, for better debugging, please add the .addIndicators() method to the scene to see indicators on the screen, which can really help in debugging while scrolling. You can try to play with the duration property as well to see if things work properly.

UPDATE: Since all the particles needed to be moving at the same time, I added a ,0 property at the end of every .add method call. This ensures that all the tweens are triggered at the same positions. You can read more about the position property here:

https://greensock.com/asdocs/com/greensock/TimelineLite.html#add()

Here's hopefully a working example this time :)

https://codepen.io/anon/pen/ryROrv

Hope this helps. Cheers.

Title: Scrollmagic TimelineMax not animating

Body:
I'm trying to figure out how to use TimelineMax with Scrollmagic.
The problem is easy to explain.

I have similar DOM elements, like particles that have to move slowly than scrolling speed.

This first implementation is WORKING (no Timeline)

var controller = new ScrollMagic.Controller();
var $particles = $("#particles li");
$particles.each(function() {
    var tween = TweenMax.to($(this), 1, { y: -100, ease: Linear.easeNone });
    var scene = new ScrollMagic.Scene({
        triggerElement: ".wrapper",
        duration: 1000
    });
    scene.setTween(tween);
    scene.addTo(controller);
});

The second implementation is NOT WORKING (uses Timeline)

var controller = new ScrollMagic.Controller();
var $particles = $("#particles li");
var timeline = new TimelineMax();
$particles.each(function() {
    timeline.to($(this), 1, {  y: -200, ease: Linear.easeNone });
});
var scene = new ScrollMagic.Scene({
    triggerElement: ".wrapper",
    duration: 1000
});
scene.setTween(timeline)
scene.addTo(controller);

I'd like to make timeline working but elements are not animating. They move but with null timing.

Thank you for help

--- CODEPENS ---

https://codepen.io/anon/pen/wJOveM (multiple scenes)

https://codepen.io/anon/pen/dvryog?editors=1111 (w/ timeline NOT WORKING)

Body:
Can you try to use the TimelineMax .add() method instead of the .to() method in you second implementation? So your code should look like this:

var controller = new ScrollMagic.Controller();
var $particles = $("#particles li");
var timeline = new TimelineMax();
$particles.each(function() {
    timeline.add(TweenMax.to($(this), 1, {  y: -200, ease: Linear.easeNone }),0);
});
var scene = new ScrollMagic.Scene({
    triggerElement: ".wrapper",
    duration: 1000
});
scene.setTween(timeline)
scene.addTo(controller);

Also, for better debugging, please add the .addIndicators() method to the scene to see indicators on the screen, which can really help in debugging while scrolling. You can try to play with the duration property as well to see if things work properly.

UPDATE: Since all the particles needed to be moving at the same time, I added a ,0 property at the end of every .add method call. This ensures that all the tweens are triggered at the same positions. You can read more about the position property here:

https://greensock.com/asdocs/com/greensock/TimelineLite.html#add()

Here's hopefully a working example this time :)

https://codepen.io/anon/pen/ryROrv

Hope this helps. Cheers.


问:
Progress bar with HttpClient
i have a file downloader function:

```<code>        HttpClientHandler aHandler = new HttpClientHandler();
        aHandler.ClientCertificateOptions = ClientCertificateOption.Automatic;
        HttpClient aClient = new HttpClient(aHandler);
        aClient.DefaultRequestHeaders.ExpectContinue = false;
        HttpResponseMessage response = await aClient.GetAsync(url);
        InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();

        // To save downloaded image to local storage
        var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
        filename, CreationCollisionOption.ReplaceExisting);
        var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);
        DataWriter writer = new DataWriter(fs.GetOutputStreamAt(0));

        writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());

        await writer.StoreAsync();
        //current.image.SetSource(randomAccessStream);
        writer.DetachStream();
        await fs.FlushAsync();
</code>```

How can i realize progress bar functionality?
Maybe i can get the writers bytes written so far? Or something?

P.S. I cant use DownloadOperation(Background transferring) because data from server requests certificate - and this functionality doesn't exist in DownloadOperations.

答:
Here's a self-contained class that'll do the download, and report back the progress percentage, based on code from TheBlueSky on this SO answer, and eriksendc on this GitHub comment.

```<code>public class HttpClientDownloadWithProgress : IDisposable
{
    private readonly string _downloadUrl;
    private readonly string _destinationFilePath;

    private HttpClient _httpClient;

    public delegate void ProgressChangedHandler(long? totalFileSize, long totalBytesDownloaded, double? progressPercentage);

    public event ProgressChangedHandler ProgressChanged;

    public HttpClientDownloadWithProgress(string downloadUrl, string destinationFilePath)
    {
        _downloadUrl = downloadUrl;
        _destinationFilePath = destinationFilePath;
    }

    public async Task StartDownload()
    {
        _httpClient = new HttpClient { Timeout = TimeSpan.FromDays(1) };

        using (var response = await _httpClient.GetAsync(_downloadUrl, HttpCompletionOption.ResponseHeadersRead))
            await DownloadFileFromHttpResponseMessage(response);
    }

    private async Task DownloadFileFromHttpResponseMessage(HttpResponseMessage response)
    {
        response.EnsureSuccessStatusCode();

        var totalBytes = response.Content.Headers.ContentLength;

        using (var contentStream = await response.Content.ReadAsStreamAsync())
            await ProcessContentStream(totalBytes, contentStream);
    }

    private async Task ProcessContentStream(long? totalDownloadSize, Stream contentStream)
    {
        var totalBytesRead = 0L;
        var readCount = 0L;
        var buffer = new byte[8192];
        var isMoreToRead = true;

        using (var fileStream = new FileStream(_destinationFilePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
        {
            do
            {
                var bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length);
                if (bytesRead == 0)
                {
                    isMoreToRead = false;
                    TriggerProgressChanged(totalDownloadSize, totalBytesRead);
                    continue;
                }

                await fileStream.WriteAsync(buffer, 0, bytesRead);

                totalBytesRead += bytesRead;
                readCount += 1;

                if (readCount % 100 == 0)
                    TriggerProgressChanged(totalDownloadSize, totalBytesRead);
            }
            while (isMoreToRead);
        }
    }

    private void TriggerProgressChanged(long? totalDownloadSize, long totalBytesRead)
    {
        if (ProgressChanged == null)
            return;

        double? progressPercentage = null;
        if (totalDownloadSize.HasValue)
            progressPercentage = Math.Round((double)totalBytesRead / totalDownloadSize.Value * 100, 2);

        ProgressChanged(totalDownloadSize, totalBytesRead, progressPercentage);
    }

    public void Dispose()
    {
        _httpClient?.Dispose();
    }
}
</code>```

Usage:

```<code>var downloadFileUrl = "http://example.com/file.zip";
var destinationFilePath = Path.GetFullPath("file.zip");

using (var client = new HttpClientDownloadWithProgress(downloadFileUrl, destinationFilePath))
{
    client.ProgressChanged += (totalFileSize, totalBytesDownloaded, progressPercentage) => {
        Console.WriteLine($"{progressPercentage}% ({totalBytesDownloaded}/{totalFileSize})");
    };

    await client.StartDownload();
}
</code>```

Result:

```<code>7.81% (26722304/342028776)
8.05% (27535016/342028776)
8.28% (28307984/342028776)
8.5% (29086548/342028776)
8.74% (29898692/342028776)
8.98% (30704184/342028776)
9.22% (31522816/342028776)
</code>```

Title: Progress bar with HttpClient

Body:
i have a file downloader function:

        HttpClientHandler aHandler = new HttpClientHandler();
        aHandler.ClientCertificateOptions = ClientCertificateOption.Automatic;
        HttpClient aClient = new HttpClient(aHandler);
        aClient.DefaultRequestHeaders.ExpectContinue = false;
        HttpResponseMessage response = await aClient.GetAsync(url);
        InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();

        // To save downloaded image to local storage
        var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
        filename, CreationCollisionOption.ReplaceExisting);
        var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);
        DataWriter writer = new DataWriter(fs.GetOutputStreamAt(0));

        writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());

        await writer.StoreAsync();
        //current.image.SetSource(randomAccessStream);
        writer.DetachStream();
        await fs.FlushAsync();

How can i realize progress bar functionality?
Maybe i can get the writers bytes written so far? Or something?

P.S. I cant use DownloadOperation(Background transferring) because data from server requests certificate - and this functionality doesn't exist in DownloadOperations.

Body:
Here's a self-contained class that'll do the download, and report back the progress percentage, based on code from TheBlueSky on this SO answer, and eriksendc on this GitHub comment.

public class HttpClientDownloadWithProgress : IDisposable
{
    private readonly string _downloadUrl;
    private readonly string _destinationFilePath;

    private HttpClient _httpClient;

    public delegate void ProgressChangedHandler(long? totalFileSize, long totalBytesDownloaded, double? progressPercentage);

    public event ProgressChangedHandler ProgressChanged;

    public HttpClientDownloadWithProgress(string downloadUrl, string destinationFilePath)
    {
        _downloadUrl = downloadUrl;
        _destinationFilePath = destinationFilePath;
    }

    public async Task StartDownload()
    {
        _httpClient = new HttpClient { Timeout = TimeSpan.FromDays(1) };

        using (var response = await _httpClient.GetAsync(_downloadUrl, HttpCompletionOption.ResponseHeadersRead))
            await DownloadFileFromHttpResponseMessage(response);
    }

    private async Task DownloadFileFromHttpResponseMessage(HttpResponseMessage response)
    {
        response.EnsureSuccessStatusCode();

        var totalBytes = response.Content.Headers.ContentLength;

        using (var contentStream = await response.Content.ReadAsStreamAsync())
            await ProcessContentStream(totalBytes, contentStream);
    }

    private async Task ProcessContentStream(long? totalDownloadSize, Stream contentStream)
    {
        var totalBytesRead = 0L;
        var readCount = 0L;
        var buffer = new byte[8192];
        var isMoreToRead = true;

        using (var fileStream = new FileStream(_destinationFilePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
        {
            do
            {
                var bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length);
                if (bytesRead == 0)
                {
                    isMoreToRead = false;
                    TriggerProgressChanged(totalDownloadSize, totalBytesRead);
                    continue;
                }

                await fileStream.WriteAsync(buffer, 0, bytesRead);

                totalBytesRead += bytesRead;
                readCount += 1;

                if (readCount % 100 == 0)
                    TriggerProgressChanged(totalDownloadSize, totalBytesRead);
            }
            while (isMoreToRead);
        }
    }

    private void TriggerProgressChanged(long? totalDownloadSize, long totalBytesRead)
    {
        if (ProgressChanged == null)
            return;

        double? progressPercentage = null;
        if (totalDownloadSize.HasValue)
            progressPercentage = Math.Round((double)totalBytesRead / totalDownloadSize.Value * 100, 2);

        ProgressChanged(totalDownloadSize, totalBytesRead, progressPercentage);
    }

    public void Dispose()
    {
        _httpClient?.Dispose();
    }
}

Usage:

var downloadFileUrl = "http://example.com/file.zip";
var destinationFilePath = Path.GetFullPath("file.zip");

using (var client = new HttpClientDownloadWithProgress(downloadFileUrl, destinationFilePath))
{
    client.ProgressChanged += (totalFileSize, totalBytesDownloaded, progressPercentage) => {
        Console.WriteLine($"{progressPercentage}% ({totalBytesDownloaded}/{totalFileSize})");
    };

    await client.StartDownload();
}

Result:

7.81% (26722304/342028776)
8.05% (27535016/342028776)
8.28% (28307984/342028776)
8.5% (29086548/342028776)
8.74% (29898692/342028776)
8.98% (30704184/342028776)
9.22% (31522816/342028776)


问:
7zip Commands from Python
There is a post on this topic already, but it does not have an explicit answer to the fundamental question which I am re-asking here:

How do you make 7zip commands from Python?

Attempting to use the subprocess module, I implemented the following which runs but does nothing (from what I can tell):

```<code>import subprocess
cmd = ['7z', 'a', '"Test.7z"', '"Test"', '-mx9']
subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
</code>```

I know that the following 7zip command works, as I have tested on the Windows command line itself:

```<code>7z a "Test.7z" "Test" -mx9
</code>```

How could I implement that simple 7zip command from Python?

答:
You can wrap it as a function using the following:

```<code>import subprocess

def sevenzip(filename, zipname, password):
    print("Password is: {}".format(password))
    system = subprocess.Popen(["7z", "a", zipname, filename, "-p{}".format(password)])
    return(system.communicate())
</code>```

This definitely works as I've tried and tested it. If you want to tweak it i.e. to Extract files then you can use the following:

```<code>def extractfiles(zipname):
    system = subprocess.Popen(["7z", "e", zipname])
    return(system.communicate())
</code>```

Give this a try and lemme know how you get on.

Bear in mind this is for Linux. In Windows, swap "7z" with "C:\Program Files\7-Zip\7z.exe" (i think that's the right location).

Title: 7zip Commands from Python

Body:
There is a post on this topic already, but it does not have an explicit answer to the fundamental question which I am re-asking here:

How do you make 7zip commands from Python?

Attempting to use the subprocess module, I implemented the following which runs but does nothing (from what I can tell):

import subprocess
cmd = ['7z', 'a', '"Test.7z"', '"Test"', '-mx9']
subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)

I know that the following 7zip command works, as I have tested on the Windows command line itself:

7z a "Test.7z" "Test" -mx9

How could I implement that simple 7zip command from Python?

Body:
You can wrap it as a function using the following:

import subprocess

def sevenzip(filename, zipname, password):
    print("Password is: {}".format(password))
    system = subprocess.Popen(["7z", "a", zipname, filename, "-p{}".format(password)])
    return(system.communicate())

This definitely works as I've tried and tested it. If you want to tweak it i.e. to Extract files then you can use the following:

def extractfiles(zipname):
    system = subprocess.Popen(["7z", "e", zipname])
    return(system.communicate())

Give this a try and lemme know how you get on.

Bear in mind this is for Linux. In Windows, swap "7z" with "C:\Program Files\7-Zip\7z.exe" (i think that's the right location).

ContentLicense: CC BY-SA 4.0


问:
How to debug "Invalid Bundle" error which happens only after submitting to app store
I have a lot of frameworks in my app. App works fine in adhoc/enterprise release. Only if I submit to the app store for testflight testing I get this error email from apple:

Dear developer,

We have discovered one or more issues with your recent delivery for "My app's name here". To process your delivery, the following
  issues must be corrected:

Invalid Bundle - One or more dynamic libraries that are referenced by your app are not present in the dylib search path.

Once these issues have been corrected, you can then redeliver the corrected binary.

Regards,

The App Store team

there is no specific information here. How can I debug it?

答:
In my case, in the build settings, this was fixed when I added the following to the build settings for the library:

```<code> DYLIB_INSTALL_NAME_BASE = @rpath
</code>```

The clue was a linker warning: 'YourLibrary has an install name beginning with “/”, but it is not from the specified SDK'

Body:
In my case, in the build settings, this was fixed when I added the following to the build settings for the library:

 DYLIB_INSTALL_NAME_BASE = @rpath

The clue was a linker warning: 'YourLibrary has an install name beginning with “/”, but it is not from the specified SDK'


问:
how to remove comma white space during explode and replace?
```<code>$data = "google,facebook,youtube,twitter,bing";

$exp = explode(",",$data);

$rep = str_replace("facebook",$exp);
$final = implode(",",$rep);

echo $final

output// google,,youtube,twitter,bing
</code>```

How can I remove this blank space with comma?

答:
RobertPitt's answer is the only one that bothers to loop and is more complicated than necessary.
Jonah's and Colin O'Dell's methods are interesting but also heavier than necessary.

Orbling got really close with his preg_replace method, it takes too many commas away and also doesn't account for the possibility of the needle being the only value.

str_replace and preg_replace both have the clear advantage of not bothering to explode and implode.  This needs to be the primary separator of the answers on this page.  Methods that convert the string to an array and back to a string (not to mention additional handling) will be less efficient than the _replace methods.

I'll also note that no one mentioned array_diff in their explode/implode methods so I'll include it in my list of methods even though it relies on explode and implode.  It is purely for demonstration's sake.

All str_replace methods are potentially untrustworthy if the needle is a substring of another value.  Because the OP's sample input doesn't offer a conflict in this regard, I've built a str_replace method.

My one-liner preg_replace method is lean and solid.

```<code>echo preg_replace("/,facebook\b|\bfacebook,|\bfacebook\b/","",$data);
</code>```

By using word boundaries (\b), my regex pattern is guarded against the possibility of a needle existing inside another value.  See  By checking for the needle with a leading comma, then a trailing comma, then no comma; the pattern still holds up if the only value in the string is the needle.  Finally, if the needle is not present in the csv string, there is no error.  THIS is the answer that SO readers should be implementing.

If you are generating the needle dynamically, you can declare your pattern two ways:

```<code>$needle="facebook";

echo preg_replace("/,$needle\b|\b$needle,|\b$needle\b/","",$data);
// OR
echo preg_replace("/,".$needle."\b|\b".$needle.",|\b".$needle."\b/","",$data);
</code>```

(Demo)

My second place offering uses str_replace:

```<code>$args=[["facebook",",,"],["",","]];
echo trim(str_replace($args[0],$args[1],$data),",");
</code>```

It replaces facebook then replaces any double-commas with a single comma, then trims off any leading or trailing commas from the resulting string.

And in third place, explode->array_diff->implode as a one-liner:

```<code>echo implode(',',array_diff(explode(',',$data),["facebook"]));
</code>```

It's a tight one-liner, but still has to go to the trouble to explode, filter, and implode.

Here is my testing ground where I put all three methods through the paces.

ContentLicense: CC BY-SA 2.5

Body:
$data = "google,facebook,youtube,twitter,bing";

$exp = explode(",",$data);

$rep = str_replace("facebook",$exp);
$final = implode(",",$rep);

echo $final

output// google,,youtube,twitter,bing

How can I remove this blank space with comma?

Body:
RobertPitt's answer is the only one that bothers to loop and is more complicated than necessary.
Jonah's and Colin O'Dell's methods are interesting but also heavier than necessary.

Orbling got really close with his preg_replace method, it takes too many commas away and also doesn't account for the possibility of the needle being the only value.

str_replace and preg_replace both have the clear advantage of not bothering to explode and implode.  This needs to be the primary separator of the answers on this page.  Methods that convert the string to an array and back to a string (not to mention additional handling) will be less efficient than the _replace methods.

I'll also note that no one mentioned array_diff in their explode/implode methods so I'll include it in my list of methods even though it relies on explode and implode.  It is purely for demonstration's sake.

All str_replace methods are potentially untrustworthy if the needle is a substring of another value.  Because the OP's sample input doesn't offer a conflict in this regard, I've built a str_replace method.

My one-liner preg_replace method is lean and solid.

echo preg_replace("/,facebook\b|\bfacebook,|\bfacebook\b/","",$data);

By using word boundaries (\b), my regex pattern is guarded against the possibility of a needle existing inside another value.  See  By checking for the needle with a leading comma, then a trailing comma, then no comma; the pattern still holds up if the only value in the string is the needle.  Finally, if the needle is not present in the csv string, there is no error.  THIS is the answer that SO readers should be implementing.

If you are generating the needle dynamically, you can declare your pattern two ways:

$needle="facebook";

echo preg_replace("/,$needle\b|\b$needle,|\b$needle\b/","",$data);
// OR
echo preg_replace("/,".$needle."\b|\b".$needle.",|\b".$needle."\b/","",$data);

(Demo)

My second place offering uses str_replace:

$args=[["facebook",",,"],["",","]];
echo trim(str_replace($args[0],$args[1],$data),",");

It replaces facebook then replaces any double-commas with a single comma, then trims off any leading or trailing commas from the resulting string.

And in third place, explode->array_diff->implode as a one-liner:

echo implode(',',array_diff(explode(',',$data),["facebook"]));

It's a tight one-liner, but still has to go to the trouble to explode, filter, and implode.

Here is my testing ground where I put all three methods through the paces.


问:
Can a bcrypt hashed password be converted to SHA2?
I have two applications that use different ways to hash the users password. I want to syncronize these applications so that the user is allowed to login with the same user credentials.

Is it possible to convert a bcrypt password to SHA2?

答:
Bcrypt and SHA-256 is a one-way hashing algorithm, you can't decrypt hashes (without brute-forcing). You cannot do a bulk password change. However, it is still possible to convert your database from one algorithm to another. Here's how:

Each time a user is logged into your website, compare if the supplied password matches the hash saved in your database.

If there is a match, then take the supplied password which would probably be in $_POST['password'] and then hash it to your destination algorithm like hash('mypassword', 'mypassword');

That's the only way you would be able to convert those hashed password.

In previous version of WordPress, they used to store passwords as hashed MD5. They have now introduced a new password algorithm and that how it works to convert old MD5 password hashes when you upgrade.


问:
SAS: Merging two tables with identical columns while dropping null values
I'm not sure if the title does this question justice, but here it goes:

I have three datasets Forecasts1, Forecasts2 and Forecasts3. They are all time series data composed of a date variable and variables r1 through r241.

For a given r variable (lets just use r1-r3, and only Forecasts 1 and 2 for now) each dataset has only one row where the value isn't null, and it is a different row in each dataset.

Forecast 1 looks like this:

Forecast 2 looks like this:

I need to be able to combine them such that r1-r3 contain all the non-null values, without creating duplicate date rows to hold the null values.

So ideally the finished produce would look like this:

I've tried various types of merges and sets, but I keep getting duplicate date rows. How would I go about doing this properly for all 241 (or more) variables? (specifically in SAS or Proc SQL?)

LINKS TO GOOGLE DOCS CONTAINING DATA:

Forecasts1: https://docs.google.com/spreadsheets/d/1iUEwPltU6V6ijgnkALFiIdrwrolDFt8xaITZaFC4WN8/edit?usp=sharing

Forecasts2:
https://docs.google.com/spreadsheets/d/1lQGKYJlz6AAR-DWtoWnl8SwzCNAmSpj7yxRqRgnybr8/edit?usp=sharing

答:
Consider a union query with aggregation. The only drawback is writing out the aggregates for all 241 columns in outer query.

proc sql;
   SELECT sub.date, Max(sub.r1) AS R1, Max(sub.r2) AS R2, Max(sub.r3) AS R3, ...
   FROM
     (SELECT *
      FROM Forecasts1 f1
      UNION ALL
      SELECT *
      FROM Forecasts2 f2) As sub
    GROUP BY sub.date
quit;
```


问:
Create a devise user from Ruby console
Any idea on how to create and save a new User object with devise from the ruby console?

When I tried to save it, I'm getting always false. I guess I'm missing something but I'm unable to find any related info.

答:
You can add false to the save method to skip the validations if you want.

```<code>User.new({:email => "guy@gmail.com", :roles => ["admin"], :password => "111111", :password_confirmation => "111111" }).save(false)
</code>```

Otherwise I'd do this

```<code>User.create!({:email => "guy@gmail.com", :roles => ["admin"], :password => "111111", :password_confirmation => "111111" })
</code>```

If you have confirmable module enabled for devise, make sure you are setting the confirmed_at value to something like Time.now while creating.

Title: Create a devise user from Ruby console

Body:
You can add false to the save method to skip the validations if you want.

User.new({:email => "guy@gmail.com", :roles => ["admin"], :password => "111111", :password_confirmation => "111111" }).save(false)

Otherwise I'd do this

User.create!({:email => "guy@gmail.com", :roles => ["admin"], :password => "111111", :password_confirmation => "111111" })

If you have confirmable module enabled for devise, make sure you are setting the confirmed_at value to something like Time.now while creating.


问:
SQL Server user defined function returns table -- cannot call it from select query
I cannot get this type of select query (pseudo-code) to work. The UDF returns a table with 8 columns in a single row for a given 'UID_VEHICLE'.  It works perfectly when the 'UID_VEHICLE' is provided as a constant like 3308. But I need one row of these function-results for each vehicle for a given customer -- up to 100 rows to be returned.

```<code>SELECT
    *
FROM
    [dbo].[fnGetNextDOT_InspectionData](UID_VEHICLE)
WHERE
    UID_VEHICLE IN (SELECT UID_VEHICLE
                    FROM tVEHICLES
                    WHERE UID_CUSTOMER = 88);
</code>```

Your comments and solutions are welcome...thanks...John

答:
When passing row values from a query into a TVF, you need to use CROSS APPLY or OUTER APPLY (starting with SQL Server 2005):

```<code>SELECT   * -- or dot.*, or whatever is desired
FROM     tVEHICLES veh
CROSS APPLY [dbo].[fnGetNextDOT_InspectionData](veh.UID_VEHICLE) dot
WHERE    veh.UID_CUSTOMER = 88;
</code>```

Body:
I cannot get this type of select query (pseudo-code) to work. The UDF returns a table with 8 columns in a single row for a given 'UID_VEHICLE'.  It works perfectly when the 'UID_VEHICLE' is provided as a constant like 3308. But I need one row of these function-results for each vehicle for a given customer -- up to 100 rows to be returned.

SELECT
    *
FROM
    [dbo].[fnGetNextDOT_InspectionData](UID_VEHICLE)
WHERE
    UID_VEHICLE IN (SELECT UID_VEHICLE
                    FROM tVEHICLES
                    WHERE UID_CUSTOMER = 88);

Your comments and solutions are welcome...thanks...John

Body:
When passing row values from a query into a TVF, you need to use CROSS APPLY or OUTER APPLY (starting with SQL Server 2005):

SELECT   * -- or dot.*, or whatever is desired
FROM     tVEHICLES veh
CROSS APPLY [dbo].[fnGetNextDOT_InspectionData](veh.UID_VEHICLE) dot
WHERE    veh.UID_CUSTOMER = 88;


问:
Displaying only user specific items from MongoDB collection in Meteor
I am new to Meteor, and creating a meteor web application for teachers in order for them to keep track of the classes they teach and the students within each class. After logging in, the teacher sees a running list of all of the classes that they personally teach, and will be able to select each individual class in order to view a list of students in that particular class, with options to remove, edit, or add. The teacher will then be able to select an individual student's name, which will take them to a page where the teacher can upload documents (pdfs, word documents, etc) corresponding to the specific student they have chosen. The problem I am running into is how exactly I can display, add, and edit only information that applies to each teacher, since there will be many teachers using the app, each with different classes and students. I have a single collection for both classes and students, but can not seem to wrap my mind around how to only display items that correspond to the presently logged in teacher. What is the best way to go about this? </p>

答:
teacher collection could have an array of classes they teach.

classes collection could have an array of objects. Each object has a teacher and an array of students for that class

Teacher Collection

```<code>teacher [
classes: {class_id1, class_id2, class_id3}
]
</code>```

Classes Collection

```<code>classes [
{
 class: history
  {teacher: teacher_id1
   children: { childid1, child_id2, child_id3 }
  }
 {teacher: teacher_id2
  children: { child_id1, child_id2, child_id3 }
 }
},
{
 class:geography {
next iteration
}
</code>```

}
]

You can manage the file uploads by naming the folders uniqueylyy for a teacher class student combination

Body:
teacher collection could have an array of classes they teach.

classes collection could have an array of objects. Each object has a teacher and an array of students for that class

Teacher Collection

teacher [
classes: {class_id1, class_id2, class_id3}
]

Classes Collection

classes [
{
 class: history
  {teacher: teacher_id1
   children: { childid1, child_id2, child_id3 }
  }
 {teacher: teacher_id2
  children: { child_id1, child_id2, child_id3 }
 }
},
{
 class:geography {
next iteration
}

}
]

You can manage the file uploads by naming the folders uniqueylyy for a teacher class student combination


问:
How does lambda capture local static variable?
In below code I do not specify any capture mode, yet some_static is visible inside closure. So the question is whether it is actually captured, or maybe somehow referenced in other way.

Bonus question is whether compiler is allowed to turn such lambda into a free function instead of closure - that would be possible as no capture list is specified.

```<code>std::vector<std::function<bool(int)>> filters;

int main()
{
    static int some_static = 1;
    filters.emplace_back([](int){
      return some_static == 2;
    });
}
</code>```

答:
You don't need to capture global or static variables. Only automatic variables have to be captured if you want to use them.

Because of that, yes, you can convert such lambda to a function pointer.

Cppreference:

The identifier in any capture without an initializer (other than the this-capture) is looked up using usual unqualified name lookup in the reaching scope of the lambda. The result of the lookup must be a variable with automatic storage duration declared in the reaching scope.

(emphasis mine)

"To capture" means to put a copy or a reference to a variable into a lambda object itself.

Global and static variables have fixed memory location. You don't need to store copies or references to them to use them since their location is known at compile time and doesn't change.

(If you really want to have a copy of a global or static variable, you can create it using named capture from C++14, which lets you create a custom member variable in a lambda object. But such capture is not necessary if you just want to use that global / static variable.)

Automatic variables, on the other hand, don't have a fixed location. Multiple lambdas created at the exact same place could refer to different automatic variables. Because of that, a lambda object has to capture such variable - which means to contain either a reference to used automatic variable or a copy of it.

Body:
In below code I do not specify any capture mode, yet some_static is visible inside closure. So the question is whether it is actually captured, or maybe somehow referenced in other way.

Bonus question is whether compiler is allowed to turn such lambda into a free function instead of closure - that would be possible as no capture list is specified.

std::vector<std::function<bool(int)>> filters;

int main()
{
    static int some_static = 1;
    filters.emplace_back([](int){
      return some_static == 2;
    });
}


问:
Chaining of services - Java
At the moment I'm using multiple REST services to process my data.
A workflow would be like this:

User requests the speed of a car:
Ask the SpeedService the most recent speed => SpeedService requests the latests positions of the car from the PositionService and the PositionService achieves this by calling the DatabaseService in order to get the raw unprocessed data from the car. However the part where I'm having issues is calling a service withing another service. I've achieved this for now by making uses of the invocation api.

Example:

```<code>Client client = ClientBuilder.newClient();
        WebTarget target = client.target("http://mylocalRestserver.example/webresources/").path("speed");
        target = target.queryParam("carId", carId);
        Invocation invocation = target.request(MediaType.APPLICATION_JSON).buildGet();
        Speed speed = new Genson().deserialize(invocation.invoke(String.class), Speed.class);
        return speed;
</code>```

However whenever I try to simulate concurrent users - running multiple curl queries - the REST service breaks due to SocketTimeouts, I assume because multiple requests are sent on the same serversocket? Is there any way to achieve this "chaining of services"?

答:
Your idea is sound but cannot be implemented with such a naive approach.

What you are trying to achieve is location transparency while keeping the system responsive, which is not an easy task.

There are big frameworks that deal with this problem, AKKA comes to mind.

If your objective is just separation of concerns (each service deals with is part of the problem and invokes other services to get what it needs), you can just use the relevant classes without making http request from the server to itself.

If instead you want to be able to distribute your services across several nodes you should rely on frameworks like akka, doing it yourself is an unfeasible task.

Title: Chaining of services - Java

Body:
At the moment I'm using multiple REST services to process my data.
A workflow would be like this:

User requests the speed of a car:
Ask the SpeedService the most recent speed => SpeedService requests the latests positions of the car from the PositionService and the PositionService achieves this by calling the DatabaseService in order to get the raw unprocessed data from the car. However the part where I'm having issues is calling a service withing another service. I've achieved this for now by making uses of the invocation api.

Example:

Client client = ClientBuilder.newClient();
        WebTarget target = client.target("http://mylocalRestserver.example/webresources/").path("speed");
        target = target.queryParam("carId", carId);
        Invocation invocation = target.request(MediaType.APPLICATION_JSON).buildGet();
        Speed speed = new Genson().deserialize(invocation.invoke(String.class), Speed.class);
        return speed;

However whenever I try to simulate concurrent users - running multiple curl queries - the REST service breaks due to SocketTimeouts, I assume because multiple requests are sent on the same serversocket? Is there any way to achieve this "chaining of services"?


问:
Insert a Node at the Tail of a Linked List python HackerRank
Its a very simple program of adding a node at the end of a link list. I dont know what mistake I am doing. has it something to do with the exoected output of hackerRank or there's a mistake in my code.
I m trying to implement the Python2

```<code>class Node(object):

   def __init__(self, data=None, next_node=None):
       self.data = data
       self.next = next_node
def Insert(head, data):

    if (head.head == None):
        head.head = Node(data)
    else:
        current = head.head
        while (current.next != None) and (current.data == data):
                           current = current.next
        current.next = Node(data)
</code>```

Heres a link to the question.
https://www.hackerrank.com/challenges/insert-a-node-at-the-tail-of-a-linked-list

答:
Node Class:

class Node(object):
    def init(self, item):
        self.data = item
        self.next = None

```<code>def getdata(self):
    return self.data

def setdata(self, item):
    self.data = item

def getnext(self):
    return self.next

def setnext(self, item):
    self.next = item
</code>```

and method to insert at the end is

```<code> def insert(head, item):
    newNode = Node(item)
    newNode.setdata(item)
    current = head
    while current.getnext() != None:
        current = current.getnext()
    current.setnext(newNode)
</code>```

Body:
Its a very simple program of adding a node at the end of a link list. I dont know what mistake I am doing. has it something to do with the exoected output of hackerRank or there's a mistake in my code.
I m trying to implement the Python2

class Node(object):

   def __init__(self, data=None, next_node=None):
       self.data = data
       self.next = next_node
def Insert(head, data):

    if (head.head == None):
        head.head = Node(data)
    else:
        current = head.head
        while (current.next != None) and (current.data == data):
                           current = current.next
        current.next = Node(data)

Heres a link to the question.
https://www.hackerrank.com/challenges/insert-a-node-at-the-tail-of-a-linked-list

Body:
Node Class:

class Node(object):
    def init(self, item):
        self.data = item
        self.next = None

def getdata(self):
    return self.data

def setdata(self, item):
    self.data = item

def getnext(self):
    return self.next

def setnext(self, item):
    self.next = item

and method to insert at the end is

 def insert(head, item):
    newNode = Node(item)
    newNode.setdata(item)
    current = head
    while current.getnext() != None:
        current = current.getnext()
    current.setnext(newNode)


问:
Python web scraping: difference between sleep and request(page, timeout=x)
When scraping multiple websites in a loop, I notice there is a rather large difference in speed between,

```<code>sleep(10)
response = requests.get(url)
</code>```

and,

```<code>response = requests.get(url, timeout=10)
</code>```

That is, timeout is much faster.

Moreover, for both set-ups I expected a scraping duration of at least 10 seconds per page before requesting the next page, but this is not the case.

Why is there such a difference in speed?

Why is the scraping duration per page less than 10 seconds?

I now use multiprocessing, but I think to remember the above holds as well for non-multiprocessing.

答:
time.sleep stops your script from running for certain amount of seconds, while the timeout is the maximum time wait for retrieving the url. If the data is retrieved before the timeout time is up, the remaining time will get skipped. So it's possible to take less than 10 seconds using timeout.

time.sleep is different, it pauses your script completely until it's done sleeping, then it will run your request taking another few seconds. So time.sleep will take more than 10 seconds every time.

They have very different uses, but for your case, you should make a timer so if it finished before 10 seconds, make the program to wait.

Body:
When scraping multiple websites in a loop, I notice there is a rather large difference in speed between,

sleep(10)
response = requests.get(url)

and,

response = requests.get(url, timeout=10)

That is, timeout is much faster.

Moreover, for both set-ups I expected a scraping duration of at least 10 seconds per page before requesting the next page, but this is not the case.

Why is there such a difference in speed?

Why is the scraping duration per page less than 10 seconds?

I now use multiprocessing, but I think to remember the above holds as well for non-multiprocessing.


问:
Boost loop performance when reshaping huge amount of data
This is an extended question from previous question here. I'm reshaping the data according to the code below. However when the data size get increased, in=rand(291081,1920);, the answer (preallocation) in the previous question can't handle it anymore, MATLAB even freezed the whole laptop. Thus as suggested by Teddy in the last question, I'm opening a new question to boost the performance of the loop.

Some quite similar but not alike question can be found here. From there, the answer given suggested to modify the loop to be column-wise. However, since my loop required to access row and column simultaneously, it seem the answer is not applicable in my case.

Is this loop can still be modified to improve its performance? Or can this loop be done without freezes the whole laptop? If possible, without getting involve with GPUs.

```<code>in=rand(291081,1920);
m=581;
[R,C]=size(in);
R_out=R/m;

out=zeros(m*C,R_out);
for k=1:m %from row 1 to nth row
    for i=1:C %reshape every column of nth row
        out(i+C*(k-1),:) = in(k:m:end,i)';
    end
end
</code>```

P/S: In previous question, when the data size getting bigger, the loop and arrayfun seem to not have large performance difference.

Thanks in advance!

答:
Firstly, thanks @NLindros for providing the answer, which had inspired this answer. It seems using reshape is so far the most efficient way to handle huge data. Thus to avoid the usage of transpose as suggested, permute and reshape is used, as below.

out=reshape(permute(reshape(in,m,R_out,[]),[1 3 2]),[],R_out);

This by far is the fastest way to reshape.

I'll mark this as answer if there's no more better answer.

Body:
This is an extended question from previous question here. I'm reshaping the data according to the code below. However when the data size get increased, in=rand(291081,1920);, the answer (preallocation) in the previous question can't handle it anymore, MATLAB even freezed the whole laptop. Thus as suggested by Teddy in the last question, I'm opening a new question to boost the performance of the loop.

Some quite similar but not alike question can be found here. From there, the answer given suggested to modify the loop to be column-wise. However, since my loop required to access row and column simultaneously, it seem the answer is not applicable in my case.

Is this loop can still be modified to improve its performance? Or can this loop be done without freezes the whole laptop? If possible, without getting involve with GPUs.

in=rand(291081,1920);
m=581;
[R,C]=size(in);
R_out=R/m;

out=zeros(m*C,R_out);
for k=1:m %from row 1 to nth row
    for i=1:C %reshape every column of nth row
        out(i+C*(k-1),:) = in(k:m:end,i)';
    end
end

P/S: In previous question, when the data size getting bigger, the loop and arrayfun seem to not have large performance difference.

Thanks in advance!


问:
javascript create dictionary from array
I have an array like this

```<code>propertiesToCheck: [
    {name: 'name', type: 'type', enabled: true},
    {
        name: 'name2',
        type: 'type2',
        templateUrl: 'something.html',
        preferences: {
            places: [place1, place2,...],
            placesDict: ????
        },
        enabled: true
    }
]
</code>```

In the places array there are objects with id, name, etc. Now I want to create a dictionary placesDict that should look like {place1.id: 0, place2.id: 0, ...}, so all values will be set to 0. How can I do that?

答:
```<code>var placesDict = {};
propertiesToCheck[1].preferences.places.forEach(place => {
  placesDict[place.id] = 0;
});
</code>```

Same thing but using function definition instead of arrow function.

```<code>var placesDict = {};
propertiesToCheck[1].preferences.places.forEach(setPlace);

function setPlace (place) {
  placesDict[place.id] = 0;
}
</code>```

To have this functionality attached to a method of the preferences object:

```<code>propertiesToCheck: [
    {name: 'name', type: 'type', enabled: true},
    {
        name: 'name2',
        type: 'type2',
        templateUrl: 'something.html',
        preferences: {
            places: [place1, place2,...],
            placesDict: () => {
              newDict = {};
              propertiesToCheck[1].preferences.places.forEach(place => newDict[place.id] = 0);
              return newDict;
            }
        },
        enabled: true
    }
]

console.log(propertiesToCheck[1].preferences.placesDict()); // {place1.id: 0, place2.id: 0, ...}
</code>```

Setting the property placesDict to be equal to a function return value:

```<code>propertiesToCheck: [
    {name: 'name', type: 'type', enabled: true},
    {
        name: 'name2',
        type: 'type2',
        templateUrl: 'something.html',
        preferences: {
            places: [place1, place2,...],
            placesDict: createDict()
        },
        enabled: true
    }
]

function createDict() {
  var placesDict = {};
  propertiesToCheck[1].preferences.places.forEach(place => {
    placesDict[place.id] = 0;
  });
}
</code>```

I hope this helped.

Title: javascript create dictionary from array

Body:
I have an array like this

propertiesToCheck: [
    {name: 'name', type: 'type', enabled: true},
    {
        name: 'name2',
        type: 'type2',
        templateUrl: 'something.html',
        preferences: {
            places: [place1, place2,...],
            placesDict: ????
        },
        enabled: true
    }
]

In the places array there are objects with id, name, etc. Now I want to create a dictionary placesDict that should look like {place1.id: 0, place2.id: 0, ...}, so all values will be set to 0. How can I do that?

Body:
var placesDict = {};
propertiesToCheck[1].preferences.places.forEach(place => {
  placesDict[place.id] = 0;
});

Same thing but using function definition instead of arrow function.

var placesDict = {};
propertiesToCheck[1].preferences.places.forEach(setPlace);

function setPlace (place) {
  placesDict[place.id] = 0;
}

To have this functionality attached to a method of the preferences object:

propertiesToCheck: [
    {name: 'name', type: 'type', enabled: true},
    {
        name: 'name2',
        type: 'type2',
        templateUrl: 'something.html',
        preferences: {
            places: [place1, place2,...],
            placesDict: () => {
              newDict = {};
              propertiesToCheck[1].preferences.places.forEach(place => newDict[place.id] = 0);
              return newDict;
            }
        },
        enabled: true
    }
]

console.log(propertiesToCheck[1].preferences.placesDict()); // {place1.id: 0, place2.id: 0, ...}

Setting the property placesDict to be equal to a function return value:

propertiesToCheck: [
    {name: 'name', type: 'type', enabled: true},
    {
        name: 'name2',
        type: 'type2',
        templateUrl: 'something.html',
        preferences: {
            places: [place1, place2,...],
            placesDict: createDict()
        },
        enabled: true
    }
]

function createDict() {
  var placesDict = {};
  propertiesToCheck[1].preferences.places.forEach(place => {
    placesDict[place.id] = 0;
  });
}

I hope this helped.


问:
A POST form that contains all properties of a model
I want to create a POST form that contains all properties in model. Each property would be set as hidden input item:

```<code>@using (Html.BeginForm("MyAction", "MyController"))
{
    @Html.HiddenFor(m => m.Field1)
    @Html.HiddenFor(m => m.Field2)
    ...
    @Html.HiddenFor(m => m.FieldN)

    <button type="submit" class="btn btn-primary">Launch query</button>
}
</code>```

Ideally, I would like to do something like (pseudocode):

```<code>@using (Html.BeginForm("MyAction", "MyController"))
{
    foreach(var prop in m.Props)
    {
        @Html.HiddenFor(m => m[prop])
    }

    <button type="submit" class="btn btn-primary">Launch query</button>
}
</code>```

答:
Maybe something like:</p>

```<code>@foreach (var property in Model.GetType().GetProperties())
{
    <input id="@property.Name" name="@property.Name" value="@property.GetValue(Model, null)" type="hidden" />
}
</code>```

Body:
I want to create a POST form that contains all properties in model. Each property would be set as hidden input item:

@using (Html.BeginForm("MyAction", "MyController"))
{
    @Html.HiddenFor(m => m.Field1)
    @Html.HiddenFor(m => m.Field2)
    ...
    @Html.HiddenFor(m => m.FieldN)

    <button type="submit" class="btn btn-primary">Launch query</button>
}

Ideally, I would like to do something like (pseudocode):

@using (Html.BeginForm("MyAction", "MyController"))
{
    foreach(var prop in m.Props)
    {
        @Html.HiddenFor(m => m[prop])
    }

    <button type="submit" class="btn btn-primary">Launch query</button>
}

Body:
Maybe something like:

@foreach (var property in Model.GetType().GetProperties())
{
    <input id="@property.Name" name="@property.Name" value="@property.GetValue(Model, null)" type="hidden" />
}


问:
Which npm packages will and will not work on Angular 2? How do I tell?
Does an NPM package need to be modified to be compatible with Angular 2 (eg. add in typings, make directives for them) or will any existing package work? If they're not all compatible, how do I know what is and what is not compatible?

For example, say I want to import this package (https://github.com/pvorb/node-md5). I'm aware there is a ts-md5 package for angular 2 to do md5 - I'm just using this package as an example.

How would I get this to work?

I've installed it using

```<code>npm install md5 --save
npm install @types/md5 --save
</code>```

but I can't seem to be import it

```<code>import {md5} from 'md5';
</code>```

I get this error message after I try to run

Module
  '"/Users/xxx/Source/tempProjects/ngUnderscore/node_modules/@types/md5/index"'
  resolves to a non-module entity and cannot be imported using this
  construct.

I'm not sure what this message means. Does it mean that in its current state, the package is not compatible or am I trying to use the package incorrectly?

答:
I managed to make it work using declare and require instead of import (import won't work for this non-module lib)

```<code>declare const require: any;
const md5 = require('md5');
</code>```

If you don't want to workaround import like this, you can try using Typescript MD5 implementation called ts-md5. Then import like the one below should work. (referenced from this question)

```<code>import { Md5 } from 'ts-md5/dist/md5'
</code>```

If there is no TS implementation, you can search for the types in DefinitelyTyped and then simply install package by npm i --save-dev @types/{package-name}

Body:
Does an NPM package need to be modified to be compatible with Angular 2 (eg. add in typings, make directives for them) or will any existing package work? If they're not all compatible, how do I know what is and what is not compatible?

For example, say I want to import this package (https://github.com/pvorb/node-md5). I'm aware there is a ts-md5 package for angular 2 to do md5 - I'm just using this package as an example.

How would I get this to work?

I've installed it using

npm install md5 --save
npm install @types/md5 --save

but I can't seem to be import it

import {md5} from 'md5';

I get this error message after I try to run

Module
  '"/Users/xxx/Source/tempProjects/ngUnderscore/node_modules/@types/md5/index"'
  resolves to a non-module entity and cannot be imported using this
  construct.

I'm not sure what this message means. Does it mean that in its current state, the package is not compatible or am I trying to use the package incorrectly?

Body:
I managed to make it work using declare and require instead of import (import won't work for this non-module lib)

declare const require: any;
const md5 = require('md5');

If you don't want to workaround import like this, you can try using Typescript MD5 implementation called ts-md5. Then import like the one below should work. (referenced from this question)

import { Md5 } from 'ts-md5/dist/md5'

If there is no TS implementation, you can search for the types in DefinitelyTyped and then simply install package by npm i --save-dev @types/{package-name}


问:
Html file upload to server
I am building a Cordova app and I want the user to upload it's profile image through a HTML form. If the form is like the example from W3C ( the example bellow) how the Php file must look like? I tried the example from W3C but it's not saving anything to the server. I use 000webhost as server.  Someone said that instead of using upload.php, I can just write there (at action=" ") the adress of the server and the folder, is that working?</p>

```<code><form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</code>```

答:
Configure The "php.ini" File
First, ensure that PHP is configured to allow file uploads.

In your "php.ini" file, search for the file_uploads directive, and set it to On:

Title: Html file upload to server

Body:
I am building a Cordova app and I want the user to upload it's profile image through a HTML form. If the form is like the example from W3C ( the example bellow) how the Php file must look like? I tried the example from W3C but it's not saving anything to the server. I use 000webhost as server.  Someone said that instead of using upload.php, I can just write there (at action=" ") the adress of the server and the folder, is that working?

<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>


问:
Current Visible item in RecyclerView
I want to find the current visible item/items in Vertical Linear layout (RecyclerView), So that I can attach Exoplayer to the top most element rather than all the items. And even play that item on visibility. I am not able to find any idea to this implement this.

Should this be handled in Fragment or Adapter.

Thanks, I am new to Android development.

答:
In LinearLayoutManager, you can use some methods which they can help.

```<code>layoutManager.findFirstVisibleItemPosition();
layoutManager.findFirstCompletelyVisibleItemPosition();
layoutManager.findLastVisibleItemPosition();
layoutManager.findLastCompletelyVisibleItemPosition();
</code>```

These returns position as integer. You can use like below:

```<code>LinearLayoutManager layoutManager = ((LinearLayoutManager) recyclerView.getLayoutManager());
int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
</code>```

But you should note that, in some cases, findFirstVisibleItemPosition() in some devices not worked stable for me. For example, it was working at Sony, LG and Samsung devices, but same code, didn't worked at Nexus 5. I am not sure why it did not worked, but I changed my approach because of this bug.

Title: Current Visible item in RecyclerView

Body:
In LinearLayoutManager, you can use some methods which they can help.

layoutManager.findFirstVisibleItemPosition();
layoutManager.findFirstCompletelyVisibleItemPosition();
layoutManager.findLastVisibleItemPosition();
layoutManager.findLastCompletelyVisibleItemPosition();

These returns position as integer. You can use like below:

LinearLayoutManager layoutManager = ((LinearLayoutManager) recyclerView.getLayoutManager());
int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

But you should note that, in some cases, findFirstVisibleItemPosition() in some devices not worked stable for me. For example, it was working at Sony, LG and Samsung devices, but same code, didn't worked at Nexus 5. I am not sure why it did not worked, but I changed my approach because of this bug.


问:
OpenGL Color Index for iPhone's OpenGL ES 1.1?
Is it possible to use color pallettes in openGL ES 1.1?

I'm currently developing a game which has player sprites, and the player sprites need to be able to be changed to different teams' colors. For example, changing the shirts' colors but not the face colors, which rules out simple hue rotation.

Is this possible, or will this have to be implemented manually (modifying the texture data directly)?

答:
It's not a hardware feature of the MBX but a quick check of gl.h for ES 1.x from the iPhone SDK reveals that GL_PALETTE4_RGB8_OES, GL_PALETTE8_RGBA8_OES and a bunch of others are available as one of the constants to pass to glCompressedTexImage2D, as per the man page here. So you can pass textures with palettes to that, but I'll bet anything that the driver will just turn them into RGB textures on the CPU and then upload them to the GPU. I don't believe Apple support those types of compressed texture for any reason other than that they're part of the ES 1.x spec.

On ES 2.x you're free to do whatever you want. You could easily upload the palette as one texture (with, say, the pixel at (x, 0) being the colour for palette index x) and the paletted texture as another. You'll then utilise two texture units to do the job that one probably could do when plotting fragments, so use your own judgment as to whether you can afford that.


问:
Capybara ambiguous match errors
The project is a reboot of the original, and I am trying to get to grips with the various gems - the rails composer does a brilliant job of everything but me gaining understanding of what is going on.

I am getting this Capybara error that is tied to the signup code (I have several specs using the call, but have only included one of them here as they all call the same helper).

```<code> Capybara::Ambiguous:
       Ambiguous match, found 2 elements matching field "Password"
</code>```

I have looked on StackOverflow (several times), and used the power of Messr Google - who mainly suggests I look here.

At first I thought it was to do with having a mismatch of

```<code>fill_in 'Email', with: email
</code>```

and

```<code>fill_in 'Email', :with => email
</code>```

but neither seems to make a difference.

From reading the documentation (I know: hangs head in shame) at rubydoc.info capybara fill-in , the fill-in takes a locator and an options array.

My understanding is that fill_in 'Password', with: password would match the Password locator, which is the id="user_password" part of the html. I don't see any others on the page, so am now reaching out for help.

All my code is on the SO001 branch of my projectGithub project branch to match this question.

sign_up_spec.rb

```<code>feature 'Sign Up', :devise do
  # Scenario: Visitor can sign up with valid email address and password
  #   Given I am not signed in
  #   When I sign up with a valid email address and password
  #   Then I see a successful sign up message
  scenario 'visitor can sign up with valid email address and password' do
    sign_up_with('test@example.com', 'please123', 'please123')
    txts = [I18n.t( 'devise.registrations.signed_up'), I18n.t( 'devise.registrations.signed_up_but_unconfirmed')]
    expect(page).to have_content(/.*#{txts[0]}.*|.*#{txts[1]}.*/)
  end
    # ... others snipped for space
end
</code>```

spec/support/helpers/session_helpers.rb

```<code>module Features
  module SessionHelpers
    def sign_up_with(email, password, confirmation)
      visit new_user_registration_path
      save_and_open_page
      fill_in 'Email', with: email
      fill_in 'Password', with: password
      fill_in 'Password confirmation', :with => confirmation
      click_button 'Sign up'
    end

    def signin(email, password)
      visit new_user_session_path
      fill_in 'Email', with: email
      fill_in 'Password', with: password
      click_button 'Sign in'
    end
  end
end
</code>```

The devise new.html.erb code is

Sign up

```<code><%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.input :email, required: true, autofocus: true %>
    <%= f.input :password, required: true, hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length) %>
    <%= f.input :password_confirmation, required: true %>
  </div>

  <div class="form-actions">
    <%= f.button :submit, "Sign up" %>
  </div>
<% end %>

<%= render "devise/shared/links" %>
</code>```

The form part of the html has

```<code><form novalidate="novalidate" class="simple_form new_user" id="new_user" action="/users" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" />

  <div class="form-inputs">
    <div class="form-group email required user_email">
        <label class="control-label email required" for="user_email">
            <abbr title="required">*</abbr> Email
        </label>
        <input class="form-control string email required" autofocus="autofocus" required="required" aria-required="true" type="email" value="" name="user[email]" id="user_email" />
    </div>
    <div class="form-group password required user_password">
        <label class="control-label password required" for="user_password">
            <abbr title="required">*</abbr>
            Password</label>
        <input class="form-control password required" required="required" aria-required="true" type="password" name="user[password]" id="user_password" />
        <p class="help-block">6 characters minimum</p>
    </div>
    <div class="form-group password required user_password_confirmation">
        <label class="control-label password required" for="user_password_confirmation">
            <abbr title="required">*</abbr>
            Password confirmation
        </label>
        <input class="form-control password required" required="required" aria-required="true" type="password" name="user[password_confirmation]" id="user_password_confirmation" />
    </div>
  </div>

  <div class="form-actions">
    <input type="submit" name="commit" value="Sign up" class="btn btn-default" data-disable-with="Sign up" />
  </div>
</form>
</code>```

答:
As documented, Capybara's fill_in will match an element on either its id or name attributes, or on the text of an associated label element.  The attribute matches need to be exact and the text of an associated label element may be an exact or substring match depending on the setting of a few options.

In the current versions of Capybara, Capybara.exact defaults to :smart which when looking for an associated label text match will first attempt for an exact match, and if none is found will attempt for a substring match.  In your case the label text of two of your fields are *Password and *Password confirmation which when checked for an exact match with Password fail, and when checked with a substring match both match - hence the "Ambiguous match" error since more that one element matched.

To fix this (while still using fill_in) you could do any of the following

```<code>fill_in '*Password', with: password # will match exactly on one elements label text

find('div.user_password').fill_in 'Password' with: password # scope fill_in so substring match is unique

fill_in 'user_password', with: password # match on id attribute

fill_in 'user[password]', with: password # match on name attribute
</code>```

Title: Capybara ambiguous match errors

Body:
The project is a reboot of the original, and I am trying to get to grips with the various gems - the rails composer does a brilliant job of everything but me gaining understanding of what is going on.

I am getting this Capybara error that is tied to the signup code (I have several specs using the call, but have only included one of them here as they all call the same helper).

 Capybara::Ambiguous:
       Ambiguous match, found 2 elements matching field "Password"

I have looked on StackOverflow (several times), and used the power of Messr Google - who mainly suggests I look here.

At first I thought it was to do with having a mismatch of

fill_in 'Email', with: email

and

fill_in 'Email', :with => email

but neither seems to make a difference.

From reading the documentation (I know: hangs head in shame) at rubydoc.info capybara fill-in , the fill-in takes a locator and an options array.

My understanding is that fill_in 'Password', with: password would match the Password locator, which is the id="user_password" part of the html. I don't see any others on the page, so am now reaching out for help.

All my code is on the SO001 branch of my projectGithub project branch to match this question.

sign_up_spec.rb

feature 'Sign Up', :devise do
  # Scenario: Visitor can sign up with valid email address and password
  #   Given I am not signed in
  #   When I sign up with a valid email address and password
  #   Then I see a successful sign up message
  scenario 'visitor can sign up with valid email address and password' do
    sign_up_with('test@example.com', 'please123', 'please123')
    txts = [I18n.t( 'devise.registrations.signed_up'), I18n.t( 'devise.registrations.signed_up_but_unconfirmed')]
    expect(page).to have_content(/.*#{txts[0]}.*|.*#{txts[1]}.*/)
  end
    # ... others snipped for space
end

spec/support/helpers/session_helpers.rb

module Features
  module SessionHelpers
    def sign_up_with(email, password, confirmation)
      visit new_user_registration_path
      save_and_open_page
      fill_in 'Email', with: email
      fill_in 'Password', with: password
      fill_in 'Password confirmation', :with => confirmation
      click_button 'Sign up'
    end

    def signin(email, password)
      visit new_user_session_path
      fill_in 'Email', with: email
      fill_in 'Password', with: password
      click_button 'Sign in'
    end
  end
end

The devise new.html.erb code is

Sign up

<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= f.error_notification %>

    <%= f.input :email, required: true, autofocus: true %>
    <%= f.input :password, required: true, hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length) %>
    <%= f.input :password_confirmation, required: true %>

    <%= f.button :submit, "Sign up" %>

<% end %>

<%= render "devise/shared/links" %>

The form part of the html has

<form novalidate="novalidate" class="simple_form new_user" id="new_user" action="/users" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" />

            * Email

        <input class="form-control string email required" autofocus="autofocus" required="required" aria-required="true" type="email" value="" name="user[email]" id="user_email" />

            *
            Password
        <input class="form-control password required" required="required" aria-required="true" type="password" name="user[password]" id="user_password" />

6 characters minimum

            *
            Password confirmation

        <input class="form-control password required" required="required" aria-required="true" type="password" name="user[password_confirmation]" id="user_password_confirmation" />

    <input type="submit" name="commit" value="Sign up" class="btn btn-default" data-disable-with="Sign up" />

</form>

Body:
As documented, Capybara's fill_in will match an element on either its id or name attributes, or on the text of an associated label element.  The attribute matches need to be exact and the text of an associated label element may be an exact or substring match depending on the setting of a few options.

In the current versions of Capybara, Capybara.exact defaults to :smart which when looking for an associated label text match will first attempt for an exact match, and if none is found will attempt for a substring match.  In your case the label text of two of your fields are *Password and *Password confirmation which when checked for an exact match with Password fail, and when checked with a substring match both match - hence the "Ambiguous match" error since more that one element matched.

To fix this (while still using fill_in) you could do any of the following

fill_in '*Password', with: password # will match exactly on one elements label text

find('div.user_password').fill_in 'Password' with: password # scope fill_in so substring match is unique

fill_in 'user_password', with: password # match on id attribute

fill_in 'user[password]', with: password # match on name attribute


问:
Solving systems with Groebner basis
Suppose that a finite set of polynomials in C[x,y,z] has a finite number of solutions (i.e. the generated ideal is 0-dimensional).

Suppose also that the Groebner basis with respect to lex order x>y>z is

[f(z), g(y,z), h(y,z), k(x,y,z)]

As well known, the system can be now easily solved: choose a root z0 of f, plug it into g and h and look for a common root (y0) etc.

The question is the following:
Is it true that for EVERY root z0 of f there exist y0, z0 such that (x0,y0,z0) satisfy the system?

In all the examples I have seen this is true, but I don't know whether this is true in general or there is a counterexample.

Thank you.

答:
Yes, any root z0 of f can be extended to a root (x0,y0,z0) of the system f = g = h = k = 0.

To see this consider that Iz = <f>,
where Iz is the intersection of the generated zero dimensional ideal I with C[z] and <f> is the ideal generated by f. As can be seen in the proof that non-trivial intersections of I with C[xi] for all variables xi implies a finite zero set (see e.g. here, page 2 bottom and especially page 3 top), <f> contains a polynomial which factors only in (powers of) minimal polynomials of values appearing as z-value in the common roots of I. Since f divides this polynomial, it also has only roots that can be extended to roots of the system.

Title: Solving systems with Groebner basis


问:
Count lowercase letters till the input is string
I wrote a short code in C which count the lowercase letters (only letters) and it'll stop working when I enter a number or something else. Here is the code:

```<code>char letter;
int num=0;
do
    if(islower(letter = getchar()))
       num++;
while(isalpha(letter));
printf("%d", num);
return 0;
</code>```

My problem is that it isn't working properly (only print "1" as result).
And it has to be stopped when the next character isn't alphabetical letter. Not sure that part is right.

Any idea what did I wrong? Thanks.

答:
what's about this?

```<code>char letter;
int num=0;
while (isalpha(letter = getchar())) {
    if (islower(letter)) num++;
}
printf("%d", num);
return 0;
</code>```

And it has to be stopped when the next character isn't alphabetical letter.

keyboard input can be buffered - not processing until Enter be pressed

only print "1" as result

can you write some examples of inputed in console caused to "1" output?

Body:
I wrote a short code in C which count the lowercase letters (only letters) and it'll stop working when I enter a number or something else. Here is the code:

char letter;
int num=0;
do
    if(islower(letter = getchar()))
       num++;
while(isalpha(letter));
printf("%d", num);
return 0;

My problem is that it isn't working properly (only print "1" as result).
And it has to be stopped when the next character isn't alphabetical letter. Not sure that part is right.

Any idea what did I wrong? Thanks.

Body:
what's about this?

char letter;
int num=0;
while (isalpha(letter = getchar())) {
    if (islower(letter)) num++;
}
printf("%d", num);
return 0;

And it has to be stopped when the next character isn't alphabetical letter.

keyboard input can be buffered - not processing until Enter be pressed

only print "1" as result

can you write some examples of inputed in console caused to "1" output?


问:
Python Linked List Append
I made an append method for an UnorderedList() class that works fine in my IDLE window but when its assigned to the University's test of:

```<code>my_list = UnorderedList()
my_list.append(13)
for num in my_list:
    print(num, end=" ")
print()
</code>```

it returns an error: AttributeError: Nonetype object has no attribute 'getNext'.

Here is the append method:

```<code>def append(self,item):
    current = self.head
    while current.getNext() != None:
        current = current.getNext()
    current.setNext(Node(item))
</code>```

Here is the rest of my classes and code:

```<code>class Node:
    def __init__(self,initdata):
        self.data = initdata
        self.next = None

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def setData(self,newdata):
        self.data = newdata

    def setNext(self,newnext):
        self.next = newnext

class UnorderedList:

    def __init__(self):
        self.head = None
        self.count = 0

    def append(self,item):
        current = self.head
        while current.getNext() != None:
            current = current.getNext()
        current.setNext(Node(item))
</code>```

Why is the test returning that error and how I can fix my append method?

答:
Adding little more elaborated append methods

Method to insert at the beginning

```<code>def inserAtBeginning(self, item):
    newNode = Node(item)
    newNode.setdata(item)
    if self.listLength() == 0:
        self.head = newNode
    else:
        newNode.setnext(self.head)
        self.head = newNode
</code>```

Method to insert at the end

```<code>def insertAtEnd(self, item):
    newNode = Node(item)
    newNode.setdata(item)
    current = self.head
    while current.getnext() != None:
        current = current.getnext()
    current.setnext(newNode)
</code>```

Method to insert at the  specified position

```<code>def insertAtPos(self, pos, item):
    if pos > self.listLength() or pos < 0:
        return None
    if pos == 0:
        self.inserAtBeginning(item)
    else:
        if pos == self.listLength():
            self.insertAtEnd(item)
        else:
            newNode = Node(item)
            newNode.setdata(item)
            current = self.head
            count = 0
            while count < pos - 1:
                count += 1
                current = current.getnext()
            newNode.setnext(current.getnext())
            current.setnext(newNode)
</code>```

Title: Python Linked List Append

Body:
I made an append method for an UnorderedList() class that works fine in my IDLE window but when its assigned to the University's test of:

my_list = UnorderedList()
my_list.append(13)
for num in my_list:
    print(num, end=" ")
print()

it returns an error: AttributeError: Nonetype object has no attribute 'getNext'.

Here is the append method:

def append(self,item):
    current = self.head
    while current.getNext() != None:
        current = current.getNext()
    current.setNext(Node(item))

Here is the rest of my classes and code:

class Node:
    def __init__(self,initdata):
        self.data = initdata
        self.next = None

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def setData(self,newdata):
        self.data = newdata

    def setNext(self,newnext):
        self.next = newnext

class UnorderedList:

    def __init__(self):
        self.head = None
        self.count = 0

    def append(self,item):
        current = self.head
        while current.getNext() != None:
            current = current.getNext()
        current.setNext(Node(item))

Why is the test returning that error and how I can fix my append method?

Body:
Adding little more elaborated append methods

Method to insert at the beginning

def inserAtBeginning(self, item):
    newNode = Node(item)
    newNode.setdata(item)
    if self.listLength() == 0:
        self.head = newNode
    else:
        newNode.setnext(self.head)
        self.head = newNode

Method to insert at the end

def insertAtEnd(self, item):
    newNode = Node(item)
    newNode.setdata(item)
    current = self.head
    while current.getnext() != None:
        current = current.getnext()
    current.setnext(newNode)

Method to insert at the  specified position

def insertAtPos(self, pos, item):
    if pos > self.listLength() or pos < 0:
        return None
    if pos == 0:
        self.inserAtBeginning(item)
    else:
        if pos == self.listLength():
            self.insertAtEnd(item)
        else:
            newNode = Node(item)
            newNode.setdata(item)
            current = self.head
            count = 0
            while count < pos - 1:
                count += 1
                current = current.getnext()
            newNode.setnext(current.getnext())
            current.setnext(newNode)


问:
Accessing Variable inside Inner Class
I have a listener and I want to access variable outside the listener method. But even after initializing the variable globally its showing "0" outside scope.

Can anyone explain the reason

```<code>public class MapsActivity{
   double origin_lat;
   //
   @Override
   public void onMapReady(GoogleMap googleMap) {
       //
       srcLat.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            double value = (double) dataSnapshot.getValue();
            origin_lat=value;  -- > value shows here
            Log.d("SourceLatitude",Double.toString(value));

        }
       });
   Log.d("OutsideScope",Double.toString(origin_lat)); -- > shows "0"
   }
 }
</code>```

答:
I have a listener and I want to access variable outside the listener
  method. But even after initializing the variable globally its showing
  "0" outside scope.

Can anyone explain the reason

because onMapReady/onDataChange is/are async and not sync as you think. Android calls it their initialization, in the first case and when the new data is available in the second case. The purpose of having them async is to avoid to block the UI Thread in case of heavy computation, leaving your users the possibility to interact with the UI

Title: Accessing Variable inside Inner Class

Body:
I have a listener and I want to access variable outside the listener method. But even after initializing the variable globally its showing "0" outside scope.

Can anyone explain the reason

public class MapsActivity{
   double origin_lat;
   //
   @Override
   public void onMapReady(GoogleMap googleMap) {
       //
       srcLat.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            double value = (double) dataSnapshot.getValue();
            origin_lat=value;  -- > value shows here
            Log.d("SourceLatitude",Double.toString(value));

        }
       });
   Log.d("OutsideScope",Double.toString(origin_lat)); -- > shows "0"
   }
 }


问:
Dictionary is getting overriden while adding another entry
I have a function to create dictionary

```<code>def Bowler_creator (Name):

    """
    This function will create the dictionaries for the batting player

    """
    global bowler;
    bowler =    {
            Name : { "number_of_overs":0.0,
                    "number_of_runs":0,
                    "number_of_wickets":0,
                    'economy_rate':0.0,
                    'Maiden overs':0
                    },

                }
Current_Bowler = input("Enter the bowler's name\n");

Bowler_creator(Current_Bowler);
Bowler_creator('jafda');
</code>```

My idea is that i will be calling this function like below so that new key with the same entry values will be created for this dictionary

So as per my idea, the dictionary should have created two elements with two keys Current_Bowler and jafda, but after I try to print the dictionary it´s returning the latest one only. Could you please let me know why my dictionary is getting overridden with a newer key?

答:
You are replacing the dictionary with an entirely new dictionary each time.

You should create the dictionary once, then add keys:

```<code>bowler = {}

def Bowler_creator (Name):
    bowler[Name] = {
        "number_of_overs":0.0,
        "number_of_runs":0,
        "number_of_wickets":0,
        'economy_rate':0.0,
        'Maiden overs':0
    }
</code>```

Note: because the function no longer needs to assign a new object to bowler, you don't need to mark it as a global either. Assigning directly to the key modifies the global dictionary directly.

Body:
I have a function to create dictionary

def Bowler_creator (Name):

    """
    This function will create the dictionaries for the batting player

    """
    global bowler;
    bowler =    {
            Name : { "number_of_overs":0.0,
                    "number_of_runs":0,
                    "number_of_wickets":0,
                    'economy_rate':0.0,
                    'Maiden overs':0
                    },

                }
Current_Bowler = input("Enter the bowler's name\n");

Bowler_creator(Current_Bowler);
Bowler_creator('jafda');

My idea is that i will be calling this function like below so that new key with the same entry values will be created for this dictionary

So as per my idea, the dictionary should have created two elements with two keys Current_Bowler and jafda, but after I try to print the dictionary it´s returning the latest one only. Could you please let me know why my dictionary is getting overridden with a newer key?

Body:
You are replacing the dictionary with an entirely new dictionary each time.

You should create the dictionary once, then add keys:

bowler = {}

def Bowler_creator (Name):
    bowler[Name] = {
        "number_of_overs":0.0,
        "number_of_runs":0,
        "number_of_wickets":0,
        'economy_rate':0.0,
        'Maiden overs':0
    }

Note: because the function no longer needs to assign a new object to bowler, you don't need to mark it as a global either. Assigning directly to the key modifies the global dictionary directly.


问:
When should you make an interface/contract, and when not?
As the title says: What are key points indicating you should use and interface. And what are key points indicating that you should not use an interface?

答:
The entire point of interfaces is to give you the flexibility to have your class be forced to implement multiple interfaces, but still not allow multiple inheritance. The issues with inheriting from multiple classes are many and varied.

Interfaces are a compromise. Most of the problems with multiple inheritance don't apply to abstract base classes, so most modern languages these days disable multiple inheritance yet call abstract base classes interfaces and allows a class to "implement" as many of those as they want.


问:
How do I refactor css?
I have been tasked with refactoring the css of a website, and I am quite new to refactoring process. What is the exact process I can undergo in order to refactor the css of my website? What are the tools I can use in order to ease this process?</p>

答:
Code refactoring is the process of restructuring existing computer code—changing the factoring—without changing its external behavior.

Take from this link here

One way is you try to avoid writting duplicated codes for each html elements that has the same properties

example Look at styling three divs each has same rule

#d1 {
  color: red;
  padding-left: 15px;
  background-color: green;
}

#d2 {
  color: red;
  background-color: blue;
  padding-left: 15px;
}

#d3 {
  padding-left: 15px;
  color: red;
  background-color: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="d1">d1</div>
<div id="d2">d1</div>
<div id="d3">d3</div></code>```

Instead of adding a color:red for each element, we can do

```<code>#d1,#d2,#d3 {
  color: red;
}
</code>```

Snippet below

#d1 {
  background-color: green;
}
#d2 {
  background-color: blue;
}
#d3 {
  background-color: yellow;
}
#d1,#d2,#d3 {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="d1">d1</div>
<div id="d2">d1</div>
<div id="d3">d3</div></code>```

Title: How do I refactor css?

Body:
Code refactoring is the process of restructuring existing computer code—changing the factoring—without changing its external behavior.

Take from this link here

One way is you try to avoid writting duplicated codes for each html elements that has the same properties

example Look at styling three divs each has same rule

#d1 {
  color: red;
  padding-left: 15px;
  background-color: green;
}

#d2 {
  color: red;
  background-color: blue;
  padding-left: 15px;
}

#d3 {
  padding-left: 15px;
  color: red;
  background-color: yellow;
}

<div id="d1">d1</div>
<div id="d2">d1</div>
<div id="d3">d3</div>

Instead of adding a color:red for each element, we can do

#d1,#d2,#d3 {
  color: red;
}

Snippet below

#d1 {
  background-color: green;
}
#d2 {
  background-color: blue;
}
#d3 {
  background-color: yellow;
}
#d1,#d2,#d3 {
  color: red;
}

<div id="d1">d1</div>
<div id="d2">d1</div>
<div id="d3">d3</div>


问:
What is Object Mocking and when do I need it?
Many people use Mock Objects when they are writing unit tests. What is a Mock Object? Why would I ever need one? Do I need a Mock Object Framework?

答:
Object Mocking is a way to create a "virtual" or mocked object from an interface, abstract class, or class with virtual methods.  It allows you to sort of wrap one of these in your own definition for testing purposes.  It is useful for making an object that is relied on for a certain code block your are testing.

A popular one that I like to use is called Moq, but there are many others like RhinoMock and numerous ones that I don't know about.


问:
LINQ to SQL for self-referencing tables?
I have a self referencing Categories table. Each Category has a CategoryID, ParentCategoryID, CategoryName, etc. And each category can have any number of sub categories, and each of those sub categories can have any number of sub categories, and so and and so forth. So basically the tree can be X levels deep.

Then Products are associated to leaf (sub) Categories. Is there a way to get all the Products for any given Category (which would be all the products associated to all its leaf descendants) using LINQ to SQL?

This feels like a recursive problem. Is it better to used a Stored Procedure instead?

答:
The performant approach is to create an insert/modify/delete trigger which maintains an entirely different table which contains node-ancestor pairs for all ancestors of all nodes. This way, the lookup is O(N).

To use it for getting all products belonging to a node and all of its descendants, you can just select all category nodes which have your target node as an ancestor. After this, you simply select any products belonging to any of these categories.

OwnerDisplayName: Ricky

OwnerDisplayName: Sander


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答: Absolutely while! But my programming experience is pretty recent.

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych

OwnerDisplayName: Tunnuz