Q:

Sql Server: Selective XML Index not being efficiently used

I'm exploring ways of improving the performance of an application which I can only affect on the database level to a limited degree. The SQL Server version is 2012 SP2 and the table and view structure in question is (I cannot really affect this + note that the xml document may have several hundred elements in total):
CREATE TABLE Orders(
    id nvarchar(64) NOT NULL,
    xmldoc xml NULL,
    CONSTRAINT PK_Order_id PRIMARY KEY CLUSTERED (id)
);

CREATE VIEW V_Orders as
SELECT
    a.id, a.xmldoc
    ,a.xmldoc.value('data(/row/c1)[1]', 'nvarchar(max)') "Stuff"
    ,a.xmldoc.value('data(/row/c2)[1]', 'nvarchar(max)') "OrderType"
etc..... many columns
from Orders a;

A typical query (and the one being used for testing below):
SELECT id FROM V_Orders WHERE OrderType = '30791'

All the queries are performed against the view and I can affect neither the queries nor the table/view structure.
I thought adding a selective XML index to the table would be my saviour:
CREATE SELECTIVE XML INDEX I_Orders_OrderType ON Orders(xmldoc)
FOR(
    pathOrderType = '/row/c2' as SQL [nvarchar](20)
)

But even after updating the statistics the execution plan is looking weird. Couldn't post a pic as new account so the relevant details as text:

Clustered index seek from selectiveXml (Cost: 2% of total). Expected number of rows 1 but expected number of execution times 1269 (number of rows in the table)
-> Top N sort (Cost: 95% of total)
-> Compute scalar (Cost 0)
Separate branch: Clustered index scan PK_Order_id (Cost: 3% of total). Expected number of rows 1269
-> Merged to the Computer scalar results with Nested loops (Left outer join)
-> Filter
-> Final result (Expected number of rows 1269)

