text:
Q: How access variables within method block? I'm trying to access a method block but I have no idea how to:
__block NSString *username;
PFUser *user = [[self.messageData objectAtIndex:indexPath.row] objectForKey:@"author"];
[user fetchIfNeededInBackgroundWithBlock:^(PFObject *object, NSError *error) {
    username = [object objectForKey:@"username"];
    NSLog(@"%@", username); //returns "bob";
}];
NSLog(@"%@", username); //returns null

How do I access the variable 'username' from this code outside of the block?

A: Actually you are accessing the variable username outside the block. You are getting null because the block runs in another thread and you set the value after the block finish it's execution. So, your last line has been already executed in main thread while the block was running , so it's value was not set when last line was executed.That's why you are getting null.

A: fetchIfNeededInBackgroundWithBlock is an asynchronous method. That's why your last NSLog returns null because this it is performed before username was retrieved. So what you want is probably to call some method inside the block to be sure that it executes after you fetched your user data. Something like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyUserCell *userCell = (MyUserCell *)[tableView dequeueReusableCellWithIdentifier:MyUserCellIdentifier];
    PFUser *user = [[self.messageData objectAtIndex:indexPath.row] objectForKey:@"author"];
    userCell.user = user;
    [user fetchIfNeededInBackgroundWithBlock:^(PFObject *object, NSError *error) {
        if (object == userCell.user && !error) {
            username = [object objectForKey:@"username"];
            cell.textLabel.text = userName;
        }
    }];
}

UPDATE: The answer is updated to for the case when the block is called inside tableView:cellForRowAtIndexPath: method as requested.
NOTE: Here you will probably need a custom cell to store a reference to the current user, because if you are reusing your cells the block callback might be called after the same cell was reused for a different indexPath (so it will have a different user).

A: I would suggest using NSOperationQueue as presented in WWDC. See this article for reference, it think it would be helpful:
https://stavash.wordpress.com/2012/12/14/advanced-issues-asynchronous-uitableviewcell-content-loading-done-right/

A: Below is the example of what I do: try it:
Write this below import statement
typedef double (^add_block)(double,double);

Block - Write this in view did load
__block int bx=5;
[self exampleMethodWithBlockType:^(double a,double b){
    int ax=2;
    //bx=3;
    bx=1000;
    NSLog(@"AX = %d && BX = %d",ax,bx);
    return a+b;
}];

NSLog(@"BX = %d",bx);

Method:
-(void)exampleMethodWithBlockType:(add_block)addFunction {
    NSLog(@"Value using block type = %0.2f",addFunction(12.4,7.8));
}


text:
Q: Как получить данные от API? Создал кнопку на сайте, при нажатии должно в обработчике показать массив
Array (
[Result] => ok
)
в файле payViaPos.php у меня идет подключение к API
<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
define('DATALIFEENGINE', 'dsdd');
require_once '../../engine/classes/mysql.php';
include('../../engine/data/dbconfig.php');
include("../../engine/api.php");
include("../vendor/utils.php");
$api=new api();
switch ($_POST['action']) {
case 'PayViaPOS':
PayViaPOS($config);
break;
default:
header('Location: /');
break;
}
function PayViaPOS($config) {
global $api;
$url = "PayViaPOS/";
$api->post = array(
'ProductOrderId' => $_POST['ProductOrderId'],
'price'=> $_POST['price']
    );
$data = $api->sendrequest($url);
print_r($data);
}
?>

в файле index.php у меня кнопка и скрипт который получает данные
<button type="button" class="button button--prime" id="PayViaPOS">Рассчитать</button>

в файле apik.php данные от api
/* =====================PayViaPOS =========================================== */
$url = "PayViaPOS//";
echo 'PayViaPOS';

$api->post = array(
    'price' => '3',
    'ProductOrderId' => '111111'
);
echo '

';
print_r($api->sendrequest($url));
echo '

';
exit;

при нажатии на кнопку ничего не происходит, с помощью обработчика ошибки не смог даже ошибку вывести, я только изучаю api и php в целом, помогите разобраться в чем проблема

A: не вполне понятно что это должно быть, тем не менее...

*

*ошибка забыли кавычки тут:
ProductOrderId: "<?=$_GET['productOrderId']?>",

*jquery подключить не забыли?

A: Если работаете в хроме, посмотрите следующее:
Ошибки в консоли браузера(вкладка 'Console').
Во вкладке 'Network' проверьте уходит ли что-то на apik.php и что уходит (вкладка 'Headers').Так же посмотрите что отвечает ваше api (вкладка 'Response').
После этого сможете сделать отладку вашего кода.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can my weapons have more than 3 upgrades? The weapon info screen shows 3 slots. They seem to be for the unique upgrades of each gun. Am I limited to only 3 upgrade installations per gun or can I add for example silencer, AP, laser as well as damage?

A: No, you are not limited to three upgrades per gun. The three upgrade slots you see, are actually for attachments and unique upgrades, like silencer, laser sight, armor piercing, scope,  etc.
The damage output, reload speed, ammo capacity and rate of fire upgrades are different from the attachments and unique upgrades. While examining a weapon, you can see how many times to can upgrade an attribute by looking at the green bars next to the specific attribute.

A: Take a look at this in-game image of the 10 mm pistol (taken from Wikia):

The three icons next to the weapon image always represent (in order) the Laser Sight, Silencer and a Specialist upgrade. If a weapon cannot take any of these specific upgrades they will be crossed out and they would be highlighted green if fitted. We can see in this example that the pistol can take all three, but has none yet fitted.
Below these are the weapon's four statistics. The bright orange elements here show the weapon's base performance, then there sometimes dark green bits following these. The number of dark green bits in each line is how many weapon mods of that type the weapon can take, and these become green when fitted. If there are no dark green bits the weapon cannot take any upgrades of that type.
Continuing on from the same example, let's look closer at this pistol's damage:

Base damage is three units, one damage upgrade has been fitted, and the weapon will take another three (for a total of four damage upgrades).
What this means in this example, the 10mm Pistol, can take all of:

*

*Laser Sight

*Silencer

*Special Upgrade (AP Bullets)

*4 × Rate of Fire Upgrade

*4 × Reload Speed Upgrade

*4 × Damage Upgrade

*4 × Ammo Capacity Upgrade

For a maximum total of 19 different upgrades of varying types.


text:
Q: Can't install Ubuntu on new Skylake ultrabook? (Thinkpad Yoga 260) it's my first post to askubuntu, therefore I will try my best.
My problem is, that I bought a Thinkpad Yoga 260 and tried to install Ubuntu on it, but if I start the boot USB key and select the installation of Ubuntu, it get's stuck on a black screen.
I googled a lot and tried to add various flags to run the installation, but it ended always on a black screen. Afterwards I tried to install Mint Cinnamon and I succeeded. Therefore I thought to try out Mint and give it a try, but I discovered that the touchscreen and Wacom Pen doesn't work. After some research I found out that Mint doesn't support touchscreen.
Therefore I'm back to my problem, to install Ubuntu on my Thinkpad Yoga 260. My actual point of knowledge is that the new Skylake cpu's and gpu's are supported by the kernel 4.3 and this kernel is integrated in the 16.04 Alpha. But I don't succeed to install it.
It would be great if somebody could help me or struggles with the same problem.
Greetings,
albflo

