text:
Q: mysql - join two tables based on starting date and date I have the following table structure
Table hour_rate
CREATE TABLE `hour_rate` (
 `hour_rate_id` int(11) NOT NULL AUTO_INCREMENT,
 `hour_rate` decimal(8,2) NOT NULL,
 `from_date` date NOT NULL,
 `employee_id` int(11) NOT NULL,
 PRIMARY KEY (`hour_rate_id`),
 UNIQUE KEY `idx-unique-hour_rate-from_date-employee_id`
     (`from_date`,`employee_id`),
 KEY `idx-hour_rate-employee_id` (`employee_id`),
 CONSTRAINT `fk-hour_rate-employee_id` FOREIGN KEY (`employee_id`)
     REFERENCES `employee` (`employee_id`) ON DELETE CASCADE ON UPDATE CASCADE,
) ENGINE=InnoDB;

Table employee_work
CREATE TABLE `employee_work` (
 `employee_work_id` int(11) NOT NULL AUTO_INCREMENT,
 `project_id` int(11) NOT NULL,
 `employee_id` int(11) NOT NULL,
 `date` date NOT NULL,
 `hours` int(11) NOT NULL,
 PRIMARY KEY (`employee_work_id`),
 UNIQUE KEY `idx-unique-employee_work-employee_id-date`
     (`employee_id`,`date`),
 KEY `idx-employee_work-employee_id` (`employee_id`),
 CONSTRAINT `fk-employee_work-employee_id` FOREIGN KEY (`employee_id`)
     REFERENCES `employee` (`employee_id`) ON DELETE CASCADE ON UPDATE CASCADE,
) ENGINE=InnoDB;

Table hour_rate contains records about employees and their hour rates (hour_rate) starting from date (from_date)
Table employee_work contains records with employees working hours per day
I want to select all records employee_work with appropriate hour rate from hour_rate based on date and from_date, so I can calculate the payment for the employee (hour_rate*hours)
For example i have the following records
in hour_rate
+-----------+------------+-------------+
| hour_rate | from_date  | employee_id |
+-----------+------------+-------------+
|     11.00 | 2018-01-10 |           1 |
|     12.00 | 2018-01-14 |           1 |
|     13.00 | 2018-01-18 |           1 |
|      5.00 | 2018-01-01 |           1 |
|     10.00 | 2018-01-15 |           2 |
+-----------+------------+-------------+

and in employee_work
+-------------+------------+-------+
| employee_id | date       | hours |
+-------------+------------+-------+
|           1 | 2018-01-01 |     8 |
|           1 | 2018-01-02 |     8 |
|           1 | 2018-01-03 |     8 |
|           1 | 2018-01-04 |     8 |
|           1 | 2018-01-05 |     8 |
|           1 | 2018-01-08 |     8 |
|           1 | 2018-01-09 |     8 |
|           1 | 2018-01-10 |     8 |
|           1 | 2018-01-11 |     8 |
|           1 | 2018-01-12 |     8 |
|           1 | 2018-01-15 |     8 |
|           1 | 2018-01-16 |     8 |
|           1 | 2018-01-17 |     8 |
|           1 | 2018-01-18 |     8 |
|           1 | 2018-01-19 |     8 |
+-------------+------------+-------+

I expect to produce the following results
+-------------+------------+-------+--------+
| employee_id | date       | hours | payment|
+-------------+------------+-------+--------+
|           1 | 2018-01-01 |     8 |    40.0|
|           1 | 2018-01-02 |     8 |    40.0|
|           1 | 2018-01-03 |     8 |    40.0|
|           1 | 2018-01-04 |     8 |    40.0|
|           1 | 2018-01-05 |     8 |    40.0|
|           1 | 2018-01-08 |     8 |    40.0|
|           1 | 2018-01-09 |     8 |    40.0|
|           1 | 2018-01-10 |     8 |    88.0|
|           1 | 2018-01-11 |     8 |    88.0|
|           1 | 2018-01-12 |     8 |    88.0|
|           1 | 2018-01-15 |     8 |    96.0|
|           1 | 2018-01-16 |     8 |    96.0|
|           1 | 2018-01-17 |     8 |    96.0|
|           1 | 2018-01-18 |     8 |   104.0|
|           1 | 2018-01-19 |     8 |   104.0|
+-------------+------------+-------+--------+

A: One method uses a correlated subquery to get the rate:
select ew.*,
       (ew.hours *
        (select hr.hour_rate
         from hour_rate hr
         where hr.employee_id = ew.employee_id and
               hr.from_date >= ew.date
         order by hr.from_date
         limit 1
        )
       ) as daily_pay
from employee_work ew;

A: You can do this by using select with 2 tables. The example for your data is below:
select ew.employee_id, ew.date, ew.hours, hr.employee_id, hr.from_date (hr.hour_rate * ew.hours) as payment

from employee_work ew, hour_rate hr

where ew.employee_id = hr.employee_id


text:
Q: application getting launched even if it is open android In  my android application as soon as the user clicks on the application icon from menu the app is getting launched.It is happening even if the application is open earlier.
I would like to maintain the state like if the application is opened then the app should show the default opened page and should not launch it again.
Please let me know your valuable suggestions.
Thanks in advance :)

A: Hey i solved this issue.Earlier i was using android:launchmode as single instance.When i removed this its working fine :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Execute Python String inside a Python code using Python3 If I have a srting inside my Python code that looks like this:
x = "print('Hello World')"

I want to execute it as if it is like a seperate .py file. Is there something like
execute(x)

A: exec(x)

See the documentation
But be careful of injection vulnerabilities: if the string comes from a user, they will have the power to control your computer - e.g. something like __import__('shutil').rmtree('/') could remove a whole directory.


text:
Q: Intellij Attach Sources does not seem to work I have followed various posts about how to attach sources in IJ. None are working. Here I will walk through this.  I am on IJ 13.1.2
We have a library with missing sources here (not in maven):

Let us try to attach the sources using the "Attach sources" link in upper right:

But nothing changes : the sources are not attached.  So this is the first bug.

Now let us try by navigating to the library within the Project View:

Well that seems to have made progress!

However: we STILL DO NOT HAVE SOURCES when we click on a class within that library, the message "Sources not found" still occurs.
Is this supposedly fixed?  Any workarounds?

A: It turns out the source jar file was corrupted.

A: Try changing the sources extension from jar to zip and then import.


text:
Q: "instanceof" equivalent in Golang I have these structs:
type Event interface {
    Accept(EventVisitor)
}

type Like struct {
}

func (l *Like) Accept(visitor EventVisitor) {
    visitor.visitLike(l)
}

How can I test that event is a Like instance?
func TestEventCreation(t *testing.T) {
    event, err := New(0)
    if err != nil {
        t.Error(err)
    }
    if reflect.TypeOf(event) != Like {
        t.Error("Assertion error")
    }
}

I get:

Type Like is not an expression event Event

A: Late answer but this works fine
package main

import (
  "fmt"
  "reflect"
)

type SomeStruct1 struct{}
type SomeStruct2 struct{}

func IsInstanceOf(objectPtr, typePtr interface{}) bool {
  return reflect.TypeOf(objectPtr) == reflect.TypeOf(typePtr)
}

func main() {
  //sample variables
  someString := "Some String"
  someFloat := float32(2.4)
  someStruct1 := SomeStruct1{}
  someStruct2 := SomeStruct2{}
  someStruct1Ptr := &SomeStruct1{}

  // primitive string
  fmt.Println("string <-> *string \t\t", IsInstanceOf(someString, (*string)(nil)))   //false
  fmt.Println("*string <-> *string \t\t", IsInstanceOf(&someString, (*string)(nil))) //true

  // primitive float32
  fmt.Println("float32 <-> *float32 \t\t", IsInstanceOf(someFloat, (*float32)(nil)))   //false
  fmt.Println("*float32 <-> *float32 \t\t", IsInstanceOf(&someFloat, (*float32)(nil))) //true

  // structure
  fmt.Println("SomeStruct1 <-> *SomeStruct1 \t", IsInstanceOf(someStruct1, (*SomeStruct1)(nil)))     //false
  fmt.Println("*SomeStruct1 <-> *SomeStruct1 \t", IsInstanceOf(&someStruct1, (*SomeStruct1)(nil)))   //true
  fmt.Println("*SomeStruct2 <-> *SomeStruct1 \t", IsInstanceOf(&someStruct2, (*SomeStruct1)(nil)))   //false
  fmt.Println("*SomeStruct1 <-> *SomeStruct1 \t", IsInstanceOf(someStruct1Ptr, (*SomeStruct1)(nil))) //true
}

Playground ( run it online ) : https://play.golang.org/p/tcQqdzUGMlL

A: You could just do a type assertion and see if it fails:
event, err := New(0)
if err != nil {
    t.Error(err)
}
_, ok := event.(Like)
if !ok {
    t.Error("Assertion error")
}

A: The closest translation of:
// java
if (x instanceof y) {
    // x is a y
}

is:
// go
if _, ok := x.(y); ok {
    // x is a y
}

