text:
Q: Determinant of $V^* V$ where $V$ is rectangular Vandermonde matrix with nodes on unit circle Let $z_{1},\dots,z_{k}$
  be distinct complex numbers with $\left|z_{j}\right|=1,\;j=1,\dots,k$. For any natural $N\geqslant k$
  consider the rectangular Vandermonde matrix
$$
V_{N}=\begin{pmatrix}1 & 1 & \dots & 1\\
z_{1} & z_{2} &  & z_{k}\\
\vdots & \vdots &  & \vdots\\
z_{1}^{N-1} & z_{2}^{N-1} &  & z_{k}^{N-1}
\end{pmatrix}.
 $$
Let $V_{N}^{*}$ denote the conjugate transpose of $V_{N}$. Since
$V_{N}$ has full rank, the square $k\times k$ matrix $V_{N}^{*}V_N$
is nonsingular. We are interested in the quantity
$$
D\left(N\right)=\det\left(V_{N}^{*}V_N\right).
$$
For $N=k$ we have by the well-known explicit formula
$$
D\left(k\right)=\prod_{i<j}\left|z_{i}-z_{j}\right|^{2}.
$$
Question: Does there exist an explicit ``simple'' expression
for $D\left(N\right)$ with arbitrary $N>k$?
Example of a simple expression in the special case $k=2$:
Without loss of generality $z_{1}=1$
and $z_{2}=\exp\left(\imath x\right)$ for $x\in\left[-\pi,\pi\right]\setminus\{0\}.$
An explicit computation gives the following:
$$
D\left(N\right)=N^{2}-\frac{\sin^{2}\frac{N}{2}x}{\sin^{2}\frac{x}{2}}.
$$

A: This is a partial answer only - but there is a clear place to start.
The Cauchy-Binet theorem gives the answer as a sum of products of all maximal minors of the two matrices, where the minors are taken with matching sets of rows/columns.  All of these minors are themselves ordinary, N by N Vandermonde determinants.  So the answer is the symmetrization of the squared Vandermonde determinant, over all possible choices of N of the k variables.
This is probably not simple enough for you, but at least it's a formula.  I haven't assumed anything about the z variables, nor attempted to do any simplification.

A: I guess that the determinant only factors if there is a stronger relation between the $z_j$. As example one can give a closed expression for $D_k(N)$ if  $z_j = \exp(\iota (j-1) x)$. For $N$ even and $k=3$ one finds
$$
D_k(N) = N^k
 -N \left[ 2 \frac{\sin^2\frac{Nx}{2}}{\sin^2\frac{x}{2}}
+ \frac{\sin^2 (Nx)}{\sin^2 x} \right]
+ 2\frac{\sin^2\frac{Nx}{2}}{\sin^2\frac{x}{2}}
\frac{\sin(Nx)}{\sin x}.
$$
I think the cases $k>3$ can also be derived. Note that for equidistant $z_j$ the Vandermonde becomes the discrete Fourier transform, at least if $N=k$.


text:
Q: rspec - add multiple types to a test wondering if it's possible to have a test tagged with multiple types, for example:
  it 'should run as part of smoke or integration tests', :type => 'smoke,integration' do
    response = @sample_request.echo("EXAMPLE5", "EXAMPLE6")
    expect(response.status).to equal(200)
  end

and have it run when either of the the two filters is applied:
bundle exec rspec --tag type:smoke

OR
bundle exec rspec --tag type:integration

A: You should be able to do this using an array.
it '...', :type => ['smoke', 'integration'] do

redpajama_set_name: RedPajamaStackExchange


text:
Q: _spPageContextInfo in modern pages Using SPFx extension (application customizer) added JS files to all SharePoint pages (including modern pages), something like mentioned in below blog:
 Step by Step Procedure to Add a JS file to all pages in a SPFx Modern Pages using SharePoint Framework Extension.
I am using some custom JavaScript logic which runs in almost all pages, I am using _spPageContextInfo object extensively, it works fine in classic pages.
In modern page I get _spPageContextInfo is undefined.
Are there any alternative ways I can get _spPageContextInfo object value using normal JavaScript in modern pages.
In SPFx we can use this.context.pageContext.legacyPageContext but not in JavaScript

A: Try using below solutions:
Solution 1:
Use legacyPageContext to access the pageContext information:
// This is how you can access the page context info
this.context.pageContext.legacyPageContext;

// Retreive current user display name
this.context.pageContext.legacyPageContext["userDisplayName"]);

Source: Access _spPageContextInfo details in SharePoint Framework - Check the list of properties you can access using legacyPageContext.
Solution 2:
Use _spPageContextInfo under window object:
const pageContext: any = (window as any)._spPageContextInfo;

Source: SPFx Extensions - Multi-Lingual Support.
Solution 3:

*

*Get the pageContext from this.context.pageContext.legacyPageContext;.

*Push the whole object under window or document object.

*Access it from window or document.


text:
Q: Get current country in Android - traveling I'm making an app in which I assign different values to each country and do something based on that value. Like:
Argentina 3
Australia 7
USA 23

To choose the country, I need to use the user's current country, for that I'm using Google's geocoder:
geocoder.getFromLocation

Geocoder documentation
But if I have many users (hopefully), it will be a problem, because of the API usage restriction of 2500 (With/Without an API key: 2,500 requests per 24 hour period.)
Geocoder API Limits
Question 1: About the usage restriction, Is that number the maximum amount of requests for all the users using my map?
EDIT: I found this

As geocoding limits are per user session, there is no risk that your
  application will reach a global limit as your userbase grows.
  Client-side geocoding will not face a quota limit unless you perform a
  batch of geocoding requests within a user session. Therefore, running
  client-side geocoding, you generally don't have to worry about your
  quota.
  usage Limits

Question 2: Let's say I do use Geocoder.getFromLocation(), Is there a list of the country names that Google uses? For example, they could have "USA", "US" or "United States", or even "The United States of America". I need this is in order to access the country's value in the table above.
I'm thinking about initially obtaining the country using the typical ways:
telephonyManager.getSimCountryIso();

or
context.getResources().getConfiguration().locale.getCountry();

and adding a refresh button so the user can update it when traveling (using geocoder).
Question 3: Do you have any other suggestions? alternatives?

A: For #2-  its a country code.  This is an ISO standard.  It will be the 2 letter code.  The list can be found here http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2

A: New answer as promised to fersarr a new solution, this works with the GPS and google maps API, also not my best code but
private GeoPoint getLocation() {
try {
    LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria,true);
//In order to make sure the device is getting the location, request updates.
// this requests updates every hour or if the user moves 1 kilometer
Location curLocation = locationManager.getLastKnownLocation(provider);
GeoPoint curGeoPoint = new GeoPoint((int)(curLocation.getLatitude() * 1e6), (int)(curLocation.getLongitude()*1e6));
return curGeoPoint;
} catch (NullPointerException e) {
    Log.e("your app name here","Log your error here");
}
return null;
}

public static String getCountryName(Context context, GeoPoint curLocal) {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = null;
try {
    addresses = geocoder.getFromLocation((double)curLocal.getLatitudeE6() / 1e6,(double)curLocal.getLongitudeE6()/ 1e6,1);
} catch (IOException ignored) {
    Address result;
    if (addresses != null && !addresses.isEmpty()) {
        return addresses.get(0).getCountryName();
    }
    return null;
}
return addresses.get(0).getCountryCode();
}

You will need to do some clean up in this code, as this is on the fly no clean up going on code. but what this does, is first method getLocation will pull in your current Geo point from the GPS (if you can not use a GPS system on the device this will not work) then you can pass the geopoint and the context (your activity) to the getCountryName that should return the country name (in my case it was also US) it returns a list you might have to deal with more then on country code coming back for disputed locations.

A: I did a quick Google search and found
Where am I? - Get country
basically if you call
String locale = getResources().getConfiguration().locale.getCountry();
Log.d("IssuesEtc","the local is " + locale);

it should give you the country code.  I ran the above snipit, and I got back
    the local is US
so it appears to work on my phone (Samsung S blaze, cyagin mod, on T-Mobile)
I should also note the the call was done inside of a class that extended Activity, if you are out side of a class that has in it ansestory context you will need to obtain the context to run the getResources() method.


text:
Q: Getting the body of an http POST request, using mod-perl 2 I am writing a quick script to munge a submitted file, and return that content to the user.
My test code looks like this:
#!/path/to/bin/perl
use strict;
use warnings;
use utf8;

use Apache2::RequestRec;
use Apache2::RequestIO;

my ( $xmlin, $accepts ) = (q{}, q{});
my $format = 'json';

# read the posted content
while (
    Apache2::RequestIO::read($xmlin, 1024)
      ) {};

{
  no warnings;
  $accepts = $Apache2::RequestRec::headers_in{'Accepts'};
}
if ($accepts) {
  for ($accepts) {
    /application\/xml/i && do {
      $format = 'xml';
      last;
    };
    /text\/plain/i && do {
      $format = 'text';
      last;
    };
  } ## end for ($accepts)
} ## end if ($accepts)
print "format: $format; xml: $xmlin\n";

