text:
Q: Copying and modifying a file to incorporate additional data I am novel to Perl and I am still in the exploring/beginners stage.
I have a text file that is built up as follows:
Naam;ISIN;Symbol;Market;Trading Currency\n
IDI;FR0000051393;IDIP;Euronext Paris;EUR\n
BETER BED;NL0000339703;BBED;Euronext Amsterdam;EUR\n
ALCATEL-LUCENT;FR0000130007;ALU;Euronext Paris;EUR\n
FIPP;FR0000038184;FIPP;Euronext Paris;EUR\n
...

With the following code, I manage to read the text file in the hashes/lists.
use strict;
use warnings;

my %data;
my @names;

my $myFile = "myfile.csv";
open(FH, '<', $myFile) or error("Cannot open file ($!)");

while (<FH>) {
    chomp;
    my @list = split(';');
    for (my $i = 0; $i <= $#list; $i++) {
        if ($. == 1) {
            $names[$i] = $list[$i];
        } else {
            push @{$data{$names[$i]}}, $list[$i];
        }
    }
}
close FH;

I have the following two questions.

*

*I wish to create an additional column (hash/list) called Ticker, which does roughly the following:
if ($Market eq "Euronext Paris") {
    $Symbol = "$Symbol.PA";
    {print "$Symbol\n"};
} elsif ($Market eq "Euronext Brussels") {
    $Symbol = "$Symbol.BR";
    {print "$Symbol\n"};
}

and so on for the other markets. (Note the above code worked when I read the file into an array, however, but I find it difficult to modify to the hases/lists compatible syntax.)

*How can I export the columns: Name, Symbol, Market and Ticker to a tab delimited text file?

A: Since you're doing a fairly simple transformation on your input file, the best best is to read your input file and create your output file at the same time. I've adapted your script to do this, and have put comments throughout the code on what is going on. Please ask if you don't understand what the script is doing.
#!/usr/bin/perl
use warnings;
use strict;

# here are some tickers (including some I made up)
# initialise these at the top of your script in a hash
# if you want to get the abbreviation for, say, 'Euronext Roma',
# you access it using $tickers{'Euronext Roma'}
my %tickers = (
    'Euronext Paris' => 'PA',
    'Euronext Brussels' => 'BR',
    'Euronext Madrid' => 'MA',
    'Euronext Roma' => 'RO'
);

# set up the input file
my $infile = "myfile.csv";
open my $in, '<', $infile or die "Cannot open file $infile: $!";

# this will be our output
my $outfile = 'stocks_with_tickers.txt';
open my $out, '>', $outfile or die "Cannot open file $outfile: $!";

# print out the column headers for the new file
# the function join takes a separator as its first argument,
# and joins the array of variables following it with that separator
print { $out } join "\t", "Name", "Symbol", "Market", "Ticker\n";

# input file format:
# Naam;ISIN;Symbol;Market;Trading Currency
# when we split the line to form an array, we will want the values
# in array positions 0, 2, 3 (the first array position is 0 in Perl)

# output file format:
# Name; Symbol; Market; Ticker
# we get the ticker by looking for $tickers{ MARKET }
#

while (<$in>){
    # skip the line unless it contains some alphanumeric characters
    next unless /\w+/;
    # $. is the number of the line that we are on.
    # Skip the first line of the file (the header row)
    if ($. == 1) {
        next;
    }

    # split up the line
    my @list = split ";";
    # print cols 0, 2, 3 to the output
    # note that the braces around $out ( i.e. { $out } ) are to make it
    # clearer that $out is the file that you're printing the results in
    print { $out } join "\t", $list[0], $list[2], $list[3],

    # we're going to use the ternary form of if/else, which allows
    # us to do an in/else test within the print statement
    # this line tests if $tickers{ MARKET } exists
    ( exists $tickers{ $list[3] } )
    # if it does, print out the market symbol plus the ticker abbrev
    ? $list[2] . "." . $tickers{$list[3]} . "\n"
    # otherwise, leave it blank
    : "\n";
}
close $in;
close $out;
# we're done!


text:
Q: What is the purpose of attribute "population" in OpenLayer Features? In feature usage example, there is 2 attributes called population and rainfall.
...
var iconFeature = new ol.Feature({
    geometry: new ol.geom.Point([0, 0]),
    name: 'Null Island',
    population: 4000,
    rainfall: 500
});
...

What does it means? I searched around and didn't find any information.

A: It's an example of adding generic properties to a feature that you can then use elsewhere. The example doesn't make it super obvious. In that example you could add another property called 'numberOfDonkeys' with a value of 20, and then you could use that in the click event that fires the popup.
Foe example, I can change the Feature to be this.
var iconFeature = new ol.Feature({
  geometry: new ol.geom.Point([0, 0]),
  name: 'Null Island',
  population: 4000,
  rainfall: 500,
  numberOfDonkeys: 20
});

And change the map click event to this.
// display popup on click
map.on('click', function(evt) {
  var feature = map.forEachFeatureAtPixel(evt.pixel,
      function(feature) {
        return feature;
      });
  if (feature) {
    var coordinates = feature.getGeometry().getCoordinates();
    popup.setPosition(coordinates);
    $(element).popover({
      'placement': 'top',
      'html': true,
      'content': feature.get('name') + ' Pop: ' + feature.get('population') + ' Donkeys: ' + feature.get('numberOfDonkeys')
    });
    $(element).popover('show');
  } else {
    $(element).popover('destroy');
  }
});

And you'll see the Population and numberOfDonkeys attributes in the popup.
jsFiddle Example - https://jsfiddle.net/6vd5gtho/
Ultimately you don't need those attributes at all, you could get rid of them, they are just examples of where you could put attributes you wanted to reuse in this way.

A: It doesn't mean anything. Null Island is an imaginary feature with some attributes defined, that's all.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple loading in Redux On my page, I have 3 dropdowns that are taking data from the API and I need 3 loadings for each one of them.
const {loading, error, watchMakes } = watchMakeList;
const {loading, error, watchModels } = watchModelList;
const {loading, error, watchSize} = watchSizeList;

But I cannot do it like this because I am getting an error that says Identifier 'loading' has already been declared. So can you give me an idea to fix this issue and use the loading in multiple places?

A: You can do the renaming of those loading and error variables like this:
const {loading: makeListLoading, error:makeListError, watchMakes } = watchMakeList;
const {loading: modeListLoading, error: modeLsitError, watchModels } = watchModelList;
const {loading: sizeListLoading, error: sizeListError, watchSize} = watchSizeList;

A: you can assigning to new variable names like this:
const {loading: makeLoading, error, watchMakes } = watchMakeList;
const {loading: modeLoading, error, watchModels } = watchModelList;
const {loading: sizeLoading, error, watchSize} = watchSizeList;

A: try assigning loading to a new variable name. It's not a feature in React. It's Javascript Destructuring.
const {loading: newVariableOne, error, watchMakes } = watchMakeList;
const {loading: newVariableTwo, error, watchModels } = watchModelList;
const {loading: newVariableThree, error, watchSize} = watchSizeList;

https://wesbos.com/destructuring-renaming is a good resource about this topic.


text:
Q: Decimal to string - FloatToStrF gives back imprecise result - alternative solution? I'm using Delphi7.
GetLocaleFormatSettings(1038, FS);
FS.DecimalSeparator := '.';
FS.ThousandSeparator := #0;
FS.NegCurrFormat := 5;
FS.CurrencyString := '';

XMLNode.Text := FloatToStrF(Query.FieldByName('Quantity').AsFloat, ffGeneral, 18, 2, FS);

Quantity DB field (Firebird) is 18,2 DECIMAL.
The problem:
If the value of Quantity is 15.6, sometimes FloatToStrF will give back 15.600000012 or 15.59999996 or similar.
I'm putting the result into an XML file with strict validation (18,2) and it is generating an error.
Restarting the computer may solve the problem.
I'm thinking this is a floating point issue, but what can I use instead of FloatToStrF to convert a decimal number to string?
Thank you!


text:
Q: Send push notification using php and ionic alpha push notification I have follow the all steps to built simple app in ionic framework from here.And I am using php code for server side to call the ionic API for push notification. I have Used the following code but i am not getting notification in my app , Please suggest the solution.
    <?php
    $androidAppId = "e2c77770";
    $data = array(
      "tokens" => "APA91bF2YePDKxE6K6vZYs2KQ27Z4mdehJg-EaZaPy10w-RHN5RUgC_P6Uie24Qu_M28j9bfZcbU6pu8Awofa8h2G5j9jABnebrVIUgKM5JcZPEJHYVW2NINirAm7VnSqGOrqm4YicAoI9Xiw5zkgTx4edqXIANLEhvqsqSCeq-_gAuzZB8wvrQ",
      "notification" => "Hello World!"
    );
    $data_string = json_encode($data);
    $ch = curl_init('https://push.ionic.io/api/v1/push');
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'X-Ionic-Application-Id: '.$androidAppId,
        'Content-Length: ' . strlen($data_string))
    );

    $result = curl_exec($ch);
    ?>

A: I've never dealt with ionic but according to the python example given in http://docs.ionic.io/v1.0/docs/push-sending-push you should add Authorization header to the request.
private_key = YOUR_PRIVATE_API_KEY
b64 = base64.encodestring('%s:' % private_key).replace('\n', '')
#I didn't get why they used colon while encoding the api key??
req.add_header("Authorization", "Basic %s" % b64)

PHP implementation of that python snippet would be like that;
<?php
$yourApiSecret = "YOUR API SECRET";
$androidAppId = "e2c77770";
$data = array(
  "tokens" => "APA91bF2YePDKxE6K6vZYs2KQ27Z4mdehJg-EaZaPy10w-RHN5RUgC_P6Uie24Qu_M28j9bfZcbU6pu8Awofa8h2G5j9jABnebrVIUgKM5JcZPEJHYVW2NINirAm7VnSqGOrqm4YicAoI9Xiw5zkgTx4edqXIANLEhvqsqSCeq-_gAuzZB8wvrQ",
  "notification" => "Hello World!"
);
$data_string = json_encode($data);
$ch = curl_init('https://push.ionic.io/api/v1/push');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'X-Ionic-Application-Id: '.$androidAppId,
    'Content-Length: ' . strlen($data_string),
    'Authorization: Basic '.base64_encode($yourApiSecret)
    )
);

$result = curl_exec($ch);
var_dump($result);

Also output of the result may tell you a lot about the status of push notification you want to send.

A: I have created a complete library that allows you to consume the Ionic Cloud API for sending push notifications (normal and scheduled), get a paginated list of sending push notifications, get notifications messages, get information of registered devices, remove registered devices by token, etc.
This library requires PHP 5.1+ and cURL.

Installation:
composer require tomloprod/ionic-push-php

Sending a notification:
use Tomloprod\IonicApi\Push;

$ionicPushApi = new Push($ionicProfile, $ionicAPIToken);

// Configuration of the notification
$notificationConfig = [
    'title' => 'Your notification title',
    'message' => 'Your notification message. Bla, bla, bla, bla.'
];

// [OPTIONAL] You can also pass custom data to the notification. Default => []
$payload = [
    'myCustomField' => 'This is the content of my customField',
    'anotherCustomField' => 'More custom content'
];

// [OPTIONAL] And define, if you need it, a silent notification. Default => false
$silent = true;

// [OPTIONAL] Or/and even a scheduled notification for an indicated datetime. Default => ''
$scheduled = '2016-12-10 10:30:10';

