Q: find out the number of multiples of K among the given N numbers
You are given N numbers. Now you have Q queries. For each query you
will be given an integer K
Input Format The first line consists of number N. Next N line contains N numbers. Next line contains number of queries Q. Next Q
lines contains Integer K for each query
Output Format Output Q lines the answer for every query.
Constraints 1 <= N <= 10^5; 1 <= numbers <= 10^5; 1 <= Q <= 10^5; 1 <= K <= 10^5
Sample Input
4
5
8
10
8
1
2

Sample Output
3

My code, getting one failed test case which uses 78000 inputs:
ans = []
def countSieve(arr, n):
    MAX=max(arr)
    global ans
    ans = [0]*(MAX + 1)
    cnt = [0]*(MAX + 1)
    for i in range(n):
        cnt[arr[i]] += 1
    for i in range(1, MAX+1):
        for j in range(i, MAX+1, i):
            ans[i] += cnt[j]

def countMultiples(k):
    return(ans[k])

n=int(input())
a=[]
count=0
for i in range(n):
    j=int(input())
    a.append(j)
countSieve(a,n)
q=int(input())
k=[]
for i in range(q):
    c=int(input())
    k.append(c)
i=0
for i in k:
    print(countMultiples(i))

A: The problem is that you create an array of size MAX(a) with a the list of your n numbers. This is inefficient if MAX(a) = 10^5 for example.
You should find another way to check if a number A is multiple of number B, for example A%B == 0 (use of modulo).
Try to remove countSieve and changed countMultiples.

def countMultiples(query, numbers):
    count = 0
    for i in numbers:
        if i%query == 0:
            count += 1
    return count

n=int(input())
numbers = []
for i in range(n):
    j=int(input())
    numbers.append(j)
q=int(input())
queries = []
for i in range(q):
    c=int(input())
    queries.append(c)
for i in queries:
    print(countMultiples(i, numbers))

