text:
Q: Redirect to login page on "page not found" - Laravel 5.4 I want to make so that if the user is not logged in and the page is not found (unexisting route), the user to be redirected to the login page instead to show the 404 page. If the user is logged in then the 404 page should be displayed. I'm using Laravel 5.4.

A: Use this in your Exceptions/Handler.php
 public function render($request, Exception $e)
    {
        if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException){

            return response(redirect(url('/')), 404);
        }
        return parent::render($request, $e);

    }

A: You can listen for any exception in App\Exceptions\Handler@render:
if ($e instanceof NotFoundHttpException) {
    if ( \Auth::guest() ) {
        return redirect()->to('/login');
    }

    return response()->view('errors.404', [], 404);
}

Don't forget use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; at the top of your file.
EDIT
You have to enable the session for all routes so you can have the user data on not found routes. In your app/Http/Kernel.php add the following items to the $middleware array:
protected $middleware = [
    ....

    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
];

A: The correct way to implement this would be as follows;
Route::group(['middleware' => ['auth']], function() {
  // add your routes here;
});

Single route;
Route::get('profile', function () {
    // Only authenticated users
})->middleware('auth');


text:
Q: Mule EE jars vs CE jars We are using mule (enterprise edition) and are debating whether to use EE jars (whenever available) or CE jars. Is there a reason to go one way or another. The application is eventually going to deployed in Mule Enterprise edition.

A: You need to use the EE jars in order to have the EE versions of the XML schemas to resolve properly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Invalid Host Header when ngrok tries to connect to React dev server I'm trying to test my React application on a mobile device. I'm using ngrok to make my local server available to other devices and have gotten this working with a variety of other applications. However, when I try to connect ngrok to the React dev server, I get the error:
Invalid Host Header

I believe that React blocks all requests from another source by default. Any thoughts?

A: I'm encountering a similar issue and found two solutions that work as far as viewing the application directly in a browser
ngrok http 8080 --host-header="localhost:8080"
ngrok http --host-header=rewrite 8080

obviously, replace 8080 with whatever port you're running on
this solution still raises an error when I use this in an embedded page, that pulls the bundle.js from the react app. I think since it rewrites the header to localhost when this is embedded, it's looking to localhost, which the app is no longer running on

A: If you use webpack devServer the simplest way is to set disableHostCheck, check webpack doc like this
devServer: {
    contentBase: path.join(__dirname, './dist'),
    compress: true,
    host: 'localhost',
    // host: '0.0.0.0',
    port: 8080,
    disableHostCheck: true //for ngrok
},

A: Option 1
If you do not need to use Authentication you can add configs to ngrok commands

ngrok http 9000 --host-header=rewrite

or

ngrok http 9000 --host-header="localhost:9000"

But in this case Authentication will not work on your website because ngrok rewriting headers and session is not valid for your ngrok domain
Option 2
If you are using webpack you can add the following configuration
devServer: {
    disableHostCheck: true
}

In that case Authentication header will be valid for your ngrok domain

A: I used this set up in a react app that works. I created a config file named configstrp.js that contains the following:
module.exports = {
ngrok: {
// use the local frontend port to connect
enabled: process.env.NODE_ENV !== 'production',
port: process.env.PORT || 3000,
subdomain: process.env.NGROK_SUBDOMAIN,
authtoken: process.env.NGROK_AUTHTOKEN
},   }

Require the file in the server.
const configstrp      = require('./config/configstrp.js');
const ngrok = configstrp.ngrok.enabled ? require('ngrok') : null;

and connect as such
if (ngrok) {
console.log('If nGronk')
ngrok.connect(
    {
    addr: configstrp.ngrok.port,
    subdomain: configstrp.ngrok.subdomain,
    authtoken: configstrp.ngrok.authtoken,
    host_header:3000
  },
  (err, url) => {
    if (err) {

    } else {

    }
   }
  );
 }

Do not pass a subdomain if you do not have a custom domain

A: Don't know why but tried everything and it didn't work for me.
What finally worked for me is this:
ngrok http https://localhost:4200 -host-header="localhost:4200"
it might be useful for someone

A: Windows, ngrok v3
ngrok http <url> --host-header=<host>:<port>

A:
I am attaching a error image which i was facing but after a google and documentation search, i found the exact solution.
ngrok http 4200 --host-header="localhost:4200"

NOTE : I was working on angular that's why I used 4200 port, but you can select a port as per your requirement.
#angular #ngrok #localhost


text:
Q: How to configure File[] on Maven plugin? I have a Maven plugin that expects File[] for one of its config parameters (docs: maven-failsafeplugin). How do you configure such parameter in pom.xml? Ideally, I would like to say "include all files in directory X" or "my-test-output/*.xml".

A: <executions>
    <execution>
        <configuration>
          <summaryFile>path/to/file</summaryFile>
          <summaryFile>path/to/file2</summaryFile>
          <summaryFile>...</summaryFile>
        </configuration>
    <execution/>
    <execution>
        ....
    <execution/>
</executions>

Look at the usage page for more info and samples