This code fails to compile with Undefined subroutine &Apache2::RequestIO::read
If I comment out the while loop, the code runs fine.
Unfortunately the Apache2::RequestIO code is pulled in via Apache2::XSLoader::load __PACKAGE__; so I can't check the actual code.... but I don't understand why this doesn't work
(and yes, I've also tried $r->read(...), to no avail)

A: I think I have a good idea of why your code is not working.
The module Apache2::RequestIO added new functionality to Apache2::RequestRec.
In other words to add new methods/functions to the Apache2::RequestRec namespace.
I would first change Apache2::RequestIO::read to Apache2::RequestRec::read.
If that does not work move use a handler.
I have code that works which does a similar the thing
In your httpd.conf
PerlSwitches -I/path/to/module_dir
PerlLoadModule ModuleName
PerlResponseHandler ModuleName

ModuleName.pm
package ModuleName;
use strict;
use warnings;
use Apache2::RequestIO();
use Apache2::RequestRec();
use Apache2::Const -compile => qw(OK);
sub handler {
    my ($r) = @_;
    {
        use bytes;
        my $content = '';
        my $offset = 0;
        my $cnt = 0;
        do {
            $cnt = $r->read($content,8192,$offset);
            $offset += $cnt;
        } while($cnt == 8192);
    }
   return Apache2::Const::HTTP_OK;
}

A: I also use Apache2::RequestIO to read the body:
sub body {
    my $self =  shift;

    return $self->{ body }   if defined $self->{ body };
    $self->apr->read( $self->{ body }, $self->headers_in->get( 'Content-Length' ) );

    $self->{ body };
}

In this case you should subclass original Apache2::Request. Especially pay attention to our @ISA = qw(Apache2::Request);
I do not know why, but standard body method return me:
$self->body        # {}
$self->body_status # Missing parser

when Content-Type is application/json. So I work around that in such way. Then parse body myself:
sub content {
    my $self =  shift;

    return   $self->{ content }   if defined $self->{ content };

    my $content_type =  $self->headers_in->get('Content-Type');
    $content_type =~ s/^(.*?);.*$/$1/;

    return   unless exists $self->{ $content_type };

    return $self->{ content } =  $self->{ $content_type }( $self->body, $self );
}

where:
use JSON;
sub new {
    my ($proto, $r) = @_;

    my $self = $proto->SUPER::new($r);
    $self->{ 'application/json' } =  sub {
        decode_json shift;
    };
    return $self;
}


text:
Q: How can I get the location of a tile from a cell in libGDX using floats? I am currently making a game. It is a 2D tile based game. I tried to make it so that when you step on water your players speed and size changes.
I am running this every 60th of a second:
if(map.getTileTypeByCoordinate(0, player.sprite.getX()/4.0f, player.sprite.getY()/4.0f) == TileType.WATER){
    player.sprite.setScale(2, 1.75f);
    player.speed = 3;
} else {
    player.sprite.setScale(2, 2);
    player.speed = 5;
}

The map.getTileTypeByCoordinate(int layer, float x, float y); method is the following:
public TileType getTileTypeByCoordinate(int layer, float col, float row) {
    Cell cell = ((TiledMapTileLayer) tiledMap.getLayers().get(layer)).getCell((int)(col), (int)(row));

    if(cell != null){
        TiledMapTile tile = cell.getTile();

        if(tile != null){
            int id = tile.getId();
            return TileType.getTileTypeById(id);
        }
    }

    return TileType.GRASS;
}

If I don't cast col and row to integers, then I get an error, obviously.
The reason this is a problem is because I am using Box2D to check collisions. I divide everything by my scale (10.0f) so that the physics simulations are more accurate and I can make the player move faster.
I was wondering if there is a way to get a tile from a float location instead of an int location. Will I have to stop using Box2D for collision detection? I am fine with this, but I am not any good with programming my own collision detection, so if this is the case, how would I go about making my own?

A: If you are using a scale to use Box2D then you'll need to scale your coordinates back up.
If you're sprite is at pixel 100 then it's box2d coordinate is 10m. Tiled wants coordinates in pixels so just multiply by your scale.
player.sprite.getX() * scale
Of course there might be some casting with the scale.
Hope this helped and comment if you've any further questions!


text:
Q: Plots don't consistently appear in PyCharm IPython notebook MATLAB -> Python convert trying to get IPython notebooks to work.  Running PyCharm 2016.3.2 and Python 2.7.13 through Anaconda2 on Windows 7.
I have an IPython notebook that runs just fine on my machine Jupyter that I'm trying to run outside of a browser.  The minimum working example that shows the behavior is broken out into two cells.  First cell is the function definition (cut down for demo purposes) and the second (and subsequent cells not shown) repeatedly call the first:
def spectrumPlot(NspectraFiles, laserLines, gaussAmp):

    import numpy as np
    import matplotlib.pyplot as plt

    def rgb(r, g, b):
        outMap = (float(r)/255, float(g)/255, float(b)/255)
        return outMap

    def gaussian(x, mu, sig):
        return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))

    def genData(gaussAmp):

        csv = np.empty([550, 3])
        csv[:,0] = np.linspace(350, 900, 550)
        csv[:,1] = gaussAmp*gaussian(csv[:,0], np.random.rand(1)*550 + 350, 100)
        csv[:,2] = gaussAmp*gaussian(csv[:,0], np.random.rand(1)*550 + 350, 100)

        return csv

    fluorColorCycle = [rgb(155, 89, 182),
                       rgb(52, 152, 219),
                       rgb(46, 204, 113),
                       rgb(230, 126, 34),
                       rgb(192, 57, 43)]

    for k in range(0, NspectraFiles):

        dataHere = genData(gaussAmp)

        plt.plot(dataHere[:,0], dataHere[:,1], color=fluorColorCycle[k], ls = '--', linewidth=0.5)
        plt.plot(dataHere[:,0], dataHere[:,2], color=fluorColorCycle[k], linewidth = 2)

    # Add in lasers

    for k in range(0, len(laserLines)):

        plt.plot([laserLines[k], laserLines[k]], [0, 100], color = fluorColorCycle[k], linewidth = 5)

    plt.xlabel('Wavelength (nm)', fontsize=14)
    plt.ylabel('Intensity (a.u.)', fontsize=14)
    plt.rcParams["figure.figsize"] = [10, 5]
    plt.xlim(350, 900)

    plt.show()

NspectraFiles = 5

laserLines = [405, 488, 561, 637, 730]

spectrumPlot(NspectraFiles, laserLines, 45)

What should happen after executing these two cells is that I get a plot that appears showing some vertical colored bars at the indicated 'laserLines' positions and amplitude of 100 and NspectraFiles randomly-placed Gaussian peaks of amplitude of the third argument to spectrumPlot (45 here).  But if that third argument is greater than 45, then the plot doesn't always appear.  If it's between ~44-50 then the plot will appear but won't
I've tried setting
%matplotlib inline

under the import statements in the first cell.  This makes the plots reliably appear but I cannot seem to re-size them with the
plt.rcParams["figure.figsize"]

property.
Any help on why the plots wouldn't appear based on a calculation parameter?  Or a work-around that allows me to still modify the plot size?


text:
Q: How do I remove an apostrophe from the filename? I need to remove the spaces and any apostrophes from the filename of my file that is uploaded. I have figured out how to remove the spaces but I am not sure how to remove the apostrophes. I am using coldfusion. Below is my code for removing the spaces. How should I modify this code to also remove any apostrophes. Thanks in advance for any help.
  <cfset mySpaceFreeVariable = ReReplace(filename, "[[:space:]]","","ALL")>

A: <cfset mySpaceFreeVariable = ReReplace(filename, "[\s']","","ALL")>


text:
Q: MySQL Import only one column to existing table I have the following problem.
I have a table which contains the following fields (example):
id, id2, id3, id4

Due to a mistake, I have accidently deleted all values of id3. (They are NULL now).
I have a second file (backup) which is a bit older, so it doesn't have the same count as the damaged table. The id3 is present there.
How do I "join" these tables, to restore at least the bigger part? Insert id3 ONLY to the damaged table from the non-damaged table?
I tried this:
UPDATE table1 SET `id3` = SELECT `id3` FROM table2

In my case, only phpMyAdmin or SQL Syntax solution (no console) would work...
Please help!

A: If we assume that one, two, or three of the ids define each row, then you can use join:
update table1 t1 join
       table2 t2
       on t1.id = t2.id
    set t1.id3 = t2.id3;

This assumes that id is unique in the two tables.  You might want to use a more complex expression:
update table1 t1 join
       table2 t2
       on t1.id = t2.id and t1.id2 = t2.id2 and t1.id4 = t2.id4
    set t1.id3 = t2.id3;

A: Assuming id is an unique attribute.
You can simply run this query:
UPDATE table1 SET id3 = (SELECT id3 FROM table2 WHERE table2.id = table1.id)


text:
Q: Right-align NA values in 4d array Context: I'm working with survey data organized as a 4D array with this structure: m[n_sites, n_surveys, n_years, n_species].
Question: There are data missing randomly, though, and I want to move the missing data to the end of each row.
Example: Here's the original data:
, , 1, 1

   1  2  3  4  5
1 NA  2 NA  2  3
2 NA  3  1 NA NA
3  4 NA NA  4  6
4  2 NA NA  2  1

... and I want to rearrange this to be:
, , 1, 1

   1  2  3  4  5
1  2  2  3 NA NA
2  3  1 NA NA NA
3  4  4  6 NA NA
4  2  2  1 NA NA

Note: The data are very large, though, so I need something efficient and fairly simple.
Reproducible code:
library(magrittr)  ## for %>% pipe
library(reshape2)  ## for acast
set.seed(1)

# Simulate survey data
df <- expand.grid(
  species = c(1,2),
  year = c(1,2,3),
  site = c(1,2,3,4),
  survey = c(1,2,3,4,5))
df$counts <- rpois(n = nrow(df), lambda = 3)

# Add random NAs (missing data)
posNA <- sample(x = 1:nrow(df), size = 0.5 * nrow(df), replace = FALSE)
df$counts[posNA] <- NA

# Cast to 4d array
m <- df %>% acast(site ~ survey ~ year ~ species)

A: You may use na.omit on rows and the 3rd and 4th dimension, correct the length by cumber of columns and transpose result using aperm.
## 4D-array
apply(m, c(1, 3, 4), \(x) `length<-`(na.omit(x), dim(m)[2])) |> aperm(c(2, 1, 3, 4))
# , , 1, 1
#
#   [,1] [,2] [,3] [,4] [,5]
# 1    2    2    3   NA   NA
# 2    3    1   NA   NA   NA
# 3    4    4    6   NA   NA
# 4    2    2    1   NA   NA
#
# , , 2, 1
#
#   [,1] [,2] [,3] [,4] [,5]
# 1    3    0    3   NA   NA
# 2    3    3    2    3   NA
# 3    3    4   NA   NA   NA
# 4    6    3    1   NA   NA
#
# , , 3, 1
#
#   [,1] [,2] [,3] [,4] [,5]
# 1    2   NA   NA   NA   NA
# 2    2    1   NA   NA   NA
# 3    4    2   NA   NA   NA
# 4    4    0    4    3   NA
#
# , , 1, 2
#
#   [,1] [,2] [,3] [,4] [,5]
# 1    2    2   NA   NA   NA
# 2    4    3    8   NA   NA
# 3    2    1    2    3   NA
# 4    4   NA   NA   NA   NA
#
# , , 2, 2
#
#   [,1] [,2] [,3] [,4] [,5]
# 1    5    5   NA   NA   NA
# 2    4   NA   NA   NA   NA
# 3    2    1   NA   NA   NA
# 4    5   NA   NA   NA   NA
#
# , , 3, 2
#
#   [,1] [,2] [,3] [,4] [,5]
# 1    5    2    2    2   NA
# 2    1    4    2    3   NA
# 3    8    2    3   NA   NA
# 4    5   NA   NA   NA   NA

Here additionally at a simpler array to demonstrate the logic:
## 3D-array
a
# , , 1
#
#      [,1] [,2] [,3] [,4]
# [1,]   NA   NA    1    3
# [2,]    4    1    1   NA
# [3,]   NA    3   NA    4
#
# , , 2
#
#      [,1] [,2] [,3] [,4]
# [1,]    3    2    2    4
# [2,]    1   NA    3    4
# [3,]    1   NA    4    3

apply(a, c(1, 3), \(x) `length<-`(na.omit(x), dim(a)[2])) |> aperm(c(2, 1, 3))
# , , 1
#
#      [,1] [,2] [,3] [,4]
# [1,]    1    3   NA   NA
# [2,]    4    1    1   NA
# [3,]    3    4   NA   NA
#
# , , 2
#
#      [,1] [,2] [,3] [,4]
# [1,]    3    2    2    4
# [2,]    1    3    4   NA
# [3,]    1    4    3   NA

Data:
m <- structure(c(NA, NA, 4L, 2L, 2L, 3L, NA, NA, NA, 1L, NA, NA, 2L,
NA, 4L, 2L, 3L, NA, 6L, 1L, 3L, 3L, NA, 6L, 0L, 3L, NA, 3L, NA,
2L, 3L, 1L, 3L, 3L, 4L, NA, NA, NA, NA, NA, 2L, 2L, 4L, 4L, NA,
NA, NA, 0L, NA, NA, NA, NA, NA, NA, NA, 4L, NA, 1L, 2L, 3L, NA,
4L, 2L, NA, NA, 3L, 1L, NA, NA, NA, 2L, 4L, 2L, NA, NA, NA, 2L,
8L, 3L, NA, 5L, NA, NA, NA, NA, NA, NA, NA, 5L, NA, 2L, NA, NA,
4L, 1L, 5L, NA, NA, NA, NA, 5L, 1L, 8L, NA, 2L, 4L, NA, NA, 2L,
NA, 2L, 5L, NA, 2L, NA, NA, 2L, 3L, 3L, NA), dim = c(4L, 5L,
3L, 2L), dimnames = list(c("1", "2", "3", "4"), c("1", "2", "3",
"4", "5"), c("1", "2", "3"), c("1", "2")))