EDIT :
Here is an optimization. First I search for numbers divisors, for each divisor I increment a counter in a dict d, then for a query q I print d[q], which is the exact amount of multiples present in the n numbers.
The method to search divisors of a number n : I make a loop until the square root of n, then for each divisor i, I also add r = n//i.
I also use a dict divs to store divisors for each number n, in order not to re-calculate them if I already found them.
Try this (it succeeded the problem https://hack.codingblocks.com/app/dcb/938) :

import math
d = {}
divs = {}

for _ in range(int(input())):
    num = int(input())
    if num in divs:
        for e in divs[num]:
            d[e] = d.get(e, 0) + 1
    else:
        div_list = []
        for i in range(1, math.floor(math.sqrt(num)) + 1):
            if not num % i:
                div_list.append(i)
                d[i] = d.get(i, 0) + 1
            r = num // i
            if (not num % r and r != i):
                div_list.append(r)
                d[r] = d.get(r, 0) + 1
        divs[num] = div_list

for i in range(int(input())):
    q = int(input())
    print(d.get(q, 0))

A: Alternatively, you could try counting how often each number appears and then checking the counts for each multiple of k up to the largest of the N numbers.
import collections

n = int(input())
nums = [int(input()) for _ in range(n)]
counts = collections.Counter(nums)
m = max(nums)

q = int(input())
for _ in range(q):
    k = int(input())
    x = sum(counts[i] for i in range(k, m+1, k))
    print(x)

At first sign, this does not look much different than the other approaches, and I think this even still has O(N*Q) in theory, but for large values of Q this should give quite a boost.
Let's say Q = 100,000. For all K > 10 (i.e. all except 10 values for K) you will only have to check at most 10,000 multiples (since m <= 100,000). For all K > 10,000 (i.e. 90% of possible values) you only have to check at most 10 multiples, and for 50% of Ks only K itself!
I other words, unless there's an error in my logic, in the worst case of N = Q = 100,000, you only have about 1,1 million check instead of 10,000,000,000.
>>> N = Q = 100000
>>> sum(N//k for k in range(1,Q+1))
1166750

(This assumes that all K are different, but if not, you can cache the results in a dict and then will only need a single check for the duplicates, too.)

On closer inspection, this approach is in fact pretty similar to what your sieve does, just a bit more compact and computing the values for each k as needed instead of all at once.

I did some timing analysis using random inputs using gen_input(n, q, max_k). First, all the algorithms seem to produce the same results. For small-ish input sizes, there is no dramatic difference in speed (except for naive modulo), and your original sieve is indeed the fastest. For larger inputs (maximal values), yours is still the fastest (even by a larger margin), and the divisors approach is considerably slower.
>>> n, q = gen_input(10000, 1000, 1000)
>>> modulo(n, q) == mine(n, q) == sieve(n, q) == modulo(n, q)
True

>>> %timeit modulo(n, q)
1 loop, best of 3: 694 ms per loop
>>> %timeit mine(n, q)
10 loops, best of 3: 160 ms per loop
>>> %timeit sieve(n, q)
10 loops, best of 3: 112 ms per loop
>>> %timeit divisors(n, q)
1 loop, best of 3: 180 ms per loop

>>> n, q = gen_input(100000, 100000, 100000)
>>> %timeit mine(n, q)
1 loop, best of 3: 313 ms per loop
>>> %timeit sieve(n, q)
10 loops, best of 3: 131 ms per loop
>>> %timeit divisors(n, q)
1 loop, best of 3: 1.36 s per loop

Not sure why you are getting timeouts for yours and mine algorithm while @phoenixo's divisors allegedly works (did not try it, though)...


Q: Bootstrap 3 is unable to unmark the justified dropdown button group for the inactive options With Bootstrap 3.3.7, I am trying to have a justified navigation dropdown button group, to mark correctly, after selection. I am having the problem of both menu options being marked, in the dropdown button, when one after another options being selected. Are there anyways to have the dropdown menu to mark only the option being selected, while being a justified group dropdown navigation button? Thank you!
sample code

        Left
        Middle

             Dropdown

drop 1

drop 2

please select 1 of the options in the dropdown

please try the dropdown on the right

please try select drop 2 also, then both are marked under the dropdown

please try select drop 1 also, then both are marked under the dropdown

A: Instead of using button groups I'd recommend using the Nav component instead styled with the pills modifier class. It's not the same but very close and the Tab panels are built to work with the pills styling.
It will solve the problem you have now with the active class remaining on the dropdown options.

Home

Profile

      Dropdown

Messages

Settings

home

profile

messages

settings

https://codepen.io/partypete25/pen/Moooaq?editors=1100

A: I tailored @partypete25 answers, to my needs. Thanks again @partypete25!
sample code

Left

Middle

                 Dropdown

drop 1

drop 2

please select 1 of the options in the dropdown

please try the dropdown on the right

please try select drop 2 also, then both are marked under the dropdown

please try select drop 1 also, then both are marked under the dropdown


Q: Sort array by name with array key I have an array like this, how can I sort by "name"
Array (
    [0] => Array (
        [id] => 1
        [name] => status_category_confide
    )
    [1] => Array (
        [id] => 2
        [name] => status_category_love
    )
    [2] => Array (
        [id] => 3
        [name] => status_category_household
    )
    [3] => Array (
        [id] => 4
        [name] => status_category_family
    )
    [4] => Array (
        [id] => 5
        [name] => status_category_friends
    )
    [5] => Array (
        [id] => 6
        [name] => status_category_colleague
    )
    [6] => Array (
        [id] => 7
        [name] => status_category_work
    )
    [7] => Array (
        [id] => 8
        [name] => status_category_ambition
    )
)

I've tried using the "sort" function but it doesn't work
$get_status_mood=mysqli_query($con, "select id, name from category");
while ($gsm=mysqli_fetch_array($get_status_mood)) {
    //array_push($status_category, constant($gsm['name']));
    $status_category[] = array(
        "id"=>$gsm['id'],
        "name"=>$gsm['name']
    );
}

sort($status_category);
for ($i=0; $i<count($status_category); $i++) {
    echo"<option value='".$status_category[$i]['id']."'>".$status_category[$i]['name']."</option>";
}

I want to display the results in the order of the name

A: Try the SQL order by option
$get_status_mood=mysqli_query($con, "select id, name from category order by name asc");

A: You can sort it using array_column and array_multisort functions.
$keys = array_column($array, 'name');

array_multisort($keys, SORT_ASC, $array);

A: You can try it with usort this sort an array by values using a user-defined comparison function
   function cmp($a, $b)
{
  return strcmp($a["name"], $b["name"]);
}
usort($vc_array, "cmp");

A: $a = array();
$a[] = array('id' => 1, 'name' => 'status_category_confide');
$a[] = array('id' => 2, 'name' => 'status_category_love');
$a[] = array('id' => 3, 'name' => 'status_category_household');

function cmp($x, $y) {
    if (strcmp($x['name'], $y['name']) == 0) {
        return 0;
    }
    return (strcmp($x['name'], $y['name']) < 0) ? -1 : 1;
}
usort($a, "cmp");

print_r($a);


Q: updating query parameters in SQL Data Source I have following code that updates the value of query parameters of a SQL Data Source after going through some conditions.
SqlDataSource sdm = new SqlDataSource("<our connection string>", "SELECT  [Message Id] ,[To] ,[From] ,[Reply To] ,[Subject] ,[Message] ,[Date added] FROM [database].[dbo].[User Messages] where ([to]=@sid or [from]=@sid) and ([to]=@qid or [from]=@qid)  and [reply to]=@rid");

string user = Session["USERID"].ToString();
string to = Request["to"].ToString();
string from = Request["from"].ToString();
sdm.UpdateParameters["rid"].DefaultValue = Request["replyid"].ToString();
sdm.UpdateParameters["sid"].DefaultValue = user;
if (user == to)
  sdm.UpdateParameters["qid"].DefaultValue=from;
else
  sdm.UpdateParameters["qid"].DefaultValue= to;

sdm.Update();
sdm.DataBind();
Repeater1.DataSource = sdm;
Repeater1.DataBind();

Its showing NullReferenceException at sdm.UpdateParameters["rid"].DefaultValue = Request["replyid"].ToString();
rid is already set in query string as ?rid=a

A: You'll want to use the Request.QueryString collection to get your rid parameter out:
sdm.UpdateParameters["rid"].DefaultValue = Request.QueryString["rid"];

Using an indexer with Request will get you values out of the QueryString, Form, Cookies or ServerVariables collections, using Request.QueryString directly makes your intentions that little bit clearer.

A: Shouldn't the query string be ?replyid=a instead of ?rid=a?.
It seems that Request["replyid"] returns null, and then ToString() throws the exception.


Q: How to display Date to Ext Js Column with Json response stackoverflow forum member I need some help from you.
I am getting the server response for the startDate in json format as
"startDate":1328466599000
I want to display it to my ExtJs column. But I am not able to display it.
My column in which i am displaying StartDate is
[Ext.Date.format(values.StartDate, "c")]
and my TaskModel is
Ext.define("TaskModel", {
        extend : "Gnt.model.Task",

        // Some custom field definitions
        fields : [
            { name: 'Id', type: 'int', useNull : true, mapping: 'id'},
            { name: 'StartDate', type: 'date', mapping: 'startDate'},
            { name: 'EndDate', type: 'date', mapping: 'endDate', dateFormat: 'MS'},
            { name: 'Priority', defaultValue : 1, mapping: 'priority', dateFormat: 'MS' },
            { name: 'Duration', mapping: 'duration'},
             { name: 'PercentDone', mapping: 'percentDone'},
             { name: 'DurationUnit', mapping: 'durationUnit'},
             { name: 'parentId', mapping: 'parentId', type: 'int'},
             { name: 'Name', mapping: 'taskName'},
             { name: 'index', mapping: 'taskindex'},
             { name: 'depth', mapping: 'depth'},
        ]
    });

I am not able to view my startDate I am receiving as response to my Column.
Does anyone have any idea as to what is causing this error? If anyone has a solution to this problem please help me.

A: Could it be that you have defined the dateformat on the priority column, not startdate column?

A: I did a blog post here: http://peterkellner.net/2011/08/24/getting-extjs-4-date-format-to-behave-properly-in-grid-panel-with-asp-net-mvc3/
sorry for digging up something from a while back but I was just searching for the same thing and ran into my blog post first (before this item)


Q: jQuery two column (one dimensional) array? I have a simple one dimensional array but I want to split the long list into two columns using jQuery. How can I achieve this?
var articles = ['article10','article9','article8','article7','article6','article5','article4','article3', 'article2', 'article1'];
for ( var articCounter = articles.length; articCounter > 0; articCounter--) {
    document.write(' ' + articles[articCounter-1] + '
');
} // end for

I don't want to have to create two different arrays for two different float divs....
I've googled this many times but many other methods deal with multidimensional arrays.
Thank you very much for the help in advance.
EDIT: Right now it's just one long list like so:
Article1
Article2
Article3
....
But I would like to achieve this:

A: This will split your array into 2 arrays:
var articles = ["article1", "article2", "article3", "article4", "article5", "article6", "article7", "article8", "article9", "article10"];
var separatorIndex = articles.length & 0x1 ? (articles.length+1)/2 : articles.length/2;

var firstChunk = articles.slice(0,separatorIndex);
//["article1", "article2", "article3", "article4", "article5"]
var secondChunk = articles.slice(separatorIndex,articles.length);
//["article6", "article7", "article8", "article9", "article10"]

Then you can use them where and/or how you want.
Explanation
The 2nd line finds an anchor index (alias -> middle index of division),by which array should be divided into 2 chunks. The array can have odd and even lengths,and those 2 situations must be distinguished. As it is impossible to divide odd-length array into 2 equal parts, it must be divided in such way, that 1st chunk will have 1 element more or less,than 2nd chunk.Here, I have implemented first case,that is, 1st chunk will have 1 element more,than 2nd one. Here are the examples of different situations:
total length | 1st (length) | 2st (length) | separatorIndex
    10            0-4 (5)        5-9 (5)          5
    11            0-5 (6)       6-10 (5)          6
    12            0-5 (6)       0-11 (6)          6

In table, number-number syntax shows accordingly start and end indexes in array. The division is done by .slice() function.


Q: Delete unpersisted record I wonder what's the procedure to delete a non persisted record.
I have a domain that has many redirections
I start to create a redirection with
domain = @modelFor('domain')
redirection = @store.createRecord('redirection')
domain.get('redirections').pushObject(redirection)

is this correct ? And how to delete the redirection object if my user click on cancel button ?
I've tried this but that does not work.
redirection = @get('model')
redirection.rollback()
redirection.unloadRecord()

I'm using ember and ember-data both in canary version.
Thanks.

A: You should be able to do
redirection = @get('model')
@store.deleteRecord(redirection)


Q: IPython change input cell syntax highlighting logic for entire session You can use extensions or display helpers in IPython to make whatever syntax highlighting you'd like on output cells.
For some special cell magics, like %%javascript you can also see the input cell itself is rendered with that language's natural syntax highlighting.
How can you cause every input cell to be displayed with some chosen, non-Python syntax highlighting (regardless of any magics used on a cell, regardless of whether the cell embodies Python code, some other language).
In my case I am working with a custom-made cell magic for a proprietary language. The %%javascript syntax highlighting works well for this language, but if I have my own %%proprietarylang magic function, I obviously can't use %%javascript to help me with how the cell is displayed.
Is there a setting I can enable when I launch the notebook, or some property of the ipython object itself that can be programmatically set inside of my magic function, which will cause the same display logic to happen as if it was %%javascript.
I know that general-purpose on-the-fly syntax highlighting is not supported by the notebook currently. I'm asking specifically about how to make use of pre-existing syntax highlighting effects, such as that of %%javascript.
I've seen some documentation referring to IPython.config.cell_magic_highlight but this does not seem to exist anymore. Is there a standard replacement for it?

A: To replace IPython.config.cell_magic_highlight, you can use something like
import IPython
js = "IPython.CodeCell.config_defaults.highlight_modes['magic_fortran'] = {'reg':[/^%%fortran/]};"
IPython.core.display.display_javascript(js, raw=True)

so cells which begin with %%fortran will be syntax-highlighted like FORTRAN. (However, they will still be evaluated as python if you do only this.)

A: For recent IPython version, the selected answer no longer works. The 'config_default' property was renamed options_default (Ipython 6.0.0).
The following works:
import IPython
js = "IPython.CodeCell.options_default.highlight_modes['magic_fortran'] = {'reg':[/^%%fortran/]};"
IPython.core.display.display_javascript(js, raw=True)


Q: How to output vertical bar format in textfile I am trying to save my contents in the textfile in this format
|Name|Description|

|QY|Hello|

But for now mine is returning me as this output:
|2014 1Q    2014 2Q 2014 3Q 2014 4Q|

|96,368.3   96,808.3    97,382  99,530.5|

Code:
def write_to_txt(header,data):
    with open('test.txt','a+') as f:
        f.write("|{}|\n".format('\t'.join(str(field)
                          for field in header))) # write header
        f.write("|{}|\n".format('\t'.join(str(field)
                          for field in data))) # write items

Any idea how to change my code so that I would have the ideal output?

A: This is happenning because you are joining the fields inside data iterable using \t , use | in the join as well for your requirement. Example -
def write_to_txt(header,data):
    with open('test.txt','a+') as f:
        f.write("|{}|\n".format('|'.join(str(field)
                          for field in header))) # write header
        f.write("|{}|\n".format('|'.join(str(field)
                          for field in data)))


Q: Why does adding a new element to an array list replace all the previous elements with the new one? I have a method in my class TextPlan, which calls all my rules in another class RSTRule and adds all rules to an array list. For this method I have used import java.lang.reflect.InvocationTargetException andimport java.lang.reflect.Method.
But it adds to the array list incorrectly. For example, the result ofadd(RSTRule)` in each call of RST methods are as follows:
 call 1: RSTRules.add(RSTRule)=R1
 call 2: RSTRules.add(RSTRule)=R2,R2
 call 3: RSTRules.add(RSTRule)=R3,R3,R3
 call 4: RSTRules.add(RSTRule)=R4,R4,R4

That means that every time I add a new element, it removes the previous elements from the array list, but repeats the new element.
Here is my code:
public class TextPlan extends ArrayList<Object>  {

  RSTRules rstRules=new RSTRules();

  public RSTRules produceAllRSTRules(RSTRules rstRules) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    RSTRule rstRule=new RSTRule();
        Method[] methods =rstRule.getClass().getMethods();
        for (Method method : methods) {
             if (method.getName().startsWith("generate")) {
            rstRule=(RSTRule)method.invoke(rstRule);
            rstRules.add(rstRule) ;
               }
         }
          return rstRules;
   }
}

hier one of my methodes in "RSTRule", which i call all of them in "TextPlan" to produce an instance of all Rules;
public class RSTRule{
    protected String ruleName;
    protected DiscourseRelation discourseRelation;
    protected String ruleNucleus;
    protected String ruleSatellite;
    protected String condition;
    int heuristic;

    public RSTRule generateBothAppearBothCosts_Join(){
            this.discourseRelation=DiscourseRelation.Join;
            this.ruleNucleus="BothProductAppear_Elaboration";
            this.ruleSatellite="BothProductCost_Elaboration";
            this.ruleName="BothProductAppearAndBothProductCost_Join";
            this.condition=null;
            this.heuristic=9;
            return this;
        }
}

A: You're not adding four new RSTRule instances to the list, you're adding the same RSTRule instance four times and modifying it each time through. Since it's the same instance stored four times, the modifications show up in every position of the list.


Q: chosen-select not working bootstrap 3 modal? I cannot fix a chosen-select from a modal which i am following here http://jsfiddle.net/koenpunt/W6dZV/,  I cannot apply it  to my code, please see this image
I have a chosen select on its page, but not on modal, I want to apply it on my modal,
this is my code on button:

Bootstrap starter template

Use this document as a way to quickly start any new project.
 All you get is this text and a mostly barebones HTML document.

  Launch demo modal

anyway, I am still applying the codes on the fiddle to mide.
the modal:

          ×
          Modal title

        United States
        United Kingdom
        Afghanistan
        Aland Islands
        Albania
        Algeria
        American Samoa
        Andorra
        Angola
        ....

          Close
          Save changes

and for the script.

As you can see, I have chosen select at the background, but i cannot apply it on modal.


Q: Getting an error on my do while loop in the doAgain method Getting an error on my do while loop in my doAgain method. Not sure why. Trying to use another Boolean method to check for mistakes in the user input :
import java.util.Scanner;
import java.util.Random;

public class Lottery {
    public static void main(String[] args) {
        do {
            int digits = getDigits();
            System.out.println(createNumber(digits));
        } while (doAgain() != false);
    }

    public static int getDigits() {
        Scanner kb = new Scanner(System.in);
        System.out.println("How many digits do you want the num to be?");
        int digits = kb.nextInt();
        return digits;
    }

    public static String createNumber(int digits) {
        Random r = new Random();
        StringBuilder sb = new StringBuilder(digits);
        for (int i = 0; i < digits; i++)
            sb.append((char) ('0' + r.nextInt(10)));
        return sb.toString();
    }

    public static boolean doAgain() {
        do {
            Scanner kb = new Scanner(System.in);
            String answer;
            System.out.println("Do you want to do this again? Enter yes to continue or no to quit");
            answer = kb.nextLine();
            if (answer.equals("yes"))
                return true;
            else
                return false;
        } while (incorrect(answer) != false);
    }

    public static boolean incorrect(String answer) {
        if (!answer.equals("yes") || !answer.equals("no"))
            return true;
        else
            return false;
    }
}

A: You should declare String answer=""; inside doAgain function. Otherwise you will get cannot find symbol error in this line
while (incorrect(answer) != false);

Modify doAgain function to this
 public static boolean doAgain() {
        String answer="";
        do {
            Scanner kb = new Scanner(System.in);
//            String answer;  // remove this
            System.out.println("Do you want to do this again? Enter yes to continue or no to quit");
            answer = kb.nextLine();
            if (answer.equals("yes")) {
                return true;
            } else {
                return false;
            }
        } while (incorrect(answer) != false);
    }

A: Here a some mistakes you made:

*

*!answer.equals("yes") || !answer.equals("no") always returns true.

*answer in } while (incorrect(answer) != false); is out of scope. You need to declare String answer = ""; before the do-while loop.

*The loop never repeats, because of you if else which always returns in the loop.
The fixed code can be:
public static boolean doAgain() {
    Scanner kb = new Scanner(System.in);
    String answer = "";
    do {
        System.out.println("Do you want to do this again? Enter yes to continue or no to quit");
        answer = kb.nextLine();
    } while (incorrect(answer)); // Better not use double negative

    if (answer.equals("yes"))
        return true;
    else
       return false;
}

public static boolean incorrect(String answer) {
    if (answer.equals("yes") || answer.equals("no"))
        return false; // answer is correct
    else
        return true; // answer is incorrect
}


Q: Validation of IP address in Scala I want to validate the IP address in scala. I have implemented the method but I am seeing some errors.
Can anyone look into it and suggest if they have better solution. I am not trying to implement functionally.
 def validIPAddress(IP: String): String = {

       var isValidIP = true
       if(IP.contains(":")) {
            var numbers= IP.split(":")   //create an array
            if (numbers.length!=8) return "Neither"
            for (n <- numbers) {
                if(n.length = 0 or n.length > 4) return "Neither"
                else {
                    for (m <- n) {
                        if(!m in "0123456789abcdefABCDEF") return "Neither"
                    }
                }
            }
            return "IPv6"
       }
       else if(IP.contains(".") {     //192.168.1.1
              nums = IP.split(".")
              if(nums.length!=4) isValidIP = false  //Array.length
              else {
                for (a <- nums) {
                  println(a)
                  try {
                    var intA = a.toInt
                    if(intA <=0 || IntA > 255) {
                      isValid = false
                    }

                  } catch (NumberFormatException e)  {
                    case e: Exception => None
                  }
                }

                if(isValid == true) {
                  println("Valid IP")
                } else {
                  println("Invalid IP")
                }

              }
       } return "IPv4"

       else {
         return "neither"
       }

       }

A: You might not intend to implement funcationaly but there is no need for imperative code in your example at all and returns and vars cause some serious issues when it comes to reading the intend of the code.
I would rewrite the code to something like this
sealed trait IP extends Product with Serializable
object IP {
  final case class V4(a: Int, b: Int, c: Int, d: Int) extends IP
  final case class V6(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int, g: Int, h: Int) extends IP
}

val ipV4 = """(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})""".r
val ipV6 = """([0-9a-fA-F]+):""".r

def validIPAddress(ip: String): Either[String, IP] = {
  def parseV4(s: String) = {
    val i = Integer.parseInt(s)
    if (0 <= i && i <= 255) Right(i) else Left(s"$i is not a valid IPv4 number")
  }
  def parseV6(s: String) = Integer.parseInt(s, 16)

  ip match {
    case ipV4(a, b, c, d) =>
      for {
        a1 <- parseV4(a)
        b1 <- parseV4(b)
        c1 <- parseV4(c)
        d1 <- parseV4(d)
      } yield IP.V4(a1, b1, c1, d1)
    case ipV6(a, b, c, d, e, f, g, h) =>
      // technically speaking this isn't exhausting all possible IPv6 addresses...
      // as this regexp would ignore e.g. ::1 or ::
      Right(IP.V6(parseV6(a), parseV6(b), parseV6(c), parseV6(d), parseV6(e), parseV6(f), parseV6(g), parseV6(h)))
    case _ =>
      Left(s"$ip is neither V4 nor V6 format")
  }
}

to make it easier to follow and debug errors, though as I checked this implementation is NOT really conforming to what IPv6 does, as some tuning around regexp usage would be necessary. As a matter of the fact, I would prefer to avoid rolling my own solution altogether if I couldn't afford some time for writing down like 15-20 test cases.
So, unless there is a reason to implement your own validator I would delegate that task to some library which already tested handling corner cases.
If you have to, however, do the following things:

*

*don't use return - in Scala it does something different than what you think it does

*don't use vars unless you're optimizing - the way you use them have nothing to do with optimization (isValid is never used, so why override it? and other vars are never modified)

*don't use string for everything because that is asking for trouble on its own (e.g. "neither" and "Neither" - should the caller use .equalsIgnoreCase on your code to check results?)

*start with tests written basing on specification. While I translated your code it fails valid IPv6 addresses. If I skipped the requirement that Iv6 is fixed size, it  would be even shorter to:

sealed trait IP extends Product with Serializable
object IP {
  final case class V4(a: Int, b: Int, c: Int, d: Int) extends IP
  final case class V6(values: List[Int]) extends IP
}

val ipV4 = """(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})""".r
val ipV6 = """([0-9a-fA-F]*)((:[0-9a-fA-F]*){2,})""".r

def validIPAddress(ip: String): Either[String, IP] = {
  def parseV4(s: String) = {
    val i = Integer.parseInt(s)
    if (0 <= i && i <= 255) Right(i) else Left(s"$i is not a valid IPv4 number")
  }
  def parseV6(s: String) = if (s.isEmpty) 0 else Integer.parseInt(s, 16)

  ip match {
    case ipV4(a, b, c, d) =>
      for {
        a1 <- parseV4(a)
        b1 <- parseV4(b)
        c1 <- parseV4(c)
        d1 <- parseV4(d)
      } yield IP.V4(a1, b1, c1, d1)
    case ipV6(head, tail, _) =>
      val segments = head +: tail.substring(1).split(':')
      Right(IP.V6(segments.map(parseV6).toList))
    case _ =>
      Left(s"$ip is neither V4 nor V6 format")
  }
}

which handled more correct cases but is still far from ready. So if you can - avoid doing it yourself and use a library.


Q: How to upload video file on parse in android? I am trying to upload video file on parse. For uploading the video I am using following code:
    File inputFile = new File(uri.toString());
    FileInputStream fis = new FileInputStream(inputFile);
    ByteArrayOutputStream bos= new ByteArrayOutputStream();
    byte[] buf = new byte[(int)inputFile.length()];

        for (int readNum; (readNum=fis.read(buf)) != -1;){
            bos.write(buf,0,readNum);
        }
        byte[] bytes = bos.toByteArray();
    ParseFile file = new ParseFile("testVideo1.mp4", bytes);
    ParseObject parseObject = new ParseObject("chat1");
    parseObject.saveInBackground();

But inputfile the File object not converted to FileInputStream.

A: thanks for the this, helped me get started with uploading a video to parse, I figure out your issue, you just didn't put the parse file in your parseobject. basically you never sent the video
File inputFile = new File(uri.toString());
FileInputStream fis = new FileInputStream(inputFile);
ByteArrayOutputStream bos= new ByteArrayOutputStream();
byte[] buf = new byte[(int)inputFile.length()];

    for (int readNum; (readNum=fis.read(buf)) != -1;){
        bos.write(buf,0,readNum);
    }
    byte[] bytes = bos.toByteArray();
ParseFile file = new ParseFile("testVideo1.mp4", bytes);
ParseObject parseObject = new ParseObject("chat1");
//addition
parseObject.put("video",file);
//it should work with this
parseObject.saveInBackground();


Q: How to use string keys in (fluent) NHibernate I am working with brownfield database that uses strings as primary keys.
Using Fluent NHibernate with Sqlite (in-memory provider for unit testing) and SQL Server 2005.
I have the following entity:
public class Entity
{
    public virtual DateTime TimeStamp { get; set; }

    public virtual string Name { get; set; }
}

With this mapping:
public class EntityMap : ClassMap<Entity>
{
    public EntityMap()
    {
        Map(_ => _.TimeStamp);
        Id(_ => _.Name).CustomType("AnsiString");
    }
}

However it does not work saying NHibernate.TypeMismatchException : Provided id of the wrong type. Expected: System.Int32, got System.String
How make this work? Also, is there any good documentation about fluent nhibernate available?
Thanks in advance.

A: If you are using strings as your primary keys you'll probably have to do something like this:
public class EntityMap : ClassMap<Entity>
{
    public EntityMap()
    {
        Id(x => x.Name).GeneratedBy.Assigned();
        Map(x => x.TimeStamp);
    }
}

From the nhibernate documentation:

5.1.4.7. Assigned Identifiers
If you want the application to assign identifiers (as opposed to
  having NHibernate generate them), you may use the assigned generator.
  This special generator will use the identifier value already assigned
  to the object's identifier property. Be very careful when using this
  feature to assign keys with business meaning (almost always a terrible
  design decision).
Due to its inherent nature, entities that use this generator cannot be
  saved via the ISession's SaveOrUpdate() method. Instead you have to
  explicitly specify to NHibernate if the object should be saved or
  updated by calling either the Save() or Update() method of the
  ISession.

Also here is a related article. It is a bit dated but still applies to your situation:
http://groups.google.com/group/fluent-nhibernate/browse_thread/thread/6c9620b7c5bb7ca8


Q: Adding custom function to handle additional column/ data while resampleBarFeed in PyAlgoTrade I am resampling custom columns with pyalogtrade.
Say I have an extra column called EX other than the default columns (open, close, high, low, etc). This is initialized and passed around in the bar.BasicBar() function as {'extraCol1' : 1.09 }.
By default, when the data is resampled, the EX is 0 in the resampled data. How/ where do we change, or override this default behaviour of pyalogtrade.
Example:
Say if we have three 1-minute OHLCV EX bars as follows (toy example)
       Cols: [O H L C V EX]
1-min bar#1: [1 1 1 1 1 1]
1-min bar#2: [2 2 2 2 2 2]
1-min bar#3: [3 3 3 3 3 3]

While resampling it for 3-minute, we get a bar like this:
       Cols: [O H L C V EX]
3-min bar#1: [1 3 1 3 3 *0*]

Suppose we want custom handling of the EX column, say:
resampled EX = 3rd minute - 1st minute = 3 - 2 = 1 (instead of the 0)
How does one achieve that?


Q: Hide parent div if :empty Trying to hide a parent div if a sibling is empty when document is ready. Doesn't seem to work for me:

$('.pp-post-content-location:empty').parent().hide();

  Location

A: First of All You Haven't included Document .ready in your Script
Here's The Code Try this
$(document).ready(function(){
var text=$('.pp-post-content-location').text(); //text Is Jquery Function which gets the content inside a element

if(text==""){
$('.pp-post-content-location').parent().hide();
}
});

Then Just a Simple If Condition to check That is there any Content In Specified Element If it has not Any content then it will hide the PARENT element


Q: CSS Selector for last-of-type/last-child but different parents? Would like to access item 6 only through css

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

A: EDIT
I think that it is duplicate. Select :last-child with especific class name (with only css)
So you need which div you want to point. In this case, this is second div so we specified:
div:nth-child(2)

And then we just select last li as below:
li:last-child

So finaly we got:
div:nth-child(2) li:last-child{
  background-color: red;
}

EDIT
With jQuery:
$('li').last().css('background', 'red');

Just to let you know, your html structure is incorrect as you should set li right after ul or ol

$('li').last().css('background', 'red');

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6


Q: jsp failed to embed applet from jar, class-file not found I try to embed an applet into my Applet.jsp via jsp:plugin.
When I call the jsp through tomcat, the applet throws a "ClassNotFoundException".
So far I figured out, that the jar-file could be found and even downloaded, when I entered the classpath into url. In my tomcat-logs I see, that the test.jar is found, but not the MyClass.class in it.
My project-structure:
webapp
- applets
  - test.jar
- WEB-INF
  - templates
    - Applet.jsp
  - web.xml

The jar file only contains MyClass.class.
Applet.jsp
<jsp:plugin type="applet" /webapp/applets/test.jar" code="MyClass.class" width="300" height="300"></jsp:plugin>

Tomcat log
"POST /webapp/servlet/applet HTTP/1.1" 200
"GET /webapp/applets/test.jar/MyClass.class HTTP/1.1" 404

I also tried
Applet.jsp
<jsp:plugin type="applet" archive="/webapp/applets/test.jar" code="MyClass" width="300" height="300"></jsp:plugin>

and several variations, but no luck.
Tomcat log
"POST /webapp/servlet/applet HTTP/1.1" 200
"GET /webapp/applets/test.jar HTTP/1.1" 200
"GET /webapp/servlet/MyClass.class HTTP/1.1" 404

Versions are java 1.7, tomcat 7
Why isn't MyClass.class found in the test.jar?
EDIT
I figured out, that is has to do with the jsp or so.
My html with embeded applet-jar works, the jsp still fails.
html
<html>
<head>
  <title>Time</title>
</head>
<body>
  <object codetype="application/java-vm" width="300" height="300" archive="test.jar" classid="java:MyClass.class"></object>
</body>
</html>

Has anybody some ideas about why jsp won't cooperate?
And at least I would love to use jsp:plugin


Q: Socket Program to demonstrate Link layer communication in a network without using ip address As we all know that within a network, communication is by the MAC address and not by the ip address. So I always used to think that whether we can write a socket program in server-client paradigm which are only using MAC address for communication but not ip address i.e. the struct sock_in should be left unfilled, and within a lan they should be able to communicate.

A: Raw sockets, as given by the example above (by Carl) can work to give you access for L3 header. However, note that on more up-to-date Windows (XP SP3, Vista and 7) raw sockets are greatly restricted by the socket layer, making it difficult to send arbitrary data of your choosing.
You can also use special libraries that allow for a much more raw access to the Ethernet adapter. WinPcap (for Windows) or libpcap (for Linux) will allow you to manipulate the entire packet data, including the Ethernet header, and indeed send any other L2 protocol you wish.


Q: Magento properly reindex everything I have searched for a while, followed this answer even looked at the shell indexer script, and I came with this. Basically, I have
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_MANUAL));
$processes->walk('save');

// Importing data here...

Mage::getModel('catalog/product_image')->clearCache();

// rebuild everything!!!
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('reindexEverything');
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME));
$processes->walk('save');

But I still get this screen in my backend

...How to "update" the indexes?
** UPDATE **
Problem solved!
To properly index everything, just call everything!
// rebuild everything!!!
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME));
$processes->walk('save');

$processes->walk('reindexAll');
$processes->walk('reindexEverything');

A: If you run indexer.php from cli, using the following parameters, do the alerts become resolved:
indexer.php reindex all
If so, is executing indexer.php with those params as part of your script an option?
Edit: also, in Mage_Index_Model_Process take a look at reindexEverything() method.
indexer.php has an example of its usage.

A: I just encountered this issue in CE v1.9.0.1. My admin module was getting all processes as a collection and looping through each one calling reindexEverything(). I based the code on the adminhtml process controller which was working fine, but my code wasn't working at all.
I finally figured out the issue was that I had previously set the reindex mode to manual (to speed up my product import routine) as follows:
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_MANUAL));

// run product import

$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
foreach($processes as $p)
{
    if($p->getIndexer()->isVisible())
    {
        $p->reindexEverything();
        //echo $p->getIndexer()->getName() . ' reindexed
';
    }
}

$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME));

SOLUTION: set mode back to MODE_REAL_TIME before reindexing everything:
$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_MANUAL));

// run product import

$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME));

$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
foreach($processes as $p)
{
    if($p->getIndexer()->isVisible())
    {
        $p->reindexEverything();
        //echo $p->getIndexer()->getName() . ' reindexed
';
    }
}

Note: these are snips from a few different methods hence the repeated assignment of $processes etc..
It seemed reindexEverything() wasn't doing anything when the processes index mode was set to MODE_MANUAL. Setting mode back to MODE_REAL_TIME and then calling reindexEverything worked fine.
I hope this helps someone as I had a few frustrated hours figuring this one out!
Thanks


Q: How to pre-populate a form from a web app on a different server I have Web Application A on Server A that links to Web Application B on Server B. I'm linking to a form that I want to pre-populate with data from Web Application A. So:
Web App A --Links to form and sends data for pre-population--> Web App B
Since they're on seperate servers I importunately can't just plop something into Session, so I'm going to have to be a little more creative. I'm considering a few different options and I'm looking for the simplest of those solutions. Any suggestions?
Here's a few options I'm considering:

*

*Pass the form data in the link via query string parameters. This seems simple enough, is the legit to do? Or is it a security concern? I'd be passing about 8 parameters, the most sensitive being e-mail address and address. This would all be over SSL.

*Similarly, I could pass the data as POST parameters.

*Web App A writes a cookie, Web App B reads the data from the cookie. (This seems like more of a security concern than passing as GET or POST parameters)

*I could share an object via JNDI to use for prepopulation. Then I guess I could pass a unique ID on the query string which Web App B could use to pick up the object. This seems like it might be "overkill" and I'm not sure how this would work.

*I could store the data in a database against a unique ID, pass the unique ID on the query string, then pick it up in Web App B from that same database. Again, this might be "overkill".

Any thoughts? Or is there a better solution that I don't have listed?

A: In my opinion the GET params are the simplest way to do it, and I don't think there are important security implications.

A: You should assume anything that web app A puts in the redirect can be read/stolen/modified/spoofed before it gets to web app B (unless you are using SSL on both app A and B). If this isn't a problem then putting the params on the redirect URL should do you fine.
A secure way would be for app A to generate a unique ID (non guessable and short lived) and to store the info against this ID. The ID is passed with the request to app B. Server B then accesses the data from server A using the ID in a private secure way, for example be calling a web service on server A that is not publically accessible.


Q: How to query recursive MongoDB Document [File System of files and folders] I am developing an application that uses MongoDB (typegoose) to store file system-like (recursive) documents composed of files and folders. However, I do not know how to query such a schema. For querying, I am provided the following.

*

*users _id

*the array of folder names in order ex. ['root', 'nestedFolder1', 'nestedFolder2', 'etc...']

*_id of the last folder chosen

The schema is as follows

import { Types } from "mongoose";
interface File {
    _id: Types.ObjectId;
    fileName: string;
    isDir: false;
    content: string;
    title: string;
    description: string;
}

interface FileSystem {
    _id: Types.ObjectId;
    folderName: string;
    isDir: true;
    files: File[] | [];
    folders: FileSystem[] | [];
}

interface Project {
    _id: Types.ObjectId;
    projectName: string;
    fileSystem: FileSystem;
}
interface User {
    _id: Types.ObjectId;
    projects: Project[];
}

Update:
Here's a replit for reference
https://replit.com/@alphacoma18/mongodb-recursive-schema#server.ts

A: 1- Most trivial query, get all FileSystem Documents:
const fileSystems = await FileSystem.find({
    // Empty Object means no condition thus give me all your data
});

2- Using the $eq operator to match documents with a certain value
const fileSystems = await FileSystem.find({

        isDir: true,
        folderName: { $eq: 'root' }
    });

3- Using the $in operator to match a specific field with an array of possible values.
const fileSystems = await FileSystem.find({
    isDir: true,
    folderName: { $in: ['root', 'nestedFolder1', 'nestedFolder2'] }
});

4- Using the $and operator to specify multiple conditions
const fileSystems = await FileSystem.find({
    $and: [
        { isDir: true },
        { folderName: { $in: ['root', 'nestedFolder1', 'nestedFolder2'] } }
    ]
});

5- Retrieve all documents that are directories and are not empty.
const fileSystems = await FileSystem.find({
    isDir: true,
    $or: [
        { files: { $exists: true, $ne: [] } },
        { folders: { $exists: true, $ne: [] } }
    ]
});

6- All directories that have a folder name that starts with the letter 'n'
const fileSystems = await FileSystem.find({
    isDir: true,
    folderName: { $regex: '^n' }
});

Now the tougher queries:
1- count the total number of documents
const count = await FileSystem.aggregate([
    { $count: 'total' }
]);

2- count the total number of documents that are directories
const count = await FileSystem.aggregate([
    { $match: { isDir: true } },
    { $count: 'total' }
]);

3- Get 'foldername' and 'filename; of all documents that are files.
const fileSystems = await FileSystem.aggregate([
    { $match: { isDir: false } },
    { $project: { folderName: 1, fileName: 1 } }
]);

4-  Retrieve the total number of files (isDir: false) in each directory (isDir: true)
const fileCounts = await FileSystem.aggregate([
    { $match: { isDir: true } },
    {
        $project: {
            folderName: 1,
            fileCount: {
                $size: {
                    $filter: {
                        input: '$files',
                        as: 'file',
                        cond: { $eq: ['$$file.isDir', false] }
                    }
                }
            }
        }
    }
]);

5- Recursive structure querying:
The FileSystem interface is recursive, because it has both an array of files and an array of folders, which are both of type File[] and FileSystem[].
To query this recursive schema, you can use the $lookup operator in an aggregate pipeline, to make a left join between FileSystem and itself, based on some criteria.
//Retrieve All Documents from FileSystem and their child documents
const fileSystems = await FileSystem.aggregate([
    {
        $lookup: {
            from: 'FileSystem',
            localField: '_id',
            foreignField: 'parentId',
            as: 'children'
        }
    }
]);

//Use the match operator in the pipeline to filter the results:
const fileSystems = await FileSystem.aggregate([
    {
        $lookup: {
            from: 'FileSystem',
            localField: '_id',
            foreignField: 'parentId',
            as: 'children'
        }
    },
    { $match: { isDir: true } }
]);


Q: VS2008 and ClearCase : opening solution requests a checkout for no reason I have a little issue that's causing my automated builds to fall over.
When we open a solution recently converted from VS2005 to VS2008 VS through ClearCase requests that we checkout the solution file.
If we allow it then it makes no changes anyway and by default ClearCase doesn't like checkins without changes.  So we undo the checkout - and from then on VS is happy, it was able to write the .suo file.
If we un-read protect the solution file, start up VS2008 it creates the .suo file ok, if we then un-hijack the .sln file (no changes anyway so VS2008 doesn't notice) and fire up VS2008 again it's fine - doesn't ask for a checkout.
In my build script I delete all view private files from the view and then do an update with forced un-hijack of controlled files.  And then we build the deployment projects (and thus all dependencies), and as the .suo file is being deleted it falls into the checkout .sln file behaviour every time.
And on the build server there isn't anybody around to see the dialog asking for a checkout, the build hangs.
I could change (aka bodge) the build script to not delete the .suo file, but I would rather not do this.
edit:  clarification - the .suo file is NOT checked into ClearClase - it is a view private file that is being created by VS2008, however to create this file it wants to check out the .sln file for not real reason.
Further Edit:
I have found the solution to this - I've disabled the integration as per my follow up post on this thread.

A: Okay, I found the solution to the problem and it was quite simple in reality.
I disabled the Visual Studio ClearCase integration on the build server.
VS is being used as we need to build deployment projects and so we call devenv to do this for us.  However we are only using it as a build engine, there is never a need for the build engine to know how to modify the source items as they will all have just come from ClearCase.  The only items we allow the build server to modify are the assembly file version number attributes in the AssemblyInfo files, but we do that in the NAnt and not in Visual Studio.
So, disable the functionality and problem goes away.  Probably not the solution for everybody but on a build server it was the way forward.

A: This troubleshooting item, got me to this fix pack which has solved the issue in our development environment. We're still using VS2005, but I would expect that it's the same issue as what was going wrong in VS2008.

A: This seems to be normal for VS2008, it checks out the .sln file when opening a solution. I dont like it either.
Your problem however is the fact that the .suo file is also checked in. This file should not be placed under source control. It is like the proj.user files. I suspect suo stands for Solution User Options.

A: You could:

*

*update your script in order to hijack the sln file in your snapshot view just after your "cleartool update -force -overwrite".

*or, to avoid the sln to be checked-out, you could try and keep the .suo file checked-in,

If the above suggestion works, then here is a couple of reason why one would want to keep this file under version control:

*

*Since the .suo file is disposable (VS2008 just creates a new one if it does not exist), having under source control might been seen as a way to avoid that creation (hence avoiding the ClearCase plugin detecting it and trying to "add to source control" it or checking it out).

*Another advantage to having .suo file under version control (but not updated through any further checkout/checkin) is when you are comparing your checked out project with another checked out version of the same project downloaded elsewhere: that file will always be identical, as opposed to systematically different (since if is a binary file, and any new version of a binary file would register itself as different)


Q: I can't connect to the webserver I have a WordPress instance running locally on my mac with XAMPP.
It's working fine but when I want to install something I have to login with my ftp username and password.
I've tried to use my username and password which I use to logon to WordPress. Also I used my tried my database credentials. I really have no idea which other logon credentials I should have.

A: FTP credentials do not refer to your login details, it refers to credentials for File Transfer Protocol, it is given to you when you purchase a web hosting service or setup one yourself on your machine.
An alternative to this would be to download the plugin or theme you want and paste it to your /{website folder}/wp-content/themes or /{website folder}/wp-content/plugins

A: Try to

*

*Right click to htdocs folder, choose Get info

*Click the lock icon, type your MacOS account password to unlock below options.

*Allow everyone Read & Write permission, the click the cog icon and choose Apply to enclosed items..., this should apply all r+w permission to sub-folders.

*Done


Q: Trouble connecting to laravel api with jwt while hosting on 000webhost i am trying to host a project on 000webhost free tier and i am stuck on this problem. I have searched everywhere i could and still no solution. The project is a laravel 5.7 api using jwt for authentication and works fine on localhost. i uploaded everything on 000webhost without a problem and set up the database with this.
I know it is up and working to a certain degree as i can access the index.php and it shows up.(It is just a page showing 'hello' on it).
My problem is when i try to make a call to the '/api/showAuthUser' endpoint using postman I get this error.
Argument 3 passed to Lcobucci\JWT\Signer\Hmac::doVerify() must be an instance of Lcobucci\JWT\Signer\Key, null given, called in /storage/ssd1/450/8968450/vendor/lcobucci/jwt/src/Signer/BaseSigner.php on line 42

When i try to make a call to '/api/login' using postman i get this error.
Argument 2 passed to Lcobucci\JWT\Signer\Hmac::createHash() must be an instance of Lcobucci\JWT\Signer\Key, null given, called in /storage/ssd1/450/8968450/vendor/lcobucci/jwt/src/Signer/BaseSigner.php on line 34

I am sure I have the database connected correctly and I have the jwt secret in the .env file. I have tried every solution I could find online with no joy. The only one i have not tried was running php artisan jwt:secret as I can not run commands in 000webhost or I just don't know how to do this.
Sorry if this is not enough information but I am new to api's and this is my last hope. Thank you.

A: You have a jwt.php file in your config folder (config/jwt.php). In there please replace the JWT_SECRET with your generated jwt secret key on your .env file
In jwt.php file
'secret' => env('JWT_SECRET', 'PLACE YOUR JWT KEY HERE'),

Hope this will solve your problem


Q: How to create a link without .lnk extension? If I have a file named "C\Test\mypic.jpg", can I create a shortcut with path "C\Test2\mypic.jpg"? Windows always seems to add a ".lnk" suffix, which is unwanted in my case.

A: Link in this case can mean several things but we can unpack all the possible scenarios:

*

*A shortcut (.lnk file). These files must have the .lnk extension because the file extension is how Windows decides which handler to invoke when you double-click/execute the file. If you create a shortcut to a jpg file the real name can be link.jpg.lnk but the user will see the name as link.jpg in Explorer because .lnk is a special extension that is hidden.

*A symbolic link (symlink). These are links on the filesystem level and can have any extension. mklink "c:\mylink.jpg" "c:\file.jpg"

*A hardlink. This is another name for the same file (alias), it does not create a shortcut. mklink /H "c:\anothername.jpg" "c:\file.jpg"


Q: How to convert this Oracle query into HSQL query I am trying to convert this Oracle query into HSQL, but i have difficulties.
select a.t_user_id, listagg(et.event_type_name,', ') within group (order by a.t_user_id )
from t_agency a inner join t_agency_event_type aet on a.t_user_id = aet.agency_id
                inner join t_event_type et on aet.t_event_type_id=et.id
group by a.t_user_id;

Can anybody help me? Thanks in advance!
ADDED:
My HSQL query is like this:
Query queryEventTypes = em.createQuery("select agency, GROUP_CONCAT(et.eventTypeName SEPARATOR ', ') as  eventTypeName " +
                        "from TAgency agency join agency.tAgencyEventTypes eat " +
                        "join eat.tEventType et " +
                        "group by hiredAgency.tUserId, hiredAgency.address, hiredAgency.city, hiredAgency.information, "
                        + "hiredAgency.website");

But it gives me the error:
unexpected token: SEPARATOR near line 1, column 46 [select agency, GROUP_CONCAT(et.eventTypeName SEPARATOR ', ')
                    as  eventTypeName from bg.fmi.master.thesis.model.TAgency agency join agency.tAgencyEventTypes eat join eat.tEventType et
                    group by hiredAgency.tUserId, hiredAgency.address, hiredAgency.city, hiredAgency.information, hiredAgency.website]

A: Try the GROUP_CONCAT function supported by HSQLDB version 2.3.x and later. The HSQLDB syntax is different and documented here.
http://hsqldb.org/doc/2.0/guide/dataaccess-chapt.html#dac_aggregate_funcs
The example given in the Guide shows how you specify the grouping and ordering of the results;
SELECT LASTNAME, GROUP_CONCAT(DISTINCT FIRSTNAME ORDER BY FIRSTNAME DESC SEPARATOR ' * ') FROM Customer  GROUP BY LASTNAME


Q: Why does my then() never get invoked whenever I add a stream to my stream controller? I have a bloc which has a stream controller and in the constructor of the bloc I add the stream to the controller. I wait until the stream is added and then I add a listener to it. But the then() never get's invoked. I'm sure that GeoLocator() code works because I had it in a stateful widget before and that worked like a charm but I decided to move the business logic to a bloc.
import 'dart:async';

import 'package:geolocator/geolocator.dart';

class LocationBloc {
  final Geolocator _geolocator = Geolocator();
  final LocationOptions _locationOptions = LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 10);
  StreamController<Position> _positionStreamController = StreamController<Position>();
  double _speed = 0;

  double get speed => _speed;

  LocationBloc() {
    print('it gets here');
    final Stream<Position> positionStream = _geolocator.getPositionStream(_locationOptions);
    print('and here');
    _positionStreamController.addStream(positionStream).then((value) {
      print('it never gets here');
      print(value);
      _positionStreamController.stream.listen((Position position) {
        this._speed = position == null ? 0 : position.speed;
      });
    });
  }

  void dispose() {
    print('dispose location stream');
    _positionStreamController.close();
    _speed = 0;
  }
}

When I dispose of he bloc provider when the widget get's disposed and call the dispose in the bloc it throws the following error
Bad state: Cannot add event while adding a stream

The stateless widget
class DigitalSpeedMeter extends StatelessWidget {

  static Widget create(BuildContext context) {
    return Provider(
      create: (_) => LocationBloc(),
      child: DigitalSpeedMeter(),
      dispose: (BuildContext context, LocationBloc bloc) => bloc.dispose(),
    );
  }

A: I ended up using this
import 'dart:async';

import 'package:geolocator/geolocator.dart';

class LocationBloc {
  final Geolocator _geolocator = Geolocator();
  final LocationOptions _locationOptions = LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 10);
  StreamController<double> _streamController = StreamController<double>();
  Stream<double> get stream => _streamController.stream;

  LocationBloc() {
    _streamController.addStream(_geolocator.getPositionStream(_locationOptions).map((position) => position.speed ?? 0.0));
  }

  void dispose() {
    _streamController.close();
  }
}

With a stream builder widget.


Q: Ionic2 cloud google login with asp.net web api I am building an ionic2 app and implemented google login flow. Which works fine and i get the token after a success full. How do i use this token to authenticate my project web api Endpoint  ( using Oauth for generating the tokens). I am using default asp.net web api project template


Q: How to establish a boost asio tcp socket over http proxy? I am trying to establish a TCP socket over http proxy. My current understand is,

*

*create tcp socket connecting to http_proxy_ip:http_proxy_port

*Via the socket send: CONNECT http://my.server.com:80 HTTP/1.0\r\n\r\n

My question is : is there need to wrap each tcp packet with some http header or use it like normal TCP sokcet(which is not over http proxy)?
Is there any equivalent for boost::asio TCP connection through http proxy
Thanks.


Q: Android app to create .txt file I'm trying to create an app where a user selects a few checkboxes, then when they hit submit it creates a .txt file with a sentence in it for every checkbox selected.
I have had one successful build of this, and it created the file properly, but I need it saved to an accessible file location so that it can be attached to an email.  I don't really care where it saves to, as long as it is accessible.
The following code causes a crash when run in Android Virtual Device and my Galaxy 2.  The application is a proof of concept for a later app.   Thank you.
        @Override
        public void onClick(View v)
        {
             String nochartOutput = " ";
             if (sitting.isChecked())
                 nochartOutput += "The patient was sitting in a chair. ";
             if (breathing.isChecked())
                 nochartOutput += "The patient was breathing. ";
             if (alert.isChecked())
                 nochartOutput += "The patient was alert. ";

             FileOutputStream fOut = null;
             File sdDir = Environment.getExternalStorageDirectory();
             try {
                 fOut = openFileOutput(sdDir + "/AutoWriter/samplefile.txt",MODE_WORLD_READABLE);
             } catch (FileNotFoundException e) {
                 e.printStackTrace();
             }
             OutputStreamWriter osw = new OutputStreamWriter(fOut);
             try {
                 osw.write(nochartOutput);

                 osw.flush();
                 osw.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
        }

03-04 18:39:53.604: W/dalvikvm(10453): threadid=1: thread exiting with uncaught exception (group=0x40c211f8)
03-04 18:39:53.624: E/AndroidRuntime(10453): FATAL EXCEPTION: main
03-04 18:39:53.624: E/AndroidRuntime(10453): java.lang.IllegalArgumentException: File /mnt/sdcard/samplefile.txt contains a path separator
03-04 18:39:53.624: E/AndroidRuntime(10453):   at android.app.ContextImpl.makeFilename(ContextImpl.java:1703)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at android.app.ContextImpl.openFileOutput(ContextImpl.java:723)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:165)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at com.example.com.dresdor.autowriter.MainActivity$1.onClick(MainActivity.java:48)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at android.view.View.performClick(View.java:3620)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at android.view.View$PerformClick.run(View.java:14292)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at android.os.Handler.handleCallback(Handler.java:605)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at android.os.Handler.dispatchMessage(Handler.java:92)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at android.os.Looper.loop(Looper.java:137)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at android.app.ActivityThread.main(ActivityThread.java:4507)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at java.lang.reflect.Method.invokeNative(Native Method)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at java.lang.reflect.Method.invoke(Method.java:511)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
03-04 18:39:53.624: E/AndroidRuntime(10453):   at dalvik.system.NativeStart.main(Native Method)

A: Your existing code is a mashup of writing to internal storage and external storage.  The line
fOut = openFileOutput(sdDir + "/AutoWriter/samplefile.txt",MODE_WORLD_READABLE);

attempts to create a file in the app's private data directory, and you can only pass file names to this method, not a deeper path.  That's where the crash is coming from, but it's not what you want.
You started to create a path to external storage, but never actually used it.  To write the file to that location on the external SD card, modify your code like so:
FileOutputStream fOut = null;
//Since you are creating a subdirectory, you need to make sure it's there first
File directory = new File(Environment.getExternalStorageDirectory(), "AutoWriter");
if (!directory.exists()) {
    directory.mkdirs();
}

try {
    //Create the stream pointing at the file location
    fOut = new FileOutputStream(new File(directory, "samplefile.txt"));
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(fOut);

//...etc...

Using the SD card allows the file to be accessed by anyone.

A: openFileOutput() writes file in the internal memory and not sd card. So change
fOut = openFileOutput(sdDir + "/AutoWriter/samplefile.txt",MODE_WORLD_READABLE);

to
fOut = openFileOutput("samplefile.txt", MODE_WORLD_READABLE);

Also the file name can not contain path separators. See Android Developers Reference
public abstract FileOutputStream openFileOutput (String name, int mode)

Open a private file associated with this Context's application package
  for writing. Creates the file if it doesn't already exist.
Parameters name   The name of the file to open; can not contain path
  separators.

The file can be then be accessed like this.
FileInputStream fis = openFileInput("samplefile.txt");

Note:
For files which are huge in size, it's better to save it in sd card. Here is the code snippet.
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
    FileOutputStream fos = null;
    try {
        File rootPath = new File(Environment.getExternalStorageDirectory(), "AutoWriter");
        if (!rootPath.exists())
            rootPath.mkdirs();

        File file = new File(rootPath, "samplefile.txt");
        fos = new FileOutputStream(file);

        // ... more lines of code to write to the output stream

    } catch (FileNotFoundException e) {
        Toast.makeText(this, "Unable to write file on external storage", Toast.LENGTH_LONG).show();
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {}
        }
    }
}


Q: How to make a rich tooltip with a HTML form in it I have a paragraph of text with a link in it. I want to make a rich tool tip with a title on the top and a field to collect email addresses appear on hovering the link. What approach should I take?
I have looked into tool tip libraries but none seem to have form support. Please find the code below
The content in which the link is present:

Pellentesque habitant Link to show tooltip morbi senectus
tristique senectus et netus et malesuada pellentesque habitant senectus
fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies
eget,  tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.
Aenean ultricies mi vitae est. Mauris placerat eleifend leo.

Tool tip content:

Tooltip title

Vestibulum tortor quam, feugiat vitae, ultricies
  eget,  tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.
  Aenean ultricies mi vitae est. Mauris placerat eleifend leo.

  <form>
    <input type="email" placeholder="john@doe.com" />
    <input type="submit" value="subscribe" />
  </form>
  This is our branding message

Now the effect I want to achieve is when I hover the link in the content the tooltip content should appear in a styled div. How should I do it?

A: Check this snippet
Updated

$("a").bind("mousemove", function(event) {
    $("div.tooltip").css({
        top: event.pageY + 10 + "px",
        left: event.pageX + 10 + "px"
    }).show();
})
$('.close').bind('click', function(){
  $("div.tooltip").fadeOut();
});
body{
    font-family:arial;
    font-size:12px;
}
.tooltip {
    width:350px;
    position:absolute;
    display:none;
    z-index:1000;
    background-color:#CB5757;
    color:white;
    border: 1px solid #AB4141;
    padding:15px 20px;
    box-shadow: 0px 3px 2px #8D8D8D;
    border-radius: 6px;
}
.close{
  right: 15px;
  position: absolute;
  background: #fff;
  color: #555;
  width: 20px;
  height: 20px;
  text-align: center;
  line-height: 20px;
  border-radius: 50%;
  font-size: 10px;
  cursor:pointer;
}

Pellentesque habitant Link to show tooltip morbi senectus
    tristique senectus et netus et malesuada pellentesque habitant senectus
    fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies
    eget,  tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.
    Aenean ultricies mi vitae est. Mauris placerat eleifend leo.

    X

Tooltip title

Vestibulum tortor quam, feugiat vitae, ultricies
        eget,  tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.
        Aenean ultricies mi vitae est. Mauris placerat eleifend leo.

    <form>
        <input type="email" placeholder="john@doe.com" />
        <input type="submit" value="subscribe" />
    </form>
    This is our branding message

A: Follow these steps:

*

*Add the link and the tooltip div inside a new div.

*Set tooltip div property to be visibility: hidden;

*and on hover set the property of this tooltip to be visible.

like:
HTML:

 Link to show tooltip

 ......

CSS:
.link {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}

.link .tooltip {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;

position: absolute;
z-index: 1;
}

.link:hover .tooltip {
visibility: invisible;
}

A: You could try to display yout tooltip element with the tilde selector on link hover:
.tooltip {
  display: none;
}

a:hover ~ .tooltip{
  display: block;
}

And then place your tooltip after the link element.

  blabla
  hover me
  tooltip content
  blabla

Here a pen where it works


Q: Facebook offline conversions without customer data I need to send offline conversions to facebook (https://developers.facebook.com/docs/marketing-api/offline-conversions) but often I don't know the email or other user data.
Is it possible to use data such as the Google Analytics client ID as an identifier?
I tried to send in the facebook pixel an additional field extern_id which is set to the analytics client id.
I send this identifier to Facebook with the offline API, unfortunately I don't find these conversions in facebook ads...


Q: Finding minimum sum of graph edge weight? I have been given a undirected weighted graph, witch represents the road with junctions. The task is in every cycle, which begins and ends in a same vertex choose the edge with the lowest weight and calculate the sum of all these edges in graph.
Idea is to use Prim algorithm, but there is a chance that some cycles doesn't include edge from MST.
How to solve this problem, and how to modify Prim's algorithm?


Q: conditionally set both fill and color in geom_point ggplot R what is wrong my code that does not change the filling color?
cars %>%
  ggplot() +
  geom_point(aes(x = speed, y = dist,
                 color= I(ifelse(dist >50, 'red', 'black')),
                 fill= I(ifelse(dist >50, 'pink', 'gray'))

                 )

             )

A: You need to have a point shape that allows both fill and colour.
library(ggplot2)
cars %>%
    ggplot() +
    geom_point(
        aes(x = speed, y = dist,
            color= I(ifelse(dist >50, 'red', 'black')),
            fill= I(ifelse(dist >50, 'pink', 'gray')),
        ),
        shape = 21,
        size = 4 # changing size so it's easy to visualise
    )

To check point shapes that allow both fill and colour use help(points) and refer to the 'pch' values section


Q: .Net AES encrypt mismatch after decrypt on Java I have to send the AES encrypted json as content to web server. But after decryption, the content has extra trash symbols appeared at the beggining of the line.
My test method creates the object that is serialized and being send:
[TestMethod]
public void SendModeChangeWorksAsExpected()
{
    var snpashot2Send = new ModeChangedReport
    {

        ControlWorkMode = ModeEnumeration.Stopped,
        //Controls
        ControlDate = DateTime.Now,
        IsSent = false,
        SentTime = null,
        ReportType = ReportType.ModeChanged,

        Line = new Line
        {
            AgencyId = "a799eb4f-86da-4af1-a221-9ed8b741b5ce"
        }
    };

    //Создаём шифрованное значение
    var encryptedString = _agencyReportEncriptingTranslator.ConvertModeChange2CypheredString(snpashot2Send);
    //Отправляем в Агентство и получаем результат
    var value = _agencyClient.SendModeChangeReport(encryptedString);
}

Here are the serialization and encrypt methods:
public string ConvertModeChange2CypheredString(ModeChangedReport report)
{
    if (report == null) throw new ArgumentNullException(nameof(report));

    //obj to json
    var json = new ModeChangedReportJson
    {
        LineId = report.Line.AgencyId,
        Mode = CreateModeFromIktToUzbekistan(report.ControlWorkMode),
        ActionDate = ConvertDateToAgencyString(report.ControlDate)
    };

    //Serialization
    var retString = _agencyJsonSerializer.SerializeReport2Json(json);

    //Шифруем сериализованный json
    var cypheredValue = _encryptionService.EncryptString(retString);
    return cypheredValue;
}

Encrypt method:
public string EncryptString(string plaintext)
{
    var plainTextBytes = Encoding.UTF8.GetBytes(plaintext);
    var cypheredTextBytes = Encrypt(plainTextBytes);
    var converted2Base64Value = Convert.ToBase64String(cypheredTextBytes);
    return converted2Base64Value;
}

private byte[] Encrypt(byte[] bytes)
{
    #region Args Validation

    if (bytes == null || bytes.Length < 1)
    {
        throw new ArgumentException("Invalid bytes to encrypt");
    }

    if (_key == null || _key.Length < 1)
    {
        throw new InvalidOperationException("Invalid encryption key");
    }

    #endregion

    byte[] encrypted;

    try
    {
        using (AesManaged aes = new AesManaged())
        {
            aes.Key = _key;
            aes.IV = _iv;
            aes.Padding = PaddingMode.PKCS7;
            aes.Mode = CipherMode.CBC;

            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, _iv);
            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(aes.IV, 0, aes.IV.Length);
                using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                {
                    cs.Write(bytes, 0, bytes.Length);
                }
                encrypted = ms.ToArray();
            }
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }

    return encrypted;
}

Http client send method:
public bool SendModeChangeReport(string cypheredValue)
{
    var token = GetAccessToken();

    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AuthorizationToken);
        client.DefaultRequestHeaders.Add("DEVICE_ID", _agencyAppSettings.DeviceId);

        var content2Post = new StringContent(cypheredValue, Encoding.UTF8, "application/json");
        using (var response = client.PostAsync(_agencyAppSettings.SendModeChangedReportUrl, content2Post).Result)
        {
            string tokenResponse = null;
            try
            {
                tokenResponse = response.Content.ReadAsStringAsync().Result;
                response.EnsureSuccessStatusCode();
                return true;
            }
            catch (Exception ex)
            {
                _eventLogManager.LogError("При попытке отправить отчёт о смене режима, произошла ошибка: "
                    + $"Код: {response.StatusCode}. Контент: {tokenResponse}. Ошибка: {ex.Message}.");
                return false;
            }
        }
    }
}

After decryption on receiving server, the string grows with extra trash characters at the beginning, like G���h R��EQ�Z {"lineid":"a799eb4f-86da-4af1-a221-9ed8b741b5ce"...
The decrypt method of the server (Java):

I think that the problem is the padding difference: PKCS7 on my side, and PKCS5 on server.
How can I solve this problem with the extra chars appear on server side?

A: Those aren't trash characters, they're the Unicode Replacement Character returned when bytes are decoded into text using the wrong character set.
The very fact you got readable text means decrypting succeeded. It's decoding the bytes into text that failed.
The bug is in the Java code. It's using the String(byte[]) which, according to the docs:

Constructs a new String by decoding the specified array of bytes using the platform's default charset.

That's obviously not UTF8. The String(byte[] bytes,Charset charset) or String(byte[] bytes,String charsetName) constructors should be used instead, passing the correct character set, eg :
byte[] decryptedBytes = cipher.doFinal(....);
return new String(decryptedBytes, StandardCharsets.UTF_8);

The hacky alternative is to change the remote server's default character set to UTF8.


Q: Break the loop into half, if the loop count is even I want to break the loop into half of the total loop count. If the total loop count is odd, I would like to remove the last array item in order to make the total loop count even and add the deleted item to the second half.
Here is the code structure to demonstrate the loop-
<?php
$faqs = new WP_Query( array (
    'post_type' => 'faq'
));
?>

      <?php
      while ($faqs->have_posts()) : $faqs->the_post();
          the_content();
      endwhile();
      ?>

      <?php
      while ($faqs->have_posts()) : $faqs->the_post();
          the_content();
      endwhile();
      ?>

I don't know how to control the loop based on my mentioned conditions. That's why I couldn't able to try loop controlling.

A: In a single loop. Hopefully, it'll work. Couldn't test so let me if you face any situation.
<?php
$faqs = new WP_Query([
    'post_type' => 'faq',
    'post_status' => 'publish',
]);
$half = intval($faqs->post_count / 2);
$counter = 0;
?>

    <?php while ($faqs->have_posts()) : $faqs->the_post(); ?>
        <?php if ( $counter === $half ) : ?>

        <?php endif; ?>

        <?php the_content(); ?>
    <?php ++$counter; endwhile; ?>

A: try it like this
<?php
$faqs = new WP_Query( array (
    'post_type' => 'faq'
));
?>

      <?php
      $i=0;
      while ($faqs->have_posts() && $i < $faqs->post_count / 2) : $faqs->the_post(); $i++
          the_content();
      endwhile();
      ?>

      <?php
      while ($faqs->have_posts()) : $faqs->the_post();
          the_content();
      endwhile();
      ?>

https://wordpress.stackexchange.com/questions/27116/counting-the-posts-of-a-custom-wordpress-loop-wp-query


Q: MySQL and PHP application fails - Error 2002 I've written a php-based site on my local machine and I'm trying to run it using the Apache Web Server in XAMPP and a mySQL database, which is on my local machine, external to XAMPP. When I go to the page where it should be, however, I get the following error:
Sorry, a problem occurred. Please try later.SQLSTATE[HY000] [2002] No such file or directory
I've seen a lot of people saying this points to php.ini not being able to access mysql.sock, but all of the changes haven't worked for me. I don't have any mysql.sock files, but I do have mysqld.sock files, and I've put the paths to them in php.ini at all the points where it asks for them. I haven't seen anyone talking about mysqld.sock files and whether or not it's an issue, so any help would be valuable.
Here's my config.php, if that's valuable:
ini_set( "display_errors", true );
date_default_timezone_set( "Europe/London" );  // http://www.php.net/manual/en/timezones.php
define( "DB_DSN", "mysql:host=localhost;dbname=dog_site" );
define( "DB_USERNAME", "root" );
define( "DB_PASSWORD", "***" );
define( "CLASS_PATH", "classes" );
define( "TEMPLATE_PATH", "templates" );
define( "HOMEPAGE_NUM_POSTS", 5 );
define( "ADMIN_USERNAME", "admin" );
define( "ADMIN_PASSWORD", "***" );
require( CLASS_PATH . "/User.php" );
require( CLASS_PATH . "/Litter.php" );
require( CLASS_PATH . "/Post.php" );
require( CLASS_PATH . "/PostLikes.php" );
require( CLASS_PATH . "/LitterLikes.php" );
require( CLASS_PATH . "/PostComments.php" );
require( CLASS_PATH . "/LitterPhotos.php" );
require( CLASS_PATH . "/PostPhotos.php" );

function handleException( $exception ) {
  echo "Sorry, a problem occurred. Please try later.";
  echo $exception->getMessage();
  error_log( $exception->getMessage() );
}

set_exception_handler( 'handleException' );
?>```


Q: How to configure Maven to build two versions of an artifact, each one for a different target JRE I have a maven module that I need to use in the J2ME client and in the EJB server. In the client I need to compile it for target 1.1 and in the server for target 1.6 .
I also need to deploy the 1.6 version to a Nexus repository, so the members working on the server project can include this dependency without needing to download the source code.
I've read at http://java.dzone.com/articles/maven-profile-best-practices that using profiles is not the best way of doing this, but the author didn't say what's the best way.
Here is my pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>proj-parent</artifactId>
        <groupId>br.com.comp.proj</groupId>
        <version>0.0.4-SNAPSHOT</version>
    </parent>

    <artifactId>proj-cryptolib</artifactId>
    <name>proj - Cryto Lib</name>

    <dependencies>
        <dependency>
            <groupId>br.com.comp</groupId>
            <artifactId>comp-proj-mobile-messages</artifactId>
            <version>0.0.2-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <build>

        <plugins>

            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.3</source>
                    <target>1.1</target>
                    <fork>true</fork>
                </configuration>
            </plugin>

        </plugins>

    </build>

</project>

A: As Haylem suggests thought you'll need to do it in two steps, one for the compile and one for the jars.
For the compiler
<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.5</version>
    <executions>
      <execution>
        <configuration>
          <source>1.3</source>
          <target>1.5</target>
          <fork>true</fork>
          <outputDirectory>${project.build.outputDirectory}_jdk5</outputDirectory>
        </configuration>
      </execution>
      <execution>
        <configuration>
          <source>1.3</source>
          <target>1.6</target>
          <fork>true</fork>
          <outputDirectory>${project.build.outputDirectory}_jdk6</outputDirectory>
        </configuration>
      </execution>
    </executions>
 </plugin>

And then for the jar plugin
<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>2.3.1</version>
        <executions>
          <execution>
            <goals>
              <goal>jar</goal>
            </goals>
            <configuration>
              <classesDirectory>${project.build.outputDirectory}_jdk5</classesDirectory>
              <classifier>jdk5</classifier>
            </configuration>
          </execution>
          <execution>
            <goals>
              <goal>jar</goal>
            </goals>
            <configuration>
              <classesDirectory>${project.build.outputDirectory}_jdk6</classesDirectory>
              <classifier>jdk6</classifier>
            </configuration>
          </execution>
        </executions>
      </plugin>

you can then refer to the required jar by adding a <classifier> element to your dependency. e.g.
<dependency>
    <groupId>br.com.comp.proj</groupId>
    <artifactId>proj-cryptolib</artifactId>
    <version>0.0.4-SNAPSHOT</version>
    <classifier>jdk5</classifier>
</dependency>

A: You can configure this via the Maven compiler plugin.
Take a look at the Maven compiler plugin documentation.
You could enable this via different profiles for instance.
If you only want to have different target versions you could simply use a variable target.  Something like this:
<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
        <source>1.3</source>
        <target>${TARGET_VERSION}</target>
        <fork>true</fork>
    </configuration>
 </plugin>

A: To complement my comment to wjans' answer, as you requested more details.
The following would have the compiler plugin executed twice to produce two different sets of classfiles, identified by what is called a classifier (basically, a marker for Maven to know what you refer to when a single project can produce multiple artifacts).
Roughly, something like:
<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.5</version>
    <executions>
      <execution>
        <configuration>
          <source>1.3</source>
          <target>1.5</target>
          <fork>true</fork>
          <classifier>jdk5</classifier>
        </configuration>
      </execution>
      <execution>
        <configuration>
          <source>1.3</source>
          <target>1.6</target>
          <fork>true</fork>
          <classifier>jdk6</classifier>
        </configuration>
      </execution>
    </executions>
 </plugin>

Note that people sometimes frown on using classifiers, as they on using profiles, as they can possibly mean that your project should be scinded in multiple projects or that you are harming your build's portability.


Q: A better way to do this htaccess rewrite rule I have this rewrite rule that checks for a country code in the url and fetches content accordingly.
Problem is there are 60+ countries. Can this be done in a different way rather than entering codes of all the countries in the rule?
RewriteRule ^/?(us|uk|ca)/p([0-9]+)/?$

Note the (us|uk|ca) part? A whole lot more need to go in there. Any better way to do this?

A: RewriteRule ^/?([a-z][a-z])/p([0-9]+)/?$

But it doesn't check if the language is a valid one (and I don't know if you expect language codes with more than 2 characters if such a thing exists)
EDIT : this regexp is shorter :
RewriteRule ^([a-z]{2})/p\d+/?$

The first slash is useless and \d+ means one or more digits, see @TerryE's comment


Q: mysql query that has join and counts I need help getting the top 5 results and their counts from columns from two different tables in a mysql database joined together.
table1 cols
-------
id, country, timestamp

table2 cols
--------
id, table1_id, reason

The results id like to get are the top 5 countries and their number of times found between two timestamps, and the top 5 reasons and their counts for all the rows used to generate the first count. There is a one to many relationship between table1 and table2. This is stumping me and I appreciate any insight you could give me.

A: It's not entirely clear what resultset you want to return.
This may be of some help to you:
SELECT t.country
     , COUNT(DISTINCT t.id) AS count_table1_rows
     , COUNT(r.id)          AS count_table2_rows
     , COUNT(*)             AS count_total_rows
  FROM table1 t
  LEFT
  JOIN table2 r
    ON r.table1_id = t.id
 WHERE t.timestamp >= NOW() - INTERVAL 7 DAY
   AND t.timestamp  < NOW()
 GROUP BY t.country
 ORDER BY COUNT(DISTINCT t.id) DESC
 LIMIT 5

That will return a maximum of 5 rows, one row per country, with counts of rows in table1, counts of rows found in table2, and a count of the total rows returned.
The LEFT keyword specifies an "outer" join operation, such that rows from table1 are returned even if there are no matching rows found in table2.
To get the count for each "reason", associated with each country, you could do something like this:
SELECT t.country
     , COUNT(DISTINCT t.id) AS count_table1_rows
  FROM table1 t
  LEFT
  JOIN ( SELECT s.country
              , r.reason
              , COUNT(*) AS cnt_r
           FROM table1 s
           JOIN table2 r
             ON s.table1_id = t.id
          WHERE s.timestamp >= NOW() - INTERVAL 7 DAY
            AND s.timestamp  < NOW()
          GROUP
             BY s.country
              , r.reason
       ) u
    ON u.country = t.country
 WHERE t.timestamp >= NOW() - INTERVAL 7 DAY
   AND t.timestamp  < NOW()
 GROUP
    BY t.country
     , u.reason
 ORDER
    BY COUNT(DISTINCT t.id) DESC
     , t.country DESC
     , u.cnt_r DESC
     , u.reason DESC

This query doesn't "limit" the rows being returned. It would be possible to modify the query to have only a subset of the rows returned, but that can get complex. And before we muck the complexity of adding "top 5 within top 5" type limits, we want to ensure that the rows returned by a query are a superset of the rows we actually want.

A: Is this what you want?
select t2.reason, count(*)
from (select t1.country, count(*)
      from table1 t1
      where timestamp between @STARTTIME and @ENDTIME
      group by country
      order by count(*) desc
      limit 5
     ) c5 join
     table1 t1
     on c5.country = t1.country and
        t1.timestamp between @STARTTIME and @ENDTIME join
     table2 t2
     on t2.table1_id = t1.id
group by t2.reason;

The c5 subquery gets the five countries.  The other two bring back the data for the final aggregation.


Q: R: Print list to a text file I have in R a list like this:
> print(head(mylist,2))
[[1]]
[1] 234984  10354  41175 932711 426928

[[2]]
[1] 1693237   13462

Each element of the list has different number of its elements.
I would like to print this list to a text file like this:
mylist.txt
234984  10354  41175 932711 426928
1693237   13462

I know that I can use sink(), but it prints names of elements [[x]], [y] and I want to avoid it. Also because of different number of elements in each element of the list it is not possible to use write() or write.table().

A: Not tested, but it should work (edited after comments)
lapply(mylist, write, "test.txt", append=TRUE, ncolumns=1000)

A: Format won't be completely the same, but it does write the data to a text file, and R will be able to reread it using dget when you want to retrieve it again as a list.
dput(mylist, "mylist.txt")

A: I saw in the comments for Nico's answer that some people were running into issues with saving lists that had lists within them. I also ran into this problem with some of my work and was hoping that someone found a better answer than what I found however no one responded to their issue.
So:
@ali, @FMKerckhof, and @Kerry the only way that I found to save a nested list is to use sink() like user6585653 suggested (I tried to up vote his answer but could not). It is not the best way to do it since you link the text file which means it can be easily over written or other results may be saved within that file if you do not cancel the sink. See below for the code.
sink("mylist.txt")
print(mylist)
sink()

Make sure to have the sink() at the end your code so that you cancel the sink.

A: depending on your tastes, an alternative to nico's answer:
d<-lapply(mylist, write, file=" ... ", append=T);

A: Another way
writeLines(unlist(lapply(mylist, paste, collapse=" ")))

A: Here's another way using sink:
sink(sink_dir_and_file_name); print(yourList); sink()

A: Here is another
cat(sapply(mylist, toString), file, sep="\n")

A: I solve this problem by mixing the solutions above.
sink("/Users/my/myTest.dat")
writeLines(unlist(lapply(k, paste, collapse=" ")))
sink()

I think it works well


Q: Clearing a text file in PHP I have a text file that ends up with over 500 lines of text each day. I'm setting up a cron job to manually clear the file at the end of the day but I cannot get it to clear. I've looked online and tried the methods below, but nothing seems to clear the text file... (I ran the file on my server and checked the .txt file using Transmit FTP Client to check the text file and the 500+ lines of text were still there.)
$handle = fopen ("emails.txt", "w+");
fclose($handle);

file_put_contents('emails.txt', '');

$handle = fopen("emails.txt", "w+");
fwrite($handle , '');
fclose($handle);

How can I empty this text file using PHP?

A: This works for me:
$f = fopen('emails.txt','r');
$content = file('emails.txt');
array_splice($content, 0, 500);
file_put_contents('emails.txt', $content);
fclose($f);

A: It looks like you want to truncate your file.
Try with w, instead of w+ http://www.tizag.com/phpT/filetruncate.php
You may also want to check your error logs. If the file isn't writeable by the web / apache user then nothing significant will occur.

A: If you have this on a cron task, you may want to use sed instead.  Sed can remove as many lines as you wish from a file.
Unix Sed Command to Delete lines in file
sed '1d' file removes the first line in a file, while sed '2,4d' file would remove lines 2 through 4.
If you do this via cron, be sure to include the full path to your file, from / (root) forward.

A: Assuming that your script have permissions to write to the text file and that the two files are located in the same directory. I guess that you're not running the script from the same directory, so you could try this :
$handle = fopen (__DIR__."/emails.txt", "w");
fclose($handle);


Q: Fastest way to get residuals from linear, poisson, and negative binomial regressions across many responses I have a numeric, a count, and an over-dispersed count large matrices:
set.seed(1)
numeric.mat <- matrix(rnorm(10000*6000),10000,6000)
count.mat <- matrix(rpois(10000*6000,10),10000,6000)
dispersed.count.mat <- matrix(rnegbin(10000*6000,10,2),10000,6000)

And one corresponding factors data.frame (can be a matrix too):
factors.df <- data.frame(f1 = sample(LETTERS[1:3], 10000, replace = T),
                         f2 = sample(LETTERS[4:5], 10000, replace = T))

The number of factors is pretty small (in this case only 2 but won't be more than 5 for real data), and the number of levels in each (they're all categorical) is also small (also up to 5).
I'd like to obtain the residuals for fitting a linear, poisson, and negative binomial regression models to each of the columns in each of the matrices, respectively.
So for a single column:
data.df <- factors.df %>%
    dplyr::mutate(numeric.y = numeric.mat[,1],
                  count.y = count.mat[,1],
                  dispersed.count.y = dispersed.count.mat[,1])

I'd use:
lm(numeric.y ~ f1+f2, data = data.df)$residuals
residuals(object = glm(count.y ~ f1+f2, data = data.df, family = "poisson"), type = 'pearson')
residuals(object = glm.nb(formula = model.formula, data = regression.df), type = 'pearson')

For the three regression models.
Is there a faster way of obtaining these residuals other than, for example, using do.call, for each. E.g.:
do.call(cbind,
        lapply(1:ncol(numeric.mat),
               function(i)
                   lm(numeric.y ~ f1+f2,
                      data = dplyr::mutate(factors.df,
                                           numeric.y = numeric.mat[,i])
                   )$residuals
))

A: I'd slightly readjust how the workflow runs and allow it to be easily run in parallel.
# Use variables to adjust models, makes it easier to change sizes
iter <- 60
iter_samps <- 1000

factors_df <- data.frame(f1 = sample(LETTERS[1:3], iter_samps, replace = T),
                         f2 = sample(LETTERS[4:5], iter_samps, replace = T))

# using a data.frame in a longer format to hold the data, allows easier splitting
data_df <- rep(list(factors_df), iter) %>%
  bind_rows(.id = "id") %>%
  mutate(numeric_y = rnorm(iter_samps * iter),
         count_y = rpois(iter_samps * iter, 10),
         dispersed_count_y = MASS::rnegbin(iter_samps * iter, 10, 2))

# creating function that determines residuals
model_residuals <- function(data) {
  data$lm_resid <- lm(numeric_y ~ f1+f2, data = data)$residuals
  data$glm_resid <- residuals(object = glm(count_y ~ f1+f2, data = data, family = "poisson"), type = 'pearson')
  return(data)
}
# How to run the models not in parallel
data_df %>%
  split(.$id) %>%
  map(model_residuals) %>%
  bind_rows()

To run the models in parallel you can use multidplyr to do all the annoying work
library("multidplyr")
test = data_df %>%
  partition(id) %>%
  cluster_library("tidyverse") %>%
  cluster_library("MASS") %>%
  cluster_assign_value("model_residuals", model_residuals) %>%
  do(results = model_residuals(.)) %>%
  collect() %>%
  .$results %>%
  bind_rows()