text:
Q: Calculating Inverse of Polynomial Rings I try to understand the NTRU-PKCS and wanted to implement a simple Version in Java, therefore I used a self-implemented method (extend euclid) for calculating the Inverse of a Polynomial in a Ring.
Most of the times my Algorithm works, but when I try the example from the NTRU-PKCS-Tutorial PKCS-Tutorial it fails and I dont know why.
The Example is:
f: -x^10+1x^9+0x^8+0x^7+1x^6+0x^5-x^4+0x^3+1x^2+1x^1-x^0
f^-1 mod 32: 30x^10+18x^9+20x^8+22x^7+16x^6+15x^5+4x^4+16x^3+6x^2+9x^1+5x^0
Ring: x^11-1
My Code is:
public PolynomialMod inverse(int N, int mod) {
    int loop = 0;
    PolynomialMod G = PolynomialMod.ZERO.clone();
    G.setNMod(N, mod);
    PolynomialMod newG = (PolynomialMod) PolynomialMod.ONE.clone();
    newG.setNMod(N, mod);
    int[] coeffR = { 1, 1, 0, 1, 1, 0, 0, 0, 1 };

    PolynomialMod quotient = null;
    PolynomialMod newR = this.clone();
    PolynomialMod R = this.getRing(N, mod);
    R.setNMod(N, mod);
    newR.setNMod(N, mod);

    while (!newR.equalsZero()) {
        if (DEBUG && loop != 0)
            System.out.println("loop: " + loop);
        if (DEBUG && loop == 0)
            System.out.println("========Initial Values========");
        if (DEBUG)
            System.out.println("R   : " + R);
        if (DEBUG)
            System.out.println("newR: " + newR);
        if (DEBUG)
            System.out.println("Quotient: " + quotient);
        if (DEBUG)
            System.out.println("G   : " + G);
        if (DEBUG)
            System.out.println("newG: " + newG);
        if (DEBUG && loop == 0)
            System.out.println("========Initial Values========");
        if (DEBUG)
            System.out.println("\n");

        quotient = R.div(newR)[0];
        PolynomialMod help = R.clone();
        R = newR.clone();
        PolynomialMod times = quotient.times(newR);
        times.reduceBetweenZeroAndQ();
        newR = help.sub(times);
        newR.deleteLeadingZeros();
        newR.degree = newR.values.size() - 1;
        help = G.clone();
        G = newG.clone();
        PolynomialMod times2 = quotient.times(newG);
        times2.reduceBetweenZeroAndQ();
        newG = help.sub(times2);
        loop++;

    }
    if (R.getDegree() > 0)
        throw new ArithmeticException("irreducible or multiple");

    return G.div(R)[0];
}

The output is like:
========Initial Values========
R   : [ -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
newR: [ -1, 1, 1, 0, -1, 0, 1, 0, 0, 1, -1 ]
Quotient: null
G   : [ 0 ]
newG: [ 1 ]
========Initial Values========

loop: 1
R   : [ -1, 1, 1, 0, -1, 0, 1, 0, 0, 1, -1 ]
newR: [ 30, 0, 2, 1, 31, 31, 1, 1, 0, 1 ]
Quotient: [ 31, 31 ]
G   : [ 1 ]
newG: [ 1, 1 ]

loop: 2
R   : [ 30, 0, 2, 1, 31, 31, 1, 1, 0, 1 ]
newR: [ 1, 31, 31, 1, 1, 0, 31, 0, 1 ]
Quotient: [ 1, 31 ]
G   : [ 1, 1 ]
newG: [ 0, 0, 1 ]

loop: 3
R   : [ 1, 31, 31, 1, 1, 0, 31, 0, 1 ]
newR: [ 30, 31, 3, 2, 30, 30, 1, 2 ]
Quotient: [ 0, 1 ]
G   : [ 0, 0, 1 ]
newG: [ 1, 1, 0, 31 ]

The Problem is: if I calculate R/newR now I have to find the inverse of 2 mod 32 but since the greatest common divisor of 32 and 2 is 2 not 1, there is no inverse...
Have I implemented the algorithm wrong?

A: Problem was solved: It wasnt an euclidean ring, so I had to calculate the inverse mod 2 and then lift it to mod 32...
how it works


text:
Q: Language for Google Voice Actions queries I made a demo app in Android with Kotlin and Google Voices Action to allow me to search in an app after a "Ok Google" (SEARCH_ACTION). It works perfectly well when I said

"Search this thing in my app name"

But doesn't work when I said it in french.
I tried to:

*

*set up my default research language in french

*delete others recognizable languages

*set up the region in France

*create a second strings.xml for a french version

Is it actually possible to use an other language then english to execute an action in an app from the voice api ? If yes, how ?
Thanks !

A: I had my answer here.

Where you can use voice search
These actions are available in English in the United States, United Kingdom, Australia, Canada, India, Ireland, Singapore, and South Africa.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Interested in finding k shortest path in opl cplex by dijkstra algorithm I am interested in finding k shortest path from source node to destination node by dijkstra's algorithm. i have solved the same problem with the help of dvar boolean to declear a boolean variables for the link which can take value 1 if the link is selected for path and 0 otherwise but the problem there this variable calculate the shortest path for each flow which is much time consuming. Now i am interested to get rid of flow conservation constraint and use some type of algorithm for column generation approaches which can resolve the problem at once not to calculate the path for each variable. I am looking forward to hearing from you

A: If you are concerned about performance then it is probably not a good idea to attack this problem with a general integer programming solver. As you can see for example here, there are dedicated algorithms available to solve the k-shortest path problem efficiently.
If you want to stick with OPL then you could implement those algorithms using OPLScript.


text:
Q: Why 1.5x ratio limitation for synchronizing slow signals into fast clock domain? Why 1.5x ratio limitation for Synchronizing Slow Signals Into Fast Clock Domain ?

A: Thanks for sharing the information. I enjoyed reading it.
I am no match for Nyquist, Shannon, or the authors of your reference documents. And, I thought I had to interpret x1.5 in a little different way. I forgot how I did, but I will try to explain. Please do not down vote or alter this, so we can promote independent thinking.

When Metastability is concerned, clock has the maximum of 1/2 cycle time for setup + hold, to be recorgnized as an edge, either rising or falling. Thus, rising edge is valid at a certain time after a valid falling edge, and vice versa. And we may apply the same setup and hold time to other signals in the Metastability perspective.
Thus, a signal from a clock domain's minimum residency is 1/2 cycle time of the clock. Let's the clock to be cycle time of Tcy, and the frequency of Fcy. And, we will analyze how a clock (domain) samples a signal from another clock domain.
When a signal was sampled (n0) at the earliest moment, 0xTcy, of the valid signal, the next sample (n1) window comes in duration of W1 from the current sample point,

1xTcy < W1 < 1.5xTcy --- (1)

When a signal is sampled at the latest moment, 0.5xTcy, of a valid signal,
the next sample window comes in duration of W2,

W2 = W1 - 0.5xTcy => 0.5xTcy < W2 < 1xTcy ---(2)

Thus, the sampling frequency, f1, of window W1 is:

(1 / 1xTcy) > f1 > (1 / 1.5xTcy) ---(3)

The sampling frequency, f2, of window W2 is:

(1 / 0.5xTcy) > f2 > (1 / 1xTcy) ---(4)

From the relation of 1xTcy = 1/Fcy:

1xFcy > f1 > (1xFcy / 1.5) ---(3-1)
2xFcy > f2 > 1xFcy ---(4-1)

However, the reluctant sampling of 1.5xTcy misses sampling moment in the following cycles (n2, n3, ...). And, apparently;

A sampling window can be caught only by more than one shots (sampling) per a cycle. --- (5)

In order to find how many shots are needed, Let's call multiple of f1 fm1.

fm1 = f1 x M ---(6)

Now, eq(3) can be converted to:

(1xFcy x M) > (f1 x M) > (1xFcy / 1.5) x M ---(3-2)

From what we have found in (5), the lowest frequency has to be 1xFcy, or a shot per cycle. This leads to:

1xFcy = (1xFcy / 1.5) x M, and M = 1.5 ---(7)

Which resolves eq(3) to:

1.5xFcy > fm1 > 1xFcy ---(3-3)

Applying M to eq(4),

3xFcy > fm2 > 1.5xFcy ---(4-3)

The intersection of eq(3-3) and eq(4-3) occurs at 1.5xFcy, which tells;
Minimum of 1.5 times faster clock is required to sample a signal from another clock domain.

Concept of maximum setup and hold time for a clock domain.

Concept of signal residency and interval, compared to clock cycle.

Early alignment: f1, W1, and fm1.

Late alignment: f2, W2, and fm2.

A: There is no speed limit. They can be any ratio <=1. The 1.5x factor assumes the slow clock is perfectly 50% d.c. or 010101.
Consider only the fundamental freq. with the requirement being ; 1) no missing or extra cycle counts (or glitches). You must sample at least 50% faster, assuming the slow clock is perfectly 50% duty cycle.
Shannon's Theorem says you need 2x f to sample a sine fundamental to detect that frequency, but you do not recover the phase or amplitude perfectly, only detect that fundamental exists. Here, we sample with an edge and reset with an edge if about the same speed to detect if the slower input is high at least once during that interval.  You won't get duty cycle or harmonic content. The 2 state single FF satisfies the Shannon criterion in the case of widely separated frequencies. Whereas, a dual FF edge trigger is used for "almost synchronous" or pleisiochronous clocks.
If a slow clock or bit of information clocks a 1 into a flip-flop and at any time that output is sent into a much faster bit stream, it resets the flip-flop at the same time as the read output latch to ensure it is always sent only once.
Anecdote. I used this method in '77 to send dual Servo Motor currents as digital bits using a voltage controlled one-shot as a 1kHz max tachometer signal into a 10 Mbps bit stream. It was sent some slow spare status bits, to get real-time feedback  but with lower Bandwidth from a nuclear reactor to the control building over coax. It served to monitor servo friction in a robotic SCADA custom design I once did. (long time ago, far,far away) It appeared very accurate on analog edge-meters on the console. Without that async to sync, there were aliasing effects.

A: There is nothing special about the value of 1.5x. The author goes on to explain what he means a few paragraphs further down:

[This will work,] as long as the signal generated in [one] clock domain is wider than the cycle time of the [other] clock [...] A safe rule of thumb is the signal must be wider than 1.5x the cycle width of the destination clock

I.e., it must be guaranteed that the receiving clock is at least a little bit faster than the clock the signal originates from. In theory, 1.0001x would be good enough, but there are always sources of error:

*

*all flip-flops have a setup and hold time, i.e. the signal must be stable for a certain time, often many percent of the cycle time. If the pulse is short, we might miss the setup time requirement in one cycle and miss the hold time requirement in the next cycle, effectively missing the whole pulse.

*Oscillator frequencies vary with temperature and voltage and it's not guaranteed that both clocks vary in the same way and by the same amount throughout all operating conditions.

*Clocks have jitter, i.e. clocks generated by a PLL can have period variations of 100 ps, which can easily be a couple of percent of the total clock period.

*Switching times of flip-flops and all the transistors encountered during routing are not homogeneous. The transition time from high to low can well be different to the one from low to high. This results in the signal (that should be active for exactly one clock cycle) to be active for less or more than one clock period.

*Switching thresholds of each and every transistor in the circuit is not equal, some may have a higher threshold and effectively shorten the length of the pulse.

*All routing inside the chip depends strongly on the temperature and the current operating voltage in this specific location of the chip. If there is a lot of activity from other signals, voltage may drop locally and alter rise times and propagation delays, leading to a distorted signal length.
As a result, the receiving clock domain must be "quite a bit" faster than the source domain. A factor of 1.2 might be on the safe side, if operating conditions are favorable and the clock speeds are not close to the maximum the chip can deliver. I would be quite cautious if my clocks were this close in frequency and give the design a thorough test. With the cited factor of 1.5x you'll be on the safe side in any current FPGA no matter what happens. (Exceptions exist, e.g. ASICs built in custom processes can exhibit uncommon behaviors.)