// [OPTIONAL] Filename of audio file to play when a notification is received. Setting this to default will use the default device notification sound. Default => 'default'
$sound = 'default';

// Configure notification:
$ionicPushApi->notifications->setConfig($notificationConfig, $payload, $silent, $scheduled, $sound);

// Send notification to all registered devices:
$ionicPushApi->notifications->sendNotificationToAll();

// or send notification to some devices:
$ionicPushApi->notifications->sendNotification([$desiredToken1, $desiredToken2, $desiredToken3]);

You can read more about this library here: https://github.com/tomloprod/ionic-push-php


text:
Q: AJAX xmlhttprequest popup Basically, what I'm trying to do is have a fade in/out popup in the corner of my page. e.g. John Doe has just come online. I'm using AJAX to check for the latest updates, if they are new, display the popup.
the function to display popup (using jquery) is:
function hidepop(){
  $("#popup").fadeOut("slow");
}

function showpop(){
  $("#popup").fadeIn("slow");
  setTimeout("hidepop()",4000);
}

The code to update and show the popup, if necessary, is:
function getHTTPObject(){
  if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
  else if (window.XMLHttpRequest) return new XMLHttpRequest();
  else {
    alert("Your browser does not support AJAX. Please download Google Chrome or Firefox.");
    return null;
  }
}

function checkUpdates(old){
  httpObject = getHTTPObject();
  var randomnumber=Math.floor(Math.random()*10000);
  if (httpObject != null) {
    link = "updates.php?rnd="+randomnumber;
    httpObject.open("GET", link , true);
    httpObject.onreadystatechange = function() {
      if(httpObject.readyState == 4){
        var response = httpObject.responseText;
        var objDiv = document.getElementById("popup");
        objDiv.innerHTML = response;
        if(response == old){
          var time = setTimeout(function(){checkUpdates(response); response = null},5000);
        }else{
          var objDiv = document.getElementById("popup");
          objDiv.innerHTML = response;
          showpop();
          var time = setTimeout(function(){checkUpdates(response); response = null},5000);
        }
      }
    }
  }
}

Then, to start it all off:
onload="checkUpdates('');"

on the body tag.
So, my problem is... nothing happens.  I know that showing the popup works because if I call showpop() it will show.
This is probably some stupid mistake but, could you please give me some ideas/pointers to what the problem might be and how to fix it.
Thank you very much,
Calum.

A: I would start by using jquery's 'get' method, since you seem to be using jquery already.
var old = '';
function checkUpdates() {
    var randomnumber = Math.floor(Math.random() * 10000);
    link = "updates.php?rnd=" + randomnumber;
    $.get(link, function(data) {
        /* called when the resource was successfully retrieved */
        if (old != data) {
            $('#popup').html(data); // set the new data in the popup element
            showpop();              // show the popup
            old = data;             // store the retrieved data
        }
        setTimeout(checkUpdates, 5000);
    });
}

Your showpop and hidepop functions are not really defined correct.
Maybe you could read up on document.ready(...).
This should do the trick (notice that with jquery's delay function you can nicely chain everything:
function hidepop(){
    $("#popup").fadeOut("slow");
}

function showpop(){
    $("#popup").fadeIn("slow");
    setTimeout(function() {hidepop();}, 4000);
}


text:
Q: Asymptotic behaviour of $\sum_{k=1}^{n}\frac{R_{k+1}+R_k}{R_{k+1}-R_k}$, where $R_k$ are the Ramanujan primes I was inspired in the following post from this Math Overflow that was asked yerterday Asymptotic behavior of a certain sum of ratios of consecutives primes to ask about a similar question for ratios involving Ramanujan primes $R_n$.
As motivation (I think that) Ramanujan primes have a special importance in the theory of prime gaps, thus I think that this series should be also interesting and a good companion of the question asked yesterday. I add as reference this Wikipedia Ramanujan prime.

Question. We denote the sequence of Ramanujan primes as $R_k$. What work can be done about the asymptotic behaviour of $$\sum_{k=1}^{n}\frac{R_{k+1}+R_k}{R_{k+1}-R_k}$$
  as $n\to\infty$? I'm asking if you can improve/refute my calculations below, adding what statement (in Landau notation or as an asymptotic equivalence) you can to get.  Many thanks.

The part that I know is that using Sondow's asymptotic and the comment of one of  the professors of the mentioned MO post 351875 the quotient in our series should be roughly $$\frac{(4k+1)\log(2k)+2(k+1)\log\left(1+\frac{1}{k}\right)}{2\log(2k)+2(k+1)\log\left(1+\frac{1}{k}\right)}$$
and from this, and that $\sum_{k=1}^n\frac{4k+1}{2}=n^2+\frac{3n}{2}$, my guess that (Vinogradov's notation)
$$\sum_{k=1}^{n}\frac{R_{k+1}+R_k}{R_{k+1}-R_k}\ll\left(n^2+\frac{3n}{2}\right)\log\log n$$
as $n\to\infty$, I don't know if the factor $\log\log n$ in RHS of previous is the most suitable.
References:
[1] J. Sondow, Ramanujan primes and Bertrand's postulate, Amer. Math. Monthly, 116 (7): 630–635 (2009).


text:
Q: CountryDropdownField - Setting default to what is set in setEmptyString()? I am using the CountryDropdownField. I have set the empty string. It keeps defaulting to United States though. How I do I make it default to what is set in the empty string?
$fields = new FieldList(
    CountryDropdownField::create('Country')
        ->setEmptyString('-- Please choose a country --')
);

A: Adding the following to the mysite_config\config.yml (then ensure a dev/build?full=1 is run) to achieve this...
CountryDropdownField:
  default_to_locale: false
  default_country: ''


text:
Q: How to globally rotate the screen to a specified orientation (even with private api) in jailbroken iOS? My tweak is running inside SpringBoard, in which I need it be able to rotate the whole screen to a specified orientation and keep there.I've searched much with Google but got nothing, most of them are just talking about how to get the orientation changed notification.How can I set the orientation by force, could anyone help?I'll very appreciate it.
This code looks fit but doesn't work in my testing:
[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationPortrait];

A: For iOS 7
NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];

for iOS 8
let value = UIInterfaceOrientation.LandscapeLeft.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")

Write above code in an event on which you want to rotate your screen.
And make sure the app supports orientation that you want.
To enable multiple orientation go in the app targets and check mark orientation like below


text:
Q: How to write unit test on code that is using Google Maps for JS I'm writing some JavaScript module that is meant to running in browser (client side, not server side). This module is using Google Maps JavaScript API.
I want to cover my code by unit tests. I also want my tests to be isolated. I found several vcr-like JS libraries for recording and mocking HTTP-requests that Google Maps Api is producing. But all of them are for Node.JS (because PhantomJS doesn't support using fs module). Also Node.JS has more rich and readable backtraces than PhantomJS has.
So I'm wondering how to include Google Maps Javascript API to my tests with Node.JS-based test runner and how to write test for my code?
P.S. I'm not stick with some certain JS unit-test library. It can be Jasmine, QUnit or any other.
P.P.S It not necessary should be Node.JS runner. If there are another options it is completely OK!
P.P.P.S. My goal is to avoid following things:

*

*to avoid dependency on internet connection and corresponding delays in tests

*to avoid failing tests because of changing some GEO data on Google servers. For example: if I use directions, I don't really care if it 2000 meters or 2001 meters, I just wanna know, that I get some appropriate data from Google and perform some calculations with it.

P.P.P.P.S. Thanks to @MichaelGeary answer we know that Google saves only 3 versions of their API. But I'm not focusing only on Google Maps, I chose it in that question because of it's popularity/ I have the same question applied to any other maps api like Yandex.Maps, Leaflet (with openstreet), Bing and etc. Most of them don't delete old APIs, so I can fix version and rely on not changing internal API and HTTP requests.
Also I want to avoid mock hell, because my code is quite complex and uses a lot of geo objects of different kind. So it will not be easy to mock all of them and then support that code. It looks like unbearable thing.
My idea is to fix version of API for some time (in Google case for not so long time) and rely on persistence of internal HTTP requests format. And from time to time delete all recorded data to be sure that everything is still OK in real world.
I want myself to be one who control when I should fix my test. I don't wanna Google to break my tests at random moment of time.

A: Recording or mocking the HTTP requests made by the Maps API is certainly an interesting idea!
Unfortunately, like any other undocumented features of the API, these requests are an internal implementation detail and are subject to change at any time. Google rolls out new versions of the API code four times a year, along with patch revisions as frequently as every few weeks. Any of the API internals—including the HTTP requests—could change from one version to the next, even in the patch revisions. The only thing they guarantee to be stable across versions or patches is the documented API.
Google does give you the ability to request a specific API version, but they don't keep old versions around for very long, and they don't keep old patch revisions at all. In fact, only three versions are live at any time. At this writing, these versions are available:

*

*The experimental version, currently 3.21.4.

*The release version, currently 3.20.12.

*The frozen version, currently 3.19.19.

When the next experimental version (3.22) is rolled out, 3.21 will become the release version, 3.20 the frozen version, and 3.19 will be retired and no longer available.
The frozen version does have one difference from the release and experimental versions: it no longer receives any patches so it is completely stable. It should be safe to assume that the HTTP requests made by the frozen version won't change. But this only helps until that version is retired.
Here is a fiddle to experiment with requesting different API versions and displaying what version is actually loaded. The code looks like this:
<!DOCTYPE html>

    <title>Google Maps API version test</title>

The fiddle uses a v=3.18 parameter in the Maps API script URL to request version 3.18, but it actually loads version 3.19.19 at this moment. You can change the v= parameter to different values to see which API version gets loaded. (Besides the specific numbered versions, you can also use v=3 to get the current stable version, or v=3.exp to get the current experimental version.)
The sharp-eyed reader may note that the google.maps.version property this code displays is itself undocumented! But hey, this is experimental test code. :-)
It's fairly common for the HTTP requests to change from version to version, and even possible for them to change in a patch revision. As you can see from the list above, version 3.19 has gone through 19 patch revisions, and 3.20 has gone through 12 patch revisions.
If you want to write unit tests for your Maps API code, my suggestion is to mock the documented Maps API itself instead of mocking any of its internals. For example, your mock for google.maps.Map could check that its first parameter is a DOM node and that its second (optional) object parameter contains only known properties with legitimate values for those properties.
Of course the Maps API exposes quite a large number of objects, methods, and properties, but you don't have to mock the whole thing, just the parts of it you are using.


text:
Q: How to redirect to application after login the twitter(iPhone settings page)? How can I back to the iPhone application after login the twitter?(See the image)
Is it possible to redirect from the settings page?
Please help me. Thanks in advance.

A: There's no way of doing that, but an alternative would be opening the external link in a UIWebView, then you will always be in your app!

A: NO you can not redirect back to your app. Apple does not provide any means to do this.

A: You can't redirect from the Settings app, but if you want to redirect between other apps, you can use UrlShemes. UrlShemes

A: There is no way to do that because that is not a standard iPhone functionality.
You can't redirect from one app to another, and Settings is an application like all the rest. Furthermore you can't change the behaviour of existing applications, each app is in a sandbox and is separate from others.
There is no need to do something like this and users don't expect that kind of behaviour.


text:
Q: Spec$(\mathbb{C}[x_1^2,x_2]) =$? I want to make sure that Spec($\mathbb{C}[x_1^2,x_2]) \cong \mathbb{C}^2/\mathbb{Z}_2(1,2)$. (Silly example while learning quotient singularities)
The variety $\mathbb{C}^2/\mathbb{Z}_2(1,2)$ is defined as the quotient of $\mathbb{C}^2$ where $-1 \in \mathbb{Z}_2$ acts by $(x_1, x_2) \to (-x_1, x_2)$. The ring of functions invariant under the action is $\mathbb{C}[x_1^2,x_2]$. How do I find at least all the maximal ideals? My guess is they are of form $(x_1^2-a, x_2-b)$.
How is the ring $\mathbb{C}[x_1^2,x_2]$ related to $\mathbb{C}[x_1, x_2]$?
This action gives us a morphism between varieties $\mathbb{C}^2 \to \mathbb{C}^2/\mathbb{Z}_2(1,2)$, so the induced homomorphism of coordinate rings should be $\mathbb{C}[x_1^2,x_2] \to \mathbb{C}[x_1, x_2]$ by sending $x_1^2 \to x_1$. But isn't that an isomorphism...?

A: The canonical morphism of varieties $\mathbb{C}^2\to\mathbb{C}^2/\mathbb{Z}_2(1,2)$ does not correspond to the homomorphism $\mathbb{C}[x_1^2,x_2]\to\mathbb{C}[x_1,x_2]$ sending $x_1^2$ to $x_1$ (and $x_2$ to $x_2$), which you correctly observe is an isomorphism.  Instead, the corresponding homomorphism is just the inclusion map, which sends $x_1^2$ to $x_1^2$ and $x_2$ to $x_2$.  Indeed, when you identify the coordinate ring of $\mathbb{C}^2/\mathbb{Z}_2(1,2)$ with the invariant subring of the coordinate ring of $\mathbb{C}^2$, you are implicitly identifying the coordinate ring of $\mathbb{C}^2/\mathbb{Z}_2(1,2)$ with its image in $\mathbb{C}[x_1,x_2]$ under the canonical homomorphism.  Once you have made this identification the canonical homomorphism becomes just the inclusion map.
As for determining the maximal ideals of $\mathbb{C}[x_1^2,x_2]$, your guess is correct, and this follows by combining the Nullstellensatz with the isomorphism $\mathbb{C}[x_1^2,x_2]\to\mathbb{C}[y,z]$ sending $x_1^2$ to $y$ and $x_2$ to $z$ (I use different variable names to emphasize, as above, that this is not the canonical homomorphism given by the action).  In fact, this isomorphism gives an isomorphism of varieties $\mathbb{C}^2/\mathbb{Z}_2(1,2)\cong \mathbb{C}^2$.


text:
Q: A specific calculation problem about 1D path integral Description
In Littlejohn's note 9, the author deduce 1D propagator by using 1D path integral.
$$
K(x,x_0,t)=\lim_{N\rightarrow\infty}(\frac{m}{2\pi i\hbar\epsilon})^{N/2}\int {\rm d}x_1...{\rm d}x_{N-1}\times\exp\{\frac{i\epsilon}{\hbar}\sum_{j=0}^{N-1}[\frac{m(x_{j+1}-x_j)^2}{2\epsilon^2}-V(x_j)]\}. \tag{25}
$$
After that, the author tries to simplify this formule by using stationary phase approximation, which means   we only consider about some path which are close to the classical path.
In the derivation of this formule, we need to calculate a matrix's determinant. The elements of this matrix are $$
Q_{kl}=2\delta_{kl}-\delta_{k+1,l}-\delta_{k-1,l}-\frac{\epsilon^2}{m}V^{\prime\prime}(x_k)\delta_{kl}-{\rm eq}.(66)
$$
In the following part of this note, the author translate this problem to a differential equation.
$$
m\frac{{\rm d}^2 F(\tau)}{{\rm d}\tau^2}=-V^{\prime\prime}(\bar{x}(\tau))-{\rm eq}.(76)
$$
Then the author skip some details and directly get the final result
$$
\lim_{N\rightarrow\infty}{\rm det}Q_{kl}=-\frac{m}{\epsilon}(\frac{\partial^2 S}{\partial x\partial x_0})^{-1}-{\rm eq}.(79)
$$
Problem
I don't really understand how to derive eq.(66) to eq.(79), especially the derivation from eq.(76) to eq.(79). I wish someone could tell me the specific details about this derivation.


text:
Q: add callback function for poll in c I am working on a project which requires monitoring on a socket. I know how to do the busy waiting using while-loop to keep reading incoming data if there is one.
Is there a way to setup a callback function so that whenever there is data on the I/O, it will read the data and call my callback function?

A: There are more-or-less supported socket calls: poll(), select(), epoll() which don't provide a callback, but are better than simple read(). On a fully compliant POSIX system, there is posix_aio. For cross platform support, there are several libraries (not part of standard C library) that provide what you want, like libuv, libevent, etc. –  srdjan.veljkovic


text:
Q: Jupyter conda tab 'An error occurred while retrieving package information.' In my root environment I run
$ jupyter notebook

and in the browser, click on the 'Conda' tab. This always used to list my conda environments and the packages in them. Now I'm greeted by the following error.

I recently created and deleted some conda environments, maybe that is relevant. The only console output is
[W 10:30:20.948 NotebookApp] 404 GET /environments?_=1476811818902 (::1) 13.19ms referer=http://localhost:8888/tree
[W 10:30:20.951 NotebookApp] 404 GET /packages/available?_=1476811818903 (::1) 1.77ms referer=http://localhost:8888/tree

A: See this issue:
https://github.com/Anaconda-Platform/nb_conda/issues/23
The issue seems to be a conflict between the notebook config file in the conda environment and the config file in the users directory.
To fix the issue and get the tab to display properly the content, I had to remove that file:
rm jupyter_notebook_config.json in ~/.jupyter
Note that, for me, that was not an issue as it did not really contain anything.

A: As pointed out at: https://github.com/Anaconda-Platform/nb_conda/issues/23#issuecomment-239813091
The following command helped in resolving the issue:
jupyter serverextension disable nb_conda
jupyter serverextension enable nb_conda

This basically rewrites the config file in the ~/.jupyter folder.

A: On windows, running conda install -c conda-forge nb_conda_kernels worked for me.

A: If no of the commands work for you, try adding kernels manually for each of the environments (as pointed out by Andreas Mueller):
source activate <my_environment>
python -m ipykernel install --user --name <my_environment> --display-name "<Display name>"

A: I replaced for env in info['envs']] by for env in info['envs'] if env != info['root_prefix']] in this pathanaconda3\pkgs\nb_conda-2.2.1-py38_1\envmanager.py
and that solve all errors