A: the TypeOf() method returns an object of type Type, and you can get the name of that type as a string with the Name() method.
I haven't tested this, but something like this may work:
if reflect.TypeOf(event).Name() != "Like" {

A: the func may be need defined like this:
func (l Like) Accept(visitor EventVisitor)


text:
Q: Are most numbers of the form $a\cdot b^n+c$ composite? It seems evident that for $a,b,c$ with $a>0$ and $b>1$ that there are only $o(x)$ primes of the form $a\cdot b^n+c$ with $n\le x.$ Has this been proven?
Hooley (Applications of Sieves to the Theory of Numbers) proves this for Cullen numbers, and apparently this proof generalizes to forms $n\cdot2^{n+a}+b$.
A reference would be great, if one can be found. Otherwise, I'll take what I can get!

A: It seems that the problem is entirely open, as seen by this answer on MathOverflow.
The difficulty is that the Cullen form gets equidistribution in all odd moduli from the $n$, while the general case has more restricted residue classes that are harder to control.


text:
Q: Python: How do I use variables in a string pulled from a json file? So I have a string stored in a JSON file, but when I pull it into my Python code, there are certain parts I want to replace with variables. How would I go about doing that? Here's what I currently have that's relevant: (I'm coding as discord bot with discord.py if that changes anything)
guildname = member.guild.name
        memberid = member.id
        await thatchannel.send(f"{config['newmembermessage']}")

and from the json file
{
    "modlogsid": 492165353544351745,
    "enablenewmemberchannel": false,
    "newmemberchannel": "465976927932",
    "newmembermessage": "Welcome to {guildname}, <@{memberid}>! Read <#477198353541627913> and you're set, enjoy!"
}

A: Treat config["newmembermessage"] as you would any other string.
new_member_message = config["newmembermessage"].format(guildname, memberid)


text:
Q: Nuances in meanings: paradox , conundrum, dilemma , plight What are the subtle differences in meanings between the following words?

*

*Paradox

*Conundrum

*Dilemma

*Plight

A: Some of these words have multiple meanings, but I am pointing the specific meaning which is in political/social or economic context as mentioned by you. (This answer took me so much time to write, hope it helps)
Paradox (noun) means a situation or statement that seems impossible or is difficult to understand because it contains two opposite facts or characteristics.
For example:

It's a paradox that drinking too much water makes you feel thirsty.
It's a paradox that our government talks about secularism and still
  favours a particular religion.

Conundrum (noun) is a problem or puzzle which is difficult or impossible to solve.
For example:

We tried to empower women in the region, but they opposed us saying
  'they don't want to go against their husbands.' What a conundrum!

Dilemma (noun) is a difficult situation in which you have to choose between two or more almost similarly difficult alternatives.
For example:

I was trapped between a dry well and a high end cliff, there's no
  place to go instead of the two. God, what a dilemma!
Our government is facing a dilemma of either being secularist or
  nationalist.

Plight (noun) is an unpleasant condition, especially a serious, sad, or difficult one.
For example:

My problems don't carry any significance with the plight of the storm victims.

Hope, it helped :) Oof, I am tired now.

A: Paradox

*

*Used to describe two or more irreconcilable truths. In common speech, a paradox can be used to describe a situation with conflicting qualities.

*E.g. "Paradoxically, Senator So-and-So's approval rating among Democrats rose sharply after she officially left the party."

Conundrum

*

*Used to describe a difficult problem, in particular a confusing problem.

*E.g. "President So-and-So faced the conundrum of how to stem the flow of a drug that nobody had even named yet."

Dilemma

*

*The meaning of dilemma is similar to that of conundrum, and there are instances where the two could be used interchangeably. A differentiating factor is that a dilemma usually refers to an especially difficult problem, regardless of whether the issue is confusing or complicated. Often there is no "good" solution to a dilemma.

*E.g. "Mayor So-and-So addressed the dilemma of funding fire prevention in a community where the tax revenue had plummeted because of fire damage in the industrial area."

Plight

*

*Plight refers to a person or thing's misfortune. A challenging or dangerous situation can be described as a plight, and the word is often used to describe the symptoms of a problem, rather than the problem on its face.

*E.g. "Governor So-and-So's bill to add more teachers to inner-city schools aims to address the plight of underserved urban students."


text:
Q: Orion Context Broker GEOLOCATION, How to deal with location not known? Regarding "position" below. I am trying to find what is the best way to define the value of "position" attribute as Location not known. I means how to represent location not known in orion database.
{
    "contextElements": [
        {
            "type": "City",
            "isPattern": "false",
            "id": "Madrid",
            "attributes": [
                {
                    "name": "position",
                    "type": "geo:point",
                    "value": "LocationNotKnown"
                }
            ]
        }
    ],
    "updateAction": "APPEND"
}

Many thanks.

A: At the present moment (up to Orion 2.3.0) geo:point attribute needs a valid point as value, so thinks like "LocationNotKnown" will not work.
However, we have been discussing the possibility of allowing null or "" as valid value for geo:point (and other similar attribute types) to mean "no location" (or "no date", in the case of DataTime). You can join the discussion on the corresponing github issue and provide your opinion there.
On the meanwhile, the recommended workaround is to remove the attribute. Thus, if your entity includes the "location" attribute (with a valid geo:point as value) then it is localized. If your entity doesn't include the "location" attribute is not localized.


text:
Q: generate BZHI instruction with gcc I'm trying to make gcc generate the bzhi instruction, part of BMI2,
without using intrinsics,
in order to create a portable code.
Given the outcome of bzhi, I expected that objective to be relatively accessible.
The following SO answer provides a code example, simplified below :
unsigned bzhi32(unsigned value, int nbBits)
{
    return value & ((1u << nbBits) - 1);
}

clang has no problem generating bzhi instruction with it, while I haven't found any similar outcome for gcc so far :
https://godbolt.org/g/jYrh8F
I was wondering if this was possible.
This capability was at least requested, but not sure if it was completed.
If it was, maybe there are just some subtle issues in the code snippet, for example with type or properties, which could be fixed to succeed this transformation with gcc.
edit : added u for constant, as suggested by @chux. It marginally changes the outcome for gcc, though it's still a 4-instructions function without bzhi.

A: This optimization is not implemented in gcc as of January 2018 (there is a feature request). You can get the instruction by using intrinsics:
#include <x86intrin.h>

unsigned bzhi32(unsigned value, int nbBits) {
   return _bzhi_u32(value, nbBits);
}


text:
Q: Autocomplete Dropdown as Search Bar I'm new to website building and have never coded other than the odd font styling change so please bare with me.
I've been trying to build a website (Wordpress) but have been struggling when it comes to the sites search bar.
Someone on Reddit suggested I use an autocomplete dropdown as seen on W3Schools and then suggested I come here to find answers to how to make the results linkable to urls.
Of that code is it possible to have the results linked to a url so there isn't a need for a search button?
Also as its currently written results for the United States of America wouldn't show by typing America. Can that be changed?
`

<form autocomplete="off" action="/action_page.php">

    <input id="myInput" type="text" name="myCountry" placeholder="Country">

  <input type="submit">
</form>

var countries = ["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua & Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia & Herzegovina","Botswana","Brazil","British Virgin Islands","Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Canada","Cape Verde","Cayman Islands","Central Arfrican Republic","Chad","Chile","China","Colombia","Congo","Cook Islands","Costa Rica","Cote D Ivoire","Croatia","Cuba","Curacao","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Falkland Islands","Faroe Islands","Fiji","Finland","France","French Polynesia","French West Indies","Gabon","Gambia","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guam","Guatemala","Guernsey","Guinea","Guinea Bissau","Guyana","Haiti","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Isle of Man","Israel","Italy","Jamaica","Japan","Jersey","Jordan","Kazakhstan","Kenya","Kiribati","Kosovo","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macau","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Mauritania","Mauritius","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Montserrat","Morocco","Mozambique","Myanmar","Namibia","Nauro","Nepal","Netherlands","Netherlands Antilles","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","North Korea","Norway","Oman","Pakistan","Palau","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Puerto Rico","Qatar","Reunion","Romania","Russia","Rwanda","Saint Pierre & Miquelon","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Korea","South Sudan","Spain","Sri Lanka","St Kitts & Nevis","St Lucia","St Vincent","Sudan","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor L'Este","Togo","Tonga","Trinidad & Tobago","Tunisia","Turkey","Turkmenistan","Turks & Caicos","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States of America","Uruguay","Uzbekistan","Vanuatu","Vatican City","Venezuela","Vietnam","Virgin Islands (US)","Yemen","Zambia","Zimbabwe"];
* { box-sizing: border-box; }
body {
  font: 16px Arial;
}
.autocomplete {
  /*the container must be positioned relative:*/
  position: relative;
  display: inline-block;
}
input {
  border: 1px solid transparent;
  background-color: #f1f1f1;
  padding: 10px;
  font-size: 16px;
}
input[type=text] {
  background-color: #f1f1f1;
  width: 100%;
}
input[type=submit] {
  background-color: DodgerBlue;
  color: #fff;
}
.autocomplete-items {
  position: absolute;
  border: 1px solid #d4d4d4;
  border-bottom: none;
  border-top: none;
  z-index: 99;
  /*position the autocomplete items to be the same width as the container:*/
  top: 100%;
  left: 0;
  right: 0;
}
.autocomplete-items div {
  padding: 10px;
  cursor: pointer;
  background-color: #fff;
  border-bottom: 1px solid #d4d4d4;
}
.autocomplete-items div:hover {
  /*when hovering an item:*/
  background-color: #e9e9e9;
}
.autocomplete-active {
  /*when navigating through the items using the arrow keys:*/
  background-color: DodgerBlue !important;
  color: #ffffff;
}
unction autocomplete(inp, arr) {
  /*the autocomplete function takes two arguments,
  the text field element and an array of possible autocompleted values:*/
  var currentFocus;
  /*execute a function when someone writes in the text field:*/
  inp.addEventListener("input", function(e) {
      var a, b, i, val = this.value;
      /*close any already open lists of autocompleted values*/
      closeAllLists();
      if (!val) { return false;}
      currentFocus = -1;
      /*create a DIV element that will contain the items (values):*/
    a = document.createElement("DIV");
      a.setAttribute("id", this.id + "autocomplete-list");
      a.setAttribute("class", "autocomplete-items");
      /*append the DIV element as a child of the autocomplete container:*/
      this.parentNode.appendChild(a);
      /*for each item in the array...*/
      for (i = 0; i < arr.length; i++) {
        /*check if the item starts with the same letters as the text field value:*/
        if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
          /*create a DIV element for each matching element:*/
          b = document.createElement("DIV");
          /*make the matching letters bold:*/
          b.innerHTML = "" + arr[i].substr(0, val.length) + "";
          b.innerHTML += arr[i].substr(val.length);
          /*insert a input field that will hold the current array item's value:*/
          b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
          /*execute a function when someone clicks on the item value (DIV element):*/
              b.addEventListener("click", function(e) {
              /*insert the value for the autocomplete text field:*/
              inp.value = this.getElementsByTagName("input")[0].value;
              /*close the list of autocompleted values,
            (or any other open lists of autocompleted values:*/
              closeAllLists();
        });
          a.appendChild(b);
        }
      }
  });
  /*execute a function presses a key on the keyboard:*/
  inp.addEventListener("keydown", function(e) {
      var x = document.getElementById(this.id + "autocomplete-list");
      if (x) x = x.getElementsByTagName("div");
      if (e.keyCode == 40) {
        /*If the arrow DOWN key is pressed,
        increase the currentFocus variable:*/
        currentFocus++;
        /*and and make the current item more visible:*/
        addActive(x);
    } else if (e.keyCode == 38) { //up
        /*If the arrow UP key is pressed,
        decrease the currentFocus variable:*/
        currentFocus--;
        /*and and make the current item more visible:*/
        addActive(x);
    } else if (e.keyCode == 13) {
        /*If the ENTER key is pressed, prevent the form from being submitted,*/
        e.preventDefault();
        if (currentFocus > -1) {
          /*and simulate a click on the "active" item:*/
          if (x) x[currentFocus].click();
        }
    }
  });
  function addActive(x) {
    /*a function to classify an item as "active":*/
    if (!x) return false;
    /*start by removing the "active" class on all items:*/
    removeActive(x);
    if (currentFocus >= x.length) currentFocus = 0;
    if (currentFocus < 0) currentFocus = (x.length - 1);
    /*add class "autocomplete-active":*/
    x[currentFocus].classList.add("autocomplete-active");
  }
  function removeActive(x) {
    /*a function to remove the "active" class from all autocomplete items:*/
    for (var i = 0; i < x.length; i++) {
    x[i].classList.remove("autocomplete-active");
    }
  }
  function closeAllLists(elmnt) {
    /*close all autocomplete lists in the document,
    except the one passed as an argument:*/
    var x = document.getElementsByClassName("autocomplete-items");
    for (var i = 0; i < x.length; i++) {
      if (elmnt != x[i] && elmnt != inp) {
    x[i].parentNode.removeChild(x[i]);
    }
  }
}
/*execute a function when someone clicks in the document:*/
document.addEventListener("click", function (e) {
    closeAllLists(e.target);
});}

`


text:
Q: From semidirect to direct product of groups I was studying some properties of semidirect products, and I noticed this sentence on Wiki

Suppose $G$ is a semidirect product of the normal subgroup $N$ and the subgroup $H$. If $H$ is also normal in $G$, or equivalently, if there exists a homomorphism $G\to N$ which is the identity on $N$, then $G$ is the direct product of $N$ and $H$.

So I tried proving myself that having such homomorphism from $\varrho \colon G\to N$ which is the identity on $N$ was sufficient to imply $H$ normal (because I think this is the point) and so having two normal subsets $H,N$ with $H\cap N=1$ it's easy to see that $G\cong N \times H$.
The problem is that I'm not able to prove that $\ker \varrho=H$ (either the two implications).
Being $\varrho$ surjective I tried considering the iso $G/\ker \varrho \to N$, but I do not know how to prove that $H \subset \ker \varrho$. In fact I proved that, for every $g \in G$, exists $n \in N$ such that $[g]=[n]$, but from this I do not know how to proceed further, because I'd have $h w=n$ for $w$ element in the kernel. But to apply the fact that the intersection is trivial I need to know that the kernel is contained in $H$, which I cannot prove.
Can someone help me please? because this fact seems a triviality but it's bugging me


text:
Q: Triggering Mechanisms of Devops REST APIs I am referring to the below MSFT doc for Devops REST API:
https://learn.microsoft.com/en-us/rest/api/azure/devops/pipelines/runs/get?view=azure-devops-rest-7.0
As per the doc, one can trigger the API only via PAT as seen below:

Can someone confirm whether there is no other way possible other than PAT?
Also, is it possible to provide access tp an App/service principal to an Azure Devops  Project ?
I can only see users/groups:

Because we would like to leverage service principal PAT rather than individual/service account.


text:
Q: Is there way to get Development/Distribution/APN certificate without p12 file I know that we can get this certificates using P12,
But is it possible to get certificate without p12 file.
I have Developer Account credential, But not able to contact older developer who has created Certificate.
So i have to create new certificate or is it possible to get certificate without P12 files?


text:
Q: Transcode HLS Segments individually using FFMPEG I am recording a continuous, live stream to a high-bitrate HLS stream.  I then want to asynchronously transcode this to different formats/bitrates.  I have this working, mostly, except audio artefacts are appearing between each segment (gaps and pops).
Here is an example ffmpeg command line:
ffmpeg -threads 1 -nostdin -loglevel verbose \
   -nostdin -y -i input.ts -c:a libfdk_aac \
   -ac 2 -b:a 64k -y -metadata -vn output.ts

Inspecting an example sound file shows that there is a gap at the end of the audio:

And the start of the file looks suspiciously attenuated (although this may not be an issue):

My suspicion is that these artefacts are happening because transcoding are occurring without the context of the stream as a whole.
Any ideas on how to convince FFMPEG to produce audio that will fit back into a HLS stream?
** UPDATE 1 **
Here are the start/end of the original segment.  As you can see, the start still appears the same, but the end is cleanly ended at 30s.  I expect some degree of padding with lossy encoding, but I there is some way that HLS manages to do gapless playback (is this related to iTunes method with custom metadata?)

** UPDATED 2 **
So, I converted both the original (128k aac in MPEG2 TS) and the transcoded (64k aac in aac/adts container) to WAV and put the two side-by-side.  This is the result:

I'm not sure if this is representative of how a client will play it back, but it seems a bit odd that decoding the transcoded one introduces a gap at the start and makes the segment longer.  Given they are both lossy encoding, I would have expected padding to be equally present in both (if at all).
** UPDATE 3 **
According to http://en.wikipedia.org/wiki/Gapless_playback - Only a handful of encoders support gapless - for MP3, I've switched to lame in ffmpeg, and the problem, so far, appears to have gone.
For AAC (see http://en.wikipedia.org/wiki/FAAC), I have tried libfaac (as opposed to libfdk_aac) and it also seems to produce gapless audio.  However, the quality of the latter isn't that great and I'd rather use libfdk_aac is possible.

A: This is more of a conceptual answer rather than containing explicit tools to use, sorry, but it may be of some use in any case - it removes the problem of introducing audio artifacts at the expense of introducing more complexity in your processing layer.
My suggestion would be to not split your uncompressed input audio at all, but only produce a contiguous compressed stream that you pipe into an audio proxy such as an icecast2 server (or similar, if icecast doesn't support AAC) and then do the split/recombine on the client-side of the proxy using chunks of compressed audio.
So, the method here would be to regularly (say, every 60sec?) connect to the proxy and collect a chunk of audio a little bit bigger than the period that you are polling (say, 75sec worth?) - this needs to be set up to run in parallel, since at some points there will be two clients running - it could even be run from cron if need be or backgrounded from a shell script ...
Once that's working, you will have a series of chunks of audio that overlap a little - you'd then need to do some processing work to compare these and isolate the section of audio in the middle which is unique to each chunk ...
Obviously this is a simplification, but assuming that the proxy does not add any metadata info (ie, ICY data or hinting) then splitting up the audio this way should allow the processed chunks to be concatenated without any audio artifacts since there is only one set of output for the original audio input and comparing them will be a doddle since you actually don't care one whit about the format, it's just bytes at that point.
The benefit here is that you've disconnected the audio encoder from the client, so if you want to run some other process in parallel to transcode to different formats or bit rates or chunk the stream more aggressively for some other consumer then that doesn't change anything on the encoder side of the proxy - you just add another client to the proxy using a tool chain similar to the above.


text:
Q: Cannot open local .txt file to read in NLTK I'm not an experienced programmer and I am solely trying to use it for some data analysis with NLTK. I'm following the online book, but the following code does not open to read the file.
#download nltk

import nltk
nltk.download()

#import everything from nltk
from nltk.book import *

import io
open('ALL FEMALES1.txt', encoding="ISO-8859-1")

The output:
<_io.TextIOWrapper name='ALL FEMALES1.txt' mode='r' encoding='ISO-8859-1'>
I've tried to use
f = open('ALL FEMALES1.txt')
>>> raw = f.read()

But this gives me the following error:
'utf-8' codec can't decode byte 0xd5 in position 18929: invalid continuation byte
Any advice? I'm using Jupyter Notebook if that matters.

A: Opening files can be nicely done with
with open('sample_file.txt', encoding="ISO-8859-1") as f:
    print(f.read())


text:
Q: Use StyleCop checkin policy with StyleCop+ I have a StyleCop and StyleCop+ which are integrated into projects via StyleCop.MSBuild.
All warnings related to StyleCop+ are shown correctly after project build. I need to integrate my rules with StyleCop checkin policy. Now during checkin StyleCop warnings are shown as errors, but I see that StyleCop+ warnings are not considered as errors.
Not sure if it's possible, but can I force checkin policy to handle StyleCop+ warnings as errors during checkin? (like it's working for plain StyleCop)
[UPDATE]
I need to produce errors only during checkin and only for files which are changed because it's an old project and I want to force others to fix only those files which they change during checkin. By default this is working properly for all warnings of StyleCop but not for warnings of StyleCop+

A: So, I just took sources of StyleCop checkin policy, added reference to StyleCopPlus.dll for CheckinPolicy project, did rebuild of Vsix2019 and now VSIX supports StyleCop+.


text:
Q: Ionic plugin ThemeableBrowser offset issue on iPhone X I am using ThemeableBrowser plugin

cordova-plugin-themeablebrowser 0.2.17 "ThemeableBrowser"

in my Ionic 3 project. In all of the devices it works fine, recently i tried to update the app to display correctly on iPhone X , by following the official ios11 checklist - https://blog.ionicframework.com/ios-11-checklist/
All the issues i had were resolved, apart from the ThemeableBrowser, which opens pages with an negative offset. I tried using insertCss method of themeable browser as suggested  HERE , but this didn't work either.
This is initial state of the page when it opens:

Is there any other possible workaround?

A: I resolved this issue by editing CDVThemableBrowser.m - there is an obvious bug for all iOS devices, it's just more obvious on iPhone X as it has bigger status bar. The rePositionViews , which set the position of webview doesn't add the statusBar height to it's Y position
I changed:
- (void) rePositionViews {
  CGFloat toolbarHeight = [self getFloatFromDict:_browserOptions.toolbar withKey:kThemeableBrowserPropHeight withDefault:TOOLBAR_DEF_HEIGHT];
  CGFloat webviewOffset = _browserOptions.fullscreen ? 0.0 : toolbarHeight;`

To:
- (void) rePositionViews {
  CGFloat toolbarHeight = [self getFloatFromDict:_browserOptions.toolbar withKey:kThemeableBrowserPropHeight withDefault:TOOLBAR_DEF_HEIGHT];
  CGFloat statusBarOffset = [self getStatusBarOffset];
  CGFloat webviewOffset = _browserOptions.fullscreen ? 0.0 : toolbarHeight + statusBarOffset;`

This solves the problem with the content offset


text:
Q: Does Weka test results on a separate holdout set with 10CV? I used 10-fold cross validation in Weka.
I know this usually means that the data is split in 10 parts, 90% training, 10% test and that this is alternated 10 times.
I am wondering on what Weka calculates the resulting AUC. Is it the average of all 10 test sets? Or (and I hope this is true), does it use a holdout test set? I can't seem to find a description of this in the weka book.

A: Weka averages the test results. And this is a better approach then the holdout set, I don't understand why you would hope for such approach. If you hold out the test set (of what size?) your test would not be statisticaly significant, It would only say, that for best chosen parameters on the training data you achieved some score on arbitrary small part of data. The whole point of cross validation (as the evaluation technique) is to use all the data as training and as testing in turns, so the resulting metric is approximation of the expected value of the true evaluation measure. If you use the hold out test it would not converge to expected value (at least not in a reasonable time) and what is even more important - you would have to choose another constant (how big hold out set and why?) and reduce the number of samples used for training (while cross validation has been developed due to the problem with to small datasets for both training and testing).

A: I performed cross validation on my own (made my own random folds and created 10 classifiers) and checked the average AUC. I also checked to see if the entire dataset was used to report the AUC (similar as to when Weka outputs a decision tree under 10-fold).
The AUC for the credit dataset with a naive Bayes classifier as found by...

*

*10-fold weka = 0.89559

*10-fold mine = 0.89509

*original train = 0.90281

There is a slight discrepancy between my average AUC and Weka's, but this could be from a failure in replicating the folds (although I did try to control the seeds).


text:
Q: What is the best way to query multiple databases in a stored procedures across different environments I was wondering what the best way was to query multiple databases in a stored procedure. I can hard code the database names in the stored procedure
i.e:
Select *
from [Audit].[dbo].[AuditTable] inner join
     [Core].[dbo].[CoreTable]
     on ....

But I would like to store the stored procedures in a version control system and then migrate them to different environments. So I was wondering the best way to do this. The database name is different for different environments.
Possible solutions:

*

*Using a view to span tables in different databases? The database name
will only exist in one place

*Extended properties for the database/ passing the name into a stored
procedure. It is possible to dynamically change the name of the
database used in a stored procedure: Changing database name in a
stored procedure dynamically But I am worried this will be messy

*Separate environments with the same database name across all
environments?

It seems that this is a duplicate of:
Cross-database queries with different DB names in different environments

A: Separate environments with the same database name across all environments seems like the cleanest option.
But if that is not an option, maybe substitution variables might work. SQL Server Data Tools for Visual Studio handles it this way - a referenced database is referred to using a token e.g. [Audit] would be replaced by [$(Audit)]. Then when you publish the database you define a value for each $variable and these values get substituted in place of the tokens.
Obviously this would require you to have a mechanism to make these replacements.


text:
Q: undefined method `each' in a factory_girl / rspec2 scenario I'm trying to Factory a Post associated with a Vote. So that Post.votes would generate the Vote's that are associated with it.
Factory.define :voted_post, :parent => :post, :class => Post do |p|
  p.association :votes, :factory => :vote
end

And my rspec2 is relatively straightforward :
describe "vote scores" do
  it "should show me the total vote score" do
    @post = Factory(:voted_post)
    @post.vote_score.should == 1
  end
end

So why would it return this error :
Failures:
   1) Post vote scores should show me the total vote score
     Failure/Error: @post = Factory(:voted_post)
     undefined method `each' for #<Vote:0x105819948>

ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0]
Rails 3.0.0

A: If you want to assign has_many association which expects array and not a single value, you should use the long form:
Factory.define :voted_post, :parent => :post, :class => Post do |p|
  p.votes { |vote| [vote.association(:vote)] }
end

And encapsulate the creation of the association with [] to ensure that array would be returned

A: Factory.define :voted_post, :parent => :post, :class => Post do |p|
  p.association :votes, :factory => :vote
end

Is the same as trying to go
some_voted_post.votes = Factory(:vote)

Basically you're attempting to assign a single vote as an array.
EDIT
You can have an array containing a single vote, but you can't just have a single vote.
It's the difference between:
some_voted_post.votes = Factory(:vote)

and
some_voted_post.votes = [Factory(:vote)]

The former is not an array, and therefore does not work, the latter is an array.


text:
Q: Is there any better way to understand angular error/exception messages in AngularJS? During development we often encounter errors/exceptions in developer console. But for me its not easy recognize the error properly (:P ).
Is there any better way to get more information about error/exception like due to which code, line number, which line etc.
Thanks!

A: Use Chrome for debugging. In Chrome the Angular messages are displayed as a nice stracktrace with a clickable link to the error description.
You can also use the non-minified version of angular to get more descriptive error messages.


text:
Q: Butter knife is not working in my existing project after using another project as a library in android compile 'com.jakewharton:butterknife:8.7.0'
@BindView(R.id.tvName)
TextView tvName;
private Unbinder unbinder;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_profile_view, container, false);

unbinder = ButterKnife.bind(this, view);
tvName.setText(name);    //its throwing null pointer exception
}