A: The File[] should be reflected by some collection type element in which you can nest.
For example summaryFiles:
<summaryFiles>
    <summaryFile>/topping/*.xml</pizza>
    <summaryFile>/topping/special/cheese.xml</pizza>
</summaryFiles>


text:
Q: End of Record Indicator in MySQL Query I'm trying to write and automate a MySQL query that gets ingested by some downstream reporting platforms.  The platform requires the CSV to have an end or record indicator (EOR) to show the last record in the document.  They're wanting a dollar sign ($) to indicate the EOR and, while it's easy to manually enter that, I want to automate the report but can't seem to find a way to enter the $ in the last row, last cell.  Any ideas?
Example:

First name
Last name
DOB

Mike
Smith
1-1-1900

Mike
Jones
1-1-1900

$

A: Just append it with a UNION ALL statement -
<YOUR_SELECT_QUERY>
UNION ALL
SELECT '$', <NULLS FOR OTHER_COLS>;

You have to use as many NULLS in your last union statement as there are columns in your first query to match the no of columns in your query.


text:
Q: Trying to find a live action movie with CGI monsters The story involved a family (single mother) who moves into a new house.  It turns out that this house is special and goblin like creatures are trying to get into it because there is a book inside which they want.
The house is protected with a magical barrier and the only way the kids can see the monsters is by using some sort of seeing device.  At the end they travel to some place where they meet someone they thought was dead (grand father possibly).  They want to take him back but he can't go because if he returns he would age and die.
The movie is not that old since it had CGI monsters and it was shown on Hulu some time ago.  The language of the movie was English.

A: Sounds like The Spiderwick Chronicles.
From the Wiki description, we see some of the main points:
Single-mother family, new house, goblins:

Recently divorced Helen Grace (Mary-Louise Parker) moves into the Spiderwick Estate in the woods with her children when it is given to her by her elderly aunt Lucinda (Joan Plowright), though identical twins Jared and Simon (Freddie Highmore) and their older sister Mallory (Sarah Bolger) do not want to move from New York. When Jared uncovers a dumbwaiter system behind a wall, he finds a monogrammed key and discovers the study of the late owner of the estate, Arthur Spiderwick (David Strathairn). Jared then uses the key to open a chest. In it, he finds Spiderwick's field guide to fairies; although an attached note warns him not to read it, he does so anyway. When Jared explained about his discovery on the existence of magical creatures, Helen and Mallory don't believe him.

Device to see the creatures that are normally invisible, house protected by magic:

Soon after, Jared meets a brownie named Thimbletack (Martin Short), who explains that magical creatures are normally invisible, but can reveal themselves at will. He tells Jared about a protective circle that Arthur Spiderwick placed around the house and gives him a stone with a hole through which he can see fairies.

Monsters want the book:

However, a shapeshifting ogre named Mulgarath (Nick Nolte) wants the field guide for himself so he can rule over all fairy-kind. He sends his goblins, led by Redcap (Ron Perlman) the Pompous Goblin General, to obtain it and they kidnap Simon, mistaking him for Jared. Meanwhile, Jared meets Hogsqueal (Seth Rogen), a hobgoblin and bitter enemy of Mulgarath because Mulgarath killed his entire family. Hogsqueal gives Jared the ability to see fairies without the aid of the stone by spitting in his eyes.

"At the end they travel to some place where they meet someone they thought was dead (grand father possibly). They want to take him back but he can't go because if he returns he would age and die.":

Suddenly, the Sylphs appear, bringing Arthur, as he was allowed to visit his home since the book was now safe. He cannot remain outside of the fairie realm, or he will turn to dust.

Here's a trailer to see for yourself if it sparks memories:


text:
Q: pandas series sort_index() not working with kind='mergesort' I needed a stable index sorting for DataFrames, when I had this problem:
In cases where a DataFrame becomes a Series (when only a single column matches the selection), the kind argument returns an error. See example:
import pandas as pd
df_a = pd.Series(range(10))
df_b = pd.Series(range(100, 110))
df = pd.concat([df_a, df_b])
df.sort_index(kind='mergesort')

with the following error:
----> 6 df.sort_index(kind='mergesort')

TypeError: sort_index() got an unexpected keyword argument 'kind'

If DataFrames (more then one column is selected), mergesort works ok.
EDIT:
When selecting a single column from a DataFrame for example:
import pandas as pd
import numpy as np
df_a = pd.DataFrame(np.array(range(25)).reshape(5,5))
df_b = pd.DataFrame(np.array(range(100, 125)).reshape(5,5))
df = pd.concat([df_a, df_b])

the following returns an error:
df[0].sort_index(kind='mergesort')

...since the selection is casted to a pandas Series, and as pointed out the pandas.Series.sort_index documentation contains a bug.
However,
df[[0]].sort_index(kind='mergesort')

works alright, since its type continues to be a DataFrame.

A: pandas.Series.sort_index() has no kind parameter.
here is the definition of this function for Pandas 0.18.1 (file: ./pandas/core/series.py):
# line 1729
@Appender(generic._shared_docs['sort_index'] % _shared_doc_kwargs)
def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
               sort_remaining=True):

    axis = self._get_axis_number(axis)
    index = self.index
    if level is not None:
        new_index, indexer = index.sortlevel(level, ascending=ascending,
                                             sort_remaining=sort_remaining)
    elif isinstance(index, MultiIndex):
        from pandas.core.groupby import _lexsort_indexer
        indexer = _lexsort_indexer(index.labels, orders=ascending)
        indexer = com._ensure_platform_int(indexer)
        new_index = index.take(indexer)
    else:
        new_index, indexer = index.sort_values(return_indexer=True,
                                               ascending=ascending)

    new_values = self._values.take(indexer)
    result = self._constructor(new_values, index=new_index)

    if inplace:
        self._update_inplace(result)
    else:
        return result.__finalize__(self)

file ./pandas/core/generic.py, line 39
_shared_doc_kwargs = dict(axes='keywords for axes', klass='NDFrame',
                          axes_single_arg='int or labels for object',
                          args_transpose='axes to permute (int or label for'
                          ' object)')

So most probably it's a bug in the pandas documentation...
Your df is Series, it's not a  data frame


text:
Q: How to display a column value in "hint" property in Oracle Forms 6i? I'm new in Oracle Forms and I would like to display in "Hint" section of my forms a value from every column comments from the table used in the forms. Do you have any idea? Thanks.

A: You can use get_item_property and set_item_property to dynamically get and set the hint text from items:

Get_Item_Property(it_id,HINT_TEXT);
Set_Item_Property(it_id,HINT_TEXT,'value');

A: Maybe you want to retrive column table comments in the following way:
select comments
from all_col_comments
where table_name = 'EMPLOYEES'
and column_name = 'FIRST_NAME';

In a form trigger WHEN_NEW_ITEM_INSTANCE at form level,
you could retrive that comment according to the current item and current block.


text:
Q: Using reflection to trim all strings on an object Say I have a simple model structure like below and I want to trim the whitespace off of each string in the nested model (Request which contains a Friend)
{
    public string id { get; set; }
    public string name { get; set; }
}

public class Request
{
    public string name{ get; set; }
    public string street { get; set; }
    public List<string> tags { get; set; }
    public Friend friend { get; set; }
    public string greeting { get; set; }
    public string favoriteFruit { get; set; }
}

This implementation only handles the strings on the top Request level - I need to be able to handle the Friend level (nested) strings as well.
private static T TrimWhiteSpaceOnRequest<T>(T obj)
    {
        if (obj != null)
        {
            PropertyInfo[] properties = obj!.GetType().GetProperties();
            foreach (PropertyInfo property in properties) {
                try
                {
                    if (property.PropertyType == typeof(string))
                    {
                        var o = property.GetValue(obj, null) ?? "";
                        string s = (string)o;
                        property.SetValue(obj, s.Trim());
                    }
                    else
                    {
                        //handle nested Friend object here

                    }
                }
                catch (Exception)
                {
                    log.info("Error converting field " + field.getName());
                }
            }

        }
        return obj;
    }

What can I put in the else to reach the nested layer?

A: You can recursively call TrimWhiteSpaceOnRequest on the value of non-string properties:
else
{
    TrimWhiteSpaceOnRequest(property.GetValue(obj));
}

A: You can call your TrimWhiteSpaceOnRequest function on the value of any property that isn't a string.
if (prop.PropertyType == typeof(string)
{
    // Your existing code...
}
else
{
    TrimWhiteSpaceOnRequest(property.GetValue(obj));
}

However, that won't get you all the way there. You also need to deal with properties that are collections, like IEnumerable. For example, what if instead of a single Friend instance Request could have multiple Friend instances?
You could handle that by checking to see if obj can be cast to System.Collections.IEnumerable, iterating through it if it can and calling TrimWhiteSpaceOnRequest on each instance in the IEnumerable.
public static void TrimWhiteSpaceOnRequest<T>(this T obj)
{
    if (obj != null)
    {
        System.Collections.IEnumerable objAsEnumerable = obj as System.Collections.IEnumerable;
        if (objAsEnumerable != null)
        {
            foreach (object enumerableObj in objAsEnumerable)
            {
                if (enumerableObj != null)
                {
                    TrimStringProperties(enumerableObj);
                }
            }
            return;
        }
        // The rest of your code...
    }
}

However, that still isn't going to get you there. You also need to handle mutable collections of string, for example your Request.tags property.
One approach to handling that would be to see if obj can be cast to a System.Collections.Generic.IList<string>. If it can, iterate through it via a for loop and trim each non-null string.
public static void TrimWhiteSpaceOnRequest<T>(this T obj)
{
    if (obj != null)
    {
        System.Collections.Generic.IList<string> objAsList = obj as System.Collections.Generic.IList<string>;
        if (objAsList != null)
        {
            for (int i = 0; i < objAsList.Count; i++)
            {
                string listObject = objAsList[i];
                if (listObject != null)
                {
                    objAsList[i] = listObject.Trim();
                }
            }
            return;
        }
        // Check if obj is IEnumerable...
        // The rest of your code...
    }
}

This should handle your Request class as you've presented it. But, you're likely to encounter cases that aren't covered here as you add to that class, or if you try to use TrimWhiteSpaceOnRequest on other classes.


text:
Q: Alamofire: How to get parts of response JSON I have a question about Alamofire.
I'm doing this:
var mutableURLRequest = NSMutableURLRequest(URL:url!)
        mutableURLRequest.setValue(response!.allHeaderFields["TOKEN"] as! String, forHTTPHeaderField: "X-AUTH-TOKEN")
        mutableURLRequest.HTTPMethod = "GET"

        let manager = Alamofire.Manager.sharedInstance // or create a new one
        let request = manager.request(mutableURLRequest)
        request.responseJSON { (request, response, string, error) in
            println(response!.statusCode)
            println(string!)

        }

When I print string the output is JSON. I want to search for a single element (f.e. username or something else) in that JSON response.
How can I do that?
Thank you and best regards,
Alban Veliu

A: You can do it in Swift, but IMHO it's a lot easier using the SwiftyJSON framework. It has an excellent tutorial and documentation and you should be up an running in no time : https://github.com/SwiftyJSON/SwiftyJSON


text:
Q: Playing samples with different sample_spec's in PulseAudio I am developing an application that receives a stream of audio samples from a remote server via custom UDP protocol. The stream consists of small sequences of samples, every sequence may have different number of channels and rate.
As I understand, the sample_spec of the stream can only be set during the stream's creation (pa_simple_new, pa_stream_new, etc) and there is no way to switch it afterwards.
My question is: what would be the most efficient approach to these samples' playback in PulseAudio? I see three options:

*

*Keep a single PulseAudio stream, manually resample the sample sequences and mix channels when needed (in order to feed PulseAudio with samples of the same sample_spec)

*Keep a single PulseAudio stream, close and reopen it with new sample_spec when specs change

*Keep a number of streams, one for every kind of samples I have to work with

Option 1 seems like a lot of manual work, and pretty much resource-consuming, too. Option 2 seems to be terribly inefficient. Option 3 looks like probably the best one, but I am concerned about resource consumption. Is there something I may be missing?

A: Resampling yourself would be a wasted effort. You do have the option of updating the sample rate dynamically. You need to set the PA_STREAM_VARIABLE_RATE and use pa_stream_update_sample_rate(). This still doesn't handle sample spec changes, though.
2 and 3 are both valid, and clearly there's a tradeoff between allocating resources up front (option 3) and having a minor performance penalty (option 2). To be quite honest, stream creation isn't that expensive, and holding a stream shouldn't be high overhead either (unless you're in a severely resource-constrained environment).
So if you've got a fixed number of spec/rate combinations, just create the streams upfront. If the change in spec/rate is rare, just tear down and recreate the stream again.


text:
Q: PHP sending HTML to JS I have a div on the page where the contents change depending on the value selected in a drop down. Because there is a large amount of formatted content in this div I want to have a php script supply html which is stored in a file on the system.
I can't seam to figure out how to have php return the contents of that file, which essentially contains many div tags and content, as text to the ajax script. Which would then change the content in the div on the page.
The back end php is using CakePHP and using YUI3 as the front end framework.
A solution doesn't need to include any Cake if need be.
Thanks!

A: readfile()

A: "I can't seam to figure out how to have php return the contents of that file"
echo file_get_contents( $filepath );

For the ajax part in the website (although you don't seem to ask for that):
var xmlhttp;
if( window.XMLHttpRequest )
    xmlhttp = new XMLHttpRequest();
else if( window.ActiveXObject )
    xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP" );     // Use ActiveX in IE
else {
    alert( 'Your browser doesn\'t support XMLHttpRequest.' );
    return;
}
xmlhttp.eid = eid; // <-- id of the div to be filled with the content from the file
xmlhttp.onreadystatechange = function() {
    if( xmlhttp.readyState == 4 ) {
        document.getElementById( xmlhttp.eid ).innerHTML = xmlhttp.responseText;
    }
}
xmlhttp.open( "GET", "phpfile.php", true );
xmlhttp.send( null );

Edit: Please consider that this solution may not be the way it's done with your framework.

A: You can also create view for each type of html form and return it through ajax helper. It will give you more flexibility; you can even add some php logic to this html form and so on...
Storing formatted html form in file is too primitive because it is really easy to imagine the situation when you'll need to fill some  tags with content from your DB. Doing it with "view" will give you this opportunity.
Best regards.


text:
Q: finding the ionic.zip.dll in dotnetzip Sure I am being stupid but I can't find the ionic.zip.dll
On their page I clicked on the download archive button. I have unzipped all the files but I can't see the dll. Clearly I am doing something wrong but what?
I have search the folder foe the file and nothing is returned

A: The dll is within this download, it's just been renamed in a manifest, as can been viewed within the json file '\releases\releaseList.json'
To access the latest version, extract the following file:
'\releases\9\f8f1b2b3-518d-4802-ab92-ac64f37b6c85'

Rename this file to 'DotNetZipLib-DevKit-v1.9.zip'
Within this zip there are a few different projects (I'm assuming zip-v1.9 is the .net zip package)
eg: '\zip-v1.9\Release\Ionic.Zip.dll'

A: The legacy DotNetZip project was moved into the Archive on CodePlex.  To get the Ionic.Zip.Dll from the Archive download, some file manipulation is needed:

*

*Extract the archive download.

*Navigate to \releases\9

*Locate the file called 5cea1d3e-6620-4516-b3db-ea1791d01f90
(the file mentioned in the other answer does not contain the dll)

*In Windows Explorer, right-click the above file and select Copy (or press CTRL+C)

*Press CTRL+V to paste as a new file, and name it tools.zip or some other appropriate name

*Double-click the tools.zip you just created, and you'll find not only the DLL you seek but also various compiled EXE's including the sample WinForm.

NOTES

*

*I'd have made this correction to the other answer but don't have sufficient reputation yet to do so.

*If you want the most up-to-date versions, you may consider alternatively using NuGet in Visual Studio to simply add DotNetZip to your project, and do an Imports Ionic.Zip

*The OP may not need this answer at this point, but I was just looking for this answer myself so I'm posting this in case it helps others.  However big thanks to @Radderz for getting me 90% of the way there.

*You'll find the DLL in some of the other files, too, but the one I mentioned has the other compiled tools as well, which might be useful.

*Don't overlook the license file - it's in one of the other accompanying files.


text:
Q: extract IP and port from string in vb.net i have string
Timestamp: 1594312360   Host: 127.0.0.1 ()        Ports: 22/open/tcp//ssh//
Timestamp: 1412355121   Host: 127.0.0.1 ()  Ports: 21/open/tcp//telnet//
Timestamp: 1594741231  Host: 127.0.0.1 ()        Ports: 8080/open/tcp//http//
Timestamp: 1232370123   Host: 127.0.0.1 ()  Ports: 443/open/tcp//https//

and i would like a with just the ip:Port
127.0.0.1:22
127.0.0.1:21
127.0.0.1:8080
127.0.0.1:443

can anyone help me do this i am using Vb.net
if use Regex no problem

A: Split it on space (your data appears to contain spaces rather than tabs), with the RemoveEmptyEntries option set:
For Each line in File.ReadLines("c:\temp\mylog.txt")

  'line is eg "Timestamp: 1594312360   Host: 127.0.0.1 ()        Ports: 22/open/tcp//ssh//"
  Dim array = line.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)

Next line

Array now contains:
(0): Timestamp:
(1): 1594312360
(2): Host:
(3): 127.0.0.1
(4): ()
(5): Ports:
(6): 22/open/tcp//ssh//

You can reach the IP using the third index and the port via the 6th, or last (which you choose depends on what your data contains on other lines we can't see)
You'll have to discard everthing after the first index of '/' in the ports line:
Dim port = array(6).Remove(array(6).IndexOf("/"c))

If you want to use regex (which you should indicate in your question; by just asking open ended "how can i?" it doesn't impose any constraint as to how..) you can look at something like:
Dim r = new Regex("Host: (?<ip>[0-9.]+).*?Ports: (?<p>\d+)")

Dim m = r.Match(line)

Console.WriteLine(m.Groups("ip").Value)
Console.WriteLine(m.Groups("p").Value)

The regex means

Host: (?<ip>[0-9.]+).*?Ports: (?<p>\d+)

Find Host: , followed by multiple digits or periods and capture them into a group named ip, followed by any number of anything until the word Ports: , followed by any number of digits captured into a group named p


text:
Q: get the current scope of the users oauth token in Google API? Is is possible to obtain the scope(Google API's) an Oauth token can access??
I have tried searching for it but no luck.
However facebook has something called as access token debugger which does the job does google have something similar to it ?

A: you can call Google's tokeninfo endpoint, as in:
curl https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=<access_token>

and get back something similar to:
{
 "issued_to": "<>
 "audience": "<>
 "user_id": "<>
 "scope": "https://www.googleapis.com/auth/plus.me",
 "expires_in": 3245,
 "access_type": "offline"
}


text:
Q: Books not appearing in iBooks on iPad I have several books in my iBooks app on my iPad, but when I'm without wifi, ibooks doesn't even show the books are sitting in my library, why?

A: If the books don't show up when offline that means that they have not actually been downloaded to your iPad. You should see a little cloud icon in the corner of the book icon to say that it's on the cloud rather than the device.


text:
Q: Does not name a type error for c++ namespace So I was building a C++ program and I have no idea how to solve this namespace issue. I am running on C++17 so there shouldn't be an issue with nested namespaces. I keep getting the error on line 3 in the .cpp file.
This is the .h file:
#include <memory>
#include "Entity.h"

namespace Hearthstonerepl::Action
{
    class Playcard
    {
    private:
        std::unique_ptr<Entity> card;

    public:
        Playcard(std::unique_ptr<Entity>& Card);
        ~Playcard() = default;
    };
}

And this is the .cpp file:
#include "Playcard.h"

namespace Hearthstonerepl::Action // error: expected '{' before '::' token
                                  //'Action' in namespace '::' does not name a type
{
    Playcard::Playcard(std::unique_ptr<Entity>& Card)
    {
        card = std::move(Card);
    }
}

Thanks!


text:
Q: Is there a polynomial-time algorithm to find a prime larger than $n$? Is there a polynomial-time algorithm to find a prime larger than $n$?
If Cramér's conjecture is true, we can use AKS to test $n+1$, $n+2$, etc. until the next prime is found, and this method will find a prime in polynomial time (in $\log n$) because AKS runs in polynomial time and Cramér's conjecture guarantees $O((\log{n})^2)$ primes to test.
Without assuming Cramér's conjecture, and without requiring that the prime to be found is the next prime following $n$, only that it is larger than $n$, can such a prime be found in time $O((\log{n})^k)$ for some $k$?
This question is motivated by some thoughts I wrote about in the comments on this answer by Gerry Myerson.

A: This is Rick Sladkey's comment as a CW answer. An algorithm is given in this paper: "Deterministic Methods to Find Primes".


text:
Q: DBUnit issue with hibernate statelessSession I'm trying to test my code using Spring and DBunit (http://springtestdbunit.github.io/)
Once inside the unit test:
sessionFactory.getCurrentSession().createCriteria(MyEntity.class).list()

will return the list of entities inserted by DBUnit, so it did insert records in teh database (MYSQL).
But:
sessionFactory.openStatelessSession().createCriteria(MyEntity.class).scroll(FORWARD_ONLY).next()

will return false! It can't find any records using the stateless session.
Beforehand, I use to insert the same records using Liquibase, and this piece of code worked perfectly.
Using HSql it's even worse, it totally freezes when trying to open the stateless session... (on the scroll() instruction...)
Thank you for your help!

A: OK! So this actually have nothing to do with DBunit, sort of...
This code simple shows the same issue, and no DBUnit involve:
MyEntity myEntity = new MyEntity ();
    sessionFactory.getCurrentSession().save(myEntity );
    assertEquals(1, sessionFactory.getCurrentSession().createCriteria(MyEntity .class).list()
            .size());
    assertTrue(sessionFactory.openStatelessSession().createCriteria(MyEntity .class)
            .scroll(ScrollMode.FORWARD_ONLY).next());

First assert is ok, second fails.
So I guess it is a simple hibernate problem, and I also guess that liquibase was doing something to prevent it somehow... Probably a transaction issue?

A: SO! It seems to be a transaction issue in the end as a simple
sessionFactory.getCurrentSession().getTransaction().commit();

make the test go green!
Question now is how to make DBUnit commit the transaction I suppose...
At the beginning of the test, after DBUnit initialization, I run:
sessionFactory.getCurrentSession().getTransaction().wasCommitted()

And it returns false. This think the issue comes from there.

A: Problem solved!
Thanks to this:
https://tadaya.wordpress.com/2008/04/27/transaction-aware-datasource-use-dbunit-hibernate-in-spring/


text:
Q: mysql функция возврат всех значений Подскажите как реализовать. Есть функция на сервере,
 BEGIN
 DECLARE v1 INT DEFAULT 5;
 DECLARE rs VARCHAR(50);
 DECLARE i INT;
 DECLARE counter INT;
 SET i = (SELECT COUNT(*) FROM invoice WHERE STATUS = 'personAgree');
 SET counter = 1;
 WHILE i <= counter DO
 SET counter = counter +1;
 SET rs = rs + ':' + (SELECT id INTO rs FROM invoice WHERE STATUS = 'personAgree');
END WHILE;
RETURN rs;
 END

Хочу сделать так, чтобы по запросу этой функции она собрала значение всех строк, удовлетворяющим критериям в одну переменную rs и вернула  эту строку. Но не могу понять как это правильно сделать?


text:
Q: How does apache PHP memory usage really work? To give some context:
I had a discussion with a colleague recently about the use of Autoloaders in PHP. I was arguing in favour of them, him against.
My point of view is that Autoloaders can help you minimise manual source dependency which in turn can help you reduce the amount of memory consumed when including lots of large files that you may not need.
His response was that including files that you do not need is not a big problem because after a file has been included once it is kept in memory by the Apache child process and this portion of memory will be available for subsequent requests. He argues that you should not be concerned about the amount of included files because soon enough they will all be loaded into memory and used on-demand from memory. Therefore memory is less of an issue and the overhead of trying to find the file you need on the filesystem is much more of a concern.
He's a smart guy and tends to know what he's talking about. However, I always thought that the memory used by Apache and PHP was specific to that particular request being handled.
Each request is assigned an amount of memory equal to memory_limit PHP option and any source compilation and processing is only valid for the life of the request.
Even with op-code caches such as APC, I thought that the individual request still needs to load up each file in it's own portion of memory and that APC is just a shortcut to having it pre-compiled for the responding process.
I've been searching for some documentation on this but haven't managed to find anything so far. I would really appreciate it if someone can point me to any useful documentation on this topic.
UPDATE:
Just to clarify, the autoloader discussion part was more of a context :).
It may not have been clear but my main question is about whether Apache will pool together its resources to respond to multiple requests (especially memory used by included files), or whether each request will need to retrieve the code required to satisfy the execution path in isolation from other requests handled from the same process.
e.g.:
Files 1, 2, 3 and 4 are an equal size of 100KB each.
Request A includes file 1, 2 and 3.
Request B includes file 1, 2, 3 and 4.
In his mind he's thinking that Request A will consume 300KB for the entirety of it's execution and Request B will only consume a further 100KB because files 1,2 and 3 are already in memory.
In my mind it's 300KB and 400KB because they are both being processed independently (if by the same process).
This brings him back to his argument that "just include the lot 'cos you'll use it anyway" as opposed to my "only include what you need to keep the request size down".
This is fairly fundamental to how I approach building a PHP website, so I would be keen to know if I'm off the mark here.
I've also always been of the belief that for large-scale website memory is the most precious resource and more of a concern than file-system checks for an autoloader that are probably cached by the kernel anyway.
You're right though, it's time to benchmark!

A: Here's how you win arguments: run realistic benchmark, and be on the right side of the numbers.
I've had this same discussion, so I tried an experiment. Using APC, I tried a Kohana app with a single monolithic include (containing all of Kohana) as well as with the standard autoloader. The final result was that the single include was faster at a statistically irrelevant rate (less than 1%) but used slightly more memory (according to PHP's memory functions). Running the test without APC (or XCache, etc) is pointless, so I didn't bother.
So my conclusion was to continue use autoloading because it's much simpler to use. Try the same thing with your app and show your friend the results.
Now you don't need to guess.
Disclaimer: I wasn't using Apache. I cannot emphasize enough to run your own benchmarks on your own hardware on your own app. Don't trust that my experience will be yours.

A: You are the wiser ninja, grasshopper.
Autoloaders don't load the class file until the class is requested.  This means that they will use at most the same amount memory as manual includes, but usually much less.
Classes get read fresh from file each request even if an apache thread can handle multiple requests, so your friends 'eventuall all are read' doesn't hold water.
You can prove this by putting an echo 'foo'; above the class definition in the class file.  You'll see on each new request the line will be executed regardless of if you autoload or manually include the whole world of class files at start.
I couldn't find any good concise documentation on this--i may write some with some memory usage examples--as i also have had to explain this to others and show evidence to get it to sink in.  I think the folks at zend didn't think anyone would not see the benifits of autoloading.
Yes, apc and such (like all caching solutions) can overcome the resouce negatives and even eek out small gains in performance, but you eat up lots of unneeded memory if you do this on a non-trivial number of libraries and serving a large number of clients. Try something Like loading a healthy chunk of the pear libraries in a massive include file while handling 500 connections hitting your page at the same time.
Even using things like Apc you benefit from using autoloaders with any non-namespaced classes (most of the existing php code currently) as it can help avoid global namespace pollution when dealing with large  umbers of class libraries.

A: This is my opionion.
I think autoloaders are a very bad idea for the following reasons

*

*I like to know what and where my scripts are grabbing the data/code from. Makes debugging easier.

*This also has configuration problems in so far as if one of your developers changes the file (upgrade etc) or configuration and things stop working it is harder to find out where it is broken.

*I also think that it is lazy programming.

As to memory/preformance issues it is just as cheap to buy some more memory for the computer if it is struggling with that.


text:
Q: Reroute From Direct URL to Partial unless from modal I'm having a bit of trouble stopping direct access to my partial pages. For example Home/Create I don't want accessible or would return them to Home/Index.
I can't seem to use the [ChildActionOnly] attribute in the controller as it stops the partial appearing in a modal pop up which I use in conjuncture with jQuery.
Is there a way of doing this?

A: You can check whether the request is an ajax request or not and return/redirect based on that. Use the Request.IsAjaxRequest() method inside your controller aciton.
public ActionResult Create()
{
   if(Request.IsAjaxRequest())
   {
     // return partial view
      return PartialView("Create");
   }
   return RedirectToAction("Index");
}

Internally, this method will check the request headers and look for "X-Requested-With" header. When your call is an ajax call, the value will be "XMLHttpRequest"
Side note  : Angualar http service won't send this header by default. You need to explicitly enable it.
var app= angular.module('yourApp', []);

app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);


text:
Q: WooCommerce Modify Line Breaking of Address Information It seems WooCommerce breaks Shipping/Billing Information prematurely (it's rather unprofessional looking). I'd like to know how to override it.
The way it posts:
First Name Last Name
Company
Street Address
City
State
Zip
It really should be (at least in the United States):
First Name Last Name
Company
Street Address
City, State Zip
Any recommendations?

A: Use the following function hooked in woocommerce_localisation_address_formats filter hook, to change the displayed formatted address for United States of America as desired:
add_filter( 'woocommerce_localisation_address_formats', 'change_usa_localisation_address_format', 20, 2 );
function change_usa_localisation_address_format( $address_formats ){
    $address_formats['US'] = "{name}\n{company}\n{address_1} {address_2}\n{city}, {state} {postcode}\n{country}";

    return $address_formats;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.
If you like to don't display country, you will remove from the string at the end: \n{country}…


text:
Q: Addactionlistener doesnot take parameter import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class Concentration extends JFrame implements ActionListener {

    private JButton buttons[][]=new JButton[4][4];
    int i,j,n;

    public Concentration() {
        super ("Concentration");
        JFrame frame=new JFrame();
        setSize(1000,1000);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel=new JPanel(new GridLayout(4,4));
        panel.setSize(400, 400);
        for( i=0; i<buttons.length; i++){
            for (j=0; j<buttons[i].length;j++){
                n=i*buttons.length+buttons[i].length;
                buttons[i][j]=new JButton();
                panel.add(buttons[i][j]);
                buttons[i][j].addActionListener(this);
            }
        }
        add(panel);
        pack();
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        buttons[i][j].setIcon(new ImageIcon(
                 getClass().getResource("/images/2.jpg")));
    }

    public static void main(String args[]){
        new Concentration();
    }
}

This is my code. I am making memory game. I want to make that, each time clicked a button, that button shows image but
 buttons[i][j].addActionListener(this);

in that, methot can not take i and j and doesnot show any image.
But for example when i do
 buttons[2][2].addActionListener(this);

it shows only in 2x2 . image. What can i do to solve that?

A: Possible solutions:

*

*Inside the ActionListener, iterate through the button array to see which JButton in the array matches the button that was pressed, obtained by calling e.getSource()

*Give your JButtons actionCommand Strings that correspond to i and j

*Create a separate ActionListener implementing class that has i and j fields that can be set via a constructor, and give each button a unique ActionListener with i and j set.

A: Try this code:
public void actionPerformed(ActionEvent e) {
    if(e.getSource() instanceof JButton){
        JButton pressedButton = (JButton) e.getSource();
        if(pressedButton.getIcon() == null){
            pressedButton.setIcon(new ImageIcon(getClass().getResource("/images/2.jpg")));
        } else {
            pressedButton.setIcon(null);
        }
    }
}

Direct form EventObject javadoc:

public Object getSource()
The object on which the Event initially occurred.
Returns:
      The object on which the Event initially occurred.

This means there's no need to know the array indexes of pressed button as it could be known through getSource() method.


text:
Q: Bokeh Multi-line with hover I have pandas dataframe which looks like this
           'A' 'B' 'C'
2018/1/1    10  20  20
2018/1/2    34  13  23
2018/1/3    23  45  43
2018/1/4    14  98  76
2018/1/5    58  65  57

How do I convert this to columnDataSource ?
How do I create a multi-line graph in bokeh with hover tool.
X-axis as the date

A: Imports:
import pandas as pd
from bokeh.models import ColumnDataSource, HoverTool
from bokeh.plotting import figure, show, output_notebook
output_notebook()

Here's the data as you present it:
days = ['2018/1/1', '2018/1/2', '2018/1/3', '2018/1/4', '2018/1/5']
data_a = [10, 34, 23, 14, 58]
data_b = [20, 13, 45, 98, 65]
data_c = [20, 23, 43, 76, 57]

Create DataFrame:
df_plot = pd.DataFrame({'A': data_a, 'B': data_b, 'C': data_c}, index=days)

             A   B   C
2018/1/1    10  20  20
2018/1/2    34  13  23
2018/1/3    23  45  43
2018/1/4    14  98  76
2018/1/5    58  65  57

However, the index is not a proper datetime format, so create a dates column with the proper format:
df_plot['dates'] = pd.to_datetime(df_plot.index, format='%Y/%m/%d')

             A   B   C       dates
2018/1/1    10  20  20  2018-01-01
2018/1/2    34  13  23  2018-01-02
2018/1/3    23  45  43  2018-01-03
2018/1/4    14  98  76  2018-01-04
2018/1/5    58  65  57  2018-01-05

Now for the plotting:
source = ColumnDataSource(df_plot)
p = figure(x_axis_type="datetime")
p.line('dates', 'A', source=source, color='red')
p.line('dates', 'B', source=source, color='blue')
p.line('dates', 'C', source=source, color='green')
p.add_tools(HoverTool(tooltips=[("A", "@A"), ("B", "@B"), ("C", "@C")]))
show(p)

This is just a png, the actual output will have hoover tools.


text:
Q: scroll whole page while hovering absolute div I want to scoll the whole page even if I am not hovering the part which is longer than the screen.
Here is the code:

html, body {
    height: 100%;
    margin: 0px;
    background: #3a3a3a;
    overflow: auto;
}

body {
    background: green no-repeat center center;
    background-attachment: fixed;
    -webkit-background-size: cover;
}

.menu, .submenu li {
    line-height: 50px;
    text-align: center;
    font-size: 22px;
    background: #4096ee;
    border-radius: 10px;
    margin-top: 50px;
    cursor: pointer;
    color: white;
    transition: background 0.5s;
}

.submenu li {
    //display: none;
}

.center {
    margin: 0 auto;
    width: 25%;
    position: relative;
    border: 1px solid transparent;
}

#mask {
    background-color: rgba(0,0,0,0.7);
    position: fixed;
    top: 0px;
    left: 0px;
    right: 0px;
    bottom: 0px;
}

klick

one

two

three

four

five

six

seven

eight

nine

ten

I want to scroll while hovering the "margin". Its a little hard to explain, just try to scroll while hovering the green side left or right.
The center-div do not have to be with 25%, it could be in px.

A: Your browser can't scroll an element it hasn't rendered. The center div is only rendered across 25% of the screen (centered horizontally) due to width: 25%; and therefore you can't scroll it on the edges. You could try some JS trickery to make it work with width: 25%; but in reality it's probably easier to just make the list have a margin that gives it a rendered width of 25% and a true width of 100%. Consider that with a left margin of 37.5% and a right margin of 37.5%, the rendered content width is 25% and it's centered/scrollable.
This works because now both the center div takes up the entire width of the screen. The menu just isn't rendering its content across the entire area due to the margin-right and margin-left statements. Try out "inspect element," it's pretty good at showing where the true vs the rendered boundaries of content are.

html, body {
    height: 100%;
    margin: 0px;
    background: #3a3a3a;
    overflow: auto;
}

body {
    background: green no-repeat center center;
    background-attachment: fixed;
    -webkit-background-size: cover;
}

.menu, .submenu li {
    line-height: 50px;
    text-align: center;
    font-size: 22px;
    background: #4096ee;
    border-radius: 10px;
    margin-top: 50px;
    margin-left: 37.5%;
    margin-right: 37.5%;
    cursor: pointer;
    color: white;
    transition: background 0.5s;
}

.submenu li {
    //display: none;
}

.center {
    margin: 0 auto;
    position: relative;
    border: 1px solid transparent;
}

#mask {
    background-color: rgba(0,0,0,0.7);
    position: fixed;
    top: 0px;
    left: 0px;
    right: 0px;
    bottom: 0px;
}

klick

one

two

three

four

five

six

seven

eight

nine

ten


text:
Q: Feed value from a C# .Net Framework Console Application into a Console Command I want to feed the value I get from a .NET Framework console application into the change directory command with the extra argument /d. I don't know how I can achieve this and especially not how I can make my console application return a value that can be used in the command line interface.
What I want to do is something like this in cmd.exe:
myapplication.exe argument1 | cd /d

But how can I do this?
My application would use the argument1 in order to print/return a path which should be then used by the cmd.exe change directory command in order to get to that path. Does anyone know how to do this? (I know how to write C# console applications and how to use the argument my only problem is with outputting the result and feeding it into the cd command)

A: This is a bit hacky, but you could do it using a combination of a batch file and piping the output of your application to a file. Create a .bat file containing the following and run it:
myapplication.exe argument1 > output.txt
set /P cdtarget=<output.txt
cd %cdtarget%


text:
Q: External CSS: How to implement a class from a external css? I'm having trouble figuring out how to use this class from my external css:
.row.rectanglebox {
    margin-top:30px;
    margin-bottom:30px;
    height: 210px;
    border: solid black;
    padding: 20px;
}

I've tried adding the following (which I normally would use) but to no avail:

 sample text

What I'm trying to achieve is the following image:

A: The issue here is that in your CSS file, with .row.rectangle you are saying that any element that contains the .row class, and then the .rectanglebox class, or any element with the row class that has a child element with the .rectanglebox class will have these styles applied to it.
You can either change your code to class="row rectangleclass" or just change your CSS to simply .rectangleclass { ... }

A: You forgot the .row class in your div, do this:
HTML:

 sample text

when you see this: .row.rectanglebox it means that the element have both classes, but your div have only .rectanglebox class.
regards!

A: It works here

.row.rectanglebox {
  margin-top: 30px;
  margin-bottom: 30px;
  height: 210px;
  border: solid black;
  padding: 20px;
}

 sample text


text:
Q: How to put method into the AsyncTask Hello i have little problem. How and where i should put that method in asyncTask or maybe better, how it should look in asyncTask.
Here's my code
public void licz()
{
     wyniki.setText("");
        N = Integer.parseInt(liczbaN.getText().toString());
        tablica = new String [90];
        int i=0;
            for(licz1=99;licz1>=10;licz1--)
            {
                for(licz2=10;licz2<=licz1;licz2++)
                {
                    if(N==licz1/licz2 && licz1%licz2==0)
                    {
                        String nap1 = Integer.toString(licz1);
                        String nap2 = Integer.toString(licz2);
                        napis = (nap1+ " " + nap2 +"\n");   // moj string
                        lista.add(napis);
                        tablica[i]=napis;
                        i++;
                        wyniki.setText("");
                    }
                }
                String listString = "";
                for (String s : tablica)
                {
                    listString += s;
                }
                listString=listString.replaceAll("null", "");
                wyniki.setText(listString);
            }
}

A: *

*Declare the AsyncTask<Void, String, Void>.

*Put this code inside doInBackground().

*Replace all occurences of wyniki.setText(whatever); with publishProgress(whatever);

*In onProgressUpdate(), use wyniki.setText(progress[0]);

The last two steps are important, you cannot change UI views from the background thread.

A: Create a new class that extends AsyncTask and override its doInBackground() method. Put your licz() method inside of it.

A: Implement AsyncTask class and override its methods:
private class MyTask extends AsyncTask<String, Void, String> {
@Override
    protected String doInBackground(String... params) {
        //Put your code here

        return "Executed";
    }

    @Override
    protected void onPostExecute(String result) {
        //do something after background execution is complete
        //Executes on main thread
    }

    @Override
    protected void onPreExecute() {
         //do something before background execution starts
        //Executes on main thread
    }
}

Call new MyTask().execute("");
Note:
Update UI related changes in onPostExecute.

A: Change your method and make it return a String instead of void
public String licz() {
    String result = "";
    // do your fancy array stuff
    return result;
}

Then create a class extending AsyncTask<Void, Void, String> and in the doInBackground() call your method and return the result. Than use the result in the onPostExecute() and update the TextView:
private class MyTask extends AsyncTask<Void, Void, String> {
    @Override
    protected String doInBackground(Void... params) {
        return licz();
    }

    @Override
    protected void onPostExecute(String result) {
        wyniki.setText(result);
    }
}


text:
Q: Eclipse: what is the thing next to the scrollbar called? In the text editing view of Eclipse, there is a vertical bar to the right of the scroll bar. It has little colored markings corresponding to lines of the file with errors/warnings/notes, and you can click the markings (or anywhere on it) to jump to that line. Also when you click a symbol, white or light gray markings light up on the bar corresponding to instances of the symbol in the file.
What is this vertical bar thing called?
(I would screenshot it, but it is not working on my system which is why I'm trying to find the name of it, so that I can search for a solution as to why it seems to have disappeared)

A: In "Window : Preferences : General : Edtors : Text Editors : Annotations" it's called the "overview ruler".
Also in this javadoc.
This bug report indicates that there is a hidden, unsettable, preferences option to turn it off. Might have happened to you.


text:
Q: Windows 2003 hidden anonymous shares with IP restriction I have created anonymous(everyone account) "hidden" shares on Windows 2003 to let our ASP.NET application access it from another server without credentials. I have added $ to share name to hide it from other users, but actually this is not solution because such shares can be easily discovered by other OS or some tools on Win.
Can I restrict shared folder access by IP?
Regards,
Tomas

A: I don't know of any way to do that short of playing with a specialized set of firewall rules; have you considered instead having the application run with particular privileges and giving that application access to the share via that privilege account? I.e., application runs as user foo, and you give foo specific access to the share or folder at the NTFS level (or share level, if you have it set so that would work; I often give shares full access to anyone but restrict everything at the filesystem level for fine-grained access control without troubleshooting interaction between shares and filesystem permissions...)


text:
Q: MD5 Hash Faster I have a wordlist with ~68000 words from level 20 at 0xf.at and want to hash two words to get a hash. Then compare this hash to an existing hash until i found the two words.
I have tried it in java but I am unexpirenced and it is to slow.
import java.io.*;

public class Main {

public static void main(String[] args) throws FileNotFoundException,
        IOException {

    try (BufferedReader br = new BufferedReader(new FileReader("E:/Trojan/Desktop/wordlist.txt"))) {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();
        Hash h = new Hash();
        String myHash = "cd48323bcf01557f5deadc2ec301affb";
        while (line != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine();
        }
        String everything = sb.toString();
        String lines[] = everything.split("\\r?\\n");
        for (int j = 1; j <= 68848; j++) {
            for (int i = 1; i <= 68847; i++) {
                //System.out.println(i+":"+lines[i]+" "+j+":"+lines[j]);
                if (h.getHash(lines[i]+lines[j],  "MD5") == myHash){
                    System.out.println(lines[i]+lines[j]);
                     break;
                }
            }
        }
    }
}
}

And the md5 hash function i took from an exmaple of stackoverflow:
public class Hash {
/**
 *
 * @param txt, text in plain format
 * @param hashType MD5 OR SHA1
 * @return hash in hashType
 */