A: There is an issue with Skylake processors and Intel pstate drivers in the Linux kernel that hangs the boot process, usually on the message "Intel_pstate: HWP enabled".
If you add "intel_pstate=no_hwp" to the GRUB boot parameters it should work. (Instructions: https://wiki.ubuntu.com/Kernel/KernelBootParameters)
However, this disables the more efficient frequency scaling capability (= longer battery times) in Skylake, so hopefully it will be solved soon.
The issue is being worked on here:
https://bugzilla.kernel.org/show_bug.cgi?id=110941

A: To help other people, which are struggling with an equivalent issue, I will post here my solution.
Thanks to @bain I got to this thread New laptop (Skylake) cannot boot Xubuntu even with boot parameters where an equivalent problem was posted.
There solution was to add some kernel flags to the boot options, therefore I tried it and got into Ubuntu Live USB with a display resolution of 640x480. To get full resolution and the final opportunity to install Ubuntu I deleted nomodeset from my flags and got full resolution. My final kernel flags for the boot option replaced quiet splash --- :
i915.preliminary_hw_support=1 nouveau.blacklist=1 edd=on nolapic pcie_aspm=force tpm_tis.interrupts=0 ---
Now I have installed Ubuntu 15.10 and upgraded to kernel 4.3, but I'm still struggling to get a GRUB menu and to boot finally into Ubuntu.
EDIT:
After various tries I edit a Ubuntu live USB key to start the grub from my Ubuntu and was able to enter my Ubuntu installation. But to set up the UEFI boot menu is still a problem and I will try later to solve it. Now I try to set up my Wifi: I installed the new firmware from Intel and the driver, also I tried to add intel_pstate=no_hwp to the kernel parameters, because it was suggested in a similar thread. But it doesn't solve the problem for me.
I will add later more details of my progress.
EDIT: I tried different kernel parameters for the boot options and now I only need nolapic to be able to boot Ubuntu and i915.preliminary_hw_support=1 to enable the touchscreen and the active pen.
EDIT: I tried to install kernel 4.4, but afterwards Ubuntu showed a fatal error. Therefore I thought it could be worth to try out a daily of 16.04. To install it I needed intel_pstate=no_hwp in the kernel parameters and on 16.04 I had no issues with my wifi. The only remaining problem was that I wasn't able to enable my touchscreen and active pen, but after some days and some updates of Ubuntu it worked perfect.
Now I have no system problems left and can work with my new notebook, my last thing to solve is only to enable grub on the startup.
Thanks everyone for the help!!

A: You could try the kernel command-line addition:
i915.preliminary_hw_support=1

It is my understanding that all is good with kernel 4.4, so once installed upgrade and you should be sweet.
Please let me know if this works, I just ordered a yoga 260 to replace my x201T.
source: http://www.phoronix.com/scan.php?page=news_item&px=intel-skl-prelim-support


text:
Q: Content from TinyMce and Bootstrap I want to use the html Content generated by TinyMCE in a Bootstrap environment, but Bootstrap is overwirting the styles given from the TinyMCE editor.
is there a way to disable all bootstrap classes within a "
" ?

A: I remember having the same issue in the same context. Here is my code
JavaScript

HTML

        <textarea id="myarea" name="myarea"><?php echo(stripslashes(html_entity_decode($myarea))); ?></textarea>

PHP : once the text has been typed, I submit it via PHP and it goes through these functions before being saved in a database.
htmlspecialchars($myarea);
trim($myarea);
addslashes($myarea);

Send some code if you'd like a more customed answer though.


text:
Q: How to apply squeeze theorem to this limit. I'm trying to solve $$\int_0^∞ e^{-x} \cos(x)\,dx$$
It is not hard to find that $$\int e^{-x} \cos(x)=\frac{1}{2}(e^{-x} \sin(x)-e^{-x} \cos(x))+C$$
From all this follows that
$$\lim_{t\to\infty}\int_0^te^{-x} \cos(x) \, dx = \frac{1}{2}\lim_{t\to\infty}(e^{-t} \sin(t) - e^{-t} \cos(t))+\frac{1}{2}$$
Notice that I have simplified already a lot the expression we are taking the limit of.
I have not been able to find this limit; a collegue student told me that I had to use the squeeze theorem, but I do not find how nor where. Any guides on how the theorem can help with this limit?

A: The values of trigonometric functions oscillate between $1$ and $-1$.
Your upper bound is:
$$
\lim_{t \to \infty} \int_{0}^{t} e^{-x}\cos(x)\,dx =
\frac{1}{2} \lim_{t \to \infty}(e^{-t}(1) - e^{-t}(-1)) + \frac{1}{2}.
$$
We don't know what value our trigonometric functions take at infinity but they can't take any larger value clearly. So we set $\cos$ to $-1$ and $\sin$ to $1$ as it will give $\frac{1}{2}(2e^{-t})+\frac{1}{2}$.
And our lower bound is:
$$
\lim_{t \to \infty} \int_{0}^{t} e^{-x}\cos(x)\,dx =
\frac{1}{2} \lim_{t \to \infty}(e^{-t}(-1) - e^{-t}(1)) + \frac{1}{2}.
$$
Which gives us $\frac{1}{2}(-2e^{-t}) + \frac{1}{2}$.
It's clear that $e^{-t}$ goes to zero and so our limit is 'squeezed' to $\frac{1}{2}$ from both sides.

A: It is easiest to compute this integral using the identity $\cos x = \frac12(e^{ix}+e^{-ix})$. From this we have
\begin{align}
\int_0^\infty e^{-x}\cos x\ \mathsf dx &= \frac12\int_0^\infty e^{-x}(e^{ix}+e^{-ix})\ \mathsf dx\\
&= \frac12\int_0^\infty \left((e^{(i-1)x}+e^{-(i+1)x}\right)\ \mathsf dx\\
&=\frac12\left[\frac1{i-1}e^{(i-1)x} - \frac1{i+1}e^{-(i+1)x} \right]_0^\infty\\
&= \frac12\left(\frac1{i+1} - \frac1{i-1} \right)\\
&=\frac12\left(\frac1{1+i} + \frac1{1-i}\right)\\
&=\frac12\left(\frac{1-i + 1 + i}{(1+i)(1-i)} \right)\\
&= \frac12\left(\frac2{1-i^2} \right)\\
&= \frac12.
\end{align}

A: $$\because\sin x-\cos x=\sqrt 2(\cos\frac{\pi}{4}\sin x-\sin\frac{\pi}{4}\cos x)=\sqrt 2\sin (x-\frac{\pi}{4})$$
$$\therefore\lim_{t\rightarrow +\infty}|e^{-t}\sin t-e^{-t}\cos t|= \lim_{t\rightarrow +\infty}|\sqrt 2e^{-t}\sin (t-\frac{\pi}{4})|\leqslant \lim_{t\rightarrow +\infty}|\sqrt 2e^{-t}|=0$$
$$\therefore\lim_{t\rightarrow +\infty}(e^{-t}\sin t-e^{-t}\cos t)=0$$
$$\therefore\frac{1}{2}\lim_{t\rightarrow +\infty}(e^{-t}\sin t-e^{-t}\cos t)+\frac{1}{2}=\frac{1}{2}$$

A: \begin{align}
& \lim_{t\to\infty} \left( e^{-t} \sin t - e^{-t} \cos t \right) \\[8pt]
= {} & \left( \lim_{t\to\infty} e^{-t}\sin t \right)  - \left( \lim_{t\to\infty} e^{-t} \cos t \right) \\
& \text{provided these last two limits exist} \\
& \text{(and are finite).}
\end{align}
Then, since $-1 \le \sin t \le 1,$ we have
$$
-e^{-t} \le e^{-t}\sin t \le e^{-t}.
$$
The first and third expressions above both approach $0$ as $t\to\infty.$
(And the one involving the cosine is done the same way.)


text:
Q: How to do loop in pentaho for getting file names? I have 100 000 files.
I want to get the name of those file names and have to put in database,
I have to do like this

*

*get 10 files name's;

*update/insert names into  database;   and

*move those 10 files to another directory;
and loop these three steps till no files are found.

Is this possible?

A: I'm attaching a working example (I tested it with ~400 text files on kettle 4.3.).
transformation.ktr
job.kjb
Both transformation and job contain detailed notes on what to set and where.

*

*Transformation.ktr It reads first 10 filenames from given source folder, creates destination filepath for file moving. It outputs filenames to insert/update (I used dummy step as a placeholder) and uses "Copy rows to resultset" to output needed source and destination paths for file moving.

*job.kjb All the looping is done in this job. It executes "transformation.ktr" (which does insert/update for 10 files), and then moves those 10 files to destination folder. After that, it checks whether there's any more files in source folder. If there is, process is repeated, if not, it declares success.


text:
Q: Add an element to a list past the end of the list in python Is there a pythonic way to add to a list at a known index that is past the end of the list? I cannot use append, as I'm looking add at an index that is more than 1 past the end. (For example, I want to put a value at x[6] when len(x) == 3).
I have a code that performs actions for sequential steps, and each step has a set of inputs. The users create an input file with these inputs. I store those inputs as a dictionary for each step, then a list of dictionaries to keep the order of the steps. I had just been reading the inputs for each step, then appending the dictionary to the list. I want to harden the code against the steps being out of order in the input files. If the user puts step 6 before step 3, I can't just append. I do not know the total number of steps until after the file has been read. I have a method worked out, but it seems clunky and involves multiple copies.
My kludgy attempt. In this case InputSpam and CurrentStep would actually be read from the user file
import copy
AllInputs = []
InputSpam = {'Key',999}
for i in xrange(0,3):
   AllInputs.append(InputSpam.copy())

CurrentStep = 7
if CurrentStep - 1 == len(AllInputs):
   AllInputs.append(InputSpam.copy())
elif CurrentStep - 1 < len(AllInputs):
   AllInputs[CurrentStep-1] = InputSpam.copy()
elif CurrentStep - 1 > len(AllInputs):
   Spam = [{}]*CurrentStep
   Spam [:len(AllInputs)] = copy.deepcopy(AllInputs)
   AllInputs = copy.deepcopy(Spam)
   AllInputs[CurrentStep-1] = InputSpam.copy()
   del Spam

A: Only after I wrote the answer I notice you use pyhton 2. Python 2 is unsupported for a long time now. You should switch to python 3. (The following solution is only valid for python 3.)
You can use collections.UserList to crate your own variation of a list like this:
from collections import UserList

class GappedList(UserList):
    PAD_VALUE = object()  # You may use None instead
    def __setitem__(self, index, value):
        self.data.extend(self.PAD_VALUE for _ in range(len(self.data), index+1))
        self.data[index] = value

Inheriting from the UserList makes the whole structure to mostly behave like a regular list, unless specified otherwise. The data attribute gives access to "raw" underlying list. Only thing we need to redefine here is __setitem__ method which cares to assignments like my_list[idx] = val. We redefine in to firstly fill in a gap inbetween the end of the current list and the index you want to write in. (Actually it fills the list including the index you want to write to and then re-writes to value -- it makes the code a bit simpler).
You might need to redefine alse __getitem__ method if you want to handle access to index in the gaps somewhat differently.
Usage:
my_list = GappedList([0,1,2])
my_list.append(3)
my_list[6] = 6
my_list.append(7)
my_list[5] = 5
print(my_list)

# output:
[0, 1, 2, 3, <object object at 0x7f42cbd5ec80>, 5, 6, 7]


text:
Q: Overlaying spatial polygon with grid and checking in which grid element specific coordinates are located using R How can one use R to

*

*split a shapefile in 200 meter squares/sub-polygons,

*plot this grid (incl. ID numbers for each square) over the original map below, and

*evaluate in which square specific geographic coordinates are located.

I am a beginner in GIS and this is perhaps a basic question, but I haven't found a tutorial on how to do this in R.
What I have done so far is loading a shapefile of NYC and plotting some exemplary geographic coordinates.
I am looking for an example (R code) how to this with the data below.
# Load packages
library(maptools)

# Download shapefile for NYC
# OLD URL (no longer working)
# shpurl <- "http://www.nyc.gov/html/dcp/download/bytes/nybb_13a.zip"
shpurl <- "https://www1.nyc.gov/assets/planning/download/zip/data-maps/open-data/nybb_13a.zip"

tmp    <- tempfile(fileext=".zip")
download.file(shpurl, destfile=tmp)
files <- unzip(tmp, exdir=getwd())

# Load & plot shapefile
shp <- readShapePoly(files[grep(".shp$", files)])
plot(shp)

# Define coordinates
points_of_interest <- data.frame(y=c(919500, 959500, 1019500, 1049500, 1029500, 989500),
                 x =c(130600, 150600, 180600, 198000, 248000, 218000),
                 id  =c("A"), stringsAsFactors=F)

# Plot coordinates
points(points_of_interest$y, points_of_interest$x, pch=19, col="red")

A: Here is an example using a SpatialGrid object:
### read shapefile
library("rgdal")
shp <- readOGR("nybb_13a", "nybb")

proj4string(shp)  # units us-ft
# [1] "+proj=lcc +lat_1=40.66666666666666 +lat_2=41.03333333333333
# +lat_0=40.16666666666666 +lon_0=-74 +x_0=300000 +y_0=0 +datum=NAD83
# +units=us-ft +no_defs +ellps=GRS80 +towgs84=0,0,0"

### define coordinates and convert to SpatialPointsDataFrame
poi <- data.frame(x=c(919500, 959500, 1019500, 1049500, 1029500, 989500),
                  y=c(130600, 150600, 180600, 198000, 248000, 218000),
                  id="A", stringsAsFactors=F)
coordinates(poi) <- ~ x + y
proj4string(poi) <- proj4string(shp)

### define SpatialGrid object
bb <- bbox(shp)
cs <- c(3.28084, 3.28084)*6000  # cell size 6km x 6km (for illustration)
                                # 1 ft = 3.28084 m
cc <- bb[, 1] + (cs/2)  # cell offset
cd <- ceiling(diff(t(bb))/cs)  # number of cells per direction
grd <- GridTopology(cellcentre.offset=cc, cellsize=cs, cells.dim=cd)
grd
# cellcentre.offset 923018 129964
# cellsize           19685  19685
# cells.dim              8      8

sp_grd <- SpatialGridDataFrame(grd,
                               data=data.frame(id=1:prod(cd)),
                               proj4string=CRS(proj4string(shp)))
summary(sp_grd)
# Object of class SpatialGridDataFrame
# Coordinates:
#      min     max
# x 913175 1070655
# y 120122  277602
# Is projected: TRUE
# ...

Now you can use the implemented over-method to obtain the cell IDs:
over(poi, sp_grd)
#   id
# 1 57
# 2 51
# 3 38
# 4 39
# 5 14
# 6 28

To plot the shapefile and the grid with the cell IDs:
library("lattice")
spplot(sp_grd, "id",
       panel = function(...) {
         panel.gridplot(..., border="black")
         sp.polygons(shp)
         sp.points(poi, cex=1.5)
         panel.text(...)
       })

or without colour/colour key:
library("lattice")
spplot(sp_grd, "id", colorkey=FALSE,
       panel = function(...) {
         panel.gridplot(..., border="black", col.regions="white")
         sp.polygons(shp)
         sp.points(poi, cex=1.5)
         panel.text(..., col="red")
       })

A: If you have not looked at the R raster package, it has tools to convert to/from vector GIS objects so you should be able to a) create a raster (grid) with 200x200m cells and b) convert it to a set of polygons with a logical id of some kind.  From there I would look at the sp package to help with intersecting the points and the polygon grid.  This http://cran.r-project.org/web/packages/sp/vignettes/over.pdf page might be a good start.  Wandering through the sp package docs you might be able to start with the SpatialGrid-class and just skip the raster part entirely.