text:
Q: Zorn's Lemma's chain condition Zorn's Lemma requires that every chain in a partially ordered set $X$ has an upper bound. In this article Gowers uses Zorn's Lemma to find a maximal linearly independent (over $\mathbb{Q}$) subset of $\mathbb{R}$. He does this by looking at the set of all linearly independent subsets of $\mathbb{R}$ with the partial order $\subset$.
He checks that every chain has an upper bound by considering a collection $Y$ of nested linearly independent subsets of $\mathbb{R}$. He defines the upper bound as their union. Thus every chain has an upper bound and Zorn's lemma can show that a basis for $\mathbb{R}$ over $\mathbb{Q}$ exists.
But what if $Y$ is infinite? It's not too hard to think of a chain in this case that has no upper bound- just keep adjoining appropriately chosen irrational numbers to get another subset of $\mathbb{R}$ linearly independent over $\mathbb{Q}$. The chain of such subsets has no upper bound, right?
In general, when you prove that every chain in $X$ has an upper bound, you need to consider finite and infinite chains, right? So how come Gowers, in paragraph 24 (below), implicitly assumed that $Y$ is a finite collection? Obviously it is easy to find the upper bound of a finite chain.

All we have to do if we want to apply Zorn's lemma is check that every chain has an upper bound. So let us imagine that we have a collection $Y$ of linearly independent subsets of $\mathbb{R}$ and that for any two of those sets one is contained in the other. What could serve as an upper bound? By definition it has to be a set that contains all the sets in $Y$, so it has to contain their union. We want it to be linearly independent, so the smaller it is, the better. So there is basically only one candidate to try: the union itself. Is the union linearly independent? Well, if $t_1,\dots,t_n$ belong to the union, then each $t_i$ belongs to some linearly independent set $L_i\in Y$. Because $Y$ is a chain, one of these sets $L_i$ contains all the others. If that is $L_j$, then the linear independence of $L_j$ implies that no non-trivial linear combination of $t_1,\dots,t_n$ can be zero, which proves that the union of the sets in $Y$ is linearly independent, just as we wanted. Therefore, by Zorn's lemma, there is a maximal linearly independent set.

A: The assumption is not that $Y$ is finite. But in order to verify that $\bigcup Y$, as the increasing union of linearly independent sets, is linearly independent, we only need to verify that finite combinations with non-zero coefficients do not produce $0$.
So given finitely many vectors (or in this case, real numbers) in $\bigcup Y$, there is some $Y_1,\ldots,Y_n$ that each real number lies in one of the $Y_i$'s, but since this is a finite chain, there is some $Y_k$ such that $Y_i\subseteq Y_k$ for all $i\in\{1,\ldots,n\}$. And since $Y_k$ is linearly independent, the vectors we picked initially cannot produce $0$, so they cannot do so in $\bigcup Y$ either.

This is a very typical use of Zorn's lemma. We pick some property which is of finite character. So if it wouldn't hold, there would be a finite subchain whose maximal element will witness this failure.
But you are correct. We cannot just assume our chains are finite. Finite chains are always bounded, since they have a maximal element.


text:
Q: Verify bash scripts with "bash -n " before installing, how do I do that in a CMakeLists.txt? I have the following in my CMakeLists.txt file to install a bash script:
install(
    PROGRAMS
        backup-wordpress

    DESTINATION
        bin
)

That works as expected, no issue here.
However, before being able to install that script, I'd like to run:
bash -n backup-wordpress

to generally make sure it will run and not just fail because of some basic syntax error.
How do I run that bash -n ... command against a file which just gets installed by the cmake install command and make sure that command happens every time the script is modified?
I know of add_custom_target() and add_custom_command(), but those are expected to create an intermediate file. I'm not too sure how it would apply to my case.


text:
Q: Convert string to a List type I have a List method where I need to return my enum values as a list type. The Status datatype is an enum object.
Here is my code:
public List<string> Statusstring
    {
        get
        {
            foreach (Status stat in System.Enum.GetValues(typeof(Status)).Cast<Status>().ToList())
            {
                status = stat;
            }

            return new List<string> { status.ToString() };
        }

    }

Here is my enum value:
public enum Status
{
    Enable,
    Disable
}

This is the error message I am getting:

Cannot implicitly convert type 'System.Collections.Generic.List<char>' to 'System.Collections.Generic.List<string>'

Can someone please help me on this.

A: If you have to return List only - Then below is a #hack
                if (reader["PRODUCTION_LINE_CODE"].ToString() == "1")
                {
                    return new List<string> { Status.Enable.ToString() };
                }
                else
                {
                    return new List<string> {Status.Disable.ToString() };
                }

Update:- After discussion with OP
if (reader["PRODUCTION_LINE_CODE"].ToString() == "1")
                {
                    return new List<string> { Status.Enable.ToString(), Status.Disable.ToString() };
                }
                else
                {
                    return new List<string> {Status.Disable.ToString() };
                }

A: What I see are a pretty much very convoluted solutions to a simple problem.
private static List<string> StatusString() => Enum.GetNames(typeof(Status)).ToList();

But since Enum values are not going to change during run time I would go for static member
You can define a static member→
private static List<string> StatusString = Enum.GetNames(typeof(Status)).ToList();

A: There is a built-in construct for this in .NET:
public IEnumerable<string> Statuses => Enum.GetNames(typeof(Status))

If you return IEnumerable<string> instead of a list you can assign this to arrays or lists. And the Enum.GetNames(...) returns as a string[].
The documentation for this method is here

A: The property is named as Statustring but it is a List<string>?
I guess the codes below might be the proper implementation:
public string Statusstring
{
    get
    {
        string query;

        query = "Select PRODUCTION_LINE_CODE from productionlineconfig where ID = '" + ProductionLineConfigs.ProductionLineId + "'";

        reader = db.QueryCommand(query);
        while (reader.Read())
        {
            if (reader["PRODUCTION_LINE_CODE"].ToString() == "1")
            {
                return Status.Enable.ToString();
            }
            else
            {
                return Status.Disable.ToString();
            }
        }
}

Or, if you have to return a List<string> you can try this
public List<string> Statusstring
{
    get
    {
        string query;

        query = "Select PRODUCTION_LINE_CODE from productionlineconfig where ID = '" + ProductionLineConfigs.ProductionLineId + "'";

        reader = db.QueryCommand(query);
        while (reader.Read())
        {
            if (reader["PRODUCTION_LINE_CODE"].ToString() == "1")
            {
                return new List<string>().Add(Status.Enable.ToString());
            }
            else
            {
                return new List<string>().Add(Status.Disable.ToString());
            }
        }
}

A: First enum to list
var enumList = Enum.GetValues(typeof(Status))
        .Cast<int>()
        .Select(x => x.ToString())
        .ToList();

then cast enumList to list of string
var stringList  = enumList.OfType<string>();
return stringList;

A: This should do.
using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<string> list = System.Enum.GetValues(typeof(Status))
            .Cast<Status>()
            .Select(x => x.ToString())
            .ToList();

        list.ForEach(Console.WriteLine);
    }
}

public enum Status
{
    Enable,
    Disable
}

A: How about this:
Enum.GetValues(typeof(Status)).Cast<Status>()

will return an Ienumerable.
 Enum.GetValues(typeof(Status)).Cast<Status>().ToList();


text:
Q: Generate file inside _site with Jekyll plugin I have written a Jekyll plugin, "Tags", which generates a file and returns string of links to that file.
Everything is fine, but if I write that file directly into the _site folder, it is removed. If I put that file outside the _site folder, it is not generated inside _site.
Where and how should I add my file so that it is available inside the _site folder?

A: You should use class Page for this and call methods render and write.
This is an example to generate the archive page at my blog:
module Jekyll
  class ArchiveIndex < Page
    def initialize(site, base, dir, periods)
      @site = site
      @base = base
      @dir = dir
      @name = 'archive.html'
      self.process(@name)
      self.read_yaml(File.join(base, '_layouts'), 'archive_index.html')
      self.data['periods'] = periods
    end
  end

  class ArchiveGenerator < Generator
    priority :low

    def generate(site)
        periods = site.posts.reverse.group_by{ |c| {"month" => Date::MONTHNAMES[c.date.month], "year" => c.date.year} }

        index = ArchiveIndex.new(site, site.source, '/', periods)
        index.render(site.layouts, site.site_payload)
        index.write(site.dest)
        site.pages << index
    end
  end
end


text:
Q: awk compare one column from two CSV files and display fields from both files I want to compare second column of 1st file with 1st column of 2nd file, if match found display all fields from 1st file and all fields from 2nd file.
file1:
"971525408953","a8:5b:78:5a:dd:dc","TRUE"
"971558216784","ec:1f:72:24:7b:30","TRUE"
"971506509910","e8:50:8b:d8:f3:b5","TRUE"
"971509525934","c8:14:79:b4:bc:da","FALSE"
"971506904830","58:48:22:83:87:7f","TRUE"

file2:
"fc:e9:98:1e:a2:a2",2016-03-07 23:39:29,"TRUE"
"c8:14:79:b4:bc:da",2016-03-08 04:26:06,"TRUE"
"78:a3:e4:87:df:19",2015-12-30 01:22:42,"TRUE"
"18:f6:43:b1:82:47",2016-03-08 08:38:41,"TRUE"
"58:48:22:83:87:7f",2015-12-22 01:22:42,"TRUE"

output expected:
"c8:14:79:b4:bc:da",2016-03-08 04:26:06,"TRUE","971509525934","c8:14:79:b4:bc:da","FALSE"
"58:48:22:83:87:7f",2015-12-2201:22:42,"TRUE","971506904830","58:48:22:83:87:7f","TRUE"

But if i run following command i get this output without n[$2] and n[$3]
awk -F","  'NR==FNR { n[$2] = $1; next }  ($1 in n)  {print  $1,$2,$3,n[$1],n[$2],n[$3] }'  file1 file2

"c8:14:79:b4:bc:da",2016-03-0804:26:06,"TRUE","971509525934",, "58:48:22:83:87:7f",2015-12-22 01:22:42,"TRUE","971506904830",,

Can any one help me on this?

A: awk -F","  -v OFS="," 'NR==FNR { n[$2] = $1$2$3; next }  ($1 in n)  {print  $1,$2,$3, n[$1] }' file1 file2
output:
"c8:14:79:b4:bc:da",2016-03-08 04:26:06,"TRUE","971509525934""c8:14:79:b4:bc:da""TRUE"
"58:48:22:83:87:7f",2015-12-22 01:22:42,"TRUE","971506904830""58:48:22:83:87:7f""TRUE"


text:
Q: ngb-pagination shows as first page, cannot set the page number, programmatically I am using ngb pagination
following is the code:
      <ngb-pagination class='float-right' [maxSize]=10
                                                        (pageChange)="currentPage=$event;paginationNavigation('pagination');"
                                                        [collectionSize]="totalobjects" [(pageSize)]="pageSize"
                                                        [(page)]="currentPage" aria-label="Default pagination">
      </ngb-pagination>

I am getting currentPage value from query params:
const params  = this._route.snapshot.queryParams
this.currentPage=parseInt(params['currentPage']) || 1;

But this doesn't set the pagination html value when refreshing/loading the page,it shows as first page.

A: if you don't change the page not work put in ngOnInit const params  = this._route.snapshot.queryParams because the ngOnInit it's not execute again else you refresh the navigator or when change the page (I want to say that you are in /default and go to /product-list/2, but ngOnInit it's not execute again if you're in product-list/1 and go to product-list/2)
You need subscribe to ActivatedRoute.queryParams
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
  this.activatedRoute.queryParams.subscribe(params => {
    this.currentPage = (+params['currentPage']) || 1;
  });
}