a <- structure(c(NA, 4L, NA, NA, 1L, 3L, 1L, 1L, NA, 3L, NA, 4L, 3L,
1L, 1L, 2L, NA, NA, 2L, 3L, 4L, 4L, 4L, 3L), dim = c(3L, 4L,
2L))

A: We could use
m1 <- m
for(i in seq_len(dim(m)[3]))
    for(j in seq_len(dim(m)[4]))
      m1[,, i, j]  <- t(apply(m1[,, i, j], 1,
              function(x) x[order(is.na(x))]))

-output
> m1[,, 1, 1]
  1 2  3  4  5
1 2 2  3 NA NA
2 3 1 NA NA NA
3 4 4  6 NA NA
4 2 2  1 NA NA


text:
Q: How do I number Excel rows with a prefix? I need the following text displayed in column A, as follows. It just needs to be plain text.
Cell A1: "R1" {without quoutes}
Cell A2: "R2" {without quoutes}
Cell A3: "R3" {without quoutes}

and so on, for thousands of cells.
How can I achieve this?

A: If I understand your question correctly, you will want to put the following formula in cell A1:
=CONCATENATE("R";ROW(A1))

This should place R1 in cell A1.
Now copy this cell, make a selection of all cells that should have this and paste.
If for example you select cells A2 to A99, Cell A87 will have the text R87 in it.
The formula explained:
=CONCATENATE(              concatenate joins text and formulas together

             "R"           start with the string R

                ;          function separator

                 ROW(A1)   row(a1) returns the row number of cell a1. When copy/pasting
                           this formula, A1 is updated to a new value relative to the
                           original position. Since the formula itself is in A1, the new
                           cell will have its cell in that formula automatically. So if
                           you paste this in G19, the function becomes ROW(G19)

                        )  This is the end bracket for the formula.

A: There are a number of options, this would be my preference:
Type the following formula in cell A1
="R"&TEXT(ROW(A1),"#")

If you want leading zeros so the number "looks nicer" use the following instead:
="R"&TEXT(ROW(A1),"0000#")

or use as many leading zeros as you need, depending on the maximum value you expect to get to.
Then,
Select the cell. Click and drag on the handle at bottom right of the cell as far down as you want the formula to copy. Alternatively copy the cell, select all the cells you want to copy it to and paste.
You can also use
=CONCATENATE ("R",(ROW(A1))

if you don't like using the TEXT  function
Alternatively you can just type R1 in cell A1, R2 in cell A2, select both cells together and drag the handle at the bottom right corner of the selection down as far as you want to go. Excel will automatically add one to the previous number every time it copies a further cell down

A: If you need / want the numbering to differ from the excel ROW-number:
= "R" & ROWS($A$50:A50) in e.g. A50 - to have "R1" in A50, then enter and pull (copy) down.
The same can be used with COLUMNS()
And as always, TEXT(number,"formatcode") can be used for display formatting the number.

A: If you still want to be able to do maths on those numbers, consider using a custom number format... or the currency formatting for the South African Rand 8)


text:
Q: Forced domain for Rickshaw.js slider We are currently displaying some graph with Rickshaw.js, in function of the time. This time can be in local time, or universal time.
The matter is: when we reduce the slider, then switch the time from local to universal (or the inverse), the slider also change its position.
I looked how the slider window was determined, but I don't see any ways to modify it...
Does someone have an idea ?
Thank you very much !


text:
Q: My MVC Razor Data anotations and some razor helpers arent working My Data annotations and some helpers like @validationMessage  arent working, please help, it is on [required], [maxlength], etc.
this is my model:

this is my html helper

   @Html.LabelFor(c => c.baseNumber)
                        @Html.TextBoxFor(c => c.baseNumber, new { @class = "form-control", @maxlength = "7", pattern = "[0-9,.,-]+" })
                        @Html.ValidationMessage("baseNumber", new { @class = "text-danger" })

my model
        [Required(ErrorMessage = "Base number is required.")]
        [Display(Name = "Base number")]
        [Range(1, 9999999, ErrorMessage = "Value length must be of 7.")]

it doesnt work

A: Script references in _Layout.cshtml and _ValidationScriptsPartial.cshtml support client-side validation.Here is an official doc.You need to add <partial name="_ValidationScriptsPartial"> to your view.:
    <form>
    @Html.LabelFor(c => c.baseNumber)
                            @Html.TextBoxFor(c => c.baseNumber, new { @class = "form-control", @maxlength = "7", pattern = "[0-9,.,-]+" })
                            @Html.ValidationMessage("baseNumber", new { @class = "text-danger" })

    </form>
@section Scripts{

<partial name="_ValidationScriptsPartial">
}

result:

Or you can copy the script references in _ValidationScriptsPartial.cshtml  to your view:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.12/jquery.validate.unobtrusive.js"></script>


text:
Q: If $p\geq 5$ is Prime, Prove that $\binom{p^2}{p}-p$ is a multiple of $p^5$ If $p\geq 5$ is Prime, Prove that $$\binom{p^2}{p}-p$$ is a multiple of $p^5$
I started using the fact that:
$$\binom{n}{r}=\frac{n}{r}\binom{n-1}{r-1}$$
So we have:
$$\binom{p^2}{p}-p=\frac{p^2}{p}\binom{p^2-1}{p-1}-p=p\left(\binom{p^2-1}{p-1}-1\right)$$
Now it suffices to prove that:
$$\binom{p^2-1}{p-1}-1$$ is divisible by $p^4$
Any help from here?

A: It is perhaps interesting, that this congruence follows from other well known congruences in the literature. The result is attributed to Schwarz, who seems to have proven it first in $1959$ (see the link above).
First,
Jacobsthal proved $1952$ in the paper On the divisibility of the difference between two binomial coefficients the following result, for all $c\le b\le a$, and any prime $p\ge 5$,
$$
\binom{p^a}{p^b}\equiv \binom{p^{a-c}}{p^{b-c}}\bmod p^{3+a+2b-3c}.
$$
For $(a, b,c)=(2,1,1)$ we obtain
$$
\binom{p^2}{p}\equiv p \bmod p^{4}.
$$
This can be found in the paper Wolstenholme's Theorem. There one can also find the result by Helou and Terjanian
in $2008$, which says that
$$
\binom{np}{mp}\equiv \binom{n}{m}\bmod p^k,
$$
where $k$ is the exact power of $p$ dividing $p^3mn(n-m)\binom{n}{m}$.
For $n=p$ and $m=1$ this yields
$$
\binom{p^2}{p}\equiv p \bmod p^{5}.
$$


text:
Q: Problema con ejecución de funciones Actualmente estoy haciendo una librería y quisiera saber el porque al momento de llamar mis funciones me las remplaza y solo pone los datos o la información que le doy de la ultima función declarada, la única que me respeta es la función base que es stStyle pero si le agrego las demás pasa ese error y solo ejecuta la ultima.
CODIGO
function styleTxt (selector) {
  const obj = {
    getElement (selector) {
      return document.querySelector(selector)
    },
    stStyle (color, bgColor) {
      document.onmouseup = function () {
        if (window.getSelection().toString().length > 0) {
          window
            .getSelection()
            .getRangeAt(0)
            .surroundContents(createSpanTag())
          const selectedElement = document.getElementById(`stElement${auto}`)
          selectedElement.style.color = color
          selectedElement.style.backgroundColor = bgColor
          window.getSelection().removeAllRanges()
          auto++
        }
      }
      return this
    },
    stSize (ftSize) {
      document.onclick = () => {
        const selectedElement = document.getElementById(`stElement${auto - 1}`)
        selectedElement.style.fontSize = `${ftSize}px`
      }
      return this
    },
    txtBold () {
      document.onclick = () => {
        const selectedElement = document.getElementById(`stElement${auto - 1}`)
        selectedElement.style.fontWeight = 'bolder'
      }
      return this
    },
    stBorder () {
      document.onclick = () => {
        const selectedElement = document.getElementById(`stElement${auto - 1}`)
        selectedElement.style.border = '5px solid black'
      }
      return this
    }
  }

  return obj
}

EJEMPLO
styleTxt('#element').stStyle('white', 'orange').stSize(20).txtBold().stBorder()


text:
Q: Is, "$|f_n|\leq g$ eventually", sufficient for dominated convergence theorem Dominated Convergence Theorem: If $(f_n:n\geq 1)$ is a sequence of measurable functions and there exists a Lebesgue integrable function $g$ such that
$|f_n|\leq g$ for all $n\geq 1$, then $\lim\int f_n\,d\mu=\int \lim f_n\,d\mu$.
My question: If we relax the hypothesis "$|f_n|\leq g$ for all $n\geq 1$" to
"$|f_n|\leq g$ for all $n\geq N$", where $N$ is some positive integer, does the conclusion still hold?


text:
Q: How to manage memory alignments and generic pointer arithmetics in a portable way in C? I have to implement an optimized version of malloc/realloc/free (tailored for my particular application). At the moment the code runs on a particular platform, but I would like to write it in a portable way, if possible (the platform may change in the future), or at least I would like to concentrate the possible platform differences in a single point (probably a .h). I am aware of some of the problems:

*

*differences in memory alignment

*differences in smallest memory blocks size suitable for "generic" allocation

*differences in pointer size

(I'll ignore the differences in the basic system services for memory allocation here, since on some embedded systems they may be unavailable at all. Let's imagine that we work on a big preallocated memory block to be used as "heap").
The question(s):

*

*Are there standard macros or functions in C for this kind of purpose?

*What other issues may I face in this job?

A: The classic way to ensure that you maintain alignment suitable for all the basic types is to define a union:
union alloc_align {
    void *dummy1;
    long long dummy2;
    long double dummy3;
};

...then ensure that the addresses you hand out are always offset by a multiple of sizeof (union alloc_align) from the aligned addresses you recieve from the system memory allocator.
I believe a method similar to this is described in K&R.