A: The New York dataset provided in the question is no longer available for download. I use the nc dataset from sf package to demonstrate a solution using sf package:
library(sf)
library(ggplot2)

# read nc polygon data and transform to UTM
nc <- st_read(system.file('shape/nc.shp', package = 'sf')) %>%
  st_transform(32617)

# random sample of 5 points
pts <- st_sample(nc, size = 5) %>% st_sf

# create 50km grid - here you can substitute 200 for 50000
grid_50 <- st_make_grid(nc, cellsize = c(50000, 50000)) %>%
  st_sf(grid_id = 1:length(.))

# create labels for each grid_id
grid_lab <- st_centroid(grid_50) %>% cbind(st_coordinates(.))

# view the sampled points, polygons and grid
ggplot() +
  geom_sf(data = nc, fill = 'white', lwd = 0.05) +
  geom_sf(data = pts, color = 'red', size = 1.7) +
  geom_sf(data = grid_50, fill = 'transparent', lwd = 0.3) +
  geom_text(data = grid_lab, aes(x = X, y = Y, label = grid_id), size = 2) +
  coord_sf(datum = NA)  +
  labs(x = "") +
  labs(y = "")

# which grid square is each point in?
pts %>% st_join(grid_50, join = st_intersects) %>% as.data.frame

#>   grid_id                 geometry
#> 1      55 POINT (359040.7 3925435)
#> 2      96   POINT (717024 4007464)
#> 3      91 POINT (478906.6 4037308)
#> 4      40 POINT (449671.6 3901418)
#> 5      30 POINT (808971.4 3830231)

A: The "GIS universe" is complex and have many standards that your data must be compliant. All "GIS tools" interoperates by GIS-standards. All "serious GIS data" today (2014) are  stored in a database.
The best way to "use R" in a GIS context, with other FOSS tools, is embedded into SQL. The best tools are PostgreSQL 9.X (see PL/R) and PostGIS.

You answer:

*

*To import/export shape files: use shp2pgsql and pgsql2shp.

*To "split a shape file in 200 meter squares/sub-polygons": see ST_SnapToGrid(), ST_AsRaster(), etc. We need understand better your needs to express into a "recipe".

*you say that need "geographic coordinates are located" .. perhaps ST_Centroid() of the squares (?)... You can express "more mathematically" so I understand.

... Perhaps you not need any raster convertion, only a matrix of regurlar-sampled points.

A primitive way is use R without PL/R,  in a your usual external compiler: only convert your polygons and export as shape or as WKT (see ST_AsText), then convert data with awk or another filter to the R format.


text:
Q: DSGET - determine if no match is found I have the following code in a batch file to return a given users email address:
for /f "tokens=1-3" %%A in (users.txt) do (
dsquery user -name "*%%A*, *%%C*"|dsget user -email >> result.txt
)

It works fine, but I would like some help with the following:
1 - Determine if no match was found and output a suitable line to the result file eg: echo No match found for %%A, %%B >> results.txt ?
2 - I want to remove all the additional output from DSGET eg: DSGET succeeded and 'email' and just leave the email address ?

A: After some trial and error, I got the following to give me the desired output:
@echo off
setlocal enabledelayedexpansion

for /f "tokens=1-3" %%A in (users.txt) do (
dsquery user -name "%%A, %%B* *%%C*" |dsget user -email |findstr "succeeded"

if !errorlevel!== 0 (
for /f "tokens=*" %%a in ('dsquery user -name "%%A, %%B* *%%C*" ^|dsget user -email ^|findstr /v "email" ^|findstr /v "dsget"') do @echo %%a >> result.txt)

if !errorlevel!== 1 echo Match Not found %%A, %%B >> result.txt
)


text:
Q: How to fix "MessagingGatewayBadRequest" error in ARM template? I am creating namespace and service bus queues using ARM template. I can create namespace successfully but getting following error while it tries to create queues:

"code": "MessagingGatewayBadRequest",
"message": "400SubCode=40000. Bad Request. To know more visit https://aka.ms/sbResourceMgrExceptions.

I am not able to find out the root cause of this error. There is nothing complicated about queue in my template, so not sure what is the root cause. Not seeing this error in  Microsoft doc as well.
ARM template:
{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "metadata": {
    "_generator": {
      "name": "bicep",
      "version": "0.5.6.12127",
      "templateHash": "15173749018276299351"
    }
  },
  "parameters": {
    "environment": {
      "type": "string",
      "allowedValues": ["Dev", "Test", "Prod"],
      "metadata": {
        "description": "Environment for resource group"
      }
    },
    "resourceTags": {
      "type": "object",
      "defaultValue": {
        "Environment": "[parameters('environment')]",
        "BillTo": "specialprojects",
        "Architecture": "AppService",
        "AlertName": "mgmt"
      }
    },
    "serviceBusNamespaceName": {
      "type": "string",
      "metadata": {
        "description": "Name of the Service Bus namespace"
      }
    },
    "queues": {
      "type": "array",
      "metadata": {
        "description": "Array of the Queue"
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Location for all resources."
      }
    }
  },
  "resources": [
    {
      "type": "Microsoft.ServiceBus/namespaces",
      "apiVersion": "2021-11-01",
      "name": "[toLower(parameters('serviceBusNamespaceName'))]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "Standard"
      },
      "properties": {},
      "tags": "[parameters('resourceTags')]"
    },
    {
      "type": "Microsoft.ServiceBus/namespaces/queues",
      "apiVersion": "2021-11-01",
      "name": "[format('{0}/{1}', toLower(parameters('serviceBusNamespaceName')), parameters('queues')[copyIndex()].name)]",
      "copy": {
        "name": "QueueCopy",
        "count": "[length(parameters('queues'))]"
      },
      "properties": {
        "lockDuration": "PT5M",
        "maxSizeInMegabytes": 1024,
        "requiresDuplicateDetection": true,
        "requiresSession": false,
        "deadLetteringOnMessageExpiration": true,
        "duplicateDetectionHistoryTimeWindow": "PT10M",
        "maxDeliveryCount": 10,
        "enablePartitioning": false,
        "enableExpress": false,
        "maxMessageSizeInKilobytes": 10240,
        "autoDeleteOnIdle": "PT48H"
      },
      "dependsOn": [
        "[resourceId('Microsoft.ServiceBus/namespaces', toLower(parameters('serviceBusNamespaceName')))]"
      ],
      "tags": "[parameters('resourceTags')]"
    }
  ]
}

parameters.json:
{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "environment": {
      "value": "Dev"
    },
    "serviceBusNamespaceName": {
      "value": "c4p-dev"
    },
    "queues": {
      "value": [
        {
          "name": "dmp"
        },
        {
          "name": "smp"
        },
        {
          "name": "auction"
        }
      ]
    }
  }
}

Error:
{
  "code": "DeploymentFailed",
  "message": "At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/DeployOperations for usage details.",
  "details": [
    {
      "code": "MessagingGatewayBadRequest",
      "message": "<Error>400<Detail>SubCode=40000. Bad Request. To know more visit https://aka.ms/sbResourceMgrExceptions. . TrackingId:06e867e5-289e-4fdd-956c-2b9684760455_G8, SystemTracker:c4p-dev.servicebus.windows.net:smp, Timestamp:2022-08-11T14:50:04</Detail></Error>"
    },
    {
      "code": "MessagingGatewayBadRequest",
      "message": "<Error>400<Detail>SubCode=40000. Bad Request. To know more visit https://aka.ms/sbResourceMgrExceptions. . TrackingId:5fbdd148-e1c9-4db9-90ac-4ae9dc966ad9_G0, SystemTracker:c4p-dev.servicebus.windows.net:auction, Timestamp:2022-08-11T14:50:04</Detail></Error>"
    },
    {
      "code": "MessagingGatewayBadRequest",
      "message": "<Error>400<Detail>SubCode=40000. Bad Request. To know more visit https://aka.ms/sbResourceMgrExceptions. . TrackingId:005c726d-e8fc-46cc-bd97-d9e688e9cab6_G17, SystemTracker:c4p-dev.servicebus.windows.net:dmp, Timestamp:2022-08-11T14:50:04</Detail></Error>"
    }
  ]
}

*

*

A: I was able to fix this issue by creating queues separately. Meaning, following way (array) to create queue(s) is not supported by ARM template. This would work for cosmos and blobStorage ARM template though. Not sure why serviceBus is different.
  "name": "[format('{0}/{1}', parameters('serviceBusNamespaceName'), parameters('queues')[copyIndex()].name)]",
  "copy": {
    "name": "QueueCopy",
    "count": "[length(parameters('queues'))]"
  },

Correct way to create queue(s):
{
  "type": "Microsoft.ServiceBus/namespaces/queues",
  "apiVersion": "2017-04-01",
  "name": "[format('{0}/{1}', parameters('serviceBusNamespaceName'), parameters('smpQueue'))]",
  "properties": {
    "lockDuration": "PT5M",
    "maxSizeInMegabytes": 1024,
    "requiresDuplicateDetection": true,
    "requiresSession": false,
    "deadLetteringOnMessageExpiration": true,
    "duplicateDetectionHistoryTimeWindow": "PT10M",
    "maxDeliveryCount": 10,
    "enablePartitioning": false,
    "enableExpress": false,
    "maxMessageSizeInKilobytes": 10240,
    "autoDeleteOnIdle": "PT48H"
  },
  "dependsOn": [
    "[resourceId('Microsoft.ServiceBus/namespaces', parameters('serviceBusNamespaceName'))]"
  ],
  "tags": "[parameters('resourceTags')]"
},
{
  "type": "Microsoft.ServiceBus/namespaces/queues",
  "apiVersion": "2017-04-01",
  "name": "[format('{0}/{1}', parameters('serviceBusNamespaceName'), parameters('auctionQueue'))]",
  "properties": {
    "lockDuration": "PT5M",
    "maxSizeInMegabytes": 1024,
    "requiresDuplicateDetection": true,
    "requiresSession": false,
    "deadLetteringOnMessageExpiration": true,
    "duplicateDetectionHistoryTimeWindow": "PT10M",
    "maxDeliveryCount": 10,
    "enablePartitioning": false,
    "enableExpress": false,
    "maxMessageSizeInKilobytes": 10240,
    "autoDeleteOnIdle": "PT48H"
  },
  "dependsOn": [
    "[resourceId('Microsoft.ServiceBus/namespaces', parameters('serviceBusNamespaceName'))]"
  ],
  "tags": "[parameters('resourceTags')]"
}


