text:
Q: How can I use WordPress ajax to set a cookie and redirect before a page loads I'm working on a WordPress site requirement to redirect a user when they're in a certain country to their country specific homepage.
(I've had to do this via WP Ajax because full page caching prevents it working directly on live hosting environment - I was previously doing it quite simply in functions.php hooked into 'init').
This works when I call it at the start of the header template, but only after the current page content is shown. It would be great if I could hook it in to happen before the page is displayed e.g. like using hooks such as: 'wp_loaded', 'template_redirect' but jQuery needs to be available...
Here is my code. It needs tidying some more but appreciate any suggestions as how to make a redirect happen before page contents displayed?
function invoke_county_redirection() {

    ob_start();
    ?>

    <script type="text/javascript">
    var ajax_url = "<?= admin_url( 'admin-ajax.php' ); ?>";
        jQuery.post(ajax_url, {
            'action': 'country_redirection',
        }, function (response) {
            // Set the cookie to say we're performing the redirect - this will flag it not to happen again
            createCookie('redirected', 'true');
            if (response != '') {
                window.location.replace(response);
            }

        function createCookie(name, value, days) {
            var expires = "";
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toUTCString();
            }
            document.cookie = name + "=" + value + expires + "; path=/";
        }
    </script>
    <?php
       echo ob_get_clean();
       return;
    }

    function country_redirection() {

        $redirect_url = '';

        if ( $_COOKIE['redirected'] !== 'true' ) {

            /* declare empty result url */
            $result['url'] = '';

            /* Call on geoip plugin to get the country from their IP address */
            $userInfo = geoip_detect2_get_info_from_current_ip();
            $country_code = $userInfo->country->isoCode;

            /* if we've retreived the country code for the current user */
            if ( $country_code ) {
                /* GET THE CORRECT REDIRECT URL IF APPLICABLE TO THE USER COUNTRY */
                $redirect_url = get_country_url($country_code);
            }
        }
        echo $redirect_url;
        wp_die();
    }
    add_action( 'wp_ajax_nopriv_country_redirection', 'country_redirection' );
    add_action( 'wp_ajax_country_redirection', 'country_redirection' );

A: Quick update in case anyone else can be helped by this.
I hooked the hooked the function invoke_county_redirection() into the wp_head hook as follows...
add_action('wp_head', "invoke_county_redirection");

This means that jQuery would be loaded and the country detect/redirect process runs.
However, it doesn't make the request syncronous and in this particular scenario with wanting to redirect before the page loads, I have given up on this. There is a minefield of issues trying to get around full page caching trying to store a cookie and do a redirect before the page loads. I should have just insisted that caching remained off where this needs to run, so this is our conclusion. We are instead optimsing the site as best we can with GTMetrix and loader.io and we will cross the bridge of scalability as and when we need to.


text:
Q: Google Dataflow "Workflow failed" with no reason I am running Dataflow-Jobs on Google Cloud Platform and one new Error I get is  "Workflow failed" without any explanations.
The logs I get are the following:
 2017-08-25 (00:06:01) Executing operation ReadNewXXXFromStorage/Read+JsonStringsToXXX+RemoveLanguagesFromXXX...
 2017-08-25 (00:06:01) Executing operation ReadOldXYZ_ABC_1234_123_ns_123123123123123/GroupByKey/Create
 2017-08-25 (00:06:01) Starting 1 workers in europe-west1-b...
 2017-08-25 (00:06:01) Executing operation ReadOldXYZ_ABC_1234_123_ns_123123123123123/ParDo(SplitQuery)+ReadOldXYZ...
 2017-08-25 (00:06:48) Workflow failed.
 2017-08-25 (00:06:48) Stopping worker pool...
 2017-08-25 (00:06:58) Worker pool stopped.

How am I supposed to find out whats going wrong? It should not be a problem with rights on the object, as similar jobs run successfully.
When I try to rerun the template from Google Cloud Console, I get the message:

No metadata file found for this template

But I am able to start the template and now it runs successfully. May this have to do with exceeded quotas? We just increased our CPU and IP-Quota for Dataflow and I increased our parallel running jobs from 5 to 15 to be able to use the quota. When I rerun the template without any other Jobs running, everything seems to work fine.
Any Input is highly appreciated. Thanks
EDIT: Seems like the Jobs failed because of exceeded CPU-Quota, but usually we would get an error-description where it says "could not spawn enough workers". Nevertheless, Everything works fine after I reduced the maximum number of workers per job, so that our quota cannot be exceeded.

A: I believe the "No metadata file found for this template" should be considered a warning, not an error. A template is able to have a "metadata" file associated with it which allows validation of parameters. If no such file is present, the parameters aren't validated, but everything else works as normal -- the message is just the indicator of this situation.
It sounds like the problem was the job being unable for other reasons. Based on your description and the edit, it sounds like this was because of lack of quota to run the job.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Display lines in reverse order fgetcsv How do I display lines in reverse order?
CSV file:

column1;column2;column3
cell1;cell1;cell1
cell2;cell2;cell2
cell3;cell3;cell3

It should appear like this:

column1;column2;column3
cell3;cell3;cell3
cell2;cell2;cell2
cell1;cell1;cell1

Code:
if (($handle = fopen($path, 'r')) !== FALSE)
{
    echo '

';
    // Get headers
    if (($data = fgetcsv($handle, 1000, ';')) !== FALSE)
    {
        echo '
'.implode('	', $data).'
';
    }
    echo '

';
    // Get the rest
    while (($data = fgetcsv($handle, 1000, ';')) !== FALSE)
    {
        echo '
'.implode('	', $data).'
';
    }
    fclose($handle);
    echo '

';
}

Thanks in advance.

A: Here what you need to do: instead of direct echoing row - store it to a variable:
// Get the rest
$rest = '';
while (($data = fgetcsv($handle, 1000, ';')) !== FALSE)
{
    // main trick here - add every new row BEFORE old ones
    $rest = '
'.implode('	', $data).'
' . $rest;
}
// echo gathered data
echo $rest;

A: Collect first
$collect = array();
while (($data = fgetcsv($handle, 1000, ';')) !== FALSE)
{
  $collect[]= '
'.implode('	', $data).'
';
}
echo implode(PHP_EOL,array_reverse($collect));

Reverse the array at the end.


text:
Q: Python: Frequency Analysis of Sound Files I am generating some sound files that play tones at various frequencies with a certain number of harmonics.
Ultimately, these sounds will be played on a device with a small speaker.
I have the frequency response curve of the speaker and want to do the following in Python:

*

*Plot the frequency spectrum of sound file. I need a take the FFT of the file and plot it with gnuplot

*Apply a nonlinear transfer function based on the frequency response curve in the data sheet.

*Plot the result after the function is applied.

Does anyone know :

*

*What the simplest way to do this would be?

*or of an Application (GNU/Linux based) that could do this for me?

A: you can use numpy and matPlotLib. Something like the code below:
spectrum = numpy.fft.fft(signal)
frequencies = numpy.fft.fftfreq(len(spectrum))
pylab.plot(frequencies,spectrum)
pylab.show()

That will show a graph of the fft spectrum.

A: I know you didn't mention Pylab/Matplotlib, but it works. Here is an example (assumes single-channel signal):
x, fs, nbits = audiolab.wavread('schubert.wav')
audiolab.play(x, fs)
N = 4*fs    # four seconds of audio
X = scipy.fft(x[:N])
Xdb = 20*scipy.log10(scipy.absolute(X))
f = scipy.linspace(0, fs, N, endpoint=False)
pylab.plot(f, Xdb)
pylab.xlim(0, 5000)   # view up to 5 kHz

Y = X*H
y = scipy.real(scipy.ifft(Y))

A: scipy has an FFT and hooks nicely into gnuplot. You should be able to use the signal module to do the math.


text:
Q: NGINX Reverse Proxy not handling domains with Dashes Running Ubuntu 18.04 and nginx 1.17.8
Running multiple docker containers and nginx in a container to host multiple sites.
Everything is working fine for about half of the sites, the half without dashes in the domain names.
domain.com - proxies fine
my-domain.com - never matches and fails
I have several files as such in /etc/nginx/conf.d/sites-available, 1 for each domain.
each one looks like this.
server {
  listen        80;
  server_name   www.domainname.com domainname.com;

  location / {
    proxy_pass  http://containername;
    proxy_set_header Host www.domainname.com;
  }
}

The sites that have dashes in the domain, ex: this-is-my-domain.com,
all go to the default site, as they never match.
I have already changed (per hours of googling ):
server_names_hash_bucket_size  128;


text:
Q: Send ROOM Database List Data in Body in Array through Retrofit Android I want to send Room Database saved data in Body through Retrofit. I am saving data in list in Room and will send the same in body through Retrofit Networking Library. Below is the code of the same.
Room Table class
@Entity(tableName = "cash")
public class Cash implements Serializable {
@PrimaryKey(autoGenerate = true)
private int id;
@SerializedName("UserID")
@ColumnInfo(name = "UserID")
private String UserID;
@SerializedName("FareAmount")
@ColumnInfo(name = "FareAmount")
private String FareAmount;
@SerializedName("TransactionId")
@ColumnInfo(name = "TransactionId")
private String TransactionId;

public String getTransactionId() {
    return TransactionId;
}

public void setTransactionId(String transactionId) {
    TransactionId = transactionId;
}
public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getUserID() {
    return UserID;
}

public void setUserID(String userID) {
    UserID = userID;
}
public String getFareAmount() {
    return FareAmount;
}

public void setFareAmount(String fareAmount) {
    FareAmount = fareAmount;
}

Dao Interface
@Dao
public interface CashDao {

@Query("Select * from cash ORDER BY id ASC")
List<Cash> getCashList();
@Insert
void insertCash(Cash cash);
@Update
void updateCash(Cash cash);
@Delete
void deleteCash(Cash cash);

@Query("DELETE FROM cash")
void deleteAll();

}

TransactionDatabase Class
@Database(entities = {Cash.class}, exportSchema = false, version = 3)
public abstract class TransactionDatabase extends RoomDatabase {

private static final String DB_NAME = "transaction_db";
private static TransactionDatabase instance;

public static synchronized TransactionDatabase getInstance(Context context){
    if (instance == null){
        instance =
Room.databaseBuilder(context.getApplicationContext(),TransactionDatabase.class,DB_NAME)
                .fallbackToDestructiveMigration()
                .allowMainThreadQueries()
                .build();
    }
    return instance;
}

public abstract CashDao cashDao();
}

MainActivity
btn_save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            cash = new Cash(str_userId, str_fareAmount,str_transactionId);
            appDB.cashDao().insertCash(cash);
            }
    });

   btn_upload.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        List<Cash> cashlist = appDB.cashDao().getCashList();
        if(cashlist.size() == 0){
            Toast.makeText(MainActivity.this,"Data is already uploaded!",Toast.LENGTH_SHORT).show();
        } else {
        // upload data code here
        }
        appDB.cashDao().deleteAll();
    }
});

public interface AppServiceAPI{

@POST("/Api/OfflineCashTransaction")
Call<ServiceOfflineAPI> cashtxn(@Body Cash cash);
}

