text:
Q: CAST number as varchar, then update into another table as date I'll as brief as possible, but start by saying I'm a network guy, not a DBA.
SQL Server Enterprise 11.0.5343
Scenario - Need to get three columns (each with a part of a date) together, and then update another table with the full date.
Source table: UT210AP
Columns:
  UTONMM (Utility On Month - 2 digit)
  UTONDD (Utility On Day - 2 digit)
  UTONYY (Utility On Year - 2 digit)
  UTONCV (Utility On Century - 0 = 19xx, 1 = 20xx)

I can select the data into a "date" with this code (the source data is on an IBM AS/400 linked server)
CAST(UTONMM as varchar) + '/' +
CAST(UTONDD as varchar) + '/' +
CASE WHEN UTONCV = '1'
THEN
RIGHT('20' + CONVERT(varchar(4), RIGHT('00' + CONVERT(varchar(4),UTONYY),2)),4)
ELSE
RIGHT('19' + CONVERT(varchar(4), UTONYY),4)
END AS UTON

And I get these results in the column I named "UTON":
4/6/1994
7/1/1988
11/14/1990
6/6/2014

QUESTION:
I have a nightly import job that runs, and I need to get the "date" (like 4/6/1994) into a field called TIME_CONNECT as part of this update statement from the job:
Update [responder].[Temp_RX_CUSTOMERS]
set CustomerID = lf.UTCSID
from [responder].[Temp_RX_CUSTOMERS] LEFT Outer Join
[HTEDTA].[THOR].[HTEDTA].UT210AP lf ON [responder].[Temp_RX_CUSTOMERS].LocationID = lf.UTLCID
where lf.UTOFMM = 0

The "UTOFMM" in the code above is "Utility Off Month", I don't even care about checking for it's value, I just want to get the "UTON" date from the top select statement into the "TIME_CONNECT" field in the "Temp_RX_CUSTOMERS" field.

A: Is this what you want?  This copies the value into the field, assuming time_connect is a string.
Update [responder].[Temp_RX_CUSTOMERS]
set CustomerID = lf.UTCSID,
    time_connect = (CAST(UTONMM as varchar) + '/' +
                    CAST(UTONDD as varchar) + '/' +
                    (CASE WHEN UTONCV = '1'
                          THEN RIGHT('20' + CONVERT(varchar(4), RIGHT('00' + CONVERT(varchar(4),UTONYY),2)),4)
                          ELSE RIGHT('19' + CONVERT(varchar(4), UTONYY),4)
                    END)
                   )
from [responder].[Temp_RX_CUSTOMERS] LEFT Outer Join
     [HTEDTA].[THOR].[HTEDTA].UT210AP lf
     ON [responder].[Temp_RX_CUSTOMERS].LocationID = lf.UTLCID
where lf.UTOFMM = 0;

If time_connect is a date/datetime data type, you can use datefromparts() (available in SQL Server 2012+):
Update [responder].[Temp_RX_CUSTOMERS]
set CustomerID = lf.UTCSID,
    time_connect = DATEFROMPARTS(1800 + UTONCV * 100 + UNONYY,
                                 UTONMM, UTONDD)
from [responder].[Temp_RX_CUSTOMERS] LEFT Outer Join
     [HTEDTA].[THOR].[HTEDTA].UT210AP lf
     ON [responder].[Temp_RX_CUSTOMERS].LocationID = lf.UTLCID
where lf.UTOFMM = 0;


text:
Q: Facebook Swift SDK compile error when migrate to Swift 3 Due to iOS 10, I need to update Xcode to version 8 and Swift 3. There are many compile errors. Spend long hours to trace one by one and eventually there is one I don't know how to fix. Please help.
From the file
FacebookCore | GraphRequestConnection.swift
public func add<T: GraphRequestProtocol>(
_ request: T,
batchParameters: [String : AnyObject]?,
completion: ((_ connectionHTTPResponse: HTTPURLResponse?, _ result: GraphRequestResult<T>) -> Void)? = nil) {
sdkConnection.add(request.sdkRequest,
                  completionHandler: completion.map(sdkRequestCompletion),  // compile error here
                         batchParameters: batchParameters)

}

Error Message: Cannot convert call result type '_?' to expected type 'FBSDKGraphRequestHandler!'

I updated the line to
completion.map(sdkRequestCompletion) as! FBSDKGraphRequestHandler!

but cause segmentation error.
Any advise?
Thanks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Maximize over vector with conditional expression I am unable to maximize a function containing an If statement and a vector variable. To give an MWE (not my original problem), consider the following:
x = {x1, x2};
Maximize[If[x[[2]] == 1, 1, -x[[1]]^2], x]

This returns no error, but returns
Maximize[If[x2 == 1, 1, -x[[1]]^2], {x1, x2}]

As you can see, it refuses to convert the second vector element to x1. If I do that manually by entering
x = {x1, x2};
Maximize[If[x[[2]] == 1, 1, -x1^2], x]

then it easily spits out
{1, {x1 -> 33/10, x2 -> 1}}