text:
Q: Python Requests taking a long time Basically I am working on a python project where I download and index files from the sec edgar database. The problem however, is that when using the requests module, it take a very long time to save the text in a variable (between ~130 and 170 seconds for one file).
The file roughly has around 16 million characters, and I wanted to see if there was any way to easily lower the time it takes to retrieve the text. -- Example:
import requests

url ="https://www.sec.gov/Archives/edgar/data/0001652044/000165204417000008/goog10-kq42016.htm"

r = requests.get(url, stream=True)

print(r.text)

Thanks!

A: What I found is in the code for r.text, specifically when no encoding was given ( r.encoding == 'None' ). The time spend detecting the encoding was 20 seconds, I was able to skip it by defining the encoding.
...
r.encoding = 'utf-8'
...

Additional details
In my case, my request was not returning an encoding type. The response was 256k in size, the r.apparent_encoding was taking 20 seconds.
Looking into the text property function. It tests to see if there is an encoding. If there is None, it will call the apperent_encoding function which will scan the text to autodetect the encoding scheme.
On a long string this will take time. By defining the encoding of the response ( as described above), you will skip the detection.
Validate that this is your issue
in your above example :
from datetime import datetime
import requests

url = "https://www.sec.gov/Archives/edgar/data/0001652044/000165204417000008/goog10-kq42016.htm"

r = requests.get(url, stream=True)

print(r.encoding)

print(datetime.now())
enc = r.apparent_encoding
print(enc)

print(datetime.now())
print(r.text)
print(datetime.now())

r.encoding = enc
print(r.text)
print(datetime.now())

of course the output may get lost in the printing, so I recommend you run the above in an interactive shell, it may become more aparent where you are losing the time even without printing datetime.now()

A: From @martijn-pieters

Decoding and printing 15MB of data to your console is often slower than loading data from a network connection. Don't print all that data. Just write it straight to a file.


text:
Q: Appearence of long labels on x-axis I have really long labels for the x axis. They overflow at the margins. See here:

The outer right label overflows. It should be r,r,r,r,r,N,N,r.
Is there a way to display them vertical or diagonal like in Excel?
Another option woould be to make the spacing bigger around the graph but when I call
$graph = new Graph(600, 300);

the whole graph is scaled accordingly. How can I change that?

A: You can increase the margin around the graph:
$graph->img->SetMargin(50, 60, 50, 50); // left, right, top, bottom

Result:


text:
Q: assertion versus statement This may seem like a stupid question from an English teacher (2nd year), but I am confounded.  What is the difference between writing an assertion to start a body paragraph versus writing a statement to begin a body paragraph?  My sophomores are working on their research papers and a colleague of mine said he keeps getting statements versus assertion sentences at the beginning of his students' paragraphs.  Is there truly a difference between the two?  I thought as long as the "topic sentence" mentioned a part of the premise/assertion from the thesis statement, the body paragraph was set up to argue and support that particular line of argument.  Am I just getting caught up in the minutiae or is there a literal difference.  I want to be clear and concise so my students learn from this experience and I don't want to confuse them or teach them something that is incorrect.  This is verbose, but I appreciate any and all advice.

A: All assertions are statements, but not all statements are assertions:

*

*assertions are positive, but statements may be positive or negative;

*assertions do not supply proof or support, but statements may supply those.

Given that your colleague is suggesting a difference, it must be in those distinctions. Your colleague is seeing negative statements or statements that provide proof or support, or statements that are both negative and provide proof or support, rather than bald assertions, as topic sentences.
For a simple example, suppose the thesis is that fathers are more able to teach their children how to shoot guns. Then, the statement

Mothers may not have the experience they need to teach children how to shoot, because they have been deprived by their circumstances.

contrasts with the assertion

Mothers are less experienced shooters than fathers.

Whether this is what your colleague has in mind, I don't know (you'd have to ask, caprice being the norm). Likewise, whether or not requiring assertions as opposed to statements for topic sentences is pedagogically correct for your students is outside my purview.

A: For what it's worth:
What your Colleague may have in Mind is that an Assertion is like a Hypothesis, while a Statement is a full-fledged Theory.
A Hypothesis does not require Proof: it is just an Idea. It may be Right, or it may be Wrong, and it's up to the Author to supply Evidence in Favor of his or her Hypothesis (assertion).
A Theory, on the other Hand, is Something that may already be Known to Others, along with all the necessary Evidence, just like a Statement.
Here's a statement:

John Singer Sargent was an American painter specializing in Realism and Impressionism.

Here's an assertion:

John Singer Sargent was an American painter who drew his inspiration from Rembrandt, Hals, Delacroix, Manet, and, to a lesser extent, William Meritt Chase.

There former is a well-known fact. The latter is an assertion: the author is expected to supply some evidence, verbal or otherwise, that would prove his point.


text:
Q: A student must answer five out of $10$ questions on a test, including at least two of the first five questions. A student must answer five out of $10$ questions on a test, including at least two
of the first five questions. How many subsets of five questions can be answered?
$$\binom52\binom53+\binom53\binom52+\binom54\binom51+\binom55$$
if im correct , is there any other way to think about this problem ?

A: What you've done is correct. You could also have calculated
$$\binom{10}5-\binom51\binom54+\binom55\;,$$
i.e., the total number of ways to choose $5$ questions minus the number of ways that include $1$ or $0$ questions from the first $5$.

A: You are correct.
You need to choose at least 2 from first 5. So you have 2 from first 5, 3 from the other group; 3 from first 5, 2 from the other group; 4 from first 5, 1 from the other group; all 5 from the first group of 5


text:
Q: windbg/cdb hangs when bp hit I have a problem where cdb or windbg hangs frequently, but not all the time, when I'm debugging with it and I attach to a specific application on my machine.
I found this article: http://www.nynaeve.net/?p=164 which talks about a symbol loading race condition being the problem, but I can force load the symbols, actually have a breakpoint in-app work, and still have it hang elsewhere.
Here is the stack from cdb itself when I attach to it with another debugger:
ntdll!NtReadFile
kernel32!ReadFile
cdb!ReadNonConLine
cdb!ConIn
cdb!MainLoop
cdb!main

!analyze reports that APPLICATION_HANG_BusyHang is the problem bucket, and 'ReadNonConLine' is the offending function.
as far as the stack goes:
ffffffff`fffffffe 00000000`00000000 00000001`3f641498 00000000`0014ea50 : kernel32!ReadFile+0x86
00000000`000002a4 00000000`0014ebb0 00000000`00001000 00000000`00000000 : cdb!ReadNonConLine+0x6d

ReadNonConLine has the string "g" at 0014ebb0 passed as a param, which may be part of the command I had at the hanging breakpoint (it was something like bp foo "dt a; g")
ReadFile takes a handle as its first parameter. I'm surprised by the value -2, though, that doesn't look valid.
Any help is appreciated.
Thanks!
Aaron

A: I was debugging a 32 bit app with the 64 bit tools, so I decided to switch to the 32 bit Debug Tools and I haven't had a hang since.
The app in question is pretty graphically intensive, I'm guessing that it was this interacting poorly with WoW64 in a debugging environment...


text:
Q: How to pass data to the final view controller I am new to Swift and am building an app to learn. Right now I am making the registration section of the app.
I thought the UX would be better if there were multiple VC's asking a single question, i.e. one for your name, one for your birthdate, etc as opposed to jamming all that into a single view controller. The final view controller collects all of that information and sends a dictionary as FUser object to be saved on Firebase.
I figured I could instantiate the final view controller on each of the previous five view controllers and pass that data directly to the end. I kept getting errors and figured out that the variables were nil. It works just fine if I pass the data directly to the next view controller but it doesn't seem to let me send it several view controllers down. Obviously there's a nuance to how the memory is being managed here that I'm not tracking.
Is there a way to do what I am trying to do or do I have to pass the data through each view controller along the way?
import UIKit

class FirstViewController: UIViewController {

    //MARK: - IBOutlets
    @IBOutlet weak var firstNameTextField: UITextField!

    //MARK: - ViewLifeCycle
    override func viewDidLoad() {
        super.viewDidLoad()

    }

    //MARK: - IBActions
    @IBAction func continueToMiddleViewController(_ sender: Any) {

       let vcFinal = storyboard?.instantiateViewController(withIdentifier:
 "finalVC") as! finalViewController
       vcFinal.firstName = firstNameTextField.text

       let vc = storyboard?.instantiateViewController(withIdentifier:
 "middleVC") as! middleViewController
       vc.modalPresentationStyle = .fullScreen
       present(vc, animated: false)

    }

    ...

}

import UIKit

class FinalViewController: UIViewController {

    var firstName: String?
    ...

    //MARK: - ViewLifeCycle
    override func viewDidLoad() {
        super.viewDidLoad()

    }

    ...

}

A: TL;DR: The fastest one that would solve your problem is creating a singleton
There are many strategies for this. For a starter, it might be a good idea to read some begginer articles, like this one. I can update this answer if you don't find it useful, but it'd look just like the article

A: Viewcontroller's variable can't be initiated until any of the init method is called.
There are detailed answers on this thread.
Passing Data between ViewControllers

A: Another way to approach this problem could be to make use of closures. Note that personally I've moved away from using storyboards but I'll try to explain still. Closures are also referred to as callbacks, blocks, or in some context like here - completions.
You can declare a closure like let onSubmitInfo: (String?) -> Void below, it stores a reference to a block of code that can be executed at a later stage just like a function and it takes an optional string as a parameter just like a function can.
The closures are specified in the initialisers where a block of code is passed into the respective classes below and the closures are then called in the IBActions that will trigger the block of code that is defined where the below classes are initialised:
class First: UIViewController {
    // MARK: - IBOutlets
    @IBOutlet weak var firstNameTextField: UITextField!

    // MARK: - Properties
    private let onSubmitInfo: (String?) -> Void

    init(onSubmitInfo: (String?) -> Void) {
        self.onSubmitInfo = onSubmitInfo
    }

    // MARK: - IBActions
    @IBAction func continue(_ sender: Any) {
        onSubmitInfo(firstNameTextField.text)
    }
}

class Second: UIViewController {
    // MARK: - IBOutlets
    @IBOutlet weak var lastNameTextField: UITextField!

    // MARK: - Properties
    private let onSubmitInfo: (String?) -> Void

    init(onSubmitInfo: (String?) -> Void) {
        self.onSubmitInfo = onSubmitInfo
    }

    // MARK: - IBActions
    @IBAction func continue(_ sender: Any) {
        onSubmitInfo(lastNameTextField.text)
    }
}

To manage showing the above views and collecting the values returned by their closures (i.e. onSubmitInfo) we create a FlowController class that will also show the next view when the closure is called.
In FlowController we define the closures or blocks of code to be executed when it is called inside the IBAction in the respective First and Second classes above.
The optional string that is provided in the respective First and Second classes is used as the (firstName) and (secondName) closure properties below:
class FlowController: UIViewController {
    private var fistName: String?
    private var lastName: String?

    ...