I want to send data in body json and type will be POST as below through Retrofit.
[{
"UserId":"Test",
"FareAmount":"65",
"TransactionId":202008281139
},{
"UserId":"Test",
"FareAmount":"95",
"TransactionId":202008281140
},{
"UserId":"Test",
"FareAmount":"195",
"TransactionId":202008281156
}]

Response will be as below:
 {
"Status": true,
"Error": "",
"Message": "3 : Transaction  successfully Saved!!.",
"Data": ""
}

A: This is a pretty broad question. A nice practice would be to break it down to simpler/smaller problems and trying to solve them one by one.
Anyway use the method below to get the JsonObject:
public JsonObject listToJson(ArrayList<Object> objects) {
    JsonArray jsonArray = new Gson().toJsonTree(objects).getAsJsonArray();
    JsonObject obj = new JsonObject();
    obj.add("my_custom_key", jsonArray);
    return obj;
}

To use Retrofit, you need an API interface like this:
 public interface APIInterface {
    @POST("your_sub_url")
    Call<Response<YourResponsePOJO>> sendData(@Header("Content-Type") String contentType, @Body JsonObject body);
}

This will be your retrofit client class:
public class RetrofitClientInstance {
private static Retrofit retrofit;
private static final String BASE_URL = "your_base_url";
public static Retrofit getRetrofitInstance() {
    if (retrofit == null) {
        retrofit = new retrofit2.Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}

}
This is the POJO response you expect from server:
public class MyExpectedResponse<T> {
    @SerializedName("errorCode")
    public int errorCode;
    @SerializedName("errorMessage")
    public String errorMsg;
    @SerializedName("response")
    public T response;

    //setter getter methods
}

And finally calling the API:
 public void sendData (JsonObject paramsFromRoom) {
    APIInterface apiService =
            RetrofitClientInstance.getRetrofitInstance().create(APIInterface.class);
    Call<MyExpectedResponse<Void>> call = apiService.sendData("application/json", paramsFromRoom);
    call.enqueue(new Callback<MyExpectedResponse<Void>>() {
        @Override
        public void onResponse(Call<MyExpectedResponse<Void>> call, MyExpectedResponse<Void> response) {

        }

        @Override
        public void onFailure(Call<MyExpectedResponse<Void>> call, Throwable t) {

        }
    });
}


text:
Q: Make pip stop if any kind of error happened I'm creating an installation in which all pip packages have to work.
But when I'm installing packages from requirements.txt, even if some packages failed, it will still continue installation as usual.
Is there any way to stop the entire installation and throw an error?
Thanks!


text:
Q: Boost Graph: Algorithm to traverse a tree down to single leaf Here's what I want to achieve:

*

*I have a fixed graph which structure is similar to a tree's roots: single head, multiple levels down, most levels have single nodes, some levels have sibling nodes. No circular branching.

*On each run, I want to traverse the graph from the head to first leaf encountered.

*On subsequent runs, I want to traverse again but using an alternating branch at each level. Branch toggling occurs from top first then propagates down.

*At each level I want to perform an action on the nodes hit by the traversal. No action modifies the graph.

I could do that from scratch but I think Boost Graph is most likely my best friend here. But there are so many different structures and algorithms with names only experts understand.
Do you know if what I want to do (here above) already exists in Boost Graph?

A: Your requirements seem contradictory:

*

*On each run, I want to traverse the graph from the head to first
leaf encountered.

This is exactly typical for depth-first traversal (DFS)

*

*On subsequent runs, I want to traverse again but using an
alternating branch at each level. Branch toggling occurs from top
first then propagates down.

This is typical of breadth-first traversal (BFS)
I can show you standard BFS/DFS with Boost,but if you want your own hybrid algorithm you'll probably have to write it yourself. My guess is that you actually want BFS¹
Code

*

*I have a fixed graph which structure is similar to a tree's roots: single head, multiple levels down, most levels have single nodes, some levels have sibling nodes. No circular branching.

auto make_graph() {
    enum { root, a, b, c, d, e, f, g, h, i, j };
    boost::adjacency_list<> graph(j+1);
    add_edge(root, a, graph);
    add_edge(root, b, graph);
    add_edge(root, c, graph);
    add_edge(a,    d, graph);
    add_edge(a,    e, graph);
    add_edge(d,    f, graph);
    add_edge(b,    h, graph);
    add_edge(h,    i, graph);
    add_edge(i,    j, graph);
    return graph;
}

That corresponds to
Do The Traversal:
The simplest BFS would be:
int main() {
    Graph const graph = make_graph();

    boost::default_bfs_visitor vis;

    std::vector<boost::default_color_type> colors(num_vertices(graph));
    boost::breadth_first_visit(graph, Vertex{ root },
        boost::visitor(vis).color_map(colors.data()));
}

This uses the default visitor, and it effectively does nothing.
You can override any of the events, e.g.:
struct Vis : boost::default_bfs_visitor {
    void discover_vertex(Vertex u, Graph const&) {
        std::cout << "Discover " << names[u] << "\n";
    }
    void examine_vertex(Vertex u, Graph const& g) {
        if (0 == out_degree(u, g)) {
            std::cout << "Examine Leaf Node " << names[u] << "\n";
        }
    }
    using Edge = Graph::edge_descriptor;
    void tree_edge(Edge e, Graph const& g) const {
        auto a = source(e, g);
        auto b = target(e, g);
        std::cout << "Tree edge " << names[a] << " -> " << names[b] << "\n";
    }
} vis;

Which, when all enabled, will print:
Discover root
Tree edge root -> a
Discover a
Tree edge root -> b
Discover b
Tree edge root -> c
Discover c
Tree edge a -> d
Discover d
Tree edge a -> e
Discover e
Tree edge b -> h
Discover h
Examine Leaf Node c
Tree edge d -> f
Discover f
Examine Leaf Node e
Tree edge h -> i
Discover i
Examine Leaf Node f
Tree edge i -> j
Discover j
Examine Leaf Node j

The full documentation of the events is here: https://www.boost.org/doc/libs/1_73_0/libs/graph/doc/BFSVisitor.html

¹ (because even then the first leaf will still be reported first, the fact that it visits other nodes underway may not be observable)


text:
Q: what's the best scenario to use XSLT I am learning xslt, but don't know the best scenarios for use xml + xsl.

A: The best scenario to use XSLT is when you need to display XML data in different formats.
I.E., when you have an XML with products, and you need to output them in HTML, TXT, XHTML, WML, you can use XSLT transformations to do that.
The best part of XSLT transformations is that you can do SERVER SIDE transformations, if your client (browser) does not support XSLT natively (like some Mobile Browsers).

A: In addition to Pablo Santa Cruz' answer, the other common case where you'd want to use XSLT is to manipulate an XML file and get new XML code. For instance, you might use XSLT to change some settings in your web.config before deploying an ASP.NET project.


text:
Q: Symfony 2: Abstracting data input in order to allow many controllers, one model I'm currently banging my head against the wall trying to find a decent architecture for a system, but i guess i need some help from the Symfony experts here. I'm building a very simple application with two interfaces: normal web app (HTML forms, etc.) and a RESTful API. The two are not the same, but they share a lot of CRUD operations.
I have two Bundles, each one contains Controllers specific to each interface. One creates and validates forms using the Form component, another just parses data from the Request in whatever format it was sent (JSON or XML). However, this sucks. There's a lot of shared code between those two interfaces, such as parameter binding and validation. Although the model is the same, the way i receive the data from the user and interact with the model is pure anti-DRY.
Is there a way of bringing input binding and validation into a single, abstracted, operation? I started by creating a class that received the Request object from each controller, validated each parameter and communicated with the model. It worked great for the API, but i completely lost the Form component advantages.

A: You could try using 2 different routes for each action but going to the same actual action
blah_blah.blahbadeblah:
    pattern: /blah/
    defaults:
        _controller: "BlahBlahBundle:Blah:index"
        json: false

blah_blah.blahbadeblah_json:
    pattern: /json/blah/
    defaults:
        _controller: "BlahBlahBundle:Blah:index"
        json: true

And then you could do a check at the end of the controller for json and then either respond with the full template or the JsonResponse containing the minimal stuff.


text:
Q: Use xsl:analyze-string and preserve markup (like in an identity transform) I would like to process an XML file so that whatever stands before or after two newlines in a row gets turned into a paragraph (like in LaTeX).
This is the source file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE letter SYSTEM "../Schema_and_DTD/entities.dtd">
<letter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../Schema_and_DTD/letter.xsd" page_id="940"title="1695-08-17_Faeh_Georg-Bernoulli_Johann_I" catalogue_id="000055848">

<facsimile src=""/> Colendissime ac ornatissime Domine etc.

Colendissimae dominationi Vestrae gratificandi ergo, exactissima diligentia tum in Bibliotheca nostra Conventuali, tum in Bibliopolio mihi commisso perquisivi Chronicon Joannis Vitodurani<ref>Die Chronik Johanns von Winterthur (Chronica Iohannis Vitodurani), herausgegeben von F. Baethgen und C. Brun in: Scriptores rerum Germanicarum, Nova series 3, Berlin 1924.</ref>, sed nihil de eo repertum fuit.<ref>Leibniz hat die Chronik des Johannes von Winterthur später aus Bremen erhalten und in seinem Codex juris gentium diplomaticus, Hanoverae 1693, abgedruckt.</ref> Hisce post mei recommendationem omnem prosperitatem a Bono Deo intime apprecans sum et ero Ornatissimae vestrae dominationis Addictissimus servus P. Georgius Fäch.

Ex Eremo B. V. M.<ref>Einsiedeln</ref> 17. Augusti Anno 1695.

</letter>

I found this solution: XSLT - add
 into text strings instead of \n
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>

<xsl:template match="letter">

    <xsl:analyze-string select="." regex="

">
            <xsl:non-matching-substring>

                    <xsl:value-of select="." disable-output-escaping="yes" />

            </xsl:non-matching-substring>
        </xsl:analyze-string>

</xsl:template>

This comes already close to what I want but the problem is that <xsl:value-of select="." disable-output-escaping="yes" /> does not preserve any of the markup. In the end, I just have paragraph-tags containing the textual contents (all the tags got removed).
I thought of an identity transform but I am not allowed to use <xsl:apply-templates /> instead of <xsl:value-of select=".">.
What I want to produce is this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE letter SYSTEM "../Schema_and_DTD/entities.dtd">
<letter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../Schema_and_DTD/letter.xsd" page_id="940" title="1695-08-17_Faeh_Georg-Bernoulli_Johann_I" catalogue_id="000055848">

<facsimile src=""/> Colendissime ac ornatissime Domine etc.

Colendissimae dominationi Vestrae gratificandi ergo, exactissima diligentia tum in Bibliotheca nostra Conventuali, tum in Bibliopolio mihi commisso perquisivi Chronicon Joannis Vitodurani<ref>Die Chronik Johanns von Winterthur (Chronica Iohannis Vitodurani), herausgegeben von F. Baethgen und C. Brun in: Scriptores rerum Germanicarum, Nova series 3, Berlin 1924.</ref>, sed nihil de eo repertum fuit.<ref>Leibniz hat die Chronik des Johannes von Winterthur später aus Bremen erhalten und in seinem Codex juris gentium diplomaticus, Hanoverae 1693, abgedruckt.</ref> Hisce post mei recommendationem omnem prosperitatem a Bono Deo intime apprecans sum et ero Ornatissimae vestrae dominationis Addictissimus servus P. Georgius Fäch.

Ex Eremo B. V. M.<ref>Einsiedeln</ref> 17. Augusti Anno 1695.

</letter>

Is there a way to get the whole non-matching substring (including markup) and just wrap it with paragraph tags?

A: I think you need two passes, one that inserts a certain element (I have choosen br but of course you can choose anything that does not interfere with your existing vocabulary), and a second that uses for-each-group group-starting-with="br":
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