Can anybody offer me some insight into what's going on here? Is there a way to tweak it that doesn't involve manual rewriting? (If I have to type out all vector operations, it's going to be a long ugly formula...)

A: You'll want to use Piecewise[] to represent your function, Indexed[] to extract coordinates, and FullRegion[2] as the search domain. Thus:
Maximize[Piecewise[{{1, Indexed[x, 2] == 1}}, -Indexed[x, 1]^2], x ∈ FullRegion[2]]
   {1, {x -> {33/10, 1}}}


text:
Q: Python: Optimizing a tree evaluator I know tree is a well studied structure.
I'm writing a program that randomly generates many expression trees and then sorts and selects by a fitness attribute.
I have a class MakeTreeInOrder() that turns the tree into a string that 'eval' can evaluate.
but it gets called many many times, and should be optimized for time.
below is a function that builds a tree that adds successive numbers to use as a test.
I was wondering if there is an optimized way to evaluate an expression that is in a tree structure. I figured that
that it's used quite a bit and somebodys already done this.
import itertools
from collections import namedtuple

#Further developing Torsten Marek's second suggestion

KS = itertools.count()
Node = namedtuple("Node", ["cargo", "args"])

def build_nodes (depth = 5):
    if (depth <= 0):
        this_node = Node((str(KS.next())), [None, None])
        return this_node
    else:
        this_node = Node('+', [])
        this_node.args.extend(
          build_nodes(depth = depth - (i + 1))
          for i in range(2))

        return this_node

The following is the code that I think can be made a lot faster. And I was hoping for some ideas.
class MakeTreeInOrder(object):
    def __init__(self, node):
        object.__init__(self)
        self.node = node
        self.str = ''
    def makeit(self, nnode = ''):
        if nnode == '':
            nnode = self.node
        if nnode == None: return
        self.str +='('
        self.makeit(nnode.args[0])
        self.str += nnode.cargo
        self.makeit(nnode.args[1])
        self.str+=')'
        return self.str

def Main():
    this_tree = build_nodes()
    expression_generator = MakeTreeInOrder(this_tree)
    this_expression = expression_generator.makeit()
    print this_expression
    print eval(this_expression)

if __name__ == '__main__':
    rresult = Main()

A: Adding a touch of object orientation here makes things simpler. Have subclasses of Node for each thing in your tree, and use an 'eval' method to evaluate them.
import random

class ArithmeticOperatorNode(object):
    def __init__(self, operator, *args):
        self.operator = operator
        self.children = args
    def eval(self):
        if self.operator == '+':
            return sum(x.eval() for x in self.children)
        assert False, 'Unknown arithmetic operator ' + self.operator
    def __str__(self):
        return '(%s)' % (' ' + self.operator + ' ').join(str(x) for x in self.children)

class ConstantNode(object):
    def __init__(self, constant):
        self.constant = constant
    def eval(self):
        return self.constant
    def __str__(self):
        return str(self.constant)

def build_tree(n):
    if n == 0:
        return ConstantNode(random.randrange(100))
    else:
        left = build_tree(n - 1)
        right = build_tree(n - 1)
        return ArithmeticOperatorNode('+', left, right)

node = build_tree(5)
print node
print node.eval()

To evaluate the tree, just call .eval() on the top level node.
node = build_tree(5)
print node.eval()

I also added a __str__ method to convert the tree to a string so you can see how this generalizes to other tree functions. It just does '+' at the moment, but hopefully it's clear how to extend this to the full range of arithmetic operations.

A: Your example imports numpy and random but never uses them. It also has a "for i in range(2))" with no body. This is clearly not valid Python code.
You don't define what 'cargo' and the nodes are supposed to contain. It appears that 'cargo' is a number, since it comes from itertools.count().next(). But that makes no sense since you want the result to be a eval'able Python string.
If you are doing a one-time evaluation of the tree then the fastest solution would be to evaluate it directly in-place, but without an actual example of the data you're working with, I can't show an example.
If you want to make it even faster then look further upstream. Why do you generate the tree and then evaluate it? Can't you evaluate the components directly in the code which currently generates the tree structure? If you have operators like "+" and "*" then consider using operator.add and operator.mul instead, which can work directly on the data without using an intermediate step.
==update==
This builds on Paul Hankin's answer. What I've done is taken away the intermediate tree structure and just evaluate the expression directly.
def build_tree2(n):
    if n == 0:
        return random.randrange(100)
    else:
        left = build_tree2(n-1)
        right = build_tree2(n-1)
        return left+right

That clocks at about 5 times faster than Paul's solution.
It may be that you need to know the actual tree structure of the best solution, or the top k of N, where k << N. If that's the case then you can post-hoc regenerate those trees if you also keep track of the RNG state used to generate the results. For example:
def build_tree3(n, rng=random._inst):
    state = rng.getstate()
    return _build_tree3(n, rng.randrange), state

def _build_tree3(n, randrange):
    if n == 0:
        return randrange(100)
    else:
        left = _build_tree3(n-1, randrange)
        right = _build_tree3(n-1, randrange)
        return left+right

Once you've found the best values, use the key to regenerate the tree
# Build Paul's tree data structure given a specific RNG
def build_tree4(n, rng):
    if n == 0:
        return ConstantNode(rng.randrange(100))
    else:
        left = build_tree4(n-1, rng)
        right = build_tree4(n-1, rng)
        return ArithmeticOperatorNode("+", left, right)

# This is a O(n log(n)) way to get the best k.
# An O(k log(k)) time solution is possible.
rng = random.Random()
best_5 = sorted(build_tree3(8, rng) for i in range(10000))[:5]
for value, state in best_5:
    rng.setstate(state)
    tree = build_tree4(8, rng)
    print tree.eval(), "should be", value
    print "  ", str(tree)[:50] + " ..."

Here's what it looks like when I run it
10793 should be 10793
   ((((((((92 + 75) + (35 + 69)) + ((39 + 79) + (6 +  ...
10814 should be 10814
   ((((((((50 + 63) + (6 + 21)) + ((75 + 98) + (76 +  ...
10892 should be 10892
   ((((((((51 + 25) + (5 + 32)) + ((40 + 71) + (17 +  ...
11070 should be 11070
   ((((((((7 + 83) + (77 + 56)) + ((16 + 29) + (2 + 1 ...
11125 should be 11125
   ((((((((69 + 80) + (11 + 64)) + ((33 + 21) + (95 + ...


text:
Q: saving entities with many to one relationships I have the following entities
@Entity
public class Session{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    private String name;
    @OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, orphanRemoval=true)
    @JoinColumn(name="session_id", referencedColumnName="id")
    private List<SessionChart> sessionCharts;

    public List<SessionChart> getSessionCharts() {
        return sessionCharts;
    }

    public void setSessionCharts(List<SessionChart> sessionCharts) {
        this.sessionCharts = sessionCharts;
    }
}

and an entity
@Entity
@Table(name="session_chart")
public class SessionChart implements  {

    @Transient
    private boolean isActive = false;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    private String chartName;
}

suppose i have retrieved my sessioncharts from a specific session
List<SessionChart> mySessionCharts = new ArrayList<SessionChart>();
mySessionCharts = session.getSessionCharts();

and in my code I change the name of one sessionChart. If I save the session(merge) entity then the sessionCharts ArrayList will be updated. My question is the following:
Can I save just the SessionChart object from the list without saving the session? Will it work if i delete a session chart and just remove it from the ArrayList?
I am using jpa hibernate and EntityManager and EntityManagerFactory to do the database transactions.

A:
Can I save just the SessionChart object from the list without saving the session?

Yes, that is possible as long as the entities are still managed and your transaction is still alive. So this code will work:
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Session session = em.find(Session.class, 1);
List<SessionChart> mySessionCharts = session.getSessionCharts();
for (SessionChart sessionChart : mySessionCharts) {
    sessionChart.setChartName("test"); // this will update each session chart name in the DB
}
em.getTransaction().commit();
em.close();

Will it work if i delete a session chart and just remove it from the ArrayList?

I'm not sure if I understand your question, but here's the thing: if you just remove just the SessionChart object from the collections object, then call on em.merge(session), this will just unlink the SessionChart object from its parent Session. Example below:
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Session session = em.find(Session.class, 1);
List<SessionChart> sessionChartList = session.getSessionCharts();
sessionChartList.remove(0); // remove the first object from the list
em.merge(session);
em.getTransaction().commit();

This will result to an SQL update on the session_chart table:
update
    session_chart
set
    session_id=null
where
    session_id=1
    and id=1

You still have to invoke em.remove(sessionChart) to explicitly remove it from the DB.


text:
Q: Ajax on Success redirect URL from controller Current Page is Add.phtml..when click saves button, it should be redirected to index.phtml..the URL for index page already inside a controller.
but I can't make it..can anyone point me which part is wrong?
JS inside add.phtml
function addMembAndAppDetail(){
        var m_register = 0;
        if($('input[name="register"]').is(':checked'))
        {
             m_register = 1;
        }
        var m_active = 0;
        if($('input[name="status"]').is(':checked'))
        {
            m_active = 1;
        }

        $.ajax({
            url: '/membership/membership-setup/ajax-add-multiple/',
            type: 'POST',
            async : false,
            data: {
                        'm_owner' : $('#m_owner').val(),

            },
            dataType: 'json',
            success: function(response){
                 window.location.href = response.url;
            }
        });
    }

Inside Controller
    public function ajaxAddMultipleAction(){

        $auth = Zend_Auth::getInstance();
        $data = array(
            'm_owner' => $this->_getParam('m_owner', null)
        );

        $membershipDb = new Membership_Model_DbTable_TblMembership();
        $membershipDb->addData($data);

        $this->_helper->flashMessenger->addMessage(array('success' => "Record saved"));
        $url = $this->_redirect($this->baseUrl . '/membership/membership-setup/index');

        echo json_encode(array('msg'=>"Success.", 'url'=>$url, 'status'=>true));
    }

A: You just returning the url but you never used it. if your url is valid then you can change your success method to redirect the client
success: function(response){
    window.location.href = response.url
}

Edit
I tested out your ajax call and it looks like that if you remove dataType: 'json' it works perfectly. I don't know why it cause the issue but after removing it it should work.
anyways dataType default value is Intelligent Guess so it will guess the data type automatically for you


text:
Q: South custom models location I have quite a big django project which has a lot of applications and a lot of models.
In order to avoid circular imports several models modules must be used:
app/models.py
app/models_add.py
app/models_aux.py

and so on.
Each time I have to make a migration I have to write
from app.models_add import Model

in the app/models.py in order for South to track the model's changes.
This seems to be quite annoying because there are a lot of changes in models.
The question is: is there a way to point South which modules/files to track?

A: You could try setting the app_label on the Meta class of your model.
class Meta:
    app_label = "app"

Also try setting your directory structure to:
app/models/__init__.py
app/models/add.py

That should tell everything to initialize properly. This is what I recently did, but for backwards compatibility in other areas of my project I import everything in models/__init__.py


text:
Q: Minimize sum of product of two uneven consecutive arrays I've got an optimization problem in which I need to minimize the sum product of two uneven but consecutive arrays, say:
A = [1, 2, 3]
B = [4, 9, 5, 3, 2, 10]

Shuffling of values is not allowed i.e. the index of the arrays must remain the same.
In other words, it is a distribution minimization of array A over array B in consecutive order.
Or: Given that len(B)>=len(A) Minimize the sum product the values of Array A of length n over n values of array B without changing the order of array A or B.
In this case, the minimum would be:
min_sum = 1*4 + 2*3 + 3*2 = 16

A brute force approach to this problem would be:
from itertools import combinations

sums = [sum(a*b for a,b in zip(A,b)) for b in combinations(B,len(A))]
min_sum = min(sums)

I need to do this for many sets of arrays however. I see a lot of overlap with the knapsack problem and I have the feeling that it should be solved with dynamic programming. I am stuck however in how to write an efficient algorithm to perform this.
Any help would be greatly appreciated!

A: Having two lists
A = [1, 2, 3]
B = [4, 9, 5, 3, 2, 10]

the optimal sum product can be found using:
min_sum = sum(a*b for a,b in zip(sorted(A), sorted(B)[:len(A)][::-1]))

In case A is always given sorted, this simplified version can be used:
min_sum = sum(a*b for a,b in zip(A, sorted(B)[:len(A)][::-1]))

The important part(s) to note:

*

*You need factors of A sorted. sorted(A) will do this job, without modifying the original A (in contrast to A.sort()). In case A is already given sorted, this step can be left out.

*You need the N lowest values from B, where N is the length of A. This can be done with sorted(B)[:len(A)]

*In order to evaluate the minimal sum of products, you need to multiply the highest number of A with the lowest of B, the second hightst of A with the second lowest of B. That is why after getting the N lowest values of B the order gets reversed with [::-1]
Output
print(min_sum)
# 16
print(A)
# [1, 2, 3]              <- The original list A is not modified
print(B)
# [4, 9, 5, 3, 2, 10]    <- The original list B is not modified

A: With Python, you can easily sort and flip sets. The code you are looking for is
A, B = sorted(A), sorted(B)[:len(A)]
min_sum = sum([a*b for a,b in zip(A, B[::-1])])

A: You may need to get the values one by one from B, and keep the order of the list by having each value assigned to a key.
A = [1, 3, 2]
B = [4, 9, 5, 3, 2, 10]

#create a new dictionary with key value pairs of B array values
new_dict = {}
j=0
for k in B:
    new_dict[j] = k
    j+= 1

#create a new list of the smallest values in B up to length of array A
min_Bmany =[]
for lp in range(0,len(A)):
    #get the smallest remaining value from dictionary new_dict
    rmvky=  min(zip(new_dict.values(), new_dict.keys()))

    #append this item to minimums list
    min_Bmany.append((rmvky[1],rmvky[0]))
    #delete this key from the dictionary new_dict
    del new_dict[rmvky[1]]

#sort the list by the keys(instead of the values)
min_Bmany.sort(key=lambda r: r[0])

#create list of only the values, but still in the same order as they are in original array
min_B =[]
for z in min_Bmany:
    min_B.append(z[1])

print(A)
print(min_B)

ResultStr = ""
Result = 0

#Calculate the result
for s in range(0,len(A)):
    ResultStr = ResultStr + str(A[s]) +"*" +str(min_B[s])+ " + "
    Result = Result + A[s]*min_B[s]

print(ResultStr)
print("Result = ",Result)

The output will be as follows:
A = [1, 3, 2]
B = [4, 9, 5, 3, 2, 10]
1*4 + 3*3 + 2*2 +
Result =  17

Then change the A, and the output becomes:
A = [1, 2, 3]
B = [4, 9, 5, 3, 2, 10]
1*4 + 2*3 + 3*2 +
Result =  16

A: Not sure if this is helpful, but anyway.
This can be formulated as a mixed-integer programming (MIP) problem. Basically, an assignment problem with some side constraints.
  min sum((i,j),x(i,j)*a(i)*b(j))
      sum(j, x(i,j)) = 1    ∀i        "each a(i) is assigned to exactly one b(j)"
      sum(i, x(i,j)) ≤ 1    ∀j        "each b(j) can be assigned to at most one a(i)"
      v(i) = sum(j, j*x(i,j))         "position of each a(i) in b"
      v(i) ≥ v(i-1)+1       ∀i>1      "maintain ordering"
      x(i,j) ∈ {0,1}                  "binary variable"
      v(i) ≥ 1                        "continuous (or integer) variable"

Example output:
----     40 VARIABLE z.L                   =       16.000

----     40 VARIABLE x.L  assign

            j1          j4          j5

i1       1.000
i2                   1.000
i3                               1.000

----     40 VARIABLE v.L  position of a(i) in b

i1 1.000,    i2 4.000,    i3 5.000

Cute little MIP model.
Just as an experiment I generated a random problem with len(a)=50 and len(b)=500. This leads to a MIP with 650 rows and 25k columns. Solved in 50 seconds (to proven global optimality) on my slow laptop.

A: It turns out using a shortest path algorithm on a direct graph is pretty fast. Erwin did a post showing a MIP model. As you can see in the comments section there, a few of us independently tried shortest path approaches, and on examples with 100 for the length of A and 1000 for the length of B we get optimal solutions in the vicinity of 4 seconds.

A: The graph can look like:

Nodes are labeled n(i,j) indicating that visiting the node means assigning a(i) to b(j). The costs a(i)*b(j) can be associated with any incoming (or any outgoing) arc. After that calculate the shortest path from src to snk.
BTW can you tell a bit about the background of this problem?


text:
Q: Parse timezone int to string (timezone name) (facebook api) How do you convert a timezone from int to string (etc: Europe/Stockholm)?
I'm using Facebooks PHP api and that returns ["timezone"] => int(2). How am I suppose to parse that?

A:
How do you convert a timezone from int to string (etc: Europe/Stockholm)?

You can't.  Read "Time Zone != Offset" in the timezone tag wiki.
Facebook's documentation explains that the timezone field is the user's timezone offset from UTC.
What it doesn't make clear, but I have found through experimentation, is that it is not necessarily the user's current offset, but it instead it is the offset as of the user's last log in.  If the user changes time zones, or daylight saving time begins or ends, that will not be reflected in the Facebook data until the user's next log in.
See also these posts:

*

*Facebook API, timezone and country

*FaceBook Time zone and Event Times

A: You can get the timezone name by using timezone_name_from_abbr("", $value*3600, false);. $value is the timezone offset you get from Facebook.
Thanks to minaz.


text:
Q: Bind values in JSP without converting to string? UPDATE: looks like spring:bind does work for some collections - it might be a problem with my model, causing it not to recognise certain collections. When I've got to the bottom of this I'll update my question and/or provide an answer.

The spring:bind tag is useful for accessing values in order to print them on the page or as a form field value, e.g.
<spring:bind path="filename">
  <c:out value="${status.value}" />
</spring:bind>

status.value is always a String, converted using whatever PropertyEditor is detected. But this is unhelpful if I want to access a property that's a List so that I can loop over it. I can access the variable directly in JSP but then I have to know the name of the command, and I can't take advantage of things like spring:nestedPath.
Can spring:bind provide access to the actual original value rather than the converted String, or is there another tag that can do this?
I'm using Spring 3.1.

A: you can access the original object by
${status.actualValue}


text:
Q: "Parameters or Publish" which method best suits to pass parameters to a canvas app from a visualforce page? I understand from the documentation that we can pass parameters to canvas app using the parameters attribute of <apex:canvasApp visualforce tag.
Also using the canvas javascript sdk we can publish the data from visualforce page so that the canvas app can subscribe to it.
But i am wondering which method best suits to pass parameters to a canvas app from a visualforce page and what is the advantage of one over other? And any differences between these methods. How does the communication between vf page and canvas app differs with parameters and publish? Pleas suggest.

A: The Canvas Javascript publish is an event. You can trigger it multiple times and vary the payload each time. Your canvas app needs to subscribe to these events to receive them. You can also publish events from the canvas app back to the Visualforce page.
The <apex:canvasApp> parameters in contrast are fixed at the time the page is rendered and are one way (Visualforce Page to Canvas App). You can read these parameters out of the signed request that is sent to the canvas app.
So, if you need interaction between the canvas app and its container the events will be required. If the data is fixed, the signed request parameters will be easier as you don't need to subscribe to events and then raise the events from the container.


text:
Q: network programming / message framing I have a short question about message framing for network programming:
You often see implementations that define a MAGIC flag and a corresponding bitmask to retrieve it.
The header may contain other message relevant information, flipping the bits with logical OR.
Various implementations check for the magic flag using (header & MASK) == MAGIC.
What is the benefit of seperating these concerns?
You could also do: (header & MAGIC) == MAGIC.

A: Simple example:
MASK   = 0x000F
MAGIC  = 0x0001
header = 0x0005

Then (header & MASK) == MAGIC checks if all bits that are set in MASK (here the lower 4 bits) have the same value as the corresponding bits in MAGIC. This is not true for
the example header.
On the other hand, (header & MAGIC) == MAGIC checks only if all bits that are set in the MAGIC are also set in the header, which is true in this example.
In your example, header = 0xFFFF would pass the test (header & MAGIC) == MAGIC,
but not the test (header & MASK) == MAGIC.
Of course there is no difference if MASK == MAGIC.


text:
Q: How to copy a file in a folder 2 level up where the shell file is being run on OSX? The shell script is run from Parent/SubfolderA/SubfolderB/
The target directory is Parent
What is the correct path way to use with cp command?
Thank you

A: using relative path
cp file  ../../
or
using absolute path
cp file  Parent/  here parent is the full path to parent directory

A: *

*Go to parent directory using the cmd cd parent

*sudo cp -a SubfolderA/SubfolderB/file . to copy the file and its permission as well. Using sudo would get temporary root permission for this command, so that you would not encounter "permission denied".


text:
Q: How to add Web API to Visual Studio I have Visual Studio 2017 without Web API component, I want to add it to my VS (not to a project), how do I do that?
I looked for it in the 'new project section' tried to get it from tools\ get tools and features and to get it from Extensions and updates - got nothing.. what am I missing ?


text:
Q: Text drawn by grid.text is not placed at the right location in ggplot Suppose we have the following faceted plot.
library(ggplot2)
library(grid)

ggplot(mpg, aes(displ, hwy)) +
  geom_point() +
  facet_wrap(~ cyl)

If we would like to include the text 'center' at the exact center of the plot, we may call to grid.locator(), click at the center of the plot and store the location of our mouse click using a specified coordinate system.
crds <- grid.locator(unit = 'npc') # click in the center of the plot
> crds
$x
[1] 0.534709193245779npc

$y
[1] 0.643171806167401npc

We can now use these coordinates in a call to grid.text() to place the text at the very center of the plot.
grid.text(
  label = 'center',
  x = unit(crds$x, 'npc'),
  y = unit(crds$y, 'npc'),
  gp = gpar(fontsize = 11, fontface = 2)
)

The printed text appears at the right x coordinate, but the y coordinate seems to deviate about 15% from the expected location.

Does anyone know why this happens and how to fix it?


text:
Q: 3d plot of custom function with matplotlib I need to do a 3d plot with python. In the documentation there are not example that I can use.
Here my code:
f0=interp1d(t1,sig1,kind="cubic",bounds_error=False,fill_value=0)
g0=interp1d(t1,sig2,kind="cubic",bounds_error=False,fill_value=0)

""" Linear example """
A=5.
B=1.1
C=0
I=arange(t1.min(),t1.max(),1)

# g(t) and f1(t) are the periodical extension of f0 and g0
def s(t):
    return A+B*t+C*t*t

def g(t):
    M=g0.x.max()
    m=g0.x.min()

    t=t+m
    t=t%M

    return g0(t)

def f1(t):
    M=f0.x.max()
    m=g0.x.min()
    t=t+m
    t=t%M
    return f0(t)

# f(t) is the shifted version of f1(t).
def f(t):
    return f1(s(t))

# This is the cost function that we are trying to minimize
def cost(x):
    b=x[0]
    a=x[1]
    return norm(g(b*I+a)-f(I))

I2=array([s(t) for t in I]) # the interval defined by s(t)

aa=arange(A,A+10,0.5)
bb=arange(-1.5*B,1.5*B,0.1)
plot3d(aa,bb,cost) # This is what I would like<---------------

So that I can have a 3d plot of the cost function.
How can I do that?


text:
Q: Can I retire a required protobuf field? I have a client-server application where the server transmits serialized objects in protobuf format to a client, and I would like to retire a required field. Unfortunately I can't change both client and server at the same time to use the new .proto definition.
If I change a required field to be optional, but only for code that serializes messages (i.e. deserializing code has not been rebuilt and still thinks it's a required field), can I continue to publish messages that can be deserialized as long as I populate a value for the now-optional field?
(It appears to be fine to do so, at least for a few trivial cases I experimented with (only using Java), but I'm interested if it's a generally sensible approach, and whether there are any edge cases etc I should worry about).
Motivation: My goal is to retire a required field in a client-server application where the server publishes messages that are deserialized by the client. My intended approach is:

*

*Change required field to optional on the trunk.

*If it's necessary to deploy new server code (for unrelated features/fixes), ensure that the optional field continues to be populated in the message.

*Gradually deploy updated code for all clients (this will take time as it requires involvement of other teams with their own release schedules)

*Confirm that all clients have been updated.

*Begin to retire (i.e. not populate) the optional field.

A: As long as the field is set, using the parseFrom(byte[]) method to deserialize will still work, because the byte[] will be the same.
However, one would wonder why you would change the field from required to optional until you are ready to allow it to be optional? Basically you are just making it "optional" in the .proto file, but you are enforcing that it is required by always populating it. Just a thought.

A: According to the encoding format documentation, whether a field is required or not is not encoded in serialized byte stream itself. That is, optional or required makes no difference in the encoded serialized message.
I've confirmed this in practice, using the Java generated code, by writing serialized messages to disk and comparing the output - using a message containing all of the supported primitive types as well as fields representing other types.


text:
Q: std::copy runtime_error when working with uint16_t's I'm looking for input as to why this breaks.  See the addendum for contextual information, but I don't really think it is relevant.
I have an std::vector<uint16_t> depth_buffer that is initialized to have 640*480 elements.  This means that the total space it takes up is 640*480*sizeof(uint16_t) = 614400.
The code that breaks:
void Kinect360::DepthCallback(void* _depth, uint32_t timestamp) {
    lock_guard<mutex> depth_data_lock(depth_mutex);

    uint16_t* depth = static_cast<uint16_t*>(_depth);
    std::copy(depth, depth + depthBufferSize(), depth_buffer.begin());/// the error
    new_depth_frame = true;
}

where depthBufferSize() will return 614400 (I've verified this multiple times).
My understanding of std::copy(first, amount, out) is that first specifies the memory address to start copying from, amount is how far in bytes to copy until, and out is the memory address to start copying to.
Of course, it can be done manually with something like
#pragma unroll
for(auto i = 0; i < 640*480; ++i) depth_buffer[i] = depth[i];

instead of the call to std::copy, but I'm really confused as to why std::copy fails here.  Any thoughts???

Addendum: the context is that I am writing a derived class that inherits from FreenectDevice to work with a Kinect 360.  Officially the error is a Bus Error, but I'm almost certain this is because libfreenect interprets an error in the DepthCallback as a Bus Error.  Stepping through with lldb, it's a standard runtime_error being thrown from std::copy.  If I manually enter depth + 614400 it will crash, though if I have depth + (640*480) it will chug along.  At this stage I am not doing something meaningful with the depth data (rendering the raw depth appropriately with OpenGL is a separate issue xD), so it is hard to tell if everything got copied, or just a portion.  That said, I'm almost positive it doesn't grab it all.
Contrasted with the corresponding VideoCallback and the call inside of copy(video, video + videoBufferSize(), video_buffer.begin()), I don't see why the above would crash.  If my understanding of std::copy were wrong, this should crash too since videoBufferSize() is going to return 640*480*3*sizeof(uint8_t) = 640*480*3 = 921600.  The *3 is from the fact that we have 3 uint8_t's per pixel, RGB (no A).  The VideoCallback works swimmingly, as verified with OpenGL (and the fact that it's essentially identical to the samples provided with libfreenect...).  FYI none of the samples I have found actually work with the raw depth data directly, all of them colorize the depth and use an std::vector<uint8_t> with RGB channels, which does not suit my needs for this project.

I'm happy to just ignore it and move on in some senses because I can get it to work, but I'm really quite perplexed as to why this breaks.  Thanks for any thoughts!

A: The way std::copy works is that you provide start and end points of your input sequence and the location to begin copying to. The end point that you're providing is off the end of your sequence, because your depthBufferSize function is giving an offset in bytes, rather than the number of elements in your sequence.
If you remove the multiply by sizeof(uint16_t), it will work. At that point, you might also consider calling std::copy_n instead, which takes the number of elements to copy.
Edit: I just realised that I didn't answer the question directly.
Based on my understanding of std::copy, it shouldn't be throwing exceptions with the input you're giving it. The only thing in that code that could throw a runtime_error is the locking of the mutex.
Considering you have undefined behaviour as a result of running off of the end of your buffer, I'm tempted to say that has something to do with it.


text:
Q: Getting duplicates on sort with uniq at bash I tried to combine 2 files and do the sort + uniq in it, but I am still getting duplicate values in the output.
❯ cat new_ids.txt existing_ids.txt|  sort | uniq | head
009fff77-e6f2-46b1-8353-a271e3e1bdea
00AB4E27-4D4F-4E4F-B4EC-2BE83B85CEF8
00a6ceff-cac8-42e3-bdc9-cbf2538e31ea
00a6ceff-cac8-42e3-bdc9-cbf2538e31ea
00ab4e27-4d4f-4e4f-b4ec-2be83b85cef8
00ab4e27-4d4f-4e4f-b4ec-2be83b85cef8
00c650d7-902a-4223-b11b-c5b41ab8f1f5
00e55256-981e-4a4a-ad8b-a0a6cb75f47c
00eead4b-1d8f-418b-80c1-976c55abb629
00eead4b-1d8f-418b-80c1-976c55abb629

I tried to normalize line delimiters, by
❯ cat new_ids.txt existing_ids.txt| sed 's/\r$//' | tr -d '\t' | tr -d ' '| sort | uniq | head
009fff77-e6f2-46b1-8353-a271e3e1bdea
00AB4E27-4D4F-4E4F-B4EC-2BE83B85CEF8
00a6ceff-cac8-42e3-bdc9-cbf2538e31ea
00a6ceff-cac8-42e3-bdc9-cbf2538e31ea
00ab4e27-4d4f-4e4f-b4ec-2be83b85cef8
00ab4e27-4d4f-4e4f-b4ec-2be83b85cef8
00c650d7-902a-4223-b11b-c5b41ab8f1f5
00e55256-981e-4a4a-ad8b-a0a6cb75f47c
00eead4b-1d8f-418b-80c1-976c55abb629
00eead4b-1d8f-418b-80c1-976c55abb629

But I am still getting duplicates. Any help on identifying what is wrong with this is highly appreciated.
❯ cat new_ids.txt existing_ids.txt| sed 's/\r$//' | tr -d '\t' | tr -d ' '| sort | uniq | head | hexdump -C
00000000  30 30 39 66 66 66 37 37  2d 65 36 66 32 2d 34 36  |009fff77-e6f2-46|
00000010  62 31 2d 38 33 35 33 2d  61 32 37 31 65 33 65 31  |b1-8353-a271e3e1|
00000020  62 64 65 61 0a 30 30 41  42 34 45 32 37 2d 34 44  |bdea.00AB4E27-4D|
00000030  34 46 2d 34 45 34 46 2d  42 34 45 43 2d 32 42 45  |4F-4E4F-B4EC-2BE|
00000040  38 33 42 38 35 43 45 46  38 0a 30 30 61 36 63 65  |83B85CEF8.00a6ce|
00000050  66 66 2d 63 61 63 38 2d  34 32 65 33 2d 62 64 63  |ff-cac8-42e3-bdc|
00000060  39 2d 63 62 66 32 35 33  38 65 33 31 65 61 0a 30  |9-cbf2538e31ea.0|
00000070  30 61 36 63 65 66 66 2d  63 61 63 38 2d 34 32 65  |0a6ceff-cac8-42e|
00000080  33 2d 62 64 63 39 2d 63  62 66 32 35 33 38 65 33  |3-bdc9-cbf2538e3|
00000090  31 65 61 0d 0a 30 30 61  62 34 65 32 37 2d 34 64  |1ea..00ab4e27-4d|
000000a0  34 66 2d 34 65 34 66 2d  62 34 65 63 2d 32 62 65  |4f-4e4f-b4ec-2be|
000000b0  38 33 62 38 35 63 65 66  38 0a 30 30 61 62 34 65  |83b85cef8.00ab4e|
000000c0  32 37 2d 34 64 34 66 2d  34 65 34 66 2d 62 34 65  |27-4d4f-4e4f-b4e|
000000d0  63 2d 32 62 65 38 33 62  38 35 63 65 66 38 0d 0a  |c-2be83b85cef8..|
000000e0  30 30 63 36 35 30 64 37  2d 39 30 32 61 2d 34 32  |00c650d7-902a-42|
000000f0  32 33 2d 62 31 31 62 2d  63 35 62 34 31 61 62 38  |23-b11b-c5b41ab8|
00000100  66 31 66 35 0d 0a 30 30  65 35 35 32 35 36 2d 39  |f1f5..00e55256-9|
00000110  38 31 65 2d 34 61 34 61  2d 61 64 38 62 2d 61 30  |81e-4a4a-ad8b-a0|
00000120  61 36 63 62 37 35 66 34  37 63 0a 30 30 65 65 61  |a6cb75f47c.00eea|
00000130  64 34 62 2d 31 64 38 66  2d 34 31 38 62 2d 38 30  |d4b-1d8f-418b-80|
00000140  63 31 2d 39 37 36 63 35  35 61 62 62 36 32 39 0a  |c1-976c55abb629.|
00000150  30 30 65 65 61 64 34 62  2d 31 64 38 66 2d 34 31  |00eead4b-1d8f-41|
00000160  38 62 2d 38 30 63 31 2d  39 37 36 63 35 35 61 62  |8b-80c1-976c55ab|
00000170  62 36 32 39 0d 0a                                 |b629..|
00000176

It seems there is an extra '.', but not sure how to remove that.
(*) edit to update the results with hexdump

A: Thank you @Zilog80,
I was able to fix the issue with the following command
❯ cat new_ids.txt existing_ids.txt|sed 's/[^[:print:]]//' | sort | uniq | head
009fff77-e6f2-46b1-8353-a271e3e1bdea
00AB4E27-4D4F-4E4F-B4EC-2BE83B85CEF8
00a6ceff-cac8-42e3-bdc9-cbf2538e31ea
00ab4e27-4d4f-4e4f-b4ec-2be83b85cef8
00c650d7-902a-4223-b11b-c5b41ab8f1f5
00e55256-981e-4a4a-ad8b-a0a6cb75f47c
00eead4b-1d8f-418b-80c1-976c55abb629
0141c42a-0fad-499c-8867-964aa4db8e3e
018f1eb1-8344-4864-a232-6671262e3713
01900813-721e-4d1e-a686-695c49b92238


text:
Q: Why do I keep getting GNU GRUB? My computer is not a dual-boot it is just Ubuntu.
Why when I boot up do I get the GNU GRUB menu? It has options like recovery mode and stuff.

A: If your question is really not "Why do I get this?" but instead "How can I get rid of this?", try the answer here.


text:
Q: Passing a set of structurally typed elements I have a function:
def collapse(relations: Set[Relation] ...
Where Relation is a structural type
  type Relation = {
    def source: NodeId
    def target: NodeId
  }

I have two case classes:
case class ViewRelation(id: Option[NodeId],
                        source: NodeId,
                        target: NodeId, ...

and
case class IndirectRelation(source: NodeId,
                        target: NodeId...

I can not, for practical reasons, make them extend from the same trait. Therefore I have decided to use a structural type.
I want to pass a val viewRelations = Set[ViewRelation] and val indirectRelations: Set[IndirectRelation] as an argument: collapse(viewRelations ++ indirectRelations). Unfortunately that does not seem to work. Even passing just viewRelations or indirectRelations does not work. I finally worked around it this way:
collapse(Set[Relation](relations.toSeq: _*) ++ Set[Relation](indirectRelations.toSeq: _*))
Is there a better way? This is very wasteful as I can expect relatively large numbers of relations and the operation will need to run often.

A: You could also use Set.empty[Relation] ++ viewRelations ++ indirectRelations.


text: Q: How to Login to my Chegg account with python and extract the answer I want to know how I can log in to my Chegg account with python without selenium then extract an exact answer to an HTML page how can I do that (I am a beginner) Please If Any Can Help me Answer me.


text:
Q: how to insert without duplicate from one table into another I tried to insert from one table into another and im having with the redundancy..
I came up with a query but every time when i execute it, It cannot deals with duplicate.
here's my query...
INSERT INTO balik ( balik_date, balik_time, balik_cardID, balik_status,balik_type)
select current_date(), '00:00:00', L_CardID, 'BELUM BALIK', L_Type
FROM logdetail t1
LEFT JOIN balik t2 ON (t1.L_CardID = t2.balik_cardID)
WHERE t1.L_Type = 'IN'

any help will be greatly appreciated

A: Use  INSERT IGNORE instant of INSERT.

Use INSERT IGNORE rather than INSERT. If a record doesn't duplicate an
  existing record, MySQL inserts it as usual. If the record is a
  duplicate, the IGNORE keyword tells MySQL to discard it silently
  without generating an error.

OR
Check row count for unique field. If row exist don't insert or update.
OR

Use REPLACE rather than INSERT. If the record is new, it's inserted
  just as with INSERT. If it's a duplicate, the new record replaces the
  old one:

Source for definitions MySQL Handling Duplicates


text:
Q: Congestion Control Query for cars on road using Esper Query Language I am receiving the data from a simulation in the following format:
As it can be seen that for the time being there are two cars that are going from Street 7 to Street 11 (as they cross numerous zones where sensors are placed to monitor the movement).
Now I want to stop a signal when the latest time difference between car#1 and car#2 is  only 3 seconds or less.
How can I do that in esper query language.
I have to write a query for complex event processing that will let me generate an event as soon as the above condition is met.
As from the data it can be seen that initially the time when car#1 enters Street#7 is 42500, whereas when car#2 enters Street#7 the time is 42508, making the time difference of 8 secs.
    { time: 42500,
      location: { Zone: 'Z3', Street: 'Street#7' },
      carID: 'car#1' }
    ---------------------------------------
    { time: 42502,
      location: { Zone: 'Z5', Street: 'Street#7' },
      carID: 'car#1' }
    ---------------------------------------
    { time: 42502,
      location: { Zone: 'Z1', Street: 'Street#8' },
      carID: 'car#1' }
    ---------------------------------------
    { time: 42504,
      location: { Zone: 'Z4', Street: 'Street#8' },
      carID: 'car#1' }
    ---------------------------------------
    { time: 42505,
      location: { Zone: 'Z5', Street: 'Street#8' },
      carID: 'car#1' }
    ---------------------------------------
    { time: 42505,
      location: { Zone: 'Z1', Street: 'Street#9' },
      carID: 'car#1' }
    ---------------------------------------
    { time: 42507,
      location: { Zone: 'Z4', Street: 'Street#9' },
      carID: 'car#1' }
    ---------------------------------------
    { time: 42508,
      location: { Zone: 'Z3', Street: 'Street#7' },
      carID: 'car#2' }
    ---------------------------------------
    { time: 42508,
      location: { Zone: 'Z5', Street: 'Street#9' },
      carID: 'car#1' }
    ---------------------------------------
    { time: 42508,
      location: { Zone: 'Z1', Street: 'Street#10' },
      carID: 'car#1' }
    ---------------------------------------
    { time: 42509,
      location: { Zone: 'Z4', Street: 'Street#10' },
      carID: 'car#1' }
    ---------------------------------------
    { time: 42509,
      location: { Zone: 'Z5', Street: 'Street#7' },
      carID: 'car#2' }
    ---------------------------------------
    { time: 42509,
      location: { Zone: 'Z1', Street: 'Street#8' },
      carID: 'car#2' }
    ---------------------------------------
    { time: 42511,
      location: { Zone: 'Z5', Street: 'Street#10' },
      carID: 'car#1' }
    ---------------------------------------
    { time: 42511,
      location: { Zone: 'Z1', Street: 'Street#11' },
      carID: 'car#1' }
    ---------------------------------------
    { time: 42511,
      location: { Zone: 'Z4', Street: 'Street#8' },
      carID: 'car#2' }
    ---------------------------------------
    { time: 42512,
      location: { Zone: 'Z4', Street: 'Street#11' },
      carID: 'car#1' }
    ---------------------------------------
    { time: 42512,
      location: { Zone: 'Z5', Street: 'Street#8' },
      carID: 'car#2' }
    ---------------------------------------
    { time: 42512,
      location: { Zone: 'Z1', Street: 'Street#9' },
      carID: 'car#2' }
    ---------------------------------------
    { time: 42513,
      location: { Zone: 'Z5', Street: 'Street#11' },
      carID: 'car#1' }
    ---------------------------------------
    { time: 42513,
      location: { Zone: 'Z1', Street: 'Street#12' },
      carID: 'car#1' }
    ---------------------------------------

A: This sounds a bit like a join of events for car 1 with events of car 2. The question is then what subset of events to join. The use case seems to require retaining some history of streets that were visited by each car. For this we could use a length window or a unique window or a union of these windows. Lets use a length window that considers the last 10 streets or events. For example a query like this:
select * from Event(carID="car#1").win:length(20) as car1, Event(carID="car#2").win:length(20) as car2 where Math.abs(car1.time-car2.time) > 3 and car1.Location.Street = car2.Location.Street


text:
Q: Webpack/Babel not detecting javascript errors before transpiling I have configured webpack-dev-server for a new React project. I am using babel-loader to transpile ES6 code. In previous projects we were able to detect obvious errors in our javascript code prior to transpilation, eg missing import statements or undefined variables.
Why is webpack / babel-loader not detecting obvious errors? And how can I configure babel-loader to not transpile these errors and instead log to the command prompt?
Here is my package.json
{
  "name": "advent-calendar",
  "version": "1.0.0",
  "description": "",
  "main": "src/entry.js",
  "scripts": {
    "dev": "webpack-dev-server --config config/webpack.config.dev.js",
    "build:webpack": "cross-env NODE_ENV=production && webpack --config config/webpack.config.prod.js",
    "build": "npm run build:webpack --verbose --color",
    "test": "cross-env NODE_ENV=development ./node_modules/.bin/mocha --opts mocha.opts",
    "test:watch": "npm run test -- --watch",
    "lint": "npm run -s lint:css:raw ; npm run -s lint:js:raw",
    "lint:css": "npm run -s lint:css:raw",
    "lint:css:raw": "stylelint \"src/**/*.{css,less,scss}\"",
    "lint:js": "npm run -s lint:js:raw",
    "lint:js:raw": "eslint  \"src/**/*.js\"",
    "lint:js:raw:fix": "./node_modules/.bin/eslint --fix \"src/**/*.js\"",
    "lint:js:watch": "esw \"src/**/*.js\" --watchyar",
    "lint:watch": "npm run lint:js:watch"
  },
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-eslint": "^8.0.2",
    "babel-loader": "^7.1.2",
    "babel-polyfill": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-es2017": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-1": "^6.24.1",
    "chai": "^4.1.2",
    "chai-enzyme": "^0.8.0",
    "cross-env": "^5.1.1",
    "css-loader": "^0.28.7",
    "enzyme": "^3.1.1",
    "enzyme-adapter-react-16": "^1.0.4",
    "eslint": "^4.10.0",
    "eslint-loader": "^1.9.0",
    "eslint-plugin-chai-friendly": "^0.4.0",
    "eslint-plugin-eslint-comments": "^2.0.1",
    "eslint-plugin-import": "^2.8.0",
    "eslint-plugin-jsx-a11y": "^6.0.2",
    "eslint-plugin-react": "^7.4.0",
    "file-loader": "^1.1.5",
    "html-webpack-plugin": "^2.30.1",
    "jsdom": "^9.9.1",
    "less": "^2.7.3",
    "less-loader": "^4.0.5",
    "mocha": "^4.0.1",
    "node-sass": "^4.6.0",
    "nyc": "~9.0.1",
    "path": "^0.12.7",
    "prop-types": "^15.6.0",
    "sass-loader": "^6.0.6",
    "simple-jsdom": "^3.0.0",
    "sinon": "^4.1.2",
    "sinon-chai": "^2.14.0",
    "style-loader": "^0.19.0",
    "stylelint": "^8.2.0",
    "webpack": "^3.8.1",
    "webpack-dev-server": "^2.9.4"
  },
  "dependencies": {
    "classnames": "^2.2.5",
    "crypto-js": "^3.1.9-1",
    "css-reset": "^0.0.1",
    "react": "^16.0.0",
    "react-dom": "^16.0.0",
    "react-redux": "^5.0.6",
    "react-transition-group": "^2.2.1",
    "redux": "^3.7.2",
    "redux-devtools-extension": "^2.13.2",
    "redux-saga": "^0.16.0"
  }
}

This is my .babelrc
{
   "presets": [
      "es2015",
      "react",
      "stage-1"
   ]
}

My loader for javascript files is
{
   test: /\.$|\.js$|\.jsx$/,
   exclude: /node_modules\/[^@]/,
   use: [{
     loader: 'babel-loader',
   }],
}

A:
And how can I configure babel-loader to not transpile these errors and instead log to the command prompt?

Webpack-dev-server has enough configuration for error logging, which can be provided in declarative mode.
Just use following script (name it run-dev.js and patch package.json respectively) for launching client part:
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';

import config from './webpack.dev.config';

const outputConfig = {
    colors: true,
    hash: false,
    version: false,
    timings: false,
    assets: false,
    chunks: false,
    modules: false,
    reasons: false,
    children: false,
    source: false,
    errors: true,
    errorDetails: true,
    warnings: true,
    publicPath: false
};

const clientCompiler = webpack(config);

const clientDevServer = new WebpackDevServer(clientCompiler, {
    stats: outputConfig
});

clientDevServer.listen(3000, '127.0.0.1');

Then you can customize outputConfig object depend on requirements and verbose degree of output. Don't forget to turn on errors and errorDetails options, which will indicate chunks and source code lines with compile errors.
Read mode here https://webpack.js.org/configuration/stats/ about outputConfig configuration, including filter patter for error output, which can be used for excluding redundant logging in console.


text:
Q: Oracle Apex Interactive Grid Cell Format Basic question please, I have an IG.
Trying to format a column using the following:
SELECT
   CASE
    WHEN my_number <= 3 THEN 'u-color-7-bg'
    WHEN my_number > 3  THEN 'u-color-8-bg'
   END some_color
FROM my_table

I'm modifying the resulting column 'some_color' to be an HTML Expression type.
On its HTML Expression part I have:
&MY_NUMBER.
But it doesn't work, no format is getting applied whatsoever.
Can anybody give me a hand please?

A: u-color-xx are CSS classes not actual colors. It should work if you try &MY_NUMBER. instead.
Alternatively you can use CSS-Variables defined by APEX in newer versions like this: &MY_NUMBER.


text:
Q: Analogs of concurrent collections in Portable .NET Framework Moving my code to portable framework, I found that there are no Concurrent collections available at all in Portable Class Library (PCL), this discussion explains it very well.
But still I need concurrent dictionary analog to run there.
And I'm more interested in read/contains performance than in modifying performance.

A: If you're more interested in reading, you should use a ReaderWriterLockSlim.
This is a locking primitive that allows multiple readers or one writer to enter the critical region at any given time. This will incur virtually no performance hit while the dictionary is being read by multiple threads, and apply mutual exclusion only when a thread tries to write.
You would implement it as so (I omitted most methods for brevity - I left Add as a writer example, and Contains as a reader example):
public class CustomDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
    private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
    private readonly IDictionary<TKey, TValue> _dictionary = new Dictionary<TKey, TValue>();

    public bool Contains(KeyValuePair<TKey, TValue> item)
    {
        _lock.EnterReadLock();
        try
        {
            return _dictionary.Contains(item);
        }
        finally
        {
            _lock.EnterReadLock();
        }
    }

    public void Add(KeyValuePair<TKey, TValue> item)
    {
        _lock.EnterWriteLock();
        try
        {
            _dictionary.Add(item);
        }
        finally
        {
            _lock.ExitWriteLock();
        }
    }
}

Now, the GetEnumerator is a little trickier to lock, because the dictionary will actually be read after calling GetEnumerator, not while it's being called.
So you should implement the enumerator yourself and apply a read-lock like this, so that the lock will be held while the collection is being enumerated:
    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
    {
        _lock.EnterReadLock();
        try
        {
            foreach (var entry in _dictionary)
                yield return entry;
        }
        finally
        {
            _lock.ExitReadLock();
        }
    }

A: The great benefits of Dictionary collections are fast key access and fast contains evaluation.
All dictionaries uses different complicated algorithms (check this one) and it will be very hard to write your own from the scratch.
So I've tried to reuse source code of original ConcurrentDictionary from BCL (you can get source code for every base class).
But, it is very complicated and uses dozens of private classes and low level functions to manage the memory. It is not accident, that it is not available in PCL from the beginning :)
Second thought was to make wrapper of ordinary dictionary and add lock section to every method invocation. Despite the fact that critical sections are not expensive it led to dramatic performance decrease.
So I've ended with clear interlocked implementation of Dictionary<,> wrapper. It happens so, that normal dictionary supports reading and enumeration from different threads, as far it is not modified in same time.
So, on every change we cloning all dictionary. All threads which reading it in that time will continue iterate older copy.
public class InterlockedDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>
{
    private Dictionary<TKey, TValue> _dictionary = new Dictionary<TKey, TValue>();

    public TValue this[TKey key]
    {
        get
        {
            return _dictionary[key];
        }
        set
        {
            ApplyAndChange(dict => dict[key] = value);
        }
    }

    public Dictionary<TKey, TValue>.KeyCollection Keys
    {
        get
        {
            return _dictionary.Keys;
        }
    }

    public Dictionary<TKey, TValue>.ValueCollection Values
    {
        get
        {
            return _dictionary.Values;
        }
    }

    public int Count
    {
        get
        {
            return _dictionary.Count;
        }
    }

    public void Add(KeyValuePair<TKey, TValue> item)
    {
        ApplyAndChange(dict => dict.Add(item.Key, item.Value));
    }

    public void Clear()
    {
        _dictionary = new Dictionary<TKey, TValue>();
    }

    public bool ContainsKey(TKey key)
    {
        return _dictionary.ContainsKey(key);
    }

    public void Add(TKey key, TValue value)
    {
        ApplyAndChange(dict => dict.Add(key, value));
    }

    public bool Remove(TKey key)
    {
        bool result = false;
        ApplyAndChange(dict => result = dict.Remove(key));
        return result;
    }

    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
    {
        return _dictionary.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    private void ApplyAndChange(Action<Dictionary<TKey, TValue>> action)
    {
        Dictionary<TKey, TValue> initialDictionary, updatedDictionary, replacedDictionary;
        do
        {
            initialDictionary = _dictionary;
            updatedDictionary = new Dictionary<TKey, TValue>(initialDictionary);
            action(updatedDictionary);
        } while (Interlocked.CompareExchange(ref _dictionary, updatedDictionary, initialDictionary) != initialDictionary);
    }
}

This implementation does not implement IDictionary<,> as a lots of not required members there. But it can be easily done by invoking directly underlying dictionary for all non modifying methods and wrapping all modifying methods with ApplyAndChange(dict => ...).
N.B. - As for performance, comparing to original Dictionary<,> this implementation has worse Set, Add and Remove and equal to Read and Contains performance.


text:
Q: Why does my player_turns() not increment by 1? I am working on a 2-player battleships game written in python. My player_turns() makes it so that it alternates between player 1 and player 2. However when you play it stays only on player 1, why is this the case?
Also, I've noticed that if you find the ship's location and start a new game, the ship does not find a new location and keeps the same coordinates as it had last game. How can I make it so that the coordinates change every game?
from random import randint

game_board = []
player_one = {
    "name": "Player 1",
    "wins": 0,
    "lose": 0
}
player_two = {
    "name": "Player 2",
    "wins": 0,
    "lose": 0
}

# Building our 5 x 5 board
def build_game_board(board):
    for item in range(5):
        board.append(["O"] * 5)

def show_board(board):
    print("Find and sink the ship!")
    for row in board:
        print(" ".join(row))

# Defining ships locations
def load_game(board):
    print("WELCOME TO BATTLESHIP!")
    print("START")
    del board[:]
    build_game_board(board)
    show_board(board)
    ship_col = randint(1, len(board))
    ship_row = randint(1, len(board[0]))
    return {
        'ship_col': ship_col,
        'ship_row': ship_row,
    }

ship_points = load_game(game_board)

# Players will alternate turns.
def player_turns():
    total_turns = 0
    if total_turns % 2 == 0:
        return player_one
        total_turns += 1

    else:
        return player_two

# Allows new game to start
def play_again():
    answer = input("Would you like to play again? ")
    if answer == "yes" or answer == "y":
        total_turns = 0
        ship_points = load_game(game_board)

    else:
        print("Thanks for playing!")
        exit()

# What will be done with players guesses
def input_check(ship_row, ship_col, player, board):
    guess_col = 0
    guess_row = 0
    while True:
        try:
            guess_row = int(input("Guess Row:")) - 1
            guess_col = int(input("Guess Col:")) - 1
        except ValueError:
            print("Enter a number only: ")
            continue
        else:
            break
    match = guess_row == ship_row - 1 and guess_col == ship_col - 1
    not_on_game_board = (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4)

    if match:
        player["wins"] += 1
        print("Congratulations! You sunk my battleship!")
        print("Thanks for playing!")
        play_again()

    elif not match:
        if not_on_game_board:
            print("Oops, that's not even in the ocean.")

        elif board[guess_row][guess_col] == "X":
            print("You guessed that one already.")

        else:
            print("You missed my battleship!")
            board[guess_row][guess_col] = "X"
        show_board(game_board)

    else:
        return 0

def main():
    begin = input('Type \'start\' to begin: ')
    while (begin != str('start')):
        begin = input('Type \'start\' to begin: ')
    for games in range(3):
        for turns in range(6):

            if player_turns() == player_one:
                print("Player One")
                input_check(
                    ship_points['ship_row'],
                    ship_points['ship_col'],
                    player_one, game_board
                )

            elif player_turns() == player_two:
                print("Player Two")
                input_check(
                    ship_points['ship_row'],
                    ship_points['ship_col'],
                    player_two, game_board
                )

            if turns == 6:
                print("The game is a draw")
                play_again()

if __name__ == "__main__":
    main()

A: You need to use the return statement after incrementing total_turns.
Once the return statement is executed, the function is exited.


text:
Q: Customizing msbuild for .NET Core with something like CustomBeforeMicrosoftCommonTargets For a long time, I have been very successful at non-invasively customizing many .NET Framework builds by setting CustomBeforeMicrosoftCommonTargets and CustomAfterMicrosoftCommonTargets as environment variables in a command-line shell that corresponds to a given development/build workspace.
I would set these environment variables to point to custom msbuild targets files that would then be automatically imported (before and after respectively) the import of the standard Microsoft provided targets files. This has worked great for a long time, but now .NET Core comes along and I find no mechanism quite like that.
I am aware of Directory.Build.props and that does not appear to be equivalent. For one, it is invasive requiring me to add a file to a source tree that I don't want to necessarily touch in order to customize its build (maybe its an open source project and I don't want to be injecting new files into it). For two, it doesn't provide the dual Before/After import hooks which are very important (if this duality weren't important Microsoft would never have provided it).
I also don't like dropping magic files in magic global locations as my build policies/customizations are themselves versioned source code which can vary from one developer workspace to another (even on the very same machine for the very same developer).
It seems odd that Microsoft would fail to retain such a long-standing and fundamentally useful msbuild customization capability in .NET Core. Am I missing an equivalently powerful, easy to use and non-invasive mechanism? Is it there and I just haven't found it?

A: CustomBeforeMicrosoftCommonTargets and CustomAfterMicrosoftCommonTargets are still part of MSBuild 15 which is included in VS 2017 and the .NET Core SDK.
Setting them as global variables will still import them and override the default locations used if not set. Use the /bl argument to generate a binary build log and the MSBuild structured log viewer to diagnose issues you may have with it.


text:
Q: How to use GDAL with PyPy? I am trying to optimize my python code using pypy. While I am able to import most libraries and run succesfully, I am not able to import GDAL libraries. The same libraries when imported in Python 2.7 run fine.
I have tried adding GDAL location to PYTHONPATH, and even tried downloading GDAL Python bindings to PyPy directory, somehow pypy does not want to recognize GDAL, and comes with the following error.
Traceback (most recent call last):

  File "app_main.py", line 51, in run_toplevel

  File "ImportENC-P.py", line 50, in <module>

    from osgeo import gdal, ogr, osr

  File "B:\PYPY\site-packages\osgeo\__init__.py", line 21, in <module>

    _gdal = swig_import_helper()

  File "B:\PYPY\site-packages\osgeo\__init__.py", line 13, in swig_import_helper

    import _gdal

ImportError: No module named _gdal

A: Pypy is not compatible with SWIG (see also this answer in StackOverflow), which is what the C bindings of GDAL use to talk to the Python compiler. Afraid it's a no dice unless you can spend the time to re-write the GDAL Python bindings with C-Types (which I suspect is pretty unlikely)...


text:
Q: Can mustache iterate a top-level array? My object looks like this:
['foo','bar','baz']

And I want to use a mustache template to produce from it something like this:
"

foo

bar

baz

"

But how? Do I really have to munge it into something like this first?
{list:['foo','bar','baz']}

A: Building on @danjordan's answer, this will do what you want:
Mustache.render('
{{#.}}
{{.}}
{{/.}}
',['foo','bar','baz']);

returning:

foo

bar

baz

A: Following are the examples to render multi-dimensional array in a template:
Example 1
'use strict';

var Mustache = require('mustache');

var view = {test: 'div content', multiple : ['foo', 'bar'], multiple_2 : ['hello', 'world']};
var template = '
{{test}}

{{#multiple}}
{{.}}
{{/multiple}}

{{#multiple_2}}
{{.}}
{{/multiple_2}}
';

var output = Mustache.render(template, view);

console.log(output);

Example 2
'use strict';

var Mustache = require('mustache');

var view = {test: 'div content', multiple : [{name: 'foo', gender: 'male'}, {name: 'bar', gender: 'female'}], multiple_2 : [{text: 'Hello', append: '**', prepend: '**'}, {text: 'World', append: '**', prepend: '**'}]};
var template = '
{{test}}

{{#multiple}}
Hello my name is {{name}}. And I am {{gender}}
{{/multiple}}

{{#multiple_2}}
{{prepend}}_{{text}}_{{append}}
{{/multiple_2}}
';

var output = Mustache.render(template, view);

console.log(output);

For test run, save above examples in file called 'test.js', run following command in commandline
nodejs test.js

A: You can do it like this...
Mustache.render('
{{#.}}
{{.}}
{{/.}}
', ['foo','bar','baz']);

It also works for things like this...
var obj = [{name: 'foo'}, {name: 'bar'}];
var tmp = '
{{#.}}
{{name}}
{{/.}}
';
Mustache.render(tmp, obj);

A: I had the same problem this morning and after a little experimentation I discovered you can use the {{.}} to refer to the current element of an array:

  {{#yourList}}

{{.}}

  {{/yourList}}

A: Simplest solution for an array named Strengths:
{
   "ViewModel":
    {
       "StrengthsItems":
        {
           "Strengths": ["Dedicated", "Resourceful", "Professional", "Positive"]
        }
    }
}

works for me like a charm is as following:
{{#ViewModel.StrengthsItems}}

{{Strengths}}

{{/ViewModel.StrengthsItems}}

A: I don't think mustache can do this!  (surprisingly)
You can iterate over a list of objects, and then access the attributes of each object, but you can't seem to iterate over a simple list of values!
So, you have to transform your list into:
[ {"value":"foo"},{"value":"bar"},{"value":"baz"} ]

and then your template would be:

  {{#the_list}}

{{value}}

  {{/the_list}}

To me, this seems like a severe problem with Mustache -- any template system should be able to loop over a list of simple values!


text:
Q: I am using the .grid command but its not lined up correctly and is not straight I am writing a program that makes a calculator with a GUI and I'm using tkinter but when I use the .grid command and assign it to a column it doesn't line up correctly and there is a bit of a gap between them... I am using python 3.7. Any ideas please.
I have tried using the grid and pack commands. I know there is the place method but not sure the exact co-ordinates I have to use so any idea on how to use the grid method correctly.
from tkinter import *
#from Tkinter import *

root = Tk()
root.title("Calculator")

#========================Screen=======================
Display = Entry(root, fg='white', bg='green',
    justify='right', bd=25)
Display.grid(columnspan=4)

#=======================Row1==========================
b7 = Button(root, padx=30, pady=15, bd=8, fg='black', text='7').grid(row=1, column=0)
b8 = Button(root, padx=30, pady=15, bd=8, fg='black', text='8').grid(row=1, column=1)
b9 = Button(root, padx=30, pady=15, bd=8, fg='black', text='9').grid(row=1, column=2)
clear = Button(root, padx=30, pady=15, bd=8, fg='black', text='C', highlightbackground='green', highlightthickness=0.1).grid(row=1, column=3)

#=======================Row2==========================
b4 = Button(root, padx=30, pady=15, bd=8, fg='black', text='4').grid(row=2, column=0)
b5 = Button(root, padx=30, pady=15, bd=8, fg='black', text='5').grid(row=2, column=1)
b6 = Button(root, padx=30, pady=15, bd=8, fg='black', text='6').grid(row=2, column=2)
plus = Button(root, padx=30, pady=15, bd=8, fg='black', text='+', highlightbackground='orange', highlightthickness=0.1).grid(row=2, column=3)

#=======================Row3==========================
b1 = Button(root, padx=30, pady=15, bd=8, fg='black', text='1').grid(row=3, column=0)
b2 = Button(root, padx=30, pady=15, bd=8, fg='black', text='2').grid(row=3, column=1)
b3 = Button(root, padx=30, pady=15, bd=8, fg='black', text='3').grid(row=3, column=2)
minus = Button(root, padx=30, pady=15, bd=8, fg='black', text='-', highlightbackground='orange', highlightthickness=0.1).grid(row=3, column=3)

root.mainloop()

I want the C, + and - to be lined up in the same column


text:
Q: How do I apply an UNINITIALISED class to an object in Typescript? I hope this code sample is clear enough about what I'm trying to do.
Note that this is a reduced test case to demonstrate the core trouble that I'm having. I don't want to know how to make this example simpler. I want to know how to stop TypeScript from complaining. I also don't want to use the any type.
// start with a class
class HelloWorld {
    hello = 'hello'

    world(): string {
        return this.hello + ' world'
    }
}

// Create an interface for an object
interface Greeting {
    Hello: HelloWorld
}

// The interface is applied to an object
// The class is applied to a value inside the object
// Note that it is an UNINITIALISED class
const greet: Greeting = {
    // ERROR: Type 'typeof HelloWorld' is missing the following properties
    // from type 'HelloWorld': hello, world ts(2739)
    Hello: HelloWorld,
}

// Later in the code you initialise it like this
// ERROR: This expression is not constructable.
// Type 'HelloWorld' has no construct signatures.ts(2351)
const greeting = new greet.Hello()

console.log(greeting.world()) // "hello world"

A: You're treating a normal class as an instance's interface here. It works only for it's instances that are declared using new keyword. To properly use class types in interfaces, convert the class to a type or interface, so that the TypeScript will know you're inferring the class itself, instead of it's instances.
Here is how you declare interface for both class and instance of a class
interface Greeting {
    // declaring type for the class itself
    Hello: typeof HelloWorld,

    // declaring the type for it's instance
    hello: HelloWorld
}

const greet: Greeting = {
    // Assigning the class itself
    Hello: HelloWorld,

    // Assigning an instances of HelloWorld
    hello: new HelloWorld()
}

const greeting = new greet.Hello()

// `greeting` is now identical to `greet.hello`


text:
Q: Regression coefficient signs different for log/asinh and level versions of same variable I ran two regressions. First, say, y=βx, and the second one, asinh(y)=βx, which I read is asymptotically equivalent to log(y)=βx, where x and y are the same variables with same data set for these two equations.
My confusion is that β is negative for the first regression (which I expected), but is positive for the second regression.
The sample size is the same for both regressions. Since I used asinh(y) instead of log(y), it did not drop zero values of y.
If it helps, I could totally regress in level-level mode, but the y variable is not normally distributed, and therefore, the asinh/log transformation.
Am I missing something?


text:
Q: How to update tableViewCells in firstVC in realtime when secondVC is updated I am currently in a bit of a trouble. I am creating a simple task manager. The user sets reminder in the secondVC and a bell icon is shown in the tableviewcell in firstVC for the appropriate cell. Now when you tap the cell and you move to secondVC, code is invoked in viewDidLoad() that compares the time_set for that task to the current time and says 'Time's Up' if current time is more than time_set. This then updates the icon and removes it from the cell in the firstVC.
However, I want the cells in the firstVC to be updated without first tapping in the cell and invoking code in viewDidLoad(). Is there any way I can run a function in the secondVC continuously and if a change occurs, then in realtime update the tableViewCell?


text:
Q: AngularJS/JavaScript - Substring of searched term and marked it with  I have a long string, for example:
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Duis viverra diam non justo. Maecenas fermentum, sem in pharetra pellentesque, velit turpis volutpat ante, in pharetra metus odio a lectus.

I want create (probably) a filter, which will find specific part, mark it with span tag and return it with some number of chars before and after too (rounded to whole words).
So for our example:
Filter should be:
text | 'ridiculus' : 10 : 20

And it should returned:
nascetur ridiculus mus. Duis viverra

The best would be, if the filter returns array of these substrings for each occurrence of the search term.
Thanks a lot for help.
EDIT 1:
Highlighting works. Thanks. But I need also to split the string to array of substrings with highlighted search term and given number of characters before and after too.

A: Logic

*

*Accept search and content from DOM.

*Parse search: replace all spaces to allow multi-word search.

*Then create a regex using search value. Note to add flags g and i for recursive and case-insensitive search.

*Create a function that accepts a string and returns HTML in necessary style.

*Then replace the content string using this regex and above declared function.

*Set return value as innerHTML.

document.getElementById("btnSearch").addEventListener("click", processSearch)

function processSearch(){
  var search = document.getElementById('txtSearch').value;
  search = search.replace(/ /g, '|');
  var contentDiv = document.querySelector('.content')
  contentDiv.innerHTML = getHighlightHTML(contentDiv.innerHTML, search);
}

function getHighlightHTML(text, search){
  var regex = new RegExp(search, "gi");
  return text.replace(regex, wrapHighlight)
}

function wrapHighlight(str){
  return "" + str + ""
}
.highlight{
  border-bottom: 2px solid cyan;
}
<input type="text" id="txtSearch" />
<button id="btnSearch" >Search</button>

  This is a random test, just to simulate word highlight based on search value.

A: you can just pass your full text and searched text in the filter defined. and in span, you can take html binding. Please look the working code on jsfiddle below :

Demo


text:
Q: How to test function that calls Ember.run.debounce in ember-qunit? The controller I would like to test contains the following:
filterText: '',
filteredFoos: (Ember.A()),

filterFoosImpl: function() {
    console.log('filterFoos begin' );
    var filterText = this.get('filterText');
    var filteredFoos = this.forEach(function(foo) {
        return (foo.get(name).indexOf(filterText) >= 0);
    });
    this.set('filteredFoos', filteredFoos);
},

filterFoos: function() {
    Ember.run.debounce(this.filterFoosImpl.bind(this), 300);
}.observes('model', 'filterText'),

Now I would like to write a test that asserts that filteredFoos is updated when I set filterText.
To do this correctly, I will need to take into account Ember.run.debounce,
and wait for that to occur before I perform my assertion.
How can I do this?

A: I was running into this problem as well and in order to stub out debounce, I did the following:
test('it triggers external action on a keyup event', function() {
    expect(1);

    // stub out the debounce method so we can treat this call syncronously
    Ember.run.debounce = function(target, func) {
      func.call(target);
    };

    var component = this.subject();
    var $component = this.append();

    var targetObject = {
      externalAction: function() {
        ok(true, 'external action called');
      }
    };

    component.set('keyUpAction', 'externalAction');

    component.set('targetObject', targetObject);

    $component.keyup();
});

The component I was testing looks like this:
export default Ember.TextField.extend({
  triggerKeyUpAction: function() {
    this.sendAction('keyUpAction', event);
  },

  keyUp: function(/*event*/) {
    Ember.run.debounce(this, this.triggerKeyUpAction, 200);

    if(!this.get('value')){
      return;
    }

    this.set('value', String(this.get('value')).replace(/[^\d\.\,]/g, ''));
  }
});

A: Add
await settled();

Before your assertion
See https://guides.emberjs.com/v3.15.0/testing/testing-components/#toc_waiting-on-asynchronous-behavior it has a specific example for Ember debounce.
Took me a while to find this :).


text:
Q: up-to-date TeX distribution In order to use the "LGRx package" I've been told in a previous question that I've made, that I should have an up-to-date TeX distribution.
So, I wonder what is this and how can I install it to my PC?
Note that my OS is the windows 7.

A: As of today, MikTeX  version 2.9 is the latest stable distribution, so you should be fine for now.
However, for future refence (and based on Torbjorn), you should check:
How do I update my TeX distribution?
Also, I recommend you give a little read to this question, since you are also trying to use a package:
How often do I have to synchronize MikTeX?


text:
Q: Problem with empty values in MMS proxy and MMS Port while sending MMS I am trying to send MMS programatically by using the post How to send image via MMS in Android? ....
I am trying to retrieve the APN values MMSC, MMSProxy and MMSPort , but I am getting empty values for the MMSProxy and MMSPort..  then I checked for these values in my HTC device by navigating  "Settings-->Wireless&Networks-->MobileNetworks-->AccessPointNames-->MMS-->"
but here actually nothing is was set for MMSProxy and MMSPort....
but I am able to send MMS manually..
Please help me in how to get MMSProxy and MMSPort values..  or plz tell me if built-in MMS application will use any other mechanism to send MMS..??
plz help me in this...

A: It might not matter, proxy can mean an "alternate" route. maybe sending MMS doesn't need an alternate route so it's null?
the built in MMS app uses a class called TransactionSettings.java and that class queries the Telephony content provider, code excerpt.
public TransactionSettings(Context context, String apnName) {
    String selection = (apnName != null) ? APN + "='" + apnName.trim() + "'" : null;

    Cursor cursor = SqliteWrapper.query(context, context.getContentResolver(), Uri.withAppendedPath(Uri.parse(TELEPHONY_CONTENT_URI), "current"),
            APN_PROJECTION, selection, null, null);

    if (cursor == null) {
        Log.e(TAG, "Apn is not found in Database!");
        return;
    }

    boolean sawValidApn = false;
    try {
        while (cursor.moveToNext() && TextUtils.isEmpty(mServiceCenter)) {
            // Read values from APN settings
            if (isValidApnType(cursor.getString(COLUMN_TYPE), APN_TYPE_MMS)) {
                sawValidApn = true;
                mServiceCenter = cursor.getString(COLUMN_MMSC).trim();
                mProxyAddress = cursor.getString(COLUMN_MMSPROXY);
                if (isProxySet()) {
                    String portString = cursor.getString(COLUMN_MMSPORT);
                    try {
                        mProxyPort = Integer.parseInt(portString);
                    } catch (NumberFormatException e) {
                        if (TextUtils.isEmpty(portString)) {
                            Log.w(TAG, "mms port not set!");
                        } else {
                            Log.e(TAG, "Bad port number format: " + portString, e);
                        }
                    }
                }
            }
        }
    } finally {
        cursor.close();
    }

That being said, I use this method and still get null values.
Maybe you had better luck?


text:
Q: Gulp error, cannot find module 'vinyl' I have been struggling with getting flux/react to work properly and thought that my npm, node or gulp versions were to old.
So I updated everything to the latest version and now I get the following error when i run gulp in ALL my projects:
module.js:340
throw err;
^

Error: Cannot find module 'vinyl'
      at Function.Module._resolveFilename (module.js:338:15)
      at Function.Module._load (module.js:289:25)
      at Module.require (module.js:366:17)
      at require (module.js:385:17)
      at Object.<anonymous> (/usr/local/lib/node_modules/gulp/node_modules/gulp-util/index.js:2:9)
      at Module._compile (module.js:425:26)
      at Object.Module._extensions..js (module.js:432:10)
      at Module.load (module.js:356:32)
      at Function.Module._load (module.js:313:12)
      at Module.require (module.js:366:17)

I have:

*

*Uninstalled node and gulp through npm.

*Uninstalled npm.

*Installed node and npm via https://nodejs.org/en/

*Installed gulp through npm

And it's still not working..
Anyone have any ideas?

A: As @keithRousseau pointed out, when I reinstalled the packages I forgot to install them with the parameter -g to install them as global packages.
Reinstalled them with -g and now it works!


text:
Q: Select from one table but filtering other two Let's say i've got this database:
 book
| idBook | name     |
|--------|----------|
|      1 |Book#1    |

category
| idCateg| category |
|--------|----------|
|      1 |Adventures|
|      2 |Science F.|

book_categ
| id     | idBook | idCateg  |   DATA |
|--------|--------|----------|--------|
|   1    |      1 |       1  | (null) |
|   2    |      1 |       2  | (null) |

I'm trying to select only the books which are in category 1 AND category 2 something like this
SELECT book.* FROM book,book_categ
WHERE book_categ.idCateg = 1 AND book_categ.idCateg = 2

Obviously, this giving 0 results becouse each row has only one idCateg it does work width OR but the results are not what I need. I've also tried to use a join, but I just can't get the results I expect.
Here it's the SQLFiddle of my current project, with my current DB, the data at the begining is just a sample. SQLFiddle
Any help will be really appreciated.

A: Solution using EXISTS:
select *
  from book b
 where exists (select 'x'
          from book_categ x
         where x.idbook = b.idbook
           and x.idcateg = 1)
   and exists (select 'x'
          from book_categ x
         where x.idbook = b.idbook
           and x.idcateg = 2)

Solution using join with an inline view:
select *
  from book b
  join (select idbook
          from book_categ
         where idcateg in (1, 2)
         group by idbook
        having count(*) = 2) x
    on b.idbook = x.idbook

A: You could try using ALL instead of IN (if you only want values that match all criteria to be returned):
SELECT book.*
FROM book, book_categ
WHERE book_categ.idCateg = ALL(1 , 2)

A: One way to get the result is to do join to the book_categ table twice, something like
SELECT b.*
  FROM book b
  JOIN book_categ c1
    ON c1.book_id = b.id
   AND c1.idCateg = 1
  JOIN book_categ c2
    ON c2.book_id = b.id
   AND c2.idCateg = 2

This assumes that (book_id, idCateg) is constrained to be unique in the book_categ table. If it isn't unique, then this query can return duplicate rows.  Adding a GROUP BY clause or the DISTINCT keyword will eliminate any generated duplicates.
There are several other queries that can get generate the same result.
For example, another approach to finding book_id that are in two categories is to get all the rows with idCateg values of 1 or 2, and then GROUP BY book_id and get a count of DISTINCT values...
SELECT b.*
  FROM book b
  JOIN ( SELECT d.book_id
           FROM book_categ d
          WHERE d.idCateg IN (1,2)
          GROUP BY d.book_id
         HAVING COUNT(DISTINCT d.idCateg) = 2
       ) c
   ON c.book_id = b.id


text:
Q: Book where a guy is saved by his glow-in-the-dark watch? A guy ends up in another (possibly parallel) world where there are primitive humanoids living in a barren land. There are also huge single-cell organisms. Because he has a glow-in-the-dark watch which contains some radioactivity, he is able to enter and kill a single-cell organism, thus creating fertile ground for agriculture.
I could swear it was called Dimension D but I can't find it by googling that title. I probably read it in the late 70's and I'd say it was fairly new at the time. I would like to confirm the book's title and author.


text:
Q: ValueError: shapes (1,6) and (5,5) not aligned: 6 (dim 1) != 5 (dim 0) The NN must have 5 inputs, 4 hidden layers and 1 output. Learning rate 0.2, error threshold 0.2. Retrieves the data from an excel:

The error ValueError: shapes (1,6) and (5,5) not aligned: 6 (dim 1) != 5 (dim 0) is being displayed. I think I have something wrong with multiplying of weights and matrices the error line: hidden_in = np.dot(inputs, w1). I can't seem to solve it. Can someone help?
def train(inputs_list, w1, w2, w3, targets_list, lr, error):
   ....
    while global_error > error:
        # local error
        local_error = np.array([])

        for i, inputs in enumerate(inputs_list):
            # translates the inputs sheet into a two-dimensional view (to enable the transposition operation)
            inputs = np.array(inputs, ndmin=2)
            print("Inputs", inputs)
            # targets - contains the local target for this input
            targets = np.array(targets_list[i], ndmin=2)
            print("Target should be 1", targets)
            # forward propagation
            # scalar product of string and weight matrix
            hidden_in = np.dot(inputs, w1)
            # apply an activation function to a vector
            hidden_out = f(hidden_in)
            # adding an imaginary unit to the beginning of the vector to train the network
            hidden_out = np.array(np.insert(hidden_out, 0, [1]), ndmin=2)
            # scalar product of string and weight matrix
            hidden_in2 = np.dot(hidden_out, w2)
            # apply an activation function to a vector
            hidden_out2 = f(hidden_in2)
            # adding an imaginary one to the beginning of the vector
            hidden_out2 = np.array(np.insert(hidden_out2, 0, [1]), ndmin=2)

            # scalar product of string and weight matrix
            final_in = np.dot(hidden_out2, w3)
            # the activation function of the output layer is a straight line y = x, so
            # here the value of "out" is equal to the value of "in"
            final_out = final_in

            # output layer error calculation
            output_error = targets - final_out

            # calculating the error of the second hidden layer
            hidden_error2 = np.dot(output_error, w3.T)
            # calculating the error of the first hidden layer
            hidden_error = np.dot(hidden_error2[:, 1:], w2.T)
            # adding the current error to the list of local errors
            local_error = np.append(local_error, output_error)
            # error backpropagation
            # changing the weight matrix 3 because derivative of the activation function (y = x)
            # y` = 1 in dW = lr*output_error*hidden_out2.T is not multiplied by this derivative
            w3 += lr * output_error * hidden_out2.T
            # in the backpropagation method, the imaginary one is excluded for the coincidence of dimensions
            # hidden_error2[:,1:] - means the whole vector except for the first element
            w2 += lr * hidden_error2[:, 1:] * f1(hidden_out2[:, 1:]) * hidden_out.T
            w1 += lr * hidden_error[:, 1:] * f1(hidden_out[:, 1:]) * inputs.T
        # global error is the module average of all local errors
        global_error = abs(np.mean(local_error))
        # global_error = np.sqrt(((local_error) ** 2).mean())
        last_gl_e = global_error
        # epoch incremented by 1
        era += 1
        # output to the console the current global error
        # print('era=',era, 'global_error=', global_error, 'k_sup=', k_sup)
        # a global error is added to the list of errors
        list_error.append(global_error)
        # if during training the number of epochs exceeds the threshold of 10000, then training will stop
        if era > 1000:
            print('gl=', global_error)
            break
        # returns the modified weights, number of epochs, and list of errors
    print(global_error)
    return w1, w2, w3, era, list_error

# function to test the trained network and output the result
def query(inputs_list, w1, w2, w3):
    # create a list in which we will store "outs" for the test set
    final_out = np.array([])
    for i, inputs in enumerate(inputs_list):
        # forward propagation just like training for "out"
        inputs = np.array(inputs, ndmin=2)

        hidden_in = np.dot(inputs, w1)
        hidden_out = f(hidden_in)
        hidden_out = np.array(np.insert(hidden_out, 0, [1]), ndmin=2)

        hidden_in2 = np.dot(hidden_out, w2)
        hidden_out2 = f(hidden_in2)
        hidden_out2 = np.array(np.insert(hidden_out2, 0, [1]), ndmin=2)

        final_in = np.dot(hidden_out2, w3)

        final_out = np.append(final_out, final_in)
    # return the value of the vector "out" rounded to an integer
    return np.around(final_out)

# read data from csv using pandas library
# Titanic Passenger Data
# Set the column that will be indexed index_col='PassengerId'
data_titanic = "titanic_dataset.csv"
data = pd.read_csv(data_titanic)
# column Survived from data
# .values means that the data from the dataframe is converted to a numpy array
target_data = data['Survived'].values
# remove the Survived column from the dataset and convert it to an array
# data = data.drop(columns=['Survived']).values
data = data.drop('Survived', 1).values
# compose a sample of the training set from the first 600 rows of the dataset
inputs = data[0:600]
# add a column of imaginary ones for the set
inputs = np.c_[np.ones(600), inputs]
# compose the target set
targets = target_data[0:600]

# from the remaining 114 lines we make a test set
test = data[600:714]
test = np.c_[np.ones(114), test]
targets_test = target_data[600:714]

# learning rate
lr = 0.2
# allowable learning error (** is the degree)
eps = 0.2

# number of nodes in the input layer, taking into account one
# i.e. number of dataset columns +1 imaginary one
input_layer = 5

hidden_layer = 4
hidden_layer2 = 2

output_layer = 1

# initialization of weights depending on the number of nodes in the network layers
w1, w2, w3 = init_weight(input_layer, hidden_layer, hidden_layer2, output_layer)

w1, w2, w3, era, lst = train(inputs, w1, w2, w3, targets, lr, eps)

A: Going by the convention that of weights are (n_neurons, n_inputs), I think the shape of your first hidden layer (W1) should be  -> number of neurons in that layer, number of attributes/features in the sample.
Assuming you are outputing the Survived column, your features should be 5.
If there are 4 neurons in that layer, then the shape is (4,5) and your input's shapes will be (n_features, number_of_samples in a batch = m) or (5,m).
In this case the hidden_in = np.dot(inputs, w1) should be of shape (4,m).
I believe your error might be that you are including the Survived in the input data as well.


text:
Q: Expression, phrase, or idiom that describes lazy team members/coworkers who work only on the least important and demanding tasks I'm looking for a expression, idiom, or even proverb that could be used to describe situations like

*

*In a work environment where it becomes apparent that coworkers set aside  duties that require prompt attention for other duties that are not time-sensitive or just ignore  them because they want other coworkers to attend to it.

*Calling out a lazy quality you notice in individuals on a group project that take on the least demanding tasks.

*Cherrypicking work duties that one likes to do again and again while leaving the latter for others to do. Typically the most difficult.
It is not perfect but what comes to my mind is:

I'm not gonna play hot potato with you on [describes the work]"

It sounds a bit intense but

While you focus on extinguishing the candle, I'll focus on the forest fire.


text:
Q: UIImagePickerController allowsEditing issue I am using a UIImagePickerController to take an image through the camera and by setting allowsEditing to true I had hoped to crop the image to a perfect square such as Instagram, ect. I understand there has been a bug since iOS 6 resulting in the cropping box not being able to be dragged. I have been looking for a solution on how to make what I want to happen work, except I can't find anything in Swift. Does anyone know where I should look. By the way the code is this:
if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){
    //load the camera interface
    var picker : UIImagePickerController = UIImagePickerController()
    picker.sourceType = UIImagePickerControllerSourceType.Camera
    picker.delegate = self
    picker.allowsEditing = true
    self.presentViewController(picker, animated: true, completion: nil)
    self.resetBottomBar()
}else{
    //no camera available
    var alert = UIAlertController(title: "Error", message: "There is no camera available", preferredStyle: .Alert)
    alert.addAction(UIAlertAction(title: "I Kno.", style: .Default, handler: {(alertAction)in
    alert.dismissViewControllerAnimated(true, completion: nil)
    }))
}


text:
Q: How to score all user-product combinations in Spark MatrixFactorizationModel? Given a MatrixFactorizationModel what would be the most efficient way to return the full matrix of user-product predictions (in practice, filtered by some threshold to maintain sparsity)?
Via the current API, once could pass a cartesian product of user-product to the predict function, but it seems to me that this will do a lot of extra processing.
Would accessing the private userFeatures, productFeatures be the correct approach, and if so, is there a good way to take advantage of other aspects of the framework to distribute this computation in an efficient way? Specifically, is there an easy way to do better than multiplying all pairs of userFeature, productFeature "by hand"?

A: Spark 1.1 has a recommendProducts method that can be mapped to each user ID. This is better than nothing but not really optimized for recommending to all users.
I would double-check that you really mean to make recommendations for everyone; at scale, this is inherently a big slow operation. Consider predicting for users that have been recently active only.
Otherwise, yes your best bet is to create your own method. The cartesian join of the feature RDDs is probably too slow as it's shuffling so many copies of the feature vectors. Choose the larger of the user / product feature set, and map that. In each worker, hold the other product / user feature set in memory in each worker. If this isn't feasible you can make this more complex and map several times against subsets of the smaller RDD in memory.

A: As of Spark 2.2, recommendProductsForUsers(num) would be the method.

Recommends the top "num" number of products for all users. The number of recommendations returned per user may be less than "num".

https://spark.apache.org/docs/2.2.0/api/python/pyspark.mllib.html


text:
Q: Increase chance of rare loot drops I have the Vault Hunter's Relic which increases the chance of rare loot drops by 5%. Unfortunately, I am very displeased with the rarity settings of the game in general. I would like to know if there is any way to mod the game to make vending machines and enemies drop rare loot more often.
For example, it would be nice if that 5% in the Relic could be upped to something like 25%. I am level 21 at the moment and almost all of the weapons and stuff I find and see in vending machines is white. It is a rare pleasure to see green stuff, and blue/purple almost never happens. I would like to somehow mod this game to make rare stuff at least somewhat less rare.
If anybody knows of a way to do this either by modding the game or the relic above, I'd really appreciate it. I don't want to cheat completely via the golden chest, btw, just increase the chance of getting rare items in general.

A: The Vault Hunter's Relic only drops the chances of white item drops by 5% and then splits that 5% between the green and blue drops.  so say if the odds of drops are:
No drop:40%, white:30%, green:15%, blue:10%, purple:5%, orange:Only on named & bosses (and often about 1% or less there) OR 3 borderlands symbols on a slot machine (about a 1 in 5,000 chance)
The Vault Hunters Relic would only make that:
No drop:40%, white:25%, green:18%, blue:12%, purple:5%, orange:Only on named & bosses (and often about 1% or less there) OR 3 borderlands symbols on a slot machine (about a 1 in 5,000 chance)
assuming those numbers were accurate (the orange is pretty close but the others I am mearly speculating) then even if it were modded to be a 30% better chance (thus eliminating white drops all together) it would still only be about: None:40%, White:0%, Green:38%, Blue:17%, Purple:5%, Orange:special.
No modding of %'s will make the Vault Hunters Relic really worth wearing once others become an option. Better to wear a relic that works to improve your strengths (such as an elemental boost on a siren or a brand-specific relic that helps boost your best weapon) or compensate for a weakness (+shield capacity or max health if you find yourself dying too easily).

A: A few of my friends had an idea to get four of us in a co-op game, that itself will give you a boost in the rare item drops,
but we had a thought that what if we all equiped the vault hunters relic, will it put the rare drop up to 20%??
why dont you see if you can get 3 other friends together with that relic, and see what happens.
hope that helps somewhat