    private func showFirstView() {
        let firstViewController = First(onSubmitInfo: { (firstName) in
            self.firstName = firstName
            showSecondView()
        })
        navigationController?.pushViewController(
            firstViewController,
            animated: true)
    }

    private func showSecondView() {
        let secondViewController = Second(onSubmitInfo: { (lastName) in
            self.lastName = lastName
            showFinalView()
        })
        navigationController?.pushViewController(
            secondViewController,
            animated: true)
    }

    private func showFinalView() {
        let finalViewController = Final(
            firstName: firstName,
            lastName: lastName)
        navigationController?.pushViewController(
            finalViewController,
            animated: true)
    }
}

The FlowController finally shows the Final view controller after it has collected the firstName form the First view controller and the lastName form the Second view controller in the showFinalView function above.
class Final: UIViewController {
    let firstName: String
    let lastName: String
    ...
}

I hope this is a shove in the right direction. I have moved away from storyboards because I find creating views in code is more verbose and clear on peer reviews and it was also easier for me to manage constraints and just to manage views in general.


text:
Q: Marquee scrolling inside a table cell I am trying to create a table where the 1st column is a "subject" that doesn't scroll and the 2nd column is text that scrolls using a marquee format. In the example below, the subject: "Astrology" would not scroll but the text in column 2 should scroll.
I'm using a table as I want to have the subject and scrolling text on the same line. When I run this, the text in column 2 does not scroll. However, if I remove the <"TableRow"> tags from activity_main.xml, the marquee text scrolls but it is not on the same line.
Is it possible to scroll text in 1 column of a table row and not scroll the text in another column of the same row?
Example: (The 1st column subject: "Astrology" should not scroll)
| 1st column |       2nd column                                      |
Astrology:       <-- Capricorn: This text scrolls from right to left <--
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@android:color/black"
    android:textColor="#FFFFFFFF"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:stretchColumns="1">

    <TableRow>
        <TextView
            android:layout_column="1"
            android:textColor="#FFFFFFFF"
            android:text="Astrology:"
            android:padding="3dip" />
        <TextView
            android:layout_height="wrap_content"
            android:textColor="#FFFFFFFF"
            android:text="Capricorn: This is a test of the emergency broadc ..."
            android:id="@+id/tvText1"
            android:layout_width="fill_parent"
            android:singleLine="true"
            android:ellipsize="marquee"
            android:marqueeRepeatLimit="marquee_forever"
            android:scrollHorizontally="true"
            android:paddingLeft="15dip"
            android:paddingRight="15dip"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:freezesText="true" />
    </TableRow>

MainActivity:
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {
    TextView tvText1,tvText2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvText1 = (TextView)findViewById(R.id.tvText1);
        tvText2 = (TextView)findViewById(R.id.tvText2);

        tvText1.setSelected(true);
        tvText2.setSelected(true);
    }

A: I was able to get this to work using Ramakrishna's ScrollTextView solution that lets you change the scrolling speed. Here's that link:
Marquee Set Speed  I replaced the 2nd column TextView with the ScrollTextView as shown below.
<TableRow>
    <TextView
        android:layout_column="1"
        android:textColor="#FFFFFFFF"
        android:text="Astrology:"
        android:padding="3dip" />
    <TextView
    <com.example.jack.tablemarquee.ScrollTextView
        android:layout_height="wrap_content"
        android:textColor="#FFFFFFFF"
        android:text="Capricorn: This is a test of the emergency broadcast system. Had this been an actual emergency..."
        android:id="@+id/scrolltext"
   />
</TableRow>


text:
Q: Why does Lucene program quit with OutOfMemoryError? Please someone help me. My program is working fine when i use a small sample of data but with my real data  which is 40MB its giving this error: java.lang.OutOfMemoryError: Java heap space
Here is my code;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;

public class RechercheEngine {

    static  ArrayList<String> resultat = new ArrayList<String>();
    final static String file ="Ressources/file_collection.txt";
    static LireFichierCollection rf = new LireFichierCollection();
    static LireRequete ls = new LireRequete();

public static void indexerEtRechercherDocument( boolean exchange) throws IOException, org.apache.lucene.queryparser.classic.ParseException{

    System.out.println("Analyzing documents...");
    Directory directory = new RAMDirectory();
    Analyzer analyzer = new StandardAnalyzer();
    IndexWriterConfig config = new IndexWriterConfig(analyzer);
    IndexWriter indexWriter  =  new IndexWriter(directory, config);

    Document doc = new Document();
    rf.readFile(file);
    System.out.println("Indexing documents...");
        for(Map.Entry <String, String> entry : rf.hashMap.entrySet()) {
            doc.add(new StringField("DocKey",entry.getKey(), Field.Store.YES));
            Stemming st = new Stemming();
            if (exchange){
                doc.add(new TextField("DocContent",  st.stemmingAvecStopWord(entry.getValue()), Field.Store.NO));
            }
            else{
                doc.add(new TextField("DocContent",  entry.getValue(), Field.Store.NO));
            }
            indexWriter.addDocument(doc);
        }
    indexWriter.close();
    System.out.println("Indexing documents done");

    ls.readList();
    System.out.println("Researching documents...");

        for(Map.Entry <String, String> entry : ls.map.entrySet()) {
            Stemming st = new Stemming();
            Query query;
            if (exchange){
                query = new QueryParser("DocContent", analyzer).parse(st.stemmingAvecStopWord(entry.getValue()));
            }
            else{
                query = new QueryParser("DocContent", analyzer).parse(entry.getValue());
            }
            IndexReader reader=DirectoryReader.open(directory);
            IndexSearcher searcher = new IndexSearcher(reader);
            ScoreDoc[] hits = searcher.search(query, 2).scoreDocs;
            for (int i = 0; i < hits.length; i++) {
                int docId = hits[i].doc;
                Document hitDoc = searcher.doc(docId);
                 String docKey = hitDoc.get("DocKey");
                HashMap<String, String> X= new HashMap<String, String>();
                for (IndexableField field : hitDoc.getFields())
                {
                    X.put(field.name(), field.stringValue() );
                }

             resultat.add(entry.getKey()+ " " + docKey+ " " + hits[i].score);
            }
            reader.close();
        }
}

}


text:
Q: Assigning number to .find(type) in Jquery I have a function that allows me to select a random radio button and click on it. But on different pages I have different .find(type). Example:
Page1.html: controlTypeToIterateOn='label'
Page2.html: controlTypeToIterateOn=':radio'
//Radio button
function randomNumberGenerator(max, min) {
  var randomNumber = Math.floor(Math.random() * (max - min + 1) + min);
  return randomNumber;
}

function SelectRandonRadioButton(radioButtonContainer, controlTypeToIterateOn) { //Genereal function
  var radios = $(radioButtonContainer).find(controlTypeToIterateOn);
  if (controlTypeToIterateOn == ':radio')
    controlTypeToIterateOn = 1;
  else if (controlTypeToIterateOn == 'label')
    controlTypeToIterateOn = 0;

  var randomnumber = randomNumberGenerator(radios.length - 1, 0);
  //randomizing number
  $(radios[randomnumber]).click();
  return $(radios[randomnumber]);

}

function SelectLiveRandomRadioButton(radioButtonContainer, controlTypeToIterateOn) {
  var elem = SelectRandonRadioButton(radioButtonContainer, controlTypeToIterateOn);
  $(elem).mousedown();
}

function call() {
  $(".YesNoRadio").each(function() {
    SelectLiveRandomRadioButton($(this), 1);
  });
}

call();

My if condition that checks the input type does not seem to work. I want to assign a numeric value that I can pass in my SelectLiveRandomRadioButton() function that's inside the call function. For example if I pass '0',my controlTypeToIterateOn = 'label', if I pass 1, my controlTypeToIterateOn = ':radio'. Anyone who can help me with this? Thanks.

A: I am not sure what you are trying to do, but from looking at your code, I guess you might want to do something like this:
function SelectRandonRadioButton(radioButtonContainer, controlTypeToIterateOn) {
  var toFind;
  if (controlTypeToIterateOn === 1) {
    toFind = ':radio';
  } else if (controlTypeToIterateOn === 0) {
    toFind = 'label';
  }
  var hits = $(radioButtonContainer).find(toFind);
  var randomnumber = randomNumberGenerator(hits.length - 1, 0);
  $(hits[randomnumber]).click();
  return $(hits[randomnumber]);
}

function call() {
  $(".YesNoRadio").each(function() {
    // where 1 would find radio, and 0 label
    SelectLiveRandomRadioButton($(this), 1);
  });
}

call();


text:
Q: Cython is slower than Numpy (example from Python Cookbook) The snippet comes from the book Python Cookbook. There are three files.
sample.pyx
cimport cython

@cython.boundscheck(False)
@cython.wraparound(False)

cpdef clip(double[:] a, double min, double max, double[:] out):

    if min > max:
        raise ValueError('min must be <= max')

    if a.shape[0] != out.shape[0]:
        raise ValueError('input and output arrays must be the same size!')

    for i in range(a.shape[0]):
        if a[i] < min:
            out[i] = min
        elif a[i] > max:
            out[i] = max
        else:
            out[i] = a[i]

setup.py
from distutils.core import setup

from Cython.Build import cythonize

setup(ext_modules=cythonize("sample.pyx"))

and main.py as test file
b = np.random.uniform(-10, 10, size=1000000)

a = np.zeros_like(b)

since = time.time()
np.clip(b, -5, 5, a)
print(time.time() - since)

since = time.time()
sample.clip(b, -5, 5, a)
print(time.time() - since)

Surprisingly, the Numpy runs 2x faster than Cython code, while the book claims the opposite.
The performance on my machine is:
0.0035216808319091797
0.00608062744140625

Why is that?
Thank you in advance.

A: I can confirm your results (numpy 1.15 vs Cython 0.28.3 + gcc-5.4):
>>>  %timeit sample.clip(b, -5, 5, a)
20.5 ms ± 230 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
>>>  %timeit np.clip(b, -5, 5, a)
11.7 ms ± 312 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

It is hard to tell, why the author of cookbook got other timings: other numpy version or maybe other compiler. In the case of np.clip there is not much room to improvement other than using SIMD-instructions.
However, your Cython-code isn't optimal. You can improve it by declaring, that the memory views are contiguous i.e double[::1] rather than double[:]. This results in a cythonized C-code which is easier to optimizer for the compiler (for more info see this SO-question):
cpdef clip2(double[::1] a, double min, double max, double[::1] out):
   ....

>>>  %timeit sample.clip2(b, -5, 5, a)
11.1 ms ± 69.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Which is about the as fast as the numpy version.
However, for getting best results I would recommend Numba: it is much easier to get better performance with Numba, than with Cython (see for example this SO-question):
import numba as  nb
@nb.njit
def nb_clip(a, min, max, out):

    if min > max:
        raise ValueError('min must be <= max')

    if a.shape[0] != out.shape[0]:
        raise ValueError('input and output arrays must be the same size!')

    for i in range(a.shape[0]):
        if a[i] < min:
            out[i] = min
        elif a[i] > max:
            out[i] = max
        else:
            out[i] = a[i]

 ...
 %timeit nb_clip(b, -5, 5, a)
 4.7 ms ± 333 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