public static String getHash(String txt, String hashType) {
    try {
                java.security.MessageDigest md = java.security.MessageDigest.getInstance(hashType);
                byte[] array = md.digest(txt.getBytes());
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < array.length; ++i) {
                    sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
             }
                return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
            //error action
        }
        return null;
}

public static String md5(String txt) {
    return Hash.getHash(txt, "MD5");
}

public static String sha1(String txt) {
    return Hash.getHash(txt, "SHA1");
}
}

How can I get this faster?

A: You create too many temporary objects inside method getHash. Try reduce. E.g.
private static final char[] HEX ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f',};
public static String getHash(String txt, MessageDigest md) {
    byte[] array = md.digest(txt.getBytes());
    char[] result = new char[array.length*2];
    for (int i = 0; i < array.length; ++i) {
        byte b = array[i];
        result[2*i] = HEX[(b&0x0f0)>>>4];
        result[2*i+1] = HEX[b&0x0f];
    }
    return new String(result);
}

EDIT
Moreover you do not need String objects at all. You should return byte[] and use Arrays.equals method.


text:
Q: mobilefirst - Response type in Java adapters I have a class (stored in server/java) that returns a Response type object and I want to use it in adapters.
public class CorsResponse {
public static Response build() {
    return Response
            .ok()
            .header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Methods", "GET, POST")
            .header("Access-Control-Allow-Headers", "accept, origin, content-type")
            .header("Access-Control-Max-Age", "1728000")
            .build();
}

If I use this class in an adapter's method, I get an exception:

javax.servlet.ServletException: java.lang.LinkageError: loader
  constraint violation: loader (instance of
  com/ibm/ws/classloading/internal/AppClassLoader) previously initiated
  loading for a different type with name "javax/ws/rs/core/Response" ...
Caused by: java.lang.LinkageError: loader constraint violation: loader
  (instance of com/ibm/ws/classloading/internal/AppClassLoader)
  previously initiated loading for a different type with name
  "javax/ws/rs/core/Response"

How can I set which Response type to load?

A: I have managed to create an external project, put the class there, compile it to a jar file and include it in the adapters/adapter_name/lib folder (added to build path also).

A: If you are interested in a CorsFilter I suggest implementing it like show below and adding the class to your Application instead...
@Provider
public class ResponseCorsFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext,
            ContainerResponseContext responseContext) throws IOException {

        responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");

        String reqHead = requestContext.getHeaderString("Access-Control-Request-Headers");

        if(null != reqHead && !reqHead.equals("")){
            responseContext.getHeaders().add("Access-Control-Allow-Headers", reqHead);
        }

    }

}