A: For me I just needed to close the current Jupyter notebook session and start again, then the error disappeared and it was able to load the envs.


text:
Q: I am implementing pset3 Felipe's Taqueria in cs50p; but I have noticed something odd in the variables after running debug My code seems to work perfectly except it output a float with only one decimal place instead of two as per dictionary created.
The dictionary gave each item a price e.g "Taco": 3.00; surprisingly when I run debug dictionary has different value e.g "Taco": 3.0 instead of 3.00
I would like to know why it is behaving this way.
here is my code:
# make a dictionary
dict = {
    "Baja Taco": 4.00,
    "Burrito": 7.50,
    "Bowl": 8.50,
    "Nachos": 11.00,
    "Quesadilla": 8.50,
    "Super Burrito": 8.50,
    "Super Quesadilla": 9.50,
    "Taco": 3.00,
    "Tortilla Salad": 8.00
}
# with a while loop prompt for item and add item value until user input exit
total = 0
while True:
    try:
        item = input("Item: ").strip().title()
        for order in dict:
            if order == item:
                total = total + (dict[order])
                print(f"${total}")
    except EOFError:
        break

I expected my program to output a total of two decimal places instead of just one.


text:
Q: SwiftUI button path problem: unrecognized selector error pops up when ran Thread 1: Exception: "-[UniversityFinder.ViewController ButtonTapped:]: unrecognized selector sent to instance 0x7fa924f04f00"
I'm using a storyboard to create a university finder and I needed a path for my button that leads to another page. I created a segue with the present modally mode. But when I run the Xcode, the error above pops up in the AppDelegate.swift page. Any advice to fix this error? Much appreciated.

A: You can try check storyboard or xib with this button outlet, delete all and reconnect outlet with function "ButtonTapped".


text:
Q: Changing a programs "start in" property via batch file I am trying to change the "Start In" property of a program via batch file for an install script that I am writing for windows 10. I have not been able to find any info about where or how to do this. I've been dealing with the registry to other reasons, but I can't seem to find these fields in the registry. Here is photo of what I am trying to change for more clarity.
Here is a link to the image because my reputation is too low:
https://cdn.discordapp.com/attachments/362700323099246593/523723895199629315/GetAttachmentThumbnail.png

A: Download Shortcut.zip and extract it to a temporary directory. Read the file ReadMe.txt and copy the small executable Shortcut.exe written by Marty List into the directory of the batch file.
In the batch file use:
"%~dp0Shortcut.exe" /F:"C:\Path of\Shortcut.lnk" /A:E /W:"C:\Full path to new\Start in"

The small executable Shortcut.exe can be used of course also to create the *.lnk file.

A: I'm partial to solutions that work with native Windows components. PowerShell has access to the Windows shell object, which is where all the shortcut behavior is defined (or, at least, accessible).
In your case, you want to set the 'WorkingDirectory' field.
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\MyShortcut.lnk")
$Shortcut.TargetPath = "path\to\parametric.bat"
$Shortcut.WorkingDirectory = "C:\Data\proengineer"
$Shortcut.Save()

More Info

*

*.CreateShortcut (SS64.com) (Sadly, I cannot find a standard reference from Microsoft about CreateShortcut())

*How to create a shortcut using PowerShell (StackOverflow)

*How to create a desktop shortcut with the Windows Script Host (support.microsoft.com)


text:
Q: Map not getting loaded and showing error in android Hi I am Struggling for two days, in my Map Application Map is not displayed  and getting the below error.. i Searched lot and din't get any proper solution yet..
Xml File
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
      android:layout_height="match_parent"
    tools:context=".MainActivity" >

  <fragment
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
  class="com.google.android.gms.maps.SupportMapFragment" />