NOTE: be sure you are defined your route as path: 'product-list/:currentPage'


text:
Q: how to sort data in datatables with no i want to sort the data in the datatables with numeric function in both ways ascending and descending. i used the following codebut was not working.
$('#data_table').dataTable( {
    "aaData": dataSet,
    "aaSorting": [[1,'asc','desc'],[3,'asc','desc']],
    "iDisplayLength": 4,
    "bInfo": true,
    "bLengthChange": false,
    "bPaginate": true,
    "sPaginationType": "full_numbers",
    "bAutoWidth": true,
    "aoColumns": [
        {
            "sTitle": "Seller",
            "sClass": "grey" ,
            "fnRender": function(obj) {
                var data = obj.aData[ obj.iDataColumn ];
                return ""+ data.title +"";
            }
        }

A: What do you mean that you want to sort both ways? aaSorting is used to sort the table on inizialization so
 "aaSorting": [[1,'asc','desc'],[3,'asc','desc']],

is not valid you should do (for example):
 "aaSorting": [[1,'asc'],[3,'desc']],

This would sort the table on the first pass with ascending sorting on the second column and descending sorting on the fourth column.

A: unable to understand, do u want to sort same column in both asc and desc order
jQuery.fn.dataTableExt.oSort['string-case-asc']  = function(x,y) {
return ((x < y) ? -1 : ((x > y) ?  1 : 0));};

jQuery.fn.dataTableExt.oSort['string-case-desc'] = function(x,y) {
return ((x < y) ?  1 : ((x > y) ? -1 : 0));};

check this


text:
Q: Find top salary per department - is there a more efficient query? I have a query that works but I suspect I'm doing this inefficiently. Is there a more elegant approach to find the top salary in each department and the employee that earns it?
I'm doing a cte to find the max salary per dept id and then join that up with the employee data by matching salary and dept id. I have code below to build/populate the tables and the query at the end.
CREATE TABLE employee (
emplid SERIAL PRIMARY KEY,
name VARCHAR NOT NULL,
salary FLOAT NOT NULL,
depid INTEGER
);

INSERT INTO employee (name, salary, depid)
VALUES
('Chris',23456.99,1),
('Bob',98756.34,1),
('Malin',34567.22,2),
('Lisa',34967.73,2),
('Deepak',88582.22,3),
('Chester',99487.41,3);

CREATE TABLE department (
depid SERIAL PRIMARY KEY,
deptname VARCHAR NOT NULL
);

INSERT INTO department (deptname)
VALUES
('Engineering'),
('Sales'),
('Marketing');

--top salary by department
WITH cte AS (
SELECT d.depid, deptname, MAX(salary) AS maxsal
FROM employee e
JOIN department d ON d.depid = e.depid
GROUP BY d.depid, deptname
)
SELECT cte.deptname, e.name, cte.maxsal
FROM cte
JOIN employee e ON cte.depid = e.depid
AND e.salary = cte.maxsal
ORDER BY maxsal DESC;

Here is the target result:
"Marketing"     "Chester"       "99487.41"
"Engineering"   "Bob"           "98756.34"
"Sales"         "Lisa"          "34967.73"

A: In Postgres this can solved using the distinct on () operator:
SELECT distinct on (d.depid) d.depid, deptname, e.name, e.salary AS maxsal
FROM employee e
  JOIN department d ON d.depid = e.depid
order by d.depid, e.salary desc;

Or you can use a window function:
select depid, deptname, emp_name, salary
from (
  SELECT d.depid,
         deptname,
         e.name as emp_name,
         e.salary,
         max(e.salary) over (partition by d.depid) AS maxsal
  FROM employee e
    JOIN department d ON d.depid = e.depid
) t
where salary = maxsal;

Online example: https://rextester.com/MBAF73582

A: You should have an index:
create index employee_depid_salary_desc_idx on employee(depid, salary desc);

And then use the following query that can use the index:
select
  depid,
  deptname,
  (
    select
      emplid
    from employees
    where depid=department.depid
    order by salary desc
    limit 1
  ) as max_salaried_emplid
from department;

(A join for retrieving data from the emplid left as an exercise for the reader).


text:
Q: What are the best practices to think about when sending a username and password to an authentication server? I'm wondering what sorts of things I need to keep in mind when sending a username and password to an authentication server using ajax. I'm using phoneGap and jQuery to develop a web app, which I'm very new to, and I want to make sure I go about it the right way. Any advice is welcome.

A: You should use a challenge-response mechanism.
The server should send the client a non-reusable expiring nonce and the user's salt.
The client should hash the password with the salt, hash the resulting hash with the nonce, and send that hash back to the server.
The server should store pre-salted password hashes in its database.
It should then hash the stored hash with the nonce, and compare that to the hash from the client.
This makes it impossible for an attacker to learn the original password, even if the attacker is an active man-in-the-middle and has stolen the database.
However, if the attacker steals the database, he will be able to login by bypassing your UI and using the known hash.

A: Is this an app you're building yourself, or will you be talking to an existing web-based service?
Using HTTPS is a must, assuming it's available. If you're building the website yourself, I'd recommend looking into a token-based system, similar to those used by many popular websites.
The basic flow goes like this:

*

*You, the developer, register with the site for an API key and possibly a token of some kind.

*In your app, you combine the user's password with your app's token and run them through a hashing algorithm.

*Your app submits the hashed password, along with your API key, to the server.

*If the user's credentials check out, the server replies with an authentication token, which is just a short code. Your app has to include this token with every request to the server.

*Authentication tokens may expire at some point, so you may need to reauthenticate at some point.

In general, avoid storing the user's password in plain text. Hash it in a form that's compatible with the server's authentication system, and then store that value.

A: I've used Raymond's examples. Also i've hash password in client side.
http://www.raymondcamden.com/index.cfm/2011/11/10/Example-of-serverbased-login-with-PhoneGap


text:
Q: Setting values given two column I have 2-time series data frames. Both contain values [0,1] only. The first one is called init_signal and the second is called end_signal. The idea is to create a new data frame when init_signal has a 1, it will find the NEXT 1 in end_signal.
The example below merges both the init_signal and end_signal as one data frame. the first column is init_signal and the second column is end_signal.
For example:
2016-06-13  1  0
2016-06-14  0  0
2016-06-15  0  1
2016-06-16  0  0

Will become:
2016-06-13  1
2016-06-14  1
2016-06-15  1
2016-06-16  0

For example 2:
2016-06-13  1  1
2016-06-14  0  0
2016-06-15  0  1
2016-06-16  0  0

Will become:
2016-06-13  1
2016-06-14  1
2016-06-15  1
2016-06-16  0

In the 2nd example, if there is also a 1 in the same row as the init_signal, it will be ignored.
I've been using a complex loop. Is there a non-looping way?

A: I hope this helps and covers all the boundary conditions.
import pandas as pd
import datetime as dt

# Dummy data
df = pd.DataFrame()
df['init_signal'] = [0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0]
df['end_signal']  = [0,1,0,0,0,0,1,0,1,0,0,1,0,1,0,0,0,1,0]
df.index = [dt.date.today()+dt.timedelta(-i) for i in reversed(range(len(df)))]

# Cumsum for calculation
df['init_c'] = df['init_signal'].cumsum()
df['end_c']  = df['end_signal'].cumsum()

# result calculation
func = lambda x: (x==x.min()).shift().fillna(True)
df['result'] = df.groupby('init_c')['end_c'].transform(func)
df['result'] = df['result']&df['init_c'].astype(bool)
df['result'] = df['result'].astype(int)

# dropping temp columns
df.drop(['init_c','end_c'], axis=1, inplace=True)

print(df)

Output:
            init_signal  end_signal  result
2018-12-12            0           0       0
2018-12-13            0           1       0
2018-12-14            0           0       0
2018-12-15            1           0       1
2018-12-16            0           0       1
2018-12-17            0           0       1
2018-12-18            0           1       1
2018-12-19            0           0       0
2018-12-20            1           1       1
2018-12-21            0           0       1
2018-12-22            0           0       1
2018-12-23            0           1       1
2018-12-24            0           0       0
2018-12-25            0           1       0
2018-12-26            0           0       0
2018-12-27            0           0       0
2018-12-28            1           0       1
2018-12-29            0           1       1
2018-12-30            0           0       0

A: Let's try:
df1 = df.assign(end_signal = df['end_signal'].where(df['init_signal'].values != 1, 0))
df1 = df1.set_index('time')
(df1['init_signal'] + df1['end_signal'].shift().bfill()*-1).cumsum()

Output:
         time    0
0  2016-06-13  1.0
1  2016-06-14  1.0
2  2016-06-15  1.0
3  2016-06-16  0.0

A: This can achieved in three steps and 0 loops:

*

*Create a single column with the init_signal and end_signal.
(Records with both default to start signal only.)

*Fill the dates with
no activity.

*Add the end signal back as active.

Note: I'm not sure how to handle cases at the beginning. I'm presuming that there will always be an init_signal preceding an end_signal. If that's not true, you'll need to build a handler for that, but that would be a simple conditional at the end of these steps.
Step 1: A single columns
In this step we create a column that has only days where there was a init_signal and end_signal.
 import numpy as np
 df['result'] = np.nan
 #Add end dates
 mask = (df['end_signal'] == 1)
 df.loc[mask,'result'] = 0
 #Add init_signals.
 #Note: This will overwrite days that already have an end_signal
 mask = (df['init_signal'] == 1)
 df.loc[mask,'result'] = 1

Step 2: Fill the columns
This will take the na values and replace them with the status that occurred most recently.
 df.fillna(method='ffill',inplace=True)

Step 3: Set end_signal to active.
In definitions, we said that dates with an end_signal should be 1, so we need to add that back to the dataframe.
 mask = (df['end_signal'] == 1)
 df.loc[mask,'result'] = 1

A: I don't think there is a non-looping way to incorporate the logic you want (and if there is, it isn't simpler than a loop). See below...
df['status'] = 0
for i in df.index:
    if df.xs(i)['init_signal'] == 1:
        df.at[i,'status'] = 1
    elif i != 0 and df.xs(i-1)['status'] == 1 and df.xs(i)['end_signal'] != 1:
        df.at[i,'status'] = 1
    else:
        df.at[i,'status'] = 0

This creates a 'status' column that will be zero until init_signal is turned 'on' and will remain 'on' until end_signal = 1 on a day where the init_signal is also not equal to 1 (per your example 2). Other non-looping solutions seem to run into trouble when multiple end/init signals are given in a row.


text:
Q: Order of elements of quotient group How do we prove the following without using Cauchy's theorem? (From Pinter p156 problem H3.)
Let $G$ be a finite abelian group, and the order $|G|$ be a multiple of a prime number, $p$.
Let $a$ be an element of $G$ and $\text{ord}(a)$ not a multiple of $p$. It can be shown that the order of the quotient group $|G/\langle a \rangle|$ is a multiple of $p$.
Prove $G/\langle a\rangle$ must have an element of order $p$.

A: Looking at page 156, I see that this question is in the context of "induction on $|G|$: an example." The series of four exercises is walking you through a proof of Cauchy's theorem for the special case of finite abelian groups, using induction.
For the benefit of others reading this question, I'll summarize the context here.
Claim: if $G$ is a finite abelian group, and $p$ is any prime factor of $|G|$, then $G$ has an element of order $p$. The base case, $|G| = 1$, is trivially true since there are no prime factors of $|G|$. Assume that $|G| = k$ and the result is proven for orders smaller than $k$. Take any nonidentity element $a \in G$. If $\text{ord}(a) = p$, then we're done. Otherwise:

*

*If $\text{ord}(a) = tp$ for some positive integer $t$, what element of $G$ has order $p$?

*Suppose $\text{ord}(a)$ is not a multiple of $p$. Then $G/\langle a \rangle$ is a group having fewer than $k$ elements. (Explain why.) The order of $G/\langle a \rangle$ is a multiple of $p$. (Explain why.)

*Why must $G / \langle a \rangle$ have an element of order $p$?

*Conclude that $G$ has an element of order $p$.
I assume you have answered 2 and now want to know why 3 is true. But this is simply because $|G / \langle a \rangle| < k$ and $p$ divides $|G / \langle a \rangle|$ (by problem 2), and we are assuming that we have proved the result for finite abelian groups of order is less than $k$ and divisible by $p$. (Induction hypothesis.)
By the way, problem 2 doesn't mention it, but for completeness you need to show that $G/\langle a \rangle$ is abelian. Fortunately, this is easy.
Problem 4 is actually the key part of the proof. Do you see why it's true? Hint: by 3, there is an element of $G/\langle a \rangle$ with order $p$. The elements of this group are cosets of $\langle a \rangle$, so let's call the element $g\langle a\rangle$. If $g\langle a\rangle$ has order $p$, then what does that tell you about the order of $g$?

A: As explained by Kevin Carlson, this implies Cauchy's Theorem anyway. So let's prove Cauchy's Theorem for finite abelian groups.
Write $G = \bigoplus_q G_q$ with $G_q = \{a \in G : \exists n \geq 0 ( q^n a = 0)\}$ for primes $q$. Then $|G_q|$ is a power of $q$, because any element $a \in G_q$ has order a power of $q$ and we can do induction by considering $G_q / \langle a \rangle$. Now if a prime $p$ divides $|G|$, it divides some $|G_q|$. By the result before, we must have $q=p$. This means $G_p \neq 1$, i.e. there is some element $a$ of order $p^n$, $n \geq 1$. Then $p^{n-1} a$ has order $p$.


text:
Q: How do you show the fields of some nodes on Neo4j? I am using Neo4j for the first time. When I am querying nodes, it would only show their name. Would it be possible to show multiple fields beside a name, like age, location, etc..?

A: If you are using the neo4j Browser, the default Graph tab (in the light-gray vertical panel to the left of the visualization) only supports showing a single value for a node at a time (since there is not much room to display such data when a lot of nodes and relationships are displayed).
But you can see node (and relationship) properties by clicking on the Table or Text tab.


text:
Q: mocking python class dictionary I am fairly new to python. I am trying to use mock to write a unit test. Here is the pattern of the code.
# mod3.py
import mod1.class1
import mod2.class2

d = {
"c1": class1
"c2": class2
}

def func1(c, v):
   cl = d[c]
   o = cl().meth1(v)
   return o

I want to write an unit test for func1.
def test_func1(c, v):
   c, v = mock.Mock(), mock.Mock()
   r = mod3.func1(c,v)
   e = {"key1": "value1"}
   #want to check if the ret val is as expected

How would I use mock to essentially mock cl().meth1(v)

A: # cat class1.py
def func(v):
    return v
# cat class2.py
def func(v):
    return v
#cat mock.py
import class1, class2
d = { "c1": class1, "c2": class2 }
def func1(c, v):
    cl = d[c]
    o = cl.func(v)
    return o

class1 and class2 are modules in python. Do you want this?


text:
Q: Generate Random Hexidecimal in Scala? How can I generate a random hexadecimal in scala?
The purpose it to essentially to use this as a UDF to generate random 64 char hexadecimals per column in a DataFrame.
I understand one can utilize below for an Int and etc:
val r = scala.util.Random
println(r.nextInt)

Is there an equivalent or another method simple method for a hexadecimal? particularly with 64 chars? Ex) 6e89f0c4c8a86812ef594229e5f4d997cb38aadc8a694f1b3be24a543b7699de

A: Since a Byte is 2 hex digits, one can generate an array of 32 random bytes, render them as hex, and join them into a string:
def randomHex256(): String = {
  val arr = Array[Byte](32)
  scala.util.Random.nextBytes(arr)
  // iterator avoids creating a strict intermediate collection
  arr.iterator.map(b => String.format("%02x", Byte.box(b))).mkString("")
}

A: Below is a sample code(Scala) for base64 where concept for the hex generation will be similar, the difference is as explained below:
base64 has less overhead (base64 produces 4 characters for every 3 bytes of original data while hex produces 2 characters for every byte of original data).
import java.util.Base64

def encodeToBase64String(bytes: Array[Byte]): String = Base64.getEncoder.encodeToString(bytes)

val dm_with_clsr_two =(inputString:String) => encodeToBase64String(inputString.getBytes("UTF-8"))
spark.udf.register("DATA_MASK_TWO", dm_with_clsr_two)
spark.sql("select id,DATA_MASK_TWO(id), gender, birthdate, maiden_name, lname, fname, address, city, state, zip, cc_number, DATA_MASK_TWO(cc_number), cc_cvc, cc_expiredate from sample_ssn_data").show(5,false)

+-----------+--------------------------------+------+----------+-----------+------+--------+--------------------+-----------+-----+-----+-------------------+--------------------------------+------+-------------+
|id         |UDF:DATA_MASK_ONE(id)           |gender|birthdate |maiden_name|lname |fname   |address             |city       |state|zip  |cc_number          |UDF:DATA_MASK_TWO(cc_number)    |cc_cvc|cc_expiredate|
+-----------+--------------------------------+------+----------+-----------+------+--------+--------------------+-----------+-----+-----+-------------------+--------------------------------+------+-------------+
|2022-25-005|4DDA8A5D35947B12B948EFF6EF14579A|m     |1958/04/21|Smooth     |White |John    |10932 California Rd |Calfornia creek |CA|94025|5270 2020 2022 5516|4F88DDF6489891710B9C5A5D8412129E|123   |2010/06/25   |


text:
Q: grid.draw Cutting Off Facet Grid Title and X&Y Labels I am trying to create a facet_grid() in ggplot() and am having issues with the margins of my plot. I am using grid.draw() for my final plot, and cannot figure out how to adjust the margins for printing. When I save my plot, it appears fine (see below). However, when I actually print my plot out to hard copy, half of the X&Y labels and my plot title are cut off.
I've attempted using par() to no avail. Here is a reproducible example, similar to my actual plot. I need to keep the panel <- off part because in my actual plot, I have plotted numbers above each bar and they get cut off by the facet sides for days at the beginning/end of each month. I'm thinking this might be the root of the issue, but I'm not really sure to be honest.
data(airquality)

library(stats)
library(ggplot2)
library(gtable)
library(gridExtra)
library(grid)
library(dplyr)
library(scales)

facet <- ggplot() +
  geom_bar(data=airquality,aes(y=Wind,x=Day,fill=Temp),colour="black",stat="identity",position='stack') +
  #theme_bw() +
  facet_grid(~Month) +
  theme(axis.title.x=element_text(face="bold",size=14),axis.title.y=element_text(face="bold",size=14),axis.text.x=element_text(face="bold",size=10),axis.text.y=element_text(face="bold",size=10))+
  ylab("Wind") +
  theme(panel.margin = unit(5, "mm"),panel.border=element_rect(color="black",fill=NA),panel.background = element_rect(fill="grey84"),plot.title = element_text (size=20,face="bold"),legend.position="right",panel.grid.minor=element_blank(),strip.text.x=element_text(size=12,face="bold"),strip.background=element_rect(fill=NA,colour="black"),legend.title=element_text(size=14,face="bold")) +
  ggtitle("Test")

gt <- ggplot_gtable(ggplot_build(facet))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)