text:
Q: Display HTML from access DB while showing the background of the form? So I am trying to display HTML from a column in an access DB. I am able to do this using this below.
webBrowser1.DocumentText = dataGridView1.Rows[1].Cells[3].Value.ToString();

The problem is I want the control to be "transparent" basically show the text with html formatting but show the form background behind it... and I have not found a way to do that.
Is there another way to display this HTML while showing the form background and keep the format of the contents? The HTML is just text with li tags etc.

A: Have you tried applying a style to the stored HTML? You can make things transparent, or coloured using a CSS style.


text:
Q: Is there a countifs function in python pandas I have a dataframe
df.head(9)

+------------+-------------+-------------+------------+---------+-------------+-------+--------+------------------+
| session_id |   Enter     |    Exit     | Difference | User_id |    date     | Buyer | Seller | Non_buyer_seller |
+------------+-------------+-------------+------------+---------+-------------+-------+--------+------------------+
| a          |       43770 |       43770 | 0:00:00    |       1 | 01/Nov/2019 |     1 |      0 |                0 |
| b          | 43770.79991 | 43770.79994 | 0:00:02    |       2 | 01/Nov/2019 |     1 |      0 |                0 |
| c          |  43770.5634 | 43770.56351 | 0:00:09    |       3 | 01/Nov/2019 |     0 |      0 |                1 |
| d          |  43770.5525 |  43770.5528 | 0:00:25    |       4 | 01/Nov/2019 |     1 |      0 |                0 |
| e          | 43770.33724 | 43770.33726 | 0:00:01    |       4 | 01/Nov/2019 |     1 |      0 |                0 |
| f          | 43770.65617 | 43770.65623 | 0:00:05    |       5 | 01/Nov/2019 |     0 |      0 |                1 |
| g          | 43770.54055 | 43770.54093 | 0:00:32    |       6 | 01/Nov/2019 |     0 |      0 |                1 |
| h          | 43770.54203 | 43770.54281 | 0:01:07    |       7 | 01/Nov/2019 |     0 |      0 |                1 |
| i          | 43770.64442 | 43770.64478 | 0:00:31    |       8 | 01/Nov/2019 |     0 |      1 |                0 |
+------------+-------------+-------------+------------+---------+-------------+-------+--------+------------------+