In actuality with my test data the query doesn't even return any results but whether it returns one or few doesn't make any difference. Execution times support the query really taking as long as could be deduced from the execution plan and have read counts in the thousands.
So my question is why is the selective xml index not being used properly by the optimizer? Or have I got something wrong? How would I optimize this specific query's performance with selective xml indexing (or perhaps persisted column)?
Edit:
I did additional testing with larger sample data (~274k rows in the table with XML documents close to average production sizes) and compared the selective XML index to a promoted column. The results are from Profiler trace, concentrating on CPU usage and read counts. The execution plan for selective xml indexing is basically identical to what is described above.
Selective XML index and 274k rows (executing the query above):
CPU: 6454, reads: 938521
After I updated the values in the searched field to be unique (total records still 274k) I got the following results:
Selective XML index and 274k rows (executing the query above):
CPU: 10077, reads: 1006466
Then using a promoted (i.e. persisted) separately indexed column and using it directly in the view:
CPU: 0, reads: 23
Selective XML index performance seems to be closer to full table scan than proper SQL indexed column fetch. I read somewhere that using schema for the table might help drop the TOP N step from execution plan (assuming we're searching for a non-repeating field) but I'm not sure whether that's a realistic possibility in this case.

A:

The selective XML index you create is stored in an internal table with the primary key from Orders as the leading column for the clustered key for the internal table and the paths specified stored as sparse columns.
The query plan you get probably looks a something like this:

You have a scan over the entire Orders table with a seek in the internal table on the primary key for each row in Orders. The final Filter operator is responsible for checking the value of OrderType returning only the matching rows.
Not really what you would expect from something called an index.
To the rescue comes a secondary selective XML index. They are created for one of the paths specified in the primary selective index and will create a non-clustered key on the values extracted in the path expression.
It is however not all that easy. SQL Server will not use the secondary index on predicates used on values extracted by the values() function. You have to use exists() instead. Also, exists() requires the use of XQUERY data types in the path expressions where value() uses SQL data types.
Your primary selective XML index could look like this:
CREATE SELECTIVE XML INDEX I_Orders_OrderType ON Orders(xmldoc)
FOR
(
  pathOrderType = '/row/c2' as sql nvarchar(20),
  pathOrderTypeX = '/row/c2/text()' as xquery 'xs:string' maxlength (20)
)

With a secondary on pathOrderTypeX.
CREATE XML INDEX I_Orders_OrderType2 ON Orders(xmldoc)
  USING XML INDEX I_Orders_OrderType FOR (pathOrderTypeX)

And with a query that uses exist() you will get this plan.
select id
from V_Orders
where xmldoc.exist('/row/c2/text()[. = "30791"]') = 1

The first seek is a seek for the value you are looking for in the non-clustered index of the internal table. The key lookup is done on the clustered key on the internal table (don't know why that is necessary). And the last seek is on primary key in the Orders table followed by a filter that checks for null values in the column xmldoc.
If you can get away with using property promotion, creating calculated indexed columns in the Orders table from the XML, I guess you would still get better performance than using secondary selective XML indexes.


Q:

Ejecutar esta consulta desde .Bat

Hola quisiera me ayudarn Gracias, tengo la siguiente consulta:
CREATE DATABASE almacen;

la cual quiero ejecutar mediante un Bat, pense en algo como esto:
@echo off
echo --test >crear.sql
echo CREATE DATABASE almacen1;>>crear.sql
C:\xampp\mysql\bin\mysql.exe -h localhost -u root -ptresa456 < "crear.sql"

pero no me corre, ¿como la puedo ejecutar desde batch?

A:

Prueba pasar el SQL en la misma línea, asi te evitas que el mysql.exe no encuentre el archivo
C:\xampp\mysql\bin\mysql.exe -h localhost -u root -ptresa456 -e "CREATE DATABASE IF NOT EXISTS almacen1;"


Q:

Tools to automatically generate Daos

I'm not interested in Spring/JPA etc. I like straight up JDBC/ODBC.
I was wondering what are the good (actually production ready) tools to enable taking a database schema and generating objects/daos that fetch/update them? I am intersted in Java and C++.
I am interested in ramping up more on C++ in order to get away from all of this Spring/Maven/Hibernate madness and stop abstracting abstraction. I'd like to get down to the code. I like how I can investigate a generated JDBC dao and understand what's going on with my particular transaction isolation level. I like actually being able to debug tricky deadlocks because I can understand simple JDBC code. That aside, I'm just looking for some good code generation tools for Java/C++ that make production quality Daos.
This is a great tool, but it only works with java.
http://www.codefutures.com/products/firestorm/
By the way, why is it that the Dao/POJO/POCO model as prevalent in the C++ world. It makes understanding code so much easier!

A:

You can try the Telosys code generator with the templates for native JDBC DAO.
It's simple to use and everything is free.
It works from an existing database or from a simple text model.
At the moment the templates are mainly for Java, Python and JavaScript, but you can customize existing templates in order to generate C/C++ DAO.
See http://www.telosys.org
And the templates for JDBC DAO available on GitHub : https://github.com/telosys-templates-v3


Q:

IDENT_CURRENT value is higher than max(id)

Error:
Arithmetic overflow error converting IDENTITY to data type int.
Arithmetic overflow occurred.
Debugging:
id = my Identity column, datatype INT. Increment=1, Seed=1
select max(id) as max, min(id) as min from eventlogreport
    Result: 6728550 1

select count(*) from eventlogreport
    Result: 6728550

So far soo good. It looks like we have plenty of room for more rows. But inserting 600 000 more rows gives the overflow error. More debugging.
SELECT IDENT_CURRENT ('EventLogReport') AS Current_Identity;
    Result: 2147483647

Questions:

How can the current identity value be so high when the table doesn't
contain the same amount of rows, and there are no ids that has been
skipped?
How can I safely set the IDENT_CURRENT to the same number as max(id)? Or maybe it's easier to reseed, as long as the id columns isn't references?

A:

Identity values don't participate in transactions - so if you've had a large number of attempted inserts (after all current rows were added) that have subsequently been rolled back, then IDENT_CURRENT can be much higher than the highest observed value in the table.
Similarly, if you'd actually inserted 2147483647 rows but then deleted all rows with an ID greater than 6728550, you'd observe the same situation.
Thirdly, someone may have reseeded the identity to be 2147483647.
So there are many ways you may have reached this situation. It's impossible for us to know how it came about.

To set the identity value to be appropriate for the next insert, use DBCC CHECKIDENT twice:
DBCC CHECKIDENT(Table,RESEED,1)
DBCC CHECKIDENT(Table,RESEED)

The first sets the next value to use as 2. The second then invokes this part:

If the current identity value for a table is less than the maximum identity value stored in the identity column, it is reset using the maximum value in the identity column. See the 'Exceptions' section that follows.


Q:

C# Cursor and PictureBox

When ever my PictureBox is created, the cursor position in at x=0,y=0 which is the top left corner of the PictureBox. I want to place my Cursor in the center.
Cursor.Position = new Point(Cursor.Position.X - 75, Cursor.Position.Y - 75);

I tried doing this but it didn't helped. As the size of my PictureBox is 150,150

A:

Cursor.Position = this.PointToScreen(new Point(pictureBox1.Location.X + pictureBox1.Width / 2 ,pictureBox1.Location.Y + pictureBox1.Height / 2 ));


Q:

Run a script (or set stringsAsFactors = FALSE) while loading a package in R

I previously used Rprofile.site to set options(stringsAsFactors = FALSE). However, numerous sources state using Rprofile.site for this purpose makes code less portable. My solution has been to run source('C:/...startup.script.R') every time I load R. This startup script sets stringsAsFactors = FALSE (along with accomplishing other tasks). This works, but in order to share my scripts with others I would have to share the script of interest and my startup.script.R script.
I am creating a custom package that will allow me to share my custom functions. I plan to put require(MyCustomFunctionsPackage) (or something to that effect) at the beginning of all of my scripts in order to load my custom functions. I want to embed source('C:/...startup.script.R') (or something to that effect) and the startup.script.R file in the MyCustomFunctionsPackage package such that, when I share my scripts, I will only need to share the script of interest with a call to devtools::install_github('MyCustomFunctionsPackage','github_username') and all of my custom functions and settings will be loaded. Is there a way to do this? I'm sure the answer is in Hadley's book or the CRAN literature somewhere, but I'm not sure what keywords to search.

A:

You can supply a function named .onLoad() that will be called whenever the package is loaded. Here's a simple reproducible example showing how it can be used:
## Create and install a package containing a function `.onLoad()`
library(pkgKitten)
kitten("myopts")
cat(
".onLoad <- function(libname, pkgname) {
    options(stringsAsFactors = FALSE)
}
", file = "myopts/R/zzz.R")

devtools::install("myopts")

## Confirm that loading the package sets stringsAsFactors
options('stringsAsFactors')
## $stringsAsFactors
## [1] TRUE

library(myopts)
options('stringsAsFactors')
## $stringsAsFactors
## [1] FALSE


Q:

Mostrar informacion segun el usuario logueado, clase ListView? - Django

models.py
class Torneo(models.Model):
    user = models.ForeignKey(User)
    descripcion = models.CharField(max_length=200)

  def __str__(self):
     return (self.descripcion)

views.py
 class Torneo_ListView(ListView):
     template_name = 'torneos/torneo_listar.html'

    def get_queryset(self, *args, **kwargs):
        return Torneo.objects.filter(user=self.request.user)

Me sale este error

A:

El error que te muestra indica que la identación de código está mal. En el código que posteas la identación está mal en ambas clases , no se si es resultado de copiar el código o lo tienes así originalmente. Si usas identado de 4 espacios que es lo recomendado en PEP 8 debería ser así:
models.py
class Torneo(models.Model):
    user = models.ForeignKey(User)
    descripcion = models.CharField(max_length=200)

    def __str__(self):
        return (self.descripcion)

views.py
class Torneo_ListView(ListView):
    template_name = 'torneos/torneo_listar.html'

    def get_queryset(self, *args, **kwargs):
        return Torneo.objects.filter(user=self.request.user)

Vigila también que no estes mezclando espacios y tabulaciones para identar el código.


Q:

IRouteHandler not routing through RouteConfig

I have a IRouteHander class which I use to resize images on the fly and add expire headers to them, Recently I moved to MVC5 and now updating my code. I tried to register the same route for that class in RouteConfig.cs
routes.Add(new Route("Image/{w}/{h}/{src}", new ThumbImageRouteHandler()));

but this route isn't working anymore like it was on MVC3 and giving 404 error in MVC5. Is there anything I am missing here? this route leads to
public class ThumbImageRouteHandler : IRouteHandler
{
         public IHttpHandler GetHttpHandler(RequestContext requestContext)
            {
                HttpHanler httpHandler = new HttpHanler();
                return httpHandler;
            }
            public class HttpHanler : IHttpHandler
            {
                public bool IsReusable
                {
                    get
                    {
                        return false;
                    }
                }
                public void ProcessRequest(HttpContext context)
                {
                //Do something
                }
               }
           }
}

Please help me fixing this issue. Thanks

A:

After research I found out that I need to add a line in webconfig in order to make it work, here's how.
  <system.webServer>
    <handlers>
      <add name="ApiURIs-ISAPI-Integrated-4.0-Image" path="/Image/*" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>

Because IRouteHandler is generating re-sized images with a dynamic path, and IIS thinks this is the actual path to a directory because of dot(.) in the link and it thinks it's an extension, which is actually not. So we have to add a handler in Web.Config to make it work.


Q:

Pandas resample based on higher resolution data

I have two time-series one on 30 min resolution and one on 15 minute resolution A and B as shown under. I would like to Upsample A to a 15 minute resolution using B to scale the values for the given interval. So for the first value it would be:
B['final']['01/11/2017  07:30:00'] =  77.0*29.7/(29.7+12.67)

A['irrad']
2017-11-01 07:30:00     77.0
2017-11-01 08:00:00    214.0
2017-11-01 08:30:00    470.0
2017-11-01 09:00:00    714.0

B['util']
2017-11-01 07:15:00     12.67
2017-11-01 07:30:00     29.70
2017-11-01 07:45:00     46.80
2017-11-01 08:00:00     74.07
2017-11-01 08:15:00    166.27
2017-11-01 08:30:00    256.50
2017-11-01 08:45:00    271.70
2017-11-01 09:00:00    354.33

So the final series would be
B['final']
01/11/2017 07:30    54.0
01/11/2017 07:45    82.9
01/11/2017 08:00    131.1
01/11/2017 08:15    184.8
01/11/2017 08:30    285.2

I was looking into Pandas resample or merge functions but could see this being possible. Any ideas?

A:

Say you upsample, then left-merge to util:
A.index = pd.to_datetime(A.index)
B.index = pd.to_datetime(B.index)
merged = pd.merge(B, A.resample('15s').ffill(), left_index=True, right_index=True, how='left')
>>> merged

util    irrad
index
2017-11-01 07:15:00 12.67   NaN
2017-11-01 07:30:00 29.70   77.0
2017-11-01 07:45:00 46.80   77.0
2017-11-01 08:00:00 74.07   214.0
2017-11-01 08:15:00 166.27  214.0
2017-11-01 08:30:00 256.50  470.0
2017-11-01 08:45:00 271.70  470.0
2017-11-01 09:00:00 354.33  714.0

Now you can use
>>> merged.irrad * merged.util / (merged.util + merged.util.shift(-1))
index
2017-11-01 07:15:00           NaN
2017-11-01 07:30:00     29.894118
2017-11-01 07:45:00     29.813850
2017-11-01 08:00:00     65.952318
2017-11-01 08:15:00     84.163446
2017-11-01 08:30:00    228.237410
2017-11-01 08:45:00    203.982237
2017-11-01 09:00:00           NaN
dtype: float64

Note that this isn't what you specified in your question. Feel free to clarify how you got to your final results.


Q:

django-rest ModelSerializer select fields to display in nested relationship

I'm going to reference the django-rest-framework API example on this. Lets say we have two serializers defined as below.
class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ['order', 'title', 'duration']

class AlbumSerializer(serializers.ModelSerializer):
    tracks = TrackSerializer(many=True, read_only=True)

    class Meta:
        model = Album
        fields = ['album_name', 'artist', 'tracks']

Now if i do a GET request and retrieve an Album instance, it will return me a response with a list of Track instances inside it where each instance contains all the fields of Track. Is there a way to return only a selected subset of the fields in the Track model? For example to only return the title and duration field to the client but not the 'order' field.

A:

You can make a specific TrackSerializer for your Album, like:
class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ['order', 'title', 'duration']

class TrackForAlbumSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ['title', 'duration']

class AlbumSerializer(serializers.ModelSerializer):
    tracks = TrackForAlbumSerializer(many=True, read_only=True)

    class Meta:
        model = Album
        fields = ['album_name', 'artist', 'tracks']
You do not have to define a single serializer per model, you can define multiple serializers you each use for a dedicated task.


Q:

Execute zsh alias when name contains a hyphen

A stock-standard zsh behaves as follows with an alias with a - in it, eg: a-a:
% zsh -f
svelte% alias a-a=date
svelte% a-a
Sun 19 Jul 2020 17:20:05 +07

My configuration has it behave as follows:
% alias a-a=date
% alias | grep a-a
a-a=date
% a-a
zsh: command not found: a-a

Non-hyphen aliases work fine.
What option would be causing zsh to not find the alias named with a hyphen?

A:

In addition to the basic 10 chars that a working alias can not accept in zsh:  "&');<>`|, setting the option posixaliases adds 12 more
#$(*-?[\]^{~
That includes the dash -, which is valid without posixaliases.
Alias options
There are few options in zsh that affect aliases:
ALIASES ALIAS_FUNC_DEF POSIX_ALIASES

The aliases option enables all or none, not the option to control only a-b.
The aliasfuncdef is more related to how function definitions are parsed.
posixaliases
So, the only one left to try is posixaliases. The man description is:

When  this  option  is set, reserved words are not candidates for alias expansion:

Doesn't seem to apply to this question.
POSIX defined aliases
However, knowing that the POSIX description of alias is:

3.10 Alias Name

In the shell command language, a word consisting solely of underscores, digits, and alphabetics from the portable character set and any of the following characters: '!', '%', ',', '@'.

Implementations may allow other characters within alias names as an extension.

That is: for POSIX, the list of available characters is _0-9a-zA-Z!%,@.
That description doesn't include the dash -, even if it is allowed as an extension.
So, it may be possible that a posix_alias is limiting alias in some way.
In fact, it is.
alias allowed chars
In general, the list of valid characters for alias is somewhat obscure and difficult to find. In practice, it seems to allow all Unicode chars:
% for  c in ä å é ë þ ü ú í ó ö á ß ð f g h ï œ ø ¶ æ œ © ® b ñ µ ç;
> do   d=a${c}b;
>      alias $d="echo alias $d";
> done
% alias
a©b='echo alias a©b'
a®b='echo alias a®b'
aµb='echo alias aµb'
a¶b='echo alias a¶b'
aáb='echo alias aáb'
aßb='echo alias aßb'
aäb='echo alias aäb'
aåb='echo alias aåb'
aæb='echo alias aæb'
açb='echo alias açb'
aéb='echo alias aéb'
aëb='echo alias aëb'
aíb='echo alias aíb'
aïb='echo alias aïb'
aðb='echo alias aðb'
añb='echo alias añb'
aób='echo alias aób'
aöb='echo alias aöb'
aøb='echo alias aøb'

But zsh is more restrictive when using ASCII characters:
% for c in ! @ % +; do d=a${c}b; alias $d="echo alias $d"; done

But a!b only works if quoted as a\!b and some characters like # $ ^ * can not be used easily (not used above).
In fact, the whole list of ASCII, {\ ..~} could be tested to define an alias:
for c in {\ ..~}; do d="a${c}b"; alias $d="echo alias ${(q)d}";done

But only some aliases actually work:
for c in {\ ..~}; do d="a${c}b"; if e=$(eval $d) 2>/dev/null; then print $d $e; else print "failed char: $c"; fi; done

we get 10 failed chars:  "&');<>`|, some syntax chars can be defined as aliases but will not work (unquoted): <=>&;, some chars are pattern chars [? that get searched in the file system, and some aliases get incorrectly defined with this unquoted chars: \`$#.
In POSIX aliases only "plain unquoted chars" may be valid and in zsh, setting the posixaliases enforces that definition making 12 additional chars become directly failed chars in the test above:
#$(*-?[\]^{~
Those characters could not be used in a working alias. That includes the -, the source of your question.
Note from man zsh:

When POSIX_ALIASES  is  set, only plain unquoted strings are eligible for aliasing. The alias builtin does not reject ineligible aliases, but they are not expanded.


Q:

WCF Service in C# should send different data to different client consumers with different access rights

I have a scenario where my WCF service is hosted but should return different response to different clients and also different security/authentication options.
How to implement that ? Idea and small model code would be appreciable.
Client A and Client B suppose consumes the service. Client A should be given some data and Client B should be given some other data and also both of them should have different access rights/permissions....
Thank you...

A:

There's a lot of ways to do this; bottomline is you have to identify the user that's connecting. This can be done using an X509 client certificate, HTTP (basic/digest) authentication or a custom API key (or credentials) that the client sends during each request (in the HTTP headers, in the message headers or simply in a field in the message body).
Once you've got that part figured out, you can let your code decide what to do based on who's making the request.


Q:

If $V \times W$ with the product norm is complete, must $V$ and $W$ be complete?

Let $V,W$ be two normed vector spaces (over a field $K$). Then their product $V \times W$ with the norm $\|(x,y)\| = \|x\|_V + \|y\|_W$ is a normed space.
Using this norm it's easy to show that if $V,W$ are complete then so is $V \times W$. To see this, let the limit of the sequence $(x_n , y_n)$ be $(x,y) = (\lim x_n, \lim y_n)$.  Then for $n$ large enough, both $\|x - x_n\|_V$ and $\|y - y_n\|_W$ are less than $\varepsilon / 2$ and hence $\|(x,y) - (x_n, y_n)\|< \varepsilon$.
The other direction does (probably) not hold. Can someone show me an example of a space $V \times W$ that is complete but either $V$ or $W$ (or both) are not?

A:

If $V$ is not complete and $V\times W$ complete, take $\{v_n\}$ a Cauchy sequence which doesn't converge in $V$. Then $(v_n,0)$ is a Cauchy sequence in $V\times W$ and converges to $(v,w)\in V\times W$. We have
$$\lVert (v_n,0)-(v,w)\rVert_{V\times W}=\lVert v_n-v\rVert+\lVert w\rVert\to 0$$
hence $v_n\to v$ in $V$, a contradiction.
Hence $V\times W$ is complete if and only if so are $V$ and $W$.

A:

I believe that the spaces $V$ and $W$ must be complete whenever $V\times W$ is complete.
Closed subspace of a complete normed space is complete.
The space $V$ is isometrically isomorphic to the closed subspace $V\times\{0\}$ of $V\times W$.


Q:

Jquery click function effect

I have a jquery code, but I'm a little bit confused on how can I put a css on this:

$(document).ready(function () {
    $('span.account-menu').click(function () {
    $('ul.menu').slideToggle('medium');
    });
});

I wanted to add this css in the click function.

border: 1px solid #999999;
background-color: #333333;

This style, I wanted to effect only in 'span.account-menu' and not affecting ul.menu. I try the code that you have given but the problem is when I click back the menu the style will not disappear.

A:

You can either

add those css attributes manually by using .css()
add a css class by using .addClass()

Example
$(document).ready(function () {
   $('span.account-menu').click(function () {
      $('ul.menu').slideToggle('medium', function(){
         $(this).css({
            border:           '1px solid #999999',
            backgroundColor:  '#333333'
         });
      });
   });
});


Q:

linker ignores /openmp in qtcreator on windows

when I try to compile the openmp cpp file from this  website, I got a link warning saying that the openmp flag is ignored.
LNK4044:unrecognized option '/openmp'; ignored

I have already added these code to the pro. file
QMAKE_CXXFLAGS+= -openmp
QMAKE_LFLAGS +=  -openmp

or
QMAKE_CXXFLAGS += -fopenmp
LIBS += -fopenmp

as suggeted by some other stack overflow questions.But that does not solve the problem.
Can any one help me to solve this problem? I am using the qt creator 3.1.2 with msvc2013 compiler on windows 7.

A:

MSVC's linker does not need or accept the /openmp option.  You only need that option for GCC (in which case the option is -fopenmp). Although I use CMake now with QtCreator instead of qmake here is a sample from the last qmake file I use.
msvc {
  QMAKE_CXXFLAGS += -openmp -arch:AVX -D "_CRT_SECURE_NO_WARNINGS"
  QMAKE_CXXFLAGS_RELEASE *= -O2
}

gcc {
  QMAKE_CXXFLAGS += -fopenmp -mavx -fabi-version=0 -ffast-math
  QMAKE_LFLAGS += -fopenmp
  QMAKE_CXXFLAGS_RELEASE *= -O3
}


Q:

Woman mistakenly orders a hit on herself

It was a live action film set in the US.  I saw the first part of it about 25 years ago on TV.  I only saw the first part and am keen to watch the whole thing.  The below scenes are all from the first half and hour or so:

It began with a woman being told by a doctor that she did not have, I think, cancer.  She is not happy.
Later she is sitting on a bench and is approached by a man, I think he was French or he at least had an similar accent.  She is looking at the floor when he starts talking to her and she jumps and shouts "Don't kill me!".  He is bemused and says that anyone who shouts that as a stranger could probably do with help.
It turned out that she thought she had cancer so had hired a hitman to kill herself but did not know how to track him down to stop him now she knew she was healthy.
The man who approached her was a police officer who offered to help her.  In my memory he looks and sounds like Ricardo Montalban but I am not sure how reliable that is.
He tells her to always walk on the wallside of him and as soon she should always get in the back seat of the car and duck down immediately,
As he took her somewhere he noticed that they had seen the same blond man in two separate locations doing something innocuous, the second time he was reading a newspaper.
She does not believe he could be the hitman as he looks too nice, the police man is exasperated and reprimands her for being so naive.

A:

I think this was an episode of Starsky and Hutch - Cover Girl

A gorgeous but terminally ill model puts a hit out on herself, but when her cancer goes into remission, she asks Hutch to stop the contract killer.

I found this by searching IMDB for the keyword Suicide By Hitman.

A:

The Face of Fear (1971)
This was a made-for-TV movie from the 70s, based on the book 'Sally' by Howard Fast (writing under the pseudonym 'E.V. Cunningham').
Edited from this page, here's a synopsis:

Sally Dillman [played by Elizabeth Ashley] is an Idaho school teacher
  who thinks she's dying of leukemia. She goes to San Fransisco for a
  last fling and gives $5,000 to a man in the underworld to hire a
  gunman to hasten her death. When she learns she is in perfect health,
  she tries to find the gunman and cancel her death-contract.
Ricardo Montalban and Jack Warden play police detectives Sgt. Frank
  Ortega and Lt. Coye who help Sally in her dilemma. They know that a
  gunman is tracking her every move – even after it is apparent that he
  doesn't have to fulfill his contract.

I couldn't find any video clips to help you out. You can browse through some photos in the link posted above. Just in case you missed it here it is again.
There's also this page featuring some of the cast members. Keep in mind, they don't look anything like that in the movie :-)