MainActivity.java
    package com.example.googlegpstracker;

     import com.google.android.gms.common.GooglePlayServicesUtil;

     import android.os.Bundle;
      import android.support.v4.app.FragmentActivity;
    import android.view.Menu;

     public class MainActivity extends FragmentActivity {
    private GoogleMap map;

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

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

mainfest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.googlegpstracker"
android:versionCode="1"

android:versionName="1.0" >
 <uses-sdk
android:minSdkVersion="17"
 android:targetSdkVersion="17" />

     <permission
   android:name="com.example.googlegpstracker.permission.MAPS_RECEIVE"
     android:protectionLevel="signature" />

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="com.example.googlegpstracker.permission.MAPS_RECEIVE" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
   android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
     android:theme="@style/AppTheme" >
     <activity
  android:name="com.example.googlegpstracker.MainActivity"
  android:label="@string/app_name" >
     <intent-filter>
      <action android:name="android.intent.action.MAIN" />

   <category android:name="android.intent.category.LAUNCHER" />
  </intent-filter>
      </activity>

      <meta-data
      android:name="com.google.android.maps.v2.API_KEY"
    android:value="AIzaSyC0hlJU8lEbvXmqckdUHHRhRoRkF0KpYR8" />
        </application>

   </manifest>

And below is my Logcat
     06-22 13:53:41.197: E/AndroidRuntime(1638): FATAL EXCEPTION: main
           06-22 13:53:41.197: E/AndroidRuntime(1638): java.lang.RuntimeException: Unable       to start activity        ComponentInfo{com.example.googlegpstracker/com.example.googlegpstracker.MainActivity}: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
06-22 13:53:41.197: E/AndroidRuntime(1638):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
06-22 13:53:41.197: E/AndroidRuntime(1638):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-22 13:53:41.197: E/AndroidRuntime(1638):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-22 13:53:41.197: E/AndroidRuntime(1638):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-22 13:53:41.197: E/AndroidRuntime(1638):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-22 13:53:41.197: E/AndroidRuntime(1638):     at android.os.Looper.loop(Looper.java:137)
06-22 13:53:41.197: E/AndroidRuntime(1638):     at android.app.ActivityThread.main(ActivityThread.java:5041)
06-22 13:53:41.197: E/AndroidRuntime(1638):     at java.lang.reflect.Method.invokeNative(Native Method)
06-22 13:53:41.197: E/AndroidRuntime(1638):     at java.lang.reflect.Method.invoke(Method.java:511)
06-22 13:55:22.367: E/AndroidRuntime(1707): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.maps.SupportMapFragment" on path: /data/app/com.example.googlegpstracker-1.apk
06-22 13:55:22.367: E/AndroidRuntime(1707):     at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65)
06-22 13:55:22.367: E/AndroidRuntime(1707):     at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
06-22 13:55:22.367: E/AndroidRuntime(1707):     at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
06-22 13:55:22.367: E/AndroidRuntime(1707):     at android.support.v4.app.Fragment.instantiate(Fragment.java:391)

A: Seems like you don't have the Google Play Services SDK referenced as a library project, which would explain why the class cannot be found.  Since com.google.android.gms.maps.SupportMapFragment is only referenced in xml, it would come up at run time and you wouldn't catch it before running the app.
Check out:
https://developers.google.com/maps/documentation/android/intro#sample_code
And here for info about setting up the SDK:
http://developer.android.com/google/play-services/setup.html

A: Try this.before this make sure that you have google API and you entered proper key and all in you.
`

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

</activity>

<uses-library android:name="com.google.android.maps" />

`


text:
Q: How to create ul li elements from nested JSON data in HTML DROPDOWN
But below is what I could find on internet. I want to create something like above. Below is the code snippet. It works totally fine. But how can I make it dynamic. I mean if I add ul and li manually the tree gets rendered correctly. But I want that to happen as per the JSON received from REST API. How to add ul and li elements from nested JSON data. Can someone please help me.
Working Code Link:
http://jsfiddle.net/jddevight/esS4k/
Working Code snippet:
var dropdown = $("#dropdown").kendoDropDownList({
    dataSource: [{ text: "", value: "" }],
    dataTextField: "text",
    dataValueField: "value",
    open: function (e) {
        // If the treeview is not visible, then make it visible.
        if (!$treeviewRootElem.hasClass("k-custom-visible")) {
            $treeviewRootElem.slideToggle('fast', function() {
                dropdown.close();
                $treeviewRootElem.addClass("k-custom-visible");
            });
        }
    }
}).data("kendoDropDownList");
var $dropdownRootElem = $(dropdown.element).closest("span.k-dropdown");

var treeview = $("#treeview").kendoTreeView({
    select: function (e) {
        // When a node is selected, display the text for the node in the dropdown and hide the treeview.
        $dropdownRootElem.find("span.k-input").text($(e.node).children("div").text());
        $treeviewRootElem.slideToggle('fast', function() {
            $treeviewRootElem.removeClass("k-custom-visible");
        });
    }
}).data("kendoTreeView");
var $treeviewRootElem = $(treeview.element).closest("div.k-treeview");

// Hide the treeview.
$treeviewRootElem
    .width($dropdownRootElem.width())
    .css({ "border":"1px solid grey", "display": "none", "position": "absolute" });

// Position the treeview so that it is below the dropdown.
$treeviewRootElem
    .css({ "top": $dropdownRootElem.position().top + $dropdownRootElem.height(), "left": $dropdownRootElem.position().left });

$(document).click(function(e) {
    // Ignore clicks on the treetriew.
    if ($(e.target).closest("div.k-treeview").length == 0) {
        // If visible, then close the treeview.
        if ($treeviewRootElem.hasClass("k-custom-visible")) {
            $treeviewRootElem.slideToggle('fast', function() {
                $treeviewRootElem.removeClass("k-custom-visible");
            });
        }
    }
});

HTML:

Item 1

Item 1.1

Item 1.2

Item 2

Item 2.1

Item 1.1

Item 1.2

Item 2.2

<input id="dropdown"></input>

