text:
Q: Evaluating (...) in a function argument in R I have the following functions:
ignore <- function(...) NULL
tee <- function(f, on_input = ignore, on_output = ignore) {
function(...) {
    on_input(...)
    output <- f(...)
    on_output(output)
    output
  }
}

My question would be on how is the (...) expression evaluated in the on_input in the tee function? I understand that in the case of ignore function,  it will simply take any arguments and still return a NULL value. However, I am unsure if on_input and on_output are functions and also on what will happen to the on_input and output function in this case?

A: you took that code from Wickham Book Advanced R.
In this book you can find an example
g <- function(x) cos(x) - x
zero <- uniroot(g, c(-5, 5))
show_x <- function(x, ...) cat(sprintf("%+.08f", x), "\n")

# The location where the function is evaluated:
zero <- uniroot(tee(g, on_input = show_x), c(-5, 5))

You can imagine that on_input and on_output are function that work with the input and the output of the function.
In this case for example you are printing the input of each iteration on the g function.
zero <- uniroot(tee(g, on_output = show_x), c(-5, 5))

On this case on the contrary you are printing the output of the function on each iteration.
To summarise, yes on_input and on_output are functions and this function simply work with the input and the output of the function f.
EDIT
Just an easier example to understand what is going on
pow2<-function(x){x^2}
input<-function(x){
  cat(paste("input is ",x,"\n",sep=""))
}
output<-function(x){
  cat(paste("output is ",x,"\n",sep=""))
}

tee(pow2,on_input=input,on_output=output)(2)

input is 2
output is 4
[1] 4

the main function here is obviously pow2
tee take pow2 and return a function that run on_input, pow2 and on_output.
Notice also that you have to call and pass an argument to the result of tee, in fact tee is returning a function and not a value
(...) match all additional arguments passed


text:
Q: Uncaught type error & Uncaught reference error while calling EXTJS method from JSP Small part of the XTJS code :
Ext.define('MyApp.Alarms.Exporter', {
namespace : undefined,
exportMax : undefined,
pdfLink : undefined,
excelLink : undefined,
totalAlarms : 0,
//UI
windowDialog : undefined,

constructor : function(namespace, pdfLink, excelLink,
        exportMax) {
    this.namespace = namespace;
    this.pdfLink = pdfLink;
    this.excelLink = excelLink;
    this.exportMax = exportMax;
},

setTotalAlarms : function(value) {
    this.totalAlarms = value;
},

doExport : function(format) {
    var url = '';
    var totalAlarms = this.totalAlarms;

    if (totalAlarms > this.exportMax) {
        if (this.exportMax != 0) {
            totalAlarms = this.exportMax;
        }
    }

    if (totalAlarms > 0) {
        if (format == 'pdf') {
            url = this.pdfLink;
        } else {
            url = this.excelLink
        }

        this.show(url, totalAlarms);
    } else {
        Ext.Msg.show({
            title : 'Export Alarms',
            msg : 'There are no alarms to export',
            buttons : Ext.Msg.OK,
            icon : Ext.Msg.INFO
        });
    }
}

});
JSP Code:
Create the object AlarmsExporter with a random namespace
    if (typeof <%= table.getNamespace() %>AlarmsExporter == 'undefined') {
    <%= table.getNamespace() %>AlarmsExporter = Ext.create('MyApp.Alarms.Exporter', '<%=table.getNamespace()%>', '<%=Util.encodeUrl(request, response, table.getPdfLink())%>', '<%=Util.encodeUrl(request, response, table.getExcelLink())%>', '<%= Util.getNumAlarmsExport()%>');
}

Call the ext method doExport()
            <a href="javascript:<%= table.getNamespace() %>AlarmsExporter.doExport('xls');">
           <img src="<%= xlsIcon %>" alt="Save as Excel Spreadsheet">

        <a href="javascript:<%= table.getNamespace() %>AlarmsExporter.doExport('pdf');">
           <img src="<%= pdfIcon %>" alt="Save as PDF"/>

Now when I'm clicking those link I am getting error that :
Uncaught TypeError: object is not a function

and
Uncaught ReferenceError: _mo_navigation_WAR_ManagedObjectsPortlets_INSTANCE_Bk8L_AlarmsExporter is not defined

A: Because the .js file which contains the extjs code is either missing or not reachable from your JSP. Check in the JSP that are you including the .js or the path is correct or not.
I believe this should fix your problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the best way to train marines? When training marines, there are 4 options: Hacking, Mechanical, Engineering and All Skills. Does training all skills simply distribute the experience a marine would receive by focusing on one skill to all three, or is it actually faster? Similarly, do the 3 different levels of training (Quick, Normal, Advanced) have the same teaching rate, or are more expensive options faster?
What's the fastest way for a marine to achieve maximum skill in:

*

*Engineering and Hacking or Mechanical;

*All three skills.