I used to use countifs in excels to count the session like this
Buyers_0-to-1 min : =COUNTIFS($G:$G,1, $D$2:$D$671746,">=00:00:00",$D$2:$D$671746,"<=00:01:00")
Buyers_1.1-to-5 min : =COUNTIFS($G:$G,1, $D$2:$D$671746,">=00:01:01",$D$2:$D$671746,"<=00:05:00")

Sellers_0-to-1 min : =COUNTIFS($H:$H,1, $D$2:$D$671746,">=00:00:00",$D$2:$D$671746,"<=00:01:00")
Non_buyer_sellers_0to-1 min : =COUNTIFS($I:$I,1, $D$2:$D$671746,">=00:00:00",$D$2:$D$671746,"<=00:01:00")

So how can I do the same in python for my data frame.
Thanks in advance

A: To perform the first COUNTIF you listed, you can try this.
import pandas as pd

d = {'Difference': ["00:00:00", "00:00:02", "00:00:09", "00:00:25", "00:00:01", "00:00:05", "00:00:32", "00:01:07", "00:00:31"]}
df = pd.DataFrame(data=d)

# 'Difference' column to timedelta
df['Difference'] = pd.to_timedelta(df['Difference'])

# Conditional sum statement
df[(df.Difference >= "00:00:00") & (df.Difference <= "00:01:00")].sum()