if I remove the library from my project then butterknife is working perfectly.

A: I had the same issue, after adding an empty library module to a project, ButterKnife stopped working and it reported an error on all @BindView annotation usages.
Incorrectly typed data found for annotation element
public abstract int butterknife.BindView.value() (Found data of type R.id)

The issue turned out to be that the package name of the library module was the same as the one of the app module. After changing the package name, the errors went away.


text:
Q: accessing parts of sub-queries to build HTML in a PHP server I have a query that returns the count of active and inactive posts, plus the specific post details. Here's the query
$fetch = mysql_query("SELECT SQL_CALC_FOUND_ROWS * FROM
(SELECT DISTINCT propertyID, streetAddress, city FROM residence.property
WHERE residence.contact.contactEmailAddress1 ='$contactEmailAddress1' AND activePosting = '0') inactposts,
    (SELECT FOUND_ROWS() AS 'inactiveCount') inact,
(SELECT DISTINCT propertyID, streetAddress, city FROM residence.property
INNER JOIN contact ON residence.contact.ContactID = residence.property.ContactID
WHERE residence.contact.contactEmailAddress1 ='$contactEmailAddress1' AND activePosting = '1') actposts,
    (SELECT FOUND_ROWS() AS 'activeCount') act;")
or die('
Ooops
'.mysql_error());

The query works in my web page. In MySQL Workbench it returns things looking like:
propID   address        city        inactCount  propID  address     city        actCount
366   110 Main Street   Perinton        1       352    3 Some Place Perinton        3
366   110 Main Street   Perinton        1       353    5 Joe Place  Perinton        3
366   110 Main Street   Perinton        1       356    111 Main     Perinton        3

The issue for me is the 2 parts of the sub-query results don't have an identifier (that I can find), so in the HTML constructed by the PHP server, I can't separate the lists into into inactive posts (inactposts) and active posts (actposts). Currently the HTML only returns the list of active posts. I've tried putting "inactposts", the name of the temporary table, in various places and I just get error messages
Here's the PHP doing the HTML construction:
if( mysql_num_rows($fetch) ) {
while ($row = mysql_fetch_array($fetch)) {
    $inactiveCount = $row["inactiveCount"];
    $activeCount = $row["activeCount"];
    $storedStreetAddress = $row["streetAddress"];
    $storedCity3 = $row['city3'];
    $error_NumberInactives = "
You have $activeCount active posts and $inactiveCount inactive posts.
";
    $error_List_Actives = "
Your $activeCount active posts are:
";
    $errorMessages[0] = $error_NumberInactives;
    $errorMessages[1] = $error_List_Actives;
    $errorMessages[] = "
 $storedStreetAddress, $storedCity3
";
}else{ //error message}

How can I construct separate lists of sub-query results from this query? Or do I need a different query?

A: You'll need another query without the aggregation if you want the individual rows.
Alternately, select all of the posts (with details) in one query and parse the result in php to count the number of active and inactive:
SELECT DISTINCT propertyID, streetAddress, city, activePosting FROM residence.property
INNER JOIN contact ON residence.contact.ContactID = residence.property.ContactID
WHERE residence.contact.contactEmailAddress1 ='$contactEmailAddress1'

p.s. I assume you have sanitized your inputs outside of the provided code, otherwise you need to do that.


text:
Q: How do I define a nested Pydantic model with a Tuple containing Optional models? I am currently working with following nested model (FinalModel):
class Model1(BaseModel):
    count: int

class Model2(BaseModel):
    method: str
    selector: dict
    count: int

class FinalModel(BaseModel):
    slow: bool
    models: Tuple[
        Optional[Model1],
        Optional[Model2],
    ]]

I am expecting the Tuple to have a variable length since I'd like to pass in either Model1 or Model2 or both based on the requirements. However, the tuple seems to be expecting a fixed length of 2.
Please note that Union is not an option for me since I expect number of models to increase in future and the possible combinations will increase as well.

A: To specify a variable-length tuple of multiple types you can use ellipsis literal ... and Union, like below:
class FinalModel(BaseModel):
    slow: bool
    models: Tuple[Union[Model2, Model1], ...]

When using Union one also need to keep in mind that:

However, as can be seen above, pydantic will attempt to 'match' any of the types defined under Union and will use the first one that matches.[...]
As such, it is recommended that, when defining Union annotations, the most specific type is included first and followed by less specific types.

Therefore, for your example, Model2 must precede Model1 in Union, since the objects of Model2 when parsing will match with Model1, and the other members will be discarded. Or use extra = forbid.
class Model1(BaseModel):
    count: int

    class Config:
        extra = "forbid"

A: Are  you sure you want to use a tuple? A tuple is fixed size in its nature, using it in you Pydantic model will require both elements to be present.
Instead, you could use a List[Union[Model1, Model2]]


text:
Q: Nodejs render multiple items with the same name I'm trying to render using underscore js, and instead of making a template for each, I decided to use one for all. However, this code only renders the last item( accessories : luggage). Any way to make it work?
exports.maccess = function(req, res) {
    collectionp.find({ "primary_category_id": "mens-accessories-gloves"}).toArray(function(err, gloves) {
        collectionp.find({ "primary_category_id": "mens-accessories-ties"}).toArray(function(err, ties) {
            collectionp.find({ "primary_category_id": "mens-accessories-luggage"}).toArray(function(err, luggage) {
                res.render("maccess", {
                    _     : _,
                    accessories : ties,
                    accessories : gloves,
                    accessories : luggage
                });
            });
        });
    });
};

A: If ties, gloves, and luggage are all arrays, and you're using the same template on all of them, try just passing them along as a single array, e.g.
accessories : ties.concat(gloves).concat(luggage)

Try it out and let me know if it works or if I've misunderstood something..

A: Javascript object cannot contain multiple entries with the same key (in your case - accessories).
You have to write something like:
accessories: [ties, gloves, luggage]

(and use it in the template: accessories[0], accessories[1], accessories[2])
or:
accessories: {
  ties: ties,
  gloves: gloves,
  luggage: luggage
}

And use it: accessories.ties, accessories.gloves, etc


text:
Q: Why is my iOS app second build, uploaded in apple store connect as a different app? So I decided to continue the development of the (react-native) app in an external ssd drive.
Thus, I cloned the app from GitHub, run npm i and cd ios pod install, run the app in a simulator and then made an Archive an uploaded to apple store connect.
But when I visited the apple store connect, I saw that the build was uploaded as another app with the same name.
I tried to copy/paste the ios folder of the old app into the new. Deleted the build folder and the DerivedData, made the Archive etc, but the new build was uploaded again in the second app.
Is there something that I'm not doing right?
I could delete the old app (in apple store connect) and go on with the new, (it's not in production yet) but I just wonder, why is this happening, and how can I avoid it.
Thank you


text:
Q: LSTM wrong shape in prediction I have trained a model:
trainX = trainX.reshape(1, 43164, 17)
trainY = trainY.reshape(43164, 1)

model = Sequential()
model.add(LSTM(2, input_shape=(43164, 17)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY[0], epochs=100)

testX.shape # (8633, 17)
testX = testX.reshape(1, 8633, 17)

When I do a prediction for this data, I obtained an error:
Error when checking input: expected lstm_26_input to have shape (43164, 17)
but got array with shape (8633, 17)

What can I do in order to obtaing good results?

A: In Sequential modesls  of Deep learning network you can either pass the data with the limited short windows with the stride of changing window or
passing all sequence with 1 dimensional vectors
trainX = trainX.reshape( 43164,1, 17)
trainY = trainY.reshape(43164, 1)

model = Sequential()
model.add(LSTM(2, input_shape=(1, 17)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY[0], epochs=100)

testX.shape # (8633, 17)
testX = testX.reshape(8633,1, 17)


text:
Q: How to find the limit of recursive sequence?
Suppose $a_0 = 0$, $a_1 = 1$, and
  $$ a_{n+1} = a_n+2 a_{n-1}$$
  if $n \ge 1$.
  Find
  $$\lim_{n\rightarrow\infty}\frac{a_{n+1}}{a_n}$$

Usually, what's the approach we use for recursive sequence like this?
I know another type of recursive question with no fraction involved,
but don't know how to do the type with fraction....

A: Here's a completely different approach. Divide the recurrence by $a_n$ to get
$$\frac{a_{n+1}}{a_n}=1+\frac{2a_{n-1}}{a_n}=1+\frac2{a_n/a_{n-1}}\;.\tag{1}$$
If we set $b_n=\dfrac{a_{n+1}}{a_n}$, we can rewrite $(1)$ as $$b_n=1+\frac2{b_{n-1}}\;.\tag{2}$$
Since $a_0=0$ and $a_1=1$, we can't define $b_0$, but $a_2=a_1+2a_0=1$, so $b_1=\dfrac11=1$. Then $b_2=3$, $b_3=\frac53$, $b_4=\frac{11}5$, $b_5=\frac{21}{11}$, $b_6=\frac{43}{21}$, and $b_7=\frac{85}{43}$. This is enough to show a clear pattern: if $b_n=\frac{c_n}{d_n}$ in lowest terms, it appears that
$$c_{n+1}=2c_n+(-1)^{n+1}\tag{3}$$
and
$$d_{n+1}=c_n\;,\tag{4}$$
so that $$b_{n+1}=\frac{c_{n+1}}{d_{n+1}}=\frac{2c_n+(-1)^{n+1}}{c_n}=2-\frac{(-1)^n}{c_n}\;.\tag{5}$$
It's not too hard to use $(2)$ to prove $(3)$ and $(4)$ by induction on $n$. $(3)$ and the fact that $c_1=1$ imply that $\langle c_n:n\in\Bbb Z^+\rangle$ is a strictly increasing sequence of positive integers, and $(5)$ then allows us to calculate $\lim\limits_{n\to\infty}b_n$ very easily.

A: Let $\lim\limits_{n\to \infty}\dfrac{a_{n+1}}{a_n}=l$. Now, $l=\lim\limits_{n\to \infty}\dfrac{a_{n+1}}{a_n}=1+\dfrac{2}{l}$. Thus $l^2=l+2$. The root of this equation gives the limit.

A: I'd use discrete calc to find a direct formula for $a_n$ in terms of just n and then do the limit.
$(E^2)a=(E)a+(2I)a$
where $E$ is a shift operator and $I$ the identity.
then you can solve for the eigenvalue for E
$(E^2-E-2I)a=0$
which factors to
$(E-2I)(E+I)a=0$
so $E=2I$ or $E=-1I$
if $E=bI$ where $b$ is a constant that means $a=c(b^n)$ where $c$ is a evaluated at $n=0$, but since there's two solutions for $E$, we add the two corresponding solutions for $a$
so
$a_n=b(2)^n+c(-1)^n$
and to solve for $b$ and $c$ we just plug in the $n=0$ and $n=1$ values to make two linear equations and solve them.
It's not too hard to show $b=1/3$ and $c=-1/3$
so ultimately $a_n=((2)^n - (-1)^n)/3$
and then you can compute the limit.
remember that the power of two will end up overwhelming the $(-1)^n$ so in the limit $a_n$ is approximately equal to $2^n/3$

A: The recursion is linear, so you can express it as a $2\times2$ matrix  with entries:
$a_{11}=1, a_{12}=2 , a_{21}=1 , a_{22}=0 $ , that maps the $2\times1$-vector ($a_n,a_{n+1}$) to the $2\times1$-vector ($a_{n+1},a_n$). Try diagonalizing the matrix to find a closed form for $a_n$


text:
Q: Создание объектов конструктора, желательно при помощи цикла for Пусть есть конструктор Cat(String colour). Как создать определенное кол-во (пусть 20) объектов этого конструктора (с разными именами: cat1, cat2, ..., catN) и подать на вход случайные цвета? Остальное содержимое конструктора значения не имеет, там константы типа кол-ва лап. Желательно циклом for. Помогите разобраться пожалуйста. Может быть можно в конструкторе тоже сделать автоматически чтобы задавало рандомный цвет из массива заранее созданного в классе конструктора? Это корректно будет?
//Не судите строго, я только учусь, могу писать какие-нибудь глупости

A: Перечисление цветов со статичным методом, который выдаёт случайный цвет:
public enum CatColor {
    BLACK, WHITE, GREY, RED, BLUE;

    private static Random random = new Random();
    private static int colorsCount = values().length;

    public static CatColor getRandomColor() {
        return values()[random.nextInt(colorsCount)];
    }
}

Класс кота:
public class Cat {
    private String name;
    private CatColor color;

    public Cat(String name, CatColor color) {
        this.name = name;
        this.color = color;
    }

    public String getName() {
        return name;
    }

    public CatColor getColor() {
        return color;
    }

    @Override
    public String toString() {
        return "Cat " + name + " has color " + color;
    }
}

main метод:
public static void main(String[] args) {
    List<Cat> cats = new ArrayList<>();
    //создаём котов
    for (int i = 0; i < 20; i++) {
        Cat cat = new Cat("cat"+(i+1), CatColor.getRandomColor());
        cats.add(cat);
    }
    //печатаем котов
    cats.forEach(System.out::println);
}

Вывод:
Cat cat1 has color BLUE
Cat cat2 has color WHITE
Cat cat3 has color BLACK
Cat cat4 has color BLACK
Cat cat5 has color RED
Cat cat6 has color BLUE
Cat cat7 has color WHITE
Cat cat8 has color RED
Cat cat9 has color WHITE
Cat cat10 has color BLUE
Cat cat11 has color RED
Cat cat12 has color WHITE
Cat cat13 has color GREY
Cat cat14 has color WHITE
Cat cat15 has color BLACK
Cat cat16 has color GREY
Cat cat17 has color GREY
Cat cat18 has color BLACK
Cat cat19 has color BLUE
Cat cat20 has color BLACK

A: Массив номеров не нужен - есть ведь счётчик цикла. А добавить его к строке - например, с помощью Integer.ToString()  (или String.valueOf(number), или формировать сложную строку с помощью String.format)
for (int i = 0; i < 20; i++)
       System.out.println("cat" + Integer.toString(i));

и даже работает (IMHO, нехорошо для типизированного языка)
 System.out.println("cat" + i);

По поводу цветов - полностью случайный выбор может привести к генерации очень похожих цветов. Если количество экземпляров ограничено, то разумно создать массив/список не очень близких цветов, и случайно выбирать из него (например, с помощью одной итерации тасования Фишера-Йетса)


text:
Q: Error while exporting to Excel with named sheets Using Mathematica v9.0.1
This example is from the docs:
data1 = Table[{t, 9.8*t^2}, {t, 0, 3, .1}];
data2 = Table[{t, 9.8*t^2}, {t, 0, 5, .2}];
Export["datasets.xlsx", "Sheets" -> {"Experiment 1" -> data1,
                                     "Experiment 2" -> data2}, "Rules"]

Returns:

JLinkJava::argxs: The static method SystemConvertExcelDumpwrite was called with an incorrect number or type of arguments. The arguments, shown here in a list, were {XLSX,C:\Documents and Settings\xxx\datasets.xlsx,{Experiment 1,Experiment 2},{{{0.,0.},{0.1,0.098},<<27>>,{2.9,82.418},{3.,88.2}},{<<1>>}},{{{Null}}},{{{}}},Author->Created by Wolfram Mathematica 9.0 : www.wolfram.com}.

While the following:
Export["datasets.xlsx", {data1, data2}]

works OK, but I need sheet names.
Any idea?

A: The following syntax works for exporting the two sheets:
data1 = Table[{t, 9.8*t^2}, {t, 0, 3, .1}];
data2 = Table[{t, 9.8*t^2}, {t, 0, 5, .2}];
Export["datasets.xlsx", {"Experiment 1" -> data1,
  "Experiment 2" -> data2}]

It creates an XLSX file with two seperate sheets holding the datasets:

However, i agree with the comments above that QA for this is indeed very poor.


text:
Q: DaggerAppComponent not created With dagger 2.10 I used to be able to create the app component by doing
    sAppComponent = DaggerAppComponent.builder()
            .appModule(new AppModule(this))
            .sessionModule(new SessionModule())
            .netModule(new NetModule())
            .dataModule(new DataModule())
            .build();

I was already using the AndroidInjector for Activities and everything was fine.
Now I switched to 2.11 and I can't find the way to create the app component.
In the google tutorial I see:
DaggerYourApplicationComponent.create()
    .inject(this);

to be added in the onCreate of the Application.
In my case DaggerYourApplicationComponent = DaggerAppComponent. The problem is that DaggerAppComponent class isn't created anymore.
I have:
public class App extends android.support.multidex.MultiDexApplication implements HasActivityInjector {
    @Inject DispatchingAndroidInjector<Activity> mDispatchingActivityInjector;
    @Override
    public void onCreate() {
        super.onCreate();

        sAppComponent = DaggerAppComponent.create().inject(this); //here the error

and:
@Singleton
@Component(modules = {
        AppModule.class,
        MainActivityModule.class,
        ...
})
public interface AppComponent {
        void inject(App app);
        ...
}

in the build.gradle file I have:
def daggerVer = 2.11
compile "com.google.dagger:dagger:$daggerVer"
compile "com.google.dagger:dagger-android-support:$daggerVer"
annotationProcessor "com.google.dagger:dagger-android-processor:$daggerVer"

A: With the dependencies listed below everything works:
If you are using Kotlin
apply plugin: 'kotlin-kapt'

dependencies {
    def daggerVer = 2.27 // or latest version

    implementation "com.google.dagger:dagger:$daggerVer"
    implementation "com.google.dagger:dagger-android-support:$daggerVer"
    kapt "com.google.dagger:dagger-android-processor:$daggerVer"
    kapt "com.google.dagger:dagger-compiler:$daggerVer"
}

If you are using Java:
dependencies {
    def daggerVer = 2.27 // or latest version

    implementation "com.google.dagger:dagger:$daggerVer"
    implementation "com.google.dagger:dagger-android-support:$daggerVer"
    annotationProcessor "com.google.dagger:dagger-android-processor:$daggerVer"
    annotationProcessor "com.google.dagger:dagger-compiler:$daggerVer"
}

See google tutorial
You can find the latest release number here.

A: in my case (currently using kotlin)
i use this build gradle
  implementation 'com.google.dagger:dagger:2.24'
  annotationProcessor 'com.google.dagger:dagger-compiler:2.24'
  annotationProcessor 'com.google.dagger:dagger-android-processor:2.24'
  implementation 'com.google.dagger:dagger-android-support:2.24'

after sync gradle,

*

*I quit Android studio (Command + Q).

*Delete folder "build" inside 'app' folder

*reopen Android Studio
DaggerAppComponent created.

A: In Kotlin, we have to add kapt compiler plugin to use Dagger 2.
In your app gradle, add this plugin
apply plugin: 'kotlin-kapt'

And add dependencies as below
dependencies
{
    implementation "com.google.dagger:dagger:$latest_version"
    kapt  "com.google.dagger:dagger-compiler:$latest_version"
    implementation "com.google.dagger:dagger-android:$latest_version"
    kapt  "com.google.dagger:dagger-android-processor:$latest_version"
    implementation "com.google.dagger:dagger-android-support:$latest_version"
    kapt  "com.google.dagger:dagger-android-support:2.12"
}

See Kotlin
  Documentation

A: The latest version of Dagger2 only support below settings in Gradle:
https://github.com/google/dagger#gradle
def daggerVer = 2.24 // or latest version
api "com.google.dagger:dagger:$daggerVer"
annotationProcessor "com.google.dagger:dagger-compiler:$daggerVer"
api "com.google.dagger:dagger-android:$daggerVer"
api "com.google.dagger:dagger-android-support:$daggerVer" // if you use the support libraries
annotationProcessor "com.google.dagger:dagger-android-processor:$daggerVer"


text:
Q: What are the default values for extended slice with negative and positive step What are the default values of start and stop in list slice? Do they change if the step is positive or negative?
For example:
 a = [1,2,3,4,5,6]
 print(a[::1])
 >>> [1, 2, 3, 4, 5, 6]

Above code makes it look that default value of start and stop are 0 and len(a).
But if we use a step = -1
 a = [1,2,3,4,5,6]
 print(a[::-1])
 >>> [5, 4, 3, 2, 1, 0]

Following python documenttation from https://docs.python.org/3/tutorial/introduction.html#strings

Slice indices have useful defaults; an omitted first index defaults to
  zero, an omitted second index defaults to the size of the string being
  sliced.

If that is the case we should get an empty list.
 a = [1,2,3,4,5,6]
 print(a[0:len(a):-1])
 >>> []

 a = "python"
 a[0:len(a):-1]
 >>>> ''


text:
Q: Access props.location object from redux-saga My end goal is to access this.props.location.pathname inside redux-saga when making API calls. Here's my current working solution, albeit with react raising an error. I'm using mxstbr/react-boilerplate-brand as my codebase.
In my wrapping component, App, I have the following line in my render method.
render() {
  this.props.onUpdateLocation(this.props.location)
}

In my mapDispatchToProps I have following. Basically I'm just saving this.props.location into the React store:
function mapDispatchToProps(dispatch) {
  return {
    onUpdateLocation: (location) => {
      dispatch(updateLocation(location));
    },
    dispatch,
  };
}

Inside my redux-saga I access the location from state and just use it as need be; however, here's the error React raises.
warning.js:44 Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.

I can't put it in componentWillMount because that only gets fired once when the app starts, and I can't put it in componentWillUpdate because this.props.location gets updated in the render method. I can't put it in componentDidUpdate because that's too late.
Am I just missing some easy obvious way to access the react-router location inside my redux-saga?

A: if you have <Route path='profile' component={ Profile } />
the Profile component can access the react-router props in the second argument ownProps of:
mapStateToProps(state, [ownProps]) and
mapDispatchToProps(dispatch, [ownProps])

A: TL;DR:
export class App extends React.Component {
  componentWillMount() {
    this.props.onUpdateLocation(this.props.location.pathname);
  }
  componentWillReceiveProps(nextProps) {
    this.props.onUpdateLocation(nextProps.location.pathname);
  }
  render() {
    // Render stuff here
  }
}

function mapDispatchToProps(dispatch) {
  return {
    onUpdateLocation: (location) => {
      dispatch(updateLocation(location));
    },
    dispatch,
  };
}

My reducer receives the action and updates location in the state. Now I can access the current pathname using a selector that grabs location from the state.
Long Answer:
IGL's answer is pretty good info, especially the wildcard naming info that you can use in routes and is returned by the ownProps param of mapDispatchToProps. Here is how I solved the problem...
Initially I thought the warning was about be accessing this.props.location or something else; however, it was a much simpler issue. React doesn't like it when you call a function without it being because of an action like a click. The warning message, which suggest a solution, led me on the right track.
First to see what fired when and where, I placed each of the React lifecycle functions in my code, console logging when they were hit. componentWillMount, componentDidMount, componentWillReceiveProps, shouldComponentUpdate, componentWillUpdate, componentDidUpdate, componentWillUnmount.
I discovered that componentWillMount is fired on initial page load, and componentWillReceiveProps is fired on each navigation. With that in mind, I console logged this.props.location and discovered that componentWillReceiveProps still had the old location; however, it's takes one param, nextProps that has the new location. so, nextProps.location is what I want. I placed this in my App container, which takes other containers as its children, and now I can access the current location in my sagas where I use it to make API calls.


text:
Q: React page rendering blank on refresh Having a bit of trouble with one of my pages on my react site. Whenever I try to reload the Home.js page via refreshing the browser, it shows up blank, but when I use the back navigation button in the browser, it works perfectly fine. I've searched most of the related listings on S.O. but nothing I've tried seems to work. Any help or advice would be greatly appreciated!
App.js
import React, { useContext, useEffect, Fragment } from 'react';
import logo from './logo.svg';
import './App.css';
import { Navigate, Route, Routes, Router, useLocation } from 'react-router-dom';

import LandingPage from './pages/LandingPage';
import 'bulma/css/bulma.min.css';

import BNavbar from './components/b-navbar';
import HomePage from './pages/Home';
import HomeDetailPage from './pages/HomeDetailPage';
import SellPage from './pages/SellPage';
import PropertyAddPage from './pages/PropertyAddPage';
import NetworkingPage from './pages/Networking';
import InvestorDetailPage from './pages/InvestorDetailPage';
import LenderDetailPage from './pages/LenderDetailPage';
import PhotographerDetailPage from './pages/PhotographerDetailPage';
import CheckEmailPage from './pages/CheckEmailPage';
import SignInPage from './pages/SignInPage';
import AboutUsPage from './pages/AboutUsPage';
import AlertBox from './components/b-alertbox';
import ForgotPassword from './pages/Forgot';
import EditProfilePage from './pages/EditProfilePage';
import ProfilePage from './pages/ProfilePage';
import { AuthContext } from './contexts/auth-context';

function App() {
  const { isAuth, user, CheckAuthState, authLoading } = useContext(AuthContext);

  useEffect(() => {
    CheckAuthState()
  }, [])

  function AuthNavigator() {
    return (
      <Fragment>
        <BNavbar user={null} />

        <Routes>
          <Route exact path="/" element={<LandingPage />} />
          <Route path="/about-us" element={<AboutUsPage />} />
          <Route path="/listings" element={<HomePage />} />
          <Route path="/listings/:id" element={<HomeDetailPage />} />
          <Route path="/signin" element={<SignInPage />} />
          <Route path="/forgot" element={<ForgotPassword />} />
          <Route path="/sell" element={<SellPage />} />
          <Route path="/networking" element={<NetworkingPage />} />
          <Route>{'404'}</Route>
        </Routes>
        <AlertBox />
      </Fragment>
    )
  }

  function MainNavigator({ user }) {

    return (

      <Fragment>
        <BNavbar user={user} />
        <Routes>
          <Route exact path="/" element={<LandingPage />} />
          <Route path="/listings" element={<HomePage />} />
          <Route path="/listings/:id" element={<HomeDetailPage />} />
          <Route path="/about-us" element={<AboutUsPage />} />
          <Route path="/sell" element={<SellPage />} />
          <Route path="/property-add" element={<PropertyAddPage />} />
          <Route path="/networking" element={<NetworkingPage />} />
          <Route path="/investor/:id" element={<InvestorDetailPage />} />
          <Route path="/lender/:id" element={<LenderDetailPage />} />
          <Route path="/photographer/:id" element={<PhotographerDetailPage />} />
          <Route path="/check-email" element={<CheckEmailPage />} />
          <Route path="/forgot" element={<ForgotPassword />} />
          <Route path="/edit/profile" element={<EditProfilePage />} />
          <Route path="/profile/:id" element={<ProfilePage />} />
          <Route>{'404'}</Route>
        </Routes>
        <AlertBox />
      </Fragment>
    )
  }
  if (authLoading) {
    return <progress className="progress is-small is-info" max="100">60%</progress>

  }

  return (
    isAuth && !authLoading ?
      <MainNavigator user={user} />
      :
      <AuthNavigator />
  );
}

export default App;

Home.js
import React, { Fragment, useContext, useEffect, useState } from 'react';
import BSearchBar from '../components/b-searchbar';
import GMap from '../components/g-map';
import Home from '../components/Home';
import { DatabaseContext } from '../contexts/database-context';
import '../scss/pages/HomePage.scss'

function HomePage() {
    document.title = 'Λcquired | Search for Properties for sale near you';

    const [propertyListings, setPropertyListings] = useState([]);

    const { listings, GetListing, selectedLocation } = useContext(DatabaseContext);
    let location = localStorage.getItem('location');
    location = JSON.parse(location);

    const mapLocation = selectedLocation || location;

    const [activeTab, setActiveTab] = useState(0);

    const handleChangeIndex = (tab) => {
        setActiveTab(tab)
    }
    const tabs = [
        'Recently Listed',
        'Recently Sold',
    ]

    const getImages = (images) => {
        return Object.values(images)
    }
    useEffect(() => {
        if (listings.length > 0) {
            setPropertyListings(listings);
        }
    }, [listings])

    useEffect(() => {
        GetListing()
    }, [])

    if (!listings) return null;

    return (

                    <BSearchBar className='search-container' isHome={true} navigationPath={'/listings'} placeholder='Enter an address, city, or ZIP code' />

                        {
                            tabs.map((item, index) => {
                                return (

 handleChangeIndex(index)}>{item}

                                )
                            })
                        }

                    <GMap location={location} listing={propertyListings} />

                    {
                        activeTab === 0 &&

                            {
                                propertyListings.filter(item => (item.price !== 'SOLD'))
                                    .map((item, index) => {
                                        return (

                                                <Home
                                                    isHighlighted={mapLocation?.address?.label === item.address}
                                                    address={item.address}
                                                    bathrooms={item.bathrooms}
                                                    bedrooms={item.bedrooms}
                                                    creationDate={item.creationDate}
                                                    description={item.description}
                                                    images={getImages(item.images)}
                                                    postKey={item.key}
                                                    latitude={parseFloat(item.latitude)}
                                                    longitude={parseFloat(item.longitude)}
                                                    postRef={item.postRef}
                                                    postUrl={item.postUrl}
                                                    poster={item.poster}
                                                    price={item.price}
                                                    rawPrice={item.rawPrice}
                                                    squareFeet={item.squareFeet}
                                                    view_Count={item.view_Count}

                                                />

                                        )
                                    })
                            }

                    }
                    {
                        activeTab === 1 &&

                            {
                                propertyListings.filter(item => (item.price === 'SOLD'))
                                    .map((item, index) => {
                                        return (

                                                <Home
                                                    isHighlighted={mapLocation?.address?.label === item.address}
                                                    address={item.address}
                                                    bathrooms={item.bathrooms}
                                                    bedrooms={item.bedrooms}
                                                    creationDate={item.creationDate}
                                                    description={item.description}
                                                    images={getImages(item.images)}
                                                    postKey={item.key}
                                                    latitude={parseFloat(item.latitude)}
                                                    longitude={parseFloat(item.longitude)}
                                                    postRef={item.postRef}
                                                    postUrl={item.postUrl}
                                                    poster={item.poster}
                                                    price={item.price}
                                                    rawPrice={item.rawPrice}
                                                    squareFeet={item.squareFeet}
                                                    view_Count={item.view_Count}

                                                />

                                        )
                                    })
                            }

                    }

    )
}

export default HomePage;

A: The way the map was set up originally was causing the issue. Re-created a new map component that works much better and does not cause any errors when refreshing.


text:
Q: select where column contains exact string table arts column tags - example:
sky, code, earth, codepen
$tag = 'code';
$sql = "select * from arts where tags like ('%" . $tag . "%')";

Result - code, codepen
I need only code in result, i.e somethin like this:
$sql = "select * from arts where tags contains only (' . $tag . ')";

Any help?

A: You can use FIND_IN_SET to check values in a CSV column.
$sql = "select * from arts where FIND_IN_SET('" . $tag . "', tags)";


text:
Q: "Invalid time zone specified" with date-fns-tz in React Native I have an Expo project and use date-fns and date-fns-tz to manipulate time and timezones.
Regarless of the timezone I use (Europe/Paris, UTC, America/New_York'...), I get the following error:

Invalid time zone specified: Europe/Paris

I've tried to copy/paste the example from the documentation, but same thing.
Here is a code snippet:
import { formatDuration, intervalToDuration, parseISO } from "date-fns";
import { formatInTimeZone} from "date-fns-tz";
formatInTimeZone(
      date,
      "Europe/Paris",
      "yyyy-MM-dd HH:mm:ssXXX"
    );

I've tried the solution described here but my app gets errors.
Using "date-fns": "^2.16.1" and     "date-fns-tz": "^1.3.7".

A: i had the same problem with react-native(CLI) and doesn`t achieved to resolve the problem. I saw something about a version of hermes, I think in react-native 0.59 or higher this is solved.


text:
Q: Old React install is having issue compiling NPM 8.6.0
NODE 18
running npm run start
Will get the webpage up and running however will not recompile the components..
Main.js reads as
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';

import App from './components/app';
import reducer from './reducers';

let store = createStore(reducer);

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value.
Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/

ERROR in ./app/Main.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Plugin/Preset files are not allowed to export objects, only functions. In /Users/herbstzu/Desktop/REPOS/MIT_WEBS/tripsharing/node_modules/babel-preset-react/lib/index.js
    at createDescriptor (/Users/xxx/Desktop/REPOS/_WEBS/tripsharing/node_modules/@babel/core/lib/config/config-descriptors.js:211:11)
    at createDescriptor.next (<anonymous>)
    at step (/Users/xxx/Desktop/REPOS/_WEBS/tripsharing/node_modules/gensync/index.js:261:32)
    at /Users/xxx/Desktop/REPOS/_WEBS/tripsharing/node_modules/gensync/index.js:273:13
    at async.call.result.err.err (/Users/xxx/Desktop/REPOS/_WEBS/tripsharing/node_modules/gensync/index.js:223:11)

webpack 5.73.0 compiled with 1 error and 1 warning in 6873 ms

dependencies": {
    "csv": "^6.2.0",
    "d3": "^7.6.1",
    "gsap": "^3.10.4",
    "immutable": "4.1.0",
    "jquery": "^3.6.0",
    "json-loader": "0.5.7",
    "lodash": "4.17.21",
    "rc-slider": "^10.0.0",
    "react": "16.14.0",
    "react-dom": "16.14.0",
    "react-motion": "0.5.2",
    "react-redux": "8.0.2",
    "react-retina-image": "^2.0.5",
    "redux": "^4.2.0",
    "stats-webpack-plugin": "^0.7.0",
    "textures": "^1.2.3",
    "turf": "3.0.5"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "8.2.5",
    "babel-preset-es2015": "6.6.0",
    "babel-preset-react": "6.24.1",
    "babel-preset-stage-2": "6.24.1",
    "grunt": "^1.5.3",
    "grunt-contrib-concat": "~2.1.0",
    "grunt-contrib-nodeunit": "^4.0.0",
    "grunt-contrib-sass": "~2.0.0",
    "grunt-contrib-watch": "^1.1.0",
    "webpack": "^5.73.0",
    "webpack-cli": "^4.10.0",
    "webpack-dev-server": "^4.9.3"
  }


text:
Q: How to print to logger while using pytest on pycharm? I am trying to have my prints be live to stdout but they only print after the test is completed. I am using pycharm and a lot of the solutions I have found are for using the command line. For example if I run this code below it doesnt output the hello's until the test has passed.
output from test
def test():
    for x in range(6):
        print('hello')

A: Add assert 0 at the end of the test. It will fail and pytest will print what you need in the report.
You can also check this one How can I see normal print output created during pytest run?


text:
Q: Maven plugin not running in Eclipse on install I want to add 2 *.sql files to be imported to database on building project with Maven.
When I launch "clean install" on my project, plugin is not being executed. I can't figure out what is going wrong. Shouldn't plugin be executed if I run "install" and my plugin has "install" goal ? Can anyone point out what is wrong and how to achieve the result I want? Here is my configuration, settings screenshot and output of "clean install" command:
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>
  <groupId>voip-web</groupId>
  <artifactId>voip-web-server</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <org.springframework.version>3.2.1.RELEASE</org.springframework.version>
  </properties>
  <dependencies>
    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <!-- Hibernate resources -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.2.11.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.2.11.Final</version>
    </dependency>
    <!-- JSP Tag -->
    <dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.1.2</version>
    </dependency>
    <!-- dependency to fix JSPServletException -->
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>jsp-api</artifactId>
        <version>6.0.32</version>
        <scope>provided</scope>
    </dependency>
    <!-- Apache Commons FileUpload -->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
    </dependency>
    <!-- Apache Commons IO -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>
    <!-- For messages and locale -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.3.2</version>
    </dependency>
    <!-- MySQL -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>
    <!-- Log4j -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.14</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
    <!-- Http Servlet -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>
    <!-- Jackson JSON Mapper -->
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.10</version>
    </dependency>
    <!-- JUnit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.scala-lang</groupId>
        <artifactId>scala-library</artifactId>
        <version>2.10.4</version>
    </dependency>
    <!-- For integrating schema -->
    <dependency>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>sql-maven-plugin</artifactId>
        <version>1.5</version>
    </dependency>
  </dependencies>
  <build>
    <testSourceDirectory>src/test/java</testSourceDirectory>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
      <resource>
        <directory>src/main/webapp</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.3</version>
        <configuration>
          <failOnMissingWebXml>true</failOnMissingWebXml>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>sql-maven-plugin</artifactId>
        <version>1.5</version>
        <dependencies>
          <!-- specify the dependent JDBC driver here -->
          <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
          </dependency>
        </dependencies>
        <!-- common configuration shared by all executions -->
        <configuration>
          <driver>com.mysql.jdbc.Driver</driver>
          <url>jdbc:mysql://localhost:3306/voip-web?autoReconnect=true</url>
          <username>root</username>
          <password>root</password>
        </configuration>

        <executions>

          <execution>
            <id>id.default-cli</id>
             <phase>default-cli</phase>
             <goals>
              <goal>install</goal>
             </goals>
            <!-- specific configuration for this execution -->
            <configuration>
              <!-- specify your SQL commands, can be all of the following configurations -->
              <echo
                            message="########### Creating Voip Web Database ##############"
              />
              <orderFile>ascending</orderFile>
              <autocommit>true</autocommit>
              <srcFiles>
                <srcFile>${basedir}/src/main/sql/2015-01-03-asterisk-db.sql</srcFile>
                <srcFile>${basedir}/src/main/sql/2015-01-04-voip-web.sql</srcFile>
              </srcFiles>
              <echo
                             message="##################### END ########################"
              />
            </configuration>
          </execution>

        </executions>
      </plugin>
    </plugins>
  </build>
</project>

Eclipse settings screenshot

Maven output:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building voip-web-server 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.4.1:clean (default-clean) @ voip-web-server ---
[INFO] Deleting C:\EclipseKeplerJEE\myprojects\workspace\voip-web-server\target
[INFO]
[INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ voip-web-server ---
[debug] execute contextualize
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 4 resources
[INFO] Copying 44 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ voip-web-server ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 11 source files to C:\EclipseKeplerJEE\myprojects\workspace\voip-web-server\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.5:testResources (default-testResources) @ voip-web-server ---
[debug] execute contextualize
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ voip-web-server ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to C:\EclipseKeplerJEE\myprojects\workspace\voip-web-server\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.10:test (default-test) @ voip-web-server ---
[INFO] Surefire report directory: C:\EclipseKeplerJEE\myprojects\workspace\voip-web-server\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.nikzgs.voip.web.entity.test.CallTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.094 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] --- maven-war-plugin:2.3:war (default-war) @ voip-web-server ---
[INFO] Packaging webapp
[INFO] Assembling webapp [voip-web-server] in [C:\EclipseKeplerJEE\myprojects\workspace\voip-web-server\target\voip-web-server-0.0.1-SNAPSHOT]
[INFO] Processing war project
[INFO] Copying webapp resources [C:\EclipseKeplerJEE\myprojects\workspace\voip-web-server\src\main\webapp]
[INFO] Webapp assembled in [968 msecs]
[INFO] Building war: C:\EclipseKeplerJEE\myprojects\workspace\voip-web-server\target\voip-web-server-0.0.1-SNAPSHOT.war
[INFO]
[INFO] --- maven-install-plugin:2.3.1:install (default-install) @ voip-web-server ---
[INFO] Installing C:\EclipseKeplerJEE\myprojects\workspace\voip-web-server\target\voip-web-server-0.0.1-SNAPSHOT.war to C:\Users\Nikita\.m2\repository\voip-web\voip-web-server\0.0.1-SNAPSHOT\voip-web-server-0.0.1-SNAPSHOT.war
[INFO] Installing C:\EclipseKeplerJEE\myprojects\workspace\voip-web-server\pom.xml to C:\Users\Nikita\.m2\repository\voip-web\voip-web-server\0.0.1-SNAPSHOT\voip-web-server-0.0.1-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 7.432s
[INFO] Finished at: Sat Jan 10 17:08:06 EET 2015
[INFO] Final Memory: 15M/37M
[INFO] ------------------------------------------------------------------------


text:
Q: z-index IE8 not working, while in FF it is i'm stuck with a problem related to z-index in IE8.
Here's the fiddle:
http://fiddle.jshell.net/uFPBz/show/
The first problem is that the issue I want to show you is working in the fiddle, there's something I can't see that is fixing it.
However, if I save that entire fiddle page and open in IE8, the problem comes back. So, i'm like WTF?
When you mouseover the preview image, a bigger one shows up. But the bottom of this LARGER PREVIEW hides behind the SMALL IMAGE of the BOX that is below the mouseover'd Box.
This only happens in IE8, the largerPreviewBox has z-index of 3, while the ImgThumbBox has z-index of 2.
Reading this: http://caffeineoncode.com/2010/07/the-internet-explorer-z-index-bug/ and this IE 6 & IE 7 Z-Index Problem I see it these z-index properties are irrelevant because they are in other levels. But I don't know how to fix it.
Will be better if you download the HTML and see it by yourself:
http://www.filefactory.com/file/417sp9zi1lhp/n/HTML_Error_tar_gz
Thanks a lot!
Edit:
Image of the problem:

A: update the doctype
it will work fine.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

i tested on ie8
else you can press f12 and check your browser mode and document mode :-)

A: You can accomplish your task only with CSS and with less HTML lines. See the JSFiddle.
In your case the HTML is:

and you can use this CSS:
div.container{
  position:relative;
  display:inline-block;
  float:left;
  width: 122px;
  height: 160px; }
div.container > img {
  position:relative;
  width: 122px;
  height: 160px;
  display:block;}

div.container > img:hover {
  position: absolute;
  left: 50%;
  margin-left: -150px;
  top: 50%;
  margin-top: -175px;

  width: 300px;
  height: 350px;
  border:1px solid black;
  //use other styles....
}


text:
Q: Python Snappy is already installed, as part of zip deployed but throws error on AWS lambda We are using Python 3.9 and installed the package "python-snappy" The code works fine in decompressing avro format on local. However - AWS lambda throws following error:
[ERROR] valueError: snappy codec is supported but you need to install python-snappy.
I faced same error on local before installing python-snappy but after installing the package, the error is resolved. I zipped the same package on local including python snappy and deployed on AWS lambda
Tried manual deployment
automatic deployment using terraform with requirements.txt

A: It could be differences between the runtime environment of the local machine and the AWS Lambda Runtime environment.
Assuming that the runtime is different. Have you tried using AWS SAM with --use-container option? The dependencies will be build to suit the target AWS Lambda Runtime.


text:
Q: Which is better - components on both sides or components on one side of the PCB? I am working on a PCB design. 50k PCBs will be produced.
SMD components: 100
Through-hole components: 25
I need to minimize PCB size. There are no high-speed signals or sensitive signals in the design.
I have two options:

*

*Components on single-side PCB with multilayer (4 or higher) layout

*Components on both (double side) sides of PCB with 2 layer layout
I need to clarify which costs less in production.

A: PCB size is not the only cost consideration and you need to consider recurring costs vs. one time (non-recurring) costs (some of the non-recurring may actually occur more than once for a 50k run).
Note that using double sided techniques rarely (if ever) yield a PCB half the size of a single sided part - in my experience you may get one that is perhaps 40% smaller if it is given lots of attention.
The non-recurring costs associated with PCBs includes the cost of tooling and the cost of solder stencils (which really are not that expensive although with a run of 50k you may need to use new ones after a certain number of runs which is very specific to the actual PCB).
Also in this category is test tooling which does have a certain amount of volume costs (50k boards will require the test tooling to have a certain amount of maintenance).
Another non-recurring cost is the fabrication and assembly documentation; poor documentation will incur recurring costs as you will be constantly fielding calls from the assembler and the specifics of the PCB may not be as controlled as you need. I suggest using the guidelines from IPC-D-326 (which incorporates IPC-D-325).
Recurring costs are:
Fabrication
Number of layers
Size (panelizing can reduce this depending on the specifics of the PCB)
Number of drill holes (often forgotten but can be a major cost driver)
Size of drill holes (to minimise costs keep the aspect ratio - the thickness of the PCB to the diameter of the drill - no higher than 8:1 and no smaller than 0.3mm)
The quality of the material (in particular Tg) as identified from IPC-4101. If you have high via densities you will need a relatively high Tg or you risk breaking the via barrels; this is a very common 'gotcha' that can destroy yields at assembly (the bare PCB test will not pick this up as it will only show up post reflow - the time above Tg is critical).
The PCB class (as identified from IPC-A-600)
Assembly
The assembly class as identified from IPC-A-610.
The number of passes through reflow and perhaps in your case selective soldering; basically there is a recurring cost for each process step required. You should also keep in mind that if a cleaning process is applied, it will normally be done for each pass through soldering.
The number of boards in a single panel; the more the better, in general (so you get more PCBs through for each process step although pick and place will have a higher cost but that is usually small compared to the gains from fitting more PCBs per panel).
Component density has an impact here as well; there will inevitably be some waste of components (usually the smaller parts) and the higher the density the higher that waste is typically.
Testing.
An automated test will have a non-recurring cost for the implementation and the lowest possible recurring cost (apart from no test at all). In terms of cost, it increases as you go from automated -> unskilled test labour -> skilled test labour on a per unit time basis.
There are other issues but these are the main ones in my experience and there is no single (or simple) answer; it depends on the specifics of your PCB. In the past where I have had the space for a single sided unit I have had the design done for both single sided and double sided design (incurring another non-recurring cost at the design stage) for high volume applications and sent both for quotations and the result can often be quite surprising.
In one case (where the design was always going to be double sided due to space constraints), the overall cost of fabrication and assembly was lower (by about 20%) when I increased the layer count from 14 to 18.
This significantly reduced the via count and eliminated high aspect ratio drills (the lower layer count had aspect ratios of up to 12 - the higher layer count maxed out at 10) and had the serendipitous effect of enhanced signal integrity (as I was able to use single layer routing for the majority of high speed signals).
[The methods required to run high speed signals across multiple layers while minimising losses is beyond the scope of this answer - suffice to say they are quite involved and use up more space than would otherwise be necessary]


text:
Q: iPhone - Memory leaks in NSSortDescriptor I am receiving memory leaks using the following code:
Interface:
@property (nonatomic, retain) NSArray *sortedItems;

Implementation:
NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"ScannedDate" ascending:NO] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [self.items sortedArrayUsingDescriptors:sortDescriptors];
self.sortedItems = [NSArray arrayWithArray:sortedArray]; // memory leak 100% here

- (void)viewDidUnload {
  self.sortedItems = nil;
  [super viewDidUnload];
}

- (void)dealloc {
  [sortedItems release];
  [super dealloc];
}

A: Well, you are creating two unnecessary arrays.
Replace this:
NSArray *sortedArray = [self.items sortedArrayUsingDescriptors:sortDescriptors];
self.sortedItems = [NSArray arrayWithArray:sortedArray]; // memory leak 100% here

... with this:
self.sortedItems = [self.items sortedArrayUsingDescriptors:sortDescriptors];

Every time you create an array, you send a retain to the objects held by the array. If the array is autoreleased (which the convenience methods above do create) then the point at which their release messages is sent is uncontrolled by the programmer. This can produce apparent leaks depending on circumstances at runtime.