The performance difference between Numba and the original Cython-version is here due to clang (which is what Numba uses for compilation) being able to generate better assembler than gcc in this particular case. When I switch to clang-5.0 in Cython, I can match (and even slightly beat) Numba.


text:
Q: Translations from English to predicate logic, using quantifiers. Let "book" be the set of all books and "Author" be the set of all authors. $\in$ denotes set membership.
Consider the following predicates:
short(x) is a predicate indicating x is a short book.
by(x,y) is a predicate indicating that book y was written by x.
Formalize each of the following sentences as a predicate logic formula using the above predicates:

*

*i) "Every book has an author" My answer : $∀b\in \text{ Books }\land ∃a\in \text{ Authors }$

*ii) "There is an author who has not written a book" My answer: $∃a\in \text{ Authors } \land ∃b\in \text{ Books } \land ¬\text{by}\,(b,a)$

*iii)"Every author has written a short book" My answer: $∀a \in \text{ Authors } \land ∃x\in \text{ Books } \land \text{ short}\,(x) \rightarrow \text{by}\,(x,a)$

A: You are a bit off on your answers, and one of the reasons is because you haven't delineated the scope of some of the quantified variables; as a result the reappearance of such a variable outside of the scope of its quantifier is then free.
Another more substantive problem is it seems you haven't grasped the general form for a universally quantified statement versus an existentially quantified statement.
For example: "All humans are mortal": This is a universally quantified statement. If we let $H(x)$ represent "x is a human," and let $M(x)$ represent "x is mortal", then what we are essentially saying, in loglish, is "For all x, IF x is human, THEN x is mortal". This translates, symbolically, to the following:
$$\forall x\,(H(x) \rightarrow M(x))\tag{1}$$
Compare the above to the following: suppose we had written:
$$\forall x\, (H(x) \land M(x))\tag{(2) incorrect}$$
What this incorrect translation says is: "For all x, x is human and x is mortal." This states that everything is human and everything is mortal, whereas what we want to say is something regarding all and only those things that are human.
With that in mind, try to rewrite your first statement accordingly.

On the other hand, the general form for an existentially quantified statement uses conjunction to assert "there exists something such that that something is P and that something is Q."
For example, suppose we want to translate: "Some student missed class today." Crudely, we can denote by $S(x)$: "x is a student." And we can denote by $M(x)$: "x missed class today."  Then the symbolic translation amounts to:
$$\exists x\, (S(x) \land M(x)).$$

I'll deal with the second statement, in part to make explicit the scope of each quantified variable, and in part to correct the translation for the statement that includes both an existential and universal quantifier.

"There is an author who has not written a book". $\iff$ "There exists an $a$ such that $a$ is an author AND, for all $b$, IF $b$ is a book, THEN it is NOT the case that book $b$ was written by author $a$."

A full symbolic translation, then, gives us:
$$\exists a \Big(a \in  \text{ Author }\land \forall b(b\in \;\text{Book}\;\rightarrow \lnot \operatorname{by}(a, b))\Big)$$
Note that we want $\lnot$by$(a, b)$ since we are talking about book $b$ not being written by author $a$, per your definition.

A: I'll use the more customary $\in$ for "belongs to". Your usage of the "and" connective is wrong.
"Every book has an author" should be
$$
\forall b(b\in\mathrm{Books} \to (\exists a(a\in\mathrm{Authors} \land \mathrm{by}(a,b))))
$$
If relativized quantifiers are allowed by the language, it could be
$$
\forall b\in\mathrm{Books}(\exists a\in\mathrm{Authors}(\mathrm{by}(a,b)))
$$
Your other formulas are similarly wrong.
Let's see how you can build the third formula from the ground up:

Every author has written a short book

Translation: For every author, we can find a book which is short and whose author is the one we're talking about
So the book $b$ is short, $\mathrm{short}(b)$, and its author is $a$, $\mathrm{by}(a,b)$: the bulk of the formula is then $\mathrm{short}(b) \land \mathrm{by}(a,b)$. Now we can add the quantifiers.
$$
\forall a\in\mathrm{Authors}(\exists b\in\mathrm{Books}(\mathrm{short}(b) \land \mathrm{by}(a,b)))
$$
Without relativized quantifiers:
$$
\forall a(a\in\mathrm{Authors}\to(\exists b(b\in\mathrm{Books}\land (\mathrm{short}(b) \land \mathrm{by}(a,b)))))
$$


text:
Q: Launch Genius via AppleScript I would like to launch a Genius playlist for the currently playing song in iTunes via an AppleScript.
A prerequisite would be for the script to work when iTunes is in full screen.
And ideally, it wouldn't :

*

*bring iTunes to front

*leave an error message when genius isn't available for that song

*depend on the system language

I found this script, but it doesn't work for me when iTunes is in full screen. Still, it's a great start.
It would maybe be possible to use the protocol the iOS "Remote" app uses, but that seems to be overkill.
Any help would be appreciated.
(the goal is to launch genius from softwares like Keyboard Maestro or Alfred)

A: Try this :
tell application "iTunes" to try
    activate
    with timeout of 10 seconds
        reveal current track -- error if no current track
        set tName to name of (first window whose its class is browser window or its class is playlist window)
    end timeout
on error
    return "Can't find track!"
end try

tell application "System Events"
    tell application process "iTunes"
        try
            set b to (first button of window tName whose value of attribute "AXDescription" is "Genius")
            if not (enabled of b) then return "Genius button disabled" -- (film, video clip,...)
            perform action "AXPress" of b
        on error -- no Genius button (radio, podcast, .....) playlist
            return "Can't create genius list from that track!"
        end try
        delay 2
        tell front window to if value of attribute "AXSubRole" is "AXDialog" then -- dialog opened.
            perform action "AXPress" of button "OK" -- close the dialog
            return "Can't create genius list from that track!"
        end if
    end tell
end tell
return "Done"


text:
Q: obtain function pointer of bound/inferred capturing lambda with static local variable Is it possible to obtain a C style function pointer of a capturing lambda using static local variables?
I am trying to bind the first the argument of the derived function to the original parameter
template <typename F>
class entry_hook
{
public:
  entry_hook(void* original, F&& hook)
  {
    static auto bound = [&](auto&&... args)
    {
      return hook(original, std::forward<decltype(args)>(args)...);
    };

    auto* function_ptr = +[](auto&&... args) // -> decltype(bound(std::forward<decltype(args)>(args)...))
    {
      return bound(std::forward<decltype(args)>(args)...);
    };
  }
};

Using:
const auto hook = entry_hook(nullptr, [](void* original)
{
  // ...
});

Fails to compile - unable to convert closure to function pointer
Removing the parameter pack from the wrapping lambda (by changing the following lines):

*

*auto* function_ptr = +[](auto&&... args) to auto* function_ptr = +[]()

*return bound(std::forward<decltype(args)>(args)...); to return bound();
Succesfully compiles and runs, although I would have assumed that by using a parameter pack that can be inferred at compile time on a lambda, wouldn't result in that lambda becoming a closure as such (being unconvertable to a function pointer as it requires a context)

I'm ideally trying to achieve:
const auto hook = entry_hook(nullptr, [](auto original, int param1, double param2)
{
  // ...
});

Where original is of type void(*)(int, double) and entry_hook can expose a function pointer to the passed in lambda

Reference:
This answer converts a capturing lambda into a function pointer C++ lambda with captures as a function pointer
This answer converts a lambda into a function pointer Obtaining function pointer to lambda?

A: No: it's impossible.
Because the lambda that you trying to convert to a function pointer
[](auto && ... args) { /* something */ }

is a generic (and variadic; but the point is that is a generic one) lambda.
So is almost as a (variadic) template function (more exactly: as a struct with a variadic template operator() in it) as
template <typename ... As>
SomeRetType func (As && ... as)
 { /* do something */ }

and you can't have a pointer from func()
auto fp = &func;  // same problem

because func() isn't an object but a set of objects.


text:
Q: Bad handling of PHP sessions variables? I'm currently using the following code in my cms to check if visitor is logged in as admin so that he can edit the current page:
if($_SESSION['admin']=="1")
{
        echo "edit";
}

But I'm worried that the code is unsafe. Can't $_session variables easily be modified by the user?
What would be a safer practice?

A: No, that's a good way to do it. The user can't modify the $_SESSION global, unless he has access to your server. Remember to stay away from client-side cookies.
To make it even more safe, a good way is to store the IP-adress and check that it stays the same between every request.

A: The code is OK, you're just showing a link. Just make sure that your UPDATE script is protected as well.

A: Session variables should be safe enough once your coding is secure.
Also, use the follow instead. Stops mistakes with ==
Probably should also use true too as it is a lot quicker than string comparisons.
if( "1" === $_SESSION['admin'] )

A: $_SESSION variables can not be set by the user. The code is therefore perfectly fine, although you would usually ask your user backend (typically just a table users, sometimes LDAP) about the current user's privileges.

A: I found this presentation about session security

*

*http://talks.php.net/show/phpworks2004-php-session-security/
It explains how to avoid:

*

*Session fixation.

*Session hijacking.

Also the slide with more information has some really goods links

*

*http://talks.php.net/show/phpworks2004-php-session-security/18

A: This code is no longer safe:
if mypage.php contains this code:

session_start();
$_SESSION['admin']==1;
echo "link";

If the link is clicked, the session admin as 1 will be carried to your page and the edit button will be appeared.
safest way is to set a token (this is a very simple step) right after login is authenticated.
e.g $token = sh512($var.....); $_SESSION['token']=$token;
on top of every page put something like this:
if(!isset($_SESSION['token'])){ die('Access Denied');}
if(!isset($_SESSION['username'])){ die('Access Granted');}

first check the token carry in the SESSION and then Check the user ID, including level of permissions for users. This is just a simple approach, put more fingerprint scan code at the beginning to make it complex to intercept sessionid.


text:
Q: Use of undeclared crate or module with workspaces I have the following structure:
-- project/
|
|-- Cargo.toml
|-- Cargo.lock
|-- src/
  |
  |-- main.rs
|-- crate1/
  |-- lib.rs
  |-- Cargo.toml
|-- tests
  |-- Cargo.toml
  |-- test.rs

and this are the content of the Cargo.toml
# Cargo.toml
...

[workspace]
members = [
  "crate1",

  "tests"
]

...

# crate1/Cargo.toml
[package]
name = "crate1"

...

[lib]
path = "lib.rs"

...

here I'm using another lib for my tests, I don't think the problem is here, because I already used this way to do my tests several times, and it worked perfectly, but for some reason, now this is happening to me, I don't know if everything is a typo error of my self or not, but I already checked it a lot of times
# tests/Cargo.tom
[package]
name = "tests"
version = "0.1.0"
edition = "2021"
publish = false

[dev-dependencies]
crate1 = { path = "../crate1" }

[[test]]
name = "crate1_test"
path = "crate1_test.rs"

[[test]]
name = "other_crate1_test"
path = "other_crate1_test.rs"

this is how one of the tests looks like
// tests/crate1_test.rs
use crate1::random_func;

[test]
fn random_func_test() {
    assert!(random_func());
}