Difference   00:01:45
dtype: timedelta64[ns]

I have assumed that the times are stored as a string, and converted them to timedelta prior to performing the sum.
Note the sum contains conditions, much like a COUNTIF statement in excel. You can modify the statement to add more conditions, or adjust the ones listed to get whatever output you're looking for.


text:
Q: pygame.gfxdraw.aacircle gows funny for big circles, any alternatives? Working on my Major project for software design and development and have run into the hurdle that when using pygame.gfxdraw.aacircle to draw big circles, the output goes screwy as seen here

the window in the picture is showing a section of a circle with a radius of size 1561
if no-one can suggest a fix or alternate way of drawing aa circles i will probably just use the regular circle function as it doesn't look to bad at sch a large radius.

A: I would suggest not to use pygame.gfxdraw, since it is clearly marked as experimental.
From the documentation:

EXPERIMENTAL!: meaning this api may change, or dissapear in later
  pygame releases. If you use this, your
  code will break with the next pygame
  release.

Just stick with the regular circle function.
EDIT:
Maybe you should open a bugreport on the pygame bugtracker or the pygame mailinglist.


text:
Q: Abort trap: 6 in Mongodb - MAC OS I am trying to run my mongodb. So I go to the appropriate folder's location and type:
$ mongod --dbpath=data

Then I get a funny message which I don't know how to fix.
----- BEGIN BACKTRACE -----
...
...
...
----- END BACKTRACE -----
Abort trap: 6

Any ideas how can this be fixed?
Thanks,
Theo.

A: Your data folder is corrupted.
Delete that folder and open up the terminal on the parent folder of data folder and type:
mongod --dbpath=data


text:
Q: I want to know what's happening in this script?? What is the difference? In CodeIgniter
 $confirm=$this->video->videoupdate(any values);// Here i am just updating my database
 if($confirm)
 echo "<script>window.location='index';</script>";

 $this->video->videoupdate(any values);// Here i am just updating my database
 echo "<script>window.location='index';</script>";

Can u explain me detail guys...
is it compulsory  to check this condition?

A: In the first example you are setting a variable $confirm which (I assume) will either be true or false based on whether the update succeeds and then redirecting if it does. In the second example you are redirecting regardless of whether the update succeeds or not.

A: In first case script redirect if the record is successfully updated.
in second case does not matter what happen with the record it will always redirect.

A: // example 1
$confirm=$this->video->videoupdate('any values');
if($confirm)
{
    echo "window.location='index';";
}

// example 2
$this->video->videoupdate('any values');
echo "window.location='index';";

Your videoupdate method will return a value. Generally you return true or false, but can also return data. In example one you are assigning the result of the statement to $confirm.
if $confirm is true then the condition will be executed. Note that unless $confirm is explicitly set to false, any value will evaluate to true, so the condition will always be true.
A better option would be to do:
if($confirm==true)
{
    // redirect
}
else
{
   // something else has happened
}

This logic can be used to control the flow of an application in the result of an error, for instance, or the failure of a query.
In the second example, the echo statement will occur regardless of outcome, which may be intended, but could result in unexpected behaviour - was the query successful or not at that point in the script.


text:
Q: Can We use page breaks in for loops? I wanted to print barcodes using for loop in python. This is my code:
`{%- from "templates/print_formats/standard_macros.html" import add_header -%}

{% set a = doc.end %}
{% set count = 0 %}

{%- for i in range(doc.start,doc.end) -%}

00000000000000{{ i }}

{% set count = count + 1 %}
{{count}}

{%- endfor -%}

        {{ _("Authorized Signatory") }}

`

The problem is,I wanted to restrict the number of barcodes printed on one sheet of paper to 24.Is there any way to do that?

A: You can add a page break after every 24th barcode using:
{% if count % 24 %}

{% endif %}

A: HTML doesn't have a really good concept of "paper sheet size". A HTML page has an infinite height and browser's are notoriously bad a printing HTML in a readable way (with the notable exception of Opera).
With CSS 3, three page break properties were defined.
They might be supported by your browser. If they are, then wrap 24 bar codes in a
 and give that
 a class which tells the browser to break the page afterwards.
If the browser emits an empty page at the end, then you need two classes: One for the first
 without a page break and one for every successive
 and a page-break-before: always;
If that doesn't work well, you should look at PDF. PDF allows you place elements exactly on pages with a known, fixed size.


text:
Q: ASP.net: How to make list of object sortable when bind to control such as gridview? I got a class let's call it Blah. I use ObjectDataSource to get the data from the database and the value is bind it to Blah's property for example, Column Foo is Blah.Foo in my class. I can bind ObjectDataSource with a list of Blah to a gridview but i can't make it sortable since the datasource is not datatable. Does anyone have link or tutorial on how to make object to be sortable for control like gridview.
thank
Jack

A: First you could use the AllowSorting property of the gridview with SortExpression on your fields. Here is a tutorial
Second, you could made a generic list of Blah and then call .Sort()
List<Blah> test = new List<Blah>;
test.AddRange(ObjectDataSource);
test.Sort();

msdn information
Third you could sort the gridview directly from an expression like
CustomersGridView.Sort(expression, direction);

link

A: You need to implement the IComparable interfaces.  There may be other interfaces you need to implement, but they will all be in the same vein.

A: You have to implement Icomparable then pass the sort expression from the gridview to your custom sort method.
Imar Spaanjaars has a nice tutorial and code examples of creating sortable business object collections that you can bind to asp.net controls

A: You may want to try to sort your list using anonymous delegates:
List<YourObject> MyList = new List<YourObject>();

MyList.Sort(delegate(YourObject o1, YourObject o2)
{ return o1.SomeProperty.CompareTo(o2.SomeProperty);});

More about anonymous and delegate: MSDN


text:
Q: Password protect existing HSQLDB DB I need to be able to password protect an existing HSQLDB.
Looks like the HSQLDB documentation provides insights into how to initially setup a HSQLDB with a username and password - but how to go about protecting an existing HSQLDB?

A: You can use the SET PASSSWORD command. This is covered in the Guide:
http://hsqldb.org/doc/2.0/guide/accesscontrol-chapt.html#acc_statements
You connect to the database then set the password.


text:
Q: iPhone MultiView App Issue
Possible Duplicate:
iPhone App Dev - Loading View From View Controller

I have a root view controller with a tool bar which has a button. When the root view controller loads I want it to load a subview underneath the toolbar:
//assigns JSON to question objects
-(void) setQuestions {
    questionArray = [[NSMutableArray alloc] init];
    for (NSDictionary *q in self.questions) {
        /* Create our Question object and populate it */
        QuestionViewController *question = [[QuestionViewController alloc]init];
        [question setQuestionId:[q objectForKey:@"questionId"] withTitle:[q objectForKey:@"question"] number:[q objectForKey:@"questionNumber"] section:[q objectForKey:@"sectionId"]];
        /* Add it to our question (mutable) array */
        [questionArray addObject:question];
        [question release];
    }
}

-(void) startQuestionnaire {
    currQ = [questionArray objectAtIndex:0];
    [self.view insertSubview:currQ.view atIndex:0];
    [currQ release];
}

I use the startQuestionnaire to load the viewcontroller from questionArray which contains a load of QuestionViewController objects...When I click on the slider in the view that is loaded the program crashes...Do I have have to hand control over to the subview or something?The program doesnt crash when I emove the code within startQuestionnaire

A: While it's tough to say without seeing the rest of your code, it looks like your problem is somewhere in the way you're instantiating / referencing objects.
If I were you, I'd approach this slightly differently in the interest of simplifying things.
First off, try to use @property and @synthesize, and get used to referencing ivars with 'self'. Retain counts & memory management issues are often the cause of crashes, and you can clean things up quite a bit by being more formal with your ivars. Here's some reading: http://www.optictheory.com/iphone-dev/2010/02/objective-c-primer-part-3-property-and-synthesize/
Second, I would refrain from creating your QuestionViewController until you're ready to add it to your root ViewController (ie. inside startQuestionnaire).  You can pass your JSON data into it with a custom init function.  This way, you can ensure that there aren't other QuestionViewController instances lying around that might be causing complications, and taking up memory when they're not being used.
As for the slider issue itself, it's tough to say without seeing the actual error, but hopefully this helps a bit.
Best of luck


text:
Q: how to fix Error environment when using reticulate with command install_miniconda() I can't fix this error when I install miniconda in Windows 11 with reticulate.
Here is the message :

reticulate::install_miniconda()

*

*Installing Miniconda -- please wait a moment ...

*Downloading "https://repo.anaconda.com/miniconda/Miniconda3-latest-Windows-x86_64.exe" ...
trying URL 'https://repo.anaconda.com/miniconda/Miniconda3-latest-Windows-x86_64.exe'
Content type 'application/octet-stream' length 74687656 bytes (71.2 MB)
downloaded 71.2 MB

*

*"C:/Users/charl/AppData/Local/r-miniconda/condabin/conda.bat" "create" "--yes" "--name" "r-reticulate" "python=3.8" "numpy" "--quiet" "-c" "conda-forge"
Error: Error creating conda environment 'r-reticulate' [exit code 1]

Thanks if you can help me