    <xsl:output indent="yes"/>

    <xsl:template match="@*|node()" mode="#all">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" mode="#current"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="letter">
        <xsl:copy>
            <xsl:apply-templates select="@*"/>
            <xsl:variable name="letter-with-line-breaks">
                <xsl:apply-templates select="." mode="breaks"/>
            </xsl:variable>
            <xsl:for-each-group select="$letter-with-line-breaks/letter/node()" group-starting-with="br">

                    <xsl:apply-templates select="current-group()[not(self::br)]"/>

            </xsl:for-each-group>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="letter//text()" mode="breaks">
        <xsl:analyze-string select="." regex="

">
          <xsl:matching-substring>

          </xsl:matching-substring>
          <xsl:non-matching-substring>
              <xsl:value-of select="."/>
          </xsl:non-matching-substring>
        </xsl:analyze-string>
    </xsl:template>
</xsl:transform>

That should give you an idea, I think you need some white space tuning.

A: There are two approaches to this problem.
One is to add markup to the text, and then use facilities like grouping to process the structure indicated by the markup: that's the approach Martin is using.
The second approach is to convert the existing markup to textual annotation of some kind, then use analyze-string to manipulate the text, and then convert the textual annotation back to markup.
With XSLT 3.0, the second approach can be achieved by serializing the content of the
 element to a string (using fn:serialize()), then applying xsl:analyze-string, then parsing the results back to nodes in a tree  using fn:parse-xml().


text:
Q: jquery, how to define a dom template and use it over and over again How do I use some dom as a template, so something like

     v1
     v2
     v3

and then programmatically replace v1-v3 with some values (that i get off an xhr repsonse)

A: You can do something like this:
$template = $('
v1v2v3
');

$new_dom_element = $template.clone();
// do your thing with replacing the content.

A: You can simply store it as a string, then drop it in a jQuery object whenever you need a new copy.
Once it is part of a jQuery object, you can traverse it just like it was already in the DOM, and update its content.
Something like this: http://jsfiddle.net/bZz96/
var div_template = "
 v1  v2  v3
";

$(div_template).find('span')
    .text( function(i) { return 'some new value ' + i; } )
    .end().appendTo('body');

A: Mustache.js is really good for this.

A: Microsoft is building a JQuery plugin (it might be incorporated into JQuery) for templates.
Microsoft, jQuery, and Templating
I'm still waiting to see if anything happens with it, but it seems promising. I just looked at the github repository and it looks like there have been some recent changes (within the last several days), so it's still in progress.


text:
Q: iterating collections in .net I have a class that has this code,
pCollection pub = RSSXmlDeserializer.GetPub(path, fReload);

get pub is the method that returns a collections of pub's...
How can i iterate them. I tried,
for (var n = 0; n < pub.Count; n++ ){

}
this is the getPub method
    public static PCollection GetPub(string path, bool fReload)
    {
        HttpApplicationState session = HttpContext.Current.Application;

        PCollection pub = session["PUB"] as PCollection;

        if pub == null || fReload)
        {
            StreamReader reader = null;

            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(PCollection));
                reader = new StreamReader(path);
                pub = (PCollection)serializer.Deserialize(reader);
                session["PUB"] = pub;
            }
            catch (Exception ex)
            {
                //throw ex;
            }
            finally
            {
                reader.Close();
            }
        }
        return pub;
    }

}

[Serializable()]
public class Pub
{
    [System.Xml.Serialization.XmlElement("title")]
    public string Title { get; set; }

    [System.Xml.Serialization.XmlElement("description")]
    public string Description { get; set; }

    [System.Xml.Serialization.XmlElement("imageUrl")]
    public string ImageUrl { get; set; }

}

[Serializable()]
[System.Xml.Serialization.XmlRoot("RPublications")]
public class PCollection
{
    [XmlArray("Pub")]
    [XmlArrayItem("Pub", typeof(Pub))]
    public Pub[] Pub { get; set; }
}

but 'Count' is not recognised. I get this message , pCollection does not have a definition for 'Count'...
How do i iterate the collection n get the collection elements? pls help.

A: You could use:
foreach(var p in pub.Pub)
{
     // Do work on p
}

Note that your PCollection class is not following good .NET practices, as it's named "Collection" but not implementing any of the standard interfaces for collections.  You may want to consider reworking this to be more "standardized".

A: PCollection is not really a collection. It is a class that contains a collection (more precisely an array). So to iterate you need to iterate the array:
for (Int32 i = 0; i < pub.Pub.Length; ++i) {
  Pub p = pub.Pub[i];
  ...
}

Or if you don't care about the index and just want to go through the collection from start to finish:
foreach (Pub p in pub.Pub) {
  ...
}

(A more consistent naming of types and members would probably help.)


text:
Q: Sum a product of Bernoulli numbers and binomial coefficients Context: I am interested in developing the large-$x$ asymptotic series of the digamma function
$$\psi\Big(\frac{1}{2}+ix\Big)$$
for real positive $x$.
For this I am using the known asymptotic expansion of $\psi(x)$:
$$\psi(z) \sim \ln z - \frac{1}{2z} - \sum_{n=1}^\infty \frac{B_{2n}}{2n z^{2n}}, \qquad z\rightarrow \infty$$
where $B_{2n}$ are the Bernoulli numbers, in conjunction with the generalized binomial expansion for negative powers:
$$\frac{1}{(1+y)^p} = \sum_{n=0}^\infty \begin{pmatrix}-p\\n\end{pmatrix} y^n$$.
Question:  In the process of applying the binomial expansions to the third term of the large $x$ behavior of the digamma function, I end up with the following double sum:
$$S = -\sum_{d=2}^\infty \Big(\sum_{n=1}^{\lfloor d/2 \rfloor} \frac{B_{2n}}{2n} \begin{pmatrix}-2n\\d-2n\end{pmatrix}2^{2n}\Big)\big(\frac{-i}{2x}\big)^d$$
What is the closed-form formula for the inner $n$-sum, for $d$ odd and for $d$ even?  I believe this should be possible since the odd $d$ case leads to a series that is purely imaginary which (I observe by explicit computation of the first few terms) exactly cancels the imaginary part arising from the expansion of $\ln(z) - \frac{1}{2z}$.  I am therefore able to guess
$$-\sum_{n=1}^{\lfloor d/2 \rfloor} \frac{B_{2n}}{2n} \begin{pmatrix}-2n\\d-2n\end{pmatrix}2^{2n} = 1-\frac{1}{d},\qquad d = \{3,5,7,\ldots\}$$

*

*How can I prove this relation? And what is the closed-form result for $d$ even and positive?

*Bonus: what is the large $x$ behavior of $\psi(\frac{1}{2}+ix)$?

A: We seek to evaluate
$$\sum_{q=1}^{\lfloor n/2\rfloor} \frac{B_{2q}}{2q}
{-2q\choose n-2q} 2^{2q}.$$
Taking advantage of the odd index Bernoulli numbers being zero except
$B_1$ this is
$$(-1)^{n+1} + \sum_{q=1}^n \frac{B_{q}}{q}
{-q\choose n-q} 2^q.$$
Now with the binomial coefficient we get
$$(-q)^{\underline{n-q}}/(n-q)! =
(-1)^{n-q} (n-1)^{\underline{n-q}}/(n-q)! =
(-1)^{n-q} {n-1\choose n-q}.$$
Continuing,
$$(-1)^{n+1} +
\sum_{q=1}^n \frac{B_q}{q} (-1)^{n-q} {n-1\choose q-1} 2^q
= (-1)^{n+1} +
\frac{1}{n} \sum_{q=1}^n B_q (-1)^{n-q} {n\choose q} 2^q
\\ = (-1)^{n+1} + \frac{1}{n} (-1)^{n+1}
+ \frac{1}{n} \sum_{q=0}^n B_q (-1)^{n-q} {n\choose q} 2^q
\\ = (-1)^{n+1} \frac{n+1}{n}
+ (n-1)! [z^n] \exp(-z) \frac{2z}{\exp(2z)-1}.$$
Now we have
$$\frac{2}{\exp(2z)-1} =
\frac{1}{\exp(z)-1} - \frac{1}{\exp(z)+1}$$
as well as
$$\frac{1}{\exp(z)} \frac{1}{\exp(z)-1}
= \frac{1}{\exp(z)-1} - \frac{1}{\exp(z)}$$
and
$$\frac{1}{\exp(z)} \frac{1}{\exp(z)+1}
= - \frac{1}{\exp(z)+1} + \frac{1}{\exp(z)}$$
which yields for the sum
$$(-1)^{n+1} \frac{n+1}{n}
+ (n-1)! [z^n]
\left[\frac{z}{\exp(z)-1} + \frac{z}{\exp(z)+1}
- \frac{2z}{\exp(z)} \right]$$
or
$$(-1)^{n+1} \frac{1-n}{n}
+ \frac{1}{n} B_n
+ (n-1)! [z^n] \frac{z}{\exp(z)+1}.$$
Observe that
$$\frac{z}{\exp(z)+1}
= \frac{z}{\exp(z)-1} - \frac{2z}{\exp(2z)-1}$$
This will produce at last
$$(-1)^{n+1} \frac{1-n}{n}
+ \frac{1}{n} B_n
+ \frac{1}{n} B_n - \frac{1}{n} 2^n B_n$$
or alternatively
$$\bbox[5px,border:2px solid #00A000]{
(-1)^{n+1} \frac{1-n}{n} +
\frac{1}{n} (2-2^n) B_n.}$$
Again with the Bernoulli numbers at odd indices being zero we get for
$n\ge 3$, $n$ odd the closed form
$$\bbox[5px,border:2px solid #00A000]{
\frac{1-n}{n}.}$$
Here we have consulted OEIS A036968, the
Genocchi  numbers.