A: Advanced training all skills is most cost-effective. But training time increase radicaly with current skill of marine.
According to this discussion, you don`t need all marines trained in all skills. During boarding checked skills of 1 or 2 marines.
Use of Boarding pod increase Engineering skill.


text:
Q: Anchor to portion of table I need an anchor to a portion of an HTML table.
I have the following code that is in a page called Speakers.html:

Phil Mat

From another page I have the following:

Phil Mat

when I click on the above link, it does not go to the designated area. Am I doing something wrong?

A: You need to give id attribute to your link


text:
Q: Linking against a specific shared library version in linux My build process consists of Qt's qmake Makefile generator and the typical make utility bundled with linux.
My application consists of a few shared libraries and the main application is linked against them.
How can I apply the typical linux versioning scheme on my libraries? (Use version 2 -> link against foo.so.2 that points to foo.so.2.y.z with an ldconfig generated link).
The answer doesn't have to be specific for my build process.

A: Your library should be named libfoo.so.2.y.z, with symlinks of libfoo.so.2 and libfoo.so both pointing to that. The library should be created using -soname libfoo.so.2 in the linker command line (or -Wl,-soname,libfoo.so.2 on the gcc command line).
Hope that helps!


text:
Q: Design of Google Play Services wanted to understand more about the design of google play services.
like to use it we need to create an object of GoogleApiClient(see below code) and then we need to add API to which we are interested.
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */,
                  this /* OnConnectionFailedListener */)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.build();

can any body help me how they built it this whole mechanism.
this article is help full
http://wiresareobsolete.com/2016/06/play-services-complexity/
but i want to understand more details.

A: You could try the official document - Overview of Google Play Services

With Google Play services, your app can take advantage of the latest, Google-powered features such as Maps, Google+, and more, with automatic platform updates distributed as an APK through the Google Play store. This makes it faster for your users to receive updates and easier for you to integrate the newest that Google has to offer.

An illustration showing how the Google API Client provides an interface for connecting and making calls to any of the available Google Play services such as Google Play Games and Google Drive.
To get started, you must first install the Google Play services library (revision 15 or higher) for your Android SDK. If you haven't done so already, follow the instructions in Set Up Google Play Services SDK.

Here is a code sample for an activity that implements the callback interfaces and adds them to the Google API Client:
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import gms.drive.*;
import android.support.v4.app.FragmentActivity;

public class MyActivity extends FragmentActivity
        implements OnConnectionFailedListener {
    private GoogleApiClient mGoogleApiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Create a GoogleApiClient instance
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */,
                                  this /* OnConnectionFailedListener */)
                .addApi(Drive.API)
                .addScope(Drive.SCOPE_FILE)
                .build();

        // ...
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // An unresolvable error has occurred and a connection to Google APIs
        // could not be established. Display an error message, or handle
        // the failure silently

        // ...
    }
}


text:
Q: Javascript converted to Excel VB Function Produces #NUM! error Hey guys, I have a javascript function that produces a 12 digit UPC code (Based on the first 11 digits:
function ccc12(rawVal) {
  factor = 3;
  sum = 0;
  rawVal = rawVal.toString();
  if (rawVal.length!=11){
      throw "The UCC-12 ID Number requires that you enter 11 digits.";
  }
  for (index = rawVal.length; index > 0; --index) {
    sum = sum + rawVal.substring (index-1, index) * factor;
    factor = 4 - factor;
  }
  return ((1000 - sum) % 10);
}

Assuming the above if I gave 84686400201 as the rawVal, then 2 would be the outcome returned.
This was then converted to
Function generateUPC(upcCode As Integer) As String
    Dim upcCheckDigit, factor, sum As Integer
    Dim upcString As String
    factor = 3
    sum = 0

    For i = Len(upcCode) To 0 Step -1
        sum = sum + Mid(upcCode, i - 1, 1) * factor
        factor = 4 - factor
    Next i
    upcCheckDigit = ((1000 - sum) Mod 10)
    upcString = upcCode & upcCheckDigit

    generateUPC = upcString
End Function

This function returns the original string plus the last digit, but instead i get #NUM! in the worksheet when I put =generateUPC(84686400201) into the cell.
Any ideas? Never really bothered doing VB Macros etc before so this is new to me

A: VBA integers are -32k to +32k
VBA Longs are -2B to +2B
Your 'upcCode' integer is larger than the long data type so I tried it with Double, which is a float, but works:
Function generateUPC(upcCode As Double) As String
    Dim upcCheckDigit, factor, sum As Double
    Dim upcString As String
    factor = 3
    sum = 0

    For i = Len(upcCode) To 0 Step -1
        sum = sum + Mid(upcCode, i - 1, 1) * factor
        factor = 4 - factor
    Next i
    upcCheckDigit = ((1000 - sum) Mod 10)
    upcString = upcCode & upcCheckDigit

    generateUPC = upcString

End Function

A: I suggest changing upcCode to a string to avoid overflow and changing the indexes of your loop and within the Mid function to avoid out-of-bounds errors.
Function generateUPC(upcCode as String) As String
    Dim upcCheckDigit, factor, sum As Integer
    Dim upcCode, upcString As String
    factor = 3
    sum = 0

    For i = Len(upcCode) To 1 Step -1
        sum = sum + Mid(upcCode, i, 1) * factor
        factor = 4 - factor
    Next i
    upcCheckDigit = ((1000 - sum) Mod 10)
    upcString = upcCode & upcCheckDigit

    generateUPC = upcString
End Function


text:
Q: How to create a function in typescript 1.I have the data like below:
[{
    "BatchConfigName": "End1",

    "EndDateTime": "2019-01-06T11:10:00"
  },
  {
    "BatchConfigName": "End2 - Non-Gas",

    "EndDateTime": "2019-01-07T05:54:00"
  },
  {
    "BatchConfigName": "Secure",

    "EndDateTime": "2019-01-07T04:48:00"
  }
}

*i want to create the typescript function that assign this data like
var datawebsiteViewsChart = {
labels: ['End1', 'End2 - Non-Gas', 'Secure'],
series: [
    [11: 10, 05: 54, 04: 48]
]
};

None

A:
function map(data) {
    const labels = [];
    const series = [];

    for (itemKey of data) {
        labels.push(itemKey);
        series.push(data[itemKey]);
    }

    return {
        labels,
        series
    };
}


text:
Q: Is it safe to use a 10.8v battery on a laptop that normally uses a 14v battery? My friend just bought a a 10.8v battery for her toshiba satellite that previously used a 14v battery I just need to know if there will be any problems if she uses her new battery.

A: Generally it's a "bad" idea to use anything that isn't a perfect match in terms of voltage.
Over-voltage may damage components (permanently) and should be avoided.
Under-voltage may cause components to be unable to function (but is unlikely to cause permanent damage); it might not work at all, it might work unreliably, it might work fine.
In this case, we're looking at under-voltage - which, as said, might work but I'd personally still recommend against it. And don't forget that the amperage and/or power output of the batteries should be compared as well, it's also important.
If your friend insists on using a weaker battery, I'd advice they turn down all the power settings to the lowest options they can stand.

A: Generally a bad idea if they're that much different.  I'm surprised that it would fit.  Usually the manufacturers go out of their way to make the cases different if the battery is incompatible with another one in their line.  If new battery is not from Toshiba I'd be even more wary.


text:
Q: How to undo init in a cloned git repository I have a git repository cloned from the remote master. I ran init on the local cloned copy by mistake, my bad. So its now a brand new repo to git and git remote etc don't show any connection to the remote origin, of course. How can I 'reparent' or tell it again what's its remote origin is/was?

A: Running git init in an existing repository does not produce any harm. The documentation says:

Running git init in an existing repository is safe. It will not overwrite things that are already there. The primary reason for rerunning git init is to pick up newly added templates (or to move the repository to another place if --separate-git-dir is given).

At least it doesn't remove the remotes, as you say. You probably ran git init in a subdirectory and it created a new repository there. In that case, git has created a hidden .git/ folder in that subdirectory. Find it and remove it.
If this is not the case and the repository you cloned was affected somehow, there is a simple way to repair it. Add the original repo as a remote and fetch all the commits from it again.
git remote add origin url-of-the-repo-you-cloned-before
git fetch origin

Now your repo contains all the commits that are present in the remote repository. What you do next depends on what you did before you found out the commits are gone. Run git status to decide. If you are on the correct branch then you can continue working and commit at some point. If you are not on the branch you want (or you are not on a branch at all) then you can try to git checkout the branch you need. If it doesn't work because it would replace files that you modified and didn't commit then you have to stash your changes, checkout the new branch and pop the changes from the stash (git stash, git checkout correct-branch, git stash pop).


text:
Q: git - automatically git reset after trying to pick a commit that I already have I'm trying to git cherry-pick start..end, and I already have a lot of commits commited that are in start..end and each time it tries to pick one there is I get such message:
On branch master
Your branch is ahead of 'origin/master' by 9 commits.
  (use "git push" to publish your local commits)

You are currently cherry-picking commit e0a5d27bed8.

nothing to commit, working tree clean
The previous cherry-pick is now empty, possibly due to conflict resolution.
If you wish to commit it anyway, use:

    git commit --allow-empty

If you wish to skip this commit, use:

    git reset

Then "git cherry-pick --continue" will resume cherry-picking
the remaining commits.

I have tried using rev-list like this: git rev-list --remove-empty --reverse start..end . | git cherry-pick --stdin
with adding --remove-empty and a . but that does not help.
Is there a way to do to skip these type of commits?


text:
Q: (Python) Bittrex API v3 keeps returning invalid content hash Writing a bot for a personal project, and the Bittrex api refuses to validate my content hash. I've tried everything I can think of and all the suggestions from similar questions, but nothing has worked so far. Tried hashing 'None', tried a blank string, tried the currency symbol, tried the whole uri, tried the command & balance, tried a few other things that also didn't work. Reformatted the request a few times (bytes/string/dict), still nothing.
Documentation says to hash the request body (which seems synonymous with payload in similar questions about making transactions through the api), but it's a simple get/chcek balance request with no payload.
Problem is, I get a 'BITTREX ERROR: INVALID CONTENT HASH' response when I run it.
Any help would be greatly appreciated, this feels like a simple problem but it's been frustrating the hell out of me. I am very new to python, but the rest of the bot went very well, which makes it extra frustrating that I can't hook it up to my account :/
import hashlib
import hmac
import json
import os
import time
import requests
import sys

# Base Variables
Base_Url = 'https://api.bittrex.com/v3'
APIkey = os.environ.get('B_Key')
secret = os.environ.get('S_B_Key')
timestamp = str(int(time.time() * 1000))
command = 'balances'
method = 'GET'
currency = 'USD'
uri = Base_Url + '/' + command + '/' + currency

payload = ''
print(payload)  # Payload Check

#  Hashes Payload
content = json.dumps(payload, separators=(',', ':'))
content_hash = hashlib.sha512(bytes(json.dumps(content), "utf-8")).hexdigest()
print(content_hash)

#  Presign
presign = (timestamp + uri + method + str(content_hash) + '')
print(presign)

# Create Signature
message = f'{timestamp}{uri}{method}{content_hash}'
sign = hmac.new(secret.encode('utf-8'), message.encode('utf-8'),
hashlib.sha512).hexdigest()

print(sign)

headers = {
    'Api-Key': APIkey,
    'Api-Timestamp': timestamp,
    'Api-Signature': sign,
    'Api-Content-Hash': content_hash
    }
print(headers)

req = requests.get(uri, json=payload, headers=headers)
tracker_1 = "Tracker 1: Response =" + str(req)
print(tracker_1)

res = req.json()

if req.ok is False:
    print('bullshit error #1')
    print("Bittex response: %s" % res['code'], file=sys.stderr)

A: I can see two main problems:

*

*You are serialising/encoding the payload separately for the hash (with json.dumps and then bytes) and for the request (with the json=payload parameter to request.get). You don't have any way of knowing how the requests library will format your data, and if even one byte is different you will get a different hash. It is better to convert your data to bytes first, and then use the same bytes for the hash and for the request body.

*GET requests do not normally have a body (see this answer for more details), so it might be that the API is ignoring the payload you are sending. You should check the API docs to see if you really need to send a request body with GET requests.


text:
Q: What is the difference between setlevel and addfilter in logging python I have recently started implementation logging in python. I have a hard time in understanding the difference between the setlevel and addfilter methods of logging. I feel they serve the same purpose. For ex, if we add logger.setlevel(debug) and logger.addfilter(logging.debug), they output same records. isn't?

A: According to the documentation:

The base filter class only allows events which are below a certain
  point in the logger hierarchy. For example, a filter initialized with
  'A.B' will allow events logged by loggers 'A.B', 'A.B.C', 'A.B.C.D',
  'A.B.D' etc. but not 'A.BB', 'B.A.B' etc. If initialized with the
  empty string, all events are passed.
Note that filters attached to handlers are consulted before an event
  is emitted by the handler, whereas filters attached to loggers are
  consulted whenever an event is logged (using debug(), info(), etc.),
  before sending an event to handlers. This means that events which have
  been generated by descendant loggers will not be filtered by a
  logger's filter setting, unless the filter has also been applied to
  those descendant loggers.

A: I think i found the answer myself. Filter is designed to let us add additional function-based filters on top of the level-based filtering that is done by default.
I found the answer from the link: https://realpython.com/python-logging-source-code/#the-filter-and-filterer-classes


text:
Q: Show that $\sum\limits_{n=1}^{\infty}\frac{x}{1+n^2x^2}$ is not uniformly convergent in $[0,1]$
Show that $\sum\limits_{n=1}^{\infty}\frac{x}{1+n^2x^2}$ is not uniformly convergent in $[0,1]$.

I was thinking in the direction of taking the maximum value of each term $\frac{x}{1+n^2x^2}$, which is $\frac{1}{2n}$, and of summing them. That is clearly a divergent series.
But then those maximum values don't occur at the same value of $x$ for each term. For the $n$th term the maximum occurs at $x = \frac{1}{n}$.
So, how to proceed?

A: You are on the right track. For clarity, let's denote the partial sum $\sum_{n = 1}^N \frac{x}{1 + n^2x^2}$ by $S_N(x)$. One way to show the result is to investigate $\sup_{x \in [0, 1]}|S_{2N}
(x) - S_{N}(x)|$:
\begin{align}
\sup_{x \in [0, 1]} |S_{2N}(x) - S_N(x)| & = \sup_{x \in [0, 1]}\sum_{n = N + 1}^{2N} \frac{x}{1 + n^2x^2} \geq \sum_{n = N + 1}^{2N} \frac{1/N}{1 + n^2/N^2} \\
& \geq \frac{1}{N} \times N \times \frac{1}{1 + (2N)^2/N^2} = \frac{1}{5}
\end{align}
which doesn't converge to $0$ as $N \to \infty$. Thus we do not have uniform convergence (if $\{S_N(x)\}$ converges uniformly, then the above quantity is bounded to converge to $0$ as $N \to \infty$, in view of Cauchy's criterion).

A: The problem is that $$\lim_{x \rightarrow 0}\; \sum_{n=1}^{\infty} \frac{x}{1 + n^2 x^2}$$ is not $0$, so the function defined by the series isn't continuous. You can see that by evaluating at $x = 1/k:$ $$\sum_{n=1}^{\infty} \frac{1/k}{1 + n^2 / k^2}$$ is a Riemann sum for the integral $$\int_0^{\infty} \frac{1}{1+y^2} \, \mathrm{d}y$$ and so it tends to $\pi/2$ as $k \rightarrow \infty.$


text:
Q: Uncertainty of measurement with goniometer I got a goniometer with scale -90 to 90 degree. I use only 0 to 90 degree. One section of the scale has 1 degree. I read a value of $62^\circ$. What is the uncertainty of this measurement?
I thougt like this. If one section has $1^\circ$, then I can be mistaken by half of this value. I could put together range and this error as
$$\frac{90\cdot 0.5}{100 \sqrt{3}} =\pm~ 0.26^\circ$$
or
$$\frac{180\cdot 0.5}{100 \sqrt{3}} =\pm ~ 0.52^\circ$$
What do you think?
I asked this question on Electrical Engineering stack exchange, but they said it doesn't belong to that site. I asked in Physics stack exchange, but nobody responded. Shall I ask this question here?


text:
Q: Does GetSqlValues get hidden fields? I want to know how many columns a query returned in order to create an array of that size for reading the result.
Using an SqlDataReader I want to do something like:
object[] array = new object[rdr.FieldCount];
rdr.GetSqlValues(array);

but I'm not sure if I should use FieldCount or VisibleFieldCount. (I'm not even sure what a hidden field is. But I'll leave that for now.)

A: This is the decompiled code from GetSqlValues()
public virtual int GetSqlValues(object[] values)
{
    SqlStatistics statistics = null;
    int num3;
    try
    {
        statistics = SqlStatistics.StartTimer(this.Statistics);
        this.CheckDataIsReady();
        if (values == null)
        {
            throw ADP.ArgumentNull("values");
        }
        this.SetTimeout(this._defaultTimeoutMilliseconds);
        int num2 = (values.Length < this._metaData.visibleColumns) ? values.Length : this._metaData.visibleColumns;
        for (int i = 0; i < num2; i++)
        {
            values[this._metaData.indexMap[i]] = this.GetSqlValueInternal(i);
        }
        num3 = num2;
    }
    finally
    {
        SqlStatistics.StopTimer(statistics);
    }
    return num3;
}

As you can see the array is checked against the visibleColumns internal value. This is the same value returned by VisibleFieldCount.
As you can see the code checks the length of the passed array and copy a number of columns that could fit in the passed array.  Because (as from docs on VisibleFieldCount) the hidden fields are appended at the end of the internal array if you pass an array of FieldCount element, you will retrieve just the visible fields.


text:
Q: Why does Windows DNS require a double domain suffix? We have a DNS server at work that maps <developername>.zende.sk to each developer's computer so we can see one another's work. These paths are not routable from the WAN. On OSX and on virtualized Windows (which I presume uses the underlying OSX's DNS lookups), I can go to http://me.zende.sk, but this fails on a Windows XP machine.
When I run nslookup me.zende.sk from the Windows machine, I get
Server:  someresolver.com
Address:  1.2.3.4

Non-authoritative answer:
Name:    something.zende.sk
Address:  9.8.7.6
Aliases:  me.zende.sk.zende.sk

I tried going to http://me.zende.sk.zende.sk and it worked like a charm. Why?
I've gone into my networking settings in Windows and fiddled with the "Append primary and connection specific DNS suffxes," "Append parent suffixes of the primary DNS suffix," and "Append these DNS suffixes (in order)" settings, all to no avail.

A: I think your DNS server may be misconfigured - could some entries in the zonefile be lacking the trailing . that is normally required?

A: Go to your network connections, right click on your network adapter and select "Properties".  Look for some kind of IP v4 option (it shows up as Internet Protocol Version 4 (TCP/IPv4) on my Windows 7 system, but will likely be a little different on XP.  Double-click this and then click the Advanced button the window that opens.  Now click on the "DNS" tab.
Here there are several options that control how your domain is appended as a DNS suffix.  I don't know what is set there or what is supposed to be set there - it depends on how your dhcp server is configured.  But whatever you see there now is wrong, and playing with the settings a bit should give you something that works.
And Apple got lucky on this one - Apple's Bonjour/mDNSResponsder service is a steaming pile.


text:
Q: XGBoost feature_names mismatch time series I am trying to predict the stock trend where 1 is the stock increases and 0 is the stock decreases on that particular day. My input features are close price, volume, current  day trend and my output is the trend the next day. When applying XGBClassifier() I encounter an error:
ValueError                                Traceback (most recent call last)
<ipython-input-101-d14cdb520e55> in <module>
      1 val = np.array(test[0, 0]).reshape(1, -1)
      2
----> 3 pred = model.predict(val)
      4 print(pred[0])

~/opt/anaconda3/lib/python3.8/site-packages/xgboost/sklearn.py in predict(self, data, output_margin, ntree_limit, validate_features, base_margin)
    968         if ntree_limit is None:
    969             ntree_limit = getattr(self, "best_ntree_limit", 0)
--> 970         class_probs = self.get_booster().predict(
    971             test_dmatrix,
    972             output_margin=output_margin,

~/opt/anaconda3/lib/python3.8/site-packages/xgboost/core.py in predict(self, data, output_margin, ntree_limit, pred_leaf, pred_contribs, approx_contribs, pred_interactions, validate_features, training)
   1483
   1484         if validate_features:
-> 1485             self._validate_features(data)
   1486
   1487         length = c_bst_ulong()

~/opt/anaconda3/lib/python3.8/site-packages/xgboost/core.py in _validate_features(self, data)
   2058                             ', '.join(str(s) for s in my_missing))
   2059
-> 2060                 raise ValueError(msg.format(self.feature_names,
   2061                                             data.feature_names))
   2062

ValueError: feature_names mismatch: ['f0', 'f1', 'f2', 'f3'] ['f0']
expected f2, f1, f3 in input data

My code is as follows:
def xgb_predict(train, val):
    train = np.array(train)
    x, y = train[:, :-1], train[:, -1]
    model = XGBClassifier()
    model.fit(x, y)

    val = np.array(val).reshape(1, -1)
    pred = model.predict(val)
    return pred[0]

xgb_predict(train, test[0, 0])

I receive an error on the 8th line. Thank you very much for the help:)
Edit: Included a sample of data

A: The column selection of your test data must be done as you do for the train data. This means that your last line should be:
xgb_predict(train, test[0, :-1])

so you can select all columns/features but the last one which is the target value.


text:
Q: About JS and HTML var selectElement = document.getElementById("sel");
for(i = 0; i < names.length; i++) {
    opt = new Option(names[i]);
    selectElement.options.add(opt);
}

I do not understand the meaning of this code " selectElement.options.add(opt);"
could somebody please explain for me, thanks!

A: Here's what each component of your code does:
var selectElement = document.getElementById("sel");

This makes a variable selectElement which represents the element with ID sel.
for(i = 0; i < names.length; i++) {

Makes a variable i which is looped over for each element in the array names.
opt = new Option(names[i]);

Sets opt to an option created with the index in the array names current iteration of i.
selectElement.options.add(opt);

Adds opt to the list of options in the selectElement variable.
}

Ends the for loop


text:
Q: Excel formula to prevent duplicate name entries I am creating a work chart for a project with excel table. However with so many people to manage I have ran into an issue of often putting same person twice on different columns of the same row (he/she can't work on two places at same time!)
So, I am looking for help with a formula that notices if the same name appears twice on a row but does not count multiple blank cells as duplicates. My understanding of excel is very basic and so far I have managed to get this far
=COUNTIF(A6:W6;A6:W6)=1
which returns to me with false, which I assume is because of the blank, unfilled cells still within the table being counted as duplicates.
Help would be appreciated, thanks.

A: You can't have a range as the second argument of a Countif. The range you pass into the formula will resolve to just the first value. Use the Evaluate Formula tool to see what I mean.
If you want to determine if ANY name in the range A1:W1 appears more than once (and exclude blanks), you will need a recursive function. That can only be done with VBA, not with a formula.
You could use a Countif in a conditional format to highlight duplicate names in a row. That's a piece of cake. Pipe up if you want to do that.


text:
Q: Read req.body whether multipart/form-data or application/x-www-form-urlencoded entype form? I'm building a form backend like Formspree on NextJS, so I need to be able to receive all form POSTs at the same endpoint, without being able to control what the forms enctype is set as. I need to be able to read the req.body no matter the enctype, and if it's a multipart form then I need to get the files that are attached to the request too.
Currently I do this by running the request though both multer and bodyparser everytime like so:
    // Middleware helper
    const runMiddleware = (req, res, fn) => new Promise((resolve, reject) => {
      fn(req, res, (result) => {
        if (result instanceof Error) {
          return reject(result);
        }
        return resolve(result);
      });
    });

    handler.post(async (req, res) => {
      const fileUploadAllowed = // business logic
      if (fileUploadAllowed) {
        // Parse req.files
        await runMiddleware(
          req,
          res,
          multer({
            limits: { fileSize: MAX_FILE_SIZE },
            storage: multerS3({
              s3,
              bucket: process.env.FILE_SERVER_BUCKET,
              acl: 'public-read',
              key(_, file, cb) {
                cb(null, `${user._id}/${form._id}/${submissionId}/${file.originalname}`);
              },
            }),
          }).array('_file', 5),
        );
      }
      // Parse the req.body
      await runMiddleware(
        req,
        res,
        bodyParser.urlencoded({ extended: true }),
      );
      await runMiddleware(
        req,
        res,
        bodyParser.json(),
      );

      // Access here
      console.log(req.files, req.body);
    });

This setup works if the forms enctype is multipart/form-data or application/x-www-form-urlencoded, but the problem is if the fileUploadAllowed is false then the req never runs through Multer, and if the form is multipart then the body will be empty too and the whole POST is rejected. I can't just run it through Multer no matter what because the files are automatically uploaded to my S3 bucket.
What is the best way to handle this setup?


text:
Q: JavaScript-TypeError: Cannot add property __id, object is not extensible I defined a HOC React component and save it as a tsx file.
const Hoc = WrappedComponent => class extends WrappedComponent {

  constructor(props, context) {
    super(props, context)
    this.__id = ''
  }
}

Once deliver it to the compiler, error would be cast.
TypeError: Cannot add property __id, object is not extensible


text:
Q: How can I avoid duplicating data in a document database like RavenDB? Given that document databases, such as RavenDB, are non-relational, how do you avoid duplicating data that multiple documents have in common?  How do you maintain that data if it's okay to duplicate it?

A: There's no one "right" answer to your question IMHO. It truly depends on how mutable the data you're duplicating is.
Take a look at the RavenDB documentation for lots of answers about document DB design vs. relational, but specifically check out the "Associations Management" section of the Document Structure Design Considerations document. In short, document DBs use the concepts of reference by IDs when they don't want to embed shared data in a document. These IDs are not like FKs, they are entirely up to the application to ensure the integrity of and resolve.

A: With a document database you have to duplicate your data to some degree. What that degree is will depend on your system and use cases.
For example if we have a simple blog and user aggregates we could set them up as:
  public class User
  {
    public string Id { get; set; }
    public string Name  { get; set; }
    public string Username  { get; set; }
    public string Password  { get; set; }
  }

  public class Blog
  {
     public string Id  { get; set; }
     public string Title  { get; set; }

     public class BlogUser
     {
       public string Id  { get; set; }
       public string Name  { get; set; }
     }
  }

In this example I have nested a BlogUser class inside the Blog class with the Id and Name properties of the User Aggregate associated with the Blog. I have included these fields as they are the only fields the Blog class is interested in, it doesn't need to know the users username or password when the blog is being displayed.
These nested classes are going to dependant on your systems use cases, so you have to design them carefully, but the general idea is to try and design Aggregates which can be loaded from the database with a single read and they will contain all the data required to display or manipulate them.
This then leads to the question of what happens when the User.Name gets updated.
With most document databases you would have to load all the instances of Blog which belong to the updated User and update the Blog.BlogUser.Name field and save them all back to the database.
Raven is slightly different as it support set functions for updates, so you are able to run a single update against RavenDB which will up date the BlogUser.Name property of the users blogs without you have to load them and update them all individually.
The code for doing the update within RavenDB (the manual way) for all the blog's would be:
  public void UpdateBlogUser(User user)
  {
    var blogs = session.Query<Blog>("blogsByUserId")
                  .Where(b.BlogUser.Id == user.Id)
                  .ToList();

    foreach(var blog in blogs)
       blog.BlogUser.Name == user.Name;

    session.SaveChanges()
  }

I've added in the SaveChanges just as an example. The RavenDB Client uses the Unit of Work pattern and so this should really happen somewhere outside of this method.


text:
Q: Transformation matrix for a basis I have the follow question here.

Let $B=\{u_1,u_2,u_3\}$ with $u_1=1$, $u_2=x$, $u_3=x^2$ denote a basis for the space of polynomials of the second order polynomials $P^2$. Let $T(a_0+a_1x+a_2x^2)=a_0+a_1(x-1)+a_2(x-1)^2$ be a linear transformation form $P^2$ to itself. Construct the representation matrix $[T]_{BB}.$

My approach was the following:
$T(1+0x+0x^2)=1+0(x-1)+0(x-1)^2=1$. So the 1st column of the transformation matrix is $\begin{pmatrix}1 \\ 0\\ 0 \end{pmatrix}$.
$T(0+1x+0x^2)=0+1(x-1)+0(x-1)^2=x-1$. So the 2nd column of the transformation matrix is $\begin{pmatrix}-1 \\ 1\\ 0 \end{pmatrix}$.
$T(0+0x+1x^2)=0+0(x-1)+1(x-1)^2=(x-1)^2=x^2-2x+1$. So the 3rd column of the transformation matrix is $\begin{pmatrix}1 \\ -2\\ 1 \end{pmatrix}$.
So we get that $T_{BB}=\begin{pmatrix}  1 & -1 & 1\\ 0 & 1 & -2\\ 0 & 0 & 1\\\end{pmatrix}$.
Is this the right approach? Essentially, I am applying a linear map for the coordinates of the input and I get coordinates for the output which I map. If this isn't correct, what am I doing wrong and can someone correct me? Thanks!


text:
Q: struct as an argument of sucessive functions... little error need fixing. (C) So I got that:
typedef struct {
    int score;
    char init;
} Student;

int changestuff(Student *students) {

    students->score = 100;

    students++;

    students->score = 200;

    changestuffagain(students);

}

int changestuffagain(Student *students) {

     students->score = 100;

    students++;

    students->score = 200;
}

int main() {

    Student students[2];

    changestuff(students);

}

I call the function changestuff and it modifiys correctly the socre of players[0] and players[1], but my little problem, is that when I call the second function changestuffagain, the argument does not pass players[0] and players[1], it passes just players[1] (the value of players at the moment of calling changestuffagain)
How i could fix that?

A: Well, that's what you told it to do. When your changestuff function calls changestuffagain, you've incremented the value of students, so it now points to the second Student in the array. If you want to keep the pointer in the same place, you should pass the non-incremented value.

A: When you call students++ you jump to the next memory position where it is allocated a Student(in your case students[1]). You could decrement students before making the call of changestuffagain().
For example:
students--;
changestuffagain(students);


text:
Q: Error while doing "npm install" I am new to this. I do not know if this has to be taken seriously or I can proceed with what I am upto. Only here I can post it with full detail.
npm ERR! error installing express@3.3.5
npm ERR! error rolling back express@3.3.5 Error: UNKNOWN, unknown error '/home/ubuntu/vengit/node_modules/express'

npm ERR! Unsupported
npm ERR! Not compatible with your version of node/npm: connect@2.8.5
npm ERR! Required: {"node":">= 0.8.0"}
npm ERR! Actual:   {"npm":"1.1.4","node":"0.6.12"}
npm ERR!
npm ERR! System Linux 3.2.0-40-virtual
npm ERR! command "node" "/usr/bin/npm" "install"
npm ERR! cwd /home/ubuntu/vengit
npm ERR! node -v v0.6.12
npm ERR! npm -v 1.1.4
npm ERR! code ENOTSUP
npm ERR! message Unsupported
npm ERR! errno {}
npm http GET https://registry.npmjs.org/keypress
npm http GET https://registry.npmjs.org/mime
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /home/ubuntu/vengit/npm-debug.log
npm not ok

A: The error is because one of Express' dependencies (Connect) requires Node 0.8.0 or later.
npm ERR! Required: {"node":">= 0.8.0"}
npm ERR! Actual:   {"npm":"1.1.4","node":"0.6.12"}

And, since you have Node 0.6.12 installed, you won't be able to install Express 3.3.5.
You can try to install an older version of Express or update Node to at least 0.8.0.


text:
Q: How to set up toolbar to be fixed in vuetify? In vuetify I use a toolbar
    <v-toolbar dark color="primary">
        <v-toolbar-side-icon @click.stop="drawer.drawer = !drawer.drawer"></v-toolbar-side-icon>
        <v-toolbar-title>{{drawer.title}}</v-toolbar-title>
    </v-toolbar>
    <router-view v-bind:page="pageData"></router-view>

But I want to make it fixed, and not overlap with the vuerouter contents. How can I do that? I tried putting fixed but it still overlaps.
Thanks

A: Since version 2.0.0 v-toolbar isn't fixable use v-app-bar https://vuetifyjs.com/en/components/app-bars

A: *

*Add the app attribute to the toolbar

*Put your router outlet content inside a v-content element.

*Finally, make sure the whole shebang is inside a v-app element.

A: Use css arguments in style tags.
Cf.) https://journal.simondepelchin.be/2019/03/04/how-to-make-a-sticky-tabs-bar-with-vuetify/
<template>
  <v-toolbar class="fixed-bar">
    <!-- ... -->
  </v-toolbar>
</template>

<style scoped>
.fixed-bar {
  position: sticky;
  position: -webkit-sticky; /* for Safari */
  top: 6em;
  z-index: 2;
}
</style>

A: Use app-bar outside from router-view
Use this example https://vuetifyjs.com/en/components/application/#application

<!-- App.vue -->

<v-app>
  <v-navigation-drawer app>
    <!-- -->
  </v-navigation-drawer>

  <v-app-bar app>
    <!-- -->
  </v-app-bar>

  <!-- Sizes your content based upon application components -->
  <v-content>

    <!-- Provides the application the proper gutter -->
    <v-container fluid>

      <!-- If using vue-router -->
      <router-view></router-view>
    </v-container>
  </v-content>

  <v-footer app>
    <!-- -->
  </v-footer>
</v-app>


text:
Q: Getting Not defining \perthousnad and Not defining \micro when compiling beamer with Kile I have some experience using LaTeX with Miktex on windows, but am only taking baby steps in learning how to do it on Ubuntu. I am using Kile as IDE for making beamer presentations. The pdf file is nicely generated after the compilation, however, I get the following error message:
./file.tex:0: Not defining \perthousnad
./file.tex:0: Not defining \micro

I don't know what is going with Kile during compilation of beamer document classe! Could anyone suggest me any thing that may help!! thank you.

A: They are not errors, but warnings from the gensymb package, and if you look in the .log file I think you'll find:
Package gensymb Warning: Not defining \perthousand.

Package gensymb Warning: Not defining \micro.

So it has nothing to with either beamer or Kile. If you don't use those two symbols, don't worry about it. If you want to get rid of those warnings anyway, you can load the textcomp package before gensymb with \usepackage{textcomp, gensymb}. (Reference: http://www.latex-community.org/forum/viewtopic.php?f=4&t=3364#p13124)

A: This error is generated by the textcomp packaged imported by gensymb. You can prevent it by explicitly importing textcomp before gensymb:
\usepackage{textcomp}
\usepackage{gensymb}

...


text:
Q: Python TypeError: coercing to Unicode: need string or buffer, tuple found #!/usr/bin/env python
import sys
import os

print "Scan a file for ""ErrorScatter"" payload"
print "Drag the suspicious file here then press enter."
filepath = raw_input("File Location: ")
fixpath = filepath , "/Contents/MacOS/ErrorScatter"
scan = os.path.exists(fixpath)

So i am making a program to check if a file has a "ErrorScatter" payload but i keep coming across and error when testing my creation. Since i'm a newb i do not know how to fix this.
This is the error i'm getting:
TypeError: coercing to Unicode: need string or buffer, tuple found

Would anyone know how to fix this?

A: , operator in Python is used to create tuples, for example
1, 2, 3

makes 3-element tuple
(1, 2, 3)

and
"blah", "bleh"

means 2-element tuple
("blah", "bleh")

To concatenate strings, you could use + as Gaurav already suggested:
fixpath = filepath + "/Contents/MacOS/ErrorScatter"

but in fact the better way is to
import os

fixpath = os.path.join(filepath, "Contents/MacOS/ErrorScatter")

or even
fixpath = os.path.join(filepath, "Contents", "MacOS", "ErrorScatter")

(using os.path.join is a habit you will appreciate once you happen to run some scripts on windows, this one is not too likely but habits grow by repetition...)


text:
Q: Returning ResultSet without close? I would like to have a database connection managing class which I can use for simple SQL commands like SELECT, INSERT etc. by simple calling something like this (class below):
ResultSet test = DataService.getResultSet("SELECT NOW()");
test.first();
System.out.println(test.getString(1));

This is class I've found on web:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Database object to load drivers and perform queries
 * @author Abdulsalam Umar blog.salamtura.com
 */
public class DataService {

    private static Connection con;
    private static final String Driver = "oracle.jdbc.driver.OracleDriver";
    private static final String ConnectionString = "Your database connection string";
    private static final String user = "username";
    private static final String pwd = "password";

    /**
     * create Database object
     */
    public DataService() {
    }

    /**
     * to load the database base driver
     * @return a database connection
     * @throws SQLException throws an exception if an error occurs
     */
    public static Connection loadDriver() throws SQLException {
        try {
            Class.forName(Driver);
        } catch (ClassNotFoundException ex) {
            System.out.println(ex.getMessage());
        }
        con = DriverManager.getConnection(ConnectionString, user, pwd);
        return con;
    }

    /**
     * to get a result set of a query
     * @param query custom query
     * @return a result set of custom query
     * @throws SQLException throws an exception if an error occurs
     */
    public static ResultSet getResultSet(String query) throws SQLException {
        Connection con = loadDriver();
        ResultSet rs;
        PreparedStatement st = con.prepareStatement(query);
        rs = st.executeQuery();

        return rs;
    }

    /**
     * to run an update query such as update, delete
     * @param query custom query
     * @throws SQLException throws an exception if an error occurs
     */
    public static void runQuery(String query) throws SQLException {
        Connection con = loadDriver();
        ResultSet rs;
        PreparedStatement st = con.prepareStatement(query);
        st.executeUpdate();
    }
}

Is this way of returning ResultSet without closing it (and closing the statement) right? How can I return the ResultSet from the method?

A: Returning result set is not a good idea. So,fetch the required data and make use of collection to return the data.
This answer may be useful

A: How about passing a callback that takes ResultSet as parameter and let client code do whatever needs to inside it while you make sure that everything is cleaned up afterwards.
This is pattern in used in spring JDBC ResultSetExtractor and RowMapper. Look at this answer.

A: You can't return ResultSet because it will be closed when method destroyed. But you can get raw data from ResultSet, try this:
public ArrayList<ArrayList<byte[]>> getResultQuery(String query){
    ArrayList<ArrayList<byte[]>> tableResult = new ArrayList<>();
    ArrayList<byte[]> row;
    conn = getConnection(db_url);
    try {
        Statement statement = conn.createStatement();
        ResultSet resultSet = statement.executeQuery(query);
        int countColumn = resultSet.getMetaData().getColumnCount();
        if (countColumn==0) return null;
        while (resultSet.next()){
            row = new ArrayList<>();
            for (int i = 0; i<countColumn; i++){
                row.add(i,resultSet.getBytes(i+1));
            }
            tableResult.add(row);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return tableResult;
}

public static Connection getConnection (String db_url){
    Connection conn = null;
    try{
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        conn = DriverManager.getConnection(db_url);
    }catch(Exception e){
        e.printStackTrace();
    }
    return conn;
}

In this, i try to return ArrayList of ArrayList<byte[]>, ArrayList<byte[]> = 1 row in ResultSet. If you want to get some value, just use row.get(i) to get value from column i+1 in ResultSet which look like a 2 dimensions Matrix


text:
Q: Why can't I ping while I can see in ARP? There are several questions asked the same way; I have been trying various solutions for 3 days with no luck; that's why I am asking from scratch.
I have a wireless router and a wireless access point attached with a cable. Router is DHCP Server (192.168.1.1), access point has DHCP disabled with a fixed IP (192.168.1.250).
I have 8 machines (Windows 8.1 and Windows 10) connected to the router both wirelessly and wired. The problem is; all of the machines can ping each other except one. (192.168.1.154). This Windows 10 box cannot ping the server (192.168.1.147). Of course the server cannot ping it back either.
Shortly; 154 can ping all the network except 147. 147 can ping all the network except 154. So much weird enough; when I connect 154 to the access point rather than the router, it can then ping 147. Weird more; I can cross-see them in each other's arp table as dynamic entries.
I installed Microsoft Network Monitor, cleared arp, reset netsh both for TCP and Winsocks, and started cleanly capturing the network traffic. I can see this machine (154) sends an arp request to the server (147) by IP. In a matter of seconds, IP resolves to the server's name correctly. Then arp -a command lists the server by it's IP and MAC dynamically. But still cannot ping! (Most of the times connect timout. Less, "host unreachable")
Sometimes the server gets off the arp table arbitrarily and gets back in.
What I have tried so far:

*

*Turn off firewall on both machines. (No 3rd party firewalls installed.)

*Turn off firewall on the router (no MAC or IP filters)

*Turn off isolation on the router

*Change IP of both machines, both to automatic and something else fixed.

*Try adding a static arp entry on both machines.

*Run network related services which are set to run manually.

*Turn on network discovery and sharing on both machines.

*Set network type to "private".

Yesterday, two different machines were in this situation and there was no problem with 154. It was able to connect to the server. Today, that two machines can connect to the server but 154 cannot. Yesterday those 2 machines were also able to connect using the access point.
I bet this is a crappy Windows issue. Any ideas?


text:
Q: What is your expected waiting time if limousine inter-departure times follow an exponential distribution?
Limousines depart from the railway station to the airport from the early morning till late at night. The limousines leave from the railway station with independent inter-departure times that are exponentially distributed with an expected value of $20$ minutes. Suppose you plan to arrive at the railway station at three o'clock in the afternoon. What are the expected value and the standard deviation of your waiting time at the railway station until a limousine leaves for the airport?

Shouldn't the expected waiting time be $20$ minutes? Since it's an exponential distribution then for $t\to$  time to the departure, $f(t) = \frac{1}{20}e^{-\frac{1}{20}t}$. The expected value for this distribution would be $20$.
Is this correct?

A: This is a special case of the so called "stationary excess distribution".
The CDF of the time you have to wait is given by $F(t) = \frac{1}{20} \int_0^t [1-F(s)] ds$ where $F(s)$ is the CDF of an Exponential RV with mean 20.
An alternative way to do this is to use the fact that you're dealing with a poisson process, and if you start a poisson process at any time, it is still a poisson process with the same parameters, so the distribution to the next arrival is still Exponential with mean 20.

A: This is not exactly correct. If the number of limousines run every day is a constant $n$ = 60*(LateAtNight-YearlyMorning)/20,  and then the answer will be
$$20 * (n/(n+1)*(1+1/(n+1)/(n+2)) + 60*(24-(LateatNight-YearlyMorning))*pow((ArrivalTime-YearlyMorning)/(LateatNight-YearlyMorning),n)$$
As such, for a station opened from 5 AM till 1 AM and you arrived at 3PM, you have to wait ~ 19' 40''.


text:
Q: Import data with Comma as decimal seperator and do calculations I would like to read data from a csv and then do some calculations.
The problem here is the comma as a decimal separator. With a point as decimal seperator in my csv data everything woks but with a comma it does not. Are there any solutions available to solve my problem?
\documentclass{article}
\usepackage{pgfplotstable}
\pgfplotsset{compat=newest}
\pagestyle{empty}
\begin{document}

\begin{tikzpicture}
\begin{axis}[xlabel=$x$,ylabel=$y$]
\addplot [
           color=red,
           only marks,
           mark=*,
           mark size=1.5pt,
         ]
         table
         [ col sep=semicolon,
           /pgf/number format/read comma as period,
           x=x,
           y expr=\thisrow{y}*2
         ] {test.csv};
\end{axis}
\end{tikzpicture}

\end{document}

The Data:
x;y
1;1
2;1
3;1
4;8,5
5;2
6;2


text:
Q: Order confirmation email sent multiple time - same order confirmation sent to all - unable to stop sending I am using Magento Enterprise 1.9.1.0.
After creating two client account to run tests, I placed two order, one for each client.
An order confirmation for the first order is sent to both client 61 times per hour since then.
I tried removing all mention of the sending sales@ email address from the configuration panel and disabling  email sending from config. Both the server and the template support indicate that it stems from a bug in Magento.
How can I :
1. Stop the flow of email
2. Ensure proper functioning of automated order confirmation sending

A: This issue could be related to the new Magento Email Queue system, that leaves orphan records on the Recipients table.
If this is your issue, I've sent a fix on this post: https://magento.stackexchange.com/a/87299/23057

A: In the backend there's an option to turn off all mail sending:
System > Configuration > System > Mail Sending settings
Set "Disable Email Communications" to "Yes". This and:
System > Configuration > Design > HTML Head > "Display Demo Store Notice"
is what I try to do with every new test / development install. Now, why your mail is not being marked as sent, is difficult to say. Judging from the code, a field "processed_at" should be NOT NULL for a message to be considered as sent. This is done by Mage_Core_Mode_Email_Queue::send().
If an exception is thrown, then processed_at never gets set. I can only assume that your mailer returns a non-transient error code.


text:
Q: How to throw an error if user role is not allowed Laravel I am trying to leverage the Laravel auth system and add logic that does not allow you to log in if you have the user role of user. I want to extend authenticate users.
protected function sendLoginResponse(Request $request)
{
    $user = $this->guard()->user();

    $request->session()->regenerate();
    if ($user->role != 'admin') {
        return redirect()->back()->with('error', 'You do not have permissions to view this page');

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
    }
}

The issue is it still logs me in. How can I make this logic work?

A: Add this function to your LoginController, it will override the default function and add an extra constraint for logging in:
/**
 * override to add check
 *
 * @param \Illuminate\Http\Request $request
 * @return array
 */
protected function credentials(Request $request)
{
    $credentials = $request->only($this->username(), 'password');
    $credentials['role'] = 'admin'; //only login admin

    return $credentials;
}


text:
Q: How do I take the repeated values in an array and print out the number of duplicates using a for loop ?(Java) I have written the following program which takes the duplicates in the doubleArray and adds them to a counter.
Then I wrote a for loop to print out the values in the array going from the smallest value, up by 0.1, to the highest value. Then the program is supposed to put a dollar sign after each number that is represented in the array.
double[] doubleArray = {1.7,1.7,2.0,1.3,1.0};
int count = 0;
Arrays.sort(doubleArray);
for(int i = 0;i<doubleArray.length-1;i++){
    for(int j =i+1;j<doubleArray.length;j++){
        if (doubleArray[i] == doubleArray[j]) {
            count++;
        } else {
            break;
        }
    }
}

int finalDub = doubleArray.length;
double min = doubleArray[0];
double max = doubleArray[finalDub - 1];

for (double i = min; i < max+0.1; i += 0.1) {
    System.out.printf("%.1f ", i);
    System.out.print("$".repeat(count));
    System.out.print("\n");
}

But when I run the code, the following gets outputted
1.0 $
1.1 $
1.2 $
1.3 $
1.4 $
1.5 $
1.6 $
1.7 $
1.8 $
1.9 $
2.0 $

When it should be the following because I want it to add the $ only after a double represented in the array, and multiple '$''s for duplicate values.
1.0 $
1.1
1.2
1.3 $
1.4
1.5
1.6
1.7 $$
1.8
1.9
2.0 $

I believe what is happening is the count integer is being set once and never updating. Either way, how can I update my counter logic to represent what I want to be outputted?

A: I made a custom Counter class to keep track of each Double and the counts of the Double. You can iterate through all your doubles, add the non-duplicates, and if duplicate, increment count.
import java.util.ArrayList;
import java.util.Arrays;

public class test {

    static class Counter{
        Double value;
        int count;

        Counter(Double d, int c){
            this.value = d;
            this.count = c;
        }

        public String toString() { return value+":"+count; }
    }

    public static void main(String[] args){
        double[] doubleArray = {1.7,1.7,2.0,1.3,1.0};
        ArrayList<Counter> list = new ArrayList<>();

        Arrays.sort(doubleArray);
        for(int i = 0;i<doubleArray.length;i++){
            int size = list.size();
            if (size == 0){
                list.add(new Counter(doubleArray[0], 1));
            }else{
                Counter current = list.get(size-1);
                if (doubleArray[i] != current.value){
                    list.add(new Counter(doubleArray[i], 1));
                }else{
                    current.count = current.count +1;
                }
            }
        }

//        for (int i=0; i< list.size(); i++){
//            System.out.println(list.get(i).toString());
//        }

        int finalDub = doubleArray.length;
        double min = doubleArray[0];
        double max = doubleArray[finalDub - 1];

        for (double i = min; i < max+0.1; i += 0.1) {
            int count = 0;
            System.out.printf("%.1f ", i);
            for (int j=0; j< list.size(); j++){
                Counter obj = list.get(j);
                double val = Double.parseDouble(String.format("%.1f", i));
//this is necessary to format the floating point number to the exact accuracy stored in your array
                if (obj.value == val){
                    count = obj.count;
                    break;
                }else{
                    continue;
                }
            }
            System.out.print("$".repeat(count));
            System.out.print("\n");
        }
    }
}

I also found that for some reason, your loop to iterate through values from min to max have some floating point issues that cause it to not have the same value as the double stored in the array.

A: BUG FOUND o_o (REFERENCE ONLY)
NOTE THIS IS NOT A FULL SOLUTION ONLY A RECOMMENDATION
Instead of creating a nested loop with a break statement, I would 1000% recommend an approach closer to this.
    int size = doubleArray.length - 1, count = 0;
    double number = doubleArray[0];

    for(int index = 1; index < size; index++)
    {
        if(number == doubleArray[index])
        {
            count++;
        }
        number = doubleArray[index + 1];
    }

Though I do not know exactly where the issue is with your code, the easier it is to read the easier the bug will be to find!
EDIT after MY found bug ha
This part works great and is what you want
if(number == doubleArray[index])
{
    count++;
}

But if this is in the for-loop,
number = doubleArray[index + 1];

Each number after that will be considered a match.

A:
How could I change it so it is updated for each value

If you create a second array to track each digit you could do so pretty reliably, though I am sure there are more efficient ways out there.
int[] digitCount = new int[11]; // 1.0 - 2.0
...
if(number == doubleArray[index])
{
    digitCount[number]++;
}
...

And then down in your print
...
System.out.print("$".repeat(digitCount[i]));
...

Make sure that the i (or whatever you call it) is a WHOLE number because you cannot have decimal indecies.


text:
Q: Can Launchy's Weby plugin work with Opera? I want to use Opera as my default web browser because I really want to use the keyboard navigation feature. Using the keyboard (more) helps quell the tendinitis in my wrists.
I use Launchy to launch programs, search, etc.
Problem:

*

*Launchy's Weby works with IE, Firefox, Chrome, but it doesn't work with Opera

*"Doesn't work" = it doesn't follow (execute) the link generated by Weby

Suspicion:

*

*IE, Firefox, Chrome seem to adhere to the same convention for accessing the address bar (i.e. hit F6 in all and it selects the address bar), and Opera doesn't.

Any ideas?

A: For me, Opera works with Weby from Launchy.
Maybe it's a matter of versions, but typically, if I try with "lets search something", it opens "http://www.google.com/search?source=launchy&q=lets%20search%20something" in Opera, in a new tab.
I'm using Opera 10.0 beta 3, and Launchy 2.1.2

Note that if you use a 10.0 beta like me, opening a link (execute) with Opera being initially closed, will probably not work if you use "save previous session". For me, it opens Opera with the restored session, but not with the new link. But this is a known issue from the beta. It works if you open a link, with Opera already opened.

This opening link from a closed Opera worked with the 9.x versions, so I guess it will work again, it's only a temporary bug during beta. In general, this problem happens too if you try to click a link in some other software, when it will require Opera to open, it won't work on first try.
For now, what you can do is to write in Launchy your Weby request ; it will open Opera, without your wanted link ; call launchy again and press enter directly, to send again the same request ; this time it will work.
Keep in mind that this is a temporary issue from Opera beta, and will most likely be fixed in the final version.

If the problem is in Opera 9.64 too, then maybe I'm wrong, and I remember badly. Maybe I was not saving sessions then, I'm not sure. Anyway, I'll submit it to Opera, restoring session or not, it should open the link.

Update on the problem
The issue with Opera, which was not opening links from external, on launch, has been solved in the Release Candidate version. You can find it here : http://www.opera.com/browser/next/ (or use the direct link to installer).
I checked with Launchy and its Weby plugin, it works now correctly, even if Opera is closed.


text:
Q: Decreasing sequences Can a decreasing sequence be bounded below but not above? Does it make sense to have such a sequence?
I was looking at a Theorem: if a sequence is bounded and decreasing, then it's limit is going to be the greatest lower bound.
So, let's say the sequence starts off with some number, then it starts decreasing, it makes sense for the limit to be the greatest lower bound. I also understand why we need the bounded condition (since bounded =bounded above and bounded below): because if it wasn't bounded below we couldn't find the limit right? Could we say in this example that the sequence is bounded below rather than saying its bounded above too? (and consequently saying it is bounded?)
I'm sorry if this is a confusing-looking question. Thank you in advance.

A: A nonincreasing sequence (a fortiori a decreasing one) $(x_n)_{n\geq 1}$ is always bounded above by $x_1$. So it is bounded if and only if it is bounded below.


text:
Q: Floating images are not at the same height on relative position I need a set of icons grouped under a div to appear to the right of my logo (which is located on the top-left corner). I need the logo and all icons to have a position of relative. I am using float:left for both divs, but the second div (the group of icons) appears below the logo and not to its right. I have also tried grouping them under an unordered list and input style="float:left" as HTML, but it does not work either.
Here is the CSS:

div.container {
  width: 1111px;
}

#parent {
  display: flex;
}

.logo {
  float: left;
  position: relative;
  top: 0px;
  margin-left: 0px;
}

#icons {
  position: relative;
  float: left;
  white-space: nowrap;
  width: 100%;
  display: table;
  max-width: 100%;
}

.all-icons {
  position: relative;
  float: left;
  vertical-align: middle;
  padding: 15px;
  display: table-cell;
}

.all-icons img {
  height: auto;
  width: auto;
  max-height: 77px;
  max-width: 100%;
  margin: 15px;
}

A: Is this what you look for?

div.container {
  /* width: 1111px; */
}
#parent {
  display: flex;
}
.logo img {
  margin: 15px;
}
.all-icons {
  white-space: nowrap;
}
.all-icons img {
  margin: 15px;
}

If you can't use flex, try display: table

div.container {
  /* width: 1111px; */
}
#parent {
  display: table;
}
.logo {
  display: table-cell;
}
.all-icons {
  display: table-cell;
}
.logo img {
  margin: 15px;
}
.all-icons {
  white-space: nowrap;
}
.all-icons img {
  margin: 15px;
}

A: Add #icons { text-align: right; }, i think this will help you.
please do remove #parent { display: flex;} and also remove #icons { width: 100% }

A: It looks in line to me (see below image) however the margins/padding make it look like it's below and to the right.

Other things which may prove useful having seen your code:

*

*display: inline-table

*http://flexboxgrid.com/

*remembering to keep CSS files as small as possible, not as comprehensive as possible to make it easy to find and fix things

A: Your image of logo class not in center of its parent. Add
text-align: center;
 margin: auto;
into you .logo class


text:
Q: How to find if a set of objects share one property, which can be either of two properties? I'm trying to check whether a list of objects have one of two properties identical between them.
As in:
class Test():
  def __init__(self, prop1, prop2):
    self.prop1 = prop1
    self.prop2 = prop2

print(Check([Test(1, 1), Test(1, 2), Test(1, 3)]))
print(Check([Test(1, 1), Test(2, 1), Test(3, 1)]))
print(Check([Test(1, 1), Test(2, 1), Test(1, 2)]))

Would result in an output of:
(True, "prop1")
(True, "prop2")
(False, None)

Because:

*

*for all three objects prop1 == 1.

*for all three objects prop2 == 1.

*for all three objects there is no attribute with the same value.

How can this be done? What should be the Check function?

A: Assuming all objects are from the same class, you can iterate over the attributes, and check if they are identical through all objects:
def Check(objects):
    for attr, value in vars(objects[0]).items():
        if all(getattr(obj, attr) == value for obj in objects[1:]):
            return (True, attr)

    return (False, None)

A: You can use the __dict__ method to get the attributes then apply set intersection to get the match
from functools import reduce

def Check(l):
    match = reduce(lambda x,y: set(x).intersection(y), [i.__dict__.items() for i in l])
    return (True, match) if len(match)>0 else (False, None)

class Test():
    def __init__(self, prop1, prop2):
        self.prop1 = prop1
        self.prop2 = prop2

print(Check([Test(1, 1), Test(1, 2), Test(1, 3)]))
print(Check([Test(1, 1), Test(2, 1), Test(3, 1)]))
print(Check([Test(1, 1), Test(2, 1), Test(1, 2)]))

# (True, {('prop1', 1)})
# (True, {('prop2', 1)})
# (False, None)

A: You could build a set out of the properties and see whether its size is one when you've finished:
def Check(values):
    prop1 = {v.prop1 for v in values}
    prop2 = {v.prop2 for v in values}
    if len(prop1) == 1:
        return True, 'prop1'
    elif len(prop2) == 1:
        return True, 'prop2'
    else:
        return False, None


text:
Q: How to throttle power consumption of a heating coil? Which is an appropriate but simple electrical circuit to reduce the energy (power) consumed by a heating coil which has an AC feeding without generating an asymmetric load (large DC component, e.g. with a diode)?
I know that this would make it cooler.
Some heating coils consume a lot of power (kilowatts), so a simple resistor in series would be a bad idea (difficult to cool). A capacitor in series is also very easy, but way to expensive for the two months application I want it for.
I think what I need is a kind of dimmer, a thyristors or triac. But I want to have a fixed rating, it doesn't have to be adjustable. Of course I have no problem if it is adjustable if the electrical network is still easy to understand and to build.
E.g. if my power source is 230 V AC, 50 Hz. The heating coil has a power consumption of 2300 Watts at this voltage but I want it to consume only 1400 Watts, which parts are most recommendable and how would the circuit look like (or what is it's name, I could then search for it).
PS: This is the second attempt to ask this question. The first one was to specific on my dishwasher and inverter, but also got some interesting answers.

A: The argument:
If your heating element is rated to dissipate 2300 watts with 230 volts across it, then when it's dissipating 2300 watts the current through it will be:
I = P/E = 2300W/230V = 10 amperes,
and its resistance will be:
R = E/I = 230V/10A = 23 ohms.
In order for the element to dissipate 1400 watts, then, the voltage across it must be decreased to:
E = sqrt (PR) = sqrt (1400W * 23R) ~ 180 volts,
and the current through it decreased to:
I = P/E = 1400W/180V ~ 7.8 amperes
Since the mains voltage is unchangeable at 230 volts, then in order to limit the current through the heating element to 7.8 amperes, a series attenuating element must be introduced into the circuit which will drop the mains' 230 volts down to the 180 volts required by the heater.
That's 50 volts, and it must pass the 7.8 ampere heater current, so its resistance will be:
R = E/I = 50V/7.8A = 6.4 ohms.
The total resistance of the series string will therefore be 29.4 ohms, the sum of the two resistances,.
If we use a capacitor to losslessly drop the voltage to the heater, then we can define the resistance of the string as an impedance,
Z² = R² + Xc², where:
Z is the impedance of the string,
R is the heater resistance, and
Xc is the reactance of the series capacitor, all in ohms.
Rearranging to solve for Xc we get:
Xc = sqrt (Z² - R²) = sqrt (864.4R - 529R) = 18.3 ohms
and, finally, to get the capacitance,
C = 1/(2pi f Xc) = 1/(6.28 * 50Hz * 18.3R )= 174 microfarads .
Cornell-Dubilier makes a nice line of caps which seem perfect for this application.
Pricey, no doubt, but probably less so - and certainly lighter and smaller - than an inductor or a transformer capable of doing the same job.
The LTspice proof:
Version 4
SHEET 1 1460 680
WIRE 256 64 96 64
WIRE 256 96 256 64
WIRE 96 160 96 64
WIRE 256 192 256 160
WIRE 96 320 96 240
WIRE 256 320 256 272
WIRE 256 320 96 320
WIRE 96 368 96 320
FLAG 96 368 0
SYMBOL voltage 96 144 R0
WINDOW 3 24 96 Invisible 2
WINDOW 123 0 0 Left 2
WINDOW 39 0 0 Left 2
SYMATTR InstName V1
SYMATTR Value SINE(0 325 50)
SYMBOL cap 240 96 R0
SYMATTR InstName C1
SYMATTR Value 180µ
SYMBOL res 240 176 R0
SYMATTR InstName R1
SYMATTR Value 23
TEXT 104 344 Left 2 !.tran 1

A:
A series resistor would be difficult to cool.

This is true, but let's follow this idea to see where it leads.  The heating element is a resistor, and note that it gets hot without damage.  This tells us that the kind of resistor you want would be another heating element.
Now, it seems as though you're getting nowhere because you've just moved the power from one heating element to another.  But the power decreases if you add resistance.  The total resistance is higher, so the current through both is reduced.  The voltage (across both) is still the same, so if you wanted to calculate the power, you'd use the same voltage times the new current.  (Or V^2/R).
Just as an easy example, if you got two of the same heating elements and wired them in series, they would draw half the power (a quarter going to each).
Note: This is a late answer to an old question, but this explanation may be useful to someone with a similar issue who searched and found your question.

A: The schematic below shows a pretty simple way to do it, and there's an LTspice simulation here that shows the circuit in action.
In words, U1 is wired as a 4-bit binary down counter which uses the mains for a clock source and is designed to count down to zero from 14 in one instance, and then down to zero from 9 in the next, the plan being to keep the mains connected to the heater for 14 mains cycles, disconnect it for 9, and then to repeat that sequence forever, causing the heater to dissipate 1400 watts over the long term, instead of 2300.
In order to do that, U1's carry out (COUT) is used to toggle U3, which sets U1's broadside load inputs to either 1110 or 1001,  which is then loaded into U1 by the high on U1-PE, which SETs or RESETs U1's internal count stages. That causes COUT to go high, enabling the counter and allowing it to count down until it gets to zero, when U3 will toggle and the cycle will begin anew with the new preset.
During the time the counter is counting down from from 14 to zero, U3 is used to turn on the zero-crossing TRIAC driver, U4, which in turn turns on the TRIAC and connects the heater to the mains. Then, when U1 gets to zero, U3 will toggle and the TRIAC will be turned OFF for 9 mains cycles.  Then, when U1 counts down to zero, from 9, U3 will toggle again, starting the cycle anew by turning on the TRIAC for 14 mains cycles.

A: As I need this power reduction only for one or two months (until my 3000 watts inverter is repaired and shipped to me again), I used the cheapest method, which was an electric waffle iron I already had, and which was broken in two parts – but the heating still works.
So I used this waffle iron as a resistor, where the iron itself is the heat sink for the attached heating coil of he waffle iron. It gets quite warm and smells like waffles (because I never cleaned the broken waffle iron) when the dishwasher heats. But it works, and it cost me nothing, because I reused the cables and the screw terminals from the waffle iron.

A: You can use an SSR to power on and off the load. By varying on-off duty cycles, you have a slow PWM. Unlike with series resistors, the unused power is not wasted - but just unused.
You can get a precise control as described
TRIAC Angle of Firing vs Power Delivered to Load, how calculate?

A: If you want to limit power then control the voltage or the current.  Your dimmer link is fine.  How much current/ power.  The first thing I thought about was a variac/ auto-transformer.  (also in your dimmer link.)


text:
Q: Scalable architecture for many uses and large amount of data (MSMQ?) im designing a system where i will have multiple users uploading large amount of data. My initial example is 100 users uploading 100Mb each every day.
I need to get the data, insert it into a database, process the data in the database (ETL) and then use the "polished" data for analysis.
The uploaded files will be received in chunks of 65k (initial design).
To avoid getting bottlenecks im thinking on building this using a MSMQ where i put the data into the MQ and then pass it on to different "programs/tools" that will process the data and in turn signal to the ETL tool via MSMQ to start doing its thing.
Alternatively im thinking on a "linear" approach:
--> receive data
--> save data to sql
--> wait for upload finish (run the two above until no more chunks)
--> signal the ETL to do its thing
--> When ETL is done report "Done" to callee

Which approach seem to be the better one? Is there any alternatives to look into? The ambition is to have several thousands of users... As far as i see this approach it locks the client/downloader.

A: I prefer the first approach. The advantage over the second approach would be that you can send and process the MSMQ messages asynchronously and have them transactional secure with very little efort.
Not that the second efford would not work - but the first looks like much less effort to me.
I also suggest that you might want to look at some frameworks that sit on top of the MSMQ. As a C# programmer I can recommend NServiceBus - but I do not know what you might using.

A: I suggest that after you've received the data you sort it according to the most often-used index of the target table. You should do this in RAM and you can either sort it 100MB at a time or all 100*100MB (it's only 10 GB of RAM) in one big sort. That way the block insertion will be faster (the indexing component will have less to do) and subsequent selects will find related rows more bunched together (physically next to each other on the disk) and less randomly spread inside the table. This will result in fewer physical reads for a given select thereby improving execution times.


text:
Q: Displaying array in tableView Currently developing an app which has a list of all items in an existing array (which is in a separate .swift file). This is done by a tableView. However, I only get a empty tableview each time. Any idea what goes wrong?
import UIKit
import MapKit

//Initialize the TableViewController
class CategoriesController: UIViewController, UITableViewDataSource, UITableViewDelegate {

//Retrieve the array
var locationsAll = [Location]()

//Outlet
@IBOutlet var tableView: UITableView!

//Load view
override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return locationsAll.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "allCell") ?? UITableViewCell(style: .subtitle, reuseIdentifier: "allCell")

    let location = locationsAll[indexPath.row]
    cell.textLabel?.text = location.title
    cell.detailTextLabel?.text = location.rating

    return cell
    }
}

As for the array, I've used a struct. The struct is called on MKMapView as well.
struct Location {
    let title: String
    let rating: String
    let description: String
    let latitude: Double
    let longitude: Double
}

The .swift file containing the struct & data:
struct Location {
        let title: String
        let rating: String
        let description: String
        let latitude: Double
        let longitude: Double
    }

let locations = [
    Location(title: "something", rating: "", description: "Old.", latitude: 10.11111, longitude: 1.11111),
        Location(title: "something", rating: "", description: "Old.", latitude: 10.11111, longitude: 1.11111),
        Location(title: "something", rating: "", description: "Old.", latitude: 10.11111, longitude: 1.11111)
]

I call it in the file using var locationsAll = [Location]()
Thank you in advance!

A: Then you need
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return locations.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "allCell") ?? UITableViewCell(style: .subtitle, reuseIdentifier: "allCell")

    let location = locations[indexPath.row]
    cell.textLabel?.text = location.title
    cell.detailTextLabel?.text = location.rating

    return cell
    }
}

as it appears let locations = [ is a global var so it's accessible everywhere , or you can declare
var locationsAll = [Location]()

then in viewDidLoad
locationsAll  = locations

A: It's discouraged to use a global array as data source. Data is supposed to be encapsulated in a struct, class, or enum.
You could create the locations inside the controller.
Replace
var locationsAll = [Location]()

with
var locationsAll = [
    Location(title: "something", rating: "", description: "Old.", latitude: 10.11111, longitude: 1.11111),
    Location(title: "something", rating: "", description: "Old.", latitude: 10.11111, longitude: 1.11111),
    Location(title: "something", rating: "", description: "Old.", latitude: 10.11111, longitude: 1.11111)
]

Or declare the locations as static variable in the struct
struct Location {
    let title: String
    let rating: String
    let description: String
    let latitude: Double
    let longitude: Double

    static let locations = [
        Location(title: "something", rating: "", description: "Old.", latitude: 10.11111, longitude: 1.11111),
        Location(title: "something", rating: "", description: "Old.", latitude: 10.11111, longitude: 1.11111),
        Location(title: "something", rating: "", description: "Old.", latitude: 10.11111, longitude: 1.11111)
    ]
}

and populate the data source array
var locationsAll = Location.locations

A: The count will equal 0. That's why no cells are rendered.  after adding data you need to relodData on the table view.
I assume you set up the cell in a storyboard? Otherwise you need to register the cell before using.


text:
Q: Unable to read 'checked' property in Qunit test case I have below mentioned code in my JS file.
initialize: function () {

        if (!$("#Res").is(':checked'))
        {
            $("#Res").attr('checked', true);
        }
}

When I tried to run test case using Qunit.js and blanekt.js. It shows me error that "Cannot read property 'checked' of null"
Can please anyone assist me to fix this issue or re-write test case. I am using Jquery 1.4.1.js version. Is issue related to version of Jquery?
test("initialize test", 1, function () {
    $('<input>').appendTo("body");
    $('<select>').appendTo("body");
    $('<input>', { type: "checkbox", checked: true, id: "Res"}).appendTo("body");
    var result = mydomain.initialize();
    equal(undefined, result, "passed");
    $('input, select').trigger("blur");
    ok(true, "blur event called");
    $('input, select').trigger("change");
    ok(true, "change event called");
    $("input").remove();
    $("select").remove();
});

A: Option 1.
Using your browser's dev tools, execute the following command:
$("#Res")
If you come up with null it means that your control isn't being created as you were expected.
Option 2.
If Option 1 is fine then you might be calling the initialize function before the input is created.
In any case it is difficult to help you because you haven't posted the resulting HTML by viewing the source of the page once it loads.
Option 3.
Checkbox libraries commonly use css and hide the actual checkbox input after they've initialised. You should check for available events or properties to check their state.


text:
Q: Spring Security 4 & CDI I want to use SpringSecurity4 in a CDI/EJB environment.
Is this possible? Can SpringSecurity can be used without using Spring?
What I want to do, is to use SpringSecurity with my EJB and CDI components.

A: Spring Security is basically a filter machine, filtering all the incoming requests. However, plenty of it's functionality is Spring-core dependent. It is possible to utilize Spring in a CDI application, but Spring's core is heavyweight and it's functionality is funny compared to CDI. That would be a downgrade and there would be no point in using CDI.
What you can do is to have a look at some Security projects for JEE world.

*

*Apache DeltaSpike and it's Security module.

*Keycloak - The absolute solution. Keycloak goes far, far beyond Spring security's functionality. It is an evolution of old PicketLink libraries developed by JBoss, but those are discontinued and merged into Keycloak instead. An example how simple usage of Keycloak is can be found here.

It is also not that hard to write own security interceptor using @WebFilter and @Inject :), there are several projects on GitHub:

*

*https://github.com/rmpestano/security-interceptor

*https://github.com/clairton/security

*https://github.com/Rudin-Informatik/cdi-security

*https://github.com/rafaelodon/my-security-context
I have no experience with these projects. However, I am always amazed how easily can Spring Security be replaced :)

A: I am using Spring Security with CDI but I can say it is not very healthy since Spring Security is based on spring and spring is messing with the CDI beans.
Here is what happened to me. I customized the AuthenticationProvider of spring security in order to authenticate users through my authentication server. When implementing this mechanism I used my predefined CDI beans by injecting them using (@Inject) annotation. At this point spring somehow intercepts the injection and creates its own bean, which means you cannot use any of the values you set to the CDI bean previously.
In order to solve this, I did some trick like this:
@Inject
private LoginController loginController;

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    //Here, the injected bean is empty, I am requesting my old bean from CDI and assign it back.
    LoginController bm = (LoginController) CDI.current().select(LoginController.class).get();
    loginController = bm;

I don't know if this is the answer you are looking for but i hope this helps...


text:
Q: Print data in a listview to look like an invoice I have created a simple POS system and want to print the data in a listview consisting of products prices and quantity.
I wish to add the logo of the company at the very top and then the data in the columns that follow.

A: You can try using PrintDocument of .NET, like this:
   try {
        // If you want a preview use the PrintPreviewDialog
        PrintPreviewDialog preview = new PrintPreviewDialog();

        PrintDocument document = new PrintDocument();
        document.PrintPage += new PrintPageEventHandler(document_PrintPage);

        preview.Document = document;
        // Then show the dialog window.
        preview.Show();

        // Otherwise, just call the document.Print();

   } catch {
       throw;

   }

And have your printpage event like this, with this you can get the values from your listview control and format the layout as necessary to look much like an invoice:
    protected void document_PrintPage(object sender, PrintPageEventArgs ev) {
        Font printFont = new Font("Arial", 14);
        ev.Graphics.DrawString("Sample String", printFont, Brushes.Black, ev.MarginBounds.Left, ev.MarginBounds.Top, new StringFormat());
    }

This will directly print the text you want, but if you want to select the printer first, you may want to use the PrintDialog of .NET.


text:
Q: Need help repairing adjustable DC power supply stuck on 48V I have a cheap benchtop dual-output adjustable DC power supply. One of the outputs is working alright, the other one "burned out" when it was left loaded somewhere near 80% of its maximum for 24 hours.
After opening it up and taking a look, I found a few burned power resistors (0.5Ω rated for 5W) plus some resistors which were surprisingly still functional (though burned beyond recognition) sandwiched between/around them, all of which I replaced:
Before:

After (with 3 resistors in parallel to give me an equivalent circuit until the replacement power resistor arrives - they haven't burned out in testing, so I'm good for now):

When these power resistors went out, they took a few more resistors nearer to the middle of the board out with them, and I replaced those as well. Powering up the board burned the regular resistors in the middle again, so I replaced them once more and tested all the other components on the board:

Luckily for me, there are two identical halves of the device, and I was able to quickly compare resistance across components leads (disconnecting some where I wasn't sure, but not all of them) and don't seem to have any remaining bad components. None of the capacitors are visibly damaged and their basic functionality checks out (though I'm unable to test their compliance to their rated capacitance as at 470uF they are out of my DMM's range and I don't have an ESR). The diodes seem to check out (though I'm having trouble positively testing some of the high-voltage protection diodes). The rectifiers have tested OK, and none of the transistors are shorted out so far as I can tell.
Crucially, I'm not sure what failed components would result in this behavior. The power supply is actually advertised as being 0-30V (and 0-5A), the 48V it's giving out now are well out of spec.
The problem is much complicated by the fact that the PCB design is an absolute mess. A number of traces appear to have been (by comparison to the other, functioning board) purposely joined together via globs of solder. The solder obviously reflowed around the burned power resistors and possibly in a few other places, but tracing it as best as I could and comparing it to the other board, it seems that everything is fine (and the burned traces are still functional).
The unit is still stuck at 48 volts no matter how I adjust the pots (and I tested them, just in case it was ironically just a control problem after everything I did and tested - I also disconnected the control and output boards entirely to no effect), and I'm not sure what else to try. I'm not very well-versed in analog, though I've tried isolating the problem as much as I could only to always end up disproving my hypotheses.
Here's the board now:

The unit itself:

I found a few schematics online for similar Chinese units, but I haven't been able to find any that match one-for-one my unit.
EDIT
The power transistors up close:


text:
Q: Sinatra + Fibers + EventMachine I would like to know to to pause a Root Fiber in ruby (if possible).
I have this Sinatra app, and I am making async calls to an external API with EventMachine.
I don't want to respond to the client until the api responds me.
For example, sleeping the Root Fiber in Sinatra until the EventMachine callback wake it up.
Thanks.

A: get '/some/route/' do
  fib = Fiber.current
  req = EM::SomeNonBlokingLib.request
  req.callback do |response|
    fib.resume(response)
  end
  req.errback do |err|
    fib.resume(err)
  end
  Fiber.yield
end

EDIT
In your case you should spawn a Fiber for each request. So. Firstly create Rack config file and add some magick:
# config.ru
BOOT_PATH = File.expand_path('../http.rb',  __FILE__)
require BOOT_PATH

class FiberSpawn
  def initialize(app)
    @app = app
  end

  def call(env)
    fib = Fiber.new do
      res = @app.call(env)
      env['async.callback'].call(res)
    end
    EM.next_tick{ fib.resume }
    throw :async
  end
end

use FiberSpawn
run Http

Then your http Sinatra application:
# http.rb
require 'sinatra'
require 'fiber'

class Http < Sinatra::Base
  get '/' do
    f = Fiber.current
    EM.add_timer(1) do
      f.resume("Hello World")
    end
    Fiber.yield
  end
end

Now you could run it under thin for example:
> thin start -R config.ru

Then if you will visit locakhost:3000 you'll see your Hello World message


text:
Q: Как выравнивать таблицу по размеру окна? У меня проблема с отображением таблицы в браузере.
Так выглядит таблица на большом экране браузера

Но когда размер экрана уменьшается, происходит следующее:

Как можно это исправить?
Код стиля:
<style type="text/css">
   TABLE {
    width: 300px; /* Ширина таблицы */
    border-collapse: collapse; /* Убираем двойные линии между ячейками */
   }
   TD, TH {
    padding: 3px; /* Поля вокруг содержимого таблицы */
    border: 1px solid black; /* Параметры рамки */
   }
   TH {
    background: #b0e0e6; /* Цвет фона */
   }
   {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.table-fixed-head {
  width: 100%;
  table-layout: fixed;
  border-collapse: collapse;
  height: 100vh;
}

.table-fixed-head th,
.table-fixed-head td {
  padding: 5px;
  text-align: center;
  width: 33.333vw;
}

.table-fixed-head thead {
  background-color: #333;
  color: #FDFDFD;
}

.table-fixed-head thead tr {
  display: block;
  position: relative;
}

.table-fixed-head tbody {
  display: block;
  overflow: auto;
  width: 100%;
  height: calc(100vh - 30px);
}

.table-fixed-head tbody tr:nth-child(even) {
  background-color: #DDD;
}
  </style>

A: Вам нужно отключить overflow при определенных размерах экрана:
@media (max-width: 1000px) {
.table-fixed-head tbody {
  overflow: visible;
}

Или попробуйте другие его свойства


text:
Q: How can I get the value of children in Firebase database using Javascript? How do you get the value of a specific key-value pair in firebase using javascript? I am creating a function for firebase cloud messaging. My function looks like this:
'use strict'

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/notifications/{receiver_user_id}/{notification_key}').onWrite((event, context)=>{
    const receiver_user_id = context.params.receiver_user_id;
    const notification_key = context.params.notification_key;
    console.log('We have a notification to send to : ', receiver_user_id);
    // Grab the current value of what was written to the Realtime Database.
    const snapshot = event.after.val();
    console.log('Uppercasing', context.params.notification_key, snapshot);
    console.log('original value : ', snapshot);

    if(!event.after.val()){
        console.log('A notification has been deleted: ', notification_key);
        return null;
    }

    const sender_fullname = admin.database().ref(`/notifications/${receiver_user_id}/{notification_key}/notifying_user_fullname`).once('value').toString();
    console.log('full name value : ', sender_fullname);

    const DeviceToken = admin.database().ref(`/tokens/${receiver_user_id}/device_token`).once('value');

        return DeviceToken.then(result=>{
        const token_id = result.val();
        console.log('token id value : ', token_id);

            const payload = {
            notification: {
                title: sender_fullname.toString(),
                body: "You have a new message!",
                icon: "default"
                }
            };

            return admin.messaging().sendToDevice(token_id, payload).then(response=>{
                console.log('Message has been sent');
            });

        });

});

Right now sender_fullname produces [object Promise] in the console log and the notification that is sent. I am uncertain how to get the exact value. An example entry in my realtime database looks like this:
original value :  { date_created: '02-21-2020T17:50:32',
  my_id: '0ntpUZDGJnUExiaJpR4OdHSNPkL2',
  notification_key: '-M0dwVL3w1rKyPYbzUtL',
  notification_type: 'liked',
  notifying_user: 'OiBmjJ7yAucbKhKNSHtYHsawwhF2',
  notifying_user_fullname: 'Captain Proton',
  post_key: '-LzSJrOq9Y7hGgoECHRK',
  read: 'false' }

Is there any way to get the exact value of say, "notifying_user_fullname"? Any help would be appreciated.

A: To get the value of sender_fullname, you have to do exactly the way you do for DeviceToken!
The once() method returns a promise which resolves with a DataSnapshot, so you need to use the then() method in order to get the DataSnapshot and then, use the val() method.
So the following should do the trick (untested):
exports.sendNotification = functions.database.ref('/notifications/{receiver_user_id}/{notification_key}')
    .onWrite((event, context) => {
        const receiver_user_id = context.params.receiver_user_id;
        const notification_key = context.params.notification_key;
        console.log('We have a notification to send to : ', receiver_user_id);
        // Grab the current value of what was written to the Realtime Database.
        const snapshot = event.after.val();
        console.log('Uppercasing', context.params.notification_key, snapshot);
        console.log('original value : ', snapshot);

        if (!event.after.val()) {
            console.log('A notification has been deleted: ', notification_key);
            return null;
        }

        let sender_fullname;

        return admin.database().ref(`/notifications/${receiver_user_id}/${notification_key}/notifying_user_fullname`).once('value')
            .then(dataSnapshot => {

                sender_fullname = dataSnapshot.val();
                return admin.database().ref(`/tokens/${receiver_user_id}/device_token`).once('value');

            })
            .then(dataSnapshot => {

                const token_id = dataSnapshot.val();
                console.log('token id value : ', token_id);

                const payload = {
                    notification: {
                        title: sender_fullname,
                        body: "You have a new message!",
                        icon: "default"
                    }
                };

                return admin.messaging().sendToDevice(token_id, payload)

            })
            .then(() => {
                console.log('Message has been sent');
                return null;  // <-- Note the return null here, to indicate to the Cloud Functions platform that the CF is completed
            })
            .catch(error => {
                console.log(error);
                return null;
            })

    });

Note how we chain the different promises returned by the asynchronous methods, in order to return, in the Cloud Function, a Promise, which will indicate to the platform that the Cloud Function work is complete.
I would suggest you watch the 3 videos about "JavaScript Promises" from the Firebase video series which explains the importance of this point.