text:
Q: Find the total number of solutions of $ \log_e |\sin x| = - x^2 + 2x $ Find   the total number of solutions of $ \log_e |\sin x| = - x^2 + 2x $  in 0 to $ \pi $ close interval.
So my book solves this problem by making graph. I am a high school student. I don't know how to make graph of such functions.
I know the graph of log and I I know the graph of |sin| but I don't know how to solve this sin inside log.
If you can give a source which teaches that , that will solve my problem. I am not allowed to use calculator.
I tried solving the equations, I also tied finding range  of both the sides to see if there is any intersection.

A: First, let's see the difference between the graphs of $|\sin(x)|$ and $\log|\sin(x)|$. Below, you can see what the log function does to the $|\sin(x)|$.

Now, let's talk about the computational side. I assume you may use a calculator. For graphing such functions, constructing a table would be a wise option. To obtain a value for each step, if you are unfamiliar, you can do the following. Assume you want to calculate the $y$ value for $x=\pi/2 \ (\approx 1.57)$ (you can also enter the following in one line in your calculator).
sin(pi/2)
  1
log(ans)
  0
which is in line with the graph above. Now compute several of these points to graph the function yourself.
I assume you are now ready to start building your own table, and thereby also graphing your function? If not, or you want to check, I will provide a small table below.
Exercise for you: explain the symmetry within the table, and why did I choose my $x$ this way?


text:
Q: Error in React Native using axios - Error: Network Error I'm using axios on my React Native APP and i'm getting this error on my post request -> [Error: Network Error]
A few informations that are relevants:

*

*This error not happen on IOS (same project)

*API is hosted on Azure.

*This error starts to happen after turn on WAF on API.

When I make the same call on postman, I receive the follow message: Unable to verify the first certificate (but the request works because SSL certificate verification is disabled.
"react-native": "^0.67.5",
"axios": "^0.26.1",
node: 14.7.0
I tried to disabled SSL Verification on Android, but I don't wanna follow this approach, because it's a security config.


text:
Q: Question regarding ratio I was trying to prove some of the results related to beta function and I came across this step

Therefore,
  $$\frac{B(m+1,n)}{m}=\frac{B(m,n+1)}{n}=k,\quad\mathrm{say}\quad\ldots(i)$$
  This yields
  $$k=\frac{B(m+1,n)+B(m,n+1)}{m+n}$$

Can anyone tell me how they got the value of $k$? Thanks in advance.

A: From the first equation, we get $km=B(m+1,n)$ and $kn=B(m,n+1)$.  Thus,
$$k=\frac{k(m+n)}{m+n}=\frac{km+kn}{m+n}=\frac{B(m+1,n)+B(m,n+1)}{m+n}$$

A: The first equation equates three different expresssion. We may pick any two to make an equation. Take the first and last, with a slight rearrangement:
$B(m+1,n) = m k$
then the second and last:
$B(m,n+1) = n k$
Now, just add these two equations I just wrote. The final step should be obvious.


text:
Q: Link only spam answers I'm slightly wary of flagging a link only answer, along the lines of this one, and a few other's I've just flagged as spam because they are solely links. The answer was as follows:

It's very simple , please visit here for detail enter link description
  here

I had a better example but it got dealt with immediately! Thank you whoever that was
This seems, at face value, to be a genuine, if fairly bad, answer. It's only after clicking on the link that it becomes obvious that it's spam.
I've been vacillating between flagging them as spam and flagging these as "other" along with an explanation that this is spam and sometimes that the user has a number of other similar or identical answers.
If I flag these as spam, and therefore help to remove them quicker, do moderators look at the links or am I risking getting these flags declined and having the spam stay around? Are the flags more likely to be acted upon if I flag them as "other" and clarify that this is actually spam and not just a bad answer?

A: Moderators will generally not decline spam flags without taking a closer look at the links contained in the post (though actually visiting them is usually not necessary). There is no reason not to flag spam.
Spam is often a bit deceptive on first glance, embedding a spam link inside copy-pasted content that fits the general theme of the question is not uncommon. So moderators are used to a certain amount of deception with spam.

A: Answers such as the one you linked to should / would be removed even if the link were to a genuine place. Just providing a link to elsewhere isn't an answer to a question.
However, if the poster left a long and useful answer but left a closing line of 'there is more information about this here' and that link was just unrelated spam then that's where the problem would come in. The Moderators would have to check that such links were not genuine ('genuine' meaning the citation source or other such reference, and not some random pharmaceutical product sales site or whatever spam it could be).
If you do spot such schemes then flag it as spam and the moderator should check to see if there are any links in the text, and where they are linking to. If it's flagged as spam then the moderator knows what they're looking for when reviewing the post. (i.e. they are looking for spam content / links). If it's flagged as something else then it's less likely the moderator will pick up on the spam link.

A: Genuine how? Aside from it being only a link, you can immediately tell without even visiting the page that it doesn't even link to a specific article that might be related to the question, only the base domain is shown when hovering over the link. Pure spam. Another giveaway was they did not acknowledge any part of the question and only provided a generalized "visit here" line.
Why are you at all worried about being it declined? If you know it's spam, flag it as spam. No need to explain why. You should not use the "other" option because that just makes it take longer for it to get auto-deleted. Imagine if everyone flagged using other. Then the spam sits there forever until a moderator comes along and deletes it. As well, a moderator can determine if it's spam. They're not going to look at it as "just another link-only answer" when there's a bright red box that says "spam" right in their face.

A: Flagging it directly as spam has the advantage that 6 flags cause automatic deletion, therefore not requiring moderator intervention in most cases, so it is highly advisable over "usual" flags. The spam flag will also count as a downvote. For more information, see the community FAQ.


text:
Q: error: Could not find the correct Provider above this Consumer Widget Why i can't print all of List. I was debug the project, every data has map to list but i still can print it out. The project show me error: Could not find the correct Provider above this Consumer Widget. Please help me.
Here my Screen to show the list
class MapScreen extends StatelessWidget {
  const MapScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        FutureProvider(
          create: (context) => GeolocatorService().getLocation(),
          initialData: null,
        ),
        ProxyProvider<Position, Future<List<Place>>>(
          update: (context, position, places) {
            return PlacesService()
                .getPlaces(position.latitude, position.longitude);
          },
        )
      ],
      child: const MaterialApp(
        home: GetScreen(),
      ),
    );
  }
}

class GetScreen extends StatelessWidget {
  const GetScreen({super.key});

  @override
  Widget build(BuildContext context) {
    final currentPosition = Provider.of<Position?>(context);
    if (currentPosition != null) {
      final placeService = Provider.of<Future<List<Place>>>(context);
      return FutureProvider(
        create: (context) => placeService,
        initialData: const [],
        child: Scaffold(
            appBar: AppBar(
              leading: IconButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  icon: const Icon(Icons.arrow_back_ios_new_rounded)),
              title: const Text('Tìm nhà hàng'),
              elevation: 0,
              backgroundColor: Colors.purple,
              centerTitle: true,
            ),
            // ignore: unnecessary_null_comparison
            body: Consumer<List<Place>>(
              builder: (context, places, child) {
                return Column(
                  children: <Widget>[
                    SizedBox(
                      height: MediaQuery.of(context).size.height / 3,
                      width: MediaQuery.of(context).size.width,
                      child: GoogleMap(
                        initialCameraPosition: CameraPosition(
                            target: LatLng(currentPosition.latitude,
                                currentPosition.longitude),
                            zoom: 16.0),
                        zoomGesturesEnabled: true,
                      ),
                    ),
                    const SizedBox(
                      height: 10.0,
                    ),
                    Expanded(
                        child: ListView.builder(
                            itemCount: places.length,
                            itemBuilder: (context, index) {
                              return Card(
                                child: ListTile(
                                  title: Text(
                                    places[index].name,
                                  ),
                                ),
                              );
                            }))
                  ],
                );
              },
            )),
      );
    }
    return Scaffold(
        appBar: AppBar(
          leading: IconButton(
              onPressed: () {
                Navigator.pop(context);
              },
              icon: const Icon(Icons.arrow_back_ios_new_rounded)),
          title: const Text('Tìm nhà hàng'),
          elevation: 0,
          backgroundColor: Colors.purple,
          centerTitle: true,
        ),
        body: const Center(child: CircularProgressIndicator()));
  }
}

Here my code to get data and map them to list. After the code map data to list done, i didn't see the code comeback to MapScreen().
class PlacesService {
  final key = 'AIzaSyDM32Kzq-Pz_MPorUAYxWgDX7qb3nt2S6M';

  Future<List<Place>> getPlaces(double lat, double lng) async {
    var response = await http.get(Uri.parse(
        'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$lng&type=restaurant&rankby=distance&key=$key '));
    var json = convert.jsonDecode(response.body);
    var jsonResults = json['results'] as List;
    return jsonResults.map((place) => Place.fromJson(place)).toList();
  }
}

class Place {
  final Geometry geometry;
  final String name;
  final double rating;
  final int userRatingCount;
  final String vicinity;

  Place(this.geometry, this.name, this.rating, this.userRatingCount,
      this.vicinity);

  Place.fromJson(Map<dynamic, dynamic> parsedJson)
      : geometry = Geometry.fromJson(parsedJson['geometry']),
        name = parsedJson['name'],
        rating = (parsedJson['rating'] != null)
            ? (parsedJson['rating'])!.toDouble()
            : 0.0,
        userRatingCount = (parsedJson['user_ratings_total'] != null)
            ? parsedJson['user_ratings_total']
            : 0,
        vicinity = parsedJson['vicinity'];
}

And the Screen is return Center(child: CircularProgressIndicator())) all the time.
The screen

A: Try adding Position as the type for the FutureProvider:
 providers: [
        FutureProvider<Position?>(
          create: (context) => GeolocatorService().getLocation(),
          initialData: null,
        ),
        ProxyProvider<Position?, Future<List<Place>>>(
          update: (context, position, places) {
            if (position == null) return [];
            return PlacesService()
                .getPlaces(position.latitude, position.longitude);
          },
        )


text:
Q: zero's or singularity of a complex valued function at $z=0$. We have a function
$$f(z)=e^{\frac{-1}{z^2}}$$ then $$\lim_{z\rightarrow 0} f(z)=0$$
 Is $z=0$ zero's of $f(z)$? Or at $z=0$
$f(z)$ has any type of singularity.please help.
Thanks

A: $$f(z)=e^{-\frac{1}{z^{2}}}=1-\frac{1}{z^2}+\frac{1}{2!}\frac{1}{z^4}-...$$which contains infinite number of negative powers of $z$.
So $f(z)$ has an essential singularity at $z=0$.


text:
Q: how to get the value from DB sql then put it in Switch () with controller TextField, which is a Material Design text field that can be controlled with TextEditingController. how for type instead of Text, let's say for example like Switch, it's type bool, is it also using TextEditingController ??
Example :
(String) Text : final TextEditingController _valuetext = TextEditingController();
(bool) Switch Selection : ??
please Help :)