And for some reason cargo don't recognize the "crate1" crate and throws me this error each time I import the crate:
error[E0433]: failed to resolve: use of undeclared crate or module `crate1`
 --> tests/crate1_test.rs:1:5
  |
1 | use crate1::random_func;
  |     ^^^^^^ use of undeclared crate or module `crate1`

For more information about this error, try `rustc --explain E0433`.
error: could not compile `project-manager` due to previous error

A: I found the problem, it was that I didn't make the crate1 as a dependency of the main project, this is how my root Cargo.toml looks now:
[package]
name = "project"
version = "0.1.0"
edition = "2021"

[workspace]
members = [
  "crate1",

  "tests"
]

[dependencies]
crate1 = { path = "crate1" }
reqwest = "0.11.13"
tokio = { version = "1", features = ["full"] }

and now I can build my tests correctly

A: In src/main.rs you have to add mod crate1; and potentially mod tests;


text:
Q: Powershell Can I loop multiple -headers Invoke-RestMethod? I'm a newbie at powershell/programming in general and  currently attempting to update admin passwords on Chatsworth CPI PDUs. The PDUs are daisy-chained together and accessed through the primary/alternate PDU IPs. Each PDU has a unique identifier that is passed as a header. After validation the API returns a Sessionid that must also be passed with the identifier to other endpoints. The Sessionid is only valid for 10 minutes
I'm looking for a way to loop both the identifiers and Sessionid with the Invoke-RestMethod to update all of the passwords.
What would be the best method to accomplish this?
This is what I am currently running to test retrieving the sessionids
 #Unique Identifier for each PDU
$Identifier = @("80224", "80245", "80181", "76998", "80226", "80949", "80479", "80556", "86619", "86621", "80521", "80925", "80293", "80924", "76893", "80514", "80363", "81280", "80476")

#Loop each identifier to endpoint
$Sessionid = foreach ($identity in $Identifier) {
    <# $$header is the current item #>

    $Newheader = @{
        "PDUSelector" = $identity

    }

    Invoke-RestMethod -Uri $Login -Method Post -SkipCertificateCheck -Body $body -ContentType application/json -Headers $Newheader

}
#Sessionids returned
$Sessionid.SessionID

This is an example of the sessionids that are returned:
+KZWXna9xd2yvw==
yL6FALD8n/5B2g==
AZyCuSvqScOXTA==
oPvKWulUCqpjzA==
8utMMVZ5o0aIag==
VVY7QQcsCPPHCw==
BRhvFvCLQGEkiQ==
FmFMLZc/3ITQrQ==
g+XrlAaImDcGAw==
bXYRvNw0yRIDUw==
mYTW3HtjT1Mopg==
3Bk9PX4bQXvp+g==
sqZJGKO/SnrDdQ==
COg4+s84jurHgA==
mKL6a35Y3m5gnw==
qqTjRHxtLV5sXw==
skyV2hB9/dqJ8A==
MolN0nt1rqBg/A==
VhbAj/43I/yGyw==

A: Something like this can get you started. If you wanted to multi thread each of the password updates, that would take a little more depending on which approach you want to take.
#Unique Identifier for each PDU
$Identifier = @('80224', '80245', '80181', '76998', '80226', '80949', '80479', '80556', '86619', '86621', '80521', '80925', '80293', '80924', '76893', '80514', '80363', '81280', '80476')

$splat = @{
    Uri = $Login
    Method = 'Post'
    SkipCertificateCheck = $true
    Body = $body
    ContentType = 'application/json'
}

#Loop each identifier to endpoint
$Sessionids = $Identifier | ForEach-Object { Invoke-RestMethod @splat -Headers @{ PDUSelector = $_ } }

# Given sessionIds ordinally match with $Identifier
$splat.Uri = $setPassword
$splat.Method = 'Put' # or whatever method is appropriate
$splat.Body = "Password=$password"

for( $ptr = 0; $ptr -lt $SessionIds.Count) {
    $headers = @{
               PDUSelector = $Identifier[$ptr]
               SessionId = $SessionIds[$ptr].SessionID
               }
    Invoke-RestMethod @splat -Headers $headers
}


text:
Q: Use of shall with "I and we"
I _ meet my friend tomorrow.

Usually shall is used with first person: I and we.
So, in the above sentence is it fair to use shall in the blank.
Actually  my book mentioned the answer as Will, therefore I wanted to clarify.
Thank you.

A: Longman English Grammar: Future tense: "will" is used with all persons, but
"shall"can be used as an alternative with "I" and "we". My view: "I/we shall do" is a bit elevated style and it is individual usage. I think that older people may use it more frequently as the younger generations. When shall and will are contracted to 'll you don't see any difference.
Perhaps I should mention why the conjugation of the future tense has this curious irregularity of "shall" in the first person.
Original the verb will refers to volition and "I will do it" had the sense of "I have the firm intention to do it". When "will" was adopted to express future tense "I will do it" became ambiguous, it could express intention or future tense. So "shall" was used in the first person to avoid this ambiguity. By the way Dutch uses "zullen" (shall) as auxiliary verb for all three persons of future tense.

A: From Merriam-Webster entry for shall (emphasis mine...)

Usage Discussion of shall
    From the reams of pronouncements written about the distinction between shall and will—dating back as far as the 17th century—it is clear that the rules laid down have never very accurately reflected actual usage. The nationalistic statements of 18th and 19th century British grammarians, who commonly cited the misuses of the Irish, the Scots, and occasionally the Americans, suggest that the traditional rules may have come closest to the usage of southern England. Some modern commentators believe that English usage is still the closest to the traditionally prescribed norms. Most modern commentators allow that will is more common in nearly all uses. The entries for shall and will in this dictionary show current usage.


text:
Q: Why "google.scrpt.run" does not work with google tasks auth in GAS script? I'm using google.script.run in html template file, and it works well as I expected.
but it doesn't work after adding the oauthScope "https://www.googleapis.com/auth/tasks" to appsscript.json file.
Error log is just uncaught, so couldn't investigate the cause more.

Is there any relation or dependency between both?
I need to add this to manage google tasks.
Let me share the detail information.

*

*there are 2 scripts
・container bound script for GSS
・library script referred by above container bound script.

*html template in library script
・call google.script.run.registerSome() in html template.
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <button onclick="showMessage()">showMessage</button>
    <script>
      function showMessage () {
        google.script.run.showMessage();
      }
    </script>
  </body>
</html>

*

*source code in library script
・show above html file as dialog on GSS Edit.

function onEdit(e, spreadsheetId) {
  const htmlTmpl = HtmlService.createTemplateFromFile('someHtml')
  const html = htmlTmpl.evaluate().setWidth(900).setHeight(600)
  SpreadsheetApp.getUi().showModalDialog(html, 'title')
}

function showMessage () {
  Browser.msgBox('Hello world')
}

*

*appsscript.json in library
・before adding the "https://www.googleapis.com/auth/tasks"