A: About your second question. The rays $\arg z =\pm \frac{\pi}{2}$ are Stokes lines for $\log \Gamma \!\left( {\frac{1}{2} + z} \right)$ and $\psi\!\left( {\frac{1}{2} + z} \right)$, where exponentially small contributions are "switched on". It is known that
\begin{align*}
\log \Gamma\! \left( {\tfrac{1}{2} + ix} \right) \sim ix\log x - \left( {\tfrac{\pi }{2} + i} \right)x & + \frac{1}{2}\log(2\pi) - \frac{1}{2}\log (1 + e^{ - 2\pi x} ) \\ & + i\sum\limits_{n = 1}^\infty  {\frac{{( - 1)^n (2^{1 - 2n}  - 1)B_{2n} }}{{2n(2n - 1)x^{2n - 1} }}}
\end{align*}
as $x\to +\infty$ (see https://doi.org/10.2298/AADM130124002N). Differentiation yields
$$
\psi\! \left( {\tfrac{1}{2} + ix} \right) \sim \log x + \frac{{\pi}}{2}i\tanh (\pi x) + \sum\limits_{n = 1}^\infty  {\frac{{( - 1)^n (1 - 2^{1 - 2n} )B_{2n} }}{{2n}}\frac{1}{{x^{2n} }}}
$$
as $x\to +\infty$. Now $\tanh (\pi x) - 1$ is exponentially small in comparison with the (divergent) algebraic expansion involving the Bernoulli numbers so it may seem superfluous. However, when the algebraic expansion is truncated at its least term, that is at $n \approx \pi x$, we find
$$
\left| {\frac{{( - 1)^n (1 - 2^{1 - 2n} )B_{2n} }}{{2n}}\frac{1}{{x^{2n} }}} \right| \sim \frac{2}{{\sqrt x }}e^{ - 2\pi x}  \ll \tanh (\pi x) - 1 \sim e^{ - 2\pi x}
$$
(cf. http://dlmf.nist.gov/24.11.E2). Therefore, when the algebraic expansion is truncated optimally, the exponentially small contribution becomes relevant.
As a final remark, let me add that if you substitute the asymptotic expansion of $\psi(z)$ into the right-hand side of the functional equation (see http://dlmf.nist.gov/5.5.E8)
$$
\psi \!\left( {\tfrac{1}{2}+z} \right) = 2\psi (2z) - \psi (z) - 2\log 2
$$
you immediately obtain the asymptotic expansion of $\psi\!\left( { \frac{1}{2}+z} \right)$ without any tedious computation.


text:
Q: Orthogonal Projection; Range and Kernel I am trying to prove the following

Let $M$ be a subspace of $V$, prove that
(1) $R(P_M) = M$ and (2) $Ker(P_M)=M^\perp$ where $P_M$ is the projection onto $M$

For (1) I have
Proof
$R(P_M) = \{ m \in V: m = P_M(m) \}$ and $M = \{v \in V : v \in M \}$
Let $x \in R(P_M),$ then $x  = P_M(x) \implies x \in M$ and $x \in M \implies x = P_M(x)$
For (2) I have
Proof
$Ker (P_M) = \{ m \in M: P_M(m) = 0 \}$ and $M^\perp = \{ v \in V: \langle v, m\rangle = 0, \forall m \in M \}$
Let $x \in Ker(P_M) \implies P_M(x) = 0 $. I am not sure what to do now.

A: Given vectors $u,v$ we may write $u=u_1+u_2$, such that $u_1$ is a multiple of $v$, and $\langle u_2,v\rangle=0$, i.e. $u$ is normal to $v$.  $u_1$ is called the projection of $u$ onto $v$, and is given by $\frac{\langle u,v\rangle}{\langle v,v\rangle}v$.  $u_2$ is found via $u_2=u-u_1$.  Projection onto $M$ is defined in a different way, but yields the same decomposition.
Now, if $x\in M$, then when we write $x=x_1+x_2$, $x_2=0$.  If $x\in M^\perp$, then when we write $x=x_1+x_2$, $x_1=0$.  Proving these two facts (using the definition of projection onto $M$ you were given) will solve this problem.


text:
Q: Is "StringBuilder" an application of the Builder Design Pattern? Is the "Builder" pattern restricted to addressing the "telescoping constructor" anti-pattern, or can it be said to also address the more general problem of complicated creation of immutable objects?
The StringBuilder class has the word "builder" in its name, but it has nothing to do with telescoping constructors, it simply helps us collect all the data that we need to pass to the constructor of an immutable object.
To me it appears like the answer is a very clear "yes", but there appears to be some disagreement on the topic, so I was hoping that someone could perhaps clarify it.
I was answering this question: Programmers SE: Legitimate "real work" in a constructor? where the OP wants to create a (presumably immutable) object containing a complex tree, and the idea of the "builder" pattern popped up, and while researching it I found this Q&A which seems to say that "StringBuilder" style of object creation is not an application of the "Builder" pattern, for reasons which are not clear to me: Stackoverflow - StringBuilder and Builder Pattern. (Those answering that question failed to make a convincing point as far as I can tell.)

A: A StringBuilder is similar to a the Builder Pattern, but does not share much with the GoF description of this design pattern. The original point of the design pattern was

Separate the construction of a complex object from its representation so that the same construction process can create different representations.
— from Design Patterns, by Gamma, Helm, Johnson, Vlissides.

(note: "complex" primarily means "composed of multiple parts", not necessarily "complicated" or "difficult")
The "different representations" is key here. E.g. assuming this construction process:
interface ArticleBuilder {
  void addTitle(String title);
  void addParagraph(String paragraph);
}

void createArticle(ArticeBuilder articleBuilder) {
  articleBuilder.addTitle("Is String Builder an application of ...");
  articleBuilder.addParagraph("Is the Builder Pattern restricted...");
  articleBuilder.addParagraph("The StringBuilder class ...");
}

we might end up with a HtmlDocument or a TexDocument or a MarkdownDocument depending on what concrete implementation is provided:
class HtmlDocumentBuilder implements ArticleBuilder {
  ...
  HtmlDocument getResult();
}

HtmlDocumentBuilder b = new HtmlDocumentBuilder();
createArticle(b);
HtmlDocument dom = b.getResult();

So one central point of the Builder pattern is polymorphism. The Design Patterns book compares this pattern to the Abstract Factory:

Abstract Factory is similar to the Builder in that it too may construct complex objects. The primary difference is that the Builder pattern focuses on constructing a complex object step by step. […] Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.
— from Design Patterns, by Gamma, Helm, Johnson, Vlissides.

This step-by-step aspect has then become the more popular aspect of the Builder pattern, so that in common parlance the Builder pattern is understood like this:

Split construction of an object into multiple steps. This allows us to use named arguments or optional parameters even in languages that do not support these features.

Wikipedia defines the pattern like this:

The builder pattern is an object creation software design pattern. Unlike the abstract factory pattern and the factory method pattern whose intention is to enable polymorphism, the intention of the builder pattern is to find a solution to the telescoping constructor anti-pattern[citation needed]. […]
The builder pattern has another benefit. It can be used for objects that contain flat data (html code, SQL query, X.509 certificate...), that is to say, data that can't be easily edited. This type of data cannot be edited step by step and must be edited at once. The best way to construct such an object is to use a builder class.[citation needed]
— from Builder Pattern on Wikipedia, by various contributors.

So as we can see, there is no truly common understanding of which pattern this name refers to, and in some points different definitions even contradict one another (e.g. regarding the relevance of polymorphism for Builders).
The only common property of the StringBuilder with various interpretations of the pattern is that the product is created step by step rather than in one go. It does not meet a strict reading of the GoF definition of the design pattern, but please note that design patterns are malleable concepts meant to facilitate communication. I would continue to call StringBuilder an example of the Builder Pattern, albeit an atypical one – the main reason for that structure in Java is performant concatenation in the presence of immutable strings, but not some interesting object-oriented design.


text:
Q: Scraping web table using R and rvest I'm new in web scraping using R.
I'm trying to scrape the table generated by this link:
https://gd.eppo.int/search?k=saperda+tridentata.
In this specific case, it's just one record in the table but it could be more (I am actually interested in the first column but the whole table is ok).
I tried to follow the suggestion by Allan Cameron given here (rvest, table with thead and tbody tags) as the issue seems to be exactly the same but with no success maybe for my little knowledge on how webpages work. I always get a "no data" table. Maybe I am not following correctly the suggested step "# Get the JSON as plain text from the link generated by Javascript on the page".
Where can I get this link? In this specific case I used "https://gd.eppo.int/media/js/application/zzsearch.js?7", is this one?
Below you have my code.
Thank you in advance!
library(httr)
library(rlist)
library(rvest)
library(jsonlite)
library(dplyr)

pest.name <- "saperda+tridentata"

url <- paste("https://gd.eppo.int/search?k=",pest.name, sep="")
resp <- GET(url) %>% content("text")

json_url <- "https://gd.eppo.int/media/js/application/zzsearch.js?7"
JSON <- GET(json_url) %>% content("text", encoding = "utf8")

table_contents <- JSON     %>%
  {gsub("\\\\n", "\n", .)}  %>%
  {gsub("\\\\/", "/", .)}   %>%
  {gsub("\\\\\"", "\"", .)} %>%
  strsplit("html\":\"")    %>%
  unlist                   %>%
  extract(2)               %>%
  substr(1, nchar(.) -2)   %>%
  paste0("
")

new_page <- gsub("
", table_contents, resp)

read_html(new_page)   %>%
  html_nodes("table") %>%
  html_table()

A: The data comes from another endpoint you can see in the network tab when refreshing the page. You can send a request with your search phrase in the params and then extract the json you need from the response.
library(httr)
library(jsonlite)

params = list('k' = 'saperda tridentata','s' = 1,'m' = 1,'t' = 0)
r <- httr::GET(url = 'https://gd.eppo.int/ajax/search', query = params)
data <- jsonlite::parse_json(r %>% read_html() %>% html_node('p') %>%html_text())
print(data[[1]]$e)


text:
Q: Security of using HTTPS based services on an HTTP site This question has come up at my job a few times, and I was hoping to get some community backing.
We are working on a Single Page WebApp, but require that the data coming from our services API be secure to prevent snooping of the data. We are also trying to iron out the prod environment details for where our SPA will be hosted. One of the options is using something like Amazon's S3, which doesn't support SSL (to my knowledge).
There's a group that believes the whole site needs to be hosted over SSL. However, it's my understanding that SSL will only protect the transmission of the data. So the point I'm trying to make is that hosting the services from an HTTPS site and the client code from non-SSL based URLs will be just as secure as hosting everything from an SSL site.
Could anyone clarify this for me?
Thanks in advance.

A: Yes, SSL just encrypts the transmission of the data, and does not offer any type of protection of the runtime environment on any client-side code.
Now, it is generally considered a best practice to host everything over SSL, for these reasons:

*

*Users can get warnings that a site is transmitting data with an untrusted source if parts are from SSL and parts are not.

*Any cookies, will be sent in the clear when requesting the non-SSL files and may contain information that should be kept private.


text:
Q: How to use jQuery's formatItem, formatMatch, and formatResult options for .autocomplete? I am making use of jQuery's .autocomplete plugin, and I would appreciate some assistance formating the results that show up in the dropdown menu that populates when text is written into the input field.
In order to get the data to populate the autocomplete, I pull from mySQL using this PHP:
 $sql = ( 'SELECT tag, title, author, content, id FROM labels' );
 $result = mysql_query( $sql );
 $Response = array();
 while( $row = mysql_fetch_object( $result ) ){
 $Response[] = array(
                           "id" => $row->id,
                           "name" => $row->tag . ": " . $row->title . ": " . $row->content .""
                         );
 }

When a user selects the option from the autocomplete that is best for them, I convert the "name" above into the "id" using this method:
    var AllTagData = ;
      var Tags = [];
  for(var i in AllTagData){
     Tags.push(AllTagData[i].name);
  }

  function getIdFromTag(_name){
      for(var i in AllTagData){
          if(_name == AllTagData[i].name){
              return AllTagData[i].id;
          }
      }
  }

So far, so good. Finally, I use the jQuery autocomplete plugin to output the data for the user:
$(document).ready(function(){
     $("#Responses").autocomplete({
         source: Tags,
         matchContains: true,
         autoFill: true,
         select: function(e, ui){
             $("#hidden_tags").val( getIdFromTags($("#Responses").val()) );
          }});
 });

This final portion of the code is where I need help implementing the formatItem, formatMatch, and formatResult options.
From the PHP given above, I output Tags, Title, and Content all in the "name". The way that I would like to format my autocomplete options for the user is

*

*Show Tags & Title

*Hide Content

*Search through Tags, Title, and Content for possible matches

Therefore, even though I want the autocomplete to search through Content, I don't want Content showing up in the populated autocomplete list. I only want the Tags and Title to show.
I've been having a lot of trouble with this and have searched quite extensively to find an answer and would really appreciate any help you can give on how to accomplish this. Please ask any follow up questions if you need further clarification.
Thanks!

A: I think you are using a different version of the plugin, but if you look at this one:
http://code.google.com/p/jquery-autocomplete/
You will find a file index.html with the examples you ask for, for example:
showResult: function(value, data) {
    return '' + value + '';
},

Good luck!


text:
Q: Cloudfoundry application with Jboss buildpack fails to deploy I'm investigating features of Pivotal Cloudfoundry (http://run.pivotal.io) and now I'm trying to deploy simple Spring-powered application (https://github.com/spring-projects/spring-petclinic/) on Cloudfoundry using Jboss buildpack (https://github.com/cloudfoundry-community/jboss-buildpack).
After executing
cf push -p target/petclinic.war -b https://github.com/cloudfoundry-community/jboss-buildpack.git

deployment starts, and CLI indicates that deployment process finishes successfully. However logs in CF web interface show
ERR: Error cloning to /tmp/buildpack/jboss

and it seems that CF tries to reclone buildpack again and again and is unable to start the application. Application is actually not started.
So the question is: what's wrong with CF and Jboss buildpack or is it something with the deployment process?


text:
Q: Iterating map in C++ containing class objects I am creating a map in C++ which contains a integer key and the value is an object of class User. I am able to insert the object into the map with the following code -
std::map<std::string,User>::iterator it = usermap.begin();
        usermap.insert (it, std::pair<string,User>(object.userid,object));

The code I am using to write the objects in a .bin file is -
map<std::string, User>::iterator it;
for ( it = usermap.begin(); it != usermap.end(); it++ )
{
myfile2 << "Object:" << it->second << "\n";
}

But the error I am getting when I am trying to run the code is -
In file included from /usr/include/c++/4.8.2/iostream:39:0,
                 from a3part2_5.cpp:2:
/usr/include/c++/4.8.2/ostream:548:5: note: template std::basic_ostream& std::operator<<(std::basic_ostream&, const unsigned char*)
     operator<<(basic_ostream& __out, const unsigned char* __s)
     ^
/usr/include/c++/4.8.2/ostream:548:5: note:   template argument deduction/substitution failed:
a3part2_5.cpp:90:31: note:   cannot convert 'it.std::_Rb_tree_iterator<_Tp>::operator->, User> >()->std::pair, User>::second' (type 'User') to type 'const unsigned char*'
  myfile2 << "Obejct: " << it->second << "\n";
Any solutions for resolving the error?
My User class is defined as -
class User
{
public:
string userid; string uid; string gid; string gecos; string directory; string shell;
User() {}
};

A: User is user-defined class and hence ostream cannot understand your User objects when you do myfile2 << "Object:" << it->second << "\n";
This should help Overloading the << Operator for Your Own Classes.
So you should overload operator << for your class.

A: An example:
ostream& operator << (ostream &os, User const& u){
    os << "userid:\t" u.userid << "\n";
    // ...
    return os;
}


text:
Q: Laravel auth middleware redirects to localhost even after changing the APP_URL I have deployed my Laravel 8 application on live server and have set up the reverse proxy successfully to access the laravel app from a url like example.com/app/my-app.
Now the problem is, as I have used auth middleware which requests user to log in before he/she can access the app, opening example.com/app/my-app redirects to localhost:8000/login
Which is wrong as it is supposed to redirect to example.com/app/my-app/login
I have:

*

*set the 'url' => "example.com/app/my-app" in config/app.php

*ran php artisan optimize:clear

*ran php artisan cache:clear

*And also stopped the app and ran php artisan serve again

Can you please help me? Am I missing something?

A: You can use in web.php, if user not auth redirect '/' => '/login'
    Route::group(['middleware' => 'guest'], function () {
        // Redirect '/' => '/login'
        Route::redirect('/', '/login');
        // Auth routes
        Auth::routes();
    });

A: Remove the file inside the bootstrap/cache directory.Then run the following command :
php artisan cache: clear
php artisan config: clear
php artisan view: clear
php artisan route: clear
php artisan config: cache
php artisan optimize

Hope this will fixed your problems.


text:
Q: how to split .csv data in python into specific structure? I have a file contains the following:
X1, y1,50
X1, y2,20
X1, y3,30
X1, y4,40
X1, y1,70
X1, y2,40
X1, y3,60
X1, y4,80
X3, y1,100
X3, y2,200
X3, y3,300
X3, y4,400
X3, y1,500
X3, y2,600
X3, y3,700
X3, y4,800
X3, xx, d

How to create a list from the above data in the following structure:
[[X1,[50,20,30,40],[-1],[70,40,60,80],[-1]],[X2,[100,200,300,400],[-1], [500,600,700,800],[+1]]]
The first value store the information of sensor number Ex: X1,X3,X2,….. (no sequence)
Each sensor send 4 different variables and its value in 4 different lines(except one case :last case):y1=50 y2=20,y3=30,y4=40
The value -1/+1 depends on the next line followed the y4:
Case 1:
If the next line contain the same sensor number (ex:X1) and the variable y1 then -1
Case 2:
If the next line contain the different sensor number (ex:X2) and the variable y1 then -1
Case 3:
If the next line contain the same sensor number (ex:X1) and the variable xx then +1

A: I'm new to programming, so I had a go at this just to learn for myself. This is LIKELY not a very efficient solution, but hey - it's something :-)
import csv  # import csv-module

with open("foo.txt", "r") as csvfile:   # Open file as csvfile
    foo = csv.reader(csvfile)           # Read as comma-separeted file
    raw_data = []
    for row in foo:
        raw_data.append(row)

    def get_sensor_data(sensor_name):
        """This function iterates through raw_data looking for a unique sensor name.
        It makes and packs lists in lists as per your rules on StackOverflow
        ...and returns the correct format for the data of one sensor."""
        sensor_data = [sensor_name]
        sensor_data_block = []

        for line in raw_data:

            if line[1] == " xx":
                sensor_data_block.append([1])
            if line[0] == sensor_name and line[1] == " y4":
                sensor_data_block.append(line[2])
                sensor_data.append(sensor_data_block)
                sensor_data.append([-1])
                sensor_data_block = []
            if line[0] == sensor_name and line[1] != " xx" and line[1] != " y4":
                sensor_data_block.append(line[2])
        return sensor_data

    def make_data_object():
        """This function identifies unique sensor-names in the raw data.
        It uses those names to call the get_sensor_data-function.
        The lists returned from the call are stored in the data_object list. """
        sensor_list = []
        data_object = []

        for line in raw_data:
            # Identifying unique sensor names, and calling the get_sensor_data function to get its data
            try:
                sensor_list.index(line[0])
            except:
                sensor_list.append(line[0])

        for i in sensor_list:
            data = get_sensor_data(i)
            data_object.append(data)

        return data_object

    print(make_data_object())


text:
Q: Keeping certain patterns unevaluated I often need to debug by preventing some definition from evaluating and checking intermediate results. I accomplish this by doing initAll;clearAll[f,g,h]. I don't like it because

*

*It forces you to put everything in a single init block

*It's not flexible enough to only keep certain patterns like f[1] unevaluated

Instead I'd like to have a list forbidden patterns and have any pattern that matches left unevaluated. How can I achieve this?
Edit
So far I found this pattern the most useful (it's Michael Pilat's answer except with HoldForm and BlankNullSequence)
eh[expr_, symbols : {___Symbol}] := Block[symbols, HoldForm@Evaluate[expr]]

A: Block can help with what you want:
f[x_] := x + 1;
g[x_] := x - 1;

In[13]:= Block[{f},
 Hold@Evaluate[(f[g[a]]^2)]
 ]

Out[13]= Hold[f[-1 + a]^2]

Do you want to prevent evaluation for certain down-value patterns of f? (E.g., block f[x_] but allow f[x_, y_])?
UPDATE
Here's a functional form:
SetAttributes[EvaluateHeld, HoldAll];
EvaluateHeld[expr_, symbols : {__Symbol}] :=
  Block[symbols, Hold@Evaluate[expr]
]

In[7]:= EvaluateHeld[f[g[a]]^2, {f}]

Out[7]= Hold[f[-1 + a]^2]


text:
Q: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List I am trying to populate Transaction data where AccountNumber does not exist. I need to access the Account table to get that. I am getting the following error where I am trying to return IEnumerable
Cannot implicitly convert type System.Collections.Generic.IEnumerable<AnonymousType#1> to System.Collections.Generic.List<ProjectModel.Transaction>
The error is shown on top of .ToList(); part of the code. What am I doing wrong?
the code is:
    public static IEnumerable<Transaction>GetAllTransactions()
    {
       List<Transaction> allTransactions = new List<Transaction>();
        using (var context = new CostReportEntities())
        {
            allTransactions = (from t in context.Transactions
                               join acc in context.Accounts on t.AccountID equals acc.AccountID
                               where t.AccountID == acc.AccountID
                               select new
                               {
                                   acc.AccountNumber,
                                   t.LocalAmount
                               }).ToList();

        }
        return allTransactions;

    }

A: List of anonymous types cannot be casted to list of transactions. Looks like your Transaction class do not have AccountNumber property. Also you cannot return anonymous objects from methods. So you should create some type which will hold required data:
public class AccountTransaction
{
    public int LocalAmount { get; set; }
    public int AccountNumber { get; set; }
}

And return these objects:
public static IEnumerable<AccountTransaction> GetAllTransactions()
{
    using (var context = new CostReportEntities())
    {
        return (from t in context.Transactions
                join acc in context.Accounts
                     on t.AccountID equals acc.AccountID
                select new AccountTransaction {
                     AccountNumber = acc.AccountNumber,
                     LocalAmount = t.LocalAmount
                }).ToList();
    }
}

BTW you don't need duplicate join condition in where filter

A: The anonymous type which you're projecting in the "select new" section of your Linq query cannot be casted directly to your "Transaction" type.
Instead, you should project a new instance of Transaction.  The following might help:
allTransactions = (from t in context.Transactions
    join acc in context.Accounts on t.AccountID equals acc.AccountID
    where t.AccountID == acc.AccountID
    select new Transaction()
    {
        AccountNumber = acc.AccountNumber,
        LocalAmount = t.LocalAmount
    }).ToList();


text:
Q: Why aren't my Windows Apache log messages being written to the ErrorLog location specified in my VirtualHost? I'm attempting to override the ErrorLog location in my httpd.conf file by specifying it in my .vhost, but it's creating the file only and still writing to the .conf one.
I have the following in my httpd.conf file:
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error.log"

# Virtual hosts
Include conf/vhosts/xyz_apache.vhost

Then I have this in my xyz_apache.vhost file (on one line):
ErrorLog  "C:/Program Files (x86)/Apache Software Foundation/
           Apache2.2/logs/xyzerrors.log"

If I start up apache and look in my logs directory to see what was created, I see a blank xyzerrors.log and an error.log file with startup messages in it ("Starting thread to listen on port 80, etc.).
Any idea why this might be happening, or advice as to how I can fix it?  The xyzerrors.log file was clearly created, so it seems my file paths and spelling of "ErrorLog" and my vhost configuration and all the obvious parts should be correct.  But it's writing to the file specified in my httpd.conf, which, if I understand correctly, should only be the backup location, should there not be one specified in the .vhost.  I wondered if permissions might be an issue somehow (maybe it didn't have write access to the xyzerror.log it created so it wrote to error.log instead?), but both files are in the same directory.  Is there another configuration piece I missed?
I verified what was happening by renaming the .conf ErrorLog and deleting the .vhost ErrorLog, and again saw the .vhost log created and the .conf log created and written to.  I have similar setups running in Linux with no problems.
Update: Here's another piece. I was fixing an issue with lxml (I got an error, installed a newer version of it, then restarted apache), and noticed that a couple of messages appeared in my xyzerror.log.  Here's what it looks like:
error.log
[Wed Oct 09 09:14:52 2013] [notice] Child 42900: Starting thread to listen on port 80.
[Wed Oct 09 09:48:11 2013] [error] ERROR:django.request:Internal Server Error: /admin/
[Wed Oct 09 09:48:11 2013] [error] Traceback (most recent call last):
[Wed Oct 09 09:48:11 2013] [error] ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed. (Rest of traceback omitted)
[Wed Oct 09 09:54:50 2013] [notice] Parent: Received shutdown signal -- Shutting down the server.
Apache server interrupted...
Apache server interrupted...
Apache server interrupted...
Apache server interrupted...
Apache server interrupted...
Released the start mutex
[Wed Oct 09 09:54:52 2013] [notice] Child 42900: All worker threads have exited.
[Wed Oct 09 09:54:52 2013] [notice] Child 42900: Child process is exiting
[Wed Oct 09 09:54:52 2013] [notice] Parent: Child process exited successfully.
[Wed Oct 09 09:54:53 2013] [warn] mod_wsgi: Compiled for Python/2.7.
[Wed Oct 09 09:54:53 2013] [warn] mod_wsgi: Runtime using Python/2.7.2.
[Wed Oct 09 09:54:53 2013] [notice] Apache/2.2.22 (Win32) mod_wsgi/3.3 Python/2.7.2 configured -- resuming normal operations
[Wed Oct 09 09:54:53 2013] [notice] Server built: Jan 28 2012 11:16:39
[Wed Oct 09 09:54:53 2013] [notice] Parent: Created child process 40284
[Wed Oct 09 09:54:53 2013] [warn] mod_wsgi: Compiled for Python/2.7.
[Wed Oct 09 09:54:53 2013] [warn] mod_wsgi: Runtime using Python/2.7.2.
[Wed Oct 09 09:54:53 2013] [notice] Child 40284: Child process is running
[Wed Oct 09 09:54:53 2013] [notice] Child 40284: Acquired the start mutex.
[Wed Oct 09 09:54:53 2013] [notice] Child 40284: Starting 64 worker threads.
[Wed Oct 09 09:54:53 2013] [notice] Child 40284: Starting thread to listen on port 80.

xyzerror.log
[Wed Oct 09 09:47:54 2013] [info] [client 127.0.0.1] mod_wsgi (pid=42900, process='', application='XYZ.sysname.mydomain.local|'): Loading WSGI script 'C:/Users/etc/etc/XYZ_wsgi.py'.
[Wed Oct 09 09:48:11 2013] [error] [client 127.0.0.1] client denied by server configuration: C:/Users/etc/etc/site_media

So maybe these aren't ErrorLog messages and I need to investigate my CustomLog settings?  I'm seeing similar behavior with those (an xyzaccess.log file is being written but my access.log in my .conf is being written to), but I didn't include it here for simplicity.
Update 2:
If I continue to browse my site and watch the log files, I see that logs are eventually getting written to the xyzerror.log (and the xyzaccess.log) in my vhost location.  Only the initial startup messages ("listening on port..", etc.) and one site-related error were in the conf location.
Can anyone explain or suggest a solution?
Apache 2.2/Windows 7/Django 1.5/Python 2.7

A:
if I understand correctly, should only be the backup location, should there not be one specified in the .vhost

Not at all !
This is normal behaviour, because the ErrorLog directive can either apply globally, or to the VirtualHost it is declared in.
Think about it. When an error is reported to the error log for apache internal events, such as startup events or module loading failure, how can it use a specific virtual host's error log, since virtual host resolution is not even possible yet ?
Apache knows which Virtual Host to use only when a client makes a request and the request is identified to refer to a specific virtual host, either via IP resolution or Hostname resolution.
Therefore, only those errors will appear in your vhost-specific error log, such as PHP errors pertaining to that vhost, or HTTP errors such as 401 or 404 codes.


text:
Q: Trouble passing data from controller to view I'm using the Unsplash api to display photos in a new rails 6.0 app. I'm successfully able to access photos using the API directly in the view:
<%= image_tag Unsplash::Photo.find('_wcgFg4GC5A')[:urls][:small] %>

I would like to move that out of the view, however. So, I now have this in my controller:
@photo = Unsplash::Photo.find('_wcgFg4GC5A')[:urls][:small]

and I've updated the view:
<%= image_tag @photo %>

Refreshing the site after these changes returns this error: "Nil location provided. Can't build URI."
It's been a few years since I've touched Ruby/Rails, so I'm sure it's something silly. Any suggestions?


text:
Q: remember user/password and auto login firebase - swift Hi i have an application that connected to the Firebase and i have two viewController, first viewController is for log in , the second one is a tableViewController. i want to let user log in automatically when they open the application. i mean when they close the Application and open it again i want the Application log in the user automatically. I tried to use firebase documentation in AppDelegate firebase and i tried to use SwiftKeychainWrapper but it didn't help me.
this is my code for the logInController :
import UIKit
import Firebase
import FirebaseAuth
import FirebaseFirestore

class logInViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate {

@IBOutlet var userNameField: UITextField!
@IBOutlet var passwordField: UITextField!
@IBOutlet var logInButton: UIButton!

var db: Firestore!

override func viewDidLoad() {

    super.viewDidLoad()
    logInButton.layer.cornerRadius = 4.0
    userNameField.delegate = self
    passwordField.delegate = self

}

@IBAction func logInButtonClicked(_ sender: Any) {

    Auth.auth().signIn(withEmail: (userNameField.text ?? ""), password: (passwordField.text ?? "")) { (result, error) in
        if let _eror = error{
            let alert = UIAlertController(title: "Error", message: error!.localizedDescription, preferredStyle: .alert)
            let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
            alert.addAction(okAction)
            self.present(alert,animated: true)
            print(_eror.localizedDescription)
        }else{

            if let _res = result{

                print(_res)

            }

            let VC1 = self.storyboard!.instantiateViewController(withIdentifier: "order1") as! OrderTableViewController
            self.navigationController!.pushViewController(VC1, animated: true)
        }
    }
}
}

this is my AppDelegate code :
class AppDelegate: UIResponder, UIApplicationDelegate {
var db: Firestore!
var firebaseToken: String = ""
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    FirebaseApp.configure()

    self.registerForFirebaseNotification(application: application)
    Messaging.messaging().delegate = self

    if Auth.auth().currentUser != nil {

        //======
        let homeController = OrderTableViewController()
        self.window?.rootViewController = homeController
        self.window?.makeKeyAndVisible()

    } else {

        let logInController = logInViewController()
        self.window?.rootViewController = logInController
        self.window?.makeKeyAndVisible()

    }

    return true

}

A: Firebase store all info about auth and user locality in phone.
try this code, it worked in my app
if let _ = Auth.auth().currentUser {
    //======
    // Load user data (profile) from firebase if needed
    //======
    let homeController = OrderTableViewController()
    self.window?.rootViewController = homeController
    self.window?.makeKeyAndVisible()

} else {

  let rootController = firstViewController()
  self.window?.rootViewController = rootController
  self.window?.makeKeyAndVisible()

}

for use UserDefaults:
if let id = UserDefaults.standard.string (forKey: "userId") as? String, id != "" {
    //======
    // Load user data (profile) from firebase if needed
    //======
    let homeController = OrderTableViewController()
    self.window?.rootViewController = homeController
    self.window?.makeKeyAndVisible()

} else {

  let rootController = firstViewController()
  self.window?.rootViewController = rootController
  self.window?.makeKeyAndVisible()

}

A: Firebase already persists the user credentials and restores them when the app restarts. But since this requires a call to the server, it happens asynchronously and probably hasn't completed yet by the time your Auth.auth().currentUser runs.
The solution is to use an auth state listener, as shown in the first snippet in the documentation on getting the current user:
handle = Auth.auth().addStateDidChangeListener { (auth, user) in
    if user != nil {
        let homeController = OrderTableViewController()
        self.window?.rootViewController = homeController
        self.window?.makeKeyAndVisible()
    } else {
        let logInController = logInViewController()
        self.window?.rootViewController = logInController
        self.window?.makeKeyAndVisible()
    }
}


text:
Q: How should I implement Certificate Authentication into my web service client? I have created a web service client.I have been provided with a certificate "Certificate.Security.pfx" file, which I have placed on my local system.
I am looking for a java code example which shows how to access a secure web service over SSL using a PFX certificate.
I don't have any other details and this is my first time working with a certificate based web service.
Browsing through the internet, somewhere I found I need to change it to "JKS". Is that true?
Thanks,
Paul


text:
Q: Graph Bookings API - List appointment returning empty customers array When invoking either
GET /solutions/bookingBusinesses/{id}/calendarView

or
GET /solutions/bookingBusinesses/{id}/appointments

the returned bookingAppointment object has an empty customer array. However the customers appear in the UI. Any idea why this may be the case?

A: Looks like a bug in Graph API.
According to the documentation the customers property is optional. Sometimes you have to specify optional property in $select statement.
GET solutions/bookingBusinesses/{id}/calendarView?start=2018-04-30T00:00:00Z&end=2018-05-10T00:00:00Z&$select=customers

Another option is trying beta version instead of v1.0
GET beta/solutions/bookingBusinesses/{id}/calendarView?start=2018-04-30T00:00:00Z&end=2018-05-10T00:00:00Z


text:
Q: IE aborts html5 video load for 1 file I am trying to create a front end webpage to host tutorial/troubleshoot videos for commonly occurring questions in my company. I am using html5 and am trying to have the page work in the latest versions of IE FF and Chrome. The webpage works in all three except that IE is is acting a bit strange. I have multiple mp4 videos of IE however only one seems to be abort every time. I was wondering how I could fix this issue.
Here is a sample of my code. I'm pretty sure this is all correct.

        Alternate Link

        <video  controls id="player0" class="players">
            <source src="How_to_Compress_a_Folder.mp4" type="video/mp4">
            <source src="How_to_Compress_a_Folder.ogv" type="video/ogg">
        </video>

         Alternate Link

        <video id="player1" controls class="players">
            <source src="How_to_Map_a_Network_Drive_on_Windows_7.mp4" type="video/mp4">
        </video>

How to map a Network Drive loads and plays properly but How to Compress a folder does not any suggestions. I've tried to convert the .ogv file to mp4 to see if that would work as well but it does not. Again it is just this one file that is giving me issues. I would like to avoid rerecording the video because there is no guarantee this issue will not occur again.

A: The solution was actually simple. there wasn't a problem with the code but the file itself. It appears that the person who created the videos recorded some of them as mp4 and others as avi then converted to mp4. He originally used Miro Converter to covert them to mp4 which is why it didn't work. He then tried a different converter (not sure which one) and it was fine.


text:
Q: MySQL + JDBC updateBlob and updateBinaryStream throws NotUpdateable I've been searching both Google and StackOverflow for the better part of two hours, and I've not found a solution to this question. So I've turned to asking the question.
I'm working on a project that requires insertion of data into a table. I'm required to use the methods inside the ResultSet class (such as updateXXXXX and insertRow).
Particularly, I need to be able to insert a binary stream/blob (either works in my case). However, the MySQL Java Driver implementation doesn't support this (implementation here). In fact, it doesn't support any of the updateBlob or updateBinaryStream methods.. they throw NotUpdateable.
Before you post that I need to create the Statement in a way that supports ResultSet.CONCUR_UPDATEABLE, be assured that I've done that and checked it more than enough times. Please see below:
// Create statement that is insensitive to insertion of data, and allows updating.
Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

// Get an empty query ready for insertion of data
ResultSet rs = s.executeQuery("SELECT * FROM TableName WHERE 1=0");

// This is a stream of bytes. If it were a String I would be fine.
rs.updateBinaryStream("password", new ByteArrayInputStream(db.password), db.password.length);

So the crux of the matter is that from what I can see there's no equivalent way of doing this, without using a different Driver.
If you know of a way of getting this to work, I would absolutely love to hear it. Even if it's just a theory. The last thing I want to do is create multiple columns and store the array as BIGINT compositions of the bytes.
Thanks in advance,
Nick.

A: Don't use updatable result set, especially now that you've concluded that it won't work.
Since you're "working on a project that requires insertion of data into a table", you should try using an actual INSERT statement instead.
Also, you might as well use a byte[] method, since that's what you have, instead of trying to use an InputStream method.
String sql = "INSERT INTO TableName (password) VALUES (?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
    stmt.setBytes(1, db.password);
    stmt.executeUpdate();
}


text:
Q: how to unset the foreground color of whitespace-mode for Emacs In programming files, I use whitespace-mode to highlight the tab and long lines. The default highlighting is too garnish for me.I just want to highlight them with a gray background and keep whatever normal color it should be for the font. How could I set that?
The following setup does not work. I'd like the code beyond 80 columns appearing yellowish, as the characters inside 80 columns in the snapshot.
;; face for long lines' tails
(set-face-attribute 'whitespace-line nil
                    :background "#555"
                    :weight 'bold)

;; face for Tabs
(set-face-attribute 'whitespace-tab nil
                    :background "#555"
                    :weight 'bold)

A: set-face-attribute changes only the attributes you specify.
Set :foreground to nil:
(set-face-attribute 'whitespace-line nil
                    :foreground nil
                    :background "#555"
                    :weight 'bold)

A: For me the unpleasant color turned out to be trailing-whitespace and I'm using this:
;; whitepace looks rediculous in color themes.
(defadvice color-theme-install (after my-color-theme-install-after activate)
  "Fix trailing-whitespace after color theme destroys it"
  (set-face-attribute 'trailing-whitespace nil
                      :foreground 'unspecified
                      :inverse-video 'unspecified
                      :slant 'unspecified
                      :weight 'unspecified
                      :background "#fff"))


text:
Q: Setting up custom certificate authentication in IIS 10 using OWIN We are trying to setup multiple authentication using OWIN/Katana and the webapi will be hosted on IIS 10 with certificate authentication and windows authentication. I'm following this blog by Andras Nemes to setup my local client and server certificate authentication. Unfortunately, after setting up the Web API in IIS, when I try to access the website with the client certificate, I'm getting 403 Forbidden error which says that the certificate is not trusted or invalid. I'm not sure what is causing this issue.
I tried setting up my IIS by following other posts also, I've tried to add the website certificate to IIS and bind it with mylocalsite.local and tried with and without editing "system.webServer/security/authentication/iisClientCertificateMappingAuthentication".

After searching a lot I found similar results but none of them worked. I'm not sure if it is because of the IIS 10 has a different workflow of configuring client server certificate authentication mechanism or is there a problem with my certificates.

Following are my self signed certificates, and I also have there pfx files.
RootCertificate:

RootCertificate.cer has been installed in Local Computer Trusted Root Certification Authorities as well as in Current User Trusted certificates.

localtestclientcert:

localtestclientcert.pfx has been installed in Current User under Personal certificates.

mylocalsite.local:

mylocalsite.local.pfx has been installed in Local Computer under personal certificates.

IIS Server certificates

website bindings

SSL settings of the website

EDIT 1: Modified "Trusted Certificates" to "Trusted Root Certification Authorities" for clarity

A: The solution is to add the root certificate to the trusted authorities using MMC (machine account) as indicated in this tutorial
https://learn.microsoft.com/en-gb/archive/blogs/asiatech/how-to-create-an-iis-website-that-requires-client-certificate-using-self-signed-certificates
If you import the certif to perosnal account using certmgr you'll get this error


text:
Q: Create a Cloud Foundry Service from a hosted Cloud Foundry application I have a Cloud Foundry application hosted using Swisscom. One of the features I require from the application is that the user can set up a Cloud Foundry Service - Specifically the Swisscom Secrets-Store service. However, this is turning out to be a bit of a challenge.
Firstly, I used the cloudfoundry-cli NPM module to create the service from my application much like the example provided:
const cf = require('cloudfoundry-cli')
cf.provisionService({
  name: 'mongoNo1',
  type: 'compose-for-mongodb',
  plan: 'Standard'
}, function(err) {
  if (err) return console.log(err)
  console.log('Service provisioned')
})

This worked fine when I was running my application locally because obviously I have the CF CLI installed on my computer. However, when I pushed the application to Swisscom and tried to create the service nothing happened as the CF CLI isn't installed on the application.
I have also checked out cf-nodejs-client which is suggested if you don't want to install the CF CLI by allowing you to pass your Cloud Foundry login details and API endpoint. However, I've checked the docs and it seems this NPM module doesn't allow you to create services. The documents show you can either getService, getServicePlans, getServices, or remove - No option to create.
Worst case scenario I thought I could SSH into the running application and install the CF CLI, but for that you need root access which is not possible.
My question is - Is it possible to install the CF CLI on the application when it is being pushed? Perhaps a buildpack which can install the CF CLI when the application is being pushed? I have checked the list of community buildpacks and this doesn't seem to exist and I wouldn't know where to start creating one. Otherwise, does anyone know how to create Cloud Foundry services from a Node application without the need of the CF CLI.

A:
Is it possible to install the CF CLI on the application when it is being pushed?

One option would be to simply bundle the cf cli with your application. It's a static binary, so it's pretty easy to bundle with your app. The following should work.

*

*Download the cf cli for Linux from here & unzip it.

*Put this into a folder that's under your application root. For example: mkdir bin/ then move your binary from step #1 to the bin/ folder.

*Add a .profile file to the root of your application. In that file, put export PATH=$PATH:$HOME/bin, which will put the bin/ directory from step #2 on the PATH (change bin to whatever you named that folder).

Now cf push your app. This will include the binary. When it starts up, the .profile script will execute and put the path to your cf binary on the PATH. Thus you can run cf ... commands in your container.
Hope that helps!


text:
Q: Run loginhook but get UID of current logged in user I hope I'm not asking something that will upset the great minds of stack overflow users; I believe I have done my homework but have come up empty handed.
In OS X, I'm trying to create a loginhook that will check to see if a file exists in the /usr/share folder, and if it does not exists, it should create an empty file with a title of the UID of the user who is logging in.
For example, if my UID is 501, while logging in, the script should check if a file called "501" exists in /usr/share. If it does not exist, it should create it.
The issue I'm running into is that all loginhooks are run as root, so if a file is created, it's file name is simply "0".
The only thing I have come up with thus far is:
#!/bin/bash
userID=$(id -u)
if [ ! /usr/share/$userID ]
touch /usr/share/$userID
fi

A: With the help and direction of vego, I've found my answer. Vego was mostly correct in that
    sudo userID=$(id -u $(logname))
will produce 501 (because my UID is 501) versus producing 0, which is the UID of root.
The thing about Login Hooks, however it appears, is that the account that runs the script is mDNSResponder. I came to this conclusion because after running my script, I got a file with the title of "65"; a little digging around and I found out which account has the UID of 65 on my machine.
So, the solution is this:
    userID=$(id -u $1)
and the reason why this works is because accruing to an Apple KB article, "In the login hook script, the variable $1 returns the short name of the user who is logging in."

A: Try adding man 1 logname.
userID=$(id -u $(logname))

# compare
sudo id -u
sudo id -u $(logname)


text:
Q: Modificar table AspNetUserClaims Asp.net Identity Bom dia,
Estou com um probleminha de lógica com o identity.
Preciso criar uma tela de acesso e gostaria de usar a table claim já disponibilizada pelo mesmo. O grande problema é que a tabela cria uma chave estrangeira para a table AspNetUsers, gostaria que este campo fosse uma chave estrangeira de uma table que vou criar.
Como posso modificar esta relação entre as tabelas?

A: Se você está usando ASP.NET Identity, o correto é sua entidade de Usuario herdar de IdentityUser:
public class Usuario : IdentityUser { ... }

A configuração de nomenclatura de tabelas pode ser mudada através do evento OnModelCreating usando Fluent API:
public class ApplicationDbContext : IdentityDbContext<Usuario>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }

    protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<IdentityUser>()
            .ToTable("Usuarios", "dbo").Property(p => p.Id).HasColumnName("UsuarioId");
        modelBuilder.Entity<Usuario>()
            .ToTable("Usuarios", "dbo").Property(p => p.Id).HasColumnName("UsuarioId");
    }
}

Analogamente, isso pode ser feito para IdentityUserClaim:
public class UsuarioIdentificacao : IdentityUserClaim { ... }

E a configuração:
        modelBuilder.Entity<IdentityUserClaim>()
            .ToTable("UsuarioIdentificacoes", "dbo").Property(p => p.Id).HasColumnName("UsuarioIdentificacaoId");
        modelBuilder.Entity<UsuarioIdentificacao>()
            .ToTable("UsuarioIdentificacoes", "dbo").Property(p => p.Id).HasColumnName("UsuarioIdentificacaoId");


text:
Q: htaccess redirect with query string I've url with a link parameter in it. I want redirect this to a php file.
How can I implement this using htaccess file?

Source url: www.example.com/?id=15&L=1&link=androidapp
Target url: www.example.com/test.php

I want to check if "link=androidapp" exists, then redirect to the php file.
I've tried the following code, but not working;
RewriteCond %{QUERY_STRING} ^link=androidapp$
RewriteRule ^(.*)$ http://www.example.com/test.php? [R=301,L]

Can you guys please help me to solve the problem?
Thanks.

A: It should work if you skip the ^ and the $ like this:
RewriteCond %{QUERY_STRING} link=androidapp
RewriteRule ^(.*)$ http://www.example.com/test.php? [R=301,L]

The ^ means that the your pattern matches only from the beginning of the querystring, but your querystring begins with id=15...

A: Use this:
RewriteCond %{QUERY_STRING} link=androidapp(&|$)
RewriteRule ^ http://www.example.com/test.php? [R=301,L]


text:
Q: QStringList file directory and filename I have been trying to get a list of all the file names of some images in a directory into a QStringList, the only problem is that I want the name of the directories to also be included in the resulting string.  For example, my list only consists of various image names such as "image_x.jpg" but I want the directories included too, such as "../../images/image_x.jpg". I have been trying different methods for the past few hours and have looked at the Qt docs and I am still stuck. Thanks in advance.
QDir dir ("../../images/");
dir.setSorting(QDir::Name);
QStringList list = dir.entryList(QDir::AllEntries | QDir::Dirs);

for (int i = 1; i < list.size(); i++)
{
    qDebug() << "Filename " + QString::number(i) + " = " + list.at(i);
}

A: You can use QDir::entryInfoList and QFileInfo::filePath:
QFileInfoList list = dir.entryInfoList(QDir::AllEntries);
for (int i = 1; i < list.size(); i++)
{
    qDebug() << "Filename " + QString::number(i) + " = " + list.at(i).filePath();
}

Alternatively, you can use QDir::filePath:
QStringList list = dir.entryList(QDir::AllEntries);
for (int i = 1; i < list.size(); i++)
{
    qDebug() << "Filename " << i << " = " << dir.filePath(list.at(i));
}

Note that QDir::AllEntries already includes QDir::Dirs, so there is no point in adding it again.
This approach has advantage against manually adding dir path to file path: Qt will correctly process cases when path ends or not ends with slash, and possibly other unforeseen cases.


text:
Q: JSoup Selector for multiple tags containing a phrase In JSoup, how do I write a selector that matches an element that can be from multiple tags, and contains a text phrase?
For example, I want to match any header tag that contains "phrase".
This works, but I want to avoid repetition:
:has(h1:contains(phrase), h2:contains(phrase), h3:contains(phrase))
This only matches h3's containing the phrase:
:has(h1, h2, h3:contains(phrase))

Sorry I didn't specify earlier because I wanted to keep the question simple. :( I need a pure selector solution as I'm actually using jsoup https://jsoup.org/cookbook/extracting-data/selector-syntax which "supports a CSS (or jquery) like selector syntax to find matching elements".

A: JSoup supports the select(String query) method not only on objects of type Document, but also on objects of type Elements. select(String query) itself returns Elements. Therefore you may concatenate several select statements to filter out what you want:
Elements hWithText = doc.select("h1,h2,h2").select(":matchesOwn(regEx)");

Of course you can also use select(":contains(whatever)", if you do not need the flexibility of regular expressions.

A: One option would be using the filter() method.

$(document).ready(function() {
  $("h1,h2,h3").filter(":contains('key word')").addClass('bingo');
});
.bingo {
  color: #ff0000;
}

This header does not contain the phrase

This header does not contain the phrase

This header does not contain the phrase

This header contains the key word

This header contains the key word

This header contains the key word

This header contains the key word but is an H4


text:
Q: java.sql.SQLNonTransientConnectionException: Could not create connection to database server- Google Cloud Platform I'm trying to create a spring boot application that inserts some data into GCP Mysql.But everytime I'm trying to run application it shows exception -
  java.sql.SQLNonTransientConnectionException: Could not create connection to database server.
Caused by: java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials

Now following is my application.properties file.Actual paparmeters not defined here-
     spring.cloud.gcp.sql.database-name=DemoDatabase
        spring.cloud.gcp.sql.instance-connection-name=xxxxxxxxxxx
        spring.datasource.initialization-mode=always
spring.cloud.gcp.credentials.location=C:/Users/utkar/Downloads/spring-boot-7208e0222fb1.json
    spring.datasource.url=jdbc:mysql://google/DemoDatabase?cloudSqlInstance=XXXXXXXXXXX&socketFactory=com.google.cloud.sql.mysql.SocketFactory&useSSL=false
        spring.datasource.username=XXXXX
        spring.datasource.password=XXXXXX

Please help.Thanks in advance

A: Run the following command on the CLI:
gcloud auth application-default login


text:
Q: python 3.7 venv broken after upgrade to Ubuntu 20.04 I've just upgraded to Ubuntu 20.04. I was working with a python 3.7 project using Django inside a virtual environment, so I was confident even with the upgraded distro (which involved the installation of python 3.8) my venv would still worked. Unfortunately, that's not the case: when I activate my venv, the interpreter of python is still the 3.8 version, and nothing works. python 3.7 is completely missing. What can I do to restore my project?

A: Same problem for me. This is my solution if you do not want to upgrade everything (perhaps not all package are upgradable).

*

*Install python 3.7 which is gone with upgrade to ubuntu 20
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt-get install python3.7

*in your virtualenv dir (e.g env/) edit last line in pyenv.cfg
version = 3.7

*set back soft link of python3 in env/bin linking back to 3.7
ln -s  /usr/bin/python3.7 python3

You may need to delete old symlik before creating new one
Now, should work: it does for me!

A: In my case, it was solved just by deleting and recreating the virtual env, and reinstalling Django, of course. After that, just reloaded Apache and everything worked again.


text:
Q: Add product short description in cart Woocommerce I would like to add short product description to cart: I do add it to the cart but whats weird that it does not show on checkout page, as my cart is in the header. Any ideas or other solutions are very helpful thanks in advance
function excerpt_in_cart() {

$excerpt = get_the_excerpt();
$excerpt = substr($excerpt, 0, 80);
return '

' . $excerpt .'...' . '
';
}
add_action( 'woocommerce_cart_item_name', 'excerpt_in_cart', 40 );

When on checkout page it does not show this part from the code ' . $excerpt .' p shows up with the class just fine.

A: function excerpt_in_cart($cart_item_html, $product_data) {
global $_product;

$excerpt = get_the_excerpt($product_data['product_id']);
$excerpt = substr($excerpt, 0, 80);

echo $cart_item_html . '

' . $excerpt . '...' . '
';
}

add_filter('woocommerce_cart_item_name', 'excerpt_in_cart', 40, 2);

First of all woocommerce_cart_item_name hook is filter hook not the action hook.
Most of the things you did correctly few minor issues are

*

*You have to use add_filter with woocommerce_cart_item_name hook.

*Overwrote the woocommerce created html instead of concatenate your excerpt.

*Missed to handle each cart item's excerpt by using their product ID.

Additional info:
This is from wordpress core file plugin.php
function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
    return add_filter($tag, $function_to_add, $priority, $accepted_args);
}

function add_action is just the wrapper function of add_filter.


text:
Q: Save or Merge Patch Entity I want following functionality in spring data rest.
If I post to a collection resource end point, server should check if the object exists. if it exists already it should perform the same functionality as it does with merge-patch on item resource. If object does not exist already it should create it.
Is this achievable in spring data rest. If so then how?

A: If it is possible in your use case, you might want to use PUT instead of POST, as PUT should work as you expected.
Solution with POST
You can achieve the desired behavior with Spring Data REST Event handlers.
Just create a Handler method which accepts your entity and annotate it with @HandleBeforeCreate. In this method, you can implement your behavior, i.e. check if the object exists and update it manually or just do nothing and let the Spring Data REST handle the entity creation.
@RepositoryEventHandler
public class EntityEventHandler {

   @Autowired
   private EntityService entityService;

   @HandleBeforeCreate
   public void handleEntityCreate(Entity e) {
      if (entityService.exists(e)) {
         entityService.update(e);
      }
   }
}

EDIT:
I just realized that you would also need to stop the create event after your update. You might try throwing a custom Exception and Handling it to return 200 and the updated entity.


text:
Q: Visual studio 2017 - IDE black parts Some areas in Visual Studio 2017 are black(not refreshed) when i open it or i swich tabs. Text is showed again if i select it.

The biggest issue is in aspx files - it shows previous aspx file. When i hover over some menu options its fixed for that menu. Or if i change size of window its fixed but some areas stays black - line numbers.

A: Please try following this Microsoft thread to rectify the issues with the IDE.


text:
Q: FirebaseMessagingService onNewToken() is called but not onMessageReceived() I know that this question has been asked many times and answered, my issue has to do with Firebase Console telling me that my app never communicated with their servers even when my app successfully receives the registration token.
When I uninstall and reinstall my app, it does invoke onNewToken() method of FirebaseMessagingService class (or rather the class that extends from it).
Even FirebaseInstanceId.getInstance().getInstanceId() works fine and fetches the token.
But since firebase console says that the app never communicated with their servers, when I send a notification from the console, it does not reach my phone. At least, onMessageReceived() never gets called.
I do not know if there is a way to filter logcat to find out if a notification was indeed received by the phone and that there is something else wrong in my set up. If you know of such a way, that would help too.
In any case, if you have any suggestion, I would highly appreciate that. I have tried to send notifications with/without data from the console. I even tried to send to a topic and made the app subscribe to the topic. Yet, onMessageReceived() did not get called and notification did not get displayed. Quite frustrated. Please help.
app/build.gradle has:
dependecies {
implementation 'com.google.firebase:firebase-analytics:17.2.0'
implementation 'com.google.firebase:firebase-messaging:20.0.0'
}

apply plugin: 'com.google.gms.google-services'

project/build.gradle has:
buildscript {
    repositories {
        google()
        jcenter()
        maven { url 'https://jitpack.io' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.2'
        classpath 'com.google.gms:google-services:4.3.2'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://jitpack.io' }
    }
}

A: Did you also include the intent filter into your manifest? Like this:
<service
    android:name=".FirebaseServiceClassName"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>


text:
Q: Calling a function pointer with Emscripten With Emscripten, is it possible to call a function pointer (thus, a number) from JavaScript?
The signature of the function is variable, so I can't write a helper and be done.
To illustrate an example, I've got a function like this:
// Returns a function pointer to call, with the appropiate
// arguments, to initialize the demanded feature.
void* get_feature_activator(feature_t feat);

You're supposed to use it as follows:
// Initialize the speaker
void* activator = get_feature_activator(FEATURE_SPEAKER);
// We know this function needs one float, so we cast and call it
((void(*)(float))activator) (3.0);

To do the same with JavaScript:
var activator = _get_feature_activator(constants.FEATURE_SPEAKER);
// TODO: Need to call this pointer with one float

A: You can call a C function pointer from JS using Runtime.dynCall. See for example
https://github.com/kripken/emscripten/blob/ee17f05c0a45cad728ce0f215f2d2ffcdd75434b/src/library_browser.js#L715
The arguments are (type signature, pointer, array of arguments). For example, the type 'vi' means return void, receive one integer parameter. This corresponds to FUNCTION_TABLE_vi which you can see in the generated code.

A: I would create a C function:
void call_feature_activator(int activator, float in_val) {
  ((void(*)(float))activator) (in_val);
}

You can then call the function on the JavaScript side to trigger your activator call and it will handle casting back to a function pointer and calling it.