text:
Q: Как функцией получить отсортированную строку значений с разделителем без повторений? Как написать PL/SQL функцию, которая на вход принимает строку значений с разделителем по-умолчанию «;», а как результат возвращает строку в этом же формате, но со значениями без повторений и отсортированными в алфавитном порядке?
Например, результатом обработки строки:
test12 34;test 12;abv;abvavb;test 12;

будет такая строка:
abv;abvavb;test 12;test12 34;

A: Самый простой способ (на db<>fiddle):
create function normalize (str varchar2, delimiter char := ';') return varchar2 is
    ret varchar2 (32000);
begin
    select listagg (col, ';') within group (order by col)||delimiter into ret
    from (
        select distinct trim (column_value) col
        from xmlTable (('"'||replace (str, delimiter, '","')||'"')));
    return ret;
end normalize;
/

Так запустить и получить результат:
var result varchar2
exec :result := normalize (str=>'test12 34;test 12;abv;abvavb;test 12;')

RESULT
-----------------------------
abv;abvavb;test 12;test12 34;

A: Реализация функции на чистом PL/SQL с ассоциативной коллекцией для сохранения промежуточного результата. Причём, сохранять надо только ключи, т.к ключи ассоциативной коллекции по своей проироде - уникальны и отсортированы. Так как, нет переключения контекста выполнения, это будет наиболее эффективным по производительности решением.
create or replace function normalize (str varchar2, delimiter char := ';') return varchar2 is
    type aarr is table of char (1) index by varchar2 (96);
    function split (str varchar2, delimiter char) return aarr is
        type posvals is record (s int := 1, e int  := 0);
        pos posvals;
        tokens aarr;
        len constant int := length (str);
    begin
        <<split>> loop
            pos.e := instr (str, delimiter, pos.s);
            exit split when pos.e = 0 and pos.s >= len;
            if pos.e = 0 then pos.e := len+1; end if;
            tokens(substr (str, pos.s, pos.e-pos.s)) := null;
            pos.s := pos.e + length (delimiter);
        end loop;
        return tokens;
    end split;
    function join (aa aarr, delimiter char) return varchar2 is
        key varchar2 (96) := aa.first;
        ret varchar2 (32000);
    begin
        while key is not null loop
            ret := ret||key||delimiter;
            key := aa.next (key);
        end loop;
        return ret;
    end join;
begin
    return (join (split (str, delimiter), delimiter));
end normalize;
/

Запуск и результат (на db<>fiddle):
var result varchar2
exec :result := normalize (str=>'test12 34;test 12;abv;abvavb;test 12;')

RESULT
-----------------------------
abv;abvavb;test 12;test12 34;


text:
Q: Arduino Serial analogWrite How am I able to read the serial input on the arduino and write that value to an LED?
i.e. if I type 042 into my console, it should execute analogWrite(led, 42);

A: Start with this tutorial then work your way up to looping over Serial.read to read in a line of text and use int to convert the text to an integer.

A: if(Serial.available()){
    int val = Serial.read();
    digitalWrite(led, val);
}


text:
Q: while executing queries on multithreading it says connection pool exhausted I am executing 3 queries for a single table and I am running it on 5 tables, so I am using threading per table, when I tried to execute the program, it always says below error message:
I have tried with the below code:
def get_cursor()
pool = ThreadedConnectionPool(
            minconn=3,
            maxconn=5,
            dbname=databaseb_name,
            user=user,
            password=password,
            host=host,
            port=port
        )
conn = pool.getcon()
cursor = conn.cursor()
return cursor

but it couldn't help.
please suggest.


text:
Q: Installing specific laravel version with composer create-project The fastest and simplest way of installing Laravel is via composer command. From the laravel docs (http://laravel.com/docs/quick), it shows that we can install it with this:
composer create-project laravel/laravel your-project-name --prefer-dist

But, when you run the above command, it will grab the latest version of Laravel. How can I control it if I want to install latest version of 4.0.x? Or, 4.1.x when 4.2 is out?

A: composer create-project laravel/laravel=4.1.27 your-project-name --prefer-dist

And then you probably need to install all of vendor packages, so
composer install

A: If you want to use a stable version of your preferred Laravel version of choice, use:
composer create-project --prefer-dist laravel/laravel project-name "5.5.*"

That will pick out the most recent or best update of version 5.5.* (5.5.28)

A: To install specific version of laravel try this & simply command on terminal
composer create-project --prefer-dist laravel/laravel:5.5.0 {dir-name}

A: Installing specific laravel version with composer create-project

composer global require laravel/installer

Then, if you want install specific version then just edit version values "6." , "5.8."

composer create-project --prefer-dist laravel/laravel Projectname "6.*"

Run Local Development Server

php artisan serve

A: From the composer help create-project command

The create-project command creates a new project from a given
  package into a new directory. If executed without params and in a
  directory                 with a composer.json file it installs the
  packages for the current project.
                                                                                You can use this command to bootstrap new projects or setup a clean
  version-controlled installation for developers of your project.
[version]
                                                                                You can also specify the version with the package name using = or : as
  separator.
                                                                                To install unstable packages, either specify the version you want, or
  use the               --stability=dev (where dev can be one of RC,
  beta, alpha or dev).

This command works:
composer create-project laravel/laravel=4.1.27 your-project-name --prefer-dist

This works with the * notation.

A: Have a look:
Laravel 4.2 Documentation
Syntax (Via Composer):
composer create-project laravel/laravel {directory} 4.2 --prefer-dist

Example:
composer create-project laravel/laravel my_laravel_dir 4.2

Where 4.2 is your version of laravel.
Note: It will take the latest version of Laravel automatically If you will not provide any version.

A: Try via Composer Create-Project
You may also install Laravel by issuing the Composer create-project command in your terminal:
composer create-project laravel/laravel {directory} "5.0.*" --prefer-dist


text:
Q: Optimized computation of pairwise correlations in Python Given a set of discrete locations (e.g. "sites") that are pairwise related in some categorical ways (e.g. general proximity) and contains local level data (e.g. population size), I wish to efficiently compute the mean correlation coefficients between local level data on pairwise locations that are characterized by the same relationships.
For example, I assumed 100 sites and randomized their pairwise relations using values 1 to 25, yielding the triangular matrix relations:
import numpy as np

sites = 100
categ = 25

relations = np.random.randint(low=1, high=categ+1, size=(sites, sites))
relations = np.triu(relations) # set relation_ij = relation_ji
np.fill_diagonal(relations, 0) # ignore self-relation

I also have 5000 replicates of simulation results on each site:
sims = 5000
res = np.round(np.random.rand(sites, sims),1)

To compute the mean pairwise correlation for each specific relation category, I first calculated for each relation category i the correlation coefficient rho[j] between the simulation results res of each unique site pairs j, and then taking the average across all possible pairs with relation i:
rho_list = np.ones(categ)*99

for i in range(1, categ+1):
    idr = np.transpose(np.where(relations == i)) # pairwise site indices of the same relation category
    comp = np.vstack([res[idr[:,0]].ravel(), res[idr[:,1]].ravel()]) # pairwise comparisons of simulation results from the same relation category
    comp_uniq = np.reshape(comp.T, (len(idr), res.shape[1], -1)) # reshape above into pairwise comparisons of simulation results between unique site pairs

    rho = np.ones(len(idr))*99 # correlation coefficients of all unique site pairs of current relation category

    for j in range(len(idr)): # loop through unique site pairs
        comp_uniq_s = comp_uniq[j][np.all(comp_uniq!=0, axis=2)[j]].T # shorten comparisons by removing pairs with zero-valued result
        rho[j] = np.corrcoef(comp_uniq_s[0], comp_uniq_s[1])[0,1]

    rho_list[i-1] = np.nanmean(rho)

Although this script works, but once I increase sites = 400, then the entire computation can take more than 6 hrs to finish, which leads me to question my use of array functions. What is the reason for this poor performance? And how can I optimize the algorithm?

A: We can vectorize the innermost loop with j iterator with some masking to take care of the ragged nature of data being processed at each iteration of that loop. We can also take out slowish np.corrcoef (inspired by this post). Additionally, we can optimize few steps at the start of the outer-loop, specially the stacking steps, which could be the bottlenecks.
Thus, the complete code would reduce to something like this -
for i in range(1, categ+1):
    r,c = np.where(relations==i)

    A = res[r]
    B = res[c]

    mask0 = ~((A!=0) & (B!=0))
    A[mask0] = 0
    B[mask0] = 0

    count = mask0.shape[-1] - mask0.sum(-1,keepdims=1)
    A_mA = A - A.sum(-1, keepdims=1)/count
    B_mB = B - B.sum(-1, keepdims=1)/count

    A_mA[mask0] = 0
    B_mB[mask0] = 0

    ssA = np.einsum('ij,ij->i',A_mA, A_mA)
    ssB = np.einsum('ij,ij->i',B_mB, B_mB)
    rho = np.einsum('ij,ij->i',A_mA, B_mB)/np.sqrt(ssA*ssB)

    rho_list[i-1] = np.nanmean(rho)

Runtime tests
Case # 1: On given sample data, with sites = 100
In [381]: %timeit loopy_app()
1 loop, best of 3: 7.45 s per loop

In [382]: %timeit vectorized_app()
1 loop, best of 3: 479 ms per loop

15x+ speedup.
Case # 2: With sites = 200
In [387]: %timeit loopy_app()
1 loop, best of 3: 1min 56s per loop

In [388]: %timeit vectorized_app()
1 loop, best of 3: 1.86 s per loop

In [390]: 116/1.86
Out[390]: 62.36559139784946

62x+ speedup.
Case # 3: Finally with sites = 400
In [392]: %timeit vectorized_app()
1 loop, best of 3: 7.64 s per loop

This took 6hrs+ at OP's end with their loopy method.
From the timings, it became clear that vectorizing the inner loop was the key to getting noticeable speedups for large sites.


text:
Q: Problems with READ_PHONE_STATE I'm trying to upload a version to the Play Store but strangely it tells me that error, looking on the internet says it's just to modify the android Manifest and put 'tools: node = "remove"' in that same line to do them I can not do the prod release because when it compiles the files it re-adds the line but without the remove and it throws me errror.
Do not know how to remove that permission.enter image description here


text:
Q: how do I access mysql data from a flutter app using http I have over 20 years coding and dev experience and am now learning app development in flutter/dart/kotlin using androidStudio and trying to read/write data in a MySQL database. I have found docs on the http package but don't understand how that connects to my database. My web server and mysql db are on the same host. Any help or pointers to docs appreciated.
I am still in the info gathering phase so haven't tried any actual code yet.