Thanks for any and all help! Please, let me know if you need any clarification or have any questions.

A: you have two options:

*

*set some margins in the ggplot theme

*assign a viewport of specific size to the plot/gtable, smaller than the device window by some margin. Here's an illustration of using both strategies at once

library(grid)

fig_size <- c(6, 4) # inches
margin <- unit(4, "line")

p <- ggplot() + theme(plot.background=element_rect(colour="red", size=2, fill="grey50"),
                      plot.margin = unit(1:4, "line"))
g <- ggplotGrob(p)
g$vp <- viewport(width = unit(fig_size[1], "in") - margin, height=unit(fig_size[2],"in")- margin)

ggsave("plot.pdf", g, width=fig_size[1], height=fig_size[2])


text:
Q: c# HtmlHelper cannot convert lambda expression I'm trying to create a custom HtmlHelper for kendogrid to use with parameters.
My problem is how to refact my viewmodel to accept an interface the htmlhelper?
here is my htmlhelper class
using System;
using System.Web.Mvc;
using Kendo.Mvc.UI;
using System.Linq;
using Popup.BLL.ViewModel;

namespace Popup.Web.KendoHelper
{
    public static class PickListHelper
    {
        public static Kendo.Mvc.UI.Fluent.GridBuilder<T> PickList<T>(this HtmlHelper helper, string gridName, string gridClass, int gridHeight)
             where T : class
        {
            return helper.Kendo().Grid<T>()
            .Name(gridName)
                    .Columns(columns =>
                    {
                        columns.Bound(c => c.Text).Title("Associated");
                    })
            .HtmlAttributes(new { @class = gridClass, style = "height: " + gridHeight + "px;" })
            .Scrollable()
            .Sortable()
            .Selectable(selectable => selectable
                .Mode(GridSelectionMode.Multiple))
            .Events(events => events.Change("onSelectAssociatedGridElements"))
            .DataSource(datasource => datasource.Ajax().Read(read => read.Data("getAssociatedGridDataSource")));

        }
    }
}`

and my viewmodel class
public class TextViewModel
    {
       public int Id { get; set; }
       public string Text { get; set; }
    }

problem: c => c.Text
MSVS: Cannot convert lambda expression to type 'string' because it is not a delegate type

A:  .Columns(columns =>
  {
    columns.Bound(c => c).Title("Text");
  })


text:
Q: How to add data and return result I am getting null at the result and I think its because I am not adding data to the actual output but if I do then I get exception
If I add data like this
result.Result.Items = new List<Item>(); object reference
result.Result.Items.Add(textField); I get null reference
public class Result <T, TError>
{
    public T Result { get; set; }
}

 public class Doc
    {
        public Items Items { get; set; }
    }

Here I am adding data
  public Result<Doc, Error> ReturnDataSample()
            {
                var result = new Result<Doc, Error>();
                var doc = new Doc();
                doc.Items = new List<Item>();

                doc.Source.ItemsRawData = "Json";
                var imageField = new ImageField();
                imageField.Image = new Image();
                imageField.Image.Data = "image";
                imageField.PageIndex = 1;

                doc.Items.Add(imageField);

                TextField textFormField = new TextFormField();
                textField.Text = "originalValue ";
                textField.PageIndex = 1;
                textFField.FieldType = "Test";

              doc.Items.Add(textField);

              return result;

here I am Getting result
 var data =  regula.ReturnDataSample();
            Console.WriteLine(data);
            Console.WriteLine(data.Result);

If I add data like this
result.Result.Items = new List<Item>(); object reference
result.Result.Items.Add(textField); I get null reference

A: The issue you have is that Result is never initialized, as Progman has already pointed that out in the comment section. You cannot add an item to that which does not exist:
result.Result = doc;
result.Result.Items.Add(textField);


text:
Q: Get product custom fields ACF in post page wordpress I am trying to get a product custom field ( ACF ) based on product ID in a post page.
I tried things like this $price[] = get_sub_field('price', $productId); but it doesn't seems to work when taking something else than the post id.
I managed to get the title though by doing like this <?php echo $product->get_title(); ?> but not sure on how to go to get the custom fields.

A: As we know $product->ID will not work anyway. So I think now your problem is how to get the product ID.
=> In Archive pages like shop or in Single product pages:
  Using get_the_id() will give you mostly always the product id (the post ID).
$price= get_post_meta( get_the_id(), 'price', true );

reference link
You can also use global $product; with $product->get_id()
global $product;
$price = get_post_meta( $product->get_id(), 'price', true );


text:
Q: Its possible Reverse mysql fetch array with out ORDER By clauses? Its possible to reverse mysql_fetch_array values,without using ORDER BY clauses in SELECT query?

A: If what you want is just to reverse the returned array, then you can use array_reverse:
array_reverse($array);

You can find more information at the documentation.

A: When you do a select statement, you can never be certin of the order of items returned.  So in order to be certain, you must use a order by clause.  If you want a reverse order, do
ORDER BY columnA DESC

Most of the time, most databases will return things, without an order by in the order that rows were added, but it is non-deterministic.


text:
Q: Sha hash not respected in CSP style-src I have an ASP.NET web application that makes use of asp-validation-summary. Because of this an inline style is added to an HTML element in my page.
This gives me the following error in console (Chrome v78.0.3904.108) when I run my application:

Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' https://fonts.googleapis.com". Either the 'unsafe-inline' keyword, a hash ('sha256-aqNNdDLnnrDOnTNdkJpYlAxKVJtLt9CtFLklmInuUAE='), or a nonce ('nonce-...') is required to enable inline execution.

So I added the hash to my CSP, which now looks like this:
style-src 'self' https://fonts.googleapis.com 'sha256-aqNNdDLnnrDOnTNdkJpYlAxKVJtLt9CtFLklmInuUAE=';

When I load my page I still get a similar error:

Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' https://fonts.googleapis.com 'sha256-aqNNdDLnnrDOnTNdkJpYlAxKVJtLt9CtFLklmInuUAE='". Either the 'unsafe-inline' keyword, a hash ('sha256-aqNNdDLnnrDOnTNdkJpYlAxKVJtLt9CtFLklmInuUAE='), or a nonce ('nonce-...') is required to enable inline execution.

This is the entire CSP header:
X-Content-Security-Policy: default-src 'self'; object-src 'none'; frame-ancestors 'none'; sandbox allow-forms allow-same-origin allow-scripts; base-uri 'self'; upgrade-insecure-requests; style-src 'self' https://fonts.googleapis.com 'sha256-aqNNdDLnnrDOnTNdkJpYlAxKVJtLt9CtFLklmInuUAE='; font-src 'self' https://fonts.gstatic.com;

As you can see I've added the hash, as sugested in the error. It also seems to be a valid header.
But why isn't this working?

A: You must add unsafe-hashes.
unsafe-hashes allows to enable specific inline event handlers. If you only need to allow inline event handlers and not inline  elements or javascript: URLs, this is a safer method compared to using the unsafe-inline expression.
Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/style-src


text:
Q: Wordpress rewrite rule for specific page and second parametr doesnt work I have a link like this: https://example.com/page-test/?v=p300 and I created rewrite rule to point new url: https://example.com/page-test/p300/ but it doesnt work.
Just there is redirect to correct website but second parametr "v" is empty.
My code:
add_action('init', 'add_test_url');
function add_test_url() {
    add_rewrite_rule('^page-test/([^/]+)/?$', 'index.php?pagename=page-test&v=p300', 'top');
}

So first argument pagename is OK and website is redirected to the correct page but second parametr is empty ... why ? Or course after the change I save the settings permalinks.

A: OK I solved this problem:
New code:
add_action('init', 'add_test_url');
function add_test_url() {
    global $wp_rewrite;
    add_rewrite_tag('%v%', '(.+)');
    add_rewrite_rule('^page-test/([^/]+)/?$', 'index.php?pagename=page-test&v=$matches[1]', 'top');
    $wp_rewrite->flush_rules();
}

/// for debug GET value:
function console_log($content) {
    echo "<!-- console_log: " . get_query_var('v') . "-->";
}
add_filter('loop_start', 'console_log', 9);

Only thing left is .htaccess redirects from old url to new url:
<IfModule mod_rewrite.c>
    RewriteRule ^page-test/old_dir/([^/]+)/? page-test/$1 [R=301,L]
</IfModule>

In my case I had make a little change for the requests Ajax script and pass variable from GET request:
$get_example_v = get_query_var('v');


text:
Q: Data sharing on multiple angular apps Seeking your advice on effective ways of sharing data in between multiple angular apps (not multiple apps in one project. multiple war file).

*

*Local storage has few limitations

*Url driven approach is not good for keeping json like data

Can i have the best possible options ?
Thanks
Nuwan


text:
Q: Copy from a dynamic range in excel I have two workbooks, on being a template of the analyses, the other being the source of our database with no formatting at all.
I have a button that I click, select the file and it imports every row until there is a blank on the first column of the range (Column A in my case) this is a good thing. But I have cases where the first column is filled with blanks, and the second column doesn't have a single blank.
So I want to copy until Column B hits a blank, but still have column A copied.
Bellow is my code at the moment
Sub test()
    Dim fileName As Variant

    fileName = Application.GetOpenFilename()

    If fileName <> False Then
        Workbooks.Open fileName:=fileName
        MsgBox "Success!", copy()
    End If
End Function

Function copy()
    Dim myrange

    Set myrange = Sheets("Sheet1").Range("A3:L3")
    myrange.Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.copy ThisWorkbook.Worksheets("Sheet1").Range("A10")
End Function

A: The code below finds the # rows under "A3:L3" and copies the contents (as values) under "A10". It find the first blank in column A, and column B, and uses the largest of the two.
Public Sub CopyInSheet1()

    Dim myrange As Range
    Set myrange = Sheets("Sheet1").Range("A3")

    ' Find non-empty rows (check two columns)
    Dim n_rows_A As Long, n_rows_B As Long, n_rows As Long
    n_rows_A = CountRows(myrange)
    n_rows_B = CountRows(myrange.Offset(0, 1))
    n_rows = WorksheetFunction.Max(n_rows_A, n_rows_B)

    ' Do the copy here
    Sheets("Sheet1").Range("A10").Resize(n_rows, 12).Value = _
        myrange.Resize(n_rows, 12).Value

End Sub

Function CountRows(ByRef r As Range) As Long
    If IsEmpty(r) Then
        CountRows = 0
    ElseIf IsEmpty(r.Offset(1, 0)) Then
        CountRows = 1
    Else
        CountRows = r.Worksheet.Range(r, r.End(xlDown)).Rows.Count
    End If
End Function


text:
Q: Question regarding convergence to zero Let $0 \leq \epsilon < 1$ and $\{a_k\}$ be a sequence of positive numbers converging to $0$. What can we say about the sequence
$$b_n = \sum_{k=0}^n \epsilon^{n-k} a_k$$
It seems that this should converge to $0$.

A: Your guess is correct.
First of all, $b_n >0$ obviously. As $a_n$ is convergent, there is $M$ so that $a_n \le M$ for all $n$. On the other hand, let $\delta >0$. Then there is $N \in \mathbb N$ so that $a_n \le \delta$ for all $n \ge N$. Then for $m \ge N$, we have
$$\begin{split}
b_m &= \sum_{k=0}^m \epsilon ^{m-k} a_k \\
&= \sum_{k=0}^{N-1} \epsilon ^{m-k} a_k+ \sum_{k = N}^m \epsilon ^{m-k} a_k\\
&\le M \sum_{k=0}^{N-1} \epsilon ^{m-k} + \delta \sum_{k = N}^m \epsilon ^{m-k} \\
&\le MN \epsilon^{m-N+1} + \delta \sum_{k=0}^m \epsilon^{m-k}\\
&\le MN\epsilon^{m-N} + \delta \frac{1-\epsilon^{m+1}}{1-\epsilon} \\
&\le  MN\epsilon^{m-N} + \delta \frac{1}{1-\epsilon}
\end{split}$$
Now for all $\gamma >0$, first we choose $\delta >0$ so that
$$ \delta \frac{1}{1-\epsilon} <\frac{\gamma}{2},$$
then (fixing this $\delta$) we choose $N_\gamma > N$ so that
$$ MN\epsilon^{m-N} < \frac{\gamma}{2}$$
whenever $m\ge N_\gamma$. Thus we have $b_m <\gamma $ whenever $m\ge N_\gamma$. Thus $\lim b_n =0$.


text:
Q: Get new DataFrame with string column values replaced conditionally Sorry for this easy question, can't quite figure it out.
I have a DataFrame (there are other columns which I want to keep):
0          ROBBERY
1          THEFT
2          CRIM SEXUAL ASSAULT
3          ASSAULT
4          ASSAULT
            ...
1324690    THEFT
1324691    CRIMINAL TRESPASS
1324692    CRIMINAL DAMAGE
1324693    CRIMINAL TRESPASS
1324694    CRIMINAL DAMAGE
Name: Primary Type, Length: 1324695, dtype: object

I want a new DataFrame with the same values, except replacing all values in a column if they're not in a provided list e.g.
print (len(crime_df))
print (crime_df["Primary Type"])

allowed_field_values = ['BATTERY', 'THEFT', 'NARCOTICS']

# Return this DataFrame, replacing all "Primary Type" column values with "OTHER" if they're not in the list
df = crime_df.loc[~crime_df["Primary Type"].isin(allowed_field_values), "Primary Type"] = "OTHER"

print (len(df))
print (crime_df["Primary Type"])
print (df["Primary Type"])

assert(len(df) == len(crime_df))

This outputs:
1324695
0          ROBBERY
1          THEFT
2          CRIM SEXUAL ASSAULT
3          ASSAULT
4          ASSAULT
            ...
1324690    THEFT
1324691    CRIMINAL TRESPASS
1324692    CRIMINAL DAMAGE
1324693    CRIMINAL TRESPASS
1324694    CRIMINAL DAMAGE
Name: Primary Type, Length: 1324695, dtype: object

5

0          OTHER
1          THEFT
2          OTHER
3          OTHER
4          OTHER
           ...
1324690    THEFT
1324691    OTHER
1324692    OTHER
1324693    OTHER
1324694    OTHER
Name: Primary Type, Length: 1324695, dtype: object
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-207-4599b4364781> in <module>()
      9 print (len(df))
     10 print (crime_df["Primary Type"])
---> 11 print (df["Primary Type"])
     12
     13 assert(len(df) == len(crime_df))

TypeError: string indices must be integers


text:
Q: Binding Textblock with Property having text "Audit" displays text "Audi" I am binding a TextBLock with a string Property but whenever this Property contains the text "Audit", the actual text displayed on the UI is "Audi". For any other scenario, this works fine.
I am using .Net 4.0 and OS is win XP.
I am not sure if this is a bug but I can't get rid of this. If it is a bug, where do I report WPF bugs? Can anyone else also reproduce this issue? If yes, is there a workaround?
Edit: The Binding for the textblock is:
<TextBlock Padding="0,5,5,5" TextWrapping="Wrap" Text="{Binding TaskRoleMapping}" FontWeight="Bold" Foreground="White" FontFamily="Segoe UI" Margin="3,0,0,0" VerticalAlignment="Center"/>

I am sure it's not a problem with the textlength as much bigger text gets displayed alright.
Edit: The TextBlock is contained in a StackPanel
<StackPanel Height="40" Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Left" Width="Auto">
        <ContentControl Content="ContentControl" Template="{DynamicResource vector_Summary}" Height="16"/>
        <TextBlock Padding="5,5,0,5" Height="28"
                   Text="{Binding Path=[LABEL.MAIN.HEADER], Source={x:Static Util:Util.labelDictionary}}"
                   FontFamily="Segoe UI" FontSize="12"
                   Foreground="#FFFFFF" Margin="1,7,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" Width="Auto"/>
        <TextBlock Padding="0,5,5,5" TextWrapping="Wrap" Text="{Binding TaskRoleMapping}" FontWeight="Bold" Foreground="White" FontFamily="Arial" Margin="3,0,0,0" VerticalAlignment="Center"/>
</StackPanel>

A: I like  Kent Boogaart's comment/points. Basically 't' char is being cut off/out from the view. So change the font size to smaller, or remove "Bold" or introduce min size  of the TextBlock, or it's parent and 't' in "Audi" will magically appear


text:
Q: No usable Polish keyboard layout I'm using Ubuntu 12.04 with the XFCE desktop, all packages up to date.
I wanted to set up a keyboard layout for the Polish language (Polish uses the Roman alphabet, with a few additional characters like ą, ł, ż, etc). I went to the keyboard control panel, and under Polish I saw several options - all of them useless to me. One was for Kashubian. One was the obsolete QWERTZ layout. Several variations of DVORAK. And one for Russian - I don't even know what it was doing there. What was missing was the de-facto standard layout, known as "polski programisty" ("Polish programmer's").

*

*Is there a package that has the layout I want?

*If not, how do I create my own layout? And where do I send the patch?

A: Take the default Polish layout (the one with the name Polish, with no further specification). This is the programmers layout.

EDIT: Alternatively, you can always do setxkbmap -layout pl -variant basic or just setxkbmap -layout pl, but that will not be kept across sessions.
Both XFCE and the default Unity shell use the same layouts, just with different interfaces. I guess the reason that XDE uses a tree structure is that all the different variants of the Polish layout are defined in the same file, /usr/share/X11/xkb/symbols/pl. By the way, it is a simple text file; creating your own layout is not hard.

A: I was having the same problem after update to xbuntu 13.10.
Selecting Polish programmers keyboard is even more counter intuitive, as the selection dialog shows a tree instead of a list.
Here the way to select Polish programmers keyboard:

This dialog is accessible via Settings Manager > Keyboard > Layout > Add/Edit


text:
Q: Show UIButton over an Admob Banner? I'm trying to display a UIButton over an AdmobBanner like the example below (the black X obviously). I looked for this option in the Admob SDK but couldn't find anything.
I've tried selecting the button->Editor->Arrange->Send to Front with no results.

Help is much appreciated.
This is the code I use to show my banner:
CGPoint origin = CGPointMake(0.0,0.0);

// Use predefined GADAdSize constants to define the GADBannerView.
self.adBanner = [[GADBannerView alloc] initWithAdSize:kGADAdSizeBanner
                                                origin:origin];

// Note: Edit SampleConstants.h to provide a definition for kSampleAdUnitID
// before compiling.
self.adBanner.adUnitID = @"a150xxxxxxxxxxx";
self.adBanner.delegate = self;
[self.adBanner setRootViewController:self];
[self.view addSubview:self.adBanner];
self.adBanner.center =
CGPointMake(self.view.center.x, self.adBanner.center.y);
[self.adBanner loadRequest:[self createRequest]];

A: Im assuming you're using interface builder here, and that both the AdMob view and your button are subviews of the same parent view. If that is the case, just make sure the button comes before the AdMob view in the list of subviews in the Objects pane on the left.
Another option is to make the following call in viewDidLoad:
[self.view bringSubviewToFront:button]

Make sure you do this after inserting the AdMob view, if you're doing it programmatically


text:
Q: table [...] has no column named [...] SQLite java I know there have been some topics about that and I tried following all the answers given there however it didn't help with my situation. I keep getting error that column SecondPhone does not exist

E/SQLiteLog: (1) table Contacts has no column named SecondPhone
  E/SQLiteDatabase: Error inserting SecondPhone= Phone=
  PhotoUri=android.resource://project.contactmanager/drawable/untitled_1.png
  Email= Address= Name=Test
                                                                    android.database.sqlite.SQLiteException: table Contacts has no column
  named SecondPhone (code 1): , while compiling: INSERT INTO
  Contacts(SecondPhone,Phone,PhotoUri,Email,Address,Name) VALUES
  (?,?,?,?,?,?)

This is part of the error message I'm getting
And this is part my code. I expect the problem being here but it might elsewhere
public class DatabaseSQL extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 2;
    //setting variables for future database columns
private static final String DATABASE_NAME = "ContactManagerLite",
        TABLE_CONTACTS = "Contacts",
        KEY_NAME = "Name",
        KEY_PHONE = "Phone",
        KEY_SECONDPHONE = "SecondPhone",
        KEY_EMAIL = "Email",
        KEY_ADDRESS = "Address",
        KEY_PHOTOURI = "PhotoUri",
        KEY_ID = "ID";

public DatabaseSQL(Context context){
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db){                       //creates a table upon starting the application
    db.execSQL("CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT" + KEY_PHONE + " TEXT" + KEY_SECONDPHONE + " TEXT" + KEY_EMAIL + " TEXT" + KEY_ADDRESS + " TEXT" + KEY_PHOTOURI + " TEXT)");

}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){                       //if something changes the old table is being deleted and new one is being created with new data
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
    onCreate(db);
}
public void createContact(contactList contact){        //variables from getters in contactList are being set as values for database
    SQLiteDatabase db= getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getListName());
    values.put(KEY_PHONE, contact.getListPhone());
    values.put(KEY_SECONDPHONE, contact.getSecondPhone());
    values.put(KEY_EMAIL, contact.getEmail());
    values.put(KEY_ADDRESS, contact.getAddress());
    values.put(KEY_PHOTOURI, contact.getProfilePhotoUri().toString());

    db.insert(TABLE_CONTACTS, null, values);
    db.close();
}

I'm working on AndroidStudio

A: Its typo, you have not seperated any of your column name. Put (,) after datatype of each column
KEY_NAME + " TEXT," + KEY_PHONE + " TEXT," + KEY_SECONDPHONE + " TEXT," +
KEY_EMAIL + " TEXT," + KEY_ADDRESS + " TEXT," + KEY_PHOTOURI + " TEXT)"

once it is done, reinstall your app

A: You are missing commas in this create table query
db.execSQL("CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT" + KEY_PHONE + " TEXT" + KEY_SECONDPHONE + " TEXT" + KEY_EMAIL + " TEXT" + KEY_ADDRESS + " TEXT" + KEY_PHOTOURI + " TEXT)");

This should be
db.execSQL("CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT," + KEY_PHONE + " TEXT," + KEY_SECONDPHONE + " TEXT," + KEY_EMAIL + " TEXT," + KEY_ADDRESS + " TEXT," + KEY_PHOTOURI + " TEXT)");

(you have to re-run the query to make it updates, so delete app's datas on the phone before running)
Hope this helps, let me know

A: You did not put comma after every column. Try this
db.execSQL("CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT," + KEY_PHONE + " TEXT," + KEY_SECONDPHONE + " TEXT," + KEY_EMAIL + " TEXT," + KEY_ADDRESS + " TEXT," + KEY_PHOTOURI + " TEXT)");

Run your project after clearing data or reinstalling the app
Hope this helps you.


text:
Q: How to set Theme in controller test in cakePHP I use themes on my cakePHP 2.6 project and would like to test my application.
I have a view file in /app/View/Pages/view.ctp
I overwrite it here /app/View/Themed/Theme/Pages/view.ctp
How can I change the $this->theme to get the result of the themed view?
I tried this (without result):
public function testView() {
    $this->theme = 'Theme';
    $url = Router::url(array('controller' => 'Pages', 'action' => 'view'));
    $options = array(
        'return' => 'contents'
    );
    $result = $this->testAction($url, $options);
    $this->assertNotEmpty($result);
}


text:
Q: Display elements of json array using AngularJS Being a novice to angularjs framework I'm attempting to use a controller to retrieve a JSON and display elements,but the desired result is not displayed.
index.html

<input type="text" id="{{post.id}}" ng-model="post.value" placeholder="{{post.placeholder}}">

Controller : processJson.js
 var getJson = angular.module('getJson', []).controller('controller1',   function ($scope, $http) {
var url = "../../routes/fields.js";
console.log(url);
$http.get(url).success(function (data) {
    $scope.posts = data;
  });

 });

fields.js
var express=require('express');
var router =express.Router();

 router.get('/fieldlist',function(req,res){
  var db=req.db;
  var collection=db.get('domlist');
   collection.find({},{},function(e,docs){
    res.json(docs);
  });
});

module.exports=router;

Also utilising mongodb to store and retrieve as JSON data.. URL http://localhost:3000/fields/fieldlist  returns my  json array stored in mongodb.

A: Can you try $scope.posts = data.data.
The HTTP request will return an object with the data property inside:

The response object has these properties:
data – {string|Object} – The response body transformed with the
  transform functions. status – {number} – HTTP status code of the
  response. headers – {function([headerName])} – Header getter function.
  config – {Object} – The configuration object that was used to generate
  the request. statusText – {string} – HTTP status text of the response.

For more information: API Reference - $http

A: You have a ng-switch-when without an ng-switch around that causes me an error:
Error: [$compile:ctreq] Controller 'ngSwitch', required by directive 'ngSwitchWhen', can't be found!

I've prepared a JSFiddle https://jsfiddle.net/5ab19ozh/


text:
Q: Get extra input which name is not in the model class I have the following model.
public class M
{
    public int A { get; set; }
    public int B { get; set; }
}

And I have the following Razor view.
@model MyApp.Models.M
@using (Html.BEginForm("Create", "Test", new { id = ...}, FormMethod.Post)) {
    @Html.EditorFor(m => m.A)
    @Html.EditorFor(m => m.B)
    <input name="C">
}

The controller method,
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Guid id, M m)
{
    // How to get C?
}

How to get the value of input C in the controller? (one solution may be creating an extra ViewModel and map it to model, is there any simpler method?)

A: You can add an additional method parameter called FormCollection formCollection and you can interrogate this formCollection for 'C'
e.g.
var yourValueForC = formCollection["C"]

Or you could just interrogate the request as follows
var yourValueForC = Request.Form["C"]


text:
Q: Insert/Update/Delete is disabled for this control. message of EntityDataSource I use ASPxGridView and EntityDataSource as its datasource. In EntityDataSource, I write CommandText, so I can not set "EnableInsert", "EnableUpdate", or "EnableDelete" to true. That's why, I manipulate (insert, update, delete) data manually. Changes are made manually pass through to database. But at the side of the GridView these errors are given:
For inserting: "Insert is disabled for this control."
For updating:  "Update is disabled for this control."
For deleting:  "Delete is disabled for this control."
How can I solve this problem?
(The reason of using CommandText is where parameters and joining of more than 1 tables for showing in GridView.)

A: First you must have primary ID in table, and you must have it in form so you can insert it, or ideally, you set incrementing key, and just input values.
Then you have to set value property for control.
And then it should work.

A: I made workaround to this problem.
in gridview I have template column (I'm passing two arguments in CommandArgument):
<asp:TemplateField>
                   <ItemTemplate>
                       <asp:ImageButton ToolTip="Delete" ID="button4" ButtonType="Image" ImageUrl="~/Projectimages/img_del.png" Text="" CommandName="Select" CommandArgument='<%#Eval("ID") + ";" +"Delete"%>' runat="server"/>
                   </ItemTemplate>
               </asp:TemplateField>

in code behind I'm splitting CommandArgument and saving values in variables and then using them in SelectedIndexChanged event:
string selectCommand = "";
    int selectCommandID = -1;
    protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {
            if (!e.CommandArgument.ToString().Contains(";"))
                selectCommand = "Select";
            else
            {
                selectCommandID = Convert.ToInt32(e.CommandArgument.ToString().Split(';')[0]);
                selectCommand = e.CommandArgument.ToString().Split(';')[1];
            }
        }
    }

    protected void GridView_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (selectCommand == "Select")
        {
            //Select Code Here
        }
        else if (selectCommand == "Delete")
        {
            MyTestEntities context = new MyTestEntities();
            Table1 selectedRow = context.Table1.Single(a => a.ID == selectCommandID);
            context.Table1.DeleteObject(selectedRow);
            context.SaveChanges();

            EntityDataSource1.DataBind();
        }
    }

this works. You can use this for updating gridview row too.


text:
Q: Team Foundation Server with Blackberry Project in Eclipse not synching correctly I am using eclipse 3.5.2 with Team Foundation Everywhere plugin (TFS plugin).
I have several blackberry projects in my eclipse workspace which i have successfully added to TFS. However I have found that the BlackBerry_App_Descriptor.xml is not being updated in TFS when i make changes to it.
For example when I change the name and version number of the application TFS see's no change in the file so when I check in the server version is still the old data. We are developing on several machines so having changes i do on my machine not propigate to the others is causing problems.
Does anyone know why this is happening? I can see from visual inspection of the .xml file that it is changing but why does TFS not considered it any different?
I have tried manually 'check out for edit' on the file, then change the name and check it back in. But it sees that there are no changes and disreguards my checkin.
Thanks,
Stephanie

A: Incase anyone else runs into this, it seems that the eclipse plugin for TFS is having issues with comparing XML files. If i manually change the XML contents and save to disk. Then do 'Compare local with server version' it will say 'files are identical'. What I ended up doing was removing the file from TFS. Doing my edits on a local version then readding it. It gets the updates into TFS so the whole team gets the same version. Wish it would just work though because now everytime we want to change anything in an xml file its a long process instead of being a simple update/checkin


text:
Q: How do I correctly return a sequence of classes with the query expression? I am new to F# and having trouble translating some C# code.
I have a class similar to this:
type car () =
    member val Model = "" with get,set
    member val Year = "" with get,set

I have this query expression that pulls car data from the database:
query{
    for row in db do
    select // <-- what is the correct syntax to create a sequence of new car
           //    classes here
}

A: it's a lot easier if you don't translate 1:1 or at least if you add an constructor.
For example using a primary-constructor this should work:
type Car (model, year) =
   member __.Model with get() = model
   member __.Year with get() = year

query {
   for row in db do
   select (Car (row.Model, row.Year))
}

now of course I don't know how the rows in your db looks like and this will give you immutable data - but for what I see it should be fine

I just realised that this might be a problem (just as in C#) as the ctor probably cannot be translated into a SQL-statement - you can still try but I guess you really need to do
query {
   for row in db do
   select
} |> Seq.map (fun row -> Car (row.Model, row.Year))

instead (sorry - cannot really try right now)


text:
Q: Pandas and Fuzzy Match Currently I have two data frames. I am trying to get a fuzzy match of client names using fuzzywuzzy's process.extractOne function. When I have run the following script on sample data I get good results and no error, but when I run the following on my current data frames I get both an Attribute and Type error. I am not able to provide the data for security reasons, but if anyone can figure out why I am getting errors based on the script provided I would be much obliged.
names2 = list(dftr3['Common Name'])
names3 = dict(zip(names2,names2))
def get_fuzz_match(row):
            match = process.extractOne(row['CLIENT_NAME'],choices = n3.keys(),score_cutoff = 80)
            if match:
                return n3[match[0]]
            return np.nan
 dfmi4['Match Name'] = dfmi4.apply(get_fuzz_match, axis=1)

I know not having some examples makes this more difficult to troubleshoot, so I will answer any question and edit the post to help this process along. The specific errors are:
1.AttributeError: 'dict_keys' object has no attribute 'items'
2.TypeError: expected string or buffer

A: The AttributeError is straightforward and to be expected, I think. Fuzzywuzzy's process.extract function, which does most of the actual work in process.extractOne, uses a try:... except: clause to determine whether to process the choices parameter as dict-like or list-like. I think you are seeing the exception because the TypeError is raised during the except: clause.
The TypeError is trickier to pin down, but I suspect it occurs somewhere in the StringProcessor class, used in the processor module, again called by extract, which uses several string methods and doesn't catch exceptions. So it seems likely that your apply call is passing something that is not a string. Is it possible that you have any empty cells?


text:
Q: Is it better to default to using OR or AND logic when it comes to database search? Let's say I have a database containing student info, and I have the following fields:
1) Age group
2) Course name
3) Country of origin
If I were to build a search function, would it be better to assume that the user wants to search for students that matches:
Age group OR Course name OR Country of origin?
Or should I assume that users want to search for students that fulfil ALL criteria (i.e. AND logic)?
What's the best practice? I assume people mean OR most of the time, as that gives the most results.
What do you think?
Thanks very much for the feedback!!

A: If it's a big concern, give people the option. Otherwise, it depends on how it's commonly used. I'd expect to see AND so I can produce the most restrictive output and not have to sift through the stuff I don't want -- but I don't know what your user base is like; you should ask them.

A: This is an excellent candidate for User Focus Groups.  If you are building a site (as opposed to a software product or internal company application) where you do not have access to organizing focus groups, you could try and solicit feedback from your users in the form of surveys or a contact form.

A: You could always create a fulltextindex against all those fields then do a search against the index.
CREATE FULLTEXT INDEX giveitaname ON mytable (agefield, coursename, country);

Then query the index like this:
SELECT * FROM mytable WHERE MATCH(agefield, coursename, country) against ('%search_variable_here%')

Now your search will work with partial words, mismatched orders and potentially be much more relevant and yield less zero-result results.
In the meantime, I personally wouldn't worry too much about the load between OR or AND, especially if you have your indexes set up properly.  You should make the choice based on the data set you are working with and what is most intuitive and relevant for your user base.


text:
Q: How to know on Rails if Solr if up or not? I'm using sunspot gem to manage a solr service to index information. I want to do a fordward way for when solr is down to continue showing things to my users going to the db instead of indexed data while the service is up again. In base of this I want know in some before actions if solr is up or not, but researching I could't find a way to ask it to Sunspot solr. Do you know a way to do it?

A: Solr is a separate server on your machine. Let's say it's supposed to be running on localhost:3001. You can just ping that address with a CURL request.


text:
Q: How drop columns by CLASSES I have the following data.frame:
data_1 <- structure(list(Line = structure(1:4, .Label = c("K1", "K2", "K3",
"K4"), class = "factor"), A = c(4L, 1L, -1L, 2L), B = c(3L, -2L,
-1L, 4L), C = c(-1L, 1L, 2L, 5L), D = c(2L, -5L, 3L, -7L), E = c(4L,
1L, 4L, 9L)), class = "data.frame", row.names = c(NA, -4L))

I want drop integer columns. I try:
rapply(object = data_1, classes = 'integer', how = 'list', f = function(x) {
  x <- NULL
})

and
lapply(X = data_1, FUN = function(x) {
  Filter(f = is.integer, x = x) <- NULL
})

But doesn't work.
I also need to do this for a list:
list_1 <- list(data_1 = structure(list(Line = structure(1:4, .Label = c("K1",
"K2", "K3", "K4"), class = "factor"), A = c(4L, 1L, -1L, 2L),
B = c(3L, -2L, -1L, 4L), C = c(-1L, 1L, 2L, 5L), D = c(2L,
-5L, 3L, -7L), E = c(4L, 1L, 4L, 9L)), class = "data.frame", row.names = c(NA,
-4L)), data_2 = structure(list(Line = structure(1:4, .Label = c("K1",
"K2", "K3", "K4"), class = "factor"), A = c(4L, 1L, -1L, 2L),
B = c(3L, -2L, -1L, 4L), C = c(-1L, 1L, 2L, 5L), D = c(2L,
-5L, 3L, -7L), E = c(4L, 1L, 4L, 9L)), class = "data.frame", row.names = c(NA,
-4L)), data_3 = structure(list(Line = structure(1:4, .Label = c("K1",
"K2", "K3", "K4"), class = "factor"), A = c(4L, 1L, -1L, 2L),
B = c(3L, -2L, -1L, 4L), C = c(-1L, 1L, 2L, 5L), D = c(2L,
-5L, 3L, -7L), E = c(4L, 1L, 4L, 9L)), class = "data.frame", row.names = c(NA,
-4L)))

I try:
rapply(object = list_1, classes = 'integer', how = 'list', f = function(x) {
  rapply(x, rm(x))
})

lapply(X = list_1, FUN = function(x) {
  lapply(X = Filter(is.integer, x), rm(x))
})

But, also doesn't work.
Desire output:
  Line
1   K1
2   K2
3   K3
4   K4

I need a solution with R base only, not additional packages (with dplyr and your _if functions).

A: here is a R base solution using lapply:
myfun <- function(df){
  idx <- sapply(seq_len(ncol(df)), function(x) class(df[,x])) != "integer"

  df[, idx]
}

lapply(list_1, myfun)


text:
Q: GNOME minimizing/restoring all windows of a specific application In GNOME desktop, how can I minimize/restore all windows of a specific application?
I know the shortcut Super + d hides all normal windows and then restores them, but I'm looking for its equivalent that works only for windows of a given application (for example, the application running in the current window).

A: I came up with rather a hacky, non-universal solution using wmctrl and xdotool. A custom keyboard shortcut registered with the command
/bin/bash -c "for wid in $(wmctrl -l -p | grep $(xdotool getactivewindow getwindowpid) | awk '{print $1}') ; do xdotool windowactivate $wid > /dev/null 2>&1 ; done"

activates specific windows that have the same PID as the current one's, and works as desired with applications like GNOME Terminal, Nautilus, Firefox, and others. The minimization shortcut can be added with the windowminimize option replacing windowactivate. I tested the shortcuts in Ubuntu 18.04 with GNOME version 3.28.4.
Since the command discriminates windows by their PIDs, this solution does not work when windows of the same application have different PIDs.


text:
Q: Does MariaDB support ST_Distance_Sphere? Running mariadb, I'm getting

ERROR 1305 (42000): FUNCTION ST_Distance_Sphere does not exist

When I run a basic query like
SELECT ST_Distance_Sphere( POINT(0,0), POINT(0,1) );

However, I'm using a pretty new version.
Server version: 10.1.25-MariaDB-1 Ubuntu 17.10

What's going on here.

A: 10.2+
This issue has been fixed and backported with MDEV-13467. It's available 10.2.38, 10.3.29, 10.4.19, 10.5.10
Find their support matrix here.

A: ST_Distance_Sphere was added only recently to MySQL -- 5.7.6.  10.1 is not the newest; there is 10.2 and 10.3.  Sure, 10.1.25 came out recently (2017-07-04), but the development effort has shifted to 10.2.x and 10.3.x .
Feel free to file a feature request with MariaDB.


text:
Q: SlickNav menu issue in google Chrome Here is my site: http://www.reliableairinc.com, The slickNav responsive menu icon disappears upon re sizing the browser window  on dynamic pages. Facing this problem only in chrome.

A: I didn't get it, try to change the type attribute from text/x-javascript to text/javascript in the script tag. I think text/x-javascript is invalid content type.


text:
Q: How to check if a row is a subset of a data.frame? Let's say we have this data.frame df
uid | aid | Freq
-----------------
 2  |  4  |  3
 9  |  1  |  2

How do we check if this row r <- data.frame(uid=9, aid=1) is in df
For vectors >> we use %in% but it didn't work here.

A: You can check with merge. Just be sure that column names match:
df <- head(mtcars)
r <- data.frame(mpg=18.1, cyl=6)
mrg <- merge(df, r)
#    mpg cyl disp  hp drat   wt  qsec vs am gear carb
# 1 18.1   6  225 105 2.76 3.46 20.22  1  0    3    1

There are many ways you can turn this into a logical test.
nrow(mrg) > 0


text:
Q: Выдает ошибку ValueError: not enough values to unpack (expected 2, got 0) Помогите пожалуйста.

a, x=map(int, input() .split())
k=1
while True:
    y=((16*k*x**3)/((x**2+1)**3))-((12*x**2)/(x**2+1)**2)-((12*(k+1)*x)/(x**2+1))
    if y<a:
        break
    else:
        k+=1
        print(k)
---------------------------------------
ValueError  Traceback (most recent call last)
Cell In[111], line 1
----> 1 a, x=map(int, input() .split())
      2 k=1
      3 while True:
ValueError: not enough values to unpack (expected 2, got 0)


text:
Q: Como funciona [modus operandi] o autoload em PHP? Suponhamos que eu tenha a seguinte estrutura de arquivos na raiz do meu site:
index.php
autoload.php

----| /Models
--------| /MainModel
------------| MainModel.php

----| /Controllers
--------| /MainController
------------| MainController.php

Suponhamos que exista um método em MainModel.php chamado de mainMethod() como segue:
<?php namespace Models\MainModel;

class MainModel
{

    public function mainMethod()
    {
        return json_encode(array('mensagem' => 'Tudo funcionando por aqui'));
    }
}

Na index.php, eu incluo o arquivo autoload.php
<?php

include_once 'autoload.php';

// resto do código

O meu arquivo autoload.php tem o seguinte código:
spl_autoload_register(function ($class) {

    $prefix = '';

    $base_dir = __DIR__.'/';

    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }

    $relative_class = substr($class, $len);

    $file = $base_dir.str_replace('\\', '/', $relative_class).'.php';

    if (file_exists($file)) {
        require $file;
    }
});

Agora, vem a bruxaria que eu não entendo como funciona. Se eu fizer:
<?php

include_once 'autoload.php';

$obj = new Models\MainModel\MainModel;

echo $obj->mainMethod();

// Output: {"mensagem": "Tudo funcionando por aqui"}

Mesmo se eu indicar as classes dos controllers o reconhecimento é o mesmo. Funciona!
Bem, eu tenho uma closure autoload que funciona, mas como essa closure funciona? Como o autoloading do PHP reconhece as classes dentro de pastas, mesmo eu tendo indicado somente a raiz do projeto?
O PHP está indo lá dentro das pastas e reconhecendo as classes, como isso é possível?
O grande detalhe disso tudo é que se o arquivo MainModel.php não estiver dentro de uma pasta MainModel (com o mesmo nome do arquivo) o autoload não funciona.
Outra coisa curiosa é que os namespace têm que indicar o caminho do arquivo até a classe a partir da raiz Models\MainModel, depois eu declaro a classe.
Eu não quero saber como usar o autoload, porque isso eu já consegui, mas sim como funciona, porque eu estou usando algo que eu não sei como funciona.
Minha pergunta é completamente diferente da optada pelos moderados do site: ver "possível duplicada"

A: O spl_autoload_register intercepta todas suas chamadas que forem feitas assim:

*

*$foo = new AlgumaCoisa(); instanciar uma classe

*echo AlgumaCoisa::teste; pegar uma constante

*echo AlgumaCoisa::$teste; pegar uma variável estática

*$baz = AlgumaCoisa::funcao(); chama um método estático

Ele funciona como um "proxy", ele é executado antes de concluir a instancia da classe por exemplo.
Agora eu recomendo não usar require ou require_once, e nem file_exists, faça assim:
if (is_file($file)) {
    include_once $file;
}

Isso porque ele pode afetar os erros, pois se o erros esperado é Class not found quando a classe não existir o teu código vai emitir um erro de require, o que é certo, mas não para o PSR.
E o file_exists verifica arquivos e pastas, se por ventura tiver uma pasta com o nome qualquercoisa.php pode quebrar a aplicação, is_file não tem diferença de performance significativa se comparado file_exists, talvez só se executar 100.000 classes ao mesmo tempo você perca 0.0002 segundos.
Eu recomendo usar um destes exemplos:

*

*https://pt.stackoverflow.com/a/91512/3635 (PSR-4)

*https://pt.stackoverflow.com/a/157958/3635 (PSR-0)

Se for PSR-4 deve ficar assim, (adaptei para o seu caso e simplifiquei bem retirando o que acredito que não seria usado):
<?php
spl_autoload_register(function($class) {
    $class = ltrim($class, '\\');

    $file = str_replace('\\', '/', $class) . '.php';

    if (is_file($file)) {
        include_once $file;
    }
});

de fator usar uma função anonima ou não é indiferente.
Entendendo o código
Como disse você escreve o spl_autoload como desejar, existem várias maneira de implementar ele, mas vou explicar o código que escrevi:

*

*Remove \ do começo (é um bug no php 5.3, nas demais versões esse problema não existe, então basicamente é uma "retrocompatibilidade"):
$class = ltrim($class, '\\');

*Por exemplo, se $class recebe Models\MainModel\MainModel, isto irá trocar \ por /:
$file = str_replace('\\', '/', $class) . '.php';

E gera isto na variavel $file:
"Models/MainModel/MainModel.php"

Então a partir do valor de $file vamos checar se o arquivo existe e se existir ele irá incluir:
if (is_file($file)) {
    include_once $file;
}

E então o processo da chamada do new Models\MainModel\MainModel irá prosseguir

*

*P: O grande detalhe disso tudo é que se o arquivo MainModel.php não estiver dentro de uma pasta MainModel (com o mesmo nome do arquivo) o autoload não funciona.

*R: O autoload funciona, ele só não consegue fazer o include, pois não encontrou o arquivo

*P: Outra coisa curiosa é que os namespace têm que indicar o caminho do arquivo até a classe a partir da raiz Models\MainModel, depois eu declaro a classe.

*R: Isso é relativo, você implementa como quiser, mas em quase todas linguagens o namespace é representado por uma estrutura de pastas e arquivos, tem linguagens que não, como o C++, aonde o arquivo pode estar em qualquer lugar, pois o include dele não é feito no momento que usa a classe e sim quando usar #include "localfisico.h"


text:
Q: Understanding Dapper splitOn I'm getting an unexpected result showing Products with an empty Items list following the expected result with the correct Items list. It's only happening for the Product that contains multiple items. Does anyone know how to code this for Dapper?
This is my test code:
    public IEnumerable<Customer> Test2()
    {
        var query = @"select cast(1 as int) CustomerId, 'name' CustomerName,cast(1 as int) CustomerId, cast(1 as int) ProductId, 'a' ProductName, 'x' AccountOpened, cast(1 as int) ProductId, cast(1 as int) ItemId, 'a' ItemName
UNION
select cast(1 as int) CustomerId, 'name' CustomerName,cast(1 as int) CustomerId, cast(1 as int) ProductId, 'a' ProductName, 'x' AccountOpened, cast(1 as int) ProductId, cast(2 as int) ItemId, 'b' ItemName
UNION
select cast(1 as int) CustomerId, 'name' CustomerName, cast(1 as int) CustomerId, cast(2 as int) ProductId, 'b' ProductName, 'x' AccountOpened, cast(2 as int) ProductId, cast(3 as int) ItemId, 'b' ItemName
UNION
select cast(2 as int) CustomerId, 'name1' CustomerName, cast(2 as int) CustomerId, cast(1 as int) ProductId, 'a' ProductName, 'x' AccountOpened, cast(1 as int) ProductId, cast(1 as int) ItemId, 'a' ItemName
UNION
select cast(2 as int) CustomerId, 'name1' CustomerName, cast(2 as int) CustomerId, cast(1 as int) ProductId, 'a' ProductName, 'x' AccountOpened, cast(1 as int) ProductId, cast(2 as int) ItemId, 'b' ItemName
UNION
select cast(2 as int) CustomerId, 'name1' CustomerName, cast(2 as int) CustomerId, cast(2 as int) ProductId, 'b' ProductName, 'x' AccountOpened, cast(2 as int) ProductId, cast(3 as int) ItemId, 'b' ItemName
UNION
select cast(2 as int) CustomerId, 'name1' CustomerName, cast(2 as int) CustomerId, cast(3 as int) ProductId, 'c' ProductName, 'x' AccountOpened, cast(3 as int) ProductId, cast(4 as int) ItemId, 'c' ItemName";
        var lookup = new Dictionary<int, Customer>();
        DbConnection.Query<Customer, Product, Item, Customer>(query, (c, p, i) =>
        {
            if (!lookup.TryGetValue(c.CustomerId, out var cust))
                lookup.Add(c.CustomerId, cust = c);
            if (cust.Products == null)
                cust.Products = new List<Product>();
            var product = p;
            if (cust.Products.Exists(prod => prod.ProductId == p.ProductId))
            {
                product = cust.Products.Find(prod => prod.ProductId == p.ProductId);
            }
            cust.Products.Add(p);
            if (product.Items == null)
                product.Items = new List<Item>();
            product.Items.Add(i);
            return cust;
        }, splitOn: "CustomerId,ProductId");
        return lookup.Values;
    }

    public class Customer
    {
        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
        public List<Product> Products { get;set; }
    }
    public class Product
    {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
        public string AccountOpened { get; set; }
        public List<Item> Items { get; set; }
        //public int CustomerId { get; set; }
    }
    public class Item
    {
        public int ItemId { get; set; }
        public string ItemName { get; set; }
        //public int ProductId { get; set; }
    }

This is the JSON-ized response I'm getting back:
[
  {
    "customerId": 1,
    "customerName": "name",
    "products": [
      {
        "productId": 1,
        "productName": "a",
        "accountOpened": "x",
        "items": [
          {
            "itemId": 1,
            "itemName": "a"
          },
          {
            "itemId": 2,
            "itemName": "b"
          }
        ]
      },
      {
        "productId": 1,
        "productName": "a",
        "accountOpened": "x",
        "items": null
      },
      {
        "productId": 2,
        "productName": "b",
        "accountOpened": "x",
        "items": [
          {
            "itemId": 3,
            "itemName": "b"
          }
        ]
      }
    ]
  },
  {
    "customerId": 2,
    "customerName": "name1",
    "products": [
      {
        "productId": 1,
        "productName": "a",
        "accountOpened": "x",
        "items": [
          {
            "itemId": 1,
            "itemName": "a"
          },
          {
            "itemId": 2,
            "itemName": "b"
          }
        ]
      },
      {
        "productId": 1,
        "productName": "a",
        "accountOpened": "x",
        "items": null
      },
      {
        "productId": 2,
        "productName": "b",
        "accountOpened": "x",
        "items": [
          {
            "itemId": 3,
            "itemName": "b"
          }
        ]
      },
      {
        "productId": 3,
        "productName": "c",
        "accountOpened": "x",
        "items": [
          {
            "itemId": 4,
            "itemName": "c"
          }
        ]
      }
    ]
  }
]

A: I see te problem is where you work with products in query.
This may help
var product = p;
if (cust.Products.Exists(prod => prod.ProductId == p.ProductId))
{
   product = cust.Products.Find(prod => prod.ProductId == p.ProductId);
}
else
{
   cust.Products.Add(p);
}

if (product.Items == null)
   product.Items = new List<Item>();
product.Items.Add(i);

A: This is what I changed to fix the code:
        var product = p;
        if (cust.Products.Exists(prod => prod.ProductId == p.ProductId))
        {
            product = cust.Products.Find(prod => prod.ProductId == p.ProductId);
        }
        cust.Products.Add(p);

To this:
        var product = cust.Products.FirstOrDefault(prod => prod.ProductId == p.ProductId);
        if (product == null)
            cust.Products.Add(product = p);

A: The Problem is your query, Every ProductId should have the same List of Items
Your Query which should be
SELECT * FROM Customer c
INNER JOIN Product p ON c.CustomerId = p.CustomerId
INNER JOIN Item i ON i.ProductId = p.ProductId

Your Dapper query is like
var cust = DbConnection.Query<Customer, Product, Item, Customer>(query, (c, p, i) =>
    {
        c.Products.Add(p);
        p.Items.Add(i);

        return c;
    }, splitOn: "ProductId,ItemId");
return cust;

You may need to initialize your Lists if they are null.


text:
Q: How to merge columns that both have blank spaces in Google refine im working with a data base in google refine and I have 2 columns with the information "year". Both columns have values and blank spaces, and where one has a value, the other has a blank space so I want to merge both.
I found this tutorial:
http://kb.refinepro.com/2011/07/merge-2-columns-that-have-both-blank.html
Where the formula: cells["col1"].value + " " + cells["col2"].value
is used, but I dont get what I want, I just get errors and a blank new column.

A: try something like if(cells["col1"], cells["col1"].value, "") + if(cells["col2"], cells["col2"].value, "")
It looks like calling value on an empty cell is causing an error