{
  "timeZone": "Asia/Tokyo",
  "dependencies": {
  },
  "webapp": {
    "access": "ANYONE",
    "executeAs": "USER_ACCESSING"
  },
  "exceptionLogging": "STACKDRIVER",
  "oauthScopes": [
                  "https://www.googleapis.com/auth/script.external_request",
                  "https://www.googleapis.com/auth/spreadsheets.currentonly",
                  "https://www.googleapis.com/auth/spreadsheets",
                  "https://www.googleapis.com/auth/script.container.ui"
                  ],
  "runtimeVersion": "V8"

*

*container bound script
・if this function is not declared, showMessage is not a function log is output on the browser console.
・_onEdit is bind to installable trigger onEdit.
(to use some process asking the user for authorization)

function _onEdit(e) {
  // `-` is symbol for library.
  _.onEdit()
}
function showMessage () {
  //no logic here
}

*

*replicating

*

*Add library script to container bound script(symbol is - in above sample)

*Bind _onEdit function to installable edit trigger.

*Open GSS

*Edit some cell

*Dialog is shown

*Press the showMessage button

*Hello world message is shown

*Adding the oauthScope "https://www.googleapis.com/auth/tasks" to appsscript.json file in the library.

*Then, do 3-6 process again

*Message is not shown and error log uncaught is output.

Does anybody know what the cause is?
Thanks,


text:
Q: Java Scanner input with if else statement Hi I'm new to java and trying to make a Quiz to practice. I wanna make a Question where the user has to combine words from to categories to pairs. Like A1 B4 C3 D2. What I did now is using an if else statement to check if the input is the correct answer, but it only works with 1A. For the others I can do 6 inputs, which is not what I want, and even if there's a correct one I don't get a point.
public class HelloWorld {

    public static void main(String[] args) {

        Scanner walther = new Scanner(System.in);

        String cro = "1A";
        String dan = "2C";
        String fin = "4D";
        String dut = "3F";
        String fre = "5B";
        String ger = "6E";
        int x = 0;

        if (cro.equalsIgnoreCase(walther.nextLine())){
            ++x;
            walther.close();
        }
        else if (dan.equalsIgnoreCase(walther.nextLine())){
            ++x;
            walther.close();
        }
        else if (fin.equalsIgnoreCase(walther.nextLine())){
            ++x;
            walther.close();
        }
        else if (dut.equalsIgnoreCase(walther.nextLine())){
            ++x;
            walther.close();
        }
        else if (fre.equalsIgnoreCase(walther.nextLine())){
            ++x;
            walther.close();
        }
        else if (ger.equalsIgnoreCase(walther.nextLine())){
            ++x;
            walther.close();
        }
        else {
            walther.close();
        }

    System.out.println(x + " Point!");
    }
}

A: Calling nextLine() consumes a line from the scanner. You do this on the first if, so the subsequent else if branches are, in fact, comparing the following lines (or null, if you don't have any additional input). Instead, you should consume the line only once, save it to a local variable and use that in your comparisons:
String input = walther.nextLine();
if (cro.equlasIgnoreCase(input)) { // etc...

Having said that, using and if-else structure isn't the neatest solution. You can save  a lot of code bloat by using a case insensitive TreeSet:
TreeSet<String> set = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
set.addAll(Arrays.asList("1A", "2C", "4D", "3F", "5B", "6E"));
String input = walther.nextLine();
if (set.contains(input)) {
   ++x;
   walther.close();
}

A: People the fact remains that the above provided answer is confusing especially to those who are relatively new to the java community.
Hence the requirement is for an easier and simpler answer.
Now, Java understands Strings only by the following code :
Scanner sc=new Scanner(System.in);
String a=sc.next();

if (a.equals("xyzzy"))
{
  System.out.println("yes");


text:
Q: Save traffic source data With the old version of Google Analytics it was possible to extract information about users acquisition channels using the source, medium, term, content, campaign, and gclid parameters that were stored in the __utmz cookie.
This is not possible with the new version of Google Analytics, that uses only the _ga cookie and store the previously mentioned data only server side.
Is there a way to retrieve the same data? For exaple for the source I could use the referer header, right? What about the other parameters?
Do you know if this is possible maybe using any other analytics platform (e.g. Clicky or Piwik)?


text:
Q: import google skd in cakephp 2 I'm a bit new to cakephp and I'm struggling to find a good tutorial which explains how to import the Google PHP SDK into my cakephp 2 project.
I only want to use the Google+ bit to allow users to authenticate with Google. I've downloaded the SDK from https://github.com/google/google-api-php-client and placed the src folder inside a Google Folder in the Vendor Folder. So like this: app/Vendor/Google/src/...
Then in my controller I try to load the class using:
App::import('Vendor','Google');
$client = new Google_Client();

I have tried a bunch of other variations which I've found online but I believe they are old because the folder structure of the SDK is different.
Can anyone please tell me how I can include it properly.
thanks

A: You can try  require .'path_to_google_sdk/autoload.php';


text:
Q: What is $i$ exponentiated to itself $i$ times? I was just wondering about this. I searched about it on the net and found that it is called tetration and after this comes pentation and then hexation and so on so forth.
I don't really understand tetration but I'm curious about the answer.
What is $i$ raised to itself $i$ times?
Also if it makes any sense, what is $i$ 'pentated' or 'hexated' to itself $i$ times? Is there even an answer to this? And if yes, till which 'stage' can we do this ('stage' in the sense 'tetration', 'pentation')? Can we do this indefinitely? Is there a formula for it?
I will apologise if this question has been asked earlier.

I think my question is a little unclear. Here's what I'm saying:
$i$ exponentiated to itself $1$ time: $i^1$
$i$ exponentiated to itself $2$ times: $i^{i^{1}}$
$i$ exponentiated to itself $3$ times: $i^{i^{i^{1}}}$
$i$ exponentiated to itself $i$ time(s): ?

Edit: The 'possible duplicate' links provided are not asking the same thing. Here's another try:

Now consider the case where $a = i$ and $n = i$.
I'm not asking what is $i$ multiplied by itself $i$ time(s) (which is equal to $i^i$). I'm asking what is $i$ to the power of $i$ to the power of $i$... this is done '$i$ times'.

A: Well, why not. The goal of such topics is to take a function $f(z)$ defined in some region of the complex plane, often including the real line or part of it, then defining $f_1(z) = f(z)$ and $f_0(z) = z.$ The desire is to be able to define $f_s(z)$ for real or even complex $s,$ such that we get a group
$$  f_{s+t}(z) = f_t(f_s(z)) = f_s(f_t(z)).  $$
Now, the only setting where this is an unreserved success is when $f$ is a linear fractional transformation. The traditional topic of fractional iteration is asking about $$ f_{1/2}(z).   $$ As Baker found, and his student Liverpool finished up, it is fairly common to have such fractional iterates without being able to extend to irrational $s$ or non-real $s.$
I am actually not completely certain how exponentiation towers are set up in this setting. Still, one way or another, you are asking to extend from $s$ a positive integer to $s=i,$ and there is simply no guarantee that there is any way to do this. Certainly none has been found.
As I said in comment, see BAKER_ECALLE. This topic is most naturally part of complex dynamics, although it may not appear that way now.

A: As Will Jagy already pointed out, there is no accepted solution for this. There is a formal procedere which can sometimes lead to a meaningful/approximate answer; but this is then dependent on the convergence of some series, which occur in that procedere, and also, in which way we want to make sense of noninteger powers of negative or complex numbers.
I mean the procedere which applies the Schröder-function on a recentered powerseries.
The formal way to do this is to

*

*determine a fixpoint t for the exponentiation with base b such that $b^t = t$ (here our base is $b=i$ ). Also denote the log of $t$ as $\log(t)=u$

*define the helper function $f(x) = t^x-1 $

*compute the (lower) triangular Carleman-/Bell-matrix for $f(x)$ , call it for instance $U$

*diagonalize the matrix $U$ into $M$, $D$, $W (=M^{-1})$ . Then in the diagonal of $D$ are the consecutive powers of $u$

*define the Schröder-function $s$ from the second column of $M$ such that
   $ s(x) = \sum_{k=1}^\infty m_{k,1} x^k $   and its inverse from the second column of $W$ such that $ s^{-1}(x) = \sum_{k=1}^\infty w_{k,1} x^k $

*compute the schröder-value $\sigma = s(x/t-1) $ for some argument $x$. (For instance $x=1$ -this is also tacitly assumed if we write b^^h for the h'th tetrate with base b)

*compute the function value for the h'th tetration-height by $x_h = (s^{-1}(\sigma u^h)+1) \cdot t$

I've just tried this with the base $b=i$ in Pari/GP (that gave also $ \small t \sim 0.438282936727 + 0.360592471871 i $ and $ \small u \sim -0.566417330285 + 0.688453227108 i$)
and for small integer heights h this gives good approximations (although we have complex powerseries involved(!)). However, we see in the last step, that the log $u$ of the fixpoint has to be taken to the h'th power - and this means for your question a complex value to the $i$'th power. This is not unique and the powers of this ("incidentally" selected) value occur then in the formula for the inverse Schröder-function.
Now, after I simply inserted $h=i$ and let Pari/GP determine the result using $\sigma u^i $ for the $i$'th tetrate (beginning from $x_0=1$) with basis $i$ then I arrive at something like $x_i = i^{\text{^^}i} \sim   0.500129061734+0.324266941213 i $ .
This whole procedure has - even for the case of a real base and real fixpoints, the further unsolved disadvantage, that the result will be depending on the selection of the fixpoint $t$ . Moreover, even for simple fractional $h$ , say $h=0.5$ , the occuring series are not or only roughly converging correctly, such that the half-iterate from $x$ to $x_{0.5}$ and then the further half-iterate from $x_{0.5}$ to $x_1$ is only approximate with (practically necessarily) truncated power series. So besides the non-uniqueness at the point, where we raise the complex $u$ to the $i$'th power in  our specific example, there is also basically a problem of convergence with that whole procedure.
Note, there is one claim that a general solution for the tetration to complex heights was found; look at citizendium at the article of Dmitri Kouznetsov, but I've not yet seen that it had externally been confirmed (and I cannot do it myself). Also we have in the tetration-forum the claim, that we can uniquely determine fractional tetrates at least for some "nontrivial" bases, which is basically derived from Kneser's ansatz for the fractional iteration with base $b=e$. Look at the posts of user "Sheldonison" (Levenstein) who even provides a set of Pari/GP-procedures to compute fractional tetrates for a range of bases outside the "easy" range $1 \ldots e^{1/e} $ of real bases. Unfortunately I'm not yet capable to judge over that claims of Kouznetsov and of Levenstein.

[update] There has been an attempt today to insert in my answer a statement, that the Kouznetsov-method were "the official" tetration, based on some consideration of reasons. I reject that. Without more qualified echo in the professional mathematical community it is not my part to claim such and generate avoidable obfuscation. Please do not attempt to extend the focus of my answer in such a way - you can always put it in another answer.


text:
Q: Editando exif de uma imagem Preciso editar as informações exif de uma imagem, como localização e data, por exemplo, mas não estou conseguindo achar nenhuma biblioteca que faça isso com Python 3.4 e Windows. O máximo que eu consegui foi utilizando a Pillow ler essas propriedades, entretanto, quando eu edito e tento salvar a imagem da seguinte forma:
image.save(path+'/teste.jpg', 'JPEG', exif=tags)

Onde tags é um dict, ele diz que o parâmetro exif não aceita o tipo dict, até porque ele é um binário. Eu recupero o exif da seguinte forma:
tags = image._getexif()

Se eu tentar salvar direto com esse exif, ele apontará o mesmo erro, só que se eu utilizar:
tags = image.info['exif']

Eu consigo utilizar tags para salvar, entretanto vem em um formato que é impossível editar. Então, existe alguma lib pra Windows e Python 3 que resolva esse problema?

A: Pelo visto, uma boa opção é a piexif -
https://pypi.python.org/pypi/piexif/1.0.1
Fiz um teste rápido aqui, só instalei e li as informações de uma imagem. Os exemplos na documentação mostram como obter as informações e salva-las de volta usando-a em conjunto com a PIL.
A biblioteca é Python puro, independente de sistema operacional  - teste no Pyhon 3.3 em Linux 64bit.


text:
Q: How to convert below code in CakePHP 3?

      Title

        <input type="text" style="width: 45%;" class="form-control" id="titleId" name="title" placeholder="Title">

I have this type of code in my add.ctp file and I don't know how to convert it into like
<? echo $this->Html->input('title',['class'=>'']);

A: You have to use Form helper instead of CakePHP Html helper. Form helper helps you to create form field as well as help to validate the form. But Html helper helps you to create Html like Html for image displaying. Here we go
$this->Form->input('title', [
    'label' => [
        'text' => 'Title',
        'class' => 'col-lg-2'
    ],
    'style' => [
        'width: 45%;'
    ]
]);

I would like to advise you to go to this link, have a deeper look on the docs :)
Here is the Form helper of CakePHP 3
Here is the Html helper of CakePHP 3


text:
Q: parse json response in jquery Laravel 5.1 I have read other questions but my problem is little different. I am getting the response in a format like this from an eloquent query in Laravel.
[{"id":1,"message":"sdfsdf","message_for":1,"message_by":2},{"id":2,"message":"hello","message_for":4,"message_by":2},{"id":4,"message":"hi how are you?","message_for":1,"message_by":2}]

There is no variable attached to each object like in this question div1 , div2 etc.
This is my ajax code
$.ajax({
        url: '/chat',
        type: 'POST',
        dataType: 'json',
        data: { id: sessionStorage.getItem('user_id') },
        //cache: false,
        success:function(data){
            /*var x;
            for(x in data){
                /!*$("span.messages").fadeIn("slow").append(data[x]);
                $("span.messages").append("
");*!/

            }*/
        },
        error: function(data) {
            console.log('data is :'+data.id);
            console.log("error");
        }
    });

And this is my controller function from where I am returning the response.
public function getUserMessages(Request $request){

        $id = (int)$request->request->get('id');
        $messages = Message::where('message_by' , $id)->get()->toJson();

        return $messages;
    }

I tried using data["message"] but it does not work. Using data[0] will return [.

A: I used foreach to get the data
$.each(data, function(i, obj) {
  alert(obj.message);
});

A:
Using data[0] will return [

That seems like data is a String, not an Object.
One solution is to modify your PHP code so it tells the browser it is sending JSON:
header('Content-Type: application/json');

Another solution is to explicitly parse the JSON to get the object.
var data = JSON.parse(response);

Additionally, you have an array.  The conventional way to iterate through an array is to increment an index.  The newer way is to use the built-in .forEach() method.  Alternatively, use jQuery's $.each() as another answer suggested.
success:function(response){
        var data = JSON.parse(response);
        var x;
        for (i = 0; i < data.length; i += 1)
            {
            var record = data[i];
            $("span.messages").fadeIn("slow").append(record.message);
            $("span.messages").append("
");
        }
    },

A: you are getting a collection of object from the controller. so you can do like this.
   success:function(data){
        var x;
        for(x in data){
            $("span.messages").fadeIn("slow").append(data[x]['message']);
            $("span.messages").append("
");

        }

  },

the x will be your index.. based from your return.. you can call
data[x]['id']
data[x]['message']
data[x]['message_for']
data[x]['message_by']

depending what you need