A: Don't initialize treeview on ul element. Instead use div element. Then use datasource to assign data from json.
var treeview = $("#treeview").kendoTreeView({
  dataSource : [
    {
      "id"   :100,
      "text" :"tree",
      "items":[...

To update data simply call dataStore.data(newData).
treeview.dataSource.data([
  { text: "bar", items: [
    { text: "baz" }
  ] }
]);

Here's example how to that: http://jsfiddle.net/m2Lpw52g/


text:
Q: Can one app call another which then returns a result? I know it's possible to launch another app from within an app, using the openURL method. Also it is possible to check with canHandleURL if that app can open that URL.
But is there also a way to call an app and just let it do a calculation and then return the result?

A: Take a look here (example how to send a text to the called app)
in your case: let's say you have 2 apps (app1 and app2)
and 2 url schemes (protocolThatCallsApp1:// and protocolThatCallsApp2://)
in your app1, you call app2 using protocolThatCallsApp2://
then in your app2 you make your calculations and call app1 using protocolThatCallsApp1://+yourCalculations and you make the required parsing to get the result in your app1

A: The second app should use the same mechanism (openURL) to call the first app.
The Facebook sdk uses this method to implement Single Sign-On:

If the app is running in a version of iOS that supports multitasking, and if the device has the Facebook app of version 3.2.3 or greater installed, the SDK attempts to open the authorization dialog within the Facebook app. After the user grants or declines the authorization, the Facebook app redirects back to the calling app, passing the authorization token, expiration, and any other parameters the Facebook OAuth server may return.


text:
Q: SqlPackage Object reference not set to an instance of an object When I attempt to deploy DACPACs via SqlPackage.exe,
I encounter the error below :
An unexpected failure occurred: Object reference not set to an instance of an object..

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Data.Tools.Schema.Sql.SchemaModel.ReverseEngineerPopulators.Sql90TableBaseColumnPopulator`1.InsertElementIntoParent(SqlColumn element, TElement parent, ReverseEngineerOption option)
   at Microsoft.Data.Tools.Schema.Sql.SchemaModel.ReverseEngineerPopulators.ChildModelElementPopulator`2.CreateChildElement(TParent parent, EventArgs e, ReverseEngineerOption option)
   at Microsoft.Data.Tools.Schema.Sql.SchemaModel.ReverseEngineerPopulators.ChildModelElementPopulator`2.PopulateAllChildrenFromCache(IDictionary`2 cache, SqlReverseEngineerRequest request, OrdinalSqlDataReader reader, ReverseEngineerOption option)
   at Microsoft.Data.Tools.Schema.Sql.SchemaModel.ReverseEngineerPopulators.TopLevelElementPopulator`1.Populate(SqlReverseEngineerRequest request, OrdinalSqlDataReader reader, ReverseEngineerOption option)
   at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlReverseEngineerImpl.ExecutePopulators(ReliableSqlConnection conn, IList`1 populators, Int32 totalPopulatorsCount, Int32 startIndex, Boolean progressAlreadyUpdated, ReverseEngineerOption option, SqlReverseEngineerRequest request)
   at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlReverseEngineerImpl.ExecutePopulatorsInPass(SqlReverseEngineerConnectionContext context, ReverseEngineerOption option, SqlReverseEngineerRequest request, Int32 totalCount, Tuple`2[] populatorsArray)
   at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlReverseEngineerImpl.PopulateBatch(SqlReverseEngineerConnectionContext context, SqlSchemaModel model, ReverseEngineerOption option, ErrorManager errorManager, SqlReverseEngineerRequest request, SqlImportScope importScope)
   at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlReverseEngineer.PopulateAll(SqlReverseEngineerConnectionContext context, ReverseEngineerOption option, ErrorManager errorManager, Boolean filterManagementScopedElements, SqlImportScope importScope, Boolean optimizeForQuery, ModelStorageType modelType)
   at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeploymentEndpointServer.ImportDatabase(SqlReverseEngineerConstructor constructor, DeploymentEngineContext context, ErrorManager errorManager)
   at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeploymentEndpointServer.OnLoad(ErrorManager errors, DeploymentEngineContext context)
   at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeployment.PrepareModels()
   at Microsoft.Data.Tools.Schema.Sql.Deployment.SqlDeployment.InitializePlanGeneratator()
   at Microsoft.SqlServer.Dac.DacServices.<>c__DisplayClass21.<CreateDeploymentArtifactGenerationOperation>b__1f(Object operation, CancellationToken token)
   at Microsoft.SqlServer.Dac.Operation.Microsoft.SqlServer.Dac.IOperation.Run(OperationContext context)
   at Microsoft.SqlServer.Dac.ReportMessageOperation.Microsoft.SqlServer.Dac.IOperation.Run(OperationContext context)
   at Microsoft.SqlServer.Dac.OperationExtension.Execute(IOperation operation, DacLoggingContext loggingContext, CancellationToken cancellationToken)
   at Microsoft.SqlServer.Dac.DacServices.GenerateDeployScript(DacPackage package, String targetDatabaseName, DacDeployOptions options, Nullable`1 cancellationToken)
   at Microsoft.Data.Tools.Schema.CommandLineTool.DacServiceUtil.<>c__DisplayClasse.<DoDeployAction>b__4(DacServices service)
   at Microsoft.Data.Tools.Schema.CommandLineTool.DacServiceUtil.ExecuteDeployOperation(String connectionString, String filePath, MessageWrapper messageWrapper, Boolean sourceIsPackage, Boolean targetIsPackage, Func`1 generateScriptFromPackage, Func`2 generateScriptFromDatabase)
   at Microsoft.Data.Tools.Schema.CommandLineTool.DacServiceUtil.DoDeployAction(DeployArguments parsedArgs, Action`1 writeError, Action`2 writeMessage, Action`1 writeWarning)
   at Microsoft.Data.Tools.Schema.CommandLineTool.Program.DoDeployActions(CommandLineArguments parsedArgs)
   at Microsoft.Data.Tools.Schema.CommandLineTool.Program.Run(String[] args)
   at Microsoft.Data.Tools.Schema.CommandLineTool.Program.Main(String[] args)

Below is the command I run:
SET vardeploy2=/Action:Script
set varBlockOnDriftParameter=/p:BlockWhenDriftDetected=False

"SSDTBinaries\SqlPackage.exe" %vardeploy2% %varBlockOnDriftParameter% /SourceFile:"dacpacs\DBName.dacpac" /Profile:"Profiles\%1.DBName.Publish.xml" >> Log.txt 2>>&1

I deploy to a SQL Server 2008 R2. The SqlPackage.exe version is 11.0.2820.0.
The issue is intermittent, which suggests it's not related to the DACPAC being deployed or the destination database's schema. My best guess is that something about the state of the database is causing the problem.
Still, I haven't been able to identify anything unusual at the time of the failures.
When recreating the issue locally, using schema locks results in a different error message.
Has anyone know of a solution?

A: Upgrade to a more resent SQL Server Data Tools.


text:
Q: Apache - Redirect /folder to /folder/index.php using .htaccess when somebody visits
http://127.0.0.1/something
I want to redirect him to
http://127.0.0.1/something/index.php
using .htaccess.

*

*How can I do that?

*Is it possible to do that without showing the user that they got redirected, like YouTube does (YouTube.com/user/channel/videos/)

Thanks in advance!

A: I finally found out how to do it.
Warning: I have no experience with mod_rewrite, so this may not be the best solution. It works for me though.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUESTFILENAME} !-f
RewriteRule ^(.*)/$ /$1/index.php [L]
</IfModule>


text:
Q: Programatically view the number of PowerBI licences I've tried searching for either a REST Api or powershell cmdlet that will tell me the number of powerbi licences we have.
I know I can view this in the Azure Portal or in the Microsoft 365 Admin centre but I want to be able to programatically get the data.

A: Rui Romano's PBI Monitor gathers this data and a whole lot more.  So you can implement that, or refer to how it gets this data from the Microsoft Graph in Fetch Graph.ps1.


text:
Q: How to get a specific value using regex I need to get only the numbers in the brackets like this, having the following string:
itsonlyaexample[0:4:2]test
I need to extract only 0 , 4 , 2
OR
itsonlyaexample[0]test
I need to extract only 0
How to do this with C#?
I've tried this, but not get only the numbers in brackets:
(\[[0-9]{1}\]|\[[0-9]{1}:[0-9]{1}\])

A: var str = "itsonlyaexample[0:4:2]test";
var result = str
    .Split('[')[1]
    .Split(']')[0]
    .Split(':')
    .ToList();

or
var takeBrackets = str
    .SkipWhile(x => x != '[')
    .Skip(1)
    .TakeWhile(x => x != ']');

var result = string.Concat(takeBrackets).Split(':');

A: You can use this kind of pattern with a global research:
@"(?:\G(?!\A):|\[)([0-9]+)(?=:|(]))"

demo
The pattern use the \G anchor that matches the position after the previous match result. So with this anchor, you can find consecutive elements in a string.
The lookahead with a capture group inside at the end is only here to check if the closing square bracket is reached. (if the second capture group contains ], it's good).
The main interest of this approach is that it can deal with an undetermined number of items. An other advantage with the final lookahead is that you can check the format by testing the existence of the second capture group.
Note: if you are looking for these number in a large amount of datas, you can try to improve your pattern with the first character discrimination technic  by adding a lookahead at the begining to skip all the character until the opening square bracket (or a semicolon):
@"(?=[\[:])(?:\G(?!\A):|\[)([0-9]+)(?=:|(]))"

This will avoid to test the two branch of the alternation for each characters before a possible opening square bracket.
pattern details:
(?:             # the two possible entry points:
    \G(?!\A):      # after a previous match, so followed by a semicolon
  |               # OR
    \[             # an opening square bracket
)
([0-9]+)        # capture the number
(?=             # lookahead to test if you have reached the end
    :
  |
    (])
)

This way can be used in several languages like .net, perl, java, php, ruby...
an other approach for .net
But you can use a .net particularity that allows to store the different results of a repeated capturing group:
string input = @"itsonlyaexample[0:4:2]test";
string pattern = @"\[(?:([0-9]+):?)+]";

Match match = Regex.Match(input, pattern);
if (match.Success) {
   foreach (Capture capture in match.Groups[1].Captures) {
       Console.WriteLine(capture.Value);
   }
}

A: If the input contains balanced parenthesis then you could use a positive lookahead assertion to match all the numbers which are inside the parenthesis.
@"\b\d\b(?=[^\[\]]*\])"

OR
@"\b\d+\b(?=[^\[\]]*\])"

The above regex matches the number only if it's followed by any character but not of [ or ] zero or more times and after that there must be a closing ] parenthesis. (?=[^\[\]]*\]) is a positive lookahead assertion which won't consume any characters but it's the one which decides where the match to be occur.
DEMO
Code:
String input = "itsonlyaexample[0:4:2]test\nitsonlyaexample[0]test";
Regex rgx = new Regex(@"\b\d\b(?=[^\[\]]*\])");
foreach (Match m in rgx.Matches(input))
{
Console.WriteLine(m.Groups[0].Value);
}

IDEONE
Explanation:
\b                       the boundary between a word char (\w) and
                         something that is not a word char
\d                       digits (0-9)
\b                       the boundary between a word char (\w) and
                         something that is not a word char
(?=                      look ahead to see if there is:
  [^\[\]]*                 any character except: '\[', '\]' (0 or
                           more times)
  \]                       ']'
)                        end of look-ahead

Update:
(?:\[|(?<!^)\G)\D*(\d+)\b(?=[^\[\]]*\])

Get the numbers within parenthesis from group index 1.
DEMO


text:
Q: Overloaded + operator issue being mixed with friend function in other class #include <iostream>
#include "NumDays.h"
#include "Overtime.h"
#include <math.h>
using namespace std;

NumDays::NumDays(double hourss)
{

    if(hourss > 0)
    {
        hours = hourss;
    }
    else
    {
        cout << endl << "Invalid number given.";
        cout << endl << "Hours set to 0." << endl;
        hours = 0.00;
    }

}

NumDays operator + (const NumDays& right)
{
    NumDays temp;

    temp.hours = this->hours + right.hours;
    return temp;
}

#ifndef NUMDAYS_H
#define NUMDAYS_H
#include "Overtime.h"

class Overtime;

class NumDays
{
    friend class Overtime;

    private:
        //double hours = 0.00;
        int days = 0;
        friend void setHoursOT(NumDays&, Overtime&);

    public:
        double hours = 0.00;
        NumDays();
        NumDays(double hourss);
        void getTime();
        double getHours() {return hours;}
        void setHours(double);

        //Overloaded operators
        NumDays operator + (const NumDays&);
        NumDays operator - (const NumDays&);
};

#endif

#ifndef OVERTIME_H
#define OVERTIME_H
#include "NumDays.h"

class NumDays;

class Overtime
{

    private:
        double hours2 = 0.00;
        friend void setHours(NumDays&, Overtime&);

    public:
        Overtime(double hourz);

};
#endif

Every single time I compile it won't let me finish.  I need to have an overloaded operator but I've had the same problem with trying it on the + operator the - operator and a few others.  It will pop up on line 50 of the implementation file where it says "temp1 = this.hours + rhs.hours;" and say that something is wrong every time.  Also it will sometimes pop up on other variations of doing this saying that a either hours2 in the Overtime piece is private or that hours in the NumDays class is private and won't let me do anything past that.  I have googled since 6 hours ago and found multiple things that ultimately got me nowhere.  The most common solution I had found included  something along the lines of NumDays NumDays::operator+ (const NumDays& lhs, const NumDays& rhs) and adding them that way, but even when I do that it provides me the same error on line 50.  I've tried this->, this. *this. *this-> etc.  No dice.
 I've also tried doing it without the Overtime.h/Overtime.cpp and nothing related to that file in there and it ends up saying returned 1 exit status.  Everything works but the overloaded functions and I just can't find where I'm messing up.

A: thisis a pointer, not a reference, so you should write temp1 = this->hours + rhs.hours; instead of temp1 = this.hours + rhs.hours;
That's most likely the error you got at "line 50" as you report.
Moreover:

*

*your operator- is declared as internal but implemented as external.

*your operator- implementation makes no sense. double has no hours attribute...

I recommend that you first work on operator+, make it work and later implemente operator-. Looks like you wrote many code before you first tried to compile, that's a not a good strategy for beginners, compile every time you add a new function, then it will be easier for you to spot out where errors reported by the compiler come from.
Correct implementation will be:
NumDays NumDays::operator+(const NumDays& right)
{
    NumDays temp;
    temp.hours = this->hours + right.hours;
    return temp;
}

or
NumDays NumDays::operator+(const NumDays& right)
{
    double temp;
    temp = this->hours + right.hours;
    return NumDays(temp);
}


text:
Q: How to log in to Tomcat? I installed Tomcat on VPS with Ubuntu 16.04, everything works, but I can not log in. At the moment in the file tomcat-users.xml these are the settings:
<tomcat-users xmlns="http://tomcat.apache.org/xml"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd" version="1.0">

<role rolename="tomcat"/>
  <role rolename="role1"/>
  <role rolename="manager-gui"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
  <user username="manager" password="manager" roles="manager-gui"/>
 </tomcat-users>

I use manager, but I can not enter. Tell me what could be the problem? In the files manager and host-manager everything is configured, otherwise there would be another error. Location of tomcat-users: /opt/tomcat/conf/tomcat-users.xml
Contents of tomcat.service:
[Unit]
Description=Apache Tomcat Web Application Container
After=network.target

[Service]
Type=forking

Environment=JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre
Environment=CATALINA_PID=/opt/tomcat/temp/tomcat.pid
Environment=CATALINA_HOME=/opt/tomcat
Environment=CATALINA_BASE=/opt/tomcat
Environment='CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC'
Environment='JAVA_OPTS=-Djava.awt.headless=true -Djava.security.egd=file:/dev/./urandom'

ExecStart=/opt/tomcat/bin/startup.sh
ExecStop=/opt/tomcat/bin/shutdown.sh

User=tomcat
Group=tomcat
UMask=0007
RestartSec=10
Restart=always

[Install]
WantedBy=multi-user.target


text:
Q: Where can I start learning how to style the HTML5 Video and Audio elements? How would I style the HTML5 Audio and Video and how do I use  the API?

A: http://videojs.com - makes it easy to style up the HTML5 video player using only CSS. I've worked with it in the past and it's really easy to get started with.
http://dev.opera.com/articles/view/everything-you-need-to-know-about-html5-video-and-audio/  - This article from Opera goes into great detail about the whole spec, encoding, etc and has a really in-depth article on creating your own controls by adding Javascript listeners. Not for the novice, but adds a great amount of control and flexibility (search for "roll my own controls", it's about halfway down the page).


text:
Q: printing operation with the ternary I often use the following if block (no else/elseif clauses;just for a specific check)
if(value==10){system.out.print("true");}

So I tried using it with the ternary:
(a==1)?System.out.println("true");

but it is not working. Mainly, I wanted to know that does ternary operator can act like a single if? (and although I haven't pondered over it, but can it work like an if-else_if-else clause?)

A: What you are trying to achieve isn't possible. If you must use a ternary, though, try this
String a = (value==10) ? "Yes" : "No";
System.out.println(a);

Otherwise you can also do this,
System.out.println((value==10)?"Yes":"No");

A: The ternary operator is just shorthand for if-else, but it MUST return something. You need to use the format
something = (x)?(if x==true, return this):(if x==false, return this)
To do what you want, put a ternary inside the print statement. I.E.
System.out.println((a==1)?("true"):(""));

A: First of all as mentioned by Kevin, the ternary operator should have a left hand assignment variable.
Secondly it should be always accompanied with an else operation
Following expressions works.

String s = a==10 ? "true" : "false";
System.out.println(s);

A: Adding to the above-mentionned answers, in case of  aggregating a string to your  expression you can use  the  below code snippet:
System.out.println("any text you want"+ (value == 10)?"value is greater than 10":"value is lower than 10");


text:
Q: gradle dsl ndkBuild() not found Error:(8, 0) Gradle DSL method not found: 'ndkBuild()'
Possible causes:

The project 'OCR4' may be using a version of Gradle that does not contain the method.
Open Gradle wrapper file

The build file may be missing a Gradle plugin.
Apply Gradle plugin

I have the above error in my code although I have included all the dependencies. The path to ndk-build is also specified
task ndkBuild(type: Exec) {
        workingDir = file("${android.sdkDirectory}/ndk-bundle")
        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
            commandLine 'C:\\Users\\yogita\\Download\\android-ndk-r10e\\ndk-build.cmd', '-C', file('.').absolutePath,
                    '-j', Runtime.runtime.availableProcessors()
        } else {
            commandLine './ndk-build', '-C', file('.').absolutePath,
                    '-j', Runtime.runtime.availableProcessors()
        }
    }

    tasks.withType(JavaCompile) {
        compileTask -> compileTask.dependsOn ndkBuild
    }

    // cleanup task
    task ndkClean(type: Exec) {
        workingDir = file("${android.sdkDirectory}/ndk-bundle")
        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
            commandLine 'C:\\Users\\yogita\\Download\\android-ndk-r10e\\ndk-build.cmd', '-C', file('.').absolutePath, 'clean'
        } else {
            commandLine './ndk-build', '-C', file('.').absolutePath, 'clean'
        }
    }

    tasks.withType(Delete) {
        cleanTask -> cleanTask.dependsOn ndkClean
    }


text:
Q: Can not create new route after adding Swagger Laravel I've used this documentation https://codefactory.searchmymarket.com/install-swagger-in-laravel/ to create swagger documentation for all APIs in my Laravel project
The documentation works fine for already added APIs, but when I try to add new routes, even if they are Web routes, they are not displayed when I try to access their link using browser/Postman/Swagger , the new APIs are displayed in the Swagger documentation but if I try to access them, they give me error 404 like they never exists
I tried to use the command php artisan route:list to display list of routes in my project, but it does not show me my new routes like they never exists
Any help would be appreciated, thanks

A: The problem is solved, it is only required to clear route cache using
php artisan route:clear


text:
Q: cmake: Multiple builds from the same source subdir possible? I have a subdirectory containing Python language bindings of the project, and I want to build it for several Python version (Python 2  and 3). How can I do that?
I thought to create two bindirs from the same source first:
add_subdirectory(python, python2)
add_subdirectory(python, python3)

[edit] However, they need specific parameters, and so I tried to set them in advance:
set(PYTHON_INCLUDE_PATH /usr/include/python2.7)
[...]
add_subdirectory(python, python2)
set(PYTHON_INCLUDE_PATH /usr/include/python3.6)
[...]
add_subdirectory(python, python3)

However, then Cmake complains about duplicated target names.
How can I solve this? Or is there a better way to run multiple builds from the same source?

A: The CMakeLists.txt file in the python subdir can add multiple targets via add_executable or add_library or (add_custom_target and add_custom_command). Each target added in this manner will need a different target name so it would probably look something like this:
add_libary(my_python2_bindings <list_of_sources>)
add_library(my_python3_bindings <another_list_of_sources>)

The drawback is that both can't use the same name as the target name, which is what the ultimate file name will be based on. If that's a requirement you could use set the target properties for the output name and for where it is created.
 project(my_python_bindings)

 add_libary(my_python2_bindings <list_of_sources>)
 set_target_properties(my_python2_bindings PROPERTIES OUTPUT_NAME "${PROJECT_NAME}")
 set_target_properties(my_python2_bindings PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/python2")

 add_library(my_python3_bindings <another_list_of_sources>)
 set_target_properties(my_python3_bindings PROPERTIES OUTPUT_NAME "${PROJECT_NAME}")
 set_target_properties(my_python3_bindings PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/python3")

Edit: for many python versions do something like this in the CMakeLists.txt in the python subdir you would have a list containing all python versions PYTHON_VERSION_LIST and then
foreach(version ${PYTHON_VERSION_LIST})
  add_library(my_python${version}_bindings <list_of_sources>)
  set_target_properties(my_python${version}_bindings PROPERTIES OUTPUT_NAME "${PROJECT_NAME}")
  set_target_properties(my_python${version}_bindings PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/python3")
endforeach()

But now you need to add an if clause for different source lists for each version. In that case its probably easier to just expand my original example to be 2.7, 3.5, and 3.6 instead of only 2 and 3.
Also, if each version is genuinely different like it sounds like they are, you probably want to think hard about giving them all the same filename.


text:
Q: Must everyone who uses my program see the ugly code next to it? I started working on some beginner projects and games to test my abilities.
I found that all I was doing is simply writing a code and seeing the ugly output next to it (in the interactive window). The code works, but that's not how I want a normal user to interfere with it.
I'm looking for a way to display my python program properly to a user. Is there some sort of interface manipulating that I should learn in order to accomplish that? thanks.

A: It sounds like you're seeking to build a GUI for your programs.
In several of my early projects, I used the built-in Tkinter module to accomplish what you're suggesting. It may not give you the most modern-looking GUI, but it's nice to use due to it being included with Python by default and the abundance of documentation and tutorials.
There are tons of great videos on YT that walk you through step-by-step on everything from pop-up, dialog-box messages, to full on user-input, menu-laden GUIs. Just search "tkinter tutorials".


text:
Q: Disposing Apache FTP object after use I'm trying to delete some files I have temporarily created and uploaded with the apache commons ftp-class.
FTPClient ftp = new FTPClient();
ftp.login(user, password);

/* Some FTP-Operations in between... not really important*/

File uploadFile = new File("tempfile.txt");

/* Filling the file here... */

ftp.storeFile(uploadFile.getName(), new FileInputStream(uploadFile));

/* Some more operations on FTP and Filesystem */

uploadFile.delete();

uploadFile.delete(); returns false. If the line
ftp.storeFile(uploadFile.getName(), new FileInputStream(uploadFile));

is left out, the deletion works perfectly fine.
I have also tried to disconnect before I delete the file:
ftp.logout();
ftp.disconnect();

Still no luck.
However, if I force the garbage collector to run
System.gc();
System.runFinalization();

The file can be deleted after the upload.
The problem now is: I was given to unterstand that you can't really force the garbage collection. You can merely suggest it. So, it's not a save bet.
Is there a way to dispose the ftp-object in any way? It does not have a dispose() oder flush() method or anything.
Or is it really the correct and "professional" way to call the garbage collector and hope for the best?


text:
Q: HTML form returns nothing on Firefox&IE (ok on Chrome) I have this form in my HTML:
<form action="/vcontent?topic={{ topic.name }}" method="post">
  {% if user and user.email in c.users_up %}
    <input type="image" src="icons/thumb-up.png" alt="Up!" name = "vote" value = "up" />
  {% else %}
    <input type="image" src="icons/thumb-up_gray.png" alt="Up!" name = "vote" value = "up" />
  {% endif %}
  {% if user and user.email in c.users_down %}
     <input type="image" src="icons/thumb-down.png" alt="Down!" name = "vote" value = "down" />
  {% else %}
     <input type="image" src="icons/thumb-down_gray.png" alt="Down!" name = "vote" value = "down" />
  {% endif %}
  <input name= "content_key" type="hidden" value="{{ c.key.urlsafe() }}">
</form>

When I try to upvote a content on Chrome, it works fine. When I get the value with:
vote = self.request.get('vote')

I get either "up" or "down", as it's supposed to be.
But when i do the same thing on IE and Firefox i get an empty string as a result.
(The if/else statements in the HTML mean that if the user has not yet voted that specific content the icon shows up gray, otherwise it's black).
I'm working on Google App Engine using Jinja2 as a template engine.

A: Try this. Instead of using an image, use a button:
<style>button {height:32px; width:32px;}</style>

<form action="/vcontent?topic={{ topic.name }}" method="post">
  {% if user and user.email in c.users_up %}
     <button type="submit" style="background: url(icons/thumb-up.png)" title="Up!" name="vote" value="up" />
  {% else %}
     <button type="submit" style="background: url(icons/thumb-up_gray.png)" title="Up!" name="vote" value="up" />
  {% endif %}
  {% if user and user.email in c.users_down %}
     <button type="submit" style="background: url(icons/thumb-down.png)" title="Down!" name="vote" value="down" />
  {% else %}
     <button type="submit" style="background: url(icons/thumb-down_gray.png)" title="Down!" name="vote" value="down" />
  {% endif %}
  <input name= "content_key" type="hidden" value="{{ c.key.urlsafe() }}">
</form>

A: Ok I think I worked it out, I'm posting my solution for whoever might want to do this, that's the code:
<form action="/vcontent?topic={{ topic.name }}" method="post">
  {% if user and user.email in c.users_up %}
    <input type="image" src="icons/thumb-up.png" alt="Up!" name = "vote" value = "up" />
  {% else %}
    <input type="image" src="icons/thumb-up_gray.png" alt="Up!" name = "vote" value = "up" />
  {% endif %}
  <input type="hidden" name = "vote" value = "up"/>
  <input name= "content_key" type="hidden" value="{{ c.key.urlsafe() }}">
</form>
<form action="/vcontent?topic={{ topic.name }}" method="post">
  {% if user and user.email in c.users_down %}
     <input type="image" src="icons/thumb-down.png" alt="Down!" name = "vote" value = "down" />
  {% else %}
     <input type="image" src="icons/thumb-down_gray.png" alt="Down!" name = "vote" value = "down" />
  {% endif %}
  <input type="hidden" name = "vote" value = "down"/>
  <input name= "content_key" type="hidden" value="{{ c.key.urlsafe() }}">
</form>

I basically doubled the code where the first part manages the upvote, and the second manages the downvote. When I click on an icon, the vote value is returned as hidden.
I think it's inevitable to double the code, otherwise you can't set a value for the hidden value according to the icon pressed.


text:
Q: Super POM Manifest Entries not being used We have a corporate wide super-pom that we use. It sets up all of the mvn site reports, making sure that all of the users are using Findbugs, PMD, etc.
One of the things we want to do is add entered to our MANIFEST.MF file. The entries help us pin down a particular jar to a particular Jenkins build and Subversion revision. The manifest looks like this:
Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Created-By: Apache Maven
Built-By: david
Build-Jdk: 1.7.0_55

Name: Build-Information
Project-Name: tc-jsonp-filter-trunk
SVN-Revision: 23928
Build-Number: 23

Name: Module-Information
Group-ID: com.travelclick
Version: 5.1
Artifact-ID: tc-jsonp-filter

If I add the following to the local pom.xml, everything works fine:
<build>
    ...
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.1</version>
            <configuration>
                <archive>
                    <manifestSections>
                        <manifestSection>
                            <name>Build-Information</name>
                            <manifestEntries>
                                <Project-Name>${env.JOB_NAME}</Project-Name>
                                <Build-Number>${env.BUILD_NUMBER}</Build-Number>
                                <SVN-Revision>${env.SVN_REVISION}</SVN-Revision>
                            </manifestEntries>
                        </manifestSection>
                        <manifestSection>
                            <name>Module-Information</name>
                            <manifestEntries>
                                <Group-ID>${project.groupId}</Group-ID>
                                <Artifact-ID>${project.artifactId}</Artifact-ID>
                                <Version>${project.version}</Version>
                            </manifestEntries>
                        </manifestSection>
                    </manifestSections>
                </archive>
            </configuration>
        </plugin>
    </plugins>
    ....
</build>

However, if I add this to my super-pom, the MANIFEST.MF file does not contain this information.
I know the super-pom is being downloaded (I can see that), and I know that other areas are working because it does JaCoCo test coverage, and that's only found in the super-pom.

A: Found the issue:
My first attempt was using another plugin: org.apache.felix#maven-bundle-plugin. This wasn't working, so I tried the org.apache.maven.plugins#maven-jar-plugin archive configuration. This worked locally.
I then replaced my super-pom project with this change in my Maven repo, then deleted the $HOME/.m2/repository/.../super-pom.xml from my machine and tried it. It didn't work.
What I didn't realized is that I stored that super-pom in my plugins repository and not my release repository. Thus, it downloaded the older and incorrect super_pom.
Putting the super_pom in the correct directory solved the issue.


text:
Q: Parametro URL Route PHP SLim v3 estoy tratando de obtener via url(GET) un valor para poder usarlo luego:
la url seria asi http://misitio.com/blog/post donde post seria el parametro de URL
index.php

 require "core/model/config.php";
 require"core/model/routes.php";

 // Run app
 $app->run();

core/model/config.php
 <?php
 define("BASE_URL","http://" . $_SERVER['SERVER_NAME'] ."/");

 require"vendor/autoload.php";

 $container['notFoundHandler'] = function ($c) {
 return function ($request, $response) use ($c) {
 return $c['view']->render($response->withStatus(404), '404.html');
 };
 };

 // Create app
 $app = new \Slim\App($container);

 // Get container
 $container = $app->getContainer();

 // Register PHP render component on container
 $container['PHPview'] = function ($container) {
 return new \Slim\Views\PhpRenderer('core/view', [
    'cache' => false
 ]);
 };

 // Register component on container
 $container['view'] = function ($container) {
 $view = new \Slim\Views\Twig('core/view', [
    'cache' => false
 ]);
 //Override the default Not Found Handler

 // Instantiate and add Slim specific extension
 $basePath = rtrim(str_ireplace('index.php', '',
 $container->get('request')->getUri()->getBasePath()), '/');
 $view->addExtension(new Slim\Views
 \TwigExtension($container->get('router'), $basePath));
 $view->getEnvironment()->addGlobal("current_path",
 $container["request"]->getUri()->getPath());
 $view->getEnvironment()->addGlobal("Domain", "http://"
 .$_SERVER["SERVER_NAME"] ."/");

 return $view;
 };

 require_once"core/model/functions.php";

core/model/functions.php

 $blog = new Twig_SimpleFunction('Blog', function ($url) {
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_URL, 'http://blog.rbb-autoradio.com.ar
 /' . $url . '/?json=1');
 $result = curl_exec($ch);
 curl_close($ch);
 $obj = json_decode($result);
 $cadena = $obj->post->content;
 $start  = strpos($cadena,"");
 $end  = strrpos($cadena,"");
 $contenido = substr_replace($cadena,'',$start,$end);
 $html = "
" . $obj->post->title . "
";
 $html.= $contenido;

 return $html;
  });
 $container->get('view')->getEnvironment()->addFunction($blog);

core/model/routes.php
 <?php
 $app->get('/blog/{post}', function ($request, $response, $args) {
 return $this->view->render($response, 'post.html', ['post' =>
 $args['post']]);
 });

post.html
 {% extends "main.layout.html" %}

 {% block head%}
 <link rel="amphtml" href="">
 {{ parent() }}
 {% endblock %}

 {% block title %}

 {% endblock %}

 {% block desc %}
 {% endblock %}

 {% block keysWords %}
 {% endblock %}

 {% block sideNav%}
 {% endblock %}

 {% block container %}

 {% autoescape false %}
 {{ Blog(post) }}
 {% endautoescape %}

 {% endblock %}

Editado: asi me funciona bien, lo que no puedo hacer es con una vista PHP


text:
Q: Squiggly arrow in xypic giving error in LyX I am trying to compile \xymatrix{A\ar@{\sim>}[r] & B} in LyX and I get the following error message:

How can I fix this? The code compiles in ERT, just not in the native xypic mathmode.
Here is a link to MWE.lyx

A: The shape input of \xymatrix in \ar@{shape}[direction] does not use mathmode and uses its own interpreter to recognize types of arrow shapes. The input is independent of the environment, and works both in textmode and mathmode:
\documentclass{article}
\usepackage[all,cmtip]{xy} % include cmtip or your arrow will be ugly

\begin{document}
\xymatrix{A\ar@{~>}[r] & B}

\begin{equation}
\xymatrix{A\ar@{~>}[r] & B}
\end{equation}
\end{document}

A: Your problem is that the xypic package requires some special characters (in particular the tilde ~), which is automatically rewritten by the math editor in LyX. It is somewhat cumbersome to make LyX insert a true tilde into the source code.
But this is a case where the LyX "Macro" feature comes in handy.

*

*Go to Insert -> Math -> Macro.

*Write \sqarrow instead of \newmacroname.

*Then you copy the text \ar@{~>}[r], and paste it directly into the TeX field of the LyX macro.

*Finally, in the LyX field of the macro, enter some symbol that resemble the output symbol, such as ~~> or \rightarrow.

You have now created a macro \sqarrow for the squiggly arrow, which you can use directly in the LyX math editor.
For the record, LyX rewrites this macro as \global\long\def\sqarrow{\ar@{~>}[r]} in the LaTeX source code.


text:
Q: How to generate the first day of the week, the last day of the week and week number between two dates in Oracle I would like to insert in table :

*

*the first day of the week starting from Monday.

*the last day of the week as Sunday.

*the WEEK number => (1-52 or 1-53) based on the ISO standard.

First i tried to select first day, the last day and week number for specific date and it's works :
WITH ranges AS
(
SELECT to_date('29-10-2012', 'dd-MM-yyyy') AS DATE_TEST FROM DUAL
)
SELECT DATE_TEST "DATE",
TO_CHAR( NEXT_DAY( TRUNC(DATE_TEST) , 'SUNDAY' )) "WEEK END DATE",
TO_CHAR(TO_DATE(DATE_TEST,'DD-MON-YYYY'),'WW')+1 "WEEK NUMBER"
FROM ranges ;

But now i would like to display this data between two dates, but i get result only for the start_date.  someone can help please.
after, when all good i will insert all in the table.
Thanks
WITH ranges AS(
   select to_date('29-OCT-2012', 'dd-MM-yyyy') START_DATE,
       to_date('31-DEC-2016', 'dd-MM-yyyy') END_DATE
from  dual
)
SELECT START_DATE "DATE",
TO_CHAR( NEXT_DAY( TRUNC(START_DATE) , 'SUNDAY' )) "WEEK END DATE",
TO_CHAR(TO_DATE(START_DATE,'DD-MON-YYYY'),'WW')+1 "WEEK NUMBER"
FROM ranges ;

A: Looks like you're looking for a calendar.
Based on your RANGES CTE, there's another - calendar which utilizes hierarchical query to create all dates between start_date and end_date. Once you have all dates, extract values you're interested in.
SQL> with
  2  ranges as
  3    (select to_date('29-OCT-2012', 'dd-MM-yyyy') start_date,
  4            to_date('31-DEC-2016', 'dd-MM-yyyy') end_date
  5     from dual
  6    ),
  7  calendar as
  8    (select start_date + level - 1 as datum
  9     from ranges
 10     connect by level <= end_date - start_date + 1
 11    )
 12  select
 13    min(datum) start_date,
 14    min(next_day(datum, 'sunday')) week_end_date,
 15    to_char(datum, 'ww') week_number
 16  from calendar
 17  group by to_char(datum, 'yyyy'), to_char(datum, 'ww')
 18  order by 1;

START_DATE WEEK_END_D WE
---------- ---------- --
29-10-2012 04-11-2012 44
04-11-2012 11-11-2012 45
11-11-2012 18-11-2012 46
18-11-2012 25-11-2012 47
25-11-2012 02-12-2012 48
<snip>
09-12-2016 11-12-2016 50
16-12-2016 18-12-2016 51
23-12-2016 25-12-2016 52
30-12-2016 01-01-2017 53

222 rows selected.

SQL>

A: Format WW returns Week of year (1-53) where week 1 starts on the first day of the year and continues to the seventh day of the year, see Datetime Format Elements
In order to get the week number according to ISO-8601 standard use format IW. I would suggest like this:
WITH ranges AS(
    SELECT
        DATE '2012-10-29' START_DATE,
        DATE '2016-12-31' END_DATE
    FROM dual
)
SELECT
    START_DATE, END_DATE,
    TRUNC(START_DATE + 7*(LEVEL-1), 'IW') AS Week_Start_Date,
    TRUNC(START_DATE + 7*(LEVEL-1), 'IW') + 6 AS Week_End_Date,
    TO_CHAR(TRUNC(START_DATE + 7*(LEVEL-1)), 'IYYY-"W"IW') WEEK_NUMBER
FROM ranges
CONNECT BY START_DATE + 7*(LEVEL-1) <= END_DATE;

A: Here is a way to make the common table expression return a range of dates.
with ranges (dt) as (
   select to_date('29-OCT-2012', 'dd-MM-yyyy') as dt
   from dual

   union all
   select ranges.dt+1
   from ranges
   where ranges.dt < to_date('31-DEC-2016', 'dd-MM-yyyy')
)

Then you can use that to calculate the other values.
SELECT dt "DATE"
, TO_CHAR(NEXT_DAY(TRUNC(dt), 'SUNDAY')) "WEEK END DATE"
, TO_CHAR(TO_DATE(dt,'DD-MON-YYYY'),'WW') + 1 "WEEK NUMBER"
, cast(TO_CHAR(dt, 'WW') as int) +
  case when cast(TO_CHAR(dt, 'D') as int) < cast(TO_CHAR(trunc(dt, 'year'), 'D') as int) then 1 else 0 end  WeekNumberInYear

FROM ranges ;

If you want to have all of your date calculations done at once, check out an example here:  https://dbfiddle.uk/?rdbms=oracle_18&fiddle=35e407af3b5bf711bb7ae53b8cf0e608

A: How are you?
to help, I tried to do some research, I found these links.
enter link description here
enter link description here
I found:
SELECT
ROUND((TRUNC(SYSDATE) - TRUNC(SYSDATE, 'YEAR')) / 7,0) CANTWEEK,
NEXT_DAY(SYSDATE, 'SUNDAY') - 7 FIRSTDAY,
NEXT_DAY(SYSDATE, 'SUNDAY') - 1 LASTDAY
FROM DUAL
and
select
to_char(sysdate - to_char(sysdate, 'd') + 2, 'yyyymmdd') first_day_of_week
, to_char(sysdate - to_char(sysdate, 'd') + 8, 'yyyymmdd') last_day_of_week
from
dual
and
select sysdate AS today,
TRUNC(next_day(sysdate,'MONDAY')-8) as DOMINGO,
TRUNC(next_day(sysdate,'SATURDAY')) as SABADO
from dual
I don't have oracle here so I couldn't test it well but it should solve what you need, anything let me know :)


text:
Q: Failed to load resource - bootstrap error 403 Everything appears as normal, however when I inspect element in my checkout page I get the following errors showing up in the console
https://maxcdn.bootstrapcdn.com/examples/navbar-static-top/navbar-static-top.css Failed to load resource: the server responded with a status of 403 (Forbidden)
https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/ie10-viewport-bug-workaround.js Failed to load resource: the server responded with a status of 403 (Forbidden)
My site has been set up for https, and I have tried the bootstrap links with and without the https: in the link.  I am new to this so it could be something silly, I would be grateful for any help.

A: Here are the correct links, hope it helps
http://getbootstrap.com/examples/navbar-static-top/navbar-static-top.css
http://getbootstrap.com/assets/js/ie10-viewport-bug-workaround.js

A: If I were you, I would donwload the files and I would upload it to my site. If the CDN has problems... your web will have it too...
I advise you to do it.
In addition, when I try to access to the links, I can't see the files too... You should use the links which @Lightwalker posted
I hope my answer will help you!


text:
Q: Statistics problem. How do I draw a sample size x from a population/matrix where N(1,3) mean = 1 and sd = 3 in R Statistics problem.  How do I draw a sample size x from a population/matrix where N(1,3) mean = 1 and sd = 3 in R can i use a filter or sample function?

A: The function you're looking for is called rnorm. In general, when looking for a function in R it helps to just search for the name of the distribution (so in this case, "R normal distribution").
Inside R, you can also use the command ??normal to search for help pages containing the term "normal". This will also contain the desired function but unfortunately it will be harder to find since the results are ordered alphabetically rather than by relevance.


text:
Q: How do I get all the rows from a mysql table, send json, iterate through array and display? I have this PHP code:
$result = mysql_query("SELECT banner FROM banners ") or die(mysql_error());
 $somethings = array();
while ($row = mysql_fetch_assoc($result)) {
    $somethings[] = $row;
}

  print json_encode($somethings);   exit;

which gives me this json response:
[{"name":"john"},{"name":"Peter"}]

and I have this JavaScript:
$(document).ready(function(){
function getdata(data) {
$.each($data, function(key, value) {jQuery('#boxes').append('==='+value); });
}
$.getJSON('editx2.php',{ 'case':9,'readonly': 'yes' }, getdata);
});

which dispays this:
[object Object],[object Object][object Object],[object Object]

I have two rows in the database. When the array is in this format:
{"name":"john","name":"peter"}

it works, but this fails:
[{"name":"john"},{"name":"Peter"}]

A: Instead of
jQuery('#boxes').append('==='+value);

use
jQuery('#boxes').append('==='+value.name);

which will print the name.


text:
Q: ASyncTask only on First open I have an Activity that extends FragmentActivity
In first Fragment (HomePage that extends Fragment) I need to load data from web, so I use ASyncTask.
Now the problem: I don't need to check and load data everytime Fragment is created/attach but just in first instance, then I want to save state and load again data only on next onCreate Activity (That I hope it means next open of app, but we know that it doesn't)
So.. Where Should I put my ASyntTask.execute()? OnCreate inside Fragment? OnCreateView inside Fragment? On Attach inside Fragment? or OnCreate of Activity, store data in Bundle and then pass them to my Fragment?
Or, maybe other solutions to this?
EDIT
Resolved!
So on my OnCreate [Fragment] I added a
 if(savedInstanceState != null) {

        data = (data[]) savedInstanceState.getParcelableArray("key");
    }
    else
        new LoadMostBooks().execute();

But I didn't setInstanceRetain(True) cause I need to pass always through onCreate();
Then on onCreateView() Method I added also a check
if(savedInstanceState != null) {
        myCustomArrayAdapter = new CustomArrayArrayAdapter(mContext,data);
        myListView.setAdapter(myCustomArrayAdapter);
    }

I also needed to make sure about save instance with a
 @Override
public void onSaveInstanceState( Bundle outState ) {
    super.onSaveInstanceState( outState );
    outState.putParcelableArray("key",data);
}

At the end I had to make data (Custom Object) implemented Parcelable to make sure everythign works!

A: You can just retain your data onSaveInstanceState then check in onCreate if its there or not.
private Data[] mData;

@Override
public void onCreate( Bundle savedInstanceState ) {

    super.onCreate( savedInstanceState );
    setRetainInstance( true );
    if ( savedInstanceState != null && savedInstanceState.containsKey( "key" ) ) {

        mData = (Data[]) savedInstanceState.getParcelableArray( "key" );
    }
    else {
        new myAsync() {

            @Override
            public void onPostExecute( Data[] data ) {

                mData = data;
            }
        }.execute();
    }
}

@Override
public void onSaveInstanceState( Bundle outState ) {

    super.onSaveInstanceState( outState );
    if ( mData != null ) {

        outState.putParcelableArray( "key", mData );
    }
}

A: What you can do is create a static field in your first activity.
public static int counter = 0;
and in your onCreate fragment you do:
if (counter == 0){
//execute Async

counter++;
}

and it will never executed again (counter will never be 0 again) until you destroy your activity.

A: only thing you need to do is : check whenever you data is loaded or not, if loaded then no need to reload ,if not load data then.
make your Fragment as singleInstance by provide private constructor :
  public static YourFragment mInstance;
         private YourFrament(){//empty constructor
          super();
         }
         public static YourFragment getInstance(){
          if(mInstance==null){
           mInstance = new YourFrament();
         }
          return mInstance;
         }

declare your data holder
private List<DataType> mDatas;

assume that you call your AsyncTask in your onActivityCreated :
 check your data first:
if(mDatas==null||mData.size<=0){
//here you need to get data by call your AsyncTask
yourAsyncTask = new AsyncTask...
yourAsyncTask.execute()
}else{
//here you have the data already, no need to load
}

and on your AsyncTask's onPostExecute() method :
 mDatas = new ArrayList<DataType>();
 mDatas=....// init your data value

A: You can make activity class provide data (lazily):
private Object data;

public static interface Callback{
    public void onData(Object data);
}

public void getData(final Callback c){

  if(data != null){
    c.onData(data);
  }else {

      AsyncTask<Void,Void,Object> task = new AsyncTask<Void, Void, Object>() {
          @Override
          protected Object doInBackground(Void... pVoids) {
              //--load data--
              return new Object();
          }

          @Override
          protected void onPostExecute(Object result) {
              super.onPostExecute(result);
              data = result;
              c.onData(data);
          }
      }.execute();

  }

}

And ask for data in fragment class:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if(getActivity() instanceof MyActivity){
        ((MyActivity) getActivity()).getData(new MyActivity.Callback() {
            @Override
            public void onData(Object data) {
                //--do something with the data in fragment
            }
        });
    }
}


text:
Q: Timezone selection in tapestry date picker as per clients Timezone We are using Tapestry at our Presentation Tier.
Now we have following situation :
Our application is going to be used by different users from different countries, with different timezones.
In our application we are using Tapestry 5.2.x datepicker,
so how can we allow date selection as per user's Timezone?

A: https://issues.apache.org/jira/browse/TAP5-841
the patch as per my comment does work. ie working with a string (2012-01-01) instead of a number (millis since epoch).


text:
Q: Button links to different links depending on what user enters I'm creating a form where each combo box is populated depending on what was entered in the last one. I have a price estimate appear after all choices are selected. However I need a submit button which depending on what 3 choices were made takes you to a different link. Any help is appreciated, thanks in advance.
My code:


text:
Q: Issues drawing multiple NVD3.js charts on dynamically-created div I'm supposed to generate a report based on a JSON document with this structure:
tables:
[
  {
    <some descriptors of the dataset>,
    series:
    [
      key: ...,
      values:
        [
          { label: ..., value: ... },
          ...
        ]
    ]
  },
  ...
]

There can be an arbitrary number of tables in the JSON array, with arbitrary series. Of course, each series holds the same set of values with different values. For each table, I have to draw a table with the given data and a multi-bar chart. I chose NVD3.js as my chart library.
Since I'm not very experienced with JavaScript, I decided to play it safe and follow the NVD3.js examples to the letter, and generate the divs and objects I need in the most archaic and stupid way possible. As soon as I feel more comfortable in JS I will implement templates and such. Here's a shortened version of my JavaScript code. I know it's horrible, so please don't judge me.
var report_data = <stupid way of getting data, will use AJAX later>;

var my_div = document.getElementById('show-report');

report_data.tables.forEach(
    function(table)
    {
        var newDiv = document.createElement('div');
        newDiv.id = 'report_' + table.name;

        var newHeader = document.createElement('h1');
        newHeader.textContent = table.name;
        newDiv.appendChild(newHeader);

                    // Generate style element for chart
        var newStyle = document.createElement('style');
        newStyle.textContent = '#' + table.name + '_chart svg {height: 500px;}';
        newDiv.appendChild(newStyle);

                    // Generate
<svg />
 where chart will be placed
        var chartDiv = document.createElement('div');
        chartDiv.id = table.name + '_chart';
        var svgEl = document.createElement('svg');
        chartDiv.appendChild(svgEl);
        newDiv.appendChild(chartDiv);

        // Here I write the table and append it to the main div. Omitted because of intense shame.

        my_div.appendChild(newDiv);

        //Draw chart
        nv.addGraph(
        function()
        {
            var chart = nv.models.multiBarHorizontalChart()
            .x(function(d) { return d.label })
            .y(function(d) { return d.value })
            .margin({top: 30, right: 20, bottom: 50, left: 175})
            .tooltips(true)
            .showControls(true);

            chart.yAxis
            .tickFormat(d3.format(',.2f'));

            d3.select('#'+ table.name +'_chart svg')
            .datum(table.series)
            .transition().duration(250)
            .call(chart);

            nv.utils.windowResize(chart.update);

            return chart;
        }
        );
    }
);

So, the code is bad, but it works... sort of. Here's the thing: it tries to draw each chart and put it in its div, but each chart just shows in plain text with no style. See this Imgur album. If I "hardcode" a div with the name of one of my tables, it draws the chart without a hitch inside it. To me, it looks like the newly-created divs aren't applying the NVD3.js CSS file. I don't even know if that's possible, since I know even less about CSS than JavaScript.
Has anyone tried something like this or does anyone know what could be causing that behavior?

A: I just ran into this issue, and after looking around on GitHub I found the problem.

you cant create SVG elements using document.createElement, you have to use document.createElementNS and specify the xml namespace for SVG, or just use d3´s append method: d3.select(...).append("svg")

My problem was specifically involved jQuery, which resulted in me generating the SVG element using:
var $svg = d3.select($jqElement[0]).append("svg")

For non-jQuery users, regular DOM elements can be passed into d3.select.  In the example, $jqElement[0] is called to get the DOM version of the jQuery object.


text:
Q: Prop-function mock not being called I have a component function like so:
onSomethingDoSomething = async (arg) {
   /* logic */
   const result = await this.props.theFunctionIWantToTest()
   /* more logic */
}

With Jest/Enzyme I'm trying to assert that this.props.theFunctionIWantToTest has been called when onSomethingDoSomething has been called.
By a series of logging statements I can see that theFunctionIWantToTest is, in fact, being invoked during my test and by logging console.log(theFunctionIWantToTest) in my component I can see that the function itself is a mocked function. However,
expect(instance.props.theFunctionIWantToTest).toHaveBeenCalled()

results in a failure:
Expected mock function to have been called

My testing setup is as such:
const props = {
  theFunctionIWantToTest: jest.fn()
}

const wrappedComp = mount(
    <Provider store={store}>
      <MemoryRouter>
        <MyComponent {...props} />
      </MemoryRouter>
    </Provider>)

const instance = wrappedComp.find(MyComponent).getNode()

instance.onSomethingDoSomething()

expect(instance.props.theFunctionIWantToTest).toHaveBeenCalled()

Again, throwing console.logs in onSomethingDoSomething I can see that the function type of my tested function is a mock and I can see mocked results being logged after theFunctionIWantToTest is invoked, but the expectation fails. Why?

A: You need to use the await keyword in your call to instance.onSomethingDoSomething() in your test, since it's an async function.