Q:

LED bulb goes dim

I have a ceiling fan in my living room, which has sockets for 3 candelabra bulbs.  When there were incandescent bulbs in it, it worked perfectly.  I replaced the incandescent bulbs with 3 LED bulbs.  2 of the bulbs work fine.  I noticed one bulb would go visibly dimmer than the others at random.  It would stay that way for a while, then randomly get bright again.  This happened over a course of several months, until the bulb just died.  I assumed it was just a defective bulb.  However, I replaced the bulb and the same thing is happening.  It could be wiring, but I dont know why it would be so inconsistent.  Additionally, the fan is never on.  So its not as if the vibrations of the fan are moving the wires.
Im not sure where to begin troubleshooting.  Ideas?

A:

I have solved the issue.  I sprayed the inside of the socket with (electric) contact cleaner.  I then took the dead bulb and screwed it in and out a few times to work the solution around the metal of the socket.  I then let it dry.  Just for good measure I sprayed the socket with some canned air.  The issue is fixed and has stayed working properly for months, so far.


Q:

jshint ignore the node_modules folder

I tried to let grunt jshint scans all the js file except the files in the node_modules folder. I tried the follow configuration of grunt, it still scan all the files including the ones in node_modules. anyone know why? also can anyone explain /**/*.js **/*.js. what is the double star mean. here is my grunt config files
module.exports = function(grunt) {

    grunt.initConfig({
        jshint: {
            all: ['**/*.js'],
            options: {
                ignores: ['node_modules']
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-jshint');
};

A:

Base on @ateich hint, I realized I can do the following to fix the problem
module.exports = function(grunt) {
    grunt.initConfig({
        jshint: {
            all: ['**/*.js'],
            options: {
                jshintrc: true,
                ignores: ['node_modules/**/*.js']
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-jshint');
};


Q:

Event isn't firing when using javascript to postback

I'm trying to use Telerik's RadSpell to spellcheck some text when the user submits it.
The way this is supposed to work is by stopping the postback, triggering the spellcheck through javascript, then in the spellcheckfinished event manually starting the real postback.  The problem is that in the last step the Clicked event isn't firing for the button and the server side event handler never gets called.
Here is the relevant .aspx code:

                <asp:Button ID="btnSubmit" OnClientClick="return doSpellCheckStuff(this);" Text="Submit"
                            OnClick="btnSubmit_Click" runat="server" />

            <telerik:RadSpell   ID="rsMessage" ControlToCheck="txtMessage" ButtonType="None"
                                UseClassicDialogs="true" FragmentIgnoreOptions="All"
                                OnClientCheckFinished="checkFinished" runat="server" />

Any idea why btnSubmit_Click isn't getting called and how I can fix it?

A:

Try to inject your postback script as :
string script = @"function MySubmit(){" +
                  this.Page.ClientScript.GetPostBackEventReference(myButton, string.Empty);
                  "}";

if (!this.Page.ClientScript.IsClientScriptBlockRegistered("myPostBackScript"))
{
    this.Page.ClientScript.RegisterClientScriptBlock(typeof(MyPage), "myPostBackScript", script, true);
}


Q:

PHP Random including the mentioned "text" on top 1 to 5 statements

I been trying to add the mentioned "text" in my web crawler extracted statements.
php web crawler ::
<?php
    function get_data($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL,$url);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    $returned_content = get_data('http://www.usmle-forums.com/usmle-step-1-forum/');
    $first_step = explode( '$element) {
    $child_first = explode( '<td class="alt1"' , $element );
    $child_second = explode( '	' , $child_first[1] );
    $child_third = explode( '<a href=' , $child_second[0] );
    $child_fourth = explode( '' , $child_third[1] );
    $final = "<a href=".$child_fourth[0]."
";
?>

        text<?php echo $final?>

<?php
    if($key==10){
        break;
    }
}
?>

now i been trying to insert the "text" mentioned in span tag to be added randomly on the first five statements extracted by the web crawler.
so whenever user refreshes the page, the "text" in span tag should shuffle in between top 5 statements.
Any help is appreciated..

A:

Not sure if this is what you want:
<?php
  function get_data($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL,$url);
    $result=curl_exec($ch);
    curl_close($ch);
    return $result;
  }
  $returned_content = get_data('http://www.usmle-forums.com/usmle-step-1-forum/');
  $first_step = explode( '$element) {
    $child_first = explode( '<td class="alt1"' , $element );
    $child_second = explode( '	' , $child_first[1] );
    $child_third = explode( '<a href=' , $child_second[0] );
    $child_fourth = explode( '' , $child_third[1] );
    $final = "<a href=".$child_fourth[0]."
";

    echo '
';
    if($key < 5 && rand(0,1) == 1) {
      echo 'YOUR TEXT ';
    }

    echo $final;
    echo '
';

    if($key==10) {
      break;
    }

  }
?>

It adds "YOUR TEXT" randomly to the first five lines.
Output:
YOUR TEXT
1 Attachment(s)
Pass Your Step 1 Exam - 100% Guaranteed!
USMLE Step 1 Live prep/Boot Camp in Chicago
YOUR TEXT  1 Attachment(s)
Picmonic for Medicine
Increase Your Step 1 Score Through 1-on-1 Online Tutoring
Low Score on Step 1?
step 1 tutoring
Frustrated USMLE taker mom.
Looking for a tutor


Q:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 8

I am trying to read a CSV using pd.read_csv, but I get an error:

UnicodeDecodeError                        Traceback (most recent call
  last) pandas_libs\parsers.pyx in
  pandas._libs.parsers.TextReader._convert_tokens()
pandas_libs\parsers.pyx in
  pandas._libs.parsers.TextReader._convert_with_dtype()
pandas_libs\parsers.pyx in
  pandas._libs.parsers.TextReader._string_convert()
pandas_libs\parsers.pyx in pandas._libs.parsers._string_box_utf8()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in
  position 8: invalid start byte
During handling of the above exception, another exception occurred:
UnicodeDecodeError Traceback (most recent call last)
  ipython-input-84-c0272ccf19e6 in module

Sample of my data:
Time,Type,Instrument,Product,Qty.,Avg. price,Status
3/27/2019 13:46,BUY,MFSL,MIS,1600,115.25,COMPLETE
3/27/2019 13:46,BUY,MFSL,MIS,500,115.3,COMPLETE

i have already tried checking if there is an invalid character (using Notepad++). "Show all characters"
I couldn't find any difference when comparing this file with a similar one that could be loaded.
Just Need help Troubleshooting the above, If someone can point me in the right direction.

A:

The data you posted works fine for me, but it's several degrees removed from your source. Specifying an encoding when opening the file may fix the problem. You can do this a couple of ways: use the codecs package to open the file and let that decide the encoding, or specify the encoding in csv_read()
    import codecs

doc = codecs.open('document','rU','UTF-16') #open for reading with "universal" type set

df = pandas.read_csv(doc, sep=',')

You also might want to sanitize your column names, as spaces and decimals can cause problems in referencing.
df.columns = df.columns.str.strip().str.lower().str.replace(' ', '_').str.replace('(', '').str.replace(')', '').str.replace('.', '')


Q:

Check if a tree is a BST using a provided higher order function in OCAML

So let me start by saying this was part of a past homework I couldn't solve but as I am preparing for a test I would like to know how to do this. I have these implementations of map_tree and fold_tree provided by the instructor:
let rec map_tree (f:'a -> 'b) (t:'a tree) : 'b tree =
match t with
| Leaf x -> Leaf (f x)
| Node (x,lt,rt) -> Node (f x,(map_tree f lt),(map_tree f rt))

let fold_tree (f1:'a->'b) (f2:'a->'b->'b->'b) (t:'a tree) : 'b =
  let rec aux t =
    match t with
     | Leaf x -> f1 x
     | Node (x,lt,rt) -> f2 x (aux lt) (aux rt)
  in aux t

I need to implement a function that verifies a tree is a BST using the above functions, so far this is what I've accomplished and I'm getting the error:
 Error: This expression has type bool but an expression was expected of type
     'a tree

This is my code:
 let rec smaller_than t n : bool =
 begin match t with
 | Leaf x -> true
 | Node(x,lt,rt) -> (x<n) && (smaller_than lt x) && (smaller_than rt x)
 end

 let rec greater_equal_than t n : bool =
 begin match t with
 | Leaf x -> true
 | Node(x,lt,rt) -> (x>=n) && (greater_equal_than lt x) && (greater_equal_than rt x)
 end

 let check_bst t =
 fold_tree (fun x -> true) (fun x lt rt -> ((check_bst lt) && (check_bst rt)&&(smaller_than lt x)&&(greater_equal_than rt x))) t;;

Any suggestions? I seem to have trouble understanding exactly how higher order functions work in OCAML

A:

What is the specification of a BST? It's a binary tree where:

all the elements in the left subtree (which is also a BST) are strictly smaller than the value stored at the node
and all the ones in the right subtree (which is also a BST) are bigger or equal than the value stored at the node

A fold is an induction principle: you have to explain how to deal with the base cases (the Leaf case here) and how to combine the results for the subcases in the step cases (the Node case here).
A Leaf is always a BST so the base case is going to be pretty simple. However, in the Node case, we need to make sure that the values are in the right subtrees. To be able to perform this check, we are going to need extra information. The idea is to have a fold computing:

whether the given tree is a BST
and the interval in which all of its values live

Let's introduce type synonyms to structure our thoughts:
type is_bst      = bool
type 'a interval = 'a * 'a

As predicted, the base case is easy:
let leaf_bst (a : 'a) : is_bst * 'a interval = (true, (a, a))

In the Node case, we have the value a stored at the node and the results computed recursively for the left (lih as in left induction hypothesis) and right subtrees respectively. The tree thus built is a BST if and only if the two subtrees are (b1 && b2) and their values respect the properties described earlier. The interval in which this new tree's values live is now the larger (lb1, ub2).
let node_bst (a : 'a) (lih : is_bst * 'a interval) (rih : is_bst * 'a interval) =
  let (b1, (lb1, ub1)) = lih in
  let (b2, (lb2, ub2)) = rih in
  (b1 && b2 && ub1 < a && a <= lb2, (lb1, ub2))

Finally, the function checking whether a tree is a BST is defined by projecting out the boolean out of the result of calling fold_tree leaf_bst node_bst on it.
let bst (t : 'a tree) : bool =
  fst (fold_tree leaf_bst node_bst t)


Q:

C++: Unresolved external symbol _sprintf and _sscanf in Visual Studio 2015

For a research project, I'm writing a C++ add-on to a scientific computing language. Unfortunately the library that allows users to do this is not kept very well up-to-date.
I started the project in XCode, where it built fine. Later I had to move to a PC, so I migrated the code to Visual Studio 2015. Since doing this, I haven't been able to build due to the following errors:
LNK2001 : unresolved external symbol _sprintf
LNK2019 : unresolved external symbol _sscanf referenced in function _GetDDouble
LNK2019 : unresolved external symbol _sprintf referenced in function _CheckRunningInMainThread

An attempted fix was to add the header #define _CRT_SECURE_NO_WARNINGS. However, this a) fixed no errors and b) added the warning C4005 : '_CRT_SECURE_NO_WARNINGS': macro redefinition. I assume the library already defined this macro, anticipating this problem. Regardless, it didn't solve the problem.
How should I proceed?

A:

Add the following library to the linker input files:
legacy_stdio_definitions.lib

VS 2015 now uses inline definitions that call internal functions for many of the stdio.h functions.  If an object file (or library member) depends on one of those functions, then the legacy_stdio_definitions.lib provides an externally linkable version of the function that can be linked to.
Your other option is to recompile the unit that depends on those functions with VS 2015 (this is probably the preferred option).


Q:

Adding back layer heading in ArcMap?

I deleted the layer heading thinking that I didn't need it. But after doing some refactoring, it turns out that I do need it but I can't figure out any way to add it back.
How do I add it back?
I'm using ArcMap 10.6.

A:

It is called the layer heading.
Go to symbology.
Change the value field to something else.
Change it back.
It should reappear.
The proper way is
Make sure the layer has headings. ...
Double-click the legend to open the Legend Properties dialog box and select the Items tab.
Click Style.
Click Properties.
Select the General tab.
Choose a heading from the 'Only show classes from this heading' dropdown list.
https://support.esri.com/en/technical-article/000002820


Q:

How to start debugging?

I have learned C and I would like to start to improve open source software. I would like to hack away one irritating bug in GTK+. To see the bug I need to use Gedit.
How can I download the sources of GTK+ and gedit and compile both of them so that I can see where the bug is? And I have never used any debugger in Linux so is there somewhere a tutorial for that?

A:

You can get information about downloading and compiling of gedit here:
http://projects.gnome.org/gedit/developers.html
My Debugger of choice is GDB:
http://www.gnu.org/software/gdb/
GDB is a console application that may be hard to handle for a beginner. Try an IDE like Eclipse that provides a GUI to GDB.

A:

Almost all Linux debuggers are front-ends for or adaptations of the gdb debugger. You should therefore learn how to use this first, preferably by starting on
small programs of your own construction, not giant FOSS codebases. The gdb manual,
available from here is actually a pretty good tutorial.

A:

The information on building and installing GTK+ should be here:
http://www.gtk.org/development.html
The sources should be here:
http://www.gtk.org/download-linux.html
You can check out gdb:
http://www.gnu.org/software/gdb/ That's a pretty standard linux debugger. I would spend time with it on something simple first, or get an IDE that uses it. Learning gdb can be worth the time though.


Q:

Add "Improve edit" option to wiki edit reviews

Subj, for the same reasons we have it for normal suggested edits: if the edit is good, but not quite good enough.
I don't yet see a use case for "Reject and edit".

A:

You see these options for post edits because you can edit them straight. Basically, this is implemented as: 1) approve the suggested edit; 2) immediately make a further edit yourself. This even shows in the revision list (example). Reviewing and editing posts are both obtained at 2,000 rep.
For the tag edits, on the other hand, 5k is required to review (approve/reject), but 20k to edit instantly, therefore you can't actually improve or reject'n'edit until you reach 20k, so you have those options hidden until then.
Of course, nothing stops you from suggesting your improvement independently. But you can only do so after the current edit is decided upon (before that, you see "edit pending" instead of the "edit" link in the tag wiki UI). This is done to avoid conflicting changes.


Q:

Whether to take a holiday or get research experience when transitioning from masters to PhD?

Background:
I'm in a precarious situation.
I'm currently in the sixth semester of a ten-semester (five-year) combined bachelor's/master's program in engineering. So far I've had two relevant industry internships and have been getting stellar grades, but I lack research experience in my field. I am still unsure if I want to pursue a PhD, and I'm a bit apprehensive to make that life decision now.
All six semesters I've been taking classes and conducting research in a not-so-relevant field (mainly because research in my field is hard to get as an undergraduate) - suffice it to say after three years of this, I've somewhat burned out.
I'm currently signing up for classes for my seventh semester, which is the first semester I'm required to take graduate classes. Because I've felt a lot of academic pressure, I decided to sign up for less classes than usual to give myself a respite.
In response to this, my academic adviser recommended that I conduct research at a lab near campus to prepare me for a prospective PhD. I'm reluctant to agree because I wanted to take the semester to relax and pursue various interests I've fallen out of touch with since the start of university.
I voiced my concerns to my adviser and he is continually trying to pressure me to conduct research, citing that not doing so would be a huge missed opportunity and might hurt my chances of applying for a PhD.
Question
I don't want to leave this as an open-ended question (a la "what should I do?"), so I'll try to make it more structured:

How important is having research in a relevant field when applying to PhD programs?
Would PhD programs look unfavourably upon taking a semester to "relax," considering that a PhD requires a great deal of dedication?

A:

Wanna relax, then do so. Don't be somewhere you don't want to be. You have to be mentally ready to do a research. I have seen many cases of young intelligent individuals who started doing PhD, and then for various reasons gave up, because some serious work needed to be done and they want to have well... some fun (rightfully so)!
I would recommend do not burn the bridge with your supervisor as you might start doing PhD in upcoming years. Tell him/her in a meeting that you would like to finish your studies and enjoy life a little bit; before committing yourself to doing research.


Q:

wordpress taxonomy issue?

I am having an issue with the product permalinks on a website I have been asked to fix.
website page where links are broken: http://fallenangelbakery.com/menu/cupcakes/
There is a product-types taxonomy created which gets to the above page ok. However, the links to the individual products do not work. When editing the products, the permalink and the shortlink dont work.
loop code in taxonomy-product-types.php

<?= single_tag_title( '', false ) ?>

<?= category_description()?>

            <? if($wp_query->post_count < 8 && $wp_query->post_count > 4 || $wp_query->post_count == 3){
                    $class = 'medium';
                } else if($wp_query->post_count <= 4){
                    $class = 'large';
                } else {
                    $class = 'small';
                }
            ?>
            <ul class="product-list <?=$class?>">
            <? while ( have_posts() ) : the_post(); ?>

                <a href="<?= the_permalink(); ?>" title="<? the_title(); ?>">

                            <? the_post_thumbnail( 'fab-'.$class.'-image' ); ?>

                    <? the_title(); ?>

            <? endwhile; ?>

the taxonomy is associated with "products" and we get products and product types as menu items in the wp-admin
taxonomy: product-types
label of taxonomy: products
slug: menu
query var: product-types
singular name: product-type
in order to get to the single product i have created a file called taxonomy-product.php.
can anyone give an idea why the product permalink doesnt work at all... even when trying to preview the page in wp-admin
https://wordpress.org/plugins/ultimate-taxonomy-manager/
Many thanks in advance

A:

You should review this: http://codex.wordpress.org/Function_Reference/register_taxonomy
I believe this is a problem with the taxonomy not being public.


Q:

Parsing data using XDocument yield no result -Why?

I have an xml file as under
<!--Sample Person Data-->
<Person>
  <PersonDetail PersonId="1">
    <Name>Priyanka Das</Name>
    <Age>30</Age>
    <Sex>Male</Sex>
    <LivesIn>Bangalore</LivesIn>
    <Email>nb@training.com</Email>
  </PersonDetail>
  <PersonDetail PersonId="2">
    <Name>Shashidhar Nikatani</Name>
    <Age>40</Age>
    <Sex>Male</Sex>
    <LivesIn>Bangalore</LivesIn>
    <Email>sn@training.com</Email>
  </PersonDetail>
  <PersonDetail PersonId="3">
    <Name>Arundhuti Roy</Name>
    <Age>27</Age>
    <Sex>Female</Sex>
    <LivesIn>Kerala</LivesIn>
    <Email>ab@training.com</Email>
  </PersonDetail>
  <PersonDetail PersonId="4">
    <Name>Nitin Mallik</Name>
    <Age>28</Age>
    <Sex>Male</Sex>
    <LivesIn>Bangalore</LivesIn>
    <Email>ng@training.com</Email>
  </PersonDetail>
  <PersonDetail PersonId="5">
    <Name>Essaki Raja Kandaswamy</Name>
    <Age>27</Age>
    <Sex>Male</Sex>
    <LivesIn>Madras</LivesIn>
    <Email>er@training.com</Email>
  </PersonDetail>
</Person>

I need to find out the details of Persons who Lives In Bangalore.
I have done the below but not able to get any result
 XDocument xmlSource = null;
   xmlSource = XDocument.Load(@"D:\Personsample.xml");

            var query = from data in xmlSource.Descendants("Person")
                        where (string)data.Element("LivesIn") == "Bangalore"
                        select data;

Help needed

A:

There are no direct "LivesIn" children of "Person", so data.Element("LivesIn") will invariably not yield anything.
Are you sure you didn't mean:
from data in xmlSource.Descendants("PersonDetail")
                    where (string)data.Element("LivesIn") == "Bangalore"
                    select data;


Q:

Setting a Git alias which uses TR to translate backslash into forward slash

I am trying to set up a Git alias which has to convert a backslash to a forward slash to pass it later to filter-branch command (the need arises since I use Posh and will pass DOS based file path as a parameter).
So I have this alias:
echo-test = "!f() { path=$(echo $1 | tr '\\' '/'); echo $path; }; f"

But I get this error:

tr: warning: an unescaped backslash at end of string is not portable

I tried writing tr '\\\\' '/' inside, thinking that Git simply escapes the \ and bash gets a single \, but I get the same error.
Any ideas?

A:

You need to write 8 backslashes here, because the string will be unescaped three times.
echo-test = "!f() { path=$(echo $1 | tr '\\\\\\\\' '/'); echo $path; }; f"

The first doubling is due to tr as OP have already used.
The second doubling is due to the format of .gitconfig

Inside double quotes, double quote " and backslash \ characters must be escaped: use \" for " and \\ for \.

The third doubling is due to executing the command using sh -c "…".


Q:

Smart Contract to send ether

I have Solidity contract that is meant to send ether to someone. Unfortunately it's giving me a cryptic error message after I confirm the transaction in MetaMask.
I'm testing on a local ethereum network running on ganache and the project was built using a react truffle box.
Contract:
pragma solidity ^0.4.24;

contract Sender {
    uint256 public balance;

    function send(address _receiver) payable {
        msg.sender.transfer(msg.value);
    }

    function getBalance() public returns (uint) {
        return address(this).balance;
    }

}

JavaScript
userInputHandler = (event) => {
    this.setState({amountToPay: event.target.value})

    const contract = require('truffle-contract')
    const sender = contract(Sender);
    sender.setProvider(this.state.web3.currentProvider);

    this.state.web3.eth.getAccounts((error, accounts) => {
        sender.deployed().then((instance) => {

            console.log("Seems to explode after here" );
            return instance.sendTransaction({
                from: accounts[0],
                to: accounts[4],
                value: this.state.web3.toWei(this.state.amountToPay, "ether"),
                gas: "220000"}).then((result) => {

                console.log("result: " + result);
        })
    })
})

};
ErrorMessage
inpage.js:1
MetaMask - RPC Error: Error: Error: [ethjs-rpc] rpc error with payload
{
"id": 8476063269707,
"jsonrpc": "2.0",
"params": ["0xf87182011a85174876e80083035b609406c1939f6cbb68d42333f140cae815cc36d341b0880de0b6b3a764000080822d46a011d708c9d53a5e7e9195c32fab4f6f3cad259887436eadd521d93ac853541455a0176061761d6d14c063eb2b0c359457dec982d72d52f19bdf33fa8f5be20ed939"],
"method": "eth_sendRawTransaction"
} Error: VM Exception while processing transaction: revert

Uncaught (in promise) Error: Error: Error: [ethjs-rpc] rpc error with payload  Error: VM Exception while processing transaction: revert

Solution
send seems to be some kind of reserved word or function that was getting overridden. I changed the function name to sendMoney and all suggestions from @Jaime which fixed my problems.

A:

The error is that your contract can not receive ether because it doesn't have a fallback function. Just add this to it:
function () public payable{
}

This will allows your contract to accept ether.
Another thing is that in your send function you have:
msg.sender.transfer(msg.value);

but should be
 _receiver.transfer(msg.value);

Also, is not clear what are you trying to do in your js code, are you trying to send ether to the contract, or are you trying to use the 'send' function?
In the first case (sending ether to the contract use):
web3.eth.sendTransaction({....})
In the second case (trying to use the send function in your contract), having your contract instance as 'contractInstance' you can do something like this:
var account = web3.eth.accounts[0];
var mycontract = web3.eth.contract(ABI);
var contractInstance = mycontract.at('contractaddress...')
contractInstance.send('0x...',{'value':web3.toWei(myvalue,'ether')} function(err,res){
        if(err){
            console.log('transaction failed')
        }
    })

hope this helps


Q:

How to create and draw a visual swipe gesture

I'd like to try implementing a visual swipe for an iPhone project, like they do in some games, like Fruit Ninja.  As you drag your finger around the screen, it leaves a trail that disappears after a while.  I would think that you could have a fixed number of points in the "chain" and as new points are added to the front, old ones are removed from the rear.  I can see using -touchesMoved to generate new points and an NSMutableArray to keep track of the points.  I just can't imaging what method I'd use to actually draw the segments.  Would I make one CALayer and draw a line connecting the active points?  Or use some other view object and join them together at the points...
Any ideas?

A:

Something like this would work, if you had populated 'points' with CGPoints. Caveat: this is a quick cut, paste and edit job - so there will probably be errors. Also, I use stl::vector for 'points'. You may want to use some other structure.
CGContextRef context = UIGraphicsGetCurrentContext();
CGMutablePathRef dataPath = CGPathCreateMutable();
bool firstPoint = YES;

for (int i=0; i < points.size(); ++i)
    {
    CGPoint point = points[i];
    if (firstPoint)
        {
        CGPathMoveToPoint(dataPath, NULL, point.x, point.y);
        firstPoint = NO;
        }
    else
        {
        CGPathAddLineToPoint(dataPath, NULL, point.x, point.y);
        }
    }

CGContextSetRGBStrokeColor( context, 1.0, 0.0, 0.0, 1.0);
CGContextSetLineWidth( context, 5);
CGContextBeginPath( context );
CGContextAddPath( context, dataPath );
CGContextDrawPath( context, kCGPathStroke);

CGPathRelease(dataPath);


Q:

Including directory and keep it working php

I'm using Codeigniter and facing the following problem.
In a controller, I want to include in some way an application (Not written in Codeigniter) in my controller. I am using file_get_contents now. It's working fine and the application is shown in the controller I made. The problem is, the application contains a lot of forms which are posted to other pages in the application itself. Using file_get_contents, the forms redirect the user to a target outside my controller. This may sound a bit vague, so here's an example:

The user navigates to the controller: 'game/login' and therefore wants
  to visit the login page. The user fills in the form. The form posts
  the data to assets/game/index.php?page=login. This makes the user
  redirect to assets/game/index.php?page=login, and therefore making him
  leave the controller page.

Does anyone have an idea on how to fix this problem?
defined('BASEPATH') OR exit('No direct script access allowed');
class Game extends CI_Controller{

    public function __construct(){
        parent::__construct();
    }

    public function index($page = ''){
        file_get_contents(FCPATH . 'assets/game/index.php?page=' . $page);
    }

}

A:

You can load your external php pages in a iframe but i would suggest you should convert your php files to codeigniter MVC structure to get the advantages.
The quick way is using iframe,but i would ask you to refer this post to get an idea on Iframes when to use & when not to.
Are iframes considered 'bad practice'?


Q:

blender vse video height not divisible by 2 or pillowboxing

I record an area of my desktop for upload to youtube with ffmpeg the area is a 16x9 aspect ratio with a width of 2952x1458
I can upload this video to youtube and it plays properly but of course I need some editing, mainly to remove some junk frames from the beginning and end of the video.
I load up blender vse and make the preferences changes

and go down and edit the encoding settings as well

mainly to go along with youtube recommended video settings
The problem is that when I try to hit animation, blender complains that this video's height is not divisible by 2.

When I change the percentage below x & y to 100% from 50% then the output video has horrible pillow boxing. As you can see from this screenshot:

How can I actually get blender to just take the video that I recorded, cut of the few parts that I don't need and export the video, in pretty much the same way it came in, while avoiding these issues?
Edit
I grab the screen with this ffmpeg command
ffmpeg -an -f "x11grab" -framerate "120" -video_size "2594"x"1458" -i :0.0+5,+257 -c:v "libx264" -crf "16" -bf "2" -flags "+cgop" -movflags "faststart" -pix_fmt "yuv420p" -preset "ultrafast" "$1".mkv
here is the raw upload: https://www.youtube.com/watch?v=2NzSlo3knbk
here is the out output from blender: https://www.youtube.com/watch?v=LYUTu6UV5ug
these are the export settings that I setup in blender render preferences

A:

EDIT: The most direct answer to the question is the discrepancy between the capture dimensions and the export dimensions. The video is being captured in 2594*1458, which is a 16:9 ratio, whereas blender is exporting at 2952*1458, which is not a 16:9 ratio. It is likely to be a simple typo. This ratio difference is causing the letterboxing on the exported video.
sambler: Requiring dimensions to be divisible by two is a limitation of the H.264 encoder in Blender.
Original post
Render Dimensions:
The first problem here is blender downsizes the video to a non-divisible-by-two height. A simple way around this is to bump your scaling percentage up or down one or two percent. A better way would be to manually input dimensions instead of using the percentage slider. Blender can do math in text input fields, so you can simply put 2952/2 into the X dimension and 1458/2 in Y. If the result is an odd number, just bump it up one pixel. Amaranth Toolset (included in blender) has a nifty tool to show the final resolution of the render. Enable it in your user prefs and a new line of dimensions will show up in the render properties:

Letterboxing:
The second problem is letterboxing, the black bars on the top and bottom of the video. This is actually Youtube's fault because your video isn't a perfect 16:9 aspect ratio. To see your aspect ratio, simply divide your width by your height, in this case 2952/1458 = 2.024... Compare this width/height ratio with that of HD video: 1920/1080 = 1.777... You can see now the ratios are different. This difference ends up as letterboxing on Youtube. Pillarboxing occurs when your video is more square than the 16:9 player.
There are three ways you can deal with this difference: upload the video in its original aspect ratio and accept the letterboxing Youtube gives you; crop the sides off the footage to get a perfect 1.777... ratio on your output; distort the footage to fit within the desired ratio.
Personally, I would take the letterboxing because it means the entire area of my footage is visible without distortion, especially because the whole desktop is important.
Distortion:
If you absolutely do not want letterboxing, but still want all of the footage, you will need to distort the footage to fit in the 1.777 ratio. To do this, simply change your render output dimensions to a 16:9 ratio (2592/1458, 1920/1080, 1280/720, etc.). Blender distorts VSE strips to fit the render dimensions.
Cropping:
To make your video 16:9 ratio, your dimensions would need to be 2592 wide by 1458 tall (or some percentage of). A normal application would allow you to crop the video, but blender does not. You will need to use a transform layer on your VSE footage to compensate the aspect ratio difference between your footage and the new render dimensions.
Start out with your footage in the VSE. Change your render dimensions to 2592 wide by 1458 tall. Your footage will look distorted; this is expected. Select your strip in the VSE and add a transform layer effect. Open the properties region for the strips by pressing N. The Effect Strip panel contains scale controls for X and Y dimensions. The one you need to worry about is X. Input this value into X: 1.139 - this corrects the ratio difference. I came to this number by dividing your original ratio (2.024...) by the desired ratio (1.777...). If you have multiple strips, you will need to do this for each one because the effect strip is linked to only a single input strip.

Final Thoughts:
Letterboxing may be ugly, but it is a necessary evil if you don't want to lose information. Cropping may be more acceptable for camera footage. I can't think of a time when distortion is acceptable.


Q:

Nginx only serving first 72kbs of my JS files

Nginx appears to only be loading the first 72kbs of my javascript files. I've searched all around  my nginx config files and cannot see this setting anywhere. I've added things like
location / {
    ...
    proxy_max_temp_file_size 1m;
    ...
}

and
location / {
    ...
    sendfile on;
    sendfile_max_chunk 1m;

    ...
}

But still I'm unable to overwrite this weird setting that is only allowing first part of the file to load.
The connection uses nginx proxy_pass to foward port 80 to kibanas port '5601'. I feel like there could be a setting that limits file transfer over proxy? Just not sure where to find it.
proxypass connection looks like:
server {
    listen 80;

    server_name logs.mydomain.com;

    auth_basic "Restricted Access";
    auth_basic_user_file /etc/nginx/htpasswd.users;

    location / {
        proxy_pass http://localhost:5601;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

And my default nginx settings is posted here:

http://www.heypasteit.com/clip/OEKIR

A:

Would appear when disk space is low NGINX defaults to minimal safe settings.
When I checked the VMs health I noticed that the disk drive was full. Elasticsearch was logging a couple of GBs worth of text in to error logs each day. I still Have not fully identified why elastic search is flooding the error logs.
But I think excessive disk space usage has contributed to this error. Nginx could be detecting this and switching over to minimal safe configuration which would only allow 72kbs of data to be served per file.
Once I cleared out the excessive logs, Nginx began serving the full JS files again without needing to restart nginx or kibana.


Q:

How do declare an array in C++ as a parameter?

I am working with propriety code in my iOS project and all I have access to is the header files for my project. How do you declare an array in C++ so that it will return an array when I make a call?
Here's the header file method,
 short WI_GetIDsFromList(int32_t module, int32_t *idsArray, uint32_t *count);

How do you declare an array to received an array of in32_t? I keep getting a parameter error for returnedIdsArray when I make this call? It works perfectly fine for count? I tried making it into a pointer but it did not work?
    //Array of ID's
    int32_t returnedIdsArray[] = {};

    // Array of ID's count
    uint32_t count;

 rc += WI_GetIDsFromList(mod, returnedIdsArray, &count);

Another Example
short dpCount;

//Get number of data points from the device
WI_GetDatapointCount(modIDHDS, &dpCount);

//dpCount now has returned value of method WI_GetDatapointCount
NSLog@"%d", int(dpCount);

A:

I think Mochi's question is how to declare the array that it suits the need of the function given in the header. If I understand him right, he has no influence to the function taking the array as parameter.
Did you try:
int32_t returnedIdsArray[MaximumExpectedIds];

Maybe there is also a function in the API giving you the number of Ids that you could use to determine the array size.


Q:

General database design: Is it ever considered "okay" to create a non-normalized table on purpose?

After-edit: Wow, this question go long.  Please forgive =\
I am creating a new table consisting of over 30 columns.  These columns are largely populated by selections made from dropdown lists and their options are largely logically related.  For example, a dropdown labeled Review Period will have options such as Monthly, Semi-Annually, and Yearly.  I came up with a workable method to normalize these options down to numeric identifiers by creating a primitives lookup table that stores values such as Monthly, Semi-Annually, and Yearly.  I then store the IDs of these primitives in the table of record and use a view to join that table out to my lookup table.  With this view in place, the table of record can contain raw data that only the application understands while allowing external applications and admins to run SQL against the view and return data that is translated into friendly information.
It just got complicated.  Now these dropdown lists are going to have non-logically-related items.  For example, the Review Period dropdown list now needs to have options of NA and Manual.  This blows my entire grouping scheme out of the water.
Similar constructs that have been used in this application have resorted to storing repeated string values across multiple records.  This means you could have hundreds of records with the string 'Monthly' stored in the table's ReviewPeriod column.  The thought of this happening has made me cringe since I've started working here, but now I am starting to think that non-normalized data may be the best option here.
The only other way I can think of doing this using my initial method while allowing it to be dynamic and support the constant adding of new options to any dropdown list at any time is this:  When saving the data to the database, iterate through every single property of my business object (.NET class in this case) and check for any string value that exists in the primitives table.  If it doesn't, add it and return the auto-generated unique identifier for storage in the table of record.  It seems so complicated, but is this what one is to go through for the sake of normalized data?

A:

Anything is possible.  Nobody is going to haul you off to denormalization jail and revoke your DBA card.  I would say that you should know the rules and what breaking them means.  Once you have those in hand, it's up to your and your best judgement to do what you think is best.


Q:

Ruby Enumerable with underlying Hash

I have a class that uses Enumerable and Forwardable mixins. The things is that even though #each has been implemented (or delegated), #member? (which also comes with Enumerable) is not working properly.
require "forwardable"
class RestrictedHash
  include Enumerable
  extend Forwardable

  def_delegators :@hash, :[], :[]=, :each

  def initialize
    @hash = {}
  end
end

r_h = RestrictedHash.new
r_h[:a] = []
r_h.member?(:a)       #=> false
r_h.member?(:a, [])   #=> Wrong number of arguments (2 for 1)
r_h.member?([:a, []]) #=> true

h = {}
h[:a] = []
h.member?(:a)         #=> true
h.member?([:a, []])   #=> false

Any ideas of why I am getting this difference in behavior?

A:

The reason for this is that the each method on a Hash yields pairs of key and value so for your example @hash:
irb(main):001:0> h = {}
=> {}
irb(main):002:0> h[:a] = []
=> []
irb(main):003:0> h.each { |i| puts i.inspect }
[:a, []]

This means that when the implementation of member? in Enumerable uses each to check if the value specified is a member it will successfully find ([:a, []] but not the key :a on its own.
In the Hash class itself member? is implemented to call rb_hash_has_key.


Q:

iPhone Theos, audio recording and saving with one button?

i've never been good with c++ but im learning with theos and i waswondering, is there a way to make a button that can start recording audio, then stop when it is pressed again? or even better, could i have it record until the phone detects that you are done talking???

A:

Yes.  The combination of a UIButton, one BOOL state variable, and the use of an iOS audio API (there are several, such as the Audio Queue API) will do this.


Q:

How to use model.fit_generator in keras

When and how should I use fit_generator?
What is the difference between fit and fit_generator?

A:

If you have prepared your data and labels in all necessary aspects and simply can assign these to an array x and y, than use model.fit(x, y).
If you need to preprocess and/or augment your data while training, than you can take advantage of the generators that Keras provides.
You could for example augment images by applying random transforms (very helpful if you only have little data to train with), pad sequences, tokenize text, let Keras automagically read your data from a folder and assign appropiate classes (flow_from_directory) and much more.
See here for examples and boilerplate code for image preprocessing: https://keras.io/preprocessing/image/
or here for text preprocessing:
https://keras.io/preprocessing/text/
fit_generator also will help you to train in a more memory efficient way since you load data only when needed. The generator function yields (aka "delivers") data to your model batch by batch on demand, so to say.


Q:

Program a full screen uncloseable window on OS X

We have a game at work where if you can send the security guy an email from someones unlocked computer you get a prize. This Halloween I am setting a trap.
I have a simple program called systems-engage that starts a key listener and opens my inbox programmatically. When someone starts using the keyboard I want my program to launch a full-screen visual assault of horror film images with extremely loud screaming.
I can handle everything else mentioned, I just need a dead simple way to open a full screen window that can only be closed by an escape sequence I define in code.
I'm going for lowest hanging fruit here (Obj-C, C++, Java, python ruby, javascript hell whatever gets the job done quick and dirty
I read a primer on opening a full screen window in Obj-C but it can be closed really easily. The point of this prank is to shame my coworker for invading my computer for at least 10 or 20 seconds and I can't do that if he can just hit Appl-Q.
Happy Halloween!

A:

To get something like this with a Cocoa app, you can place the following code in your app delegate's - (void)applicationDidFinishLaunching: (or similar):
// Set the key equivalent of the "Quit" menu item to something other than ⌘-Q.
// In this case, ^-⌥-⌘-Q.
// !!! Verify this and make sure you remember it or else you're screwed. !!!
NSMenu *mainMenu = [NSApplication sharedApplication].mainMenu;
NSMenu *appMenu = [[mainMenu itemAtIndex:0] submenu];
NSMenuItem *quitItem = [appMenu itemWithTitle:@"Quit <Your App Name Here>"];
quitItem.keyEquivalentModifierMask = NSEventModifierFlagControl | NSEventModifierFlagOption | NSEventModifierFlagCommand;
quitItem.keyEquivalent = @"q";

// Enable "kiosk mode" -- when fullscreen, hide the dock and menu bar, and prevent the user from switching away from the app or force-quitting.
[NSApplication sharedApplication].presentationOptions = NSApplicationPresentationHideDock
                                                      | NSApplicationPresentationHideMenuBar
                                                      | NSApplicationPresentationDisableProcessSwitching
                                                      | NSApplicationPresentationDisableForceQuit
                                                      | NSApplicationPresentationDisableSessionTermination;

// Remove the window's close button, making it no longer close with ⌘-W.
self.window.styleMask = self.window.styleMask & ~NSWindowStyleMaskClosable;

// Make the window take up the whole screen and make it full-screen.
[self.window setFrame:[[NSScreen mainScreen] frame] display:YES];
[self.window toggleFullScreen:self];

This will make a "kiosk" type app which can only be closed via the custom quit shortcut you set (or, you know, shutting down the computer forcibly). The presentation options prevents the user from accessing the menu bar, dock, and app switching (via ⌘-Tab) or spaces, bringing up the force-quit window, or bringing up the shutdown/restart/sleep window. Basically, make sure you set up a keyboard shortcut that you remember to terminate the app, otherwise, you're going to be locked out of your machine short of forcibly powering it off. It's a total PITA.
Of course, some of these customizations can be done in Interface Builder too (setting the key equivalent of the "Quit" menu item is easier there, and you can turn off the window's close control as well, as mentioned in comments above), but I just wanted to include this as code so it was more transparent (rather than uploading an Xcode project).
Happy Halloween!


Q:

Add data to a generic collection in java

Is there any way i can add data to a generic collection in Java.
For eg:-
import java.util.List;
import java.util.Vector;

public class testGenerics {
    public static void main(String args[]) {
        Vector<? extends Number> superNumberList = null;

        // I can do this
        Vector<Integer> subList = new Vector<Integer>();
        subList.add(2);
        superNumberList = subList;

        // But i cannot do this
        // Gives the below compilation error.
        //The method add(capture#2-of ? extends Number) in the type
        //Vector<capture#2-of ? extends Number> is not applicable for the arguments (Integer)
        superNumberList = new Vector<Integer>();
        superNumberList.add(new Integer(4));

        superNumberList = new Vector<Float>();
        superNumberList.add(new Float(4));
    }

}

As mentioned in my comments i have compilation errors when i try to add an Integer or Float data to superNumberList.
I am able to do it , the first way , but would like to do it the second way and not sure why Java does not allow me to do it the second way.
I have a suitation where i have a super class which has this superNumberList and all the subclasses are trying to use this same variable but has different data types in this collection like Integer , Float etc.

A:

A Vector<? extends Number> is a Vector of an unknown Number type. As such, you cannot add anything into it.
It could be a Vector<Float>. So you cannot add an Integer.
But it could also be a Vector<Integer>. So you cannot add a Float.
The only thing you know about it is that whatever you pull out of the Vector will be a Number.

If you have a superclass that has subclasses for Integer, Float and so on, you should make the superclass generic:
class SuperClassWithVector<T extends Number>{
    protected Vector<T> myVector;
}

class FloatSubClass extends SuperClassWithVector<Float>{
   // here myVector takes Float
}

If you want a Vector that can take both Integer and Float (not sure if that is what you want), then you can use a Vector<Number>.


Q:

MySQL multiple results with find in set of values

I need to get multiple rows with articles where the article IDs are in the list below. (in the string list)
SELECT id, title FROM articles WHERE FIND_IN_SET(id, "1,2,3,4,5,9,25");

How to do that correctly?

A:

Try:
SELECT id, title
FROM articles
WHERE FIND_IN_SET(id, '1,2,3,4,5,9,25') <> 0


Q:

Comment exprimer son agrément avec une négation : par « oui » ou par « non » ?

Exemple :

— Ce n'est pas une question déjà posée.
— Non, c'en est une nouvelle.

ou

— Ce n'est pas une question déjà posée.
— Oui, c'en est une nouvelle.

A:

L'agrément s'exprime normalement avec un « non » qui reprend la négation de l'assertion.

— Ce n'est pas une question déjà posée.
— Non, c'en est une nouvelle.

Oui est peu idiomatique ici mais néanmoins équivalent à non.

— Oui, c'en est une nouvelle.

Référence: TLFi, « oui »

Oui, adv.
...
III. − [En concurrence avec non; marque l'acceptation d'un énoncé négatif: là
où non porterait sur l'énoncé lui-même (en confirmant son signe négatif), oui
porte sur l'énonciation et signifie «vous avez raison de dire que (+ énoncé
négatif)», «il est vrai que (+ énoncé négatif)»]

On pourrait donc aussi répondre,

— C'est vrai, c'en est une nouvelle.

La contradiction utilise si:

— Si, c'est une question déjà posée !

Référence: TLFi, « non »

Non, adv.
...
B. − [Signifie l'acceptation d'un énoncé négatif; s'oppose à si exprimant le
rejet]


Q:

PHPExcel ReadFilter Class

I am attempting to use a ReadFilter with PHPExcel to only read in certain columns.
I am using the example from their documentation:
class columnFilter implements PHPExcel_Reader_IReadFilter
{
    private $_startRow = 0;
    private $_endRow = 0;
    private $_columns = array();

    public function __construct($startRow, $endRow, $columns) {
        $this->_startRow    = $startRow;
        $this->_endRow      = $endRow;
        $this->_columns     = $columns;
    }

    public function readCell($column, $row, $worksheetName = '') {
        if ($row >= $this->_startRow && $row <= $this->_endRow) {
            if (in_array($column,$this->_columns)) {
                return true;
            }
        }
        return false;
    }
}

I am using an array called $importColsFilter which is shown below. I am passing this as the column for the ReadFilter.
$importColsFilter

Array (
    [0] => A
    [1] => B
    [2] => C
    [3] => H
    [4] => I
    [5] => J
)

$filterColumns = new columnFilter(2,8,$importColsFilter);
$objReader->setReadFilter($filterColumns);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);

When I grab the entire sheet ($sheetData), I was expecting to only get Columns A, B, C, H, I, and J. However, I am getting columns A through J as a range and anything in between that as seen with the array dump below.
$sheetData

Array (
    [A] => CellValue1
    [B] => CellValue2
    [C] => CellValue3
    [D] =>
    [E] =>
    [F] =>
    [G] =>
    [H] => CellValue4
    [I] => CellValue5
    [J] => CellValue6
)

The above looks to be the behavior of passing a range array to the filter instead of a normal array like so: new columnFilter(2,8,range('A','J'))
It appears the filter works for grabbing the data, but it's dumping the columns into the array anyway with NULL value. Is this the expected behavior? Can I just return the columns I want?
I was looking for a clean solution using the PHPExcel class. If there is no way there, I can just remove the array entries that are returned as NULL and dump it into another array. An example below:
foreach(array_Keys($sheetData) as $sheetDataKey) {
    foreach($sheetData[$sheetDataKey] as $key => $value) {
        if(array_key_exists($key, $sheetData[$sheetDataKey]) && is_null($sheetData[$sheetDataKey][$key])) {
            unset($sheetData[$sheetDataKey][$key]);
        }
    }
}

The portion in the class that is checking for the column to be read is in the array passed to the function, that it would only return that column. I wasn't expecting to see columns returned with a NULL value.  if (in_array($column,$this->_columns))
Is there anyway to do this with straight PHPExcel, or should I just pop the array entries that are NULL?

A:

I made PHPExcelFormatter if I needed to get only certain columns from excel file. Unfortunately it dosen't support $startRow and $endRow, but it should be quite easy to add it.
It's basically like your columnFilter. It outputs array with your own keys.
It takes array as in demo $formatterColumns. For example, to skip D-G.
<?php

// Load file
$formatter = new PHPExcelFormatter('example1.xls');

// Output columns array (document dosen't have column names on first row)
$formatterColumns = array(
    0 => 'A',
    1 => 'B',
    2 => 'C',
    7 => 'H',
    8 => 'I',
    9 => 'J'
)

// Set our columns
$formatter->setFormatterColumns($formatterColumns);

// Output as array
$output = $formatter->output('a');

// Print array
echo '<pre>'.print_r($output, true).'</pre>';

?>

Output would be:
Array (
    [A] => CellValue1
    [B] => CellValue2
    [C] => CellValue3
    [H] => CellValue4
    [I] => CellValue5
    [J] => CellValue6
)


Q:

A different way to prove that $\int_{1+\sqrt{2}}^{\infty} \frac{\ln(1+x)}{1+x^{2}} \, dx = \frac{3 G}{4} + \frac{\pi}{16} \, \ln 2$

From the fact that $$\int_{0}^{1} \int_{0}^{1} \frac{1}{2-x^{2}-y^{2}} \, dx \, dy $$ is an integral representation of Catalan's constant ($G$), I was able to deduce that $$\int_{1+\sqrt{2}}^{\infty} \frac{\ln(1+x)}{1+x^{2}} \, dx = \int_{0}^{\pi/8} \ln(1+ \cot u) \, du = \frac{3G}{4} + \frac{\pi}{16} \, \ln 2\tag{1}.$$

What is another way to prove $(1)$ that preferably doesn't involve the dilogarithm function?

EDIT:
In response to Dr. MV's comment, the following is how I deduced $(1)$ from that integral representation of Catalan's constant.
$$ \begin{align}  G&= \int_{0}^{1} \int_{0}^{1} \frac{1}{2-x^{2}-y^{2}} \, dx \, dy \\ &= \int_{0}^{1} \frac{1}{2-y^{2}} \int_{0}^{1} \frac{1}{1-\frac{x^{2}}{2-y^{2}}} \, dx \, dy \\ &= \int_{0}^{1} \frac{1}{\sqrt{2-y^{2}}} \,  \text{artanh} \left(\frac{1}{\sqrt{2-y^{2}}} \right) \, dy \\ &= \int_{0}^{\pi/4} \text{artanh} \left(\frac{1}{\sqrt{2} \cos \theta} \right) \, d \theta \\ &= \frac{1}{2} \int_{0}^{\pi/4} \ln \left(\frac{\sqrt{2} \cos \theta +1}{\sqrt{2} \cos \theta -1} \right) \, d \theta \\ &= \frac{1}{2} \int_{0}^{\pi/4} \ln \left(\frac{(\sqrt{2} \cos \theta+1)^{2}}{2  \cos^{2} \theta -1} \right) \, d \theta \\ &=\int_{0}^{\pi/4} \ln (\sqrt{2} \cos \theta +1) \, d \theta - \frac{1}{2} \int_{0}^{\pi/4} \ln(\cos 2 \theta) \, d \theta \\ &= \int_{0}^{\pi/4} \ln\left(\sqrt{2} \cos \left(\frac{\pi}{4}  - \phi\right)+1\right) \, d \phi - \frac{1}{4} \int_{0}^{\pi/2} \ln( \cos \tau) \, d \tau \\ &= \int_{0}^{\pi/4} \ln \left(\sin(\phi) + \cos(\phi)+1\right) \, d \phi - \frac{1}{4} \left(- \frac{\pi}{2} \,  \ln 2 \right) \\ &= \int_{0}^{\pi/4} \ln (\sin \phi) \, d \phi + \int_{0}^{\pi/4} \ln \left(1+ \frac{1+ \cos \phi}{\sin \phi} \right) \, d \phi + \frac{\pi}{8} \,  \ln 2 \\ &= - \frac{G}{2} - \frac{\pi}{4} \,  \ln 2 + \int_{0}^{\pi/4} \ln \left(1+ \cot \frac{\phi}{2} \right) \, d \phi + \frac{\pi}{8} \, \ln 2 \\ &=  - \frac{G}{2} - \frac{\pi}{8} \, \ln 2 + 2 \int_{0}^{\pi/8} \ln (1 + \cot u) \, du \end{align}$$

A:

Using the following trigonometric identitiy:
$$(1+\cot x)^2 =\frac{ 2 \tan\left(\frac{\pi}{4}+x\right)}{\tan(2 x) \, \tan(x)},$$
We have
\begin{align}2 \int_0^{\pi/8} \ln(1+ \cot x) \, dx=
 & \ln2 \int_0^{\pi/8} dx-\int_0^{\pi/8} \ln \tan 2 x \, dx
  \\ -
 & \int_0^{\pi/8} \ln \tan x \, dx+\int_0^{\pi/8} \ln \tan\left(\frac{\pi}{4}+x\right)\, dx \tag{1}
  \\ =
  & \frac{\pi}{8} \ln 2-\frac12 \int_0^{\pi/4} \ln \tan x \, dx
 \\ -
  & \int_0^{\pi/8} \ln \tan x \, dx-\int_{\pi/8}^{\pi/4} \ln \tan x \, dx \tag{2}
  \\ =
  & \frac{\pi}{8} \ln 2-\frac32  \int_0^{\pi/4} \ln \tan x \, dx
  \\=
  &  \frac{\pi}{8} \ln 2 + \frac32 G.
 \end{align}
Where, to arrive at $(2)$ from $(1)$ we have substituted $x \mapsto x/2$ in the second integral, and in the last integral we
substituted $x \mapsto \pi/4-x$, in tandem with the fact that $\tan(\pi/2-x) = 1/\tan(x)$.
Also, the integral $\int_0^{\pi/4} \ln \tan x \, dx = - G$ is well known and can be easily reproduced.

A:

Using the identity

$$
\log(\cos(x))=-\log(2)+\sum_{k=1}^\infty(-1)^{k-1}\frac{\cos(2kx)}k\tag{1}
$$

and the evaluations

$$
\begin{align}
\sin(3k\pi/4)-\sin(k\pi/4)
&=2\color{#C00000}{\cos(k\pi/2)}\color{#00A000}{\sin(k\pi/4)}\\
&=\left\{\begin{array}{}
\color{#C00000}{0}&\text{if $k$ is odd}\\
2(-1)^{\frac{k/2+1}2}&\text{if $k/2$ is odd}\\
\color{#00A000}{0}&\text{if $k/2$ is even}
\end{array}\right.\tag{2}\\
\sin(k\pi/2)&=\left\{\begin{array}{}
(-1)^{\frac{k-1}2}&\text{if $k$ is odd}\\
0&\text{if $k$ is even}
\end{array}\right.\tag{3}
\end{align}
$$

we get
$$
\begin{align}
&\int_{1+\sqrt2}^\infty\frac{\log(1+x)}{1+x^2}\,\mathrm{d}x\tag{4a}\\
&=\int_{3\pi/8}^{\pi/2}\log(1+\tan(x))\,\mathrm{d}x\tag{4b}\\
&=\int_{3\pi/8}^{\pi/2}\left[\log(\cos(x)+\sin(x))-\log(\cos(x))\right]\,\mathrm{d}x\tag{4c}\\
&=\int_{3\pi/8}^{\pi/2}\left[\log(\sqrt2\cos(x-\pi/4))-\log(\cos(x))\right]\,\mathrm{d}x\tag{4d}\\
&=\frac\pi{16}\log(2)+\int_{\pi/8}^{\pi/4}\log(\cos(x))\,\mathrm{d}x-\int_{3\pi/8}^{\pi/2}\log(\cos(x))\,\mathrm{d}x\tag{4e}\\
&=\frac\pi{16}\log(2)+\left[\sum_{k=1}^\infty(-1)^{k-1}\frac{\sin(2kx)}{2k^2}\right]_{\pi/8}^{\pi/4}\,-\left[\sum_{k=1}^\infty(-1)^{k-1}\frac{\sin(2kx)}{2k^2}\right]_{3\pi/8}^{\pi/2}\tag{4f}\\
&=\frac\pi{16}\log(2)+\sum_{k=1}^\infty(-1)^{k-1}\frac{\sin(k\pi/2)-\sin(k\pi/4)+\sin(3k\pi/4)}{2k^2}\tag{4g}\\
&=\frac\pi{16}\log(2)+\sum_{k=0}^\infty\frac{(-1)^k}{2(2k+1)^2}+\frac{2(-1)^k}{2(4k+2)^2}\tag{4h}\\
&=\frac\pi{16}\log(2)+\frac34\mathrm{G}\tag{4i}
\end{align}
$$
Explanation:
$\text{(4b)}$: substitute $x\mapsto\tan(x)$
$\text{(4c)}$: $(1+\tan(x))\cos(x)=\cos(x)+\sin(x)$
$\text{(4d)}$: $\cos(x)+\sin(x)=\sqrt2\cos(x-\pi/4)$
$\text{(4e)}$: substitute $x\mapsto x+\pi/4$ in the left integral
$\text{(4f)}$: apply $(1)$
$\text{(4g)}$: evaluate at the limits
$\text{(4h)}$: apply $(2)$ and $(3)$
$\text{(4i)}$: apply the definition of Catalan's Constant

A:

Perform the change of variable $y=\arctan x$,
$\displaystyle I=\int_{1+\sqrt{2}}^{\infty} \frac{\ln(1+x)}{1+x^{2}} \, dx=\int_{\tfrac{3\pi}{8}}^{\tfrac{\pi}{2}}\ln(1+\tan x)dx=\int_{\tfrac{3\pi}{8}}^{\tfrac{\pi}{2}} \ln\left(\sin x+\cos x\right)dx-\int_{\tfrac{3\pi}{8}}^{\tfrac{\pi}{2}}\ln\left(\cos x\right)dx$
$\begin{align}\displaystyle \int_{\tfrac{3\pi}{8}}^{\tfrac{\pi}{2}} \ln\left(\sin x+\cos x\right)dx&=\int_{\tfrac{3\pi}{8}}^{\tfrac{\pi}{2}}\ln\left(\sqrt{2}\cos\left(\dfrac{\pi}{4}-x\right)\right)dx\\
&=\dfrac{\pi}{16}\ln 2+\int_{\tfrac{3\pi}{8}}^{\tfrac{\pi}{2}}\ln\left(\cos\left(\dfrac{\pi}{4}-x\right)\right)dx\\
&=\dfrac{\pi}{16}\ln 2+\int_{\tfrac{\pi}{8}}^{\tfrac{\pi}{4}}\ln(\cos x)dx\\
&=\dfrac{\pi}{16}\ln 2+\int_{0}^{\tfrac{\pi}{4}}\ln(\cos x)dx-\int_{0}^{\tfrac{\pi}{8}}\ln(\cos x)dx
\end{align}$
Perform the change of variable $y=\dfrac{\pi}{2}-x$,
$\displaystyle \int_{\tfrac{3\pi}{8}}^{\tfrac{\pi}{2}}\ln\left(\cos x\right)dx=\int_{0}^{\tfrac{\pi}{8}}\ln\left(\sin x\right)dx$
Therefore,
$\begin{align}
\displaystyle I&=\dfrac{\pi}{16}\ln 2+\int_{0}^{\tfrac{\pi}{4}}\ln(\cos x)dx-\int_{0}^{\tfrac{\pi}{8}}\ln(\cos x)dx-\int_{0}^{\tfrac{\pi}{8}}\ln\left(\sin x\right)dx\\
&=\dfrac{\pi}{16}\ln 2+\int_{0}^{\tfrac{\pi}{4}}\ln(\cos x)dx-\int_{0}^{\tfrac{\pi}{8}}\ln(\cos x\sin x)dx\\
&=\dfrac{\pi}{16}\ln 2+\int_{0}^{\tfrac{\pi}{4}}\ln(\cos x)dx-\int_{0}^{\tfrac{\pi}{8}}\ln\left(\dfrac{\sin(2x)}{2}\right)dx\\
&=\dfrac{\pi}{16}\ln 2+\int_{0}^{\tfrac{\pi}{4}}\ln(\cos x)dx-\dfrac{1}{2}\int_{0}^{\tfrac{\pi}{4}}\ln\left(\dfrac{\sin x}{2}\right)dx\\
&=\dfrac{3\pi}{16}\ln 2+\int_{0}^{\tfrac{\pi}{4}}\ln(\cos x)dx-\dfrac{1}{2}\int_{0}^{\tfrac{\pi}{4}}\ln\left(\sin x\right)dx\\
&=\dfrac{3\pi}{16}\ln 2+\dfrac{1}{2}\int_{0}^{\tfrac{\pi}{4}}\ln(\cos x)dx+\dfrac{1}{2}\int_{0}^{\tfrac{\pi}{4}}\ln(\cot x)dx
\end{align}$
Since,
$\displaystyle \int_{0}^{\tfrac{\pi}{4}}\ln(\cos x)dx=\dfrac{1}{2} G-\dfrac{1}{4}\pi\ln 2$
and,
$\displaystyle \int_{0}^{\tfrac{\pi}{4}}\ln(\cot x)dx=G$
then,
$\begin{align}
I&=\dfrac{3\pi}{16}\ln 2+\dfrac{1}{4} G-\dfrac{1}{8}\pi\ln 2+\dfrac{1}{2}G\\
&=\dfrac{\pi}{16}\ln 2+\dfrac{3}{4}G
\end{align}$
PS:
Proof of
$\displaystyle \int_{0}^{\tfrac{\pi}{4}}\ln(\cos x)dx=\dfrac{1}{2} G-\dfrac{1}{4}\pi\ln 2$
$\begin{align}
\displaystyle \int_0^{\tfrac{\pi}{4}}\ln(\sin x)dx+\int_0^{\tfrac{\pi}{4}}\ln(\cos x)dx&=\int_0^{\tfrac{\pi}{4}}\ln(\sin x)dx+\int_{\tfrac{\pi}{4}}^{\tfrac{\pi}{2}}\ln(\sin x)dx\\
&=\int_0^{\tfrac{\pi}{2}}\ln(\sin x)dx\\
&=2\int_0^{\tfrac{\pi}{4}}\ln\left(\sin(2x)\right)dx\\
&=2\int_0^{\tfrac{\pi}{4}}\ln\left(2\sin x\cos x\right)dx\\
&=\dfrac{1}{2}\pi\ln 2+2\int_0^{\tfrac{\pi}{4}}\ln(\sin x)dx+2\int_0^{\tfrac{\pi}{4}}\ln(\cos x)dx
\end{align}$
Therefore,
$\displaystyle \int_0^{\tfrac{\pi}{4}}\ln(\sin x)dx+\int_0^{\tfrac{\pi}{4}}\ln(\cos x)dx=-\dfrac{1}{2}\pi\ln 2$
and,
$\displaystyle G=\int_0^{\tfrac{\pi}{4}}\ln(\cot x)dx=\int_0^{\tfrac{\pi}{4}}\ln(\cos x)dx-\int_0^{\tfrac{\pi}{4}}\ln(\sin x)dx$
therefore,
$\displaystyle \int_0^{\tfrac{\pi}{4}}\ln(\cos x)dx=\dfrac{1}{2}G-\dfrac{1}{4}\pi\ln 2$
$\displaystyle \int_0^{\tfrac{\pi}{4}}\ln(\sin x)dx=-\dfrac{1}{2}G-\dfrac{1}{4}\pi\ln 2$


Q:

Pulling a specific link from a site

I a m trying to pull links from a website, the HTML of what I want look like the below:

  NA LCS Week 8 Tease: TSM

My test code looks like:
string mainURL = "http://na.leagueoflegends.com/en/news/";
HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = web.Load(mainURL);

var findClass = doc.DocumentNode.Descendants("div")
                   .Where(d => d.Attributes.Contains("class") &&
                               d.Attributes["class"].Value.Contains("default-2-3"));
MessageBox.Show(findClass.ElementAt(1).ToString());

Currently the message box shows:

HtmlAgilityPack.htmlNode

I based my code off of this finding specific link from website, I am new to using HTMLAgilityPack beyond just copying the XPath.
For reference, the site I am trying to extract information is: http://na.leagueoflegends.com/en/news/

A:

You are close to the final step. Just a little more.
var findClass = doc.DocumentNode.Descendants("div").Where(d => d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("default-2-3")).Select(_ => _.Descendants("a").FirstOrDefault()?.Attributes["href"]);


Q:

Match timestamp with preg_match

I have this regular expression right now and it's just printing out 1: ^[0-9]{10,15}$^. I want to see if there is any timestamp in the filename (for example 3843_1328414035.jpg) or not. What do I wrong?
Thanks in advance.

A:

you can have this preg_match statement
$matches = array();
preg_match("/(\d{10})/","1234_1328414035.jpg",$matches);
print_r($matches);

or simply check if pattern exists
if(preg_match("/(\d{10})/","1234_1328414035.jpg")) {echo "found";}


Q:

tmux mouse scrolling without altering copy/paste?

I'm having difficultly finding an explanation for allowing the OS default copy/paste capabilities (i.e. highlight a portion of text and then use standard shortcut or right click menu) and allow mouse scrolling at the same time. Mouse mode turns on tmux's own copy/paste system, but leaving it off removes the mouse scrolling. As I'm switching between an IDE, browser, and terminal with tmux I would like the controls to be consistent between all of them. Is there a way to have the standard OS copy/paste controls while also allowing the mouse to scroll in tmux?
(Note: I originally asked, but deleted, this question on SO. I decided it was more appropriate here.)

A:

Hold the shift key when attempting to copy and paste when in 'mode-mouse on'

A:

It depends on whether you are relying upon tmux to interpret the wheel-mouse, or not.  If that's tmux — no, you cannot, because tmux would only see the wheel mouse events if it turned on the terminal's mouse operations.
Without turning on the mouse operations, some terminals may send up/down cursor keys to the application when it has switched to the alternate screen.  VTE (gnome-terminal) has done that unconditionally for a few years.  The same feature is an option(alternateScroll) in xterm.  tmux switches to the alternate screen if the terminal description has that in the terminfo smcup and rmcup capabilities.  While in the alternate screen, normally (except for this fairly recent up/down cursor feature), the wheel mouse would have no effect on the terminal.
So...  you can get some limited use of the wheel  mouse while running tmux, and it depends on the terminal and how it is configured.


Q:

Extend DataSet Class Fill From SqlDataAdapter

class InspectionEquip : DataSet
{
    private readonly SqlConnection CPEC = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());

    public InspectionEquip(string store)
    {
        CPEC.Open();
        SqlCommand comm = new SqlCommand("Select * From Equip3 Where Store = '" + store + "'", CPEC);
        SqlDataAdapter da = new SqlDataAdapter(comm);
        da.Fill(/* What to Put Here? Tried "this" and it just returns blank */);
        CPEC.Close();
    }
}

A:

You have a problem with your SQL query (no matching data, bad parameter). da.Fill(this) works fine.
If you want proof - swap this SqlCommand line with yours...
SqlCommand comm = new SqlCommand("select * from INFORMATION_SCHEMA.COLUMNS", CPEC);

You should also probably extend DataTable, not DataSet if you only ever plan on storing a single tables results.


Q:

Should we add Music ID to the FAQ?

We've gotten a little influx of Music ID questions as of late.  I was wondering if we should specifically add Music Identification to the off-topic section of the FAQ.
Maybe changing it to:
Please note that the following subjects are considered off-topic here:

Distribution
Movie/TV purchasing/viewing locations
The operation of playing a movie whether it be digital or physical format.
Unimportant trivia that does not add to the understanding or appreciation of the title.
Music Identification
TV news and current affairs
A title's release date or rumors about a specific title or series.
Opinions about or recommendations for a movie or TV show

There might be a better way to word it, but that's the general gist of my thoughts.

List of recently closed music id questions:

Awake Pilot ending song
Name of the opera music in American Horror Story
Electronic Piece in American Dad
What songs has lyle lovett performed
What other movies use this song
Music when Barney is absent minded

A:

I agree with Robert that adding this to the list would make it a bit unwieldy.  That list of items is getting pretty big.  If Music Identification is to be added, I'd recommend that you take this time to also consolidate that list a bit.  Several of those items overlap, and could better be summed up in a short, general statement.  Namely:

These all deal with how/when movies are available, and could be combined into a general 'where to buy or shopping questions'

Distribution
Movie/TV purchasing/viewing locations
A title's release date

I think these could be combined into a 'current events' sort of item:

TV news and current affairs
rumors about a specific title or series.

With these consolidated, you get a shorter list of items that give a quicker impression of what is off-topic.


Q:

Are there other filter models besides IIR and FIR for processing digital signals?

I am very familiar with IIR and FIR filters for processing digital signals (audio is my main interest). I am keen to know if there are alternative filters based on different mathematical models to IIR and FIR?
I have a degree in maths but learning about DSP is just a hobby (I didn't study it at university) so I haven't a clue whether this is a stupid question or not :-)

A:

FIR and IIR filters are discrete-time linear time-invariant (LTI) filters. There are also (linear) time-varying systems, which could be implemented just like FIR or IIR filters, but with time-varying coefficients. Audio effects like chorus, flanger, or phaser are time-varying filters.
Of course there are also non-linear filters, the most well-known of which is probably the median filter, which is very useful for removing impulsive noise. Many different types of non-linear filters are used in image processing.
Note that none of the above mentioned filters can be characterized by their impulse response or, equivalently, by their frequency response. This is only possible for LTI systems.


Q:

Getting intimidating looking at /config files in projects at github, is there a book that covers this?

I'm looking at some open source apps on github, specifically the files in the /config folder like:
boot.rb, application.rb, etc.
They seem too complicated!
Is there a book that details all of this?
I'm finding the basics easy to understand, but configuration, setup is always a tricky part and a solid book on these topics would be great.

A:

Agile Web Development With Rails is pretty much the gold standard. There are some other good resources listed in this SO thread.