A: aligned memory differs from compiler to compiler unfortunately (this is one issue), on MSVC, you have aligned_malloc, you also have POSIX memalign for Linux, and then there is also _mm_alloc  which works under ICC, MSVC and GCC, IIRC, which should be the most portable.
The second issue is memory wastage from aligning it, it wouldn't be major, but on embedded systems, its something to take note of.
if you are stack allocating things that require alignment (like SIMD types), you also want to look into __attribute__((__aligned__(x))) and __declspec(align(x)).
in terms of portability of pointer arithmetic, you can use the types from stdint.h/pstdint.h to do it, but the standards may say something about UB when casting between uintptr_t and a pointer (unfortunately standards aren't my strong point :().

A: Alignment features are only handled in the new C standard, C11. It has keywords _Alignof, _Alignas and a function aligned_alloc. Theses features are not very difficult to emulate with most modern compilers (as indicated in other answers), so I'd suggest you write yourself small macros or wrappers that you'd use depending on __STDC_VERSION__.

A: The main problem is that you only provide the total size of the memory block to malloc() and friends, without any information about the object granularity. If you view an allocation as an array of objects, then you have a size that is the sizeof of the basic object, and a number n that is the number of objects in the array, e.g.:
p = malloc(sizeof(*p) * n);

If you have only the total size, then you don't know if s=4 and n=10, or if s=2 and n=20, or s=1 and n=40, because all multiply to the total size of 40 bytes.
So the basic question is, do you want a direct substitute for the original functions, e.g. when you have thrown native calls all over your code base, or do you have a centralized and DRY modularity with wrapper functions. There you could use functions that provide s and n.
void *my_malloc (size_t s, size_t n)

Most of the time it should be a safe bet when the returned absolute memory address is a multiple of s to guarantee correct alignment.
Alternatively, when porting your implementation, you simply look at the alignment that the native malloc() uses for the target platform (e.g. multiples of 16), and use this for your own implementation.

A: If you have a look at #pragma pack, this may help you as it allows you to define structure packing and is implemented on most compilers.

A: C says malloc returns a pointer to memory aligned for any purpose. There is no portable way in C to achieve that with C features. This has the consequence that malloc is a function that if written in C cannot be written in a portable way.

(C99, 7.20.3p1) "The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated)."


text:
Q: Remove duplicate file using bash script I have two files at path1 and path2 respectively.
I want to delete file at path2 if content of both the files are same.
I tried to achieve this using
cmp -s path1 path2 rm path2 ||echo "files are different"

but it doesn't work. Why not?

A: You're missing an &&.
cmp -s path1 path2 && rm path2 || echo "files are different"

I would use if/else rather than &&/|| here. If rm happens to fail the above code will incorrectly say "files are different". Using if/else avoids this hiccup.
if cmp -s path1 path2; then
    rm path2
else
    echo "files are different"
fi

(As a general rule, only use &&/|| if the command after && always succeeds. If there's any chance it could fail stick with an explicit if/else.)


text:
Q: Rails 4: GROUP BY date with time zone I am trying to get the number of LaserSheets cut per day to use in a chart.
pages_controller.rb:
start_date = 7.days.ago
recent_cut_stats = LaserSheet.where('cut_at IS NOT NULL')
                             .where('cut_at > ?', start_date.beginning_of_day)
                             .group("DATE(cut_at)")
                             .count

I am running into problems because the rest of my site uses the time zone set in application.rb, but the above query returns results grouped by date in UTC time. After 5:00pm PDT (UTC -0700) I start seeing results for tomorrow. Is there a way to convert group("Date(cut_at)" to the application's time zone?

A: As the comment above suggests, you'll need to cast the date using SQL your native database:
start_date = 7.days.ago
recent_cut_stats = LaserSheet.where('cut_at IS NOT NULL')
                             .where('cut_at > ?', start_date.beginning_of_day)
                             .group("DATE(CONVERT_TZ(cut_at, 'UTC','<name of time zone>'))")
                             .count

See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for a list of database time zones.
For the .where('cut_at > ?', start_date.beginning_of_day) statement, make sure your timezone is correctly set in Rails:
in application.rb:
config.time_zone  = '<name of time zone>'

A: .group("DATE(created_at at time zone 'utc' at time zone 'Europe/Amsterdam')").count

Timezone names:
https://popsql.com/learn-sql/postgresql/how-to-convert-utc-to-local-time-zone-in-postgresql/


text:
Q: change audio src in an array when click on each a tag (Jquery) I want to change audio src when I click on each a tags, for example when I click on the first a tag, just the first src in the array should play and so on.
I wrote this code but by clicking on a tags the src will change every time (I want the first src just for the first a tag and second for second...);
  $(function () {
        const sources = [
            '1',
            '2',
            '3',
            '4',
            '5',
            '6',
            '7',
            '8',
            '9',
            '10'
        ];

        for (var i = 0; i < $('a').length; i++) {
            $('a').eq(i).on('click', function () {
                if (i <
                    sources.length ) {
                    i++;
                } else {
                    i = 0;
                }
                $('#music').attr('src', sources[i]);
                $('#music').get(0).play();
            })

        };

    });

A: the i variable is hoisted so you should declare it as let (if ES2015 is possible) or use a closure for that. Also, you probably shouldn't modify i inside the loop as you did so that you wouldn't need to account for an infinite loop case. A better loop would be:
const a = $('a');
for (let i = 0; i < a.length; i++) {
    a[i].on('click', function () {
        $('#music').attr('src', sources[i % sources.length]);
        $('#music').get(0).play();
    })
};

A: If I got you right then you can use $.index() to get the source to the clicked  element.

.index() / .index( selector ) / .index( object )
Description: Search for a given element from among the matched elements.
Return Values
If no argument is passed to the .index() method, the return value is
an integer indicating the position of the first element within the
jQuery object relative to its sibling elements.
If .index() is called on a collection of elements and a DOM element or
jQuery object is passed in, .index() returns an integer indicating the
position of the passed element relative to the original collection.
If a selector string is passed as an argument, .index() returns an
integer indicating the position of the first element within the jQuery
object relative to the elements matched by the selector. If the
element is not found, .index() will return -1.

$(function() {
  const sources = [ '1','2','3','4','5','6','7','8','9','10' ],
        anchors = $("a");

  anchors.on('click', function(ev) {
    ev.preventDefault();

    const indexOfClickedAnchor = anchors.index(this),
          source = sources[indexOfClickedAnchor];

    console.log(indexOfClickedAnchor, source);

    /*
    $('#music').attr('src', source)
               .get(0)
               .play();
    */
  });
});

12345
678910


text:
Q: Could not understand the reason behind the output I am quite new to python and could not get this
Consider the following program i have written:
def value_updating(value,list_value):
    value = value+28
    list_value.append(120)

def main():
   value = 15
   list_value = [60,90,100]
   value_updating(value,list_value)
   print(value,list_value)

I was expecting the output to be 43 and [60,90,100,120].
But the answer given by the interpreter is 15 and [60,90,100,120].
Can any one explain this to me?

A: it's because when you pass to the function the value that in the main scope is 15, inside there function the is a different value variable in the scope that change to 43 but it's not returning to the main value scope since then when you print(value,list_value) it's printing the value of value variable in the main scope 15.
The fix for that will be
def value_updating(value,list_value):
    value = value+28
    list_value.append(120)
    return value

def main():
   value = 15
   list_value = [60,90,100]
   value = value_updating(value,list_value)
   print(value,list_value)

A: This is because Python functions are pass-by-object-reference.
This means that mutable objects are passed-by-reference, but immutable objects are pass-by-value. So value inside your function is a new version of value outside (i.e. different pointers and different objects in memory), but list_value points to the same object both inside and out.
The following are immutable in Python:

*

*bool

*int

*float

*tuple

*str

*frozenset

All other variables will be mutable and thus pass-by-reference.

A: Just take out 'print' outside the function.
def value_updating(value,list_value):
    value = value+28
    list_value.append(120)

def main():
   value = 15
   list_value = [60,90,100]
   value_updating(value,list_value)
print(value,list_value)


text:
Q: why the normal counter runs only last setCount argument and functional counter runs all setCount Why the first one is only running the last setCount argument and when we are using the arrow function for setCount it's running both the argument.
eg: if you click the Normal button the count will be 5 as it should be 9
If you click the Functional button the count will be 2 as it is running both the SetCount
import react, { useState, useEffect } from "react";

export default function App() {
 const [count, setCount] = useState(0);
 console.log(count);
 return (

     <button
       onClick={() => {
         setCount(count + 1);
         setCount(count + 3);
         setCount(count + 5);
       }}
     >
       Normal
     </button>

     <button
       onClick={() => {
         setCount((c) => c + 1);
         setCount((c) => c + 1);
       }}
     >
       Functional
     </button>

 );
}


text:
Q: DisplayPort monitor not detected if switched off and on again I am running Ubuntu Desktop 14.04 on a desktop PC with a Nvidia GTX 660 connected to a HP LP2475w 24" monitor over DisplayPort.
It boots up fine, but if I switch off the monitor and switch it on again (for example at night) Ubuntu does not recognize the monitor at switch-on. Screen remains black, and the only way out is to reboot.
This is particularly annoying as I can and do switch the monitor to a different machine and back again, and the same thing happens. I have to reboot the Ubuntu machine to get the display back. Windows 8.1 manages this without an issue.
If I connect over DVI there is no problem; however, when I change to a 4K monitor I will need to use DP. Please help!

UPDATE
If I have a second monitor connected using DVI, I still loose the DisplayPort monitor if I switch it off and on again, but I am able to recover it by using Ctrl-Alt-F1 and then Ctrl-Alt-F7.
If the DisplayPort monitor is connected on its own, this method does not help. This is still a serious issue for me.
I can't believe no-one else is having it. Anyone care to share any experiences?
Do different graphics cards work better? Different monitors?

A: I just had the same problem with a Dell u2913wm connected to a i5-5775c Iris Pro 6200 via Displayport. When I switched inputs on the monitor, it would not display an image afterwards.
The problem could be solved by using ssh to log into the machine and running:
env DISPLAY=:0 xset dpms force off
env DISPLAY=:0 xset dpms force on

While not very practical, that would turn the screen back on.
After reading the answer that mentioned turning off DDC/CI, I fiddled with my monitor settings since manually setting dpms off and on is too cumbersome. DDC/CI setting did nothing for me, but my monitor had an additional Displayport 1.2 setting that was disabled.
After switching the Displayport 1.2 setting to enabled, my monitor started working again after changing inputs, or turning it off, just as it is supposed to.

A: I have this same issue. However, my screen also wont sleep. So any workaround (eg. turning screen on/off) hits this issue.
This bug has been raised on LaunchPad:
launchpad >> bug 1313539
However, it is currently marked as a duplicate of a more generic bug:
launchpad >> bug 1308105 (still open)

UPDATE: Jan-17
I just tried with a DVI Dual-Link cable.
Unfortunately my video card does not support Dual-Link, only Single-Link. However, to the best of my knowledge the HP DL139A ('DMS-59 to DVI Dual-head Y-Cable') does. (Anyone else know?)
No issues (screen saver, screen sleep, or wakeup) under DVI, except drops to 1920x1200 resolution. Inconclusive, but issue is NOT present with same 27" screen, and identical OS / driver setup.

UPDATE: Jan-19
New (bigger/faster) video card still on order.
Tried with another video card, with dual DisplayPort (instead of DMS-59).
Unfortunately the HP adapter (HP P/N 481409-220, included) is only DisplayPort to DVI Single-Link. They have another adapter (HP P/N NR078AA) that does DisplayPort to DVI Dual-Link, but it costs USD $150 (a rip off).
No issues (screen saver/screen sleep, or wakeup) under DVI, except drops to 1920x1200 resolution. Direct DisplayPort cable (from this card) still has same issues.

UPDATE: Feb-12
Resolved for now, by moving screen close to PC and using (Samsung supplied) DVI Dual-Link cable that came with monitor.
Still unable to use properly with DisplayPort cable.

A: My solution to this was making an xbindkeys hotkey (Win+M, but you might want another one) to run the following command:
xrandr --output DP2 --mode 3840x2160

This command will restore the video mode of the monitor when you run it.
mode parameter here is the native resolution of my monitor, which is normally automatically chosen on boot-up when the monitor is on. You can determine the name and resolution of your output if you simply run xrandr without arguments.
Now, if I press power button on the monitor to turn it off, and then press it again to turn it back on, I can simply type my Win+M hotkey, and the image is back on the screen.

A: I had the same issues. I connect my Windows 7 PC to my Dell 2709W monitor by DisplayPort. (Nvidia GTX 750)
I found solutions here:
https://superuser.com/questions/630555/
I disabled the "DDC/CI" in my monitor setting. This solved the problem. I hope this helps.

A: I had the same issue with my ASUS laptop and Dell monitor. What I end up doing is to use xset dpms force off command to make monitor go into power saving mode, instead of turning the monitor off with its power button. I can wake up the screen by pressing a key on keyboard or moving the mouse. With this method to turn off the screen, I never run into the issue of having a black screen when I turn on the screen again. I also made a monitorOff.desktop in /usr/share/applications and pin it to launcher, so I can just click on the icon to turn off the monitor.

A: I ran into something similar on a 4-Monitor configuration connected via DisplayPort to a NVidia GK107 [NVS 510] running under KUbuntu 14.04
Whenever one of the Displays is being disabled, the other Displays will randomly rearrange their positions. When switching the Display back on this does not bring the old configuration back.
Just recently I noticed a memory leak with SSH and
KDE Bug 280381.
Harshly just killing the kde4d (since I needed that memory) I noticed afterwards that the display setting stays the same. I have been able to reproduce that behavior, so I think that the problem may lie somewhere with kded4.
Update:
Since I don't think that killing the whole kded4 process is a valid option, I dug a little into the Services and found that disabling the KScreen2 Service (System Settings > Startup and Shutdown > Service Manager) solves the problem.

A: I too had an issue similar to this in 14.04 with a monitor not waking up while connected to the displayport. After investigating it, it didn't seem to be an issue with the monitor.
What seems to be working for me(last 24hrs) is the downgrade of xfce-settings as suggested in this bug report, posting #7
https://bugs.launchpad.net/ubuntu/+bug/1313539
apt-get couldn't find the downgraded package for saucy.
I found it on launchpad.
Installed it via:
sudo dpkg -i xfce4-settings_4.11.0-1ubuntu1_amd64.deb

Confirmed it installed via:
xfce4-settings-manager -V

I can now have my monitor go to sleep and it seems to be waking up as expected.

A: Just to add to the mix here, my best solution so far:
Disable input auto-switching on the monitor. Lock it in to DisplayPort.
I'm like 99% success on waking from lock screen now.


text:
Q: Create a Column Based on Another Column Using grepl Let's consider a df with two columns word and stem. I want to create a new column that checks whether the value in stem is entailed in word and whether it is preceded or succeeded by some more characters. The final result should look like this:
WORD     STEM     NEW
rerun    run      prefixed
runner   run      suffixed
run      run      none
...      ...      ...

And below you can see my code so far. However, it does not work because the grepl expression is applied on all rows of the df. Anyways, I think it should make clear my idea.
df$new <- ifelse(grepl(paste0('.+', df$stem, '.+'), df$word), 'both',
             ifelse(grepl(paste0(df$stem, '.+'), df$word), 'suffixed',
                ifelse(grepl(paste0('.+', df$stem), df$word), 'prefixed','none')))

A: You can use mapply to use grepl per line like:
ifelse(mapply(grepl, paste0(".+", x$STEM, ".+"), x$WORD), "both",
ifelse(mapply(grepl, paste0(x$STEM, ".+"), x$WORD), "suffixed",
ifelse(mapply(grepl, paste0(".+", x$STEM), x$WORD), "prefixed", "none")))
#"prefixed" "suffixed"     "none"

Or using startsWith and endsWith and use subseting form vector:
c("none", "both", "prefixed", "suffixed")[1 + (1 + startsWith(x$WORD, x$STEM) +
 2*endsWith(x$WORD, x$STEM)) * (nchar(x$WORD) > nchar(x$STEM) &
 mapply(grepl, x$STEM, x$WORD))]
#[1] "suffixed" "prefixed" "none"

A: You can create the new column like this
df$new <- ifelse(startsWith(df$word, df$stem) & endsWith(df$word, df$stem), 'none',
                 ifelse(startsWith(df$word, df$stem), 'suffixed',
                        ifelse(endsWith(df$word, df$stem), 'prefixed',
                               'both')))

Or, in you are in a dplyr pipeline and you want to avoid all the annoying df$
df %>%
  mutate(new = ifelse(startsWith(df$word, df$stem) & endsWith(df$word, df$stem), 'none',
                      ifelse(startsWith(df$word, df$stem), 'suffixed',
                             ifelse(endsWith(df$word, df$stem), 'prefixed',
                                    'both'))))

Output
#       word stem     new1
# 1    rerun  run prefixed
# 2   runner  run suffixed
# 3      run  run     none
# 4    aruna  run     both

A: Here's an approach with str_locate from stringr and dplyr:
library(dplyr)
library(stringr)
data %>%
  mutate_at(vars(WORD,STEM), as.character) %>%
  mutate(NEW =
         case_when(str_locate(WORD,STEM)[,"start"] > 1 &
                   str_locate(WORD,STEM)[,"end"] < nchar(WORD) ~ "both",
                   str_locate(WORD,STEM)[,"start"] > 1 ~ "prefixed",
                   str_locate(WORD,STEM)[,"end"] < nchar(WORD) ~ "suffixed",
                   TRUE ~ "none"))
    WORD STEM      NEW
1  rerun  run prefixed
2 runner  run suffixed
3    run  run     none

I added a line to convert WORD and STEM to character in case they were factors.


text:
Q: Grails-ish way to model Users with emails on different networks What I have is a set of Users and a set of Networks, and those users need to have different email addresses on the various networks -- some are internal, some are external, some are development, and they've all got their own naming & addressing schemes.
What I have so far is this, simplified, with extraneous code removed:
class Network {

    String name

    static hasMany = [email: Email]

}

class User {

    String login

    static hasMany = [email: Email]

}

class Email {

    string address

    static belongsTo = [user: User, network: Network]

}

Where I'm struggling a bit, assuming this is the right way to construct this relationship, is with how to address the email addresses for a given user and network. For example, in a user creation page:
<g:each
    in="${com.damascusgrp.dto.Network.findAll()}">

            ${it.name}
            *

        <g:field type="email" name="email" required="" value="${userInstance?.email}"/>

</g:each>

But while I'm certain that "value" is incorrect, I just can't wrap my head around what it ought to be. Call it Java preventing me from properly thinking in Groovy.
Or is there a more grails-ish way to do this altogether that I've completely missed? I'm upgrading this code from a single email address as part of the User class to this and while I considered making a HashMap that lived within User, I wanted to try this first.
-----Update-----
I created an empty project with just the three classes as listed above and let Grails build controllers & views for them to see what it would do. What I've modified from that appears below:

    <g:each in="${userInstance?.email?}" var="e">

<g:link controller="email" action="show" id="${e.id}">${e?.encodeAsHTML()}</g:link>

    </g:each>

        <g:link controller="email" action="create" params="['user.id': userInstance?.id]">${message(code: 'default.add.label', args: [message(code: 'email.label', default: 'Email')])}</g:link>

I took this basically verbatim from the scaffolded view and folded it into my code. I just now need to figure out how to "hide" the user field from the email creation page, or better yet do this all on one page using JQuery or something like that. Or switch to a Map as was suggested.
------2nd Update-----
Instantiating is the only remaining issue. When I try to instantiate this, and add a new Email to it, I get an NPE:
java.lang.NullPointerException: Cannot invoke method collectEntries() on null object
    at com.damascusgrp.dto.User.getEmailsByNetwork(User.groovy:37)
    at com.damascusgrp.dto.UserSpec.Fully constructed user is good(UserSpec.groovy:44)

I've tried various ways to pre-load this, or set it up with blank entries for each of the defined networks, but nothing has worked right yet. Here's the code as it stands now, with Ian's help in place.
class User {

    String login
    String password
    String firstName
    String lastName
    String filePath
    static hasMany = [requests:Request, email: Email]

    static transients = ['emailsByNetwork']

    def User(String l) {
        login = l
    }

    def getName() {
        "${firstName} ${lastName}"
    }

    String toString() {
        login
    }

    static constraints = {
        login blank:false, size:5..15, matches:/[\S]+/, unique:true
        password blank:false, size:5..15, matches:/[\S]+/
        firstName blank:false
        lastName blank:false
        filePath blank:false
    }

    Map getEmailsByNetwork() {
        email.collectEntries { [(it.network.id), it] }
    }

    def addToEmail(Email em) {
        email[em.network.id] = em
    }

}

A: Your sample GSP suggests that the domain model has each User with exactly one Email on each Network - a User can't have two different Email objects on the same Network.  So I'd add a transient property to the User domain class
class User {

    String login

    static hasMany = [email: Email]

    Map getEmailsByNetwork() {
      (email?.collectEntries { [it.network.id, it] }) ?: [:]
    }

    static transients = ['emailsByNetwork']

}

Now user.emailsByNetwork will be a map from Network id to Email, and in the GSP you can say
<g:set var="emailsByNet" value="${userInstance.emailsByNetwork}" />
<g:each var="net"
    in="${com.damascusgrp.dto.Network.findAll()}">

            ${net.name}
            *

        <g:field type="email" name="net_${net.id}_email" required="" value="${emailsByNet[net.id]?.email}"/>

</g:each>

In the controller that receives this form post you'll have to handle the various params.net_1_email etc. appropriately, updating the existing emailsByNetwork[n] if it exists or userInstance.addToEmail(new Email(network:Network.load(n), email:value)) if not.


text:
Q: How to make google fonts visible for mobile? I am developing a portfolio and I used google fonts in it. But I am unable to display it on the mobile. Please find the portfolio here
You can find the head tag below
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Courgette&family=Poppins:wght@300&display=swap"
    rel="stylesheet

A: You have .d-none set to display: none !important; on some media queries which is why the text disappears on smaller screens

A: Sometimes the link tag does not work on mobile browser . It's better to use CSS import :
   <style>

      @import url('https://fonts.googleapis.com/css2?
      family=Courgette&family=Poppins:ital,wght@0,100;0,200;0
     ,300;0,400;0,500;0,600;1,100;1,200;1,300;1,400;1,500&
      display=swap');

   </style>


text:
Q: For loop not working properly? What did I do wrong? I'm not sure what's wrong the expected output is "0 5 25 100".
The output I get is "20 3 15 60":

http://hastebin.com/tibirakoni.dos
@echo off
setlocal EnableDelayedExpansion
cls
:vars
set numbercheck=50
set number2=0
set number3=0
set number4=0
:calc
for %%a in (0, 1, 100) do (
    if !numbercheck GEQ 10 (
        set /a numbercheck= !numbercheck! - 10
        set /a number2= !number2! +1
        set /a number3= !number3! +5
        set /a number4= !number4! +20
    )
)
goto echo
:echo
echo !numbercheck!
echo !number2!
echo !number3!
echo !number4!
pause

A: I'm not sure what's wrong - the expected output is 0 5 25 100

The output I get is 20 3 15 60
...
for %%a in (0, 1, 100) do (
    if !numbercheck GEQ 10 (

...

There are two mistakes in the above code:

*

*Missing /l in the for command, it should be:
for /l %%a in (0, 1, 100) do (

Without the /l the for loop will return 0,1,100 and will only loop 3 times. With the /l the for loop will return 1,2,3,...,100

*Missing ! in the if command, it should be:
if !numbercheck! GEQ 10 (

Corrected batch file:
@echo off
setlocal EnableDelayedExpansion
cls
:vars
set numbercheck=50
set number2=0
set number3=0
set number4=0
:calc
for /l %%a in (0, 1, 100) do (
    if !numbercheck! GEQ 10 (
        set /a numbercheck= !numbercheck! - 10
        set /a number2= !number2! +1
        set /a number3= !number3! +5
        set /a number4= !number4! +20
    )
)
goto echo
:echo
echo !numbercheck!
echo !number2!
echo !number3!
echo !number4!
pause

Example output:
0
5
25
100
Press any key to continue . . .

Further Reading

*

*An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.

*for /l - Conditionally perform a command for a range of numbers.


text:
Q: Estimating time in harmonic signal I hope someone can help me with the following problem:
Assume a periodic signal of the form
$$\begin{align}
s(t) &= \sum\limits_{p=1}^P \sin(p\Omega_0t)\\
     &= \sum\limits_{p=1}^P \sin(\theta_p(t)),
\end{align}$$
with $0 \leq t < \frac{2\pi}{\Omega_0}$ (only one period of the fundamental frequency).
We take measurements $\theta^*_p(t_0)$ of the phases $\theta_p(t_0)$ at a certain (unknown) time $t_0$ for $p \in [2,\ldots,P]$ (i.e. for all harmonics except the fundamental). The measurements are phase wrapped, i.e. projected to the interval $[-\pi,\pi[$:
$$
\theta^*_p(t_0) = \theta_p(t_0) + n_p \cdot 2\pi
$$
How can we estimate/determine the time $t_0$ at which the measurements have been taken?
Here is a diagram to illustrate the problem:

From the diagram it becomes clear that for $p=2$, the phase value $\theta^*_2(t_0)$ can occur at two points in time (see red marker). For $p=3$, the phase value $\theta^*_3(t_0)$ can occur at three points in time, etc. But only at $t_0$ they all fall together. Can we use this property to estimate $t_0$?

A: OK, the phase is obviously linear in time here, so we should assume that the phase measurements, when unwrapped, want to fall on a line.  So the idea, albeit a bit crude, it to go through the measurements for increasing $p$, and increase the $p$th phase in increments of $2 \pi$ until that phase is larger than the $p-1$th phase.  As an example, allow me to glean off some values from your graphs:
$$\left ( \begin{array} \\2 t_0 & 0.33 \pi \\ 3 t_0 & -0.55 \pi \\ 4 t_0 & 0.55 \pi \\ 5 t_0 & -0.39 \pi\end{array} \right )$$
Begin by taking the value of the phase at $t=2 t_0$ as is.  For the phase at $t=3 t_0$, see that it is less than the phase at $t=2 t_0$, so increase by $2 \pi$ to get $1.45 \pi$, which is the smallest phase greater than the previous phase; we then move on to $4 t_0$, and you hopefully get the point.  When you finish, you get something like this
$$\left ( \begin{array} \\2 t_0 & 0.33 \pi \\ 3 t_0 & 1.45 \pi \\ 4 t_0 & 2.55 \pi \\ 5 t_0 & 3.61 \pi\end{array} \right )$$
A best fit line takes the form $\theta(p) = -1.844 \pi+1.094 \pi p$, so plugging in $p=1$ corresponding to $t=t_0$, you get a phase of about $-0.75 \pi$ (which makes sense on your graph), so that knowing $\Omega_0$, you may then determine the value of $t_0$.  I hope that helps.

A: If I may have understood your case then
given:
$$2 \Omega_0 t_0 = \theta_2$$
$$3 \Omega_0 t_0 = \theta_3$$
$$\dots$$
and $\theta_2$ and $\theta_3$ known, then
$$\Omega_0=\frac{\theta_2}{2 t_0}=\frac{\theta_3}{3 t_0}=\dots=\frac{\theta_p}{p t_0}$$
So you see from your given constraints, $t_0$ can be any time, (it will change through all harmonics) and the system is under-determined .
The answer under the given constraints is that we can not specify a specific $t_0$ or ($\Omega_0$).
For the new information you brought in your question we have now
$$\theta^*_p(t_0) - n_p \cdot 2\pi = \theta_p(t_0) $$
hence:
$$\Omega_0=\frac{\theta^*_2(t_0) - n_2 \cdot 2\pi }{2 t_0}=\dots=\frac{\theta^*_p(t_0) - n_p \cdot 2\pi }{p t_0}$$
It does not look better for getting $t_0$.


text:
Q: How to use SBT IntegrationTest configuration from Scala objects To make our multi-project build more manageable we split up our Build.scala file into several files, e.g. Dependencies.scala contains all dependencies:
import sbt._

object Dependencies {
  val slf4j_api = "org.slf4j" % "slf4j-api" % "1.7.7"
  ...
}

We want to add integration tests to our build. Following the SBT documentation we added
object Build extends sbt.Build {
  import Dependencies._
  import BuildSettings._
  import Version._
  import MergeStrategies.custom

  lazy val root = Project(
    id = "root",
    base = file("."),
    settings = buildSettings ++ Seq(Git.checkNoLocalChanges, TestReport.testReport)
  ).configs(IntegrationTest).settings(Defaults.itSettings: _*)
  ...
}

where Dependencies, BuildSettings, Version and MergeStrategies are custom Scala objects definied in their own files.
Following the documentation we want to add some dependencies for the IntegrationTest configuration in Dependencies.scala:
import sbt._

object Dependencies {

  val slf4j_api = "org.slf4j" % "slf4j-api" % "1.7.7"

  val junit = "junit" % "junit" % "4.11" % "test,it"
...
}

Unfortunately this breaks the build:

java.lang.IllegalArgumentException: Cannot add dependency
  'junit#junit;4.11' to configuration 'it' of module ... because this configuration doesn't exist!

I guess I need to import the IntegrationTest configuration. I tried importing the IntegrationTest configuration in Dependencies.scala:
import sbt.Configurations.IntegrationTest

IntegrationTest is a lazy val defined in the Configurations object:
object Configurations {
  ...
  lazy val IntegrationTest = config("it") extend (Runtime)
  ...
 }

But that did not solve the problem.
Does someone has an idea how to solve this?

A: You need to add the config to the Project object before you add the dependency to the Project object.
Your code quotes show you doing the former, but you don't show where you are doing the latter in your quoted code.
Please could you post the full config, or try moving those two around each other?
Here is where the config is added to the Project object in the SBT docs you linked to:
lazy val root = (project in file(".")).
  configs(IntegrationTest).

Your quoted code above which declares a lazy val but does not use it is not sufficient to get the "it" config into use:
lazy val IntegrationTest = config("it") extend (Runtime)


text:
Q: How to subclass a widget to add more elements to it? I'm trying to make a subclass of QTableView that has an embedded QLineEdit at the top for filtering the results as-you-type. I need my table to have the same API as a normal QTableView, so I want to subclass it rather than subclassing QWidget and adding a QLineEdit and QTableView to it.
I thought I could just re-implement paintEvent(QPaintEvent*), alter the QPaintEvent's rect() to start a bit lower (the height of a QLineEdit, so it draws under it) and then pass it thru to QTableView::paintEvent(), but the QPaintEvent argument only dictates what region needs to be repainted, not the region where the widget should be painted.

A: Anything you do in this regard is going to be hacky and result in just as much work (probably more work) as manually mapping all of the signals and slots to a child widget. You'll need to do a lot more than just change the paint events, you'd also have to adjust all of the mouse events, adjust any update rectangles, etc.
Alternatively you could just take the QTableView class from the Qt source and modify it directly (though that will probably break the LGPL and require you to publish your source if you don't have a commercial license.) But the easiest clean method is going to be implementing a container widget with the QTableView as a child.

A: I would try overriding the paintEvent, changing the widget::pos to be abit lower than it is and call QTableView::paintEvent()

A: I have to agree with Daniel: I don't think this is the right approach. You will likely want to create a custom widget with a line edit for performing the filtering. Otherwise, you will be entering into the challenging world of Qt hacking.
If you really need to provide access to the QTableView interface then simply add a public get method that returns a reference to the table.
This is somewhat similar to how Qt provides a QTabWidget class that inherits QWidget but has a private QTabBar that it uses internally. One significant difference is that it provides a protected tabBar() accessor rather than a public one.


text:
Q: Java json append value to a json array how do I append value to an existing json array ?
I have existing json array with below values
{
  "test": [
    1,
    2,
    3,
    4
  ]
}

I wanted to add "0" in to the json array so that the new json array would look like
{
  "test": [
    0,
    1,
    2,
    3,
    4
  ]
}

A: Using Java and the Jackson library, you can deserialize the (json) String to a Java object, add the entry, and then serialize the modified object (print it to Json format).
In example, with this code
package json;
import java.util.Collections;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class UseJson {
  public static void main(String[] args) throws Exception {
    ObjectMapper om = new ObjectMapper();
    String json = "{\r\n" +
    "  \"test\": [\r\n" +
    "    1,\r\n" +
    "    2,\r\n" +
    "    3,\r\n" +
    "    4\r\n" +
    "  ]\r\n" +
    "} ";
    System.out.println("json="+json);
    Wrap val = om.readValue( json, Wrap.class);
    System.out.println("read val="+val);
    val.test.add(0);
    Collections.sort(val.test);
    System.out.println("val="+val);
    om.enable(SerializationFeature.INDENT_OUTPUT);
    String json2 = om.writeValueAsString(val);
    System.out.println("json2="+json2);
  }
}

class Wrap {
  public List<Integer> test;
  @Override
  public String toString() {
    return "Wrap[test=" + test + "]";
  }
}

you get..
json={
  "test": [
    1,
    2,
    3,
    4
  ]
}
read val=Wrap[test=[1, 2, 3, 4]]
val=Wrap[test=[0, 1, 2, 3, 4]]
json2={
  "test" : [ 0, 1, 2, 3, 4 ]
}

(to be compiled in a Maven project including jackson-core and jackson-databind)


text:
Q: React-testing-library: getByTestId() or queryByTestId() not working, thros Unable to find an element by data-testid component is like:
<Button and <Icon are customized components which wrap up the <button and <icon

const handleToggleShow = useCallback(() => {
    setShow(!show);
}, [show]);

const displayUI = (

        <Icon
            testId="editIcon"
            onClick={handleToggleShow}
            className="edit-icon"
        >

);

const editUI = (
 <form data-testid="form" onSubmit={handleSubmit}
    <InputComponent />
    <Button
        testId="saveButton"
        text="Save"
        disabled={...}
        size="large"
        color="blue"
        type="submit"
    />
    <Button
        testId="cancelButton"
        text="Cancel"
        disabled={...}
        size="large"
        color="grey"
        onClick={handleClickCancel}
    />
 </form>
);

return(

    {show ? editUI}
    {!show? displayUI}

);

Test is like:
test("show render edit ui when click button", () => {
    render()
    const icon = screen.getByTestId("editIcon");
    expect(icon).toBeInDocument();

    fireEvent.click(element);
    const form = screen.getByTestId("form");
   //here throws error: unable to find an element by [data-testid="form"]
    expect(form).toBeInDocument();
});

Then I tried queryByTestId("form") and tried getByTestId("saveButton"), it throws error "received value must be an HTMLElement or as an SVGElement",
I was thinking maybe icon click event was not triggered, then I ran this test, still got error
test("show render edit ui when click button", () => {
    const handleToggleShow = jest.fn();
    render()
    const icon = screen.getByTestId("editIcon");
    expect(icon).toBeInDocument();

    fireEvent.click(element);
    expect(handleToggleShow).toHaveBeenCalled(); //received number of calls 0
});

Anyone can help? why getByTestId or queryByTestId is not working

A: Update here:
In the previous test, I didn't pass any mock props to the component.
after passing props, the issue somehow fixed.


text:
Q: How i can install android studio 2.2 in ubuntu 18 I have Linux (Ubuntu 18)
i want to install android 2.2 but
when go to this link
Android Studio
only have latest version not found 2.2
How i found version 2.2 and download to ubuntu

A: Instead of looking at the main downloads page you need to go to the archive. However, the oldest version they have there is 2.3.2.
https://developer.android.com/studio/archive


text:
Q: .bat file that opens cmd in certain location without admin permission I'm really new to this but I found a bat file online with the following code in it:
@echo off
cls
title Batchcc Prompt C:
color 0a
cls
:cmd
set /p "cmd=%CD%>"
%cmd%
echo.
goto cmd

I'm looking for a way to open Command Prompt w/o admin access in C: however this one opens in whatever location the bat is stored in. Is there a way to edit this to open in C:? Or is there another way to do the same thing?

A: Possibly the simplest way would be cd /d
@echo off
cd /d C:\
cls
title Batchcc Prompt C:
color 0a
cls
:cmd
set /p "cmd=%CD%>"
%cmd%
echo.
goto cmd


text:
Q: How to fix error Extender Provider failed to return an Extender for this object when open any report in VS 2019? I installed VS 2019 and opened my project which is built before with VS 2015
I can open the project and run it without any errors but the error appeared when I try to open any report when double click the report this error show up
 The Extender Provider failed to return an Extender for this object

I tried the solutions in this question but the error still show and not solved
https://stackoverflow.com/questions/3397779/extender-provider-failed-to-return-an-extender/7072526

I tried these solutions but still show the error :
1- Closing the solution in Visual Studio
2- Deleting the obj and bin directories from the problematic project.
3- run Visual Studio as administrator
4- Clean the project close and open again
5- deleting ProjectName.csproj.user file and then reloading the project.
6- I have 64 bit runtime and installed 32 runtime
7- I removed old reference for crystal reports version 13.0.2000.0 and added new references for VS 2019 version 13.0.4000.0
Also I tried to add new crystal report its added to the project but cannot open it show same error
I need your help please to solve this issue
thank you in advance

A: Try uninstall crystal reports and crystal report runtime .
Confirm the crystal report version for VS 2019 it must be of version SP 25 and above
After uninstall install crystal report SP 30 and crystal report runtime 64-bit , which is compatible with VS 2019.


text:
Q: How can I use the apply() function for a single column? I have a pandas dataframe with two columns. I need to change the values of the first column without affecting the second one and get back the whole dataframe with just first column values changed. How can I do that using apply() in pandas?

A: Let me try a complex computation using datetime and considering nulls or empty spaces. I am reducing 30 years on a datetime column and using apply method as well as lambda and converting datetime format. Line if x != '' else x will take care of all empty spaces or nulls accordingly.
df['Date'] = df['Date'].fillna('')
df['Date'] = df['Date'].apply(lambda x : ((datetime.datetime.strptime(str(x), '%m/%d/%Y') - datetime.timedelta(days=30*365)).strftime('%Y%m%d')) if x != '' else x)

A: Given a sample dataframe df as:
   a  b
0  1  2
1  2  3
2  3  4
3  4  5

what you want is:
df['a'] = df['a'].apply(lambda x: x + 1)

that returns:
   a  b
0  2  2
1  3  3
2  4  4
3  5  5

A: You don't need a function at all. You can work on a whole column directly.
Example data:
>>> df = pd.DataFrame({'a': [100, 1000], 'b': [200, 2000], 'c': [300, 3000]})
>>> df

      a     b     c
0   100   200   300
1  1000  2000  3000

Half all the values in column a:
>>> df.a = df.a / 2
>>> df

     a     b     c
0   50   200   300
1  500  2000  3000

A: Although the given responses are correct, they modify the initial data frame, which is not always desirable (and, given the OP asked for examples "using apply", it might be they wanted a version that returns a new data frame, as apply does).
This is possible using assign: it is valid to assign to existing columns, as the documentation states (emphasis is mine):

Assign new columns to a DataFrame.
Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten.

In short:
In [1]: import pandas as pd

In [2]: df = pd.DataFrame([{'a': 15, 'b': 15, 'c': 5}, {'a': 20, 'b': 10, 'c': 7}, {'a': 25, 'b': 30, 'c': 9}])

In [3]: df.assign(a=lambda df: df.a / 2)
Out[3]:
      a   b  c
0   7.5  15  5
1  10.0  10  7
2  12.5  30  9

In [4]: df
Out[4]:
    a   b  c
0  15  15  5
1  20  10  7
2  25  30  9

Note that the function will be passed the whole dataframe, not only the column you want to modify, so you will need to make sure you select the right column in your lambda.

A: If you are really concerned about the execution speed of your apply function and you have a huge dataset to work on, you could use swifter to make faster execution, here is an example for swifter on pandas dataframe:
import pandas as pd
import swifter

def fnc(m):
    return m*3+4

df = pd.DataFrame({"m": [1,2,3,4,5,6], "c": [1,1,1,1,1,1], "x":[5,3,6,2,6,1]})

# apply a self created function to a single column in pandas
df["y"] = df.m.swifter.apply(fnc)

This will enable your all CPU cores to compute the result hence it will be much faster than normal apply functions. Try and let me know if it become useful for you.

A: For a single column better to use map(), like this:
df = pd.DataFrame([{'a': 15, 'b': 15, 'c': 5}, {'a': 20, 'b': 10, 'c': 7}, {'a': 25, 'b': 30, 'c': 9}])

    a   b  c
0  15  15  5
1  20  10  7
2  25  30  9

df['a'] = df['a'].map(lambda a: a / 2.)

      a   b  c
0   7.5  15  5
1  10.0  10  7
2  12.5  30  9

A: Given the following dataframe df and the function complex_function,
import pandas as pd

def complex_function(x, y=0):
    if x > 5 and x > y:
        return 1
    else:
        return 2

df = pd.DataFrame(data={'col1': [1, 4, 6, 2, 7], 'col2': [6, 7, 1, 2, 8]})

   col1  col2
0     1     6
1     4     7
2     6     1
3     2     2
4     7     8

there are several solutions to use apply() on only one column. In the following I will explain them in detail.
I. Simple solution
The straightforward solution is the one from @Fabio Lamanna:
df['col1'] = df['col1'].apply(complex_function)

Output:
   col1  col2
0     2     6
1     2     7
2     1     1
3     2     2
4     1     8

Only the first column is modified, the second column is unchanged. The solution is beautiful. It is just one line of code and it reads almost like english: "Take 'col1' and apply the function complex_function to it."
However, if you need data from another column, e.g. 'col2', it won't work. If you want to pass the values of 'col2' to variable y of the complex_function, you need something else.
II. Solution using the whole dataframe
Alternatively, you could use the whole dataframe as described in this SO post or this one:
df['col1'] = df.apply(lambda x: complex_function(x['col1']), axis=1)

or if you prefer (like me) a solution without a lambda function:
def apply_complex_function(x):
    return complex_function(x['col1'])
df['col1'] = df.apply(apply_complex_function, axis=1)

There is a lot going on in this solution that needs to be explained. The apply() function works on pd.Series and pd.DataFrame. But you cannot use df['col1'] = df.apply(complex_function).loc[:, 'col1'], because it would throw a ValueError.
Hence, you need to give the information which column to use. To complicate things, the apply() function does only accept callables. To solve this, you need to define a (lambda) function with the column x['col1'] as argument; i.e. we wrap the column information in another function.
Unfortunately, the default value of the axis parameter is zero (axis=0), which means it will try executing column-wise and not row-wise. This wasn't a problem in the first solution, because we gave apply() a pd.Series. But now the input is a dataframe and we must be explicit (axis=1). (I marvel how often I forget this.)
Whether you prefer the version with the lambda function or without is subjective. In my opinion the line of code is complicated enough to read even without a lambda function thrown in. You only need the (lambda) function as a wrapper. It is just boilerplate code. A reader should not be bothered with it.
Now, you can modify this solution easily to take the second column into account:
def apply_complex_function(x):
    return complex_function(x['col1'], x['col2'])
df['col1'] = df.apply(apply_complex_function, axis=1)

Output:
   col1  col2
0     2     6
1     2     7
2     1     1
3     2     2
4     2     8

At index 4 the value has changed from 1 to 2, because the first condition  7 > 5 is true but the second condition 7 > 8 is false.
Note that you only needed to change the first line of code (i.e. the function) and not the second line.

Side note
Never put the column information into your function.
def bad_idea(x):
    return x['col1'] ** 2

By doing this, you make a general function dependent on a column name! This is a bad idea, because the next time you want to use this function, you cannot. Worse: Maybe you rename a column in a different dataframe just to make it work with your existing function. (Been there, done that. It is a slippery slope!)

III. Alternative solutions without using apply()
Although the OP specifically asked for a solution with apply(), alternative solutions were suggested. For example, the answer of @George Petrov suggested to use map(); the answer of @Thibaut Dubernet proposed assign().
I fully agree that apply() is seldom the best solution, because apply() is not vectorized. It is an element-wise operation with expensive function calling and overhead from pd.Series.
One reason to use apply() is that you want to use an existing function and performance is not an issue. Or your function is so complex that no vectorized version exists.
Another reason to use apply() is in combination with groupby(). Please note that DataFrame.apply() and GroupBy.apply() are different functions.
So it does make sense to consider some alternatives:

*

*map() only works on pd.Series, but accepts dict and pd.Series as input. Using map() with a function is almost interchangeable with using apply(). It can be faster than apply(). See this SO post for more details.
df['col1'] = df['col1'].map(complex_function)

*applymap() is almost identical for dataframes. It does not support pd.Series and it will always return a dataframe. However, it can be faster. The documentation states: "In the current implementation applymap calls func twice on the first column/row to decide whether it can take a fast or slow code path.". But if performance really counts you should seek an alternative route.
df['col1'] = df.applymap(complex_function).loc[:, 'col1']

*assign() is not a feasible replacement for apply(). It has a similar behaviour in only the most basic use cases. It does not work with the complex_function. You still need apply() as you can see in the example below. The main use case for assign() is method chaining, because it gives back the dataframe without changing the original dataframe.
df['col1'] = df.assign(col1=df.col1.apply(complex_function))

Annex: How to speed up apply()?
I only mention it here because it was suggested by other answers, e.g. @durjoy. The list is not exhaustive:

*

*Do not use apply(). This is no joke. For most numeric operations, a vectorized method exists in pandas. If/else blocks can often be refactored with a combination of boolean indexing and .loc. My example complex_function could be refactored in this way.

*Refactor to Cython. If you have a complex equation and the parameters of the equation are in your dataframe, this might be a good idea. Check out the official pandas user guide for more information.

*Use raw=True parameter. Theoretically, this should improve the performance of apply() if you are just applying a NumPy reduction function, because the overhead of pd.Series is removed. Of course, your function has to accept an ndarray. You have to refactor your function to NumPy. By doing this, you will have a huge performance boost.

*Use 3rd party packages. The first thing you should try is Numba. I do not know swifter mentioned by @durjoy; and probably many other packages are worth mentioning here.

*Try/Fail/Repeat. As mentioned above, map() and applymap() can be faster - depending on the use case. Just time the different versions and choose the fastest. This approach is the most tedious one with the least performance increase.

A: Make a copy of your dataframe first if you need to modify a column
Many answers here suggest modifying some column and assign the new values to the old column. It is common to get the SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. warning. This happens when your dataframe was created from another dataframe but is not a proper copy.
To silence this warning, make a copy and assign back.
df = df.copy()
df['a'] = df['a'].apply('add', other=1)

apply() only needs the name of the function
You can invoke a function by simply passing its name to apply() (no need for lambda). If your function needs additional arguments, you can pass them either as keyword arguments or pass the positional arguments as args=. For example, suppose you have file paths in your dataframe and you need to read files in these paths.
def read_data(path, sep=',', usecols=[0]):
    return pd.read_csv(path, sep=sep, usecols=usecols)

df = pd.DataFrame({'paths': ['../x/yz.txt', '../u/vw.txt']})

df['paths'].apply(read_data)                            # you don't need lambda

df['paths'].apply(read_data, args=(',', [0, 1]))        # pass the positional arguments to `args=`

df['paths'].apply(read_data, sep=',', usecols=[0, 1])   # pass as keyword arguments

Don't apply a function, call the appropriate method directly
It's almost never ideal to apply a custom function on a column via apply(). Because apply() is a syntactic sugar for a Python loop with a pandas overhead, it's often slower than calling the same function in a list comprehension, never mind, calling optimized pandas methods. Almost all numeric operators can be directly applied on the column and there are corresponding methods for all of them.
# add 1 to every element in column `a`
df['a'] += 1

# for every row, subtract column `a` value from column `b` value
df['c'] = df['b'] - df['a']

If you want to apply a function that has if-else blocks, then you should probably be using numpy.where() or numpy.select() instead. It is much, much faster. If you have anything larger than 10k rows of data, you'll notice the difference right away.
For example, if you have a custom function similar to func() below, then instead of applying it on the column, you could operate directly on the columns and return values using numpy.select().
def func(row):
    if row == 'a':
        return 1
    elif row == 'b':
        return 2
    else:
        return -999

# instead of applying a `func` to each row of a column, use `numpy.select` as below

import numpy as np
conditions = [df['col'] == 'a', df['col'] == 'b']
choices = [1, 2]
df['new'] = np.select(conditions, choices, default=-999)

As you can see, numpy.select() has very minimal syntax difference from an if-else ladder; only need to separate conditions and choices into separate lists. For other options, check out this answer.


text:
Q: PHP SQL Insert Error I have an error when inserting into the database.
Code:
dbquery("INSERT INTO site_news_comments (articleid,title,short,comment,timestamp,userid,main,type,topstory) VALUES ($article,'".clean($commentss['title'])."','','".mysql_real_escape_string($_POST['comment'])."',current_timestamp,'".USER_ID."','0','".$commentss['type']."','')");

Ignore the dbquery, works exactly as mysql_query.
The error I am receiving is:
 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''title','short','

No idea why this error is being thrown!

A: EDIT
I read too quickly the first time around; The error does not appear to be in the column list, it looks like it's in the value list. The only place the query can have a syntax error is if $article is empty (or un-sanitized data, such as non-numeric). Try adding quotes around it in the query and/or verifying it has at least a default value:
$article = (empty($article) || !is_numeric($article)) ? 0 : $article;
dbquery("... VALUES ('".$article."', '".clean($commentss['title'])."', '', '".mysql_real_escape_string($_POST['comment'])."', current_timestamp, '".USER_ID."', '0', '".$commentss['type']."', '')");

Original Answer
There is a list of reserved words used by MySQL that, if you use them for column names, you have to escape them with backticks.
Try updating all of them to fix:
dbquery("INSERT INTO site_news_comments (`articleid`, `title`, `short`, `comment`, `timestamp`, `userid`, `main`, `type`, `topstory`) VALUES ...

A: Teaching a man how to fish.
If a query fails, the first thing you should do is to echo the query you're about to send:
$sql = "INSERT INTO site_news_comments (articleid,title,short,comment,timestamp,userid,main,type,topstory) VALUES ($article,'".clean($commentss['title'])."','','".mysql_real_escape_string($_POST['comment'])."',current_timestamp,'".USER_ID."','0','".$commentss['type']."','')";

echo $sql;

It's usually pretty obvious what's wrong with the final query; pay particular attention to the dynamic stuff in your query and generally around the area where MySQL complains about.
If that still looks okay, then you look for words that might need escaping, such as the reserved words.
Conclusion
Having looked at the code mysql, I would have to conclude that the problem lies with $article and it causes problems in your query. You should probably escape it as well, just in case :)
Recommendation
You should learn about PDO / mysqli and using prepared statements:
// PDO example
$stmt = $db->prepare('INSERT INTO site_news_comments (articleid, title, short, comment, timestamp, userid, main, type, topstory) VALUES (:article, :title, :short, :comment, CURRENT_TIMESTAMP, :user, :main, :type, :topstory)');
$stmt->execute(array(
    ':article' => $article,
    ':title' => $commentss['title'],
    ':short' => '',
    ':comment' => $_POST['comment'],
    ':user' => USER_ID,
    ':main' => 0,
    ':type' => $commentss['type'],
    ':topstory' => '',
));

A: Thanks for the help guys! But I fixed the problem!
It seems that the cause of the problem was of the "URL". The URL was
news/1/&page=2
So when I inserted the $article, it came as '1/', this was because it thought that the ID was 1/ , not 1 because of the URL.
So I've just changed it to
news/1&page=2
Thanks!

A: //change this line :
dbquery("INSERT INTO site_news_comments (articleid,title,short,comment,timestamp,userid,main,type,topstory) VALUES ($article,'".clean($commentss['title'])."','','".mysql_real_escape_string($_POST['comment'])."',current_timestamp,'".USER_ID."','0','".$commentss['type']."','')");

//to this : (surround $articleid with single quote)
dbquery("INSERT INTO site_news_comments (articleid,title,short,comment,timestamp,userid,main,type,topstory) VALUES ('".$article."','".clean($commentss['title'])."','','".mysql_real_escape_string($_POST['comment'])."',current_timestamp,'".USER_ID."','0','".$commentss['type']."','')");


text:
Q: Undefined control sequence "\DeclareSortingNamekeyScheme" Biber I tried using the solution here https://tex.stackexchange.com/a/373581/100078 with XeLaTeX. It always gives the error Undefined control sequence "\DeclareSortingNamekeyScheme".
This is the code i'm trying to compile:
\documentclass{article}

\usepackage[backend=biber, style=authoryear]{biblatex}

\DeclareSortingNamekeyScheme{
  \keypart{
    \namepart{given}
  }
  \keypart{
    \namepart{prefix}
  }
  \keypart{
    \namepart{family}
  }
  \keypart{
    \namepart{suffix}
  }
}

\DeclareNameAlias{sortname}{default}

\begin{document}
\cite{sigfridsson,worman,geer,cicero,nussbaum,knuth:ct:a}
\printbibliography
\end{document}

This seems to be taken straight out of the docs and it still does not work.
I have given up on trying to find the solution to fix this. Any help, please?
P.S. I want to sort the authors by their first name, then last name. I tried another method (in place of default), but even this does not produce the effect.
\DeclareNameAlias{sortname}{first-last}

P.S. Doesn't matter what the references are. Biber compiles (if XeLaTeX produces its .bcf file).
The error log corresponding to the error:
(/usr/share/texlive/texmf-dist/tex/latex/biblatex/biblatex.cfg
File: biblatex.cfg
)))
! Undefined control sequence.
l.5 \DeclareSortingNamekeyScheme
                                {
The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

! Undefined control sequence.
l.6   \keypart
              {
The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

! Undefined control sequence.
l.7     \namepart
                 {given}
The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

! LaTeX Error: Missing \begin{document}.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

A: \DeclareSortingNamekeyScheme was introduced in version 3.3 and renamed in 3.8 to \DeclareSortingNamekeyTemplate. You are running an older version of biblatex that defines neither of the two commands. In order to use this command you will have to update your biblatex and Biber versions.
But since your aim is to always treat names as an inseparable unit and don't want to split into first and last names, your best bet is to wrap all names in a set of curly brackets, that way they will be treated as atomic.
author = {{Anne Elk} and {Elizabeth Ditor}},

Will always come out the same even with the standard settings, you don't even need to change the sortname format or \DeclareSortingNamekeyScheme.
Since the name parsing and splitting is done by the backend, there is no biblatex solution to treat a name as atomic if it wasn't input as atomic. We can only try to manipulate everything so that it looks as though the name is never split, but that is much more work than just putting the name in curly brackets.


text:
Q: How to save login credentials on app build in Xcode 9.2 I have been experiencing extreme difficulties finding out a way to save users login information on my build (hours and hours of researching). I have tried to implement UserDefaults and Core Data, but I have already created the login/sign up views with other integrated lines of code and can't figure out the correct place to put these other lines of code(UserDefaults/CoreData) without receiving errors/ or interfering with other actions. I am a beginner and any input would be fantastic!
this is an example of my login ViewController :
import UIKit
import Parse

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var emailfield: UITextField!
    @IBOutlet weak var passwordfield: UITextField!

    var actInd : UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 150, height: 150)) as UIActivityIndicatorView

    override func viewDidLoad() {
        self.actInd.center = self.view.center
        self.actInd.hidesWhenStopped = true
        self.actInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray

        view.addSubview(self.actInd)
        emailfield.delegate = self
        passwordfield.delegate = self
        super.viewDidLoad()

        emailfield.attributedPlaceholder = NSAttributedString(string: "Username:",
        attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])

        passwordfield.attributedPlaceholder = NSAttributedString(string: "Password:",
        attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        if textField == emailfield {
            passwordfield.becomeFirstResponder()
        } else if textField == passwordfield {
            textField.resignFirstResponder()
        }
        return true

A: I think it should be the place where you use the username/password to make the actual login request. That's the place you'll have the complete info and just save it to the NSUserDefaults


text:
Q: overflow-x stacks divs on window resize I would like to setup a horizontal container that holds multiple (smaller) columns within it. I have the following setup:
http://jsfiddle.net/f464W/1/
As you can see, when you resize the window, the .column containers just stack vertically when the width of the window is too small to contain them all.
Shouldn't
overflow-x: hidden

Stop the .column class from being displayed when they run off the side of .container?

A: With overflow-x: hidden will hide what exceeds on the right of your div. But the natural behaviour of the divs are to wrap to the line below when they're out of space, therefore nothing exceeds.
You need to make the divs not wrap. if you add white-space: nowrap to your container CSS they will only stack horizontally.

A: Add white-space: no-wrap the .container
http://jsfiddle.net/feitla/f464W/17/
.container {
    max-height: 600px;
    width: 100%;
    margin-top: 100px;
    background: red;
    padding: 0;
    overflow-y: hidden;
    overflow-x: hidden;
    white-space: nowrap;
}

A: You can add float: left; to .column and that should give you the desired effect. You'll then have to play with margin if you want to maintain the spacing you had between the columns.